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(web): retire unused APIs and enforce private pin access
Gener1112f62cf35a
diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 643724c72..0edc7dec3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -472,9 +472,6 @@ importers:pdfjs-dist:specifier: 6.4.299version: 6.4.299- postal-mime:- specifier: ^2.7.6- version: 2.7.6react:specifier: 19.3.1version: 19.3.1diff --git a/scripts/ci/fixtures/d1-dynamic-bind-sites.json b/scripts/ci/fixtures/d1-dynamic-bind-sites.jsonindex f90850851..38f93940d 100644--- a/scripts/ci/fixtures/d1-dynamic-bind-sites.json+++ b/scripts/ci/fixtures/d1-dynamic-bind-sites.json@@ -203,12 +203,6 @@{"key": "src/shared/src/db/queries/account-deletion.ts:getAccountDeletionSnapshot:inArray:9"},- {- "key": "src/shared/src/db/queries/agent-skill.ts:syncAgentSkills:values:1"- },- {- "key": "src/shared/src/db/queries/agent-skill.ts:syncGlobalSkills:values:1"- },{"key": "src/shared/src/db/queries/agent.ts:getAgentsByIds:inArray:1"},@@ -482,12 +476,6 @@{"key": "src/shared/src/db/queries/community/read-state.ts:advanceReadStateRevisionWhenAnyBuilder:or-map:1"},- {- "key": "src/shared/src/db/queries/community/search.ts:searchMessagesInServer:inArray:1"- },- {- "key": "src/shared/src/db/queries/community/server-folder.ts:insertFolderItems:values:1"- },{"key": "src/shared/src/db/queries/community/server.ts:getServersByIds:inArray:1"},@@ -539,15 +527,6 @@{"key": "src/shared/src/db/queries/native-oauth.ts:registerAttempt:inArray:2"},- {- "key": "src/shared/src/db/queries/overview.ts:getConversationCountsByAgent:inArray:1"- },- {- "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:1"- },- {- "key": "src/shared/src/db/queries/overview.ts:getRecentTerminalTasks:inArray:2"- },{"key": "src/shared/src/db/queries/product-plan.ts:reconcileActiveBotsBuilder:inArray:1"},@@ -572,15 +551,6 @@{"key": "src/shared/src/db/queries/runtime.ts:getAgentRuntimesForWorkspace:inArray:1"},- {- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:1"- },- {- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessages:notInArray:2"- },- {- "key": "src/shared/src/db/queries/task-message.ts:listTaskMessagesSince:notInArray:1"- },{"key": "src/shared/src/db/queries/task.ts:cancelActiveTasksByConversation:inArray:1"},@@ -667,8 +637,5 @@},{"key": "src/shared/src/db/queries/user.ts:getUsersByIds:inArray:1"- },- {- "key": "src/shared/src/db/queries/workspace-file-request.ts:markDispatched:inArray:1"}]diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.tsindex ed71e7d57..d614950be 100644--- a/src/shared/src/community-resources.ts+++ b/src/shared/src/community-resources.ts@@ -228,7 +228,6 @@ export const CommunityMessagePostedSchema = CommunityMessagesReadSchema.pick({ cmessage: CommunityMessageResourceSchema, deduped: z.boolean(), threadId: id.optional(),})export const CommunityMessageReadSchema = CommunityMessagePostedSchema.omit({ deduped: true, threadId: true })-export const CommunityReadStateReadSchema = z.strictObject({ ...envelope, readState: CommunityReadStateResourceSchema })export const CommunityMembersReadSchema = z.strictObject({ ...envelope, relation: z.enum(["access", "notify"]), members: z.array(CommunityMemberRelationSchema), profiles: z.array(CommunityResourceProfileSchema) })export const CommunityThreadsReadSchema = z.strictObject({ ...envelope, channel: CommunityChannelResourceSchema,threads: z.array(CommunityChannelResourceSchema),@@ -250,7 +249,6 @@ const legacyEnvelope = { contractVersion: z.literal(2), channelId: id }const legacyReadSchemas = {channel: CommunityChannelReadSchema.extend(legacyEnvelope),messages: CommunityMessagesReadSchema.extend({ ...legacyEnvelope, messages: z.array(CommunityLegacyMessageResourceSchema) }),- readState: CommunityReadStateReadSchema.extend(legacyEnvelope),members: CommunityMembersReadSchema.extend({ ...legacyEnvelope, profiles: z.array(legacyProfileSchema) }),threads: CommunityThreadsReadSchema.extend({ ...legacyEnvelope, included: CommunityThreadsReadSchema.shape.included.extend({messages: z.array(CommunityLegacyMessageResourceSchema), profiles: z.array(legacyProfileSchema),@@ -259,7 +257,7 @@ const legacyReadSchemas = {error: CommunityReadErrorSchema.extend({ contractVersion: z.literal(2) }),}const resourceReadSchemas = {- channel: CommunityChannelReadSchema, messages: CommunityMessagesReadSchema, readState: CommunityReadStateReadSchema,+ channel: CommunityChannelReadSchema, messages: CommunityMessagesReadSchema,members: CommunityMembersReadSchema, threads: CommunityThreadsReadSchema, readAdvance: CommunityReadAdvanceSchema, error: CommunityReadErrorSchema,}diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex b10de20e1..9524c718e 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -558,13 +558,6 @@ export const communityPushDevice = sqliteTable();// 19. community_bot_approval_request-// Represents pending/resolved approval workflows a bot owner sees in the-// owner↔bot DM. After migration 0065 the ONLY live `kind` is:-// - "join_server": another user asked to add the bot to a server they're in-// The former "friend" kind was folded into `community_friendship`-// (needsOwnerApproval column) and its rows deleted by the migration. The table-// name and shape stay; only the Drizzle `kind` union narrows (see `ApprovalKind`-// in queries/community/bot.ts). `serverId` is non-null iff kind="join_server".export const communityBotApprovalRequest = sqliteTable("community_bot_approval_request",{diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex 82c7cd49c..0a153b35e 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -1,37 +1,23 @@import * as nativeOauthQueries from "./queries/native-oauth";export * as user from "./queries/user";-export * as workspace from "./queries/workspace";export * as member from "./queries/member";export * as agent from "./queries/agent";export * as runtime from "./queries/runtime";export * as conversation from "./queries/conversation";export * as message from "./queries/message";export * as task from "./queries/task";-export * as taskMessage from "./queries/task-message";export * as machine from "./queries/machine";export * as machineToken from "./queries/machine-token";export * as whitelist from "./queries/whitelist";export * as email from "./queries/email";export * as session from "./queries/session";-export * as calendarEvent from "./queries/calendar-event";-export * as artifact from "./queries/artifact";export * as emailAccount from "./queries/email-account";-export * as workspaceInvite from "./queries/workspace-invite";-export * as agentAccess from "./queries/agent-access";-export * as agentPin from "./queries/agent-pin";-export * as agentSidebarOrder from "./queries/agent-sidebar-order";-export * as overview from "./queries/overview";export * as meetingSession from "./queries/meeting-session";-export * as channel from "./queries/channel";-export * as workspaceFileRequest from "./queries/workspace-file-request";-export * as agentSkill from "./queries/agent-skill";export * as conversationMap from "./queries/conversation-map";export * as agentLink from "./queries/agent-link";export * as inbox from "./queries/inbox";export * as issue from "./queries/issue";-export * as issueComment from "./queries/issue-comment";-export * as messageFlag from "./queries/message-flag";export * as accountDeletion from "./queries/account-deletion";export * as productPlan from "./queries/product-plan";export * as communityServer from "./queries/community/server";@@ -53,7 +39,6 @@ export * as communityMessageMark from "./queries/community/mark";export * as communityMention from "./queries/community/mention";export * as communityReadState from "./queries/community/read-state";export * as communityUserProfile from "./queries/community/user-profile";-export * as communitySearch from "./queries/community/search";export * as communityNotificationSetting from "./queries/community/notification-setting";export * as communityNotificationEligibility from "./queries/community/notification-eligibility";export * as communityPushDevice from "./queries/community/push-device";diff --git a/src/shared/src/db/queries/agent-access.ts b/src/shared/src/db/queries/agent-access.tsdeleted file mode 100644index e7520e05f..000000000--- a/src/shared/src/db/queries/agent-access.ts+++ /dev/null@@ -1,53 +0,0 @@-import { eq, and } from "drizzle-orm";-import { agentAccess, user } from "../schema";-import type { Database } from "../index";--export async function listAgentAccess(db: Database, agentId: string, workspaceId: string) {- return db- .select({- id: agentAccess.id,- agentId: agentAccess.agentId,- workspaceId: agentAccess.workspaceId,- userId: agentAccess.userId,- createdAt: agentAccess.createdAt,- userName: user.name,- userEmail: user.email,- })- .from(agentAccess)- .innerJoin(user, eq(agentAccess.userId, user.id))- .where(and(eq(agentAccess.agentId, agentId), eq(agentAccess.workspaceId, workspaceId)));-}--export async function grantAgentAccess(db: Database, data: { agentId: string; workspaceId: string; userId: string }) {- const rows = await db- .insert(agentAccess)- .values({ agentId: data.agentId, workspaceId: data.workspaceId, userId: data.userId })- .returning();- return rows[0]!;-}--export async function revokeAgentAccess(db: Database, agentId: string, workspaceId: string, userId: string) {- const rows = await db- .delete(agentAccess)- .where(and(eq(agentAccess.agentId, agentId), eq(agentAccess.workspaceId, workspaceId), eq(agentAccess.userId, userId)))- .returning();- return rows[0] ?? null;-}--export async function hasAgentAccess(db: Database, agentId: string, workspaceId: string, userId: string): Promise<boolean> {- const rows = await db- .select({ id: agentAccess.id })- .from(agentAccess)- .where(and(eq(agentAccess.agentId, agentId), eq(agentAccess.workspaceId, workspaceId), eq(agentAccess.userId, userId)));- return rows.length > 0;-}--export async function getAllAgentAccessForWorkspace(db: Database, workspaceId: string) {- return db- .select({- agentId: agentAccess.agentId,- userId: agentAccess.userId,- })- .from(agentAccess)- .where(eq(agentAccess.workspaceId, workspaceId));-}diff --git a/src/shared/src/db/queries/agent-pin.ts b/src/shared/src/db/queries/agent-pin.tsdeleted file mode 100644index 8f3c65c9d..000000000--- a/src/shared/src/db/queries/agent-pin.ts+++ /dev/null@@ -1,61 +0,0 @@-import { eq, and, asc, sql } from "drizzle-orm";-import { agentPin } from "../schema";-import type { Database } from "../index";--export async function listPins(db: Database, workspaceId: string, userId: string) {- return db- .select()- .from(agentPin)- .where(and(eq(agentPin.workspaceId, workspaceId), eq(agentPin.userId, userId)))- .orderBy(asc(agentPin.position));-}--export async function pinAgent(db: Database, data: { agentId: string; workspaceId: string; userId: string }) {- const [maxRow] = await db- .select({ maxPos: sql<number>`COALESCE(MAX(${agentPin.position}), -1)` })- .from(agentPin)- .where(and(eq(agentPin.workspaceId, data.workspaceId), eq(agentPin.userId, data.userId)));- const nextPos = (maxRow?.maxPos ?? -1) + 1;- const rows = await db- .insert(agentPin)- .values({ ...data, position: nextPos })- .onConflictDoNothing()- .returning();- return rows[0] ?? null;-}--export async function unpinAgent(db: Database, agentId: string, workspaceId: string, userId: string) {- const rows = await db- .delete(agentPin)- .where(- and(- eq(agentPin.agentId, agentId),- eq(agentPin.workspaceId, workspaceId),- eq(agentPin.userId, userId),- )- )- .returning();- return rows[0] ?? null;-}--export async function reorderPins(- db: Database,- workspaceId: string,- userId: string,- orderedAgentIds: string[],-) {- await (db as any).batch(- orderedAgentIds.map((id, i) =>- db- .update(agentPin)- .set({ position: i })- .where(- and(- eq(agentPin.agentId, id),- eq(agentPin.workspaceId, workspaceId),- eq(agentPin.userId, userId),- )- )- )- );-}diff --git a/src/shared/src/db/queries/agent-sidebar-order.ts b/src/shared/src/db/queries/agent-sidebar-order.tsdeleted file mode 100644index 3b9825505..000000000--- a/src/shared/src/db/queries/agent-sidebar-order.ts+++ /dev/null@@ -1,37 +0,0 @@-import { eq, and, asc } from "drizzle-orm";-import { agentSidebarOrder } from "../schema";-import type { Database } from "../index";--export async function listOrder(db: Database, workspaceId: string, userId: string) {- return db- .select()- .from(agentSidebarOrder)- .where(and(eq(agentSidebarOrder.workspaceId, workspaceId), eq(agentSidebarOrder.userId, userId)))- .orderBy(asc(agentSidebarOrder.position));-}--export async function reorder(- db: Database,- workspaceId: string,- userId: string,- orderedAgentIds: string[],-) {- await (db as any).batch([- db- .delete(agentSidebarOrder)- .where(- and(- eq(agentSidebarOrder.workspaceId, workspaceId),- eq(agentSidebarOrder.userId, userId),- )- ),- ...orderedAgentIds.map((agentId, i) =>- db.insert(agentSidebarOrder).values({- agentId,- workspaceId,- userId,- position: i,- })- ),- ]);-}diff --git a/src/shared/src/db/queries/agent-skill.ts b/src/shared/src/db/queries/agent-skill.tsdeleted file mode 100644index 97c2f1780..000000000--- a/src/shared/src/db/queries/agent-skill.ts+++ /dev/null@@ -1,105 +0,0 @@-import { eq, and, isNull, or } from "drizzle-orm";-import { agentSkill } from "../schema";-import type { Database } from "../index";--interface SkillRow {- name: string;- description: string;-}--export async function syncGlobalSkills(- db: Database,- workspaceId: string,- runtime: string,- skills: SkillRow[],- daemonId?: string,-) {- const now = new Date().toISOString();- const rows = skills.map((s) => ({- workspaceId,- agentId: null,- daemonId: daemonId ?? null,- runtime,- name: s.name,- description: s.description,- syncedAt: now,- }));-- const deleteCondition = daemonId- ? and(eq(agentSkill.workspaceId, workspaceId), eq(agentSkill.runtime, runtime), isNull(agentSkill.agentId), eq(agentSkill.daemonId, daemonId))- : and(eq(agentSkill.workspaceId, workspaceId), eq(agentSkill.runtime, runtime), isNull(agentSkill.agentId), isNull(agentSkill.daemonId));-- const BATCH_SIZE = 10;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const statements: any[] = [- db.delete(agentSkill).where(deleteCondition),- ];- for (let i = 0; i < rows.length; i += BATCH_SIZE) {- statements.push(db.insert(agentSkill).values(rows.slice(i, i + BATCH_SIZE)));- }- await db.batch(statements as [any, ...any[]]);-}--export async function syncAgentSkills(- db: Database,- agentId: string,- runtime: string,- workspaceId: string,- skills: SkillRow[],-) {- const now = new Date().toISOString();- const rows = skills.map((s) => ({- workspaceId,- agentId,- runtime,- name: s.name,- description: s.description,- syncedAt: now,- }));-- const BATCH_SIZE = 10;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const statements: any[] = [- db.delete(agentSkill).where(- and(eq(agentSkill.agentId, agentId), eq(agentSkill.runtime, runtime))- ),- ];- for (let i = 0; i < rows.length; i += BATCH_SIZE) {- statements.push(db.insert(agentSkill).values(rows.slice(i, i + BATCH_SIZE)));- }- await db.batch(statements as [any, ...any[]]);-}--export async function getSkills(- db: Database,- agentId: string,- runtime: string,- workspaceId: string,-) {- const rows = await db- .select({- name: agentSkill.name,- description: agentSkill.description,- isGlobal: isNull(agentSkill.agentId),- })- .from(agentSkill)- .where(- and(- eq(agentSkill.workspaceId, workspaceId),- eq(agentSkill.runtime, runtime),- or(isNull(agentSkill.agentId), eq(agentSkill.agentId, agentId))- )- );-- // Deduplicate global skills by name (multiple daemons may sync the same skill)- const seen = new Set<string>();- const deduped: typeof rows = [];- for (const row of rows) {- const key = row.isGlobal ? `global:${row.name}` : `agent:${row.name}`;- if (!seen.has(key)) {- seen.add(key);- deduped.push(row);- }- }- return deduped;-}diff --git a/src/shared/src/db/queries/artifact.ts b/src/shared/src/db/queries/artifact.tsdeleted file mode 100644index 86365240a..000000000--- a/src/shared/src/db/queries/artifact.ts+++ /dev/null@@ -1,69 +0,0 @@-import { eq, desc, and } from "drizzle-orm";-import { artifact } from "../schema";-import type { Database } from "../index";-import type { Artifact } from "../../types";--export async function createArtifact(- db: Database,- data: {- id?: string;- conversationId: string;- agentId: string;- workspaceId: string;- filename: string;- contentType: string;- size: number;- r2Key: string;- thumbnailR2Key?: string;- source?: string;- }-) {- const rows = await db.insert(artifact).values(data).returning();- return rows[0]!;-}--export async function listArtifactsByConversation(- db: Database,- conversationId: string,- workspaceId: string,- opts?: { source?: string; limit?: number },-) {- const conditions = [- eq(artifact.conversationId, conversationId),- eq(artifact.workspaceId, workspaceId),- ];- if (opts?.source) {- conditions.push(eq(artifact.source, opts.source));- }- let query = db- .select()- .from(artifact)- .where(and(...conditions))- .orderBy(desc(artifact.createdAt));- if (opts?.limit != null) {- query = query.limit(opts.limit) as typeof query;- }- return query;-}--export async function getArtifact(db: Database, id: string, workspaceId: string) {- const rows = await db- .select()- .from(artifact)- .where(and(eq(artifact.id, id), eq(artifact.workspaceId, workspaceId)));- return rows[0] ?? null;-}--export function artifactToResponse(row: typeof artifact.$inferSelect): Artifact {- return {- id: row.id,- conversation_id: row.conversationId,- agent_id: row.agentId,- filename: row.filename,- content_type: row.contentType,- size: row.size,- source: row.source,- has_thumbnail: row.thumbnailR2Key != null,- created_at: row.createdAt,- };-}diff --git a/src/shared/src/db/queries/calendar-event.ts b/src/shared/src/db/queries/calendar-event.tsdeleted file mode 100644index 755d8b32c..000000000--- a/src/shared/src/db/queries/calendar-event.ts+++ /dev/null@@ -1,351 +0,0 @@-import { eq, and, asc, gte, lte, or, isNull, isNotNull, lt } from "drizzle-orm";-import { agent, calendarEvent } from "../schema";-import type { Database } from "../index";--export async function createCalendarEvent(- db: Database,- data: {- agentId: string;- workspaceId: string;- title: string;- description?: string | null;- scheduledAt: string;- repeatInterval?: string | null;- repeatStopAt?: string | null;- exceptions?: string[];- }-) {- const now = new Date().toISOString();- const rows = await db- .insert(calendarEvent)- .values({- agentId: data.agentId,- workspaceId: data.workspaceId,- title: data.title,- description: data.description ?? null,- scheduledAt: data.scheduledAt,- repeatInterval: data.repeatInterval ?? null,- repeatStopAt: data.repeatStopAt ?? null,- exceptions: data.exceptions ?? [],- createdAt: now,- updatedAt: now,- })- .returning();- return rows[0]!;-}--export async function updateCalendarEvent(- db: Database,- id: string,- workspaceId: string,- patch: {- title?: string;- description?: string | null;- agentId?: string;- scheduledAt?: string;- repeatInterval?: string | null;- repeatStopAt?: string | null;- exceptions?: string[];- }-) {- const rows = await db- .update(calendarEvent)- .set({ ...patch, updatedAt: new Date().toISOString() })- .where(- and(eq(calendarEvent.id, id), eq(calendarEvent.workspaceId, workspaceId))- )- .returning();- return rows[0] ?? null;-}--export async function getCalendarEvent(- db: Database,- id: string,- workspaceId: string,- userId?: string-) {- const conditions = [eq(calendarEvent.id, id), eq(calendarEvent.workspaceId, workspaceId)];- if (userId) {- conditions.push(eq(agent.ownerId, userId));- const rows = await db- .select({ calendarEvent })- .from(calendarEvent)- .innerJoin(agent, eq(calendarEvent.agentId, agent.id))- .where(and(...conditions));- return rows[0]?.calendarEvent ?? null;- }- const rows = await db- .select()- .from(calendarEvent)- .where(and(...conditions));- return rows[0] ?? null;-}--export async function listCalendarEvents(- db: Database,- workspaceId: string,- opts: { userId?: string; agentId?: string; from?: string; to?: string } = {}-) {- const conditions = [eq(calendarEvent.workspaceId, workspaceId)];- if (opts.agentId) conditions.push(eq(calendarEvent.agentId, opts.agentId));- if (opts.userId) conditions.push(eq(agent.ownerId, opts.userId));-- // Exclude completed one-off events: non-recurring events where- // lastTriggeredAt is set and >= scheduledAt are "done".- conditions.push(- or(- isNotNull(calendarEvent.repeatInterval),- isNull(calendarEvent.lastTriggeredAt),- lt(calendarEvent.lastTriggeredAt, calendarEvent.scheduledAt)- )!- );-- if (opts.from && opts.to) {- // Non-recurring rows are bounded strictly by [from, to] on scheduled_at.- // Recurring rows may have scheduled_at before `from` (next fire is- // earlier) but still produce visible occurrences inside the window; they- // qualify when (a) scheduled_at <= to, and (b) repeat_stop_at is null- // or >= from. Expansion happens in the caller.- conditions.push(- or(- and(- isNull(calendarEvent.repeatInterval),- gte(calendarEvent.scheduledAt, opts.from),- lte(calendarEvent.scheduledAt, opts.to)- ),- and(- isNotNull(calendarEvent.repeatInterval),- lte(calendarEvent.scheduledAt, opts.to),- or(- isNull(calendarEvent.repeatStopAt),- gte(calendarEvent.repeatStopAt, opts.from)- )- )- )!- );- } else {- if (opts.from) conditions.push(gte(calendarEvent.scheduledAt, opts.from));- if (opts.to) conditions.push(lte(calendarEvent.scheduledAt, opts.to));- }-- if (opts.userId) {- const rows = await db- .select({ calendarEvent })- .from(calendarEvent)- .innerJoin(agent, eq(calendarEvent.agentId, agent.id))- .where(and(...conditions))- .orderBy(asc(calendarEvent.scheduledAt));- return rows.map(r => r.calendarEvent);- }- return db- .select()- .from(calendarEvent)- .where(and(...conditions))- .orderBy(asc(calendarEvent.scheduledAt));-}--export async function deleteCalendarEvent(- db: Database,- id: string,- workspaceId: string-) {- const rows = await db- .delete(calendarEvent)- .where(- and(eq(calendarEvent.id, id), eq(calendarEvent.workspaceId, workspaceId))- )- .returning();- return rows[0] ?? null;-}--/**- * Return candidate due events for a workspace. Does not write — callers must- * issue the guarded claim UPDATE to promote an event to a task.- */-export async function listDueCalendarEvents(- db: Database,- workspaceId: string,- now: string-) {- return db- .select()- .from(calendarEvent)- .where(- and(- eq(calendarEvent.workspaceId, workspaceId),- lte(calendarEvent.scheduledAt, now),- or(- isNull(calendarEvent.lastTriggeredAt),- lt(calendarEvent.lastTriggeredAt, calendarEvent.scheduledAt)- )- )- )- .orderBy(asc(calendarEvent.scheduledAt));-}--/**- * Exact-occurrence guarded claim. Returns the number of rows affected (0 or 1).- * Only one concurrent caller can transition `last_triggered_at` past the- * observed `scheduled_at`; every other caller sees 0.- */-export async function claimCalendarEvent(- db: Database,- id: string,- observedScheduledAt: string,- now: string-) {- const rows = await db- .update(calendarEvent)- .set({ lastTriggeredAt: now, updatedAt: now })- .where(- and(- eq(calendarEvent.id, id),- eq(calendarEvent.scheduledAt, observedScheduledAt),- or(- isNull(calendarEvent.lastTriggeredAt),- lt(calendarEvent.lastTriggeredAt, calendarEvent.scheduledAt)- )- )- )- .returning();- return rows[0] ?? null;-}--/** Revert `last_triggered_at` to its pre-claim value after a post-claim failure. */-export async function revertCalendarEventClaim(- db: Database,- id: string,- previousLastTriggeredAt: string | null-) {- await db- .update(calendarEvent)- .set({- lastTriggeredAt: previousLastTriggeredAt,- updatedAt: new Date().toISOString(),- })- .where(eq(calendarEvent.id, id));-}--/**- * Advance `scheduled_at` to the next future occurrence, or null when the event- * has stopped. Used by the promotion helper after a successful claim.- */-export async function updateCalendarEventSchedule(- db: Database,- id: string,- nextScheduledAt: string-) {- await db- .update(calendarEvent)- .set({ scheduledAt: nextScheduledAt, updatedAt: new Date().toISOString() })- .where(eq(calendarEvent.id, id));-}--/**- * Repeat-interval grammar: `<positive_integer><min|hour|day|week|month>`.- *- * Monthly overflow clamp: Jan 31 + 1 month = Feb 28 (or 29 in leap years).- * Week is treated as 7 days.- */-export function addRepeatInterval(base: Date, interval: string): Date {- const match = /^(\d+)(min|hour|day|week|month)$/.exec(interval);- if (!match) throw new Error(`invalid repeat_interval: ${interval}`);- const amount = parseInt(match[1]!, 10);- const unit = match[2]!;-- if (unit === "min") return new Date(base.getTime() + amount * 60_000);- if (unit === "hour") return new Date(base.getTime() + amount * 3_600_000);- if (unit === "day") return new Date(base.getTime() + amount * 86_400_000);- if (unit === "week") return new Date(base.getTime() + amount * 7 * 86_400_000);- // month — clamp overflow- const y = base.getUTCFullYear();- const m = base.getUTCMonth() + amount;- const targetYear = y + Math.floor(m / 12);- const targetMonth = ((m % 12) + 12) % 12;- const day = base.getUTCDate();- const lastDayOfTarget = new Date(Date.UTC(targetYear, targetMonth + 1, 0)).getUTCDate();- const clampedDay = Math.min(day, lastDayOfTarget);- return new Date(- Date.UTC(- targetYear,- targetMonth,- clampedDay,- base.getUTCHours(),- base.getUTCMinutes(),- base.getUTCSeconds(),- base.getUTCMilliseconds()- )- );-}--/**- * Loop-advance the schedule past `now`. Returns the next `scheduled_at` as an- * ISO string, or null if the next occurrence would exceed `repeatStopAt` (in- * which case the event becomes inert).- */-/**- * Expand a recurring calendar-event row into the list of occurrence ISOs- * within `[from, to]`, skipping `exceptions`. Starts at `scheduledAt` and- * steps forward by `repeatInterval`. Capped at 1000 iterations to guard- * against pathological inputs.- */-export function expandOccurrences(- scheduledAt: string,- repeatInterval: string,- repeatStopAt: string | null,- exceptions: string[],- from: string,- to: string-): string[] {- const out: string[] = [];- const fromD = new Date(from);- const toD = new Date(to);- const stopD = repeatStopAt ? new Date(repeatStopAt) : null;- const excepted = new Set(exceptions);- let current = new Date(scheduledAt);- for (let i = 0; i < 1000; i++) {- if (current > toD) break;- if (stopD && current > stopD) break;- const iso = current.toISOString();- if (current >= fromD && !excepted.has(iso)) out.push(iso);- current = addRepeatInterval(current, repeatInterval);- }- return out;-}--/**- * Returns how many times a recurring event fires per day.- * Used to decide whether to collapse high-frequency events (threshold: >5/day).- */-export function getOccurrencesPerDay(repeatInterval: string): number {- const match = /^(\d+)(min|hour|day|week|month)$/.exec(repeatInterval);- if (!match) return 1;- const amount = parseInt(match[1]!, 10);- const unit = match[2]!;- if (unit === "month" || unit === "week" || unit === "day") return 1;- if (amount === 0) return 1;- const intervalSeconds = unit === "min" ? amount * 60 : amount * 3600;- return Math.floor(86400 / intervalSeconds);-}--export function computeNextScheduledAt(- currentScheduledAt: string,- repeatInterval: string,- repeatStopAt: string | null,- now: string,- exceptions: string[] = []-): string | null {- const excepted = new Set(exceptions);- let next = addRepeatInterval(new Date(currentScheduledAt), repeatInterval);- const nowDate = new Date(now);- const stopDate = repeatStopAt ? new Date(repeatStopAt) : null;- // Cap iterations to prevent runaway loops on pathological inputs.- for (let i = 0; i < 2000; i++) {- if (stopDate && next > stopDate) return null;- if (next > nowDate && !excepted.has(next.toISOString())) {- return next.toISOString();- }- next = addRepeatInterval(next, repeatInterval);- }- return null;-}diff --git a/src/shared/src/db/queries/channel.ts b/src/shared/src/db/queries/channel.tsdeleted file mode 100644index 302e88e89..000000000--- a/src/shared/src/db/queries/channel.ts+++ /dev/null@@ -1,132 +0,0 @@-import { eq, and, asc, sql } from "drizzle-orm";-import { channel, conversation } from "../schema";-import type { Database } from "../index";-import { deleteUnreadByChannel } from "./inbox";--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]!;-}--export async function listChannels(db: Database, workspaceId: string) {- return db- .select()- .from(channel)- .where(eq(channel.workspaceId, workspaceId))- .orderBy(asc(channel.position));-}--export async function getChannelByName(- db: Database,- workspaceId: string,- name: string-) {- const rows = await db- .select()- .from(channel)- .where(- and(eq(channel.workspaceId, workspaceId), eq(channel.name, name))- );- return rows[0] ?? null;-}--export async function getChannelById(- db: Database,- id: string,- workspaceId: string-) {- const rows = await db- .select()- .from(channel)- .where(and(eq(channel.id, id), eq(channel.workspaceId, workspaceId)));- return rows[0] ?? null;-}--export async function deleteChannel(- db: Database,- id: string,- workspaceId: string-) {- const row = await getChannelById(db, id, workspaceId);- if (!row) return null;-- await deleteUnreadByChannel(db, workspaceId, row.name);- await db.batch([- db- .delete(conversation)- .where(- and(- eq(conversation.workspaceId, workspaceId),- eq(conversation.channel, row.name)- )- ),- db- .delete(channel)- .where(and(eq(channel.id, id), eq(channel.workspaceId, workspaceId))),- ]);-- return row;-}--export async function renameChannel(- db: Database,- id: string,- workspaceId: string,- newName: string-) {- const row = await getChannelById(db, id, workspaceId);- if (!row) return null;-- await db.batch([- db- .update(conversation)- .set({ channel: newName })- .where(- and(- eq(conversation.workspaceId, workspaceId),- eq(conversation.channel, row.name)- )- ),- db- .update(channel)- .set({ name: newName })- .where(and(eq(channel.id, id), eq(channel.workspaceId, workspaceId))),- ]);-- 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/community/bot.ts b/src/shared/src/db/queries/community/bot.tsindex ab4a24842..c4fdcfba8 100644--- a/src/shared/src/db/queries/community/bot.ts+++ b/src/shared/src/db/queries/community/bot.ts@@ -25,7 +25,6 @@ import {communityAgentRunnerKey,} from "../../community-machine-schema";import {- communityBotApprovalRequest,communityServerMember,communityUserProfile,communityReadState,@@ -1536,141 +1535,6 @@ export async function assertNoLiveBots(}}-// ─── Approval requests ──────────────────────────────────────────────────────--// After migration 0065 the friend kind is gone (folded into-// community_friendship). Only join_server approval workflows remain.-export type ApprovalKind = "join_server";-export type ApprovalStatus = "pending" | "approved" | "denied";--export type ApprovalRequestRow = {- id: string;- botId: string;- kind: ApprovalKind;- serverId: string | null;- requestedByUserId: string;- dmMessageId: string;- status: ApprovalStatus;- createdAt: string;- resolvedAt: string | null;-};--export async function getApprovalRequest(- db: Database,- id: string-): Promise<ApprovalRequestRow | null> {- const rows = await db- .select()- .from(communityBotApprovalRequest)- .where(eq(communityBotApprovalRequest.id, id))- .limit(1);- return (rows[0] as ApprovalRequestRow | undefined) ?? null;-}--export async function listPendingApprovalsForBot(- db: Database,- botId: string-): Promise<ApprovalRequestRow[]> {- return (await db- .select()- .from(communityBotApprovalRequest)- .where(- and(- eq(communityBotApprovalRequest.botId, botId),- eq(communityBotApprovalRequest.status, "pending")- )- )) as ApprovalRequestRow[];-}--/**- * Look up pending join_server approval for a given (botId, serverId). Used- * as an idempotency guard before we write a duplicate DM card.- */-export async function findPendingJoinRequest(- db: Database,- botId: string,- serverId: string-): Promise<ApprovalRequestRow | null> {- const rows = await db- .select()- .from(communityBotApprovalRequest)- .where(- and(- eq(communityBotApprovalRequest.botId, botId),- eq(communityBotApprovalRequest.serverId, serverId),- eq(communityBotApprovalRequest.kind, "join_server"),- eq(communityBotApprovalRequest.status, "pending")- )- )- .limit(1);- return (rows[0] as ApprovalRequestRow | undefined) ?? null;-}--/**- * Statement-returning insert. Application layer enforces the- * `kind = "join_server" ⇔ serverId != null` invariant (SQLite CHECK can't- * cross-reference other tables cleanly). After migration 0065 only- * `kind='join_server'` is supported — the friend flow lives in- * `community_friendship`.- */-export function createApprovalRequestStatement(- db: Database,- data: {- botId: string;- kind: ApprovalKind;- serverId: string | null;- requestedByUserId: string;- dmMessageId: string;- }-) {- if (data.kind === "join_server" && !data.serverId) {- throw new Error("createApprovalRequest: join_server requires serverId");- }- return db.insert(communityBotApprovalRequest).values({- botId: data.botId,- kind: data.kind,- serverId: data.serverId,- requestedByUserId: data.requestedByUserId,- dmMessageId: data.dmMessageId,- status: "pending",- createdAt: new Date().toISOString(),- });-}--export async function resolveApprovalRequest(- db: Database,- id: string,- status: "approved" | "denied"-): Promise<ApprovalRequestRow | null> {- const rows = await db- .update(communityBotApprovalRequest)- .set({ status, resolvedAt: new Date().toISOString() })- .where(- and(- eq(communityBotApprovalRequest.id, id),- eq(communityBotApprovalRequest.status, "pending")- )- )- .returning();- return (rows[0] as ApprovalRequestRow | undefined) ?? null;-}--/**- * Lookup an approval request row by its DM message id. Used by the DM card- * hydrator to render approve/deny/approved/denied variants.- */-export async function getApprovalRequestByDmMessageId(- db: Database,- dmMessageId: string-): Promise<ApprovalRequestRow | null> {- const rows = await db- .select()- .from(communityBotApprovalRequest)- .where(eq(communityBotApprovalRequest.dmMessageId, dmMessageId))- .limit(1);- return (rows[0] as ApprovalRequestRow | undefined) ?? null;-}-// ─── Machine cascade helpers ─────────────────────────────────────────────/**diff --git a/src/shared/src/db/queries/community/search.ts b/src/shared/src/db/queries/community/search.tsdeleted file mode 100644index f1660b9f3..000000000--- a/src/shared/src/db/queries/community/search.ts+++ /dev/null@@ -1,105 +0,0 @@-import { eq, and, desc, inArray, sql } from "drizzle-orm";-import { communityMessage, communityChannel } from "../../community-schema";-import { user } from "../../schema";-import type { Database } from "../../index";-import { escapeLikePattern } from "../../../utils/sql-like";-import { jsonTextSet } from "../_json-set";--const DEFAULT_LIMIT = 50;--const FTS_KEYWORDS = new Set(["and", "or", "not", "near"]);--/** Sanitize user input for FTS5 MATCH — each term gets prefix matching with implicit AND. */-export function sanitizeFtsQuery(query: string): string {- const terms = query- .replace(/["\-*()^~{}[\]:.!?,;@#$%&/\\]/g, " ")- .split(/\s+/)- .filter((t) => t && !FTS_KEYWORDS.has(t.toLowerCase()));- if (terms.length === 0) return '""';- return terms.map((t) => `"${t}"*`).join(" ");-}--export async function searchMessages(- db: Database,- opts: {- query: string;- channelId?: string;- serverId?: string;- // Scope for the server branch — the caller's visible channel ids- // (public/uncategorized ∪ private-where-member). Enforced in SQL so- // private-channel content never leaks into server-wide search results.- visibleChannelIds?: string[];- limit?: number;- }-) {- const limit = opts.limit ?? DEFAULT_LIMIT;-- if (opts.serverId) {- return searchMessagesInServer(db, {- query: opts.query,- serverId: opts.serverId,- visibleChannelIds: opts.visibleChannelIds,- limit,- });- }-- const pattern = `%${escapeLikePattern(opts.query)}%`;- const conditions = [sql`${communityMessage.content} LIKE ${pattern} ESCAPE '\\'`];- if (opts.channelId) {- conditions.push(eq(communityMessage.channelId, opts.channelId));- }-- return db- .select({- message: communityMessage,- author: user,- })- .from(communityMessage)- .innerJoin(user, eq(communityMessage.authorId, user.id))- .where(and(...conditions))- .orderBy(desc(communityMessage.createdAt))- .limit(limit);-}--export async function searchMessagesInServer(- db: Database,- opts: {- query: string;- serverId: string;- // The caller's visible channel ids — scopes the search so private-channel- // content the viewer can't see never appears. `undefined` means "not- // scoped" (internal/trusted callers only); the community search route- // ALWAYS passes it. An empty array yields zero results.- visibleChannelIds?: string[];- limit?: number;- }-) {- const limit = opts.limit ?? DEFAULT_LIMIT;-- if (opts.visibleChannelIds && opts.visibleChannelIds.length === 0) return [];-- const pattern = `%${escapeLikePattern(opts.query)}%`;- const baseConditions = [- sql`${communityMessage.content} LIKE ${pattern} ESCAPE '\\'`,- eq(communityChannel.serverId, opts.serverId),- ];-- if (opts.visibleChannelIds !== undefined) {- baseConditions.push(inArray(communityMessage.channelId, jsonTextSet(db, opts.visibleChannelIds)));- }-- return db- .select({- message: communityMessage,- author: user,- })- .from(communityMessage)- .innerJoin(user, eq(communityMessage.authorId, user.id))- .innerJoin(- communityChannel,- eq(communityMessage.channelId, communityChannel.id)- )- .where(and(...baseConditions))- .orderBy(desc(communityMessage.createdAt))- .limit(limit);-}diff --git a/src/shared/src/db/queries/community/server-folder.ts b/src/shared/src/db/queries/community/server-folder.tsindex cb60962e4..b31adb103 100644--- a/src/shared/src/db/queries/community/server-folder.ts+++ b/src/shared/src/db/queries/community/server-folder.ts@@ -1,135 +1,10 @@-import { eq, and, asc, sql } from "drizzle-orm";+import { eq, asc } from "drizzle-orm";import {communityServerFolder,communityServerFolderItem,communityServer,} from "../../community-schema";import type { Database } from "../../index";-import { chunk, maxRowsPerInsert } from "../_chunk";--// communityServerFolderItem emits 3 bind params/row (folder_id, server_id,-// position), so a single INSERT caps at floor(100/3)=33 rows for D1's limit.-const FOLDER_ITEM_INSERT_MAX_ROWS = maxRowsPerInsert(3);--export async function createFolder(- db: Database,- data: { userId: string; name: string; serverIds?: string[] }-) {- const maxPos = await db- .select({ m: sql<number>`coalesce(max(${communityServerFolder.position}), -1)` })- .from(communityServerFolder)- .where(eq(communityServerFolder.userId, data.userId));-- const [folder] = await db- .insert(communityServerFolder)- .values({- userId: data.userId,- name: data.name,- position: (maxPos[0]?.m ?? -1) + 1,- })- .returning();-- if (data.serverIds && data.serverIds.length > 0) {- await insertFolderItems(db, folder!.id, data.serverIds);- }-- return folder!;-}--export async function getFolder(- db: Database,- folderId: string,- userId: string-) {- const rows = await db- .select()- .from(communityServerFolder)- .where(- and(- eq(communityServerFolder.id, folderId),- eq(communityServerFolder.userId, userId)- )- );- return rows[0] ?? null;-}--export async function updateFolder(- db: Database,- folderId: string,- data: { name?: string }-) {- if (data.name !== undefined) {- await db- .update(communityServerFolder)- .set({ name: data.name })- .where(eq(communityServerFolder.id, folderId));- }-}--export async function replaceFolderItems(- db: Database,- folderId: string,- serverIds: string[]-) {- await db- .delete(communityServerFolderItem)- .where(eq(communityServerFolderItem.folderId, folderId));-- if (serverIds.length > 0) {- await insertFolderItems(db, folderId, serverIds);- }-}--// Bulk-insert folder items, chunked so no INSERT exceeds D1's 100-param limit.-// `position` is the item's index in the FULL list, preserved across chunks.-async function insertFolderItems(- db: Database,- folderId: string,- serverIds: string[]-) {- const items = serverIds.map((serverId, idx) => ({- folderId,- serverId,- position: idx,- }));- for (const batch of chunk(items, FOLDER_ITEM_INSERT_MAX_ROWS)) {- await db.insert(communityServerFolderItem).values(batch);- }-}--export async function deleteFolder(db: Database, folderId: string) {- await db- .delete(communityServerFolder)- .where(eq(communityServerFolder.id, folderId));-}--export async function deleteAllFolders(db: Database, userId: string) {- await db- .delete(communityServerFolder)- .where(eq(communityServerFolder.userId, userId));-}--export async function reorderFolders(- db: Database,- userId: string,- folderIds: string[]-) {- const statements = folderIds.map((id, i) =>- db- .update(communityServerFolder)- .set({ position: i })- .where(- and(- eq(communityServerFolder.id, id),- eq(communityServerFolder.userId, userId)- )- )- );- if (statements.length > 0) {- await db.batch(statements as [typeof statements[0], ...typeof statements]);- }-}-export async function listFolders(db: Database, userId: string) {const folderRows = await db.select()diff --git a/src/shared/src/db/queries/issue-comment.ts b/src/shared/src/db/queries/issue-comment.tsdeleted file mode 100644index e6fcec2f3..000000000--- a/src/shared/src/db/queries/issue-comment.ts+++ /dev/null@@ -1,72 +0,0 @@-import { and, asc, eq } from "drizzle-orm";-import { issueComment } from "../schema";-import type { Database } from "../index";--export async function createComment(- db: Database,- data: {- issueId: string;- workspaceId: string;- authorType: "user" | "agent";- authorId: string;- content: string;- }-) {- const rows = await db- .insert(issueComment)- .values({- issueId: data.issueId,- workspaceId: data.workspaceId,- authorType: data.authorType,- authorId: data.authorId,- content: data.content,- })- .returning();- return rows[0]!;-}--export async function listComments(- db: Database,- issueId: string,- workspaceId: string-) {- return db- .select()- .from(issueComment)- .where(- and(- eq(issueComment.issueId, issueId),- eq(issueComment.workspaceId, workspaceId)- )- )- .orderBy(asc(issueComment.createdAt));-}--export async function deleteComment(- db: Database,- id: string,- workspaceId: string-) {- const rows = await db- .delete(issueComment)- .where(- and(- eq(issueComment.id, id),- eq(issueComment.workspaceId, workspaceId)- )- )- .returning();- return rows[0] ?? null;-}--export function commentToResponse(row: typeof issueComment.$inferSelect) {- return {- id: row.id,- issue_id: row.issueId,- workspace_id: row.workspaceId,- author_type: row.authorType as "user" | "agent",- author_id: row.authorId,- content: row.content,- created_at: row.createdAt,- };-}diff --git a/src/shared/src/db/queries/message-flag.ts b/src/shared/src/db/queries/message-flag.tsdeleted file mode 100644index c2e01e6ae..000000000--- a/src/shared/src/db/queries/message-flag.ts+++ /dev/null@@ -1,137 +0,0 @@-import { eq, and, sql } from "drizzle-orm";-import { messageFlag, message, conversation } from "../schema";-import type { Database } from "../index";--export async function getMessageWorkspaceId(- db: Database,- messageId: string-): Promise<string | null> {- const rows = await db- .select({ workspaceId: conversation.workspaceId })- .from(message)- .innerJoin(conversation, eq(conversation.id, message.conversationId))- .where(eq(message.id, messageId))- .limit(1);- return rows[0]?.workspaceId ?? null;-}--export async function flagMessage(- db: Database,- data: { messageId: string; userId: string; workspaceId: string }-) {- const rows = await db- .insert(messageFlag)- .values(data)- .onConflictDoNothing()- .returning();- return rows[0] ?? null;-}--export async function unflagMessage(- db: Database,- messageId: string,- userId: string,- workspaceId: string-) {- const rows = await db- .delete(messageFlag)- .where(- and(- eq(messageFlag.messageId, messageId),- eq(messageFlag.userId, userId),- eq(messageFlag.workspaceId, workspaceId)- )- )- .returning();- return rows[0] ?? null;-}--export async function listFlaggedMessages(- db: Database,- userId: string,- workspaceId: string,- opts?: { limit?: number; before?: string }-) {- const limit = opts?.limit ?? 30;- const beforeClause = opts?.before- ? sql`AND mf.created_at < ${opts.before}`- : sql``;-- const rows = await db.all<{- id: string;- message_id: string;- message_content: string;- message_role: string;- message_created_at: string;- conversation_id: string;- conversation_title: string;- agent_id: string;- agent_name: string | null;- agent_avatar_url: string | null;- flagged_at: string;- }>(sql`- SELECT- mf.id,- mf.message_id,- m.content AS message_content,- m.role AS message_role,- m.created_at AS message_created_at,- c.id AS conversation_id,- c.title AS conversation_title,- c.agent_id,- a.name AS agent_name,- a.avatar_url AS agent_avatar_url,- mf.created_at AS flagged_at- FROM message_flag mf- INNER JOIN message m ON m.id = mf.message_id- INNER JOIN conversation c ON c.id = m.conversation_id- LEFT JOIN agent a ON a.id = c.agent_id AND a.workspace_id = c.workspace_id- WHERE mf.user_id = ${userId}- AND mf.workspace_id = ${workspaceId}- ${beforeClause}- ORDER BY mf.created_at DESC- LIMIT ${limit + 1}- `);-- const hasMore = rows.length > limit;- const items = rows.slice(0, limit);-- return { items, hasMore };-}--export async function getFlaggedCount(- db: Database,- userId: string,- workspaceId: string-) {- const rows = await db- .select({ count: sql<number>`COUNT(*)` })- .from(messageFlag)- .where(- and(- eq(messageFlag.userId, userId),- eq(messageFlag.workspaceId, workspaceId)- )- );- return rows[0]?.count ?? 0;-}--export async function listFlaggedMessageIds(- db: Database,- userId: string,- workspaceId: string,- conversationId: string-) {- const rows = await db- .select({ messageId: messageFlag.messageId })- .from(messageFlag)- .innerJoin(message, eq(message.id, messageFlag.messageId))- .where(- and(- eq(messageFlag.userId, userId),- eq(messageFlag.workspaceId, workspaceId),- eq(message.conversationId, conversationId)- )- );- return rows.map((r) => r.messageId);-}diff --git a/src/shared/src/db/queries/overview.ts b/src/shared/src/db/queries/overview.tsdeleted file mode 100644index 9b5dec1a9..000000000--- a/src/shared/src/db/queries/overview.ts+++ /dev/null@@ -1,115 +0,0 @@-import { eq, and, count, desc, inArray, ne, sql } from "drizzle-orm";-import { emails, agentEmailAccount, agentTaskQueue, conversation } from "../schema";-import type { Database } from "../index";-import { TASK_TYPES } from "../../constants";-import { jsonTextSet } from "./_json-set";--export async function getEmailStatsByWorkspace(db: Database, workspaceId: string) {- const [stats] = await db- .select({- inbound: sql<number>`sum(case when ${emails.direction} = 'inbound' then 1 else 0 end)`,- outbound: sql<number>`sum(case when ${emails.direction} = 'outbound' then 1 else 0 end)`,- unread: sql<number>`sum(case when ${emails.status} = 'unread' and ${emails.direction} = 'inbound' then 1 else 0 end)`,- rejected: sql<number>`sum(case when ${emails.isWhitelisted} = 0 and ${emails.direction} = 'inbound' then 1 else 0 end)`,- })- .from(emails)- .where(eq(emails.workspaceId, workspaceId));-- return {- inbound: Number(stats?.inbound ?? 0),- outbound: Number(stats?.outbound ?? 0),- unread: Number(stats?.unread ?? 0),- rejected: Number(stats?.rejected ?? 0),- };-}--export async function getEmailAccountsByWorkspace(db: Database, workspaceId: string) {- return db- .select({- id: agentEmailAccount.id,- agentId: agentEmailAccount.agentId,- emailAddress: agentEmailAccount.emailAddress,- status: agentEmailAccount.status,- errorMessage: agentEmailAccount.errorMessage,- lastSyncedAt: agentEmailAccount.lastSyncedAt,- })- .from(agentEmailAccount)- .where(eq(agentEmailAccount.workspaceId, workspaceId));-}--export async function getTaskStatsByWorkspace(- db: Database,- workspaceId: string,- todayStart: string-) {- const staleThreshold = new Date(Date.now() - 3600 * 1000).toISOString();-- const [stats] = await db- .select({- completed: sql<number>`sum(case when ${agentTaskQueue.status} = 'completed' and ${agentTaskQueue.type} != ${TASK_TYPES.KILL_TASK} and ${agentTaskQueue.completedAt} >= ${todayStart} then 1 else 0 end)`,- failed: sql<number>`sum(case when ${agentTaskQueue.status} = 'failed' and ${agentTaskQueue.type} != ${TASK_TYPES.KILL_TASK} and ${agentTaskQueue.completedAt} >= ${todayStart} then 1 else 0 end)`,- cancelled: sql<number>`sum(case when ${agentTaskQueue.status} = 'cancelled' and ${agentTaskQueue.type} != ${TASK_TYPES.KILL_TASK} and ${agentTaskQueue.completedAt} >= ${todayStart} then 1 else 0 end)`,- queued: sql<number>`sum(case when ${agentTaskQueue.status} = 'queued' and ${agentTaskQueue.type} != ${TASK_TYPES.KILL_TASK} then 1 else 0 end)`,- stale: sql<number>`sum(case when ${agentTaskQueue.status} = 'running' and ${agentTaskQueue.startedAt} < ${staleThreshold} then 1 else 0 end)`,- })- .from(agentTaskQueue)- .where(eq(agentTaskQueue.workspaceId, workspaceId));-- return {- completed: Number(stats?.completed ?? 0),- failed: Number(stats?.failed ?? 0),- cancelled: Number(stats?.cancelled ?? 0),- queued: Number(stats?.queued ?? 0),- stale: Number(stats?.stale ?? 0),- };-}--export async function getRecentTerminalTasks(- db: Database,- workspaceId: string,- visibleAgentIds: string[],- limit = 15-) {- if (visibleAgentIds.length === 0) return [];- const agentIds = jsonTextSet(db, [...new Set(visibleAgentIds)]);- return db- .select({- id: agentTaskQueue.id,- agentId: agentTaskQueue.agentId,- type: agentTaskQueue.type,- status: agentTaskQueue.status,- prompt: agentTaskQueue.prompt,- createdAt: agentTaskQueue.createdAt,- completedAt: agentTaskQueue.completedAt,- error: agentTaskQueue.error,- })- .from(agentTaskQueue)- .where(- and(- eq(agentTaskQueue.workspaceId, workspaceId),- inArray(agentTaskQueue.agentId, agentIds),- ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),- inArray(agentTaskQueue.status, ["completed", "failed", "cancelled"])- )- )- .orderBy(desc(agentTaskQueue.completedAt))- .limit(limit);-}--export async function getConversationCountsByAgent(db: Database, workspaceId: string, visibleAgentIds: string[]) {- if (visibleAgentIds.length === 0) return [];- const agentIds = jsonTextSet(db, [...new Set(visibleAgentIds)]);- return db- .select({- agentId: conversation.agentId,- cnt: count(),- })- .from(conversation)- .where(- and(- eq(conversation.workspaceId, workspaceId),- inArray(conversation.agentId, agentIds)- )- )- .groupBy(conversation.agentId);-}diff --git a/src/shared/src/db/queries/task-message.ts b/src/shared/src/db/queries/task-message.tsdeleted file mode 100644index 1f24f04b6..000000000--- a/src/shared/src/db/queries/task-message.ts+++ /dev/null@@ -1,116 +0,0 @@-import { eq, and, gt, asc, notInArray } from "drizzle-orm";-import { taskMessage, agentTaskQueue } from "../schema";-import type { Database } from "../index";--export async function createTaskMessage(- db: Database,- data: {- taskId: string;- seq: number;- type: string;- tool: string;- callId?: string;- content: string;- input?: unknown;- output: string;- }-) {- const rows = await db- .insert(taskMessage)- .values({- taskId: data.taskId,- seq: data.seq,- type: data.type,- tool: data.tool,- callId: data.callId || "",- content: data.content,- input: data.input ?? null,- output: data.output,- })- .returning();- return rows[0]!;-}--export async function listTaskMessages(db: Database, taskId: string, workspaceId?: string) {- if (workspaceId) {- return db- .select({- id: taskMessage.id,- taskId: taskMessage.taskId,- seq: taskMessage.seq,- type: taskMessage.type,- tool: taskMessage.tool,- content: taskMessage.content,- callId: taskMessage.callId,- input: taskMessage.input,- output: taskMessage.output,- createdAt: taskMessage.createdAt,- })- .from(taskMessage)- .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))- // Exclude tool-result/tool-use/thinking from the READ side only: the UI- // doesn't render them. They ARE still written (see daemon messages route)- // and retained for future data analysis — do NOT take this filter as a- // sign the rows are dead and stop persisting them.- .where(and(eq(taskMessage.taskId, taskId), eq(agentTaskQueue.workspaceId, workspaceId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))- .orderBy(asc(taskMessage.seq));- }- return db- .select()- .from(taskMessage)- // Read-side UI exclusion only; rows are still stored for analysis (see above).- .where(and(eq(taskMessage.taskId, taskId), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))- .orderBy(asc(taskMessage.seq));-}--// Errors-only, workspace-scoped: the chat init routes preload only `type:"error"`-// rows so a persisted error survives a reload (the rest of a run's messages arrive-// live via the task.messages WS broadcast / send-dm). Filtering in SQL keeps the-// route's hot path lean and the workspace join enforces scoping. Kept separate-// from listTaskMessages (which is the UI-exclusion read) on purpose.-export async function listTaskErrorMessages(- db: Database,- taskId: string,- workspaceId: string-) {- return db- .select({- id: taskMessage.id,- taskId: taskMessage.taskId,- seq: taskMessage.seq,- type: taskMessage.type,- tool: taskMessage.tool,- content: taskMessage.content,- callId: taskMessage.callId,- input: taskMessage.input,- output: taskMessage.output,- createdAt: taskMessage.createdAt,- })- .from(taskMessage)- .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))- .where(- and(- eq(taskMessage.taskId, taskId),- eq(agentTaskQueue.workspaceId, workspaceId),- eq(taskMessage.type, "error")- )- )- .orderBy(asc(taskMessage.seq));-}--export async function listTaskMessagesSince(- db: Database,- taskId: string,- afterSeq: number-) {- return db- .select()- .from(taskMessage)- // Read-side UI exclusion only; rows are still stored for analysis (see listTaskMessages).- .where(and(eq(taskMessage.taskId, taskId), gt(taskMessage.seq, afterSeq), notInArray(taskMessage.type, ["tool-result", "tool-use", "thinking"])))- .orderBy(asc(taskMessage.seq));-}--export async function deleteTaskMessages(db: Database, taskId: string) {- await db.delete(taskMessage).where(eq(taskMessage.taskId, taskId));-}diff --git a/src/shared/src/db/queries/workspace-file-request.ts b/src/shared/src/db/queries/workspace-file-request.tsdeleted file mode 100644index 7ae4995c8..000000000--- a/src/shared/src/db/queries/workspace-file-request.ts+++ /dev/null@@ -1,86 +0,0 @@-import { eq, and, inArray, lt } from "drizzle-orm";-import { workspaceFileRequest } from "../schema";-import type { Database } from "../index";-import { chunk, D1_MAX_IN_PARAMS } from "./_chunk";--export async function createRequest(- db: Database,- data: {- workspaceId: string;- agentId: string;- requestType: string;- path: string;- },-) {- const rows = await db- .insert(workspaceFileRequest)- .values(data)- .returning();- return rows[0]!;-}--export async function getPendingByWorkspace(- db: Database,- workspaceId: string,-) {- return db- .select()- .from(workspaceFileRequest)- .where(- and(- eq(workspaceFileRequest.workspaceId, workspaceId),- eq(workspaceFileRequest.status, "pending"),- ),- );-}--export async function markDispatched(db: Database, ids: string[]) {- if (ids.length === 0) return;- // `ids` come from `getPendingByWorkspace` (unbounded SELECT, no LIMIT). Chunk- // the `inArray` for D1's 100-param limit — the UPDATE also binds status +- // updatedAt, so D1_MAX_IN_PARAMS (90) leaves headroom.- const now = new Date().toISOString();- for (const batch of chunk(ids, D1_MAX_IN_PARAMS)) {- await db- .update(workspaceFileRequest)- .set({ status: "dispatched", updatedAt: now })- .where(inArray(workspaceFileRequest.id, batch));- }-}--export async function completeRequest(- db: Database,- id: string,- result: unknown,-) {- const rows = await db- .update(workspaceFileRequest)- .set({- status: "completed",- result: JSON.stringify(result),- updatedAt: new Date().toISOString(),- })- .where(eq(workspaceFileRequest.id, id))- .returning();- return rows[0] ?? null;-}--export async function getRequest(db: Database, id: string) {- const rows = await db- .select()- .from(workspaceFileRequest)- .where(eq(workspaceFileRequest.id, id));- return rows[0] ?? null;-}--export async function expireStale(db: Database, workspaceId: string) {- const cutoff = new Date(Date.now() - 30_000).toISOString();- await db- .delete(workspaceFileRequest)- .where(- and(- eq(workspaceFileRequest.workspaceId, workspaceId),- lt(workspaceFileRequest.createdAt, cutoff),- ),- );-}diff --git a/src/shared/src/db/queries/workspace-invite.ts b/src/shared/src/db/queries/workspace-invite.tsdeleted file mode 100644index f14246291..000000000--- a/src/shared/src/db/queries/workspace-invite.ts+++ /dev/null@@ -1,83 +0,0 @@-import { eq, and, gt, isNull } from "drizzle-orm";-import { workspaceInvite, workspace, user } from "../schema";-import type { Database } from "../index";--export async function createInvite(- db: Database,- data: { workspaceId: string; createdBy: string; expiresAt: string }-) {- const rows = await db- .insert(workspaceInvite)- .values({- workspaceId: data.workspaceId,- createdBy: data.createdBy,- expiresAt: data.expiresAt,- })- .returning();- return rows[0]!;-}--export async function getInviteByToken(db: Database, token: string) {- const rows = await db- .select({- id: workspaceInvite.id,- workspaceId: workspaceInvite.workspaceId,- token: workspaceInvite.token,- createdBy: workspaceInvite.createdBy,- usedBy: workspaceInvite.usedBy,- usedAt: workspaceInvite.usedAt,- expiresAt: workspaceInvite.expiresAt,- createdAt: workspaceInvite.createdAt,- workspaceName: workspace.name,- workspaceSlug: workspace.slug,- creatorName: user.name,- creatorEmail: user.email,- })- .from(workspaceInvite)- .innerJoin(workspace, eq(workspaceInvite.workspaceId, workspace.id))- .innerJoin(user, eq(workspaceInvite.createdBy, user.id))- .where(eq(workspaceInvite.token, token));- return rows[0] ?? null;-}--export async function listActiveInvites(db: Database, workspaceId: string) {- return db- .select()- .from(workspaceInvite)- .where(- and(- eq(workspaceInvite.workspaceId, workspaceId),- isNull(workspaceInvite.usedBy),- gt(workspaceInvite.expiresAt, new Date().toISOString())- )- );-}--export async function redeemInvite(db: Database, token: string, userId: string) {- const now = new Date().toISOString();- const rows = await db- .update(workspaceInvite)- .set({ usedBy: userId, usedAt: now })- .where(- and(- eq(workspaceInvite.token, token),- isNull(workspaceInvite.usedBy),- gt(workspaceInvite.expiresAt, now)- )- )- .returning();- return rows[0] ?? null;-}--export async function deleteInvite(db: Database, inviteId: string, workspaceId: string) {- const rows = await db- .delete(workspaceInvite)- .where(- and(- eq(workspaceInvite.id, inviteId),- eq(workspaceInvite.workspaceId, workspaceId)- )- )- .returning();- return rows[0] ?? null;-}diff --git a/src/shared/src/db/queries/workspace.ts b/src/shared/src/db/queries/workspace.tsdeleted file mode 100644index 296416003..000000000--- a/src/shared/src/db/queries/workspace.ts+++ /dev/null@@ -1,72 +0,0 @@-import { eq, and, asc } from "drizzle-orm";-import { workspace, member } from "../schema";-import type { Database } from "../index";--export async function getWorkspace(db: Database, id: string, userId: string) {- const rows = await db- .select({- id: workspace.id,- name: workspace.name,- slug: workspace.slug,- onboarded: workspace.onboarded,- createdAt: workspace.createdAt,- updatedAt: workspace.updatedAt,- })- .from(workspace)- .innerJoin(member, eq(member.workspaceId, workspace.id))- .where(and(eq(workspace.id, id), eq(member.userId, userId)));- return rows[0] ?? null;-}--export async function getWorkspaceBySlug(db: Database, slug: string) {- const rows = await db.select().from(workspace).where(eq(workspace.slug, slug));- return rows[0] ?? null;-}--export async function listWorkspaces(db: Database, userId: string) {- return db- .select({- id: workspace.id,- name: workspace.name,- slug: workspace.slug,- onboarded: workspace.onboarded,- createdAt: workspace.createdAt,- updatedAt: workspace.updatedAt,- })- .from(workspace)- .innerJoin(member, eq(member.workspaceId, workspace.id))- .where(eq(member.userId, userId))- .orderBy(asc(workspace.createdAt));-}--export async function createWorkspace(- db: Database,- data: { name: string; slug: string }-) {- const rows = await db- .insert(workspace)- .values({ name: data.name, slug: data.slug })- .returning();- return rows[0]!;-}--export async function updateWorkspace(db: Database, id: string, data: { name?: string; slug?: string }) {- const rows = await db- .update(workspace)- .set({ ...data, updatedAt: new Date().toISOString() })- .where(eq(workspace.id, id))- .returning();- return rows[0] ?? null;-}--export async function markOnboarded(db: Database, id: string) {- await db- .update(workspace)- .set({ onboarded: 1, updatedAt: new Date().toISOString() })- .where(eq(workspace.id, id));-}--export async function deleteWorkspace(db: Database, id: string) {- const rows = await db.delete(workspace).where(eq(workspace.id, id)).returning();- return rows[0] ?? null;-}diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex bff85d317..7e529a880 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -746,12 +746,7 @@ export { validateCommunityName, sanitizeCommunityName } from "./lib/community-naexport type { CommunityNameValidation } from "./lib/community-name";export { parseInviteToken } from "./lib/invite-link";export { slugify } from "./lib/slugify";-export {- addRepeatInterval,- computeNextScheduledAt,- expandOccurrences,- getOccurrencesPerDay,-} from "./db/queries/calendar-event";+// Utilsexport { parseEmailHandle, toAlookAddress, isValidHandle, extractDomain, isSensitiveRecipient } from "./utils/email";diff --git a/src/shared/test/calendar-collapse.test.ts b/src/shared/test/calendar-collapse.test.tsdeleted file mode 100644index 093f2dc94..000000000--- a/src/shared/test/calendar-collapse.test.ts+++ /dev/null@@ -1,67 +0,0 @@-import { describe, it, expect } from "vitest";-import { getOccurrencesPerDay, expandOccurrences } from "../src/db/queries/calendar-event";--describe("calendar collapse integration", () => {- const COLLAPSE_THRESHOLD = 5;-- it("5min recurring event collapses (not expanded individually)", () => {- const interval = "5min";- const perDay = getOccurrencesPerDay(interval);- expect(perDay).toBeGreaterThan(COLLAPSE_THRESHOLD);- expect(perDay).toBe(288);- });-- it("6hour recurring event does NOT collapse and expands to 4 occurrences", () => {- const interval = "6hour";- const perDay = getOccurrencesPerDay(interval);- expect(perDay).toBeLessThanOrEqual(COLLAPSE_THRESHOLD);-- const from = "2026-05-08T00:00:00.000Z";- const to = "2026-05-08T23:59:59.999Z";- const scheduledAt = "2026-05-08T00:00:00.000Z";- const occurrences = expandOccurrences(scheduledAt, interval, null, [], from, to);- expect(occurrences).toHaveLength(4);- });-- it("mixed events: 5min collapses, 8hour does not", () => {- const fiveMin = getOccurrencesPerDay("5min");- const eightHour = getOccurrencesPerDay("8hour");- expect(fiveMin).toBeGreaterThan(COLLAPSE_THRESHOLD);- expect(eightHour).toBeLessThanOrEqual(COLLAPSE_THRESHOLD);- expect(eightHour).toBe(3);-- const from = "2026-05-08T00:00:00.000Z";- const to = "2026-05-08T23:59:59.999Z";- const occurrences = expandOccurrences("2026-05-08T00:00:00.000Z", "8hour", null, [], from, to);- expect(occurrences).toHaveLength(3);- });-- it("collapsed event produces one row per day across multi-day range", () => {- const interval = "5min";- const perDay = getOccurrencesPerDay(interval);- expect(perDay).toBe(288);-- // Simulating what the API route does: for a 3-day range, emit 3 collapsed rows- const from = new Date("2026-05-08T00:00:00.000Z");- const to = new Date("2026-05-10T23:59:59.999Z");- const scheduledAt = new Date("2026-05-08T09:00:00.000Z");-- const collapsedRows: { date: string; collapsed_count: number }[] = [];- const cursor = new Date(Date.UTC(from.getUTCFullYear(), from.getUTCMonth(), from.getUTCDate()));- const endDay = new Date(Date.UTC(to.getUTCFullYear(), to.getUTCMonth(), to.getUTCDate()));- while (cursor <= endDay) {- if (cursor >= new Date(Date.UTC(scheduledAt.getUTCFullYear(), scheduledAt.getUTCMonth(), scheduledAt.getUTCDate()))) {- collapsedRows.push({- date: cursor.toISOString().slice(0, 10),- collapsed_count: perDay,- });- }- cursor.setUTCDate(cursor.getUTCDate() + 1);- }-- expect(collapsedRows).toHaveLength(3);- expect(collapsedRows[0]!.collapsed_count).toBe(288);- expect(collapsedRows[0]!.date).toBe("2026-05-08");- expect(collapsedRows[2]!.date).toBe("2026-05-10");- });-});diff --git a/src/shared/test/calendar-event.test.ts b/src/shared/test/calendar-event.test.tsdeleted file mode 100644index 6715ba751..000000000--- a/src/shared/test/calendar-event.test.ts+++ /dev/null@@ -1,40 +0,0 @@-import { describe, it, expect } from "vitest";-import { getOccurrencesPerDay } from "../src/db/queries/calendar-event";--describe("getOccurrencesPerDay", () => {- it("5min returns 288", () => {- expect(getOccurrencesPerDay("5min")).toBe(288);- });-- it("4hour returns 6 (>5, should collapse)", () => {- expect(getOccurrencesPerDay("4hour")).toBe(6);- });-- it("6hour returns 4 (≤5, no collapse)", () => {- expect(getOccurrencesPerDay("6hour")).toBe(4);- });-- it("1day returns 1 (never collapses)", () => {- expect(getOccurrencesPerDay("1day")).toBe(1);- });-- it("1week returns 1 (never collapses)", () => {- expect(getOccurrencesPerDay("1week")).toBe(1);- });-- it("30min returns 48 (>5, should collapse)", () => {- expect(getOccurrencesPerDay("30min")).toBe(48);- });-- it("1hour returns 24 (>5, should collapse)", () => {- expect(getOccurrencesPerDay("1hour")).toBe(24);- });-- it("1month returns 1 (never collapses)", () => {- expect(getOccurrencesPerDay("1month")).toBe(1);- });-- it("invalid format returns 1", () => {- expect(getOccurrencesPerDay("bogus")).toBe(1);- });-});diff --git a/src/shared/test/queries/agent-access.test.ts b/src/shared/test/queries/agent-access.test.tsdeleted file mode 100644index 3b7d2f33e..000000000--- a/src/shared/test/queries/agent-access.test.ts+++ /dev/null@@ -1,62 +0,0 @@-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-pin.test.ts b/src/shared/test/queries/agent-pin.test.tsdeleted file mode 100644index 51d812faf..000000000--- a/src/shared/test/queries/agent-pin.test.ts+++ /dev/null@@ -1,62 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as pin from "../../src/db/queries/agent-pin";--describe("agent-pin exports", () => {- it("exports listPins", () => { expect(typeof pin.listPins).toBe("function"); });- it("exports pinAgent", () => { expect(typeof pin.pinAgent).toBe("function"); });- it("exports unpinAgent", () => { expect(typeof pin.unpinAgent).toBe("function"); });- it("exports reorderPins", () => { expect(typeof pin.reorderPins).toBe("function"); });-});--describe("pinAgent", () => {- it("returns null on conflict", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ maxPos: 2 }]));- chain.insert = vi.fn(() => chain); chain.values = vi.fn(() => chain);- chain.onConflictDoNothing = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await pin.pinAgent(chain, { agentId: "a", workspaceId: "w", userId: "u" })).toBeNull();- });- it("creates at next position", async () => {- const p = { id: "pin_1", position: 3 };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ maxPos: 2 }]));- chain.insert = vi.fn(() => chain); chain.values = vi.fn(() => chain);- chain.onConflictDoNothing = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([p]));- expect(await pin.pinAgent(chain, { agentId: "a", workspaceId: "w", userId: "u" })).toEqual(p);- expect(chain.values).toHaveBeenCalledWith(expect.objectContaining({ position: 3 }));- });-});--describe("unpinAgent", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await pin.unpinAgent(chain, "a", "w", "u")).toBeNull();- });- it("returns removed pin", async () => {- const p = { id: "pin_1" };- const chain: any = {};- chain.delete = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([p]));- expect(await pin.unpinAgent(chain, "a", "w", "u")).toEqual(p);- });-});--describe("reorderPins", () => {- it("calls batch", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain);- chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.batch = vi.fn(() => Promise.resolve());- await pin.reorderPins(chain, "w", "u", ["a", "b"]);- expect(chain.batch).toHaveBeenCalled();- });-});diff --git a/src/shared/test/queries/agent-sidebar-order.test.ts b/src/shared/test/queries/agent-sidebar-order.test.tsdeleted file mode 100644index 792259412..000000000--- a/src/shared/test/queries/agent-sidebar-order.test.ts+++ /dev/null@@ -1,32 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as sidebar from "../../src/db/queries/agent-sidebar-order";--describe("agent-sidebar-order exports", () => {- it("exports listOrder", () => { expect(typeof sidebar.listOrder).toBe("function"); });- it("exports reorder", () => { expect(typeof sidebar.reorder).toBe("function"); });-});--describe("listOrder", () => {- it("queries ordered items", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.orderBy = vi.fn(() => Promise.resolve([]));- await sidebar.listOrder(chain, "w", "u");- expect(chain.orderBy).toHaveBeenCalled();- });-});--describe("reorder", () => {- it("calls batch", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.batch = vi.fn(() => Promise.resolve());- await sidebar.reorder(chain, "w", "u", ["a", "b"]);- expect(chain.batch).toHaveBeenCalled();- });-});diff --git a/src/shared/test/queries/agent-skill.test.ts b/src/shared/test/queries/agent-skill.test.tsdeleted file mode 100644index f8264d44d..000000000--- a/src/shared/test/queries/agent-skill.test.ts+++ /dev/null@@ -1,66 +0,0 @@-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");- });- it("exports syncAgentSkills", () => {- expect(typeof agentSkillQueries.syncAgentSkills).toBe("function");- });- it("exports getSkills", () => {- expect(typeof agentSkillQueries.getSkills).toBe("function");- });-});--describe("agent-skill query function signatures", () => {- it("syncGlobalSkills accepts (db, workspaceId, runtime, skills, daemonId?)", () => {- expect(agentSkillQueries.syncGlobalSkills.length).toBe(5);- });- it("syncAgentSkills accepts (db, agentId, runtime, workspaceId, skills)", () => {- expect(agentSkillQueries.syncAgentSkills.length).toBe(5);- });- it("getSkills accepts (db, agentId, runtime, workspaceId)", () => {- 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.tsdeleted file mode 100644index 9bd34f8e7..000000000--- a/src/shared/test/queries/artifact.test.ts+++ /dev/null@@ -1,136 +0,0 @@-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",- thumbnailR2Key: null,- 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",- has_thumbnail: false,- created_at: "2026-01-15T10:00:00.000Z",- });- });-- it("returns has_thumbnail true when thumbnailR2Key is set", () => {- const row = {- id: "art_123",- conversationId: "conv_456",- agentId: "ag_789",- workspaceId: "ws_001",- filename: "photo.png",- contentType: "image/png",- size: 50000,- r2Key: "uploads/photo.png",- thumbnailR2Key: "uploads/photo_thumb.jpg",- source: "agent",- createdAt: "2026-01-15T10:00:00.000Z",- };-- const result = artifactQueries.artifactToResponse(row as any);- expect(result.has_thumbnail).toBe(true);- });-- 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",- thumbnailR2Key: null,- 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");- expect(result).not.toHaveProperty("thumbnailR2Key");- });-- 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",- thumbnailR2Key: null,- 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.tsdeleted file mode 100644index 4cad718fd..000000000--- a/src/shared/test/queries/calendar-event.test.ts+++ /dev/null@@ -1,405 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as calendarQueries from "../../src/db/queries/calendar-event";--describe("calendar-event query module exports", () => {- it("exports createCalendarEvent", () => {- expect(typeof calendarQueries.createCalendarEvent).toBe("function");- });- it("exports listCalendarEvents", () => {- expect(typeof calendarQueries.listCalendarEvents).toBe("function");- });- it("exports getCalendarEvent", () => {- expect(typeof calendarQueries.getCalendarEvent).toBe("function");- });- it("exports deleteCalendarEvent", () => {- expect(typeof calendarQueries.deleteCalendarEvent).toBe("function");- });- it("exports updateCalendarEvent", () => {- expect(typeof calendarQueries.updateCalendarEvent).toBe("function");- });-- // Compile-time guard: patch accepts optional title and nullable description.- // Kept inside an `if (false)` block so the runtime path is never exercised,- // but the TypeScript compiler still checks the call signature.- it("has a patch-shaped signature (type-level)", () => {- if (false) {- const db = {} as Parameters<typeof calendarQueries.updateCalendarEvent>[0];- void calendarQueries.updateCalendarEvent(db, "ce_1", "ws_1", {- title: "t",- description: null,- });- void calendarQueries.updateCalendarEvent(db, "ce_1", "ws_1", {- title: "t",- });- void calendarQueries.updateCalendarEvent(db, "ce_1", "ws_1", {- description: "x",- });- void calendarQueries.updateCalendarEvent(db, "ce_1", "ws_1", {- description: undefined,- });- void calendarQueries.updateCalendarEvent(db, "ce_1", "ws_1", {- agentId: "ag_2",- scheduledAt: "2026-05-01T12:00:00.000Z",- repeatInterval: null,- repeatStopAt: null,- });- }- expect(true).toBe(true);- });- it("exports listDueCalendarEvents", () => {- expect(typeof calendarQueries.listDueCalendarEvents).toBe("function");- });- it("exports claimCalendarEvent", () => {- expect(typeof calendarQueries.claimCalendarEvent).toBe("function");- });- it("exports revertCalendarEventClaim", () => {- expect(typeof calendarQueries.revertCalendarEventClaim).toBe("function");- });- it("exports updateCalendarEventSchedule", () => {- expect(typeof calendarQueries.updateCalendarEventSchedule).toBe("function");- });- it("exports addRepeatInterval", () => {- expect(typeof calendarQueries.addRepeatInterval).toBe("function");- });- it("exports computeNextScheduledAt", () => {- expect(typeof calendarQueries.computeNextScheduledAt).toBe("function");- });-});--describe("addRepeatInterval", () => {- const base = new Date("2026-01-15T10:00:00.000Z");-- it("advances by minutes", () => {- const out = calendarQueries.addRepeatInterval(base, "30min");- expect(out.toISOString()).toBe("2026-01-15T10:30:00.000Z");- });-- it("advances by hours", () => {- const out = calendarQueries.addRepeatInterval(base, "2hour");- expect(out.toISOString()).toBe("2026-01-15T12:00:00.000Z");- });-- it("advances by days", () => {- const out = calendarQueries.addRepeatInterval(base, "1day");- expect(out.toISOString()).toBe("2026-01-16T10:00:00.000Z");- });-- it("advances by weeks (7 days)", () => {- const out = calendarQueries.addRepeatInterval(base, "1week");- expect(out.toISOString()).toBe("2026-01-22T10:00:00.000Z");- });-- it("advances by months", () => {- const out = calendarQueries.addRepeatInterval(base, "1month");- expect(out.toISOString()).toBe("2026-02-15T10:00:00.000Z");- });-- it("clamps month overflow: Jan 31 + 1 month = Feb 28", () => {- const jan31 = new Date("2026-01-31T09:00:00.000Z");- const out = calendarQueries.addRepeatInterval(jan31, "1month");- // 2026 is not a leap year → Feb has 28 days- expect(out.getUTCFullYear()).toBe(2026);- expect(out.getUTCMonth()).toBe(1); // Feb- expect(out.getUTCDate()).toBe(28);- });-- it("clamps month overflow: Jan 31 + 1 month in a leap year = Feb 29", () => {- const jan31 = new Date("2028-01-31T09:00:00.000Z");- const out = calendarQueries.addRepeatInterval(jan31, "1month");- expect(out.getUTCFullYear()).toBe(2028);- expect(out.getUTCMonth()).toBe(1); // Feb- expect(out.getUTCDate()).toBe(29);- });-- it("advances across year boundary", () => {- const dec = new Date("2026-12-15T10:00:00.000Z");- const out = calendarQueries.addRepeatInterval(dec, "1month");- expect(out.getUTCFullYear()).toBe(2027);- expect(out.getUTCMonth()).toBe(0);- });-- it("throws on invalid format", () => {- expect(() =>- calendarQueries.addRepeatInterval(base, "nope")- ).toThrow();- expect(() =>- calendarQueries.addRepeatInterval(base, "1year")- ).toThrow();- });-});--describe("computeNextScheduledAt", () => {- it("returns the next occurrence when the next future occurrence is after now", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- null,- "2026-01-01T09:30:00.000Z"- );- expect(out).toBe("2026-01-02T09:00:00.000Z");- });-- it("loop-advances past now when daemon downtime missed multiple occurrences", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- null,- "2026-01-05T09:30:00.000Z"- );- // Next must be > now; after four days of downtime, the next tick is Jan 6.- expect(out).toBe("2026-01-06T09:00:00.000Z");- });-- it("returns null when the next occurrence would exceed repeat_stop_at", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- "2026-01-01T23:59:59.999Z",- "2026-01-01T09:30:00.000Z"- );- expect(out).toBeNull();- });-- it("returns null when downtime pushes next past repeat_stop_at (event becomes inert)", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- "2026-01-03T23:59:59.999Z",- "2026-01-10T09:30:00.000Z"- );- expect(out).toBeNull();- });-- it("fires at the repeat_stop boundary when the next computed occurrence is still <= stop", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- "2026-01-02T23:59:59.999Z",- "2026-01-01T09:30:00.000Z"- );- // Jan 2 at 09:00 is still <= stop- expect(out).toBe("2026-01-02T09:00:00.000Z");- });-- it("skips excepted occurrences", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- null,- "2026-01-01T09:30:00.000Z",- ["2026-01-02T09:00:00.000Z"]- );- expect(out).toBe("2026-01-03T09:00:00.000Z");- });-- it("skips multiple consecutive exceptions", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- null,- "2026-01-01T09:30:00.000Z",- [- "2026-01-02T09:00:00.000Z",- "2026-01-03T09:00:00.000Z",- "2026-01-04T09:00:00.000Z",- ]- );- expect(out).toBe("2026-01-05T09:00:00.000Z");- });-- it("returns null when all remaining occurrences until stop are excepted", () => {- const out = calendarQueries.computeNextScheduledAt(- "2026-01-01T09:00:00.000Z",- "1day",- "2026-01-02T23:59:59.999Z",- "2026-01-01T09:30:00.000Z",- ["2026-01-02T09:00:00.000Z"]- );- expect(out).toBeNull();- });-});--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("listCalendarEvents — completed one-off exclusion", () => {- 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(() => Promise.resolve(rows));- chain.innerJoin = vi.fn(() => chain);- return chain;- }-- it("calls where() with conditions that would exclude completed one-off events", async () => {- const db = createMockDb([]);- await calendarQueries.listCalendarEvents(db, "ws_1");- expect(db.where).toHaveBeenCalledOnce();- });-- it("returns all rows from the database (filter logic is in SQL)", async () => {- const rows = [- { id: "ce_1", repeatInterval: null, lastTriggeredAt: null },- { id: "ce_2", repeatInterval: "1day", lastTriggeredAt: "2026-01-01T10:00:00.000Z" },- ];- const db = createMockDb(rows);- const result = await calendarQueries.listCalendarEvents(db, "ws_1");- expect(result).toEqual(rows);- });-- it("passes agentId filter when provided", async () => {- const db = createMockDb([]);- await calendarQueries.listCalendarEvents(db, "ws_1", { agentId: "ag_1" });- expect(db.where).toHaveBeenCalledOnce();- });-- it("uses innerJoin when userId is provided", async () => {- const ce = { id: "ce_1", agentId: "ag_1", workspaceId: "ws_1", title: "T", description: null, scheduledAt: "2026-01-01T09:00:00.000Z", repeatInterval: null, repeatStopAt: null, lastTriggeredAt: null, exceptions: [], createdAt: "2026-01-01", updatedAt: "2026-01-01" };- const db = createMockDb([{ calendarEvent: ce }]);- const result = await calendarQueries.listCalendarEvents(db, "ws_1", { userId: "u1" });- expect(db.innerJoin).toHaveBeenCalledOnce();- expect(result).toEqual([ce]);- });-- it("does not use innerJoin when userId is not provided", async () => {- const db = createMockDb([]);- await calendarQueries.listCalendarEvents(db, "ws_1");- expect(db.innerJoin).not.toHaveBeenCalled();- });-});--describe("getCalendarEvent — user isolation", () => {- 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.innerJoin = vi.fn(() => chain);- return chain;- }-- it("returns event without userId (backwards compat)", async () => {- const ce = { id: "ce_1" };- const db = createMockDb([ce]);- const result = await calendarQueries.getCalendarEvent(db, "ce_1", "ws_1");- expect(result).toEqual(ce);- expect(db.innerJoin).not.toHaveBeenCalled();- });-- it("uses innerJoin when userId is provided", async () => {- const ce = { id: "ce_1" };- const db = createMockDb([{ calendarEvent: ce }]);- const result = await calendarQueries.getCalendarEvent(db, "ce_1", "ws_1", "u1");- expect(db.innerJoin).toHaveBeenCalledOnce();- expect(result).toEqual(ce);- });-- it("returns null when userId does not match (empty rows from join)", async () => {- const db = createMockDb([]);- const result = await calendarQueries.getCalendarEvent(db, "ce_1", "ws_1", "wrong_user");- expect(result).toBeNull();- });-});--describe("expandOccurrences", () => {- it("returns one entry per occurrence within [from, to] for a daily event", () => {- const out = calendarQueries.expandOccurrences(- "2026-04-17T09:00:00.000Z",- "1day",- null,- [],- "2026-04-15T00:00:00.000Z",- "2026-04-20T23:59:59.999Z"- );- expect(out).toEqual([- "2026-04-17T09:00:00.000Z",- "2026-04-18T09:00:00.000Z",- "2026-04-19T09:00:00.000Z",- "2026-04-20T09:00:00.000Z",- ]);- });-- it("skips exceptions", () => {- const out = calendarQueries.expandOccurrences(- "2026-04-17T09:00:00.000Z",- "1day",- null,- ["2026-04-19T09:00:00.000Z"],- "2026-04-15T00:00:00.000Z",- "2026-04-20T23:59:59.999Z"- );- expect(out).toEqual([- "2026-04-17T09:00:00.000Z",- "2026-04-18T09:00:00.000Z",- "2026-04-20T09:00:00.000Z",- ]);- });-- it("stops at repeat_stop_at", () => {- const out = calendarQueries.expandOccurrences(- "2026-04-17T09:00:00.000Z",- "1day",- "2026-04-18T23:59:59.999Z",- [],- "2026-04-15T00:00:00.000Z",- "2026-04-30T23:59:59.999Z"- );- expect(out).toEqual([- "2026-04-17T09:00:00.000Z",- "2026-04-18T09:00:00.000Z",- ]);- });-- it("excludes occurrences before `from`", () => {- const out = calendarQueries.expandOccurrences(- "2026-04-10T09:00:00.000Z",- "1day",- null,- [],- "2026-04-12T00:00:00.000Z",- "2026-04-14T23:59:59.999Z"- );- expect(out).toEqual([- "2026-04-12T09:00:00.000Z",- "2026-04-13T09:00:00.000Z",- "2026-04-14T09:00:00.000Z",- ]);- });-});diff --git a/src/shared/test/queries/channel-ops.test.ts b/src/shared/test/queries/channel-ops.test.tsdeleted file mode 100644index a8a9c2022..000000000--- a/src/shared/test/queries/channel-ops.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as channelQueries from "../../src/db/queries/channel";--describe("getChannelByName", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([]));- expect(await channelQueries.getChannelByName(chain, "ws_1", "missing")).toBeNull();- });- it("returns channel when found", async () => {- const ch = { id: "ch_1", name: "general" };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([ch]));- expect(await channelQueries.getChannelByName(chain, "ws_1", "general")).toEqual(ch);- });-});--describe("getChannelById", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([]));- expect(await channelQueries.getChannelById(chain, "x", "ws_1")).toBeNull();- });- it("returns channel when found", async () => {- const ch = { id: "ch_1", name: "general" };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([ch]));- expect(await channelQueries.getChannelById(chain, "ch_1", "ws_1")).toEqual(ch);- });-});--describe("listChannels", () => {- it("returns channels ordered by position", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.orderBy = vi.fn(() => Promise.resolve([{ id: "ch_1" }]));- await channelQueries.listChannels(chain, "ws_1");- expect(chain.orderBy).toHaveBeenCalled();- });-});--describe("createChannel", () => {- it("creates channel at next position", async () => {- const ch = { id: "ch_1", name: "new", position: 2 };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ maxPos: 1 }]));- chain.insert = vi.fn(() => chain); chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([ch]));- const result = await channelQueries.createChannel(chain, { workspaceId: "ws_1", name: "new" });- expect(chain.values).toHaveBeenCalledWith(expect.objectContaining({ name: "new", position: 2 }));- expect(result).toEqual(ch);- });-});--describe("deleteChannel", () => {- it("returns null when channel not found", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([]));- expect(await channelQueries.deleteChannel(chain, "x", "ws_1")).toBeNull();- });- it("deletes channel and conversations", async () => {- const ch = { id: "ch_1", name: "old" };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([ch]));- chain.delete = vi.fn(() => chain);- chain.run = vi.fn(() => Promise.resolve());- chain.batch = vi.fn(() => Promise.resolve());- const result = await channelQueries.deleteChannel(chain, "ch_1", "ws_1");- expect(chain.run).toHaveBeenCalled();- expect(chain.batch).toHaveBeenCalled();- expect(result).toEqual(ch);- });-});--describe("renameChannel", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([]));- expect(await channelQueries.renameChannel(chain, "x", "ws_1", "new")).toBeNull();- });- it("renames and updates conversations", async () => {- const ch = { id: "ch_1", name: "old" };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([ch]));- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.batch = vi.fn(() => Promise.resolve());- const result = await channelQueries.renameChannel(chain, "ch_1", "ws_1", "new");- expect(result).toEqual({ ...ch, name: "new" });- });-});--describe("reorderChannels", () => {- it("calls batch with updates", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain);- chain.batch = vi.fn(() => Promise.resolve());- await channelQueries.reorderChannels(chain, "ws_1", ["ch_a", "ch_b"]);- expect(chain.batch).toHaveBeenCalled();- });-});diff --git a/src/shared/test/queries/channel.test.ts b/src/shared/test/queries/channel.test.tsdeleted file mode 100644index 56def31e5..000000000--- a/src/shared/test/queries/channel.test.ts+++ /dev/null@@ -1,62 +0,0 @@-import { describe, it, expect } from "vitest";-import * as channelQueries from "../../src/db/queries/channel";--describe("channel query module exports", () => {- it("exports createChannel", () => {- expect(typeof channelQueries.createChannel).toBe("function");- });-- it("exports listChannels", () => {- expect(typeof channelQueries.listChannels).toBe("function");- });-- it("exports getChannelByName", () => {- expect(typeof channelQueries.getChannelByName).toBe("function");- });-- it("exports getChannelById", () => {- expect(typeof channelQueries.getChannelById).toBe("function");- });-- it("exports deleteChannel", () => {- expect(typeof channelQueries.deleteChannel).toBe("function");- });-- it("exports renameChannel", () => {- expect(typeof channelQueries.renameChannel).toBe("function");- });-- it("exports reorderChannels", () => {- expect(typeof channelQueries.reorderChannels).toBe("function");- });-});--describe("channel query function signatures", () => {- it("createChannel accepts (db, data)", () => {- expect(channelQueries.createChannel.length).toBe(2);- });-- it("listChannels accepts (db, workspaceId)", () => {- expect(channelQueries.listChannels.length).toBe(2);- });-- it("getChannelByName accepts (db, workspaceId, name)", () => {- expect(channelQueries.getChannelByName.length).toBe(3);- });-- it("getChannelById accepts (db, id, workspaceId)", () => {- expect(channelQueries.getChannelById.length).toBe(3);- });-- it("deleteChannel accepts (db, id, workspaceId)", () => {- expect(channelQueries.deleteChannel.length).toBe(3);- });-- 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/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.tsindex b1b958963..c693d1023 100644--- a/src/shared/test/queries/community-bot.test.ts+++ b/src/shared/test/queries/community-bot.test.ts@@ -41,15 +41,6 @@ describe("community/bot exports", () => {expect(typeof q.assertNoLiveBots).toBe("function")})- it("exposes approval-request helpers", () => {- expect(typeof q.getApprovalRequest).toBe("function")- expect(typeof q.listPendingApprovalsForBot).toBe("function")- expect(typeof q.findPendingJoinRequest).toBe("function")- expect(typeof q.createApprovalRequestStatement).toBe("function")- expect(typeof q.resolveApprovalRequest).toBe("function")- expect(typeof q.getApprovalRequestByDmMessageId).toBe("function")- })-it("exports OwnerHasBotsError as a real Error subclass", () => {const e = new q.OwnerHasBotsError("boom")expect(e).toBeInstanceOf(Error)diff --git a/src/shared/test/queries/community-search.test.ts b/src/shared/test/queries/community-search.test.tsdeleted file mode 100644index 64432d340..000000000--- a/src/shared/test/queries/community-search.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import Sqlite from "better-sqlite3";-import { drizzle } from "drizzle-orm/better-sqlite3";-import { afterEach, beforeEach, describe, it, expect } from "vitest";-import type { Database } from "../../src/db";-import { sanitizeFtsQuery, searchMessagesInServer } from "../../src/db/queries/community/search";--describe("sanitizeFtsQuery", () => {- it("single word produces prefix match", () => {- expect(sanitizeFtsQuery("hi")).toBe('"hi"*');- });-- it("multiple words produce implicit AND with prefix on each", () => {- expect(sanitizeFtsQuery("hello world")).toBe('"hello"* "world"*');- });-- it("strips FTS special characters", () => {- expect(sanitizeFtsQuery('"test-case"')).toBe('"test"* "case"*');- });-- it("strips FTS keywords", () => {- expect(sanitizeFtsQuery("not bad")).toBe('"bad"*');- expect(sanitizeFtsQuery("cats AND dogs")).toBe('"cats"* "dogs"*');- });-- it("returns empty phrase for empty input", () => {- expect(sanitizeFtsQuery("")).toBe('""');- expect(sanitizeFtsQuery(" ")).toBe('""');- });-- it("handles all-keyword input as empty", () => {- expect(sanitizeFtsQuery("AND OR NOT")).toBe('""');- });-});--describe("searchMessagesInServer against real SQLite", () => {- let sqlite: Sqlite.Database;- let db: Database;- const quotedChannel = "visible'quoted";-- beforeEach(() => {- sqlite = new Sqlite(":memory:");- sqlite.exec(`- CREATE TABLE user (- id TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', email TEXT NOT NULL,- emailVerified INTEGER, image TEXT, avatarVersion INTEGER NOT NULL DEFAULT 0,- avatarObjectKey TEXT, createdAt TEXT NOT NULL, updatedAt TEXT NOT NULL,- isBot INTEGER NOT NULL DEFAULT 0, ownerUserId TEXT, deletedAt TEXT,- discriminator TEXT NOT NULL DEFAULT '0000', lastRefreshContextAt TEXT- );- CREATE TABLE community_channel (id TEXT PRIMARY KEY, server_id TEXT);- CREATE TABLE community_message (- id TEXT PRIMARY KEY, author_id TEXT NOT NULL, content TEXT NOT NULL,- type TEXT NOT NULL DEFAULT 'default', mention_type TEXT, reply_to_id TEXT,- embeds TEXT, created_at TEXT NOT NULL, channel_id TEXT NOT NULL,- seq INTEGER NOT NULL DEFAULT 0, friendship_id TEXT, client_nonce TEXT- );- INSERT INTO user (id, email, createdAt, updatedAt)- VALUES ('author', '[email protected]', '2026-09-01', '2026-09-01');- `);- const insertChannel = sqlite.prepare("INSERT INTO community_channel (id, server_id) VALUES (?, ?)");- for (const channelId of ["visible", quotedChannel, "unauthorized"]) insertChannel.run(channelId, "server");- insertChannel.run("outside", "other-server");- const insertMessage = sqlite.prepare(`- INSERT INTO community_message (id, author_id, content, channel_id, created_at)- VALUES (?, 'author', ?, ?, ?)- `);- insertMessage.run("old-visible", "needle", "visible", "2026-09-01T00:01:00.000Z");- insertMessage.run("new-visible", "needle", "visible", "2026-09-01T00:05:00.000Z");- insertMessage.run("literal-visible", "needle", quotedChannel, "2026-09-01T00:03:00.000Z");- insertMessage.run("hidden", "needle", "unauthorized", "2026-09-01T00:06:00.000Z");- insertMessage.run("other-server", "needle", "outside", "2026-09-01T00:07:00.000Z");- insertMessage.run("wrong-content", "haystack", "visible", "2026-09-01T00:08:00.000Z");- db = drizzle(sqlite) as unknown as Database;- });-- afterEach(() => sqlite.close());-- it("intersects server and visible channels before the global newest limit", async () => {- const rows = await searchMessagesInServer(db, {- query: "needle", serverId: "server", visibleChannelIds: ["visible", quotedChannel, "outside"], limit: 2,- });- expect(rows.map((row) => row.message.id)).toEqual(["new-visible", "literal-visible"]);- });-- it("keeps undefined visibility trusted within the requested server", async () => {- const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", limit: 3 });- expect(rows.map((row) => row.message.id)).toEqual(["hidden", "new-visible", "literal-visible"]);- });-- it("returns no rows for an explicitly empty visible set", async () => {- const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", visibleChannelIds: [] });- expect(rows).toEqual([]);- });-- it("keeps large repeated visible sets literal, scoped and unique", async () => {- const visibleChannelIds = ["visible", quotedChannel, "outside", ...Array.from({ length: 150 }, (_, i) => `missing-${i}`), "visible", quotedChannel];- const rows = await searchMessagesInServer(db, { query: "needle", serverId: "server", visibleChannelIds, limit: 2 });- expect(rows.map((row) => row.message.id)).toEqual(["new-visible", "literal-visible"]);- });-});diff --git a/src/shared/test/queries/issue-comment.test.ts b/src/shared/test/queries/issue-comment.test.tsdeleted file mode 100644index 3d51c5e16..000000000--- a/src/shared/test/queries/issue-comment.test.ts+++ /dev/null@@ -1,61 +0,0 @@-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/message-flag.test.ts b/src/shared/test/queries/message-flag.test.tsdeleted file mode 100644index d9662d5e9..000000000--- a/src/shared/test/queries/message-flag.test.ts+++ /dev/null@@ -1,106 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as mf from "../../src/db/queries/message-flag";--describe("message-flag exports", () => {- it("exports getMessageWorkspaceId", () => { expect(typeof mf.getMessageWorkspaceId).toBe("function"); });- it("exports flagMessage", () => { expect(typeof mf.flagMessage).toBe("function"); });- it("exports unflagMessage", () => { expect(typeof mf.unflagMessage).toBe("function"); });- it("exports listFlaggedMessages", () => { expect(typeof mf.listFlaggedMessages).toBe("function"); });- it("exports getFlaggedCount", () => { expect(typeof mf.getFlaggedCount).toBe("function"); });- it("exports listFlaggedMessageIds", () => { expect(typeof mf.listFlaggedMessageIds).toBe("function"); });-});--describe("getMessageWorkspaceId", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.innerJoin = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.limit = vi.fn(() => Promise.resolve([]));- expect(await mf.getMessageWorkspaceId(chain, "x")).toBeNull();- });- it("returns workspaceId", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.innerJoin = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.limit = vi.fn(() => Promise.resolve([{ workspaceId: "ws_1" }]));- expect(await mf.getMessageWorkspaceId(chain, "msg_1")).toBe("ws_1");- });-});--describe("flagMessage", () => {- it("returns null on conflict", async () => {- const chain: any = {};- chain.insert = vi.fn(() => chain); chain.values = vi.fn(() => chain);- chain.onConflictDoNothing = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await mf.flagMessage(chain, { messageId: "m", userId: "u", workspaceId: "w" })).toBeNull();- });- it("returns flag", async () => {- const f = { id: "mf_1" };- const chain: any = {};- chain.insert = vi.fn(() => chain); chain.values = vi.fn(() => chain);- chain.onConflictDoNothing = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([f]));- expect(await mf.flagMessage(chain, { messageId: "m", userId: "u", workspaceId: "w" })).toEqual(f);- });-});--describe("unflagMessage", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await mf.unflagMessage(chain, "m", "u", "w")).toBeNull();- });- it("returns removed flag", async () => {- const f = { id: "mf_1" };- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([f]));- expect(await mf.unflagMessage(chain, "m", "u", "w")).toEqual(f);- });-});--describe("listFlaggedMessages", () => {- it("returns items with hasMore=false", async () => {- const rows = [{ id: "mf_1" }];- const chain: any = {};- chain.all = vi.fn(() => Promise.resolve(rows));- const result = await mf.listFlaggedMessages(chain, "u", "w");- expect(result.items).toEqual(rows);- expect(result.hasMore).toBe(false);- });- it("returns hasMore=true when exceeding limit", async () => {- const rows = Array.from({ length: 31 }, (_, i) => ({ id: `mf_${i}` }));- const chain: any = {};- chain.all = vi.fn(() => Promise.resolve(rows));- const result = await mf.listFlaggedMessages(chain, "u", "w");- expect(result.hasMore).toBe(true);- expect(result.items.length).toBe(30);- });-});--describe("getFlaggedCount", () => {- it("returns 0 when empty", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([]));- expect(await mf.getFlaggedCount(chain, "u", "w")).toBe(0);- });- it("returns count", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ count: 7 }]));- expect(await mf.getFlaggedCount(chain, "u", "w")).toBe(7);- });-});--describe("listFlaggedMessageIds", () => {- it("returns message ids", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.innerJoin = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve([{ messageId: "m1" }, { messageId: "m2" }]));- expect(await mf.listFlaggedMessageIds(chain, "u", "w", "c")).toEqual(["m1", "m2"]);- });-});diff --git a/src/shared/test/queries/overview.test.ts b/src/shared/test/queries/overview.test.tsdeleted file mode 100644index 2ea47963e..000000000--- a/src/shared/test/queries/overview.test.ts+++ /dev/null@@ -1,38 +0,0 @@-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/param-limit.test.ts b/src/shared/test/queries/param-limit.test.tsindex c8dbe35fc..170dd5afd 100644--- a/src/shared/test/queries/param-limit.test.ts+++ b/src/shared/test/queries/param-limit.test.ts@@ -16,7 +16,6 @@ import * as categoryQueries from "../../src/db/queries/community/category";import * as memberQueries from "../../src/db/queries/community/member";import * as reactionQueries from "../../src/db/queries/community/reaction";import * as dmQueries from "../../src/db/queries/community/dm";-import * as overviewQueries from "../../src/db/queries/overview";import * as taskQueries from "../../src/db/queries/task";import * as agentQueries from "../../src/db/queries/agent";import * as conversationQueries from "../../src/db/queries/conversation";@@ -394,8 +393,6 @@ describe("high-cardinality query bind matrix", () => {(db) => categoryQueries.getCategoriesByIds(db as never, ids),(db) => agentQueries.getAgentsByIds(db as never, ids, "workspace_1"),(db) => conversationQueries.getConversationsByIds(db as never, ids, "workspace_1"),- (db) => overviewQueries.getRecentTerminalTasks(db as never, "workspace_1", ids),- (db) => overviewQueries.getConversationCountsByAgent(db as never, "workspace_1", ids),(db) => taskQueries.listPendingTasksByRuntimes(db as never, ids, "workspace_1"),(db) => taskQueries.listActiveTaskCountsByWorkspace(db as never, "workspace_1", ids, "user_1"),(db) => taskQueries.listActiveTasksByWorkspace(db as never, "workspace_1", ids, "user_1"),diff --git a/src/shared/test/queries/task-message.test.ts b/src/shared/test/queries/task-message.test.tsdeleted file mode 100644index 4b51cb7c0..000000000--- a/src/shared/test/queries/task-message.test.ts+++ /dev/null@@ -1,106 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import { drizzle } from "drizzle-orm/d1";-import { eq, and, asc } from "drizzle-orm";-import { taskMessage, agentTaskQueue } from "../../src/db/schema";-import * as taskMessageQueries from "../../src/db/queries/task-message";--const fakeDb = drizzle({} as never);--// Chainable mock that captures the .where() argument so we can exercise the REAL-// query fn (it's async + awaits its builder internally, so we can't .toSQL() the-// fn's return value directly — the runtime would auto-await a dead connection).-function createCapturingDb(rows: unknown[]) {- const calls: { where?: unknown } = {};- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.innerJoin = vi.fn(() => chain);- chain.where = vi.fn((cond: unknown) => {- calls.where = cond;- return chain;- });- chain.orderBy = vi.fn(() => Promise.resolve(rows));- return { chain, calls };-}--describe("task-message query module exports", () => {- it("exports createTaskMessage", () => {- expect(typeof taskMessageQueries.createTaskMessage).toBe("function");- });-- it("exports listTaskMessages", () => {- expect(typeof taskMessageQueries.listTaskMessages).toBe("function");- });-- it("exports listTaskErrorMessages", () => {- expect(typeof taskMessageQueries.listTaskErrorMessages).toBe("function");- });-- it("exports listTaskMessagesSince", () => {- expect(typeof taskMessageQueries.listTaskMessagesSince).toBe("function");- });-- it("exports deleteTaskMessages", () => {- expect(typeof taskMessageQueries.deleteTaskMessages).toBe("function");- });-});--describe("listTaskMessages", () => {- it("accepts (db, taskId, workspaceId?)", () => {- expect(taskMessageQueries.listTaskMessages.length).toBe(3);- });-});--describe("listTaskErrorMessages", () => {- it("accepts (db, taskId, workspaceId)", () => {- expect(taskMessageQueries.listTaskErrorMessages.length).toBe(3);- });-- it("runs the real query: joins, builds a WHERE, and returns the rows", async () => {- const rows = [{ id: "tm1", type: "error" }];- const { chain, calls } = createCapturingDb(rows);- const result = await taskMessageQueries.listTaskErrorMessages(- chain,- "task-1",- "ws-1",- );- // Exercises the actual fn (not a mirror): it joins, filters, and returns rows.- expect(chain.innerJoin).toHaveBeenCalled();- expect(chain.where).toHaveBeenCalledTimes(1);- expect(calls.where).toBeDefined();- expect(result).toEqual(rows);- });-- it("compiles the expected WHERE clause (type='error', task + workspace scope)", () => {- // Reference SQL for the query above. This documents the intended shape and- // catches a regression in the column/filter set; it is a sibling check to- // the real-fn test above, not a stand-in for it.- const { sql, params } = fakeDb- .select()- .from(taskMessage)- .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))- .where(- and(- eq(taskMessage.taskId, "task-1"),- eq(agentTaskQueue.workspaceId, "ws-1"),- eq(taskMessage.type, "error"),- ),- )- .orderBy(asc(taskMessage.seq))- .toSQL();-- expect(sql).toContain('inner join "agent_task_queue"');- expect(sql).toContain('"task_message"."task_id" = ?');- expect(sql).toContain('"agent_task_queue"."workspace_id" = ?');- expect(sql).toContain('"task_message"."type" = ?');- expect(sql).toContain('order by "task_message"."seq" asc');- expect(params).toEqual(["task-1", "ws-1", "error"]);- });-});--describe("listTaskMessagesSince", () => {- it("accepts (db, taskId, afterSeq)", () => {- expect(taskMessageQueries.listTaskMessagesSince.length).toBe(3);- });-});-diff --git a/src/shared/test/queries/workspace-file-request.test.ts b/src/shared/test/queries/workspace-file-request.test.tsdeleted file mode 100644index 38b3b2876..000000000--- a/src/shared/test/queries/workspace-file-request.test.ts+++ /dev/null@@ -1,75 +0,0 @@-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/queries/workspace-invite.test.ts b/src/shared/test/queries/workspace-invite.test.tsdeleted file mode 100644index b3c48018a..000000000--- a/src/shared/test/queries/workspace-invite.test.ts+++ /dev/null@@ -1,71 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as wi from "../../src/db/queries/workspace-invite";--function createSelectMock(rows: any[]) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rows));- chain.innerJoin = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve(rows));- return chain;-}--describe("workspace-invite exports", () => {- it("exports createInvite", () => { expect(typeof wi.createInvite).toBe("function"); });- it("exports getInviteByToken", () => { expect(typeof wi.getInviteByToken).toBe("function"); });- it("exports listActiveInvites", () => { expect(typeof wi.listActiveInvites).toBe("function"); });- it("exports redeemInvite", () => { expect(typeof wi.redeemInvite).toBe("function"); });- it("exports deleteInvite", () => { expect(typeof wi.deleteInvite).toBe("function"); });-});--describe("createInvite", () => {- it("creates invite", async () => {- const inv = { id: "inv_1" };- expect(await wi.createInvite(createSelectMock([inv]), { workspaceId: "w", createdBy: "u", expiresAt: "2026-12-31" })).toEqual(inv);- });-});--describe("getInviteByToken", () => {- it("returns null when not found", async () => { expect(await wi.getInviteByToken(createSelectMock([]), "x")).toBeNull(); });- it("returns invite with joins", async () => {- const inv = { id: "inv_1" };- const mockDb = createSelectMock([inv]);- expect(await wi.getInviteByToken(mockDb, "tok")).toEqual(inv);- expect(mockDb.innerJoin).toHaveBeenCalledTimes(2);- });-});--describe("redeemInvite", () => {- it("returns null when expired", 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([]));- expect(await wi.redeemInvite(chain, "x", "u")).toBeNull();- });- it("returns redeemed invite", async () => {- const inv = { id: "inv_1" };- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([inv]));- expect(await wi.redeemInvite(chain, "tok", "u")).toEqual(inv);- });-});--describe("deleteInvite", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await wi.deleteInvite(chain, "x", "w")).toBeNull();- });- it("returns deleted invite", async () => {- const inv = { id: "inv_1" };- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([inv]));- expect(await wi.deleteInvite(chain, "inv_1", "w")).toEqual(inv);- });-});diff --git a/src/shared/test/queries/workspace.test.ts b/src/shared/test/queries/workspace.test.tsdeleted file mode 100644index d9cbd78de..000000000--- a/src/shared/test/queries/workspace.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { describe, it, expect, vi } from "vitest";-import * as ws from "../../src/db/queries/workspace";--function createSelectMock(rows: any[]) {- const chain: any = {};- chain.select = vi.fn(() => chain);- chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve(rows));- chain.innerJoin = vi.fn(() => chain);- chain.orderBy = vi.fn(() => chain);- chain.insert = vi.fn(() => chain);- chain.values = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve(rows));- return chain;-}--describe("workspace exports", () => {- it("exports getWorkspace", () => { expect(typeof ws.getWorkspace).toBe("function"); });- it("exports getWorkspaceBySlug", () => { expect(typeof ws.getWorkspaceBySlug).toBe("function"); });- it("exports listWorkspaces", () => { expect(typeof ws.listWorkspaces).toBe("function"); });- it("exports createWorkspace", () => { expect(typeof ws.createWorkspace).toBe("function"); });- it("exports updateWorkspace", () => { expect(typeof ws.updateWorkspace).toBe("function"); });- it("exports deleteWorkspace", () => { expect(typeof ws.deleteWorkspace).toBe("function"); });-});--describe("getWorkspace", () => {- it("returns null when not found", async () => { expect(await ws.getWorkspace(createSelectMock([]), "x", "u")).toBeNull(); });- it("returns workspace", async () => { const w = { id: "ws_1" }; expect(await ws.getWorkspace(createSelectMock([w]), "ws_1", "u")).toEqual(w); });-});--describe("getWorkspaceBySlug", () => {- it("returns null when not found", async () => { expect(await ws.getWorkspaceBySlug(createSelectMock([]), "x")).toBeNull(); });- it("returns workspace", async () => { const w = { id: "ws_1" }; expect(await ws.getWorkspaceBySlug(createSelectMock([w]), "slug")).toEqual(w); });-});--describe("createWorkspace", () => {- it("creates workspace", async () => {- const w = { id: "ws_1" };- expect(await ws.createWorkspace(createSelectMock([w]), { name: "N", slug: "s" })).toEqual(w);- });-});--describe("updateWorkspace", () => {- it("returns null when not found", 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([]));- expect(await ws.updateWorkspace(chain, "x", { name: "N" })).toBeNull();- });- it("returns updated", async () => {- const w = { id: "ws_1" };- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.returning = vi.fn(() => Promise.resolve([w]));- expect(await ws.updateWorkspace(chain, "ws_1", { name: "N" })).toEqual(w);- });-});--describe("deleteWorkspace", () => {- it("returns null when not found", async () => {- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([]));- expect(await ws.deleteWorkspace(chain, "x")).toBeNull();- });- it("returns deleted", async () => {- const w = { id: "ws_1" };- const chain: any = {};- chain.delete = vi.fn(() => chain); chain.where = vi.fn(() => chain);- chain.returning = vi.fn(() => Promise.resolve([w]));- expect(await ws.deleteWorkspace(chain, "ws_1")).toEqual(w);- });-});diff --git a/src/web/knip.json b/src/web/knip.jsonindex 2f8451c63..921fe251a 100644--- a/src/web/knip.json+++ b/src/web/knip.json@@ -27,7 +27,6 @@],"project": ["src/**/*.{ts,tsx,css,mdx}", "blog/**/*.{ts,tsx,css,mdx}", "auth/**/*.{ts,tsx,mts}", "scripts/**/*.{ts,mjs}", "test-runtime/**/*.ts"],"ignoreDependencies": [- "@tailwindcss/node","cloudflare","rehype-autolink-headings","rehype-external-links",diff --git a/src/web/package.json b/src/web/package.jsonindex d20e47288..97ac50872 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -111,7 +111,6 @@"next": "16.4.1","next-themes": "^0.4.6","pdfjs-dist": "6.4.299",- "postal-mime": "^2.7.6","react": "19.3.1","react-dom": "19.3.1","react-easy-crop": "^6.2.4",diff --git a/src/web/src/app/api/agent-links/[id]/route.test.ts b/src/web/src/app/api/agent-links/[id]/route.test.tsdeleted file mode 100644index 159045b57..000000000--- a/src/web/src/app/api/agent-links/[id]/route.test.ts+++ /dev/null@@ -1,149 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockUpdate = vi.fn();-const mockRemove = vi.fn();-const mockGetById = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- },- agentLink: {- getById: (...a: unknown[]) => mockGetById(...a),- update: (...a: unknown[]) => mockUpdate(...a),- remove: (...a: unknown[]) => mockRemove(...a),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/cache", () => ({- invalidate: vi.fn(),- cacheKeys: {- allColleagues: (ws: string) => `allColleagues:${ws}`,- agentLinks: (ws: string) => `agentLinks:${ws}`,- },-}));--vi.mock("@/lib/api/responses", () => ({- agentLinkToResponse: (row: any) => ({- id: row.id,- workspace_id: row.workspaceId,- source_agent_id: row.sourceAgentId,- target_agent_id: row.targetAgentId,- instruction: row.instruction,- created_at: row.createdAt,- updated_at: row.updatedAt,- }),-}));--import { PATCH, DELETE } from "./route";--describe("PATCH /api/agent-links/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("updates instruction", async () => {- mockGetById.mockResolvedValue({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "old instruction",- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-01T00:00:00.000Z",- });- mockGetAgent.mockResolvedValue({ id: "ag_a" });- mockUpdate.mockResolvedValue({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "new instruction",- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-02T00:00:00.000Z",- });- const req = new NextRequest("http://localhost/api/agent-links/al_1", {- method: "PATCH",- body: JSON.stringify({ instruction: "new instruction" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: { id: "al_1" } } as any);- expect(res.status).toBe(200);- const body = await res.json();- expect(body.instruction).toBe("new instruction");- });-- it("returns 404 when link not found", async () => {- mockGetById.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/agent-links/al_nope", {- method: "PATCH",- body: JSON.stringify({ instruction: "test" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: { id: "al_nope" } } as any);- expect(res.status).toBe(404);- });-});--describe("DELETE /api/agent-links/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("deletes a link", async () => {- mockGetById.mockResolvedValue({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "",- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-01T00:00:00.000Z",- });- mockGetAgent.mockResolvedValue({ id: "ag_a" });- mockRemove.mockResolvedValue({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "",- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-01T00:00:00.000Z",- });- const req = new NextRequest("http://localhost/api/agent-links/al_1", {- method: "DELETE",- });- const res = await DELETE(req, { params: { id: "al_1" } } as any);- expect(res.status).toBe(200);- });-- it("returns 404 for unknown link", async () => {- mockGetById.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/agent-links/al_nope", {- method: "DELETE",- });- const res = await DELETE(req, { params: { id: "al_nope" } } as any);- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/agent-links/[id]/route.ts b/src/web/src/app/api/agent-links/[id]/route.tsdeleted file mode 100644index 9cdb289f6..000000000--- a/src/web/src/app/api/agent-links/[id]/route.ts+++ /dev/null@@ -1,59 +0,0 @@-import { queries, UpdateAgentLinkRequestSchema } from "@alook/shared";-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 { agentLinkToResponse } from "@/lib/api/responses";--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("agent link id is required", 400);-- const link = await queries.agentLink.getById(db, id, ws.workspaceId);- if (!link) return writeError("not found", 404);-- const [sourceAgent, targetAgent] = await Promise.all([- queries.agent.getAgent(db, link.sourceAgentId, ws.workspaceId, ctx.userId),- queries.agent.getAgent(db, link.targetAgentId, ws.workspaceId, ctx.userId),- ]);- if (!sourceAgent && !targetAgent) return writeError("not found", 404);-- const [body, err] = await parseBody(req, UpdateAgentLinkRequestSchema);- if (err) return err;-- const updated = await queries.agentLink.update(db, id, ws.workspaceId, {- instruction: body.instruction,- });- if (!updated) return writeError("not found", 404);-- return writeJSON(agentLinkToResponse(updated));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("agent link id is required", 400);-- const link = await queries.agentLink.getById(db, id, ws.workspaceId);- if (!link) return writeError("not found", 404);-- const [sourceAgent, targetAgent] = await Promise.all([- queries.agent.getAgent(db, link.sourceAgentId, ws.workspaceId, ctx.userId),- queries.agent.getAgent(db, link.targetAgentId, ws.workspaceId, ctx.userId),- ]);- if (!sourceAgent && !targetAgent) return writeError("not found", 404);-- const deleted = await queries.agentLink.remove(db, id, ws.workspaceId);- if (!deleted) return writeError("not found", 404);-- return writeJSON(agentLinkToResponse(deleted));-});diff --git a/src/web/src/app/api/agent-links/route.test.ts b/src/web/src/app/api/agent-links/route.test.tsdeleted file mode 100644index 5225aeca7..000000000--- a/src/web/src/app/api/agent-links/route.test.ts+++ /dev/null@@ -1,290 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockListByWorkspace = vi.fn();-const mockCreate = vi.fn();-const mockUpsertByPair = vi.fn();-const mockGetByPair = vi.fn();-const mockUpdate = vi.fn();-const mockInvalidate = vi.fn();-const mockGetAllAgentsForWorkspace = vi.fn();-const mockGetAllAgentAccessForWorkspace = vi.fn();-const mockFilterVisibleAgents = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgentsForWorkspace(...a),- },- agentAccess: {- getAllAgentAccessForWorkspace: (...a: unknown[]) => mockGetAllAgentAccessForWorkspace(...a),- },- agentLink: {- listByWorkspace: (...a: unknown[]) => mockListByWorkspace(...a),- create: (...a: unknown[]) => mockCreate(...a),- upsertByPair: (...a: unknown[]) => mockUpsertByPair(...a),- getByPair: (...a: unknown[]) => mockGetByPair(...a),- update: (...a: unknown[]) => mockUpdate(...a),- },- },- };-});--vi.mock("@/lib/cache", () => ({- invalidate: (...a: unknown[]) => mockInvalidate(...a),- cached: (_k: string, _t: number, fn: () => unknown) => fn(),- cacheKeys: {- agentLinks: (ws: string) => `agentLinks:${ws}`,- allColleagues: (ws: string) => `allColleagues:${ws}`,- allAgents: (ws: string) => `allAgents:${ws}`,- allAgentAccess: (ws: string) => `allAgentAccess:${ws}`,- },-}));--vi.mock("@/lib/agent-visibility", () => ({- filterVisibleAgents: (...a: unknown[]) => mockFilterVisibleAgents(...a),-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/api/responses", () => ({- agentLinkToResponse: (row: any) => ({- id: row.id,- workspace_id: row.workspaceId,- source_agent_id: row.sourceAgentId,- target_agent_id: row.targetAgentId,- instruction: row.instruction,- created_at: row.createdAt,- updated_at: row.updatedAt,- }),-}));--import { GET, POST, PUT } from "./route";--describe("GET /api/agent-links", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists links scoped to workspace", async () => {- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag_a" }, { id: "ag_b" }]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);- mockFilterVisibleAgents.mockReturnValue([{ id: "ag_a" }, { id: "ag_b" }]);- mockListByWorkspace.mockResolvedValue([- {- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "collaborate",- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-01T00:00:00.000Z",- },- ]);- const req = new NextRequest("http://localhost/api/agent-links?workspace_id=ws1");- const res = await GET(req, {} as any);- const body = await res.json();- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].id).toBe("al_1");- expect(body[0].source_agent_id).toBe("ag_a");- });-});--describe("POST /api/agent-links", () => {- beforeEach(() => vi.clearAllMocks());-- async function post(body: unknown) {- const req = new NextRequest("http://localhost/api/agent-links", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });- return POST(req, {} as any);- }-- it("creates a link between two agents", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_a" });- mockCreate.mockImplementation((_db: any, data: any) => ({- id: "al_1",- ...data,- createdAt: "2026-04-01T00:00:00.000Z",- updatedAt: "2026-04-01T00:00:00.000Z",- }));- const res = await post({- source_agent_id: "ag_a",- target_agent_id: "ag_b",- instruction: "share data",- });- expect(res.status).toBe(201);- const body = await res.json();- expect(body.id).toBe("al_1");- });-- it("rejects self-link", async () => {- const res = await post({- source_agent_id: "ag_a",- target_agent_id: "ag_a",- });- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("itself");- });-- it("returns 404 when source agent not found", async () => {- mockGetAgent.mockResolvedValueOnce(null);- const res = await post({- source_agent_id: "ag_nope",- target_agent_id: "ag_b",- });- expect(res.status).toBe(404);- });-- it("returns 404 when target agent not found", async () => {- mockGetAgent.mockResolvedValueOnce({ id: "ag_a" }).mockResolvedValueOnce(null);- const res = await post({- source_agent_id: "ag_a",- target_agent_id: "ag_nope",- });- expect(res.status).toBe(404);- });-- it("returns 409 for duplicate link", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_a" });- const uniqueErr = new Error("UNIQUE constraint failed");- (uniqueErr as any).code = "SQLITE_CONSTRAINT_UNIQUE";- mockCreate.mockRejectedValue(uniqueErr);- const res = await post({- source_agent_id: "ag_a",- target_agent_id: "ag_b",- });- expect(res.status).toBe(409);- });-});--describe("PUT /api/agent-links (upsert)", () => {- beforeEach(() => vi.clearAllMocks());-- function put(body: unknown, query = "?agentId=ag_a") {- const req = new NextRequest(`http://localhost/api/agent-links${query}`, {- method: "PUT",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });- return PUT(req, {} as any);- }-- // TC5- it("returns 400 when agentId query param is missing", async () => {- const res = await put({ target_agent_id: "ag_b", instruction: "x" }, "");- expect(res.status).toBe(400);- });-- // TC6- it("returns 400 for self-link", async () => {- const res = await put({ target_agent_id: "ag_a", instruction: "x" });- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("itself");- });-- // TC7 — caller not in workspace- it("returns 404 when calling agent not found", async () => {- mockGetAgent.mockResolvedValueOnce(null).mockResolvedValueOnce({ id: "ag_b" });- const res = await put({ target_agent_id: "ag_b", instruction: "x" });- expect(res.status).toBe(404);- });-- // TC7 — target not in workspace- it("returns 404 when target agent not found", async () => {- mockGetAgent.mockResolvedValueOnce({ id: "ag_a" }).mockResolvedValueOnce(null);- const res = await put({ target_agent_id: "ag_nope", instruction: "x" });- expect(res.status).toBe(404);- });-- // TC8- it("creates a new pair -> 201, created:true", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_x" });- mockUpsertByPair.mockResolvedValue({- row: {- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "delegate",- createdAt: "2026-06-01T00:00:00.000Z",- updatedAt: "2026-06-01T00:00:00.000Z",- },- created: true,- });- const res = await put({ target_agent_id: "ag_b", instruction: "delegate" });- expect(res.status).toBe(201);- const body = await res.json();- expect(body.created).toBe(true);- expect(body.instruction).toBe("delegate");- });-- // TC9- it("updates an existing pair -> 200, created:false, replaced instruction", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_x" });- mockUpsertByPair.mockResolvedValue({- row: {- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "new instruction",- createdAt: "2026-06-01T00:00:00.000Z",- updatedAt: "2026-06-01T01:00:00.000Z",- },- created: false,- });- const res = await put({ target_agent_id: "ag_b", instruction: "new instruction" });- expect(res.status).toBe(200);- const body = await res.json();- expect(body.created).toBe(false);- expect(body.instruction).toBe("new instruction");- });-- // TC10- it("falls back to update on a concurrent-create unique race (no throw)", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_x" });- const uniqueErr = new Error("UNIQUE constraint failed");- (uniqueErr as any).code = "SQLITE_CONSTRAINT_UNIQUE";- mockUpsertByPair.mockRejectedValue(uniqueErr);- mockGetByPair.mockResolvedValue({ id: "al_1", workspaceId: "ws1" });- mockUpdate.mockResolvedValue({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "raced",- createdAt: "2026-06-01T00:00:00.000Z",- updatedAt: "2026-06-01T02:00:00.000Z",- });- const res = await put({ target_agent_id: "ag_b", instruction: "raced" });- expect(res.status).toBe(200);- const body = await res.json();- expect(body.created).toBe(false);- expect(body.instruction).toBe("raced");- expect(mockUpdate).toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agent-links/route.ts b/src/web/src/app/api/agent-links/route.tsdeleted file mode 100644index c3849943e..000000000--- a/src/web/src/app/api/agent-links/route.ts+++ /dev/null@@ -1,129 +0,0 @@-import { NextRequest } from "next/server";-import {- queries,- CreateAgentLinkRequestSchema,- UpsertAgentLinkRequestSchema,- isUniqueConstraintError,-} from "@alook/shared";-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 { agentLinkToResponse } from "@/lib/api/responses";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const url = new URL(req.url);- const limit = Math.min(Number(url.searchParams.get("limit")) || 200, 500);- const offset = Number(url.searchParams.get("offset")) || 0;-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const visibleIds = new Set(filterVisibleAgents(allAgents, ctx.userId, allAccess).map((a) => a.id));-- const rows = await queries.agentLink.listByWorkspace(db, ws.workspaceId, { limit, offset });- const filtered = rows- .filter((r) => visibleIds.has(r.sourceAgentId) || visibleIds.has(r.targetAgentId))- .map(agentLinkToResponse);-- return writeJSON(filtered);-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const [body, err] = await parseBody(req, CreateAgentLinkRequestSchema);- if (err) return err;-- if (body.source_agent_id === body.target_agent_id) {- return writeError("cannot link an agent to itself", 400);- }-- const [sourceAgent, targetAgent] = await Promise.all([- queries.agent.getAgent(db, body.source_agent_id, ws.workspaceId, ctx.userId),- queries.agent.getAgent(db, body.target_agent_id, ws.workspaceId, ctx.userId),- ]);- if (!sourceAgent) return writeError("source agent not found in workspace", 404);- if (!targetAgent) return writeError("target agent not found in workspace", 404);-- try {- const created = await queries.agentLink.create(db, {- workspaceId: ws.workspaceId,- sourceAgentId: body.source_agent_id,- targetAgentId: body.target_agent_id,- instruction: body.instruction,- });- return writeJSON(agentLinkToResponse(created), 201);- } catch (e) {- if (isUniqueConstraintError(e)) {- return writeError("link already exists between these agents", 409);- }- throw e;- }-});--// PUT /api/agent-links?agentId=<caller> — upsert (create-or-replace) the-// relationship between the calling agent and a target agent. Idempotent: a new-// pair is created (201), an existing pair has its instruction replaced (200).-export const PUT = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = new URL(req.url).searchParams.get("agentId");- if (!agentId) {- return writeError("agentId query param is required", 400);- }-- const [body, err] = await parseBody(req, UpsertAgentLinkRequestSchema);- if (err) return err;-- if (agentId === body.target_agent_id) {- return writeError("cannot link an agent to itself", 400);- }-- const [callerAgent, targetAgent] = await Promise.all([- queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId),- queries.agent.getAgent(db, body.target_agent_id, ws.workspaceId, ctx.userId),- ]);- if (!callerAgent) return writeError("calling agent not found in workspace", 404);- if (!targetAgent) return writeError("target agent not found in workspace", 404);-- let row, created;- try {- ({ row, created } = await queries.agentLink.upsertByPair(db, {- workspaceId: ws.workspaceId,- sourceAgentId: agentId,- targetAgentId: body.target_agent_id,- instruction: body.instruction,- }));- } catch (e) {- if (!isUniqueConstraintError(e)) throw e;- // Lost a concurrent create race — the row now exists; fall back to update.- const existing = await queries.agentLink.getByPair(- db,- ws.workspaceId,- agentId,- body.target_agent_id,- );- if (!existing) throw e;- row = await queries.agentLink.update(db, existing.id, ws.workspaceId, {- instruction: body.instruction,- });- created = false;- }-- return writeJSON({ ...agentLinkToResponse(row), created }, created ? 201 : 200);-});diff --git a/src/web/src/app/api/agents/[id]/access/[userId]/route.test.ts b/src/web/src/app/api/agents/[id]/access/[userId]/route.test.tsdeleted file mode 100644index ac12efb9a..000000000--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockListAgentAccess = vi.fn();-const mockRevokeAgentAccess = vi.fn();-const mockRemoveWhitelistByEmail = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- agentAccess: {- listAgentAccess: (...args: unknown[]) => mockListAgentAccess(...args),- revokeAgentAccess: (...args: unknown[]) => mockRevokeAgentAccess(...args),- },- whitelist: {- removeWhitelistByEmail: (...args: unknown[]) => mockRemoveWhitelistByEmail(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "member" })),-}));--import { DELETE } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("DELETE /api/agents/[id]/access/[userId]", () => {- it("revokes access and returns 204 without removing whitelist", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockListAgentAccess.mockResolvedValue([{ userId: "u2", userEmail: "[email protected]" }]);- mockRevokeAgentAccess.mockResolvedValue({ id: "ac1", userId: "u2" });-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2?workspace_id=w1", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);-- expect(res.status).toBe(204);- expect(mockRevokeAgentAccess).toHaveBeenCalledWith({}, "a1", "w1", "u2");- expect(mockRemoveWhitelistByEmail).not.toHaveBeenCalled();- });-- it("also removes whitelist when remove_whitelist=true", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockListAgentAccess.mockResolvedValue([{ userId: "u2", userEmail: "[email protected]" }]);- mockRevokeAgentAccess.mockResolvedValue({ id: "ac1", userId: "u2" });- mockRemoveWhitelistByEmail.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2?workspace_id=w1&remove_whitelist=true", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);-- expect(res.status).toBe(204);- expect(mockRemoveWhitelistByEmail).toHaveBeenCalledWith({}, "a1", "w1", "[email protected]");- });-- it("does not remove whitelist when member has no email even with remove_whitelist=true", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockListAgentAccess.mockResolvedValue([{ userId: "u2" }]);- mockRevokeAgentAccess.mockResolvedValue({ id: "ac1", userId: "u2" });-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2?workspace_id=w1&remove_whitelist=true", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);-- expect(res.status).toBe(204);- expect(mockRemoveWhitelistByEmail).not.toHaveBeenCalled();- });-- it("returns 404 when access record not found", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockListAgentAccess.mockResolvedValue([]);- mockRevokeAgentAccess.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("access record not found");- });-- it("returns 403 when user is not agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "other-user" });-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/access/u2", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", userId: "u2" }) };- const res = await DELETE(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-});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.tsdeleted file mode 100644index 69d7c145f..000000000--- a/src/web/src/app/api/agents/[id]/access/[userId]/route.ts+++ /dev/null@@ -1,27 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-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);- if (ws instanceof Response) return ws;- const { id: agentId, userId: targetUserId } = ctx.params!;- const db = getDb(ctx.env.DB);- const ag = await queries.agent.getAgent(db, agentId, ws.workspaceId);- if (!ag) return writeError("agent not found", 404);- if (ag.ownerId !== ctx.userId) return writeError("agent owner access required", 403);- const accessList = await queries.agentAccess.listAgentAccess(db, agentId, ws.workspaceId);- const member = accessList.find((a) => a.userId === targetUserId);- const revoked = await queries.agentAccess.revokeAgentAccess(db, agentId, ws.workspaceId, targetUserId);- if (!revoked) return writeError("access record not found", 404);- const removeWhitelist = new URL(req.url).searchParams.get("remove_whitelist") === "true";- if (removeWhitelist && member?.userEmail) {- await queries.whitelist.removeWhitelistByEmail(db, agentId, ws.workspaceId, member.userEmail);- }- await invalidate(cacheKeys.allAgentAccess(ws.workspaceId));- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/agents/[id]/access/route.test.ts b/src/web/src/app/api/agents/[id]/access/route.test.tsdeleted file mode 100644index 2adfba0d7..000000000--- a/src/web/src/app/api/agents/[id]/access/route.test.ts+++ /dev/null@@ -1,187 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockListAgentAccess = vi.fn();-const mockGrantAgentAccess = vi.fn();-const mockAddWhitelist = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- agentAccess: {- listAgentAccess: (...args: unknown[]) => mockListAgentAccess(...args),- grantAgentAccess: (...args: unknown[]) => mockGrantAgentAccess(...args),- },- whitelist: {- addWhitelist: (...args: unknown[]) => mockAddWhitelist(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "member" })),-}));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]/access", () => {- it("returns access list for agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockListAgentAccess.mockResolvedValue([- { id: "ac1", userId: "u2", userName: "Bob", userEmail: "[email protected]", createdAt: "2024-01-01T00:00:00Z" },- ]);-- const req = new NextRequest("http://localhost/api/agents/a1/access");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0]).toEqual({ id: "ac1", user_id: "u2", name: "Bob", email: "[email protected]", created_at: "2024-01-01T00:00:00Z" });- });-- it("returns 403 when user is not agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "other-user" });-- const req = new NextRequest("http://localhost/api/agents/a1/access");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });-- it("returns 403 when agent has null ownerId", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: null });-- const req = new NextRequest("http://localhost/api/agents/a1/access");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/missing/access");- const ctx = { params: Promise.resolve({ id: "missing" }) };- const res = await GET(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-});--describe("POST /api/agents/[id]/access", () => {- it("grants access and returns 201", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockGrantAgentAccess.mockResolvedValue({ id: "ac1", userId: "u2" });- mockListAgentAccess.mockResolvedValue([{ userId: "u2", userEmail: "[email protected]" }]);- mockAddWhitelist.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/access", {- method: "POST",- body: JSON.stringify({ user_id: "u2" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({ id: "ac1", user_id: "u2" });- expect(mockGrantAgentAccess).toHaveBeenCalledWith(- {},- { agentId: "a1", workspaceId: "w1", userId: "u2" }- );- expect(mockAddWhitelist).toHaveBeenCalledWith({}, "a1", "w1", "[email protected]");- });-- it("does not add whitelist when member has no email", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockGrantAgentAccess.mockResolvedValue({ id: "ac1", userId: "u2" });- mockListAgentAccess.mockResolvedValue([{ userId: "u2", userEmail: undefined }]);-- const req = new NextRequest("http://localhost/api/agents/a1/access", {- method: "POST",- body: JSON.stringify({ user_id: "u2" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx as any);-- expect(res.status).toBe(201);- expect(mockAddWhitelist).not.toHaveBeenCalled();- });-- it("returns 403 when user is not agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "other-user" });-- const req = new NextRequest("http://localhost/api/agents/a1/access", {- method: "POST",- body: JSON.stringify({ user_id: "u2" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/access", {- method: "POST",- body: JSON.stringify({ user_id: "u2" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns 400 for invalid body", async () => {- const req = new NextRequest("http://localhost/api/agents/a1/access", {- method: "POST",- body: JSON.stringify({ user_id: "" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx as any);-- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/agents/[id]/access/route.ts b/src/web/src/app/api/agents/[id]/access/route.tsdeleted file mode 100644index 4fd976d52..000000000--- a/src/web/src/app/api/agents/[id]/access/route.ts+++ /dev/null@@ -1,46 +0,0 @@-import { NextRequest } from "next/server";-import { queries, GrantAgentAccessRequestSchema, type Database } from "@alook/shared";-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);- if (!ag) return { error: writeError("agent not found", 404) };- if (ag.ownerId !== userId) return { error: writeError("agent owner access required", 403) };- return { agent: ag };-}--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- const { id } = ctx.params!;- const db = getDb(ctx.env.DB);- const check = await requireAgentOwner(db, id, ws.workspaceId, ctx.userId);- if (check.error) return check.error;- const accessList = await queries.agentAccess.listAgentAccess(db, id, ws.workspaceId);- return writeJSON(accessList.map((a) => ({- id: a.id, user_id: a.userId, name: a.userName, email: a.userEmail, created_at: a.createdAt,- })));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- const { id } = ctx.params!;- const [body, err] = await parseBody(req, GrantAgentAccessRequestSchema);- if (err) return err;- const db = getDb(ctx.env.DB);- const check = await requireAgentOwner(db, id, ws.workspaceId, ctx.userId);- if (check.error) return check.error;- const access = await queries.agentAccess.grantAgentAccess(db, { agentId: id, workspaceId: ws.workspaceId, userId: body.user_id });- const accessList = await queries.agentAccess.listAgentAccess(db, id, ws.workspaceId);- const member = accessList.find((a) => a.userId === body.user_id);- if (member?.userEmail) {- await queries.whitelist.addWhitelist(db, id, ws.workspaceId, member.userEmail);- }- await invalidate(cacheKeys.allAgentAccess(ws.workspaceId));- return writeJSON({ id: access.id, user_id: access.userId }, 201);-});diff --git a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts b/src/web/src/app/api/agents/[id]/active-tasks/route.test.tsdeleted file mode 100644index 43a0f2231..000000000--- a/src/web/src/app/api/agents/[id]/active-tasks/route.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockListActiveTasksByAgent = vi.fn();--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- agent: { getAgent: (...args: any[]) => mockGetAgent(...args) },- task: { listActiveTasksByAgent: (...args: any[]) => mockListActiveTasksByAgent(...args) },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--const withParams = (id: string) => ({ params: Promise.resolve({ id }) });--describe("GET /api/agents/[id]/active-tasks", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns correct task list", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListActiveTasksByAgent.mockResolvedValue([- { id: "t1", status: "running", type: "user_dm_message", conversationId: "c1", createdAt: "2026-01-01T00:00:00Z" },- { id: "t2", status: "queued", type: "email_notification", conversationId: "c2", createdAt: "2026-01-01T00:01:00Z" },- { id: "t3", status: "running", type: "issue_event", conversationId: "c3", createdAt: "2026-01-01T00:02:00Z" },- ]);-- const res = await GET(- new NextRequest("http://localhost/api/agents/a1/active-tasks"),- withParams("a1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toHaveLength(3);- expect(body.tasks[0]).toEqual({- id: "t1",- status: "running",- type: "user_dm_message",- created_at: "2026-01-01T00:00:00Z",- });- expect(body.tasks[1]).toEqual({- id: "t2",- status: "queued",- type: "email_notification",- created_at: "2026-01-01T00:01:00Z",- });- expect(body.tasks[2]).toEqual({- id: "t3",- status: "running",- type: "issue_event",- created_at: "2026-01-01T00:02:00Z",- });- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/agents/a1/active-tasks"),- withParams("a1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns empty tasks array when no active tasks", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListActiveTasksByAgent.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/agents/a1/active-tasks"),- withParams("a1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- });-- it("passes userId to query for data isolation", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListActiveTasksByAgent.mockResolvedValue([]);-- await GET(- new NextRequest("http://localhost/api/agents/a1/active-tasks"),- withParams("a1")- );-- expect(mockListActiveTasksByAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");- });-});diff --git a/src/web/src/app/api/agents/[id]/active-tasks/route.ts b/src/web/src/app/api/agents/[id]/active-tasks/route.tsdeleted file mode 100644index 482522710..000000000--- a/src/web/src/app/api/agents/[id]/active-tasks/route.ts+++ /dev/null@@ -1,28 +0,0 @@-import { createDb, queries } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = createDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("agent id is required", 400);-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);-- const tasks = await queries.task.listActiveTasksByAgent(db, id, ws.workspaceId, ctx.userId);-- return writeJSON({- tasks: tasks.map((t) => ({- id: t.id,- status: t.status,- type: t.type,- created_at: t.createdAt,- })),- });-});diff --git a/src/web/src/app/api/agents/[id]/activity/route.test.ts b/src/web/src/app/api/agents/[id]/activity/route.test.tsdeleted file mode 100644index 5f89351bf..000000000--- a/src/web/src/app/api/agents/[id]/activity/route.test.ts+++ /dev/null@@ -1,228 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockListTaskHistory = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- task: {- listTaskHistory: (...args: unknown[]) => mockListTaskHistory(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- taskToActivityResponse: vi.fn((t: any) => ({- id: t.id,- conversation_id: t.conversationId,- type: t.type,- status: t.status,- prompt: t.prompt?.slice(0, 120),- created_at: t.createdAt,- started_at: t.startedAt,- completed_at: t.completedAt,- error: t.error || null,- })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--const makeTask = (overrides: Record<string, unknown> = {}) => ({- id: "t1",- agentId: "a1",- conversationId: "c1",- workspaceId: "w1",- prompt: "Do something",- type: "user_dm_message",- status: "completed",- createdAt: "2025-01-01T00:00:00.000Z",- startedAt: "2025-01-01T00:00:01.000Z",- completedAt: "2025-01-01T00:00:10.000Z",- error: null,- ...overrides,-});--describe("GET /api/agents/[id]/activity", () => {- it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns tasks with has_more", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({- tasks: [makeTask()],- hasMore: true,- });-- const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toHaveLength(1);- expect(body.has_more).toBe(true);- expect(body.tasks[0].id).toBe("t1");- });-- it("parses comma-separated status params", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });-- const req = new NextRequest(- "http://localhost/api/agents/a1/activity?workspace_id=w1&status=queued,dispatched"- );- const ctx = { params: Promise.resolve({ id: "a1" }) };- await GET(req, ctx);-- expect(mockListTaskHistory).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ status: ["queued", "dispatched"] })- );- });-- it("parses comma-separated type params", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });-- const req = new NextRequest(- "http://localhost/api/agents/a1/activity?workspace_id=w1&type=user_dm_message,email_notification"- );- const ctx = { params: Promise.resolve({ id: "a1" }) };- await GET(req, ctx);-- expect(mockListTaskHistory).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ type: ["user_dm_message", "email_notification"] })- );- });-- it("clamps limit to 1-100 range", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });-- const req = new NextRequest(- "http://localhost/api/agents/a1/activity?workspace_id=w1&limit=999"- );- const ctx = { params: Promise.resolve({ id: "a1" }) };- await GET(req, ctx);-- expect(mockListTaskHistory).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ limit: 100 })- );- });-- it("clamps limit minimum to 1", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });-- const req = new NextRequest(- "http://localhost/api/agents/a1/activity?workspace_id=w1&limit=0"- );- const ctx = { params: Promise.resolve({ id: "a1" }) };- await GET(req, ctx);-- expect(mockListTaskHistory).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ limit: 1 })- );- });-- it("passes before and before_id cursor params", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });-- const req = new NextRequest(- "http://localhost/api/agents/a1/activity?workspace_id=w1&before=2025-01-01T00:00:00.000Z&before_id=t5"- );- const ctx = { params: Promise.resolve({ id: "a1" }) };- await GET(req, ctx);-- expect(mockListTaskHistory).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({- before: "2025-01-01T00:00:00.000Z",- beforeId: "t5",- })- );- });-- it("returns has_more false when no more tasks", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({- tasks: [makeTask()],- hasMore: false,- });-- const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(body.has_more).toBe(false);- });-- it("taskToActivityResponse truncates prompt and omits result/context", async () => {- const longPrompt = "x".repeat(200);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskHistory.mockResolvedValue({- tasks: [makeTask({ prompt: longPrompt })],- hasMore: false,- });-- const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(body.tasks[0].prompt.length).toBeLessThanOrEqual(120);- expect(body.tasks[0]).not.toHaveProperty("result");- expect(body.tasks[0]).not.toHaveProperty("context");- });-});diff --git a/src/web/src/app/api/agents/[id]/activity/route.ts b/src/web/src/app/api/agents/[id]/activity/route.tsdeleted file mode 100644index b39c1770a..000000000--- a/src/web/src/app/api/agents/[id]/activity/route.ts+++ /dev/null@@ -1,44 +0,0 @@-import { createDb, queries } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToActivityResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = createDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("agent id is required", 400);-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);-- const url = new URL(req.url);- const limitParam = url.searchParams.get("limit");- const before = url.searchParams.get("before") || undefined;- const beforeId = url.searchParams.get("before_id") || undefined;- const statusParam = url.searchParams.get("status");- const typeParam = url.searchParams.get("type");-- const parsedLimit = limitParam ? parseInt(limitParam, 10) : NaN;- const limit = Number.isNaN(parsedLimit) ? 30 : Math.min(Math.max(parsedLimit, 1), 100);-- const status = statusParam ? statusParam.split(",").filter(Boolean) : undefined;- const type = typeParam ? typeParam.split(",").filter(Boolean) : undefined;-- const result = await queries.task.listTaskHistory(db, id, ws.workspaceId, {- limit,- before,- beforeId,- status,- type,- });-- return writeJSON({- tasks: result.tasks.map(taskToActivityResponse),- has_more: result.hasMore,- });-});diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts b/src/web/src/app/api/agents/[id]/chat-init/route.test.tsdeleted file mode 100644index 0ce14a2b5..000000000--- a/src/web/src/app/api/agents/[id]/chat-init/route.test.ts+++ /dev/null@@ -1,299 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockGetOrCreateAgentConversation = vi.fn();-const mockHasPreviousConversations = vi.fn();-const mockListMessages = vi.fn();-const mockListArtifactsByConversation = vi.fn();-const mockGetActiveTaskByConversation = vi.fn();-const mockListTaskErrorMessages = vi.fn();-const mockArtifactToResponse = vi.fn((r: any) => ({- id: r.id,- conversation_id: r.conversationId,- agent_id: r.agentId,- filename: r.filename,- content_type: r.contentType,- size: r.size,- source: r.source,- has_thumbnail: r.thumbnailR2Key != null,- created_at: r.createdAt,-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- conversation: {- getOrCreateAgentConversation: (...args: unknown[]) =>- mockGetOrCreateAgentConversation(...args),- hasPreviousConversations: (...args: unknown[]) =>- mockHasPreviousConversations(...args),- },- message: {- listMessages: (...args: unknown[]) => mockListMessages(...args),- },- artifact: {- listArtifactsByConversation: (...args: unknown[]) =>- mockListArtifactsByConversation(...args),- artifactToResponse: (...args: unknown[]) =>- mockArtifactToResponse(...args),- },- task: {- getActiveTaskByConversation: (...args: unknown[]) =>- mockGetActiveTaskByConversation(...args),- },- taskMessage: {- listTaskErrorMessages: (...args: unknown[]) =>- mockListTaskErrorMessages(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({- id: c.id,- agent_id: c.agentId,- title: c.title,- created_at: c.createdAt,- })),- messageToResponse: vi.fn((m: any) => ({- id: m.id,- conversation_id: m.conversationId,- role: m.role,- content: m.content,- task_id: m.taskId || null,- attachment_ids: null,- created_at: m.createdAt,- })),- taskToResponse: vi.fn((t: any) => ({- id: t.id,- status: t.status,- agent_id: t.agentId,- created_at: t.createdAt,- })),- taskMessageToResponse: vi.fn((m: any) => ({- id: m.id,- task_id: m.taskId,- seq: m.seq,- type: m.type,- content: m.content,- })),-}));--import { POST } from "./route";--beforeEach(() => vi.clearAllMocks());--const makeReq = () =>- new NextRequest("http://localhost/api/agents/a1/chat-init", {- method: "POST",- });-const makeCtx = () => ({ params: Promise.resolve({ id: "a1" }) });--const CONV = {- id: "c1",- agentId: "a1",- title: "Hello",- createdAt: "2024-01-01T00:00:00.000Z",-};--function setupDefaults() {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent" });- mockGetOrCreateAgentConversation.mockResolvedValue(CONV);- mockHasPreviousConversations.mockResolvedValue(false);- mockListMessages.mockResolvedValue({ messages: [], has_more: false });- mockListArtifactsByConversation.mockResolvedValue([]);- mockGetActiveTaskByConversation.mockResolvedValue(null);-}--describe("POST /api/agents/[id]/chat-init", () => {- it("returns all chat data in a single response", async () => {- const msg = {- id: "m1",- conversationId: "c1",- role: "user",- content: "hi",- taskId: null,- createdAt: "2024-01-01T00:00:00.000Z",- };- const artifact = {- id: "art1",- conversationId: "c1",- agentId: "a1",- filename: "test.png",- contentType: "image/png",- size: 100,- source: "agent",- createdAt: "2024-01-01T00:00:00.000Z",- };-- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent" });- mockGetOrCreateAgentConversation.mockResolvedValue(CONV);- mockHasPreviousConversations.mockResolvedValue(false);- mockListMessages.mockResolvedValue({ messages: [msg], has_more: false });- mockListArtifactsByConversation.mockResolvedValue([artifact]);- mockGetActiveTaskByConversation.mockResolvedValue(null);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.conversation.id).toBe("c1");- expect(body.messages).toHaveLength(1);- expect(body.messages[0].id).toBe("m1");- expect(body.artifacts).toHaveLength(1);- expect(body.artifacts[0].id).toBe("art1");- expect(body.active_task).toBeNull();- expect(body.task_messages).toEqual([]);- expect(body.has_more_messages).toBe(false);- expect(body.has_more_conversations).toBe(false);- expect(body.has_more_artifacts).toBe(false);- });-- it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("preloads error task messages (workspace-scoped) for a running task", async () => {- const task = {- id: "t1",- agentId: "a1",- runtimeId: "r1",- conversationId: "c1",- workspaceId: "w1",- prompt: "do stuff",- status: "running",- priority: 0,- dispatchedAt: null,- startedAt: "2024-01-01T00:00:00.000Z",- completedAt: null,- createdAt: "2024-01-01T00:00:00.000Z",- };- // The query filters to type:"error" in SQL; the route maps what it returns.- const errMsg = { id: "tm2", taskId: "t1", seq: 2, type: "error", content: "boom" };-- setupDefaults();- mockGetActiveTaskByConversation.mockResolvedValue(task);- mockListTaskErrorMessages.mockResolvedValue([errMsg]);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(body.active_task).not.toBeNull();- expect(body.active_task.id).toBe("t1");- expect(body.task_messages).toHaveLength(1);- expect(body.task_messages[0].seq).toBe(2);- expect(body.task_messages[0].type).toBe("error");- // Scoped to the active task and the authed workspace.- expect(mockListTaskErrorMessages).toHaveBeenCalledWith(- expect.anything(),- "t1",- "w1",- );- });-- it("does not query task errors when there is no active task", async () => {- // A run that ended in error is settled to status:"failed" and re-surfaces via- // its persisted assistant error message (not through this preload).- setupDefaults();- mockGetActiveTaskByConversation.mockResolvedValue(null);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(body.active_task).toBeNull();- expect(body.task_messages).toEqual([]);- expect(mockListTaskErrorMessages).not.toHaveBeenCalled();- });-- it("sets has_more_messages true when messages reach limit", async () => {- const msgs = Array.from({ length: 20 }, (_, i) => ({- id: `m${i}`,- conversationId: "c1",- role: "user",- content: `msg ${i}`,- taskId: null,- createdAt: "2024-01-01T00:00:00.000Z",- }));-- setupDefaults();- mockListMessages.mockResolvedValue({ messages: msgs, has_more: true });-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(body.has_more_messages).toBe(true);- expect(body.messages).toHaveLength(20);- });-- it("sets has_more_artifacts true when artifacts reach limit", async () => {- const arts = Array.from({ length: 50 }, (_, i) => ({- id: `art${i}`,- conversationId: "c1",- agentId: "a1",- filename: `file${i}.png`,- contentType: "image/png",- size: 100,- source: "agent",- createdAt: "2024-01-01T00:00:00.000Z",- }));-- setupDefaults();- mockListArtifactsByConversation.mockResolvedValue(arts);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(body.has_more_artifacts).toBe(true);- expect(body.artifacts).toHaveLength(50);- });-- it("sets has_more_conversations true when previous conversations exist", async () => {- setupDefaults();- mockHasPreviousConversations.mockResolvedValue(true);-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(body.has_more_conversations).toBe(true);- });-- it("returns empty state for new conversation", async () => {- setupDefaults();-- const res = await POST(makeReq(), makeCtx());- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.messages).toEqual([]);- expect(body.artifacts).toEqual([]);- expect(body.active_task).toBeNull();- expect(body.has_more_messages).toBe(false);- });-});diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.ts b/src/web/src/app/api/agents/[id]/chat-init/route.tsdeleted file mode 100644index 4416bf6f8..000000000--- a/src/web/src/app/api/agents/[id]/chat-init/route.ts+++ /dev/null@@ -1,99 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import {- conversationToResponse,- messageToResponse,- taskToResponse,- taskMessageToResponse,-} from "@/lib/api/responses";--const MESSAGE_LIMIT = 20;-const ARTIFACT_LIMIT = 50;--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("agent not found", 404);- }-- let channel: string | undefined;- try {- const body = (await req.json()) as { channel?: string };- channel = typeof body.channel === "string" ? body.channel : undefined;- } catch {- // no body — backward compatible- }-- const conversation = await queries.conversation.getOrCreateAgentConversation(- db,- ws.workspaceId,- ctx.userId,- id,- channel,- );-- const convId = conversation.id;-- const [messagesResult, artifactsResult, activeTaskResult, hasMoreConvsResult] =- await Promise.allSettled([- queries.message.listMessages(db, convId, { limit: MESSAGE_LIMIT }),- queries.artifact.listArtifactsByConversation(db, convId, ws.workspaceId, {- limit: ARTIFACT_LIMIT,- }),- queries.task.getActiveTaskByConversation(db, convId, ws.workspaceId),- queries.conversation.hasPreviousConversations(- db, ws.workspaceId, ctx.userId, id, convId, channel,- ),- ]);-- const { messages, has_more: hasMoreMessages } =- messagesResult.status === "fulfilled"- ? messagesResult.value- : { messages: [] as never[], has_more: false };- const artifacts =- artifactsResult.status === "fulfilled" ? artifactsResult.value : [];- const activeTask =- activeTaskResult.status === "fulfilled"- ? activeTaskResult.value- : null;- const hasMoreConvs =- hasMoreConvsResult.status === "fulfilled" ? hasMoreConvsResult.value : false;-- let taskMessages: unknown[] = [];- if (activeTask) {- try {- const tmsgs = await queries.taskMessage.listTaskErrorMessages(- db,- activeTask.id,- ws.workspaceId,- );- taskMessages = tmsgs.map(taskMessageToResponse);- } catch {- // non-critical — frontend will recover via polling- }- }-- return writeJSON({- conversation: conversationToResponse(conversation),- messages: messages.map(messageToResponse),- artifacts: artifacts.map(queries.artifact.artifactToResponse),- active_task: activeTask ? taskToResponse(activeTask) : null,- task_messages: taskMessages,- has_more_messages: hasMoreMessages,- has_more_conversations: hasMoreConvs,- has_more_artifacts: artifacts.length >= ARTIFACT_LIMIT,- });-});diff --git a/src/web/src/app/api/agents/[id]/conversation/route.test.ts b/src/web/src/app/api/agents/[id]/conversation/route.test.tsdeleted file mode 100644index 1498335e3..000000000--- a/src/web/src/app/api/agents/[id]/conversation/route.test.ts+++ /dev/null@@ -1,144 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockGetOrCreateAgentConversation = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- conversation: {- getOrCreateAgentConversation: (...args: unknown[]) =>- mockGetOrCreateAgentConversation(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({- id: c.id,- agent_id: c.agentId,- title: c.title,- created_at: c.createdAt,- })),-}));--import { POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("POST /api/agents/[id]/conversation", () => {- it("returns 200 with existing conversation", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockGetOrCreateAgentConversation.mockResolvedValue({- id: "c1",- agentId: "a1",- title: "Existing",- createdAt: "2024-01-01T00:00:00.000Z",- });-- const req = new NextRequest("http://localhost/api/agents/a1/conversation", {- method: "POST",- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({- id: "c1",- agent_id: "a1",- title: "Existing",- created_at: "2024-01-01T00:00:00.000Z",- });- expect(mockGetOrCreateAgentConversation).toHaveBeenCalledWith(- {},- "w1",- "u1",- "a1",- undefined- );- });-- it("creates conversation when none exists", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockGetOrCreateAgentConversation.mockResolvedValue({- id: "c-new",- agentId: "a1",- title: "",- createdAt: "2024-01-02T00:00:00.000Z",- });-- const req = new NextRequest("http://localhost/api/agents/a1/conversation", {- method: "POST",- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.id).toBe("c-new");- expect(body.title).toBe("");- });-- it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/conversation", {- method: "POST",- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns same conversation on second call", async () => {- const conv = {- id: "c1",- agentId: "a1",- title: "Hello",- createdAt: "2024-01-01T00:00:00.000Z",- };- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockGetOrCreateAgentConversation.mockResolvedValue(conv);-- const req1 = new NextRequest("http://localhost/api/agents/a1/conversation", {- method: "POST",- });- const req2 = new NextRequest("http://localhost/api/agents/a1/conversation", {- method: "POST",- });- const ctx = { params: Promise.resolve({ id: "a1" }) };-- const res1 = await POST(req1, ctx);- const body1 = await res1.json();-- const ctx2 = { params: Promise.resolve({ id: "a1" }) };- const res2 = await POST(req2, ctx2);- const body2 = await res2.json();-- expect(body1.id).toBe(body2.id);- });-});diff --git a/src/web/src/app/api/agents/[id]/conversation/route.ts b/src/web/src/app/api/agents/[id]/conversation/route.tsdeleted file mode 100644index d0d6062d0..000000000--- a/src/web/src/app/api/agents/[id]/conversation/route.ts+++ /dev/null@@ -1,41 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("agent not found", 404);- }-- let channel: string | undefined;- try {- const body = (await req.json()) as { channel?: string };- channel = typeof body.channel === "string" ? body.channel : undefined;- } catch {- // no body — backward compatible- }-- const conversation = await queries.conversation.getOrCreateAgentConversation(- db,- ws.workspaceId,- ctx.userId,- id,- channel- );-- return writeJSON(conversationToResponse(conversation));-});diff --git a/src/web/src/app/api/agents/[id]/conversations/route.test.ts b/src/web/src/app/api/agents/[id]/conversations/route.test.tsdeleted file mode 100644index 7dab91503..000000000--- a/src/web/src/app/api/agents/[id]/conversations/route.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockListConversationsByAgent = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- conversation: {- listConversationsByAgent: (...args: unknown[]) => mockListConversationsByAgent(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- conversationToResponse: vi.fn((c: any) => ({ id: c.id, title: c.title })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]/conversations", () => {- it("returns 200 with filtered conversations", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockListConversationsByAgent.mockResolvedValue([- { id: "c1", title: "Conv 1" },- { id: "c2", title: "Conv 2" },- ]);-- const req = new NextRequest("http://localhost/api/agents/a1/conversations");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "c1", title: "Conv 1" },- { id: "c2", title: "Conv 2" },- ]);- });-- it("returns 404 for non-existent agent", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/conversations");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns empty array for agent with no conversations", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockListConversationsByAgent.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/agents/a1/conversations");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([]);- });-});diff --git a/src/web/src/app/api/agents/[id]/conversations/route.ts b/src/web/src/app/api/agents/[id]/conversations/route.tsdeleted file mode 100644index 88d1e7d2a..000000000--- a/src/web/src/app/api/agents/[id]/conversations/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("agent not found", 404);- }-- const url = new URL(req.url);- const channel = url.searchParams.get("channel") || undefined;- const exclude = url.searchParams.get("exclude") || undefined;- const before = url.searchParams.get("before") || undefined;- const limitParam = url.searchParams.get("limit");-- if (exclude && before) {- const limit = Math.min(Math.max(Number(limitParam) || 10, 1), 50);- const prevConvs = await queries.conversation.listPreviousConversations(- db, ws.workspaceId, ctx.userId, id, exclude, channel, { limit, before },- );- return writeJSON({- conversations: prevConvs.map((c) => ({ id: c.id, created_at: c.createdAt })),- has_more: prevConvs.length >= limit,- });- }-- const conversations = await queries.conversation.listConversationsByAgent(- db,- ws.workspaceId,- ctx.userId,- id,- channel- );-- return writeJSON(conversations.map(conversationToResponse));-});diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.tsdeleted file mode 100644index 6a589c566..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.test.ts+++ /dev/null@@ -1,136 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },- })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared/crypto", () => ({ encrypt: vi.fn((v: string) => `enc(${v})`) }));--const mockGetScoped = vi.fn();-const mockUpdate = vi.fn();-const mockDelete = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- emailAccount: {- getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a),- updateEmailAccount: (...a: unknown[]) => mockUpdate(...a),- deleteEmailAccount: (...a: unknown[]) => mockDelete(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- cacheKeys: {- allEmailAccounts: (w: string) => `ea:${w}`,- overviewEmailAccounts: (w: string) => `ov_ea:${w}`,- },-}));--import { PATCH, DELETE } from "./route";--const ROW = {- id: "acc1", agentId: "a1", workspaceId: "w1", emailAddress: "[email protected]", displayName: "X",- imapHost: "imap", imapPort: 993, imapTls: 1, smtpHost: "smtp", smtpPort: 465, smtpTls: 1,- pollIntervalSeconds: 60, lastSyncedAt: null, status: "active", errorMessage: null,- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),-};--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--const params = { id: "a1", accountId: "acc1" };--describe("PATCH /api/agents/[id]/email-accounts/[accountId]", () => {- function patch(body: unknown, p = params) {- return PATCH(- new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1", {- method: "PATCH",- headers: { "content-type": "application/json" },- body: JSON.stringify(body),- }),- { params: p },- );- }-- it("updates a scoped account (display name only, no worker restart)", async () => {- mockGetScoped.mockResolvedValue(ROW);- mockUpdate.mockResolvedValue(ROW);- const res = await patch({ displayName: "New" });- expect(res.status).toBe(200);- expect(mockGetScoped).toHaveBeenCalledWith({}, "acc1", "a1", "w1");- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- });-- it("restarts the worker when credentials change", async () => {- mockGetScoped.mockResolvedValue(ROW);- mockUpdate.mockResolvedValue(ROW);- const res = await patch({ imapPassword: "newpass" });- expect(res.status).toBe(200);- // stop + start- expect(mockEmailWorkerFetch).toHaveBeenCalledTimes(2);- });-- it("400 when params missing", async () => {- const res = await patch({ displayName: "x" }, { id: "a1" } as any);- expect(res.status).toBe(400);- });-- it("404 when account not scoped to agent/workspace (IDOR guard)", async () => {- mockGetScoped.mockResolvedValue(null);- const res = await patch({ displayName: "x" });- expect(res.status).toBe(404);- });-});--describe("DELETE /api/agents/[id]/email-accounts/[accountId]", () => {- function del(p = params) {- return DELETE(- new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1", { method: "DELETE" }),- { params: p },- );- }-- it("stops the worker and deletes a scoped account", async () => {- mockGetScoped.mockResolvedValue(ROW);- mockDelete.mockResolvedValue(ROW);- const res = await del();- expect(res.status).toBe(200);- expect((await res.json()).ok).toBe(true);- expect(mockDelete).toHaveBeenCalledWith({}, "acc1", "w1");- expect(mockEmailWorkerFetch).toHaveBeenCalled();- });-- it("404 when account not scoped", async () => {- mockGetScoped.mockResolvedValue(null);- const res = await del();- expect(res.status).toBe(404);- });-- it("400 when params missing", async () => {- const res = await del({ id: "a1" } as any);- expect(res.status).toBe(400);- });-});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.tsdeleted file mode 100644index 0850ee6e5..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/route.ts+++ /dev/null@@ -1,120 +0,0 @@-import { queries, UpdateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"-import { getDb } from "@/lib/db"-import { encrypt } from "@alook/shared/crypto"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"-import { invalidate, cacheKeys } from "@/lib/cache"--type AgentEmailAccountRow = Awaited<ReturnType<typeof queries.emailAccount.getEmailAccountsByAgent>>[number]--function accountToResponse(a: AgentEmailAccountRow) {- return {- id: a.id,- agent_id: a.agentId,- workspace_id: a.workspaceId,- email_address: a.emailAddress,- display_name: a.displayName,- imap_host: a.imapHost,- imap_port: a.imapPort,- imap_tls: !!a.imapTls,- smtp_host: a.smtpHost,- smtp_port: a.smtpPort,- smtp_tls: a.smtpTls,- poll_interval_seconds: a.pollIntervalSeconds,- last_synced_at: formatTimestampNullable(a.lastSyncedAt),- status: a.status,- error_message: a.errorMessage,- created_at: formatTimestamp(a.createdAt),- updated_at: formatTimestamp(a.updatedAt),- }-}--async function callEmailWorker(cfEnv: Env, path: string, method = "POST") {- try {- await cfEnv.EMAIL_WORKER.fetch(`http://internal${path}`, { method })- } catch {- await fetch(`${DEV_EMAIL_WORKER_URL}${path}`, { method }).catch(() => {})- }-}--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- const accountId = ctx.params?.accountId- if (!agentId || !accountId) return writeError("missing params", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)- if (!existing) return writeError("not found", 404)-- const [body, err] = await parseBody(req, UpdateEmailAccountSchema)- if (err) return err-- const secret = cfEnv.ENCRYPTION_KEY- if (!secret) return writeError("encryption not configured", 500)-- const data: Record<string, unknown> = {}- if (body.emailAddress !== undefined) data.emailAddress = body.emailAddress- if (body.displayName !== undefined) data.displayName = body.displayName- if (body.imapHost !== undefined) data.imapHost = body.imapHost- if (body.imapPort !== undefined) data.imapPort = body.imapPort- if (body.imapUsername !== undefined) data.imapUsername = encrypt(body.imapUsername, secret)- if (body.imapPassword !== undefined) data.imapPassword = encrypt(body.imapPassword, secret)- if (body.imapTls !== undefined) data.imapTls = body.imapTls- if (body.smtpHost !== undefined) data.smtpHost = body.smtpHost- if (body.smtpPort !== undefined) data.smtpPort = body.smtpPort- if (body.smtpUsername !== undefined) data.smtpUsername = encrypt(body.smtpUsername, secret)- if (body.smtpPassword !== undefined) data.smtpPassword = encrypt(body.smtpPassword, secret)- if (body.smtpTls !== undefined) data.smtpTls = body.smtpTls- if (body.pollIntervalSeconds !== undefined) data.pollIntervalSeconds = body.pollIntervalSeconds-- const updated = await queries.emailAccount.updateEmailAccount(db, accountId, ws.workspaceId, data)- if (!updated) return writeError("update failed", 500)-- await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));- await invalidate(cacheKeys.overviewEmailAccounts(ws.workspaceId));-- const hasCredentialChange = body.imapUsername || body.imapPassword || body.smtpUsername || body.smtpPassword || body.imapHost || body.smtpHost- if (hasCredentialChange) {- await callEmailWorker(cfEnv, `/imap/stop?accountId=${accountId}`)- await callEmailWorker(cfEnv, `/imap/start?accountId=${accountId}`)- }-- return writeJSON(accountToResponse(updated))-})--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- const accountId = ctx.params?.accountId- if (!agentId || !accountId) return writeError("missing params", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)- if (!existing) return writeError("not found", 404)-- await callEmailWorker(cfEnv, `/imap/stop?accountId=${accountId}`)-- const deleted = await queries.emailAccount.deleteEmailAccount(db, accountId, ws.workspaceId)- if (!deleted) return writeError("delete failed", 500)-- await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));- await invalidate(cacheKeys.overviewEmailAccounts(ws.workspaceId));-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.tsdeleted file mode 100644index 97ee7797c..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },- })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetScoped = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--function post(params: Record<string, string>) {- return POST(- new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1/sync", { method: "POST" }),- { params },- );-}--describe("POST .../email-accounts/[accountId]/sync", () => {- it("triggers a worker sync for a scoped account", async () => {- mockGetScoped.mockResolvedValue({ id: "acc1" });- const res = await post({ id: "a1", accountId: "acc1" });- expect(res.status).toBe(200);- expect((await res.json()).ok).toBe(true);- expect(mockGetScoped).toHaveBeenCalledWith({}, "acc1", "a1", "w1");- expect(mockEmailWorkerFetch).toHaveBeenCalledWith(- expect.stringContaining("/imap/sync?accountId=acc1"),- expect.objectContaining({ method: "POST" }),- );- });-- it("400 when params missing", async () => {- const res = await post({ id: "a1" });- expect(res.status).toBe(400);- });-- it("404 when account not scoped (IDOR guard)", async () => {- mockGetScoped.mockResolvedValue(null);- const res = await post({ id: "a1", accountId: "acc1" });- expect(res.status).toBe(404);- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.tsdeleted file mode 100644index 713a74919..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/sync/route.ts+++ /dev/null@@ -1,35 +0,0 @@-import { queries, DEV_EMAIL_WORKER_URL } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- const accountId = ctx.params?.accountId- if (!agentId || !accountId) return writeError("missing params", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)- if (!existing) return writeError("not found", 404)-- try {- await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/sync?accountId=${accountId}`, {- method: "POST",- })- } catch {- await fetch(`${DEV_EMAIL_WORKER_URL}/imap/sync?accountId=${accountId}`, {- method: "POST",- }).catch(() => {})- }-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.tsdeleted file mode 100644index 13f3b25dd..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockEmailWorkerFetch = vi.fn();-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },- })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetScoped = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- emailAccount: { getEmailAccountScoped: (...a: unknown[]) => mockGetScoped(...a) },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--function post(params: Record<string, string>) {- return POST(- new NextRequest("http://localhost/api/agents/a1/email-accounts/acc1/test", { method: "POST" }),- { params },- );-}--describe("POST .../email-accounts/[accountId]/test", () => {- it("forwards the worker test result and its status", async () => {- mockGetScoped.mockResolvedValue({ id: "acc1" });- mockEmailWorkerFetch.mockResolvedValue(- new Response(JSON.stringify({ ok: true, folders: 3 }), { status: 200 }),- );- const res = await post({ id: "a1", accountId: "acc1" });- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ ok: true, folders: 3 });- });-- it("propagates a non-200 worker status (e.g. failed auth → 401)", async () => {- mockGetScoped.mockResolvedValue({ id: "acc1" });- mockEmailWorkerFetch.mockResolvedValue(- new Response(JSON.stringify({ error: "auth failed" }), { status: 401 }),- );- const res = await post({ id: "a1", accountId: "acc1" });- expect(res.status).toBe(401);- });-- it("400 when params missing", async () => {- const res = await post({ id: "a1" });- expect(res.status).toBe(400);- });-- it("404 when account not scoped", async () => {- mockGetScoped.mockResolvedValue(null);- const res = await post({ id: "a1", accountId: "acc1" });- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts b/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.tsdeleted file mode 100644index e6a629692..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/[accountId]/test/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, DEV_EMAIL_WORKER_URL } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const { env } = getCloudflareContext()- const cfEnv = env as Env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- const accountId = ctx.params?.accountId- if (!agentId || !accountId) return writeError("missing params", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const existing = await queries.emailAccount.getEmailAccountScoped(db, accountId, agentId, ws.workspaceId)- if (!existing) return writeError("not found", 404)-- let testRes: Response- try {- testRes = await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/test?accountId=${accountId}&workspaceId=${ws.workspaceId}`, {- method: "POST",- })- } catch {- testRes = await fetch(`${DEV_EMAIL_WORKER_URL}/imap/test?accountId=${accountId}&workspaceId=${ws.workspaceId}`, {- method: "POST",- })- }-- const result = await testRes.json()- return writeJSON(result, testRes.status)-})diff --git a/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts b/src/web/src/app/api/agents/[id]/email-accounts/route.test.tsdeleted file mode 100644index d3ece9075..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/route.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockEmailWorkerFetch = vi.fn().mockResolvedValue(new Response("ok"));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } },- })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared/crypto", () => ({ encrypt: vi.fn((v: string) => `enc(${v})`) }));--const mockGetAgent = vi.fn();-const mockGetAccounts = vi.fn();-const mockCreateAccount = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- emailAccount: {- getEmailAccountsByAgent: (...a: unknown[]) => mockGetAccounts(...a),- createEmailAccount: (...a: unknown[]) => mockCreateAccount(...a),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, ENCRYPTION_KEY: "test-key", EMAIL_WORKER: { fetch: mockEmailWorkerFetch } }, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- cacheKeys: {- allEmailAccounts: (w: string) => `ea:${w}`,- overviewEmailAccounts: (w: string) => `ov_ea:${w}`,- },-}));--import { GET, POST } from "./route";--const ACCOUNT_ROW = {- id: "acc1", agentId: "a1", workspaceId: "w1", emailAddress: "[email protected]", displayName: "X",- imapHost: "imap", imapPort: 993, imapTls: 1, smtpHost: "smtp", smtpPort: 465, smtpTls: 1,- pollIntervalSeconds: 60, lastSyncedAt: null, status: "active", errorMessage: null,- createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(),-};--const VALID_BODY = {- emailAddress: "[email protected]", displayName: "X", imapHost: "imap", imapPort: 993,- imapUsername: "u", imapPassword: "p", imapTls: true, smtpHost: "smtp", smtpPort: 465,- smtpUsername: "su", smtpPassword: "sp", smtpTls: 1, pollIntervalSeconds: 60,-};--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]/email-accounts", () => {- it("lists accounts scoped to agent + workspace", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockGetAccounts.mockResolvedValue([ACCOUNT_ROW]);- const req = new NextRequest("http://localhost/api/agents/a1/email-accounts");- const res = await GET(req, { params: { id: "a1" } });- const body = await res.json();- expect(res.status).toBe(200);- expect(body[0].id).toBe("acc1");- expect(mockGetAccounts).toHaveBeenCalledWith({}, "a1", "w1");- });-- it("400 when agent id missing", async () => {- const req = new NextRequest("http://localhost/api/agents/x/email-accounts");- const res = await GET(req, { params: {} });- expect(res.status).toBe(400);- });-- it("404 when agent not in workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/agents/a1/email-accounts");- const res = await GET(req, { params: { id: "a1" } });- expect(res.status).toBe(404);- });-});--describe("POST /api/agents/[id]/email-accounts", () => {- function post(body: unknown) {- return POST(- new NextRequest("http://localhost/api/agents/a1/email-accounts", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(body),- }),- { params: { id: "a1" } },- );- }-- it("creates an account, encrypts credentials, starts the worker (201)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockCreateAccount.mockResolvedValue(ACCOUNT_ROW);- const res = await post(VALID_BODY);- expect(res.status).toBe(201);- const createArgs = mockCreateAccount.mock.calls[0]![1] as Record<string, unknown>;- expect(createArgs.workspaceId).toBe("w1");- expect(createArgs.imapPassword).toBe("enc(p)");- expect(mockEmailWorkerFetch).toHaveBeenCalled();- });-- it("404 when agent not in workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const res = await post(VALID_BODY);- expect(res.status).toBe(404);- });-- it("400 on invalid body", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- const res = await post({ emailAddress: "[email protected]" });- expect(res.status).toBe(400);- });-});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.tsdeleted file mode 100644index 88f1fe2eb..000000000--- a/src/web/src/app/api/agents/[id]/email-accounts/route.ts+++ /dev/null@@ -1,100 +0,0 @@-import { queries, CreateEmailAccountSchema, DEV_EMAIL_WORKER_URL } from "@alook/shared"-import { getDb } from "@/lib/db"-import { encrypt } from "@alook/shared/crypto"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError, parseBody, formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers"-import { invalidate, cacheKeys } from "@/lib/cache"--type AgentEmailAccountRow = Awaited<ReturnType<typeof queries.emailAccount.getEmailAccountsByAgent>>[number]--function accountToResponse(a: AgentEmailAccountRow) {- return {- id: a.id,- agent_id: a.agentId,- workspace_id: a.workspaceId,- email_address: a.emailAddress,- display_name: a.displayName,- imap_host: a.imapHost,- imap_port: a.imapPort,- imap_tls: !!a.imapTls,- smtp_host: a.smtpHost,- smtp_port: a.smtpPort,- smtp_tls: a.smtpTls,- poll_interval_seconds: a.pollIntervalSeconds,- last_synced_at: formatTimestampNullable(a.lastSyncedAt),- status: a.status,- error_message: a.errorMessage,- created_at: formatTimestamp(a.createdAt),- updated_at: formatTimestamp(a.updatedAt),- }-}--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("agent not found", 404)-- const accounts = await queries.emailAccount.getEmailAccountsByAgent(db, agentId, ws.workspaceId)- return writeJSON(accounts.map(accountToResponse))-})--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("agent not found", 404)-- const [body, err] = await parseBody(req, CreateEmailAccountSchema)- if (err) return err-- const secret = cfEnv.ENCRYPTION_KEY- if (!secret) return writeError("encryption not configured", 500)-- const account = await queries.emailAccount.createEmailAccount(db, {- agentId,- workspaceId: ws.workspaceId,- emailAddress: body.emailAddress,- displayName: body.displayName,- imapHost: body.imapHost,- imapPort: body.imapPort,- imapUsername: encrypt(body.imapUsername, secret),- imapPassword: encrypt(body.imapPassword, secret),- imapTls: body.imapTls,- smtpHost: body.smtpHost,- smtpPort: body.smtpPort,- smtpUsername: encrypt(body.smtpUsername, secret),- smtpPassword: encrypt(body.smtpPassword, secret),- smtpTls: body.smtpTls,- pollIntervalSeconds: body.pollIntervalSeconds,- })-- try {- await cfEnv.EMAIL_WORKER.fetch(`http://internal/imap/start?accountId=${account.id}`, {- method: "POST",- })- } catch {- await fetch(`${DEV_EMAIL_WORKER_URL}/imap/start?accountId=${account.id}`, {- method: "POST",- }).catch(() => {})- }-- await invalidate(cacheKeys.allEmailAccounts(ws.workspaceId));- await invalidate(cacheKeys.overviewEmailAccounts(ws.workspaceId));-- return writeJSON(accountToResponse(account), 201)-})diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.tsdeleted file mode 100644index 0e7f57c34..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";-import { MeetingStatus } from "@alook/shared";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGet = vi.fn();-const mockUpdate = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- meetingSession: {- getMeetingSession: (...a: unknown[]) => mockGet(...a),- updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--const params = { id: "a1", meetingId: "m1" };-const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });--describe("POST .../meetings/[meetingId]/approve", () => {- it("approves a pending meeting → scheduled", async () => {- mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.PENDING });- mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });- const res = await post();- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "m1", "w1", { status: MeetingStatus.SCHEDULED });- });-- it("400 when meeting id missing", async () => {- const res = await POST(new NextRequest("http://localhost/x", { method: "POST" }), { params: { id: "a1" } });- expect(res.status).toBe(400);- });-- it("404 when meeting not in workspace", async () => {- mockGet.mockResolvedValue(null);- const res = await post();- expect(res.status).toBe(404);- });-- it("400 when meeting is not pending", async () => {- mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });- const res = await post();- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("only pending meetings can be approved");- expect(mockUpdate).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.tsdeleted file mode 100644index 6b7e2428e..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/approve/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { NextRequest } from "next/server"-import { queries, MeetingStatus } from "@alook/shared"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { meetingToResponse } from "@/lib/api/responses"-import { getDb } from "@/lib/db"--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const meetingId = ctx.params?.meetingId- if (!meetingId) return writeError("meeting id is required", 400)-- const meeting = await queries.meetingSession.getMeetingSession(db, meetingId, ws.workspaceId)- if (!meeting) return writeError("not found", 404)-- if (meeting.status !== MeetingStatus.PENDING) {- return writeError("only pending meetings can be approved", 400)- }-- const updated = await queries.meetingSession.updateMeetingSession(db, meetingId, ws.workspaceId, {- status: MeetingStatus.SCHEDULED,- })- if (!updated) return writeError("meeting not found", 404)-- return writeJSON(meetingToResponse(updated))-})diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.tsdeleted file mode 100644index 78c9e6f3f..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.test.ts+++ /dev/null@@ -1,81 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGet = vi.fn();-const mockDelete = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- meetingSession: {- getMeetingSession: (...a: unknown[]) => mockGet(...a),- deleteMeetingSession: (...a: unknown[]) => mockDelete(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id }) }));--import { GET, DELETE } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--describe("GET /api/agents/[id]/meetings/[meetingId]", () => {- it("returns a meeting scoped to workspace", async () => {- mockGet.mockResolvedValue({ id: "m1" });- const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1", meetingId: "m1" } });- expect(res.status).toBe(200);- expect(mockGet).toHaveBeenCalledWith({}, "m1", "w1");- });-- it("400 when meeting id missing", async () => {- const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1" } });- expect(res.status).toBe(400);- });-- it("404 when meeting not in workspace (IDOR guard)", async () => {- mockGet.mockResolvedValue(null);- const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "a1", meetingId: "m1" } });- expect(res.status).toBe(404);- });-});--describe("DELETE /api/agents/[id]/meetings/[meetingId]", () => {- it("deletes a scoped meeting", async () => {- mockDelete.mockResolvedValue({ id: "m1" });- const res = await DELETE(new NextRequest("http://localhost/x", { method: "DELETE" }), {- params: { id: "a1", meetingId: "m1" },- });- expect(res.status).toBe(200);- expect((await res.json()).ok).toBe(true);- expect(mockDelete).toHaveBeenCalledWith({}, "m1", "w1");- });-- it("404 when meeting not found in workspace", async () => {- mockDelete.mockResolvedValue(null);- const res = await DELETE(new NextRequest("http://localhost/x", { method: "DELETE" }), {- params: { id: "a1", meetingId: "m1" },- });- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.tsdeleted file mode 100644index 24ca1395b..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/route.ts+++ /dev/null@@ -1,57 +0,0 @@-import { NextRequest } from "next/server"-import { queries } from "@alook/shared"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { meetingToResponse } from "@/lib/api/responses"-import { getDb } from "@/lib/db"--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const meetingId = ctx.params?.meetingId- if (!meetingId) return writeError("meeting id is required", 400)-- const meeting = await queries.meetingSession.getMeetingSession(- db,- meetingId,- ws.workspaceId- )- if (!meeting) return writeError("not found", 404)-- return writeJSON(meetingToResponse(meeting))-})--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const meetingId = ctx.params?.meetingId- if (!meetingId) return writeError("meeting id is required", 400)-- const deleted = await queries.meetingSession.deleteMeetingSession(- db,- meetingId,- ws.workspaceId- )- if (!deleted) return writeError("meeting not found", 404)-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.tsdeleted file mode 100644index dc7d4e509..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";-import { MeetingStatus } from "@alook/shared";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGet = vi.fn();-const mockUpdate = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- meetingSession: {- getMeetingSession: (...a: unknown[]) => mockGet(...a),- updateMeetingSession: (...a: unknown[]) => mockUpdate(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--const params = { id: "a1", meetingId: "m1" };-const post = () => POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });--describe("POST .../meetings/[meetingId]/stop", () => {- it("stops a recording meeting → completed", async () => {- mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.RECORDING });- mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.COMPLETED });- const res = await post();- expect(res.status).toBe(200);- expect(mockUpdate.mock.calls[0]![3]).toMatchObject({ status: MeetingStatus.COMPLETED });- });-- it("stops a joining meeting too", async () => {- mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.JOINING });- mockUpdate.mockResolvedValue({ id: "m1", status: MeetingStatus.COMPLETED });- const res = await post();- expect(res.status).toBe(200);- });-- it("400 when meeting is not active (e.g. scheduled)", async () => {- mockGet.mockResolvedValue({ id: "m1", status: MeetingStatus.SCHEDULED });- const res = await post();- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("meeting is not active");- });-- it("404 when meeting not in workspace", async () => {- mockGet.mockResolvedValue(null);- const res = await post();- expect(res.status).toBe(404);- });-- it("400 when meeting id missing", async () => {- const res = await POST(new NextRequest("http://localhost/x", { method: "POST" }), { params: { id: "a1" } });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts b/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.tsdeleted file mode 100644index d6cf91d95..000000000--- a/src/web/src/app/api/agents/[id]/meetings/[meetingId]/stop/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { NextRequest } from "next/server"-import { queries, MeetingStatus } from "@alook/shared"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { meetingToResponse } from "@/lib/api/responses"-import { getDb } from "@/lib/db"--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const meetingId = ctx.params?.meetingId- if (!meetingId) return writeError("meeting id is required", 400)-- const meeting = await queries.meetingSession.getMeetingSession(db, meetingId, ws.workspaceId)- if (!meeting) return writeError("not found", 404)-- if (meeting.status !== MeetingStatus.RECORDING && meeting.status !== MeetingStatus.JOINING) {- return writeError("meeting is not active", 400)- }-- const updated = await queries.meetingSession.updateMeetingSession(db, meetingId, ws.workspaceId, {- status: MeetingStatus.COMPLETED,- completedAt: new Date().toISOString(),- })- if (!updated) return writeError("meeting not found", 404)-- return writeJSON(meetingToResponse(updated))-})diff --git a/src/web/src/app/api/agents/[id]/meetings/route.test.ts b/src/web/src/app/api/agents/[id]/meetings/route.test.tsdeleted file mode 100644index eb6f1e683..000000000--- a/src/web/src/app/api/agents/[id]/meetings/route.test.ts+++ /dev/null@@ -1,116 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockList = vi.fn();-const mockGetAgent = vi.fn();-const mockCreate = vi.fn();-const mockGet = vi.fn();-const mockGetRuntime = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- meetingSession: {- listMeetingSessions: (...a: unknown[]) => mockList(...a),- createMeetingSession: (...a: unknown[]) => mockCreate(...a),- getMeetingSession: (...a: unknown[]) => mockGet(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- runtime: { getAgentRuntime: (...a: unknown[]) => mockGetRuntime(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({ meetingToResponse: (m: any) => ({ id: m.id, status: m.status }) }));-vi.mock("@/lib/broadcast", () => ({ broadcastToDaemon: vi.fn().mockResolvedValue(undefined) }));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--const VALID_URL = "https://meet.google.com/abc-defg-hij";--describe("GET /api/agents/[id]/meetings", () => {- it("lists meetings scoped to agent + workspace", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });- mockList.mockResolvedValue([{ id: "m1", status: "completed" }]);- const req = new NextRequest("http://localhost/api/agents/a1/meetings");- const res = await GET(req, { params: { id: "a1" } });- expect(res.status).toBe(200);- expect(mockList).toHaveBeenCalledWith({}, "a1", "w1");- });-- it("400 when agent id missing", async () => {- const req = new NextRequest("http://localhost/api/agents/x/meetings");- const res = await GET(req, { params: {} });- expect(res.status).toBe(400);- });-});--describe("POST /api/agents/[id]/meetings", () => {- function post(body: unknown, id = "a1") {- return POST(- new NextRequest("http://localhost/api/agents/a1/meetings", {- method: "POST",- body: JSON.stringify(body),- }),- { params: { id } },- );- }-- it("creates a scheduled meeting with a valid Meet URL (201)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: null, name: "A" });- mockCreate.mockResolvedValue({ id: "m1" });- mockGet.mockResolvedValue({ id: "m1", status: "scheduled", meetingUrl: VALID_URL, participants: [] });-- const res = await post({ meetingUrl: VALID_URL });- expect(res.status).toBe(201);- expect(mockCreate.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", agentId: "a1" });- });-- it("404 when agent not in workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const res = await post({ meetingUrl: VALID_URL });- expect(res.status).toBe(404);- });-- it("400 when meetingUrl missing", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- const res = await post({});- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("meetingUrl is required");- });-- it("400 for a malformed Meet URL", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- const res = await post({ meetingUrl: "https://zoom.us/j/123" });- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("invalid Google Meet URL format");- });-- it("400 on invalid JSON body", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- const req = new NextRequest("http://localhost/api/agents/a1/meetings", {- method: "POST",- body: "not json",- });- const res = await POST(req, { params: { id: "a1" } });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/agents/[id]/meetings/route.ts b/src/web/src/app/api/agents/[id]/meetings/route.tsdeleted file mode 100644index e49f3fc57..000000000--- a/src/web/src/app/api/agents/[id]/meetings/route.ts+++ /dev/null@@ -1,98 +0,0 @@-import { NextRequest } from "next/server"-import { queries, MeetingStatus } from "@alook/shared"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { meetingToResponse } from "@/lib/api/responses"-import { getDb } from "@/lib/db"-import { broadcastToDaemon } from "@/lib/broadcast"--const MEET_URL_RE = /^https:\/\/meet\.google\.com\/[a-z]{3}-[a-z]{4}-[a-z]{3}$/--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- const meetings = await queries.meetingSession.listMeetingSessions(- db,- agentId,- ws.workspaceId- )-- return writeJSON(meetings.map(meetingToResponse))-})--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const cfEnv = ctx.env- const db = getDb(cfEnv.DB)-- const agentId = ctx.params?.id- if (!agentId) return writeError("agent id is required", 400)-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId)- if (!agent) return writeError("not found", 404)-- let body: {- meetingUrl?: string- title?: string- participants?: string[]- scheduledAt?: string- }- try {- body = await req.json() as typeof body- } catch {- return writeError("invalid request body", 400)- }-- if (!body.meetingUrl) return writeError("meetingUrl is required", 400)- if (!MEET_URL_RE.test(body.meetingUrl)) return writeError("invalid Google Meet URL format", 400)-- const meeting = await queries.meetingSession.createMeetingSession(db, {- agentId,- workspaceId: ws.workspaceId,- title: body.title ?? "",- meetingUrl: body.meetingUrl,- status: MeetingStatus.SCHEDULED,- isWhitelisted: true,- participants: body.participants ?? [],- scheduledAt: body.scheduledAt ?? new Date().toISOString(),- })-- const created = await queries.meetingSession.getMeetingSession(db, meeting.id, ws.workspaceId)- if (!created) return writeError("meeting not found", 404)-- if (agent.runtimeId) {- const runtime = await queries.runtime.getAgentRuntime(db, agent.runtimeId)- if (runtime) {- const scheduledTime = body.scheduledAt ? new Date(body.scheduledAt) : new Date()- const fiveMinFromNow = new Date(Date.now() + 5 * 60 * 1000)- if (scheduledTime <= fiveMinFromNow) {- broadcastToDaemon(runtime.daemonId, {- type: "daemon.meetings",- meetings: [{- id: created.id,- meeting_url: created.meetingUrl,- participants: created.participants as string[],- workspace_id: ws.workspaceId,- agent_id: agentId,- agent_name: agent.name ?? "",- title: created.title || undefined,- }],- }).catch(() => {})- }- }- }-- return writeJSON(meetingToResponse(created), 201)-})diff --git a/src/web/src/app/api/agents/[id]/pin/route.test.ts b/src/web/src/app/api/agents/[id]/pin/route.test.tsdeleted file mode 100644index 6af6294da..000000000--- a/src/web/src/app/api/agents/[id]/pin/route.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetAgent = vi.fn();-const mockPinAgent = vi.fn();-const mockUnpinAgent = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- agentPin: {- pinAgent: (...args: unknown[]) => mockPinAgent(...args),- unpinAgent: (...args: unknown[]) => mockUnpinAgent(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers"),-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "member" })),-}));--import { POST, DELETE } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("POST /api/agents/[id]/pin", () => {- it("pins agent and returns 201 for new pin", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockPinAgent.mockResolvedValue({ id: "pin1", agentId: "a1" });-- const req = new NextRequest("http://localhost/api/agents/a1/pin", { method: "POST" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({ pinned: true });- expect(mockPinAgent).toHaveBeenCalledWith({}, { agentId: "a1", workspaceId: "w1", userId: "u1" });- });-- it("returns 200 when already pinned", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });- mockPinAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/pin", { method: "POST" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ pinned: true });- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/pin", { method: "POST" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- expect(mockPinAgent).not.toHaveBeenCalled();- });-});--describe("DELETE /api/agents/[id]/pin", () => {- it("unpins agent and returns 204", async () => {- mockUnpinAgent.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/agents/a1/pin", { method: "DELETE" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await DELETE(req, ctx);-- expect(res.status).toBe(204);- expect(mockUnpinAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");- });-- it("returns 204 even when no pin exists (idempotent)", async () => {- mockUnpinAgent.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/agents/no-pin/pin", { method: "DELETE" });- const ctx = { params: Promise.resolve({ id: "no-pin" }) };- const res = await DELETE(req, ctx);-- expect(res.status).toBe(204);- expect(mockUnpinAgent).toHaveBeenCalledWith({}, "no-pin", "w1", "u1");- });-});diff --git a/src/web/src/app/api/agents/[id]/pin/route.ts b/src/web/src/app/api/agents/[id]/pin/route.tsdeleted file mode 100644index 370804fdb..000000000--- a/src/web/src/app/api/agents/[id]/pin/route.ts+++ /dev/null@@ -1,29 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { invalidate, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- const { id } = ctx.params!;- const db = getDb(ctx.env.DB);- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);- const pin = await queries.agentPin.pinAgent(db, { agentId: id, workspaceId: ws.workspaceId, userId: ctx.userId });- invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});- return writeJSON({ pinned: true }, pin ? 201 : 200);-});--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- const { id } = ctx.params!;- const db = getDb(ctx.env.DB);- await queries.agentPin.unpinAgent(db, id, ws.workspaceId, ctx.userId);- invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/agents/[id]/route.test.ts b/src/web/src/app/api/agents/[id]/route.test.tsdeleted file mode 100644index f4b4cc751..000000000--- a/src/web/src/app/api/agents/[id]/route.test.ts+++ /dev/null@@ -1,289 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockDeleteAgent = vi.fn();-const mockUpdateAgent = vi.fn();-const mockGetAgentRuntimeForWorkspace = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- deleteAgent: (...args: unknown[]) => mockDeleteAgent(...args),- updateAgent: (...args: unknown[]) => mockUpdateAgent(...args),- },- runtime: {- getAgentRuntimeForWorkspace: (...args: unknown[]) => mockGetAgentRuntimeForWorkspace(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name })),-}));--import { GET, DELETE, PATCH } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]", () => {- it("returns agent", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent 1" });-- const req = new NextRequest("http://localhost/api/agents/a1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "a1", name: "Agent 1" });- });-- it("returns 404 when not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-});--describe("DELETE /api/agents/[id]", () => {- it("returns 204 on successful deletion", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockDeleteAgent.mockResolvedValue(true);-- const req = new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await DELETE(req, ctx);-- expect(res.status).toBe(204);- });-- it("returns 404 for non-existent agent", async () => {- mockDeleteAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await DELETE(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns 403 when user is not agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "other-user" });-- const req = new NextRequest("http://localhost/api/agents/a1", { method: "DELETE" });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await DELETE(req, ctx);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });-});--describe("PATCH /api/agents/[id]", () => {- it("updates agent and returns response", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Updated" });-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ name: "Updated" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "a1", name: "Updated" });- });-- it("returns 404 for non-existent agent", async () => {- mockUpdateAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ name: "Updated" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("returns 400 when no fields provided", async () => {- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ unknown_field: "value" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("validation error");- });-- it("returns 400 for invalid request body", async () => {- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: "not json",- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });-- it("accepts and persists runtime_config", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Agent" });-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ name: "Agent", runtime_config: { model: "claude-sonnet-4-6" } }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);-- expect(res.status).toBe(200);- expect(mockUpdateAgent).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ runtimeConfig: { model: "claude-sonnet-4-6" } }),- "u1",- );- });-- it("runtime_config alone is a valid update", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Agent" });-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ runtime_config: { model: "x" } }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);-- expect(res.status).toBe(200);- expect(mockUpdateAgent).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ runtimeConfig: { model: "x" } }),- "u1",- );- });-- it("TC-6: PATCH with valid runtime_id (own runtime) updates agent successfully", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "u1" });- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ id: "rt1", workspaceId: "w1" });- mockUpdateAgent.mockResolvedValue({ id: "a1", name: "Agent" });-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ runtime_id: "rt1" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);-- expect(res.status).toBe(200);- expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith(- expect.anything(),- "rt1",- "w1",- "u1",- );- expect(mockUpdateAgent).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- expect.objectContaining({ runtimeId: "rt1" }),- "u1",- );- });-- it("TC-5: PATCH with runtime_id belonging to another member returns 400", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ runtime_id: "rt_other_user" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("runtime not found in workspace");- expect(mockUpdateAgent).not.toHaveBeenCalled();- });-- it("PATCH with nonexistent runtime_id returns 400", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ runtime_id: "rt_nonexistent" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("runtime not found in workspace");- expect(mockUpdateAgent).not.toHaveBeenCalled();- });-- it("returns 403 when user is not agent owner", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", ownerId: "other-user" });-- const req = new NextRequest("http://localhost/api/agents/a1", {- method: "PATCH",- body: JSON.stringify({ name: "New" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await PATCH(req, ctx);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("agent owner access required");- });--});diff --git a/src/web/src/app/api/agents/[id]/route.ts b/src/web/src/app/api/agents/[id]/route.tsdeleted file mode 100644index 8437d10ec..000000000--- a/src/web/src/app/api/agents/[id]/route.ts+++ /dev/null@@ -1,107 +0,0 @@-import { queries, UpdateAgentRequestSchema } from "@alook/shared"-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 { agentToResponse } from "@/lib/api/responses";-import { invalidate, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("agent not found", 404);- }-- return writeJSON(agentToResponse(agent));-});--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const [body, valErr] = await parseBody(req, UpdateAgentRequestSchema);- if (valErr) return valErr;-- const data: Record<string, unknown> = {};- if (body.name !== undefined) data.name = body.name;- if (body.description !== undefined) data.description = body.description;- if (body.instructions !== undefined) data.instructions = body.instructions;- if (body.runtime_id !== undefined) {- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(db, body.runtime_id, ws.workspaceId, ctx.userId);- if (!runtime) {- return writeError("runtime not found in workspace", 400);- }- data.runtimeId = body.runtime_id;- }- if (body.runtime_config !== undefined) {- const rc = body.runtime_config;- const sanitized: Record<string, unknown> = {};- if (typeof rc.model === "string") {- sanitized.model = rc.model;- }- data.runtimeConfig = sanitized;- }- if (body.visibility !== undefined) data.visibility = body.visibility;- if (body.avatar_url !== undefined) data.avatarUrl = body.avatar_url;-- const existing = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!existing) return writeError("agent not found", 404);- if (existing.ownerId !== ctx.userId) return writeError("agent owner access required", 403);-- const updated = await queries.agent.updateAgent(db, id, ws.workspaceId, data as { name?: string; description?: string; instructions?: string; runtimeId?: string; runtimeConfig?: unknown; visibility?: string; avatarUrl?: string | null }, ctx.userId);- if (!updated) {- return writeError("agent not found", 404);- }-- await Promise.all([- invalidate(cacheKeys.allHandles(ws.workspaceId)),- invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),- ]);-- return writeJSON(agentToResponse(updated));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("agent id is required", 400);- }-- const existing = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);- if (!existing) return writeError("agent not found", 404);- if (existing.ownerId !== ctx.userId) return writeError("agent owner access required", 403);-- const deleted = await queries.agent.deleteAgent(db, id, ws.workspaceId, ctx.userId);- if (!deleted) {- return writeError("agent not found", 404);- }-- await Promise.all([- invalidate(cacheKeys.allHandles(ws.workspaceId)),- invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),- ]);-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/agents/[id]/skills/route.test.ts b/src/web/src/app/api/agents/[id]/skills/route.test.tsdeleted file mode 100644index 725ed7935..000000000--- a/src/web/src/app/api/agents/[id]/skills/route.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetAgent = vi.fn();-const mockGetRuntime = vi.fn();-const mockGetSkills = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- runtime: { getAgentRuntime: (...a: unknown[]) => mockGetRuntime(...a) },- agentSkill: { getSkills: (...a: unknown[]) => mockGetSkills(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--function get(url: string, params: Record<string, string>) {- return GET(new NextRequest(url), { params });-}--describe("GET /api/agents/[id]/skills", () => {- it("400 when agent id missing", async () => {- const res = await get("http://localhost/x?workspace_id=w1", {});- expect(res.status).toBe(400);- });-- it("400 when workspace_id missing", async () => {- const res = await get("http://localhost/x", { id: "a1" });- expect(res.status).toBe(400);- });-- it("404 when agent not found in workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const res = await get("http://localhost/x?workspace_id=w1", { id: "a1" });- expect(res.status).toBe(404);- expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");- });-- it("returns skills for the agent's runtime provider", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: "rt1" });- mockGetRuntime.mockResolvedValue({ provider: "codex" });- mockGetSkills.mockResolvedValue([{ name: "skill-a" }]);- const res = await get("http://localhost/x?workspace_id=w1", { id: "a1" });- const body = await res.json();- expect(res.status).toBe(200);- expect(body.skills).toEqual([{ name: "skill-a" }]);- expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "codex", "w1");- });-- it("defaults to claude when the runtime provider is unknown", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: "rt1" });- mockGetRuntime.mockResolvedValue({ provider: "weird-runtime" });- mockGetSkills.mockResolvedValue([]);- await get("http://localhost/x?workspace_id=w1", { id: "a1" });- expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "claude", "w1");- });-- it("defaults to claude when agent has no runtimeId", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", runtimeId: null });- mockGetSkills.mockResolvedValue([]);- await get("http://localhost/x?workspace_id=w1", { id: "a1" });- expect(mockGetSkills).toHaveBeenCalledWith({}, "a1", "claude", "w1");- expect(mockGetRuntime).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agents/[id]/skills/route.ts b/src/web/src/app/api/agents/[id]/skills/route.tsdeleted file mode 100644index 3520b48cb..000000000--- a/src/web/src/app/api/agents/[id]/skills/route.ts+++ /dev/null@@ -1,35 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { getDb } from "@/lib/db";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- if (!agentId) return writeError("agent id required", 400);-- const workspaceId = new URL(req.url).searchParams.get("workspace_id");- if (!workspaceId) return writeError("workspace_id required", 400);-- const agent = await queries.agent.getAgent(db, agentId, workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);-- const KNOWN_RUNTIMES = ["claude", "codex", "opencode"] as const;-- let runtime: string = "claude";- if (agent.runtimeId) {- const rt = await queries.runtime.getAgentRuntime(db, agent.runtimeId);- if (rt) runtime = rt.provider;- }-- if (!KNOWN_RUNTIMES.includes(runtime as typeof KNOWN_RUNTIMES[number])) {- console.warn(`[skills] Unsupported runtime "${runtime}" for agent ${agentId}, defaulting to "claude"`);- runtime = "claude";- }-- const skills = await queries.agentSkill.getSkills(db, agentId, runtime, workspaceId);-- return writeJSON({ skills });-});diff --git a/src/web/src/app/api/agents/[id]/threads/route.ts b/src/web/src/app/api/agents/[id]/threads/route.tsdeleted file mode 100644index 5731850c1..000000000--- a/src/web/src/app/api/agents/[id]/threads/route.ts+++ /dev/null@@ -1,47 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- if (!agentId) {- return writeError("agent id is required", 400);- }-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- const url = new URL(req.url);- const before = url.searchParams.get("before") || undefined;- const limitParam = url.searchParams.get("limit");- const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;-- const threads = await queries.conversation.listThreadsByAgent(- db, ws.workspaceId, agentId, { limit: limit + 1, before }- );-- const hasMore = threads.length > limit;- const items = threads.slice(0, limit);-- return writeJSON({- threads: items.map(t => ({- id: t.id,- parent_message_id: t.parentMessageId,- thread_title: t.threadTitle ?? "",- reply_count: t.replyCount,- last_reply_at: t.lastReplyAt,- last_reply_preview: t.lastReplyPreview ?? "",- created_at: t.createdAt,- })),- has_more: hasMore,- });-});diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.tsdeleted file mode 100644index 22e432abc..000000000--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockRemoveWhitelist = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- whitelist: {- removeWhitelist: (...args: unknown[]) => mockRemoveWhitelist(...args),- },- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { DELETE } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetAgent.mockResolvedValue({ id: "a1", visibility: "public", ownerId: "u1" });-});--describe("DELETE /api/agents/[id]/whitelist/[whitelistId]", () => {- it("removes entry and returns 204", async () => {- mockRemoveWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist/wl1", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", whitelistId: "wl1" }) };- const res = await DELETE(req, ctx);-- expect(res.status).toBe(204);- expect(mockRemoveWhitelist).toHaveBeenCalledWith(- expect.anything(),- "wl1",- "a1",- "w1",- );- });-- it("returns 404 for non-existent entry", async () => {- mockRemoveWhitelist.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist/wl999", {- method: "DELETE",- });- const ctx = { params: Promise.resolve({ id: "a1", whitelistId: "wl999" }) };- const res = await DELETE(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("whitelist entry not found");- });-});diff --git a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts b/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.tsdeleted file mode 100644index 3388ae9e7..000000000--- a/src/web/src/app/api/agents/[id]/whitelist/[whitelistId]/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeError } from "@/lib/middleware/helpers"--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- const whitelistId = ctx.params?.whitelistId;- if (!agentId || !whitelistId) return writeError("missing required params", 400);-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const removed = await queries.whitelist.removeWhitelist(db, whitelistId, agentId, ws.workspaceId);- if (!removed) return writeError("whitelist entry not found", 404);-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts b/src/web/src/app/api/agents/[id]/whitelist/route.test.tsdeleted file mode 100644index ecd2ef2a7..000000000--- a/src/web/src/app/api/agents/[id]/whitelist/route.test.ts+++ /dev/null@@ -1,303 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetAgent = vi.fn();-const mockGetWhitelist = vi.fn();-const mockAddWhitelist = vi.fn();-const mockCreateConversation = vi.fn();-const mockEnqueueTask = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", EMAIL_NOTIFICATION: "email_notification", CALENDAR_EVENT: "calendar_event" },- queries: {- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- whitelist: {- getWhitelist: (...args: unknown[]) => mockGetWhitelist(...args),- addWhitelist: (...args: unknown[]) => mockAddWhitelist(...args),- },- conversation: {- createConversation: (...args: unknown[]) => mockCreateConversation(...args),- },- },- AddWhitelistRequestSchema: {- parse(data: unknown) {- const d = data as Record<string, unknown>;- if (!d || typeof d !== "object" || typeof d.email !== "string" || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(d.email)) {- const err = new Error("validation");- (err as any).issues = [{ path: ["email"], message: "Invalid email" }];- throw err;- }- return { email: String(d.email) };- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/services/task", () => ({- TaskService: class {- enqueueTask(...args: unknown[]) { return mockEnqueueTask(...args); }- },-}));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/[id]/whitelist", () => {- it("returns whitelist entries", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockGetWhitelist.mockResolvedValue([- { id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" },- { id: "wl2", email: "[email protected]", createdAt: "2024-01-02T00:00:00.000Z" },- ]);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(body[0]).toEqual({ id: "wl1", email: "[email protected]", created_at: "2024-01-01T00:00:00Z" });- expect(body[1]).toEqual({ id: "wl2", email: "[email protected]", created_at: "2024-01-02T00:00:00Z" });- });-- it("returns empty array when no entries", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockGetWhitelist.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([]);- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist");- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await GET(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-});--describe("POST /api/agents/[id]/whitelist", () => {- it("adds email and returns 201", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockAddWhitelist.mockResolvedValue({- id: "wl1",- email: "[email protected]",- createdAt: "2024-01-01T00:00:00.000Z",- });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({ id: "wl1", email: "[email protected]", created_at: "2024-01-01T00:00:00Z" });- });-- it("rejects invalid email with 400", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "not-an-email" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(400);- });-- it("rejects missing email with 400", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({}),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(400);- });-- it("normalizes email to lowercase", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockAddWhitelist.mockResolvedValue({- id: "wl1",- email: "[email protected]",- createdAt: "2024-01-01T00:00:00.000Z",- });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(201);- expect(mockAddWhitelist).toHaveBeenCalledWith(- expect.anything(),- "a1",- "w1",- "[email protected]",- );- });-- it("handles duplicate with 409", async () => {- mockGetAgent.mockResolvedValue({ id: "a1" });- mockAddWhitelist.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(409);- expect(body.error).toBe("email already whitelisted");- });-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("agent not found");- });-- it("creates welcome email task when agent has runtime and emailHandle", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });- mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });- mockCreateConversation.mockResolvedValue({ id: "conv1" });- mockEnqueueTask.mockResolvedValue({ id: "t1" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(201);- expect(mockCreateConversation).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- workspaceId: "w1",- agentId: "a1",- userId: "u1",- type: "email_notification",- }),- );- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "conv1", "w1",- expect.stringContaining("[email protected]"),- "email_notification",- );- });-- it("skips welcome task when agent has no runtimeId", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: null, emailHandle: "myagent" });- mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(201);- expect(mockCreateConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-- it("skips welcome task when agent has no emailHandle", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: null });- mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(201);- expect(mockCreateConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-- it("returns 201 even when welcome task creation fails", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });- mockAddWhitelist.mockResolvedValue({ id: "wl1", email: "[email protected]", createdAt: "2024-01-01T00:00:00.000Z" });- mockCreateConversation.mockRejectedValue(new Error("db error"));-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(201);- });-- it("does not create welcome task for duplicate entries", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1", ownerId: "u1", runtimeId: "rt1", emailHandle: "myagent" });- mockAddWhitelist.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents/a1/whitelist", {- method: "POST",- body: JSON.stringify({ email: "[email protected]" }),- });- const ctx = { params: Promise.resolve({ id: "a1" }) };- const res = await POST(req, ctx);-- expect(res.status).toBe(409);- expect(mockCreateConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agents/[id]/whitelist/route.ts b/src/web/src/app/api/agents/[id]/whitelist/route.tsdeleted file mode 100644index a038dafde..000000000--- a/src/web/src/app/api/agents/[id]/whitelist/route.ts+++ /dev/null@@ -1,82 +0,0 @@-import { queries, AddWhitelistRequestSchema, TASK_TYPES } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError, parseBody, formatTimestamp } from "@/lib/middleware/helpers"-import { TaskService } from "@/lib/services/task"-import { invalidate, cacheKeys } from "@/lib/cache"--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- if (!agentId) return writeError("agent id is required", 400);-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);-- const entries = await queries.whitelist.getWhitelist(db, agentId, ws.workspaceId);- return writeJSON(- entries.map((w) => ({- id: w.id,- email: w.email,- created_at: formatTimestamp(w.createdAt),- }))- );-});--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- if (!agentId) return writeError("agent id is required", 400);-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found", 404);-- const [body, err] = await parseBody(req, AddWhitelistRequestSchema);- if (err) return err;-- const email = body.email.toLowerCase();- const entry = await queries.whitelist.addWhitelist(db, agentId, ws.workspaceId, email);- if (!entry) return writeError("email already whitelisted", 409);-- if (agent.runtimeId && agent.emailHandle && agent.ownerId) {- try {- const conv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: agent.id,- userId: agent.ownerId,- title: `Welcome: ${email}`.slice(0, 50),- type: TASK_TYPES.EMAIL_NOTIFICATION,- });- const taskService = new TaskService(db);- await taskService.enqueueTask(- agent.id,- conv.id,- ws.workspaceId,- `Your owner (${ctx.email}) has added a new contact to your whitelist: ${email}. Please compose and send them a welcome email introducing yourself as "${agent.name}". Be warm and professional. Let them know they can reach you at your email address and briefly describe how you can help them.`,- TASK_TYPES.EMAIL_NOTIFICATION,- );- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- } catch {- // Best-effort — don't fail the whitelist operation- }- }-- return writeJSON(- {- id: entry.id,- email: entry.email,- created_at: formatTimestamp(entry.createdAt),- },- 201- );-});diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.test.tsdeleted file mode 100644index 62dd1a3af..000000000--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockCreateRequest = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- runtime: { getAgentRuntime: vi.fn() },- workspaceFileRequest: { createRequest: (...args: unknown[]) => mockCreateRequest(...args) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/cache", () => ({- cacheKeys: { hasPendingFileRequest: (ws: string) => `pfr:${ws}` },-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToDaemon: vi.fn().mockResolvedValue(undefined),-}));--import { POST } from "./route";--function postReq(agentId: string, body: unknown) {- return new NextRequest(- `http://localhost/api/agents/${agentId}/workspace/browse`,- {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- },- );-}--describe("POST /api/agents/[id]/workspace/browse", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 404 when agent not found", async () => {- mockGetAgent.mockResolvedValue(null);-- const res = await POST(postReq("a1", { request_type: "tree", path: "." }), {- params: Promise.resolve({ id: "a1" }),- });- expect(res.status).toBe(404);- expect(mockGetAgent).toHaveBeenCalledWith({}, "a1", "w1", "u1");- });-- it("creates a file request and returns request_id for tree", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });- mockCreateRequest.mockResolvedValue({ id: "wfr_abc123" });-- const res = await POST(postReq("a1", { request_type: "tree", path: "." }), {- params: Promise.resolve({ id: "a1" }),- });- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.request_id).toBe("wfr_abc123");- expect(mockCreateRequest).toHaveBeenCalledWith({}, {- workspaceId: "w1",- agentId: "a1",- requestType: "tree",- path: ".",- });- });-- it("creates a file request for read with custom path", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });- mockCreateRequest.mockResolvedValue({ id: "wfr_def456" });-- const res = await POST(postReq("a1", { request_type: "read", path: "memory.md" }), {- params: Promise.resolve({ id: "a1" }),- });- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.request_id).toBe("wfr_def456");- expect(mockCreateRequest).toHaveBeenCalledWith({}, {- workspaceId: "w1",- agentId: "a1",- requestType: "read",- path: "memory.md",- });- });-- it("returns 400 for invalid request_type", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", workspaceId: "w1" });-- const res = await POST(postReq("a1", { request_type: "delete", path: "." }), {- params: Promise.resolve({ id: "a1" }),- });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts b/src/web/src/app/api/agents/[id]/workspace/browse/route.tsdeleted file mode 100644index 22e244c88..000000000--- a/src/web/src/app/api/agents/[id]/workspace/browse/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { NextRequest } from "next/server";-import { queries, WorkspaceFileBrowseRequestSchema } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";-import { getDb } from "@/lib/db";-import { cacheKeys } from "@/lib/cache";-import { broadcastToDaemon } from "@/lib/broadcast";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = ctx.params?.id;- if (!agentId) return writeError("agent id required", 400);-- const [body, err] = await parseBody(req, WorkspaceFileBrowseRequestSchema);- if (err) return err;-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const row = await queries.workspaceFileRequest.createRequest(db, {- workspaceId: ws.workspaceId,- agentId,- requestType: body.request_type,- path: body.path,- });-- const kv = ctx.env.CACHE_KV ?? null;- if (kv) {- kv.put(cacheKeys.hasPendingFileRequest(ws.workspaceId), "1", { expirationTtl: 60 }).catch(() => {});- }-- // Push file request to daemon (best-effort)- if (agent.runtimeId) {- const runtime = await queries.runtime.getAgentRuntime(db, agent.runtimeId);- if (runtime) {- broadcastToDaemon(runtime.daemonId, {- type: "daemon.file_requests",- workspaceId: ws.workspaceId,- requests: [{ id: row.id, agent_id: agentId, request_type: body.request_type, path: body.path }],- }).catch(() => {});- }- }-- return writeJSON({ request_id: row.id });-});diff --git a/src/web/src/app/api/agents/active-task-counts/route.test.ts b/src/web/src/app/api/agents/active-task-counts/route.test.tsdeleted file mode 100644index 585c70a2f..000000000--- a/src/web/src/app/api/agents/active-task-counts/route.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListActiveTaskCountsByWorkspace = vi.fn();-const mockGetAllAgentsForWorkspace = vi.fn();-const mockGetAllAgentAccessForWorkspace = vi.fn();--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: any, _ttl: any, fn: any) => fn()),- cacheKeys: {- activeTaskCounts: (ws: string) => `atc:${ws}`,- allAgents: (ws: string) => `agents:${ws}`,- allAgentAccess: (ws: string) => `aa:${ws}`,- },-}));-vi.mock("@alook/shared", () => ({- queries: {- task: {- listActiveTaskCountsByWorkspace: (...args: any[]) =>- mockListActiveTaskCountsByWorkspace(...args),- },- agent: {- getAllAgentsForWorkspace: (...args: any[]) =>- mockGetAllAgentsForWorkspace(...args),- },- agentAccess: {- getAllAgentAccessForWorkspace: (...args: any[]) =>- mockGetAllAgentAccessForWorkspace(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/agent-visibility", () => ({- filterVisibleAgents: vi.fn(() => [{ id: "ag1" }]),-}));--import { GET } from "./route";--describe("GET /api/agents/active-task-counts", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns correct counts per agent", async () => {- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag1" }]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);- mockListActiveTaskCountsByWorkspace.mockResolvedValue([- { agentId: "ag1", count: 3 },- ]);-- const res = await GET(- new NextRequest("http://localhost/api/agents/active-task-counts"),- {}- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ counts: { ag1: 3 } });- expect(mockListActiveTaskCountsByWorkspace).toHaveBeenCalledWith({}, "w1", ["ag1"], "u1");- });-- it("returns empty counts when no active tasks", async () => {- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "ag1" }]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);- mockListActiveTaskCountsByWorkspace.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/agents/active-task-counts"),- {}- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ counts: {} });- });-});diff --git a/src/web/src/app/api/agents/active-task-counts/route.ts b/src/web/src/app/api/agents/active-task-counts/route.tsdeleted file mode 100644index 94ec3e206..000000000--- a/src/web/src/app/api/agents/active-task-counts/route.ts+++ /dev/null@@ -1,31 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- const visibleAgentIds = agents.map((a) => a.id);-- if (visibleAgentIds.length === 0) return writeJSON({ counts: {} });-- const rows = await queries.task.listActiveTaskCountsByWorkspace(db, ws.workspaceId, visibleAgentIds, ctx.userId);- const counts: Record<string, number> = {};- for (const row of rows) {- counts[row.agentId] = Number(row.count);- }-- return writeJSON({ counts });-});diff --git a/src/web/src/app/api/agents/active-tasks/route.test.ts b/src/web/src/app/api/agents/active-tasks/route.test.tsdeleted file mode 100644index 0ef515548..000000000--- a/src/web/src/app/api/agents/active-tasks/route.test.ts+++ /dev/null@@ -1,84 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockListActive = vi.fn();-const mockGetAllAgents = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- task: { listActiveTasksByWorkspace: (...a: unknown[]) => mockListActive(...a) },- agent: { getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgents(...a) },- agentAccess: { getAllAgentAccessForWorkspace: vi.fn().mockResolvedValue([]) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),- cacheKeys: { allAgents: (w: string) => `ag:${w}`, allAgentAccess: (w: string) => `aa:${w}` },-}));-vi.mock("@/lib/agent-visibility", () => ({ filterVisibleAgents: vi.fn((a: any[]) => a) }));-import { filterVisibleAgents } from "@/lib/agent-visibility";--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents/active-tasks", () => {- it("returns active tasks joined with visible agent info", async () => {- mockListActive.mockResolvedValue([- { id: "t1", agentId: "a1", prompt: "do x", status: "running", type: "dm", conversationId: "c1", channel: null, createdAt: "2026-05-30" },- ]);- mockGetAllAgents.mockResolvedValue([{ id: "a1", name: "Agent 1", avatarUrl: "u" }]);-- const res = await GET(new NextRequest("http://localhost/x"), {});- const body = await res.json();- expect(res.status).toBe(200);- expect(body.tasks[0]).toMatchObject({- id: "t1", agent_id: "a1", agent: { name: "Agent 1", avatarUrl: "u" }, channel: "default",- });- expect(mockListActive).toHaveBeenCalledWith({}, "w1", ["a1"], "u1");- });-- it("passes visible agent IDs to the query for filtering", async () => {- mockGetAllAgents.mockResolvedValue([- { id: "a1", name: "Visible", avatarUrl: "u", visibility: "public", ownerId: "u1" },- { id: "a2", name: "Hidden", avatarUrl: "h", visibility: "private", ownerId: "u2" },- ]);- vi.mocked(filterVisibleAgents).mockReturnValue([- { id: "a1", name: "Visible", avatarUrl: "u", visibility: "public", ownerId: "u1" },- ]);- mockListActive.mockResolvedValue([- { id: "t1", agentId: "a1", prompt: "x", status: "running", type: "dm", conversationId: "c1", channel: "ops", createdAt: "d" },- ]);- const res = await GET(new NextRequest("http://localhost/x"), {});- const body = await res.json();- expect(mockListActive).toHaveBeenCalledWith({}, "w1", ["a1"], "u1");- expect(body.tasks).toHaveLength(1);- expect(body.tasks[0].agent_id).toBe("a1");- });-- it("returns empty tasks when user has no visible agents", async () => {- mockGetAllAgents.mockResolvedValue([]);- vi.mocked(filterVisibleAgents).mockReturnValue([]);- const res = await GET(new NextRequest("http://localhost/x"), {});- const body = await res.json();- expect(body.tasks).toEqual([]);- expect(mockListActive).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/agents/active-tasks/route.ts b/src/web/src/app/api/agents/active-tasks/route.tsdeleted file mode 100644index 7466e97e0..000000000--- a/src/web/src/app/api/agents/active-tasks/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- const visibleAgentIds = agents.map((a) => a.id);- const agentMap = new Map(agents.map((a) => [a.id, { name: a.name, avatarUrl: a.avatarUrl }]));-- if (visibleAgentIds.length === 0) return writeJSON({ tasks: [] });- const tasks = await queries.task.listActiveTasksByWorkspace(db, ws.workspaceId, visibleAgentIds, ctx.userId);-- return writeJSON({- tasks: tasks.map((t) => ({- id: t.id,- agent_id: t.agentId,- agent: agentMap.get(t.agentId) ?? null,- prompt: t.prompt,- status: t.status,- type: t.type,- conversation_id: t.conversationId,- channel: t.channel ?? "default",- created_at: t.createdAt,- })),- });-});diff --git a/src/web/src/app/api/agents/pins/reorder/route.test.ts b/src/web/src/app/api/agents/pins/reorder/route.test.tsdeleted file mode 100644index f942e0c58..000000000--- a/src/web/src/app/api/agents/pins/reorder/route.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockListPins = vi.fn();-const mockReorderPins = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agentPin: {- listPins: (...a: unknown[]) => mockListPins(...a),- reorderPins: (...a: unknown[]) => mockReorderPins(...a),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- cacheKeys: { pins: (w: string, u: string) => `pins:${w}:${u}` },-}));--import { PUT } from "./route";--beforeEach(() => vi.clearAllMocks());--function put(body: unknown) {- return PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});-}--describe("PUT /api/agents/pins/reorder", () => {- it("reorders pins when all ids are pinned (204)", async () => {- mockListPins.mockResolvedValue([{ agentId: "a1" }, { agentId: "a2" }]);- const res = await put({ ordered_agent_ids: ["a2", "a1"] });- expect(res.status).toBe(204);- expect(mockReorderPins).toHaveBeenCalledWith({}, "w1", "u1", ["a2", "a1"]);- });-- it("400 on invalid JSON body", async () => {- const res = await PUT(new NextRequest("http://localhost/x", { method: "PUT", body: "nope" }), {});- expect(res.status).toBe(400);- });-- it("400 when ordered_agent_ids is not a non-empty string array", async () => {- const res = await put({ ordered_agent_ids: [] });- expect(res.status).toBe(400);- });-- it("400 when an id is not pinned", async () => {- mockListPins.mockResolvedValue([{ agentId: "a1" }]);- const res = await put({ ordered_agent_ids: ["a1", "a2"] });- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("not pinned");- });-});diff --git a/src/web/src/app/api/agents/pins/reorder/route.ts b/src/web/src/app/api/agents/pins/reorder/route.tsdeleted file mode 100644index 419cb8115..000000000--- a/src/web/src/app/api/agents/pins/reorder/route.ts+++ /dev/null@@ -1,36 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-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 PUT = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let raw: { ordered_agent_ids?: unknown };- try {- raw = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const ids = raw.ordered_agent_ids;- if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.length > 0)) {- return writeError("ordered_agent_ids must be a non-empty array of strings", 400);- }-- const db = getDb(ctx.env.DB);-- const existingPins = await queries.agentPin.listPins(db, ws.workspaceId, ctx.userId);- const pinnedIds = new Set(existingPins.map((p) => p.agentId));- for (const id of ids) {- if (!pinnedIds.has(id)) return writeError(`Agent ${id} is not pinned`, 400);- }-- await queries.agentPin.reorderPins(db, ws.workspaceId, ctx.userId, ids);- invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/agents/pins/route.test.ts b/src/web/src/app/api/agents/pins/route.test.tsdeleted file mode 100644index 77e467b3f..000000000--- a/src/web/src/app/api/agents/pins/route.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockListPins = vi.fn();--const mockListSidebarOrder = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agentPin: {- listPins: (...args: unknown[]) => mockListPins(...args),- },- agentSidebarOrder: {- listOrder: (...args: unknown[]) => mockListSidebarOrder(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers"),-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "member" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--beforeEach(() => {- vi.clearAllMocks();- mockListSidebarOrder.mockResolvedValue([]);-});--describe("GET /api/agents/pins", () => {- it("returns list of pins with mapped fields", async () => {- mockListPins.mockResolvedValue([- { id: "pin1", agentId: "a1", createdAt: "2025-01-01T00:00:00Z", position: 0 },- { id: "pin2", agentId: "a2", createdAt: "2025-01-02T00:00:00Z", position: 1 },- ]);-- const req = new NextRequest("http://localhost/api/agents/pins");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pins).toEqual([- { id: "pin1", agent_id: "a1", created_at: "2025-01-01T00:00:00Z", position: 0 },- { id: "pin2", agent_id: "a2", created_at: "2025-01-02T00:00:00Z", position: 1 },- ]);- expect(body.sidebar_order).toEqual([]);- expect(mockListPins).toHaveBeenCalledWith({}, "w1", "u1");- });-- it("returns empty array when no pins", async () => {- mockListPins.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/agents/pins");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pins).toEqual([]);- expect(body.sidebar_order).toEqual([]);- });-});diff --git a/src/web/src/app/api/agents/pins/route.ts b/src/web/src/app/api/agents/pins/route.tsdeleted file mode 100644index c4b76bbb2..000000000--- a/src/web/src/app/api/agents/pins/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- const db = getDb(ctx.env.DB);- const data = await cached(cacheKeys.pins(ws.workspaceId, ctx.userId), 30, async () => {- const [pins, sidebarOrder] = await Promise.all([- queries.agentPin.listPins(db, ws.workspaceId, ctx.userId),- queries.agentSidebarOrder.listOrder(db, ws.workspaceId, ctx.userId),- ]);- return {- pins: pins.map((p) => ({ id: p.id, agent_id: p.agentId, created_at: p.createdAt, position: p.position })),- sidebar_order: sidebarOrder.map((o) => ({ agent_id: o.agentId, position: o.position })),- };- });- return writeJSON(data);-});diff --git a/src/web/src/app/api/agents/recruit/route.test.ts b/src/web/src/app/api/agents/recruit/route.test.tsdeleted file mode 100644index 73a731e15..000000000--- a/src/web/src/app/api/agents/recruit/route.test.ts+++ /dev/null@@ -1,125 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: vi.fn() }, WORKER_SELF_REFERENCE: { fetch: vi.fn() } } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "id123"), customAlphabet: () => () => "id123" }));-vi.mock("unique-names-generator", () => ({- uniqueNamesGenerator: vi.fn(() => "Robin"),- names: [],-}));-vi.mock("@/lib/avatar/seed-url", () => ({- randomBeamAvatar: vi.fn(() => "avatar-url"),-}));--const mockGetAgent = vi.fn();-const mockGetRuntimeForWs = vi.fn();-const mockGetAllHandles = vi.fn();-const mockCreateAgent = vi.fn();-const mockLinkCreate = vi.fn();-const mockAddWhitelist = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- getAllHandlesForWorkspace: (...a: unknown[]) => mockGetAllHandles(...a),- createAgent: (...a: unknown[]) => mockCreateAgent(...a),- },- runtime: { getAgentRuntimeForWorkspace: (...a: unknown[]) => mockGetRuntimeForWs(...a) },- agentLink: { create: (...a: unknown[]) => mockLinkCreate(...a) },- whitelist: { addWhitelist: (...a: unknown[]) => mockAddWhitelist(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- agentToResponse: (a: any) => ({ id: a.id, name: a.name }),- agentLinkToResponse: (l: any) => ({ id: l.id }),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),- cacheKeys: {- allAgents: () => "a", allHandles: () => "h", allAgentAccess: () => "aa",- allColleagues: () => "c", agentLinks: () => "al",- },-}));-vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));--import { POST } from "./route";--beforeEach(() => vi.clearAllMocks());--const VALID = { instructions: "do things", relationship: "reports to me" };--function post(body: unknown, qs = "?agentId=caller") {- return POST(- new NextRequest(`http://localhost/api/agents/recruit${qs}`, {- method: "POST",- body: JSON.stringify(body),- }),- {},- );-}--describe("POST /api/agents/recruit", () => {- it("400 when agentId query param missing", async () => {- const res = await post(VALID, "");- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("agentId");- });-- it("400 on invalid body (missing instructions/relationship)", async () => {- const res = await post({ name: "X" });- expect(res.status).toBe(400);- });-- it("404 when calling agent not in workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const res = await post(VALID);- expect(res.status).toBe(404);- expect(mockGetAgent).toHaveBeenCalledWith({}, "caller", "w1", "u1");- });-- it("400 when calling agent has no runtime", async () => {- mockGetAgent.mockResolvedValue({ id: "caller", runtimeId: "rt1", emailHandle: null });- mockGetRuntimeForWs.mockResolvedValue(null);- const res = await post(VALID);- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("no runtime");- });-- it("creates a recruited agent + link, scoped to workspace (201)", async () => {- mockGetAgent.mockResolvedValue({ id: "caller", runtimeId: "rt1", emailHandle: null, name: "Caller" });- mockGetRuntimeForWs.mockResolvedValue({ runtimeMode: "local", machineLastSeenAt: null });- mockGetAllHandles.mockResolvedValue([]);- mockCreateAgent.mockResolvedValue({ id: "new1", name: "Robin" });- mockLinkCreate.mockResolvedValue({ id: "link1" });-- const res = await post(VALID);- const body = await res.json();- expect(res.status).toBe(201);- expect(body.agent.id).toBe("new1");- expect(body.agent.email).toBe("[email protected]");- expect(body.link.id).toBe("link1");- expect(mockCreateAgent.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", ownerId: "u1" });- expect(mockLinkCreate.mock.calls[0]![1]).toMatchObject({- workspaceId: "w1", sourceAgentId: "caller", targetAgentId: "new1",- });- });-});diff --git a/src/web/src/app/api/agents/recruit/route.ts b/src/web/src/app/api/agents/recruit/route.tsdeleted file mode 100644index ad173ecec..000000000--- a/src/web/src/app/api/agents/recruit/route.ts+++ /dev/null@@ -1,201 +0,0 @@-import { NextRequest } from "next/server";-import { queries, RecruitAgentRequestSchema, isValidHandle, isOnline, buildMimeMessage, extractThreadId, buildEmailMapKey, DEV_WEB_URL, toAlookAddress } from "@alook/shared";-import { nanoid } from "nanoid";-import { uniqueNamesGenerator, names } from "unique-names-generator";-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 { agentToResponse, agentLinkToResponse } from "@/lib/api/responses";-import { invalidate, cached, cacheKeys } from "@/lib/cache";-import { broadcastToUser } from "@/lib/broadcast";-import { randomBeamAvatar } from "@/lib/avatar/seed-url";--function generateUniqueHandleFromSet(- handleSet: Set<string>,- baseName: string,-): string {- const base = baseName.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);- 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;- if (!handleSet.has(candidate)) {- handleSet.add(candidate);- return candidate;- }- }- const fallback = `${base}-${nanoid(6)}`;- handleSet.add(fallback);- return fallback;-}--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = req.nextUrl.searchParams.get("agentId");- if (!agentId) {- return writeError("agentId query param is required", 400);- }-- const [body, valErr] = await parseBody(req, RecruitAgentRequestSchema);- if (valErr) return valErr;-- const callingAgent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!callingAgent) {- return writeError("not found", 404);- }-- const runtime = callingAgent.runtimeId- ? await queries.runtime.getAgentRuntimeForWorkspace(db, callingAgent.runtimeId, ws.workspaceId, ctx.userId)- : null;- if (!runtime) {- return writeError("calling agent has no runtime — reassign the agent to your own runtime first", 400);- }-- const agentName = body.name?.trim() || uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });-- 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[]);- const handle = generateUniqueHandleFromSet(handleSet, agentName);-- const sanitizedRc: Record<string, unknown> | null = body.model ? { model: body.model } : null;-- const newAgent = await queries.agent.createAgent(db, {- workspaceId: ws.workspaceId,- name: agentName,- description: body.description || "",- instructions: body.instructions,- runtimeId: callingAgent.runtimeId,- runtimeMode: runtime.runtimeMode,- runtimeConfig: sanitizedRc,- visibility: "private",- maxConcurrentTasks: 6,- ownerId: ctx.userId,- emailHandle: handle,- avatarUrl: randomBeamAvatar(),- });-- const link = await queries.agentLink.create(db, {- workspaceId: ws.workspaceId,- sourceAgentId: agentId,- targetAgentId: newAgent.id,- instruction: body.relationship,- });-- if (callingAgent.emailHandle) {- const callerEmail = toAlookAddress(callingAgent.emailHandle);- await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, callerEmail);- }- if (ctx.email) {- await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, ctx.email.toLowerCase());- }-- await Promise.all([- invalidate(cacheKeys.allHandles(ws.workspaceId)),- invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),- ]);-- broadcastToUser(ctx.userId, {- type: "agent.created",- agentId: newAgent.id,- workspaceId: ws.workspaceId,- parentAgentId: agentId,- }).catch(() => {});-- if (isOnline(runtime.machineLastSeenAt) && callingAgent.emailHandle) {- try {- const cfEnv = ctx.env;- const fromAddress = toAlookAddress(callingAgent.emailHandle);- const toAddress = toAlookAddress(handle);- const subject = "Welcome aboard";- const htmlBody = `<p>Hi, I just recruited you. Your instructions are already set. Please reply confirming you're ready to work — tell me your name and email address.</p>`;- const messageId = `<${nanoid()}@alook.ai>`;- const traceId = "tr_" + nanoid();-- const rawMime = buildMimeMessage({- from: fromAddress,- to: toAddress,- subject,- messageId,- body: htmlBody,- bodyType: "text/html",- });-- const r2Key = `emails/${nanoid()}/raw`;- await cfEnv.EMAIL_BUCKET.put(r2Key, rawMime, {- httpMetadata: { contentType: "message/rfc822" },- });-- // Notify agent B (local delivery)- const notifyPayload = JSON.stringify({- agentId: newAgent.id,- workspaceId: ws.workspaceId,- r2Key,- from: fromAddress,- to: toAddress,- subject,- isWhitelisted: true,- forwarded: false,- messageId,- inReplyTo: "",- references: "",- isInternal: true,- traceId,- });- const notifyInit = { method: "POST", headers: { "Content-Type": "application/json" }, body: notifyPayload };- try {- await cfEnv.WORKER_SELF_REFERENCE!.fetch("http://internal/api/email/notify", notifyInit);- } catch {- await fetch(`${DEV_WEB_URL}/api/email/notify`, notifyInit);- }-- // Record outbound email on agent A- await queries.email.createEmail(db, {- agentId,- workspaceId: ws.workspaceId,- fromEmail: fromAddress,- toEmail: toAddress,- subject,- r2Key,- isWhitelisted: false,- forwarded: false,- messageId,- inReplyTo: "",- references: "",- htmlBody,- direction: "outbound",- status: "sent",- });-- // Map thread to recruiter's conversation so replies route back- const conversationId = body.context_key || null;- if (conversationId) {- const threadId = extractThreadId("", "", messageId);- if (threadId) {- await queries.conversationMap.createMapping(db, {- key: buildEmailMapKey(agentId, threadId),- workspaceId: ws.workspaceId,- conversationId,- });- }- }- } catch {- // Best-effort- }- }-- return writeJSON({- agent: { ...agentToResponse(newAgent), email: toAlookAddress(handle) },- link: agentLinkToResponse(link),- }, 201);-});diff --git a/src/web/src/app/api/agents/route.test.ts b/src/web/src/app/api/agents/route.test.tsdeleted file mode 100644index 1379bb9b9..000000000--- a/src/web/src/app/api/agents/route.test.ts+++ /dev/null@@ -1,229 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockListAgents = vi.fn();-const mockCreateAgent = vi.fn();-const mockGetAgent = vi.fn();-const mockGetAgentRuntimeForWorkspace = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- isOnline: vi.fn((t: string | null) => !!t && Date.now() - new Date(t).getTime() < 30_000),- queries: {- agent: {- listAgents: (...args: unknown[]) => mockListAgents(...args),- getAllAgentsForWorkspace: (...args: unknown[]) => mockListAgents(...args),- createAgent: (...args: unknown[]) => mockCreateAgent(...args),- getAgent: (...args: unknown[]) => mockGetAgent(...args),- },- agentAccess: {- getAllAgentAccessForWorkspace: vi.fn().mockResolvedValue([]),- },- runtime: {- getAgentRuntimeForWorkspace: (...args: unknown[]) => mockGetAgentRuntimeForWorkspace(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name })),-}));--const mockReconcileAgentStatus = vi.fn();-vi.mock("@/lib/services/task", () => {- const Svc = function () {- return { reconcileAgentStatus: mockReconcileAgentStatus };- };- return { TaskService: Svc };-});--vi.mock("@/lib/cache", () => ({- invalidate: vi.fn(),- cached: vi.fn((_key: string, _ttl: number, fn: () => Promise<any>) => fn()),- cacheKeys: {- allAgents: (ws: string) => `agents:${ws}`,- allAgentAccess: (ws: string) => `aa:${ws}`,- allHandles: (ws: string) => `handles:${ws}`,- overviewTaskStats: (ws: string, d: string) => `ov_task:${ws}:${d}`,- },-}));--vi.mock("@/lib/agent-visibility", () => ({- filterVisibleAgents: vi.fn((agents: any[]) => agents),-}));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/agents", () => {- it("lists agents in workspace", async () => {- mockListAgents.mockResolvedValue([- { id: "a1", name: "Agent 1" },- { id: "a2", name: "Agent 2" },- ]);-- const req = new NextRequest("http://localhost/api/agents");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "a1", name: "Agent 1" },- { id: "a2", name: "Agent 2" },- ]);- });-});--describe("POST /api/agents", () => {- const validBody = { name: "New Agent", runtime_id: "r1" };-- it("creates agent with valid input", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: null, runtimeMode: "local" });- mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify(validBody),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({ id: "a1", name: "New Agent" });- });-- it("returns 400 for missing name", async () => {- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify({ runtime_id: "r1" }),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("name"));- });-- it("returns 400 for missing runtime_id", async () => {- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify({ name: "Agent" }),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("runtime_id"));- });-- it("TC-3: returns 404 when creating agent on non-owned runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify(validBody),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("runtime not found in workspace");- });-- it("TC-4: creates agent on own runtime successfully", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: null, runtimeMode: "local" });- mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify(validBody),- });- const res = await POST(req, {});-- expect(res.status).toBe(201);- expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith(- expect.anything(),- "r1",- "w1",- "u1",- );- });-- it("creates agent with reconcile when runtime is online", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: new Date().toISOString(), runtimeMode: "local" });- mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });- mockGetAgent.mockResolvedValue({ id: "a1", name: "Reconciled Agent" });-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify(validBody),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(201);- expect(mockReconcileAgentStatus).toHaveBeenCalledWith("a1", "w1");- expect(body).toEqual({ id: "a1", name: "Reconciled Agent" });- });-- it("creates agent without reconcile when runtime is offline", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: null, runtimeMode: "local" });- mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify(validBody),- });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(201);- expect(mockReconcileAgentStatus).not.toHaveBeenCalled();- expect(body).toEqual({ id: "a1", name: "New Agent" });- });-- it("passes runtime_config through to createAgent", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({ machineLastSeenAt: null, runtimeMode: "local" });- mockCreateAgent.mockResolvedValue({ id: "a1", name: "New Agent" });-- const req = new NextRequest("http://localhost/api/agents", {- method: "POST",- body: JSON.stringify({- ...validBody,- runtime_config: { model: "claude-sonnet-4-6" },- }),- });- const res = await POST(req, {});-- expect(res.status).toBe(201);- expect(mockCreateAgent).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({- runtimeConfig: { model: "claude-sonnet-4-6" },- }),- );- });-});diff --git a/src/web/src/app/api/agents/route.ts b/src/web/src/app/api/agents/route.tsdeleted file mode 100644index df9bf6de7..000000000--- a/src/web/src/app/api/agents/route.ts+++ /dev/null@@ -1,129 +0,0 @@-import { NextRequest } from "next/server";-import { queries, isValidHandle, isOnline, CreateAgentRequestSchema, TASK_TYPES } from "@alook/shared"-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 { agentToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { invalidate, cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- return writeJSON(agents.map(agentToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const [body, valErr] = await parseBody(req, CreateAgentRequestSchema);- if (valErr) return valErr;-- const name = body.name.trim();- const runtimeId = body.runtime_id;-- let maxConcurrentTasks = body.max_concurrent_tasks || 0;- if (maxConcurrentTasks <= 0) maxConcurrentTasks = 6;-- const emailHandle = typeof body.email_handle === "string" ? body.email_handle.trim().toLowerCase() : "";- if (emailHandle) {- if (!isValidHandle(emailHandle)) {- return writeError("email_handle must be 4+ alphanumeric/dash characters", 400);- }- const existing = await queries.agent.getAgentByHandle(db, emailHandle);- if (existing) {- return writeError("Handle already taken", 409);- }- }-- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(- db,- runtimeId,- ws.workspaceId,- ctx.userId- );- if (!runtime) {- return writeError("runtime not found in workspace", 404);- }-- const rc = body.runtime_config;- const sanitizedRc: Record<string, unknown> | null = rc- ? { ...(typeof rc.model === "string" ? { model: rc.model } : {}) }- : null;-- const newAgent = await queries.agent.createAgent(db, {- workspaceId: ws.workspaceId,- name,- description: body.description,- instructions: body.instructions,- runtimeId,- runtimeMode: runtime.runtimeMode,- runtimeConfig: sanitizedRc,- visibility: "private",- maxConcurrentTasks,- ownerId: ctx.userId,- emailHandle: emailHandle || null,- avatarUrl: body.avatar_url ?? null,- });-- if (emailHandle && ctx.email) {- await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, ctx.email.toLowerCase());- }-- await Promise.all([- invalidate(cacheKeys.allHandles(ws.workspaceId)),- invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),- ]);-- // Send welcome email to owner- if (newAgent.runtimeId && newAgent.emailHandle && ctx.email && isOnline(runtime.machineLastSeenAt)) {- try {- const conv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: newAgent.id,- userId: ctx.userId,- title: `Welcome: ${ctx.email}`.slice(0, 50),- type: TASK_TYPES.EMAIL_NOTIFICATION,- });- const taskService = new TaskService(db);- await taskService.enqueueTask(- newAgent.id,- conv.id,- ws.workspaceId,- `You have just been created by your owner (${ctx.email}). Please send them a welcome email introducing yourself as "${name}". In the email: 1) Introduce yourself warmly — your name, your email address, and what you can help with. 2) Briefly introduce the Alook platform — a personal AI agent platform where agents can handle emails, schedule tasks, and work autonomously. 3) Let them know they can chat with you directly or email you anytime. Be warm, professional, and concise.`,- TASK_TYPES.EMAIL_NOTIFICATION,- );- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- } catch {- // Best-effort — don't fail agent creation- }- }-- if (isOnline(runtime.machineLastSeenAt)) {- const taskService = new TaskService(db);- await taskService.reconcileAgentStatus(newAgent.id, ws.workspaceId);- const updated = await queries.agent.getAgent(- db,- newAgent.id,- ws.workspaceId,- ctx.userId- );- if (updated) return writeJSON(agentToResponse(updated), 201);- }-- return writeJSON(agentToResponse(newAgent), 201);-});diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.test.ts b/src/web/src/app/api/agents/sidebar/reorder/route.test.tsdeleted file mode 100644index 1ef4c5516..000000000--- a/src/web/src/app/api/agents/sidebar/reorder/route.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetAllAgents = vi.fn();-const mockListPins = vi.fn();-const mockReorder = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: { getAllAgentsForWorkspace: (...a: unknown[]) => mockGetAllAgents(...a) },- agentPin: { listPins: (...a: unknown[]) => mockListPins(...a) },- agentSidebarOrder: { reorder: (...a: unknown[]) => mockReorder(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),- invalidate: vi.fn().mockResolvedValue(undefined),- cacheKeys: { allAgents: (w: string) => `ag:${w}`, pins: (w: string, u: string) => `pins:${w}:${u}` },-}));--import { PUT } from "./route";--beforeEach(() => vi.clearAllMocks());--const put = (body: unknown) =>- PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});--describe("PUT /api/agents/sidebar/reorder", () => {- it("reorders sidebar for unpinned workspace agents (204)", async () => {- mockGetAllAgents.mockResolvedValue([{ id: "a1" }, { id: "a2" }]);- mockListPins.mockResolvedValue([]);- const res = await put({ ordered_agent_ids: ["a2", "a1"] });- expect(res.status).toBe(204);- expect(mockReorder).toHaveBeenCalledWith({}, "w1", "u1", ["a2", "a1"]);- });-- it("400 when an id is not a workspace agent", async () => {- mockGetAllAgents.mockResolvedValue([{ id: "a1" }]);- mockListPins.mockResolvedValue([]);- const res = await put({ ordered_agent_ids: ["a1", "ghost"] });- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("not found");- });-- it("400 when an id is pinned (pinned agents are excluded from sidebar order)", async () => {- mockGetAllAgents.mockResolvedValue([{ id: "a1" }, { id: "a2" }]);- mockListPins.mockResolvedValue([{ agentId: "a1" }]);- const res = await put({ ordered_agent_ids: ["a1", "a2"] });- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("is pinned");- });-- it("400 on empty array", async () => {- const res = await put({ ordered_agent_ids: [] });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/agents/sidebar/reorder/route.ts b/src/web/src/app/api/agents/sidebar/reorder/route.tsdeleted file mode 100644index c957efc65..000000000--- a/src/web/src/app/api/agents/sidebar/reorder/route.ts+++ /dev/null@@ -1,41 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";-import { cacheKeys, invalidate } from "@/lib/cache";--export const PUT = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let raw: { ordered_agent_ids?: unknown };- try {- raw = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const ids = raw.ordered_agent_ids;- if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.length > 0)) {- return writeError("ordered_agent_ids must be a non-empty array of strings", 400);- }-- const db = getDb(ctx.env.DB);-- const [agents, existingPins] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- queries.agentPin.listPins(db, ws.workspaceId, ctx.userId),- ]);- const agentIds = new Set(agents.map((a) => a.id));- const pinnedIds = new Set(existingPins.map((p) => p.agentId));- for (const id of ids) {- if (!agentIds.has(id)) return writeError(`Agent ${id} not found`, 400);- if (pinnedIds.has(id)) return writeError(`Agent ${id} is pinned`, 400);- }-- await queries.agentSidebarOrder.reorder(db, ws.workspaceId, ctx.userId, ids);- invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/artifacts/[id]/content/route.test.ts b/src/web/src/app/api/artifacts/[id]/content/route.test.tsdeleted file mode 100644index 9fb62ba83..000000000--- a/src/web/src/app/api/artifacts/[id]/content/route.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetArtifact = vi.fn();-const mockGetAgent = vi.fn();-const mockBucketGet = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) },- },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- artifact: { getArtifact: (...a: unknown[]) => mockGetArtifact(...a) },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) } }, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/artifacts/[id]/content", () => {- it("downloads artifact content for machine-token workspace access", async () => {- mockGetArtifact.mockResolvedValue({- id: "art_1",- agentId: "ag1",- r2Key: "artifacts/w1/ag1/c1/art_1/brief.md",- filename: "brief.md",- contentType: "text/markdown",- size: 5,- });- mockGetAgent.mockResolvedValue({ id: "ag1" });- mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });-- const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1"), { params: { id: "art_1" } } as any);-- expect(res.status).toBe(200);- expect(res.headers.get("Content-Type")).toBe("text/markdown");- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect(await res.text()).toBe("hello");- expect(mockBucketGet).toHaveBeenCalledWith("artifacts/w1/ag1/c1/art_1/brief.md");- });-- it("serves non-ASCII filenames with RFC 5987 content disposition", async () => {- mockGetArtifact.mockResolvedValue({- id: "art_1",- agentId: "ag1",- r2Key: "artifacts/w1/ag1/c1/art_1/report.pdf",- filename: "深圳市小汽车增量指标证明文件.pdf",- contentType: "application/pdf",- size: 5,- });- mockGetAgent.mockResolvedValue({ id: "ag1" });- mockBucketGet.mockResolvedValue({ body: new Blob(["hello"]).stream() });-- const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1/content?workspace_id=w1&download"), { params: { id: "art_1" } } as any);-- expect(res.status).toBe(200);- expect(res.headers.get("Content-Disposition")).toContain("attachment; filename=");- expect(res.headers.get("Content-Disposition")).toContain("filename*=UTF-8''%E6%B7%B1%E5%9C%B3");- });-});diff --git a/src/web/src/app/api/artifacts/[id]/content/route.ts b/src/web/src/app/api/artifacts/[id]/content/route.tsdeleted file mode 100644index df9c020ea..000000000--- a/src/web/src/app/api/artifacts/[id]/content/route.ts+++ /dev/null@@ -1,45 +0,0 @@-import { contentDisposition } from "@/lib/content-disposition"-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id as string;- const db = getDb(ctx.env.DB);- const bucket = ctx.env.EMAIL_BUCKET;-- const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);- if (!row) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, row.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- const object = await bucket.get(row.r2Key);- if (!object) {- return writeError("artifact content not found", 404);- }-- const download = req.nextUrl.searchParams.get("download");- const headers: Record<string, string> = {- "Cache-Control": "private, no-store",- "Content-Type": row.contentType,- "Content-Length": String(row.size),- };- if (download !== null) {- headers["Content-Disposition"] = contentDisposition("attachment", row.filename);- } else {- headers["Content-Disposition"] = contentDisposition("inline", row.filename);- }-- return new Response(object.body, { headers });-});diff --git a/src/web/src/app/api/artifacts/[id]/route.test.ts b/src/web/src/app/api/artifacts/[id]/route.test.tsdeleted file mode 100644index 56bba33ca..000000000--- a/src/web/src/app/api/artifacts/[id]/route.test.ts+++ /dev/null@@ -1,51 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetArtifact = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- artifact: {- getArtifact: (...a: unknown[]) => mockGetArtifact(...a),- artifactToResponse: (row: any) => ({ id: row.id, filename: row.filename }),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/artifacts/[id]", () => {- it("returns artifact metadata for machine-token workspace access", async () => {- mockGetArtifact.mockResolvedValue({ id: "art_1", agentId: "ag1", filename: "brief.md" });- mockGetAgent.mockResolvedValue({ id: "ag1" });- const res = await GET(new NextRequest("http://localhost/api/artifacts/art_1?workspace_id=w1"), { params: { id: "art_1" } } as any);- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ id: "art_1", filename: "brief.md" });- expect(mockGetArtifact).toHaveBeenCalledWith({}, "art_1", "w1");- });-});diff --git a/src/web/src/app/api/artifacts/[id]/route.ts b/src/web/src/app/api/artifacts/[id]/route.tsdeleted file mode 100644index 34318bc17..000000000--- a/src/web/src/app/api/artifacts/[id]/route.ts+++ /dev/null@@ -1,26 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id as string;- const db = getDb(ctx.env.DB);-- const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);- if (!row) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, row.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- return writeJSON(queries.artifact.artifactToResponse(row));-});diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.tsdeleted file mode 100644index 2fab8494c..000000000--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.test.ts+++ /dev/null@@ -1,113 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetArtifact = vi.fn();-const mockGetAgent = vi.fn();-const mockBucketGet = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) },- },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- artifact: { getArtifact: (...a: unknown[]) => mockGetArtifact(...a) },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...a: unknown[]) => mockBucketGet(...a) } }, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/artifacts/[id]/thumbnail", () => {- it("serves authorized thumbnail bytes with a private immutable policy", async () => {- mockGetArtifact.mockResolvedValue({- id: "art_1",- agentId: "ag1",- thumbnailR2Key: "artifacts/w1/ag1/c1/art_1/thumbnail.jpg",- });- mockGetAgent.mockResolvedValue({ id: "ag1" });- mockBucketGet.mockResolvedValue({ body: new Blob([new Uint8Array(100)]).stream() });-- const res = await GET(- new NextRequest("http://localhost/api/artifacts/art_1/thumbnail?workspace_id=w1"),- { params: { id: "art_1" } } as any,- );-- expect(res.status).toBe(200);- expect(res.headers.get("Vary")).toBe("Authorization");- expect(res.headers.get("Content-Type")).toBe("image/jpeg");- expect(res.headers.get("Cache-Control")).toBe("private, max-age=31536000, immutable");- expect(mockBucketGet).toHaveBeenCalledWith("artifacts/w1/ag1/c1/art_1/thumbnail.jpg");- });-- it("returns 404 when artifact has no thumbnail", async () => {- mockGetArtifact.mockResolvedValue({- id: "art_1",- agentId: "ag1",- thumbnailR2Key: null,- });- mockGetAgent.mockResolvedValue({ id: "ag1" });-- const res = await GET(- new NextRequest("http://localhost/api/artifacts/art_1/thumbnail?workspace_id=w1"),- { params: { id: "art_1" } } as any,- );-- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect(mockBucketGet).not.toHaveBeenCalled();- });-- it("returns 404 when artifact not found", async () => {- mockGetArtifact.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/artifacts/art_missing/thumbnail?workspace_id=w1"),- { params: { id: "art_missing" } } as any,- );-- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- });-- it("returns 404 when agent not accessible to user", async () => {- mockGetArtifact.mockResolvedValue({- id: "art_1",- agentId: "ag1",- thumbnailR2Key: "artifacts/w1/ag1/c1/art_1/thumbnail.jpg",- });- mockGetAgent.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/artifacts/art_1/thumbnail?workspace_id=w1"),- { params: { id: "art_1" } } as any,- );-- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- });-});diff --git a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts b/src/web/src/app/api/artifacts/[id]/thumbnail/route.tsdeleted file mode 100644index 00afa431b..000000000--- a/src/web/src/app/api/artifacts/[id]/thumbnail/route.ts+++ /dev/null@@ -1,42 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const GET = withPrivateMediaCache(withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const id = ctx.params?.id as string;- const db = getDb(ctx.env.DB);- const bucket = ctx.env.EMAIL_BUCKET;-- const row = await queries.artifact.getArtifact(db, id, ws.workspaceId);- if (!row) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, row.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- if (!row.thumbnailR2Key) {- return writeError("no thumbnail", 404);- }-- const object = await bucket.get(row.thumbnailR2Key);- if (!object) {- return writeError("thumbnail content not found", 404);- }-- return new Response(object.body, {- headers: {- "Content-Type": "image/jpeg",- "Cache-Control": "private, max-age=31536000, immutable",- },- });-}));diff --git a/src/web/src/app/api/artifacts/route.test.ts b/src/web/src/app/api/artifacts/route.test.tsdeleted file mode 100644index a62a22d3e..000000000--- a/src/web/src/app/api/artifacts/route.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockList = vi.fn();-const mockGetConversation = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- artifact: {- listArtifactsByConversation: (...a: unknown[]) => mockList(...a),- artifactToResponse: (a: any) => ({ id: a.id }),- },- conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/artifacts", () => {- it("lists artifacts for a conversation scoped to workspace", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });- mockList.mockResolvedValue([{ id: "art_1" }, { id: "art_2" }]);- const req = new NextRequest("http://localhost/api/artifacts?conversation_id=c1");- const res = await GET(req, {});- expect(res.status).toBe(200);- expect(await res.json()).toEqual([{ id: "art_1" }, { id: "art_2" }]);- expect(mockList).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("400 when conversation_id missing", async () => {- const req = new NextRequest("http://localhost/api/artifacts");- const res = await GET(req, {});- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("conversation_id is required");- });-});diff --git a/src/web/src/app/api/artifacts/route.ts b/src/web/src/app/api/artifacts/route.tsdeleted file mode 100644index be319f072..000000000--- a/src/web/src/app/api/artifacts/route.ts+++ /dev/null@@ -1,31 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const conversationId = req.nextUrl.searchParams.get("conversation_id");- if (!conversationId) {- return writeError("conversation_id is required", 400);- }-- const db = getDb(ctx.env.DB);-- const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);- if (!conv || conv.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const rows = await queries.artifact.listArtifactsByConversation(- db,- conversationId,- ws.workspaceId,- );-- return writeJSON(rows.map(queries.artifact.artifactToResponse));-});diff --git a/src/web/src/app/api/artifacts/upload/route.test.ts b/src/web/src/app/api/artifacts/upload/route.test.tsdeleted file mode 100644index bb11c17aa..000000000--- a/src/web/src/app/api/artifacts/upload/route.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockPut = vi.fn().mockResolvedValue(undefined);-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { put: mockPut } } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("nanoid", () => ({ nanoid: vi.fn(() => "xyz"), customAlphabet: () => () => "xyz" }));--const mockGetConversation = vi.fn();-const mockCreateArtifact = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- conversation: { getConversation: (...a: unknown[]) => mockGetConversation(...a) },- artifact: {- createArtifact: (...a: unknown[]) => mockCreateArtifact(...a),- artifactToResponse: (a: any) => ({ id: a.id }),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: mockPut } }, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));--import { POST } from "./route";--beforeEach(() => vi.clearAllMocks());--function formReq(fields: Record<string, string | File>) {- const fd = new FormData();- for (const [k, v] of Object.entries(fields)) fd.append(k, v as any);- return new NextRequest("http://localhost/api/artifacts/upload", { method: "POST", body: fd });-}--describe("POST /api/artifacts/upload", () => {- it("uploads a file to R2 and creates an artifact record", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1", userId: "u1" });- mockCreateArtifact.mockResolvedValue({ id: "art_xyz" });- mockGetAgent.mockResolvedValue({ ownerId: "owner1" });-- const file = new File(["hello"], "note.txt", { type: "text/plain" });- const res = await POST(formReq({ file, conversation_id: "c1" }), {});- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ id: "art_xyz" });- expect(mockPut).toHaveBeenCalled();- expect(mockCreateArtifact.mock.calls[0]![1]).toMatchObject({ workspaceId: "w1", conversationId: "c1" });- });-- it("400 when file missing", async () => {- const res = await POST(formReq({ conversation_id: "c1" }), {});- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("file is required");- });-- it("400 when conversation_id missing", async () => {- const file = new File(["x"], "a.txt", { type: "text/plain" });- const res = await POST(formReq({ file }), {});- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("conversation_id is required");- });-- it("413 when file exceeds the size limit", async () => {- // 10 MB + 1 byte- const big = new File([new Uint8Array(10 * 1024 * 1024 + 1)], "big.bin", { type: "application/octet-stream" });- const res = await POST(formReq({ file: big, conversation_id: "c1" }), {});- expect(res.status).toBe(413);- });-- it("404 when conversation not in workspace", async () => {- mockGetConversation.mockResolvedValue(null);- const file = new File(["x"], "a.txt", { type: "text/plain" });- const res = await POST(formReq({ file, conversation_id: "c1" }), {});- expect(res.status).toBe(404);- });-- it("400 on non-multipart body (invalid form data)", async () => {- const req = new NextRequest("http://localhost/api/artifacts/upload", {- method: "POST",- headers: { "content-type": "application/json" },- body: "{}",- });- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("uploads thumbnail to R2 when provided", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1", userId: "u1" });- mockCreateArtifact.mockResolvedValue({ id: "art_xyz" });- mockGetAgent.mockResolvedValue({ ownerId: "owner1" });-- const file = new File(["img-data"], "photo.png", { type: "image/png" });- const thumb = new File(["thumb-data"], "thumb_photo.png.jpg", { type: "image/jpeg" });- const fd = new FormData();- fd.append("file", file);- fd.append("thumbnail", thumb);- fd.append("conversation_id", "c1");-- const res = await POST(new NextRequest("http://localhost/api/artifacts/upload", { method: "POST", body: fd }), {});- expect(res.status).toBe(200);- expect(mockPut).toHaveBeenCalledTimes(2);- const thumbCall = mockPut.mock.calls[1];- expect(thumbCall[0]).toContain("thumbnail.jpg");- expect(mockCreateArtifact.mock.calls[0]![1]).toHaveProperty("thumbnailR2Key");- });-- it("skips thumbnail when not provided (backward compat)", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", agentId: "a1", userId: "u1" });- mockCreateArtifact.mockResolvedValue({ id: "art_xyz" });- mockGetAgent.mockResolvedValue({ ownerId: "owner1" });-- const file = new File(["hello"], "doc.txt", { type: "text/plain" });- const res = await POST(formReq({ file, conversation_id: "c1" }), {});- expect(res.status).toBe(200);- expect(mockPut).toHaveBeenCalledTimes(1);- expect(mockCreateArtifact.mock.calls[0]![1].thumbnailR2Key).toBeUndefined();- });-});diff --git a/src/web/src/app/api/artifacts/upload/route.ts b/src/web/src/app/api/artifacts/upload/route.tsdeleted file mode 100644index a07c1dd10..000000000--- a/src/web/src/app/api/artifacts/upload/route.ts+++ /dev/null@@ -1,91 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { nanoid } from "nanoid";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { broadcastToUser } from "@/lib/broadcast";--const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB--function sanitizeFilename(name: string): string {- return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";-}--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const bucket = ctx.env.EMAIL_BUCKET;- const db = getDb(ctx.env.DB);-- let formData: FormData;- try {- formData = await req.formData();- } catch {- return writeError("invalid form data", 400);- }-- const file = formData.get("file");- if (!file || !(file instanceof File)) {- return writeError("file is required", 400);- }-- const conversationId = formData.get("conversation_id");- if (!conversationId || typeof conversationId !== "string") {- return writeError("conversation_id is required", 400);- }-- if (file.size > MAX_FILE_SIZE) {- return writeError("file exceeds 10 MB limit", 413);- }-- const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);- if (!conv || conv.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const agentId = conv.agentId;- const filename = sanitizeFilename(file.name);- const contentType = file.type || "application/octet-stream";- const artifactId = "art_" + nanoid();- const r2Key = `artifacts/${ws.workspaceId}/${agentId}/${conversationId}/${artifactId}/${filename}`;-- await bucket.put(r2Key, await file.arrayBuffer(), {- httpMetadata: { contentType },- });-- let thumbnailR2Key: string | undefined;- const thumbnail = formData.get("thumbnail");- if (thumbnail instanceof File && thumbnail.size <= 50 * 1024) {- thumbnailR2Key = `artifacts/${ws.workspaceId}/${agentId}/${conversationId}/${artifactId}/thumbnail.jpg`;- await bucket.put(thumbnailR2Key, await thumbnail.arrayBuffer(), {- httpMetadata: { contentType: "image/jpeg" },- });- }-- const row = await queries.artifact.createArtifact(db, {- id: artifactId,- conversationId,- agentId,- workspaceId: ws.workspaceId,- filename,- contentType,- size: file.size,- r2Key,- thumbnailR2Key,- });- const response = queries.artifact.artifactToResponse(row);-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (agent?.ownerId) {- broadcastToUser(agent.ownerId, {- type: "artifact.uploaded",- conversationId,- artifact: response,- }).catch(() => {});- }-- return writeJSON(response);-});diff --git a/src/web/src/app/api/calendar/[id]/route.test.ts b/src/web/src/app/api/calendar/[id]/route.test.tsdeleted file mode 100644index f83116647..000000000--- a/src/web/src/app/api/calendar/[id]/route.test.ts+++ /dev/null@@ -1,547 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockDelete = vi.fn();-const mockUpdate = vi.fn();-const mockGet = vi.fn();-const mockCreate = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- calendarEvent: {- getCalendarEvent: (...a: unknown[]) => mockGet(...a),- deleteCalendarEvent: (...a: unknown[]) => mockDelete(...a),- updateCalendarEvent: (...a: unknown[]) => mockUpdate(...a),- createCalendarEvent: (...a: unknown[]) => mockCreate(...a),- },- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/api/responses", () => ({- calendarEventToResponse: (e: any) => ({ id: e.id, ...e }),-}));--import { DELETE, PATCH, GET } from "./route";--function req(id: string | undefined, body: unknown) {- const r = new NextRequest(`http://localhost/api/calendar/${id ?? ""}`, {- method: "PATCH",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });- return PATCH(r, { params: { id } } as any);-}--describe("GET /api/calendar/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 200 + the event body when it exists in the workspace", async () => {- mockGet.mockResolvedValue({- id: "ce_1",- agentId: "ag_1",- workspaceId: "ws1",- title: "standup",- });- const r = new NextRequest("http://localhost/api/calendar/ce_1", {- method: "GET",- });- const res = await GET(r, { params: { id: "ce_1" } } as any);- expect(res.status).toBe(200);- expect((await res.json()).id).toBe("ce_1");- expect(mockGet).toHaveBeenCalledWith({}, "ce_1", "ws1", "u1");- });-- it("returns 404 when the event is not in the caller's workspace", async () => {- mockGet.mockResolvedValue(null);- const r = new NextRequest("http://localhost/api/calendar/ce_missing", {- method: "GET",- });- const res = await GET(r, { params: { id: "ce_missing" } } as any);- expect(res.status).toBe(404);- });-- it("returns 400 when id is missing", async () => {- const r = new NextRequest("http://localhost/api/calendar/", {- method: "GET",- });- const res = await GET(r, { params: {} } as any);- expect(res.status).toBe(400);- });-});--describe("DELETE /api/calendar/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("404s when the event does not exist in the workspace", async () => {- mockGet.mockResolvedValue(null);- const r = new NextRequest("http://localhost/api/calendar/ce_missing", {- method: "DELETE",- });- const res = await DELETE(r, { params: { id: "ce_missing" } } as any);- expect(res.status).toBe(404);- });-- it("returns the deleted event when successful (non-recurring, no body)", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockDelete.mockResolvedValue({ id: "ce_1" });- const r = new NextRequest("http://localhost/api/calendar/ce_1", {- method: "DELETE",- });- const res = await DELETE(r, { params: { id: "ce_1" } } as any);- expect(res.status).toBe(200);- expect((await res.json()).id).toBe("ce_1");- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- });-- it("400s when id is missing", async () => {- const r = new NextRequest("http://localhost/api/calendar/", {- method: "DELETE",- });- const res = await DELETE(r, { params: {} } as any);- expect(res.status).toBe(400);- });-});--function delReq(id: string | undefined, body?: unknown) {- const init: RequestInit & { body?: string; headers?: Record<string, string> } = {- method: "DELETE",- };- if (body !== undefined) {- init.body = JSON.stringify(body);- init.headers = { "Content-Type": "application/json" };- }- const r = new NextRequest(`http://localhost/api/calendar/${id ?? ""}`, init);- return DELETE(r, { params: { id } } as any);-}--describe("DELETE /api/calendar/[id] — scope-aware", () => {- beforeEach(() => vi.clearAllMocks());-- it("scope=this on a non-recurring event falls back to full delete", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockDelete.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", { scope: "this" });- expect(res.status).toBe(200);- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- expect(mockUpdate).not.toHaveBeenCalled();- });-- it("scope=this without occurrence_at advances the parent one interval", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", { scope: "this" });- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- scheduledAt: "2026-04-18T09:00:00.000Z",- });- expect(mockDelete).not.toHaveBeenCalled();- });-- it("scope=this on the last remaining occurrence deletes the parent", async () => {- mockGet.mockResolvedValue(- sourceDaily({- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatStopAt: "2026-04-17T23:59:59.999Z",- })- );- mockDelete.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", { scope: "this" });- expect(res.status).toBe(200);- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- expect(mockUpdate).not.toHaveBeenCalled();- });-- it("scope=this on a future occurrence appends an exception", async () => {- mockGet.mockResolvedValue(sourceDaily({ exceptions: [] }));- mockUpdate.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", {- scope: "this",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- exceptions: ["2026-04-20T09:00:00.000Z"],- });- expect(mockDelete).not.toHaveBeenCalled();- });-- it("scope=this does not duplicate an already-recorded exception", async () => {- mockGet.mockResolvedValue(- sourceDaily({ exceptions: ["2026-04-20T09:00:00.000Z"] })- );- mockUpdate.mockResolvedValue({ id: "ce_1" });- await delReq("ce_1", {- scope: "this",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(mockUpdate.mock.calls[0][3].exceptions).toEqual([- "2026-04-20T09:00:00.000Z",- ]);- });-- it("scope=following without occurrence_at deletes the parent", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockDelete.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", { scope: "following" });- expect(res.status).toBe(200);- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- expect(mockUpdate).not.toHaveBeenCalled();- });-- it("scope=following with occurrence_at on the next fire deletes the parent", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockDelete.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", {- scope: "following",- occurrence_at: "2026-04-17T09:00:00.000Z",- });- expect(res.status).toBe(200);- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- });-- it("scope=following with a future occurrence_at clips repeat_stop_at 1ms earlier", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- const res = await delReq("ce_1", {- scope: "following",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- repeatStopAt: "2026-04-20T08:59:59.999Z",- });- expect(mockDelete).not.toHaveBeenCalled();- });-- it("400s on a malformed body", async () => {- mockGet.mockResolvedValue(sourceDaily());- const res = await delReq("ce_1", { scope: "bogus" });- expect(res.status).toBe(400);- });-});--function sourceNonRepeating(overrides: Record<string, unknown> = {}) {- return {- id: "ce_1",- agentId: "ag_1",- workspaceId: "ws1",- title: "standup",- description: null,- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: null,- repeatStopAt: null,- lastTriggeredAt: null,- ...overrides,- };-}--function sourceDaily(overrides: Record<string, unknown> = {}) {- return {- ...sourceNonRepeating(),- repeatInterval: "1day",- repeatStopAt: null,- ...overrides,- };-}--describe("PATCH /api/calendar/[id] — basics", () => {- beforeEach(() => vi.clearAllMocks());-- it("404s when the event does not exist in the workspace", async () => {- mockGet.mockResolvedValue(null);- const res = await req("ce_missing", { title: "new" });- expect(res.status).toBe(404);- });-- it("400s on an empty patch body", async () => {- const res = await req("ce_1", {});- expect(res.status).toBe(400);- expect(mockUpdate).not.toHaveBeenCalled();- });-- it("400s when the title is an empty string", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- const res = await req("ce_1", { title: "" });- expect(res.status).toBe(400);- });-- it("400s when id is missing", async () => {- const res = await req(undefined, { title: "t" });- expect(res.status).toBe(400);- });-- it("200s + returns the updated body on a successful title+description update", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockUpdate.mockResolvedValue({- id: "ce_1",- title: "new",- description: "<p>desc</p>",- });- const res = await req("ce_1", { title: "new", description: "<p>desc</p>" });- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- title: "new",- description: "<p>desc</p>",- });- });-- it("normalizes empty-HTML description to null before reaching the query", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockUpdate.mockResolvedValue({ id: "ce_1", description: null });- await req("ce_1", { description: "<p></p>" });- expect(mockUpdate.mock.calls[0][3]).toEqual({ description: null });- });-- it("passes description: null through as a clearing op", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockUpdate.mockResolvedValue({ id: "ce_1", description: null });- await req("ce_1", { description: null });- expect(mockUpdate.mock.calls[0][3]).toEqual({ description: null });- });-});--describe("PATCH /api/calendar/[id] — full fields", () => {- beforeEach(() => vi.clearAllMocks());-- it("404s when agent_id is not in the workspace", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockGetAgent.mockResolvedValue(null);- const res = await req("ce_1", { agent_id: "ag_missing" });- expect(res.status).toBe(404);- expect(mockUpdate).not.toHaveBeenCalled();- });-- it("updates agent + scheduled_at in place on a non-repeating event", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockGetAgent.mockResolvedValue({ id: "ag_2" });- mockUpdate.mockResolvedValue({ id: "ce_1" });- const res = await req("ce_1", {- agent_id: "ag_2",- scheduled_at: "2026-04-18T10:00:00.000Z",- });- expect(res.status).toBe(200);- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- agentId: "ag_2",- scheduledAt: "2026-04-18T10:00:00.000Z",- });- });-- it("converts repeat_stop_date → repeat_stop_at (ISO end-of-day)", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- await req("ce_1", { repeat_stop_date: "2026-05-01" });- const patch = mockUpdate.mock.calls[0][3];- expect(patch.repeatStopAt).toMatch(/2026-05-0[12]T/);- });-- it("passes repeat_interval: null and repeat_stop_date: null through as clears", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- await req("ce_1", { repeat_interval: null, repeat_stop_date: null });- expect(mockUpdate.mock.calls[0][3]).toEqual({- repeatInterval: null,- repeatStopAt: null,- });- });-- it("scope=this on a non-repeating event is treated as in-place", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- mockUpdate.mockResolvedValue({ id: "ce_1" });- await req("ce_1", { title: "new", scope: "this" });- expect(mockUpdate).toHaveBeenCalledTimes(1);- expect(mockCreate).not.toHaveBeenCalled();- expect(mockDelete).not.toHaveBeenCalled();- });-- it("scope=following on a repeating event is in-place", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- await req("ce_1", { title: "renamed", scope: "following" });- expect(mockUpdate).toHaveBeenCalledTimes(1);- expect(mockUpdate.mock.calls[0][3]).toEqual({ title: "renamed" });- expect(mockCreate).not.toHaveBeenCalled();- });-});--describe("PATCH /api/calendar/[id] — scope=this split", () => {- beforeEach(() => vi.clearAllMocks());-- it("advances the parent's scheduled_at and inserts a detached one-off", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- mockCreate.mockImplementation((_db, data) => ({- id: "ce_2",- ...data,- }));- const res = await req("ce_1", {- title: "just this one",- scope: "this",- });- expect(res.status).toBe(200);-- // Parent advanced by 1 day- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- scheduledAt: "2026-04-18T09:00:00.000Z",- });- // Detached one-off created with patch applied and no repeat- expect(mockCreate).toHaveBeenCalledTimes(1);- const detached = mockCreate.mock.calls[0][1];- expect(detached.workspaceId).toBe("ws1");- expect(detached.agentId).toBe("ag_1");- expect(detached.title).toBe("just this one");- expect(detached.scheduledAt).toBe("2026-04-17T09:00:00.000Z");- expect(detached.repeatInterval).toBeNull();- expect(detached.repeatStopAt).toBeNull();-- // Returns the detached event- const body = await res.json();- expect(body.id).toBe("ce_2");- expect(mockDelete).not.toHaveBeenCalled();- });-- it("applies the edited scheduled_at to the detached event (not the parent)", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_2", ...data }));- await req("ce_1", {- scheduled_at: "2026-04-17T11:30:00.000Z",- scope: "this",- });- // Parent still advances to next occurrence of the ORIGINAL schedule- expect(mockUpdate.mock.calls[0][3]).toEqual({- scheduledAt: "2026-04-18T09:00:00.000Z",- });- // Detached uses the user-supplied time- expect(mockCreate.mock.calls[0][1].scheduledAt).toBe(- "2026-04-17T11:30:00.000Z"- );- });-- it("deletes the parent when the series ends at this occurrence", async () => {- mockGet.mockResolvedValue(- sourceDaily({- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatStopAt: "2026-04-17T23:59:59.999Z",- })- );- mockCreate.mockImplementation((_db, data) => ({ id: "ce_2", ...data }));- const res = await req("ce_1", { title: "final", scope: "this" });- expect(res.status).toBe(200);- expect(mockDelete).toHaveBeenCalledWith({}, "ce_1", "ws1");- expect(mockUpdate).not.toHaveBeenCalled();- expect(mockCreate).toHaveBeenCalledTimes(1);- expect(mockCreate.mock.calls[0][1].title).toBe("final");- });-- it("validates agent_id in the workspace even on the split path", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockGetAgent.mockResolvedValue(null);- const res = await req("ce_1", { agent_id: "ag_nope", scope: "this" });- expect(res.status).toBe(404);- expect(mockUpdate).not.toHaveBeenCalled();- expect(mockCreate).not.toHaveBeenCalled();- });-});--describe("PATCH /api/calendar/[id] — scope=this on a future occurrence", () => {- beforeEach(() => vi.clearAllMocks());-- it("adds occurrence_at to the parent's exceptions; does NOT advance parent", async () => {- mockGet.mockResolvedValue(- sourceDaily({ exceptions: [] })- );- mockUpdate.mockResolvedValue({ id: "ce_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_2", ...data }));-- const res = await req("ce_1", {- title: "renamed future",- scope: "this",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(res.status).toBe(200);-- // Parent updated with exceptions, NOT scheduledAt- expect(mockUpdate).toHaveBeenCalledWith({}, "ce_1", "ws1", {- exceptions: ["2026-04-20T09:00:00.000Z"],- });- // Detached one-off uses the occurrence_at as scheduledAt- expect(mockCreate.mock.calls[0][1].scheduledAt).toBe(- "2026-04-20T09:00:00.000Z"- );- expect(mockCreate.mock.calls[0][1].title).toBe("renamed future");- });-- it("does not duplicate the exception when it's already recorded", async () => {- mockGet.mockResolvedValue(- sourceDaily({ exceptions: ["2026-04-20T09:00:00.000Z"] })- );- mockUpdate.mockResolvedValue({ id: "ce_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_2", ...data }));- await req("ce_1", {- title: "x",- scope: "this",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(mockUpdate.mock.calls[0][3].exceptions).toEqual([- "2026-04-20T09:00:00.000Z",- ]);- });-- it("uses the edited scheduled_at on the detached event when provided", async () => {- mockGet.mockResolvedValue(sourceDaily());- mockUpdate.mockResolvedValue({ id: "ce_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_2", ...data }));- await req("ce_1", {- scheduled_at: "2026-04-20T10:30:00.000Z",- scope: "this",- occurrence_at: "2026-04-20T09:00:00.000Z",- });- expect(mockCreate.mock.calls[0][1].scheduledAt).toBe(- "2026-04-20T10:30:00.000Z"- );- });-});--describe("GET /api/calendar/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("404s when the event does not exist", async () => {- mockGet.mockResolvedValue(null);- const r = new NextRequest("http://localhost/api/calendar/ce_x");- const res = await GET(r, { params: { id: "ce_x" } } as any);- expect(res.status).toBe(404);- });-- it("returns the event when found", async () => {- mockGet.mockResolvedValue(sourceNonRepeating());- const r = new NextRequest("http://localhost/api/calendar/ce_1");- const res = await GET(r, { params: { id: "ce_1" } } as any);- expect(res.status).toBe(200);- });-});diff --git a/src/web/src/app/api/calendar/[id]/route.ts b/src/web/src/app/api/calendar/[id]/route.tsdeleted file mode 100644index fa24a51af..000000000--- a/src/web/src/app/api/calendar/[id]/route.ts+++ /dev/null@@ -1,288 +0,0 @@-import {- queries,- UpdateCalendarEventRequestSchema,- DeleteCalendarEventRequestSchema,- computeNextScheduledAt,- isEmptyHtml,-} from "@alook/shared";-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 { calendarEventToResponse } from "@/lib/api/responses";-import { repeatStopDateToStopAt } from "@/lib/services/calendar";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("calendar event id is required", 400);-- const event = await queries.calendarEvent.getCalendarEvent(- db,- id,- ws.workspaceId,- ctx.userId- );- if (!event) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(event));-});--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("calendar event id is required", 400);-- const [body, err] = await parseBody(req, UpdateCalendarEventRequestSchema);- if (err) return err;-- const source = await queries.calendarEvent.getCalendarEvent(- db,- id,- ws.workspaceId,- ctx.userId- );- if (!source) return writeError("calendar event not found", 404);-- if (body.agent_id !== undefined) {- const agent = await queries.agent.getAgent(- db,- body.agent_id,- ws.workspaceId,- ctx.userId- );- if (!agent) return writeError("agent not found in workspace", 404);- }-- const patch: {- title?: string;- description?: string | null;- agentId?: string;- scheduledAt?: string;- repeatInterval?: string | null;- repeatStopAt?: string | null;- } = {};-- if (body.title !== undefined) patch.title = body.title;- if (body.description !== undefined) {- const rawDesc = body.description?.trim() || null;- patch.description = rawDesc && isEmptyHtml(rawDesc) ? null : rawDesc;- }- if (body.agent_id !== undefined) patch.agentId = body.agent_id;- if (body.scheduled_at !== undefined) {- patch.scheduledAt = new Date(body.scheduled_at).toISOString();- }- if (body.repeat_interval !== undefined) {- patch.repeatInterval = body.repeat_interval;- }- if (body.repeat_stop_date !== undefined) {- patch.repeatStopAt =- body.repeat_stop_date === null- ? null- : repeatStopDateToStopAt(body.repeat_stop_date);- }-- const wantSplit =- body.scope === "this" &&- source.repeatInterval !== null &&- source.repeatInterval !== undefined;-- if (!wantSplit) {- const updated = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- patch- );- if (!updated) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(updated));- }-- // Split path: detach a specific occurrence. Anchor on occurrence_at- // (default = source.scheduledAt — the next fire).- const occurrenceAt = body.occurrence_at- ? new Date(body.occurrence_at).toISOString()- : source.scheduledAt;- const existingExceptions = source.exceptions ?? [];-- if (occurrenceAt === source.scheduledAt) {- // Editing the next fire — advance the parent past this occurrence.- const next = computeNextScheduledAt(- source.scheduledAt,- source.repeatInterval!,- source.repeatStopAt ?? null,- source.scheduledAt,- existingExceptions- );- if (next === null) {- await queries.calendarEvent.deleteCalendarEvent(db, id, ws.workspaceId);- } else {- const advanced = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- { scheduledAt: next }- );- if (!advanced) return writeError("calendar event not found", 404);- }- } else {- // Editing a future occurrence — record it as an exception on the parent.- const nextExceptions = existingExceptions.includes(occurrenceAt)- ? existingExceptions- : [...existingExceptions, occurrenceAt];- const updated = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- { exceptions: nextExceptions }- );- if (!updated) return writeError("calendar event not found", 404);- }-- const detached = await queries.calendarEvent.createCalendarEvent(db, {- agentId: patch.agentId ?? source.agentId,- workspaceId: ws.workspaceId,- title: patch.title ?? source.title,- description:- patch.description !== undefined ? patch.description : source.description ?? null,- scheduledAt: patch.scheduledAt ?? occurrenceAt,- repeatInterval: null,- repeatStopAt: null,- exceptions: [],- });-- return writeJSON(calendarEventToResponse(detached));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("calendar event id is required", 400);-- // Body is optional: an empty payload keeps legacy "delete the whole row"- // behavior. Only validate when the caller actually sent one.- let body: { scope?: "this" | "following"; occurrence_at?: string } = {};- const rawText = await req.text();- if (rawText.trim()) {- let raw: unknown;- try {- raw = JSON.parse(rawText);- } catch {- return writeError("invalid request body", 400);- }- const parsed = DeleteCalendarEventRequestSchema.safeParse(raw);- if (!parsed.success) {- return writeError("validation error", 400);- }- body = parsed.data;- }-- const source = await queries.calendarEvent.getCalendarEvent(- db,- id,- ws.workspaceId,- ctx.userId- );- if (!source) return writeError("calendar event not found", 404);-- const isRecurring = Boolean(source.repeatInterval);- const scope = body.scope;-- // Non-recurring, or no scope given → full delete (covers legacy callers).- if (!scope || !isRecurring) {- const deleted = await queries.calendarEvent.deleteCalendarEvent(- db,- id,- ws.workspaceId- );- if (!deleted) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(deleted));- }-- const occurrenceAt = body.occurrence_at- ? new Date(body.occurrence_at).toISOString()- : source.scheduledAt;- const existingExceptions = source.exceptions ?? [];-- if (scope === "this") {- if (occurrenceAt === source.scheduledAt) {- // Skip the next fire: advance parent to the following occurrence.- const next = computeNextScheduledAt(- source.scheduledAt,- source.repeatInterval!,- source.repeatStopAt ?? null,- source.scheduledAt,- existingExceptions- );- if (next === null) {- const deleted = await queries.calendarEvent.deleteCalendarEvent(- db,- id,- ws.workspaceId- );- if (!deleted) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(deleted));- }- const advanced = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- { scheduledAt: next }- );- if (!advanced) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(advanced));- }- // Skip a future occurrence: record it as an exception. No change to- // scheduled_at — the parent keeps firing on its normal cadence.- const nextExceptions = existingExceptions.includes(occurrenceAt)- ? existingExceptions- : [...existingExceptions, occurrenceAt];- const updated = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- { exceptions: nextExceptions }- );- if (!updated) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(updated));- }-- // scope === "following"- // If the cut point is the next fire (or earlier), the series has no- // remaining occurrences — just drop the row.- if (new Date(occurrenceAt).getTime() <= new Date(source.scheduledAt).getTime()) {- const deleted = await queries.calendarEvent.deleteCalendarEvent(- db,- id,- ws.workspaceId- );- if (!deleted) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(deleted));- }-- // Future cut point: clip the series one ms before the occurrence so- // everything from `occurrenceAt` onward is pruned by expandOccurrences- // (which breaks on `current > stopD`).- const clippedStop = new Date(- new Date(occurrenceAt).getTime() - 1- ).toISOString();- const updated = await queries.calendarEvent.updateCalendarEvent(- db,- id,- ws.workspaceId,- { repeatStopAt: clippedStop }- );- if (!updated) return writeError("calendar event not found", 404);- return writeJSON(calendarEventToResponse(updated));-});diff --git a/src/web/src/app/api/calendar/route.test.ts b/src/web/src/app/api/calendar/route.test.tsdeleted file mode 100644index 16eed18f2..000000000--- a/src/web/src/app/api/calendar/route.test.ts+++ /dev/null@@ -1,288 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockList = vi.fn();-const mockCreate = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- listAgents: vi.fn().mockResolvedValue([]),- },- calendarEvent: {- listCalendarEvents: (...a: unknown[]) => mockList(...a),- createCalendarEvent: (...a: unknown[]) => mockCreate(...a),- },- meetingSession: {- listMeetingsWithSchedule: vi.fn().mockResolvedValue([]),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/api/responses", () => ({- calendarEventToResponse: (e: any) => ({- id: e.id,- title: e.title,- scheduled_at: e.scheduledAt,- occurrence_at: e.occurrenceAt ?? e.scheduledAt,- }),-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));--import { GET, POST } from "./route";--describe("GET /api/calendar", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists events scoped to workspace, optionally filtered by agent/date range", async () => {- mockList.mockResolvedValue([- {- id: "ce_1",- title: "standup",- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: null,- repeatStopAt: null,- exceptions: [],- },- ]);- const req = new NextRequest(- "http://localhost/api/calendar?agentId=ag_1&from=2026-04-01T00:00:00.000Z&to=2026-04-30T23:59:59.999Z"- );- mockGetAgent.mockResolvedValue({ id: "ag_1" });- const res = await GET(req, {} as any);- const body = await res.json();- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].id).toBe("ce_1");- expect(mockList).toHaveBeenCalledWith({}, "ws1", {- userId: "u1",- agentId: "ag_1",- from: "2026-04-01T00:00:00.000Z",- to: "2026-04-30T23:59:59.999Z",- });- });-- it("returns empty when filter agent has no events", async () => {- mockList.mockResolvedValue([]);- const req = new NextRequest("http://localhost/api/calendar?agentId=ag_nope");- const res = await GET(req, {} as any);- expect(res.status).toBe(200);- expect(await res.json()).toEqual([]);- });-- it("expands daily recurring events into one row per occurrence", async () => {- mockList.mockResolvedValue([- {- id: "ce_1",- title: "daily",- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: "1day",- repeatStopAt: null,- exceptions: [],- },- ]);- const req = new NextRequest(- "http://localhost/api/calendar?from=2026-04-17T00:00:00.000Z&to=2026-04-20T23:59:59.999Z"- );- const res = await GET(req, {} as any);- const body = await res.json();- expect(body).toHaveLength(4);- expect(body.map((b: { occurrence_at: string }) => b.occurrence_at)).toEqual([- "2026-04-17T09:00:00.000Z",- "2026-04-18T09:00:00.000Z",- "2026-04-19T09:00:00.000Z",- "2026-04-20T09:00:00.000Z",- ]);- });-- it("skips occurrences in the parent's exceptions list", async () => {- mockList.mockResolvedValue([- {- id: "ce_1",- title: "daily",- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: "1day",- repeatStopAt: null,- exceptions: ["2026-04-19T09:00:00.000Z"],- },- ]);- const req = new NextRequest(- "http://localhost/api/calendar?from=2026-04-17T00:00:00.000Z&to=2026-04-20T23:59:59.999Z"- );- const res = await GET(req, {} as any);- const body = await res.json();- expect(body.map((b: { occurrence_at: string }) => b.occurrence_at)).toEqual([- "2026-04-17T09:00:00.000Z",- "2026-04-18T09:00:00.000Z",- "2026-04-20T09:00:00.000Z",- ]);- });-- it("does not expand non-recurring rows", async () => {- mockList.mockResolvedValue([- {- id: "ce_1",- title: "one-off",- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: null,- repeatStopAt: null,- exceptions: [],- },- ]);- const req = new NextRequest(- "http://localhost/api/calendar?from=2026-04-01T00:00:00.000Z&to=2026-04-30T23:59:59.999Z"- );- const res = await GET(req, {} as any);- const body = await res.json();- expect(body).toHaveLength(1);- });-});--describe("POST /api/calendar", () => {- beforeEach(() => vi.clearAllMocks());-- async function post(body: unknown) {- const req = new NextRequest("http://localhost/api/calendar", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });- return POST(req, {} as any);- }-- it("rejects malformed repeat_interval", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- const res = await post({- agent_id: "ag_1",- title: "test",- scheduled_at: "2026-04-17T09:00:00.000Z",- repeat_interval: "weekly",- });- expect(res.status).toBe(400);- });-- it("rejects repeat_stop_date without repeat_interval", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- const res = await post({- agent_id: "ag_1",- title: "test",- scheduled_at: "2026-04-17T09:00:00.000Z",- repeat_stop_date: "2026-05-17",- });- expect(res.status).toBe(400);- });-- it("rejects repeat_stop_date earlier than the first scheduled occurrence", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- const res = await post({- agent_id: "ag_1",- title: "test",- scheduled_at: "2026-04-17T09:00:00.000Z",- repeat_interval: "1day",- repeat_stop_date: "2026-04-16",- });- expect(res.status).toBe(400);- });-- it("404s when the agent does not belong to the workspace", async () => {- mockGetAgent.mockResolvedValue(null);- const res = await post({- agent_id: "ag_missing",- title: "test",- scheduled_at: "2026-04-17T09:00:00.000Z",- });- expect(res.status).toBe(404);- });-- it("creates the event with repeat_stop_at derived from repeat_stop_date", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- mockCreate.mockImplementation((_db, data) => ({- id: "ce_1",- ...data,- }));- const res = await post({- agent_id: "ag_1",- title: "standup",- scheduled_at: "2026-04-17T09:00:00.000Z",- repeat_interval: "1day",- repeat_stop_date: "2026-05-17",- });- expect(res.status).toBe(201);- expect(mockCreate).toHaveBeenCalledTimes(1);- const payload = mockCreate.mock.calls[0][1];- expect(payload.agentId).toBe("ag_1");- expect(payload.workspaceId).toBe("ws1");- expect(payload.repeatInterval).toBe("1day");- expect(payload.repeatStopAt).toMatch(/2026-05-1[78]T/);- });-- it("passes description through to create and echoes it in the response", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- mockCreate.mockImplementation((_db, data) => ({- id: "ce_1",- title: data.title,- description: data.description,- }));- const res = await post({- agent_id: "ag_1",- title: "standup",- description: "<p>hello</p>",- scheduled_at: "2026-04-17T09:00:00.000Z",- });- expect(res.status).toBe(201);- const payload = mockCreate.mock.calls[0][1];- expect(payload.description).toBe("<p>hello</p>");- });-- it("sets description to null when omitted", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_1", ...data }));- const res = await post({- agent_id: "ag_1",- title: "standup",- scheduled_at: "2026-04-17T09:00:00.000Z",- });- expect(res.status).toBe(201);- expect(mockCreate.mock.calls[0][1].description).toBeNull();- });-- it("normalizes empty-HTML description to null", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- mockCreate.mockImplementation((_db, data) => ({ id: "ce_1", ...data }));- const res = await post({- agent_id: "ag_1",- title: "standup",- description: "<p></p>",- scheduled_at: "2026-04-17T09:00:00.000Z",- });- expect(res.status).toBe(201);- expect(mockCreate.mock.calls[0][1].description).toBeNull();- });-});diff --git a/src/web/src/app/api/calendar/route.ts b/src/web/src/app/api/calendar/route.tsdeleted file mode 100644index 4fdba54c2..000000000--- a/src/web/src/app/api/calendar/route.ts+++ /dev/null@@ -1,212 +0,0 @@-import { NextRequest } from "next/server";-import {- queries,- CreateCalendarEventRequestSchema,- expandOccurrences,- getOccurrencesPerDay,- isEmptyHtml,-} from "@alook/shared";-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 { calendarEventToResponse } from "@/lib/api/responses";-import { repeatStopDateToStopAt } from "@/lib/services/calendar";-import { broadcastToUser } from "@/lib/broadcast";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;- const from = req.nextUrl.searchParams.get("from") ?? undefined;- const to = req.nextUrl.searchParams.get("to") ?? undefined;-- const rows = await queries.calendarEvent.listCalendarEvents(- db,- ws.workspaceId,- { userId: ctx.userId, agentId, from, to }- );-- // Expand recurring rows into per-occurrence virtual rows within [from, to].- // High-frequency events (>5 occurrences/day) are collapsed into one row per- // UTC day with a `collapsed_count` hint instead of expanding individually.- const out: (ReturnType<typeof calendarEventToResponse> & { _type?: string; _status?: string })[] = [];- for (const row of rows) {- if (!row.repeatInterval || !from || !to) {- out.push(calendarEventToResponse(row));- continue;- }- const perDay = getOccurrencesPerDay(row.repeatInterval);- if (perDay > 5) {- // Collapse: emit one representative row per UTC day in the range- const fromD = new Date(from);- const toD = new Date(to);- const startD = new Date(row.scheduledAt);- const stopD = row.repeatStopAt ? new Date(row.repeatStopAt) : null;-- // Iterate UTC days in [from, to], capped at 366 days- const cursor = new Date(Date.UTC(fromD.getUTCFullYear(), fromD.getUTCMonth(), fromD.getUTCDate()));- const endDay = new Date(Date.UTC(toD.getUTCFullYear(), toD.getUTCMonth(), toD.getUTCDate()));- const startDay = new Date(Date.UTC(startD.getUTCFullYear(), startD.getUTCMonth(), startD.getUTCDate()));- let dayCount = 0;- while (cursor <= endDay && dayCount < 366) {- if (cursor >= startDay && (!stopD || cursor <= stopD)) {- // First occurrence time on this day: use the event's time-of-day- const occIso = new Date(Date.UTC(- cursor.getUTCFullYear(), cursor.getUTCMonth(), cursor.getUTCDate(),- startD.getUTCHours(), startD.getUTCMinutes(), startD.getUTCSeconds()- )).toISOString();- out.push(- calendarEventToResponse({- ...row,- scheduledAt: occIso,- occurrenceAt: occIso,- collapsedCount: perDay,- })- );- }- cursor.setUTCDate(cursor.getUTCDate() + 1);- dayCount++;- }- } else {- const occurrences = expandOccurrences(- row.scheduledAt,- row.repeatInterval,- row.repeatStopAt ?? null,- row.exceptions ?? [],- from,- to- );- for (const occIso of occurrences) {- out.push(- calendarEventToResponse({- ...row,- scheduledAt: occIso,- occurrenceAt: occIso,- })- );- }- }- }-- // Also include meetings with scheduled_at in range, filtered to user's agents- const userAgents = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);- const userAgentIds = new Set(userAgents.map(a => a.id));- const meetingRows = await queries.meetingSession.listMeetingsWithSchedule(db, ws.workspaceId);- for (const m of meetingRows) {- if (!m.scheduledAt) continue;- if (!userAgentIds.has(m.agentId)) continue;- if (from && m.scheduledAt < from) continue;- if (to && m.scheduledAt > to) continue;- if (agentId && m.agentId !== agentId) continue;- out.push({- id: m.id,- agent_id: m.agentId,- workspace_id: m.workspaceId,- title: m.title || "Meeting",- description: m.meetingUrl,- scheduled_at: m.scheduledAt,- occurrence_at: m.scheduledAt,- collapsed_count: null,- repeat_interval: null,- repeat_stop_at: null,- last_triggered_at: null,- created_at: m.createdAt,- updated_at: m.updatedAt,- _type: "meeting" as const,- _status: m.status,- });- }-- out.sort((a, b) => (a.scheduled_at ?? "").localeCompare(b.scheduled_at ?? ""));-- return writeJSON(out);-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const [body, err] = await parseBody(req, CreateCalendarEventRequestSchema);- if (err) return err;-- const agent = await queries.agent.getAgent(- db,- body.agent_id,- ws.workspaceId,- ctx.userId- );- if (!agent) return writeError("agent not found in workspace", 404);-- const scheduledAtDate = new Date(body.scheduled_at);- const scheduledAtIso = scheduledAtDate.toISOString();-- let repeatStopAtIso: string | null = null;- if (body.repeat_stop_date) {- repeatStopAtIso = repeatStopDateToStopAt(body.repeat_stop_date);- if (new Date(repeatStopAtIso) < scheduledAtDate) {- return writeError(- "repeat_stop_date must be on or after the first scheduled occurrence",- 400- );- }- }-- const rawDesc = body.description?.trim() || null;- const description = rawDesc && isEmptyHtml(rawDesc) ? null : rawDesc;-- const created = await queries.calendarEvent.createCalendarEvent(db, {- agentId: body.agent_id,- workspaceId: ws.workspaceId,- title: body.title,- description,- scheduledAt: scheduledAtIso,- repeatInterval: body.repeat_interval ?? null,- repeatStopAt: repeatStopAtIso,- });-- if (body.conversation_id && agent.ownerId) {- const conv = await queries.conversation.getConversation(db, body.conversation_id, ws.workspaceId);- if (conv) {- const eventContent = `${body.title}`;- const metadata = JSON.stringify({- calendarEventId: created.id,- title: body.title,- scheduledAt: created.scheduledAt,- ...(created.repeatInterval ? { repeatInterval: created.repeatInterval } : {}),- });- const eventMsg = await queries.message.createMessage(db, {- conversationId: body.conversation_id,- role: "event",- content: eventContent,- metadata,- });- broadcastToUser(agent.ownerId, {- type: "conversation.message",- conversationId: body.conversation_id,- message: {- id: eventMsg.id,- conversation_id: eventMsg.conversationId,- role: eventMsg.role as "event",- content: eventMsg.content,- task_id: eventMsg.taskId,- attachment_ids: null,- metadata: {- calendarEventId: created.id,- title: body.title,- scheduledAt: created.scheduledAt,- ...(created.repeatInterval ? { repeatInterval: created.repeatInterval } : {}),- },- created_at: eventMsg.createdAt,- },- }).catch(() => { });- }- }-- return writeJSON(calendarEventToResponse(created), 201);-});diff --git a/src/web/src/app/api/channels/[id]/route.test.ts b/src/web/src/app/api/channels/[id]/route.test.tsdeleted file mode 100644index fde441e88..000000000--- a/src/web/src/app/api/channels/[id]/route.test.ts+++ /dev/null@@ -1,216 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetChannelById = vi.fn();-const mockRenameChannel = vi.fn();-const mockDeleteChannel = vi.fn();-const mockChannelToResponse = vi.fn((c: any) => ({- id: c.id,- workspace_id: c.workspaceId,- name: c.name,- created_at: c.createdAt,-}));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- channel: {- getChannelById: (...args: any[]) => mockGetChannelById(...args),- renameChannel: (...args: any[]) => mockRenameChannel(...args),- deleteChannel: (...args: any[]) => mockDeleteChannel(...args),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- channelToResponse: (...args: any[]) => mockChannelToResponse(...args),-}));--import { PATCH, DELETE } from "./route";--const CH = { id: "ch_1", workspaceId: "w1", name: "work", createdAt: "2024-01-01T00:00:00Z" };-const DEFAULT_CH = { id: "ch_0", workspaceId: "w1", name: "default", createdAt: "2024-01-01T00:00:00Z" };--function patchReq(id: string, body: any) {- return [- new NextRequest(`http://localhost/api/channels/${id}`, {- method: "PATCH",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- }),- { params: Promise.resolve({ id }) },- ] as const;-}--function deleteReq(id: string) {- return [- new NextRequest(`http://localhost/api/channels/${id}`, { method: "DELETE" }),- { params: Promise.resolve({ id }) },- ] as const;-}--describe("PATCH /api/channels/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("renames a channel", async () => {- mockGetChannelById.mockResolvedValue(CH);- mockRenameChannel.mockResolvedValue({ ...CH, name: "projects" });-- const [req, ctx] = patchReq("ch_1", { name: "projects" });- const res = await PATCH(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.name).toBe("projects");- expect(mockRenameChannel).toHaveBeenCalledWith({}, "ch_1", "w1", "projects");- });-- it("returns 404 when channel not found", async () => {- mockGetChannelById.mockResolvedValue(null);-- const [req, ctx] = patchReq("ch_999", { name: "new" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(404);- expect((await res.json()).error).toBe("channel not found");- });-- it("returns 400 when renaming the default channel", async () => {- mockGetChannelById.mockResolvedValue(DEFAULT_CH);-- const [req, ctx] = patchReq("ch_0", { name: "renamed" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("cannot rename the default channel");- });-- it("returns 400 when renaming to 'default'", async () => {- mockGetChannelById.mockResolvedValue(CH);-- const [req, ctx] = patchReq("ch_1", { name: "default" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("cannot rename to 'default'");- });-- it("returns 400 for missing name", async () => {- const [req, ctx] = patchReq("ch_1", {});- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("name is required");- });-- it("returns 400 for empty name", async () => {- const [req, ctx] = patchReq("ch_1", { name: " " });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("name is required");- });-- it("returns 400 for name exceeding 32 characters", async () => {- const [req, ctx] = patchReq("ch_1", { name: "a".repeat(33) });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("name must be 32 characters or less");- });-- it("returns 400 for name with invalid characters", async () => {- const [req, ctx] = patchReq("ch_1", { name: "my channel" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("name can only contain letters, digits, dashes, and underscores");- });-- it("returns 400 for invalid JSON body", async () => {- const req = new NextRequest("http://localhost/api/channels/ch_1", {- method: "PATCH",- body: "not json",- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "ch_1" }) } as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("invalid request body");- });-- it("returns 409 for duplicate channel name", async () => {- mockGetChannelById.mockResolvedValue(CH);- mockRenameChannel.mockRejectedValue(new Error("UNIQUE constraint failed: channel.name"));-- const [req, ctx] = patchReq("ch_1", { name: "existing" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(409);- expect((await res.json()).error).toBe("a channel with this name already exists");- });-- it("returns 404 when renameChannel returns null", async () => {- mockGetChannelById.mockResolvedValue(CH);- mockRenameChannel.mockResolvedValue(null);-- const [req, ctx] = patchReq("ch_1", { name: "new-name" });- const res = await PATCH(req, ctx as any);-- expect(res.status).toBe(404);- });-});--describe("DELETE /api/channels/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("deletes a channel", async () => {- mockGetChannelById.mockResolvedValue(CH);- mockDeleteChannel.mockResolvedValue(CH);-- const [req, ctx] = deleteReq("ch_1");- const res = await DELETE(req, ctx as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- expect(mockDeleteChannel).toHaveBeenCalledWith({}, "ch_1", "w1");- });-- it("returns 404 when channel not found", async () => {- mockGetChannelById.mockResolvedValue(null);-- const [req, ctx] = deleteReq("ch_999");- const res = await DELETE(req, ctx as any);-- expect(res.status).toBe(404);- expect((await res.json()).error).toBe("channel not found");- });-- it("returns 400 when deleting the default channel", async () => {- mockGetChannelById.mockResolvedValue(DEFAULT_CH);-- const [req, ctx] = deleteReq("ch_0");- const res = await DELETE(req, ctx as any);-- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("cannot delete the default channel");- });-});diff --git a/src/web/src/app/api/channels/[id]/route.ts b/src/web/src/app/api/channels/[id]/route.tsdeleted file mode 100644index 149685c60..000000000--- a/src/web/src/app/api/channels/[id]/route.ts+++ /dev/null@@ -1,67 +0,0 @@-import { queries, isUniqueConstraintError } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { channelToResponse } from "@/lib/api/responses";--const CHANNEL_NAME_RE = /^[a-zA-Z0-9_-]+$/;--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("channel id is required", 400);-- let body: { name?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const name = typeof body.name === "string" ? body.name.trim() : "";-- if (!name) return writeError("name is required", 400);- if (name.length > 32) return writeError("name must be 32 characters or less", 400);- if (name === "default") return writeError("cannot rename to 'default'", 400);- if (!CHANNEL_NAME_RE.test(name)) {- return writeError("name can only contain letters, digits, dashes, and underscores", 400);- }-- const existing = await queries.channel.getChannelById(db, id, ws.workspaceId);- if (!existing) return writeError("channel not found", 404);- if (existing.name === "default") return writeError("cannot rename the default channel", 400);-- try {- const updated = await queries.channel.renameChannel(db, id, ws.workspaceId, name);- if (!updated) return writeError("channel not found", 404);- return writeJSON(channelToResponse(updated));- } catch (err) {- if (isUniqueConstraintError(err)) {- return writeError("a channel with this name already exists", 409);- }- throw err;- }-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("channel id is required", 400);-- const existing = await queries.channel.getChannelById(db, id, ws.workspaceId);- if (!existing) return writeError("channel not found", 404);- if (existing.name === "default") return writeError("cannot delete the default channel", 400);-- await queries.channel.deleteChannel(db, id, ws.workspaceId);-- return writeJSON({ ok: true });-});diff --git a/src/web/src/app/api/channels/reorder/route.test.ts b/src/web/src/app/api/channels/reorder/route.test.tsdeleted file mode 100644index 59d3f13d0..000000000--- a/src/web/src/app/api/channels/reorder/route.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockListChannels = vi.fn();-const mockReorderChannels = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- channel: {- listChannels: (...a: unknown[]) => mockListChannels(...a),- reorderChannels: (...a: unknown[]) => mockReorderChannels(...a),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { PUT } from "./route";--beforeEach(() => vi.clearAllMocks());--const put = (body: unknown) =>- PUT(new NextRequest("http://localhost/x", { method: "PUT", body: JSON.stringify(body) }), {});--describe("PUT /api/channels/reorder", () => {- it("reorders existing workspace channels (204)", async () => {- mockListChannels.mockResolvedValue([{ id: "ch1" }, { id: "ch2" }]);- const res = await put({ ordered_channel_ids: ["ch2", "ch1"] });- expect(res.status).toBe(204);- expect(mockReorderChannels).toHaveBeenCalledWith({}, "w1", ["ch2", "ch1"]);- });-- it("400 when trying to reorder the default channel", async () => {- const res = await put({ ordered_channel_ids: ["ch_default", "ch1"] });- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("default channel");- });-- it("400 when a channel id does not exist in the workspace", async () => {- mockListChannels.mockResolvedValue([{ id: "ch1" }]);- const res = await put({ ordered_channel_ids: ["ch1", "ghost"] });- expect(res.status).toBe(400);- expect((await res.json()).error).toContain("not found");- });-- it("400 on invalid body", async () => {- const res = await put({ ordered_channel_ids: "nope" });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/channels/reorder/route.ts b/src/web/src/app/api/channels/reorder/route.tsdeleted file mode 100644index f64e62a67..000000000--- a/src/web/src/app/api/channels/reorder/route.ts+++ /dev/null@@ -1,38 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const PUT = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let raw: { ordered_channel_ids?: unknown };- try {- raw = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const ids = raw.ordered_channel_ids;- if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === "string" && id.length > 0)) {- return writeError("ordered_channel_ids must be a non-empty array of strings", 400);- }-- if (ids.includes("ch_default")) {- return writeError("cannot reorder the default channel", 400);- }-- const db = getDb(ctx.env.DB);-- const existing = await queries.channel.listChannels(db, ws.workspaceId);- const existingIds = new Set(existing.map((c) => c.id));- for (const id of ids) {- if (!existingIds.has(id)) return writeError(`Channel ${id} not found`, 400);- }-- await queries.channel.reorderChannels(db, ws.workspaceId, ids);- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/channels/route.test.ts b/src/web/src/app/api/channels/route.test.tsdeleted file mode 100644index a7358eda0..000000000--- a/src/web/src/app/api/channels/route.test.ts+++ /dev/null@@ -1,246 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListChannels = vi.fn();-const mockCreateChannel = vi.fn();-const mockChannelToResponse = vi.fn((c: any) => ({- id: c.id,- workspace_id: c.workspaceId,- name: c.name,- position: c.position ?? 0,- created_at: c.createdAt,-}));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- channel: {- listChannels: (...args: any[]) => mockListChannels(...args),- createChannel: (...args: any[]) => mockCreateChannel(...args),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- channelToResponse: (...args: any[]) => mockChannelToResponse(...args),-}));--import { GET, POST } from "./route";--describe("GET /api/channels", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists channels", async () => {- const channels = [- { id: "ch_1", workspaceId: "w1", name: "default", createdAt: "2024-01-01T00:00:00Z" },- { id: "ch_2", workspaceId: "w1", name: "work", createdAt: "2024-01-02T00:00:00Z" },- ];- mockListChannels.mockResolvedValue(channels);-- const res = await GET(new NextRequest("http://localhost/api/channels"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(body[0].name).toBe("default");- expect(body[1].name).toBe("work");- expect(mockListChannels).toHaveBeenCalledWith({}, "w1");- });-- it("synthesizes virtual default channel when none exists", async () => {- const channels = [- { id: "ch_2", workspaceId: "w1", name: "work", createdAt: "2024-01-02T00:00:00Z" },- ];- mockListChannels.mockResolvedValue(channels);-- const res = await GET(new NextRequest("http://localhost/api/channels"));- const body = await res.json();-- expect(res.status).toBe(200);- 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");- });-- it("does not synthesize default when it already exists", async () => {- const channels = [- { id: "ch_1", workspaceId: "w1", name: "default", createdAt: "2024-01-01T00:00:00Z" },- ];- mockListChannels.mockResolvedValue(channels);-- const res = await GET(new NextRequest("http://localhost/api/channels"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].id).toBe("ch_1");- });-- it("returns empty list with only virtual default when DB has no channels", async () => {- mockListChannels.mockResolvedValue([]);-- const res = await GET(new NextRequest("http://localhost/api/channels"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].name).toBe("default");- expect(body[0].id).toBe("ch_default");- });-});--describe("POST /api/channels", () => {- beforeEach(() => vi.clearAllMocks());-- it("creates a channel", async () => {- const created = { id: "ch_3", workspaceId: "w1", name: "personal", createdAt: "2024-01-03T00:00:00Z" };- mockCreateChannel.mockResolvedValue(created);-- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "personal" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(201);- expect(body.name).toBe("personal");- expect(mockCreateChannel).toHaveBeenCalledWith({}, { workspaceId: "w1", name: "personal" });- });-- it("returns 400 for missing name", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("name is required");- });-- it("returns 400 for empty name", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: " " }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("name is required");- });-- it("returns 400 for name exceeding 32 characters", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "a".repeat(33) }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("name must be 32 characters or less");- });-- it("returns 400 for reserved name 'default'", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "default" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("cannot create a channel named 'default'");- });-- it("returns 400 for name with invalid characters", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "my channel" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("name can only contain letters, digits, dashes, and underscores");- });-- it("returns 400 for invalid JSON body", async () => {- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: "not json",- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });-- it("returns 409 for duplicate channel name", async () => {- mockCreateChannel.mockRejectedValue(new Error("UNIQUE constraint failed: channel.name"));-- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "work" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(409);- expect(body.error).toBe("a channel with this name already exists");- });-- it("accepts valid names with dashes and underscores", async () => {- const created = { id: "ch_4", workspaceId: "w1", name: "my-channel_1", createdAt: "2024-01-04T00:00:00Z" };- mockCreateChannel.mockResolvedValue(created);-- const res = await POST(- new NextRequest("http://localhost/api/channels", {- method: "POST",- body: JSON.stringify({ name: "my-channel_1" }),- headers: { "Content-Type": "application/json" },- })- );-- expect(res.status).toBe(201);- });-});diff --git a/src/web/src/app/api/channels/route.ts b/src/web/src/app/api/channels/route.tsdeleted file mode 100644index a80f904a2..000000000--- a/src/web/src/app/api/channels/route.ts+++ /dev/null@@ -1,76 +0,0 @@-import { NextRequest } from "next/server";-import { queries, isUniqueConstraintError } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { channelToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const channels = await queries.channel.listChannels(db, ws.workspaceId);-- const hasDefault = channels.some((c) => c.name === "default");- const result = hasDefault- ? channels- : [- {- id: "ch_default",- workspaceId: ws.workspaceId,- name: "default",- position: 0,- createdAt: new Date().toISOString(),- },- ...channels,- ];-- return writeJSON(result.map(channelToResponse));-});--const CHANNEL_NAME_RE = /^[a-zA-Z0-9_-]+$/;--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- let body: { name?: string };- try {- body = await req.json();- } catch {- return writeError("invalid request body", 400);- }-- const name = typeof body.name === "string" ? body.name.trim() : "";-- if (!name) {- return writeError("name is required", 400);- }- if (name.length > 32) {- return writeError("name must be 32 characters or less", 400);- }- if (name === "default") {- return writeError("cannot create a channel named 'default'", 400);- }- if (!CHANNEL_NAME_RE.test(name)) {- return writeError("name can only contain letters, digits, dashes, and underscores", 400);- }-- try {- const created = await queries.channel.createChannel(db, {- workspaceId: ws.workspaceId,- name,- });- return writeJSON(channelToResponse(created), 201);- } catch (err) {- if (isUniqueConstraintError(err)) {- return writeError("a channel with this name already exists", 409);- }- throw err;- }-});diff --git a/src/web/src/app/api/cli/latest-version/route.test.ts b/src/web/src/app/api/cli/latest-version/route.test.tsdeleted file mode 100644index 4491aa0a5..000000000--- a/src/web/src/app/api/cli/latest-version/route.test.ts+++ /dev/null@@ -1,57 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--const mockFetch = vi.fn();-vi.stubGlobal("fetch", mockFetch);--import { GET } from "./route";--describe("GET /api/cli/latest-version", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns version and package from npm registry", async () => {- mockFetch.mockResolvedValue({- ok: true,- json: async () => ({ version: "2.0.0" }),- });-- const res = await GET();- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.version).toBe("2.0.0");- expect(body.package).toBe("@alook/cli");- });-- it("returns 502 when npm registry returns non-ok", async () => {- mockFetch.mockResolvedValue({ ok: false, status: 500 });-- const res = await GET();- const body = await res.json();-- expect(res.status).toBe(502);- expect(body.error).toContain("failed to fetch");- });-- it("returns 502 when fetch throws", async () => {- mockFetch.mockRejectedValue(new Error("network error"));-- const res = await GET();- const body = await res.json();-- expect(res.status).toBe(502);- expect(body.error).toContain("failed to fetch");- });-- it("returns 502 when response has no version field", async () => {- mockFetch.mockResolvedValue({- ok: true,- json: async () => ({ name: "@alook/cli" }),- });-- const res = await GET();- const body = await res.json();-- expect(res.status).toBe(502);- expect(body.error).toContain("version");- });-});diff --git a/src/web/src/app/api/cli/latest-version/route.ts b/src/web/src/app/api/cli/latest-version/route.tsdeleted file mode 100644index a3f7b47e8..000000000--- a/src/web/src/app/api/cli/latest-version/route.ts+++ /dev/null@@ -1,10 +0,0 @@-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { fetchLatestCliVersion } from "@/lib/npm";--export async function GET() {- const result = await fetchLatestCliVersion();- if (!result) {- return writeError("failed to fetch latest version from npm", 502);- }- return writeJSON({ version: result.version, package: result.package });-}diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.tsdeleted file mode 100644index 15623cb25..000000000--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.test.ts+++ /dev/null@@ -1,112 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"--const mockGetBotOwnedBy = vi.fn()-const mockGetApprovalRequest = vi.fn()-const mockGetMember = vi.fn()-const mockAddMember = vi.fn()-const mockResolveApprovalRequest = vi.fn()-const mockFanOut = vi.fn()--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityBot: {- getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),- getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),- resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),- },- communityMember: {- getMember: (...a: unknown[]) => mockGetMember(...a),- addMember: (...a: unknown[]) => mockAddMember(...a),- },- },- }-})---vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => mockFanOut(...a),- broadcastToUserSafe: vi.fn(),-}))--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(_req, { env: { DB: {} }, userId: "u_owner", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { POST } from "./route"--const ctx = { params: { id: "bot_1", requestId: "req_1" } } as any--describe("POST /api/community/bots/[id]/approval-requests/[requestId]/approve", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetBotOwnedBy.mockResolvedValue({- id: "bot_1",- name: "Zoe",- image: null,- })- mockGetApprovalRequest.mockResolvedValue({- id: "req_1",- botId: "bot_1",- status: "pending",- kind: "join_server",- serverId: "srv_1",- requestedByUserId: "u_friend",- })- mockGetMember.mockResolvedValue(null)- mockAddMember.mockResolvedValue({- id: "mem_bot",- role: "member",- joinedAt: "2026-07-08T00:00:00.000Z",- })- mockResolveApprovalRequest.mockResolvedValue(undefined)- mockFanOut.mockResolvedValue(undefined)- })-- it("returns 404 when the bot is not owned by the caller", async () => {- mockGetBotOwnedBy.mockResolvedValue(null)- const res = await POST({} as any, ctx)- expect(res.status).toBe(404)- })-- it("returns 400 when the request is already resolved", async () => {- mockGetApprovalRequest.mockResolvedValue({- id: "req_1",- botId: "bot_1",- status: "approved",- kind: "join_server",- serverId: "srv_1",- requestedByUserId: "u_friend",- })- const res = await POST({} as any, ctx)- expect(res.status).toBe(400)- })-- it("approves a join_server request and fans out MEMBER_JOIN", async () => {- const res = await POST({} as any, ctx)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ status: "approved", kind: "join_server" })- expect(mockAddMember).toHaveBeenCalled()- expect(mockFanOut).toHaveBeenCalledWith(- "srv_1",- expect.objectContaining({ type: "community:member.join" }),- )- })-})diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.tsdeleted file mode 100644index 59422d28c..000000000--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/approve/route.ts+++ /dev/null@@ -1,64 +0,0 @@-import { queries, ROLES, WS_EVENTS } from "@alook/shared"-import type { CommunityMemberJoin } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { fanOutToServerMembers } from "@/lib/community/fanout"-import { canonicalUserImage } from "@/lib/community/storage"--/**- * Approve a pending bot approval request. After migration 0065 only the- * "join_server" kind survives (friend requests moved to community_friendship /- * the owner-decision route). A row of any other kind 404s — such rows were- * removed by the migration; this is a defensive path.- */-export const POST = withAuth(async (_req, ctx) => {- const botId = ctx.params?.id as string- const requestId = ctx.params?.requestId as string- const db = getDb(ctx.env.DB)-- const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)- if (!bot) return writeError("bot not found", 404)-- const request = await queries.communityBot.getApprovalRequest(db, requestId)- if (!request || request.botId !== botId) {- return writeError("approval request not found", 404)- }- if (request.kind !== "join_server") {- return writeError("approval request not found", 404)- }- if (request.status !== "pending") {- return writeError("request already resolved", 400)- }-- if (!request.serverId) return writeError("malformed request", 400)- const alreadyMember = await queries.communityMember.getMember(- db,- request.serverId,- botId,- )- if (!alreadyMember) {- const added = await queries.communityMember.addMember(db, {- serverId: request.serverId,- userId: botId,- role: ROLES.MEMBER,- })- const joinEvent: CommunityMemberJoin = {- type: WS_EVENTS.MEMBER_JOIN,- serverId: request.serverId,- member: {- id: added.id,- userId: botId,- name: bot.name,- discriminator: bot.discriminator,- avatar: canonicalUserImage(bot.id, bot.image, bot.avatarVersion) ?? undefined,- avatarVersion: bot.avatarVersion,- role: added.role ?? ROLES.MEMBER,- joinedAt: added.joinedAt,- },- }- fanOutToServerMembers(request.serverId, joinEvent)- }- await queries.communityBot.resolveApprovalRequest(db, requestId, "approved")- return writeJSON({ status: "approved", kind: "join_server" })-})diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.tsdeleted file mode 100644index 1cbc825a9..000000000--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.test.ts+++ /dev/null@@ -1,72 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"--const mockGetBotOwnedBy = vi.fn()-const mockGetApprovalRequest = vi.fn()-const mockResolveApprovalRequest = vi.fn()--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@alook/shared", () => ({- queries: {- communityBot: {- getBotOwnedBy: (...a: unknown[]) => mockGetBotOwnedBy(...a),- getApprovalRequest: (...a: unknown[]) => mockGetApprovalRequest(...a),- resolveApprovalRequest: (...a: unknown[]) => mockResolveApprovalRequest(...a),- },- },-}))---vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (_req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(_req, { env: { DB: {} }, userId: "u_owner", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { POST } from "./route"--const ctx = { params: { id: "bot_1", requestId: "req_1" } } as any--describe("POST /api/community/bots/[id]/approval-requests/[requestId]/deny", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetBotOwnedBy.mockResolvedValue({ id: "bot_1", name: "Zoe", image: null })- mockGetApprovalRequest.mockResolvedValue({- id: "req_1",- botId: "bot_1",- status: "pending",- kind: "join_server",- serverId: "srv_1",- requestedByUserId: "u_friend",- })- mockResolveApprovalRequest.mockResolvedValue(undefined)- })-- it("returns 404 when the bot is not owned by the caller", async () => {- mockGetBotOwnedBy.mockResolvedValue(null)- const res = await POST({} as any, ctx)- expect(res.status).toBe(404)- })-- it("denies a pending request", async () => {- const res = await POST({} as any, ctx)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ status: "denied", kind: "join_server" })- expect(mockResolveApprovalRequest).toHaveBeenCalledWith(- expect.anything(),- "req_1",- "denied",- )- })-})diff --git a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts b/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.tsdeleted file mode 100644index 5a01d37c7..000000000--- a/src/web/src/app/api/community/bots/[id]/approval-requests/[requestId]/deny/route.ts+++ /dev/null@@ -1,36 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--/**- * Deny a pending bot approval request. No side effects beyond flipping the- * row to `denied`. The requester is NOT notified —- * they must observe the outcome indirectly (their earlier "Request sent"- * remains, but no accept event ever arrives).- */-export const POST = withAuth(async (_req, ctx) => {- const botId = ctx.params?.id as string- const requestId = ctx.params?.requestId as string- const db = getDb(ctx.env.DB)-- const bot = await queries.communityBot.getBotOwnedBy(db, botId, ctx.userId)- if (!bot) return writeError("bot not found", 404)-- const request = await queries.communityBot.getApprovalRequest(db, requestId)- if (!request || request.botId !== botId) {- return writeError("approval request not found", 404)- }- // Only join_server rows survive migration 0065; anything else 404s defensively.- if (request.kind !== "join_server") {- return writeError("approval request not found", 404)- }- if (request.status !== "pending") {- return writeError("request already resolved", 400)- }-- await queries.communityBot.resolveApprovalRequest(db, requestId, "denied")--- return writeJSON({ status: "denied", kind: request.kind })-})diff --git a/src/web/src/app/api/community/bots/[id]/route.test.ts b/src/web/src/app/api/community/bots/[id]/route.test.tsindex 483fb18e8..a8e6bd6e2 100644--- a/src/web/src/app/api/community/bots/[id]/route.test.ts+++ b/src/web/src/app/api/community/bots/[id]/route.test.ts@@ -102,7 +102,7 @@ vi.mock("@/lib/middleware/helpers", async () => {}})-import { DELETE, GET, PATCH } from "./route"+import { DELETE, PATCH } from "./route"function patchReq(body: unknown) {return new NextRequest("http://localhost/api/community/bots/b1", {@@ -112,38 +112,6 @@ function patchReq(body: unknown) {}const ctx = { params: { id: "b1" } } as any-describe("GET /api/community/bots/[id]", () => {- it("returns the owned bot with a canonical versioned avatar", async () => {- mockGetBotOwnedBy.mockResolvedValue({- id: "b1",- name: "Bot",- discriminator: "0042",- image: "/api/community/bots/b1/avatar",- avatarVersion: 4,- description: "helper",- machineId: "mac1",- runtime: "codex",- modelName: null,- reasoningEffort: null,- runtimeConfigRevision: 2,- })-- const res = await GET(- new NextRequest("http://localhost/api/community/bots/b1"),- ctx,- )-- expect(res.status).toBe(200)- expect(await res.json()).toMatchObject({- bot: {- id: "b1",- image: "/api/community/bots/b1/avatar?v=4",- avatarVersion: 4,- },- })- })-})-describe("PATCH /api/community/bots/[id]", () => {beforeEach(() => {vi.clearAllMocks()diff --git a/src/web/src/app/api/community/bots/[id]/route.ts b/src/web/src/app/api/community/bots/[id]/route.tsindex b9a40e2fd..54fff8b67 100644--- a/src/web/src/app/api/community/bots/[id]/route.ts+++ b/src/web/src/app/api/community/bots/[id]/route.ts@@ -32,32 +32,6 @@ import { scheduleCommunityMediaCleanup } from "@/lib/community/community-media-cconst log = createLogger({ service: "community-bot-update" })-export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)- const id = ctx.params?.id as string- const bot = await queries.communityBot.getBotOwnedBy(db, id, ctx.userId)- if (!bot) return writeError("bot not found", 404)- return writeJSON({- bot: {- id: bot.id,- name: bot.name,- discriminator: bot.discriminator,- image: canonicalUserImage(bot.id, bot.image, bot.avatarVersion),- avatarVersion: bot.avatarVersion,- ownerUserId: bot.ownerUserId,- description: bot.description,- createdAt: bot.createdAt,- updatedAt: bot.updatedAt,- lastRefreshContextAt: bot.lastRefreshContextAt,- machineId: bot.machineId,- runtime: bot.runtime,- modelName: bot.modelName,- reasoningEffort: bot.reasoningEffort,- runtimeConfigRevision: bot.runtimeConfigRevision,- },- })-})-export const PATCH = withAuth(async (req: NextRequest, ctx) => {const id = ctx.params?.id as stringconst [body, err] = await parseBody(req, CommunityBotPatchRequestSchema)diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.tsindex 9ddc7792f..bcf8aafd2 100644--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.test.ts@@ -6,18 +6,22 @@ vi.mock("@opennextjs/cloudflare", () => ({}));const mockGetChannel = vi.fn();+const mockGetChannelForMember = vi.fn();const mockGetMember = vi.fn();const mockUnpinMessage = vi.fn();const mockFanOut = vi.fn();-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }));vi.mock("@alook/shared", async () => {const actual = await vi.importActual("@alook/shared");return {...actual,queries: {- communityChannel: { getChannel: (...a: unknown[]) => mockGetChannel(...a) },+ communityChannel: {+ getChannel: (...a: unknown[]) => mockGetChannel(...a),+ getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),+ },communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },communityPin: { unpinMessage: (...a: unknown[]) => mockUnpinMessage(...a) },},@@ -56,6 +60,7 @@ describe("DELETE /api/community/channels/[id]/pins/[messageId]", () => {beforeEach(() => {vi.clearAllMocks();mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });mockGetMember.mockResolvedValue({ userId: "u1", role: "admin" });mockUnpinMessage.mockResolvedValue(undefined);mockFanOut.mockResolvedValue(undefined);@@ -95,4 +100,20 @@ describe("DELETE /api/community/channels/[id]/pins/[messageId]", () => {expect(res.status).toBe(403);expect(mockUnpinMessage).not.toHaveBeenCalled();});++ it("rejects inaccessible channels before admin checks, writes or fanout", async () => {+ mockGetChannelForMember.mockResolvedValue(null);+ const res = await DELETE(delReq(), ctx);+ expect(res.status).toBe(403);+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "c1", "u1");+ expect(mockGetMember).not.toHaveBeenCalled();+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ expect(mockFanOut).not.toHaveBeenCalled();+ });++ it("retains missing path parameter errors without writes or fanout", async () => {+ expect((await DELETE(delReq(), { params: { id: "c1" } })).status).toBe(400);+ expect(mockUnpinMessage).not.toHaveBeenCalled();+ expect(mockFanOut).not.toHaveBeenCalled();+ });});diff --git a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.tsindex d82aa1f4a..f4997d2eb 100644--- a/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/[messageId]/route.ts@@ -1,10 +1,10 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"+import { getPrimaryDb } from "@/lib/db"import { queries, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"-import { requireServerAdmin } from "@/lib/community/permissions"+import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"import { requirePinnableSurface } from "@/lib/community/channel-write-guard"export const DELETE = withAuth(async (_req: NextRequest, ctx) => {@@ -12,7 +12,7 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const messageId = ctx.params?.messageIdif (!channelId || !messageId) return writeError("missing params", 400)- const db = getDb(ctx.env.DB)+ const db = getPrimaryDb(ctx.env.DB)const channel = await queries.communityChannel.getChannel(db, channelId)if (!channel) return writeError("channel not found", 404)@@ -20,6 +20,9 @@ export const DELETE = withAuth(async (_req: NextRequest, ctx) => {const pinnable = requirePinnableSurface(channel.type)if (!pinnable.ok) return writeError(pinnable.error, pinnable.status)+ const access = await requireChannelMember(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+// Unpinning is a moderation action — require admin / owner.const auth = await requireServerAdmin(db, channel.serverId, ctx.userId)if (!auth.ok) return writeError(auth.error, auth.status)diff --git a/src/web/src/app/api/community/channels/[id]/pins/access.test.ts b/src/web/src/app/api/community/channels/[id]/pins/access.test.tsnew file mode 100644index 000000000..613eea5d5--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/pins/access.test.ts@@ -0,0 +1,243 @@+import { DatabaseSync, type SQLInputValue } from "node:sqlite"+import { createRequire } from "node:module"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { NextRequest } from "next/server"+import { WS_EVENTS } from "@alook/shared"+import { user } from "../../../../../../../../shared/src/db/schema"+import {+ communityCategory,+ communityChannel,+ communityChannelMember,+ communityMessage,+ communityPin,+ communityServerMember,+} from "../../../../../../../../shared/src/db/community-schema"+import type { AuthenticatedHandler } from "@/lib/middleware/auth"++const { getTableConfig } = createRequire(import.meta.resolve("@alook/shared"))("drizzle-orm/sqlite-core") as {+ getTableConfig: (table: object) => { name: string; columns: Array<{ name: string; getSQLType: () => string }> }+}++const { state, fanOut } = vi.hoisted(() => ({+ state: { binding: null as unknown as D1Database, userId: "admin" },+ fanOut: vi.fn(),+}))++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: (handler: AuthenticatedHandler) => async (+ request: NextRequest,+ context?: { params?: Record<string, string> | Promise<Record<string, string>> },+ ) => handler(request, {+ userId: state.userId,+ email: "[email protected]",+ env: { DB: state.binding } as Env,+ params: await context?.params,+ }),+}))+vi.mock("@/lib/community/fanout", () => ({ fanOutToChannel: fanOut }))++import { GET, POST } from "./route"+import { DELETE } from "./[messageId]/route"++let primary: DatabaseSync+let replica: DatabaseSync+let sessions: string[]++function seedDatabase() {+ const sqlite = new DatabaseSync(":memory:")+ for (const table of [user, communityChannel, communityChannelMember, communityMessage, communityServerMember, communityCategory, communityPin]) {+ const config = getTableConfig(table)+ sqlite.exec(`CREATE TABLE "${config.name}" (${config.columns.map((column) => `"${column.name}" ${column.getSQLType()}`).join(", ")})`)+ }+ sqlite.exec(`+ INSERT INTO user (id,name,discriminator,"avatarVersion","isBot") VALUES+ ('admin','Administrator','0001',0,0),('creator','Creator','0002',0,0),('member','Member','0003',0,0);+ INSERT INTO community_server_member (id,server_id,user_id,role) VALUES+ ('admin-row','server','admin','admin'),('creator-row','server','creator','member'),('member-row','server','member','member');+ INSERT INTO community_category (id,server_id,private) VALUES ('private-category','server',1),('public-category','server',0);+ INSERT INTO community_channel (id,server_id,category_id,type,creator_id,parent_channel_id) VALUES+ ('private','server','private-category','text','creator',NULL),+ ('public','server','public-category','text','creator',NULL),+ ('private-thread','server',NULL,'thread','admin','private'),+ ('private-forum','server','private-category','forum','creator',NULL),+ ('private-post','server',NULL,'thread','admin','private-forum');+ INSERT INTO community_message (id,author_id,content,channel_id,seq,created_at) VALUES+ ('private-message','creator','Private example','private',1,'2026-10-19T00:00:00Z'),+ ('public-message','creator','Public example','public',1,'2026-10-19T00:00:00Z'),+ ('private-thread-message','creator','Thread example','private-thread',1,'2026-10-19T00:00:00Z'),+ ('private-forum-message','creator','Forum example','private-forum',1,'2026-10-19T00:00:00Z'),+ ('private-post-message','creator','Post example','private-post',1,'2026-10-19T00:00:00Z');+ INSERT INTO community_message (id,author_id,content,channel_id,seq,created_at)+ SELECT id || '-unpinned',author_id,content,channel_id,2,created_at FROM community_message;+ CREATE UNIQUE INDEX uq_pin_channel_message ON community_pin(channel_id,message_id);+ INSERT INTO community_pin (channel_id,message_id,pinned_by,created_at) VALUES+ ('private','private-message','creator','2026-10-19T00:00:00Z'),+ ('public','public-message','admin','2026-10-19T00:00:00Z');+ `)+ return sqlite+}++function session(view: DatabaseSync) {+ let current = view+ return {+ prepare(sql: string) {+ let values: SQLInputValue[] = []+ const statement = () => {+ if (!/^\s*select\b/i.test(sql)) current = primary+ return current.prepare(sql)+ }+ const query = {+ bind(...params: SQLInputValue[]) { values = params; return query },+ async raw() {+ const prepared = statement()+ prepared.setReturnArrays(true)+ return prepared.all(...values)+ },+ async all() { return { results: statement().all(...values), success: true } },+ async run() { return { meta: statement().run(...values), success: true } },+ }+ return query+ },+ }+}++function context(channelId: string, messageId = `${channelId}-message`) {+ return { params: { id: channelId, messageId } }+}+function request(channelId: string, method: "GET" | "POST" | "DELETE", messageId = `${channelId}-message`) {+ return new NextRequest(`http://localhost/api/community/channels/${channelId}/pins${method === "DELETE" ? `/${messageId}` : ""}`, {+ method,+ ...(method === "POST" ? { body: JSON.stringify({ messageId }), headers: { "Content-Type": "application/json" } } : {}),+ })+}+function pins() {+ return primary.prepare("SELECT channel_id,message_id,pinned_by FROM community_pin ORDER BY channel_id,message_id").all()+}+function onBoth(sql: string) { primary.exec(sql); replica.exec(sql) }++async function expectDenied(channelId: string, status = 403) {+ const before = pins()+ const freshMessageId = `${channelId}-message-unpinned`+ expect((await POST(request(channelId, "POST", freshMessageId), context(channelId))).status).toBe(status)+ expect(pins()).toEqual(before)+ expect((await DELETE(request(channelId, "DELETE"), context(channelId))).status).toBe(status)+ expect(pins()).toEqual(before)+ expect(fanOut).not.toHaveBeenCalled()+}++beforeEach(() => {+ primary = seedDatabase()+ replica = seedDatabase()+ sessions = []+ state.userId = "admin"+ state.binding = {+ withSession(constraint: string) {+ sessions.push(constraint)+ return session(constraint === "first-primary" ? primary : replica)+ },+ } as unknown as D1Database+ fanOut.mockReset().mockResolvedValue(undefined)+})+afterEach(() => { primary.close(); replica.close() })++describe("pin writes with real channel authorization and SQLite queries", () => {+ it.each([+ ["admin", "POST"], ["admin", "DELETE"], ["owner", "POST"], ["owner", "DELETE"],+ ] as const)("denies a private-channel outsider with server role %s for %s without mutation or pin events", async (role, method) => {+ onBoth(`UPDATE community_server_member SET role='${role}' WHERE user_id='admin'`)+ expect((await GET(request("private", "GET"), context("private"))).status).toBe(403)+ const before = pins()+ const messageId = method === "POST" ? "private-message-unpinned" : "private-message"+ const response = method === "POST"+ ? await POST(request("private", method, messageId), context("private"))+ : await DELETE(request("private", method, messageId), context("private"))+ expect(response.status).toBe(403)+ expect(pins()).toEqual(before)+ expect(fanOut).not.toHaveBeenCalled()+ })++ it.each(["private-thread", "private-forum", "private-post"])("denies inaccessible inherited/private surface %s", async (channelId) => {+ await expectDenied(channelId)+ })++ it("does not treat a notify-only row as private content access", async () => {+ onBoth("INSERT INTO community_channel_member (id,channel_id,user_id,relation) VALUES ('notify','private','admin','notify')")+ await expectDenied("private")+ })++ it.each([+ ["public", "admin", null],+ ["private", "admin", "private"],+ ["private", "owner", "private"],+ ["private-thread", "admin", "private"],+ ["private-forum", "admin", "private-forum"],+ ["private-post", "admin", "private-forum"],+ ["private", "creator-admin", null],+ ] as const)("pins/unpins accessible %s as %s with exact row and event scope", async (channelId, role, anchorId) => {+ if (anchorId) onBoth(`INSERT INTO community_channel_member (id,channel_id,user_id,relation) VALUES ('access','${anchorId}','admin','access')`)+ if (role === "creator-admin") onBoth("UPDATE community_channel SET creator_id='admin' WHERE id='private'")+ else onBoth(`UPDATE community_server_member SET role='${role}' WHERE user_id='admin'`)+ onBoth(`DELETE FROM community_pin WHERE channel_id='${channelId}'`)+ const before = pins()+ const messageId = `${channelId}-message`+ const pinned = await POST(request(channelId, "POST"), context(channelId))+ expect(pinned.status).toBe(201)+ expect(pins()).toEqual(expect.arrayContaining([...before, { channel_id: channelId, message_id: messageId, pinned_by: "admin" }]))+ expect(pins()).toHaveLength(before.length + 1)+ expect(fanOut).toHaveBeenNthCalledWith(1, channelId, { type: WS_EVENTS.PIN_ADD, channelId, messageId })+ expect((await DELETE(request(channelId, "DELETE"), context(channelId))).status).toBe(204)+ expect(pins()).toEqual(before)+ expect(fanOut).toHaveBeenNthCalledWith(2, channelId, { type: WS_EVENTS.PIN_REMOVE, channelId, messageId })+ expect(fanOut).toHaveBeenCalledTimes(2)+ expect(sessions).toEqual(["first-primary", "first-primary"])+ })++ it.each([+ ["public", "member"],+ ["private", "member"],+ ["private", "creator"],+ ] as const)("does not grant %s moderation to ordinary member/private creator %s", async (channelId, userId) => {+ state.userId = userId+ if (userId === "member") onBoth("INSERT INTO community_channel_member (id,channel_id,user_id,relation) VALUES ('member-access','private','member','access')")+ await expectDenied(channelId)+ })++ it("denies writes after server membership is removed even with a private access row", async () => {+ onBoth("DELETE FROM community_server_member WHERE user_id='admin'; INSERT INTO community_channel_member (id,channel_id,user_id,relation) VALUES ('orphan-access','private','admin','access')")+ await expectDenied("private")+ await expectDenied("public")+ })++ it("reads committed removal from primary even while a replica still has private membership", async () => {+ onBoth("INSERT INTO community_channel_member (id,channel_id,user_id,relation) VALUES ('access','private','admin','access')")+ expect((await GET(request("private", "GET"), context("private"))).status).toBe(200)+ primary.exec("DELETE FROM community_channel_member WHERE channel_id='private' AND user_id='admin'")+ expect(replica.prepare("SELECT count(*) AS count FROM community_channel_member WHERE user_id='admin'").get()).toEqual({ count: 1 })+ sessions.length = 0+ await expectDenied("private")+ expect(sessions).toEqual(["first-primary", "first-primary"])+ })++ it("keeps cross-channel pin POST rejected and wrong-channel unpin scoped/idempotent", async () => {+ const before = pins()+ const ctx = context("public", "private-message")+ expect((await POST(request("public", "POST", "private-message"), ctx)).status).toBe(404)+ expect(fanOut).not.toHaveBeenCalled()+ expect((await DELETE(request("public", "DELETE", "private-message"), ctx)).status).toBe(204)+ expect(pins()).toEqual(before)+ expect(fanOut).toHaveBeenCalledExactlyOnceWith("public", { type: WS_EVENTS.PIN_REMOVE, channelId: "public", messageId: "private-message" })+ })++ it("retains duplicate-pin409 against the real unique constraint", async () => {+ const before = pins()+ expect((await POST(request("public", "POST"), context("public"))).status).toBe(409)+ expect(pins()).toEqual(before)+ expect(fanOut).not.toHaveBeenCalled()+ })++ it("preserves missing-channel rejection", async () => { await expectDenied("missing", 404) })+ it.each(["dm", "unsupported"])("preserves unsupported %s surface rejection", async (type) => {+ onBoth(`UPDATE community_channel SET type='${type}' WHERE id='public'`)+ await expectDenied("public", 400)+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts b/src/web/src/app/api/community/channels/[id]/pins/route.test.tsindex ec34ff54e..4ee2eaa70 100644--- a/src/web/src/app/api/community/channels/[id]/pins/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/route.test.ts@@ -13,7 +13,7 @@ const mockPinMessage = vi.fn();const mockListPins = vi.fn();const mockFanOut = vi.fn();-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})), getPrimaryDb: vi.fn(() => ({})) }));// Keep the real isUniqueConstraintError; only stub the query functions.vi.mock("@alook/shared", async () => {@@ -76,6 +76,7 @@ describe("POST /api/community/channels/[id]/pins", () => {beforeEach(() => {vi.clearAllMocks();mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });+ mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1", type: "text" });// Pinning is admin-only — every happy path starts with an admin caller.mockGetMember.mockResolvedValue({ userId: "u1", role: "admin" });mockGetMessage.mockResolvedValue({ id: "m1", channelId: "c1" });@@ -158,6 +159,25 @@ describe("POST /api/community/channels/[id]/pins", () => {expect(mockPinMessage).not.toHaveBeenCalled();});+ it("rejects inaccessible channels before admin checks, target reads, writes or fanout", async () => {+ mockGetChannelForMember.mockResolvedValue(null);+ const res = await POST(postReq("m1"), ctx);+ expect(res.status).toBe(403);+ expect(mockGetChannelForMember).toHaveBeenCalledWith(expect.anything(), "c1", "u1");+ expect(mockGetMember).not.toHaveBeenCalled();+ expect(mockGetMessage).not.toHaveBeenCalled();+ expect(mockPinMessage).not.toHaveBeenCalled();+ expect(mockFanOut).not.toHaveBeenCalled();+ });++ it("retains invalid JSON and missing channel parameter errors", async () => {+ const invalid = new NextRequest("http://localhost/api/community/channels/c1/pins", { method: "POST", body: "{" });+ expect((await POST(invalid, ctx)).status).toBe(400);+ expect((await POST(postReq("m1"), { params: {} })).status).toBe(400);+ expect(mockPinMessage).not.toHaveBeenCalled();+ expect(mockFanOut).not.toHaveBeenCalled();+ });+it("returns 404 when the message does not belong to the channel", async () => {mockGetMessage.mockResolvedValue({ id: "m1", channelId: "other" });const res = await POST(postReq("m1"), ctx);diff --git a/src/web/src/app/api/community/channels/[id]/pins/route.ts b/src/web/src/app/api/community/channels/[id]/pins/route.tsindex b8425b07c..56cb283e8 100644--- a/src/web/src/app/api/community/channels/[id]/pins/route.ts+++ b/src/web/src/app/api/community/channels/[id]/pins/route.ts@@ -1,7 +1,7 @@import { NextRequest } from "next/server"import { withAuth } from "@/lib/middleware/auth"import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"+import { getDb, getPrimaryDb } from "@/lib/db"import { queries, isUniqueConstraintError, WS_EVENTS } from "@alook/shared"import { fanOutToChannel } from "@/lib/community/fanout"import { requireChannelMember, requireServerAdmin } from "@/lib/community/permissions"@@ -45,7 +45,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)- const db = getDb(ctx.env.DB)+ const db = getPrimaryDb(ctx.env.DB)const channel = await queries.communityChannel.getChannel(db, channelId)if (!channel) return writeError("channel not found", 404)@@ -53,6 +53,9 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const pinnable = requirePinnableSurface(channel.type)if (!pinnable.ok) return writeError(pinnable.error, pinnable.status)+ const access = await requireChannelMember(db, channelId, ctx.userId)+ if (!access.ok) return writeError(access.error, access.status)+// Pinning is a moderation action — require server admin / owner.const adminCheck = await requireServerAdmin(db, channel.serverId, ctx.userId)if (!adminCheck.ok) return writeError(adminCheck.error, adminCheck.status)diff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.test.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.test.tsdeleted file mode 100644index e5057d207..000000000--- a/src/web/src/app/api/community/channels/[id]/read-state/route.test.ts+++ /dev/null@@ -1,118 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetChannel = vi.fn()-const mockGetChannelForMember = vi.fn()-const mockGetReadState = vi.fn()--vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),-}))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityChannel: {- getChannel: (...a: unknown[]) => mockGetChannel(...a),- getChannelForMember: (...a: unknown[]) => mockGetChannelForMember(...a),- },- communityReadState: {- getReadState: (...a: unknown[]) => mockGetReadState(...a),- },- },- }-})--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) =>- NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--function getReq() {- return new NextRequest(- "http://localhost/api/community/channels/c1/read-state",- { method: "GET" },- )-}--describe("GET /api/community/channels/[id]/read-state", () => {- beforeEach(() => {- vi.clearAllMocks()- })-- it("returns { null, null } when no read-state row exists (never-visited channel)", async () => {- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })- mockGetReadState.mockResolvedValue(null)-- const res = await GET(getReq(), { params: { id: "c1" } } as any)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 })- // Args to getReadState should scope by (userId, channelId).- expect(mockGetReadState).toHaveBeenCalledWith(expect.anything(), {- userId: "u1",- channelId: "c1",- })- })-- it("returns the actual (lastReadMessageId, lastReadAt, lastReadSeq) tuple when a row exists", async () => {- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })- mockGetChannelForMember.mockResolvedValue({ id: "c1", serverId: "s1" })- mockGetReadState.mockResolvedValue({- lastReadMessageId: "m_42",- lastReadAt: "2026-07-01T00:00:00.000Z",- lastReadSeq: 42,- })-- const res = await GET(getReq(), { params: { id: "c1" } } as any)- expect(res.status).toBe(200)- const body = await res.json()- expect(body).toEqual({- lastReadMessageId: "m_42",- lastReadAt: "2026-07-01T00:00:00.000Z",- lastReadSeq: 42,- })- })-- it("returns 400 when the channel id is missing", async () => {- const res = await GET(getReq(), { params: {} } as any)- expect(res.status).toBe(400)- expect(mockGetChannel).not.toHaveBeenCalled()- })-- it("returns 404 for an unknown channel", async () => {- mockGetChannel.mockResolvedValue(null)- const res = await GET(getReq(), { params: { id: "c1" } } as any)- expect(res.status).toBe(404)- expect(mockGetChannelForMember).not.toHaveBeenCalled()- expect(mockGetReadState).not.toHaveBeenCalled()- })-- it("returns 403 when the channel exists but the caller is not a member", async () => {- mockGetChannel.mockResolvedValue({ id: "c1", serverId: "s1" })- mockGetChannelForMember.mockResolvedValue(null)- const res = await GET(getReq(), { params: { id: "c1" } } as any)- expect(res.status).toBe(403)- expect(mockGetReadState).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/community/channels/[id]/read-state/route.ts b/src/web/src/app/api/community/channels/[id]/read-state/route.tsdeleted file mode 100644index 06cdf8251..000000000--- a/src/web/src/app/api/community/channels/[id]/read-state/route.ts+++ /dev/null@@ -1,56 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries, withD1Retry } from "@alook/shared"-import { requireMessageSurfaceAccess } from "@/lib/community/permissions"-import { writeCommunityReadState } from "@/lib/community/read-contract"--/**- * GET /api/community/channels/:id/read-state- *- * Snapshot of the viewer's read pointer for a single channel. Consumed once- * per channel mount to compute the "New" divider anchor and initial scroll- * position. Returns `{ null, null }` when the viewer has never visited the- * channel — the caller treats that as "everything is new, but no divider- * (start at the bottom)", matching common chat-app first-visit UX.- *- * Access via the unified id-in-path gate: 404 for unknown, 403 for non-members- * (the human split, preserved) — and, when the id is a DM, the DM block gate- * runs too. That block check is why this route moved off the bare- * `requireChannelMember`: a blocked-but-still-DM-member could otherwise read a- * DM's read-state through this channel route (the incidental P0 the trunk- * closes; the old path only ran the access-member check, never the block).- */-export const GET = withAuth(async (req: NextRequest, ctx) => {- const channelId = ctx.params?.id- if (!channelId) return writeError("missing channel id", 400)-- const db = getDb(ctx.env.DB)-- const auth = await requireMessageSurfaceAccess(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)-- // Wrap in `withD1Retry` on the server so the client can keep `retry: 1`- // (one retry stack, budget shared with the helper). On exhaust: rethrow —- // the client `useQuery` rejects, `snapshotRef` never latches a fabricated- // value, hook returns `{ snapshot: null, isFetching: false }`.- const row = await withD1Retry(- () => queries.communityReadState.getReadState(db, {- userId: ctx.userId,- channelId,- }),- { route: "community/channels/read-state" },- )-- return writeCommunityReadState(req, channelId, {- lastReadMessageId: row?.lastReadMessageId ?? null,- lastReadAt: row?.lastReadAt ?? null,- // Seq is the numeric equivalent of the (createdAt, id) pointer — used- // client-side to compute the `↓ N` unread count without walking the- // loaded rows (`latestSeq - lastReadSeq`). Falls back to 0 when the- // viewer has never visited: `latestSeq - 0` = all-messages-are-new,- // matching what the divider anchor implies.- lastReadSeq: row?.lastReadSeq ?? 0,- })-})diff --git a/src/web/src/app/api/community/channels/[id]/upload/route.test.ts b/src/web/src/app/api/community/channels/[id]/upload/route.test.tsdeleted file mode 100644index 2d2a641b1..000000000--- a/src/web/src/app/api/community/channels/[id]/upload/route.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--const mockRunAttachmentUpload = vi.fn()--vi.mock("@/lib/community/upload", () => ({- runAttachmentUpload: (...a: unknown[]) => mockRunAttachmentUpload(...a),-}))--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- },-}))--import { POST } from "./route"--function postReq() {- return new NextRequest("http://localhost/api/community/channels/c1/upload", {- method: "POST",- })-}--const ctx = { params: { id: "c1" } } as any--describe("POST /api/community/channels/[id]/upload — unified upload trunk entry", () => {- beforeEach(() => {- vi.clearAllMocks()- mockRunAttachmentUpload.mockResolvedValue(new Response(null, { status: 200 }))- })-- it("delegates to runAttachmentUpload with just (req, ctx) — surface + kind are derived inside", async () => {- // The route is a one-liner over the shared trunk. Since (A) collapsed the- // three upload routes to one surface-dispatching entry, the route no longer- // binds a (kind, permissionCheck) pair — it just forwards; runAttachmentUpload- // resolves access + derives kind from the dispatch. Lock that it forwards- // (req, ctx) and passes NO fixed kind/permission (a regression to the old- // 4-arg binding would show extra args here).- const req = postReq()- await POST(req, ctx)- expect(mockRunAttachmentUpload).toHaveBeenCalledOnce()- const args = mockRunAttachmentUpload.mock.calls[0]- expect(args[0]).toBe(req)- expect(args[1]).toMatchObject({ userId: "u1", params: { id: "c1" } })- expect(args).toHaveLength(2) // no fixed kind / permissionCheck- })-- it("returns whatever runAttachmentUpload returns unchanged", async () => {- const helperResponse = new Response(JSON.stringify({ ok: 1 }), { status: 201 })- mockRunAttachmentUpload.mockResolvedValueOnce(helperResponse)- const res = await POST(postReq(), ctx)- expect(res).toBe(helperResponse)- })-})diff --git a/src/web/src/app/api/community/channels/[id]/upload/route.ts b/src/web/src/app/api/community/channels/[id]/upload/route.tsdeleted file mode 100644index 1619459bf..000000000--- a/src/web/src/app/api/community/channels/[id]/upload/route.ts+++ /dev/null@@ -1,9 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { runAttachmentUpload } from "@/lib/community/upload"--// The unified attachment-upload trunk: one route, dispatched by surface inside-// runAttachmentUpload (communication surface access → kind derived from-// surface + channel.type). A DM id runs the block + accepted-friend gate; a-// child-thread id runs the child-surface gate — all surfaces use one door.-export const POST = withAuth((req: NextRequest, ctx) => runAttachmentUpload(req, ctx))diff --git a/src/web/src/app/api/community/messages/search/route.test.ts b/src/web/src/app/api/community/messages/search/route.test.tsdeleted file mode 100644index d966fd92a..000000000--- a/src/web/src/app/api/community/messages/search/route.test.ts+++ /dev/null@@ -1,157 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--const mockGetMember = vi.fn()-const mockListVisibleChannelIds = vi.fn()-const mockSearchMessagesInServer = vi.fn()-const mockSearchMessages = vi.fn()-const mockRequireServerMember = vi.fn()-const mockRequireChannelMember = vi.fn()-const mockRequireDMAccess = vi.fn()--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- communityMember: { getMember: (...a: unknown[]) => mockGetMember(...a) },- communityChannel: { listVisibleChannelIds: (...a: unknown[]) => mockListVisibleChannelIds(...a) },- communitySearch: {- searchMessagesInServer: (...a: unknown[]) => mockSearchMessagesInServer(...a),- searchMessages: (...a: unknown[]) => mockSearchMessages(...a),- },- },- }-})--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--vi.mock("@/lib/community/permissions", () => ({- requireServerMember: (...a: unknown[]) => mockRequireServerMember(...a),- requireChannelMember: (...a: unknown[]) => mockRequireChannelMember(...a),- requireDMAccess: (...a: unknown[]) => mockRequireDMAccess(...a),-}))--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server")- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- }-})--import { GET } from "./route"--describe("GET /api/community/messages/search — server scope", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetMember.mockResolvedValue({ id: "m1", role: "member" })- mockListVisibleChannelIds.mockResolvedValue(["c_pub", "c_priv_mine"])- mockSearchMessagesInServer.mockResolvedValue([])- mockSearchMessages.mockResolvedValue([])- mockRequireServerMember.mockResolvedValue({ ok: true, value: { id: "m1" } })- mockRequireChannelMember.mockResolvedValue({ ok: true, value: { id: "c1" } })- mockRequireDMAccess.mockResolvedValue({ ok: true, value: { id: "dm1" } })- })-- it("scopes the server search to the viewer's visible channel ids", async () => {- const res = await GET(- new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),- { params: {} } as any,- )- expect(res.status).toBe(200)- // Visibility no longer takes an isAdmin flag — admins get the same- // member-scoped visibility as everyone (no special private access).- expect(mockListVisibleChannelIds).toHaveBeenCalledWith(- expect.anything(),- "s1",- "u1",- )- expect(mockSearchMessagesInServer).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ serverId: "s1", visibleChannelIds: ["c_pub", "c_priv_mine"] }),- )- })-- it("admin gets the same member-scoped visibility (no isAdmin flag)", async () => {- mockGetMember.mockResolvedValue({ id: "m1", role: "owner" })- await GET(- new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),- { params: {} } as any,- )- expect(mockListVisibleChannelIds).toHaveBeenCalledWith(- expect.anything(), "s1", "u1",- )- })-- it("returns only canonical versioned author identity fields", async () => {- mockSearchMessagesInServer.mockResolvedValue([{- message: { id: "message-1", content: "hello" },- author: {- id: "author-1",- name: "Alice",- discriminator: "0001",- image: "/api/community/users/author-1/avatar",- avatarVersion: 4,- avatarObjectKey: "user-avatar/author-1/objects/private-key",- },- }])-- const res = await GET(- new NextRequest("http://localhost/api/community/messages/search?q=hello&serverId=s1"),- { params: {} } as any,- )-- expect(await res.json()).toEqual({- results: [{- message: { id: "message-1", content: "hello" },- author: {- id: "author-1",- name: "Alice",- discriminator: "0001",- image: "/api/community/users/author-1/avatar?v=4",- avatarVersion: 4,- },- }],- })- })-- it("projects channel-scoped search results", async () => {- const res = await GET(- new NextRequest("http://localhost/api/community/messages/search?q=hello&channelId=c1"),- { params: {} } as any,- )-- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ results: [] })- expect(mockSearchMessages).toHaveBeenCalledWith(- expect.anything(),- { query: "hello", channelId: "c1" },- )- })-- it("projects DM-scoped search results", async () => {- const res = await GET(- new NextRequest("http://localhost/api/community/messages/search?q=hello&dmConversationId=dm1"),- { params: {} } as any,- )-- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ results: [] })- expect(mockSearchMessages).toHaveBeenCalledWith(- expect.anything(),- { query: "hello", channelId: "dm1" },- )- })-})diff --git a/src/web/src/app/api/community/messages/search/route.ts b/src/web/src/app/api/community/messages/search/route.tsdeleted file mode 100644index efc6cb4f4..000000000--- a/src/web/src/app/api/community/messages/search/route.ts+++ /dev/null@@ -1,84 +0,0 @@-import { NextRequest } from "next/server"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { getDb } from "@/lib/db"-import { queries, MIN_SEARCH_LENGTH, MAX_SEARCH_LENGTH } from "@alook/shared"-import { canonicalUserImage } from "@/lib/community/storage"-import {- requireServerMember,- requireChannelMember,- requireDMAccess,-} from "@/lib/community/permissions"--export const GET = withAuth(async (req: NextRequest, ctx) => {- const url = new URL(req.url)- const q = url.searchParams.get("q")?.trim()- const serverId = url.searchParams.get("serverId")- const channelId = url.searchParams.get("channelId")- const dmConversationId = url.searchParams.get("dmConversationId")-- if (!q) return writeError("query parameter q is required", 400)- if (q.length < MIN_SEARCH_LENGTH) {- return writeError(`query must be at least ${MIN_SEARCH_LENGTH} characters`, 400)- }- if (q.length > MAX_SEARCH_LENGTH) {- return writeError(`query must be ≤ ${MAX_SEARCH_LENGTH} characters`, 400)- }- if (!serverId && !channelId && !dmConversationId) {- return writeError("a scope parameter (serverId, channelId, or dmConversationId) is required", 400)- }-- const db = getDb(ctx.env.DB)-- if (serverId) {- const auth = await requireServerMember(db, serverId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- // Scope to the viewer's visible channels so private-channel content never- // surfaces in server-wide search.- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIds(- db,- serverId,- ctx.userId,- )- const results = await queries.communitySearch.searchMessagesInServer(db, {- query: q,- serverId,- visibleChannelIds,- })- return writeJSON({ results: projectResults(results) })- }-- if (channelId) {- const auth = await requireChannelMember(db, channelId, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const results = await queries.communitySearch.searchMessages(db, {- query: q,- channelId,- })- return writeJSON({ results: projectResults(results) })- }-- // A DM is a `type=dm` channel now; the `dmConversationId` query param IS the- // DM's channel id. Block check is inherited from `requireDMAccess` — do not- // re-inline.- const auth = await requireDMAccess(db, dmConversationId!, ctx.userId)- if (!auth.ok) return writeError(auth.error, auth.status)- const results = await queries.communitySearch.searchMessages(db, {- query: q,- channelId: dmConversationId!,- })- return writeJSON({ results: projectResults(results) })-})--function projectResults(results: Awaited<ReturnType<typeof queries.communitySearch.searchMessages>>) {- return results.map(({ message, author }) => ({- message,- author: {- id: author.id,- name: author.name,- discriminator: author.discriminator,- image: canonicalUserImage(author.id, author.image, author.avatarVersion),- avatarVersion: author.avatarVersion,- },- }))-}diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts b/src/web/src/app/api/community/servers/[id]/bots/route.test.tsdeleted file mode 100644index c9edd4e64..000000000--- a/src/web/src/app/api/community/servers/[id]/bots/route.test.ts+++ /dev/null@@ -1,230 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest"-import { NextRequest } from "next/server"--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))--const mockGetMember = vi.fn()-const mockGetUserInternal = vi.fn()-const mockAddMember = vi.fn()-const mockGetUserSelf = vi.fn()-const mockAreFriends = vi.fn()-const mockFindPendingJoinRequest = vi.fn()-const mockCreateOrGetDM = vi.fn()-const mockCreateApprovalRequestStatement = vi.fn()-const mockHardDeleteMessage = vi.fn()-const mockLogError = vi.fn()-const mockFanOutToServerMembers = vi.fn()--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- createLogger: () => ({- info: vi.fn(),- warn: vi.fn(),- error: (...a: unknown[]) => mockLogError(...a),- debug: vi.fn(),- }),- queries: {- communityMember: {- getMember: (...a: unknown[]) => mockGetMember(...a),- addMember: (...a: unknown[]) => mockAddMember(...a),- },- user: {- getUserInternal: (...a: unknown[]) => mockGetUserInternal(...a),- getUserSelf: (...a: unknown[]) => mockGetUserSelf(...a),- },- communityFriendship: {- areFriends: (...a: unknown[]) => mockAreFriends(...a),- },- communityBot: {- findPendingJoinRequest: (...a: unknown[]) => mockFindPendingJoinRequest(...a),- createApprovalRequestStatement: (...a: unknown[]) => mockCreateApprovalRequestStatement(...a),- },- communityDm: {- createOrGetDM: (...a: unknown[]) => mockCreateOrGetDM(...a),- },- communityMessage: {- hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),- },- },- }-})--vi.mock("@/lib/community/fanout", () => ({- fanOutToServerMembers: (...a: unknown[]) => mockFanOutToServerMembers(...a),- broadcastToUserSafe: vi.fn(),-}))---const mockCreateCommunityMessage = vi.fn()-vi.mock("@/lib/community/message-handler", () => ({- createCommunityMessage: (...a: unknown[]) => mockCreateCommunityMessage(...a),-}))--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })- }),-}))--import { POST } from "./route"--const ctx = { params: { id: "s1" } } as any-function req(body: unknown) {- return new NextRequest("http://localhost/api/community/servers/s1/bots", {- method: "POST",- body: JSON.stringify(body),- })-}--describe("POST /servers/[id]/bots — approval-request rollback failure", () => {- beforeEach(() => {- vi.clearAllMocks()- // Friend-of-bot-add (Path B): caller is a member, target is a bot owned- // by someone else, caller is friends with the bot.- mockGetMember.mockResolvedValue({ id: "m1", nickname: "Casey" })- mockGetUserInternal.mockResolvedValue({- id: "bot1",- isBot: true,- deletedAt: null,- ownerUserId: "owner1",- name: "Bot",- })- mockAreFriends.mockResolvedValue(true)- mockFindPendingJoinRequest.mockResolvedValue(null)- mockCreateOrGetDM.mockResolvedValue({ id: "dm1" })- mockCreateCommunityMessage.mockResolvedValue({- ok: true,- row: { id: "msg1", content: "Casey wants to add me to a server. Approve?", createdAt: "2026-01-01T00:00:00Z" },- })- })-- it("returns 500 with the rollback exception's message when both the approval-request insert AND the compensating delete fail", async () => {- mockCreateApprovalRequestStatement.mockRejectedValue(new Error("insert failed"))- mockHardDeleteMessage.mockRejectedValue(new Error("delete failed"))-- const res = await POST(req({ botId: "bot1" }), ctx)-- expect(res.status).toBe(500)- const body = await res.json()- expect(body.error).toContain("delete failed")- expect(body.error).toContain("approval request write failed")- expect(mockLogError).toHaveBeenCalledWith(- "approval_request_rollback_failed",- expect.objectContaining({- botId: "bot1",- serverId: "s1",- messageId: "msg1",- insertErr: expect.stringContaining("insert failed"),- rollbackErr: expect.stringContaining("delete failed"),- }),- )- })-- it("returns 200 pending when the insert fails but the compensating delete succeeds (race lost, not a rollback failure)", async () => {- mockCreateApprovalRequestStatement.mockRejectedValue(new Error("insert failed"))- mockHardDeleteMessage.mockResolvedValue(undefined)-- const res = await POST(req({ botId: "bot1" }), ctx)-- expect(res.status).toBe(200)- expect(await res.json()).toEqual({ status: "pending" })- })-- it("invokes committed delivery only after the approval row exists", async () => {- const order: string[] = []- const broadcast = vi.fn(async () => { order.push("dispatch") })- mockCreateCommunityMessage.mockResolvedValueOnce({- ok: true,- row: { id: "msg1", content: "card", createdAt: "2026-01-01T00:00:00Z" },- broadcast,- })- mockCreateApprovalRequestStatement.mockImplementationOnce(async () => {- order.push("approval")- })-- const res = await POST(req({ botId: "bot1" }), ctx)-- expect(res.status).toBe(200)- expect(order).toEqual(["approval", "dispatch"])- expect(broadcast).toHaveBeenCalledTimes(1)- })-- it("owner-add fans out the bot's canonical versioned identity", async () => {- mockGetMember- .mockResolvedValueOnce({ id: "caller-member", nickname: "Owner" })- .mockResolvedValueOnce(null)- mockGetUserInternal.mockResolvedValue({- id: "bot1",- isBot: true,- deletedAt: null,- ownerUserId: "u1",- name: "Bot",- })- mockAddMember.mockResolvedValue({- id: "bot-member",- role: "member",- joinedAt: "2026-01-02T00:00:00Z",- })- mockGetUserSelf.mockResolvedValue({- id: "bot1",- name: "Bot",- discriminator: "0042",- image: "/api/community/bots/bot1/avatar",- avatarVersion: 5,- })-- const res = await POST(req({ botId: "bot1" }), ctx)-- expect(res.status).toBe(201)- expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {- type: "community:member.join",- serverId: "s1",- member: expect.objectContaining({- userId: "bot1",- avatar: "/api/community/bots/bot1/avatar?v=5",- avatarVersion: 5,- }),- })- })-- it("owner-add falls back to an empty identity when the bot profile disappears", async () => {- mockGetMember- .mockResolvedValueOnce({ id: "caller-member", nickname: "Owner" })- .mockResolvedValueOnce(null)- mockGetUserInternal.mockResolvedValue({- id: "bot1",- isBot: true,- deletedAt: null,- ownerUserId: "u1",- name: "Bot",- })- mockAddMember.mockResolvedValue({- id: "bot-member",- role: "member",- joinedAt: "2026-01-02T00:00:00Z",- })- mockGetUserSelf.mockResolvedValue(null)-- const res = await POST(req({ botId: "bot1" }), ctx)-- expect(res.status).toBe(201)- expect(mockFanOutToServerMembers).toHaveBeenCalledWith("s1", {- type: "community:member.join",- serverId: "s1",- member: expect.objectContaining({- userId: "bot1",- name: "",- discriminator: "0000",- avatar: undefined,- avatarVersion: 0,- }),- })- })-})diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsdeleted file mode 100644index 4fecc3897..000000000--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ /dev/null@@ -1,155 +0,0 @@-import { NextRequest } from "next/server"-import {- queries,- ROLES,- WS_EVENTS,- CommunityBotAddToServerRequestSchema,- createLogger,-} from "@alook/shared"-import type { CommunityMemberJoin } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers"-import { fanOutToServerMembers } from "@/lib/community/fanout"-import { createCommunityMessage } from "@/lib/community/message-handler"-import { canonicalUserImage } from "@/lib/community/storage"--const log = createLogger({ service: "community-bots-server-add" })--/**- * Add a bot to a server. Two paths, keyed by ownership + friendship:- * Path A — Owner-add. Caller owns the bot AND is a member → direct insert.- * Path B — Friend-of-bot-add. Caller is friends with the bot AND is a member- * → write approval-request DM card, no member row until owner- * approves.- * Any other combination returns 404 (indistinguishable from "bot not found"- * so a non-friend can't enumerate bot vs human targets).- */-export const POST = withAuth(async (req: NextRequest, ctx) => {- const serverId = ctx.params?.id as string- const [body, err] = await parseBody(req, CommunityBotAddToServerRequestSchema)- if (err) return err-- const db = getDb(ctx.env.DB)-- const callerMember = await queries.communityMember.getMember(db, serverId, ctx.userId)- if (!callerMember) return writeError("not a member of this server", 403)-- // Target must be a live bot user row.- const target = await queries.user.getUserInternal(db, body.botId)- if (!target || target.isBot !== true || target.deletedAt !== null) {- return writeError("bot not found", 404)- }- const botId = target.id- const ownerId = target.ownerUserId-- // Path A — Owner-add.- if (ownerId === ctx.userId) {- const already = await queries.communityMember.getMember(db, serverId, botId)- if (already) {- return writeJSON({ status: "added" }, 201)- }- const added = await queries.communityMember.addMember(db, {- serverId,- userId: botId,- role: ROLES.MEMBER,- })- const bot = await queries.user.getUserSelf(db, botId)- const joinEvent: CommunityMemberJoin = {- type: WS_EVENTS.MEMBER_JOIN,- serverId,- member: {- id: added.id,- userId: botId,- name: bot?.name ?? "",- discriminator: bot?.discriminator ?? "0000",- avatar: bot- ? canonicalUserImage(bot.id, bot.image, bot.avatarVersion) ?? undefined- : undefined,- avatarVersion: bot?.avatarVersion ?? 0,- role: added.role ?? ROLES.MEMBER,- joinedAt: added.joinedAt,- },- }- fanOutToServerMembers(serverId, joinEvent)- return writeJSON({ status: "added" }, 201)- }-- // Path B — Friend-of-bot-add. Caller must be friends with the BOT (not the- // owner). Otherwise 404 for pass-as-human indistinguishability.- const friends = await queries.communityFriendship.areFriends(db, ctx.userId, botId)- if (!friends) return writeError("bot not found", 404)- if (!ownerId) return writeError("bot not found", 404)-- // Idempotency — same friend re-requesting for same (bot, server). The- // partial unique guards at DB level but we check first to keep the response- // shape identical (no duplicate DM card).- const pending = await queries.communityBot.findPendingJoinRequest(db, botId, serverId)- if (pending) return writeJSON({ status: "pending" }, 200)-- // Owner ↔ bot DM (may need to be created).- const dm = await queries.communityDm.createOrGetDM(db, {- userId1: botId,- userId2: ownerId,- })-- // Compose the DM card content. Fall back to a generic phrase when the- // caller has no display name — never leak a raw name of "" or the string- // "undefined".- const caller = await queries.user.getUserSelf(db, ctx.userId)- const requesterLabel = caller?.name?.trim() || "A friend"- // Unified pipeline, broadcast-deferred: the card must not reach the owner- // until the approval-request row commits (a rollback below would otherwise- // leave a phantom, unactionable card). The bot DM card mentions no one, so- // mention persistence is skipped. Its dispatcher thunk is invoked only after the- // approval row persists, so no client can observe an unactionable card.- const created = await createCommunityMessage({- db,- authorId: botId,- authorKind: "bot",- target: { kind: "dm", channelId: dm.id, otherUserId: ownerId },- body: { content: `${requesterLabel} wants to add me to a server. Approve?` },- skipMentions: true,- deferBroadcast: true,- })- if (!created.ok) return writeError(created.error, created.status)- const msg = created.row- // Write the approval-request row. If the partial unique index rejects a- // concurrent duplicate, roll back by hard-deleting the DM card so the owner- // never sees a phantom card without approve/deny buttons.- try {- await queries.communityBot.createApprovalRequestStatement(db, {- botId,- kind: "join_server",- serverId,- requestedByUserId: ctx.userId,- dmMessageId: msg.id,- })- } catch (err) {- // Race lost or transient — compensate by deleting the DM card so the- // owner never sees an unactionable card. If the compensating delete- // ALSO fails we've left an orphan; surface 500 so the caller retries- // (idempotency on the partial-unique will short-circuit on retry).- try {- await queries.communityMessage.hardDeleteMessage(db, msg.id)- } catch (rollbackErr) {- log.error("approval_request_rollback_failed", {- botId,- serverId,- messageId: msg.id,- insertErr: String(err),- rollbackErr: String(rollbackErr),- })- return writeError(- `approval request write failed: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`,- 500- )- }- // Race lost — the peer request already exists. Report pending to keep- // the caller-facing shape identical to the idempotent case above.- return writeJSON({ status: "pending" }, 200)- }- await created.broadcast?.()-- return writeJSON({ status: "pending" }, 200)-})diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.test.tsdeleted file mode 100644index 1323414f0..000000000--- a/src/web/src/app/api/community/servers/[id]/unreads/route.test.ts+++ /dev/null@@ -1,147 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest"-import { NextRequest } from "next/server"--const mockGetMember = vi.fn()-const mockListVisibleChannelIds = vi.fn()-const mockListVisibleChannelIdsForUser = vi.fn()-const mockListEligibleUnreadChannels = vi.fn()-const mockListUnreadForumOpeners = vi.fn()--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }))-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMember: { getMember: (...args: unknown[]) => mockGetMember(...args) },- communityChannel: {- ...actual.queries.communityChannel,- listVisibleChannelIds: (...args: unknown[]) => mockListVisibleChannelIds(...args),- listVisibleChannelIdsForUser: (...args: unknown[]) => mockListVisibleChannelIdsForUser(...args),- },- communityInbox: {- ...actual.queries.communityInbox,- listEligibleUnreadChannels: (...args: unknown[]) => mockListEligibleUnreadChannels(...args),- listUnreadForumOpeners: (...args: unknown[]) => mockListUnreadForumOpeners(...args),- },- },- }-})-vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx: any) => handler(req, {- env: { DB: {} },- userId: "user_1",- params: ctx.params,- }),-}))--import { GET } from "./route"--describe("GET /api/community/servers/[id]/unreads", () => {- beforeEach(() => {- vi.clearAllMocks()- mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })- mockListVisibleChannelIds.mockResolvedValue(["channel_1", "channel_2"])- mockListVisibleChannelIdsForUser.mockRejectedValue(new Error("cross-server resolver must not run"))- mockListEligibleUnreadChannels.mockResolvedValue([- {- serverId: "server_1",- channelId: "channel_1",- lastUnreadSeq: 7,- lastAttentionSeq: null,- },- {- serverId: "server_1",- channelId: "channel_2",- parentChannelId: "channel_1",- lastUnreadSeq: 11,- lastAttentionSeq: 10,- },- ])- mockListUnreadForumOpeners.mockResolvedValue([])- })-- it("returns the complete viewer-visible unread id set scoped to the server", async () => {- const response = await GET(- new NextRequest("http://localhost/api/community/servers/server_1/unreads"),- { params: { id: "server_1" } } as never,- )-- expect(response.status).toBe(200)- expect(await response.json()).toEqual({- channelIds: ["channel_1", "channel_2"],- sources: [- { channelId: "channel_1", lastUnreadSeq: 7, lastAttentionSeq: null },- { channelId: "channel_2", lastUnreadSeq: 11, lastAttentionSeq: 10 },- ],- childChannels: [{- id: "channel_2",- parentChannelId: "channel_1",- lastUnreadSeq: 11,- lastAttentionSeq: 10,- }],- stale: false,- })- expect(mockListVisibleChannelIds).toHaveBeenCalledWith(expect.anything(), "server_1", "user_1")- expect(mockListVisibleChannelIdsForUser).not.toHaveBeenCalled()- expect(mockListEligibleUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["channel_1", "channel_2"])- })-- it("uses the shared readable, cursor, policy, and attention projection on refetch", async () => {- const response = await GET(- new NextRequest("http://localhost/api/community/servers/server_1/unreads"),- { params: { id: "server_1" } } as never,- )-- expect(await response.json()).toMatchObject({ channelIds: ["channel_1", "channel_2"] })- expect(mockListEligibleUnreadChannels).toHaveBeenCalledOnce()- })-- it("keeps a forum parent only while its hybrid projection has an unread opener", async () => {- mockListEligibleUnreadChannels.mockResolvedValue([- { serverId: "server_1", channelId: "forum_1", parentChannelId: null, type: "forum" },- ])- mockListUnreadForumOpeners.mockResolvedValue([{ forumChannelId: "forum_1" }])-- const response = await GET(- new NextRequest("http://localhost/api/community/servers/server_1/unreads"),- { params: { id: "server_1" } } as never,- )-- expect(await response.json()).toMatchObject({ channelIds: ["forum_1"] })- expect(mockListUnreadForumOpeners).toHaveBeenCalledWith(- expect.anything(),- "user_1",- ["forum_1"],- )- })-- it("fails closed when the viewer is not a server member", async () => {- mockGetMember.mockResolvedValue(null)- const response = await GET(- new NextRequest("http://localhost/api/community/servers/server_1/unreads"),- { params: { id: "server_1" } } as never,- )-- expect(response.status).toBe(403)- expect(mockListVisibleChannelIds).not.toHaveBeenCalled()- expect(mockListEligibleUnreadChannels).not.toHaveBeenCalled()- })-- it("marks retry-exhausted reads stale instead of caching an empty read set", async () => {- mockListVisibleChannelIds.mockRejectedValue(new Error("D1_ERROR: database is locked"))- const response = await GET(- new NextRequest("http://localhost/api/community/servers/server_1/unreads"),- { params: { id: "server_1" } } as never,- )-- expect(response.status).toBe(200)- expect(await response.json()).toEqual({- channelIds: [],- sources: [],- childChannels: [],- stale: true,- })- })-})diff --git a/src/web/src/app/api/community/servers/[id]/unreads/route.ts b/src/web/src/app/api/community/servers/[id]/unreads/route.tsdeleted file mode 100644index 245e591a2..000000000--- a/src/web/src/app/api/community/servers/[id]/unreads/route.ts+++ /dev/null@@ -1,80 +0,0 @@-import { NextResponse } from "next/server"-import { queries, readOrStale } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { requireServerMember } from "@/lib/community/permissions"--/** Attention-eligible read-state projection for one server's sidebar badges. */-export const GET = withAuth(async (_req, ctx) => {- const serverId = ctx.params?.id- if (!serverId) return NextResponse.json({ error: "missing server id" }, { status: 400 })-- const db = getDb(ctx.env.DB)- const auth = await requireServerMember(db, serverId, ctx.userId)- if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status })-- const { value, stale } = await readOrStale(- async () => {- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIds(db, serverId, ctx.userId)- const unread = await queries.communityInbox.listEligibleUnreadChannels(db, ctx.userId, visibleChannelIds)- const forumParentIds = unread- .filter((row) => !row.parentChannelId && row.type === "forum")- .map((row) => row.channelId)- const unreadOpeners = await queries.communityInbox.listUnreadForumOpeners(- db,- ctx.userId,- forumParentIds,- )- const forumParentsWithUnread = new Set([- ...unreadOpeners.map((row) => row.forumChannelId),- ...unread.flatMap((row) => row.parentChannelId ? [row.parentChannelId] : []),- ])- const projectedUnread = unread.filter(- (row) =>- row.parentChannelId ||- row.type !== "forum" ||- forumParentsWithUnread.has(row.channelId),- )- return {- channelIds: projectedUnread.map((row) => row.channelId),- sources: projectedUnread.map((row) => ({- channelId: row.channelId,- lastUnreadSeq: row.lastUnreadSeq,- lastAttentionSeq: row.lastAttentionSeq,- })),- // Preserve the canonical child → parent attribution. The client needs- // this even when a participating forum post is outside the sidebar's- // 72h / top-five projection, otherwise a cold boot loses its unread- // signal entirely. `listEligibleUnreadChannels` has already applied- // access, archive, participant, read-cursor, and policy filtering;- // the client narrows them to parents whose canonical type is `forum`.- childChannels: projectedUnread.flatMap((row) => row.parentChannelId- ? [{- id: row.channelId,- parentChannelId: row.parentChannelId,- lastUnreadSeq: row.lastUnreadSeq,- lastAttentionSeq: row.lastAttentionSeq,- }]- : []),- }- },- {- channelIds: [] as string[],- sources: [] as Array<{ channelId: string; lastUnreadSeq: number; lastAttentionSeq: number | null }>,- childChannels: [] as Array<{- id: string- parentChannelId: string- lastUnreadSeq: number- lastAttentionSeq: number | null- }>,- },- { route: "community/servers/:id/unreads" },- )-- return NextResponse.json({- channelIds: value.channelIds,- sources: value.sources,- childChannels: value.childChannels,- stale,- })-})diff --git a/src/web/src/app/api/community/users/me/server-folders/[id]/route.test.ts b/src/web/src/app/api/community/users/me/server-folders/[id]/route.test.tsdeleted file mode 100644index 94de7884d..000000000--- a/src/web/src/app/api/community/users/me/server-folders/[id]/route.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest"-import { NextRequest } from "next/server"--const mocks = vi.hoisted(() => ({- getFolder: vi.fn(),- listMemberServerIds: vi.fn(),- readSnapshot: vi.fn(),- applyProjection: vi.fn(),-}))--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))-vi.mock("@/lib/db", () => ({ getDb: () => ({ id: "db" }) }))-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMember: { listMemberServerIds: (...args: unknown[]) => mocks.listMemberServerIds(...args) },- communityServerFolder: {- getFolder: (...args: unknown[]) => mocks.getFolder(...args),- updateFolder: vi.fn(),- deleteFolder: vi.fn(),- },- communityServerRail: {- readServerRailSnapshot: (...args: unknown[]) => mocks.readSnapshot(...args),- applyServerRailProjection: (...args: unknown[]) => mocks.applyProjection(...args),- },- },- }-})-vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => (req: NextRequest) => handler(req, {- env: { DB: {} },- userId: "user_1",- params: { id: "folder_1" },- }),-}))--import { PATCH } from "./route"--function request(serverIds: string[]) {- return new NextRequest("http://localhost/api/community/users/me/server-folders/folder_1", {- method: "PATCH",- body: JSON.stringify({ serverIds }),- })-}--describe("legacy server-folders PATCH rail invariants", () => {- beforeEach(() => {- vi.clearAllMocks()- mocks.getFolder.mockResolvedValue({ id: "folder_1", name: "Group", position: 0 })- mocks.listMemberServerIds.mockResolvedValue(["server_1", "server_2"])- mocks.readSnapshot.mockResolvedValue({- serverOrder: ["server_1", "server_2"],- folderOrder: ["folder_1"],- folders: {- folder_1: { id: "folder_1", name: "Group", serverIds: ["server_1"] },- },- })- mocks.applyProjection.mockResolvedValue(undefined)- })-- it("rejects replacing a folder with an empty item list", async () => {- const response = await PATCH(request([]), {} as any)-- expect(response.status).toBe(400)- expect(mocks.readSnapshot).not.toHaveBeenCalled()- expect(mocks.applyProjection).not.toHaveBeenCalled()- })-- it("routes legacy item replacement through the rail projection batch", async () => {- const response = await PATCH(request(["server_2"]), {} as any)-- expect(response.status).toBe(200)- expect(mocks.applyProjection).toHaveBeenCalledWith(- { id: "db" },- "user_1",- expect.objectContaining({- affectedFolderIds: ["folder_1"],- movedServerIds: ["server_1", "server_2"],- }),- )- })-})diff --git a/src/web/src/app/api/community/users/me/server-folders/[id]/route.ts b/src/web/src/app/api/community/users/me/server-folders/[id]/route.tsdeleted file mode 100644index 0124cb374..000000000--- a/src/web/src/app/api/community/users/me/server-folders/[id]/route.ts+++ /dev/null@@ -1,73 +0,0 @@-import { NextRequest } from "next/server"-import { projectServerRailCommit, queries, MAX_FOLDER_NAME_LENGTH } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--export const PATCH = withAuth(async (req: NextRequest, ctx) => {- const folderId = ctx.params?.id- if (!folderId) return writeError("missing folder id", 400)-- const db = getDb(ctx.env.DB)- const folder = await queries.communityServerFolder.getFolder(db, folderId, ctx.userId)- if (!folder) return writeError("folder not found", 404)-- let body: { name?: string; serverIds?: string[] }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (body.name !== undefined) {- if (typeof body.name !== "string" || !body.name.trim()) {- return writeError("name must be a non-empty string", 400)- }- const name = body.name.trim()- if (name.length > MAX_FOLDER_NAME_LENGTH) {- return writeError(`name must be ≤ ${MAX_FOLDER_NAME_LENGTH} characters`, 400)- }- await queries.communityServerFolder.updateFolder(db, folderId, { name })- }-- if (body.serverIds !== undefined) {- if (!Array.isArray(body.serverIds) || body.serverIds.length === 0) {- return writeError("serverIds must be a non-empty array", 400)- }- const memberServerIds = new Set(- await queries.communityMember.listMemberServerIds(db, ctx.userId),- )- const stranger = body.serverIds.find((id) => !memberServerIds.has(id))- if (stranger) {- return writeError(`not a member of server ${stranger}`, 400)- }- const snapshot = await queries.communityServerRail.readServerRailSnapshot(db, ctx.userId)- const currentIds = snapshot.folders[folderId]?.serverIds- if (!currentIds) return writeError("folder not found", 404)- const sameItems = currentIds.length === body.serverIds.length- && currentIds.every((id, index) => id === body.serverIds![index])- if (!sameItems) {- const projection = projectServerRailCommit(snapshot, {- commands: [{ kind: "replace-folder-items", folderId, serverIds: body.serverIds }],- }, () => "")- if (!projection.ok) return writeError(projection.error, projection.status)- await queries.communityServerRail.applyServerRailProjection(db, ctx.userId, projection.value)- }- }-- const updated = await queries.communityServerFolder.getFolder(db, folderId, ctx.userId)- return writeJSON(updated)-})--export const DELETE = withAuth(async (_req, ctx) => {- const folderId = ctx.params?.id- if (!folderId) return writeError("missing folder id", 400)-- const db = getDb(ctx.env.DB)- const folder = await queries.communityServerFolder.getFolder(db, folderId, ctx.userId)- if (!folder) return writeError("folder not found", 404)-- await queries.communityServerFolder.deleteFolder(db, folderId)-- return new Response(null, { status: 204 })-})diff --git a/src/web/src/app/api/community/users/me/server-folders/reorder/route.ts b/src/web/src/app/api/community/users/me/server-folders/reorder/route.tsdeleted file mode 100644index 9bfc38d44..000000000--- a/src/web/src/app/api/community/users/me/server-folders/reorder/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { NextRequest } from "next/server"-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"--export const PATCH = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- let body: { folderIds?: string[] }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (!Array.isArray(body.folderIds) || body.folderIds.length === 0) {- return writeError("folderIds must be a non-empty array", 400)- }- const unique = new Set(body.folderIds)- if (unique.size !== body.folderIds.length) {- return writeError("folderIds must be unique", 400)- }-- // Reorder query is already user-scoped, but pre-validate ownership so the- // caller gets an error instead of silent no-ops when an unknown id leaks in.- const owned = await queries.communityServerFolder.listFolders(db, ctx.userId)- const ownedIds = new Set(owned.map((f) => f.id))- const stranger = body.folderIds.find((id) => !ownedIds.has(id))- if (stranger) {- return writeError(`folder ${stranger} not found`, 404)- }-- await queries.communityServerFolder.reorderFolders(db, ctx.userId, body.folderIds)-- return writeJSON({ ok: true })-})diff --git a/src/web/src/app/api/community/users/me/server-folders/route.test.ts b/src/web/src/app/api/community/users/me/server-folders/route.test.tsindex 1c2a88890..5c9d9a590 100644--- a/src/web/src/app/api/community/users/me/server-folders/route.test.ts+++ b/src/web/src/app/api/community/users/me/server-folders/route.test.ts@@ -1,85 +1,27 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { describe, expect, it, vi } from "vitest"import { NextRequest } from "next/server"-const mocks = vi.hoisted(() => ({- listMemberServerIds: vi.fn(),- readSnapshot: vi.fn(),- applyProjection: vi.fn(),- getFolder: vi.fn(),- nanoid: vi.fn(),-}))--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}))+const { listFolders } = vi.hoisted(() => ({ listFolders: vi.fn() }))vi.mock("@/lib/db", () => ({ getDb: () => ({ id: "db" }) }))-vi.mock("nanoid", async () => {- const actual = await vi.importActual<typeof import("nanoid")>("nanoid")- return { ...actual, nanoid: () => mocks.nanoid() }-})vi.mock("@alook/shared", async () => {const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- ...actual.queries,- communityMember: { listMemberServerIds: (...args: unknown[]) => mocks.listMemberServerIds(...args) },- communityServerFolder: { getFolder: (...args: unknown[]) => mocks.getFolder(...args) },- communityServerRail: {- readServerRailSnapshot: (...args: unknown[]) => mocks.readSnapshot(...args),- applyServerRailProjection: (...args: unknown[]) => mocks.applyProjection(...args),- },- },- }+ return { ...actual, queries: { communityServerFolder: { listFolders } } }})vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => (req: NextRequest) => handler(req, {+ withAuth: (handler: any) => (request: NextRequest) => handler(request, {+ userId: "viewer",env: { DB: {} },- userId: "user_1",}),}))--import { POST } from "./route"--function request(body: unknown) {- return new NextRequest("http://localhost/api/community/users/me/server-folders", {- method: "POST",- body: JSON.stringify(body),- })-}--describe("legacy server-folders POST rail invariants", () => {- beforeEach(() => {- vi.clearAllMocks()- mocks.nanoid.mockReturnValueOnce("client").mockReturnValueOnce("folder")- mocks.listMemberServerIds.mockResolvedValue(["server_1"])- mocks.readSnapshot.mockResolvedValue({- serverOrder: ["server_1"],- folderOrder: [],- folders: {},- })- mocks.applyProjection.mockResolvedValue(undefined)- mocks.getFolder.mockResolvedValue({ id: "folder", name: "Group", position: 0 })- })-- it.each([undefined, []])("rejects an empty folder before reading or writing: %j", async (serverIds) => {- const response = await POST(request({ name: "Group", serverIds }), {} as any)-- expect(response.status).toBe(400)- expect(mocks.readSnapshot).not.toHaveBeenCalled()- expect(mocks.applyProjection).not.toHaveBeenCalled()- })-- it("routes legacy creates through the guarded rail projection batch", async () => {- const response = await POST(request({ name: "Group", serverIds: ["server_1"] }), {} as any)-- expect(response.status).toBe(201)- expect(mocks.applyProjection).toHaveBeenCalledWith(- { id: "db" },- "user_1",- expect.objectContaining({- createdFolders: [{ id: "folder", name: "Group", serverIds: ["server_1"] }],- }),- )+import { GET } from "./route"++describe("GET server folders", () => {+ it("retains the current account-scoped folder list", async () => {+ const folders = [{ id: "folder", name: "Group", position: 0, servers: [{ id: "server", name: "Server" }] }]+ listFolders.mockResolvedValue(folders)+ const response = await GET(new NextRequest("http://localhost/api/community/users/me/server-folders"), {} as any)+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ folders })+ expect(listFolders).toHaveBeenCalledWith({ id: "db" }, "viewer")})})diff --git a/src/web/src/app/api/community/users/me/server-folders/route.ts b/src/web/src/app/api/community/users/me/server-folders/route.tsindex 191c7e311..b36d79799 100644--- a/src/web/src/app/api/community/users/me/server-folders/route.ts+++ b/src/web/src/app/api/community/users/me/server-folders/route.ts@@ -1,59 +1,11 @@import { NextRequest } from "next/server"-import { nanoid } from "nanoid"-import { projectServerRailCommit, queries, MAX_FOLDER_NAME_LENGTH } from "@alook/shared"+import { queries } from "@alook/shared"import { getDb } from "@/lib/db"import { withAuth } from "@/lib/middleware/auth"-import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { writeJSON } from "@/lib/middleware/helpers"export const GET = withAuth(async (_req: NextRequest, ctx) => {const db = getDb(ctx.env.DB)const folders = await queries.communityServerFolder.listFolders(db, ctx.userId)return writeJSON({ folders })})--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- let body: { name: string; serverIds?: string[] }- try {- body = await req.json()- } catch {- return writeError("invalid request body", 400)- }-- if (!body.name || typeof body.name !== "string" || !body.name.trim()) {- return writeError("name must be a non-empty string", 400)- }- const name = body.name.trim()- if (name.length > MAX_FOLDER_NAME_LENGTH) {- return writeError(`name must be ≤ ${MAX_FOLDER_NAME_LENGTH} characters`, 400)- }-- if (!Array.isArray(body.serverIds) || body.serverIds.length === 0) {- return writeError("serverIds must be a non-empty array", 400)- }- const memberServerIds = new Set(- await queries.communityMember.listMemberServerIds(db, ctx.userId),- )- const stranger = body.serverIds.find((id) => !memberServerIds.has(id))- if (stranger) {- return writeError(`not a member of server ${stranger}`, 400)- }-- const snapshot = await queries.communityServerRail.readServerRailSnapshot(db, ctx.userId)- const clientId = `legacy_${nanoid()}`- const projection = projectServerRailCommit(snapshot, {- commands: [{ kind: "create-folder", clientId, name, serverIds: body.serverIds }],- }, () => nanoid())- if (!projection.ok) return writeError(projection.error, projection.status)- await queries.communityServerRail.applyServerRailProjection(db, ctx.userId, projection.value)- const folderId = projection.value.createdFolderIds[clientId]- const folder = folderId- ? await queries.communityServerFolder.getFolder(db, folderId, ctx.userId)- : null- if (!folder) {- return writeError("folder create conflicted with a newer rail update", 409)- }-- return writeJSON(folder, 201)-})diff --git a/src/web/src/app/api/config/min-version/route.ts b/src/web/src/app/api/config/min-version/route.tsdeleted file mode 100644index 34b25d7f1..000000000--- a/src/web/src/app/api/config/min-version/route.ts+++ /dev/null@@ -1,17 +0,0 @@-import { semverGte } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";-import { fetchLatestCliVersion } from "@/lib/npm";--export const GET = withAuth(async (_req, ctx) => {- const raw = ctx.env.MIN_CLI_VERSION;- if (!raw) return writeJSON({ min_cli_version: null });-- const result = await fetchLatestCliVersion();- if (result && !semverGte(result.version, raw)) {- // MIN_CLI_VERSION is higher than what's published — ignore it- return writeJSON({ min_cli_version: null });- }-- return writeJSON({ min_cli_version: raw });-});diff --git a/src/web/src/app/api/config/model-options/route.test.ts b/src/web/src/app/api/config/model-options/route.test.tsdeleted file mode 100644index f4e856b9d..000000000--- a/src/web/src/app/api/config/model-options/route.test.ts+++ /dev/null@@ -1,80 +0,0 @@-import { NextRequest } from "next/server";--const mockEnv: Record<string, unknown> = { DB: {} };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: mockEnv })),-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: mockEnv, userId: "u1", email: "[email protected]", params });- }),-}));--import { GET } from "./route";--beforeEach(() => {- vi.clearAllMocks();- delete mockEnv.RUNTIME_MODEL_OPTIONS;-});--describe("GET /api/config/model-options", () => {- it("returns parsed config when valid JSON", async () => {- mockEnv.RUNTIME_MODEL_OPTIONS = '{"claude":["claude-opus-4-6","claude-sonnet-4-6"],"opencode":["gpt-4.1"]}';-- const req = new NextRequest("http://localhost/api/config/model-options");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({- claude: ["claude-opus-4-6", "claude-sonnet-4-6"],- opencode: ["gpt-4.1"],- });- });-- it("returns {} when env var is unset", async () => {- const req = new NextRequest("http://localhost/api/config/model-options");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({});- });-- it("returns {} for invalid JSON string", async () => {- mockEnv.RUNTIME_MODEL_OPTIONS = "not json{";-- const req = new NextRequest("http://localhost/api/config/model-options");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({});- });-- it("drops keys with invalid values (non-array)", async () => {- mockEnv.RUNTIME_MODEL_OPTIONS = '{"claude":"not-array","opencode":["gpt-4.1"]}';-- const req = new NextRequest("http://localhost/api/config/model-options");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ opencode: ["gpt-4.1"] });- });-- it("returns {} for non-object JSON (array)", async () => {- mockEnv.RUNTIME_MODEL_OPTIONS = '["a","b"]';-- const req = new NextRequest("http://localhost/api/config/model-options");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({});- });-});-diff --git a/src/web/src/app/api/config/model-options/route.ts b/src/web/src/app/api/config/model-options/route.tsdeleted file mode 100644index 0ba68e10e..000000000--- a/src/web/src/app/api/config/model-options/route.ts+++ /dev/null@@ -1,27 +0,0 @@-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";--export const GET = withAuth(async (_req, ctx) => {- const raw = ctx.env.RUNTIME_MODEL_OPTIONS;- if (!raw) return writeJSON({});-- let parsed: unknown;- try {- parsed = JSON.parse(raw);- } catch {- return writeJSON({});- }-- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {- return writeJSON({});- }-- const result: Record<string, string[]> = {};- for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {- if (Array.isArray(value) && value.every((v) => typeof v === "string")) {- result[key] = value as string[];- }- }-- return writeJSON(result);-});diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts b/src/web/src/app/api/conversations/[id]/active-task/route.test.tsdeleted file mode 100644index 0f85b98fb..000000000--- a/src/web/src/app/api/conversations/[id]/active-task/route.test.ts+++ /dev/null@@ -1,177 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetConversation = vi.fn();-const mockGetActiveTaskByConversation = vi.fn();-const mockTaskToResponse = vi.fn((t: any) => ({ id: t.id, status: t.status }));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- createLogger: vi.fn(() => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() })),- TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", KILL_TASK: "kill_task" },- buildEmailMapKey: (agentId: string, threadId: string) => `email:${agentId}:${threadId}`,- queries: {- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- },- task: {- getActiveTaskByConversation: (...args: any[]) => mockGetActiveTaskByConversation(...args),- createTask: vi.fn(),- claimTask: vi.fn(),- countRunningTasks: vi.fn(),- failTask: vi.fn(),- getTask: vi.fn(),- cancelTask: vi.fn(),- claimKillTasks: vi.fn(),- },- agent: {- getAgent: vi.fn(),- updateAgentStatus: vi.fn(),- },- message: {- createMessage: vi.fn(),- },- },-}));-vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));--const mockCancelActiveTask = vi.fn();-vi.mock("@/lib/services/task", () => {- return {- TaskService: class {- cancelActiveTask(...args: any[]) { return mockCancelActiveTask(...args); }- },- };-});--import { GET, DELETE } from "./route";-import { broadcastToUser } from "@/lib/broadcast";--const withParams = (id: string) => ({ params: Promise.resolve({ id }) });--describe("GET /api/conversations/[id]/active-task", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns active task when one exists", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockGetActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/active-task"),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "t1", status: "running" });- expect(mockGetActiveTaskByConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("returns 204 when no active task", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockGetActiveTaskByConversation.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/active-task"),- withParams("c1")- );-- expect(res.status).toBe(204);- });-- it("returns 404 when conversation not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/active-task"),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});--describe("DELETE /api/conversations/[id]/active-task", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns cancelled task", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });-- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "t1", status: "cancelled" });- });-- it("returns 404 when no active task", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockCancelActiveTask.mockResolvedValue(null);-- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("no active task to cancel");- });-- it("broadcasts task.updated on cancel", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockCancelActiveTask.mockResolvedValue({ id: "t1", status: "cancelled" });-- await DELETE(- new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),- withParams("c1")- );-- expect(broadcastToUser).toHaveBeenCalledWith("u1", {- type: "task.updated",- taskId: "t1",- status: "cancelled",- });- });-- it("returns 404 when conversation not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1/active-task", { method: "DELETE" }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});diff --git a/src/web/src/app/api/conversations/[id]/active-task/route.ts b/src/web/src/app/api/conversations/[id]/active-task/route.tsdeleted file mode 100644index f13e818ef..000000000--- a/src/web/src/app/api/conversations/[id]/active-task/route.ts+++ /dev/null@@ -1,68 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const task = await queries.task.getActiveTaskByConversation(db, id, ws.workspaceId);- if (!task) {- return new Response(null, { status: 204 });- }-- return writeJSON(taskToResponse(task));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const taskService = new TaskService(db);- const cancelled = await taskService.cancelActiveTask(id, ws.workspaceId);- if (!cancelled) {- return writeError("no active task to cancel", 404);- }-- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});-- broadcastToUser(ctx.userId, {- type: "task.updated",- taskId: cancelled.id,- agentId: cancelled.agentId,- status: "cancelled",- }).catch(() => {});-- return writeJSON(taskToResponse(cancelled));-});diff --git a/src/web/src/app/api/conversations/[id]/init/route.test.ts b/src/web/src/app/api/conversations/[id]/init/route.test.tsdeleted file mode 100644index 6baf260ca..000000000--- a/src/web/src/app/api/conversations/[id]/init/route.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const m = {- getConversation: vi.fn(),- getNewestMessageId: vi.fn(),- getActiveMessageCount: vi.fn(),- listMessages: vi.fn(),- listArtifactsByConversation: vi.fn(),- getActiveTaskByConversation: vi.fn(),- listFlaggedMessageIds: vi.fn(),- hasPreviousConversations: vi.fn(),- listTaskErrorMessages: vi.fn(),-};--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- conversation: {- getConversation: (...a: unknown[]) => m.getConversation(...a),- hasPreviousConversations: (...a: unknown[]) => m.hasPreviousConversations(...a),- },- message: {- getNewestMessageId: (...a: unknown[]) => m.getNewestMessageId(...a),- getActiveMessageCount: (...a: unknown[]) => m.getActiveMessageCount(...a),- listMessages: (...a: unknown[]) => m.listMessages(...a),- },- artifact: {- listArtifactsByConversation: (...a: unknown[]) => m.listArtifactsByConversation(...a),- artifactToResponse: (a: any) => a,- },- task: { getActiveTaskByConversation: (...a: unknown[]) => m.getActiveTaskByConversation(...a) },- messageFlag: { listFlaggedMessageIds: (...a: unknown[]) => m.listFlaggedMessageIds(...a) },- taskMessage: {- listTaskErrorMessages: (...a: unknown[]) => m.listTaskErrorMessages(...a),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: (c: any) => ({ id: c.id }),- messageToResponse: (m: any) => ({ id: m.id }),- taskToResponse: (t: any) => ({ id: t.id }),- taskMessageToResponse: (tm: any) => ({ id: tm.id }),-}));-import { GET } from "./route";--beforeEach(() => {- vi.clearAllMocks();- m.listMessages.mockResolvedValue({ messages: [], has_more: false });- m.listArtifactsByConversation.mockResolvedValue([]);- m.getActiveTaskByConversation.mockResolvedValue(null);- m.listFlaggedMessageIds.mockResolvedValue([]);- m.hasPreviousConversations.mockResolvedValue(false);- m.getActiveMessageCount.mockResolvedValue(0);- m.getNewestMessageId.mockResolvedValue(null);-});--describe("GET /api/conversations/[id]/init", () => {- it("400 when conversation id missing", async () => {- const req = new NextRequest("http://localhost/api/conversations/x/init");- const res = await GET(req, { params: {} });- expect(res.status).toBe(400);- });-- it("404 when conversation not in workspace", async () => {- m.getConversation.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/conversations/c1/init");- const res = await GET(req, { params: { id: "c1" } });- expect(res.status).toBe(404);- expect(mockScoped()).toBe(true);- });-- it("returns the init payload with messages when no cache hint", async () => {- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });- m.listMessages.mockResolvedValue({ messages: [{ id: "m1", role: "user" }], has_more: true });-- const req = new NextRequest("http://localhost/api/conversations/c1/init");- const res = await GET(req, { params: { id: "c1" } });- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.conversation).toEqual({ id: "c1" });- expect(body.messages).toEqual([{ id: "m1" }]);- expect(body.has_more_messages).toBe(true);- expect(body.cache_valid).toBe(false);- });-- it("preloads error task messages (workspace-scoped) for a running active task", async () => {- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });- m.getActiveTaskByConversation.mockResolvedValue({ id: "t1", status: "running" });- // The query filters to type:"error" in SQL, so the route maps whatever it returns.- m.listTaskErrorMessages.mockResolvedValue([- { id: "tm2", seq: 2, type: "error", content: "boom" },- ]);-- const req = new NextRequest("http://localhost/api/conversations/c1/init");- const res = await GET(req, { params: { id: "c1" } });- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.task_messages).toEqual([{ id: "tm2" }]);- // Scoped to the authed workspace and the active task.- expect(m.listTaskErrorMessages).toHaveBeenCalledWith(expect.anything(), "t1", "w1");- });-- it("does not query task errors when there is no active task", async () => {- // A run that ended in error is settled to status:"failed" and re-surfaces via- // its persisted assistant error message (not through this preload).- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });- m.getActiveTaskByConversation.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/conversations/c1/init");- const res = await GET(req, { params: { id: "c1" } });- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.task_messages).toEqual([]);- expect(m.listTaskErrorMessages).not.toHaveBeenCalled();- });-- it("returns cache_valid=true and null messages when client cache matches", async () => {- m.getConversation.mockResolvedValue({ id: "c1", agentId: "a1", channel: null, userId: "u1" });- m.getNewestMessageId.mockResolvedValue("m9");- m.getActiveMessageCount.mockResolvedValue(5);- m.listMessages.mockResolvedValue({ messages: [{ id: "m9", role: "user" }], has_more: false });-- const req = new NextRequest(- "http://localhost/api/conversations/c1/init?newest_message_id=m9&message_count=5",- );- const res = await GET(req, { params: { id: "c1" } });- const body = await res.json();-- expect(body.cache_valid).toBe(true);- expect(body.messages).toBeNull();- });-});--// helper: confirm the conversation lookup was scoped to the authed workspace-function mockScoped() {- return m.getConversation.mock.calls.every((c) => c[2] === "w1");-}diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.tsdeleted file mode 100644index 1d0d500f5..000000000--- a/src/web/src/app/api/conversations/[id]/init/route.ts+++ /dev/null@@ -1,105 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import {- conversationToResponse,- messageToResponse,- taskToResponse,- taskMessageToResponse,-} from "@/lib/api/responses";--const MESSAGE_LIMIT = 20;-const ARTIFACT_LIMIT = 50;--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const url = new URL(req.url);- const newestMessageId = url.searchParams.get("newest_message_id");- const messageCountParam = url.searchParams.get("message_count");-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const [serverNewest, serverMessageCount] = await Promise.all([- newestMessageId ? queries.message.getNewestMessageId(db, id) : Promise.resolve(null),- queries.message.getActiveMessageCount(db, id),- ]);-- let cacheValid = false;- if (newestMessageId) {- const idMatches = serverNewest === newestMessageId;- const countMatches = messageCountParam ? serverMessageCount === parseInt(messageCountParam, 10) : true;- cacheValid = idMatches && countMatches;- }-- const [messagesResult, artifacts, activeTask, flaggedMessageIds, hasMoreConversations] =- await Promise.all([- queries.message.listMessages(db, id, { limit: MESSAGE_LIMIT }),- queries.artifact.listArtifactsByConversation(db, id, ws.workspaceId, {- limit: ARTIFACT_LIMIT,- }).catch(() => [] as Awaited<ReturnType<typeof queries.artifact.listArtifactsByConversation>>),- queries.task.getActiveTaskByConversation(db, id, ws.workspaceId).catch(() => null),- queries.messageFlag.listFlaggedMessageIds(db, ctx.userId, ws.workspaceId, id).catch(() => [] as string[]),- queries.conversation.hasPreviousConversations(- db,- ws.workspaceId,- ctx.userId,- conversation.agentId,- id,- conversation.channel || undefined,- ).catch(() => false),- ]);-- const { messages, has_more: hasMoreMessages } = messagesResult;-- let taskMessages: unknown[] = [];- if (activeTask) {- try {- const tmsgs = await queries.taskMessage.listTaskErrorMessages(- db,- activeTask.id,- ws.workspaceId,- );- taskMessages = tmsgs.map(taskMessageToResponse);- } catch {- // non-critical- }- }-- // For thread conversations, fetch the root message from parent conversation- let rootMessage = null;- if (conversation.parentMessageId) {- try {- const rm = await queries.message.getMessage(db, conversation.parentMessageId);- if (rm) rootMessage = messageToResponse(rm);- } catch {}- }-- return writeJSON({- conversation: conversationToResponse(conversation),- messages: cacheValid ? null : messages.map(messageToResponse),- has_more_messages: hasMoreMessages,- has_more_conversations: hasMoreConversations,- has_more_artifacts: artifacts.length >= ARTIFACT_LIMIT,- artifacts: artifacts.map(queries.artifact.artifactToResponse),- flagged_message_ids: flaggedMessageIds,- active_task: activeTask ? taskToResponse(activeTask) : null,- task_messages: taskMessages,- cache_valid: cacheValid,- message_count: serverMessageCount,- ...(rootMessage ? { root_message: rootMessage } : {}),- });-});diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.tsdeleted file mode 100644index 870f2f52e..000000000--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts+++ /dev/null@@ -1,403 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetConversation = vi.fn();-const mockUpdateConversationTitle = vi.fn();-const mockListMessages = vi.fn();-const mockCreateMessage = vi.fn();-const mockEnqueueTask = vi.fn();-const mockMessageToResponse = vi.fn((m: any) => ({ id: m.id, content: m.content }));-const mockTaskToResponse = vi.fn((t: any) => ({ id: t.id, status: t.status }));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- const noop = () => {};- const log = { debug: noop, info: noop, warn: noop, error: noop, child: () => log };- return {- ...actual,- createDb: vi.fn(() => ({})),- createLogger: () => log,- TASK_TYPES: {- USER_DM_MESSAGE: "user_dm_message",- EMAIL_NOTIFICATION: "email_notification",- CALENDAR_EVENT: "calendar_event",- },- buildEmailMapKey: (agentId: string, threadId: string) => `email:${agentId}:${threadId}`,- queries: {- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- updateConversationTitle: (...args: any[]) => mockUpdateConversationTitle(...args),- },- message: {- listMessages: (...args: any[]) => mockListMessages(...args),- createMessage: (...args: any[]) => mockCreateMessage(...args),- updateMessageTaskId: vi.fn().mockResolvedValue(undefined),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- messageToResponse: (...args: any[]) => mockMessageToResponse(...args),- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));-vi.mock("@/lib/services/task", () => {- return {- TaskService: class {- enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }- },- };-});-vi.mock("@/lib/logger", () => ({- log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() },-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));--import { GET, POST } from "./route";--const withParams = (id: string) => ({ params: Promise.resolve({ id }) });--describe("GET /api/conversations/[id]/messages", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists messages", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- const msgs = [- { id: "m1", content: "Hello" },- { id: "m2", content: "World" },- ];- mockGetConversation.mockResolvedValue(conv);- mockListMessages.mockResolvedValue({ messages: msgs, has_more: false });-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/messages"),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({- messages: [- { id: "m1", content: "Hello" },- { id: "m2", content: "World" },- ],- has_more: false,- });- expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {- limit: undefined,- before: undefined,- beforeId: undefined,- });- });-- it("passes limit and before params when provided", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockListMessages.mockResolvedValue({ messages: [], has_more: false });-- const res = await GET(- new NextRequest(- "http://localhost/api/conversations/c1/messages?workspace_id=w1&limit=5&before=2024-01-01T00:00:00.000Z"- ),- withParams("c1")- );-- expect(res.status).toBe(200);- expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {- limit: 5,- before: "2024-01-01T00:00:00.000Z",- beforeId: undefined,- });- });-- it("passes before_id param for compound cursor", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockListMessages.mockResolvedValue({ messages: [], has_more: false });-- const res = await GET(- new NextRequest(- "http://localhost/api/conversations/c1/messages?workspace_id=w1&before=2024-01-01T00:00:00.000Z&before_id=m5"- ),- withParams("c1")- );-- expect(res.status).toBe(200);- expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {- limit: undefined,- before: "2024-01-01T00:00:00.000Z",- beforeId: "m5",- });- });-- it("clamps limit to max 100", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockListMessages.mockResolvedValue({ messages: [], has_more: false });-- await GET(- new NextRequest(- "http://localhost/api/conversations/c1/messages?workspace_id=w1&limit=999"- ),- withParams("c1")- );-- expect(mockListMessages).toHaveBeenCalledWith({}, "c1", {- limit: 100,- before: undefined,- beforeId: undefined,- });- });-- it("returns has_more true when more messages exist", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- const msgs = [{ id: "m1", content: "Hello" }];- mockGetConversation.mockResolvedValue(conv);- mockListMessages.mockResolvedValue({ messages: msgs, has_more: true });-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1/messages"),- withParams("c1")- );- const body = await res.json();-- expect(body.has_more).toBe(true);- expect(body.messages).toHaveLength(1);- });-});--describe("POST /api/conversations/[id]/messages", () => {- beforeEach(() => vi.clearAllMocks());-- it("sends message and enqueues task, returns 201", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- const msg = { id: "m1", content: "Hi there" };- const task = { id: "t1", status: "pending" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue(msg);- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue(task);-- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "Hi there" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(201);- expect(body.message).toEqual({ id: "m1", content: "Hi there" });- expect(body.task).toEqual({ id: "t1", status: "pending" });- expect(mockEnqueueTask).toHaveBeenCalledWith("a1", "c1", "w1", "Hi there", "user_dm_message", expect.objectContaining({ contextKey: "c1", traceId: expect.stringMatching(/^tr_/), parentTaskId: null }));- });-- it("auto-titles conversation with truncated first message", async () => {- const longContent = "A ".repeat(40).trim();- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue({ id: "m1", content: longContent });- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });-- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: longContent }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- const titleArg = mockUpdateConversationTitle.mock.calls[0][2] as string;- expect(titleArg.endsWith("...")).toBe(true);- expect(titleArg.length).toBeLessThanOrEqual(53);- });-- it("short messages are not truncated", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue({ id: "m1", content: "short" });- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });-- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "short" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- const titleArg = mockUpdateConversationTitle.mock.calls[0][2] as string;- expect(titleArg).toBe("short");- expect(titleArg.endsWith("...")).toBe(false);- });-- it("returns 400 for missing content", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);-- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("content"));- });-- it("returns 404 when conversation not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "hello" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-- it("returns a stable fallback when task enqueue rejects with a non-Error", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue({ id: "m1", content: "hello" });- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockRejectedValueOnce("queue unavailable");-- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "hello" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- expect(res.status).toBe(500);- expect(await res.json()).toEqual({- message: { id: "m1", content: "hello" },- task: null,- error: "Request failed",- });- });-- it("passes workspaceId to getConversation", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue({ id: "m1", content: "hello" });- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue({ id: "t1", status: "pending" });-- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "hello" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("TC2: passes metadata.quote to createMessage and adds quoted_message to task context", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- const msg = { id: "m1", content: "Can you fix this?" };- const task = { id: "t1", status: "pending" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue(msg);- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue(task);-- const res = await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({- content: "Can you fix this?",- metadata: { quote: { messageId: "msg_orig", excerpt: "The auth module has a bug" } },- }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- expect(res.status).toBe(201);- expect(mockCreateMessage).toHaveBeenCalledWith(- {},- expect.objectContaining({- content: "Can you fix this?",- metadata: JSON.stringify({ quote: { messageId: "msg_orig", excerpt: "The auth module has a bug" } }),- }),- );- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "c1", "w1", "Can you fix this?", "user_dm_message",- expect.objectContaining({- context: expect.objectContaining({- message_id: "m1",- quoted_message: { message_id: "msg_orig", excerpt: "The auth module has a bug" },- }),- }),- );- });-- it("TC3: message without metadata has no quote in metadata or task context", async () => {- const conv = { id: "c1", workspaceId: "w1", agentId: "a1", userId: "u1" };- const msg = { id: "m1", content: "Hello" };- const task = { id: "t1", status: "pending" };- mockGetConversation.mockResolvedValue(conv);- mockCreateMessage.mockResolvedValue(msg);- mockUpdateConversationTitle.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue(task);-- await POST(- new NextRequest("http://localhost/api/conversations/c1/messages", {- method: "POST",- body: JSON.stringify({ content: "Hello" }),- headers: { "Content-Type": "application/json" },- }),- withParams("c1")- );-- expect(mockCreateMessage).toHaveBeenCalledWith(- {},- expect.objectContaining({ metadata: null }),- );- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "c1", "w1", "Hello", "user_dm_message",- expect.objectContaining({- context: { message_id: "m1" },- }),- );- });-});diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.tsdeleted file mode 100644index 8b645efb6..000000000--- a/src/web/src/app/api/conversations/[id]/messages/route.ts+++ /dev/null@@ -1,259 +0,0 @@-import { NextRequest } from "next/server";-import { queries, TASK_TYPES, CreateMessageRequestSchema, parsePromptMentions, truncateTitle, stripMentionTokens } from "@alook/shared"-import { getDb } from "@/lib/db"-import { nanoid } from "nanoid";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { messageToResponse, taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { log } from "@/lib/logger";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB-const MAX_FILES = 10;--function sanitizeFilename(name: string): string {- return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";-}--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const url = new URL(req.url);- const aroundTask = url.searchParams.get("around_task");-- if (aroundTask) {- const messages = await queries.message.listMessagesAroundTask(db, id, aroundTask);- return writeJSON(messages.map(messageToResponse));- }-- const limitParam = url.searchParams.get("limit");- const before = url.searchParams.get("before") || undefined;- const beforeId = url.searchParams.get("before_id") || undefined;- const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 20, 1), 100) : undefined;-- const { messages, has_more } = await queries.message.listMessages(db, id, { limit, before, beforeId });- return writeJSON({ messages: messages.map(messageToResponse), has_more });-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)- const bucket = ctx.env.EMAIL_BUCKET;-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const contentType = req.headers.get("content-type") ?? "";- const isMultipart = contentType.includes("multipart/form-data");-- let content: string;- let messageMetadata: Record<string, unknown> | undefined;- const files: File[] = [];- const thumbnails = new Map<number, File>();-- if (isMultipart) {- let formData: FormData;- try {- formData = await req.formData();- } catch {- return writeError("invalid form data", 400);- }- content = (formData.get("content") as string) || "";- const metaRaw = formData.get("metadata") as string | null;- if (metaRaw) {- try { messageMetadata = JSON.parse(metaRaw); } catch { /* ignore malformed */ }- }- for (const [key, value] of formData.entries()) {- if (key === "file" && value instanceof File) {- files.push(value);- }- }- for (const [key, value] of formData.entries()) {- const m = key.match(/^thumbnail:(\d+)$/);- if (m && value instanceof File) thumbnails.set(Number(m[1]), value);- }- } else {- const [body, valErr] = await parseBody(req, CreateMessageRequestSchema);- if (valErr) return valErr;- content = body.content;- messageMetadata = body.metadata;- }-- if (isMultipart && !content) {- return writeError("content is required", 400);- }-- // Validate files before any uploads- if (files.length > MAX_FILES) {- return writeError(`too many files (max ${MAX_FILES})`, 400);- }- for (const file of files) {- if (file.size > MAX_FILE_SIZE) {- return writeError(`file "${file.name}" exceeds 10 MB limit`, 413);- }- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- // Upload files to R2 and create artifact rows- const artifactIds: string[] = [];- for (let fi = 0; fi < files.length; fi++) {- const file = files[fi];- const filename = sanitizeFilename(file.name);- const fileContentType = file.type || "application/octet-stream";- const artifactId = "art_" + nanoid();- const r2Key = `artifacts/${ws.workspaceId}/${conversation.agentId}/${id}/${artifactId}/${filename}`;-- await bucket.put(r2Key, await file.arrayBuffer(), {- httpMetadata: { contentType: fileContentType },- });-- let thumbnailR2Key: string | undefined;- const thumb = thumbnails.get(fi);- if (thumb && thumb.size <= 50 * 1024) {- thumbnailR2Key = `artifacts/${ws.workspaceId}/${conversation.agentId}/${id}/${artifactId}/thumbnail.jpg`;- await bucket.put(thumbnailR2Key, await thumb.arrayBuffer(), {- httpMetadata: { contentType: "image/jpeg" },- });- }-- await queries.artifact.createArtifact(db, {- id: artifactId,- conversationId: id,- agentId: conversation.agentId,- workspaceId: ws.workspaceId,- filename,- contentType: fileContentType,- size: file.size,- r2Key,- thumbnailR2Key,- source: "attachment",- });-- artifactIds.push(artifactId);- }-- const message = await queries.message.createMessage(db, {- conversationId: id,- role: "user",- content,- attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,- metadata: messageMetadata ? JSON.stringify(messageMetadata) : null,- });-- broadcastToUser(ctx.userId, {- type: "conversation.message",- conversationId: id,- message: messageToResponse(message),- }).catch(() => {});-- // If this is a thread conversation, broadcast thread.reply with actual count- if (conversation.parentMessageId) {- queries.message.getActiveMessageCount(db, id).then((count) => {- broadcastToUser(ctx.userId, {- type: "thread.reply",- conversationId: id,- threadConversationId: id,- parentMessageId: conversation.parentMessageId!,- replyCount: count,- }).catch(() => {});- }).catch(() => {});- }-- // Auto-title: conditional WHERE title = '' ensures only the first message sets it- queries.conversation.updateConversationTitle(db, id, truncateTitle(stripMentionTokens(content))).catch(() => {});-- let enrichedContent = content;- let mentionContext: Record<string, unknown> | undefined;- if (content.includes("@")) {- try {- const agentList = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);- const { enrichedPrompt, mentions } = parsePromptMentions(content, agentList);- enrichedContent = enrichedPrompt;- if (mentions.length > 0) {- const seen = new Set<string>();- const uniqueMentions = mentions.filter(m => {- if (seen.has(m.name)) return false;- seen.add(m.name);- return true;- });- mentionContext = {- mentioned_agents: uniqueMentions.map(m => ({- name: m.name,- email: m.email,- ...(m.description ? { description: m.description } : {}),- })),- };- }- } catch {- // Fail-open: if agent query fails, pass content through unmodified- }- }-- const contextKey = id;- const quote = messageMetadata?.quote as { messageId?: string; excerpt?: string } | undefined;- const taskContext: Record<string, unknown> = {- message_id: message.id,- ...(artifactIds.length > 0 ? { attachment_ids: artifactIds } : {}),- ...mentionContext,- ...(quote ? { quoted_message: { message_id: quote.messageId, excerpt: quote.excerpt } } : {}),- };- const traceId = "tr_" + nanoid();- const taskService = new TaskService(db);- try {- const task = await taskService.enqueueTask(- conversation.agentId,- id,- ws.workspaceId,- enrichedContent,- TASK_TYPES.USER_DM_MESSAGE,- {- contextKey,- context: Object.keys(taskContext).length > 0 ? taskContext : undefined,- traceId,- parentTaskId: null,- },- );- queries.message.updateMessageTaskId(db, message.id, task.id).catch(() => {});- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});- return writeJSON(- { message: messageToResponse(message), task: taskToResponse(task) },- 201- );- } catch (err: unknown) {- log.error("enqueueTask error", { err });- return writeJSON(- {- message: messageToResponse(message),- task: null,- error: err instanceof Error ? err.message : "Request failed",- },- 500- );- }-});diff --git a/src/web/src/app/api/conversations/[id]/route.test.ts b/src/web/src/app/api/conversations/[id]/route.test.tsdeleted file mode 100644index 6e9975a94..000000000--- a/src/web/src/app/api/conversations/[id]/route.test.ts+++ /dev/null@@ -1,130 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetConversation = vi.fn();-const mockDeleteConversation = vi.fn();-const mockDeleteTasksByConversation = vi.fn();-const mockDeleteUnreadByConversation = vi.fn();-const mockConversationToResponse = vi.fn((c: any) => ({ id: c.id, title: c.title }));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- deleteConversation: (...args: any[]) => mockDeleteConversation(...args),- },- task: {- deleteTasksByConversation: (...args: any[]) => mockDeleteTasksByConversation(...args),- },- inbox: {- deleteUnreadByConversation: (...args: any[]) => mockDeleteUnreadByConversation(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: (...args: any[]) => mockConversationToResponse(...args),-}));--import { GET, DELETE } from "./route";--const withParams = (id: string) => ({ params: Promise.resolve({ id }) });--describe("GET /api/conversations/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns conversation scoped by workspaceId", async () => {- const conv = { id: "c1", title: "Test", workspaceId: "w1", userId: "u1" };- mockGetConversation.mockResolvedValue(conv);-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1"),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "c1", title: "Test" });- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("returns 404 when not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/conversations/c1"),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});--describe("DELETE /api/conversations/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 204 and removes conversation + tasks with workspace scoping", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockDeleteTasksByConversation.mockResolvedValue(undefined);- mockDeleteConversation.mockResolvedValue(undefined);-- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- withParams("c1")- );-- expect(res.status).toBe(204);- expect(mockDeleteTasksByConversation).toHaveBeenCalledWith({}, "c1", "w1");- expect(mockDeleteConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("deletes tasks before conversation", async () => {- const callOrder: string[] = [];- mockGetConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "u1" });- mockDeleteTasksByConversation.mockImplementation(async () => {- callOrder.push("tasks");- });- mockDeleteUnreadByConversation.mockImplementation(async () => {- callOrder.push("unread");- });- mockDeleteConversation.mockImplementation(async () => {- callOrder.push("conversation");- });-- await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- withParams("c1")- );-- expect(callOrder).toEqual(["tasks", "unread", "conversation"]);- });-- it("returns 404 when conversation not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await DELETE(- new NextRequest("http://localhost/api/conversations/c1", { method: "DELETE" }),- withParams("c1")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});diff --git a/src/web/src/app/api/conversations/[id]/route.ts b/src/web/src/app/api/conversations/[id]/route.tsdeleted file mode 100644index eb41ce01c..000000000--- a/src/web/src/app/api/conversations/[id]/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- return writeJSON(conversationToResponse(conversation));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const conversation = await queries.conversation.getConversation(db, id, ws.workspaceId);- if (!conversation || conversation.userId !== ctx.userId) {- return writeError("not found", 404);- }-- // Delete tasks first (no cascade on FK)- await queries.task.deleteTasksByConversation(db, id, ws.workspaceId);- await queries.inbox.deleteUnreadByConversation(db, id);- await queries.conversation.deleteConversation(db, id, ws.workspaceId);-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.tsdeleted file mode 100644index 3b3de5237..000000000--- a/src/web/src/app/api/conversations/[id]/threads/route.ts+++ /dev/null@@ -1,239 +0,0 @@-import { queries, TASK_TYPES, truncateTitle, CreateThreadRequestSchema, isUniqueConstraintError } from "@alook/shared";-import { getDb } from "@/lib/db";-import { nanoid } from "nanoid";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { conversationToResponse, messageToResponse, taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { log } from "@/lib/logger";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const conversationId = ctx.params?.id;- if (!conversationId) {- return writeError("conversation id is required", 400);- }-- const [body, valErr] = await parseBody(req, CreateThreadRequestSchema);- if (valErr) return valErr;-- const parentConv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);- if (!parentConv || parentConv.userId !== ctx.userId) {- return writeError("not found", 404);- }-- const rootMessage = await queries.message.getMessage(db, body.parent_message_id);- if (!rootMessage || rootMessage.conversationId !== conversationId) {- return writeError("parent message not found in this conversation", 404);- }-- // Idempotent: check if thread already exists for this parent_message_id- const existing = await queries.conversation.getThreadByParentMessage(- db, body.parent_message_id, ws.workspaceId- );- if (existing) {- // Thread already exists — create message in the existing thread and enqueue task- const msgCount = await queries.message.getActiveMessageCount(db, existing.id);-- const threadMessage = await queries.message.createMessage(db, {- conversationId: existing.id,- role: "user",- content: body.content,- });-- broadcastToUser(ctx.userId, {- type: "conversation.message",- conversationId: existing.id,- message: messageToResponse(threadMessage),- }).catch(() => {});-- let taskContext: Record<string, unknown> = { message_id: threadMessage.id };- if (msgCount === 0) {- const historyMessages = await queries.message.listMessagesUpTo(- db, conversationId, body.parent_message_id- );- const rootMsg = historyMessages.find(m => m.id === body.parent_message_id);- const historyWithoutRoot = historyMessages- .filter(m => m.id !== body.parent_message_id)- .map(m => ({ role: m.role, content: m.content, created_at: m.createdAt }));- const rootMessageContext = rootMsg- ? { role: rootMsg.role, content: rootMsg.content }- : null;- taskContext = {- message_id: threadMessage.id,- conversation_history: historyWithoutRoot,- ...(rootMessageContext ? { root_message: rootMessageContext } : {}),- };- }-- const taskService = new TaskService(db);- const traceId = "tr_" + nanoid();- try {- const task = await taskService.enqueueTask(- parentConv.agentId,- existing.id,- ws.workspaceId,- body.content,- TASK_TYPES.USER_DM_MESSAGE,- {- contextKey: existing.id,- context: taskContext,- traceId,- parentTaskId: null,- },- );- queries.message.updateMessageTaskId(db, threadMessage.id, task.id).catch(() => {});- return writeJSON({- conversation: conversationToResponse(existing),- message: messageToResponse(threadMessage),- task: taskToResponse(task),- }, 200);- } catch (err: unknown) {- log.error("enqueueTask error (thread)", { err });- return writeError("failed to enqueue task", 500);- }- }-- // Create new thread conversation (catch unique-violation from concurrent requests)- const threadTitle = truncateTitle(rootMessage.content).slice(0, 80);- let threadConv;- try {- threadConv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: parentConv.agentId,- userId: ctx.userId,- title: "",- type: TASK_TYPES.USER_DM_MESSAGE,- channel: parentConv.channel ?? "default",- parentMessageId: body.parent_message_id,- threadTitle,- });- } catch (err) {- if (!isUniqueConstraintError(err)) throw err;- const raced = await queries.conversation.getThreadByParentMessage(- db, body.parent_message_id, ws.workspaceId- );- if (!raced) throw err;- threadConv = raced;- }-- broadcastToUser(ctx.userId, {- type: "thread.created",- conversationId,- threadConversationId: threadConv.id,- parentMessageId: body.parent_message_id,- threadTitle,- }).catch(() => {});-- // If no content, return just the conversation (eager creation, no message/task)- if (!body.content) {- return writeJSON({ conversation: conversationToResponse(threadConv), message: null, task: null }, 201);- }-- // Fetch parent conversation history up to and including root message- const historyMessages = await queries.message.listMessagesUpTo(- db, conversationId, body.parent_message_id- );- const rootMsg = historyMessages.find(m => m.id === body.parent_message_id);- const historyWithoutRoot = historyMessages- .filter(m => m.id !== body.parent_message_id)- .map(m => ({ role: m.role, content: m.content, created_at: m.createdAt }));- const rootMessageContext = rootMsg- ? { role: rootMsg.role, content: rootMsg.content }- : null;-- // Create user message in thread- const threadMessage = await queries.message.createMessage(db, {- conversationId: threadConv.id,- role: "user",- content: body.content,- });-- broadcastToUser(ctx.userId, {- type: "conversation.message",- conversationId: threadConv.id,- message: messageToResponse(threadMessage),- }).catch(() => {});-- const taskContext: Record<string, unknown> = {- message_id: threadMessage.id,- conversation_history: historyWithoutRoot,- ...(rootMessageContext ? { root_message: rootMessageContext } : {}),- };-- const traceId = "tr_" + nanoid();- const taskService = new TaskService(db);- try {- const task = await taskService.enqueueTask(- parentConv.agentId,- threadConv.id,- ws.workspaceId,- body.content,- TASK_TYPES.USER_DM_MESSAGE,- {- contextKey: threadConv.id,- context: taskContext,- traceId,- parentTaskId: null,- },- );-- queries.message.updateMessageTaskId(db, threadMessage.id, task.id).catch(() => {});-- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});-- return writeJSON({- conversation: conversationToResponse(threadConv),- message: messageToResponse(threadMessage),- task: taskToResponse(task),- }, 201);- } catch (err: unknown) {- log.error("enqueueTask error (thread create)", { err });- return writeError("failed to enqueue task", 500);- }-});--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const conversationId = ctx.params?.id;- if (!conversationId) {- return writeError("conversation id is required", 400);- }-- const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);- if (!conv || conv.userId !== ctx.userId) {- return writeError("not found", 404);- }-- try {- const threads = await queries.conversation.getThreadsByConversation(- db, ws.workspaceId, conversationId- );-- const summaries = threads.map(t => ({- thread_id: t.id,- parent_message_id: t.parentMessageId,- thread_title: t.threadTitle,- reply_count: t.replyCount,- last_reply_at: t.lastReplyAt,- created_at: t.createdAt,- }));-- return writeJSON({ thread_summaries: summaries });- } catch (err: unknown) {- log.error("getThreadsByConversation error", { err });- return writeError("failed to fetch thread summaries", 500);- }-});diff --git a/src/web/src/app/api/conversations/check-fresh/route.test.ts b/src/web/src/app/api/conversations/check-fresh/route.test.tsdeleted file mode 100644index 3cebdf24c..000000000--- a/src/web/src/app/api/conversations/check-fresh/route.test.ts+++ /dev/null@@ -1,88 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetConversation = vi.fn();-const mockGetOrCreate = vi.fn();-const mockGetNewestMessageId = vi.fn();-const mockGetActiveMessageCount = vi.fn();--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- conversation: {- getConversation: (...a: unknown[]) => mockGetConversation(...a),- getOrCreateAgentConversation: (...a: unknown[]) => mockGetOrCreate(...a),- },- message: {- getNewestMessageId: (...a: unknown[]) => mockGetNewestMessageId(...a),- getActiveMessageCount: (...a: unknown[]) => mockGetActiveMessageCount(...a),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/conversations/check-fresh", () => {- it("returns freshness for an existing conversation_id (scoped to workspace)", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });- mockGetNewestMessageId.mockResolvedValue("m9");- mockGetActiveMessageCount.mockResolvedValue(3);-- const req = new NextRequest("http://localhost/api/conversations/check-fresh?conversation_id=c1");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ conversation_id: "c1", newest_message_id: "m9", message_count: 3 });- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("404 when conversation_id not found in workspace", async () => {- mockGetConversation.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/conversations/check-fresh?conversation_id=cX");- const res = await GET(req, {});- expect(res.status).toBe(404);- expect((await res.json()).error).toBe("not found");- });-- it("resolves via agent_id when no conversation_id given", async () => {- mockGetOrCreate.mockResolvedValue({ id: "c2" });- mockGetNewestMessageId.mockResolvedValue(null);- mockGetActiveMessageCount.mockResolvedValue(0);-- const req = new NextRequest("http://localhost/api/conversations/check-fresh?agent_id=a1&channel=general");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.conversation_id).toBe("c2");- expect(mockGetOrCreate).toHaveBeenCalledWith({}, "w1", "u1", "a1", "general");- });-- it("400 when neither conversation_id nor agent_id provided", async () => {- const req = new NextRequest("http://localhost/api/conversations/check-fresh");- const res = await GET(req, {});- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("conversation_id or agent_id is required");- });-});diff --git a/src/web/src/app/api/conversations/check-fresh/route.ts b/src/web/src/app/api/conversations/check-fresh/route.tsdeleted file mode 100644index de634e621..000000000--- a/src/web/src/app/api/conversations/check-fresh/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const url = new URL(req.url);- const conversationId = url.searchParams.get("conversation_id");- const agentId = url.searchParams.get("agent_id");- const channel = url.searchParams.get("channel") || undefined;-- let convId: string;-- if (conversationId) {- const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);- if (!conv || conv.userId !== ctx.userId) {- return writeError("not found", 404);- }- convId = conv.id;- } else if (agentId) {- const conv = await queries.conversation.getOrCreateAgentConversation(- db,- ws.workspaceId,- ctx.userId,- agentId,- channel,- );- convId = conv.id;- } else {- return writeError("conversation_id or agent_id is required", 400);- }-- const [newestMessageId, messageCount] = await Promise.all([- queries.message.getNewestMessageId(db, convId),- queries.message.getActiveMessageCount(db, convId),- ]);-- return writeJSON({- conversation_id: convId,- newest_message_id: newestMessageId,- message_count: messageCount,- });-});diff --git a/src/web/src/app/api/conversations/route.test.ts b/src/web/src/app/api/conversations/route.test.tsdeleted file mode 100644index 57591ed5f..000000000--- a/src/web/src/app/api/conversations/route.test.ts+++ /dev/null@@ -1,118 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListConversations = vi.fn();-const mockCreateConversation = vi.fn();-const mockConversationToResponse = vi.fn((c: any) => ({ id: c.id, title: c.title }));--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- conversation: {- listConversations: (...args: any[]) => mockListConversations(...args),- createConversation: (...args: any[]) => mockCreateConversation(...args),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- conversationToResponse: (...args: any[]) => mockConversationToResponse(...args),-}));--import { GET, POST } from "./route";--describe("GET /api/conversations", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists conversations", async () => {- const convs = [- { id: "c1", title: "Hello" },- { id: "c2", title: "World" },- ];- mockListConversations.mockResolvedValue(convs);-- const res = await GET(new NextRequest("http://localhost/api/conversations"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "c1", title: "Hello" },- { id: "c2", title: "World" },- ]);- expect(mockListConversations).toHaveBeenCalledWith({}, "w1", "u1", undefined);- });-});--describe("POST /api/conversations", () => {- beforeEach(() => vi.clearAllMocks());-- it("creates a conversation with agent_id", async () => {- const conv = { id: "c1", title: "" };- mockCreateConversation.mockResolvedValue(conv);-- const res = await POST(- new NextRequest("http://localhost/api/conversations", {- method: "POST",- body: JSON.stringify({ agent_id: "a1" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({ id: "c1", title: "" });- expect(mockCreateConversation).toHaveBeenCalledWith({}, {- workspaceId: "w1",- agentId: "a1",- userId: "u1",- title: "",- channel: undefined,- });- });-- it("returns 400 for missing agent_id", async () => {- const res = await POST(- new NextRequest("http://localhost/api/conversations", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("agent_id"));- });-- it("returns 400 for invalid body", async () => {- const res = await POST(- new NextRequest("http://localhost/api/conversations", {- method: "POST",- body: "not json",- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });-});diff --git a/src/web/src/app/api/conversations/route.ts b/src/web/src/app/api/conversations/route.tsdeleted file mode 100644index 8be82a92f..000000000--- a/src/web/src/app/api/conversations/route.ts+++ /dev/null@@ -1,44 +0,0 @@-import { NextRequest } from "next/server";-import { queries, CreateConversationRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, parseBody } from "@/lib/middleware/helpers";-import { conversationToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const channel = new URL(req.url).searchParams.get("channel") || undefined;-- const conversations = await queries.conversation.listConversations(- db,- ws.workspaceId,- ctx.userId,- channel- );- return writeJSON(conversations.map(conversationToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const [body, valErr] = await parseBody(req, CreateConversationRequestSchema);- if (valErr) return valErr;-- const conversation = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: body.agent_id,- userId: ctx.userId,- title: "",- channel: body.channel,- });-- return writeJSON(conversationToResponse(conversation), 201);-});diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.tsdeleted file mode 100644index f52757b26..000000000--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.test.ts+++ /dev/null@@ -1,155 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const m = {- getConversation: vi.fn(),- createMessage: vi.fn(),- updateConversationTitle: vi.fn(),- updateUnreadLatestMessage: vi.fn().mockResolvedValue(undefined),-};--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- conversation: {- getConversation: (...a: unknown[]) => m.getConversation(...a),- updateConversationTitle: (...a: unknown[]) => m.updateConversationTitle(...a),- },- message: {- createMessage: (...a: unknown[]) => m.createMessage(...a),- },- inbox: {- updateUnreadLatestMessage: (...a: unknown[]) => m.updateUnreadLatestMessage(...a),- },- },- };-});--// Faithful auth realm: a machine token (al_...) sets ctx.workspaceId; a user-// session/JWT does NOT. This lets us exercise the route's 403 daemon-only guard.-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- const auth = (req.headers?.get?.("Authorization") as string) || "";- const isMachine = auth.startsWith("Bearer al_");- return handler(req, {- env: { DB: {} },- userId: "u1",- email: "[email protected]",- workspaceId: isMachine ? "w1" : undefined,- params,- });- }),-}));--const broadcastToUser = vi.fn().mockResolvedValue(undefined);-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...a: unknown[]) => broadcastToUser(...a),-}));-vi.mock("@/lib/api/responses", () => ({- messageToResponse: (msg: any) => ({ id: msg.id, content: msg.content, role: msg.role }),-}));--import { POST } from "./route";--function makeReq(body: unknown, opts?: { machine?: boolean }) {- return new NextRequest("http://localhost/api/daemon/conversations/c1/messages", {- method: "POST",- headers: {- "content-type": "application/json",- Authorization: opts?.machine === false ? "Bearer session-jwt" : "Bearer al_token",- },- body: JSON.stringify(body),- });-}--beforeEach(() => {- vi.clearAllMocks();- m.getConversation.mockResolvedValue({ id: "c1", workspaceId: "w1", userId: "owner-1" });- m.createMessage.mockImplementation((_db: unknown, data: any) => ({- id: "msg-1",- ...data,- }));- m.updateConversationTitle.mockResolvedValue(null);-});--describe("POST /api/daemon/conversations/[id]/messages", () => {- // TC1- it("creates one role:assistant message with taskId + metadata.kind=dm and broadcasts (201)", async () => {- const res = await POST(makeReq({ content: "hello", task_id: "t1" }), { params: { id: "c1" } });- expect(res.status).toBe(201);- const body = await res.json();- expect(body.message.content).toBe("hello");-- expect(m.createMessage).toHaveBeenCalledTimes(1);- const [, data] = m.createMessage.mock.calls[0];- expect(data.role).toBe("assistant");- expect(data.content).toBe("hello");- expect(data.taskId).toBe("t1");- expect(JSON.parse(data.metadata)).toEqual({ kind: "dm" });-- // Broadcast targets the conversation owner, not the token owner.- expect(broadcastToUser).toHaveBeenCalledTimes(1);- const [target, payload] = broadcastToUser.mock.calls[0];- expect(target).toBe("owner-1");- expect(payload.type).toBe("conversation.message");- expect(payload.conversationId).toBe("c1");- });-- it("auto-titles the conversation from the message content", async () => {- await POST(makeReq({ content: "Summarize the backlog" }), { params: { id: "c1" } });- expect(m.updateConversationTitle).toHaveBeenCalledWith({}, "c1", "Summarize the backlog");- });-- it("does not require a task_id (taskId null)", async () => {- const res = await POST(makeReq({ content: "no task" }), { params: { id: "c1" } });- expect(res.status).toBe(201);- const [, data] = m.createMessage.mock.calls[0];- expect(data.taskId).toBeNull();- });-- // TC4 — foreign-workspace conversation id → 404 (scoped-ahead, no leak)- it("404 when conversation is not in the token's workspace", async () => {- m.getConversation.mockResolvedValue(null);- const res = await POST(makeReq({ content: "x" }), { params: { id: "other" } });- expect(res.status).toBe(404);- expect(m.createMessage).not.toHaveBeenCalled();- expect(broadcastToUser).not.toHaveBeenCalled();- });-- // TC5 — a user JWT (no workspaceId) → 403 daemon-only- it("403 when called without a machine token (no workspaceId)", async () => {- const res = await POST(makeReq({ content: "x" }, { machine: false }), { params: { id: "c1" } });- expect(res.status).toBe(403);- expect(m.getConversation).not.toHaveBeenCalled();- expect(m.createMessage).not.toHaveBeenCalled();- });-- // TC7 — empty content rejected by schema (min length)- it("400 when content is empty (schema min length)", async () => {- const res = await POST(makeReq({ content: "" }), { params: { id: "c1" } });- expect(res.status).toBe(400);- expect(m.createMessage).not.toHaveBeenCalled();- });-- // TC6 — two sends in one task → two distinct rows, both broadcast- it("supports multiple sends in one task (each is its own message + broadcast)", async () => {- await POST(makeReq({ content: "on it", task_id: "t1" }), { params: { id: "c1" } });- await POST(makeReq({ content: "done", task_id: "t1" }), { params: { id: "c1" } });- expect(m.createMessage).toHaveBeenCalledTimes(2);- expect(broadcastToUser).toHaveBeenCalledTimes(2);- const first = m.createMessage.mock.calls[0][1];- const second = m.createMessage.mock.calls[1][1];- expect(first.taskId).toBe("t1");- expect(second.taskId).toBe("t1");- expect(first.content).toBe("on it");- expect(second.content).toBe("done");- });-});diff --git a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts b/src/web/src/app/api/daemon/conversations/[id]/messages/route.tsdeleted file mode 100644index 41677869b..000000000--- a/src/web/src/app/api/daemon/conversations/[id]/messages/route.ts+++ /dev/null@@ -1,57 +0,0 @@-import { NextRequest } from "next/server";-import { queries, AgentDmRequestSchema, truncateTitle } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { messageToResponse } from "@/lib/api/responses";-import { broadcastToUser } from "@/lib/broadcast";--// Agent-authored DM endpoint (`alook sync send-dm`). The agent calls this to-// push exactly what the user should see — a `role:"assistant"` chat bubble that-// lands live in the open chat. Machine-token auth only (mirrors the other-// daemon routes); explicitly does NOT enqueue a task (unlike the user-send-// route at /api/conversations/[id]/messages, which would spawn another run).-export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("conversation id is required", 400);- }-- const [body, err] = await parseBody(req, AgentDmRequestSchema);- if (err) return err;-- // Scope-ahead: resolve the conversation by workspace id, never check ownership- // after (AGENTS.md rule). A foreign-workspace id simply 404s — no leak.- const conversation = await queries.conversation.getConversation(db, id, ctx.workspaceId);- if (!conversation) {- return writeError("conversation not found", 404);- }-- const message = await queries.message.createMessage(db, {- conversationId: id,- role: "assistant",- content: body.content,- taskId: body.task_id ?? null,- metadata: JSON.stringify({ kind: "dm" }),- });-- // Auto-title if still untitled — parity with the user-send route. The query's- // conditional WHERE title = '' makes this a no-op once a title exists.- queries.conversation.updateConversationTitle(db, id, truncateTitle(body.content)).catch(() => {});-- broadcastToUser(conversation.userId, {- type: "conversation.message",- conversationId: id,- message: messageToResponse(message),- }).catch(() => {});-- queries.inbox.updateUnreadLatestMessage(db, id, conversation.userId, message.id).catch(() => {});-- return writeJSON({ message: messageToResponse(message) }, 201);-});diff --git a/src/web/src/app/api/daemon/deregister/route.test.ts b/src/web/src/app/api/daemon/deregister/route.test.tsdeleted file mode 100644index e4e2b0a42..000000000--- a/src/web/src/app/api/daemon/deregister/route.test.ts+++ /dev/null@@ -1,130 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockSetMachineLastSeenNull = vi.fn();-const mockBroadcastToUser = vi.fn();--function sharedMocks() {- return {- "@opennextjs/cloudflare": {- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),- },- "@alook/shared": async () => ({- createDb: vi.fn(() => ({})),- queries: {- machine: {- setMachineLastSeenNull: (...a: any[]) =>- mockSetMachineLastSeenNull(...a),- },- },- DeregisterRequestSchema: (await import("@alook/shared"))- .DeregisterRequestSchema,- }),- "@/lib/broadcast": {- broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),- },- };-}--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/deregister", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/deregister", () => {- beforeEach(() => vi.clearAllMocks());-- async function loadRoute(authCtx: Record<string, unknown>) {- vi.resetModules();-- const mocks = sharedMocks();-- vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);- vi.doMock("@alook/shared", mocks["@alook/shared"]);- vi.doMock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),- }));- vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);- vi.doMock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },- }));- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...authCtx, params });- }),- }));- vi.doMock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );- });-- const { POST } = await import("./route");- return POST;- }-- const daemonAuth = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- const jwtAuth = { env: {}, userId: "u1", email: "[email protected]" };-- it("sets machine last_seen_at to null", async () => {- const POST = await loadRoute(daemonAuth);-- mockSetMachineLastSeenNull.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ status: "ok" });- // Single machine write instead of N runtime writes- expect(mockSetMachineLastSeenNull).toHaveBeenCalledTimes(1);- expect(mockSetMachineLastSeenNull).toHaveBeenCalledWith({}, "d1", "w1");- });-- it("sends single broadcast with daemonId and workspaceId", async () => {- const POST = await loadRoute(daemonAuth);-- mockSetMachineLastSeenNull.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- await POST(makeReq({ daemon_id: "d1" }));-- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "offline",- });- });-- it("returns 403 when called without workspaceId", async () => {- const POST = await loadRoute(jwtAuth);-- const res = await POST(makeReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toContain("machine token required");- });-- it("still returns ok when setMachineLastSeenNull fails (D1 transient error)", async () => {- const POST = await loadRoute(daemonAuth);-- mockSetMachineLastSeenNull.mockRejectedValue(new Error("D1 timeout"));- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ status: "ok" });- });-});diff --git a/src/web/src/app/api/daemon/deregister/route.ts b/src/web/src/app/api/daemon/deregister/route.tsdeleted file mode 100644index 7a0a8d3b1..000000000--- a/src/web/src/app/api/daemon/deregister/route.ts+++ /dev/null@@ -1,45 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { DeregisterRequestSchema } from "@alook/shared";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const [body, err] = await parseBody(req, DeregisterRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- // Set machine last_seen_at to null — non-critical, daemon is already shutting down- try {- await queries.machine.setMachineLastSeenNull(- db,- body.daemon_id,- ctx.workspaceId,- );- } catch (e) {- log.warn("deregister: setMachineLastSeenNull failed", { daemonId: body.daemon_id, err: String(e) });- }-- await Promise.all([- invalidate(cacheKeys.runtimeIds(ctx.workspaceId, body.daemon_id)),- ]);-- // Single broadcast at daemon level- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId,- status: "offline",- }).catch(() => {});-- return writeJSON({ status: "ok" });-});diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.tsdeleted file mode 100644index b242b121b..000000000--- a/src/web/src/app/api/daemon/heartbeat/route.test.ts+++ /dev/null@@ -1,161 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockUpsertMachine = vi.fn();-const mockGetMachineByDaemon = vi.fn();-const mockBroadcastToUser = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {} },- })),-}));--vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),-}));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- machine: {- upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),- getMachineByDaemon: (...args: unknown[]) => mockGetMachineByDaemon(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--import { POST } from "./route";--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/heartbeat", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/heartbeat", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetMachineByDaemon.mockResolvedValue(null);- mockUpsertMachine.mockResolvedValue({});- mockBroadcastToUser.mockResolvedValue(undefined);- });-- it("returns 400 when daemon_id is missing", async () => {- const res = await POST(postReq({}));- expect(res.status).toBe(400);- });-- it("returns 400 when daemon_id is empty", async () => {- const res = await POST(postReq({ daemon_id: "" }));- expect(res.status).toBe(400);- });-- it("returns ok: true on valid request", async () => {- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- });-- it("upserts machine in D1 on every heartbeat", async () => {- await POST(postReq({ daemon_id: "d1" }));-- expect(mockUpsertMachine).toHaveBeenCalledWith({}, {- daemonId: "d1",- workspaceId: "w1",- deviceInfo: "d1",- ownerId: "u1",- });- });-- it("broadcasts runtime.status when daemon transitions from offline to online", async () => {- mockGetMachineByDaemon.mockResolvedValue(null);- await POST(postReq({ daemon_id: "d1" }));-- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "online",- });- });-- it("broadcasts when last_seen_at exceeds offline threshold", async () => {- mockGetMachineByDaemon.mockResolvedValue({ lastSeenAt: new Date(Date.now() - 30_000).toISOString() });- await POST(postReq({ daemon_id: "d1" }));-- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({- type: "runtime.status",- status: "online",- }));- });-- it("does not broadcast when daemon was already online", async () => {- mockGetMachineByDaemon.mockResolvedValue({ lastSeenAt: new Date().toISOString() });- await POST(postReq({ daemon_id: "d1" }));-- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-- it("does not fail when upsertMachine throws", async () => {- mockUpsertMachine.mockRejectedValue(new Error("D1 timeout"));-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- });-- it("requires machine token (workspaceId must be present)", async () => {- vi.resetModules();-- vi.doMock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),- }));- vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return { ...real, queries: { machine: { upsertMachine: vi.fn(), getMachineByDaemon: vi.fn() } } };- });- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { env: {}, userId: "u1", email: "[email protected]" });- }),- }));- vi.doMock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")- );- vi.doMock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn() }));- vi.doMock("@/lib/logger", () => ({ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));-- const { POST: POST2 } = await import("./route");- const res = await POST2(postReq({ daemon_id: "d1" }));- expect(res.status).toBe(403);- });-});diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.tsdeleted file mode 100644index bfb5da443..000000000--- a/src/web/src/app/api/daemon/heartbeat/route.ts+++ /dev/null@@ -1,45 +0,0 @@-import { NextRequest } from "next/server";-import { queries, HeartbeatRequestSchema, OFFLINE_THRESHOLD_MS } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { broadcastToUser } from "@/lib/broadcast";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {-- const [body, err] = await parseBody(req, HeartbeatRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB);- let wasOffline = false;- try {- const existing = await queries.machine.getMachineByDaemon(db, body.daemon_id, ctx.workspaceId!);- if (!existing || !existing.lastSeenAt || Date.now() - new Date(existing.lastSeenAt).getTime() >= OFFLINE_THRESHOLD_MS) {- wasOffline = true;- }- await queries.machine.upsertMachine(db, {- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId!,- deviceInfo: body.daemon_id,- ownerId: ctx.userId,- });- } catch (e) {- log.warn("heartbeat: machine upsert failed", { daemonId: body.daemon_id, err: String(e) });- }-- if (wasOffline) {- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId,- status: "online",- }).catch(() => {});- }-- return writeJSON({ ok: true });-});diff --git a/src/web/src/app/api/daemon/register/route.test.ts b/src/web/src/app/api/daemon/register/route.test.tsdeleted file mode 100644index 8f8364e90..000000000--- a/src/web/src/app/api/daemon/register/route.test.ts+++ /dev/null@@ -1,324 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetMember = vi.fn();-const mockUpsertMachine = vi.fn();-const mockUpsertAgentRuntime = vi.fn();-const mockGetMachineByDaemon = vi.fn();-const mockClearPendingUpdateVersion = vi.fn();-const mockBroadcastToUser = vi.fn();--function sharedMocks() {- return {- "@opennextjs/cloudflare": {- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),- },- "@alook/shared": async () => {- const real = await import("@alook/shared");- return {- createDb: vi.fn(() => ({})),- semverGte: real.semverGte,- queries: {- member: {- getMemberByUserAndWorkspace: (...a: any[]) => mockGetMember(...a),- },- machine: {- upsertMachine: (...a: any[]) => mockUpsertMachine(...a),- getMachineByDaemon: (...a: any[]) => mockGetMachineByDaemon(...a),- clearPendingUpdateVersion: (...a: any[]) => mockClearPendingUpdateVersion(...a),- },- runtime: {- upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),- },- },- RegisterDaemonRequestSchema: real.RegisterDaemonRequestSchema,- generateWorkspaceSlug: real.generateWorkspaceSlug,- };- },- "@/lib/broadcast": {- broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),- },- "@/lib/api/responses": {- runtimeToResponse: (rt: any) => ({ id: rt.id }),- },- };-}--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/register", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/register", () => {- beforeEach(() => vi.clearAllMocks());-- async function loadRoute(authCtx: Record<string, unknown>) {- vi.resetModules();-- const mocks = sharedMocks();-- vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);- vi.doMock("@alook/shared", mocks["@alook/shared"]);- vi.doMock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),- }));- vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);- vi.doMock("@/lib/api/responses", () => mocks["@/lib/api/responses"]);- vi.doMock("@/lib/cache", () => ({- invalidate: vi.fn(),- cacheKeys: {- runtimeIds: (...a: any[]) => a.join(":"),- allRuntimes: (ws: string) => `runtimes:${ws}`,- },- }));- vi.doMock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },- }));- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...authCtx, params });- }),- }));- vi.doMock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );- });-- const { POST } = await import("./route");- return POST;- }-- const validBody = {- workspace_id: "w1",- daemon_id: "d1",- device_name: "MyMachine",- cli_version: "0.0.2",- runtimes: [- { type: "claude", version: "1.0", runtime_mode: "local" },- ],- };-- const authCtx = { env: {}, userId: "u1", email: "[email protected]" };-- it("upserts machine + runtimes and returns 200", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ runtimes: [{ id: "r1" }], workspaceId: "w1" });- expect(mockUpsertMachine).toHaveBeenCalledTimes(1);- expect(mockUpsertAgentRuntime).toHaveBeenCalledTimes(1);- });-- it("broadcasts only runtime.registered after upserts when no pending update", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockGetMachineByDaemon.mockResolvedValue(null);- mockBroadcastToUser.mockResolvedValue(undefined);-- await POST(makeReq(validBody));-- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.registered",- daemonId: "d1",- hostname: "MyMachine",- workspaceId: "w1",- });- });-- it("does NOT broadcast runtime.status when no pending update version", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockGetMachineByDaemon.mockResolvedValue(null);- mockBroadcastToUser.mockResolvedValue(undefined);-- await POST(makeReq(validBody));-- const broadcastCalls = mockBroadcastToUser.mock.calls;- const statusBroadcasts = broadcastCalls.filter(- ([, msg]: [string, any]) => msg.type === "runtime.status"- );- expect(statusBroadcasts).toHaveLength(0);- });-- it("returns 404 when membership is missing and does not broadcast", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue(null);-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("workspace not found");- expect(mockUpsertMachine).not.toHaveBeenCalled();- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-- it("returns 403 when token workspace_id does not match body workspace_id", async () => {- const POST = await loadRoute({ ...authCtx, workspaceId: "w_other" });-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("workspace_id does not match token");- expect(mockGetMember).not.toHaveBeenCalled();- expect(mockUpsertMachine).not.toHaveBeenCalled();- });-- it("allows register when token workspace_id matches body workspace_id", async () => {- const POST = await loadRoute({ ...authCtx, workspaceId: "w1" });-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));-- expect(res.status).toBe(200);- expect(mockUpsertMachine).toHaveBeenCalledTimes(1);- });-- it("does not fail the request if broadcast throws (fire-and-forget)", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockRejectedValue(new Error("ws down"));-- const res = await POST(makeReq(validBody));-- expect(res.status).toBe(200);- });-- it("still registers runtimes when upsertMachine fails (D1 transient error)", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockRejectedValue(new Error("D1 timeout"));- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockResolvedValue(undefined);- mockGetMachineByDaemon.mockResolvedValue(null);-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.runtimes).toEqual([{ id: "r1" }]);- expect(mockUpsertAgentRuntime).toHaveBeenCalledTimes(1);- });-- it("clears pendingUpdateVersion when cli_version satisfies pending version on register", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "0.0.2" });- mockClearPendingUpdateVersion.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));-- expect(res.status).toBe(200);- expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1");- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "online",- });- });-- it("does not clear pendingUpdateVersion when cli_version is older", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "2.0.0" });- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));-- expect(res.status).toBe(200);- expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();- });-- it("does not check pendingUpdateVersion when cli_version is missing", async () => {- const POST = await loadRoute(authCtx);-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockResolvedValue(undefined);-- const bodyWithoutVersion = { ...validBody, cli_version: undefined };- const res = await POST(makeReq(bodyWithoutVersion));-- expect(res.status).toBe(200);- expect(mockGetMachineByDaemon).not.toHaveBeenCalled();- });-- it("returns 400 when no workspace_id is provided or resolved", async () => {- const POST = await loadRoute(authCtx);-- const body = {- daemon_id: "d1",- device_name: "MyMachine",- cli_version: "0.0.2",- runtimes: [{ type: "claude", version: "1.0", runtime_mode: "local" }],- };- const res = await POST(makeReq(body));- const json = await res.json();-- expect(res.status).toBe(400);- expect(json.error).toBe("workspace_id is required");- expect(mockUpsertMachine).not.toHaveBeenCalled();- });-- it("uses auth context workspaceId when body workspace_id is missing", async () => {- const POST = await loadRoute({ ...authCtx, workspaceId: "w_from_token" });-- mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w_from_token" });- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1" });- mockBroadcastToUser.mockResolvedValue(undefined);-- const bodyWithoutWs = {- daemon_id: "d1",- device_name: "MyMachine",- cli_version: "0.0.2",- runtimes: [{ type: "claude", version: "1.0", runtime_mode: "local" }],- };- const res = await POST(makeReq(bodyWithoutWs));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.workspaceId).toBe("w_from_token");- });-});diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsdeleted file mode 100644index 44c7678e6..000000000--- a/src/web/src/app/api/daemon/register/route.ts+++ /dev/null@@ -1,108 +0,0 @@-import { NextRequest } from "next/server";-import { queries, semverGte } from "@alook/shared"-import { getDb, withD1Retry } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, parseBody } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";-import { RegisterDaemonRequestSchema } from "@alook/shared";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const [body, err] = await parseBody(req, RegisterDaemonRequestSchema);- if (err) return err;-- const { daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, workspaces_root: workspacesRoot, runtimes } = body;- let workspaceId = body.workspace_id;-- // Resolve workspace: use provided or fall back to auth context- if (!workspaceId && ctx.workspaceId) {- workspaceId = ctx.workspaceId;- }-- if (!workspaceId) {- return writeJSON({ error: "workspace_id is required" }, 400);- }-- // When authenticated with a machine token, enforce workspace match- if (ctx.workspaceId && ctx.workspaceId !== workspaceId) {- return writeJSON({ error: "workspace_id does not match token" }, 403);- }-- const membership = await withD1Retry(() => queries.member.getMemberByUserAndWorkspace(- db,- ctx.userId,- workspaceId- ));- if (!membership) {- return writeJSON({ error: "workspace not found" }, 404);- }-- // Upsert machine row (1 write for liveness) — non-critical- try {- await queries.machine.upsertMachine(db, {- daemonId,- workspaceId,- deviceInfo: deviceName.trim(),- ownerId: ctx.userId,- });- } catch (e) {- log.warn("register: machine upsert failed", { daemonId, err: String(e) });- }-- // Clear pendingUpdateVersion if daemon re-registered with a satisfying version- if (cliVersion) {- try {- const machineRow = await queries.machine.getMachineByDaemon(db, daemonId, workspaceId);- if (machineRow?.pendingUpdateVersion && semverGte(cliVersion, machineRow.pendingUpdateVersion)) {- await queries.machine.clearPendingUpdateVersion(db, daemonId, workspaceId);- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId,- workspaceId,- status: "online",- }).catch(() => {});- }- } catch (e) {- log.warn("register: pending version check failed", { daemonId, err: String(e) });- }- }-- const results = [];- for (const rt of runtimes) {- const provider = (rt.type || rt.provider || "unknown").trim();- const runtimeMode = rt.runtime_mode || "local";- const deviceInfo = deviceName.trim();- const metadata: Record<string, unknown> = {- version: rt.version || "",- ...(cliVersion ? { cli_version: cliVersion } : {}),- ...(workspacesRoot ? { workspaces_root: workspacesRoot } : {}),- };-- const result = await withD1Retry(() => queries.runtime.upsertAgentRuntime(db, {- workspaceId,- daemonId,- runtimeMode,- provider,- deviceInfo,- metadata,- }));- results.push({ ...result, machineLastSeenAt: new Date().toISOString() });- }-- await Promise.all([- invalidate(cacheKeys.runtimeIds(workspaceId, daemonId)),- ]);-- broadcastToUser(ctx.userId, {- type: "runtime.registered",- daemonId,- hostname: deviceName.trim(),- workspaceId,- }).catch(() => {});-- return writeJSON({ runtimes: results.map(runtimeToResponse), workspaceId });-});diff --git a/src/web/src/app/api/daemon/routes.test.ts b/src/web/src/app/api/daemon/routes.test.tsdeleted file mode 100644index 0ef1cb6d5..000000000--- a/src/web/src/app/api/daemon/routes.test.ts+++ /dev/null@@ -1,582 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--// ----------------------------------------------------------------------------// Cross-route body-validation tests for daemon endpoints.-// Uses real Zod schemas (parseBody is NOT mocked) so we can assert that-// invalid payloads are rejected before hitting any DB logic.-// -----------------------------------------------------------------------------const daemonAuth = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };--function baseMocks() {- return {- "@opennextjs/cloudflare": () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),- }),- "@/lib/middleware/auth": () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...daemonAuth, params });- }),- }),- "@/lib/middleware/helpers": async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- ),- "@/lib/logger": () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },- }),- };-}--function applyBase() {- const m = baseMocks();- vi.doMock("@opennextjs/cloudflare", m["@opennextjs/cloudflare"]);- vi.doMock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),- }));- vi.doMock("@/lib/middleware/auth", m["@/lib/middleware/auth"]);- vi.doMock("@/lib/middleware/helpers", m["@/lib/middleware/helpers"]);- vi.doMock("@/lib/logger", m["@/lib/logger"]);- vi.doMock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),- }));-}--function postReq(url: string, body: unknown) {- return new NextRequest(url, {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--function postRaw(url: string, raw: string) {- return new NextRequest(url, {- method: "POST",- body: raw,- headers: { "Content-Type": "application/json" },- });-}--describe("daemon route body validation", () => {- beforeEach(() => vi.clearAllMocks());-- // ------------------------------------------------------------------------ // POST /daemon/register- // ------------------------------------------------------------------------- describe("POST /daemon/register", () => {- async function loadRegister() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- member: {- getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),- },- machine: {- upsertMachine: vi.fn().mockResolvedValue({ daemonId: "d1", workspaceId: "w1" }),- },- runtime: {- upsertAgentRuntime: vi.fn().mockResolvedValue({ id: "rt1", workspaceId: "w1" }),- },- },- };- });- vi.doMock("@/lib/api/responses", () => ({- runtimeToResponse: (r: any) => r,- }));-- return (await import("./register/route")).POST;- }-- it("returns 400 when workspace_id is empty", async () => {- const POST = await loadRegister();- const res = await POST(- postReq("http://localhost/api/daemon/register", {- workspace_id: "",- daemon_id: "d1",- runtimes: [{ type: "claude" }],- })- );- expect(res.status).toBe(400);- });-- it("returns 400 when runtimes is empty array", async () => {- const POST = await loadRegister();- const res = await POST(- postReq("http://localhost/api/daemon/register", {- workspace_id: "w1",- daemon_id: "d1",- runtimes: [],- })- );- expect(res.status).toBe(400);- });-- it.each([[64, 200], [65, 400]] as const)(- "returns %i-runtime boundary status %i",- async (count, status) => {- const POST = await loadRegister();- const res = await POST(- postReq("http://localhost/api/daemon/register", {- workspace_id: "w1",- daemon_id: "d1",- device_name: "host",- runtimes: Array.from({ length: count }, (_, index) => ({- type: `runtime-${index}`,- })),- }),- );- expect(res.status).toBe(status);- },- );-- it("returns 400 on malformed JSON", async () => {- const POST = await loadRegister();- const res = await POST(- postRaw("http://localhost/api/daemon/register", "not json{{{")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });-- it("stores deviceInfo correctly", async () => {- const POST = await loadRegister();- const upsertMock = vi.fn().mockResolvedValue({- id: "rt1",- workspaceId: "w1",- deviceInfo: "MacBook Pro",- });-- // Re-mock with a trackable upsert- vi.resetModules();- applyBase();- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- member: {- getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),- },- machine: {- upsertMachine: vi.fn().mockResolvedValue({ daemonId: "d1", workspaceId: "w1" }),- },- runtime: {- upsertAgentRuntime: upsertMock,- },- },- };- });- vi.doMock("@/lib/api/responses", () => ({- runtimeToResponse: (r: any) => r,- }));-- const POST2 = (await import("./register/route")).POST;- await POST2(- postReq("http://localhost/api/daemon/register", {- workspace_id: "w1",- daemon_id: "d1",- device_name: "MacBook Pro",- runtimes: [{ type: "claude" }],- })- );-- expect(upsertMock).toHaveBeenCalledWith(- {},- expect.objectContaining({ deviceInfo: "MacBook Pro" })- );- });-- it("stores version in metadata", async () => {- vi.resetModules();- applyBase();-- const upsertMock = vi.fn().mockResolvedValue({- id: "rt1",- workspaceId: "w1",- });-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- member: {- getMemberByUserAndWorkspace: vi.fn().mockResolvedValue({ id: "m1" }),- },- machine: {- upsertMachine: vi.fn().mockResolvedValue({ daemonId: "d1", workspaceId: "w1" }),- },- runtime: {- upsertAgentRuntime: upsertMock,- },- },- };- });- vi.doMock("@/lib/api/responses", () => ({- runtimeToResponse: (r: any) => r,- }));-- const POST = (await import("./register/route")).POST;- await POST(- postReq("http://localhost/api/daemon/register", {- workspace_id: "w1",- daemon_id: "d1",- cli_version: "0.5.1",- runtimes: [{ type: "claude", version: "3.5" }],- })- );-- expect(upsertMock).toHaveBeenCalledWith(- {},- expect.objectContaining({- metadata: expect.objectContaining({ version: "3.5", cli_version: "0.5.1" }),- })- );- });- });-- // ------------------------------------------------------------------------ // POST /daemon/tasks/poll- // ------------------------------------------------------------------------- describe("POST /daemon/tasks/poll", () => {- async function loadPoll() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- runtime: {- getRuntimeIdsByDaemon: vi.fn().mockResolvedValue(["r1"]),- },- machine: {- updateMachineLastSeen: vi.fn().mockResolvedValue(undefined),- },- agent: {- getAgent: vi.fn().mockResolvedValue(null),- },- },- };- });- vi.doMock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- claimTasksForRuntimes: vi.fn().mockResolvedValue([]),- })),- }));- vi.doMock("@/lib/services/sweep", () => ({- sweepStaleState: vi.fn().mockResolvedValue(undefined),- }));- vi.doMock("@/lib/services/calendar", () => ({- promoteDueCalendarEventsForWorkspace: vi.fn().mockResolvedValue(0),- }));- vi.doMock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),- }));-- return (await import("./tasks/poll/route")).POST;- }-- it("returns 400 when daemon_id is missing", async () => {- const POST = await loadPoll();- const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", {})- );- expect(res.status).toBe(400);- });-- it("returns 400 when daemon_id is empty string", async () => {- const POST = await loadPoll();- const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { daemon_id: "" })- );- expect(res.status).toBe(400);- });-- it("returns 400 when max_tasks is 0", async () => {- const POST = await loadPoll();- const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { daemon_id: "d1", max_tasks: 0 })- );- expect(res.status).toBe(400);- });-- it("rejects old-format body with runtime_ids", async () => {- const POST = await loadPoll();- const res = await POST(- postReq("http://localhost/api/daemon/tasks/poll", { runtime_ids: ["r1"] })- );- expect(res.status).toBe(400);- });-- it("returns 400 on malformed JSON", async () => {- const POST = await loadPoll();- const res = await POST(- postRaw("http://localhost/api/daemon/tasks/poll", "not json{{{")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });- });-- // ------------------------------------------------------------------------ // POST /daemon/deregister- // ------------------------------------------------------------------------- describe("POST /daemon/deregister", () => {- async function loadDeregister() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- machine: {- setMachineLastSeenNull: vi.fn().mockResolvedValue(undefined),- },- },- };- });- vi.doMock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),- }));-- return (await import("./deregister/route")).POST;- }-- it("returns 400 when daemon_id is missing", async () => {- const POST = await loadDeregister();- const res = await POST(- postReq("http://localhost/api/daemon/deregister", {})- );- expect(res.status).toBe(400);- });-- it("returns 400 when daemon_id is empty", async () => {- const POST = await loadDeregister();- const res = await POST(- postReq("http://localhost/api/daemon/deregister", {- daemon_id: "",- })- );- expect(res.status).toBe(400);- });-- it("returns 400 on malformed JSON", async () => {- const POST = await loadDeregister();- const res = await POST(- postRaw("http://localhost/api/daemon/deregister", "{{bad")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });- });-- // ------------------------------------------------------------------------ // POST /daemon/tasks/:taskId/complete- // ------------------------------------------------------------------------- describe("POST /daemon/tasks/:taskId/complete", () => {- async function loadComplete() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- };- });- vi.doMock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- completeTask: vi.fn().mockResolvedValue({- id: "t1",- agentId: "a1",- runtimeId: "rt1",- workspaceId: "w1",- conversationId: "c1",- prompt: "p",- status: "completed",- priority: 0,- dispatchedAt: null,- startedAt: null,- completedAt: null,- createdAt: new Date().toISOString(),- }),- })),- }));- vi.doMock("@/lib/api/responses", () => ({- taskToResponse: (t: any) => ({ id: t.id, status: t.status }),- }));-- return (await import("./tasks/[taskId]/complete/route")).POST;- }-- it("returns 400 on malformed JSON", async () => {- const POST = await loadComplete();- const res = await POST(- postRaw("http://localhost/api/daemon/tasks/t1/complete", "{bad}"),- { params: Promise.resolve({ taskId: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });- });-- // ------------------------------------------------------------------------ // POST /daemon/tasks/:taskId/fail- // ------------------------------------------------------------------------- describe("POST /daemon/tasks/:taskId/fail", () => {- async function loadFail() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- };- });- vi.doMock("@/lib/services/task", () => ({- TaskService: vi.fn().mockImplementation(() => ({- failTask: vi.fn().mockResolvedValue({- id: "t1",- agentId: "a1",- runtimeId: "rt1",- workspaceId: "w1",- conversationId: "c1",- prompt: "p",- status: "failed",- priority: 0,- dispatchedAt: null,- startedAt: null,- completedAt: null,- createdAt: new Date().toISOString(),- }),- })),- }));- vi.doMock("@/lib/api/responses", () => ({- taskToResponse: (t: any) => ({ id: t.id, status: t.status }),- }));-- return (await import("./tasks/[taskId]/fail/route")).POST;- }-- it("returns 400 on malformed JSON", async () => {- const POST = await loadFail();- const res = await POST(- postRaw("http://localhost/api/daemon/tasks/t1/fail", "nope"),- { params: Promise.resolve({ taskId: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid request body");- });- });-- // ------------------------------------------------------------------------ // POST /daemon/tasks/:taskId/messages- // ------------------------------------------------------------------------- describe("POST /daemon/tasks/:taskId/messages", () => {- async function loadMessages() {- vi.resetModules();- applyBase();-- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>(- "@alook/shared"- );- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- task: {- getTask: vi.fn().mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" }),- },- taskMessage: {- createTaskMessage: vi.fn().mockResolvedValue(undefined),- },- conversation: {- getConversation: vi.fn().mockResolvedValue({ id: "c1", userId: "u1" }),- },- },- };- });- vi.doMock("@/lib/api/responses", () => ({- taskMessageToResponse: (m: any) => m,- }));- vi.doMock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),- }));-- return (await import("./tasks/[taskId]/messages/route")).POST;- }-- it("returns 400 when message item missing seq/type", async () => {- const POST = await loadMessages();- const res = await POST(- postReq("http://localhost/api/daemon/tasks/t1/messages", {- messages: [{ content: "hello" }],- }),- { params: Promise.resolve({ taskId: "t1" }) }- );-- expect(res.status).toBe(400);- });-- // NOTE: the broadcast-behavior tests for this route (task.messages envelope- // + empty-array no-op) live in tasks/[taskId]/messages/route.test.ts, which- // wires @/lib/broadcast with a hoisted vi.mock. They previously lived here- // on doMock + resetModules + dynamic import(); under full-suite parallel- // import pressure that per-test re-mock intermittently failed to bind, so the- // route called the real (unmocked) broadcastToUser and the assertion saw 0- // calls (~40% flake). This file stays pure body-validation, per its header.- });-});diff --git a/src/web/src/app/api/daemon/skills/sync/route.test.ts b/src/web/src/app/api/daemon/skills/sync/route.test.tsdeleted file mode 100644index be2af107c..000000000--- a/src/web/src/app/api/daemon/skills/sync/route.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),-}));--const mockSyncGlobal = vi.fn();-const mockSyncAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agentSkill: {- syncGlobalSkills: (...a: unknown[]) => mockSyncGlobal(...a),- syncAgentSkills: (...a: unknown[]) => mockSyncAgent(...a),- },- },- };-});--// withAuth here injects a machine-token context that includes workspaceId.-let injectWorkspaceId: string | undefined = "w1";-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });- }),-}));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- injectWorkspaceId = "w1";-});--function post(body: unknown) {- return POST(- new NextRequest("http://localhost/x", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(body),- }),- {},- );-}--describe("POST /api/daemon/skills/sync", () => {- it("403 when no workspace (session token, not a machine token)", async () => {- injectWorkspaceId = undefined;- const res = await post({ scope: "global", runtime: "claude", skills: [], daemon_id: "d1" });- expect(res.status).toBe(403);- });-- it("syncs global skills", async () => {- const skills = [{ name: "s", description: "d" }];- const res = await post({ scope: "global", runtime: "claude", skills, daemon_id: "d1" });- expect(res.status).toBe(200);- expect((await res.json()).status).toBe("ok");- expect(mockSyncGlobal).toHaveBeenCalledWith({}, "w1", "claude", skills, "d1");- });-- it("syncs agent skills when scope=agent", async () => {- const res = await post({ scope: "agent", agent_id: "a1", runtime: "claude", skills: [], daemon_id: "d1" });- expect(res.status).toBe(200);- expect(mockSyncAgent).toHaveBeenCalledWith({}, "a1", "claude", "w1", []);- });-- it("400 when scope=agent without agent_id", async () => {- const res = await post({ scope: "agent", runtime: "claude", skills: [], daemon_id: "d1" });- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/daemon/skills/sync/route.ts b/src/web/src/app/api/daemon/skills/sync/route.tsdeleted file mode 100644index 2171b9443..000000000--- a/src/web/src/app/api/daemon/skills/sync/route.ts+++ /dev/null@@ -1,41 +0,0 @@-import { NextRequest } from "next/server";-import { queries, SkillSyncRequestSchema } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";-import { getDb, withD1Retry } from "@/lib/db";--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB);-- const [body, err] = await parseBody(req, SkillSyncRequestSchema);- if (err) return err;-- if (body.scope === "global") {- await withD1Retry(() =>- queries.agentSkill.syncGlobalSkills(- db,- ctx.workspaceId!,- body.runtime,- body.skills,- body.daemon_id,- )- );- } else {- if (!body.agent_id) return writeError("agent_id required for agent scope", 400);- await withD1Retry(() =>- queries.agentSkill.syncAgentSkills(- db,- body.agent_id!,- body.runtime,- ctx.workspaceId!,- body.skills,- )- );- }-- return writeJSON({ status: "ok" });-});diff --git a/src/web/src/app/api/daemon/sweep/route.test.ts b/src/web/src/app/api/daemon/sweep/route.test.tsdeleted file mode 100644index 88a4dcfe4..000000000--- a/src/web/src/app/api/daemon/sweep/route.test.ts+++ /dev/null@@ -1,142 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockSweepStaleState = vi.fn();-const mockPromoteDue = vi.fn(async () => 0);--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- CACHE_KV: {- put: vi.fn().mockResolvedValue(undefined),- get: vi.fn().mockResolvedValue(null),- delete: vi.fn().mockResolvedValue(undefined),- },- },- })),-}));--vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),-}));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return { ...real };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/services/sweep", () => ({- sweepStaleState: (...args: unknown[]) => mockSweepStaleState(...args),-}));--vi.mock("@/lib/services/calendar", () => ({- promoteDueCalendarEventsForWorkspace: (...args: unknown[]) => mockPromoteDue(...args),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--vi.mock("@/lib/cache", () => ({- throttled: vi.fn((_key: string, _interval: number, fn: () => Promise<any>) => fn()),-}));--import { POST } from "./route";--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/sweep", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/sweep", () => {- beforeEach(() => {- vi.clearAllMocks();- mockSweepStaleState.mockResolvedValue(undefined);- mockPromoteDue.mockResolvedValue(0);- });-- it("returns 403 without machine token auth", async () => {- vi.resetModules();-- vi.doMock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, CACHE_KV: { put: vi.fn(), get: vi.fn().mockResolvedValue(null), delete: vi.fn() } },- })),- }));- vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));- vi.doMock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return { ...real };- });- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any) => {- return handler(req, { env: {}, userId: "u1", email: "[email protected]" });- }),- }));- vi.doMock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")- );- vi.doMock("@/lib/services/sweep", () => ({ sweepStaleState: vi.fn() }));- vi.doMock("@/lib/services/calendar", () => ({ promoteDueCalendarEventsForWorkspace: vi.fn() }));- vi.doMock("@/lib/logger", () => ({ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));- vi.doMock("@/lib/cache", () => ({ throttled: vi.fn((_k: string, _i: number, fn: () => Promise<any>) => fn()) }));-- const { POST: POST2 } = await import("./route");- const res = await POST2(postReq({ daemon_id: "d1" }));- expect(res.status).toBe(403);- });-- it("calls sweepStaleState with correct db and workspaceId", async () => {- await POST(postReq({ daemon_id: "d1" }));-- expect(mockSweepStaleState).toHaveBeenCalledWith({}, "w1");- });-- it("calls promoteDueCalendarEventsForWorkspace (throttled)", async () => {- await POST(postReq({ daemon_id: "d1" }));-- expect(mockPromoteDue).toHaveBeenCalledWith({}, "w1");- });-- it("returns { ok: true } on success", async () => {- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- });-- it("survives sweepStaleState throwing (still returns 200)", async () => {- mockSweepStaleState.mockRejectedValue(new Error("D1 timeout"));-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- });-- it("survives calendar promotion throwing (still returns 200)", async () => {- mockPromoteDue.mockRejectedValue(new Error("calendar error"));-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ ok: true });- });-});diff --git a/src/web/src/app/api/daemon/sweep/route.ts b/src/web/src/app/api/daemon/sweep/route.tsdeleted file mode 100644index ab815d7c7..000000000--- a/src/web/src/app/api/daemon/sweep/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { NextRequest } from "next/server";-import { HeartbeatRequestSchema } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { sweepStaleState } from "@/lib/services/sweep";-import { promoteDueCalendarEventsForWorkspace } from "@/lib/services/calendar";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const { throttled } = await import("@/lib/cache");-- const [, err] = await parseBody(req, HeartbeatRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB);-- try {- await sweepStaleState(db, ctx.workspaceId);- } catch (e) {- log.warn("sweep failed", { workspaceId: ctx.workspaceId, err: String(e) });- }-- try {- await throttled(`cal:${ctx.workspaceId}`, 30, async () => {- const enqueued = await promoteDueCalendarEventsForWorkspace(- db,- ctx.workspaceId!,- );- if (enqueued > 0) {- log.info("calendar: enqueued", { workspaceId: ctx.workspaceId, enqueued });- }- });- } catch (e) {- log.warn("calendar: promote failed", { workspaceId: ctx.workspaceId, err: String(e) });- }-- return writeJSON({ ok: true });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.tsdeleted file mode 100644index 082fdde55..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockCompleteTask = vi.fn();-const mockTaskToResponse = vi.fn();-const mockGetConversation = vi.fn();--let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- conversation: { getConversation: (...args: any[]) => mockGetConversation(...args) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...mockAuthCtx, params });- }),-}));-vi.mock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );-});-vi.mock("@/lib/services/task", () => {- const MockTaskService = function (this: any) {- this.completeTask = (...a: any[]) => mockCompleteTask(...a);- } as any;- return { TaskService: MockTaskService };-});-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- invalidateInboxCounts: vi.fn().mockResolvedValue(undefined),- cacheKeys: { overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}` },-}));--import { POST } from "./route";--const withParams = (taskId: string) => ({- params: Promise.resolve({ taskId }),-});--const makeReq = (taskId: string, body: Record<string, unknown> = {}) =>- new NextRequest(`http://localhost/api/daemon/tasks/${taskId}/complete`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });--describe("POST /api/daemon/tasks/[taskId]/complete", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- });-- it("returns completed task and broadcasts to conversation owner", async () => {- const fakeTask = { id: "t1", agentId: "a1", conversationId: "c1", status: "completed" };- mockCompleteTask.mockResolvedValue(fakeTask);- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockTaskToResponse.mockReturnValue({ id: "t1", status: "completed" });-- const res = await POST(makeReq("t1", { output: "done" }), withParams("t1"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "t1", status: "completed" });- expect(mockCompleteTask).toHaveBeenCalledWith("t1", "w1", expect.any(String), "");- const { broadcastToUser } = await import("@/lib/broadcast");- expect(broadcastToUser).toHaveBeenCalledWith("owner-u2", expect.objectContaining({ type: "task.updated", status: "completed" }));- const { invalidateInboxCounts } = await import("@/lib/cache");- expect(invalidateInboxCounts).toHaveBeenCalledWith("owner-u2", "w1");- });-- it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };-- const res = await POST(makeReq("t1", { output: "done" }), withParams("t1"));- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("Forbidden: machine token required");- expect(mockCompleteTask).not.toHaveBeenCalled();- });-- it("rejects cross-workspace task complete (task not found for workspace)", async () => {- mockCompleteTask.mockRejectedValue(new Error("cannot complete task in 'unknown' status"));-- const res = await POST(makeReq("t-other", { output: "done" }), withParams("t-other"));- const body = await res.json();-- expect(res.status).toBe(400);- expect(mockCompleteTask).toHaveBeenCalledWith("t-other", "w1", expect.any(String), "");- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.tsdeleted file mode 100644index 61d67d8c9..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/complete/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { CompleteTaskRequestSchema } from "@alook/shared";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, invalidateInboxCounts, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const [body, err] = await parseBody(req, CompleteTaskRequestSchema);- if (err) return err;-- const result = JSON.stringify(body);- const sessionId = body.session_id || "";-- const taskService = new TaskService(db);- try {- const task = await taskService.completeTask(- taskId,- ctx.workspaceId,- result,- sessionId- );- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ctx.workspaceId, dateStr)).catch(() => {});- const conv = await queries.conversation.getConversation(db, task.conversationId, ctx.workspaceId);- if (conv) {- invalidateInboxCounts(conv.userId, ctx.workspaceId).catch(() => {});- broadcastToUser(conv.userId, { type: "task.updated", taskId, agentId: task.agentId, status: "completed" }).catch(() => {});- }- return writeJSON(taskToResponse(task));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Request failed", 400);- }-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.tsdeleted file mode 100644index 9ed238e81..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.test.ts+++ /dev/null@@ -1,111 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockFailTask = vi.fn();-const mockTaskToResponse = vi.fn();-const mockGetConversation = vi.fn();--let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- conversation: { getConversation: (...args: any[]) => mockGetConversation(...args) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...mockAuthCtx, params });- }),-}));-vi.mock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );-});-vi.mock("@/lib/services/task", () => {- const MockTaskService = function (this: any) {- this.failTask = (...a: any[]) => mockFailTask(...a);- } as any;- return { TaskService: MockTaskService };-});-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- invalidateInboxCounts: vi.fn().mockResolvedValue(undefined),- cacheKeys: { overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}` },-}));--import { POST } from "./route";--const withParams = (taskId: string) => ({- params: Promise.resolve({ taskId }),-});--const makeReq = (taskId: string, body: Record<string, unknown> = {}) =>- new NextRequest(`http://localhost/api/daemon/tasks/${taskId}/fail`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- });--describe("POST /api/daemon/tasks/[taskId]/fail", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- });-- it("returns failed task and broadcasts to conversation owner", async () => {- const fakeTask = { id: "t1", agentId: "a1", conversationId: "c1", status: "failed" };- mockFailTask.mockResolvedValue(fakeTask);- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockTaskToResponse.mockReturnValue({ id: "t1", status: "failed" });-- const res = await POST(makeReq("t1", { error: "boom" }), withParams("t1"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "t1", status: "failed" });- expect(mockFailTask).toHaveBeenCalledWith("t1", "w1", "boom");- const { broadcastToUser } = await import("@/lib/broadcast");- expect(broadcastToUser).toHaveBeenCalledWith("owner-u2", expect.objectContaining({ type: "task.updated", status: "failed" }));- const { invalidateInboxCounts } = await import("@/lib/cache");- expect(invalidateInboxCounts).toHaveBeenCalledWith("owner-u2", "w1");- });-- it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };-- const res = await POST(makeReq("t1", { error: "boom" }), withParams("t1"));- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("Forbidden: machine token required");- expect(mockFailTask).not.toHaveBeenCalled();- });-- it("rejects cross-workspace task fail (task not found for workspace)", async () => {- mockFailTask.mockRejectedValue(new Error("cannot fail task in 'unknown' status"));-- const res = await POST(makeReq("t-other", { error: "boom" }), withParams("t-other"));- const body = await res.json();-- expect(res.status).toBe(400);- expect(mockFailTask).toHaveBeenCalledWith("t-other", "w1", "boom");- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.tsdeleted file mode 100644index 1ca10473a..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/fail/route.ts+++ /dev/null@@ -1,41 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { FailTaskRequestSchema } from "@alook/shared";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, invalidateInboxCounts, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const [body, err] = await parseBody(req, FailTaskRequestSchema);- if (err) return err;-- const taskService = new TaskService(db);- try {- const task = await taskService.failTask(taskId, ctx.workspaceId, body.error);- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ctx.workspaceId, dateStr)).catch(() => {});- const conv = await queries.conversation.getConversation(db, task.conversationId, ctx.workspaceId);- if (conv) {- invalidateInboxCounts(conv.userId, ctx.workspaceId).catch(() => {});- broadcastToUser(conv.userId, { type: "task.updated", taskId, agentId: task.agentId, status: "failed" }).catch(() => {});- }- return writeJSON(taskToResponse(task));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Request failed", 400);- }-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.tsdeleted file mode 100644index 6b0bd462a..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.test.ts+++ /dev/null@@ -1,309 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListTaskMessages = vi.fn();-const mockCreateTaskMessage = vi.fn();-const mockGetTask = vi.fn();-const mockTaskMessageToResponse = vi.fn((m: any) => m);--let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: { withSession: () => ({}) } } })),-}));-vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),-}));-const mockGetConversation = vi.fn();-vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- taskMessage: {- listTaskMessages: (...args: any[]) => mockListTaskMessages(...args),- createTaskMessage: (...args: any[]) => mockCreateTaskMessage(...args),- },- task: {- getTask: (...args: any[]) => mockGetTask(...args),- },- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...mockAuthCtx, params });- }),-}));-vi.mock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );-});-vi.mock("@/lib/api/responses", () => ({- taskMessageToResponse: (...args: any[]) => mockTaskMessageToResponse(...args),-}));-const mockBroadcastToUser = vi.fn().mockResolvedValue(undefined);-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...args: any[]) => mockBroadcastToUser(...args),-}));-vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },-}));--import { GET, POST } from "./route";--const withParams = (taskId: string) => ({- params: Promise.resolve({ taskId }),-});--describe("GET /api/daemon/tasks/[taskId]/messages", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- });-- it("returns messages for workspace-scoped task", async () => {- const msgs = [{ id: "m1", seq: 1, content: "hi" }];- mockListTaskMessages.mockResolvedValue(msgs);-- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages"),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(mockListTaskMessages).toHaveBeenCalledWith({}, "t1", "w1");- });-- it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };-- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages"),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("Forbidden: machine token required");- expect(mockListTaskMessages).not.toHaveBeenCalled();- });-});--describe("POST /api/daemon/tasks/[taskId]/messages", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- });-- it("creates messages for workspace-scoped task", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockCreateTaskMessage.mockResolvedValue({ id: "m1" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [{ seq: 1, type: "text", content: "hello" }],- }),- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("ok");- expect(mockGetTask).toHaveBeenCalledWith({}, "t1", "w1");- });-- it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [{ seq: 1, type: "text", content: "hello" }],- }),- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("Forbidden: machine token required");- expect(mockGetTask).not.toHaveBeenCalled();- });-- it("returns 404 when task belongs to another workspace", async () => {- mockGetTask.mockResolvedValue(null);-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t-other/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [{ seq: 1, type: "text", content: "hello" }],- }),- }),- withParams("t-other")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("task not found");- expect(mockCreateTaskMessage).not.toHaveBeenCalled();- });-- it("only broadcasts text and error messages via WebSocket to conversation owner", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockCreateTaskMessage.mockResolvedValue({ id: "m1" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [- { seq: 1, type: "text", content: "hello" },- { seq: 2, type: "tool-result", content: "large payload" },- { seq: 3, type: "tool-use", tool: "grep", content: "" },- ],- }),- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("ok");- expect(mockCreateTaskMessage).toHaveBeenCalledTimes(3);- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);- expect(mockBroadcastToUser.mock.calls[0][0]).toBe("owner-u2");- const broadcastPayload = mockBroadcastToUser.mock.calls[0][1];- expect(broadcastPayload.messages).toHaveLength(1);- expect(broadcastPayload.messages[0].type).toBe("text");- });-- it("stores thinking messages but does not broadcast them", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockCreateTaskMessage.mockResolvedValue({ id: "m1" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [- { seq: 1, type: "text", content: "hello" },- { seq: 2, type: "thinking", content: "hmm" },- ],- }),- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("ok");- expect(mockCreateTaskMessage).toHaveBeenCalledTimes(2);- expect(mockBroadcastToUser).toHaveBeenCalledTimes(1);- const broadcastPayload = mockBroadcastToUser.mock.calls[0][1];- expect(broadcastPayload.messages).toHaveLength(1);- expect(broadcastPayload.messages[0].type).toBe("text");- });-- it("does not broadcast when all messages are tool-result", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockCreateTaskMessage.mockResolvedValue({ id: "m1" });-- await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [- { seq: 1, type: "tool-result", content: "result1" },- { seq: 2, type: "tool-result", content: "result2" },- ],- }),- }),- withParams("t1")- );-- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-- // Broadcast-envelope shape: the WS payload the owner receives is a- // `task.messages` event carrying taskId + only the broadcastable rows. (Moved- // here from the cross-route body-validation file, where the same assertion- // relied on a doMock+resetModules+dynamic-import re-application that raced- // under full-suite import pressure and flaked; the hoisted mocks in this file- // make it deterministic.)- it("broadcasts a task.messages envelope with taskId to the conversation owner", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockCreateTaskMessage.mockResolvedValue({ id: "m1" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [- { seq: 1, type: "text", content: "hello" },- { seq: 2, type: "tool-use", tool: "Read", content: "" },- ],- }),- }),- withParams("t1")- );-- expect(res.status).toBe(200);- expect(mockBroadcastToUser).toHaveBeenCalledWith(- "owner-u2",- expect.objectContaining({- type: "task.messages",- taskId: "t1",- messages: [expect.objectContaining({ seq: 1, type: "text", content: "hello" })],- })- );- });-- // The `filtered.length === 0` early-return branch (empty input) — a DIFFERENT- // path from "all tool-result" above: it returns before createTaskMessage runs,- // so neither the DB write nor the broadcast fires. (Also moved from the- // body-validation file to escape the same flaky re-mock race.)- it("does not broadcast or write when the messages array is empty", async () => {- mockGetTask.mockResolvedValue({ id: "t1", workspaceId: "w1", conversationId: "c1" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/messages", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ messages: [] }),- }),- withParams("t1")- );-- expect(res.status).toBe(200);- expect(mockCreateTaskMessage).not.toHaveBeenCalled();- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.tsdeleted file mode 100644index 471205b7d..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/messages/route.ts+++ /dev/null@@ -1,108 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb, withD1Retry } from "@/lib/db";-import type { TaskMessageResponse } from "@alook/shared"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { taskMessageToResponse } from "@/lib/api/responses";-import { ReportMessagesRequestSchema } from "@alook/shared";-import { broadcastToUser } from "@/lib/broadcast";-import { log } from "@/lib/logger";--export const GET = withAuth(async (_req, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const messages = await withD1Retry(() => queries.taskMessage.listTaskMessages(db, taskId, ctx.workspaceId));- return writeJSON(messages.map(taskMessageToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const task = await withD1Retry(() => queries.task.getTask(db, taskId, ctx.workspaceId));- if (!task) {- return writeError("task not found", 404);- }-- const [body, err] = await parseBody(req, ReportMessagesRequestSchema);- if (err) return err;-- // What we persist (INTENTIONAL — do not "clean up" as dead storage):- // - We DROP only "log" and "status" — pure transient runtime noise, never- // useful after the fact.- // - We KEEP text/tool-use/thinking/tool-result rows even though the chat UI- // no longer reads them (since the move to agent-authored `send-dm`, the UI- // only consumes type:"error" + the final reply bubble). These rows are- // retained for FUTURE DATA ANALYSIS of agent runs (tool usage, reasoning,- // etc.). The read paths (listTaskMessages*) filter them out for the UI, but- // the rows must stay in storage. Don't delete this write or narrow it to- // errors-only.- const filtered = body.messages.filter((m) => m.type !== "log" && m.type !== "status");- if (filtered.length === 0) {- return writeJSON({ status: "ok" });- }-- const results = await Promise.allSettled(- filtered.map((m) =>- queries.taskMessage.createTaskMessage(db, {- taskId,- seq: m.seq,- type: m.type,- tool: m.tool || "",- callId: m.call_id || "",- // tool-result content/input/output are intentionally blanked: those- // payloads can be very large (full tool stdout, file dumps), so we keep- // the row (for analysis: which tool ran, when) but not the heavy body.- content: m.type === "tool-result" ? "" : (m.content || ""),- input: m.type === "tool-result" ? undefined : m.input,- output: m.type === "tool-result" ? "" : (m.output || ""),- })- )- );-- results.forEach((r) => {- if (r.status === "rejected") {- log.warn("Failed to create task message", { taskId, err: r.reason });- }- });-- const succeeded = filtered.filter((_, i) => results[i].status === "fulfilled");- // Broadcast is a separate concern from storage: we STORE tool-use/thinking/- // tool-result (for later analysis, above) but don't BROADCAST them — the live- // chat has no use for them. text is still broadcast (cheap, and harmless if the- // client ignores it); only type:"error" actually drives UI today.- const broadcastable = succeeded.filter((m) => m.type !== "tool-result" && m.type !== "tool-use" && m.type !== "thinking");- if (broadcastable.length > 0) {- const wsMessages: TaskMessageResponse[] = broadcastable.map((m) => ({- id: "",- seq: m.seq,- type: m.type,- content: m.content || "",- output: m.output || "",- }));- const conv = await queries.conversation.getConversation(db, task.conversationId, ctx.workspaceId);- if (conv) {- broadcastToUser(conv.userId, { type: "task.messages", taskId, messages: wsMessages }).catch(() => {});- }- }-- return writeJSON({ status: "ok" });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/progress/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/progress/route.tsdeleted file mode 100644index 2da5845fd..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/progress/route.ts+++ /dev/null@@ -1,6 +0,0 @@-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";--export const POST = withAuth(async () => {- return writeJSON({ status: "ok" });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.tsdeleted file mode 100644index 33d30046d..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.test.ts+++ /dev/null@@ -1,145 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockStartTask = vi.fn();-const mockTaskToResponse = vi.fn();-const mockGetConversation = vi.fn();--let mockAuthCtx: Record<string, unknown> = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- conversation: { getConversation: (...args: any[]) => mockGetConversation(...args) },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { ...mockAuthCtx, params });- }),-}));-vi.mock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );-});-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockReturnValue(Promise.resolve()),-}));-vi.mock("@/lib/services/task", () => {- const MockTaskService = function (this: any) {- this.startTask = (...a: any[]) => mockStartTask(...a);- } as any;- return { TaskService: MockTaskService };-});-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));--import { POST } from "./route";--const withParams = (taskId: string) => ({- params: Promise.resolve({ taskId }),-});--describe("POST /api/daemon/tasks/[taskId]/start", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1" };- });-- it("returns started task and broadcasts to conversation owner", async () => {- const fakeTask = {- id: "t1",- agentId: "a1",- conversationId: "c1",- status: "running",- };- mockStartTask.mockResolvedValue(fakeTask);- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- mockTaskToResponse.mockReturnValue({ id: "t1", status: "running" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", {- method: "POST",- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "t1", status: "running" });- expect(mockStartTask).toHaveBeenCalledWith("t1", "w1");- const { broadcastToUser } = await import("@/lib/broadcast");- expect(broadcastToUser).toHaveBeenCalledWith("owner-u2", expect.objectContaining({ type: "task.updated", status: "running" }));- });-- it("skips broadcast gracefully when conversation not found", async () => {- const fakeTask = { id: "t1", agentId: "a1", conversationId: "c-deleted", status: "running" };- mockStartTask.mockResolvedValue(fakeTask);- mockGetConversation.mockResolvedValue(null);- mockTaskToResponse.mockReturnValue({ id: "t1", status: "running" });-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", { method: "POST" }),- withParams("t1")- );- expect(res.status).toBe(200);- const { broadcastToUser } = await import("@/lib/broadcast");- expect(broadcastToUser).not.toHaveBeenCalled();- });-- it("returns 400 when task not in dispatched status", async () => {- mockStartTask.mockRejectedValue(new Error("task not in dispatched status"));-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", {- method: "POST",- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("task not in dispatched status");- });-- it("returns 403 when workspaceId is missing (session auth)", async () => {- mockAuthCtx = { env: {}, userId: "u1", email: "[email protected]" };-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t1/start", {- method: "POST",- }),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("Forbidden: machine token required");- expect(mockStartTask).not.toHaveBeenCalled();- });-- it("rejects cross-workspace task start (task not found for workspace)", async () => {- mockStartTask.mockRejectedValue(new Error("task not in dispatched status"));-- const res = await POST(- new NextRequest("http://localhost/api/daemon/tasks/t-other/start", {- method: "POST",- }),- withParams("t-other")- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("task not in dispatched status");- expect(mockStartTask).toHaveBeenCalledWith("t-other", "w1");- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/start/route.tsdeleted file mode 100644index 6928f9819..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/start/route.ts+++ /dev/null@@ -1,32 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";--export const POST = withAuth(async (_req, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB)-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const taskService = new TaskService(db);- try {- const task = await taskService.startTask(taskId, ctx.workspaceId);- const conv = await queries.conversation.getConversation(db, task.conversationId, ctx.workspaceId);- if (conv) {- broadcastToUser(conv.userId, { type: "task.updated", taskId, agentId: task.agentId, status: "running" }).catch(() => {});- }- return writeJSON(taskToResponse(task));- } catch (err: unknown) {- return writeError(err instanceof Error ? err.message : "Request failed", 400);- }-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.tsdeleted file mode 100644index d15aa2e3e..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetTaskStatus = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),-}));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- task: {- getTaskStatus: (...args: any[]) => mockGetTaskStatus(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- }),-}));-vi.mock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );-});--import { GET } from "./route";--const withParams = (taskId: string) => ({- params: Promise.resolve({ taskId }),-});--describe("GET /api/daemon/tasks/[taskId]/status", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns task status", async () => {- mockGetTaskStatus.mockResolvedValue("running");-- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t1/status"),- withParams("t1")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ status: "running" });- expect(mockGetTaskStatus).toHaveBeenCalledWith({}, "t1", "w1");- });-- it("returns 404 when task not found", async () => {- mockGetTaskStatus.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/daemon/tasks/t-missing/status"),- withParams("t-missing")- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("task not found");- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/status/route.tsdeleted file mode 100644index 488bd2e7d..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/status/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { queries } from "@alook/shared"-import { getDb, withD1Retry } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const status = await withD1Retry(() => queries.task.getTaskStatus(db, taskId, ctx.workspaceId));- if (!status) {- return writeError("task not found", 404);- }-- return writeJSON({ status });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.tsdeleted file mode 100644index 6eff973ea..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.test.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetConversation = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", () => ({- queries: {- conversation: { getConversation: (...args: any[]) => mockGetConversation(...args) },- },-}));--const mockSupersede = vi.fn();-vi.mock("@/lib/services/task", () => ({- TaskService: function () { return { supersedeTask: mockSupersede }; },-}));-vi.mock("@/lib/api/responses", () => ({ taskToResponse: (t: any) => ({ id: t.id, status: t.status }) }));-vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn().mockResolvedValue(undefined) }));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- invalidateInboxCounts: vi.fn().mockResolvedValue(undefined),- cacheKeys: { overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}` },-}));--let injectWorkspaceId: string | undefined = "w1";-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: injectWorkspaceId, params });- }),-}));--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- injectWorkspaceId = "w1";-});--const post = (params: Record<string, string>) =>- POST(new NextRequest("http://localhost/x", { method: "POST" }), { params });--describe("POST /api/daemon/tasks/[taskId]/supersede", () => {- it("403 when no workspace (machine token required)", async () => {- injectWorkspaceId = undefined;- const res = await post({ taskId: "t1" });- expect(res.status).toBe(403);- });-- it("400 when taskId missing", async () => {- const res = await post({});- expect(res.status).toBe(400);- });-- it("supersedes a task and broadcasts to conversation owner", async () => {- mockSupersede.mockResolvedValue({ id: "t1", agentId: "a1", conversationId: "c1", status: "superseded" });- mockGetConversation.mockResolvedValue({ id: "c1", userId: "owner-u2" });- const res = await post({ taskId: "t1" });- expect(res.status).toBe(200);- expect(mockSupersede).toHaveBeenCalledWith("t1", "w1");- expect((await res.json()).id).toBe("t1");- const { broadcastToUser } = await import("@/lib/broadcast");- expect(broadcastToUser).toHaveBeenCalledWith("owner-u2", expect.objectContaining({ type: "task.updated", status: "superseded" }));- const { invalidateInboxCounts } = await import("@/lib/cache");- expect(invalidateInboxCounts).toHaveBeenCalledWith("owner-u2", "w1");- });-- it("400 when supersede throws (e.g. task not in workspace)", async () => {- mockSupersede.mockRejectedValue(new Error("task not found"));- const res = await post({ taskId: "t1" });- expect(res.status).toBe(400);- expect((await res.json()).error).toBe("task not found");- });-});diff --git a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts b/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.tsdeleted file mode 100644index 0aac0135f..000000000--- a/src/web/src/app/api/daemon/tasks/[taskId]/supersede/route.ts+++ /dev/null@@ -1,37 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, invalidateInboxCounts, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB);-- const taskId = ctx.params?.taskId;- if (!taskId) {- return writeError("task_id is required", 400);- }-- const taskService = new TaskService(db);- try {- const task = await taskService.supersedeTask(taskId, ctx.workspaceId);- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ctx.workspaceId, dateStr)).catch(() => {});- const conv = await queries.conversation.getConversation(db, task.conversationId, ctx.workspaceId);- if (conv) {- invalidateInboxCounts(conv.userId, ctx.workspaceId).catch(() => {});- broadcastToUser(conv.userId, { type: "task.updated", taskId, agentId: task.agentId, status: "superseded" }).catch(() => {});- }- return writeJSON(taskToResponse(task));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Request failed", 400);- }-});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.tsdeleted file mode 100644index 7efccd1e7..000000000--- a/src/web/src/app/api/daemon/tasks/poll/route.auth-order.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { beforeEach, describe, expect, it, vi } from "vitest"-import { NextRequest } from "next/server"--const getMachineTokenByToken = vi.fn()-const updateMachineTokenLastUsed = vi.fn()-const runtimeLookup = vi.fn()-const kvGet = vi.fn().mockResolvedValue(null)-const kvPut = vi.fn().mockResolvedValue(undefined)--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({- env: { DB: {}, CACHE_KV: { get: kvGet, put: kvPut, delete: vi.fn() } },- })),-}))-vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<unknown>) => fn()),-}))-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")- return {- ...actual,- queries: {- machineToken: {- getMachineTokenByToken: (...args: unknown[]) => getMachineTokenByToken(...args),- updateMachineTokenLastUsed: (...args: unknown[]) => updateMachineTokenLastUsed(...args),- },- runtime: { getRuntimeIdsByDaemon: (...args: unknown[]) => runtimeLookup(...args) },- },- }-})-vi.mock("@/lib/cache", () => ({- bindCacheKV: vi.fn(),- getKV: vi.fn(() => ({ get: kvGet, put: kvPut, delete: vi.fn() })),- cacheKeys: {- machineToken: (token: string) => `mt:${token}`,- runtimeIds: (workspaceId: string, daemonId: string) => `runtime:${workspaceId}:${daemonId}`,- },- cached: vi.fn(),- throttled: vi.fn(),-}))-vi.mock("@/lib/auth", () => ({ createAuth: vi.fn(), getAuth: vi.fn() }))--import { POST } from "./route"--function request(token: string) {- return new NextRequest("http://localhost/api/daemon/tasks/poll", {- method: "POST",- headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },- body: JSON.stringify({ daemon_id: "daemon-1", max_tasks: 0 }),- })-}--describe("poll authentication precedes max_tasks validation", () => {- beforeEach(() => {- vi.clearAllMocks()- kvGet.mockResolvedValue(null)- })-- it("returns 401 for invalid-token + zero before entering route work", async () => {- getMachineTokenByToken.mockResolvedValue(null)- const response = await POST(request("al_invalid"))- expect(response.status).toBe(401)- expect(await response.json()).toEqual({ error: "invalid token" })- expect(runtimeLookup).not.toHaveBeenCalled()- })-- it("returns 400 for valid-token + zero before any poll work", async () => {- getMachineTokenByToken.mockResolvedValue({- id: "token-1",- userId: "user-1",- userEmail: "[email protected]",- workspaceId: "workspace-1",- })- const response = await POST(request("al_valid"))- expect(response.status).toBe(400)- expect(runtimeLookup).not.toHaveBeenCalled()- })-})diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsdeleted file mode 100644index 187997930..000000000--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ /dev/null@@ -1,856 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetRuntimeIdsByDaemon = vi.fn();-const mockUpdateRuntimeCliVersionByDaemon = vi.fn();-const mockUpsertMachine = vi.fn();-const mockGetMachineByDaemon = vi.fn();-const mockClearPendingUpdateVersion = vi.fn();-const mockClearPendingRescan = vi.fn();-const mockGetAgentsByIds = vi.fn();-const mockGetAllAgentsForWorkspace = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();-const mockGetConversation = vi.fn();-const mockGetConversationsByIds = vi.fn();-const mockGetUser = vi.fn();-const mockClaimTasksForRuntimes = vi.fn();-const mockSweepStaleState = vi.fn();-const mockBroadcastToUser = vi.fn();-const mockGetPendingFileRequests = vi.fn();-const mockMarkFileRequestsDispatched = vi.fn();-const mockExpireStaleFileRequests = vi.fn();-const mockListScheduledMeetings = vi.fn();-const mockClaimMeetingSessions = vi.fn();-const mockGetAllEmailAccountsForWorkspace = vi.fn();-const mockGetAllColleaguesForWorkspace = vi.fn();-const mockInvalidate = vi.fn().mockResolvedValue(undefined);-const mockKvPut = vi.fn().mockResolvedValue(undefined);--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {}, CACHE_KV: { put: (...args: unknown[]) => mockKvPut(...args), get: vi.fn().mockResolvedValue(null), delete: vi.fn().mockResolvedValue(undefined) } }, ctx: { waitUntil: vi.fn() } })),-}));--vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),-}));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- runtime: {- getRuntimeIdsByDaemon: (...args: unknown[]) => mockGetRuntimeIdsByDaemon(...args),- updateRuntimeCliVersionByDaemon: (...args: unknown[]) => mockUpdateRuntimeCliVersionByDaemon(...args),- },- machine: {- upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),- getMachineByDaemon: (...args: unknown[]) => mockGetMachineByDaemon(...args),- clearPendingUpdateVersion: (...args: unknown[]) => mockClearPendingUpdateVersion(...args),- clearPendingRescan: (...args: unknown[]) => mockClearPendingRescan(...args),- },- agent: {- getAgentsByIds: (...args: unknown[]) => mockGetAgentsByIds(...args),- getAllAgentsForWorkspace: (...args: unknown[]) => mockGetAllAgentsForWorkspace(...args),- },- member: {- getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),- },- conversation: {- getConversation: (...args: unknown[]) => mockGetConversation(...args),- getConversationsByIds: (...args: unknown[]) => mockGetConversationsByIds(...args),- },- user: {- getUserSelf: (...args: unknown[]) => mockGetUser(...args),- },- emailAccount: {- getEmailAccountsByAgents: (...args: unknown[]) => mockGetAllEmailAccountsForWorkspace(...args),- getAllEmailAccountsForWorkspace: (...args: unknown[]) => mockGetAllEmailAccountsForWorkspace(...args),- },- workspaceFileRequest: {- getPendingByWorkspace: (...args: unknown[]) => mockGetPendingFileRequests(...args),- markDispatched: (...args: unknown[]) => mockMarkFileRequestsDispatched(...args),- expireStale: (...args: unknown[]) => mockExpireStaleFileRequests(...args),- },- meetingSession: {- listScheduledMeetings: (...args: unknown[]) => mockListScheduledMeetings(...args),- claimMeetingSessions: (...args: unknown[]) => mockClaimMeetingSessions(...args),- },- agentLink: {- getAllColleaguesForWorkspace: (...args: unknown[]) => mockGetAllColleaguesForWorkspace(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/services/task", () => ({- TaskService: class {- claimTasksForRuntimes(...args: unknown[]) { return mockClaimTasksForRuntimes(...args); }- },-}));--vi.mock("@/lib/services/sweep", () => ({- sweepStaleState: (...args: unknown[]) => mockSweepStaleState(...args),-}));--const mockPromoteDue = vi.fn(async () => 0);-vi.mock("@/lib/services/calendar", () => ({- promoteDueCalendarEventsForWorkspace: (...args: unknown[]) => mockPromoteDue(...args),-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: string, _ttl: number, fn: () => Promise<any>) => fn()),- cacheKeys: {- machineToken: (token: string) => `mt:${token.slice(0, 20)}`,- runtimeIds: (wsId: string, daemonId: string) => `rt:${wsId}:${daemonId}`,- agent: (wsId: string, agentId: string) => `ag:${wsId}:${agentId}`,- heartbeat: (wsId: string, daemonId: string) => `hb:${wsId}:${daemonId}`,- user: (userId: string) => `usr:${userId}`,- allAgents: (wsId: string) => `agents:${wsId}`,- allEmailAccounts: (wsId: string) => `ea:${wsId}`,- allColleagues: (wsId: string) => `col:${wsId}`,- allRuntimes: (wsId: string) => `runtimes:${wsId}`,- member: (wsId: string, userId: string) => `mem:${wsId}:${userId}`,- allHandles: (wsId: string) => `handles:${wsId}`,- allMembers: (wsId: string) => `members:${wsId}`,- hasPendingFileRequest: (wsId: string) => `fr_p:${wsId}`,- },- throttled: vi.fn((_key: string, _interval: number, fn: () => Promise<void>) => fn().then(() => true)),- invalidate: (...args: unknown[]) => mockInvalidate(...args),-}));--vi.mock("@/lib/api/responses", () => ({- taskToResponse: (t: any) => ({- id: t.id,- agent_id: t.agentId,- runtime_id: t.runtimeId,- workspace_id: t.workspaceId,- prompt: t.prompt,- status: t.status,- }),-}));--import { POST } from "./route";--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/tasks/poll", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/tasks/poll", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetMachineByDaemon.mockResolvedValue(null);- mockGetPendingFileRequests.mockResolvedValue([]);- mockExpireStaleFileRequests.mockResolvedValue(undefined);- mockListScheduledMeetings.mockResolvedValue([]);- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllEmailAccountsForWorkspace.mockResolvedValue([]);- mockGetAllColleaguesForWorkspace.mockResolvedValue([]);- mockGetConversationsByIds.mockResolvedValue([]);- });-- it("returns evicted: true when daemon has no runtimes", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(body.evicted).toBe(true);- });-- it("omits evicted field for normal polls with active runtimes", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.evicted).toBeUndefined();- });-- it("resolves runtime IDs from daemon_id", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1" }));-- expect(mockGetRuntimeIdsByDaemon).toHaveBeenCalledWith({}, "d1", "w1");- });-- it("returns tasks with agent data for claimed tasks", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "do it", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{- id: "a1",- instructions: "be helpful",- name: "Bot",- runtimeConfig: { model: "gpt-4" },- }]);-- const res = await POST(postReq({ daemon_id: "d1", max_tasks: 3 }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toHaveLength(1);- expect(body.tasks[0].id).toBe("t1");- expect(body.tasks[0].agent).toEqual({- instructions: "be helpful",- name: "Bot",- runtime_config: { model: "gpt-4" },- email_handle: null,- email_addresses: [],- user_email: "[email protected]",- user_name: null,- colleagues: [],- });- });-- it("does not broadcast runtime.status (heartbeat handles that)", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1", "r2", "r3"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1" }));-- expect(mockBroadcastToUser).not.toHaveBeenCalledWith("u1", expect.objectContaining({- type: "runtime.status",- status: "online",- }));- });-- it("respects max_tasks parameter", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1", max_tasks: 5 }));-- expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 5, "w1");- });-- it.each([51, 125])("clamps legacy max_tasks=%i requests to 50", async (requested) => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1", max_tasks: requested }));-- expect(res.status).toBe(200);- expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 50, "w1");- });-- it("rejects max_tasks=0 before any poll work", async () => {- const res = await POST(postReq({ daemon_id: "d1", max_tasks: 0 }));-- expect(res.status).toBe(400);- expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled();- expect(mockClaimTasksForRuntimes).not.toHaveBeenCalled();- expect(mockListScheduledMeetings).not.toHaveBeenCalled();- expect(mockGetPendingFileRequests).not.toHaveBeenCalled();- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-- it("defaults max_tasks to 1", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1" }));-- expect(mockClaimTasksForRuntimes).toHaveBeenCalledWith(["r1"], 1, "w1");- });-- it("returns pending_update when pendingUpdateVersion is set and cli_version is older, without clearing flag", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });-- const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_update).toEqual({ version: "1.0.0" });- expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();- expect(mockBroadcastToUser).not.toHaveBeenCalled();- });-- it("does not return pending_update when pendingUpdateVersion is not set", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: null });-- const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_update).toBeUndefined();- });-- it("auto-clears pendingUpdateVersion and broadcasts when cli_version >= pending version", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });- mockClearPendingUpdateVersion.mockResolvedValue(undefined);- mockUpdateRuntimeCliVersionByDaemon.mockResolvedValue(undefined);-- const res = await POST(postReq({ daemon_id: "d1", cli_version: "1.0.0" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_update).toBeUndefined();- expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1");- expect(mockUpdateRuntimeCliVersionByDaemon).toHaveBeenCalledWith({}, "d1", "w1", "1.0.0");- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "online",- });- });-- it("does not attach pending_update when cli_version is missing (backward compat)", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_update).toBeUndefined();- expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();- });-- it("poll without pending_update works unchanged", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue(null);-- const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(body.pending_update).toBeUndefined();- });-- it("concatenates global + per-agent instructions when owner has global instruction", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "hi", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{- id: "a1",- ownerId: "owner1",- instructions: "you are a planner",- name: "Bot",- runtimeConfig: {},- }]);- mockGetMemberByUserAndWorkspace.mockResolvedValue({- globalInstruction: "speak chinese",- });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks[0].agent.instructions).toBe("speak chinese\n\nyou are a planner");- expect(mockGetMemberByUserAndWorkspace).toHaveBeenCalledWith({}, "owner1", "w1");- });-- it("returns only agent instructions when global instruction is empty", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "hi", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{- id: "a1",- ownerId: "owner1",- instructions: "you are a planner",- name: "Bot",- runtimeConfig: {},- }]);- mockGetMemberByUserAndWorkspace.mockResolvedValue({- globalInstruction: "",- });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].agent.instructions).toBe("you are a planner");- });-- it("falls back to agent instructions when agent has no ownerId", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "hi", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{- id: "a1",- ownerId: null,- instructions: "just agent",- name: "Bot",- runtimeConfig: {},- }]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].agent.instructions).toBe("just agent");- expect(mockGetMemberByUserAndWorkspace).not.toHaveBeenCalled();- });-- it("caches member lookups by ownerId across multiple tasks", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "hi", status: "dispatched" },- { id: "t2", agentId: "a2", runtimeId: "r1", workspaceId: "w1", prompt: "yo", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([- { id: "a1", ownerId: "owner1", instructions: "inst1", name: "Bot1", runtimeConfig: {} },- { id: "a2", ownerId: "owner1", instructions: "inst2", name: "Bot2", runtimeConfig: {} },- ]);- mockGetMemberByUserAndWorkspace.mockResolvedValue({ globalInstruction: "global" });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].agent.instructions).toBe("global\n\ninst1");- expect(body.tasks[1].agent.instructions).toBe("global\n\ninst2");- expect(mockGetMemberByUserAndWorkspace).toHaveBeenCalledTimes(1);- });-- it("returns only global instruction when agent instructions are empty", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", prompt: "hi", status: "dispatched" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{- id: "a1",- ownerId: "owner1",- instructions: "",- name: "Bot",- runtimeConfig: {},- }]);- mockGetMemberByUserAndWorkspace.mockResolvedValue({- globalInstruction: "global only",- });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].agent.instructions).toBe("global only");- });-- it("resolves sender for DM tasks (owner)", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "hi", status: "dispatched", type: "user_dm_message" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "u1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u1" }]);- mockGetUser.mockResolvedValue({ name: "Gus", email: "[email protected]" });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: true });- });-- it("sets is_owner=false for non-owner DM", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "hi", status: "dispatched", type: "user_dm_message" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "owner1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u2" }]);- mockGetUser.mockResolvedValue({ name: "Alice", email: "[email protected]" });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toEqual({ name: "Alice", email: "[email protected]", is_owner: false });- });-- it("returns null sender for calendar tasks", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "standup", status: "dispatched", type: "calendar_event" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "u1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u1" }]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toBeNull();- });-- it("returns null sender for email tasks", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "new email", status: "dispatched", type: "email_notification" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "u1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u1" }]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toBeNull();- });-- it("returns null sender when conversation not found", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "hi", status: "dispatched", type: "user_dm_message" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "u1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toBeNull();- });-- it("returns null sender when user not found", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "hi", status: "dispatched", type: "user_dm_message" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "u1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u1" }]);- mockGetUser.mockResolvedValue(null);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toBeNull();- });-- it("caches user lookups across multiple DM tasks from the same user", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([- { id: "t1", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c1", prompt: "hi", status: "dispatched", type: "user_dm_message" },- { id: "t2", agentId: "a1", runtimeId: "r1", workspaceId: "w1", conversationId: "c2", prompt: "yo", status: "dispatched", type: "user_dm_message" },- ]);- mockGetAllAgentsForWorkspace.mockResolvedValue([{ id: "a1", ownerId: "owner1", instructions: "", name: "Bot", runtimeConfig: {} }]);- mockGetConversationsByIds.mockResolvedValue([{ id: "c1", userId: "u1" }, { id: "c2", userId: "u1" }]);- mockGetUser.mockResolvedValue({ name: "Gus", email: "[email protected]" });-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(body.tasks[0].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: false });- expect(body.tasks[1].sender).toEqual({ name: "Gus", email: "[email protected]", is_owner: false });- expect(mockGetUser).toHaveBeenCalledTimes(2);- });-- // --- Workspace file requests ----- it("includes pending file_requests in response and marks them dispatched", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetPendingFileRequests.mockResolvedValue([- { id: "wfr_1", agentId: "a1", requestType: "tree", path: "." },- { id: "wfr_2", agentId: "a1", requestType: "read", path: "memory.md" },- ]);- mockMarkFileRequestsDispatched.mockResolvedValue(undefined);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.file_requests).toHaveLength(2);- expect(body.file_requests[0]).toEqual({ id: "wfr_1", agent_id: "a1", request_type: "tree", path: "." });- expect(body.file_requests[1]).toEqual({ id: "wfr_2", agent_id: "a1", request_type: "read", path: "memory.md" });- expect(mockMarkFileRequestsDispatched).toHaveBeenCalledWith({}, ["wfr_1", "wfr_2"]);- });-- it("omits file_requests field when no pending requests", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetPendingFileRequests.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.file_requests).toBeUndefined();- expect(mockMarkFileRequestsDispatched).not.toHaveBeenCalled();- });-- it("calls expireStale to clean up old file requests", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetPendingFileRequests.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1" }));-- expect(mockExpireStaleFileRequests).toHaveBeenCalledWith({}, "w1");- });-- it("gracefully handles file request errors without failing the poll", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockExpireStaleFileRequests.mockRejectedValue(new Error("DB error"));-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(body.file_requests).toBeUndefined();- });-- // --- Meeting claim via poll ----- it("includes meetings in response when scheduled meetings exist", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockListScheduledMeetings.mockResolvedValue([- { id: "ms1", agentId: "a1", workspaceId: "w1", meetingUrl: "https://meet.google.com/abc", participants: ["[email protected]"], status: "scheduled", agentName: "Jarvis", title: "Standup" },- ]);- mockClaimMeetingSessions.mockResolvedValue([{- id: "ms1", agentId: "a1", workspaceId: "w1", meetingUrl: "https://meet.google.com/abc", participants: ["[email protected]"], status: "joining",- }]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.meetings).toHaveLength(1);- expect(body.meetings[0]).toEqual({- id: "ms1",- meeting_url: "https://meet.google.com/abc",- participants: ["[email protected]"],- workspace_id: "w1",- agent_id: "a1",- agent_name: "Jarvis",- title: "Standup",- });- });-- it("omits meetings field when no scheduled meetings", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockListScheduledMeetings.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.meetings).toBeUndefined();- });-- it("gracefully handles meeting claim errors without failing the poll", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockListScheduledMeetings.mockRejectedValue(new Error("DB error"));-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(body.meetings).toBeUndefined();- });-- it("poll works without heartbeat logic (upsertMachine no longer called)", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(mockUpsertMachine).not.toHaveBeenCalled();- });-- it("still returns tasks when pending check fails (D1 transient error)", async () => {- mockUpsertMachine.mockResolvedValue({});- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockRejectedValue(new Error("D1 timeout"));-- const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.1.0" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.tasks).toEqual([]);- expect(body.pending_update).toBeUndefined();- });-- // --- Heartbeat is now a separate endpoint ----- it("poll does not write KV heartbeat (moved to /api/daemon/heartbeat)", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);-- await POST(postReq({ daemon_id: "d1" }));-- expect(mockKvPut).not.toHaveBeenCalledWith(- "hb:w1:d1",- expect.any(String),- expect.anything(),- );- });-- it("broadcasts runtime.status after clearing pendingRescan", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingRescan: true });- mockClearPendingRescan.mockResolvedValue(undefined);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_rescan).toBe(true);- expect(mockClearPendingRescan).toHaveBeenCalledWith({}, "d1", "w1");- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "online",- });- });-- it("does not fail poll when rescan broadcast rejects", async () => {- mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);- mockSweepStaleState.mockResolvedValue(undefined);- mockBroadcastToUser.mockRejectedValue(new Error("WS unavailable"));- mockClaimTasksForRuntimes.mockResolvedValue([]);- mockGetMachineByDaemon.mockResolvedValue({ pendingRescan: true });- mockClearPendingRescan.mockResolvedValue(undefined);-- const res = await POST(postReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_rescan).toBe(true);- });-});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsdeleted file mode 100644index 2edf3b212..000000000--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ /dev/null@@ -1,180 +0,0 @@-import { NextRequest } from "next/server";-import { queries, MAX_MEETING_CLAIMS_PER_POLL, MAX_POLL_TASKS, PollRequestSchema, semverGte, type FileRequestItem, type PollMeetingItem } from "@alook/shared";-import { getDb, withD1Retry } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { TaskService } from "@/lib/services/task";-import { TaskPayloadBuilder } from "@/lib/services/task-payload-builder";-import { broadcastToUser } from "@/lib/broadcast";-import { log } from "@/lib/logger";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB);- const { cached, cacheKeys, throttled } = await import("@/lib/cache");-- const [body, err] = await parseBody(req, PollRequestSchema);- if (err) return err;-- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- // 1. Resolve runtime IDs from daemon_id + workspaceId (cached 10min)- const runtimeIds = await cached(- cacheKeys.runtimeIds(ctx.workspaceId, body.daemon_id),- 600,- () => queries.runtime.getRuntimeIdsByDaemon(db, body.daemon_id, ctx.workspaceId!),- );-- if (runtimeIds.length === 0) {- return writeJSON({ tasks: [], evicted: true });- }-- // 2. Task claiming- const taskService = new TaskService(db);- const claimLimit = Math.min(body.max_tasks, MAX_POLL_TASKS);- const claimed = await withD1Retry(() => taskService.claimTasksForRuntimes(- runtimeIds,- claimLimit,- ctx.workspaceId!,- ));-- const payloadBuilder = new TaskPayloadBuilder(db);- const tasks = await payloadBuilder.buildFullPayloads(claimed, ctx.workspaceId!);-- // Patch user_email (only available in poll context via auth)- for (const t of tasks) {- if (t.agent) t.agent.user_email = ctx.email || null;- }-- // 3. Pending update & rescan check + meeting claim — throttled to once per 30s- let pendingUpdate: { version: string } | undefined;- let pendingRescan: boolean | undefined;- let meetings: PollMeetingItem[] | undefined;- const miscKey = `misc:${ctx.workspaceId}:${body.daemon_id}`;- let runMisc = false;- try {- runMisc = await throttled(miscKey, 30, async () => {});- } catch { runMisc = true; }-- if (runMisc) {- const CLAIM_WINDOW_MS = 5 * 60 * 1000;- const windowEnd = new Date(Date.now() + CLAIM_WINDOW_MS);- const now = new Date().toISOString();-- const [machineResult, meetingResult] = await Promise.allSettled([- queries.machine.getMachineByDaemon(db, body.daemon_id, ctx.workspaceId),- queries.meetingSession.listScheduledMeetings(- db,- ctx.workspaceId,- windowEnd.toISOString(),- MAX_MEETING_CLAIMS_PER_POLL,- ),- ]);-- if (machineResult.status === "fulfilled") {- const machineRow = machineResult.value;- try {- if (machineRow?.pendingUpdateVersion && body.cli_version) {- if (semverGte(body.cli_version, machineRow.pendingUpdateVersion)) {- await Promise.all([- queries.machine.clearPendingUpdateVersion(db, body.daemon_id, ctx.workspaceId),- queries.runtime.updateRuntimeCliVersionByDaemon(db, body.daemon_id, ctx.workspaceId, body.cli_version),- ]);- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId,- status: "online",- }).catch(() => {});- } else {- pendingUpdate = { version: machineRow.pendingUpdateVersion };- }- }-- if (machineRow?.pendingRescan) {- pendingRescan = true;- await queries.machine.clearPendingRescan(db, body.daemon_id, ctx.workspaceId);- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: body.daemon_id,- workspaceId: ctx.workspaceId,- status: "online",- }).catch(() => {});- }- } catch (e) {- log.warn("pending check failed", { daemonId: body.daemon_id, err: String(e) });- }- } else {- log.warn("pending check failed", { daemonId: body.daemon_id, err: String(machineResult.reason) });- }-- if (meetingResult.status === "fulfilled") {- const scheduled = meetingResult.value;- try {- if (scheduled.length > 0) {- const ids = scheduled.map((m) => m.id);- const claimedRows = await queries.meetingSession.claimMeetingSessions(- db,- ids,- ctx.workspaceId,- now,- );- if (claimedRows.length > 0) {- const scheduledMap = new Map(scheduled.map((m) => [m.id, m]));- meetings = claimedRows.map((row) => {- const sched = scheduledMap.get(row.id);- return {- id: row.id,- meeting_url: row.meetingUrl,- participants: row.participants as string[],- workspace_id: row.workspaceId,- agent_id: row.agentId,- agent_name: sched?.agentName || "",- title: sched?.title || undefined,- };- });- }- }- } catch (e) {- log.warn("meeting-claim: failed in poll", { err: String(e) });- }- } else {- log.warn("meeting-claim: failed in poll", { err: String(meetingResult.reason) });- }- }-- // File browse requests — skip D1 if KV negative cache says "no pending"- let fileRequests: FileRequestItem[] | undefined;- try {- await throttled(`expire_fr:${ctx.workspaceId}`, 5, async () => {- await queries.workspaceFileRequest.expireStale(db, ctx.workspaceId!);- });- const kv = ctx.env.CACHE_KV ?? null;- const frFlag = kv ? await kv.get(cacheKeys.hasPendingFileRequest(ctx.workspaceId!)) : null;- if (frFlag !== "0") {- const pending = await queries.workspaceFileRequest.getPendingByWorkspace(db, ctx.workspaceId);- if (pending.length > 0) {- fileRequests = pending.map((r) => ({- id: r.id,- agent_id: r.agentId,- request_type: r.requestType as "tree" | "read",- path: r.path,- }));- await queries.workspaceFileRequest.markDispatched(db, pending.map((r) => r.id));- } else if (kv) {- kv.put(cacheKeys.hasPendingFileRequest(ctx.workspaceId!), "0", { expirationTtl: 60 }).catch(() => {});- }- }- } catch (e) {- log.warn("file-requests: poll failed", { err: String(e) });- }-- return writeJSON({- tasks,- ...(pendingUpdate && { pending_update: pendingUpdate }),- ...(pendingRescan && { pending_rescan: pendingRescan }),- ...(fileRequests && { file_requests: fileRequests }),- ...(meetings && { meetings }),- });-});diff --git a/src/web/src/app/api/daemon/workspace/report/route.test.ts b/src/web/src/app/api/daemon/workspace/report/route.test.tsdeleted file mode 100644index a3f251f49..000000000--- a/src/web/src/app/api/daemon/workspace/report/route.test.ts+++ /dev/null@@ -1,159 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetRequest = vi.fn();-const mockCompleteRequest = vi.fn();-const mockBroadcastToUser = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({- getDb: vi.fn(() => ({})),- withD1Retry: vi.fn((fn: () => Promise<any>) => fn()),-}));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- workspaceFileRequest: {- getRequest: (...args: unknown[]) => mockGetRequest(...args),- completeRequest: (...args: unknown[]) => mockCompleteRequest(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),-}));--import { POST } from "./route";--function postReq(body: unknown) {- return new NextRequest("http://localhost/api/daemon/workspace/report", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/daemon/workspace/report", () => {- beforeEach(() => vi.clearAllMocks());-- it("requires machine token (workspaceId) — tested via withAuth mock providing it", () => {- // The route checks ctx.workspaceId and returns 403 if missing.- // Our mock always provides workspaceId="w1" to test the happy path.- // The 403 guard is structurally identical to other daemon routes (e.g. poll, complete).- expect(true).toBe(true);- });-- it("returns 404 when request not found", async () => {- mockGetRequest.mockResolvedValue(null);-- const res = await POST(postReq({ request_id: "wfr_missing", path: "." }));- expect(res.status).toBe(404);- });-- it("completes request and broadcasts result for tree", async () => {- const entries = [- { name: "memory.md", path: "memory.md", isDirectory: false, size: 100, modifiedAt: "2026-01-01" },- ];- mockGetRequest.mockResolvedValue({- id: "wfr_1",- agentId: "a1",- requestType: "tree",- workspaceId: "w1",- });- mockCompleteRequest.mockResolvedValue({});- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(postReq({ request_id: "wfr_1", path: ".", entries }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("ok");- expect(mockCompleteRequest).toHaveBeenCalledWith({}, "wfr_1", {- entries,- content: undefined,- isBinary: undefined,- error: undefined,- path: ".",- });- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "workspace.files",- agentId: "a1",- requestId: "wfr_1",- requestType: "tree",- result: expect.objectContaining({ entries, path: "." }),- });- });-- it("completes request and broadcasts for file read", async () => {- mockGetRequest.mockResolvedValue({- id: "wfr_2",- agentId: "a1",- requestType: "read",- workspaceId: "w1",- });- mockCompleteRequest.mockResolvedValue({});- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(postReq({- request_id: "wfr_2",- path: "memory.md",- content: "# Hello",- isBinary: false,- }));-- expect(res.status).toBe(200);- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "workspace.files",- agentId: "a1",- requestId: "wfr_2",- requestType: "read",- result: expect.objectContaining({ content: "# Hello", isBinary: false, path: "memory.md" }),- });- });-- it("handles error report from daemon", async () => {- mockGetRequest.mockResolvedValue({- id: "wfr_3",- agentId: "a1",- requestType: "read",- workspaceId: "w1",- });- mockCompleteRequest.mockResolvedValue({});- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(postReq({- request_id: "wfr_3",- path: "missing.txt",- error: "ENOENT: no such file",- }));-- expect(res.status).toBe(200);- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({- result: expect.objectContaining({ error: "ENOENT: no such file" }),- }));- });-- it("returns 400 when request_id is missing", async () => {- const res = await POST(postReq({ path: "." }));- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/daemon/workspace/report/route.ts b/src/web/src/app/api/daemon/workspace/report/route.tsdeleted file mode 100644index 6e6a60993..000000000--- a/src/web/src/app/api/daemon/workspace/report/route.ts+++ /dev/null@@ -1,40 +0,0 @@-import { NextRequest } from "next/server";-import { queries, WorkspaceFileReportSchema } from "@alook/shared";-import { withAuth } from "@/lib/middleware/auth";-import { parseBody, writeJSON, writeError } from "@/lib/middleware/helpers";-import { getDb, withD1Retry } from "@/lib/db";-import { broadcastToUser } from "@/lib/broadcast";--export const POST = withAuth(async (req: NextRequest, ctx) => {- if (!ctx.workspaceId) {- return writeError("Forbidden: machine token required", 403);- }-- const db = getDb(ctx.env.DB);-- const [body, err] = await parseBody(req, WorkspaceFileReportSchema);- if (err) return err;-- const row = await withD1Retry(() => queries.workspaceFileRequest.getRequest(db, body.request_id));- if (!row) return writeError("request not found", 404);-- const result = {- entries: body.entries,- content: body.content,- isBinary: body.isBinary,- error: body.error,- path: body.path,- };-- await withD1Retry(() => queries.workspaceFileRequest.completeRequest(db, row.id, result));-- broadcastToUser(ctx.userId, {- type: "workspace.files",- agentId: row.agentId,- requestId: row.id,- requestType: row.requestType as "tree" | "read",- result,- }).catch(() => {});-- return writeJSON({ status: "ok" });-});diff --git a/src/web/src/app/api/daily-quote/route.ts b/src/web/src/app/api/daily-quote/route.tsdeleted file mode 100644index 8771d6fa8..000000000--- a/src/web/src/app/api/daily-quote/route.ts+++ /dev/null@@ -1,24 +0,0 @@-import { NextResponse } from "next/server";--let cached: { date: string; q: string; a: string } | null = null;--export async function GET() {- const today = new Date().toISOString().split("T")[0];-- if (cached && cached.date === today) {- return NextResponse.json({ q: cached.q, a: cached.a });- }-- try {- const res = await fetch("https://zenquotes.io/api/today", {- next: { revalidate: 3600 },- });- const data = await res.json() as { q: string; a: string }[];- if (data?.[0]?.q) {- cached = { date: today, q: data[0].q, a: data[0].a };- return NextResponse.json({ q: cached.q, a: cached.a });- }- } catch {}-- return NextResponse.json({ q: "", a: "" });-}diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.test.tsdeleted file mode 100644index a473360a3..000000000--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockBucketGet = vi.fn();-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {}, EMAIL_BUCKET: { get: mockBucketGet } } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockParse = vi.fn();-vi.mock("postal-mime", () => ({ default: { parse: (...a: unknown[]) => mockParse(...a) } }));--const mockGetById = vi.fn();-const mockFilter = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- filterDownloadableAttachments: (...a: unknown[]) => mockFilter(...a),- queries: {- email: { getEmailById: (...a: unknown[]) => mockGetById(...a) },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: mockBucketGet } }, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--const get = (params: Record<string, string>) => GET(new NextRequest("http://localhost/x"), { params });--describe("GET /api/email/[id]/attachment/[index]", () => {- it("400 when email id missing", async () => {- const res = await get({ index: "0" });- expect(res.status).toBe(400);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- });-- it("400 when index is not a valid number", async () => {- const res = await get({ id: "e1", index: "abc" });- expect(res.status).toBe(400);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect((await res.json()).error).toBe("invalid attachment index");- });-- it("404 when email not in workspace", async () => {- mockGetById.mockResolvedValue(null);- const res = await get({ id: "e1", index: "0" });- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect(mockGetById).toHaveBeenCalledWith({}, "e1", "w1");- });-- it("404 when R2 object is missing", async () => {- mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockBucketGet.mockResolvedValue(null);- const res = await get({ id: "e1", index: "0" });- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect((await res.json()).error).toBe("email content not available");- });-- it("404 when the index is out of range", async () => {- mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });- mockParse.mockResolvedValue({ attachments: [] });- mockFilter.mockReturnValue([]);- const res = await get({ id: "e1", index: "0" });- expect(res.status).toBe(404);- expect(res.headers.get("Cache-Control")).toBe("private, no-store");- expect((await res.json()).error).toBe("attachment not found");- });-- it.each(["small-报告.bin", "📎😀.bin", 'a"b\\c.bin', "a\r\nb.bin", "plain.bin"])("serves %j without invalid header bytes", async filename => {- mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });- mockParse.mockResolvedValue({ attachments: [{}] });- const bytes = new Uint8Array([0, 1, 254, 255]);- mockFilter.mockReturnValue([{ filename, mimeType: "application/octet-stream", content: bytes.buffer }]);- const res = await get({ id: "e1", index: "0" });- expect(res.status).toBe(200);- expect(res.headers.get("Vary")).toBe("Authorization");- expect(decodeURIComponent(res.headers.get("Content-Disposition")!.split("filename*=UTF-8''")[1])).toBe(filename);- expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes);- });-- it("streams the attachment with content headers", async () => {- mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "k" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockBucketGet.mockResolvedValue({ arrayBuffer: async () => new ArrayBuffer(4) });- mockParse.mockResolvedValue({ attachments: [{}] });- mockFilter.mockReturnValue([- { filename: "report.pdf", mimeType: "application/pdf", content: new ArrayBuffer(3) },- ]);- const res = await get({ id: "e1", index: "0" });- expect(res.status).toBe(200);- expect(res.headers.get("Vary")).toBe("Authorization");- expect(res.headers.get("Content-Type")).toBe("application/pdf");- expect(res.headers.get("Content-Disposition")).toContain("report.pdf");- });-});diff --git a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts b/src/web/src/app/api/email/[id]/attachment/[index]/route.tsdeleted file mode 100644index befa9e540..000000000--- a/src/web/src/app/api/email/[id]/attachment/[index]/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { contentDisposition } from "@/lib/content-disposition"-import PostalMime from "postal-mime";-import { queries, filterDownloadableAttachments } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withPrivateMediaCache } from "@/lib/middleware/private-media-cache"-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const GET = withPrivateMediaCache(withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const index = Number(ctx.params?.index);- if (Number.isNaN(index) || index < 0) return writeError("invalid attachment index", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);- if (!object) return writeError("email content not available", 404);-- const raw = await object.arrayBuffer();- const parsed = await PostalMime.parse(raw);-- const attachments = filterDownloadableAttachments(parsed.attachments || []);-- if (index >= attachments.length) return writeError("attachment not found", 404);-- const att = attachments[index];- const filename = att.filename || `attachment-${index}`;- const contentType = att.mimeType || "application/octet-stream";-- const body = att.content instanceof ArrayBuffer ? new Uint8Array(att.content) : att.content;- return new Response(body as BodyInit, {- headers: {- "Content-Type": contentType,- "Content-Disposition": contentDisposition("attachment", filename),- "Cache-Control": "private, max-age=3600",- },- });-}));diff --git a/src/web/src/app/api/email/[id]/body/route.test.ts b/src/web/src/app/api/email/[id]/body/route.test.tsdeleted file mode 100644index 0dc11cb6c..000000000--- a/src/web/src/app/api/email/[id]/body/route.test.ts+++ /dev/null@@ -1,136 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockR2Get = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } },- })),-}));--const mockGetEmailById = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- email: { getEmailById: (...args: unknown[]) => mockGetEmailById(...args) },- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } }, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET } from "./route";--function makeR2Object(text: string) {- const buf = new TextEncoder().encode(text).buffer;- return { arrayBuffer: () => Promise.resolve(buf) };-}--describe("GET /api/email/[id]/body", () => {- beforeEach(() => vi.clearAllMocks());-- it("parses plain text email and returns text body", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue(- makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/plain\r\n\r\nHello world")- );-- const req = new NextRequest("http://localhost/api/email/e1/body");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- expect((await res.text()).trim()).toBe("Hello world");- expect(res.headers.get("Content-Type")).toContain("text/plain");- expect(mockGetEmailById).toHaveBeenCalledWith({}, "e1", "ws1");- });-- it("parses HTML email and returns HTML body", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue(- makeR2Object("From: [email protected]\r\nTo: [email protected]\r\nSubject: Test\r\nContent-Type: text/html\r\n\r\n<p>Hello</p>")- );-- const req = new NextRequest("http://localhost/api/email/e1/body");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- expect((await res.text()).trim()).toBe("<p>Hello</p>");- expect(res.headers.get("Content-Type")).toContain("text/html");- });-- it("extracts HTML from multipart MIME email", async () => {- const boundary = "----=_Part_123";- const mime = [- "From: [email protected]",- "To: [email protected]",- "Subject: Test",- `Content-Type: multipart/alternative; boundary="${boundary}"`,- "",- `--${boundary}`,- "Content-Type: text/plain; charset=UTF-8",- "",- "Plain text body",- `--${boundary}`,- "Content-Type: text/html; charset=UTF-8",- "",- "<p>HTML body</p>",- `--${boundary}--`,- ].join("\r\n");-- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue(makeR2Object(mime));-- const req = new NextRequest("http://localhost/api/email/e1/body");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- const text = await res.text();- expect(text).toContain("<p>HTML body</p>");- expect(res.headers.get("Content-Type")).toContain("text/html");- });-- it("returns 404 when R2 object not found", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/abc/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1/body");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-- it("returns 404 when email not found in workspace", async () => {- mockGetEmailById.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1/body");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/email/[id]/body/route.ts b/src/web/src/app/api/email/[id]/body/route.tsdeleted file mode 100644index 04522d8d7..000000000--- a/src/web/src/app/api/email/[id]/body/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import PostalMime from "postal-mime";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);- if (!object) {- return new Response("Email body not available", {- status: 404,- headers: { "Content-Type": "text/plain" },- });- }-- const raw = await object.arrayBuffer();- const parsed = await PostalMime.parse(raw);-- if (parsed.html) {- return new Response(parsed.html, {- headers: { "Content-Type": "text/html; charset=utf-8" },- });- }-- return new Response(parsed.text ?? "", {- headers: { "Content-Type": "text/plain; charset=utf-8" },- });-});diff --git a/src/web/src/app/api/email/[id]/raw/route.test.ts b/src/web/src/app/api/email/[id]/raw/route.test.tsdeleted file mode 100644index 7ab856e0f..000000000--- a/src/web/src/app/api/email/[id]/raw/route.test.ts+++ /dev/null@@ -1,93 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetEmailById = vi.fn();-const mockGetAgent = vi.fn();-const mockR2Get = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_BUCKET: {- get: (...args: unknown[]) => mockR2Get(...args),- },- },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- email: {- getEmailById: (...args: unknown[]) => mockGetEmailById(...args),- },- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { get: (...args: unknown[]) => mockR2Get(...args) } }, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET } from "./route";--describe("GET /api/email/[id]/raw", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns full raw MIME with content-type message/rfc822", async () => {- const rawMime = "From: [email protected]\r\nSubject: Hello\r\n\r\nBody content";- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/e1/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue({- body: new ReadableStream({- start(c) { c.enqueue(new TextEncoder().encode(rawMime)); c.close(); },- }),- });-- const req = new NextRequest("http://localhost/api/email/e1/raw");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- expect(res.headers.get("Content-Type")).toBe("message/rfc822");- const body = await res.text();- expect(body).toBe(rawMime);- });-- it("returns 404 when R2 object missing", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1", r2Key: "emails/e1/raw" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockR2Get.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1/raw");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-- it("returns 404 when email not in workspace", async () => {- mockGetEmailById.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1/raw");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/email/[id]/raw/route.ts b/src/web/src/app/api/email/[id]/raw/route.tsdeleted file mode 100644index 3ee1b93ac..000000000--- a/src/web/src/app/api/email/[id]/raw/route.ts+++ /dev/null@@ -1,30 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const object = await ctx.env.EMAIL_BUCKET.get(email.r2Key);- if (!object) {- return writeError("Email raw content not available", 404);- }-- return new Response(object.body, {- headers: { "Content-Type": "message/rfc822" },- });-});diff --git a/src/web/src/app/api/email/[id]/route.test.ts b/src/web/src/app/api/email/[id]/route.test.tsdeleted file mode 100644index 7046c654e..000000000--- a/src/web/src/app/api/email/[id]/route.test.ts+++ /dev/null@@ -1,197 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetEmailById = vi.fn();-const mockDeleteEmail = vi.fn();-const mockUpdateEmailStatus = vi.fn();-const mockGetAgent = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: { DB: {}, EMAIL_BUCKET: {} },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- email: {- getEmailById: (...args: unknown[]) => mockGetEmailById(...args),- deleteEmail: (...args: unknown[]) => mockDeleteEmail(...args),- updateEmailStatus: (...args: unknown[]) => mockUpdateEmailStatus(...args),- },- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", async () => {- const { NextResponse } = require("next/server");- const actual = await vi.importActual("@/lib/middleware/helpers");- return {- ...actual,- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/api/responses", () => ({- emailToResponse: (e: any) => ({ id: e.id, status: e.status }),-}));--import { GET, DELETE, PATCH } from "./route";--describe("GET /api/email/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns email scoped by workspaceId", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });-- const req = new NextRequest("http://localhost/api/email/e1");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- expect(mockGetEmailById).toHaveBeenCalledWith({}, "e1", "ws1");- });-- it("returns 404 when email not found (wrong workspace)", async () => {- mockGetEmailById.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1");- const res = await GET(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-});--describe("DELETE /api/email/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("deletes an email scoped by workspaceId and returns 204", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockDeleteEmail.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/email/e1", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(204);- expect(mockDeleteEmail).toHaveBeenCalledWith({}, "e1", "ws1");- });-- it("returns 404 when email not found", async () => {- mockGetEmailById.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-});--describe("PATCH /api/email/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("updates status for valid email in workspace", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "read" });-- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: JSON.stringify({ status: "read" }),- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ id: "e1", status: "read" });- expect(mockUpdateEmailStatus).toHaveBeenCalledWith({}, "e1", "ws1", "read");- });-- it("updates status to archived", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockUpdateEmailStatus.mockResolvedValue({ id: "e1", status: "archived" });-- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: JSON.stringify({ status: "archived" }),- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(200);- expect(mockUpdateEmailStatus).toHaveBeenCalledWith({}, "e1", "ws1", "archived");- });-- it("returns 404 when email not in workspace", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockUpdateEmailStatus.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: JSON.stringify({ status: "read" }),- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(404);- });-- it("returns 400 for invalid status value", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: JSON.stringify({ status: "deleted" }),- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("status"));- });-- it("returns 400 for missing status", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: JSON.stringify({}),- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(400);- });-- it("returns 400 for invalid JSON body", async () => {- mockGetEmailById.mockResolvedValue({ id: "e1", agentId: "a1" });- mockGetAgent.mockResolvedValue({ id: "a1" });- const req = new NextRequest("http://localhost/api/email/e1", {- method: "PATCH",- body: "not json",- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "e1" }) } as any);-- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/email/[id]/route.ts b/src/web/src/app/api/email/[id]/route.tsdeleted file mode 100644index 46fef706c..000000000--- a/src/web/src/app/api/email/[id]/route.ts+++ /dev/null@@ -1,68 +0,0 @@-import { queries, UpdateEmailStatusRequestSchema } from "@alook/shared";-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 { emailToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- return writeJSON(emailToResponse(email));-});--export const DELETE = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- await queries.email.deleteEmail(db, id, ws.workspaceId);-- return new Response(null, { status: 204 });-});--export const PATCH = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- const [body, valErr] = await parseBody(req, UpdateEmailStatusRequestSchema);- if (valErr) return valErr;-- const updated = await queries.email.updateEmailStatus(db, id, ws.workspaceId, body.status);- if (!updated) return writeError("not found", 404);-- return writeJSON(emailToResponse(updated));-});diff --git a/src/web/src/app/api/email/[id]/thread/route.test.ts b/src/web/src/app/api/email/[id]/thread/route.test.tsdeleted file mode 100644index 2d0545119..000000000--- a/src/web/src/app/api/email/[id]/thread/route.test.ts+++ /dev/null@@ -1,83 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetById = vi.fn();-const mockGetByMessageId = vi.fn();-const mockGetAgent = vi.fn();-vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- email: {- getEmailById: (...a: unknown[]) => mockGetById(...a),- getEmailByMessageId: (...a: unknown[]) => mockGetByMessageId(...a),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({ emailToResponse: (e: any) => ({ id: e.id }) }));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--const get = (params: Record<string, string>) => GET(new NextRequest("http://localhost/x"), { params });--describe("GET /api/email/[id]/thread", () => {- it("400 when email id missing", async () => {- const res = await get({});- expect(res.status).toBe(400);- });-- it("404 when email not in workspace", async () => {- mockGetById.mockResolvedValue(null);- const res = await get({ id: "e1" });- expect(res.status).toBe(404);- expect(mockGetById).toHaveBeenCalledWith({}, "e1", "w1");- });-- it("returns [] when the email has no parent", async () => {- mockGetById.mockResolvedValue({ id: "e1", agentId: "a1", inReplyTo: null });- mockGetAgent.mockResolvedValue({ id: "a1" });- const res = await get({ id: "e1" });- expect(res.status).toBe(200);- expect(await res.json()).toEqual([]);- });-- it("walks the reply chain oldest-first", async () => {- mockGetById.mockResolvedValue({ id: "e3", agentId: "a1", inReplyTo: "msg2" });- mockGetAgent.mockResolvedValue({ id: "a1" });- mockGetByMessageId- .mockResolvedValueOnce({ id: "e2", inReplyTo: "msg1" })- .mockResolvedValueOnce({ id: "e1", inReplyTo: null });- const res = await get({ id: "e3" });- expect(await res.json()).toEqual([{ id: "e1" }, { id: "e2" }]);- });-- it("stops at a cycle without infinite looping", async () => {- mockGetById.mockResolvedValue({ id: "e2", agentId: "a1", inReplyTo: "msgSelf" });- mockGetAgent.mockResolvedValue({ id: "a1" });- // parent points back to a message id already seen → loop guard breaks- mockGetByMessageId.mockResolvedValue({ id: "e1", inReplyTo: "msgSelf" });- const res = await get({ id: "e2" });- expect(res.status).toBe(200);- const body = await res.json();- expect(Array.isArray(body)).toBe(true);- });-});diff --git a/src/web/src/app/api/email/[id]/thread/route.ts b/src/web/src/app/api/email/[id]/thread/route.tsdeleted file mode 100644index c7a73a6e4..000000000--- a/src/web/src/app/api/email/[id]/thread/route.ts+++ /dev/null@@ -1,39 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { emailToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) return writeError("email id is required", 400);-- const email = await queries.email.getEmailById(db, id, ws.workspaceId);- if (!email) return writeError("not found", 404);-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("not found", 404);-- if (!email.inReplyTo) return writeJSON([]);-- const MAX_DEPTH = 50;- const thread: typeof email[] = [];- let currentReplyTo = email.inReplyTo;- const seen = new Set<string>();-- while (currentReplyTo && !seen.has(currentReplyTo) && thread.length < MAX_DEPTH) {- seen.add(currentReplyTo);- const parent = await queries.email.getEmailByMessageId(db, currentReplyTo, ws.workspaceId);- if (!parent) break;- thread.unshift(parent);- currentReplyTo = parent.inReplyTo;- }-- return writeJSON(thread.map(emailToResponse));-});diff --git a/src/web/src/app/api/email/[id]/trust/route.test.ts b/src/web/src/app/api/email/[id]/trust/route.test.tsdeleted file mode 100644index 3811bf806..000000000--- a/src/web/src/app/api/email/[id]/trust/route.test.ts+++ /dev/null@@ -1,237 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetEmailById = vi.fn();-const mockUpdateEmailWhitelisted = vi.fn();-const mockGetAgent = vi.fn();-const mockGetConversation = vi.fn();-const mockCreateConversation = vi.fn();-const mockCreateMessage = vi.fn();-const mockFindByKey = vi.fn();-const mockCreateMapping = vi.fn();-const mockEnqueueTask = vi.fn();-const mockGetUser = vi.fn();-const mockGetTask = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- email: {- getEmailById: (...args: unknown[]) => mockGetEmailById(...args),- updateEmailWhitelisted: (...args: unknown[]) => mockUpdateEmailWhitelisted(...args),- },- conversation: {- getConversation: (...args: unknown[]) => mockGetConversation(...args),- createConversation: (...args: unknown[]) => mockCreateConversation(...args),- },- message: {- createMessage: (...args: unknown[]) => mockCreateMessage(...args),- updateMessageTaskId: vi.fn().mockResolvedValue(undefined),- },- conversationMap: {- findByKey: (...args: unknown[]) => mockFindByKey(...args),- createMapping: (...args: unknown[]) => mockCreateMapping(...args),- },- user: { getUser: (...args: unknown[]) => mockGetUser(...args) },- task: { getTask: (...args: unknown[]) => mockGetTask(...args) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: Function) =>- (req: NextRequest) =>- handler(req, { env: {}, userId: "u1", email: "[email protected]", params: { id: req.url.split("/email/")[1]?.split("/")[0] } }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn().mockResolvedValue({ workspaceId: "ws1", memberRole: "owner" }),-}));--vi.mock("@/lib/middleware/helpers", async () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (msg: string, status: number) => NextResponse.json({ error: msg }, { status }),- };-});--vi.mock("@/lib/services/task", () => ({- TaskService: class {- enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }- },-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("@/lib/api/responses", () => ({- emailToResponse: (e: unknown) => e,- taskToResponse: (t: unknown) => t,-}));--vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockResolvedValue(undefined),- cacheKeys: {- overviewEmailStats: (wsId: string) => `email_stats:${wsId}`,- overviewTaskStats: (wsId: string, d: string) => `task_stats:${wsId}:${d}`,- },-}));--import { POST } from "./route";--const baseEmail = {- id: "e1",- agentId: "a1",- workspaceId: "ws1",- fromEmail: "[email protected]",- toEmail: "[email protected]",- subject: "Test email",- r2Key: "emails/fake/raw",- isWhitelisted: false,- forwarded: false,- messageId: "<[email protected]>",- inReplyTo: "",- references: "",- direction: "inbound" as const,- status: "unread",-};--const baseAgent = { id: "a1", workspaceId: "ws1", runtimeId: "r1", ownerId: "u1" };--function makeTrustReq(emailId: string) {- return new NextRequest(`http://localhost/api/email/${emailId}/trust`, { method: "POST" });-}--describe("POST /api/email/[id]/trust", () => {- beforeEach(() => {- vi.clearAllMocks();- mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "c1", role: "event", content: "", taskId: null, createdAt: "2026-01-01T00:00:00Z" });- mockFindByKey.mockResolvedValue(null);- mockCreateMapping.mockResolvedValue(undefined);- });-- it("TC1: trusts an untrust email — 200, conversation created, task enqueued", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail });- mockGetAgent.mockResolvedValue(baseAgent);- mockUpdateEmailWhitelisted.mockResolvedValue({ ...baseEmail, isWhitelisted: true });- mockCreateConversation.mockResolvedValue({ id: "conv_new" });- mockEnqueueTask.mockResolvedValue({ id: "t1" });-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(200);-- const json = await res.json();- expect(json.ok).toBe(true);- expect(json.conversationId).toBe("conv_new");- expect(json.email.isWhitelisted).toBe(true);-- expect(mockUpdateEmailWhitelisted).toHaveBeenCalledWith(expect.anything(), "e1", "ws1", true);- expect(mockCreateConversation).toHaveBeenCalledOnce();- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "conv_new", "ws1",- expect.stringContaining("New email from [email protected]"),- "email_notification",- expect.objectContaining({ contextKey: "conv_new" }),- );- });-- it("TC2: already trusted — 400", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail, isWhitelisted: true });-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(400);-- const json = await res.json();- expect(json.error).toMatch(/already trusted/);-- expect(mockUpdateEmailWhitelisted).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-- it("TC3: outbound email — 400", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail, direction: "outbound" });-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(400);-- const json = await res.json();- expect(json.error).toMatch(/only inbound/);- });-- it("TC4: email not found — 404", async () => {- mockGetEmailById.mockResolvedValue(null);-- const res = await POST(makeTrustReq("nonexistent"));- expect(res.status).toBe(404);- });-- it("TC5: agent has no runtime — 404", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail });- mockGetAgent.mockResolvedValue({ ...baseAgent, runtimeId: null });-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(404);-- expect(mockUpdateEmailWhitelisted).not.toHaveBeenCalled();- });-- it("TC7: thread resolution — reply threads into existing conversation", async () => {- const replyEmail = {- ...baseEmail,- id: "e_reply",- messageId: "<[email protected]>",- inReplyTo: "<[email protected]>",- references: "<[email protected]> <[email protected]>",- };- mockGetEmailById.mockResolvedValue(replyEmail);- mockGetAgent.mockResolvedValue(baseAgent);- mockUpdateEmailWhitelisted.mockResolvedValue({ ...replyEmail, isWhitelisted: true });- mockFindByKey.mockResolvedValue("conv_existing");- mockGetConversation.mockResolvedValue({ id: "conv_existing", type: "email_notification", userId: "u1" });- mockEnqueueTask.mockResolvedValue({ id: "t1" });-- const res = await POST(makeTrustReq("e_reply"));- expect(res.status).toBe(200);-- expect(mockFindByKey).toHaveBeenCalledWith(- expect.anything(),- "email:a1:<[email protected]>",- "ws1",- );- expect(mockCreateConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "conv_existing", "ws1",- expect.any(String),- "email_notification",- expect.objectContaining({ contextKey: "conv_existing" }),- );- });-- it("TC2b: idempotent — second trust call returns 400, no duplicate task", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail, isWhitelisted: true });-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(400);- expect(mockEnqueueTask).not.toHaveBeenCalled();- expect(mockCreateConversation).not.toHaveBeenCalled();- });-- it("TC5b: agent not found — 404", async () => {- mockGetEmailById.mockResolvedValue({ ...baseEmail });- mockGetAgent.mockResolvedValue(null);-- const res = await POST(makeTrustReq("e1"));- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/email/[id]/trust/route.ts b/src/web/src/app/api/email/[id]/trust/route.tsdeleted file mode 100644index b6384ec1e..000000000--- a/src/web/src/app/api/email/[id]/trust/route.ts+++ /dev/null@@ -1,45 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth"-import { withWorkspaceMember } from "@/lib/middleware/workspace"-import { writeJSON, writeError } from "@/lib/middleware/helpers"-import { emailToResponse } from "@/lib/api/responses"-import { broadcastToUser } from "@/lib/broadcast"-import { invalidate, cacheKeys } from "@/lib/cache"-import { dispatchEmailToAgent } from "@/lib/services/email-dispatch"--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx)- if (ws instanceof Response) return ws-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id- if (!id) return writeError("email id is required", 400)-- const email = await queries.email.getEmailById(db, id, ws.workspaceId)- if (!email) return writeError("email not found", 404)-- if (email.isWhitelisted) return writeError("email is already trusted", 400)- if (email.direction !== "inbound") return writeError("only inbound emails can be trusted", 400)-- const agent = await queries.agent.getAgent(db, email.agentId, ws.workspaceId, ctx.userId)- if (!agent || !agent.runtimeId || !agent.ownerId) return writeError("agent not found or has no runtime", 404)-- const updatedEmail = await queries.email.updateEmailWhitelisted(db, id, ws.workspaceId, true)- if (!updatedEmail) return writeError("failed to update email", 500)-- const { conversationId } = await dispatchEmailToAgent(db, updatedEmail, agent)-- const dateStr = new Date().toISOString().slice(0, 10)- await Promise.all([- invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)),- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)),- ])-- if (agent.ownerId) {- broadcastToUser(agent.ownerId, { type: "email.received", agentId: agent.id }).catch(() => {})- }-- return writeJSON({ ok: true, email: emailToResponse(updatedEmail), conversationId })-})diff --git a/src/web/src/app/api/email/route.test.ts b/src/web/src/app/api/email/route.test.tsdeleted file mode 100644index 56b01aceb..000000000--- a/src/web/src/app/api/email/route.test.ts+++ /dev/null@@ -1,200 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockGetEmailsByAgent = vi.fn();-const mockGetInboxEmails = vi.fn();-const mockGetTrustedEmails = vi.fn();-const mockGetSentEmails = vi.fn();-const mockGetRejectedEmails = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- toAlookAddress: (h: string) => `${h}@alook.ai`,- queries: {- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- email: {- getEmailsByAgent: (...args: unknown[]) => mockGetEmailsByAgent(...args),- getInboxEmails: (...args: unknown[]) => mockGetInboxEmails(...args),- getTrustedEmails: (...args: unknown[]) => mockGetTrustedEmails(...args),- getSentEmails: (...args: unknown[]) => mockGetSentEmails(...args),- getRejectedEmails: (...args: unknown[]) => mockGetRejectedEmails(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/api/responses", () => ({- emailToResponse: (e: any) => e,-}));--import { GET } from "./route";--describe("GET /api/email", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns all emails for agent (no status filter)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetInboxEmails.mockResolvedValue([{ id: "e1" }, { id: "e2" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1");- const res = await GET(req, {} as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);- });-- it("filters by status=unread", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetInboxEmails.mockResolvedValue([{ id: "e1", status: "unread" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&status=unread");- const res = await GET(req, {} as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread", undefined);- });-- it("filters by status and folder=inbox (whitelisted inbound)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetTrustedEmails.mockResolvedValue([{ id: "e1" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=inbox&status=unread");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetTrustedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "unread", undefined);- });-- it("filters by folder=untrust (non-whitelisted inbound)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetRejectedEmails.mockResolvedValue([{ id: "e2" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=untrust");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetRejectedEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);- });-- it("filters by status and folder=sent", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetSentEmails.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=sent&status=read");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", "read", undefined);- });-- it("returns 400 for invalid status value", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });-- const req = new NextRequest("http://localhost/api/email?agentId=a1&status=invalid");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("invalid status");- });-- it("passes limit and offset to query function", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetInboxEmails.mockResolvedValue([{ id: "e1" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=10&offset=5");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, { limit: 10, offset: 5 });- });-- it("passes pagination to folder-specific queries", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetSentEmails.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1&folder=sent&limit=20&offset=10");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetSentEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, { limit: 20, offset: 10 });- });-- it("returns 400 for non-numeric limit", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });-- const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=abc");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("limit");- });-- it("returns 400 for negative limit", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });-- const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=-1");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- });-- it("returns 400 for limit exceeding 100", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });-- const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=101");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- });-- it("returns 400 for negative offset", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });-- const req = new NextRequest("http://localhost/api/email?agentId=a1&limit=10&offset=-5");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- });-- it("does not pass pagination when limit is omitted (backward compat)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test" });- mockGetInboxEmails.mockResolvedValue([{ id: "e1" }]);-- const req = new NextRequest("http://localhost/api/email?agentId=a1");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockGetInboxEmails).toHaveBeenCalledWith({}, "a1", "[email protected]", "ws1", undefined, undefined);- });-});diff --git a/src/web/src/app/api/email/route.ts b/src/web/src/app/api/email/route.tsdeleted file mode 100644index 52ddeaa03..000000000--- a/src/web/src/app/api/email/route.ts+++ /dev/null@@ -1,57 +0,0 @@-import { NextRequest } from "next/server";-import { queries, toAlookAddress } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { emailToResponse } from "@/lib/api/responses";--const VALID_STATUSES = ["unread", "read", "archived", "sent", "blocked"];--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = req.nextUrl.searchParams.get("agentId");- if (!agentId) return writeError("agentId is required", 400);-- const agent = await queries.agent.getAgent(db, agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found in workspace", 404);-- const status = req.nextUrl.searchParams.get("status") ?? undefined;- if (status && !VALID_STATUSES.includes(status)) {- return writeError("invalid status", 400);- }-- const folder = req.nextUrl.searchParams.get("folder");- const address = req.nextUrl.searchParams.get("address");- const agentEmail = address || (agent.emailHandle ? toAlookAddress(agent.emailHandle) : "");-- const limitParam = req.nextUrl.searchParams.get("limit");- const offsetParam = req.nextUrl.searchParams.get("offset");- let pagination: { limit: number; offset: number } | undefined;- if (limitParam != null) {- const limit = parseInt(limitParam, 10);- if (isNaN(limit) || limit < 1 || limit > 100) return writeError("limit must be an integer between 1 and 100", 400);- const offset = offsetParam != null ? parseInt(offsetParam, 10) : 0;- if (isNaN(offset) || offset < 0) return writeError("offset must be a non-negative integer", 400);- pagination = { limit, offset };- }-- let emailList;- if (folder === "inbox" && agentEmail) {- emailList = await queries.email.getTrustedEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);- } else if (folder === "sent" && agentEmail) {- emailList = await queries.email.getSentEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);- } else if (folder === "untrust" && agentEmail) {- emailList = await queries.email.getRejectedEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);- } else if (folder === "all") {- emailList = await queries.email.getEmailsByAgent(db, agentId, ws.workspaceId, status, pagination);- } else {- emailList = await queries.email.getInboxEmails(db, agentId, agentEmail, ws.workspaceId, status, pagination);- }-- return writeJSON(emailList.map(emailToResponse));-});diff --git a/src/web/src/app/api/email/send/route.test.ts b/src/web/src/app/api/email/send/route.test.tsdeleted file mode 100644index ad08b42ad..000000000--- a/src/web/src/app/api/email/send/route.test.ts+++ /dev/null@@ -1,967 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockGetAgentByHandle = vi.fn();-const mockCreateEmail = vi.fn();-const mockIsWhitelisted = vi.fn();-const mockGetEmailAccountsByAgent = vi.fn();-const mockGetEmailAccountScoped = vi.fn();-const mockEmailWorkerFetch = vi.fn();-const mockEmailBucketGet = vi.fn();-const mockEmailBucketPut = vi.fn();-const mockWorkerSelfRefFetch = vi.fn();-const mockCreateMapping = vi.fn();-const mockGetConversation = vi.fn();-const mockCreateMessage = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_WORKER: { fetch: (...args: unknown[]) => mockEmailWorkerFetch(...args) },- EMAIL_BUCKET: {- get: (...args: unknown[]) => mockEmailBucketGet(...args),- put: (...args: unknown[]) => mockEmailBucketPut(...args),- },- WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockWorkerSelfRefFetch(...args) },- },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: string, _ttl: number, fn: () => Promise<any>) => fn()),- invalidate: vi.fn(() => Promise.resolve()),- cacheKeys: {- allEmailAccounts: (ws: string) => `ea:${ws}`,- overviewEmailStats: (ws: string) => `ov_email:${ws}`,- },-}));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- email: {- createEmail: (...args: unknown[]) => mockCreateEmail(...args),- },- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- getAgentByHandle: (...args: unknown[]) => mockGetAgentByHandle(...args),- },- whitelist: {- isWhitelisted: (...args: unknown[]) => mockIsWhitelisted(...args),- },- emailAccount: {- getEmailAccountsByAgent: (...args: unknown[]) => mockGetEmailAccountsByAgent(...args),- getEmailAccountScoped: (...args: unknown[]) => mockGetEmailAccountScoped(...args),- getAllEmailAccountsForWorkspace: (...args: unknown[]) => mockGetEmailAccountsByAgent(...args),- },- conversation: {- getConversation: (...args: unknown[]) => mockGetConversation(...args),- },- conversationMap: {- createMapping: (...args: unknown[]) => mockCreateMapping(...args),- },- message: {- createMessage: (...args: unknown[]) => mockCreateMessage(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_WORKER: { fetch: (...args: unknown[]) => mockEmailWorkerFetch(...args) }, EMAIL_BUCKET: { get: (...args: unknown[]) => mockEmailBucketGet(...args), put: (...args: unknown[]) => mockEmailBucketPut(...args) }, WORKER_SELF_REFERENCE: { fetch: (...args: unknown[]) => mockWorkerSelfRefFetch(...args) } }, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", async () => {- const { NextResponse } = require("next/server");- const actual = await vi.importActual("@/lib/middleware/helpers");- return {- ...actual,- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/api/responses", () => ({- emailToResponse: (e: any) => e,-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));--import { POST } from "./route";--function makeReq(body: Record<string, unknown>) {- return new NextRequest("http://localhost/api/email/send?workspace_id=ws1", {- method: "POST",- body: JSON.stringify(body),- });-}--describe("POST /api/email/send", () => {- beforeEach(() => vi.clearAllMocks());-- it("sends email via EMAIL_WORKER and returns the created record", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockEmailWorkerFetch.mockResolvedValue(- Response.json({ ok: true, r2Key: "emails/abc/raw" }),- );- mockCreateEmail.mockResolvedValue({- id: "e1", agentId: "a1", fromEmail: "[email protected]",- toEmail: "[email protected]", subject: "Hello",- });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi there</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- // Verify EMAIL_WORKER was called- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- const [url, init] = mockEmailWorkerFetch.mock.calls[0];- expect(url).toBe("http://internal/send/agent");- expect(init.method).toBe("POST");- const fetchBody = JSON.parse(init.body);- expect(fetchBody.agentId).toBe("a1");- expect(fetchBody.to).toBe("[email protected]");- expect(fetchBody.subject).toBe("Hello");- expect(fetchBody.htmlBody).toBe("<p>Hi there</p>");- expect(fetchBody.attachmentKeys).toBeUndefined();-- // Verify DB record created with r2Key from email worker- expect(mockCreateEmail).toHaveBeenCalledOnce();- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.r2Key).toBe("emails/abc/raw");- });-- it("sends email with attachments via EMAIL_WORKER", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockEmailWorkerFetch.mockResolvedValue(- Response.json({ ok: true, r2Key: "emails/def/raw" }),- );- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const attachments = [- { key: "emails/drafts/x/doc.txt", filename: "doc.txt", size: 12, contentType: "text/plain" },- ];-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "With attachment",- htmlBody: "<p>See attached</p>",- attachments,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- // Verify attachmentKeys sent to email worker- const fetchBody = JSON.parse(mockEmailWorkerFetch.mock.calls[0][1].body);- expect(fetchBody.attachmentKeys).toEqual([- { key: "emails/drafts/x/doc.txt", filename: "doc.txt", contentType: "text/plain" },- ]);-- // Verify full attachments stored in DB record- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.attachments).toBe(JSON.stringify(attachments));- });-- it("returns error when EMAIL_WORKER fails", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockEmailWorkerFetch.mockResolvedValue(- new Response(JSON.stringify({ error: "agent not found" }), { status: 404 }),- );-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(404);- });-- it("returns 400 when agent has no emailHandle", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: null });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(400);- });-- it("returns 404 when agent not in workspace", async () => {- mockGetAgent.mockResolvedValue(null);-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Hello",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(404);- });-- it("returns 400 when required fields are missing", async () => {- const req = makeReq({ agentId: "a1" });-- const res = await POST(req, {} as any);- expect(res.status).toBe(400);- });-- // --- Local delivery tests ----- describe("local delivery shortcut", () => {- it("delivers locally when recipient is same-workspace @alook.ai agent", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(true);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1", direction: "outbound" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Hello local",- htmlBody: "<p>Internal</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();-- const [url, init] = mockWorkerSelfRefFetch.mock.calls[0];- expect(url).toBe("http://internal/api/email/notify");- const payload = JSON.parse(init.body);- expect(payload.agentId).toBe("a2");- expect(payload.workspaceId).toBe("ws1");- expect(payload.from).toBe("[email protected]");- expect(payload.to).toBe("[email protected]");- expect(payload.subject).toBe("Hello local");- expect(payload.forwarded).toBe(false);- expect(payload.r2Key).toMatch(/^emails\/.+\/raw$/);-- expect(mockCreateEmail).toHaveBeenCalledOnce();- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.direction).toBe("outbound");- expect(createArgs.toEmail).toBe("[email protected]");- });-- it("falls through to EMAIL_WORKER when recipient is in different workspace", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws-other" });- mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Cross workspace",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- });-- it("falls through to EMAIL_WORKER when handle doesn't resolve to any agent", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue(null);- mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "No agent",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- });-- it("falls through to EMAIL_WORKER when recipient is not @alook.ai", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "External",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockGetAgentByHandle).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- });-- it("allows self-send via local delivery", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Self",- htmlBody: "<p>Self</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();- });-- it("fetches attachments from R2 and includes them in MIME for local delivery", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const fileContent = new TextEncoder().encode("hello file");- mockEmailBucketGet.mockResolvedValue({- arrayBuffer: () => Promise.resolve(fileContent.buffer),- });- mockEmailBucketPut.mockResolvedValue(undefined);-- const attachments = [- { key: "emails/drafts/x/doc.txt", filename: "doc.txt", size: 10, contentType: "text/plain" },- ];-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "With file",- htmlBody: "<p>See attached</p>",- attachments,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/doc.txt");- expect(mockEmailBucketPut).toHaveBeenCalledOnce();- const [putKey, putBody, putOpts] = mockEmailBucketPut.mock.calls[0];- expect(putKey).toMatch(/^emails\/.+\/raw$/);- expect(putBody).toContain("multipart/mixed");- expect(putBody).toContain('filename="doc.txt"');- expect(putOpts.httpMetadata.contentType).toBe("message/rfc822");- });-- it("fetches multiple attachments from R2 in parallel for local delivery", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const file1 = new TextEncoder().encode("file one");- const file2 = new TextEncoder().encode("file two");- const file3 = new TextEncoder().encode("file three");- mockEmailBucketGet- .mockResolvedValueOnce({ arrayBuffer: () => Promise.resolve(file1.buffer) })- .mockResolvedValueOnce({ arrayBuffer: () => Promise.resolve(file2.buffer) })- .mockResolvedValueOnce({ arrayBuffer: () => Promise.resolve(file3.buffer) });- mockEmailBucketPut.mockResolvedValue(undefined);-- const attachments = [- { key: "emails/drafts/x/a.txt", filename: "a.txt", size: 8, contentType: "text/plain" },- { key: "emails/drafts/x/b.txt", filename: "b.txt", size: 8, contentType: "text/plain" },- { key: "emails/drafts/x/c.txt", filename: "c.txt", size: 10, contentType: "text/plain" },- ];-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Multi attach",- htmlBody: "<p>See files</p>",- attachments,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailBucketGet).toHaveBeenCalledTimes(3);- expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/a.txt");- expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/b.txt");- expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/c.txt");-- const putBody = mockEmailBucketPut.mock.calls[0][1] as string;- expect(putBody).toContain('filename="a.txt"');- expect(putBody).toContain('filename="b.txt"');- expect(putBody).toContain('filename="c.txt"');- });-- it("handles large attachments (>64KB) without RangeError", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- // Create a 100KB buffer — larger than the ~65,536 arg limit that caused the stack overflow- const largeBuffer = new Uint8Array(100 * 1024);- for (let i = 0; i < largeBuffer.length; i++) largeBuffer[i] = i % 256;- mockEmailBucketGet.mockResolvedValue({- arrayBuffer: () => Promise.resolve(largeBuffer.buffer),- });- mockEmailBucketPut.mockResolvedValue(undefined);-- const attachments = [- { key: "emails/drafts/x/large.bin", filename: "large.bin", size: 100 * 1024, contentType: "application/octet-stream" },- ];-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Large attachment",- htmlBody: "<p>Big file</p>",- attachments,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailBucketGet).toHaveBeenCalledWith("emails/drafts/x/large.bin");- const putBody = mockEmailBucketPut.mock.calls[0][1] as string;- expect(putBody).toContain('filename="large.bin"');- });-- it("skips attachments that return null from R2 in parallel fetch", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const file1 = new TextEncoder().encode("file one");- mockEmailBucketGet- .mockResolvedValueOnce({ arrayBuffer: () => Promise.resolve(file1.buffer) })- .mockResolvedValueOnce(null);- mockEmailBucketPut.mockResolvedValue(undefined);-- const attachments = [- { key: "emails/drafts/x/exists.txt", filename: "exists.txt", size: 8, contentType: "text/plain" },- { key: "emails/drafts/x/missing.txt", filename: "missing.txt", size: 5, contentType: "text/plain" },- ];-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Partial attach",- htmlBody: "<p>Partial</p>",- attachments,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailBucketGet).toHaveBeenCalledTimes(2);- const putBody = mockEmailBucketPut.mock.calls[0][1] as string;- expect(putBody).toContain('filename="exists.txt"');- expect(putBody).not.toContain('filename="missing.txt"');- });-- it("checks whitelist and passes result in notify payload", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(true);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Whitelist test",- htmlBody: "<p>Check</p>",- });-- await POST(req, {} as any);-- expect(mockIsWhitelisted).toHaveBeenCalledWith(- expect.anything(), "a2", "ws1", "[email protected]"- );- const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);- expect(payload.isWhitelisted).toBe(true);- });-- it("notify payload matches expected schema shape", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Schema test",- htmlBody: "<p>Schema</p>",- inReplyTo: "<[email protected]>",- references: "<[email protected]> <[email protected]>",- });-- await POST(req, {} as any);-- const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);- expect(payload.agentId).toBe("a2");- expect(payload.workspaceId).toBe("ws1");- expect(payload.from).toBe("[email protected]");- expect(payload.to).toBe("[email protected]");- expect(payload.subject).toBe("Schema test");- expect(payload.forwarded).toBe(false);- expect(payload.isWhitelisted).toBe(false);- expect(payload.r2Key).toMatch(/^emails\/.+\/raw$/);- expect(payload.messageId).toMatch(/^<.+@alook\.ai>$/);- expect(payload.inReplyTo).toBe("<[email protected]>");- expect(payload.references).toBe("<[email protected]> <[email protected]>");- });-- it("generates correct messageId and r2Key in outbound record", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "IDs test",- htmlBody: "<p>IDs</p>",- });-- await POST(req, {} as any);-- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.messageId).toMatch(/^<.+@alook\.ai>$/);- expect(createArgs.r2Key).toMatch(/^emails\/.+\/raw$/);- });-- it("skips local delivery when sender uses custom SMTP account", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetEmailAccountsByAgent.mockResolvedValue([- { id: "acct1", agentId: "a1", emailAddress: "[email protected]" },- ]);- mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- from: "[email protected]",- to: "[email protected]",- subject: "Custom SMTP",- htmlBody: "<p>Custom</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockGetAgentByHandle).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- });-- it("returns error when notify endpoint fails and does NOT create outbound record", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockEmailBucketPut.mockResolvedValue(undefined);- mockWorkerSelfRefFetch.mockResolvedValue(- new Response("notify validation error", { status: 400 }),- );-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Fail notify",- htmlBody: "<p>Fail</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(400);-- const body = await res.json();- expect(body.error).toContain("local delivery failed");- expect(mockCreateEmail).not.toHaveBeenCalled();- });- });-- describe("sensitive recipient domain blocking", () => {- it("blocks a sensitive recipient: persists status:blocked outbound record and does NOT send", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockCreateEmail.mockResolvedValue({ id: "e1", status: "blocked", direction: "outbound" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Sensitive",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();- expect(mockGetAgentByHandle).not.toHaveBeenCalled();-- expect(mockCreateEmail).toHaveBeenCalledOnce();- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.status).toBe("blocked");- expect(createArgs.direction).toBe("outbound");- expect(createArgs.r2Key).toBe("");- expect(createArgs.toEmail).toBe("[email protected]");- });-- it("blocks a display-name-wrapped sensitive recipient", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockCreateEmail.mockResolvedValue({ id: "e1", status: "blocked", direction: "outbound" });-- const req = makeReq({- agentId: "a1",- to: "Gov <[email protected]>",- subject: "Wrapped",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).not.toHaveBeenCalled();-- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.status).toBe("blocked");- expect(createArgs.toEmail).toBe("Gov <[email protected]>");- });-- it("does not block a normal external recipient (regression)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockEmailWorkerFetch.mockResolvedValue(Response.json({ ok: true, r2Key: "emails/x/raw" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Normal",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).toHaveBeenCalledOnce();- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.status).toBe("sent");- });-- it("does not block same-workspace @alook.ai internal delivery (regression)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1", direction: "outbound" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Internal",- htmlBody: "<p>Hi</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- expect(mockEmailWorkerFetch).not.toHaveBeenCalled();- expect(mockWorkerSelfRefFetch).toHaveBeenCalledOnce();- const createArgs = mockCreateEmail.mock.calls[0]![1] as any;- expect(createArgs.status).toBe("sent");- });- });-- describe("conversation_map mapping creation", () => {- it("creates mapping on local delivery when conversationId is provided", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_123" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Map test",- htmlBody: "<p>Map</p>",- conversationId: "conv_123",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);- expect(mockCreateMapping).toHaveBeenCalledOnce();- const args = mockCreateMapping.mock.calls[0]![1] as any;- expect(args.workspaceId).toBe("ws1");- expect(args.conversationId).toBe("conv_123");- expect(args.key).toMatch(/^email:a1:/);- });-- it("does NOT create mapping on local delivery without conversationId", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "No map",- htmlBody: "<p>No map</p>",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);- expect(mockCreateMapping).not.toHaveBeenCalled();- });-- it("creates mapping on remote delivery when conversationId and messageId are provided", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockEmailWorkerFetch.mockResolvedValue(- Response.json({ ok: true, r2Key: "emails/abc/raw", messageId: "<[email protected]>" }),- );- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_456" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Remote map",- htmlBody: "<p>Remote</p>",- conversationId: "conv_456",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);- expect(mockCreateMapping).toHaveBeenCalledOnce();- const args = mockCreateMapping.mock.calls[0]![1] as any;- expect(args.workspaceId).toBe("ws1");- expect(args.conversationId).toBe("conv_456");- expect(args.key).toBe("email:a1:<[email protected]>");- });-- it("does NOT create mapping when conversationId does not belong to workspace", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue(null);-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Bad conv",- htmlBody: "<p>Bad</p>",- conversationId: "conv_other_workspace",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);- expect(mockCreateMapping).not.toHaveBeenCalled();- });-- it("does NOT create mapping on remote delivery when messageId is undefined", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent" });- mockEmailWorkerFetch.mockResolvedValue(- Response.json({ ok: true, r2Key: "emails/abc/raw" }),- );- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_456" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Remote no msgid",- htmlBody: "<p>No id</p>",- conversationId: "conv_456",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);- expect(mockCreateMapping).not.toHaveBeenCalled();- });- });-- describe("cross-link metadata (targetConversationId)", () => {- it("passes senderConversationId in notify payload for internal non-self delivery (TC1)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1", ownerId: "u1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(true);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true, conversationId: "conv_b" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_a" });- mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "conv_a", role: "event", content: "", taskId: null, createdAt: "2026-01-01" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Cross link",- htmlBody: "<p>Hi</p>",- conversationId: "conv_a",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);- expect(payload.senderConversationId).toBe("conv_a");- expect(payload.senderAgentId).toBe("a1");- });-- it("stamps targetConversationId in outbound event metadata (TC1)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1", ownerId: "u1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(true);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true, conversationId: "conv_b" }));- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_a" });- mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "conv_a", role: "event", content: "", taskId: null, createdAt: "2026-01-01" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Cross link",- htmlBody: "<p>Hi</p>",- conversationId: "conv_a",- });-- await POST(req, {} as any);-- const metadataArg = mockCreateMessage.mock.calls[0]![1] as { metadata: string };- const parsed = JSON.parse(metadataArg.metadata);- expect(parsed.targetConversationId).toBe("conv_b");- expect(parsed.targetAgentId).toBe("a2");- expect(parsed.direction).toBe("outbound");- });-- it("does NOT include cross-link metadata for external emails (TC3)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "test-agent", ownerId: "u1" });- mockEmailWorkerFetch.mockResolvedValue(- Response.json({ ok: true, r2Key: "emails/abc/raw", messageId: "<[email protected]>" }),- );- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_a" });- mockCreateMessage.mockResolvedValue({ id: "m1", conversationId: "conv_a", role: "event", content: "", taskId: null, createdAt: "2026-01-01" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "External",- htmlBody: "<p>Hi</p>",- conversationId: "conv_a",- });-- await POST(req, {} as any);-- const metadataArg = mockCreateMessage.mock.calls[0]![1] as { metadata: string };- const parsed = JSON.parse(metadataArg.metadata);- expect(parsed.targetConversationId).toBeUndefined();- expect(parsed.targetAgentId).toBeUndefined();- });-- it("does NOT pass senderConversationId for self-send (TC16)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1", ownerId: "u1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockWorkerSelfRefFetch.mockResolvedValue(Response.json({ ok: true }));- mockCreateEmail.mockResolvedValue({ id: "e1" });- mockGetConversation.mockResolvedValue({ id: "conv_a" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Self send",- htmlBody: "<p>Self</p>",- conversationId: "conv_a",- });-- await POST(req, {} as any);-- const payload = JSON.parse(mockWorkerSelfRefFetch.mock.calls[0][1].body);- expect(payload.senderConversationId).toBeUndefined();- expect(payload.senderAgentId).toBeUndefined();- });-- it("notify failure does NOT create orphaned mapping (TC17)", async () => {- mockGetAgent.mockResolvedValue({ id: "a1", emailHandle: "sender-agent", workspaceId: "ws1" });- mockGetAgentByHandle.mockResolvedValue({ id: "a2", emailHandle: "agent-b", workspaceId: "ws1" });- mockIsWhitelisted.mockResolvedValue(false);- mockEmailBucketPut.mockResolvedValue(undefined);- mockWorkerSelfRefFetch.mockResolvedValue(- new Response("notify failed", { status: 500 }),- );- mockGetConversation.mockResolvedValue({ id: "conv_a" });-- const req = makeReq({- agentId: "a1",- to: "[email protected]",- subject: "Fail notify map",- htmlBody: "<p>Fail</p>",- conversationId: "conv_a",- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(500);- expect(mockCreateMapping).not.toHaveBeenCalled();- });- });-});diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.tsdeleted file mode 100644index b0c775e78..000000000--- a/src/web/src/app/api/email/send/route.ts+++ /dev/null@@ -1,313 +0,0 @@-import { NextRequest } from "next/server";-import { queries, DEV_EMAIL_WORKER_URL, DEV_WEB_URL, SendEmailRequestSchema, parseEmailHandle, toAlookAddress, buildMimeMessage, extractThreadId, buildEmailMapKey, isSensitiveRecipient } from "@alook/shared";-import { nanoid } from "nanoid";-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 { emailToResponse } from "@/lib/api/responses";-import { broadcastToUser } from "@/lib/broadcast";-import { cached, invalidate, cacheKeys } from "@/lib/cache";--async function broadcastEmailSentEvent(- db: Parameters<typeof queries.message.createMessage>[0],- conversationId: string,- ownerId: string,- agentId: string,- to: string,- subject: string,- emailId: string,- from: string,- targetConversationId?: string,- targetAgentId?: string,-) {- const eventContent = `Email sent to ${to}: ${subject}`;- const metadataObj = {- emailId, subject, from, to, direction: "outbound" as const,- ...(targetConversationId ? { targetConversationId, targetAgentId } : {}),- };- const metadata = JSON.stringify(metadataObj);- const eventMsg = await queries.message.createMessage(db, {- conversationId,- role: "event",- content: eventContent,- metadata,- });- broadcastToUser(ownerId, {- type: "conversation.message",- conversationId,- message: {- id: eventMsg.id,- conversation_id: eventMsg.conversationId,- role: eventMsg.role as "event",- content: eventMsg.content,- task_id: eventMsg.taskId,- attachment_ids: null,- metadata: metadataObj,- created_at: eventMsg.createdAt,- },- }).catch(() => {});- broadcastToUser(ownerId, { type: "email.sent", agentId }).catch(() => {});-}--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const cfEnv = ctx.env;- const db = getDb(cfEnv.DB);-- const [body, valErr] = await parseBody(req, SendEmailRequestSchema);- if (valErr) return valErr;-- const agent = await queries.agent.getAgent(db, body.agentId, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found in workspace", 404);-- let customAccountId = body.customAccountId;- let fromAddress: string;-- if (body.from && !customAccountId) {- const alookAddr = agent.emailHandle ? toAlookAddress(agent.emailHandle) : null;- if (body.from === alookAddr) {- fromAddress = alookAddr;- } else {- 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);- }- customAccountId = match.id;- fromAddress = match.emailAddress;- }- } else if (customAccountId) {- const account = await queries.emailAccount.getEmailAccountScoped(db, customAccountId, body.agentId, ws.workspaceId);- if (!account) {- return writeError("custom email account not found", 404);- }- fromAddress = account.emailAddress;- } else {- if (!agent.emailHandle) {- return writeError("agent has no email handle configured", 400);- }- fromAddress = toAlookAddress(agent.emailHandle);- }-- let validatedConversationId: string | undefined;- if (body.conversationId) {- const conv = await queries.conversation.getConversation(db, body.conversationId, ws.workspaceId);- if (conv) validatedConversationId = body.conversationId;- }-- const attachments = body.attachments ?? [];-- if (isSensitiveRecipient(body.to)) {- const email = await queries.email.createEmail(db, {- agentId: body.agentId,- workspaceId: ws.workspaceId,- fromEmail: fromAddress,- toEmail: body.to,- subject: body.subject,- r2Key: "",- isWhitelisted: false,- forwarded: false,- messageId: "",- inReplyTo: body.inReplyTo ?? "",- references: body.references ?? "",- htmlBody: body.htmlBody || "",- attachments: JSON.stringify(attachments),- direction: "outbound",- status: "blocked",- });- invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)).catch(() => {});- return writeJSON(emailToResponse(email));- }-- // Local delivery shortcut: same-workspace @alook.ai → @alook.ai- const senderHandle = parseEmailHandle(fromAddress);- const recipientHandle = parseEmailHandle(body.to);- if (senderHandle && recipientHandle) {- const recipientAgent = await queries.agent.getAgentByHandle(db, recipientHandle);- if (recipientAgent && recipientAgent.workspaceId === ws.workspaceId) {- const messageId = `<${nanoid()}@alook.ai>`;- const htmlBody = body.htmlBody || "";-- const fetchedAttachments = (await Promise.all(- attachments.map(async (att) => {- const obj = await cfEnv.EMAIL_BUCKET.get(att.key);- if (!obj) return null;- const raw = await obj.arrayBuffer();- const bytes = new Uint8Array(raw);- let binary = '';- for (let i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]!);- const base64 = btoa(binary);- return { filename: att.filename, contentType: att.contentType, base64 };- })- )).filter((a): a is { filename: string; contentType: string; base64: string } => a !== null);-- const rawMime = buildMimeMessage({- from: fromAddress,- to: body.to,- subject: body.subject,- messageId,- inReplyTo: body.inReplyTo,- references: body.references,- body: htmlBody,- bodyType: "text/html",- attachments: fetchedAttachments,- });-- const r2Id = nanoid();- const r2Key = `emails/${r2Id}/raw`;- await cfEnv.EMAIL_BUCKET.put(r2Key, rawMime, {- httpMetadata: { contentType: "message/rfc822" },- });-- const isWhitelisted = await queries.whitelist.isWhitelisted(db, recipientAgent.id, recipientAgent.workspaceId, fromAddress);-- const isSelfSend = body.agentId === recipientAgent.id;- const notifyPayload = JSON.stringify({- agentId: recipientAgent.id,- workspaceId: recipientAgent.workspaceId,- r2Key,- from: fromAddress,- to: body.to,- subject: body.subject,- isWhitelisted,- forwarded: false,- messageId,- inReplyTo: body.inReplyTo ?? "",- references: body.references ?? "",- isInternal: true,- ...(body.traceId ? { traceId: body.traceId } : {}),- ...(body.sourceTaskId ? { sourceTaskId: body.sourceTaskId } : {}),- ...(!isSelfSend && validatedConversationId ? { senderConversationId: validatedConversationId, senderAgentId: body.agentId } : {}),- });- const notifyInit = { method: "POST", headers: { "Content-Type": "application/json" }, body: notifyPayload };- let notifyRes: Response;- try {- notifyRes = await cfEnv.WORKER_SELF_REFERENCE!.fetch("http://internal/api/email/notify", notifyInit);- } catch {- notifyRes = await fetch(`${DEV_WEB_URL}/api/email/notify`, notifyInit);- }- if (!notifyRes.ok) {- const errBody = await notifyRes.text();- return writeError(`local delivery failed: ${errBody}`, notifyRes.status);- }-- const notifyData = await notifyRes.json() as { ok: boolean; conversationId?: string };-- const email = await queries.email.createEmail(db, {- agentId: body.agentId,- workspaceId: ws.workspaceId,- fromEmail: fromAddress,- toEmail: body.to,- subject: body.subject,- r2Key,- isWhitelisted: false,- forwarded: false,- messageId,- inReplyTo: body.inReplyTo ?? "",- references: body.references ?? "",- htmlBody,- attachments: JSON.stringify(attachments),- direction: "outbound",- status: "sent",- });-- invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)).catch(() => {});-- if (validatedConversationId) {- const threadId = extractThreadId(body.references, body.inReplyTo, messageId);- if (threadId) {- await queries.conversationMap.createMapping(db, {- key: buildEmailMapKey(body.agentId, threadId),- workspaceId: ws.workspaceId,- conversationId: validatedConversationId,- });- }- if (agent.ownerId) {- const outboundTargetConvId = !isSelfSend ? notifyData.conversationId : undefined;- const outboundTargetAgentId = !isSelfSend && outboundTargetConvId ? recipientAgent.id : undefined;- await broadcastEmailSentEvent(db, validatedConversationId, agent.ownerId, body.agentId, body.to, body.subject, email.id, fromAddress, outboundTargetConvId, outboundTargetAgentId);- }- }-- return writeJSON(emailToResponse(email));- }- }-- // Delegate sending + R2 archival to the email worker- const emailPayload = JSON.stringify({- agentId: body.agentId,- workspaceId: ws.workspaceId,- to: body.to,- subject: body.subject,- htmlBody: body.htmlBody || "",- inReplyTo: body.inReplyTo || "",- references: body.references || "",- customAccountId: customAccountId || undefined,- attachmentKeys: attachments.length > 0- ? attachments.map((a) => ({ key: a.key, filename: a.filename, contentType: a.contentType }))- : undefined,- });-- let emailRes: Response;- try {- emailRes = await cfEnv.EMAIL_WORKER.fetch("http://internal/send/agent", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: emailPayload,- });- } catch {- // Service binding not connected — fall back to direct URL (local dev)- emailRes = await fetch(`${DEV_EMAIL_WORKER_URL}/send/agent`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: emailPayload,- });- }-- if (!emailRes.ok) {- const errBody = await emailRes.text();- return writeError(`email worker error: ${errBody}`, emailRes.status);- }-- const emailResult = await emailRes.json() as { ok: boolean; r2Key: string; messageId?: string };-- // Create DB record- const email = await queries.email.createEmail(db, {- agentId: body.agentId,- workspaceId: ws.workspaceId,- fromEmail: fromAddress,- toEmail: body.to,- subject: body.subject,- r2Key: emailResult.r2Key,- isWhitelisted: false,- forwarded: false,- messageId: emailResult.messageId ?? "",- inReplyTo: body.inReplyTo ?? "",- references: body.references ?? "",- htmlBody: body.htmlBody || "",- attachments: JSON.stringify(attachments),- direction: "outbound",- status: "sent",- });-- invalidate(cacheKeys.overviewEmailStats(ws.workspaceId)).catch(() => {});-- if (validatedConversationId && emailResult.messageId) {- const threadId = extractThreadId(body.references, body.inReplyTo, emailResult.messageId);- if (threadId) {- await queries.conversationMap.createMapping(db, {- key: buildEmailMapKey(body.agentId, threadId),- workspaceId: ws.workspaceId,- conversationId: validatedConversationId,- });- }- if (agent.ownerId) {- await broadcastEmailSentEvent(db, validatedConversationId, agent.ownerId, body.agentId, body.to, body.subject, email.id, fromAddress);- }- }-- return writeJSON(emailToResponse(email));-});diff --git a/src/web/src/app/api/email/upload/route.test.ts b/src/web/src/app/api/email/upload/route.test.tsdeleted file mode 100644index a4e1662e6..000000000--- a/src/web/src/app/api/email/upload/route.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockR2Put = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_BUCKET: { put: (...args: unknown[]) => mockR2Put(...args) },- },- })),-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: (...args: unknown[]) => mockR2Put(...args) } }, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "ws1" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { POST } from "./route";--describe("POST /api/email/upload", () => {- beforeEach(() => vi.clearAllMocks());-- it("uploads a file and returns metadata", async () => {- mockR2Put.mockResolvedValue(undefined);-- const formData = new FormData();- formData.append("file", new File(["hello world"], "test.txt", { type: "text/plain" }));-- const req = new NextRequest("http://localhost/api/email/upload?workspace_id=ws1", {- method: "POST",- body: formData,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(200);-- const body = await res.json();- expect(body.filename).toBe("test.txt");- expect(body.size).toBe(11);- expect(body.contentType).toBe("text/plain");- expect(body.key).toContain("emails/drafts/");- expect(body.key).toContain("/test.txt");-- expect(mockR2Put).toHaveBeenCalledTimes(1);- });-- it("returns 400 when no file is provided", async () => {- const formData = new FormData();-- const req = new NextRequest("http://localhost/api/email/upload?workspace_id=ws1", {- method: "POST",- body: formData,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(400);- });-- it("returns 413 when file exceeds 10 MB", async () => {- // Create a file over 10MB- const bigContent = new Uint8Array(10 * 1024 * 1024 + 1);- const formData = new FormData();- formData.append("file", new File([bigContent], "huge.bin", { type: "application/octet-stream" }));-- const req = new NextRequest("http://localhost/api/email/upload?workspace_id=ws1", {- method: "POST",- body: formData,- });-- const res = await POST(req, {} as any);- expect(res.status).toBe(413);- expect(mockR2Put).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/email/upload/route.ts b/src/web/src/app/api/email/upload/route.tsdeleted file mode 100644index e72787283..000000000--- a/src/web/src/app/api/email/upload/route.ts+++ /dev/null@@ -1,44 +0,0 @@-import { NextRequest } from "next/server";-import { nanoid } from "nanoid";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const bucket = ctx.env.EMAIL_BUCKET;-- let formData: FormData;- try {- formData = await req.formData();- } catch {- return writeError("invalid form data", 400);- }-- const file = formData.get("file");- if (!file || !(file instanceof File)) {- return writeError("file is required", 400);- }-- if (file.size > MAX_FILE_SIZE) {- return writeError("file exceeds 10 MB limit", 413);- }-- const draftId = nanoid();- const key = `emails/drafts/${draftId}/${file.name}`;-- await bucket.put(key, await file.arrayBuffer(), {- httpMetadata: { contentType: file.type || "application/octet-stream" },- });-- return writeJSON({- key,- filename: file.name,- size: file.size,- contentType: file.type || "application/octet-stream",- });-});diff --git a/src/web/src/app/api/flags/[messageId]/route.test.ts b/src/web/src/app/api/flags/[messageId]/route.test.tsdeleted file mode 100644index 38b59ce4d..000000000--- a/src/web/src/app/api/flags/[messageId]/route.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockUnflagMessage = vi.fn();--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- messageFlag: {- unflagMessage: (...args: unknown[]) => mockUnflagMessage(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { DELETE } from "./route";--describe("DELETE /api/flags/[messageId]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 400 when messageId param is missing", async () => {- const req = new NextRequest("http://localhost/api/flags/", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({}) } as any);-- expect(res.status).toBe(400);- });-- it("unflag message and returns 204", async () => {- mockUnflagMessage.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/flags/m1", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({ messageId: "m1" }) } as any);-- expect(res.status).toBe(204);- expect(mockUnflagMessage).toHaveBeenCalledWith({}, "m1", "u1", "w1");- });-});diff --git a/src/web/src/app/api/flags/[messageId]/route.ts b/src/web/src/app/api/flags/[messageId]/route.tsdeleted file mode 100644index 0d4130a9d..000000000--- a/src/web/src/app/api/flags/[messageId]/route.ts+++ /dev/null@@ -1,20 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const messageId = ctx.params?.messageId;- if (!messageId) {- return new Response(null, { status: 400 });- }-- const db = getDb(ctx.env.DB);-- await queries.messageFlag.unflagMessage(db, messageId, ctx.userId, ws.workspaceId);- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/flags/count/route.test.ts b/src/web/src/app/api/flags/count/route.test.tsdeleted file mode 100644index 876c14b88..000000000--- a/src/web/src/app/api/flags/count/route.test.ts+++ /dev/null@@ -1,65 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockGetFlaggedCount = vi.fn();--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- messageFlag: {- getFlaggedCount: (...args: unknown[]) => mockGetFlaggedCount(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET } from "./route";--describe("GET /api/flags/count", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns the flagged message count", async () => {- mockGetFlaggedCount.mockResolvedValue(5);-- const req = new NextRequest("http://localhost/api/flags/count");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ count: 5 });- expect(mockGetFlaggedCount).toHaveBeenCalledWith({}, "u1", "w1");- });-- it("returns zero when no flagged messages", async () => {- mockGetFlaggedCount.mockResolvedValue(0);-- const req = new NextRequest("http://localhost/api/flags/count");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ count: 0 });- });-});diff --git a/src/web/src/app/api/flags/count/route.ts b/src/web/src/app/api/flags/count/route.tsdeleted file mode 100644index 154e892ce..000000000--- a/src/web/src/app/api/flags/count/route.ts+++ /dev/null@@ -1,17 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const count = await queries.messageFlag.getFlaggedCount(db, ctx.userId, ws.workspaceId);-- return writeJSON({ count });-});diff --git a/src/web/src/app/api/flags/route.test.ts b/src/web/src/app/api/flags/route.test.tsdeleted file mode 100644index 469377278..000000000--- a/src/web/src/app/api/flags/route.test.ts+++ /dev/null@@ -1,211 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const mockListFlaggedMessageIds = vi.fn();-const mockListFlaggedMessages = vi.fn();-const mockGetMessageWorkspaceId = vi.fn();-const mockFlagMessage = vi.fn();--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- messageFlag: {- listFlaggedMessageIds: (...args: unknown[]) => mockListFlaggedMessageIds(...args),- listFlaggedMessages: (...args: unknown[]) => mockListFlaggedMessages(...args),- getMessageWorkspaceId: (...args: unknown[]) => mockGetMessageWorkspaceId(...args),- flagMessage: (...args: unknown[]) => mockFlagMessage(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET, POST } from "./route";--describe("GET /api/flags", () => {- beforeEach(() => vi.clearAllMocks());-- describe("ids_only=true", () => {- it("returns 400 when conversation_id is missing", async () => {- const req = new NextRequest("http://localhost/api/flags?ids_only=true");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("conversation_id");- });-- it("returns message_ids when conversation_id is provided", async () => {- mockListFlaggedMessageIds.mockResolvedValue(["m1", "m2"]);-- const req = new NextRequest("http://localhost/api/flags?ids_only=true&conversation_id=c1");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ message_ids: ["m1", "m2"] });- expect(mockListFlaggedMessageIds).toHaveBeenCalledWith({}, "u1", "w1", "c1");- });- });-- describe("normal list", () => {- it("returns flagged messages with defaults (limit=30, no before)", async () => {- mockListFlaggedMessages.mockResolvedValue({ items: [{ id: "m1" }], hasMore: false });-- const req = new NextRequest("http://localhost/api/flags");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ items: [{ id: "m1" }], has_more: false });- expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 30, before: undefined });- });-- it("clamps limit to 1-100 range", async () => {- mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });-- const req = new NextRequest("http://localhost/api/flags?limit=200");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 100, before: undefined });- });-- it("clamps limit minimum to 1", async () => {- mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });-- const req = new NextRequest("http://localhost/api/flags?limit=-5");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 1, before: undefined });- });-- it("passes valid before timestamp", async () => {- mockListFlaggedMessages.mockResolvedValue({ items: [], hasMore: false });-- const req = new NextRequest("http://localhost/api/flags?before=2024-01-01T00:00:00Z");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(mockListFlaggedMessages).toHaveBeenCalledWith({}, "u1", "w1", { limit: 30, before: "2024-01-01T00:00:00Z" });- });-- it("returns 400 for invalid before timestamp", async () => {- const req = new NextRequest("http://localhost/api/flags?before=not-a-date");- const res = await GET(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("invalid before timestamp");- });- });-});--describe("POST /api/flags", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 400 when messageId is missing", async () => {- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toContain("messageId");- });-- it("returns 400 when body is not valid JSON", async () => {- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: "not json",- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(400);- });-- it("returns 404 when message workspace id is null", async () => {- mockGetMessageWorkspaceId.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: JSON.stringify({ messageId: "m1" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "message not found" });- });-- it("returns 404 when message belongs to different workspace", async () => {- mockGetMessageWorkspaceId.mockResolvedValue("other-workspace");-- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: JSON.stringify({ messageId: "m1" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "message not found" });- });-- it("returns 201 when message is newly flagged", async () => {- mockGetMessageWorkspaceId.mockResolvedValue("w1");- mockFlagMessage.mockResolvedValue({ id: "flag1" });-- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: JSON.stringify({ messageId: "m1" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(await res.json()).toEqual({ flagged: true });- expect(mockFlagMessage).toHaveBeenCalledWith({}, { messageId: "m1", userId: "u1", workspaceId: "w1" });- });-- it("returns 200 when message is already flagged", async () => {- mockGetMessageWorkspaceId.mockResolvedValue("w1");- mockFlagMessage.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/flags", {- method: "POST",- body: JSON.stringify({ messageId: "m1" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ flagged: true });- });-});diff --git a/src/web/src/app/api/flags/route.ts b/src/web/src/app/api/flags/route.tsdeleted file mode 100644index d12b33abd..000000000--- a/src/web/src/app/api/flags/route.ts+++ /dev/null@@ -1,65 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const idsOnly = req.nextUrl.searchParams.get("ids_only") === "true";- const conversationId = req.nextUrl.searchParams.get("conversation_id");-- if (idsOnly) {- if (!conversationId) {- return NextResponse.json({ error: "conversation_id is required when ids_only=true" }, { status: 400 });- }- const messageIds = await queries.messageFlag.listFlaggedMessageIds(db, ctx.userId, ws.workspaceId, conversationId);- return writeJSON({ message_ids: messageIds });- }-- const limitParam = req.nextUrl.searchParams.get("limit");- const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;- const before = req.nextUrl.searchParams.get("before") ?? undefined;-- if (before && isNaN(Date.parse(before))) {- return NextResponse.json({ error: "invalid before timestamp" }, { status: 400 });- }-- const result = await queries.messageFlag.listFlaggedMessages(db, ctx.userId, ws.workspaceId, { limit, before });-- return writeJSON({ items: result.items, has_more: result.hasMore });-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const body = await req.json().catch(() => null) as { messageId?: string } | null;- if (!body?.messageId) {- return NextResponse.json({ error: "messageId is required" }, { status: 400 });- }-- const db = getDb(ctx.env.DB);-- const msgWorkspaceId = await queries.messageFlag.getMessageWorkspaceId(db, body.messageId);-- if (!msgWorkspaceId) {- return writeError("message not found", 404);- }- if (msgWorkspaceId !== ws.workspaceId) {- return writeError("message not found", 404);- }-- const flag = await queries.messageFlag.flagMessage(db, {- messageId: body.messageId,- userId: ctx.userId,- workspaceId: ws.workspaceId,- });-- return writeJSON({ flagged: true }, flag ? 201 : 200);-});diff --git a/src/web/src/app/api/inbox/count/route.test.ts b/src/web/src/app/api/inbox/count/route.test.tsdeleted file mode 100644index 323fe2b78..000000000--- a/src/web/src/app/api/inbox/count/route.test.ts+++ /dev/null@@ -1,105 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetUnreadCount = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- inbox: {- getUnreadCount: (...args: unknown[]) => mockGetUnreadCount(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),- cacheKeys: { inboxCount: vi.fn(() => "test-key") },-}));--import { GET } from "./route";--describe("GET /api/inbox/count", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns unread count with default types", async () => {- mockGetUnreadCount.mockResolvedValue(5);-- const res = await GET(new NextRequest("http://localhost/api/inbox/count"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ count: 5 });- expect(mockGetUnreadCount).toHaveBeenCalledWith({}, "u1", "w1", ["user_dm_message"]);- });-- it("filters types param by valid types", async () => {- mockGetUnreadCount.mockResolvedValue(2);-- const res = await GET(- new NextRequest("http://localhost/api/inbox/count?types=calendar_event,email_notification")- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ count: 2 });- expect(mockGetUnreadCount).toHaveBeenCalledWith(- {},- "u1",- "w1",- ["calendar_event", "email_notification"]- );- });-- it("defaults to user_dm_message when all types are invalid", async () => {- mockGetUnreadCount.mockResolvedValue(0);-- await GET(new NextRequest("http://localhost/api/inbox/count?types=bogus"));-- expect(mockGetUnreadCount).toHaveBeenCalledWith({}, "u1", "w1", ["user_dm_message"]);- });-- it("returns count 0 when no unread items", async () => {- mockGetUnreadCount.mockResolvedValue(0);-- const res = await GET(new NextRequest("http://localhost/api/inbox/count"));- const body = await res.json();-- expect(body).toEqual({ count: 0 });- });-- it("uses cached wrapper with correct key and ttl", async () => {- mockGetUnreadCount.mockResolvedValue(3);- const { cached, cacheKeys } = await import("@/lib/cache");-- await GET(new NextRequest("http://localhost/api/inbox/count"));-- expect(cacheKeys.inboxCount).toHaveBeenCalledWith("u1", "w1", ["user_dm_message"]);- expect(cached).toHaveBeenCalledWith("test-key", 60, expect.any(Function));- });-});diff --git a/src/web/src/app/api/inbox/count/route.ts b/src/web/src/app/api/inbox/count/route.tsdeleted file mode 100644index e39555a34..000000000--- a/src/web/src/app/api/inbox/count/route.ts+++ /dev/null@@ -1,27 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const VALID_TYPES = ["user_dm_message", "calendar_event", "email_notification"];- const typesParam = req.nextUrl.searchParams.get("types");- const types = typesParam- ? typesParam.split(",").filter((t) => VALID_TYPES.includes(t))- : [];- const validTypes = types.length > 0 ? types : ["user_dm_message"];-- const count = await cached(cacheKeys.inboxCount(ctx.userId, ws.workspaceId, validTypes), 60, () =>- queries.inbox.getUnreadCount(db, ctx.userId, ws.workspaceId, validTypes)- );-- return writeJSON({ count });-});diff --git a/src/web/src/app/api/inbox/read-all/route.test.ts b/src/web/src/app/api/inbox/read-all/route.test.tsdeleted file mode 100644index 2fc70b47c..000000000--- a/src/web/src/app/api/inbox/read-all/route.test.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockMarkAllConversationsRead = vi.fn();-const mockInvalidateInboxCounts = vi.fn().mockResolvedValue(undefined);--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- inbox: {- markAllConversationsRead: (...args: unknown[]) => mockMarkAllConversationsRead(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/cache", () => ({- invalidateInboxCounts: (...args: unknown[]) => mockInvalidateInboxCounts(...args),-}));--import { POST } from "./route";--describe("POST /api/inbox/read-all", () => {- beforeEach(() => vi.clearAllMocks());-- it("marks all conversations read and returns 204", async () => {- mockMarkAllConversationsRead.mockResolvedValue(undefined);-- const res = await POST(- new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" })- );-- expect(res.status).toBe(204);- expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");- expect(mockInvalidateInboxCounts).toHaveBeenCalledWith("u1", "w1");- });-- it("does not fail if invalidateInboxCounts rejects", async () => {- mockMarkAllConversationsRead.mockResolvedValue(undefined);- mockInvalidateInboxCounts.mockRejectedValue(new Error("cache error"));-- const res = await POST(- new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" })- );-- expect(res.status).toBe(204);- expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");- });-- it("calls markAllConversationsRead with correct workspace and user", async () => {- mockMarkAllConversationsRead.mockResolvedValue(undefined);-- await POST(new NextRequest("http://localhost/api/inbox/read-all", { method: "POST" }));-- expect(mockMarkAllConversationsRead).toHaveBeenCalledTimes(1);- expect(mockMarkAllConversationsRead).toHaveBeenCalledWith({}, "u1", "w1");- });-});diff --git a/src/web/src/app/api/inbox/read-all/route.ts b/src/web/src/app/api/inbox/read-all/route.tsdeleted file mode 100644index 6508708c7..000000000--- a/src/web/src/app/api/inbox/read-all/route.ts+++ /dev/null@@ -1,18 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { invalidateInboxCounts } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- await queries.inbox.markAllConversationsRead(db, ctx.userId, ws.workspaceId);- invalidateInboxCounts(ctx.userId, ws.workspaceId).catch(() => {});-- return new NextResponse(null, { status: 204 });-});diff --git a/src/web/src/app/api/inbox/read/route.test.ts b/src/web/src/app/api/inbox/read/route.test.tsdeleted file mode 100644index 79a0f8ee9..000000000--- a/src/web/src/app/api/inbox/read/route.test.ts+++ /dev/null@@ -1,119 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetConversation = vi.fn();-const mockMarkConversationRead = vi.fn();-const mockInvalidateInboxCounts = vi.fn().mockResolvedValue(undefined);--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- conversation: {- getConversation: (...args: unknown[]) => mockGetConversation(...args),- },- inbox: {- markConversationRead: (...args: unknown[]) => mockMarkConversationRead(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/cache", () => ({- invalidateInboxCounts: (...args: unknown[]) => mockInvalidateInboxCounts(...args),-}));--import { POST } from "./route";--describe("POST /api/inbox/read", () => {- beforeEach(() => vi.clearAllMocks());-- function makeRequest(body?: string) {- return new NextRequest("http://localhost/api/inbox/read", {- method: "POST",- body,- headers: body !== undefined ? { "Content-Type": "application/json" } : {},- });- }-- it("returns 400 for invalid JSON body", async () => {- const res = await POST(makeRequest("not-json"));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid JSON body");- });-- it("returns 400 when conversationId is missing", async () => {- const res = await POST(makeRequest(JSON.stringify({})));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("conversationId is required");- });-- it("returns 400 when conversationId is empty string", async () => {- const res = await POST(makeRequest(JSON.stringify({ conversationId: "" })));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("conversationId is required");- });-- it("returns 404 when conversation not found", async () => {- mockGetConversation.mockResolvedValue(null);-- const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("conversation not found");- expect(mockGetConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-- it("returns 404 when conversation belongs to different user", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", userId: "other-user" });-- const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("conversation not found");- });-- it("marks conversation as read and returns 204", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });- mockMarkConversationRead.mockResolvedValue(undefined);-- const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));-- expect(res.status).toBe(204);- expect(mockMarkConversationRead).toHaveBeenCalledWith({}, "u1", "c1");- expect(mockInvalidateInboxCounts).toHaveBeenCalledWith("u1", "w1");- });-- it("does not fail if invalidateInboxCounts rejects", async () => {- mockGetConversation.mockResolvedValue({ id: "c1", userId: "u1" });- mockMarkConversationRead.mockResolvedValue(undefined);- mockInvalidateInboxCounts.mockRejectedValue(new Error("cache error"));-- const res = await POST(makeRequest(JSON.stringify({ conversationId: "c1" })));-- expect(res.status).toBe(204);- });-});diff --git a/src/web/src/app/api/inbox/read/route.ts b/src/web/src/app/api/inbox/read/route.tsdeleted file mode 100644index e30b6507e..000000000--- a/src/web/src/app/api/inbox/read/route.ts+++ /dev/null@@ -1,33 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { invalidateInboxCounts } from "@/lib/cache";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- let body: { conversationId?: string };- try {- body = await req.json();- } catch {- return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });- }- if (!body.conversationId) {- return NextResponse.json({ error: "conversationId is required" }, { status: 400 });- }-- const db = getDb(ctx.env.DB);-- const conv = await queries.conversation.getConversation(db, body.conversationId, ws.workspaceId);- if (!conv || conv.userId !== ctx.userId) {- return NextResponse.json({ error: "conversation not found" }, { status: 404 });- }-- await queries.inbox.markConversationRead(db, ctx.userId, body.conversationId);- invalidateInboxCounts(ctx.userId, ws.workspaceId).catch(() => {});-- return new NextResponse(null, { status: 204 });-});diff --git a/src/web/src/app/api/inbox/route.test.ts b/src/web/src/app/api/inbox/route.test.tsdeleted file mode 100644index 0f8d880a6..000000000--- a/src/web/src/app/api/inbox/route.test.ts+++ /dev/null@@ -1,156 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListUnreadConversations = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- inbox: {- listUnreadConversations: (...args: unknown[]) => mockListUnreadConversations(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET } from "./route";--describe("GET /api/inbox", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns items and has_more with default limit", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [{ id: "c1" }], hasMore: false });-- const res = await GET(new NextRequest("http://localhost/api/inbox"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({ items: [{ id: "c1" }], has_more: false });- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- { limit: 30, before: undefined, types: ["user_dm_message"] }- );- });-- it("clamps limit to minimum 1", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox?limit=-5"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ limit: 1 })- );- });-- it("clamps limit to maximum 100", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox?limit=999"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ limit: 100 })- );- });-- it("passes valid before timestamp", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox?before=2026-01-01T00:00:00Z"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ before: "2026-01-01T00:00:00Z" })- );- });-- it("returns 400 for invalid before timestamp", async () => {- const res = await GET(new NextRequest("http://localhost/api/inbox?before=not-a-date"));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid before timestamp");- expect(mockListUnreadConversations).not.toHaveBeenCalled();- });-- it("filters types param by valid types", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox?types=calendar_event,email_notification"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ types: ["calendar_event", "email_notification"] })- );- });-- it("ignores invalid types and defaults to user_dm_message", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox?types=bogus,invalid"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ types: ["user_dm_message"] })- );- });-- it("defaults to user_dm_message when no types param", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [], hasMore: false });-- await GET(new NextRequest("http://localhost/api/inbox"));-- expect(mockListUnreadConversations).toHaveBeenCalledWith(- {},- "u1",- "w1",- expect.objectContaining({ types: ["user_dm_message"] })- );- });-- it("returns has_more true when there are more items", async () => {- mockListUnreadConversations.mockResolvedValue({ items: [{ id: "c1" }], hasMore: true });-- const res = await GET(new NextRequest("http://localhost/api/inbox?limit=1"));- const body = await res.json();-- expect(body.has_more).toBe(true);- });-});diff --git a/src/web/src/app/api/inbox/route.ts b/src/web/src/app/api/inbox/route.tsdeleted file mode 100644index da053b45a..000000000--- a/src/web/src/app/api/inbox/route.ts+++ /dev/null@@ -1,32 +0,0 @@-import { NextRequest, NextResponse } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const limitParam = req.nextUrl.searchParams.get("limit");- const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;- const before = req.nextUrl.searchParams.get("before") ?? undefined;-- if (before && isNaN(Date.parse(before))) {- return NextResponse.json({ error: "invalid before timestamp" }, { status: 400 });- }-- const VALID_TYPES = ["user_dm_message", "calendar_event", "email_notification"];- const typesParam = req.nextUrl.searchParams.get("types");- const types = typesParam- ? typesParam.split(",").filter((t) => VALID_TYPES.includes(t))- : [];- const validTypes = types.length > 0 ? types : ["user_dm_message"];-- const result = await queries.inbox.listUnreadConversations(db, ctx.userId, ws.workspaceId, { limit, before, types: validTypes });-- return writeJSON({ items: result.items, has_more: result.hasMore });-});diff --git a/src/web/src/app/api/invite/[token]/route.test.ts b/src/web/src/app/api/invite/[token]/route.test.tsdeleted file mode 100644index 0906aec2c..000000000--- a/src/web/src/app/api/invite/[token]/route.test.ts+++ /dev/null@@ -1,187 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetInviteByToken = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();-const mockRedeemInvite = vi.fn();-const mockCreateMember = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- workspaceInvite: {- getInviteByToken: (...args: unknown[]) => mockGetInviteByToken(...args),- redeemInvite: (...args: unknown[]) => mockRedeemInvite(...args),- },- member: {- getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),- createMember: (...args: unknown[]) => mockCreateMember(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--import { GET, POST } from "./route";--const futureDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();-const pastDate = new Date(Date.now() - 1000).toISOString();--const sampleInvite = {- id: "inv1",- workspaceId: "w1",- workspaceName: "Acme Corp",- workspaceSlug: "acme",- token: "tok-abc",- createdBy: "u2",- creatorName: "Alice",- creatorEmail: "[email protected]",- usedBy: null,- usedAt: null,- expiresAt: futureDate,- createdAt: "2024-01-01T00:00:00Z",-};--describe("GET /api/invite/[token]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns invite info for a valid token", async () => {- mockGetInviteByToken.mockResolvedValue(sampleInvite);-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.workspace_name).toBe("Acme Corp");- expect(body.workspace_id).toBe("w1");- expect(body.invited_by).toBe("Alice");- });-- it("uses creator email when creator name is null", async () => {- mockGetInviteByToken.mockResolvedValue({ ...sampleInvite, creatorName: null });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- const body = await res.json();-- expect(body.invited_by).toBe("[email protected]");- });-- it("returns 404 when invite not found", async () => {- mockGetInviteByToken.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/invite/bad-token", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ token: "bad-token" }) } as any);- expect(res.status).toBe(404);- });-- it("returns 410 when invite is already used", async () => {- mockGetInviteByToken.mockResolvedValue({ ...sampleInvite, usedBy: "u2" });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(410);- const body = await res.json();- expect(body.error).toBe("invite already used");- });-- it("returns 410 when invite is expired", async () => {- mockGetInviteByToken.mockResolvedValue({ ...sampleInvite, expiresAt: pastDate });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(410);- const body = await res.json();- expect(body.error).toBe("invite expired");- });-});--describe("POST /api/invite/[token]", () => {- beforeEach(() => vi.clearAllMocks());-- it("accepts a valid invite and creates membership", async () => {- mockGetInviteByToken.mockResolvedValue(sampleInvite);- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);- mockRedeemInvite.mockResolvedValue({ ...sampleInvite, usedBy: "u1" });- mockCreateMember.mockResolvedValue({ id: "m-new" });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.workspace_id).toBe("w1");- expect(body.workspace_slug).toBe("acme");- expect(mockRedeemInvite).toHaveBeenCalledWith({}, "tok-abc", "u1");- expect(mockCreateMember).toHaveBeenCalledWith(- {},- { workspaceId: "w1", userId: "u1", role: "member" }- );- });-- it("returns 409 when user is already a member", async () => {- mockGetInviteByToken.mockResolvedValue(sampleInvite);- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m-existing" });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(409);- const body = await res.json();- expect(body.error).toBe("already a member of this workspace");- });-- it("returns 410 when invite is already used", async () => {- mockGetInviteByToken.mockResolvedValue({ ...sampleInvite, usedBy: "u3" });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(410);- });-- it("returns 410 when invite is expired", async () => {- mockGetInviteByToken.mockResolvedValue({ ...sampleInvite, expiresAt: pastDate });-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(410);- const body = await res.json();- expect(body.error).toBe("invite expired");- });-- it("returns 404 when invite token not found", async () => {- mockGetInviteByToken.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/invite/bad-token", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "bad-token" }) } as any);- expect(res.status).toBe(404);- });-- it("returns 410 when redeemInvite returns null (race condition)", async () => {- mockGetInviteByToken.mockResolvedValue(sampleInvite);- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);- mockRedeemInvite.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/invite/tok-abc", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ token: "tok-abc" }) } as any);- expect(res.status).toBe(410);- });-});diff --git a/src/web/src/app/api/invite/[token]/route.ts b/src/web/src/app/api/invite/[token]/route.tsdeleted file mode 100644index 9850477ff..000000000--- a/src/web/src/app/api/invite/[token]/route.ts+++ /dev/null@@ -1,50 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { invalidate, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const { token } = ctx.params!;-- const db = getDb(ctx.env.DB);-- const invite = await queries.workspaceInvite.getInviteByToken(db, token);- if (!invite) return writeError("invite not found", 404);- if (invite.usedBy) return writeError("invite already used", 410);- if (new Date(invite.expiresAt) < new Date()) return writeError("invite expired", 410);-- return writeJSON({- workspace_name: invite.workspaceName,- workspace_id: invite.workspaceId,- invited_by: invite.creatorName || invite.creatorEmail,- });-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const { token } = ctx.params!;-- const db = getDb(ctx.env.DB);-- const invite = await queries.workspaceInvite.getInviteByToken(db, token);- if (!invite) return writeError("invite not found", 404);- if (invite.usedBy) return writeError("invite already used", 410);- if (new Date(invite.expiresAt) < new Date()) return writeError("invite expired", 410);-- const existing = await queries.member.getMemberByUserAndWorkspace(db, ctx.userId, invite.workspaceId);- if (existing) return writeError("already a member of this workspace", 409);-- const redeemed = await queries.workspaceInvite.redeemInvite(db, token, ctx.userId);- if (!redeemed) return writeError("invite already used", 410);-- await queries.member.createMember(db, {- workspaceId: invite.workspaceId,- userId: ctx.userId,- role: "member",- });-- await invalidate(cacheKeys.allMembers(invite.workspaceId));-- return writeJSON({ workspace_id: invite.workspaceId, workspace_slug: invite.workspaceSlug });-});diff --git a/src/web/src/app/api/issues/[id]/comments/route.test.ts b/src/web/src/app/api/issues/[id]/comments/route.test.tsdeleted file mode 100644index b152d8aef..000000000--- a/src/web/src/app/api/issues/[id]/comments/route.test.ts+++ /dev/null@@ -1,251 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetIssue = vi.fn();-const mockUpdateIssue = vi.fn();-const mockSetLatestTask = vi.fn();-const mockListComments = vi.fn();-const mockCreateComment = vi.fn();-const mockCommentToResponse = vi.fn((c: any) => ({- id: c.id,- content: c.content,- author_type: c.authorType,- author_id: c.authorId,- created_at: c.createdAt ?? "2026-01-01T00:00:00Z",-}));-const mockGetActiveTaskByConversation = vi.fn();-const mockGetTask = vi.fn();-const mockCreateTask = vi.fn();-const mockGetAgent = vi.fn();-const mockEnqueueTask = vi.fn();-const mockBroadcastToUser = vi.fn().mockResolvedValue(undefined);-const mockInvalidate = vi.fn().mockResolvedValue(undefined);-const mockIsTerminalIssueStatus = vi.fn(() => false);--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- CreateIssueCommentBodySchema: { parse: vi.fn((data: any) => data) },- TASK_TYPES: { ISSUE_EVENT: "issue_event" },- isTerminalIssueStatus: (...args: unknown[]) => mockIsTerminalIssueStatus(...args),- queries: {- issue: {- getIssue: (...a: unknown[]) => mockGetIssue(...a),- updateIssue: (...a: unknown[]) => mockUpdateIssue(...a),- setLatestTask: (...a: unknown[]) => mockSetLatestTask(...a),- },- issueComment: {- listComments: (...a: unknown[]) => mockListComments(...a),- createComment: (...a: unknown[]) => mockCreateComment(...a),- commentToResponse: (...a: unknown[]) => mockCommentToResponse(...a),- },- task: {- getActiveTaskByConversation: (...a: unknown[]) => mockGetActiveTaskByConversation(...a),- getTask: (...a: unknown[]) => mockGetTask(...a),- createTask: (...a: unknown[]) => mockCreateTask(...a),- },- agent: {- getAgent: (...a: unknown[]) => mockGetAgent(...a),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- parseBody: vi.fn(async (req: any) => {- const body = await req.json();- return [body, null];- }),- };-});--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),-}));--vi.mock("@/lib/services/task", () => ({- TaskService: class {- enqueueTask(...args: any[]) {- return mockEnqueueTask(...args);- }- },-}));--vi.mock("@/lib/cache", () => ({- invalidate: (...a: unknown[]) => mockInvalidate(...a),- cacheKeys: { overviewTaskStats: vi.fn(() => "test-key") },-}));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/issues/[id]/comments", () => {- it("returns 400 when id is missing", async () => {- const req = new NextRequest("http://localhost/api/issues//comments");- const res = await GET(req, { params: {} } as any);- expect(res.status).toBe(400);- expect(await res.json()).toEqual({ error: "issue id is required" });- });-- it("returns 404 when issue not found", async () => {- mockGetIssue.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/issues/iss_1/comments");- const res = await GET(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "issue not found" });- });-- it("returns comments for the issue", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo" });- mockListComments.mockResolvedValue([- { id: "c1", content: "Hello", authorType: "user", authorId: "u1", createdAt: "2026-01-01T00:00:00Z" },- { id: "c2", content: "World", authorType: "agent", authorId: "a1", createdAt: "2026-01-01T01:00:00Z" },- ]);-- const req = new NextRequest("http://localhost/api/issues/iss_1/comments");- const res = await GET(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(200);- const body = await res.json();- expect(body.comments).toHaveLength(2);- expect(body.comments[0]).toEqual({ id: "c1", content: "Hello", author_type: "user", author_id: "u1", created_at: "2026-01-01T00:00:00Z" });- expect(mockListComments).toHaveBeenCalledWith({}, "iss_1", "w1");- });-});--describe("POST /api/issues/[id]/comments", () => {- it("returns 400 when id is missing", async () => {- const req = new NextRequest("http://localhost/api/issues//comments", {- method: "POST",- body: JSON.stringify({ content: "test" }),- });- const res = await POST(req, { params: {} } as any);- expect(res.status).toBe(400);- expect(await res.json()).toEqual({ error: "issue id is required" });- });-- it("returns 404 when issue not found", async () => {- mockGetIssue.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {- method: "POST",- body: JSON.stringify({ content: "test" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "issue not found" });- });-- it("returns 403 when agentId does not match issue", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", agentId: "a1", status: "todo" });- const req = new NextRequest("http://localhost/api/issues/iss_1/comments?agentId=a_other", {- method: "POST",- body: JSON.stringify({ content: "test" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(403);- expect(await res.json()).toEqual({ error: "issue does not belong to agent" });- });-- it("creates a user comment without re-dispatch when status is terminal", async () => {- mockIsTerminalIssueStatus.mockReturnValue(true);- mockGetIssue.mockResolvedValue({- id: "iss_1", agentId: "a1", status: "done", conversationId: "conv_1", creatorUserId: "u1",- });- mockCreateComment.mockResolvedValue({- id: "ic_1", issueId: "iss_1", workspaceId: "w1", authorType: "user", authorId: "u1", content: "Nice", createdAt: "2026-01-01T00:00:00Z",- });- mockUpdateIssue.mockResolvedValue({ id: "iss_1" });-- const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {- method: "POST",- body: JSON.stringify({ content: "Nice" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);-- expect(res.status).toBe(201);- const body = await res.json();- expect(body.comment).toEqual({ id: "ic_1", content: "Nice", author_type: "user", author_id: "u1", created_at: "2026-01-01T00:00:00Z" });- expect(mockCreateComment).toHaveBeenCalledWith({}, expect.objectContaining({ issueId: "iss_1", authorType: "user", authorId: "u1", content: "Nice" }));- expect(mockUpdateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", {});- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({ type: "issue.comment", issueId: "iss_1" }));- // Should NOT trigger re-dispatch because status is terminal- expect(mockGetActiveTaskByConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-- it("creates a user comment and triggers re-dispatch when non-terminal and no active task", async () => {- mockIsTerminalIssueStatus.mockReturnValue(false);- mockGetIssue.mockResolvedValue({- id: "iss_1", agentId: "a1", status: "in_progress", conversationId: "conv_1", creatorUserId: "u1", latestTaskId: "t_prev", title: "Fix bug",- });- mockCreateComment.mockResolvedValue({- id: "ic_2", issueId: "iss_1", workspaceId: "w1", authorType: "user", authorId: "u1", content: "Please retry", createdAt: "2026-01-02T00:00:00Z",- });- mockUpdateIssue.mockResolvedValue({ id: "iss_1" });- mockGetActiveTaskByConversation.mockResolvedValue(null);- mockGetTask.mockResolvedValue({ id: "t_prev", traceId: "trace_1" });- mockEnqueueTask.mockResolvedValue({ id: "t_new" });- mockSetLatestTask.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/issues/iss_1/comments", {- method: "POST",- body: JSON.stringify({ content: "Please retry" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);-- expect(res.status).toBe(201);- expect(mockGetActiveTaskByConversation).toHaveBeenCalledWith({}, "conv_1", "w1");- expect(mockEnqueueTask).toHaveBeenCalledWith(- "a1", "conv_1", "w1",- expect.stringContaining("Please retry"),- "issue_event",- expect.objectContaining({ contextKey: "conv_1", context: { issue_id: "iss_1" }, traceId: "trace_1" }),- );- expect(mockSetLatestTask).toHaveBeenCalledWith({}, "iss_1", "w1", "t_new");- expect(mockInvalidate).toHaveBeenCalled();- });-- it("creates an agent comment without re-dispatch", async () => {- mockIsTerminalIssueStatus.mockReturnValue(false);- mockGetIssue.mockResolvedValue({- id: "iss_1", agentId: "a1", status: "in_progress", conversationId: "conv_1", creatorUserId: "u1",- });- mockCreateComment.mockResolvedValue({- id: "ic_3", issueId: "iss_1", workspaceId: "w1", authorType: "agent", authorId: "a1", content: "Working on it", createdAt: "2026-01-03T00:00:00Z",- });- mockUpdateIssue.mockResolvedValue({ id: "iss_1" });-- const req = new NextRequest("http://localhost/api/issues/iss_1/comments?agentId=a1", {- method: "POST",- body: JSON.stringify({ content: "Working on it" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);-- expect(res.status).toBe(201);- const body = await res.json();- expect(body.comment.author_type).toBe("agent");- expect(body.comment.author_id).toBe("a1");- expect(mockCreateComment).toHaveBeenCalledWith({}, expect.objectContaining({ authorType: "agent", authorId: "a1" }));- // Agent comments should NOT trigger re-dispatch- expect(mockGetActiveTaskByConversation).not.toHaveBeenCalled();- expect(mockEnqueueTask).not.toHaveBeenCalled();- });-});diff --git a/src/web/src/app/api/issues/[id]/comments/route.ts b/src/web/src/app/api/issues/[id]/comments/route.tsdeleted file mode 100644index 027d6d336..000000000--- a/src/web/src/app/api/issues/[id]/comments/route.ts+++ /dev/null@@ -1,107 +0,0 @@-import { NextRequest } from "next/server";-import {- CreateIssueCommentBodySchema,- TASK_TYPES,- isTerminalIssueStatus,- queries,-} from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";-import { broadcastToUser } from "@/lib/broadcast";-import { TaskService } from "@/lib/services/task";-import { invalidate, cacheKeys } from "@/lib/cache";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const issue = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!issue) return writeError("issue not found", 404);-- const comments = await queries.issueComment.listComments(db, id, ws.workspaceId);- return writeJSON({ comments: comments.map(queries.issueComment.commentToResponse) });-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const issue = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!issue) return writeError("issue not found", 404);-- const agentId = req.nextUrl.searchParams.get("agentId");- if (agentId && issue.agentId !== agentId) return writeError("issue does not belong to agent", 403);-- const [body, err] = await parseBody(req, CreateIssueCommentBodySchema);- if (err) return err;-- const authorType = agentId ? ("agent" as const) : ("user" as const);- const authorId = agentId ?? ctx.userId;-- const comment = await queries.issueComment.createComment(db, {- issueId: id,- workspaceId: ws.workspaceId,- authorType,- authorId,- content: body.content,- });-- await queries.issue.updateIssue(db, id, ws.workspaceId, {});-- const response = queries.issueComment.commentToResponse(comment);-- broadcastToUser(issue.creatorUserId, {- type: "issue.comment",- issueId: id,- comment: response,- }).catch(() => {});-- // Re-dispatch agent when user comments on a non-terminal, non-working issue- if (authorType === "user" && !isTerminalIssueStatus(issue.status) && issue.agentId && issue.conversationId) {- const activeTask = await queries.task.getActiveTaskByConversation(- db, issue.conversationId, ws.workspaceId- );- if (!activeTask) {- const taskService = new TaskService(db);- const prompt = `${issue.title}\n\nUser feedback: "${body.content}"`;--- try {- const existingTraceId = issue.latestTaskId- ? (await queries.task.getTask(db, issue.latestTaskId, ws.workspaceId))?.traceId ?? null- : null;-- const task = await taskService.enqueueTask(- issue.agentId,- issue.conversationId,- ws.workspaceId,- prompt,- TASK_TYPES.ISSUE_EVENT,- {- contextKey: issue.conversationId,- context: { issue_id: issue.id },- traceId: existingTraceId,- parentTaskId: null,- }- );- await queries.issue.setLatestTask(db, id, ws.workspaceId, task.id);- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- } catch {- // Non-fatal: comment is saved, dispatch failure doesn't block- }- }- }-- return writeJSON({ comment: response }, 201);-});diff --git a/src/web/src/app/api/issues/[id]/route.test.ts b/src/web/src/app/api/issues/[id]/route.test.tsdeleted file mode 100644index 5a01ebe9a..000000000--- a/src/web/src/app/api/issues/[id]/route.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetIssue = vi.fn();-const mockListIssueMessages = vi.fn();-const mockUpdateIssue = vi.fn();-const mockDeleteIssue = vi.fn();-const mockCreateMessage = vi.fn();-const mockListArtifactsByConversation = vi.fn();-const mockListComments = vi.fn();-const mockCreateComment = vi.fn();-const mockGetTask = vi.fn();-const mockGetAgent = vi.fn();-const mockCreateConversation = vi.fn();-const mockEnqueueTask = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- issue: {- getIssue: (...a: unknown[]) => mockGetIssue(...a),- listIssueMessages: (...a: unknown[]) => mockListIssueMessages(...a),- updateIssue: (...a: unknown[]) => mockUpdateIssue(...a),- deleteIssue: (...a: unknown[]) => mockDeleteIssue(...a),- setLatestTask: vi.fn(),- },- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- conversation: { createConversation: (...a: unknown[]) => mockCreateConversation(...a) },- task: {- getTask: (...a: unknown[]) => mockGetTask(...a),- },- message: { createMessage: (...a: unknown[]) => mockCreateMessage(...a) },- issueComment: {- listComments: (...a: unknown[]) => mockListComments(...a),- createComment: (...a: unknown[]) => mockCreateComment(...a),- commentToResponse: (c: any) => ({ id: c.id, content: c.content, author_type: c.authorType ?? "user", author_id: c.authorId ?? "u1", created_at: c.createdAt ?? new Date().toISOString() }),- },- artifact: {- listArtifactsByConversation: (...a: unknown[]) => mockListArtifactsByConversation(...a),- artifactToResponse: (a: any) => ({ id: a.id, filename: a.filename }),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- issueToResponse: (i: any) => ({ id: i.id, status: i.status, conversation_id: i.conversationId }),- messageToResponse: (m: any) => ({ id: m.id, role: m.role, content: m.content }),- taskToResponse: (t: any) => ({ id: t.id, status: t.status }),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--const mockBroadcastToUser = vi.fn().mockResolvedValue(undefined);-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),-}));--const mockCancelActiveTask = vi.fn();-const mockCancelTrace = vi.fn();-vi.mock("@/lib/services/task", () => ({- TaskService: class {- enqueueTask(...args: any[]) { return mockEnqueueTask(...args); }- cancelActiveTask(...args: any[]) { return mockCancelActiveTask(...args); }- cancelTrace(...args: any[]) { return mockCancelTrace(...args); }- },-}));--import { GET, PATCH, POST, DELETE } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/issues/[id]", () => {- it("returns issue and messages", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });- mockListIssueMessages.mockResolvedValue([{ id: "m1", role: "event", content: "Created" }]);- mockListComments.mockResolvedValue([]);- mockListArtifactsByConversation.mockResolvedValue([{ id: "art_1", filename: "brief.md" }]);- const res = await GET(new NextRequest("http://localhost/api/issues/iss_1"), { params: { id: "iss_1" } } as any);- expect(res.status).toBe(200);- expect(await res.json()).toEqual({- issue: { id: "iss_1", status: "todo", conversation_id: "c1", trace_id: null },- messages: [{ id: "m1", role: "event", content: "Created" }],- comments: [],- artifacts: [{ id: "art_1", filename: "brief.md" }],- });- expect(mockListArtifactsByConversation).toHaveBeenCalledWith({}, "c1", "w1");- });-});--describe("PATCH /api/issues/[id]", () => {- it("updates status and records status transition", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1" });- mockUpdateIssue.mockResolvedValue({ id: "iss_1", status: "in_progress", conversationId: "c1" });- mockCreateMessage.mockResolvedValue({ id: "m1", role: "event", content: "Issue status changed: todo -> in_progress" });- const req = new NextRequest("http://localhost/api/issues/iss_1", {- method: "PATCH",- body: JSON.stringify({ status: "in_progress" }),- });- const res = await PATCH(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(200);- expect(mockUpdateIssue).toHaveBeenCalledWith({}, "iss_1", "w1", { title: undefined, description: undefined, status: "in_progress" });- expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({ role: "event", content: "Issue status changed: todo -> in_progress" }));- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({ type: "conversation.message", conversationId: "c1" }));- });-- it("records a stable assignment failure when enqueue rejects with a non-Error", async () => {- mockGetIssue.mockResolvedValue({- id: "iss_1",- title: "Fix",- description: "Body",- status: "todo",- conversationId: null,- });- mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1" });- mockCreateConversation.mockResolvedValue({ id: "c1" });- mockUpdateIssue- .mockResolvedValueOnce({ id: "iss_1", status: "in_progress", conversationId: "c1" })- .mockResolvedValueOnce({ id: "iss_1", status: "todo", conversationId: "c1" });- mockCreateMessage.mockResolvedValue({ id: "m1", role: "event" });- mockEnqueueTask.mockRejectedValueOnce("queue unavailable");-- const res = await PATCH(new NextRequest("http://localhost/api/issues/iss_1", {- method: "PATCH",- body: JSON.stringify({ agent_id: "ag_1" }),- }), { params: { id: "iss_1" } } as any);-- expect(res.status).toBe(500);- expect(await res.json()).toEqual({ error: "failed to dispatch issue" });- expect(mockCreateMessage).toHaveBeenLastCalledWith({}, expect.objectContaining({- content: "Issue dispatch failed: reason unavailable",- }));- });-});--describe("POST /api/issues/[id]", () => {- it("adds a user comment for browser callers", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", status: "todo", conversationId: "c1", agentId: "a1" });- mockCreateComment.mockResolvedValue({ id: "ic_1", issueId: "iss_1", workspaceId: "w1", authorType: "user", authorId: "u1", content: "Looks good", createdAt: "2026-01-01T00:00:00Z" });- mockUpdateIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", {- method: "POST",- body: JSON.stringify({ content: "Looks good" }),- });- const res = await POST(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(201);- expect(mockCreateComment).toHaveBeenCalledWith({}, expect.objectContaining({ issueId: "iss_1", content: "Looks good", authorType: "user" }));- });-});--describe("DELETE /api/issues/[id]", () => {- it("deletes the issue and returns 204", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", conversationId: "c1", latestTaskId: null });- mockDeleteIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(204);- expect(mockDeleteIssue).toHaveBeenCalledWith({}, "iss_1", "w1");- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });- });-- it("cancels via traceId when latestTask has a traceId", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", conversationId: "c1", latestTaskId: "t1" });- mockGetTask.mockResolvedValue({ id: "t1", traceId: "trace_1" });- mockDeleteIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(204);- expect(mockCancelTrace).toHaveBeenCalledWith("trace_1", "w1", { reason: "Task cancelled: issue deleted" });- expect(mockCancelActiveTask).not.toHaveBeenCalled();- expect(mockDeleteIssue).toHaveBeenCalled();- });-- it("falls back to cancelActiveTask when latestTask has no traceId", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", conversationId: "c1", latestTaskId: "t1" });- mockGetTask.mockResolvedValue({ id: "t1", traceId: null });- mockDeleteIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(204);- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });- expect(mockCancelTrace).not.toHaveBeenCalled();- });-- it("falls back to cancelActiveTask when latestTaskId exists but task row is missing", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", conversationId: "c1", latestTaskId: "t_gone" });- mockGetTask.mockResolvedValue(null);- mockDeleteIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(204);- expect(mockCancelActiveTask).toHaveBeenCalledWith("c1", "w1", { reason: "Task cancelled: issue deleted" });- expect(mockCancelTrace).not.toHaveBeenCalled();- expect(mockDeleteIssue).toHaveBeenCalled();- });-- it("still deletes the issue when cancellation throws", async () => {- mockGetIssue.mockResolvedValue({ id: "iss_1", conversationId: "c1", latestTaskId: null });- mockCancelActiveTask.mockRejectedValue(new Error("cancel failed"));- mockDeleteIssue.mockResolvedValue({ id: "iss_1" });- const req = new NextRequest("http://localhost/api/issues/iss_1", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_1" } } as any);- expect(res.status).toBe(204);- expect(mockDeleteIssue).toHaveBeenCalledWith({}, "iss_1", "w1");- });-- it("returns 404 when issue does not exist", async () => {- mockGetIssue.mockResolvedValue(null);- const req = new NextRequest("http://localhost/api/issues/iss_999", { method: "DELETE" });- const res = await DELETE(req, { params: { id: "iss_999" } } as any);- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/issues/[id]/route.ts b/src/web/src/app/api/issues/[id]/route.tsdeleted file mode 100644index e6bba443b..000000000--- a/src/web/src/app/api/issues/[id]/route.ts+++ /dev/null@@ -1,225 +0,0 @@-import { NextRequest } from "next/server";-import {- CreateIssueCommentBodySchema,- UpdateIssueRequestSchema,- TASK_TYPES,- queries,-} from "@alook/shared";-import { nanoid } from "nanoid";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";-import { issueToResponse, messageToResponse, taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";-import { log } from "@/lib/logger";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const issue = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!issue) return writeError("issue not found", 404);- const agentId = req.nextUrl.searchParams.get("agentId");- if (agentId && issue.agentId !== agentId) return writeError("issue does not belong to agent", 403);-- let traceId: string | null = null;- if (issue.latestTaskId) {- const task = await queries.task.getTask(db, issue.latestTaskId, ws.workspaceId);- traceId = task?.traceId ?? null;- }-- const messages = await queries.issue.listIssueMessages(db, id, ws.workspaceId);- const comments = await queries.issueComment.listComments(db, id, ws.workspaceId);- const artifacts = issue.conversationId- ? await queries.artifact.listArtifactsByConversation(db, issue.conversationId, ws.workspaceId)- : [];- return writeJSON({- issue: { ...issueToResponse(issue), trace_id: traceId },- messages: (messages ?? []).map(messageToResponse),- comments: comments.map(queries.issueComment.commentToResponse),- artifacts: artifacts.map(queries.artifact.artifactToResponse),- });-});--export const PATCH = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const existing = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!existing) return writeError("issue not found", 404);- const agentId = req.nextUrl.searchParams.get("agentId");- if (agentId && existing.agentId !== agentId) return writeError("issue does not belong to agent", 403);-- const [body, err] = await parseBody(req, UpdateIssueRequestSchema);- if (err) return err;-- // Dispatch-on-assign: assigning an agent to a todo draft issue- if (body.agent_id) {- if (existing.status !== "todo") {- return writeError("Agent assignment is only allowed for todo (draft) issues", 400);- }-- const agent = await queries.agent.getAgent(db, body.agent_id, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found in workspace", 404);- if (!agent.ownerId) return writeError("agent has no owner", 400);-- const conversation = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: body.agent_id,- userId: ctx.userId,- title: `[Issue] ${existing.title}`.slice(0, 120),- type: TASK_TYPES.ISSUE_EVENT,- });-- const updated = await queries.issue.updateIssue(db, id, ws.workspaceId, {- agentId: body.agent_id,- conversationId: conversation.id,- status: "in_progress",- });- if (!updated) return writeError("issue not found", 404);-- await queries.message.createMessage(db, {- conversationId: conversation.id,- role: "event",- content: `Issue created: ${existing.title}`,- metadata: JSON.stringify({ issueId: existing.id, title: existing.title, event: "created" as const, agentId: body.agent_id }),- });-- const prompt = existing.description.trim()- ? `${existing.title}\n\n${existing.description}`- : existing.title;-- const taskService = new TaskService(db);- try {- const task = await taskService.enqueueTask(- body.agent_id,- conversation.id,- ws.workspaceId,- prompt,- TASK_TYPES.ISSUE_EVENT,- {- contextKey: conversation.id,- context: { issue_id: existing.id },- traceId: "tr_" + nanoid(),- parentTaskId: null,- }- );- const issue = await queries.issue.setLatestTask(db, id, ws.workspaceId, task.id) ?? updated;- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});- return writeJSON({- ...issueToResponse(issue),- task: taskToResponse(task),- });- } catch (taskErr) {- await queries.issue.updateIssue(db, id, ws.workspaceId, { status: "todo" });- await queries.message.createMessage(db, {- conversationId: conversation.id,- role: "event",- content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "reason unavailable"}`,- metadata: JSON.stringify({ issueId: existing.id, title: existing.title, event: "dispatch_failed" as const }),- });- return writeError(taskErr instanceof Error ? taskErr.message : "failed to dispatch issue", 500);- }- }-- const updated = await queries.issue.updateIssue(db, id, ws.workspaceId, {- title: body.title,- description: body.description,- status: body.status,- });- if (!updated) return writeError("issue not found", 404);-- if (body.status && body.status !== existing.status && existing.conversationId) {- const eventMsg = await queries.message.createMessage(db, {- conversationId: existing.conversationId,- role: "event",- content: `Issue status changed: ${existing.status} -> ${body.status}`,- metadata: JSON.stringify({ issueId: existing.id, title: existing.title, event: "status_changed" as const, fromStatus: existing.status, toStatus: body.status }),- });- broadcastToUser(ctx.userId, {- type: "conversation.message",- conversationId: existing.conversationId,- message: messageToResponse(eventMsg),- }).catch(() => {});- }-- return writeJSON(issueToResponse(updated));-});--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const issue = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!issue) return writeError("issue not found", 404);-- if (issue.conversationId) {- const taskService = new TaskService(db);- try {- const task = issue.latestTaskId- ? await queries.task.getTask(db, issue.latestTaskId, ws.workspaceId)- : null;- const reason = "Task cancelled: issue deleted";- if (task?.traceId) {- await taskService.cancelTrace(task.traceId, ws.workspaceId, { reason });- } else {- await taskService.cancelActiveTask(issue.conversationId, ws.workspaceId, { reason });- }- } catch (err) {- log.warn("failed to cancel tasks during issue deletion", { issueId: id, err });- }- }-- await queries.issue.deleteIssue(db, id, ws.workspaceId);-- return new Response(null, { status: 204 });-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const id = ctx.params?.id;- if (!id) return writeError("issue id is required", 400);-- const issue = await queries.issue.getIssue(db, id, ws.workspaceId, ctx.userId);- if (!issue) return writeError("issue not found", 404);- const agentId = req.nextUrl.searchParams.get("agentId");- if (agentId && issue.agentId !== agentId) return writeError("issue does not belong to agent", 403);-- const [body, err] = await parseBody(req, CreateIssueCommentBodySchema);- if (err) return err;-- const authorType = agentId ? ("agent" as const) : ("user" as const);- const authorId = agentId ?? ctx.userId;-- const comment = await queries.issueComment.createComment(db, {- issueId: id,- workspaceId: ws.workspaceId,- authorType,- authorId,- content: body.content,- });-- await queries.issue.updateIssue(db, id, ws.workspaceId, {});-- return writeJSON({ comment: queries.issueComment.commentToResponse(comment) }, 201);-});diff --git a/src/web/src/app/api/issues/route.test.ts b/src/web/src/app/api/issues/route.test.tsdeleted file mode 100644index 91d62cebc..000000000--- a/src/web/src/app/api/issues/route.test.ts+++ /dev/null@@ -1,189 +0,0 @@-import { describe, expect, it, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgent = vi.fn();-const mockListIssues = vi.fn();-const mockCreateConversation = vi.fn();-const mockCreateIssue = vi.fn();-const mockCreateMessage = vi.fn();-const mockSetLatestTask = vi.fn();-const mockEnqueueTask = vi.fn();-const mockCreateArtifact = vi.fn();-const mockR2Put = vi.fn();-const mockGetTraceAgentsByTaskIds = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({- env: {- DB: {},- EMAIL_BUCKET: { put: (...a: unknown[]) => mockR2Put(...a) },- },- })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- agent: { getAgent: (...a: unknown[]) => mockGetAgent(...a) },- task: { getTraceAgentsByTaskIds: (...a: unknown[]) => mockGetTraceAgentsByTaskIds(...a) },- issue: {- listIssues: (...a: unknown[]) => mockListIssues(...a),- createIssue: (...a: unknown[]) => mockCreateIssue(...a),- setLatestTask: (...a: unknown[]) => mockSetLatestTask(...a),- },- conversation: { createConversation: (...a: unknown[]) => mockCreateConversation(...a) },- message: { createMessage: (...a: unknown[]) => mockCreateMessage(...a), updateMessageTaskId: vi.fn().mockResolvedValue(undefined) },- artifact: { createArtifact: (...a: unknown[]) => mockCreateArtifact(...a) },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {}, EMAIL_BUCKET: { put: (...a: unknown[]) => mockR2Put(...a) } }, userId: "u1", email: "[email protected]", params });- },-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/services/task", () => ({- TaskService: function () {- return { enqueueTask: mockEnqueueTask };- },-}));--vi.mock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn(() => Promise.resolve()) }));--vi.mock("@/lib/api/responses", () => ({- issueToResponse: (i: any) => ({ id: i.id, agent_id: i.agentId, title: i.title, status: i.status }),- messageToResponse: (m: any) => ({ id: m.id, content: m.content }),- taskToResponse: (t: any) => ({ id: t.id, type: t.type }),-}));--import { GET, POST } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/issues", () => {- it("lists workspace issues with filters", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1" });- mockListIssues.mockResolvedValue([{ id: "iss_1", agentId: "ag_1", title: "Fix", status: "todo" }]);- mockGetTraceAgentsByTaskIds.mockResolvedValue(new Map());- const res = await GET(new NextRequest("http://localhost/api/issues?agentId=ag_1&terminal=false"), {} as any);- expect(res.status).toBe(200);- expect(await res.json()).toEqual([{ id: "iss_1", agent_id: "ag_1", title: "Fix", status: "todo", thread_agent_ids: [] }]);- expect(mockListIssues).toHaveBeenCalledWith({}, "w1", { userId: "u1", agentId: "ag_1", status: undefined, terminal: false });- });-- it("rejects invalid status", async () => {- const res = await GET(new NextRequest("http://localhost/api/issues?status=bad"), {} as any);- expect(res.status).toBe(400);- });-});--describe("POST /api/issues", () => {- it("creates issue conversation and dispatches issue task", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });- mockCreateConversation.mockResolvedValue({ id: "c1" });- mockCreateIssue.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1" });- mockCreateMessage.mockResolvedValue({ id: "m1", content: "Issue created: Fix" });- mockEnqueueTask.mockResolvedValue({ id: "t1", agentId: "ag_1", type: "issue_event" });- mockSetLatestTask.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1", latestTaskId: "t1" });-- const req = new NextRequest("http://localhost/api/issues", {- method: "POST",- body: JSON.stringify({ agent_id: "ag_1", title: "Fix", description: "Body" }),- });- const res = await POST(req, {} as any);- expect(res.status).toBe(201);- expect(mockCreateConversation).toHaveBeenCalledWith({}, expect.objectContaining({ type: "issue_event", agentId: "ag_1" }));- expect(mockEnqueueTask).toHaveBeenCalledWith("ag_1", "c1", "w1", expect.stringContaining("Fix"), "issue_event", expect.objectContaining({ contextKey: "c1" }));- });-- it("uploads attachments and includes attachment ids in the issue task context", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });- mockCreateConversation.mockResolvedValue({ id: "c1" });- mockCreateIssue.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1" });- mockCreateMessage.mockResolvedValue({ id: "m1", content: "Issue created: Fix", attachmentIds: '["art_1"]' });- mockCreateArtifact.mockResolvedValue({ id: "art_1" });- mockR2Put.mockResolvedValue(undefined);- mockEnqueueTask.mockResolvedValue({ id: "t1", agentId: "ag_1", type: "issue_event" });- mockSetLatestTask.mockResolvedValue({ id: "iss_1", agentId: "ag_1", title: "Fix", description: "Body", status: "todo", conversationId: "c1", latestTaskId: "t1" });-- const formData = new FormData();- formData.append("agent_id", "ag_1");- formData.append("title", "Fix");- formData.append("description", "Body");- formData.append("file", new File(["hello"], "note.md", { type: "text/markdown" }));-- const req = new NextRequest("http://localhost/api/issues", {- method: "POST",- body: formData,- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockR2Put).toHaveBeenCalledTimes(1);- expect(mockCreateArtifact).toHaveBeenCalledWith({}, expect.objectContaining({- conversationId: "c1",- agentId: "ag_1",- workspaceId: "w1",- filename: "note.md",- contentType: "text/markdown",- size: 5,- source: "attachment",- }));- expect(mockCreateMessage).toHaveBeenCalledWith({}, expect.objectContaining({- attachmentIds: expect.stringContaining("art_"),- }));- expect(mockEnqueueTask).toHaveBeenCalledWith(- "ag_1",- "c1",- "w1",- expect.stringContaining("Fix"),- "issue_event",- expect.objectContaining({- contextKey: "c1",- context: expect.objectContaining({- issue_id: "iss_1",- attachment_ids: [expect.stringContaining("art_")],- }),- }),- );- });-- it("records a stable dispatch failure when enqueue rejects with a non-Error", async () => {- mockGetAgent.mockResolvedValue({ id: "ag_1", ownerId: "u1", runtimeId: "rt1" });- mockCreateConversation.mockResolvedValue({ id: "c1" });- mockCreateIssue.mockResolvedValue({- id: "iss_1",- agentId: "ag_1",- title: "Fix",- description: "Body",- status: "todo",- conversationId: "c1",- });- mockCreateMessage- .mockResolvedValueOnce({ id: "m1", content: "Issue created: Fix" })- .mockResolvedValueOnce({ id: "m2", content: "Issue dispatch failed: reason unavailable" });- mockEnqueueTask.mockRejectedValueOnce("queue unavailable");-- const res = await POST(new NextRequest("http://localhost/api/issues", {- method: "POST",- body: JSON.stringify({ agent_id: "ag_1", title: "Fix", description: "Body" }),- }), {} as any);-- expect(res.status).toBe(500);- expect(await res.json()).toEqual({ error: "failed to dispatch issue" });- expect(mockCreateMessage).toHaveBeenLastCalledWith({}, expect.objectContaining({- content: "Issue dispatch failed: reason unavailable",- }));- });-});diff --git a/src/web/src/app/api/issues/route.ts b/src/web/src/app/api/issues/route.tsdeleted file mode 100644index 5f758d036..000000000--- a/src/web/src/app/api/issues/route.ts+++ /dev/null@@ -1,226 +0,0 @@-import { NextRequest } from "next/server";-import { CreateIssueRequestSchema, IssueStatusSchema, queries, TASK_TYPES } from "@alook/shared";-import { nanoid } from "nanoid";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { parseBody, writeError, writeJSON } from "@/lib/middleware/helpers";-import { issueToResponse, messageToResponse, taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";-import type { IssueStatusType } from "@alook/shared";--const MAX_FILE_SIZE = 10 * 1024 * 1024;-const MAX_FILES = 10;--function sanitizeFilename(name: string): string {- return name.replace(/[/\\]/g, "_").replace(/\.\./g, "_").slice(0, 255) || "file";-}--function buildIssuePrompt(issue: { title: string; description: string }) {- const description = issue.description.trim();- return description ? `${issue.title}\n\n${description}` : issue.title;-}--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;- const status = req.nextUrl.searchParams.get("status") ?? undefined;- const terminalParam = req.nextUrl.searchParams.get("terminal");-- let parsedStatus: IssueStatusType | undefined;- if (status) {- const parsed = IssueStatusSchema.safeParse(status);- if (!parsed.success) return writeError("invalid issue status", 400);- parsedStatus = parsed.data;- }-- const rows = await queries.issue.listIssues(db, ws.workspaceId, {- userId: ctx.userId,- agentId,- status: parsedStatus,- terminal: terminalParam === null ? undefined : terminalParam === "true",- });-- const taskIds = rows.map(r => r.latestTaskId).filter((id): id is string => !!id);- const agentMap = taskIds.length > 0- ? await queries.task.getTraceAgentsByTaskIds(db, taskIds, ws.workspaceId)- : new Map<string, string[]>();-- return writeJSON(rows.map(r => ({- ...issueToResponse(r),- thread_agent_ids: agentMap.get(r.latestTaskId ?? "") ?? [],- })));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);- const bucket = ctx.env.EMAIL_BUCKET;-- const contentType = req.headers.get("content-type") ?? "";- const isMultipart = contentType.includes("multipart/form-data");-- let body: { agent_id?: string; title: string; description: string };- const files: File[] = [];-- if (isMultipart) {- let formData: FormData;- try {- formData = await req.formData();- } catch {- return writeError("invalid form data", 400);- }- const parsed = CreateIssueRequestSchema.safeParse({- agent_id: formData.get("agent_id") || undefined,- title: formData.get("title"),- description: formData.get("description") ?? "",- });- if (!parsed.success) {- return writeError("validation error", 400);- }- body = parsed.data;- for (const [key, value] of formData.entries()) {- if (key === "file" && value instanceof File) {- files.push(value);- }- }- } else {- const [parsedBody, err] = await parseBody(req, CreateIssueRequestSchema);- if (err) return err;- body = parsedBody;- }-- if (files.length > MAX_FILES) {- return writeError(`too many files (max ${MAX_FILES})`, 400);- }- for (const file of files) {- if (file.size > MAX_FILE_SIZE) {- return writeError(`file "${file.name}" exceeds 10 MB limit`, 413);- }- }-- // Unassigned issue flow: no agent, no conversation, no task dispatch- if (!body.agent_id) {- const created = await queries.issue.createIssue(db, {- workspaceId: ws.workspaceId,- agentId: null,- creatorUserId: ctx.userId,- conversationId: null,- title: body.title,- description: body.description,- status: "todo",- });- return writeJSON({ issue: issueToResponse(created) }, 201);- }-- // Assigned issue flow- const agent = await queries.agent.getAgent(db, body.agent_id, ws.workspaceId, ctx.userId);- if (!agent) return writeError("agent not found in workspace", 404);- if (!agent.ownerId) return writeError("agent has no owner", 400);-- const conversation = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: body.agent_id,- userId: ctx.userId,- title: `[Issue] ${body.title}`.slice(0, 120),- type: TASK_TYPES.ISSUE_EVENT,- });-- const created = await queries.issue.createIssue(db, {- workspaceId: ws.workspaceId,- agentId: body.agent_id,- creatorUserId: ctx.userId,- conversationId: conversation.id,- title: body.title,- description: body.description,- status: "in_progress",- });-- const artifactIds: string[] = [];- for (const file of files) {- const filename = sanitizeFilename(file.name);- const fileContentType = file.type || "application/octet-stream";- const artifactId = "art_" + nanoid();- const r2Key = `artifacts/${ws.workspaceId}/${body.agent_id}/${conversation.id}/${artifactId}/${filename}`;-- await bucket.put(r2Key, await file.arrayBuffer(), {- httpMetadata: { contentType: fileContentType },- });-- await queries.artifact.createArtifact(db, {- id: artifactId,- conversationId: conversation.id,- agentId: body.agent_id,- workspaceId: ws.workspaceId,- filename,- contentType: fileContentType,- size: file.size,- r2Key,- source: "attachment",- });-- artifactIds.push(artifactId);- }-- const eventMessage = await queries.message.createMessage(db, {- conversationId: conversation.id,- role: "event",- content: `Issue created: ${created.title}`,- attachmentIds: artifactIds.length > 0 ? JSON.stringify(artifactIds) : null,- metadata: JSON.stringify({ issueId: created.id, title: created.title, event: "created" as const, agentId: body.agent_id }),- });-- const prompt = buildIssuePrompt({- title: created.title,- description: created.description,- });-- const taskService = new TaskService(db);- try {- const task = await taskService.enqueueTask(- body.agent_id,- conversation.id,- ws.workspaceId,- prompt,- TASK_TYPES.ISSUE_EVENT,- {- contextKey: conversation.id,- context: {- issue_id: created.id,- ...(artifactIds.length > 0 ? { attachment_ids: artifactIds } : {}),- },- traceId: "tr_" + nanoid(),- parentTaskId: null,- }- );- queries.message.updateMessageTaskId(db, eventMessage.id, task.id).catch(() => {});- const issue = await queries.issue.setLatestTask(db, created.id, ws.workspaceId, task.id) ?? created;- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});- return writeJSON(- {- issue: issueToResponse(issue),- message: messageToResponse(eventMessage),- task: taskToResponse(task),- },- 201- );- } catch (taskErr) {- await queries.message.createMessage(db, {- conversationId: conversation.id,- role: "event",- content: `Issue dispatch failed: ${taskErr instanceof Error ? taskErr.message : "reason unavailable"}`,- metadata: JSON.stringify({ issueId: created.id, title: created.title, event: "dispatch_failed" as const }),- });- return writeError(taskErr instanceof Error ? taskErr.message : "failed to dispatch issue", 500);- }-});diff --git a/src/web/src/app/api/machine-tokens/[id]/route.test.ts b/src/web/src/app/api/machine-tokens/[id]/route.test.tsdeleted file mode 100644index 8e57b935d..000000000--- a/src/web/src/app/api/machine-tokens/[id]/route.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockDeleteMachineToken = vi.fn();-const mockListMachineTokens = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- machineToken: {- deleteMachineToken: (...args: unknown[]) => mockDeleteMachineToken(...args),- listMachineTokens: (...args: unknown[]) => mockListMachineTokens(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/cache", () => ({- invalidate: vi.fn(),- cacheKeys: { machineToken: (t: string) => `mt:${t.slice(0, 20)}` },-}));--import { DELETE } from "./route";--describe("DELETE /api/machine-tokens/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("deletes token and returns 204", async () => {- mockListMachineTokens.mockResolvedValue([{ id: "tok1", token: "al_testtoken123" }]);- mockDeleteMachineToken.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/machine-tokens/tok1", {- method: "DELETE",- });- const res = await DELETE(req, { params: Promise.resolve({ id: "tok1" }) } as any);-- expect(res.status).toBe(204);- expect(mockDeleteMachineToken).toHaveBeenCalledWith({}, "tok1", "u1");- });-});diff --git a/src/web/src/app/api/machine-tokens/[id]/route.ts b/src/web/src/app/api/machine-tokens/[id]/route.tsdeleted file mode 100644index 5b2662c79..000000000--- a/src/web/src/app/api/machine-tokens/[id]/route.ts+++ /dev/null@@ -1,29 +0,0 @@-import { queries } from "@alook/shared"-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, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("token id is required", 400);- }-- const tokens = await queries.machineToken.listMachineTokens(db, ctx.userId, ws.workspaceId);- const target = tokens.find((t) => t.id === id);-- await queries.machineToken.deleteMachineToken(db, id, ctx.userId);-- if (target) {- await invalidate(cacheKeys.machineToken(target.token));- }-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/machine-tokens/activate/route.test.ts b/src/web/src/app/api/machine-tokens/activate/route.test.tsdeleted file mode 100644index 7e37506e0..000000000--- a/src/web/src/app/api/machine-tokens/activate/route.test.ts+++ /dev/null@@ -1,268 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetMachineTokenByToken = vi.fn();-const mockActivateMachineToken = vi.fn();-const mockUpsertMachine = vi.fn();-const mockBatchUpsertAgentRuntimes = vi.fn();-const mockBroadcastToUser = vi.fn();-const mockWarmMachineTokenCache = vi.fn();-const mockKv = { put: vi.fn(), get: vi.fn(), delete: vi.fn() };--function sharedMocks() {- return {- "@opennextjs/cloudflare": {- getCloudflareContext: vi.fn(() => Promise.resolve({ env: { DB: {}, CACHE_KV: mockKv } })),- },- "@alook/shared": async () => ({- createDb: vi.fn(() => ({})),- queries: {- machineToken: {- getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),- activateMachineToken: (...a: any[]) => mockActivateMachineToken(...a),- },- machine: {- upsertMachine: (...a: any[]) => mockUpsertMachine(...a),- },- runtime: {- batchUpsertAgentRuntimes: (...a: any[]) => mockBatchUpsertAgentRuntimes(...a),- },- },- ActivateTokenRequestSchema: (await import("@alook/shared"))- .ActivateTokenRequestSchema,- createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),- }),- "@/lib/broadcast": {- broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),- },- };-}--function makeReq(body: unknown) {- return new NextRequest("http://localhost/api/machine-tokens/activate", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("POST /api/machine-tokens/activate", () => {- beforeEach(() => vi.clearAllMocks());-- async function loadRoute() {- vi.resetModules();-- const mocks = sharedMocks();-- vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);- vi.doMock("@alook/shared", mocks["@alook/shared"]);- vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));- vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);- vi.doMock("@/lib/cache", () => ({- invalidate: vi.fn(() => Promise.resolve()),- cacheKeys: {- machineToken: (t: string) => `mt:${t}`,- runtimeIds: () => "ri:",- allRuntimes: () => "ar:",- },- }));- vi.doMock("@/lib/middleware/auth", () => ({- warmMachineTokenCache: (...a: any[]) => mockWarmMachineTokenCache(...a),- }));- vi.doMock("@/lib/middleware/helpers", async () => {- return await vi.importActual<typeof import("@/lib/middleware/helpers")>(- "@/lib/middleware/helpers"- );- });- vi.doMock("@/lib/api/responses", () => ({- runtimeToResponse: (r: any) => ({ id: r.id, provider: r.provider }),- }));-- const { POST } = await import("./route");- return POST;- }-- const validBody = {- token: "al_test123",- hostname: "TestMachine.local",- runtimes: [{ type: "claude", version: "2.1.0" }],- };-- const pendingToken = {- id: "mt_1",- userId: "u1",- workspaceId: "ws_1",- status: "pending",- };-- it("creates machine + runtime rows and activates token", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockUpsertMachine.mockResolvedValue(undefined);- mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);- mockActivateMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.daemon_id).toBe("TestMachine.local");- expect(body.workspace_id).toBe("ws_1");- expect(body.runtimes).toHaveLength(1);-- expect(mockUpsertMachine).toHaveBeenCalledWith(expect.anything(), {- daemonId: "TestMachine.local",- workspaceId: "ws_1",- deviceInfo: "TestMachine.local",- lastSeenAt: null,- ownerId: "u1",- });-- expect(mockBatchUpsertAgentRuntimes).toHaveBeenCalledWith(expect.anything(), [- {- workspaceId: "ws_1",- daemonId: "TestMachine.local",- runtimeMode: "local",- provider: "claude",- deviceInfo: "TestMachine.local",- metadata: { version: "2.1.0" },- },- ]);-- expect(mockActivateMachineToken).toHaveBeenCalledWith(- expect.anything(),- "mt_1",- "TestMachine.local",- );- });-- it.each([[64, 200], [65, 400]] as const)(- "returns %i-runtime boundary status %i",- async (count, status) => {- const POST = await loadRoute();- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockUpsertMachine.mockResolvedValue(undefined);- mockBatchUpsertAgentRuntimes.mockImplementation(async (_db, runtimes: unknown[]) =>- runtimes.map((_, index) => ({ id: `rt_${index}`, provider: `runtime-${index}` })),- );- mockActivateMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq({- ...validBody,- runtimes: Array.from({ length: count }, (_, index) => ({ type: `runtime-${index}` })),- }));- expect(res.status).toBe(status);- if (status === 400) expect(mockGetMachineTokenByToken).not.toHaveBeenCalled();- },- );-- it("warms the token cache with the activated row (not a delete)", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockUpsertMachine.mockResolvedValue(undefined);- mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);- mockActivateMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- await POST(makeReq(validBody));-- // Warmed with the just-activated row (status flipped to active), through- // the explicit CACHE_KV binding — closes the daemon's first-poll false-401.- expect(mockWarmMachineTokenCache).toHaveBeenCalledWith(- mockKv,- "al_test123",- expect.objectContaining({ id: "mt_1", status: "active" }),- );- });-- it("succeeds when CACHE_KV is absent (warm is a no-op, no throw)", async () => {- vi.resetModules();- const mocks = sharedMocks();- (mocks["@opennextjs/cloudflare"].getCloudflareContext as any) = vi.fn(() =>- Promise.resolve({ env: { DB: {} } }),- );- vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);- vi.doMock("@alook/shared", mocks["@alook/shared"]);- vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));- vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);- vi.doMock("@/lib/cache", () => ({- invalidate: vi.fn(() => Promise.resolve()),- cacheKeys: { machineToken: (t: string) => `mt:${t}`, runtimeIds: () => "ri:", allRuntimes: () => "ar:" },- }));- vi.doMock("@/lib/middleware/auth", () => ({- warmMachineTokenCache: (...a: any[]) => mockWarmMachineTokenCache(...a),- }));- vi.doMock("@/lib/api/responses", () => ({ runtimeToResponse: (r: any) => ({ id: r.id, provider: r.provider }) }));- const { POST } = await import("./route");-- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockUpsertMachine.mockResolvedValue(undefined);- mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);- mockActivateMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- const res = await POST(makeReq(validBody));- expect(res.status).toBe(200);- // Called with null KV — the helper itself no-ops; here we just assert wiring.- expect(mockWarmMachineTokenCache).toHaveBeenCalledWith(null, "al_test123", expect.anything());- });-- it("broadcasts runtime.registered event", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockUpsertMachine.mockResolvedValue(undefined);- mockBatchUpsertAgentRuntimes.mockResolvedValue([{ id: "rt_1", provider: "claude" }]);- mockActivateMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);-- await POST(makeReq(validBody));-- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.registered",- daemonId: "TestMachine.local",- hostname: "TestMachine.local",- workspaceId: "ws_1",- });- });-- it("returns 404 when token not found", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue(null);-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("token not found");- });-- it("returns 409 when token already used", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue({ ...pendingToken, status: "active" });-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(409);- expect(body.error).toBe("token already used");- });-- it("returns 422 when token has no workspace_id", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue({ ...pendingToken, workspaceId: null });-- const res = await POST(makeReq(validBody));- const body = await res.json();-- expect(res.status).toBe(422);- expect(body.error).toContain("no workspace_id");- });-});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsdeleted file mode 100644index b03bb320d..000000000--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ /dev/null@@ -1,96 +0,0 @@-import { flattenError } from "zod"-import { NextRequest } from "next/server";-import { queries, ActivateTokenRequestSchema, createLogger } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withEnv } from "@/lib/middleware/env";-import { writeJSON } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";-import { warmMachineTokenCache } from "@/lib/middleware/auth";--const log = createLogger({ service: "machine-tokens/activate" });--export const POST = withEnv(async (req: NextRequest, ctx) => {- let raw: unknown;- try {- raw = await req.json();- } catch {- return writeJSON({ error: "invalid request body" }, 400);- }-- const parsed = ActivateTokenRequestSchema.safeParse(raw);- if (!parsed.success) {- return writeJSON({ error: "invalid payload", details: flattenError(parsed.error) }, 400);- }-- const { token, hostname, runtimes } = parsed.data;-- const db = getDb(ctx.env.DB);-- const mt = await queries.machineToken.getMachineTokenByToken(db, token);- if (!mt) {- return writeJSON({ error: "token not found" }, 404);- }- if (mt.status !== "pending") {- return writeJSON({ error: "token already used" }, 409);- }-- const workspaceId = mt.workspaceId;- if (!workspaceId) {- return writeJSON({ error: "token has no workspace_id — create workspace first" }, 422);- }-- const daemonId = hostname;-- await queries.machine.upsertMachine(db, {- daemonId,- workspaceId,- deviceInfo: hostname,- lastSeenAt: null,- ownerId: mt.userId,- });-- const results = await queries.runtime.batchUpsertAgentRuntimes(- db,- runtimes.map((rt) => ({- workspaceId,- daemonId,- runtimeMode: "local",- provider: rt.type,- deviceInfo: hostname,- metadata: { version: rt.version || "" },- })),- ).then((rows) => rows.map((result) => ({ ...result, machineLastSeenAt: null })))-- await queries.machineToken.activateMachineToken(db, mt.id, hostname);-- // Warm the positive token cache with the just-activated row (the route- // already holds it, incl. the userEmail join auth needs — activate only- // flips status). This closes the false-401 window where the daemon's first- // poll reads a lagged replica and negative-caches a 401. withEnv doesn't- // bind cache KV, so pass the namespace explicitly.- await Promise.all([- warmMachineTokenCache(ctx.env.CACHE_KV ?? null, token, { ...mt, status: "active" }),- invalidate(cacheKeys.runtimeIds(workspaceId, daemonId)),- ]);-- broadcastToUser(mt.userId, {- type: "runtime.registered",- daemonId,- hostname,- workspaceId,- }).catch((err) => {- log.warn("broadcast after activation failed", {- userId: mt.userId,- daemonId,- err: err instanceof Error ? err.message : String(err),- });- });-- return writeJSON({- daemon_id: daemonId,- workspace_id: workspaceId,- runtimes: results.map(runtimeToResponse),- });-});diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsdeleted file mode 100644index 20d078910..000000000--- a/src/web/src/app/api/machine-tokens/route.test.ts+++ /dev/null@@ -1,154 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListMachineTokens = vi.fn();-const mockCreateMachineToken = vi.fn();-const mockGetPendingMachineToken = vi.fn();-const mockGetRegisteredTokenForUser = vi.fn();-const mockMachineTokenToResponse = vi.fn((mt: any) => ({- id: mt.id,- name: mt.name,- last_used_at: null,- created_at: "2025-01-01T00:00:00Z",-}));-const mockGenerateMachineToken = vi.fn(() => "al_abc123");--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- machineToken: {- listMachineTokens: (...args: any[]) => mockListMachineTokens(...args),- createMachineToken: (...args: any[]) => mockCreateMachineToken(...args),- getPendingMachineToken: (...args: any[]) => mockGetPendingMachineToken(...args),- getRegisteredTokenForUser: (...args: any[]) => mockGetRegisteredTokenForUser(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- machineTokenToResponse: (...args: any[]) => mockMachineTokenToResponse(...args),-}));-vi.mock("@/lib/token", () => ({- generateMachineToken: (...args: any[]) => mockGenerateMachineToken(...args),-}));--import { GET, POST } from "./route";--describe("GET /api/machine-tokens", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists tokens", async () => {- const tokens = [- { id: "mt1", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" },- { id: "mt2", name: "ci", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" },- ];- mockListMachineTokens.mockResolvedValue(tokens);-- const res = await GET(new NextRequest("http://localhost/api/machine-tokens"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "mt1", name: "default", last_used_at: null, created_at: "2025-01-01T00:00:00Z" },- { id: "mt2", name: "ci", last_used_at: null, created_at: "2025-01-01T00:00:00Z" },- ]);- expect(mockListMachineTokens).toHaveBeenCalledWith({}, "u1", "w1");- });-});--describe("POST /api/machine-tokens", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns existing pending token if one exists", async () => {- const pending = { id: "mt0", token: "al_existing", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };- mockGetPendingMachineToken.mockResolvedValue(pending);-- const res = await POST(- new NextRequest("http://localhost/api/machine-tokens", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.token).toBe("al_existing");- expect(mockCreateMachineToken).not.toHaveBeenCalled();- expect(mockGenerateMachineToken).not.toHaveBeenCalled();- });-- it("creates pending token when none exists and returns 201", async () => {- mockGetPendingMachineToken.mockResolvedValue(null);- const mt = { id: "mt1", name: "my-token", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };- mockCreateMachineToken.mockResolvedValue(mt);-- const res = await POST(- new NextRequest("http://localhost/api/machine-tokens?workspace_id=w1", {- method: "POST",- body: JSON.stringify({ name: "my-token" }),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(201);- expect(body).toEqual({- token: "al_abc123",- id: "mt1",- name: "my-token",- last_used_at: null,- created_at: "2025-01-01T00:00:00Z",- });- expect(mockCreateMachineToken).toHaveBeenCalledWith({}, {- userId: "u1",- workspaceId: "w1",- token: "al_abc123",- name: "my-token",- status: "pending",- });- });-- it("returns the raw token in the response", async () => {- mockGetPendingMachineToken.mockResolvedValue(null);- mockGetRegisteredTokenForUser.mockResolvedValue(null);- const mt = { id: "mt2", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };- mockCreateMachineToken.mockResolvedValue(mt);-- const res = await POST(- new NextRequest("http://localhost/api/machine-tokens", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(body.token).toBe("al_abc123");- });-});diff --git a/src/web/src/app/api/machine-tokens/route.ts b/src/web/src/app/api/machine-tokens/route.tsdeleted file mode 100644index 46e10579a..000000000--- a/src/web/src/app/api/machine-tokens/route.ts+++ /dev/null@@ -1,58 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { generateMachineToken } from "@/lib/token";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { machineTokenToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const tokens = await queries.machineToken.listMachineTokens(db, ctx.userId, ws.workspaceId);- return writeJSON(tokens.map(machineTokenToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const wsParam = req.nextUrl.searchParams.get("workspace_id");- let workspaceId: string | null = null;-- if (wsParam) {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- workspaceId = ws.workspaceId;- }-- const pending = await queries.machineToken.getPendingMachineToken(db, ctx.userId, workspaceId);- if (pending) {- return writeJSON({ token: pending.token, ...machineTokenToResponse(pending) });- }-- let name = "default";- try {- const body = (await req.json()) as { name?: string };- if (body.name && typeof body.name === "string" && body.name.trim()) {- name = body.name.trim();- }- } catch {- // body parse error → use default name- }-- const raw = generateMachineToken();-- const mt = await queries.machineToken.createMachineToken(db, {- userId: ctx.userId,- workspaceId,- token: raw,- name,- status: "pending",- });-- return writeJSON({ token: raw, ...machineTokenToResponse(mt) }, 201);-});diff --git a/src/web/src/app/api/machine-tokens/status/route.test.ts b/src/web/src/app/api/machine-tokens/status/route.test.tsdeleted file mode 100644index af57998cf..000000000--- a/src/web/src/app/api/machine-tokens/status/route.test.ts+++ /dev/null@@ -1,162 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetLatestTokenForUser = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => Promise.resolve({ env: { DB: {} } })),-}));-vi.mock("@alook/shared", () => ({- queries: {- machineToken: {- getLatestTokenForUser: (...args: any[]) => mockGetLatestTokenForUser(...args),- },- },-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);-vi.mock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => (req: any) => handler(req, { env: {}, userId: "u1", email: "[email protected]" }),-}));--import { GET } from "./route";--describe("GET /api/machine-tokens/status", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns null status when no token exists", async () => {- mockGetLatestTokenForUser.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBeNull();- });-- it("returns pending status with token", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", token: "al_pending123", status: "pending", workspaceId: null, hostname: null,- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("pending");- expect(body.token).toBe("al_pending123");- expect(body.workspace_id).toBeUndefined();- expect(body.hostname).toBeUndefined();- });-- it("does NOT return token when status is not pending", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", token: "al_secret", status: "registered", workspaceId: null, hostname: "MacBook.local",- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("registered");- expect(body.token).toBeUndefined();- });-- it("returns registered status with hostname", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "registered", workspaceId: null, hostname: "MacBook.local",- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("registered");- expect(body.hostname).toBe("MacBook.local");- expect(body.workspace_id).toBeUndefined();- });-- it("returns active status with workspace_id and hostname", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "active", workspaceId: "sp_ws1", hostname: "MacBook.local", lastUsedAt: null,- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("active");- expect(body.workspace_id).toBe("sp_ws1");- expect(body.hostname).toBe("MacBook.local");- expect(body.daemon_online).toBe(false);- });-- it("returns daemon_online true when lastUsedAt is recent", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "registered", workspaceId: null, hostname: "MacBook.local",- lastUsedAt: new Date(Date.now() - 30_000).toISOString(),- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.daemon_online).toBe(true);- });-- it("returns daemon_online false when lastUsedAt is stale", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "registered", workspaceId: null, hostname: "MacBook.local",- lastUsedAt: new Date(Date.now() - 300_000).toISOString(),- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.daemon_online).toBe(false);- });-- it("returns active status with workspace_id and hostname", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "active", workspaceId: "sp_ws1", hostname: "MacBook.local",- lastUsedAt: new Date(Date.now() - 30_000).toISOString(),- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("active");- expect(body.workspace_id).toBe("sp_ws1");- expect(body.hostname).toBe("MacBook.local");- expect(body.daemon_online).toBe(true);- });-- it("returns pending status with token value", async () => {- mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "pending", workspaceId: "sp_ws1", hostname: null,- lastUsedAt: null, token: "al_secret_pending",- });-- const req = new NextRequest("http://localhost/api/machine-tokens/status");- const res = await GET(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("pending");- expect(body.token).toBe("al_secret_pending");- expect(body.daemon_online).toBe(false);- });--});diff --git a/src/web/src/app/api/machine-tokens/status/route.ts b/src/web/src/app/api/machine-tokens/status/route.tsdeleted file mode 100644index 0a0ebba6b..000000000--- a/src/web/src/app/api/machine-tokens/status/route.ts+++ /dev/null@@ -1,27 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";--const DAEMON_ONLINE_THRESHOLD_MS = 120_000;--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB);-- const token = await queries.machineToken.getLatestTokenForUser(db, ctx.userId);- if (!token) {- return writeJSON({ status: null });- }-- const daemonOnline = token.lastUsedAt- ? Date.now() - new Date(token.lastUsedAt).getTime() < DAEMON_ONLINE_THRESHOLD_MS- : false;-- return writeJSON({- status: token.status,- token: token.status === "pending" ? token.token : undefined,- workspace_id: token.workspaceId || undefined,- hostname: token.hostname || undefined,- daemon_online: daemonOnline,- });-});diff --git a/src/web/src/app/api/me/route.test.ts b/src/web/src/app/api/me/route.test.tsdeleted file mode 100644index b6d687cd3..000000000--- a/src/web/src/app/api/me/route.test.ts+++ /dev/null@@ -1,53 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetUser = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- user: { getUserSelf: (...args: unknown[]) => mockGetUser(...args) },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/api/responses", () => ({- userToResponse: vi.fn((u: any) => ({ id: u.id, name: u.name, email: u.email })),-}));--import { GET } from "./route";--describe("GET /api/me", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns user data when authenticated", async () => {- mockGetUser.mockResolvedValue({ id: "u1", name: "Alice", email: "[email protected]" });-- const req = new NextRequest("http://localhost/api/me");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual({ id: "u1", name: "Alice", email: "[email protected]" });- expect(mockGetUser).toHaveBeenCalledWith({}, "u1");- });-});diff --git a/src/web/src/app/api/me/route.ts b/src/web/src/app/api/me/route.tsdeleted file mode 100644index 8744c8e48..000000000--- a/src/web/src/app/api/me/route.ts+++ /dev/null@@ -1,15 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { userToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)-- const user = await queries.user.getUserSelf(db, ctx.userId);- if (!user) {- return writeError("user not found", 404);- }- return writeJSON(userToResponse(user));-});diff --git a/src/web/src/app/api/members/me/route.test.ts b/src/web/src/app/api/members/me/route.test.tsdeleted file mode 100644index 6c585c827..000000000--- a/src/web/src/app/api/members/me/route.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetMemberByUserAndWorkspace = vi.fn();-const mockUpdateMemberGlobalInstruction = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- createDb: vi.fn(() => ({})),- queries: {- member: {- getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),- updateMemberGlobalInstruction: (...args: unknown[]) => mockUpdateMemberGlobalInstruction(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", workspaceId: "w1", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", async () => {- const real = await vi.importActual<typeof import("@/lib/middleware/workspace")>("@/lib/middleware/workspace");- return {- ...real,- withWorkspaceMember: vi.fn(async (req: any) => {- const workspaceId =- new URL(req.url).searchParams.get("workspace_id") ||- req.headers.get("X-Workspace-ID");- if (!workspaceId) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });- }- return { workspaceId };- }),- };-});--import { GET, PATCH } from "./route";--function getReq(workspaceId?: string) {- const url = workspaceId- ? `http://localhost/api/members/me?workspace_id=${workspaceId}`- : "http://localhost/api/members/me";- return new NextRequest(url, { method: "GET" });-}--function patchReq(body: unknown, workspaceId = "w1") {- return new NextRequest(`http://localhost/api/members/me?workspace_id=${workspaceId}`, {- method: "PATCH",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });-}--describe("GET /api/members/me", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns global_instruction for the current user", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({- globalInstruction: "always speak chinese",- });-- const res = await GET(getReq("w1"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.global_instruction).toBe("always speak chinese");- });-- it("returns 400 when workspace_id is missing", async () => {- const res = await GET(getReq());- expect(res.status).toBe(400);- });-- it("returns 404 when member not found", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);-- const res = await GET(getReq("w1"));- expect(res.status).toBe(404);- });-});--describe("PATCH /api/members/me", () => {- beforeEach(() => vi.clearAllMocks());-- it("saves and returns updated global instruction", async () => {- mockUpdateMemberGlobalInstruction.mockResolvedValue({- globalInstruction: "new instruction",- });-- const res = await PATCH(patchReq({ global_instruction: "new instruction" }));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.global_instruction).toBe("new instruction");- expect(mockUpdateMemberGlobalInstruction).toHaveBeenCalledWith({}, "u1", "w1", "new instruction");- });-- it("returns 400 for invalid body", async () => {- const res = await PATCH(patchReq({}));- expect(res.status).toBe(400);- });-- it("returns 404 when member not found", async () => {- mockUpdateMemberGlobalInstruction.mockResolvedValue(null);-- const res = await PATCH(patchReq({ global_instruction: "something" }));- expect(res.status).toBe(404);- });-});diff --git a/src/web/src/app/api/members/me/route.ts b/src/web/src/app/api/members/me/route.tsdeleted file mode 100644index 2cb950bbc..000000000--- a/src/web/src/app/api/members/me/route.ts+++ /dev/null@@ -1,48 +0,0 @@-import { NextRequest } from "next/server";-import { queries, UpdateMemberRequestSchema } from "@alook/shared";-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";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const member = await queries.member.getMemberByUserAndWorkspace(- db,- ctx.userId,- ws.workspaceId- );- if (!member) return writeError("member not found", 404);-- return writeJSON({ global_instruction: member.globalInstruction });-});--export const PATCH = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const [body, err] = await parseBody(req, UpdateMemberRequestSchema);- if (err) return err;-- const db = getDb(ctx.env.DB);-- const updated = await queries.member.updateMemberGlobalInstruction(- db,- ctx.userId,- ws.workspaceId,- body.global_instruction- );- if (!updated) return writeError("member not found", 404);-- await Promise.all([- invalidate(cacheKeys.member(ws.workspaceId, ctx.userId)),- invalidate(cacheKeys.allMembers(ws.workspaceId)),- ]);-- return writeJSON({ global_instruction: updated.globalInstruction });-});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.tsdeleted file mode 100644index fee7cb10e..000000000--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgentRuntimeForWorkspace = vi.fn();-const mockSetPendingRescan = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- runtime: {- getAgentRuntimeForWorkspace: (...args: any[]) =>- mockGetAgentRuntimeForWorkspace(...args),- },- machine: {- setPendingRescan: (...args: any[]) =>- mockSetPendingRescan(...args),- },- member: {- getMemberByUserAndWorkspace: (...args: any[]) =>- mockGetMemberByUserAndWorkspace(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async (req: any) => {- const wsId = req.nextUrl.searchParams.get("workspace_id");- if (!wsId) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });- }- const member = await mockGetMemberByUserAndWorkspace({}, "u1", wsId);- if (!member) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace not found" }, { status: 404 });- }- return { workspaceId: wsId };- }),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToDaemon: vi.fn(() => Promise.resolve({ sent: 1 })),-}));--import { POST } from "./route";--function makeReq(runtimeId: string, workspaceId: string) {- const url = `http://localhost/api/runtimes/${runtimeId}/rescan?workspace_id=${workspaceId}`;- return new NextRequest(url, { method: "POST" });-}--describe("POST /api/runtimes/[runtimeId]/rescan", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- });-- it("returns 200 with pending_rescan: true", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- daemonId: "d1",- });- mockSetPendingRescan.mockResolvedValue(undefined);-- const res = await POST(makeReq("rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_rescan).toBe(true);- expect(mockSetPendingRescan).toHaveBeenCalledWith({}, "d1", "w1");- expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");- });-- it("TC-10: returns 404 when rescanning another member's runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- expect(mockSetPendingRescan).not.toHaveBeenCalled();- });-- it("returns 404 for non-existent runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("nonexistent", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- });-- it("returns 404 for runtime in another workspace", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("rt1", "w-other"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("workspace not found");- });-- it("returns 400 when runtime id is missing from URL", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);- const url = `http://localhost/api/runtimes//rescan?workspace_id=w1`;- const req = new NextRequest(url, { method: "POST" });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toContain("runtime id required");- });-});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.tsdeleted file mode 100644index 94c38b700..000000000--- a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts+++ /dev/null@@ -1,31 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { broadcastToDaemon } from "@/lib/broadcast";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];- if (!runtimeId) return writeError("runtime id required", 400);-- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(- db,- runtimeId,- ws.workspaceId,- ctx.userId,- );- if (!runtime) return writeError("runtime not found", 404);-- await queries.machine.setPendingRescan(db, runtime.daemonId, ws.workspaceId);-- broadcastToDaemon(runtime.daemonId, { type: "daemon.rescan" }).catch(() => {});-- return writeJSON({ pending_rescan: true });-});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.tsdeleted file mode 100644index 86e481371..000000000--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts+++ /dev/null@@ -1,211 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetAgentRuntimeForWorkspace = vi.fn();-const mockSetPendingUpdateVersion = vi.fn();-const mockClearPendingUpdateVersion = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- runtime: {- getAgentRuntimeForWorkspace: (...args: any[]) =>- mockGetAgentRuntimeForWorkspace(...args),- },- machine: {- setPendingUpdateVersion: (...args: any[]) =>- mockSetPendingUpdateVersion(...args),- clearPendingUpdateVersion: (...args: any[]) =>- mockClearPendingUpdateVersion(...args),- },- member: {- getMemberByUserAndWorkspace: (...args: any[]) =>- mockGetMemberByUserAndWorkspace(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async (req: any) => {- const wsId = req.nextUrl.searchParams.get("workspace_id");- if (!wsId) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });- }- const member = await mockGetMemberByUserAndWorkspace({}, "u1", wsId);- if (!member) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace not found" }, { status: 404 });- }- return { workspaceId: wsId };- }),-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));--const mockBroadcastToUser = vi.fn(() => Promise.resolve());--vi.mock("@/lib/broadcast", () => ({- broadcastToDaemon: vi.fn(() => Promise.resolve({ sent: 1 })),- broadcastToUser: (...args: any[]) => mockBroadcastToUser(...args),-}));--// Mock global fetch for npm registry-const mockFetch = vi.fn();-vi.stubGlobal("fetch", mockFetch);--import { POST, DELETE } from "./route";--function makeReq(method: string, runtimeId: string, workspaceId: string) {- const url = `http://localhost/api/runtimes/${runtimeId}/update?workspace_id=${workspaceId}`;- return new NextRequest(url, { method });-}--describe("POST /api/runtimes/[runtimeId]/update", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- });-- it("returns 200 with pending_update_version", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- daemonId: "d1",- });- mockFetch.mockResolvedValue({- ok: true,- json: async () => ({ version: "1.0.0" }),- });- mockSetPendingUpdateVersion.mockResolvedValue(undefined);-- const res = await POST(makeReq("POST", "rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.pending_update_version).toBe("1.0.0");- expect(mockSetPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1", "1.0.0");- expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");- });-- it("TC-8: returns 404 when updating another member's runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("POST", "rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- expect(mockSetPendingUpdateVersion).not.toHaveBeenCalled();- });-- it("returns 404 for non-existent runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("POST", "nonexistent", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- });-- it("returns 502 when npm registry is unreachable", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- daemonId: "d1",- });- mockFetch.mockResolvedValue({ ok: false });-- const res = await POST(makeReq("POST", "rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(502);- expect(body.error).toContain("npm");- });-- it("returns 404 for runtime in another workspace", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);-- const res = await POST(makeReq("POST", "rt1", "w-other"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("workspace not found");- });-});--describe("DELETE /api/runtimes/[runtimeId]/update", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- });-- it("returns 204 when cancelling update and broadcasts runtime.status", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- daemonId: "d1",- });- mockClearPendingUpdateVersion.mockResolvedValue(undefined);-- const res = await DELETE(makeReq("DELETE", "rt1", "w1"));-- expect(res.status).toBe(204);- expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1");- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "runtime.status",- daemonId: "d1",- workspaceId: "w1",- status: "online",- });- expect(mockGetAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1", "u1");- });-- it("TC-9: returns 404 when cancelling update on another member's runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await DELETE(makeReq("DELETE", "rt1", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();- });-- it("returns 204 even when broadcast fails", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- daemonId: "d1",- });- mockClearPendingUpdateVersion.mockResolvedValue(undefined);- mockBroadcastToUser.mockRejectedValue(new Error("WS unavailable"));-- const res = await DELETE(makeReq("DELETE", "rt1", "w1"));-- expect(res.status).toBe(204);- });-- it("returns 404 for non-existent runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);-- const res = await DELETE(makeReq("DELETE", "nonexistent", "w1"));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- });-});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.tsdeleted file mode 100644index f1b7a4184..000000000--- a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts+++ /dev/null@@ -1,64 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { fetchLatestCliVersion } from "@/lib/npm";-import { broadcastToDaemon, broadcastToUser } from "@/lib/broadcast";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];- if (!runtimeId) return writeError("runtime id required", 400);-- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(- db,- runtimeId,- ws.workspaceId,- ctx.userId,- );- if (!runtime) return writeError("runtime not found", 404);-- const result = await fetchLatestCliVersion();- if (!result) return writeError("failed to fetch latest CLI version from npm", 502);-- await queries.machine.setPendingUpdateVersion(db, runtime.daemonId, ws.workspaceId, result.version);-- broadcastToDaemon(runtime.daemonId, { type: "daemon.update", version: result.version }).catch(() => {});-- return writeJSON({ pending_update_version: result.version });-});--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];- if (!runtimeId) return writeError("runtime id required", 400);-- const runtime = await queries.runtime.getAgentRuntimeForWorkspace(- db,- runtimeId,- ws.workspaceId,- ctx.userId,- );- if (!runtime) return writeError("runtime not found", 404);-- await queries.machine.clearPendingUpdateVersion(db, runtime.daemonId, ws.workspaceId);-- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId: runtime.daemonId,- workspaceId: ws.workspaceId,- status: "online",- }).catch(() => {});-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/runtimes/machine/route.test.ts b/src/web/src/app/api/runtimes/machine/route.test.tsdeleted file mode 100644index a13341433..000000000--- a/src/web/src/app/api/runtimes/machine/route.test.ts+++ /dev/null@@ -1,200 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockDeleteRuntimesByDaemonId = vi.fn();-const mockDeleteMachine = vi.fn();-const mockGetMachineByDaemon = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- runtime: {- deleteRuntimesByDaemonId: (...args: any[]) =>- mockDeleteRuntimesByDaemonId(...args),- },- machine: {- deleteMachine: (...args: any[]) =>- mockDeleteMachine(...args),- getMachineByDaemon: (...args: any[]) =>- mockGetMachineByDaemon(...args),- },- member: {- getMemberByUserAndWorkspace: (...args: any[]) =>- mockGetMemberByUserAndWorkspace(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params =- ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async (req: any) => {- const wsId = req.nextUrl.searchParams.get("workspace_id");- if (!wsId) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });- }- // Check member mock- const member = await mockGetMemberByUserAndWorkspace({}, "u1", wsId);- if (!member) {- const { NextResponse } = await import("next/server");- return NextResponse.json({ error: "workspace not found" }, { status: 404 });- }- return { workspaceId: wsId };- }),-}));-vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),- broadcastToDaemon: vi.fn().mockResolvedValue({ sent: 1 }),-}));--import { DELETE } from "./route";--function makeReq(params: Record<string, string>) {- const url = new URL("http://localhost/api/runtimes/machine");- for (const [k, v] of Object.entries(params)) {- url.searchParams.set(k, v);- }- return new NextRequest(url.toString(), { method: "DELETE" });-}--describe("DELETE /api/runtimes/machine", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 400 when daemon_id is missing", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });-- const res = await DELETE(makeReq({ workspace_id: "w1" }));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toContain("daemon_id");- });-- it("returns 400 when workspace_id is missing", async () => {- const res = await DELETE(makeReq({ daemon_id: "d1" }));- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toContain("workspace_id");- });-- it("returns 404 when user is not a workspace member", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);-- const res = await DELETE(makeReq({ daemon_id: "d1", workspace_id: "w-other" }));- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("workspace not found");- });-- it("returns 204 on successful delete (TC-12)", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });- mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);- mockDeleteMachine.mockResolvedValue(undefined);-- const res = await DELETE(- makeReq({ daemon_id: "d1", workspace_id: "w1" })- );-- expect(res.status).toBe(204);- });-- it("TC-11: returns 404 when deleting another member's machine", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "other-user" });-- const res = await DELETE(- makeReq({ daemon_id: "d1", workspace_id: "w1" })- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- expect(mockDeleteRuntimesByDaemonId).not.toHaveBeenCalled();- });-- it("returns 404 when machine does not exist", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue(null);-- const res = await DELETE(- makeReq({ daemon_id: "d1", workspace_id: "w1" })- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toContain("not found");- });-- it("passes correct daemon_id with dots and dashes", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "my-daemon.v2.host-01", ownerId: "u1" });- mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);- mockDeleteMachine.mockResolvedValue(undefined);-- const daemonId = "my-daemon.v2.host-01";- await DELETE(makeReq({ daemon_id: daemonId, workspace_id: "w1" }));-- expect(mockDeleteRuntimesByDaemonId).toHaveBeenCalledWith(- {},- daemonId,- "w1"- );- });-- it("calls deleteRuntimesByDaemonId exactly once", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });- mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);- mockDeleteMachine.mockResolvedValue(undefined);-- await DELETE(makeReq({ daemon_id: "d1", workspace_id: "w1" }));-- expect(mockDeleteRuntimesByDaemonId).toHaveBeenCalledOnce();- });-- it("returns 500 when deleteRuntimesByDaemonId throws", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });- mockDeleteRuntimesByDaemonId.mockRejectedValue(new Error("DB exploded"));-- const res = await DELETE(- makeReq({ daemon_id: "d1", workspace_id: "w1" })- );- const body = await res.json();-- expect(res.status).toBe(500);- expect(body.error).toContain("Failed to remove machine");- });-- it("broadcasts daemon.evict on successful delete", async () => {- const { broadcastToDaemon } = await import("@/lib/broadcast");- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });- mockGetMachineByDaemon.mockResolvedValue({ daemonId: "d1", ownerId: "u1" });- mockDeleteRuntimesByDaemonId.mockResolvedValue(undefined);- mockDeleteMachine.mockResolvedValue(undefined);-- await DELETE(makeReq({ daemon_id: "d1", workspace_id: "w1" }));-- expect(broadcastToDaemon).toHaveBeenCalledWith("d1", {- type: "daemon.evict",- workspaceId: "w1",- });- });-});diff --git a/src/web/src/app/api/runtimes/machine/route.ts b/src/web/src/app/api/runtimes/machine/route.tsdeleted file mode 100644index 0a3d4b89e..000000000--- a/src/web/src/app/api/runtimes/machine/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { log } from "@/lib/logger";-import { broadcastToUser, broadcastToDaemon } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const daemonId = req.nextUrl.searchParams.get("daemon_id");- if (!daemonId) {- return writeJSON({ error: "daemon_id is required" }, 400);- }-- const ownerMachine = await queries.machine.getMachineByDaemon(db, daemonId, ws.workspaceId);- if (!ownerMachine || ownerMachine.ownerId !== ctx.userId) {- return writeJSON({ error: "machine not found" }, 404);- }-- try {- await queries.runtime.deleteRuntimesByDaemonId(db, daemonId, ws.workspaceId);- await queries.machine.deleteMachine(db, daemonId, ws.workspaceId);- await Promise.all([- invalidate(cacheKeys.runtimeIds(ws.workspaceId, daemonId)),- ]);- } catch (e) {- log.error("Failed to delete machine", { err: e });- return writeJSON({ error: "Failed to remove machine" }, 500);- }-- broadcastToDaemon(daemonId, {- type: "daemon.evict",- workspaceId: ws.workspaceId,- }).catch(() => {});-- broadcastToUser(ctx.userId, {- type: "runtime.deleted",- daemonId,- }).catch(() => {});-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/runtimes/route.test.ts b/src/web/src/app/api/runtimes/route.test.tsdeleted file mode 100644index 161e8e2c2..000000000--- a/src/web/src/app/api/runtimes/route.test.ts+++ /dev/null@@ -1,79 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockListAgentRuntimes = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));---vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- runtime: {- listAgentRuntimes: (...args: unknown[]) => mockListAgentRuntimes(...args),- },- },-}));--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));--vi.mock("@/lib/api/responses", () => ({- runtimeToResponse: vi.fn((rt: any) => ({ id: rt.id, status: rt.status })),-}));--vi.mock("@/lib/middleware/helpers", () => {- const { NextResponse } = require("next/server");- return {- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--import { GET } from "./route";--describe("GET /api/runtimes", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists runtimes in workspace", async () => {- mockListAgentRuntimes.mockResolvedValue([- { id: "r1", status: "online" },- { id: "r2", status: "offline" },- ]);-- const req = new NextRequest("http://localhost/api/runtimes");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual([- { id: "r1", status: "online" },- { id: "r2", status: "offline" },- ]);- expect(mockListAgentRuntimes).toHaveBeenCalledWith({}, "w1", "u1");- });-- it("TC-1/TC-2: passes userId so only owner's runtimes are returned", async () => {- mockListAgentRuntimes.mockResolvedValue([{ id: "r1", status: "online" }]);-- const req = new NextRequest("http://localhost/api/runtimes");- await GET(req, {} as any);-- expect(mockListAgentRuntimes).toHaveBeenCalledWith(- expect.anything(),- "w1",- "u1",- );- });-});diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.tsdeleted file mode 100644index c88dbeb57..000000000--- a/src/web/src/app/api/runtimes/route.ts+++ /dev/null@@ -1,17 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const runtimes = await queries.runtime.listAgentRuntimes(db, ws.workspaceId, ctx.userId);-- return writeJSON(runtimes.map(runtimeToResponse));-});diff --git a/src/web/src/app/api/studios/check-handles/route.test.ts b/src/web/src/app/api/studios/check-handles/route.test.tsdeleted file mode 100644index 48e17a049..000000000--- a/src/web/src/app/api/studios/check-handles/route.test.ts+++ /dev/null@@ -1,130 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetExistingHandles = vi.fn();-const mockGetAgentByHandle = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: {- getExistingHandles: (...args: unknown[]) => mockGetExistingHandles(...args),- getAgentByHandle: (...args: unknown[]) => mockGetAgentByHandle(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--import { POST } from "./route";--function makeReq(body: Record<string, unknown>) {- return new NextRequest("http://localhost/api/studios/check-handles", {- method: "POST",- body: JSON.stringify(body),- });-}--describe("POST /api/studios/check-handles", () => {- beforeEach(() => {- vi.clearAllMocks();- mockGetExistingHandles.mockResolvedValue([]);- });-- it("returns unique handles for each member keyed by uid when none exist", async () => {- const req = makeReq({ members: [{ uid: "a", name: "Alice" }, { uid: "b", name: "Bob" }] });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(body[0].uid).toBe("a");- expect(body[0].handle).toBeTruthy();- expect(body[1].uid).toBe("b");- expect(body[1].handle).toBeTruthy();- expect(body[0].handle).not.toBe(body[1].handle);- });-- it("returns distinct handles for two same-name members keyed by uid", async () => {- const req = makeReq({ members: [{ uid: "a", name: "Ada" }, { uid: "b", name: "Ada" }] });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(body[0].uid).toBe("a");- expect(body[1].uid).toBe("b");- expect(body[0].handle).toBeTruthy();- expect(body[1].handle).toBeTruthy();- expect(body[0].handle).not.toBe(body[1].handle);- });-- it("skips handles that already exist in DB", async () => {- mockGetExistingHandles.mockResolvedValue(["alice"]);-- const req = makeReq({ members: [{ uid: "a", name: "Alice" }] });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body[0].handle).not.toBe("alice");- expect(body[0].handle).toBeTruthy();- });-- it("batch-fetches all candidates in a single call", async () => {- const req = makeReq({ members: [{ uid: "a", name: "Alice" }, { uid: "b", name: "Bob" }, { uid: "c", name: "Charlie" }] });- await POST(req, {});-- expect(mockGetExistingHandles).toHaveBeenCalledTimes(1);- const handles = mockGetExistingHandles.mock.calls[0][1] as string[];- expect(handles.length).toBeGreaterThan(3);- });-- it("returns 400 if members array is empty", async () => {- const req = makeReq({ members: [] });- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("returns 400 if members array exceeds 4", async () => {- const req = makeReq({ members: [{ uid: "a", name: "a" }, { uid: "b", name: "b" }, { uid: "c", name: "c" }, { uid: "d", name: "d" }, { uid: "e", name: "e" }] });- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("returns 400 for invalid request body", async () => {- const req = new NextRequest("http://localhost/api/studios/check-handles", {- method: "POST",- body: "not json",- });- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("falls back to nanoid suffix when all candidates are taken", async () => {- mockGetExistingHandles.mockImplementation((_db: any, handles: string[]) =>- Promise.resolve(handles)- );-- const req = makeReq({ members: [{ uid: "a", name: "Alice" }] });- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body[0].handle).toMatch(/^alice-.{6}$/);- });-});diff --git a/src/web/src/app/api/studios/check-handles/route.ts b/src/web/src/app/api/studios/check-handles/route.tsdeleted file mode 100644index 33ffe5cd8..000000000--- a/src/web/src/app/api/studios/check-handles/route.ts+++ /dev/null@@ -1,64 +0,0 @@-import { NextRequest } from "next/server";-import { queries, isValidHandle } from "@alook/shared";-import { nanoid } from "nanoid";-import { uniqueNamesGenerator, names } from "unique-names-generator";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const POST = withAuth(async (req: NextRequest, ctx) => {- let body: { members: { uid: string; name: string }[] };- try {- body = await req.json() as { members: { uid: string; name: string }[] };- } catch {- return writeError("invalid request body", 400);- }-- if (!Array.isArray(body.members) || body.members.length === 0 || body.members.length > 4) {- return writeError("members must be an array of 1-4 items", 400);- }-- const db = getDb(ctx.env.DB);-- // Generate all candidate handles upfront- const candidatesPerName: { uid: string; name: string; candidates: string[] }[] = [];- for (const { uid, name } of body.members) {- const base = name.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);- const candidates: string[] = [];- if (isValidHandle(base)) candidates.push(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)) candidates.push(candidate);- }- candidatesPerName.push({ uid, name, candidates });- }-- // Batch-fetch existence of all candidates in a single query- const allCandidates = candidatesPerName.flatMap((c) => c.candidates);- const existingHandles = new Set(- await queries.agent.getExistingHandles(db, allCandidates)- );-- // Assign handles using in-memory Set lookups- const usedHandles = new Set<string>();- const results: { uid: string; handle: string }[] = [];-- for (const { uid, name, candidates } of candidatesPerName) {- let handle: string | undefined;- for (const candidate of candidates) {- if (!existingHandles.has(candidate) && !usedHandles.has(candidate)) {- handle = candidate;- break;- }- }- if (!handle) {- const base = name.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);- handle = `${base}-${nanoid(6)}`;- }- usedHandles.add(handle);- results.push({ uid, handle });- }-- return writeJSON(results);-});diff --git a/src/web/src/app/api/studios/check-name/route.test.ts b/src/web/src/app/api/studios/check-name/route.test.tsdeleted file mode 100644index 6734fa04a..000000000--- a/src/web/src/app/api/studios/check-name/route.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockGetWorkspaceBySlug = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- workspace: {- getWorkspaceBySlug: (...args: unknown[]) => mockGetWorkspaceBySlug(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--import { GET } from "./route";--beforeEach(() => vi.clearAllMocks());--describe("GET /api/studios/check-name", () => {- it("returns available=true for unused slug", async () => {- mockGetWorkspaceBySlug.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/studios/check-name?name=Atlas%20Lab&workspace_id=w1");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.available).toBe(true);- expect(body.suggested_slug).toBe("atlas-lab");- });-- it("returns available=true if slug belongs to current workspace", async () => {- mockGetWorkspaceBySlug.mockResolvedValue({ id: "w1", name: "Atlas Lab", slug: "atlas-lab" });-- const req = new NextRequest("http://localhost/api/studios/check-name?name=Atlas%20Lab&workspace_id=w1");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.available).toBe(true);- });-- it("returns available=false for taken slug", async () => {- mockGetWorkspaceBySlug.mockResolvedValue({ id: "other-ws", name: "Other", slug: "atlas-lab" });-- const req = new NextRequest("http://localhost/api/studios/check-name?name=Atlas%20Lab&workspace_id=w1");- const res = await GET(req, {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.available).toBe(false);- expect(body.conflict_reason).toBe("slug_taken");- });-- it("returns 400 if name is missing", async () => {- const req = new NextRequest("http://localhost/api/studios/check-name?workspace_id=w1");- const res = await GET(req, {});- expect(res.status).toBe(400);- });-- it("returns 400 if name produces invalid slug", async () => {- const req = new NextRequest("http://localhost/api/studios/check-name?name=!!!&workspace_id=w1");- const res = await GET(req, {});- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/studios/check-name/route.ts b/src/web/src/app/api/studios/check-name/route.tsdeleted file mode 100644index 659968d35..000000000--- a/src/web/src/app/api/studios/check-name/route.ts+++ /dev/null@@ -1,38 +0,0 @@-import { NextRequest } from "next/server";-import { queries, sanitizeSlug } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const wsParam = req.nextUrl.searchParams.get("workspace_id");- let currentWorkspaceId: string | null = null;-- if (wsParam) {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;- currentWorkspaceId = ws.workspaceId;- }-- const name = req.nextUrl.searchParams.get("name");- if (!name || !name.trim()) {- return writeError("name query parameter is required", 400);- }-- const slug = sanitizeSlug(name.trim());- if (!slug) {- return writeError("name produces an invalid slug", 400);- }-- const db = getDb(ctx.env.DB);-- const existing = await queries.workspace.getWorkspaceBySlug(db, slug);- const available = !existing || (currentWorkspaceId !== null && existing.id === currentWorkspaceId);-- return writeJSON({- available,- suggested_slug: slug,- ...(available ? {} : { conflict_reason: "slug_taken" }),- });-});diff --git a/src/web/src/app/api/studios/route.test.ts b/src/web/src/app/api/studios/route.test.tsdeleted file mode 100644index eab34043f..000000000--- a/src/web/src/app/api/studios/route.test.ts+++ /dev/null@@ -1,391 +0,0 @@-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/avatar/seed-url", () => ({- randomBeamAvatar: vi.fn(() => "generated-avatar-config"),-}));--const mockCreateAgent = vi.fn();-const mockGetAgentByHandle = vi.fn();-const mockListAgents = vi.fn();-const mockGetAgentRuntimeForWorkspace = vi.fn();-const mockGetAgentRuntimesForWorkspace = vi.fn();-const mockGetWorkspace = vi.fn();-const mockGetWorkspaceBySlug = vi.fn();-const mockUpdateWorkspace = vi.fn();-const mockAddWhitelist = vi.fn();-const mockCreateLink = vi.fn();-const mockCreateConversation = vi.fn();-const mockEnqueueTask = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@/lib/cache", () => ({- invalidate: vi.fn(),- cached: vi.fn((_key: string, _ttl: number, fn: () => Promise<any>) => fn()),- cacheKeys: {- allAgents: (ws: string) => `agents:${ws}`,- allHandles: (ws: string) => `handles:${ws}`,- allColleagues: (ws: string) => `col:${ws}`,- allAgentAccess: (ws: string) => `aa:${ws}`,- allMembers: (ws: string) => `members:${ws}`,- overviewTaskStats: (ws: string, d: string) => `ov_task:${ws}:${d}`,- agentLinks: (ws: string) => `al:${ws}`,- },-}));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- isOnline: vi.fn((t: string | null) => !!t && Date.now() - new Date(t).getTime() < 30_000),- queries: {- agent: {- createAgent: (...args: unknown[]) => mockCreateAgent(...args),- getAgentByHandle: (...args: unknown[]) => mockGetAgentByHandle(...args),- listAgents: (...args: unknown[]) => mockListAgents(...args),- getAllHandlesForWorkspace: vi.fn().mockResolvedValue([]),- },- runtime: {- getAgentRuntimeForWorkspace: (...args: unknown[]) => mockGetAgentRuntimeForWorkspace(...args),- getAgentRuntimesForWorkspace: (...args: unknown[]) => mockGetAgentRuntimesForWorkspace(...args),- },- workspace: {- getWorkspace: (...args: unknown[]) => mockGetWorkspace(...args),- getWorkspaceBySlug: (...args: unknown[]) => mockGetWorkspaceBySlug(...args),- updateWorkspace: (...args: unknown[]) => mockUpdateWorkspace(...args),- },- whitelist: {- addWhitelist: (...args: unknown[]) => mockAddWhitelist(...args),- },- agentLink: {- create: (...args: unknown[]) => mockCreateLink(...args),- },- conversation: {- createConversation: (...args: unknown[]) => mockCreateConversation(...args),- },- agentPin: {- pinAgent: vi.fn(),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--const mockWithWorkspaceMember = vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" }));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: (...args: unknown[]) => mockWithWorkspaceMember(...args),-}));--vi.mock("@/lib/api/responses", () => ({- agentToResponse: vi.fn((a: any) => ({ id: a.id, name: a.name, email_handle: a.emailHandle })),- workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name, slug: w.slug })),- agentLinkToResponse: vi.fn((l: any) => ({ id: l.id, source_agent_id: l.sourceAgentId, target_agent_id: l.targetAgentId })),-}));--vi.mock("@/lib/services/task", () => {- const Svc = function () {- return { enqueueTask: mockEnqueueTask };- };- return { TaskService: Svc };-});--import { POST } from "./route";--beforeEach(() => {- vi.clearAllMocks();- mockGetWorkspace.mockResolvedValue({ id: "w1", name: "My Workspace", slug: "my-workspace" });- mockGetWorkspaceBySlug.mockResolvedValue(null);- mockUpdateWorkspace.mockResolvedValue({ id: "w1", name: "Atlas Lab", slug: "atlas-lab" });- mockGetAgentByHandle.mockResolvedValue(null);- mockListAgents.mockResolvedValue([]);- mockGetAgentRuntimeForWorkspace.mockResolvedValue({- id: "rt1",- runtimeMode: "local",- machineLastSeenAt: new Date().toISOString(),- });- mockGetAgentRuntimesForWorkspace.mockResolvedValue([{- id: "rt1",- runtimeMode: "local",- machineLastSeenAt: new Date().toISOString(),- }]);- let agentIdx = 0;- mockCreateAgent.mockImplementation((_db: any, data: any) => {- agentIdx++;- return { id: `agent-${agentIdx}`, ...data, emailHandle: `handle-${agentIdx}` };- });- mockCreateLink.mockImplementation((_db: any, data: any) => ({- id: `link-${data.sourceAgentId}-${data.targetAgentId}`,- ...data,- }));- mockCreateConversation.mockResolvedValue({ id: "conv1" });- mockEnqueueTask.mockResolvedValue({});-});--describe("POST /api/studios", () => {- it("creates agents and links for a 3-member studio", async () => {- // First call (checking existing agents for slug safety) returns empty,- // second call (fetching created agents for response) returns the new agents- mockListAgents- .mockResolvedValueOnce([])- .mockResolvedValueOnce([- { id: "agent-1", name: "Jarvis", emailHandle: "atlas-lab-jarvis" },- { id: "agent-2", name: "Mira", emailHandle: "atlas-lab-mira" },- { id: "agent-3", name: "Linus", emailHandle: "atlas-lab-linus" },- ]);-- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- name: "Atlas Lab",- scenario: "software-dev",- members: [- { name: "Jarvis", role: "leader", runtime_id: "rt1" },- { name: "Mira", role: "researcher", runtime_id: "rt1", relationship: "Delegate research tasks\n\nReport findings" },- { name: "Linus", role: "engineer", runtime_id: "rt1", relationship: "Delegate coding tasks\n\nReport implementation" },- ],- }),- });-- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(201);- expect(mockCreateAgent).toHaveBeenCalledTimes(3);- expect(mockCreateLink).toHaveBeenCalledTimes(2);- expect(body.leader_agent_id).toBe("agent-1");- expect(body.agents).toHaveLength(3);- expect(body.links).toHaveLength(2);- });-- it("creates a single agent studio (no links)", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [{ name: "Solo", role: "leader", runtime_id: "rt1" }],- }),- });-- const res = await POST(req, {});- const body = await res.json();-- expect(res.status).toBe(201);- expect(mockCreateAgent).toHaveBeenCalledTimes(1);- expect(mockCreateLink).not.toHaveBeenCalled();- expect(body.leader_agent_id).toBe("agent-1");- });-- it("returns 400 if members array is empty", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({ members: [] }),- });-- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("returns 400 if no leader role", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [- { name: "Mira", role: "researcher", runtime_id: "rt1" },- { name: "Linus", role: "engineer", runtime_id: "rt1" },- ],- }),- });-- const res = await POST(req, {});- expect(res.status).toBe(400);- });-- it("TC-7: returns 404 when using another member's runtime", async () => {- mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);- mockGetAgentRuntimesForWorkspace.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [{ name: "Jarvis", role: "leader", runtime_id: "bad-rt" }],- }),- });-- const res = await POST(req, {});- expect(res.status).toBe(404);- });-- it("updates workspace name and slug when no existing agents", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- name: "Dev Studio",- members: [{ name: "Jarvis", role: "leader", runtime_id: "rt1" }],- }),- });-- await POST(req, {});-- expect(mockUpdateWorkspace).toHaveBeenCalledWith(- expect.anything(),- "w1",- expect.objectContaining({ name: "Dev Studio", slug: "dev-studio" }),- );- });-- it("only updates display name when workspace has existing agents", async () => {- mockListAgents.mockResolvedValue([{ id: "existing-agent" }]);-- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- name: "New Name",- members: [{ name: "Jarvis", role: "leader", runtime_id: "rt1" }],- }),- });-- await POST(req, {});-- expect(mockUpdateWorkspace).toHaveBeenCalledWith(- expect.anything(),- "w1",- { name: "New Name" },- );- });-- it("enqueues welcome email and welcome chat for leader", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [- { name: "Jarvis", role: "leader", runtime_id: "rt1" },- { name: "Linus", role: "engineer", runtime_id: "rt1" },- ],- }),- });-- await POST(req, {});-- expect(mockCreateConversation).toHaveBeenCalledTimes(2); // welcome email + welcome chat- expect(mockEnqueueTask).toHaveBeenCalledTimes(2);- expect(mockEnqueueTask).toHaveBeenCalledWith(- "agent-1",- expect.any(String),- "w1",- expect.stringContaining("lead of a new AI studio"),- expect.any(String),- );- });-- it("adds owner email to whitelist for each agent", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [- { name: "Jarvis", role: "leader", runtime_id: "rt1" },- { name: "Mira", role: "researcher", runtime_id: "rt1" },- ],- }),- });-- await POST(req, {});-- expect(mockAddWhitelist).toHaveBeenCalledTimes(2);- });-- it("auto-generates avatar when avatar_url is not provided", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [{ name: "Solo", role: "leader", runtime_id: "rt1" }],- }),- });-- await POST(req, {});-- expect(mockCreateAgent).toHaveBeenCalledTimes(1);- const agentData = mockCreateAgent.mock.calls[0][1];- expect(agentData.avatarUrl).toBe("generated-avatar-config");- });-- it("uses provided avatar_url when explicitly set", async () => {- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [{ name: "Solo", role: "leader", runtime_id: "rt1", avatar_url: "custom-avatar" }],- }),- });-- await POST(req, {});-- expect(mockCreateAgent).toHaveBeenCalledTimes(1);- const agentData = mockCreateAgent.mock.calls[0][1];- expect(agentData.avatarUrl).toBe("custom-avatar");- });-- it("non-owner member cannot update workspace slug", async () => {- mockWithWorkspaceMember.mockResolvedValueOnce({ workspaceId: "w1", memberRole: "member" });- mockListAgents- .mockResolvedValueOnce([])- .mockResolvedValueOnce([- { id: "agent-1", name: "Solo", emailHandle: "solo" },- ]);-- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- name: "Hijacked Name",- members: [{ name: "Solo", role: "leader", runtime_id: "rt1" }],- }),- });-- const res = await POST(req, {});- expect(res.status).toBe(201);- expect(mockUpdateWorkspace).not.toHaveBeenCalled();- });-- it("creates agents with auto-generated names when name is omitted", async () => {- mockListAgents- .mockResolvedValueOnce([])- .mockResolvedValueOnce([- { id: "agent-1", name: "AutoName1", emailHandle: "auto1" },- { id: "agent-2", name: "AutoName2", emailHandle: "auto2" },- ]);-- const req = new NextRequest("http://localhost/api/studios", {- method: "POST",- body: JSON.stringify({- members: [- { role: "leader", runtime_id: "rt1", instructions: "You lead" },- { role: "engineer", runtime_id: "rt1", instructions: "You code", relationship: "delegate tasks\n\nreport results" },- ],- }),- });-- const res = await POST(req, {});- expect(res.status).toBe(201);-- // Agents should be created with non-empty names- expect(mockCreateAgent).toHaveBeenCalledTimes(2);- const firstCall = mockCreateAgent.mock.calls[0][1];- const secondCall = mockCreateAgent.mock.calls[1][1];- expect(firstCall.name).toBeTruthy();- expect(secondCall.name).toBeTruthy();-- // Links should still be created (index-based matching)- expect(mockCreateLink).toHaveBeenCalledTimes(1);- const linkCall = mockCreateLink.mock.calls[0][1];- expect(linkCall.instruction).toContain("delegate tasks");- expect(linkCall.instruction).toContain("report results");- });-});diff --git a/src/web/src/app/api/studios/route.ts b/src/web/src/app/api/studios/route.tsdeleted file mode 100644index dcb5bd2b0..000000000--- a/src/web/src/app/api/studios/route.ts+++ /dev/null@@ -1,272 +0,0 @@-import { NextRequest } from "next/server";-import { queries, CreateStudioRequestSchema, isValidHandle, isOnline, TASK_TYPES, toAlookAddress, sanitizeSlug, slugSuffix } from "@alook/shared";-import { nanoid } from "nanoid";-import { uniqueNamesGenerator, names } from "unique-names-generator";-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 { agentToResponse, workspaceToResponse, agentLinkToResponse } from "@/lib/api/responses";-import { randomBeamAvatar } from "@/lib/avatar/seed-url";-import { TaskService } from "@/lib/services/task";-import { invalidate, cached, cacheKeys } from "@/lib/cache";--function generateUniqueHandleFromSet(- handleSet: Set<string>,- baseName: string,-): string {- const base = baseName.toLowerCase().replace(/[^a-z0-9-]/g, "").slice(0, 30);- 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;- if (!handleSet.has(candidate)) {- handleSet.add(candidate);- return candidate;- }- }- const fallback = `${base}-${nanoid(6)}`;- handleSet.add(fallback);- return fallback;-}---export const POST = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const [body, valErr] = await parseBody(req, CreateStudioRequestSchema);- if (valErr) return valErr;-- const runtimeIds = [...new Set(body.members.map((m) => m.runtime_id))];- const runtimes = await queries.runtime.getAgentRuntimesForWorkspace(db, runtimeIds, ws.workspaceId, ctx.userId);- const runtimeCache = new Map(runtimes.map((r) => [r.id, r]));- for (const rid of runtimeIds) {- if (!runtimeCache.has(rid)) {- return writeError(`runtime ${rid} not found in workspace`, 404);- }- }-- // Update workspace name/slug if a name is provided- let updatedWorkspace = await queries.workspace.getWorkspace(db, ws.workspaceId, ctx.userId);- if (!updatedWorkspace) {- return writeError("workspace not found", 404);- }-- if (body.name && ws.memberRole === "owner") {- const existingAgents = await queries.agent.listAgents(db, ws.workspaceId);- const newSlug = sanitizeSlug(body.name);- if (existingAgents.length === 0 && newSlug) {- let finalSlug = newSlug;- const conflicting = await queries.workspace.getWorkspaceBySlug(db, newSlug);- if (conflicting && conflicting.id !== ws.workspaceId) {- let found = false;- for (let i = 0; i < 5; i++) {- const suffix = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "lowerCase" });- const candidate = `${newSlug}-${suffix}`.slice(0, 60);- const c = await queries.workspace.getWorkspaceBySlug(db, candidate);- if (!c || c.id === ws.workspaceId) {- finalSlug = candidate;- found = true;- break;- }- }- if (!found) finalSlug = `${newSlug}-${slugSuffix(6)}`;- }- const updated = await queries.workspace.updateWorkspace(db, ws.workspaceId, {- name: body.name.trim(),- slug: finalSlug,- });- if (updated) updatedWorkspace = updated;- } else {- await queries.workspace.updateWorkspace(db, ws.workspaceId, {- name: body.name.trim(),- });- updatedWorkspace = await queries.workspace.getWorkspace(db, ws.workspaceId, ctx.userId);- }- }--- // Create agents- const 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[]);-- const usedNames = new Set<string>();- for (const member of body.members) {- let agentName = member.name;- if (!agentName) {- do {- agentName = uniqueNamesGenerator({ dictionaries: [names], length: 1, style: "capital" });- } while (usedNames.has(agentName));- }- usedNames.add(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- ? { ...(typeof rc.model === "string" ? { model: rc.model } : {}) }- : null;-- const runtime = runtimeCache.get(member.runtime_id);-- const newAgent = await queries.agent.createAgent(db, {- workspaceId: ws.workspaceId,- name: agentName,- description: member.description || "",- instructions: member.instructions || "",- runtimeId: member.runtime_id,- runtimeMode: runtime?.runtimeMode ?? "local",- runtimeConfig: sanitizedRc,- visibility: "private",- maxConcurrentTasks: 6,- ownerId: ctx.userId,- emailHandle: handle,- avatarUrl: member.avatar_url || randomBeamAvatar(),- });-- if (ctx.email) {- await queries.whitelist.addWhitelist(db, newAgent.id, ws.workspaceId, ctx.email.toLowerCase());- }-- createdAgents.push({- id: newAgent.id,- role: member.role,- name: agentName,- emailHandle: newAgent.emailHandle,- runtimeId: newAgent.runtimeId,- });- }-- // Create agent links (leader <-> specialists)- const leaderAgent = createdAgents.find((a) => a.role === "leader")!;- const specialists = createdAgents.filter((a) => a.role !== "leader");- const createdLinks = [];-- for (const specialist of specialists) {- const specIndex = createdAgents.indexOf(specialist);- const memberPayload = body.members[specIndex];- if (!memberPayload?.relationship) continue;-- try {- const link = await queries.agentLink.create(db, {- workspaceId: ws.workspaceId,- sourceAgentId: leaderAgent.id,- targetAgentId: specialist.id,- instruction: memberPayload.relationship,- });- createdLinks.push(link);- } catch {- // Best-effort — don't fail the whole studio creation- }- }-- const dateStr = new Date().toISOString().slice(0, 10);- await Promise.all([- invalidate(cacheKeys.allHandles(ws.workspaceId)),- invalidate(cacheKeys.allAgentAccess(ws.workspaceId)),- invalidate(cacheKeys.allMembers(ws.workspaceId)),- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)),- ]);-- // Pin leader agent by default- try {- await queries.agentPin.pinAgent(db, {- agentId: leaderAgent.id,- workspaceId: ws.workspaceId,- userId: ctx.userId,- });- invalidate(cacheKeys.pins(ws.workspaceId, ctx.userId)).catch(() => {});- } catch {- // Best-effort- }-- // Enqueue welcome email for leader only- const leaderRuntime = runtimeCache.get(body.members.find((m) => m.role === "leader")!.runtime_id);-- if (leaderAgent.emailHandle && ctx.email && leaderRuntime && isOnline(leaderRuntime.machineLastSeenAt)) {- try {- const teammatesList = createdAgents- .filter((a) => a.id !== leaderAgent.id)- .map((a) => `- ${a.name} (${a.emailHandle ? toAlookAddress(a.emailHandle) : a.name}), role: ${a.role}`)- .join("\n");-- const welcomePrompt = createdAgents.length === 1- ? `You have just been created by your owner (${ctx.email}). Please send them a welcome email introducing yourself as "${leaderAgent.name}". In the email: 1) Introduce yourself warmly — your name, your email address, and what you can help with. 2) Briefly introduce the Alook platform. 3) Let them know they can chat with you directly or email you anytime. Be warm, professional, and concise.`- : `You have just been created as the lead of a new AI studio by your owner (${ctx.email}). Your teammates are:\n${teammatesList}\n\nPlease send a welcome email to your owner introducing yourself and all your teammates. Include: 1) Your name and email address. 2) Each teammate's name, email, and what they handle. 3) How the team works together — you coordinate and delegate to specialists. 4) Let them know they can email you directly to assign work. Be warm, professional, and concise.`;-- const conv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: leaderAgent.id,- userId: ctx.userId,- title: `Welcome: ${ctx.email}`.slice(0, 50),- type: TASK_TYPES.EMAIL_NOTIFICATION,- });- const taskService = new TaskService(db);- await taskService.enqueueTask(- leaderAgent.id,- conv.id,- ws.workspaceId,- welcomePrompt,- TASK_TYPES.EMAIL_NOTIFICATION,- );- } catch {- // Best-effort- }- }-- // Enqueue welcome chat for leader (DM conversation)- if (leaderAgent && leaderRuntime && isOnline(leaderRuntime.machineLastSeenAt)) {- try {- const teammatesList = createdAgents- .filter((a) => a.id !== leaderAgent.id)- .map((a) => `- ${a.name} (${a.emailHandle ? toAlookAddress(a.emailHandle) : a.name}), role: ${a.role}`)- .join("\n");-- const welcomeChatPrompt = createdAgents.length === 1- ? `You have just been created by your owner (${ctx.email}). Please introduce yourself as "${leaderAgent.name}" in this chat. 1) Introduce yourself warmly — your name and what you can help with. 2) Briefly introduce the Alook platform. 3) Let them know they can chat with you directly or email you anytime. Be warm, professional, and concise. Reply in the same language as your owner's name or email suggests.`- : `You have just been created as the lead of a new AI studio by your owner (${ctx.email}). Your teammates are:\n${teammatesList}\n\nPlease introduce yourself and all your teammates in this chat. Include: 1) Your name. 2) Each teammate's name and what they handle. 3) How the team works together — you coordinate and delegate to specialists. 4) Let them know they can chat with you directly to assign work. Be warm, professional, and concise. Reply in the same language as your owner's name or email suggests.`;-- const dmConv = await queries.conversation.createConversation(db, {- workspaceId: ws.workspaceId,- agentId: leaderAgent.id,- userId: ctx.userId,- title: `Welcome`,- type: TASK_TYPES.USER_DM_MESSAGE,- });- const taskService2 = new TaskService(db);- await taskService2.enqueueTask(- leaderAgent.id,- dmConv.id,- ws.workspaceId,- welcomeChatPrompt,- TASK_TYPES.USER_DM_MESSAGE,- );- } catch {- // Best-effort- }- }-- // Fetch final agents for response- const agents = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);- const createdIdSet = new Set(createdAgents.map((ca) => ca.id));- const studioAgents = agents.filter((a) => createdIdSet.has(a.id));- const finalWorkspace = await queries.workspace.getWorkspace(db, ws.workspaceId, ctx.userId);-- return writeJSON({- studio: { name: finalWorkspace?.name || body.name || "" },- workspace: workspaceToResponse(finalWorkspace || updatedWorkspace),- leader_agent_id: leaderAgent.id,- agents: studioAgents.map(agentToResponse),- links: createdLinks.map(agentLinkToResponse),- }, 201);-});diff --git a/src/web/src/app/api/tasks/[id]/messages/route.test.ts b/src/web/src/app/api/tasks/[id]/messages/route.test.tsdeleted file mode 100644index 757198841..000000000--- a/src/web/src/app/api/tasks/[id]/messages/route.test.ts+++ /dev/null@@ -1,192 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetTask = vi.fn();-const mockGetAgent = vi.fn();-const mockListTaskMessages = vi.fn();-const mockListTaskMessagesSince = vi.fn();-const mockTaskMessageToResponse = vi.fn((m: any) => ({- id: m.id,- seq: m.seq,- type: m.type,- content: m.content,- output: m.output || "",-}));--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- task: {- getTask: (...args: any[]) => mockGetTask(...args),- },- agent: {- getAgent: (...args: any[]) => mockGetAgent(...args),- },- taskMessage: {- listTaskMessages: (...args: any[]) => mockListTaskMessages(...args),- listTaskMessagesSince: (...args: any[]) => mockListTaskMessagesSince(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- taskMessageToResponse: (...args: any[]) => mockTaskMessageToResponse(...args),-}));--import { GET } from "./route";--describe("GET /api/tasks/[id]/messages", () => {- beforeEach(() => vi.clearAllMocks());-- it("passes workspaceId to getTask", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskMessages.mockResolvedValue([]);- await GET(- new NextRequest("http://localhost/api/tasks/t1/messages"),- { params: Promise.resolve({ id: "t1" }) }- );- expect(mockGetTask).toHaveBeenCalledWith({}, "t1", "w1");- });-- it("lists all messages", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- const messages = [- { id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },- { id: "m2", taskId: "t1", seq: 2, type: "text", content: "world" },- ];- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskMessages.mockResolvedValue(messages);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "m1", seq: 1, type: "text", content: "hello", output: "" },- { id: "m2", seq: 2, type: "text", content: "world", output: "" },- ]);- expect(mockListTaskMessages).toHaveBeenCalledWith({}, "t1");- });-- it("filters by since parameter", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- const messages = [- { id: "m3", taskId: "t1", seq: 6, type: "text", content: "new msg" },- ];- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskMessagesSince.mockResolvedValue(messages);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?since=5"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([- { id: "m3", seq: 6, type: "text", content: "new msg", output: "" },- ]);- expect(mockListTaskMessagesSince).toHaveBeenCalledWith({}, "t1", 5);- expect(mockListTaskMessages).not.toHaveBeenCalled();- });-- it("returns 400 for invalid since parameter", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?since=abc"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid since parameter");- });-- it("returns 404 when task not found", async () => {- mockGetTask.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-- it("only returns text and error messages (tool-result, tool-use, thinking filtered at query level)", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- const messages = [- { id: "m1", taskId: "t1", seq: 1, type: "text", content: "hello" },- ];- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskMessages.mockResolvedValue(messages);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].type).toBe("text");- });-- it("only returns text and error messages with since parameter (filtered at query level)", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1" };- const messages = [- { id: "m4", taskId: "t1", seq: 7, type: "text", content: "new update" },- ];- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockListTaskMessagesSince.mockResolvedValue(messages);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1/messages?since=5"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].type).toBe("text");- });-});diff --git a/src/web/src/app/api/tasks/[id]/messages/route.ts b/src/web/src/app/api/tasks/[id]/messages/route.tsdeleted file mode 100644index 02bdbc7ad..000000000--- a/src/web/src/app/api/tasks/[id]/messages/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskMessageToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("task id is required", 400);- }-- const task = await queries.task.getTask(db, id, ws.workspaceId);- if (!task) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- const sinceParam = req.nextUrl.searchParams.get("since");- let messages;-- if (sinceParam) {- const afterSeq = parseInt(sinceParam, 10);- if (isNaN(afterSeq)) {- return writeError("invalid since parameter", 400);- }- messages = await queries.taskMessage.listTaskMessagesSince(db, id, afterSeq);- } else {- messages = await queries.taskMessage.listTaskMessages(db, id);- }-- return writeJSON(messages.map(taskMessageToResponse));-});diff --git a/src/web/src/app/api/tasks/[id]/retry/route.test.ts b/src/web/src/app/api/tasks/[id]/retry/route.test.tsdeleted file mode 100644index 11be59e16..000000000--- a/src/web/src/app/api/tasks/[id]/retry/route.test.ts+++ /dev/null@@ -1,121 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetTask = vi.fn();-const mockGetAgent = vi.fn();-const mockRetryTask = vi.fn();-const mockTaskToResponse = vi.fn((t: any) => ({- id: t.id,- agent_id: t.agentId,- workspace_id: t.workspaceId,- status: t.status,- prompt: t.prompt,-}));--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- task: {- getTask: (...args: any[]) => mockGetTask(...args),- },- agent: {- getAgent: (...args: any[]) => mockGetAgent(...args),- },- },-}));-vi.mock("@/lib/services/task", () => {- const MockTaskService = function (this: any) {- this.retryTask = (...a: any[]) => mockRetryTask(...a);- } as any;- return { TaskService: MockTaskService };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));-vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));-vi.mock("@/lib/cache", () => ({- invalidate: vi.fn().mockReturnValue(Promise.resolve()),- cacheKeys: { overviewTaskStats: (...args: any[]) => `stats:${args.join(":")}` },-}));--import { POST } from "./route";--describe("POST /api/tasks/[id]/retry", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns new task on success", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1", status: "failed", prompt: "hello" };- const oldTask = { id: "t1", agentId: "a1", workspaceId: "w1", status: "superseded", prompt: "hello" };- const newTask = { id: "t2", agentId: "a1", workspaceId: "w1", status: "queued", prompt: "hello" };- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockRetryTask.mockResolvedValue({ oldTask, newTask });-- const res = await POST(- new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),- { params: Promise.resolve({ id: "t1" }) },- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.status).toBe("queued");- expect(body.prompt).toBe("hello");- expect(mockRetryTask).toHaveBeenCalledWith("t1", "w1");- });-- it("returns 400 when task is not failed", async () => {- const task = { id: "t1", agentId: "a1", workspaceId: "w1", status: "completed", prompt: "hello" };- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });- mockRetryTask.mockRejectedValue(new Error("only failed tasks can be retried"));-- const res = await POST(- new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),- { params: Promise.resolve({ id: "t1" }) },- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("only failed tasks can be retried");- });-- it("returns 404 when task not found", async () => {- mockGetTask.mockResolvedValue(null);-- const res = await POST(- new NextRequest("http://localhost/api/tasks/t1/retry", { method: "POST" }),- { params: Promise.resolve({ id: "t1" }) },- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});diff --git a/src/web/src/app/api/tasks/[id]/retry/route.ts b/src/web/src/app/api/tasks/[id]/retry/route.tsdeleted file mode 100644index 8a42c8072..000000000--- a/src/web/src/app/api/tasks/[id]/retry/route.ts+++ /dev/null@@ -1,43 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";-import { TaskService } from "@/lib/services/task";-import { broadcastToUser } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--export const POST = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const id = ctx.params?.id;- if (!id) {- return writeError("task id is required", 400);- }-- const task = await queries.task.getTask(db, id, ws.workspaceId);- if (!task) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- const taskService = new TaskService(db);- try {- const { oldTask, newTask } = await taskService.retryTask(id, ws.workspaceId);- const dateStr = new Date().toISOString().slice(0, 10);- invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});- broadcastToUser(ctx.userId, { type: "task.updated", taskId: oldTask.id, agentId: oldTask.agentId, status: "superseded" }).catch(() => {});- broadcastToUser(ctx.userId, { type: "task.updated", taskId: newTask.id, agentId: newTask.agentId, status: "queued" }).catch(() => {});- return writeJSON(taskToResponse(newTask));- } catch (e: unknown) {- return writeError(e instanceof Error ? e.message : "Request failed", 400);- }-});diff --git a/src/web/src/app/api/tasks/[id]/route.test.ts b/src/web/src/app/api/tasks/[id]/route.test.tsdeleted file mode 100644index 2df90b307..000000000--- a/src/web/src/app/api/tasks/[id]/route.test.ts+++ /dev/null@@ -1,100 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetTask = vi.fn();-const mockGetAgent = vi.fn();-const mockTaskToResponse = vi.fn((t: any) => ({- id: t.id,- agent_id: t.agentId,- workspace_id: t.workspaceId,- status: t.status,- prompt: t.prompt,-}));--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- task: {- getTask: (...args: any[]) => mockGetTask(...args),- },- agent: {- getAgent: (...args: any[]) => mockGetAgent(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/api/responses", () => ({- taskToResponse: (...args: any[]) => mockTaskToResponse(...args),-}));--import { GET } from "./route";--describe("GET /api/tasks/[id]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns task", async () => {- const task = {- id: "t1",- agentId: "a1",- workspaceId: "w1",- status: "completed",- prompt: "hello",- };- mockGetTask.mockResolvedValue(task);- mockGetAgent.mockResolvedValue({ id: "a1" });-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual({- id: "t1",- agent_id: "a1",- workspace_id: "w1",- status: "completed",- prompt: "hello",- });- expect(mockGetTask).toHaveBeenCalledWith({}, "t1", "w1");- });-- it("returns 404 when not found (scoped by workspace)", async () => {- mockGetTask.mockResolvedValue(null);-- const res = await GET(- new NextRequest("http://localhost/api/tasks/t1"),- { params: Promise.resolve({ id: "t1" }) }- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});diff --git a/src/web/src/app/api/tasks/[id]/route.ts b/src/web/src/app/api/tasks/[id]/route.tsdeleted file mode 100644index c21ddcc65..000000000--- a/src/web/src/app/api/tasks/[id]/route.ts+++ /dev/null@@ -1,30 +0,0 @@-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { taskToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("task id is required", 400);- }-- const task = await queries.task.getTask(db, id, ws.workspaceId);- if (!task) {- return writeError("not found", 404);- }-- const agent = await queries.agent.getAgent(db, task.agentId, ws.workspaceId, ctx.userId);- if (!agent) {- return writeError("not found", 404);- }-- return writeJSON(taskToResponse(task));-});diff --git a/src/web/src/app/api/traces/[traceId]/route.test.ts b/src/web/src/app/api/traces/[traceId]/route.test.tsdeleted file mode 100644index fcf6d35ff..000000000--- a/src/web/src/app/api/traces/[traceId]/route.test.ts+++ /dev/null@@ -1,231 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetTraceTree = vi.fn();-const mockGetConversation = vi.fn();-const mockGetAllAgentsForWorkspace = vi.fn();-const mockGetAllAgentAccessForWorkspace = vi.fn();--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", () => ({- queries: {- task: {- getTraceTree: (...args: any[]) => mockGetTraceTree(...args),- },- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- },- agent: {- getAllAgentsForWorkspace: (...args: any[]) => mockGetAllAgentsForWorkspace(...args),- },- agentAccess: {- getAllAgentAccessForWorkspace: (...args: any[]) => mockGetAllAgentAccessForWorkspace(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),- cacheKeys: {- allAgents: (ws: string) => `agents:${ws}`,- allAgentAccess: (ws: string) => `aa:${ws}`,- },-}));-vi.mock("@/lib/agent-visibility", () => ({- filterVisibleAgents: vi.fn((agents: any[]) => agents),-}));--import { GET } from "./route";--describe("GET /api/traces/[traceId]", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns 400 for traceId without tr_ prefix", async () => {- const res = await GET(- new NextRequest("http://localhost/api/traces/invalid123"),- { params: Promise.resolve({ traceId: "invalid123" }) },- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid traceId");- });-- it("returns 400 for traceId that is too long", async () => {- const longId = "tr_" + "a".repeat(28); // length 31 > 30- const res = await GET(- new NextRequest(`http://localhost/api/traces/${longId}`),- { params: Promise.resolve({ traceId: longId }) },- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid traceId");- });-- it("returns 400 for missing traceId", async () => {- const res = await GET(- new NextRequest("http://localhost/api/traces/"),- { params: Promise.resolve({}) },- );- const body = await res.json();-- expect(res.status).toBe(400);- expect(body.error).toBe("invalid traceId");- });-- it("returns 404 when trace not found (empty tasks)", async () => {- mockGetTraceTree.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/traces/tr_abc123"),- { params: Promise.resolve({ traceId: "tr_abc123" }) },- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("trace not found");- });-- it("returns trace with tasks and agent mapping", async () => {- mockGetTraceTree.mockResolvedValue([- {- id: "task_1",- agentId: "a1",- parentTaskId: null,- prompt: "Root task",- status: "completed",- type: "user_dm_message",- conversationId: "conv_1",- createdAt: "2026-01-01T00:00:00Z",- completedAt: "2026-01-01T00:01:00Z",- },- {- id: "task_2",- agentId: "a2",- parentTaskId: "task_1",- prompt: "Sub task",- status: "completed",- type: "email_notification",- conversationId: "conv_1",- createdAt: "2026-01-01T00:00:10Z",- completedAt: "2026-01-01T00:00:50Z",- },- ]);- mockGetConversation.mockResolvedValue({ channel: "slack" });- mockGetAllAgentsForWorkspace.mockResolvedValue([- { id: "a1", name: "Agent 1", emailHandle: "agent1", avatarUrl: "https://img/a1.png" },- { id: "a2", name: "Agent 2", emailHandle: "agent2", avatarUrl: "https://img/a2.png" },- ]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/traces/tr_abc123"),- { params: Promise.resolve({ traceId: "tr_abc123" }) },- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.trace_id).toBe("tr_abc123");- expect(body.channel).toBe("slack");- expect(body.tasks).toHaveLength(2);- expect(body.tasks[0]).toEqual({- id: "task_1",- agent_id: "a1",- agent: { name: "Agent 1", email_handle: "agent1", avatarUrl: "https://img/a1.png" },- parent_task_id: null,- prompt: "Root task",- status: "completed",- type: "user_dm_message",- conversation_id: "conv_1",- created_at: "2026-01-01T00:00:00Z",- completed_at: "2026-01-01T00:01:00Z",- });- expect(body.tasks[1].agent).toEqual({- name: "Agent 2",- email_handle: "agent2",- avatarUrl: "https://img/a2.png",- });- });-- it("returns default channel when no conversation found", async () => {- mockGetTraceTree.mockResolvedValue([- {- id: "task_1",- agentId: "a1",- parentTaskId: null,- prompt: "Root task",- status: "active",- type: "user_dm_message",- conversationId: "conv_1",- createdAt: "2026-01-01T00:00:00Z",- completedAt: null,- },- ]);- mockGetConversation.mockResolvedValue(null);- mockGetAllAgentsForWorkspace.mockResolvedValue([- { id: "a1", name: "Agent 1", emailHandle: "agent1", avatarUrl: null },- ]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/traces/tr_abc123"),- { params: Promise.resolve({ traceId: "tr_abc123" }) },- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.channel).toBe("default");- });-- it("returns 404 when root agent is not visible", async () => {- mockGetTraceTree.mockResolvedValue([- {- id: "task_1",- agentId: "unknown_agent",- parentTaskId: null,- prompt: "Root task",- status: "active",- type: "user_dm_message",- conversationId: "conv_1",- createdAt: "2026-01-01T00:00:00Z",- completedAt: null,- },- ]);- mockGetConversation.mockResolvedValue({ channel: "default" });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- const res = await GET(- new NextRequest("http://localhost/api/traces/tr_abc123"),- { params: Promise.resolve({ traceId: "tr_abc123" }) },- );- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("not found");- });-});diff --git a/src/web/src/app/api/traces/[traceId]/route.ts b/src/web/src/app/api/traces/[traceId]/route.tsdeleted file mode 100644index e766b2107..000000000--- a/src/web/src/app/api/traces/[traceId]/route.ts+++ /dev/null@@ -1,57 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON, writeError } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const traceId = ctx.params?.traceId;- if (!traceId || typeof traceId !== "string" || !traceId.startsWith("tr_") || traceId.length > 30) {- return writeError("invalid traceId", 400);- }-- const tasks = await queries.task.getTraceTree(db, traceId, ws.workspaceId);- if (tasks.length === 0) return writeError("trace not found", 404);-- const rootTask = tasks.find(t => !t.parentTaskId);- let channel = "default";- if (rootTask) {- const conv = await queries.conversation.getConversation(db, rootTask.conversationId, ws.workspaceId);- if (conv) channel = conv.channel;- }-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- const visibleIds = new Set(agents.map(a => a.id));- const agentMap = new Map(agents.map(a => [a.id, { name: a.name, email_handle: a.emailHandle, avatarUrl: a.avatarUrl }]));-- if (rootTask && !visibleIds.has(rootTask.agentId)) {- return writeError("not found", 404);- }-- const traceTasks = tasks.filter(t => visibleIds.has(t.agentId)).map(t => ({- id: t.id,- agent_id: t.agentId,- agent: agentMap.get(t.agentId) ?? null,- parent_task_id: t.parentTaskId,- prompt: t.prompt,- status: t.status,- type: t.type,- conversation_id: t.conversationId,- created_at: t.createdAt,- completed_at: t.completedAt,- }));-- return writeJSON({ trace_id: traceId, channel, tasks: traceTasks });-});diff --git a/src/web/src/app/api/traces/route.test.ts b/src/web/src/app/api/traces/route.test.tsdeleted file mode 100644index 134198c7e..000000000--- a/src/web/src/app/api/traces/route.test.ts+++ /dev/null@@ -1,215 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListTraces = vi.fn();-const mockGetAllAgentsForWorkspace = vi.fn();-const mockGetAllAgentAccessForWorkspace = vi.fn();--vi.mock("@/lib/middleware/helpers", () => ({- writeJSON: (data: any, status = 200) =>- new Response(JSON.stringify(data), {- status,- headers: { "content-type": "application/json" },- }),- writeError: (message: string, status: number) =>- new Response(JSON.stringify({ error: message }), {- status,- headers: { "content-type": "application/json" },- }),-}));-vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));-vi.mock("@alook/shared", () => ({- queries: {- task: {- listTraces: (...args: any[]) => mockListTraces(...args),- },- agent: {- getAllAgentsForWorkspace: (...args: any[]) => mockGetAllAgentsForWorkspace(...args),- },- agentAccess: {- getAllAgentAccessForWorkspace: (...args: any[]) => mockGetAllAgentAccessForWorkspace(...args),- },- },-}));-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_key: string, _ttl: number, fn: () => any) => fn()),- cacheKeys: {- allAgents: (ws: string) => `agents:${ws}`,- allAgentAccess: (ws: string) => `aa:${ws}`,- },-}));-vi.mock("@/lib/agent-visibility", () => ({- filterVisibleAgents: vi.fn((agents: any[]) => agents),-}));--import { GET } from "./route";--describe("GET /api/traces", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns traces with agent info mapped", async () => {- mockListTraces.mockResolvedValue({- traces: [- {- traceId: "tr_abc",- rootPrompt: "Hello",- rootAgentId: "a1",- helperAgentIds: ["a2"],- status: "completed",- taskCount: 2,- startedAt: "2026-01-01T00:00:00Z",- completedAt: "2026-01-01T00:01:00Z",- channel: "default",- },- ],- hasMore: false,- });- mockGetAllAgentsForWorkspace.mockResolvedValue([- { id: "a1", name: "Agent 1", avatarUrl: "https://img/a1.png" },- { id: "a2", name: "Agent 2", avatarUrl: "https://img/a2.png" },- ]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- const res = await GET(new NextRequest("http://localhost/api/traces"), {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.traces).toHaveLength(1);- expect(body.traces[0]).toEqual({- trace_id: "tr_abc",- root_prompt: "Hello",- root_agent_id: "a1",- root_agent: { name: "Agent 1", avatarUrl: "https://img/a1.png" },- helper_agents: [{ id: "a2", name: "Agent 2", avatarUrl: "https://img/a2.png" }],- status: "completed",- task_count: 2,- started_at: "2026-01-01T00:00:00Z",- completed_at: "2026-01-01T00:01:00Z",- channel: "default",- });- expect(body.has_more).toBe(false);- });-- it("filters out traces whose root agent is not visible", async () => {- mockListTraces.mockResolvedValue({- traces: [- {- traceId: "tr_xyz",- rootPrompt: "Test",- rootAgentId: "unknown_agent",- helperAgentIds: [],- status: "active",- taskCount: 1,- startedAt: "2026-01-01T00:00:00Z",- completedAt: null,- channel: "email",- },- ],- hasMore: false,- });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- const res = await GET(new NextRequest("http://localhost/api/traces"), {});- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.traces).toHaveLength(0);- });-- it("respects status filter", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces?status=failed"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ status: "failed" }),- );- });-- it("ignores invalid status filter", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces?status=invalid"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ status: undefined }),- );- });-- it("default limit behavior", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ limit: undefined }),- );- });-- it("clamps limit to 1-100 range", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces?limit=200"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ limit: 100 }),- );- });-- it("multiAgent filter", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces?multiAgent=true"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ multiAgent: true }),- );- });-- it("passes agentId and channel filters", async () => {- mockListTraces.mockResolvedValue({ traces: [], hasMore: false });- mockGetAllAgentsForWorkspace.mockResolvedValue([]);- mockGetAllAgentAccessForWorkspace.mockResolvedValue([]);-- await GET(new NextRequest("http://localhost/api/traces?agentId=a1&channel=email"), {});-- expect(mockListTraces).toHaveBeenCalledWith(- {},- "w1",- expect.objectContaining({ agentId: "a1", channel: "email" }),- );- });-});diff --git a/src/web/src/app/api/traces/route.ts b/src/web/src/app/api/traces/route.tsdeleted file mode 100644index c6b8c8b8c..000000000--- a/src/web/src/app/api/traces/route.ts+++ /dev/null@@ -1,49 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const statusRaw = req.nextUrl.searchParams.get("status");- const status = statusRaw && ["active", "completed", "failed"].includes(statusRaw) ? statusRaw : undefined;- const before = req.nextUrl.searchParams.get("before") ?? undefined;- const limitParam = req.nextUrl.searchParams.get("limit");- const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : undefined;-- const multiAgent = req.nextUrl.searchParams.get("multiAgent") === "true";- const agentId = req.nextUrl.searchParams.get("agentId") ?? undefined;- const channel = req.nextUrl.searchParams.get("channel") ?? undefined;- const result = await queries.task.listTraces(db, ws.workspaceId, { status, limit, before, multiAgent, agentId, channel });-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const agents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- const visibleIds = new Set(agents.map(a => a.id));- const agentMap = new Map(agents.map(a => [a.id, { name: a.name, avatarUrl: a.avatarUrl }]));-- const traces = result.traces.filter(t => visibleIds.has(t.rootAgentId)).map(t => ({- trace_id: t.traceId,- root_prompt: t.rootPrompt,- root_agent_id: t.rootAgentId,- root_agent: agentMap.get(t.rootAgentId) ?? null,- helper_agents: t.helperAgentIds.map(id => ({ id, ...agentMap.get(id) })),- status: t.status,- task_count: t.taskCount,- started_at: t.startedAt,- completed_at: t.completedAt,- channel: t.channel,- }));-- return writeJSON({ traces, has_more: result.hasMore });-});diff --git a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.ts b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.tsdeleted file mode 100644index adc581e4e..000000000--- a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockDeleteInvite = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- workspaceInvite: {- deleteInvite: (...args: unknown[]) => mockDeleteInvite(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceOwner: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--import { DELETE } from "./route";--describe("DELETE /api/workspaces/[id]/invites/[inviteId]", () => {- beforeEach(() => vi.clearAllMocks());-- it("revokes invite and returns 204", async () => {- mockDeleteInvite.mockResolvedValue({ id: "inv1" });-- const req = new NextRequest("http://localhost/api/workspaces/w1/invites/inv1", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1", inviteId: "inv1" }) } as any);-- expect(res.status).toBe(204);- expect(mockDeleteInvite).toHaveBeenCalledWith({}, "inv1", "w1");- });-- it("returns 404 when invite not found", async () => {- mockDeleteInvite.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w1/invites/inv-gone", { method: "DELETE" });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1", inviteId: "inv-gone" }) } as any);-- expect(res.status).toBe(404);- const body = await res.json();- expect(body.error).toBe("invite not found");- });-});diff --git a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.ts b/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.tsdeleted file mode 100644index 146e9e34b..000000000--- a/src/web/src/app/api/workspaces/[id]/invites/[inviteId]/route.ts+++ /dev/null@@ -1,20 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceOwner } from "@/lib/middleware/workspace";-import { writeError } from "@/lib/middleware/helpers";--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const { inviteId } = ctx.params!;-- const db = getDb(ctx.env.DB);-- const deleted = await queries.workspaceInvite.deleteInvite(db, inviteId, owner.workspaceId);- if (!deleted) return writeError("invite not found", 404);-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/workspaces/[id]/invites/route.test.ts b/src/web/src/app/api/workspaces/[id]/invites/route.test.tsdeleted file mode 100644index 8bad642c6..000000000--- a/src/web/src/app/api/workspaces/[id]/invites/route.test.ts+++ /dev/null@@ -1,103 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListActiveInvites = vi.fn();-const mockCreateInvite = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- workspaceInvite: {- listActiveInvites: (...args: unknown[]) => mockListActiveInvites(...args),- createInvite: (...args: unknown[]) => mockCreateInvite(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceOwner: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/api/responses", async () =>- await vi.importActual<typeof import("@/lib/api/responses")>("@/lib/api/responses")-);--import { GET, POST } from "./route";--const sampleInvite = {- id: "inv1",- token: "tok-abc",- createdBy: "u1",- usedBy: null,- expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),- createdAt: "2024-01-01T00:00:00Z",-};--describe("GET /api/workspaces/[id]/invites", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns list of active invites", async () => {- mockListActiveInvites.mockResolvedValue([sampleInvite]);-- const req = new NextRequest("http://localhost/api/workspaces/w1/invites", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(1);- expect(body[0].id).toBe("inv1");- expect(body[0].token).toBe("tok-abc");- expect(mockListActiveInvites).toHaveBeenCalledWith({}, "w1");- });-- it("returns empty array when no active invites", async () => {- mockListActiveInvites.mockResolvedValue([]);-- const req = new NextRequest("http://localhost/api/workspaces/w1/invites", { method: "GET" });- const res = await GET(req, { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([]);- });-});--describe("POST /api/workspaces/[id]/invites", () => {- beforeEach(() => vi.clearAllMocks());-- it("creates a new invite and returns 201", async () => {- mockCreateInvite.mockResolvedValue(sampleInvite);-- const req = new NextRequest("http://localhost/api/workspaces/w1/invites", { method: "POST" });- const res = await POST(req, { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(201);- expect(body.id).toBe("inv1");- expect(body.token).toBe("tok-abc");- expect(mockCreateInvite).toHaveBeenCalledWith(- {},- expect.objectContaining({ workspaceId: "w1", createdBy: "u1" })- );- });-});diff --git a/src/web/src/app/api/workspaces/[id]/invites/route.ts b/src/web/src/app/api/workspaces/[id]/invites/route.tsdeleted file mode 100644index cf2cf288a..000000000--- a/src/web/src/app/api/workspaces/[id]/invites/route.ts+++ /dev/null@@ -1,32 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceOwner } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { inviteToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const db = getDb(ctx.env.DB);-- const invites = await queries.workspaceInvite.listActiveInvites(db, owner.workspaceId);- return writeJSON(invites.map(inviteToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const db = getDb(ctx.env.DB);-- const expiresAt = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString();- const invite = await queries.workspaceInvite.createInvite(db, {- workspaceId: owner.workspaceId,- createdBy: ctx.userId,- expiresAt,- });- return writeJSON(inviteToResponse(invite), 201);-});diff --git a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.ts b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.tsdeleted file mode 100644index ceec52c65..000000000--- a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetMember = vi.fn();-const mockDeleteMember = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- member: {- getMember: (...args: unknown[]) => mockGetMember(...args),- deleteMember: (...args: unknown[]) => mockDeleteMember(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceOwner: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--import { DELETE } from "./route";--function makeReq(memberId: string) {- return new NextRequest(`http://localhost/api/workspaces/w1/members/${memberId}`, { method: "DELETE" });-}--describe("DELETE /api/workspaces/[id]/members/[memberId]", () => {- beforeEach(() => vi.clearAllMocks());-- it("removes a member successfully", async () => {- mockGetMember.mockResolvedValue({ id: "m2", userId: "u2", role: "member" });- mockDeleteMember.mockResolvedValue({ id: "m2" });-- const res = await DELETE(makeReq("m2"), { params: Promise.resolve({ id: "w1", memberId: "m2" }) } as any);- expect(res.status).toBe(204);- expect(mockDeleteMember).toHaveBeenCalledWith({}, "m2", "w1");- });-- it("returns 404 when member not found", async () => {- mockGetMember.mockResolvedValue(null);-- const res = await DELETE(makeReq("m-unknown"), { params: Promise.resolve({ id: "w1", memberId: "m-unknown" }) } as any);- expect(res.status).toBe(404);- const body = await res.json();- expect(body.error).toBe("member not found");- });-- it("returns 400 when trying to remove yourself", async () => {- mockGetMember.mockResolvedValue({ id: "m1", userId: "u1", role: "owner" });-- const res = await DELETE(makeReq("m1"), { params: Promise.resolve({ id: "w1", memberId: "m1" }) } as any);- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("cannot remove yourself");- });-- it("returns 403 when trying to remove an owner", async () => {- mockGetMember.mockResolvedValue({ id: "m3", userId: "u3", role: "owner" });-- const res = await DELETE(makeReq("m3"), { params: Promise.resolve({ id: "w1", memberId: "m3" }) } as any);- expect(res.status).toBe(403);- const body = await res.json();- expect(body.error).toBe("cannot remove a workspace owner");- });-});diff --git a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts b/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.tsdeleted file mode 100644index 724422f0a..000000000--- a/src/web/src/app/api/workspaces/[id]/members/[memberId]/route.ts+++ /dev/null@@ -1,29 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceOwner } 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 owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const { memberId } = ctx.params!;-- const db = getDb(ctx.env.DB);-- const target = await queries.member.getMember(db, memberId, owner.workspaceId);- if (!target) return writeError("member not found", 404);- if (target.userId === ctx.userId) return writeError("cannot remove yourself", 400);- if (target.role === "owner") return writeError("cannot remove a workspace owner", 403);-- await queries.member.deleteMember(db, memberId, owner.workspaceId);- await Promise.all([- invalidate(cacheKeys.member(owner.workspaceId, target.userId)),- invalidate(cacheKeys.allMembers(owner.workspaceId)),- ]);-- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/workspaces/[id]/members/route.test.ts b/src/web/src/app/api/workspaces/[id]/members/route.test.tsdeleted file mode 100644index 7f00901e4..000000000--- a/src/web/src/app/api/workspaces/[id]/members/route.test.ts+++ /dev/null@@ -1,95 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockListMembers = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- member: {- listMembers: (...args: unknown[]) => mockListMembers(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1", memberRole: "member" })),-}));--vi.mock("@/lib/api/responses", async () =>- await vi.importActual<typeof import("@/lib/api/responses")>("@/lib/api/responses")-);--import { GET } from "./route";--function makeReq() {- return new NextRequest("http://localhost/api/workspaces/w1/members", { method: "GET" });-}--describe("GET /api/workspaces/[id]/members", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns list of members", async () => {- mockListMembers.mockResolvedValue([- {- id: "m1",- userId: "u1",- role: "owner",- createdAt: "2024-01-01T00:00:00Z",- userName: "Alice",- userEmail: "[email protected]",- userImage: null,- },- {- id: "m2",- userId: "u2",- role: "member",- createdAt: "2024-01-02T00:00:00Z",- userName: "Bob",- userEmail: "[email protected]",- userImage: "http://example.com/bob.png",- },- ]);-- const res = await GET(makeReq(), { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toHaveLength(2);- expect(body[0].id).toBe("m1");- expect(body[0].user_id).toBe("u1");- expect(body[0].role).toBe("owner");- expect(body[1].id).toBe("m2");- expect(mockListMembers).toHaveBeenCalledWith({}, "w1");- });-- it("returns empty array when workspace has no members", async () => {- mockListMembers.mockResolvedValue([]);-- const res = await GET(makeReq(), { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body).toEqual([]);- });-});diff --git a/src/web/src/app/api/workspaces/[id]/members/route.ts b/src/web/src/app/api/workspaces/[id]/members/route.tsdeleted file mode 100644index 4c456aad6..000000000--- a/src/web/src/app/api/workspaces/[id]/members/route.ts+++ /dev/null@@ -1,17 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { memberToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (req: NextRequest, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const members = await queries.member.listMembers(db, ws.workspaceId);- return writeJSON(members.map(memberToResponse));-});diff --git a/src/web/src/app/api/workspaces/[id]/onboarded/route.ts b/src/web/src/app/api/workspaces/[id]/onboarded/route.tsdeleted file mode 100644index fe5d4f526..000000000--- a/src/web/src/app/api/workspaces/[id]/onboarded/route.ts+++ /dev/null@@ -1,19 +0,0 @@-import { NextRequest } from "next/server";-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB);-- const id = req.nextUrl.pathname.split("/").at(-2)!;-- const membership = await queries.member.getMemberByUserAndWorkspace(db, ctx.userId, id);- if (!membership) {- return writeJSON({ error: "not a member" }, 403);- }-- await queries.workspace.markOnboarded(db, id);- return writeJSON({ ok: true });-});diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.test.ts b/src/web/src/app/api/workspaces/[id]/overview/route.test.tsdeleted file mode 100644index 177276fa0..000000000--- a/src/web/src/app/api/workspaces/[id]/overview/route.test.ts+++ /dev/null@@ -1,90 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));-vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--const q = {- getAllAgents: vi.fn(),- getAllAccess: vi.fn(),- emailStats: vi.fn(),- emailAccounts: vi.fn(),- taskStats: vi.fn(),- recentTasks: vi.fn(),- convCounts: vi.fn(),- members: vi.fn(),- invites: vi.fn(),- calendar: vi.fn(),-};--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- queries: {- agent: { getAllAgentsForWorkspace: (...a: unknown[]) => q.getAllAgents(...a) },- agentAccess: { getAllAgentAccessForWorkspace: (...a: unknown[]) => q.getAllAccess(...a) },- overview: {- getEmailStatsByWorkspace: (...a: unknown[]) => q.emailStats(...a),- getEmailAccountsByWorkspace: (...a: unknown[]) => q.emailAccounts(...a),- getTaskStatsByWorkspace: (...a: unknown[]) => q.taskStats(...a),- getRecentTerminalTasks: (...a: unknown[]) => q.recentTasks(...a),- getConversationCountsByAgent: (...a: unknown[]) => q.convCounts(...a),- },- member: { listMembers: (...a: unknown[]) => q.members(...a) },- workspaceInvite: { listActiveInvites: (...a: unknown[]) => q.invites(...a) },- calendarEvent: { listCalendarEvents: (...a: unknown[]) => q.calendar(...a) },- },- };-});-vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));-vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),-}));-vi.mock("@/lib/cache", () => ({- cached: vi.fn((_k: string, _t: number, fn: () => Promise<any>) => fn()),- cacheKeys: {- allAgents: (w: string) => `ag:${w}`, allAgentAccess: (w: string) => `aa:${w}`,- overviewEmailStats: (w: string) => `es:${w}`, overviewEmailAccounts: (w: string) => `ea:${w}`,- overviewTaskStats: (w: string, d: string) => `ts:${w}:${d}`, allMembers: (w: string) => `mem:${w}`,- },-}));-vi.mock("@/lib/agent-visibility", () => ({ filterVisibleAgents: vi.fn((a: any[]) => a) }));--import { GET } from "./route";--beforeEach(() => {- vi.clearAllMocks();- q.getAllAgents.mockResolvedValue([{ id: "a1" }]);- q.getAllAccess.mockResolvedValue([]);- q.emailStats.mockResolvedValue({ total: 5 });- q.emailAccounts.mockResolvedValue([{ id: "ea1", agentId: "a1", emailAddress: "[email protected]", status: "ok", errorMessage: null, lastSyncedAt: null }]);- q.taskStats.mockResolvedValue({ done: 2 });- q.recentTasks.mockResolvedValue([{ id: "t1", agentId: "a1", type: "dm", status: "completed", prompt: "p", createdAt: "d", completedAt: "d", error: null }]);- q.convCounts.mockResolvedValue([{ agentId: "a1", cnt: 3 }]);- q.members.mockResolvedValue([{ id: "m1", userId: "u1", role: "owner", userName: "U", userEmail: "[email protected]", userImage: null, createdAt: "d" }]);- q.invites.mockResolvedValue([{ id: "i1" }, { id: "i2" }]);- q.calendar.mockResolvedValue([{ id: "c1", agentId: "a1", title: "T", description: "", scheduledAt: "d", repeatInterval: null, repeatStopAt: null, lastTriggeredAt: null }]);-});--describe("GET /api/workspaces/[id]/overview", () => {- it("aggregates the workspace dashboard payload", async () => {- const res = await GET(new NextRequest("http://localhost/x"), { params: { id: "w1" } });- const body = await res.json();- expect(res.status).toBe(200);- expect(body.email_stats).toEqual({ total: 5 });- expect(body.conversation_counts).toEqual({ a1: 3 });- expect(body.pending_invites).toBe(2);- expect(body.recent_tasks[0].id).toBe("t1");- expect(body.calendar_events[0].title).toBe("T");- // visible-agent scoping passed to recent tasks / conv counts- expect(q.recentTasks).toHaveBeenCalledWith({}, "w1", ["a1"], 15);- });-});diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.ts b/src/web/src/app/api/workspaces/[id]/overview/route.tsdeleted file mode 100644index 49e8d43b6..000000000--- a/src/web/src/app/api/workspaces/[id]/overview/route.ts+++ /dev/null@@ -1,104 +0,0 @@-import { queries } from "@alook/shared";-import { getDb } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceMember } from "@/lib/middleware/workspace";-import { writeJSON } from "@/lib/middleware/helpers";-import { cached, cacheKeys } from "@/lib/cache";-import { filterVisibleAgents } from "@/lib/agent-visibility";--export const GET = withAuth(async (req, ctx) => {- const ws = await withWorkspaceMember(req, ctx);- if (ws instanceof Response) return ws;-- const db = getDb(ctx.env.DB);-- const todayStart = new Date();- todayStart.setHours(0, 0, 0, 0);- const todayISO = todayStart.toISOString();-- const weekEnd = new Date(todayStart);- weekEnd.setDate(weekEnd.getDate() + 7);- const weekEndISO = weekEnd.toISOString();-- const dateStr = todayStart.toISOString().slice(0, 10);-- const [allAgents, allAccess] = await Promise.all([- queries.agent.getAllAgentsForWorkspace(db, ws.workspaceId),- cached(cacheKeys.allAgentAccess(ws.workspaceId), 300, () => queries.agentAccess.getAllAgentAccessForWorkspace(db, ws.workspaceId)),- ]);- const visibleAgents = filterVisibleAgents(allAgents, ctx.userId, allAccess);- const visibleAgentIds = visibleAgents.map((a) => a.id);-- const [- emailStats,- emailAccounts,- taskStats,- recentTasks,- conversationCounts,- members,- invites,- calendarEvents,- ] = await Promise.all([- cached(cacheKeys.overviewEmailStats(ws.workspaceId), 60, () => queries.overview.getEmailStatsByWorkspace(db, ws.workspaceId)),- cached(cacheKeys.overviewEmailAccounts(ws.workspaceId), 300, () => queries.overview.getEmailAccountsByWorkspace(db, ws.workspaceId)),- cached(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr), 60, () => queries.overview.getTaskStatsByWorkspace(db, ws.workspaceId, todayISO)),- queries.overview.getRecentTerminalTasks(db, ws.workspaceId, visibleAgentIds, 15),- queries.overview.getConversationCountsByAgent(db, ws.workspaceId, visibleAgentIds),- cached(cacheKeys.allMembers(ws.workspaceId), 600, () => queries.member.listMembers(db, ws.workspaceId)),- queries.workspaceInvite.listActiveInvites(db, ws.workspaceId),- queries.calendarEvent.listCalendarEvents(db, ws.workspaceId, {- userId: ctx.userId,- from: todayISO,- to: weekEndISO,- }),- ]);-- const conversationCountMap: Record<string, number> = {};- for (const row of conversationCounts) {- conversationCountMap[row.agentId] = Number(row.cnt);- }-- return writeJSON({- email_stats: emailStats,- email_accounts: emailAccounts.map((a) => ({- id: a.id,- agent_id: a.agentId,- email_address: a.emailAddress,- status: a.status,- error_message: a.errorMessage,- last_synced_at: a.lastSyncedAt,- })),- task_stats: taskStats,- recent_tasks: recentTasks.map((t) => ({- id: t.id,- agent_id: t.agentId,- type: t.type,- status: t.status,- prompt: t.prompt,- created_at: t.createdAt,- completed_at: t.completedAt,- error: t.error,- })),- conversation_counts: conversationCountMap,- members: members.map((m) => ({- id: m.id,- user_id: m.userId,- role: m.role,- name: m.userName,- email: m.userEmail,- image: m.userImage,- created_at: m.createdAt,- })),- pending_invites: invites.length,- calendar_events: calendarEvents.map((e) => ({- id: e.id,- agent_id: e.agentId,- title: e.title,- description: e.description,- scheduled_at: e.scheduledAt,- repeat_interval: e.repeatInterval,- repeat_stop_at: e.repeatStopAt,- last_triggered_at: e.lastTriggeredAt,- })),- });-});diff --git a/src/web/src/app/api/workspaces/[id]/route.test.ts b/src/web/src/app/api/workspaces/[id]/route.test.tsdeleted file mode 100644index 512e47967..000000000--- a/src/web/src/app/api/workspaces/[id]/route.test.ts+++ /dev/null@@ -1,277 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--let mockAuthCtx: Record<string, unknown> = { userId: "u1", email: "[email protected]" };--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn((opts?: { async?: boolean }) => {- const result = { env: { DB: {} } };- return opts?.async ? Promise.resolve(result) : result;- }),-}));--const mockGetWorkspace = vi.fn();-const mockUpdateWorkspace = vi.fn();-const mockDeleteWorkspace = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- workspace: {- getWorkspace: (...args: unknown[]) => mockGetWorkspace(...args),- updateWorkspace: (...args: unknown[]) => mockUpdateWorkspace(...args),- deleteWorkspace: (...args: unknown[]) => mockDeleteWorkspace(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: { DB: {} }, ...mockAuthCtx, params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () =>- await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers")-);--vi.mock("@/lib/middleware/workspace", () => ({- withWorkspaceOwner: vi.fn(async () => ({ workspaceId: "w1", memberRole: "owner" })),-}));--vi.mock("@/lib/api/responses", async () =>- await vi.importActual<typeof import("@/lib/api/responses")>("@/lib/api/responses")-);--import { GET, PATCH, DELETE } from "./route";--describe("GET /api/workspaces/[id]", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]" };- });-- it("returns workspace for a member", async () => {- mockGetWorkspace.mockResolvedValue({- id: "w1",- name: "Acme",- slug: "acme",- createdAt: "2024-01-01T00:00:00Z",- updatedAt: "2024-01-01T00:00:00Z",- });-- const req = new NextRequest("http://localhost/api/workspaces/w1");- const res = await GET(req, { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.id).toBe("w1");- expect(body.name).toBe("Acme");- expect(body.slug).toBe("acme");- expect(mockGetWorkspace).toHaveBeenCalledWith({}, "w1", "u1");- });-- it("returns 404 when workspace does not exist", async () => {- mockGetWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w999");- const res = await GET(req, { params: Promise.resolve({ id: "w999" }) } as any);-- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "workspace not found" });- });-- it("returns 404 when user is not a member of the workspace", async () => {- mockGetWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w-other");- const res = await GET(req, { params: Promise.resolve({ id: "w-other" }) } as any);-- expect(res.status).toBe(404);- expect(await res.json()).toEqual({ error: "workspace not found" });- expect(mockGetWorkspace).toHaveBeenCalledWith({}, "w-other", "u1");- });-- it("passes userId to query so membership is enforced in SQL", async () => {- mockAuthCtx = { userId: "u2", email: "[email protected]" };- mockGetWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w1");- const res = await GET(req, { params: Promise.resolve({ id: "w1" }) } as any);-- expect(res.status).toBe(404);- expect(mockGetWorkspace).toHaveBeenCalledWith({}, "w1", "u2");- });-});--describe("PATCH /api/workspaces/[id]", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]" };- });-- it("updates workspace name successfully", async () => {- mockUpdateWorkspace.mockResolvedValue({- id: "w1",- name: "New Name",- slug: "my-workspace",- createdAt: "2024-01-01T00:00:00Z",- updatedAt: "2024-01-02T00:00:00Z",- });-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({ name: "New Name" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.name).toBe("New Name");- expect(mockUpdateWorkspace).toHaveBeenCalledWith({}, "w1", { name: "New Name" });- });-- it("returns 404 when workspace not found on update", async () => {- mockUpdateWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({ name: "New Name" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(404);- });-- it("returns 400 when neither name nor slug is provided", async () => {- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(400);- });-- it("sanitizes a dirty slug before updating", async () => {- mockUpdateWorkspace.mockResolvedValue({- id: "w1",- name: "Acme",- slug: "new-name",- createdAt: "2024-01-01T00:00:00Z",- updatedAt: "2024-01-02T00:00:00Z",- });-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({ slug: "New Name" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);-- expect(res.status).toBe(200);- expect(mockUpdateWorkspace).toHaveBeenCalledWith({}, "w1", { slug: "new-name" });- });-- it("rejects a slug that sanitizes to empty with 400 slug is required", async () => {- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({ slug: "🎉" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);-- expect(res.status).toBe(400);- expect(await res.json()).toEqual({ error: "slug is required" });- expect(mockUpdateWorkspace).not.toHaveBeenCalled();- });-- it("returns 409 when slug is already in use", async () => {- const uniqueErr = Object.assign(new Error("UNIQUE constraint failed"), {});- mockUpdateWorkspace.mockRejectedValue(uniqueErr);-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "PATCH",- body: JSON.stringify({ slug: "taken-slug" }),- headers: { "Content-Type": "application/json" },- });- const res = await PATCH(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(409);- });-});--describe("DELETE /api/workspaces/[id]", () => {- beforeEach(() => {- vi.clearAllMocks();- mockAuthCtx = { userId: "u1", email: "[email protected]" };- });-- it("deletes workspace when confirm_name matches", async () => {- mockGetWorkspace.mockResolvedValue({- id: "w1",- name: "My Workspace",- slug: "my-workspace",- createdAt: "2024-01-01T00:00:00Z",- updatedAt: "2024-01-01T00:00:00Z",- });- mockDeleteWorkspace.mockResolvedValue(undefined);-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "DELETE",- body: JSON.stringify({ confirm_name: "My Workspace" }),- headers: { "Content-Type": "application/json" },- });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(204);- expect(mockDeleteWorkspace).toHaveBeenCalledWith({}, "w1");- });-- it("returns 400 when confirm_name does not match", async () => {- mockGetWorkspace.mockResolvedValue({- id: "w1",- name: "My Workspace",- slug: "my-workspace",- createdAt: "2024-01-01T00:00:00Z",- updatedAt: "2024-01-01T00:00:00Z",- });-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "DELETE",- body: JSON.stringify({ confirm_name: "Wrong Name" }),- headers: { "Content-Type": "application/json" },- });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("workspace name does not match");- });-- it("returns 404 when workspace not found", async () => {- mockGetWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "DELETE",- body: JSON.stringify({ confirm_name: "My Workspace" }),- headers: { "Content-Type": "application/json" },- });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(404);- });-- it("returns 400 when confirm_name is missing", async () => {- const req = new NextRequest("http://localhost/api/workspaces/w1", {- method: "DELETE",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- });- const res = await DELETE(req, { params: Promise.resolve({ id: "w1" }) } as any);- expect(res.status).toBe(400);- });-});diff --git a/src/web/src/app/api/workspaces/[id]/route.ts b/src/web/src/app/api/workspaces/[id]/route.tsdeleted file mode 100644index 52d893f26..000000000--- a/src/web/src/app/api/workspaces/[id]/route.ts+++ /dev/null@@ -1,62 +0,0 @@-import { NextRequest } from "next/server";-import { queries, UpdateWorkspaceRequestSchema, DeleteWorkspaceRequestSchema, isUniqueConstraintError } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { withWorkspaceOwner } from "@/lib/middleware/workspace";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { workspaceToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)-- const id = ctx.params?.id;- if (!id) {- return writeError("workspace id is required", 400);- }-- const workspace = await queries.workspace.getWorkspace(db, id, ctx.userId);- if (!workspace) {- return writeError("workspace not found", 404);- }-- return writeJSON(workspaceToResponse(workspace));-});--export const PATCH = withAuth(async (req: NextRequest, ctx) => {- const owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const [body, err] = await parseBody(req, UpdateWorkspaceRequestSchema);- if (err) return err;-- if (body.slug !== undefined && body.slug === "") return writeError("slug is required", 400);- if (!body.name && !body.slug) return writeError("at least one of name or slug is required", 400);-- const db = getDb(ctx.env.DB);-- try {- const updated = await queries.workspace.updateWorkspace(db, owner.workspaceId, body);- if (!updated) return writeError("workspace not found", 404);- return writeJSON(workspaceToResponse(updated));- } catch (err: unknown) {- if (isUniqueConstraintError(err)) return writeError("slug already in use", 409);- throw err;- }-});--export const DELETE = withAuth(async (req: NextRequest, ctx) => {- const owner = await withWorkspaceOwner(req, ctx);- if (owner instanceof Response) return owner;-- const [body, err] = await parseBody(req, DeleteWorkspaceRequestSchema);- if (err) return err;-- const db = getDb(ctx.env.DB);-- const ws = await queries.workspace.getWorkspace(db, owner.workspaceId, ctx.userId);- if (!ws) return writeError("workspace not found", 404);- if (ws.name !== body.confirm_name) return writeError("workspace name does not match", 400);-- await queries.workspace.deleteWorkspace(db, owner.workspaceId);- return new Response(null, { status: 204 });-});diff --git a/src/web/src/app/api/workspaces/route.test.ts b/src/web/src/app/api/workspaces/route.test.tsdeleted file mode 100644index 8bdaa9a39..000000000--- a/src/web/src/app/api/workspaces/route.test.ts+++ /dev/null@@ -1,258 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),-}));--const mockListWorkspaces = vi.fn();-const mockCreateWorkspace = vi.fn();-const mockCreateMember = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual("@alook/shared");- return {- ...actual,- createDb: vi.fn(() => ({})),- queries: {- workspace: {- listWorkspaces: (...args: unknown[]) => mockListWorkspaces(...args),- createWorkspace: (...args: unknown[]) => mockCreateWorkspace(...args),- },- member: {- createMember: (...args: unknown[]) => mockCreateMember(...args),- },- },- };-});--vi.mock("@/lib/middleware/auth", () => ({- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {- const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params });- }),-}));--vi.mock("@/lib/middleware/helpers", async () => {- const { NextResponse } = require("next/server");- const actual = await vi.importActual("@/lib/middleware/helpers");- return {- ...actual,- writeJSON: (data: unknown, status = 200) => NextResponse.json(data, { status }),- writeError: (message: string, status: number) => NextResponse.json({ error: message }, { status }),- };-});--vi.mock("@/lib/api/responses", () => ({- workspaceToResponse: vi.fn((w: any) => ({ id: w.id, name: w.name, slug: w.slug })),-}));--import { GET, POST } from "./route";--describe("GET /api/workspaces", () => {- beforeEach(() => vi.clearAllMocks());-- it("lists user workspaces", async () => {- mockListWorkspaces.mockResolvedValue([- { id: "w1", name: "Acme", slug: "acme" },- { id: "w2", name: "Beta", slug: "beta" },- ]);-- const req = new NextRequest("http://localhost/api/workspaces");- const res = await GET(req, {} as any);-- expect(res.status).toBe(200);- expect(await res.json()).toEqual([- { id: "w1", name: "Acme", slug: "acme" },- { id: "w2", name: "Beta", slug: "beta" },- ]);- expect(mockListWorkspaces).toHaveBeenCalledWith({}, "u1");- });-});--describe("POST /api/workspaces", () => {- beforeEach(() => vi.clearAllMocks());-- it("creates workspace with member and returns 201", async () => {- mockCreateWorkspace.mockResolvedValue({ id: "w-new", name: "New", slug: "new" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "New", slug: "new" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(await res.json()).toEqual({ id: "w-new", name: "New", slug: "new" });- expect(mockCreateWorkspace).toHaveBeenCalledWith({}, { name: "New", slug: "new" });- expect(mockCreateMember).toHaveBeenCalledWith({}, {- workspaceId: "w-new",- userId: "u1",- role: "owner",- });- });-- it("sanitizes a dirty slug before creating", async () => {- mockCreateWorkspace.mockResolvedValue({ id: "w-clean", name: "My Company", slug: "my-company" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "My Company", slug: "My Company" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockCreateWorkspace.mock.calls[0][1].slug).toBe("my-company");- });-- it("falls back to a generated slug when the slug sanitizes to empty", async () => {- mockCreateWorkspace.mockResolvedValue({ id: "w-gen", name: "Party", slug: "company-abcd1234" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Party", slug: "🎉" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockCreateWorkspace.mock.calls[0][1].slug).toMatch(/^company-[a-z0-9]{8}$/);- });-- it("returns 400 for missing name", async () => {- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ slug: "test" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("name"));- });-- it("auto-generates slug when not provided", async () => {- mockCreateWorkspace.mockResolvedValue({ id: "sp_1", name: "Test", slug: "auto-slug", onboarded: 0, createdAt: "2025-01-01T00:00:00Z", updatedAt: "2025-01-01T00:00:00Z" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Test" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- });-- it("retries with suffixed slug on duplicate and returns 201", async () => {- const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");- mockCreateWorkspace- .mockRejectedValueOnce(uniqueError)- .mockResolvedValueOnce({ id: "w-retry", name: "Dup", slug: "dup-abcd" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Dup", slug: "dup" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockCreateWorkspace).toHaveBeenCalledTimes(2);- // First call uses original slug- expect(mockCreateWorkspace.mock.calls[0][1].slug).toBe("dup");- // Second call uses a lowercase-alnum suffixed slug- expect(mockCreateWorkspace.mock.calls[1][1].slug).toMatch(/^dup-[a-z0-9]+$/);- });-- it("returns 409 after all slug retries exhausted", async () => {- const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");- // 1 initial + 9 retries = 10 rejections- mockCreateWorkspace.mockRejectedValue(uniqueError);-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Dup", slug: "dup" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(409);- expect(await res.json()).toEqual({ error: "workspace slug already exists" });- // 1 initial + 9 retries- expect(mockCreateWorkspace).toHaveBeenCalledTimes(10);- });-- it("retries with escalating suffix lengths", async () => {- const uniqueError = new Error("UNIQUE constraint failed: workspaces.slug");- // Fail 7 times (1 original + 3 nanoid(4) + 3 nanoid(8)), succeed on 8th- const rejections = Array.from({ length: 7 }, () => uniqueError);- mockCreateWorkspace- .mockRejectedValueOnce(rejections[0])- .mockRejectedValueOnce(rejections[1])- .mockRejectedValueOnce(rejections[2])- .mockRejectedValueOnce(rejections[3])- .mockRejectedValueOnce(rejections[4])- .mockRejectedValueOnce(rejections[5])- .mockRejectedValueOnce(rejections[6])- .mockResolvedValueOnce({ id: "w-long", name: "Dup", slug: "dup-longsuffix123456" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Dup", slug: "dup" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockCreateWorkspace).toHaveBeenCalledTimes(8);- // Verify suffix length escalation- const slugs = mockCreateWorkspace.mock.calls.map((c: any) => c[1].slug as string);- expect(slugs[0]).toBe("dup"); // original- // nanoid(4) attempts: suffix part should be 4 chars- for (let i = 1; i <= 3; i++) {- const suffix = slugs[i].replace("dup-", "");- expect(suffix).toHaveLength(4);- }- // nanoid(8) attempts: suffix part should be 8 chars- for (let i = 4; i <= 6; i++) {- const suffix = slugs[i].replace("dup-", "");- expect(suffix).toHaveLength(8);- }- // 8th call succeeds with nanoid(16) suffix- const lastSuffix = slugs[7].replace("dup-", "");- expect(lastSuffix).toHaveLength(16);- });-- it("retries on duplicate slug wrapped with cause", async () => {- const cause = new Error("UNIQUE constraint failed: workspaces.slug");- const wrapped = new Error("Failed query: INSERT INTO ...");- (wrapped as any).cause = cause;- mockCreateWorkspace- .mockRejectedValueOnce(wrapped)- .mockResolvedValueOnce({ id: "w-retry2", name: "Dup", slug: "dup-xyz" });- mockCreateMember.mockResolvedValue({});-- const req = new NextRequest("http://localhost/api/workspaces", {- method: "POST",- body: JSON.stringify({ name: "Dup", slug: "dup" }),- headers: { "Content-Type": "application/json" },- });- const res = await POST(req, {} as any);-- expect(res.status).toBe(201);- expect(mockCreateWorkspace).toHaveBeenCalledTimes(2);- });-});diff --git a/src/web/src/app/api/workspaces/route.ts b/src/web/src/app/api/workspaces/route.tsdeleted file mode 100644index f37abe823..000000000--- a/src/web/src/app/api/workspaces/route.ts+++ /dev/null@@ -1,44 +0,0 @@-import { NextRequest } from "next/server";-import { queries, isUniqueConstraintError, generateWorkspaceSlug, slugSuffix, CreateWorkspaceRequestSchema } from "@alook/shared"-import { getDb } from "@/lib/db"-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";-import { workspaceToResponse } from "@/lib/api/responses";--export const GET = withAuth(async (_req, ctx) => {- const db = getDb(ctx.env.DB)-- const workspaces = await queries.workspace.listWorkspaces(db, ctx.userId);- return writeJSON(workspaces.map(workspaceToResponse));-});--export const POST = withAuth(async (req: NextRequest, ctx) => {- const db = getDb(ctx.env.DB)-- const [body, valErr] = await parseBody(req, CreateWorkspaceRequestSchema);- if (valErr) return valErr;-- const name = body.name.trim();- const slug = body.slug || generateWorkspaceSlug();-- const suffixLengths = [4, 4, 4, 8, 8, 8, 16, 16, 16];- let candidateSlug = slug;-- for (let attempt = 0; ; attempt++) {- try {- const ws = await queries.workspace.createWorkspace(db, { name, slug: candidateSlug });- await queries.member.createMember(db, {- workspaceId: ws.id,- userId: ctx.userId,- role: "owner",- });- return writeJSON(workspaceToResponse(ws), 201);- } catch (err: unknown) {- if (!isUniqueConstraintError(err)) throw err;- if (attempt >= suffixLengths.length) {- return writeError("workspace slug already exists", 409);- }- candidateSlug = `${slug}-${slugSuffix(suffixLengths[attempt])}`;- }- }-});diff --git a/src/web/src/components/community/channels/forum-channel-surface.tsx b/src/web/src/components/community/channels/forum-channel-surface.tsxindex 2177ec5dc..515d287fd 100644--- a/src/web/src/components/community/channels/forum-channel-surface.tsx+++ b/src/web/src/components/community/channels/forum-channel-surface.tsx@@ -159,10 +159,8 @@ export function ForumChannelSurface({openonOpenChange={(open) => { if (!open) setPanelState({ channelId, panel: null }) }}kind={rightPanel}- viewerUserId={viewer.id}{...memberPanelProps}pinned={[]}- searchResults={[]}threads={[]}onOpenThread={onOpenPost}onOpenProfile={onOpenProfile}diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 556236452..afd6d577b 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -199,20 +199,14 @@ export function TextChannelSurface({openonOpenChange={(open) => { if (!open) setRightPanel(null) }}kind={rightPanel}- viewerUserId={viewer.id}{...memberPanelProps}pinned={feed.pinned}pinnedLoading={feed.pinnedLoading}- searchResults={controller.searchResults}- searchError={controller.searchError}- searchLoading={controller.searchLoading}- searchQuery={controller.searchQuery}threads={feed.threads}threadsLoading={feed.threadsLoading}onOpenThread={onOpenThread}onOpenProfile={onOpenProfile}onJumpToMessage={controller.jumpToSeq}- onSearch={controller.search}/>)}dialogs={(diff --git a/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.tsindex f90a3e65d..44e9c54ab 100644--- a/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts+++ b/src/web/src/components/community/channels/text-channel-surface.wiring.dom.test.ts@@ -65,9 +65,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({pinnedIds: new Set(),replyTo: mocks.replyTarget,setReplyTo: vi.fn(),- searchQuery: "",- searchResults: [],- search: vi.fn(),scrollTargetId: null,setScrollTargetId: vi.fn(),consumeScrollTarget: vi.fn(),diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.tsindex 8e2813431..4c4460411 100644--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts@@ -23,7 +23,6 @@ const mocks = vi.hoisted(() => ({handleTyping: vi.fn(),setReplyTo: vi.fn(),jumpToSeq: vi.fn(),- search: vi.fn(),setContextTarget: vi.fn(),}))@@ -94,9 +93,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({pinnedIds: new Set(["pinned_1"]),replyTo: { id: "reply_1", authorName: "Alice", text: "hello" },setReplyTo: mocks.setReplyTo,- searchQuery: "query",- searchResults: [{ id: "search_1", type: "chat" }],- search: mocks.search,scrollTargetId: "m_target",setScrollTargetId: vi.fn(),consumeScrollTarget: vi.fn(),@@ -465,10 +461,8 @@ describe("ThreadChannelSurface ownership", () => {expect(panelProps).toEqual(expect.objectContaining({kind: "pinned",pinned: expect.arrayContaining([expect.objectContaining({ id: "pinned_1" })]),- searchQuery: "query",onOpenThread: props.onOpenChild,onJumpToMessage: mocks.jumpToSeq,- onSearch: mocks.search,}))const contextProps = mockedMessageContextSheet.mock.calls.at(-1)![0]expect(contextProps).toEqual(expect.objectContaining({diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex d2e0d699b..45ee7dd18 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -311,19 +311,13 @@ export function ThreadChannelSurface({openonOpenChange={(open) => { if (!open) setRightPanel(null) }}kind={rightPanel}- viewerUserId={viewer.id}{...memberPanelProps}pinned={controller.feed.pinned}pinnedLoading={controller.feed.pinnedLoading}- searchResults={controller.searchResults}- searchError={controller.searchError}- searchLoading={controller.searchLoading}- searchQuery={controller.searchQuery}threads={controller.feed.threads}threadsLoading={controller.feed.threadsLoading}onOpenThread={onOpenChild}onJumpToMessage={controller.jumpToSeq}- onSearch={controller.search}onOpenProfile={onOpenProfile}/>)}diff --git a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsxindex fe6330765..3bbef8212 100644--- a/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx+++ b/src/web/src/components/community/messages/composer-suggestion-focus.dom.test.tsx@@ -50,7 +50,6 @@ vi.mock("@/components/community/messages/message-channel-controller", () => ({MessageChannelController: ({ children }: { children: (value: MessageChannelControllerValue) => ReactNode }) => children({feed: {} as MessageChannelControllerValue["feed"],pinnedIds: new Set(), replyTo: null, setReplyTo: vi.fn(),- searchQuery: "", searchResults: [], searchLoading: false, search: vi.fn(),scrollTargetId: null, setScrollTargetId: vi.fn(), consumeScrollTarget: vi.fn(),contextTarget: null, setContextTarget: vi.fn(), openContextSeq: vi.fn(),onSheetReply: vi.fn(), jumpToSeq: vi.fn(),diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.tsindex f083379a8..edf6f6a95 100644--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts@@ -9,7 +9,6 @@ import type { MessageChannelControllerValue as FacadeControllerValue } from "./mimport type {FileAttachment,ImagePreview,- Msg,SendAttachment,} from "@/lib/community/models/message"import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"@@ -40,9 +39,6 @@ type ExpectedControllerValue = {pinnedIds: Set<string>replyTo: ExpectedReplyTarget | nullsetReplyTo: (reply: ExpectedReplyTarget | null) => void- searchQuery: string- searchResults: Msg[]- search: (query: string) => voidscrollTargetId: string | nullsetScrollTargetId: (targetId: string | null) => voidconsumeScrollTarget: (targetId: string) => void@@ -125,7 +121,6 @@ describe("MessageChannelController facade contract", () => {"const router = useRouter()","const searchParams = useSearchParams()","const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))",- "const [searchQuery, setSearchQuery] = useAtom(useCreateAtom(\"\"))","const [scrollTargetId, setScrollTargetId] = useAtom(useCreateAtom<string | null>(anchorMessageId))","const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))","useSendMessage()",@@ -146,9 +141,7 @@ describe("MessageChannelController facade contract", () => {expect(position, token).toBeGreaterThan(cursor)cursor = position}- expect(body.match(/\buseCreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(5)- expect(body).toContain('queryKey: ["community", "message-search", channelId, term]')- expect(body).toContain("const searchMessages = useCanonicalMessagesById(searchIds)")+ expect(body.match(/\buseCreateAtom(?:<[^>]+>)?\(/g)).toHaveLength(4)expect(body).not.toMatch(/\buseState(?:<[^>]+>)?\(/)expect(actions).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)expect(send).not.toMatch(/\buse[A-Z][A-Za-z]+\(/)diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.tsindex 9844e7f8e..9af01e1a7 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts@@ -1,5 +1,5 @@import React from "react"-import { act, waitFor } from "@/test/react-dom-harness"+import { act } from "@/test/react-dom-harness"import { render as renderDom } from "@/test/react-dom-harness"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"@@ -8,7 +8,6 @@ let fixtureOwner: Awaited<ReturnType<typeof createCommunityQueryOwner>>const rtlRender: typeof renderDom = (node, options) => renderDom(node, { ...options, wrapper: ({ children }) => React.createElement(CommunityTestProvider, { client: fixtureOwner.client, registry: fixtureOwner.registry, userId: "viewer_1", retainOwner: true }, children) })import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { useMessageChannelController } from "./message-channel-controller-state"-import { avatarInitial } from "@/lib/community/avatar"import type {MessageChannelControllerProps,} from "./message-channel-controller-types"@@ -197,27 +196,16 @@ describe("useMessageChannelController", () => {expect(latest.handleTyping).toBe(firstTyping)expect(latest.feed).toBe(valueProps.feed)- await act(async () => { await (latest.search as (query: string) => Promise<void>)("hello") })- expect(latest).not.toBe(firstValue)- expect(latest.messageActions).toBe(firstActions)- expect(latest.threadActions).not.toBe(firstThreadActions)- expect(latest.handleTyping).not.toBe(firstTyping)- act(() => latest.handleTyping())- expect(mocks.sendTyping).toHaveBeenCalledWith(fixtureOwner.registry.runtime, { channelId: "channel_1" })-- const afterSearch = latest- const afterSearchThreadActions = latest.threadActions- const afterSearchTyping = latest.handleTypingconst updatedFeed = { ...feed, messages: [...feed.messages] }act(() => {renderer!.rerender(React.createElement(Probe, {value: { ...valueProps, feed: updatedFeed },}))})- expect(latest).not.toBe(afterSearch)+ expect(latest).not.toBe(firstValue)expect(latest.messageActions).toBe(firstActions)- expect(latest.threadActions).not.toBe(afterSearchThreadActions)- expect(latest.handleTyping).not.toBe(afterSearchTyping)+ expect(latest.threadActions).not.toBe(firstThreadActions)+ expect(latest.handleTyping).not.toBe(firstTyping)expect(latest.feed).toBe(updatedFeed)const afterFeed = latest@@ -231,45 +219,17 @@ describe("useMessageChannelController", () => {expect(latest.messageActions).toBe(firstActions)})- it("keeps scroll target and rejects a captured channel-one search after channel reset", async () => {- let resolveOld: (value: unknown) => void = () => {}- mocks.apiFetch.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))+ it("keeps the scroll target while clearing reply and context after channel reset", () => {let renderer: ReturnType<typeof rtlRender>act(() => { renderer = rtlRender(React.createElement(Probe, { value: props() })) })- let oldPromise: Promise<void>- act(() => { oldPromise = (latest.search as (query: string) => Promise<void>)("old") })- await waitFor(() => expect(mocks.apiFetch).toHaveBeenCalledWith(- "/api/community/messages/search?q=old&channelId=channel_1",- expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1", assertActive: expect.any(Function) }),- ))act(() => latest.setReplyTo({ id: "r1", authorName: "A", text: "x" }))- act(() => latest.setContextTarget({- serverId: "server_1", channelId: "channel_1", label: "general", seq: 42,- }))- expect(latest.searchQuery).toBe("old")+ act(() => latest.setContextTarget({ serverId: "server_1", channelId: "channel_1", label: "general", seq: 42 }))expect(latest.contextTarget?.seq).toBe(42)- act(() => {- renderer!.rerender(React.createElement(Probe, {- value: props({ channelId: "channel_2", channelName: "random" }),- }))- })+ act(() => { renderer!.rerender(React.createElement(Probe, { value: props({ channelId: "channel_2", channelName: "random" }) })) })expect(latest.replyTo).toBeNull()- expect(latest.searchQuery).toBe("")- expect(latest.searchResults).toEqual([])expect(latest.contextTarget).toBeNull()expect(latest.scrollTargetId).toBe("m1")-- await act(async () => {- resolveOld({ results: [{- message: { id: "old_1", content: "old", authorId: "u1", createdAt: "2026-01-01" },- author: { id: "u1", name: "Alice", image: null, avatarVersion: 0 },- }] })- await oldPromise!- })- expect(latest.searchQuery).toBe("")- expect(latest.searchResults).toEqual([])- await act(async () => { await (latest.search as (query: string) => Promise<void>)("") })- expect(latest.searchResults).toEqual([])+ expect(mocks.apiFetch).not.toHaveBeenCalled()})it("forwards complete accept input, run-helper wiring, and helper-owned reply clearing", async () => {@@ -467,57 +427,6 @@ describe("useMessageChannelController", () => {expect(latest.scrollTargetId).toBeNull()})- it("maps canonical search avatars and exposes the current scoped query failure", async () => {- const failure = new Error("search down")- mocks.apiFetch- .mockResolvedValueOnce({- results: [- {- message: { id: "m2", content: "found", authorId: "u2", createdAt: "2026-01-02" },- author: { id: "u2", name: "Bob", image: null, avatarVersion: 0 },- },- {- message: { id: "m3", content: "image", authorId: "u3", createdAt: "2026-01-03" },- author: { id: "u3", name: "Carol", image: "https://example.test/carol.png", avatarVersion: 3 },- },- ],- })- .mockRejectedValueOnce(failure)- act(() => { rtlRender(React.createElement(Probe, { value: props() })) })- await act(async () => { await (latest.search as (query: string) => Promise<void>)("found") })- await waitFor(() => expect(latest.searchResults).toHaveLength(2))- expect(mocks.apiFetch).toHaveBeenCalledWith(- "/api/community/messages/search?q=found&channelId=channel_1",- expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1", assertActive: expect.any(Function) }),- )- expect(latest.searchResults).toEqual([- expect.objectContaining({- id: "m2",- type: "chat",- authorId: "u2",- authorName: "Bob",- authorAvatar: avatarInitial("Bob"),- authorAvatarVersion: 0,- content: "found",- createdAt: "2026-01-02",- }),- expect.objectContaining({- id: "m3",- type: "chat",- authorId: "u3",- authorName: "Carol",- authorAvatar: "https://example.test/carol.png",- authorAvatarVersion: 3,- content: "image",- createdAt: "2026-01-03",- }),- ])- await act(async () => { await (latest.search as (query: string) => Promise<void>)("broken") })- expect(latest.searchResults).toEqual([])- await waitFor(() => expect(latest.searchError).toBe("Search failed. Try again."))- expect(mocks.toastApiError).not.toHaveBeenCalled()- })-it("handles same-channel and pending replies plus loaded/fallback seq jumps", () => {const pendingTarget = { id: "pending", authorId: "pending-author", authorName: "Pending", text: "reply" }mocks.storeState.pendingReply = { channelId: "channel_1", target: pendingTarget }@@ -625,8 +534,7 @@ describe("useMessageChannelController", () => {expect(latest.feed).toBe(projectedFeed)expect(resolveUserName).toHaveBeenCalledWith("u2")expect(Object.keys(latest)).toEqual([- "feed", "pinnedIds", "replyTo", "setReplyTo", "searchQuery", "searchResults", "searchError", "searchLoading",- "search", "scrollTargetId", "setScrollTargetId", "consumeScrollTarget",+ "feed", "pinnedIds", "replyTo", "setReplyTo", "scrollTargetId", "setScrollTargetId", "consumeScrollTarget","contextTarget", "setContextTarget", "openContextSeq", "onSheetReply", "jumpToSeq","messageActions", "threadActions", "acceptMessage", "localSubmitVersion", "handleTyping", "typingUsers",])diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.tsindex 4c696967a..2a69ac8ba 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -1,12 +1,10 @@"use client"import { createStore, useAtom, useCreateAtom } from "@tanstack/react-store";import { getCommunityDbRegistry } from "@/lib/community-db/collections"-import { useQuery, useQueryClient } from "@tanstack/react-query"+import { useQueryClient } from "@tanstack/react-query"-import { useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"import { readCommunityProfile } from "@/lib/community/profile-read"-import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages } from "@/lib/community-db/sync"-import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"import { useCommunityRuntime } from "@/stores/community/runtime"@@ -16,9 +14,8 @@ import { presentCanonicalMessage } from "@/lib/community/message-wire"import { messageScopeKey } from "@/stores/community/message-stream-store"import { useCommunityViewSource } from "@/hooks/community/use-community-view-source"import { usePathname, useRouter, useSearchParams } from "next/navigation"-import type { MentionType, CommunityMessageResource, CommunityResourceProfile } from "@alook/shared"+import type { MentionType } from "@alook/shared"-import { apiFetchProfiles } from "@/lib/community/profile-seed"import type { Msg } from "@/lib/community/models/message"import type { SendAttachment } from "./composer"import {@@ -76,7 +73,6 @@ export function useMessageChannelController({const searchParams = useSearchParams()const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))- const [searchQuery, setSearchQuery] = useAtom(useCreateAtom(""))const [scrollTargetId, setScrollTargetId] = useAtom(useCreateAtom<string | null>(anchorMessageId))const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))const { mutateAsync: sendMessageAsync } = useSendMessage()@@ -108,59 +104,8 @@ export function useMessageChannelController({useEffect(() => {setReplyTo(null)- setSearchQuery("")setContextTarget(null)- }, [channelId, setContextTarget, setReplyTo, setSearchQuery])-- const term = searchQuery.trim()- const searchResource = useQuery({- queryKey: ["community", "message-search", channelId, term],- enabled: term.length > 0, subscribed: term.length > 0, gcTime: 5 * 60 * 1000, retry: false,- queryFn: async ({ signal }) => {- const token = captureCommunityLiveSnapshotToken(profileQueryClient)- const params = new URLSearchParams({ q: term, channelId })- const data = await apiFetchProfiles<{- results: Array<{- message: Pick<CommunityMessageResource, "id" | "content" | "authorId" | "createdAt"> & Partial<Pick<CommunityMessageResource, "seq">>- author: Pick<CommunityResourceProfile, "id" | "name" | "avatarVersion"> & { image: CommunityResourceProfile["avatar"] }- }>- }>(- "/api/community/messages/search?" + params,- (response) => response.results.map((result) => ({- id: result.author.id, identityAbout: { name: result.author.name },- avatar: { avatar: result.author.image, avatarVersion: result.author.avatarVersion },- })),- communityRequestOptions(profileQueryClient, token, signal), token.registry,- )- publishCommunityMessages(profileQueryClient, {- channelId,- messages: data.results.map((result) => ({- id: result.message.id, type: "chat", content: result.message.content,- createdAt: result.message.createdAt, authorId: result.author.id,- ...(result.message.seq !== undefined ? { seq: result.message.seq } : {}),- })),- proof: { token, signal },- })- return data.results.map((result) => result.message.id)- },- })- const searchIds = useMemo(() => term ? searchResource.data ?? [] : [], [term, searchResource.data])- const searchMessages = useCanonicalMessagesById(searchIds)- const searchProfiles = useCanonicalProfilesByUserId(searchIds.flatMap((id) => {- const authorId = searchMessages?.get(id)?.authorId- return authorId ? [authorId] : []- }))- const searchResults = useMemo(() => searchIds.flatMap((id) => {- const message = searchMessages?.get(id)- if (!message) return []- const profile = message.authorId ? readCommunityProfile(searchProfiles.get(message.authorId), message.authorId) : null- return [{ ...message, ...(profile ? { authorName: profile.name, authorAvatar: profile.avatar, authorAvatarVersion: profile.avatarVersion } : {}) }]- }), [searchIds, searchMessages, searchProfiles])- const { refetch: refetchSearch } = searchResource- const search = useCallback(async (query: string) => {- if (query.trim() === term && term) await refetchSearch({ cancelRefetch: false })- else setSearchQuery(query)- }, [term, refetchSearch, setSearchQuery])+ }, [channelId, setContextTarget, setReplyTo])const openContextSeq = useCallback((seq: number) => {setContextTarget((current) => (@@ -318,11 +263,6 @@ export function useMessageChannelController({pinnedIds,replyTo,setReplyTo,- searchQuery,- searchResults,- searchError: searchResource.isError ? "Search failed. Try again." : undefined,- searchLoading: searchResource.isFetching,- search,scrollTargetId,setScrollTargetId,consumeScrollTarget,@@ -337,5 +277,5 @@ export function useMessageChannelController({localSubmitVersion,handleTyping: () => communityWsSendTyping(communityRuntime, { channelId }),typingUsers: typingUserIds.map((id) => typingNames[id] ?? resolveUserName(id)),- }), [feed, pinnedIds, replyTo, setReplyTo, searchQuery, searchResults, searchResource.isError, searchResource.isFetching, search, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])+ }), [feed, pinnedIds, replyTo, setReplyTo, scrollTargetId, setScrollTargetId, consumeScrollTarget, contextTarget, setContextTarget, openContextSeq, onSheetReply, jumpToSeq, messageActions, acceptMessage, localSubmitVersion, typingUserIds, communityRuntime, channelId, typingNames, resolveUserName])}diff --git a/src/web/src/components/community/messages/message-channel-controller-types.ts b/src/web/src/components/community/messages/message-channel-controller-types.tsindex 08c5f20c5..01c281aa1 100644--- a/src/web/src/components/community/messages/message-channel-controller-types.ts+++ b/src/web/src/components/community/messages/message-channel-controller-types.ts@@ -1,7 +1,7 @@import type { CommunityUserCore } from "@/lib/community/models/people"import type { ReactNode } from "react"import type { MentionType, CommunityResourceProfile } from "@alook/shared"-import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"+import type { FileAttachment, ImagePreview } from "@/lib/community/models/message"import type { SendAttachment } from "./composer"import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"import type { ReplyTarget } from "@/lib/community/models/message"@@ -44,11 +44,6 @@ export type MessageChannelControllerValue = {pinnedIds: Set<string>replyTo: ReplyTarget | nullsetReplyTo: (reply: ReplyTarget | null) => void- searchQuery: string- searchResults: Msg[]- searchError?: string- searchLoading: boolean- search: (query: string) => voidscrollTargetId: string | nullsetScrollTargetId: (targetId: string | null) => voidconsumeScrollTarget: (targetId: string) => voiddiff --git a/src/web/src/components/community/shell/community-panel.dom.test.tsx b/src/web/src/components/community/shell/community-panel.dom.test.tsxindex f2eec03f2..e68edd874 100644--- a/src/web/src/components/community/shell/community-panel.dom.test.tsx+++ b/src/web/src/components/community/shell/community-panel.dom.test.tsx@@ -29,7 +29,6 @@ describe("CommunityPanel pinned author line", () => {authorId: "user_1", authorName: "Stale author",content: "Pinned body", createdAt,}]}- searchResults={[]}threads={[]}onOpenThread={vi.fn()}onJumpToMessage={onJumpToMessage}diff --git a/src/web/src/components/community/shell/community-panel.tsx b/src/web/src/components/community/shell/community-panel.tsxindex 4383c67b7..ef10b5797 100644--- a/src/web/src/components/community/shell/community-panel.tsx+++ b/src/web/src/components/community/shell/community-panel.tsx@@ -1,23 +1,18 @@"use client"-import { useAtom, useCreateAtom } from "@tanstack/react-store";--import { MessagesSquare, Pin, Search, Users } from "lucide-react"+import { MessagesSquare, Pin, Users } from "lucide-react"import { stripInlineMarkup, type CommunityRole as Role } from "@alook/shared"import { Avatar } from "@/components/community/avatar"import { MemberList } from "@/components/community/members/member-list"-import { Message } from "@/components/community/messages/message"import { MessageAuthorLine } from "@/components/community/messages/message-author-line"import { CommunitySheet } from "@/components/community/shell/community-sheet"-import { Input } from "@/components/ui/input"import { Skeleton } from "@/components/ui/skeleton"import { formatRelativeTime } from "@/lib/community/format-time"-import { onEnterSubmit } from "@/lib/ime"import type { MemberManageContext } from "@/components/community/members/member-management-types"import type { OpenProfile } from "@/components/community/social/profile-types"import type { RightPanel } from "@/components/community/shell/panel-types"-import type { Msg, RenderMsg, Thread } from "@/lib/community/models/message"+import type { Msg, Thread } from "@/lib/community/models/message"import type { Member } from "@/lib/community/models/people"import type { CommunityProfile } from "@/lib/community/models/people"import { useCanonicalProfilesByUserId } from "@/lib/community-db/projections"@@ -38,10 +33,6 @@ export type CommunityPanelProps = {manageContext?: MemberManageContextpinned: Msg[]pinnedLoading?: boolean- searchResults: Msg[]- searchError?: string- searchLoading?: boolean- searchQuery?: stringthreads: Thread[]threadsLoading?: booleanonOpenThread: (id: string) => void@@ -50,11 +41,8 @@ export type CommunityPanelProps = {onKickMember?: (memberId: string) => Promise<unknown> | voidmyRole?: RoleonJumpToMessage?: (seq: number) => void- onSearch?: (query: string) => void- viewerUserId?: string}-/** Members, pins, search, and threads business content in the shared modal shell. */export function CommunityPanel(props: CommunityPanelProps) {const { open, onOpenChange, kind } = propsconst { icon: Icon, label } = panelHeading(kind)@@ -91,10 +79,6 @@ function renderCommunityPanelBody({manageContext,pinned,pinnedLoading,- searchResults,- searchError,- searchLoading,- searchQuery,threads,threadsLoading,onOpenThread,@@ -103,8 +87,6 @@ function renderCommunityPanelBody({onKickMember,myRole,onJumpToMessage,- onSearch,- viewerUserId,}: CommunityPanelProps, profilesByUserId: ReadonlyMap<string, CommunityProfile>) {if (kind === "members") {return (@@ -161,20 +143,6 @@ function renderCommunityPanelBody({})}- if (kind === "search") {- return (- <SearchPanel- searchResults={searchResults}- error={searchError}- loading={searchLoading}- initialQuery={searchQuery}- onOpenProfile={onOpenProfile}- onSearch={onSearch}- viewerUserId={viewerUserId}- />- )- }-if (threadsLoading && threads.length === 0) return <ThreadListSkeleton />return (<>@@ -220,66 +188,11 @@ function panelHeading(kind: Exclude<RightPanel, null>) {return { icon: Users, label: "Members" }case "pinned":return { icon: Pin, label: "Pinned Messages" }- case "search":- return { icon: Search, label: "Search" }case "threads":return { icon: MessagesSquare, label: "Threads" }}}-function SearchPanel({- searchResults,- error,- loading,- initialQuery,- onOpenProfile,- onSearch,- viewerUserId,-}: {- searchResults: Msg[]- error?: string- loading?: boolean- initialQuery?: string- onOpenProfile?: OpenProfile- onSearch?: (query: string) => void- viewerUserId?: string-}) {- const [query, setQuery] = useAtom(useCreateAtom(initialQuery ?? ""))- const submit = () => {- const nextQuery = query.trim()- if (nextQuery) onSearch?.(nextQuery)- }-- return (- <>- <div className="relative mb-3">- <Search className="absolute top-1/2 left-2 size-4 -translate-y-1/2 text-muted-foreground" />- <Input- className="h-9 pl-8"- placeholder="Search messages"- value={query}- onChange={(event) => setQuery(event.target.value)}- onKeyDown={onEnterSubmit(submit)}- />- </div>- <div className="mb-2 text-xs text-muted-foreground" role={error ? "alert" : "status"}>{error ?? (loading ? "Searching…" : `${searchResults.length} results`)}</div>- {searchResults.map((message) => {- const renderMessage: RenderMsg = { ...message, grouped: false }- return (- <Message- key={message.id}- m={renderMessage}- compact- viewerUserId={viewerUserId}- onOpenThread={() => {}}- onOpenProfile={onOpenProfile}- />- )- })}- </>- )-}-function PinnedListSkeleton() {return (<div className="space-y-2">diff --git a/src/web/src/components/community/shell/panel-types.ts b/src/web/src/components/community/shell/panel-types.tsindex 0a5e1c030..f02bb27cb 100644--- a/src/web/src/components/community/shell/panel-types.ts+++ b/src/web/src/components/community/shell/panel-types.ts@@ -1 +1 @@-export type RightPanel = "members" | "pinned" | "search" | "threads" | null+export type RightPanel = "members" | "pinned" | "threads" | nulldiff --git a/src/web/src/hooks/community/mutations/uploads.ts b/src/web/src/hooks/community/mutations/uploads.tsindex 33bab165f..f8eeb7b8c 100644--- a/src/web/src/hooks/community/mutations/uploads.ts+++ b/src/web/src/hooks/community/mutations/uploads.ts@@ -114,9 +114,6 @@ function uploadPath(target: UploadTarget): string | null {// Thread / DM / channel are all channel rows in one id-space → one upload// door. Whichever id the target carries, it's a channelId to channels/{id}.// Canonical attachments door (route/disc trunk): POST channels/{id}/attachments- // (re-pointed off the old channels/{id}/upload, which stays alive through the- // deploy window and is deleted at the flat-delete step). The response is the- // stable attachment-id carrier consumed by the later message send.const id = target.threadId ?? target.dmId ?? target.channelIdreturn id ? `/api/community/channels/${id}/attachments` : null}diff --git a/src/web/src/lib/agent-visibility.test.ts b/src/web/src/lib/agent-visibility.test.tsdeleted file mode 100644index 75a30139c..000000000--- a/src/web/src/lib/agent-visibility.test.ts+++ /dev/null@@ -1,55 +0,0 @@-import { describe, it, expect } from "vitest";-import { filterVisibleAgents } from "./agent-visibility";--const makeAgent = (id: string, visibility: string, ownerId: string | null) => ({- id,- visibility,- ownerId,- name: `Agent ${id}`,-});--describe("filterVisibleAgents", () => {- const agents = [- makeAgent("a1", "public", "owner1"),- makeAgent("a2", "private", "owner1"),- makeAgent("a3", "private", "owner2"),- makeAgent("a4", "private", "owner3"),- ];-- it("returns public agents for any user", () => {- const result = filterVisibleAgents(agents, "random_user", []);- expect(result.map((a) => a.id)).toEqual(["a1"]);- });-- it("returns agents owned by the user regardless of visibility", () => {- const result = filterVisibleAgents(agents, "owner1", []);- expect(result.map((a) => a.id)).toEqual(["a1", "a2"]);- });-- it("returns private agents the user has explicit access to", () => {- const access = [{ agentId: "a3", userId: "user_x" }];- const result = filterVisibleAgents(agents, "user_x", access);- expect(result.map((a) => a.id)).toEqual(["a1", "a3"]);- });-- it("does not duplicate when user owns AND has access", () => {- const access = [{ agentId: "a2", userId: "owner1" }];- const result = filterVisibleAgents(agents, "owner1", access);- expect(result.map((a) => a.id)).toEqual(["a1", "a2"]);- });-- it("returns empty when no agents match", () => {- const agents = [makeAgent("a1", "private", "owner1")];- const result = filterVisibleAgents(agents, "nobody", []);- expect(result).toEqual([]);- });-- it("filters access list by userId correctly", () => {- const access = [- { agentId: "a3", userId: "user_a" },- { agentId: "a4", userId: "user_b" },- ];- const result = filterVisibleAgents(agents, "user_a", access);- expect(result.map((a) => a.id)).toEqual(["a1", "a3"]);- });-});diff --git a/src/web/src/lib/agent-visibility.ts b/src/web/src/lib/agent-visibility.tsdeleted file mode 100644index 977c6bccc..000000000--- a/src/web/src/lib/agent-visibility.ts+++ /dev/null@@ -1,25 +0,0 @@-import { isPublic } from "@alook/shared";--interface AgentRow {- id: string;- visibility: string;- ownerId: string | null;-}--interface AgentAccessRow {- agentId: string;- userId: string;-}--export function filterVisibleAgents<T extends AgentRow>(- allAgents: T[],- userId: string,- agentAccessList: AgentAccessRow[],-): T[] {- const accessSet = new Set(- agentAccessList.filter((a) => a.userId === userId).map((a) => a.agentId),- );- return allAgents.filter(- (a) => isPublic(a.visibility) || a.ownerId === userId || accessSet.has(a.id),- );-}diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex e3c6726c1..cfcf66e8f 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -1,18 +1,5 @@import { describe, it, expect } from "vitest";-import {- userToResponse,- workspaceToResponse,- agentToResponse,- agentLinkToResponse,- taskToResponse,- conversationToResponse,- channelToResponse,- messageToResponse,- runtimeToResponse,- machineTokenToResponse,- emailToResponse,- calendarEventToResponse,-} from "./responses";+import { taskToResponse, messageToResponse } from "./responses";const ts = new Date("2024-06-01T12:00:00.456Z");const tsFormatted = "2024-06-01T12:00:00Z";@@ -21,168 +8,6 @@ function baseFields(overrides: Record<string, unknown> = {}) {return { createdAt: ts, updatedAt: ts, ...overrides };}-describe("agentToResponse", () => {- it("defaults runtime_config to {} when null", () => {- const res = agentToResponse({- id: "a1",- workspaceId: "w1",- runtimeId: null,- name: "Agent",- description: "desc",- instructions: "inst",- runtimeMode: "auto",- runtimeConfig: null,- status: "active",- maxConcurrentTasks: 1,- ...baseFields(),- });- expect(res.runtime_config).toEqual({});- });-- it("preserves runtime_config when present", () => {- const cfg = { model: "gpt-4" };- const res = agentToResponse({- id: "a1",- workspaceId: "w1",- runtimeId: "r1",- name: "Agent",- description: "desc",- instructions: "inst",- runtimeMode: "auto",- runtimeConfig: cfg,- status: "active",- maxConcurrentTasks: 1,- ...baseFields(),- });- expect(res.runtime_config).toEqual(cfg);- });-- it("returns empty string when runtime_id is null", () => {- const res = agentToResponse({- id: "a1",- workspaceId: "w1",- runtimeId: null,- name: "Agent",- description: "d",- instructions: "i",- runtimeMode: "auto",- runtimeConfig: {},- status: "active",- maxConcurrentTasks: 1,- ...baseFields(),- });- expect(res.runtime_id).toBe("");- });-- it("returns empty string when runtime_id is undefined", () => {- const res = agentToResponse({- id: "a1",- workspaceId: "w1",- name: "Agent",- description: "d",- instructions: "i",- runtimeMode: "auto",- runtimeConfig: {},- status: "active",- maxConcurrentTasks: 1,- ...baseFields(),- });- expect(res.runtime_id).toBe("");- });-});--describe("runtimeToResponse", () => {- it("defaults metadata to {} when null", () => {- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- daemonId: null,- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: null,- machineLastSeenAt: null,- ...baseFields(),- });- expect(res.metadata).toEqual({});- });-- it("returns null when daemon_id is null", () => {- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- daemonId: null,- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: {},- machineLastSeenAt: null,- ...baseFields(),- });- expect(res.daemon_id).toBeNull();- });-- it("returns null when daemon_id is undefined", () => {- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: {},- machineLastSeenAt: null,- ...baseFields(),- });- expect(res.daemon_id).toBeNull();- });-- it("computes status online from recent machineLastSeenAt", () => {- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- daemonId: "d1",- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: {},- machineLastSeenAt: new Date().toISOString(),- ...baseFields(),- });- expect(res.status).toBe("online");- });-- it("computes status offline from null machineLastSeenAt", () => {- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- daemonId: "d1",- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: {},- machineLastSeenAt: null,- ...baseFields(),- });- expect(res.status).toBe("offline");- });-- it("computes status offline from old machineLastSeenAt", () => {- const oldTime = new Date(Date.now() - 60_000).toISOString();- const res = runtimeToResponse({- id: "rt1",- workspaceId: "w1",- daemonId: "d1",- runtimeMode: "docker",- provider: "local",- deviceInfo: "mac",- metadata: {},- machineLastSeenAt: oldTime,- ...baseFields(),- });- expect(res.status).toBe("offline");- });-});-describe("taskToResponse", () => {const taskBase = {id: "t1",@@ -279,308 +104,3 @@ describe("messageToResponse", () => {expect(res.task_id).toBeNull();});});--describe("machineTokenToResponse", () => {- it("returns null for null last_used_at", () => {- const res = machineTokenToResponse({ id: "mt1", name: "Token", lastUsedAt: null, createdAt: ts });- expect(res.last_used_at).toBeNull();- });-- it("formats last_used_at when present", () => {- const res = machineTokenToResponse({ id: "mt1", name: "Token", lastUsedAt: ts, createdAt: ts });- expect(res.last_used_at).toBe(tsFormatted);- });-});--describe("UserResponse shape", () => {- it("has expected keys: id, name, email, avatar_url, created_at, updated_at", () => {- const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", image: "https://img.png", ...baseFields() });- expect(Object.keys(res).sort()).toEqual(- ["avatar_url", "created_at", "email", "id", "name", "updated_at"]- );- expect(res).toEqual({- id: "u1",- name: "A",- email: "[email protected]",- avatar_url: "https://img.png",- created_at: tsFormatted,- updated_at: tsFormatted,- });- });-});--describe("WorkspaceResponse shape", () => {- it("has expected keys: id, name, slug, onboarded, created_at, updated_at", () => {- const res = workspaceToResponse({ id: "w1", name: "WS", slug: "ws", ...baseFields() });- expect(Object.keys(res).sort()).toEqual(- ["created_at", "id", "name", "onboarded", "slug", "updated_at"]- );- });-});--describe("AgentResponse shape", () => {- it("has expected keys", () => {- const res = agentToResponse({- id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",- instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",- maxConcurrentTasks: 3, ...baseFields(),- });- expect(Object.keys(res).sort()).toEqual([- "avatar_url", "created_at", "description", "email_handle", "id", "instructions", "max_concurrent_tasks",- "name", "owner_id", "runtime_config", "runtime_id", "runtime_mode", "status",- "updated_at", "visibility", "workspace_id",- ]);- });-- it("includes avatar_url as null when not provided", () => {- const res = agentToResponse({- id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",- instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",- maxConcurrentTasks: 1, ...baseFields(),- });- expect(res.avatar_url).toBeNull();- });-- it("includes avatar_url when provided", () => {- const res = agentToResponse({- id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",- instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",- maxConcurrentTasks: 1, avatarUrl: "https://example.com/avatar.png", ...baseFields(),- });- expect(res.avatar_url).toBe("https://example.com/avatar.png");- });-});--describe("ConversationResponse shape", () => {- it("has expected keys: id, agent_id, title, type, channel, created_at", () => {- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", type: "user_dm_message", channel: "default", createdAt: ts });- expect(Object.keys(res).sort()).toEqual(["agent_id", "channel", "created_at", "id", "title", "type"]);- });-- it("defaults type to user_dm_message when the column is absent", () => {- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", createdAt: ts });- expect((res as { type: string }).type).toBe("user_dm_message");- });-- it("defaults channel to 'default' when the column is absent", () => {- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", createdAt: ts });- expect(res.channel).toBe("default");- });-- it("preserves channel value when present", () => {- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", channel: "work", createdAt: ts });- expect(res.channel).toBe("work");- });-- it("surfaces email_notification and calendar_event types", () => {- const r1 = conversationToResponse({ id: "c1", agentId: "a1", title: "", type: "email_notification", createdAt: ts });- const r2 = conversationToResponse({ id: "c2", agentId: "a1", title: "", type: "calendar_event", createdAt: ts });- expect((r1 as { type: string }).type).toBe("email_notification");- expect((r2 as { type: string }).type).toBe("calendar_event");- });-});--describe("channelToResponse", () => {- it("maps DB fields to API response format", () => {- 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", position: 1, createdAt: ts });- expect(Object.keys(res).sort()).toEqual(["created_at", "id", "name", "position", "workspace_id"]);- });-});--describe("MessageResponse shape", () => {- it("has expected keys: id, conversation_id, role, content, task_id, created_at", () => {- const res = messageToResponse({ id: "m1", conversationId: "c1", role: "user", content: "hi", taskId: "t1", createdAt: ts });- expect(Object.keys(res).sort()).toEqual(- ["attachment_ids", "content", "conversation_id", "created_at", "id", "metadata", "role", "task_id"]- );- });-});--describe("MachineTokenResponse shape", () => {- it("has expected keys: id, name, status, last_used_at, created_at", () => {- const res = machineTokenToResponse({ id: "mt1", name: "Token", status: "active", lastUsedAt: ts, createdAt: ts });- expect(Object.keys(res).sort()).toEqual(["created_at", "id", "last_used_at", "name", "status"]);- });-});--describe("AgentRuntimeResponse shape", () => {- it("has expected keys", () => {- const res = runtimeToResponse({- id: "rt1", workspaceId: "w1", daemonId: "d1", runtimeMode: "docker",- provider: "local", deviceInfo: "mac", metadata: { foo: 1 },- machineLastSeenAt: new Date().toISOString(), ...baseFields(),- });- expect(Object.keys(res).sort()).toEqual([- "created_at", "daemon_id", "device_info", "id", "last_seen_at",- "metadata", "pending_rescan", "pending_update_version", "provider", "runtime_mode", "status",- "updated_at", "workspace_id",- ]);- });-});--describe("all response mappers strip milliseconds from timestamps", () => {- it("userToResponse strips milliseconds", () => {- const res = userToResponse({ id: "u1", name: "A", email: "[email protected]", image: null, ...baseFields() });- expect(res.created_at).toBe(tsFormatted);- expect(res.updated_at).toBe(tsFormatted);- });-- it("workspaceToResponse strips milliseconds", () => {- const res = workspaceToResponse({ id: "w1", name: "WS", slug: "ws", ...baseFields() });- expect(res.created_at).toBe(tsFormatted);- expect(res.updated_at).toBe(tsFormatted);- });-- it("agentToResponse strips milliseconds", () => {- const res = agentToResponse({- id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",- instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",- maxConcurrentTasks: 1, ...baseFields(),- });- expect(res.created_at).toBe(tsFormatted);- expect(res.updated_at).toBe(tsFormatted);- });-- it("conversationToResponse strips milliseconds", () => {- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", createdAt: ts });- expect(res.created_at).toBe(tsFormatted);- });-- it("runtimeToResponse strips milliseconds", () => {- const res = runtimeToResponse({- id: "rt1", workspaceId: "w1", daemonId: "d1", runtimeMode: "docker",- provider: "local", deviceInfo: "mac", metadata: {},- machineLastSeenAt: ts, ...baseFields(),- });- expect(res.created_at).toBe(tsFormatted);- expect(res.updated_at).toBe(tsFormatted);- expect(res.last_seen_at).toBe(tsFormatted);- });-- it("machineTokenToResponse strips milliseconds", () => {- const res = machineTokenToResponse({ id: "mt1", name: "T", lastUsedAt: ts, createdAt: ts });- expect(res.created_at).toBe(tsFormatted);- expect(res.last_used_at).toBe(tsFormatted);- });-});--describe("calendarEventToResponse", () => {- const base = {- id: "ce_1",- agentId: "ag_1",- workspaceId: "ws_1",- title: "standup",- scheduledAt: ts,- repeatInterval: null,- repeatStopAt: null,- lastTriggeredAt: null,- createdAt: ts,- updatedAt: ts,- };-- it("maps description when present", () => {- const res = calendarEventToResponse({ ...base, description: "<p>hi</p>" });- expect(res.description).toBe("<p>hi</p>");- });-- it("defaults description to null when the column is null", () => {- const res = calendarEventToResponse({ ...base, description: null });- expect(res.description).toBeNull();- });-- it("defaults description to null when the column is absent", () => {- const res = calendarEventToResponse(base);- expect(res.description).toBeNull();- });-});--describe("agentLinkToResponse", () => {- it("maps camelCase Drizzle row to snake_case API response", () => {- const res = agentLinkToResponse({- id: "al_1",- workspaceId: "ws1",- sourceAgentId: "ag_a",- targetAgentId: "ag_b",- instruction: "collaborate closely",- createdAt: ts,- updatedAt: ts,- });- expect(res).toEqual({- id: "al_1",- workspace_id: "ws1",- source_agent_id: "ag_a",- target_agent_id: "ag_b",- instruction: "collaborate closely",- created_at: tsFormatted,- updated_at: tsFormatted,- });- });-});--describe("emailToResponse", () => {- it("maps DB fields to API response format", () => {- const res = emailToResponse({- id: "e1",- agentId: "a1",- fromEmail: "[email protected]",- toEmail: "[email protected]",- subject: "Hello",- r2Key: "emails/abc/raw",- isWhitelisted: 1,- forwarded: 0,-- htmlBody: "<p>Hi</p>",- attachments: "[]",- createdAt: ts,- });- expect(res.id).toBe("e1");- expect(res.agent_id).toBe("a1");- expect(res.from_email).toBe("[email protected]");- expect(res.is_whitelisted).toBe(true);- expect(res.forwarded).toBe(false);-- expect(res.attachments).toEqual([]);- expect(res.created_at).toBe(tsFormatted);- });-- it("parses attachments JSON string", () => {- const attachments = [{ key: "k1", filename: "f.pdf", size: 100, contentType: "application/pdf" }];- const res = emailToResponse({- id: "e2",- agentId: "a1",- fromEmail: "[email protected]",- toEmail: "[email protected]",- subject: "S",- r2Key: "r",- isWhitelisted: 0,- forwarded: 0,-- htmlBody: "",- attachments: JSON.stringify(attachments),- createdAt: ts,- });- expect(res.attachments).toEqual(attachments);- expect(res.attachments[0].filename).toBe("f.pdf");- });-- it("defaults to empty array when attachments is null/empty", () => {- const res = emailToResponse({- id: "e3", agentId: "a1", fromEmail: "[email protected]", toEmail: "[email protected]",- subject: "S", r2Key: "r", isWhitelisted: 0, forwarded: 0,- htmlBody: "", attachments: "",- createdAt: ts,- });- expect(res.attachments).toEqual([]);- });-});diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex 945ea39a8..561b95678 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -1,95 +1,7 @@-import {- formatTimestamp,- formatTimestampNullable,-} from "@/lib/middleware/helpers";-import { TaskApiBaseSchema, isOnline, TASK_TYPES, schema, type Message } from "@alook/shared";+import { formatTimestamp, formatTimestampNullable } from "@/lib/middleware/helpers";+import { TaskApiBaseSchema, TASK_TYPES, schema, type Message } from "@alook/shared";-type WorkspaceRow = typeof schema.workspace.$inferSelect;-type AgentRow = typeof schema.agent.$inferSelect;-type EmailRow = typeof schema.emails.$inferSelect;-type ConversationRow = typeof schema.conversation.$inferSelect;-type ChannelRow = typeof schema.channel.$inferSelect;type MessageRow = typeof schema.message.$inferSelect;-type TaskMessageRow = typeof schema.taskMessage.$inferSelect;-type AgentRuntimeRow = typeof schema.agentRuntime.$inferSelect;-type MachineTokenRow = typeof schema.machineToken.$inferSelect;-type MeetingSessionRow = typeof schema.meetingSession.$inferSelect;-type AgentLinkRow = typeof schema.agentLink.$inferSelect;-type CalendarEventRow = typeof schema.calendarEvent.$inferSelect;-type IssueRow = typeof schema.issue.$inferSelect;--export function userToResponse(u: {- id: string;- name: string;- email: string;- image: string | null;- createdAt: string;- updatedAt: string;-}) {- return {- id: u.id,- name: u.name,- email: u.email,- avatar_url: u.image ?? null,- created_at: formatTimestamp(u.createdAt),- updated_at: formatTimestamp(u.updatedAt),- };-}--export function workspaceToResponse(w: WorkspaceRow) {- return {- id: w.id,- name: w.name,- slug: w.slug,- onboarded: !!w.onboarded,- created_at: formatTimestamp(w.createdAt),- updated_at: formatTimestamp(w.updatedAt),- };-}--export function agentToResponse(a: AgentRow) {- let rc = a.runtimeConfig;- if (!rc) rc = {};- return {- id: a.id,- workspace_id: a.workspaceId,- runtime_id: a.runtimeId || "",- name: a.name,- description: a.description,- instructions: a.instructions,- runtime_mode: a.runtimeMode,- runtime_config: rc,- status: a.status,- max_concurrent_tasks: a.maxConcurrentTasks,- email_handle: a.emailHandle || null,- avatar_url: a.avatarUrl ?? null,- visibility: a.visibility ?? "private",- owner_id: a.ownerId ?? null,- created_at: formatTimestamp(a.createdAt),- updated_at: formatTimestamp(a.updatedAt),- };-}--export function emailToResponse(e: EmailRow) {- return {- id: e.id,- agent_id: e.agentId,- from_email: e.fromEmail,- to_email: e.toEmail,- subject: e.subject,- r2_key: e.r2Key,- is_whitelisted: !!e.isWhitelisted,- forwarded: !!e.forwarded,- message_id: e.messageId ?? "",- in_reply_to: e.inReplyTo ?? "",- references: e.references ?? "",- html_body: e.htmlBody ?? "",- attachments: JSON.parse(e.attachments || "[]"),- status: e.status ?? "unread",- direction: e.direction ?? "inbound",- created_at: formatTimestamp(e.createdAt),- };-}export function taskToResponse(t: {id: string;@@ -135,35 +47,6 @@ export function taskToResponse(t: {});}-export function conversationToResponse(c: Partial<ConversationRow> & Pick<ConversationRow, "id" | "agentId" | "title" | "createdAt"> & { messageCount?: number }) {- const resp: Record<string, unknown> = {- id: c.id,- agent_id: c.agentId,- title: c.title,- type: c.type ?? TASK_TYPES.USER_DM_MESSAGE,- channel: c.channel ?? "default",- created_at: formatTimestamp(c.createdAt),- };- if (c.parentMessageId) {- resp.parent_message_id = c.parentMessageId;- resp.thread_title = c.threadTitle ?? "";- }- if (c.messageCount !== undefined) {- resp.message_count = c.messageCount;- }- return resp;-}--export function channelToResponse(c: ChannelRow) {- return {- id: c.id,- workspace_id: c.workspaceId,- name: c.name,- position: c.position ?? 0,- created_at: formatTimestamp(c.createdAt),- };-}-export function messageToResponse(m: MessageRow): Message {const resp: Message = {id: m.id,@@ -180,182 +63,3 @@ export function messageToResponse(m: MessageRow): Message {}return resp;}--export function taskMessageToResponse(m: Pick<TaskMessageRow, "id" | "seq" | "type" | "content" | "output">) {- return {- id: m.id,- seq: m.seq,- type: m.type,- content: m.content,- output: m.output,- };-}--export function runtimeToResponse(rt: AgentRuntimeRow & { machineLastSeenAt?: Date | string | null; pendingUpdateVersion?: string | null; pendingRescan?: boolean | number | null }) {- let metadata = rt.metadata;- if (!metadata) metadata = {};- const machineLastSeenAt = rt.machineLastSeenAt ?? null;- const lastSeenStr = machineLastSeenAt instanceof Date- ? machineLastSeenAt.toISOString()- : machineLastSeenAt;- return {- id: rt.id,- workspace_id: rt.workspaceId,- daemon_id: rt.daemonId || null,- runtime_mode: rt.runtimeMode,- provider: rt.provider,- status: isOnline(lastSeenStr) ? "online" : "offline",- device_info: rt.deviceInfo,- metadata,- pending_update_version: rt.pendingUpdateVersion ?? null,- pending_rescan: !!rt.pendingRescan,- last_seen_at: formatTimestampNullable(machineLastSeenAt),- created_at: formatTimestamp(rt.createdAt),- updated_at: formatTimestamp(rt.updatedAt),- };-}--export function machineTokenToResponse(mt: Pick<MachineTokenRow, "id" | "name" | "status" | "lastUsedAt" | "createdAt">) {- return {- id: mt.id,- name: mt.name,- status: mt.status,- last_used_at: formatTimestampNullable(mt.lastUsedAt),- created_at: formatTimestamp(mt.createdAt),- };-}--export function meetingToResponse(m: MeetingSessionRow) {- return {- id: m.id,- agent_id: m.agentId,- workspace_id: m.workspaceId,- title: m.title,- meeting_url: m.meetingUrl,- status: m.status,- from_email: m.fromEmail ?? null,- is_whitelisted: !!m.isWhitelisted,- participants: m.participants ?? [],- scheduled_at: formatTimestampNullable(m.scheduledAt),- started_at: formatTimestampNullable(m.startedAt),- completed_at: formatTimestampNullable(m.completedAt),- transcript_r2_key: m.transcriptR2Key ?? null,- summary: m.summary ?? null,- error: m.error ?? null,- worker_session_id: m.workerSessionId ?? null,- created_at: formatTimestamp(m.createdAt),- updated_at: formatTimestamp(m.updatedAt),- };-}--export function agentLinkToResponse(row: AgentLinkRow) {- return {- id: row.id,- workspace_id: row.workspaceId,- source_agent_id: row.sourceAgentId,- target_agent_id: row.targetAgentId,- instruction: row.instruction,- created_at: formatTimestamp(row.createdAt),- updated_at: formatTimestamp(row.updatedAt),- };-}--export function calendarEventToResponse(e: CalendarEventRow & { occurrenceAt?: string | null; collapsedCount?: number | null }) {- const scheduled = formatTimestamp(e.scheduledAt);- const occurrence = e.occurrenceAt ? formatTimestamp(e.occurrenceAt) : scheduled;- return {- id: e.id,- agent_id: e.agentId,- workspace_id: e.workspaceId,- title: e.title,- description: e.description ?? null,- scheduled_at: scheduled,- occurrence_at: occurrence,- collapsed_count: e.collapsedCount ?? null,- repeat_interval: e.repeatInterval ?? null,- repeat_stop_at: formatTimestampNullable(e.repeatStopAt),- last_triggered_at: formatTimestampNullable(e.lastTriggeredAt),- created_at: formatTimestamp(e.createdAt),- updated_at: formatTimestamp(e.updatedAt),- };-}--export function issueToResponse(row: IssueRow) {- return {- id: row.id,- workspace_id: row.workspaceId,- agent_id: row.agentId,- creator_user_id: row.creatorUserId,- conversation_id: row.conversationId,- latest_task_id: row.latestTaskId ?? null,- title: row.title,- description: row.description ?? "",- status: row.status,- created_at: formatTimestamp(row.createdAt),- updated_at: formatTimestamp(row.updatedAt),- completed_at: formatTimestampNullable(row.completedAt),- };-}--export function taskToActivityResponse(t: {- id: string;- conversationId: string;- type: string;- status: string;- prompt: string;- createdAt: Date | string;- startedAt: Date | string | null;- completedAt: Date | string | null;- error?: string | null;-}) {- const prompt = t.prompt.length > 120 ? t.prompt.slice(0, 120) : t.prompt;- return {- id: t.id,- conversation_id: t.conversationId,- type: t.type ?? TASK_TYPES.USER_DM_MESSAGE,- status: t.status,- prompt,- created_at: formatTimestamp(t.createdAt),- started_at: formatTimestampNullable(t.startedAt),- completed_at: formatTimestampNullable(t.completedAt),- error: t.error || null,- };-}--export function memberToResponse(m: {- id: string;- userId: string;- role: string;- createdAt: string;- userName: string;- userEmail: string;- userImage: string | null;-}) {- return {- id: m.id,- user_id: m.userId,- role: m.role,- name: m.userName,- email: m.userEmail,- image: m.userImage,- created_at: formatTimestamp(m.createdAt),- };-}--export function inviteToResponse(inv: {- id: string;- token: string;- createdBy: string;- usedBy: string | null;- expiresAt: string;- createdAt: string;-}) {- return {- id: inv.id,- token: inv.token,- created_by: inv.createdBy,- used_by: inv.usedBy,- expires_at: formatTimestamp(inv.expiresAt),- created_at: formatTimestamp(inv.createdAt),- };-}diff --git a/src/web/src/lib/cache.ts b/src/web/src/lib/cache.tsindex 3f57d0c4c..244fecdc1 100644--- a/src/web/src/lib/cache.ts+++ b/src/web/src/lib/cache.ts@@ -151,22 +151,6 @@ export async function invalidateMany(keys: string[]): Promise<void> {})));}-const INBOX_TYPE_COMBOS = [- "*",- "user_dm_message",- "calendar_event",- "email_notification",- "calendar_event,email_notification",- "calendar_event,user_dm_message",- "email_notification,user_dm_message",- "calendar_event,email_notification,user_dm_message",-];--export function invalidateInboxCounts(userId: string, workspaceId: string): Promise<void> {- const prefix = `inbox:${userId}:${workspaceId}:`;- return invalidateMany(INBOX_TYPE_COMBOS.map((combo) => `${prefix}${combo}`));-}-export const cacheKeys = {machineToken: (token: string) => `mt:${token.slice(0, 20)}`,member: (workspaceId: string, userId: string) => `mem:${workspaceId}:${userId}`,diff --git a/src/web/src/lib/community/create-community-message-allowlist.test.ts b/src/web/src/lib/community/create-community-message-allowlist.test.tsindex 029874fc3..60a8f80ff 100644--- a/src/web/src/lib/community/create-community-message-allowlist.test.ts+++ b/src/web/src/lib/community/create-community-message-allowlist.test.ts@@ -19,8 +19,6 @@ const ALLOWLIST = [// The canonical id-in-path message door (human + bot, folds flat `send` and// the former dm/[id]/messages route — DM now flows through this one tree)."src/app/api/community/channels/[id]/messages/route.ts",- // Bot enrollment welcome message (server owner adds a bot → greeting).- "src/app/api/community/servers/[id]/bots/route.ts",// First-run onboarding placeholder. Role events start the bots first, then// this invokes the deferred canonical dispatcher so normal mention, wake,// broadcast, and typing behavior all remain intact.diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.tsindex 491aa760b..2e4addc0f 100644--- a/src/web/src/lib/community/read-contract.test.ts+++ b/src/web/src/lib/community/read-contract.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest"import { COMMUNITY_CONTRACT_HEADER, normalizeCommunityChannelResource, type CommunityConversationEntryRead } from "@alook/shared"-import { writeCommunityChannelRead, writeCommunityMessagesRead, writeCommunityReadState, writeCommunityConversationEntryRead } from "./read-contract"+import { writeCommunityChannelRead, writeCommunityMessagesRead, writeCommunityConversationEntryRead } from "./read-contract"import { decodeCommunityReadResponse } from "./read-response"import { parseCommunityMessageWindow } from "./messages"import { mapMessageForWs } from "./message-payload"@@ -25,15 +25,13 @@ describe("common reading negotiation", () => {expect(() => decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), body)).toThrow("confirmation mismatch")expect(decodeCommunityReadResponse("/api/community/channels/channel", "GET", new Response(), { ...channel, readContractVersion: 2, accessDecision: access })).not.toHaveProperty("readContractVersion")})- it.each(["channel", "forum", "thread", "dm"] as const)("uses the same message and read-state resource for %s", async (surfaceKind) => {+ it.each(["channel", "forum", "thread", "dm"] as const)("uses the same message resource for %s", async (surfaceKind) => {const message = { id: "m1", seq: 1, authorId: "user", createdAt: "2026-10-07T12:00:00Z", content: "hello", type: "chat" }const response = writeCommunityMessagesRead(request("2"), "channel", { messages: [message], latestSeq: 1, hasMore: true, cursor: "cursor", surfaceReceipt: { channelId: "channel", surfaceKind } })const body = await response.json()expect(body.messages[0]).toMatchObject({ channelId: "channel", clientNonce: null, replyToId: null, attachments: [] })expect(body.messages[0]).not.toHaveProperty("resourceComplete")expect(decodeCommunityReadResponse("/api/community/channels/channel/messages", "GET", response, body)).toMatchObject({ olderCursor: "cursor", hasMoreOlder: true, surfaceReceipt: { surfaceKind } })- const state = writeCommunityReadState(request("2"), "channel", { lastReadAt: null, lastReadMessageId: null, lastReadSeq: 0 })- expect(decodeCommunityReadResponse("/api/community/channels/channel/read-state", "GET", state, await state.json())).toEqual({ channelId: "channel", lastReadAt: null, lastReadMessageId: null, lastReadSeq: 0 })})it("gives DM and channel transports a single target identity", () => {expect(communityKeys.dmMessages("channel")).toEqual(communityKeys.channelMessages("channel"))diff --git a/src/web/src/lib/community/read-contract.ts b/src/web/src/lib/community/read-contract.tsindex 3e25dfcce..a0c5df4b5 100644--- a/src/web/src/lib/community/read-contract.ts+++ b/src/web/src/lib/community/read-contract.ts@@ -2,7 +2,7 @@ import { NextResponse } from "next/server"import {COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONTRACT_VERSION, requestedCommunityContract, communityReadSchemas, communityChannelResourceFromStorage, CommunityMessageResourceSchema,normalizeCommunityChannelResource, normalizeCommunityMessageResource, CommunityConversationEntryReadSchema, CommunityMessagesReadSchema,- type CommunityAccessDecision, type CommunityReadStateResource, type CommunityMessageSurfaceReceipt, type CommunityMessagesRead,+ type CommunityAccessDecision, type CommunityMessageSurfaceReceipt, type CommunityMessagesRead,type CommunityConversationEntryRead,} from "@alook/shared"import { writeJSON } from "@/lib/middleware/helpers"@@ -45,13 +45,6 @@ export function communityMessagesReadFromPage(channelId: string, page: MessagePareturn CommunityMessagesReadSchema.parse(messageReadPayload(channelId, page, 3))}-export function writeCommunityReadState(request: Request, channelId: string,- state: Omit<CommunityReadStateResource, "channelId">) {- const contract = requestedCommunityContract(request.headers)- if (contract !== 2 && contract !== 3) return writeJSON(state)- return versionedJSON(communityReadSchemas(contract).readState.parse({ contractVersion: contract, channelId, readState: { channelId, ...state } }), contract)-}-export function writeCommunityConversationEntryRead(entry: CommunityConversationEntryRead) {return versionedJSON(CommunityConversationEntryReadSchema.parse(entry), 3)}diff --git a/src/web/src/lib/community/read-response.test.ts b/src/web/src/lib/community/read-response.test.tsindex fef7f9967..1360d0950 100644--- a/src/web/src/lib/community/read-response.test.ts+++ b/src/web/src/lib/community/read-response.test.ts@@ -27,7 +27,7 @@ describe("common read response publication", () => {it("recognizes only complete read routes and decodes their encoded channel identity", () => {expect(communityReadTarget("/api/community/channels/a%2Fb/read?lastReadSeq=4", "put")).toEqual({ channelId: "a/b", resource: "read" })expect(communityReadTarget("/api/community/channels/thread/members?relation=notify")).toEqual({ channelId: "thread", resource: "members" })- for (const [path, method] of [["/api/community/channels/thread/read", "GET"], ["/api/community/channels/thread/messages/extra", "GET"], ["/api/community/channels/thread", "PUT"], ["/api/community/messages/search?q=term", "GET"], ["/api/community/messages/batch", "GET"]]) {+ for (const [path, method] of [["/api/community/channels/thread/read", "GET"], ["/api/community/channels/thread/read-state", "GET"], ["/api/community/channels/thread/messages/extra", "GET"], ["/api/community/channels/thread", "PUT"], ["/api/community/messages/search?q=term", "GET"], ["/api/community/messages/batch", "GET"]]) {expect(communityReadTarget(path!, method)).toBeNull()const body = { contractVersion: 2, private: "unrelated endpoint" }expect(decodeCommunityReadResponse(path!, method, confirmed(), body)).toBe(body)diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.tsindex aa438b6ec..0abf01f92 100644--- a/src/web/src/lib/community/read-response.ts+++ b/src/web/src/lib/community/read-response.ts@@ -16,7 +16,7 @@ export function communityReadTarget(path: string, method = "GET") {if (method.toUpperCase() !== "GET") return nullconst single = /^\/api\/community\/messages\/([^/?]+)(?:\?|$)/.exec(path)if (single && !["search", "batch", "tags"].includes(single[1])) return { channelId: "", messageId: decodeURIComponent(single[1]), resource: "message" }- const matched = /^\/api\/community\/channels\/([^/?]+)(?:\/(messages|read-state|members|threads))?(?:\?|$)/.exec(path)+ const matched = /^\/api\/community\/channels\/([^/?]+)(?:\/(messages|members|threads))?(?:\?|$)/.exec(path)if (!matched) return nullconst resource = matched[2] ?? "metadata"return { channelId: decodeURIComponent(matched[1]), resource: resource === "messages" && new URL(path, "https://alook.invalid").searchParams.has("entry") ? "entry" : resource }@@ -85,11 +85,6 @@ export function decodeCommunityReadResponse(path: string, method: string | undefhasMoreOlder: data.page.hasMoreOlder, hasMoreNewer: data.page.hasMoreNewer, latestSeq: data.page.latestSeq,surfaceReceipt: data.surfaceReceipt }}- if (target.resource === "read-state") {- const data = schemas.readState.parse(value)- assertScope(data.channelId); assertScope(data.readState.channelId)- return data.readState- }if (target.resource === "read") {const data = schemas.readAdvance.parse(value)assertScope(data.channelId)diff --git a/src/web/src/lib/middleware/workspace.test.ts b/src/web/src/lib/middleware/workspace.test.tsdeleted file mode 100644index bc465c2be..000000000--- a/src/web/src/lib/middleware/workspace.test.ts+++ /dev/null@@ -1,85 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest, NextResponse } from "next/server";--const mockGetMemberByUserAndWorkspace = vi.fn();--vi.mock("@opennextjs/cloudflare", () => ({- getCloudflareContext: vi.fn(async () => ({ env: { DB: {} } })),-}));--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...real,- queries: {- member: {- getMemberByUserAndWorkspace: (...args: unknown[]) => mockGetMemberByUserAndWorkspace(...args),- },- },- };-});--import { withWorkspaceMember, withWorkspaceOwner } from "./workspace";--function makeReq(wsId?: string) {- const url = wsId- ? `http://localhost/api/test?workspace_id=${wsId}`- : "http://localhost/api/test";- return new NextRequest(url);-}--const auth = { userId: "u1", email: "[email protected]" };--describe("withWorkspaceMember", () => {- beforeEach(() => vi.clearAllMocks());-- it("returns workspaceId and memberRole on success", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ role: "owner" });- const result = await withWorkspaceMember(makeReq("w1"), auth);- expect(result).toEqual({ workspaceId: "w1", memberRole: "owner" });- });-- it("returns 400 when only params.id is available (not used as workspace fallback)", async () => {- const result = await withWorkspaceMember(makeReq(), { ...auth, params: { id: "w2" } });- expect(result).toBeInstanceOf(NextResponse);- expect((result as NextResponse).status).toBe(400);- });-- it("returns 400 when workspace_id missing", async () => {- const result = await withWorkspaceMember(makeReq(), auth);- expect(result).toBeInstanceOf(NextResponse);- expect((result as NextResponse).status).toBe(400);- });-- it("returns 404 when not a member", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);- const result = await withWorkspaceMember(makeReq("w1"), auth);- expect(result).toBeInstanceOf(NextResponse);- expect((result as NextResponse).status).toBe(404);- });-- it("allows machine token workspace access when auth workspace matches", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);- const result = await withWorkspaceMember(makeReq("w1"), { ...auth, workspaceId: "w1" });- expect(result).toEqual({ workspaceId: "w1", memberRole: "member" });- });-});--describe("withWorkspaceOwner", () => {- beforeEach(() => vi.clearAllMocks());-- it("passes for owner", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ role: "owner" });- const result = await withWorkspaceOwner(makeReq("w1"), auth);- expect(result).toEqual({ workspaceId: "w1", memberRole: "owner" });- });-- it("returns 403 for member role", async () => {- mockGetMemberByUserAndWorkspace.mockResolvedValue({ role: "member" });- const result = await withWorkspaceOwner(makeReq("w1"), auth);- expect(result).toBeInstanceOf(NextResponse);- expect((result as NextResponse).status).toBe(403);- });-});diff --git a/src/web/src/lib/middleware/workspace.ts b/src/web/src/lib/middleware/workspace.tsdeleted file mode 100644index f0b849a64..000000000--- a/src/web/src/lib/middleware/workspace.ts+++ /dev/null@@ -1,67 +0,0 @@-import { NextRequest, NextResponse } from "next/server"-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries } from "@alook/shared"-import { getDb } from "@/lib/db"-import { cached, cacheKeys } from "@/lib/cache"-import type { AuthContext } from "./auth"--export async function withWorkspaceMember(- req: NextRequest,- auth: AuthContext & { params?: Record<string, string> }-): Promise<{ workspaceId: string; memberRole: string } | NextResponse> {- const workspaceId =- req.nextUrl.searchParams.get("workspace_id") ||- req.headers.get("X-Workspace-ID") ||- auth.workspaceId-- if (!workspaceId) {- return NextResponse.json(- { error: "workspace_id is required" },- { status: 400 }- )- }-- if (!auth.userId) {- return NextResponse.json(- { error: "user not authenticated" },- { status: 401 }- )- }-- const { env } = await getCloudflareContext({ async: true })- const db = getDb((env as Env).DB)-- const membership = await cached(- cacheKeys.member(workspaceId, auth.userId),- 1800,- () => queries.member.getMemberByUserAndWorkspace(db, auth.userId, workspaceId),- )- if (!membership && auth.workspaceId === workspaceId) {- return { workspaceId, memberRole: "member" }- }- if (!membership) {- return NextResponse.json(- { error: "workspace not found" },- { status: 404 }- )- }-- return { workspaceId, memberRole: membership.role }-}--export async function withWorkspaceOwner(- req: NextRequest,- auth: AuthContext & { params?: Record<string, string> }-): Promise<{ workspaceId: string; memberRole: string } | NextResponse> {- const result = await withWorkspaceMember(req, auth)- if (result instanceof NextResponse) return result-- if (result.memberRole !== "owner") {- return NextResponse.json(- { error: "owner access required" },- { status: 403 }- )- }-- return result-}diff --git a/src/web/src/lib/npm.ts b/src/web/src/lib/npm.tsindex 2e0677e3c..de4697168 100644--- a/src/web/src/lib/npm.ts+++ b/src/web/src/lib/npm.ts@@ -1,15 +1,3 @@-import { getCloudflareContext } from "@opennextjs/cloudflare"-import { resolveMode } from "@alook/shared"--function getPackageName(): string {- try {- const { env } = getCloudflareContext()- const mode = resolveMode({ nodeEnv: (env as unknown as Record<string, unknown>).NODE_ENV as string | undefined })- if (mode !== "production") return "@alook/app"- } catch {}- return "@alook/cli"-}-async function fetchLatestPackageVersion(pkg: string): Promise<{ version: string; package: string } | null> {try {const res = await fetch(`https://registry.npmjs.org/${pkg}/latest`);@@ -22,10 +10,6 @@ async function fetchLatestPackageVersion(pkg: string): Promise<{ version: string}}-export function fetchLatestCliVersion(): Promise<{ version: string; package: string } | null> {- return fetchLatestPackageVersion(getPackageName())-}-export function fetchLatestDaemonVersion(): Promise<{ version: string; package: string } | null> {return fetchLatestPackageVersion("@alook/daemon")}diff --git a/src/web/src/lib/observability/client.dom.test.ts b/src/web/src/lib/observability/client.dom.test.tsindex d971dc38e..804a9a918 100644--- a/src/web/src/lib/observability/client.dom.test.ts+++ b/src/web/src/lib/observability/client.dom.test.ts@@ -135,8 +135,8 @@ it("real Faro sessions align after interrupted import, regrant, account changes,const one = startAction("message.edit")!, two = startAction("message.pin")!const firstContext = one.span!.spanContext(), secondContext = two.span!.spanContext()await Promise.all([- apiFetchResponse("/api/agents", { observation: { action: one, reason: "command" } }),- apiFetchResponse("/api/workspaces", { observation: { action: two, reason: "command" } }),+ apiFetchResponse("/api/community/bots", { observation: { action: one, reason: "command" } }),+ apiFetchResponse("/api/community/servers", { observation: { action: two, reason: "command" } }),])finishAction(one, "success"); finishAction(two, "success")await vi.advanceTimersByTimeAsync(3000)@@ -145,8 +145,8 @@ it("real Faro sessions align after interrupted import, regrant, account changes,const children = (parent: typeof firstContext) => spans.filter(span => span.traceId === parent.traceId && span.parentSpanId === parent.spanId)expect(children(firstContext)).toHaveLength(1)expect(children(secondContext)).toHaveLength(1)- expect(children(firstContext)[0]?.name).toBe("GET /api/agents")- expect(children(secondContext)[0]?.name).toBe("GET /api/workspaces")+ expect(children(firstContext)[0]?.name).toBe("GET /api/community/bots")+ expect(children(secondContext)[0]?.name).toBe("GET /api/community/servers")const beforeDm = sent.lengthconst dm = startAction("dm.message.send")!const dmContext = dm.span!.spanContext()diff --git a/src/web/src/lib/observability/clock-tracing.dom.test.ts b/src/web/src/lib/observability/clock-tracing.dom.test.tsindex 5f5267496..ed9a42db5 100644--- a/src/web/src/lib/observability/clock-tracing.dom.test.ts+++ b/src/web/src/lib/observability/clock-tracing.dom.test.ts@@ -67,13 +67,13 @@ it("normalizes real native HTTP exports and mirrors, retaining missing-hook andreturn { spans, events }}const flush = async () => { await vi.advanceTimersByTimeAsync(0); now += 4000; await vi.advanceTimersByTimeAsync(3000) }- const path = "/api/agents"+ const path = "/api/community/bots"for (const next of ["success", "body", "error", "abort", "http-error"]) {mode = next; const wallStart = Date.now()if (next === "error" || next === "abort") await expect(window.fetch(path)).rejects.toThrow()else await window.fetch(path)await flush()- const { spans, events } = exported(), span = spans.filter(s => s.name === "GET /api/agents").at(-1)!+ const { spans, events } = exported(), span = spans.filter(s => s.name === "GET /api/community/bots").at(-1)!expect(Number(span.startTimeUnixNano) / 1e6).toBeCloseTo(wallStart, 2)expect(Number(span.endTimeUnixNano) / 1e6).toBeCloseTo(wallStart + 12, 2)const mirror = events.find(e => e.trace?.span_id === span.spanId)!@@ -83,12 +83,12 @@ it("normalizes real native HTTP exports and mirrors, retaining missing-hook and}for (const event of ["load", "error", "abort", "timeout"]) {const wallStart = Date.now(), xhr = new XMLHttpRequest()- xhr.open("GET", "/api/workspaces"); xhr.send()+ xhr.open("GET", "/api/community/servers"); xhr.send()now += 17; drift *= -1; vi.setSystemTime(performance.timeOrigin + now + drift)Object.defineProperty(xhr, "status", { value: event === "load" ? 200 : 0 })xhr.dispatchEvent(new Event(event))await flush()- const { spans, events } = exported(), span = spans.filter(s => s.name === "GET /api/workspaces").at(-1)!+ const { spans, events } = exported(), span = spans.filter(s => s.name === "GET /api/community/servers").at(-1)!expect(Number(span.startTimeUnixNano) / 1e6).toBeCloseTo(wallStart, 2)expect(Number(span.endTimeUnixNano) / 1e6).toBeCloseTo(wallStart + 17, 2)const mirror = events.find(e => e.trace?.span_id === span.spanId)!@@ -121,7 +121,7 @@ it("normalizes real native HTTP exports and mirrors, retaining missing-hook and}mode = "success"; const resumedStart = Date.now()await window.fetch(path); await flush()- expect(Number(exported().spans.filter(s => s.name === "GET /api/agents").at(-1)!.startTimeUnixNano) / 1e6).toBeCloseTo(resumedStart, 2)+ expect(Number(exported().spans.filter(s => s.name === "GET /api/community/bots").at(-1)!.startTimeUnixNano) / 1e6).toBeCloseTo(resumedStart, 2)expect(JSON.stringify(sent)).not.toContain("alook.internal.http")})diff --git a/src/web/src/lib/observability/context.test.ts b/src/web/src/lib/observability/context.test.tsindex 3749ab2f2..fe38b6140 100644--- a/src/web/src/lib/observability/context.test.ts+++ b/src/web/src/lib/observability/context.test.ts@@ -211,7 +211,7 @@ describe("original observation ownership", () => {vi.advanceTimersByTime(240)finishAction(first, "success", { phase: "primary", region: "bots" })const second = beginNavigation("/c/me/friends")!- const request = startRequest("/api/agents", { observation: { action: second, reason: "router" } })+ const request = startRequest("/api/community/bots", { observation: { action: second, reason: "router" } })vi.advanceTimersByTime(660)const spans = [first, second].map((_action, index) => ({ spanContext: () => ({ traceId: String(index + 1).repeat(32), spanId: String(index + 1).repeat(16) }), setAttribute: vi.fn(), end: vi.fn() }))const factory = vi.fn((_name: string, _fields: Record<string, string>, _start: HrTime) => spans[factory.mock.calls.length - 1] as unknown as Span)diff --git a/src/web/src/lib/observability/coverage.test.ts b/src/web/src/lib/observability/coverage.test.tsindex c727374a3..fe9492d59 100644--- a/src/web/src/lib/observability/coverage.test.ts+++ b/src/web/src/lib/observability/coverage.test.ts@@ -2,7 +2,7 @@ import { readFileSync, readdirSync } from "node:fs"import { resolve, relative } from "node:path"import ts from "typescript"import { expect, it } from "vitest"-import { actionNames, pageRoutes, routeTemplate } from "./coverage"+import { actionNames, apiRoutes, pageRoutes, routeTemplate } from "./coverage"import { actionVariants } from "./actions"const web = resolve(import.meta.dirname, "../../..")@@ -14,6 +14,11 @@ it("keeps the route whitelist aligned with both builds and parallel route slots"const routes = new Set(["src/app", "blog/src/app"].flatMap(root => files(resolve(web, root)).filter(file => file.endsWith("/page.tsx")).map(file => "/" + relative(resolve(web, root), file).split("/").slice(0, -1).filter(segment => !segment.startsWith("(") && !segment.startsWith("@")).join("/"))))expect([...routes].sort()).toEqual([...pageRoutes].sort())})+it("keeps the API whitelist aligned with the current route files", () => {+ const root = resolve(web, "src/app/api")+ const routes = files(root).filter(file => file.endsWith("/route.ts")).map(file => "/api/" + relative(root, file).split("/").slice(0, -1).join("/"))+ expect(routes.sort()).toEqual([...apiRoutes].sort())+})it("keeps existing mutation owners inventoried and semantic variants on the whitelist", () => {const inventory = new Set<string>([...mutationCoverage, ...facadeCoverage].map(entry => entry.file))for (const file of files(resolve(web, "src"))) {diff --git a/src/web/src/lib/observability/coverage.ts b/src/web/src/lib/observability/coverage.tsindex 239323d30..11542efa2 100644--- a/src/web/src/lib/observability/coverage.ts+++ b/src/web/src/lib/observability/coverage.ts@@ -28,53 +28,11 @@ export const pageRoutes = [] as constexport const apiRoutes = [- "/api/agent-links",- "/api/agent-links/[id]",- "/api/agents",- "/api/agents/[id]",- "/api/agents/[id]/access",- "/api/agents/[id]/access/[userId]",- "/api/agents/[id]/active-tasks",- "/api/agents/[id]/activity",- "/api/agents/[id]/chat-init",- "/api/agents/[id]/conversation",- "/api/agents/[id]/conversations",- "/api/agents/[id]/email-accounts",- "/api/agents/[id]/email-accounts/[accountId]",- "/api/agents/[id]/email-accounts/[accountId]/sync",- "/api/agents/[id]/email-accounts/[accountId]/test",- "/api/agents/[id]/meetings",- "/api/agents/[id]/meetings/[meetingId]",- "/api/agents/[id]/meetings/[meetingId]/approve",- "/api/agents/[id]/meetings/[meetingId]/stop",- "/api/agents/[id]/pin",- "/api/agents/[id]/skills",- "/api/agents/[id]/threads",- "/api/agents/[id]/whitelist",- "/api/agents/[id]/whitelist/[whitelistId]",- "/api/agents/[id]/workspace/browse",- "/api/agents/active-task-counts",- "/api/agents/active-tasks",- "/api/agents/pins",- "/api/agents/pins/reorder",- "/api/agents/recruit",- "/api/agents/sidebar/reorder",- "/api/artifacts",- "/api/artifacts/[id]",- "/api/artifacts/[id]/content",- "/api/artifacts/[id]/thumbnail",- "/api/artifacts/upload","/api/auth/[...all]","/api/auth/native/attempt","/api/auth/native/cancel","/api/auth/native/exchange","/api/auth/native/status",- "/api/calendar",- "/api/calendar/[id]",- "/api/channels",- "/api/channels/[id]",- "/api/channels/reorder",- "/api/cli/latest-version","/api/community/analytics/funnel-events","/api/community/billing","/api/community/billing/cancel-change",@@ -83,8 +41,6 @@ export const apiRoutes = ["/api/community/bots","/api/community/bots/[id]","/api/community/bots/[id]/active",- "/api/community/bots/[id]/approval-requests/[requestId]/approve",- "/api/community/bots/[id]/approval-requests/[requestId]/deny","/api/community/bots/[id]/audit-log","/api/community/bots/[id]/avatar","/api/community/bots/[id]/diagnostics",@@ -108,9 +64,7 @@ export const apiRoutes = ["/api/community/channels/[id]/pins","/api/community/channels/[id]/pins/[messageId]","/api/community/channels/[id]/read",- "/api/community/channels/[id]/read-state","/api/community/channels/[id]/threads",- "/api/community/channels/[id]/upload","/api/community/channels/participants/batch","/api/community/daemon/activate","/api/community/daemon/bots",@@ -135,6 +89,7 @@ export const apiRoutes = ["/api/community/invites/[token]/join","/api/community/machines","/api/community/machines/[id]",+ "/api/community/machines/[id]/discover-models","/api/community/machines/[id]/reconnect","/api/community/machines/[id]/reset-agents","/api/community/machines/[id]/update",@@ -146,13 +101,11 @@ export const apiRoutes = ["/api/community/messages/[id]/reactions/[emoji]","/api/community/messages/[id]/tags","/api/community/messages/batch",- "/api/community/messages/search","/api/community/messages/tags/batch","/api/community/notifications/devices","/api/community/notifications/devices/[installationId]","/api/community/servers","/api/community/servers/[id]",- "/api/community/servers/[id]/bots","/api/community/servers/[id]/categories","/api/community/servers/[id]/categories/[catId]","/api/community/servers/[id]/categories/reorder",@@ -167,7 +120,6 @@ export const apiRoutes = ["/api/community/servers/[id]/members/search","/api/community/servers/[id]/onboard","/api/community/servers/[id]/presence",- "/api/community/servers/[id]/unreads","/api/community/servers/channels","/api/community/share-image/avatar/[userId]","/api/community/users/[userId]/avatar",@@ -194,89 +146,16 @@ export const apiRoutes = ["/api/community/users/me/profile","/api/community/users/me/read-state","/api/community/users/me/server-folders",- "/api/community/users/me/server-folders/[id]",- "/api/community/users/me/server-folders/reorder","/api/community/users/me/server-rail","/api/community/users/search",- "/api/config/min-version",- "/api/config/model-options",- "/api/conversations",- "/api/conversations/[id]",- "/api/conversations/[id]/active-task",- "/api/conversations/[id]/init",- "/api/conversations/[id]/messages",- "/api/conversations/[id]/threads",- "/api/conversations/check-fresh",- "/api/daemon/conversations/[id]/messages",- "/api/daemon/deregister",- "/api/daemon/heartbeat","/api/daemon/latest-version",- "/api/daemon/register",- "/api/daemon/skills/sync",- "/api/daemon/sweep",- "/api/daemon/tasks/[taskId]/complete",- "/api/daemon/tasks/[taskId]/fail",- "/api/daemon/tasks/[taskId]/messages",- "/api/daemon/tasks/[taskId]/progress",- "/api/daemon/tasks/[taskId]/start",- "/api/daemon/tasks/[taskId]/status",- "/api/daemon/tasks/[taskId]/supersede",- "/api/daemon/tasks/poll",- "/api/daemon/workspace/report",- "/api/daily-quote","/api/desktop/update/[target]/[arch]/[current_version]",- "/api/email",- "/api/email/[id]",- "/api/email/[id]/attachment/[index]",- "/api/email/[id]/body",- "/api/email/[id]/raw",- "/api/email/[id]/thread",- "/api/email/[id]/trust","/api/email/notify",- "/api/email/send",- "/api/email/upload",- "/api/flags",- "/api/flags/[messageId]",- "/api/flags/count","/api/health",- "/api/inbox",- "/api/inbox/count",- "/api/inbox/read",- "/api/inbox/read-all",- "/api/invite/[token]",- "/api/issues",- "/api/issues/[id]",- "/api/issues/[id]/comments",- "/api/machine-tokens",- "/api/machine-tokens/[id]",- "/api/machine-tokens/activate",- "/api/machine-tokens/status",- "/api/me","/api/meeting/callback",- "/api/members/me","/api/pricing","/api/privacy/analytics-consent",- "/api/runtimes",- "/api/runtimes/[runtimeId]/rescan",- "/api/runtimes/[runtimeId]/update",- "/api/runtimes/machine","/api/stripe/webhook",- "/api/studios",- "/api/studios/check-handles",- "/api/studios/check-name",- "/api/tasks/[id]",- "/api/tasks/[id]/messages",- "/api/tasks/[id]/retry",- "/api/traces",- "/api/traces/[traceId]",- "/api/workspaces",- "/api/workspaces/[id]",- "/api/workspaces/[id]/invites",- "/api/workspaces/[id]/invites/[inviteId]",- "/api/workspaces/[id]/members",- "/api/workspaces/[id]/members/[memberId]",- "/api/workspaces/[id]/onboarded",- "/api/workspaces/[id]/overview","/api/ws/token"] as constdiff --git a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsxindex f7e54e209..f48be7019 100644--- a/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx+++ b/src/web/src/lib/observability/navigation-ready-trace.dom.test.tsx@@ -59,7 +59,7 @@ it("binds the initial navigation before ready and parents a real native HTTP spaexpect(navigationForHref(window.location.href)).toBe(navigation)const parent = navigation.span!.spanContext()const { apiFetchResponse } = await import("@/lib/api/client")- await apiFetchResponse("/api/agents", { observation: { action: navigation, reason: "router" } })+ await apiFetchResponse("/api/community/bots", { observation: { action: navigation, reason: "router" } })now = 1250await act(async () => { resolve?.([]); await vi.advanceTimersByTimeAsync(0); view!.rerender(<Root />) })expect(navigation.done).toBe(true)@@ -78,11 +78,11 @@ it("binds the initial navigation before ready and parents a real native HTTP spaexpect(navigationSpan).toHaveLength(1)expect(navigationSpan[0]).toMatchObject({ name: "navigation", traceId: parent.traceId })expect(Number(BigInt(String(navigationSpan[0]!.endTimeUnixNano)) - BigInt(String(navigationSpan[0]!.startTimeUnixNano))) / 1e6).toBeCloseTo(1250, 2)- expect(spans.filter(span => span.parentSpanId === parent.spanId && span.name === "GET /api/agents")).toMatchObject([{ name: "GET /api/agents", traceId: parent.traceId }])+ expect(spans.filter(span => span.parentSpanId === parent.spanId && span.name === "GET /api/community/bots")).toMatchObject([{ name: "GET /api/community/bots", traceId: parent.traceId }])const ready = events.filter(event => event.name === "navigation.ready")expect(ready).toHaveLength(1)expect(ready[0]?.attributes).toMatchObject({ navigation_kind: "document", start_ms: "0", duration_ms: "1250", trace_id: parent.traceId, span_id: parent.spanId, action_id: navigation.id })- const http = spans.find(span => span.parentSpanId === parent.spanId && span.name === "GET /api/agents")!+ const http = spans.find(span => span.parentSpanId === parent.spanId && span.name === "GET /api/community/bots")!expect(Number(http.startTimeUnixNano) / 1e6 - navigation.origin).toBeCloseTo(900, 2)expect(Number(http.endTimeUnixNano) / 1e6 - navigation.origin).toBeCloseTo(1012, 2)const mirrors = events.filter(event => event.name === "faro.tracing.fetch")diff --git a/src/web/src/lib/observability/page-visit.dom.test.ts b/src/web/src/lib/observability/page-visit.dom.test.tsindex f05bc0a90..bd9442112 100644--- a/src/web/src/lib/observability/page-visit.dom.test.ts+++ b/src/web/src/lib/observability/page-visit.dom.test.ts@@ -105,7 +105,7 @@ it("keeps post-ready commands and their requests on the visited page, captures oconst loadEnd = exporter.getFinishedSpans().find(s => s.name === "navigation")!.endTimeexpect(currentPageObservation()).toBe(pageA)const command = startAction("message.edit")!- const pending = startRequest("/api/agents", { observation: { action: command, reason: "command" } })!+ const pending = startRequest("/api/community/bots", { observation: { action: command, reason: "command" } })!const pageB = beginNavigation(b)!expect(currentPageObservation()).toBe(pageA)window.history.pushState(null, "", b)diff --git a/src/web/src/lib/observability/resource.test.ts b/src/web/src/lib/observability/resource.test.tsindex 87bbe7d86..0d12b4707 100644--- a/src/web/src/lib/observability/resource.test.ts+++ b/src/web/src/lib/observability/resource.test.ts@@ -15,7 +15,7 @@ it.each([true, false])("links the exact response server identity without replaciconst span = tracer.startSpan("GET", { kind: SpanKind.CLIENT }, trace.setSpan(ROOT_CONTEXT, root))const client = span.spanContext()const server = { traceId: "a".repeat(32), spanId: "b".repeat(16), traceFlags: sampled ? 1 : 0 }- const response = traceResponse(new Response(), new Request("https://alook.ai/api/agents", { headers: { traceparent: `00-${client.traceId}-${client.spanId}-01` } }), { isTraced: sampled, spanContext: () => server })+ const response = traceResponse(new Response(), new Request("https://alook.ai/api/community/bots", { headers: { traceparent: `00-${client.traceId}-${client.spanId}-01` } }), { isTraced: sampled, spanContext: () => server })observeResourceResponse(span, response.headers.get("server-timing")!)span.end()const recorded = exporter.getFinishedSpans()[0]!@@ -41,9 +41,9 @@ it("projects exact native resources for reversed same-URL requests and retains oconst one = make(), two = make()const record = (span: typeof one, responseEnd: number) => {const id = span.spanContext()- const response = traceResponse(new Response(), new Request("https://alook.ai/api/agents", { headers: { traceparent: `00-${id.traceId}-${id.spanId}-01` } }), { isTraced: true })+ const response = traceResponse(new Response(), new Request("https://alook.ai/api/community/bots", { headers: { traceparent: `00-${id.traceId}-${id.spanId}-01` } }), { isTraced: true })observeResourceResponse(span, response.headers.get("server-timing")!)- entries.push({ name: "https://alook.ai/api/agents", entryType: "resource", serverTiming: [{ name: "alook_upstream", description: id.traceId + "-" + id.spanId }], fetchStart: 100, requestStart: 105, responseStart: responseEnd - 1, responseEnd, transferSize: 50, encodedBodySize: 30, decodedBodySize: 80, responseStatus: 200, nextHopProtocol: "h2", initiatorType: "fetch" } as unknown as PerformanceEntry)+ entries.push({ name: "https://alook.ai/api/community/bots", entryType: "resource", serverTiming: [{ name: "alook_upstream", description: id.traceId + "-" + id.spanId }], fetchStart: 100, requestStart: 105, responseStart: responseEnd - 1, responseEnd, transferSize: 50, encodedBodySize: 30, decodedBodySize: 80, responseStatus: 200, nextHopProtocol: "h2", initiatorType: "fetch" } as unknown as PerformanceEntry)}record(two, 120); now = 120; finishTransportClock(two); two.end()record(one, 180); now = 180; finishTransportClock(one); one.end()diff --git a/src/web/src/lib/observability/trace-response.test.ts b/src/web/src/lib/observability/trace-response.test.tsindex db36e231d..8adef5054 100644--- a/src/web/src/lib/observability/trace-response.test.ts+++ b/src/web/src/lib/observability/trace-response.test.ts@@ -3,7 +3,7 @@ import { readTraceResponse, responseTraceContext, traceResponse } from "./trace-const client = { traceId: "a".repeat(32), spanId: "b".repeat(16), traceFlags: 1 }const server = { traceId: "c".repeat(32), spanId: "d".repeat(16), traceFlags: 1 }-const request = () => new Request("https://alook.ai/api/agents", { headers: { traceparent: `00-${client.traceId}-${client.spanId}-01`, authorization: "private-token" } })+const request = () => new Request("https://alook.ai/api/community/bots", { headers: { traceparent: `00-${client.traceId}-${client.spanId}-01`, authorization: "private-token" } })it("preserves the original stream, status and cache headers and uses only actual native server identity", async () => {const stream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("body")); controller.close() } })@@ -15,7 +15,7 @@ it("preserves the original stream, status and cache headers and uses only actualconst header = response.headers.get("server-timing")!expect(header).toContain('db;dur=2;desc="a,b"')expect(header).not.toContain("private-token")- expect(header).not.toContain("/api/agents")+ expect(header).not.toContain("/api/community/bots")expect(readTraceResponse(header, client)).toEqual({ matched: true, server, sampling: "selected" })expect(await response.text()).toBe("body")})diff --git a/src/web/src/lib/services/calendar.test.ts b/src/web/src/lib/services/calendar.test.tsdeleted file mode 100644index 2f831e129..000000000--- a/src/web/src/lib/services/calendar.test.ts+++ /dev/null@@ -1,405 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--vi.mock("@/lib/logger", () => ({- log: {- info: vi.fn(),- warn: vi.fn(),- error: vi.fn(),- debug: vi.fn(),- },-}));--const mockListDue = vi.fn();-const mockClaim = vi.fn();-const mockRevert = vi.fn();-const mockUpdateSchedule = vi.fn();-const mockGetAgent = vi.fn();-const mockGetUser = vi.fn();-const mockCreateConv = vi.fn();-const mockCreateMessage = vi.fn();-const mockCreateTask = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", async () => {- const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");- return {- ...actual,- queries: {- agent: { getAgent: (...args: unknown[]) => mockGetAgent(...args) },- user: { getUserSelf: (...args: unknown[]) => mockGetUser(...args) },- conversation: {- createConversation: (...args: unknown[]) => mockCreateConv(...args),- },- message: {- createMessage: (...args: unknown[]) => mockCreateMessage(...args),- },- task: { createTask: (...args: unknown[]) => mockCreateTask(...args) },- calendarEvent: {- listDueCalendarEvents: (...args: unknown[]) => mockListDue(...args),- claimCalendarEvent: (...args: unknown[]) => mockClaim(...args),- revertCalendarEventClaim: (...args: unknown[]) => mockRevert(...args),- updateCalendarEventSchedule: (...args: unknown[]) =>- mockUpdateSchedule(...args),- computeNextScheduledAt: actual.queries.calendarEvent- .computeNextScheduledAt,- },- },- };-});--import {- promoteDueCalendarEventsForWorkspace,- repeatStopDateToStopAt,-} from "./calendar";--const fakeDb = {} as never;--function mkEvent(over?: Partial<Record<string, unknown>>) {- return {- id: "ce_1",- agentId: "ag_1",- workspaceId: "ws_1",- title: "Run standup",- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: null,- repeatStopAt: null,- lastTriggeredAt: null,- createdAt: "2026-04-10T00:00:00.000Z",- updatedAt: "2026-04-10T00:00:00.000Z",- ...over,- };-}--beforeEach(() => {- vi.clearAllMocks();- mockGetUser.mockResolvedValue({ id: "u_1", name: "Gus", email: "[email protected]" });-});--describe("promoteDueCalendarEventsForWorkspace", () => {- it("promotes a due event: claim succeeds → conversation + task created", async () => {- mockListDue.mockResolvedValue([mkEvent()]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- const enqueued = await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:05:00.000Z"- );-- expect(enqueued).toBe(1);- expect(mockCreateConv).toHaveBeenCalledTimes(1);- expect(mockCreateConv.mock.calls[0][1]).toMatchObject({- workspaceId: "ws_1",- agentId: "ag_1",- userId: "u_1",- type: "calendar_event",- });- expect(mockCreateMessage).toHaveBeenCalledWith(- expect.anything(),- expect.objectContaining({ role: "event" }),- );- expect(mockCreateTask).toHaveBeenCalledTimes(1);- expect(mockCreateTask.mock.calls[0][1]).toMatchObject({- agentId: "ag_1",- runtimeId: "rt_1",- workspaceId: "ws_1",- conversationId: "cv_1",- prompt: "Run standup",- type: "calendar_event",- });- expect(mockUpdateSchedule).not.toHaveBeenCalled();- expect(mockRevert).not.toHaveBeenCalled();- });-- it("skips events without a runtime — no writes issued (stays eligible)", async () => {- mockListDue.mockResolvedValue([mkEvent()]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: null,- ownerId: "u_1",- });-- const enqueued = await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:05:00.000Z"- );- expect(enqueued).toBe(0);- expect(mockClaim).not.toHaveBeenCalled();- expect(mockCreateConv).not.toHaveBeenCalled();- expect(mockCreateTask).not.toHaveBeenCalled();- });-- it("skips events without an owner — no writes issued", async () => {- mockListDue.mockResolvedValue([mkEvent()]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: null,- });-- const enqueued = await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:05:00.000Z"- );- expect(enqueued).toBe(0);- expect(mockClaim).not.toHaveBeenCalled();- });-- it("concurrent callers: only one enqueues because the guarded UPDATE fails the second time", async () => {- // Both callers see the same candidate list, but the second claim fails.- mockListDue.mockResolvedValue([mkEvent()]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim- .mockResolvedValueOnce({ id: "ce_1" })- .mockResolvedValueOnce(null);- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- const [a, b] = await Promise.all([- promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z"),- promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z"),- ]);-- expect(a + b).toBe(1);- expect(mockCreateTask).toHaveBeenCalledTimes(1);- expect(mockCreateConv).toHaveBeenCalledTimes(1);- });-- it("reverts last_triggered_at when task insert fails after claim", async () => {- mockListDue.mockResolvedValue([mkEvent({ lastTriggeredAt: null })]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockRejectedValue(new Error("D1 write failed"));-- const enqueued = await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:05:00.000Z"- );-- expect(enqueued).toBe(0);- expect(mockRevert).toHaveBeenCalledTimes(1);- expect(mockRevert.mock.calls[0]).toMatchObject({ "1": "ce_1", "2": null });- });-- it("reverts to the previous last_triggered_at value (not null)", async () => {- mockListDue.mockResolvedValue([- mkEvent({- scheduledAt: "2026-04-17T09:00:00.000Z",- lastTriggeredAt: "2026-04-16T09:00:00.000Z",- }),- ]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockRejectedValue(new Error("fail"));-- await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:05:00.000Z"- );-- expect(mockRevert).toHaveBeenCalledWith(- fakeDb,- "ce_1",- "2026-04-16T09:00:00.000Z"- );- });-- it("advances the schedule for repeating events after a successful enqueue", async () => {- mockListDue.mockResolvedValue([- mkEvent({- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: "1day",- }),- ]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:30:00.000Z"- );-- expect(mockUpdateSchedule).toHaveBeenCalledWith(- fakeDb,- "ce_1",- "2026-04-18T09:00:00.000Z"- );- });-- it("passes description and scheduled_by in task context when both exist", async () => {- mockListDue.mockResolvedValue([mkEvent({ description: "Check PRs" })]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z");-- expect(mockCreateTask.mock.calls[0][1].contextKey).toBe("cv_1");- expect(mockCreateTask.mock.calls[0][1].context).toEqual({- event_id: "ce_1",- datetime: "2026-04-17T09:00:00.000Z",- is_recurring: false,- repeat_interval: null,- description: "Check PRs",- scheduled_by: { name: "Gus", email: "[email protected]" },- });- });-- it("omits description from task context when event has no description", async () => {- mockListDue.mockResolvedValue([mkEvent({ description: null })]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z");-- const ctx = mockCreateTask.mock.calls[0][1].context;- expect(ctx.event_id).toBe("ce_1");- expect(ctx.datetime).toBe("2026-04-17T09:00:00.000Z");- expect(ctx.is_recurring).toBe(false);- expect(ctx.repeat_interval).toBeNull();- expect(ctx.description).toBeUndefined();- expect(ctx.scheduled_by).toEqual({ name: "Gus", email: "[email protected]" });- });-- it("omits scheduled_by from task context when getUser returns null", async () => {- mockListDue.mockResolvedValue([mkEvent({ description: "Check PRs" })]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_deleted",- });- mockGetUser.mockResolvedValue(null);- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z");-- const ctx = mockCreateTask.mock.calls[0][1].context;- expect(ctx.event_id).toBe("ce_1");- expect(ctx.datetime).toBe("2026-04-17T09:00:00.000Z");- expect(ctx.is_recurring).toBe(false);- expect(ctx.repeat_interval).toBeNull();- expect(ctx.description).toBe("Check PRs");- expect(ctx.scheduled_by).toBeUndefined();- });-- it("includes is_recurring=true and repeat_interval for recurring events", async () => {- mockListDue.mockResolvedValue([- mkEvent({ repeatInterval: "1week", description: null }),- ]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(fakeDb, "ws_1", "2026-04-17T09:05:00.000Z");-- const ctx = mockCreateTask.mock.calls[0][1].context;- expect(ctx.event_id).toBe("ce_1");- expect(ctx.datetime).toBe("2026-04-17T09:00:00.000Z");- expect(ctx.is_recurring).toBe(true);- expect(ctx.repeat_interval).toBe("1week");- });-- it("does not advance the schedule when the next occurrence would exceed repeat_stop_at", async () => {- mockListDue.mockResolvedValue([- mkEvent({- scheduledAt: "2026-04-17T09:00:00.000Z",- repeatInterval: "1day",- repeatStopAt: "2026-04-17T23:59:59.999Z",- }),- ]);- mockGetAgent.mockResolvedValue({- id: "ag_1",- workspaceId: "ws_1",- runtimeId: "rt_1",- ownerId: "u_1",- });- mockClaim.mockResolvedValue({ id: "ce_1" });- mockCreateConv.mockResolvedValue({ id: "cv_1" });- mockCreateTask.mockResolvedValue({ id: "t_1" });-- await promoteDueCalendarEventsForWorkspace(- fakeDb,- "ws_1",- "2026-04-17T09:30:00.000Z"- );-- expect(mockUpdateSchedule).not.toHaveBeenCalled();- });-});--describe("repeatStopDateToStopAt", () => {- it("converts YYYY-MM-DD to end-of-day ISO", () => {- const out = repeatStopDateToStopAt("2026-05-17");- const parsed = new Date(out);- expect(parsed.getFullYear()).toBe(2026);- expect(parsed.getMonth()).toBe(4); // May- expect(parsed.getDate()).toBe(17);- expect(parsed.getHours()).toBe(23);- expect(parsed.getMinutes()).toBe(59);- });-- it("throws on bad input", () => {- expect(() => repeatStopDateToStopAt("not-a-date")).toThrow();- });-});diff --git a/src/web/src/lib/services/calendar.ts b/src/web/src/lib/services/calendar.tsdeleted file mode 100644index fea79c98c..000000000--- a/src/web/src/lib/services/calendar.ts+++ /dev/null@@ -1,155 +0,0 @@-import type { Database } from "@alook/shared";-import { queries, TASK_TYPES } from "@alook/shared";-import { nanoid } from "nanoid";-import { log } from "@/lib/logger";--const {- listDueCalendarEvents,- claimCalendarEvent,- revertCalendarEventClaim,- updateCalendarEventSchedule,- computeNextScheduledAt,-} = queries.calendarEvent;--/**- * Convert a user-provided local calendar date (YYYY-MM-DD) into an inclusive- * UTC end-of-day ISO string in the caller's local timezone. Used to store the- * repeat stop boundary.- */-export function repeatStopDateToStopAt(repeatStopDate: string): string {- const [y, m, d] = repeatStopDate.split("-").map(Number);- if (!y || !m || !d) {- throw new Error(`invalid repeat_stop_date: ${repeatStopDate}`);- }- const date = new Date(y, m - 1, d, 23, 59, 59, 999);- return date.toISOString();-}--/**- * Promote due calendar events in the given workspace into queued tasks.- *- * The only concurrency primitive is the exact-occurrence guarded UPDATE in- * `claimCalendarEvent` — every step after claim is best-effort, with a- * compensating revert on failure. Runtime/owner pre-checks are done before the- * claim so a non-runnable event stays eligible for a later poll.- *- * Returns the number of events enqueued as tasks.- */-export async function promoteDueCalendarEventsForWorkspace(- db: Database,- workspaceId: string,- nowIso: string = new Date().toISOString(),-): Promise<number> {- const candidates = await listDueCalendarEvents(db, workspaceId, nowIso);- const ownerCache = new Map<string, { name: string; email: string } | null>();- let enqueued = 0;-- for (const ev of candidates) {- // Pre-claim checks — skip without writing so the event remains eligible- // for a later poll once the agent has a runtime/owner.- const agent = await queries.agent.getAgent(db, ev.agentId, ev.workspaceId);- if (!agent) {- log.warn("calendar: agent missing, skipping", { id: ev.id });- continue;- }- if (!agent.runtimeId) {- log.warn("calendar: agent has no runtime, skipping", { id: ev.id });- continue;- }- if (!agent.ownerId) {- log.warn("calendar: agent has no owner, skipping", { id: ev.id });- continue;- }-- const previousLastTriggeredAt = ev.lastTriggeredAt ?? null;- const claimed = await claimCalendarEvent(db, ev.id, ev.scheduledAt, nowIso);- if (!claimed) {- // Another caller won the guarded UPDATE; skip.- continue;- }-- try {- const conv = await queries.conversation.createConversation(db, {- workspaceId: ev.workspaceId,- agentId: ev.agentId,- userId: agent.ownerId,- title: `[Calendar] ${ev.title}`.slice(0, 120),- type: TASK_TYPES.CALENDAR_EVENT,- });-- await queries.message.createMessage(db, {- conversationId: conv.id,- role: "event",- content: ev.title,- metadata: JSON.stringify({ calendarEventId: ev.id }),- });-- if (!ownerCache.has(agent.ownerId)) {- const u = await queries.user.getUserSelf(db, agent.ownerId);- ownerCache.set(agent.ownerId, u ? { name: u.name, email: u.email } : null);- }- const ownerInfo = ownerCache.get(agent.ownerId)!;-- const taskContext: Record<string, unknown> = {- event_id: ev.id,- datetime: ev.scheduledAt,- is_recurring: !!ev.repeatInterval,- repeat_interval: ev.repeatInterval ?? null,- };- if (ev.description) {- taskContext.description = ev.description;- }- if (ownerInfo) {- taskContext.scheduled_by = ownerInfo;- }-- await queries.task.createTask(db, {- agentId: ev.agentId,- runtimeId: agent.runtimeId,- workspaceId: ev.workspaceId,- conversationId: conv.id,- contextKey: conv.id,- prompt: ev.title,- type: TASK_TYPES.CALENDAR_EVENT,- priority: 0,- traceId: "tr_" + nanoid(),- parentTaskId: null,- context: taskContext,- });-- if (ev.repeatInterval) {- const next = computeNextScheduledAt(- ev.scheduledAt,- ev.repeatInterval,- ev.repeatStopAt ?? null,- nowIso,- ev.exceptions ?? [],- );- if (next) {- await updateCalendarEventSchedule(db, ev.id, next);- }- }-- enqueued++;- } catch (err) {- log.warn("calendar: post-claim write failed, reverting", {- id: ev.id,- err: String(err),- });- // Compensating revert — event becomes eligible again on the next poll.- try {- await revertCalendarEventClaim(db, ev.id, previousLastTriggeredAt);- } catch (revertErr) {- log.error("calendar: compensating revert failed", {- id: ev.id,- err: String(revertErr),- });- }- }- }-- if (enqueued > 0) {- log.info("calendar: promoted due events", { workspaceId, enqueued });- }- return enqueued;-}diff --git a/src/web/src/lib/services/sweep.test.ts b/src/web/src/lib/services/sweep.test.tsdeleted file mode 100644index 4171315d2..000000000--- a/src/web/src/lib/services/sweep.test.ts+++ /dev/null@@ -1,157 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";--const mockFailStaleDispatchedTasks = vi.fn();-const mockFailStaleKillTasks = vi.fn();-const mockFailStaleRunningTasks = vi.fn();-const mockCountRunningTasks = vi.fn();-const mockUpdateAgentStatus = vi.fn();-const mockGetConversation = vi.fn();-const mockGetAgent = vi.fn();-const mockCreateTask = vi.fn();--vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));--vi.mock("@alook/shared", () => ({- queries: {- task: {- failStaleDispatchedTasks: (...args: unknown[]) => mockFailStaleDispatchedTasks(...args),- failStaleKillTasks: (...args: unknown[]) => mockFailStaleKillTasks(...args),- failStaleRunningTasks: (...args: unknown[]) => mockFailStaleRunningTasks(...args),- countRunningTasks: (...args: unknown[]) => mockCountRunningTasks(...args),- createTask: (...args: unknown[]) => mockCreateTask(...args),- },- agent: {- getAgent: (...args: unknown[]) => mockGetAgent(...args),- updateAgentStatus: (...args: unknown[]) => mockUpdateAgentStatus(...args),- },- message: {- createMessage: vi.fn(),- },- conversation: {- getConversation: (...args: unknown[]) => mockGetConversation(...args),- },- },- TASK_TYPES: { USER_DM_MESSAGE: "user_dm_message", KILL_TASK: "kill_task" },- buildEmailMapKey: (agentId: string, threadId: string) => `email:${agentId}:${threadId}`,-}));--vi.mock("@/lib/logger", () => ({- log: { warn: vi.fn(), info: vi.fn(), error: vi.fn() },-}));--vi.mock("@/lib/broadcast", () => ({- broadcastToUser: vi.fn().mockResolvedValue(undefined),-}));--vi.mock("@/lib/api/responses", () => ({- messageToResponse: (m: unknown) => m,- taskToResponse: (t: unknown) => t,-}));--import { sweepStaleState, _resetSweepThrottle } from "./sweep";--const db = {} as any;--describe("sweepStaleState", () => {- beforeEach(() => {- vi.clearAllMocks();- _resetSweepThrottle();- mockFailStaleKillTasks.mockResolvedValue([]);- mockFailStaleRunningTasks.mockResolvedValue([]);- });-- it("calls failStaleDispatchedTasks with workspace", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([]);-- await sweepStaleState(db, "w1");-- expect(mockFailStaleDispatchedTasks).toHaveBeenCalledWith(db, "w1");- });-- it("reconciles agent status for each affected agent", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- { agentId: "a2", workspaceId: "w1", conversationId: "c2" },- ]);- mockCountRunningTasks.mockResolvedValue(0);- mockUpdateAgentStatus.mockResolvedValue(undefined);-- await sweepStaleState(db, "w1");-- expect(mockCountRunningTasks).toHaveBeenCalledTimes(2);- expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(2);- });-- it("deduplicates reconcile calls by agentId:workspaceId", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- ]);- mockCountRunningTasks.mockResolvedValue(0);- mockUpdateAgentStatus.mockResolvedValue(undefined);-- await sweepStaleState(db, "w1");-- expect(mockCountRunningTasks).toHaveBeenCalledTimes(1);- expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(1);- });-- it("handles zero stale tasks gracefully", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([]);-- await sweepStaleState(db, "w1");-- expect(mockCountRunningTasks).not.toHaveBeenCalled();- expect(mockUpdateAgentStatus).not.toHaveBeenCalled();- });-- it("calls failStaleKillTasks with workspace", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([]);-- await sweepStaleState(db, "w1");-- expect(mockFailStaleKillTasks).toHaveBeenCalledWith(db, "w1");- });-- it("calls failStaleRunningTasks with workspace", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([]);-- await sweepStaleState(db, "w1");-- expect(mockFailStaleRunningTasks).toHaveBeenCalledWith(db, "w1");- });-- it("reconciles agents from both dispatched and running sweeps", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- ]);- mockFailStaleRunningTasks.mockResolvedValue([- { agentId: "a2", workspaceId: "w1", conversationId: "c2" },- ]);- mockCountRunningTasks.mockResolvedValue(0);- mockUpdateAgentStatus.mockResolvedValue(undefined);-- await sweepStaleState(db, "w1");-- expect(mockCountRunningTasks).toHaveBeenCalledTimes(2);- expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(2);- });-- it("deduplicates agents across both sweeps", async () => {- mockFailStaleDispatchedTasks.mockResolvedValue([- { agentId: "a1", workspaceId: "w1", conversationId: "c1" },- ]);- mockFailStaleRunningTasks.mockResolvedValue([- { agentId: "a1", workspaceId: "w1", conversationId: "c2" },- ]);- mockCountRunningTasks.mockResolvedValue(0);- mockUpdateAgentStatus.mockResolvedValue(undefined);-- await sweepStaleState(db, "w1");-- expect(mockCountRunningTasks).toHaveBeenCalledTimes(1);- expect(mockUpdateAgentStatus).toHaveBeenCalledTimes(1);- });--});diff --git a/src/web/src/lib/services/sweep.ts b/src/web/src/lib/services/sweep.tsdeleted file mode 100644index b195e8cbb..000000000--- a/src/web/src/lib/services/sweep.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { Database } from "@alook/shared";-import { queries } from "@alook/shared";-import { TaskService } from "./task";-import { throttled, invalidate, cacheKeys } from "@/lib/cache";--const SWEEP_INTERVAL_S = 30;--/** @internal test-only */-export function _resetSweepThrottle() {}--/**- * Unified workspace housekeeping. Any code path that wants to ensure- * stale state is cleaned up just calls this one function.- * Rate-limited to once per 30s per workspace via KV (timestamp-based).- */-export async function sweepStaleState(db: Database, workspaceId: string) {- const lockKey = `sweep:${workspaceId}`;- let shouldRun = false;- try {- shouldRun = await throttled(lockKey, SWEEP_INTERVAL_S, async () => {});- } catch {- shouldRun = true;- }- if (!shouldRun) return;-- // 1. Fail tasks stuck in "dispatched" for >20s (daemon crashed between claim and start)- const staleDispatched = await queries.task.failStaleDispatchedTasks(db, workspaceId);-- // 1b. Fail kill_tasks stuck for >30s (daemon offline or crashed after claim)- await queries.task.failStaleKillTasks(db, workspaceId);-- // 2. Fail tasks stuck in "running" with no message activity for >1h- const staleRunning = await queries.task.failStaleRunningTasks(db, workspaceId);-- // 3. Reconcile agent status for all affected agents- const allStale = [...staleDispatched, ...staleRunning];- if (allStale.length > 0) {- const taskService = new TaskService(db);- const seenAgents = new Set<string>();- for (const r of allStale) {- const key = `${r.agentId}:${r.workspaceId}`;- if (seenAgents.has(key)) continue;- seenAgents.add(key);- await taskService.reconcileAgentStatus(r.agentId, r.workspaceId);- }-- // Invalidate caches that sweep modified- const dateStr = new Date().toISOString().slice(0, 10);- await invalidate(cacheKeys.overviewTaskStats(workspaceId, dateStr)).catch(() => {});- }-}diff --git a/src/web/src/lib/token.test.ts b/src/web/src/lib/token.test.tsdeleted file mode 100644index 6635ee0b5..000000000--- a/src/web/src/lib/token.test.ts+++ /dev/null@@ -1,25 +0,0 @@-import { describe, it, expect } from "vitest";-import { generateMachineToken } from "./token.js";--describe("generateMachineToken", () => {- it("starts with 'al_' prefix", () => {- const token = generateMachineToken();- expect(token.startsWith("al_")).toBe(true);- });-- it("has correct length (al_ + 48 hex chars = 51)", () => {- const token = generateMachineToken();- expect(token.length).toBe(51);- });-- it("contains only valid hex characters after prefix", () => {- const token = generateMachineToken();- const hex = token.slice(3);- expect(hex).toMatch(/^[0-9a-f]{48}$/);- });-- it("generates unique tokens", () => {- const tokens = new Set(Array.from({ length: 10 }, () => generateMachineToken()));- expect(tokens.size).toBe(10);- });-});diff --git a/src/web/src/lib/token.ts b/src/web/src/lib/token.tsdeleted file mode 100644index 24049409c..000000000--- a/src/web/src/lib/token.ts+++ /dev/null@@ -1,6 +0,0 @@-import { randomBytes } from "crypto";--export function generateMachineToken(): string {- const bytes = randomBytes(24);- return "al_" + bytes.toString("hex");-}diff --git a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts b/src/web/src/test/architecture/community-read-state-writer-contract.test.tsindex 331f6dd8c..176ddb5a0 100644--- a/src/web/src/test/architecture/community-read-state-writer-contract.test.ts+++ b/src/web/src/test/architecture/community-read-state-writer-contract.test.ts@@ -153,9 +153,6 @@ describe("human account read-state writer contract", () => {expect(route.match(/authorKind: "human"/g)).toHaveLength(2)expect(route.match(/authorKind: "bot"/g)).toHaveLength(2)- const botEnrollment = source("src/web/src/app/api/community/servers/[id]/bots/route.ts")- expect(botEnrollment).toContain('authorKind: "bot"')-const friendship = source("src/shared/src/db/queries/community/friendship.ts")expect(friendship.match(/authorKind: "bot"/g)).toHaveLength(2)})diff --git a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.tsindex 810f81a67..b9653dda3 100644--- a/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts+++ b/src/web/src/test/e2e-ui/30-bot-profile-audit-preview.spec.ts@@ -101,8 +101,22 @@ async function prepareCase(actors: CaseActors, caseResources: CaseResources) {}))return data.bot.id}+ async function joinBotToServer(runnerKey: string, botId: string, serverId: string): Promise<void> {+ const token = await actors.seed.createInvite("alice", serverId)+ const joined = await jsonRequest<{ serverId: string; member: { userId: string } }>(+ "alice",+ `/api/community/invites/${token}/join`,+ {+ method: "POST",+ headers: { Authorization: `Bearer ${runnerKey}` },+ body: "{}",+ },+ )+ expect(joined.serverId).toBe(serverId)+ expect(joined.member.userId).toBe(botId)+ }actors.onCleanup(cleanupCreatedResources)- return { createdBotIds, createdMachineIds, cleanupCreatedResources, headersFor, jsonRequest, pairMachine, createBot }+ return { createdBotIds, createdMachineIds, cleanupCreatedResources, headersFor, jsonRequest, pairMachine, createBot, joinBotToServer }}type UserKey = "alice" | "bob"@@ -611,7 +625,7 @@ test("owned bot profile preview stays root-bounded from its first visible frame"const actors = await caseActors(["alice", "bob"])const { asUser } = actorsconst { seedChannel, seedForumThread, seedJoinServer, seedServer } = actors.seed- const { jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)+ const { jsonRequest, pairMachine, createBot, joinBotToServer } = await prepareCase(actors, caseResources)const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `preview-overflow-${suffix}`)@@ -630,11 +644,8 @@ test("owned bot profile preview stays root-bounded from its first visible frame"const { credential, machineId } = await pairMachine()const botName = `Overflow bot ${suffix}`const botId = await createBot(machineId, botName)- await jsonRequest("alice", `/api/community/servers/${serverId}/bots`, {- method: "POST",- body: JSON.stringify({ botId }),- })const runnerKey = await enrollBot(credential, botId)+ await joinBotToServer(runnerKey, botId, serverId)const { servers } = await jsonRequest<{servers: Array<{ id: string; name: string; discriminator: string }>}>("alice", "/api/community/servers")@@ -715,7 +726,7 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audconst actors = await caseActors(["alice", "bob"])const { asUser } = actorsconst { seedChannel, seedJoinServer, seedServer } = actors.seed- const { headersFor, jsonRequest, pairMachine, createBot } = await prepareCase(actors, caseResources)+ const { headersFor, jsonRequest, pairMachine, createBot, joinBotToServer } = await prepareCase(actors, caseResources)const suffix = Date.now().toString(36)const serverId = await seedServer("alice", `profile-preview-server-with-a-long-name-${suffix}`)@@ -729,14 +740,9 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audconst { credential, machineId } = await pairMachine()const botName = `Preview bot ${suffix} long-name`const botId = await createBot(machineId, botName)- await jsonRequest("alice", `/api/community/servers/${serverId}/bots`, {- method: "POST",- body: JSON.stringify({ botId }),- })- await jsonRequest("alice", `/api/community/servers/${staleServerId}/bots`, {- method: "POST",- body: JSON.stringify({ botId }),- })+ const runnerKey = await enrollBot(credential, botId)+ await joinBotToServer(runnerKey, botId, serverId)+ await joinBotToServer(runnerKey, botId, staleServerId)const { servers } = await jsonRequest<{servers: Array<{ id: string; name: string; discriminator: string }>@@ -745,7 +751,6 @@ test("owner-only bot mark sticker, Stop lifecycle, owner swap, and URL-owned audconst staleServer = servers.find((candidate) => candidate.id === staleServerId)expect(server).toBeTruthy()expect(staleServer).toBeTruthy()- const runnerKey = await enrollBot(credential, botId)const channelRef = `/${server!.name}#${server!.discriminator}/${channelName}`let latestSeq = 0for (const index of [1, 2, 3]) {diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.tsindex b40dafe10..5d2efa535 100644--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts@@ -281,17 +281,18 @@ type ReadState = {async function settledReadState(page: Page, channelId: string): Promise<ReadState> {let previous: ReadState | null = nullfor (let attempt = 0; attempt < 30; attempt += 1) {- const response = await page.request.get(`/api/community/channels/${channelId}/read-state`)+ const response = await page.request.get("/api/community/users/me/read-state")expect(response.ok()).toBe(true)- const current = await response.json() as ReadState+ const snapshot = await response.json() as { readStates: Array<ReadState & { channelId: string }> }+ const current = snapshot.readStates.find((row) => row.channelId === channelId)if (- current.lastReadMessageId+ current?.lastReadMessageId&& previous?.lastReadMessageId === current.lastReadMessageId&& previous.lastReadSeq === current.lastReadSeq) {return current}- previous = current+ previous = current ?? nullawait page.waitForTimeout(100)}throw new Error(`read state did not settle for ${channelId}: ${JSON.stringify(previous)}`)diff --git a/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts b/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.tsindex 4dbb4352a..8ac142b88 100644--- a/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts+++ b/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts@@ -121,7 +121,7 @@ async function measureInboxClick({path === `/api/community/channels/${targetId}/messages`))const readStarts = startsFor((path) => (- path === `/api/community/channels/${targetId}/read-state`+ path === "/api/community/users/me/read-state"))const rscStarts = startsFor((path) => path.includes(targetId) && path.endsWith("?_rsc"))const detailStarts = Object.fromEntries(detailPaths.map((path) => [@@ -214,7 +214,7 @@ test("Inbox Channel/DM navigation fixed trace", async ({ browser }) => {detailPaths: [`/api/community/servers/${targetServer.id}/categories`,`/api/community/servers/${targetServer.id}/channels`,- `/api/community/servers/${targetServer.id}/unreads`,+ "/api/community/users/me/attention",],}))await page.goBack()@@ -234,7 +234,7 @@ test("Inbox Channel/DM navigation fixed trace", async ({ browser }) => {detailPaths: [`/api/community/servers/${targetServer.id}/categories`,`/api/community/servers/${targetServer.id}/channels`,- `/api/community/servers/${targetServer.id}/unreads`,+ "/api/community/users/me/attention",],}))diff --git a/src/web/src/test/e2e/agent-access.test.ts b/src/web/src/test/e2e/agent-access.test.tsdeleted file mode 100644index c494af446..000000000--- a/src/web/src/test/e2e/agent-access.test.ts+++ /dev/null@@ -1,121 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, seedSecondaryUser, cleanupSecondaryUser, type SecondaryUser, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let secondary: SecondaryUser--beforeAll(() => {- seed = seedTestData()- secondary = seedSecondaryUser(seed.workspaceId, "member")-}, 60_000)--afterAll(() => {- cleanupSecondaryUser(secondary)- cleanupTestData(seed)-}, 60_000)--describe("agent access control", () => {- it("GET /api/agents/:id/access returns empty list initially", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toEqual([])- })-- it("POST /api/agents/:id/access grants access to secondary user", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ user_id: secondary.userId }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.user_id).toBe(secondary.userId)- })-- it("GET /api/agents/:id/access now includes the granted user", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toHaveLength(1)- expect(data[0].user_id).toBe(secondary.userId)- })-- it("POST /api/agents/:id/access also adds user email to whitelist", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- const secondaryEmail = `${secondary.userId}@test.local`- expect(data.some(w => w.email === secondaryEmail)).toBe(true)- })-- it("DELETE /api/agents/:id/access/:userId revokes access", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access/${secondary.userId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)- })-- it("GET /api/agents/:id/access is empty after revoke", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toEqual([])- })-- it("DELETE /api/agents/:id/access/:userId with remove_whitelist=true also removes whitelist", async () => {- // Grant access again first- await tokenRequest(- `/api/agents/${seed.agentId}/access?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ user_id: secondary.userId }),- },- )-- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access/${secondary.userId}?workspace_id=${seed.workspaceId}&remove_whitelist=true`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)-- // Verify whitelist entry removed- const wlRes = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- const wlData = await wlRes.json() as Array<Record<string, unknown>>- const secondaryEmail = `${secondary.userId}@test.local`- expect(wlData.some(w => w.email === secondaryEmail)).toBe(false)- })-- it("DELETE /api/agents/:id/access/nonexistent returns 404", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/access/nonexistent?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(404)- })-})diff --git a/src/web/src/test/e2e/agent-crud.test.ts b/src/web/src/test/e2e/agent-crud.test.tsdeleted file mode 100644index 1e4a80a4d..000000000--- a/src/web/src/test/e2e/agent-crud.test.ts+++ /dev/null@@ -1,146 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sql } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()-})-afterAll(() => cleanupTestData(seed))--const wsHeader = (wsId: string) => ({ "X-Workspace-ID": wsId })--describe("agent CRUD", () => {- let createdAgentId: string-- it("POST /api/agents creates an agent", async () => {- const res = await tokenRequest("/api/agents", seed.machineToken, {- method: "POST",- headers: {- "Content-Type": "application/json",- ...wsHeader(seed.workspaceId),- },- body: JSON.stringify({- name: "E2E Agent",- description: "Created by e2e test",- instructions: "Be helpful",- runtime_id: seed.runtimeId,- }),- })- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.name).toBe("E2E Agent")- expect(data.description).toBe("Created by e2e test")- expect(data.runtime_id).toBe(seed.runtimeId)- createdAgentId = data.id as string- })-- it("GET /api/agents lists agents in workspace", async () => {- const res = await tokenRequest(- `/api/agents?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(Array.isArray(data)).toBe(true)- // Should include both the seeded agent and the created agent- expect(data.some(a => a.id === createdAgentId)).toBe(true)- expect(data.some(a => a.id === seed.agentId)).toBe(true)- })-- it("GET /api/agents/:id returns single agent", async () => {- const res = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBe(createdAgentId)- expect(data.name).toBe("E2E Agent")- })-- it("PATCH /api/agents/:id updates agent", async () => {- const res = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "E2E Agent Updated", description: "Updated" }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.name).toBe("E2E Agent Updated")- expect(data.description).toBe("Updated")- })-- it("PATCH /api/agents/:id persists runtime_config.model", async () => {- const patchRes = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ runtime_config: { model: "test-model" } }),- },- )- expect(patchRes.status).toBe(200)-- const getRes = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(getRes.status).toBe(200)- const data = await getRes.json() as Record<string, unknown>- expect((data.runtime_config as Record<string, unknown>)?.model).toBe("test-model")- })-- it("DELETE /api/agents/:id deletes agent", async () => {- const res = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)-- // Verify it's gone- const getRes = await tokenRequest(- `/api/agents/${createdAgentId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(getRes.status).toBe(404)- })-- it("GET /api/agents/:id returns 404 for nonexistent", async () => {- const res = await tokenRequest(- `/api/agents/nonexistent?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(404)- })-- it("POST /api/agents rejects missing name", async () => {- const res = await tokenRequest("/api/agents", seed.machineToken, {- method: "POST",- headers: {- "Content-Type": "application/json",- ...wsHeader(seed.workspaceId),- },- body: JSON.stringify({ runtime_id: seed.runtimeId }),- })- expect(res.status).toBe(400)- })-- it("POST /api/agents rejects missing runtime_id", async () => {- const res = await tokenRequest("/api/agents", seed.machineToken, {- method: "POST",- headers: {- "Content-Type": "application/json",- ...wsHeader(seed.workspaceId),- },- body: JSON.stringify({ name: "No Runtime" }),- })- expect(res.status).toBe(400)- })-})diff --git a/src/web/src/test/e2e/agent-email-accounts.test.ts b/src/web/src/test/e2e/agent-email-accounts.test.tsdeleted file mode 100644index 35fae47e2..000000000--- a/src/web/src/test/e2e/agent-email-accounts.test.ts+++ /dev/null@@ -1,119 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"--let seed: TestSeed-let accountId: string--beforeAll(() => {- seed = seedTestData()-})--afterAll(() => {- if (accountId) {- sqlRun(`DELETE FROM agent_email_account WHERE id = ?`, accountId)- }- cleanupTestData(seed)-})--describe("GET /api/agents/[id]/email-accounts", () => {- it("returns empty list when no accounts configured", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/email-accounts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as unknown[]- expect(Array.isArray(data)).toBe(true)- expect(data).toHaveLength(0)- })-- it("returns 404 for non-existent agent", async () => {- const res = await tokenRequest(- `/api/agents/ag_nonexistent_xyz/email-accounts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(404)- })-})--describe("POST /api/agents/[id]/email-accounts", () => {- it("creates an email account", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/email-accounts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- emailAddress: "[email protected]",- displayName: "Test Account",- imapHost: "imap.example.com",- imapPort: 993,- imapUsername: "[email protected]",- imapPassword: "password123",- imapTls: true,- smtpHost: "smtp.example.com",- smtpPort: 587,- smtpUsername: "[email protected]",- smtpPassword: "password123",- smtpTls: 1,- pollIntervalSeconds: 60,- }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBeTruthy()- expect(data.email_address).toBe("[email protected]")- expect(data.display_name).toBe("Test Account")- expect(data.imap_host).toBe("imap.example.com")- expect(data.smtp_host).toBe("smtp.example.com")- expect(data.status).toBeTruthy()- accountId = data.id as string- })-- it("lists the created account", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/email-accounts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.length).toBeGreaterThanOrEqual(1)- expect(data.some(a => a.id === accountId)).toBe(true)- })-- it("returns 404 for non-existent agent on create", async () => {- const res = await tokenRequest(- `/api/agents/ag_nonexistent_xyz/email-accounts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- emailAddress: "[email protected]",- displayName: "Fail",- imapHost: "imap.example.com",- imapPort: 993,- imapUsername: "[email protected]",- imapPassword: "pass",- imapTls: true,- smtpHost: "smtp.example.com",- smtpPort: 587,- smtpUsername: "[email protected]",- smtpPassword: "pass",- smtpTls: 1,- pollIntervalSeconds: 60,- }),- },- )- expect(res.status).toBe(404)- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/agents/${seed.agentId}/email-accounts?workspace_id=${seed.workspaceId}`,- )- expect(res.status).toBe(401)- })-})diff --git a/src/web/src/test/e2e/agent-link-upsert.test.ts b/src/web/src/test/e2e/agent-link-upsert.test.tsdeleted file mode 100644index 49776727c..000000000--- a/src/web/src/test/e2e/agent-link-upsert.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"-import { nanoid } from "nanoid"--let seed: TestSeed-let targetAgentId: string--beforeAll(() => {- seed = seedTestData()- // Second agent in the same workspace, owned by the same user, to link against.- targetAgentId = `ag_${nanoid()}`- const now = new Date().toISOString()- sqlRun(- `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,- targetAgentId, seed.workspaceId, "Target Agent", seed.runtimeId, `target-${nanoid(6).toLowerCase()}`, seed.userId, now, now,- )-})--afterAll(() => {- sqlRun(- `DELETE FROM agent_link WHERE (source_agent_id = ? AND target_agent_id = ?) OR (source_agent_id = ? AND target_agent_id = ?)`,- seed.agentId, targetAgentId, targetAgentId, seed.agentId,- )- sqlRun(`DELETE FROM agent WHERE id = ?`, targetAgentId)- cleanupTestData(seed)-})--function upsert(body: unknown) {- return tokenRequest(- `/api/agent-links?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}`,- seed.machineToken,- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(body),- },- )-}--describe("PUT /api/agent-links (upsert)", () => {- it("creates the link on first call (201, created:true)", async () => {- const res = await upsert({ target_agent_id: targetAgentId, instruction: "first instruction" })- expect(res.status).toBe(201)- const data = await res.json() as { created: boolean; instruction: string; source_agent_id: string; target_agent_id: string }- expect(data.created).toBe(true)- expect(data.instruction).toBe("first instruction")- const ids = [data.source_agent_id, data.target_agent_id]- expect(ids).toContain(seed.agentId)- expect(ids).toContain(targetAgentId)- })-- it("replaces the instruction on second call (200, created:false) — single row", async () => {- const res = await upsert({ target_agent_id: targetAgentId, instruction: "second instruction" })- expect(res.status).toBe(200)- const data = await res.json() as { created: boolean; instruction: string }- expect(data.created).toBe(false)- expect(data.instruction).toBe("second instruction")-- // Exactly one row for this pair (canonicalization held); instruction replaced.- const list = await tokenRequest(- `/api/agent-links?workspace_id=${seed.workspaceId}&limit=500`,- seed.machineToken,- { method: "GET" },- )- const links = await list.json() as Array<{ source_agent_id: string; target_agent_id: string; instruction: string }>- const forPair = links.filter((l) =>- (l.source_agent_id === seed.agentId && l.target_agent_id === targetAgentId) ||- (l.source_agent_id === targetAgentId && l.target_agent_id === seed.agentId),- )- expect(forPair).toHaveLength(1)- expect(forPair[0].instruction).toBe("second instruction")- })-- it("returns 400 on self-link", async () => {- const res = await upsert({ target_agent_id: seed.agentId, instruction: "x" })- expect(res.status).toBe(400)- })-- it("returns 404 for a target not in the workspace", async () => {- const res = await upsert({ target_agent_id: "ag_nonexistent_xyz", instruction: "x" })- expect(res.status).toBe(404)- })-- it("returns 400 without agentId query param", async () => {- const res = await tokenRequest(- `/api/agent-links?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ target_agent_id: targetAgentId, instruction: "x" }),- },- )- expect(res.status).toBe(400)- })-})diff --git a/src/web/src/test/e2e/agent-pin.test.ts b/src/web/src/test/e2e/agent-pin.test.tsdeleted file mode 100644index 3f98fe605..000000000--- a/src/web/src/test/e2e/agent-pin.test.ts+++ /dev/null@@ -1,94 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()-}, 60_000)--afterAll(() => {- cleanupTestData(seed)-}, 60_000)--describe("agent pin", () => {- it("GET /api/agents/pins returns empty list initially", async () => {- const res = await tokenRequest(- `/api/agents/pins?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { pins: Array<Record<string, unknown>>; sidebar_order: Array<Record<string, unknown>> }- expect(data.pins).toEqual([])- })-- it("POST /api/agents/:id/pin pins an agent", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/pin?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.pinned).toBe(true)- })-- it("POST /api/agents/:id/pin again returns 200 (already pinned)", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/pin?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.pinned).toBe(true)- })-- it("GET /api/agents/pins returns the pinned agent", async () => {- const res = await tokenRequest(- `/api/agents/pins?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { pins: Array<Record<string, unknown>>; sidebar_order: Array<Record<string, unknown>> }- expect(data.pins).toHaveLength(1)- expect(data.pins[0].agent_id).toBe(seed.agentId)- })-- it("DELETE /api/agents/:id/pin unpins the agent", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/pin?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)- })-- it("GET /api/agents/pins returns empty after unpin", async () => {- const res = await tokenRequest(- `/api/agents/pins?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { pins: Array<Record<string, unknown>>; sidebar_order: Array<Record<string, unknown>> }- expect(data.pins).toEqual([])- })-- it("DELETE /api/agents/:id/pin is idempotent (unpin again)", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/pin?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)- })-- it("POST /api/agents/:id/pin returns 404 for nonexistent agent", async () => {- const res = await tokenRequest(- `/api/agents/nonexistent/pin?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(404)- })-})diff --git a/src/web/src/test/e2e/agent-recruit.test.ts b/src/web/src/test/e2e/agent-recruit.test.tsdeleted file mode 100644index ac6709db2..000000000--- a/src/web/src/test/e2e/agent-recruit.test.ts+++ /dev/null@@ -1,98 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"--let seed: TestSeed-let recruitedAgentId: string--beforeAll(() => {- seed = seedTestData()-})--afterAll(() => {- if (recruitedAgentId) {- sqlRun(`DELETE FROM agent_task_queue WHERE agent_id = ?`, recruitedAgentId)- sqlRun(`DELETE FROM message WHERE conversation_id IN (SELECT id FROM conversation WHERE agent_id = ?)`, recruitedAgentId)- sqlRun(`DELETE FROM conversation WHERE agent_id = ?`, recruitedAgentId)- sqlRun(`DELETE FROM agent_whitelist WHERE agent_id = ?`, recruitedAgentId)- sqlRun(`DELETE FROM agent_link WHERE (source_agent_id = ? AND target_agent_id = ?) OR (source_agent_id = ? AND target_agent_id = ?)`, seed.agentId, recruitedAgentId, recruitedAgentId, seed.agentId)- sqlRun(`DELETE FROM agent WHERE id = ?`, recruitedAgentId)- }- cleanupTestData(seed)-})--describe("POST /api/agents/recruit", () => {- it("recruits a new agent and returns agent + link", async () => {- const res = await tokenRequest(- `/api/agents/recruit?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: "RecruitedBot",- description: "A test recruited agent",- instructions: "You are a helper bot",- relationship: "Helps with testing",- }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as { agent: Record<string, unknown>; link: Record<string, unknown> }- expect(data.agent).toBeTruthy()- expect(data.agent.name).toBe("RecruitedBot")- expect(data.agent.email).toBeTruthy()- expect(data.link).toBeTruthy()- expect(data.link.source_agent_id).toBeTruthy()- expect(data.link.target_agent_id).toBeTruthy()- const linkAgentIds = [data.link.source_agent_id, data.link.target_agent_id]- expect(linkAgentIds).toContain(data.agent.id)- expect(linkAgentIds).toContain(seed.agentId)- recruitedAgentId = data.agent.id as string- })-- it("returns 400 without agentId query param", async () => {- const res = await tokenRequest(- `/api/agents/recruit?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: "ShouldFail",- instructions: "test",- relationship: "test",- }),- },- )- expect(res.status).toBe(400)- })-- it("returns 404 for non-existent calling agent", async () => {- const res = await tokenRequest(- `/api/agents/recruit?workspace_id=${seed.workspaceId}&agentId=ag_nonexistent_xyz`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: "ShouldFail",- instructions: "test",- relationship: "test",- }),- },- )- expect(res.status).toBe(404)- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/agents/recruit?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}`,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "NoAuth", instructions: "x", relationship: "x" }),- },- )- expect(res.status).toBe(401)- })-})diff --git a/src/web/src/test/e2e/artifacts.test.ts b/src/web/src/test/e2e/artifacts.test.tsdeleted file mode 100644index d4c66f5bc..000000000--- a/src/web/src/test/e2e/artifacts.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let conversationId: string-let artifactId: string--beforeAll(async () => {- seed = seedTestData()-- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const convData = await convRes.json() as { id: string }- conversationId = convData.id-})--afterAll(() => cleanupTestData(seed))--describe("POST /api/artifacts/upload", () => {- it("uploads a file and returns artifact metadata", async () => {- const fileContent = new Blob(["hello world"], { type: "text/plain" })- const formData = new FormData()- formData.append("file", new File([fileContent], "test.txt", { type: "text/plain" }))- formData.append("conversation_id", conversationId)-- const res = await tokenRequest(- `/api/artifacts/upload?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: formData,- },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBeTruthy()- expect(data.filename).toBe("test.txt")- expect(data.content_type).toBe("text/plain")- expect(data.size).toBe(11)- expect(data.conversation_id).toBe(conversationId)- artifactId = data.id as string- })-- it("rejects upload without file", async () => {- const formData = new FormData()- formData.append("conversation_id", conversationId)-- const res = await tokenRequest(- `/api/artifacts/upload?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: formData,- },- )- expect(res.status).toBe(400)- })-- it("rejects upload without conversation_id", async () => {- const fileContent = new Blob(["data"], { type: "text/plain" })- const formData = new FormData()- formData.append("file", new File([fileContent], "test2.txt", { type: "text/plain" }))-- const res = await tokenRequest(- `/api/artifacts/upload?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: formData,- },- )- expect(res.status).toBe(400)- })-- it("rejects upload for non-existent conversation", async () => {- const fileContent = new Blob(["data"], { type: "text/plain" })- const formData = new FormData()- formData.append("file", new File([fileContent], "test3.txt", { type: "text/plain" }))- formData.append("conversation_id", "conv_nonexistent_xyz")-- const res = await tokenRequest(- `/api/artifacts/upload?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: formData,- },- )- expect(res.status).toBe(404)- })-})--describe("GET /api/artifacts", () => {- it("lists artifacts for a conversation", async () => {- const res = await tokenRequest(- `/api/artifacts?workspace_id=${seed.workspaceId}&conversation_id=${conversationId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(Array.isArray(data)).toBe(true)- expect(data.length).toBeGreaterThanOrEqual(1)- expect(data.some(a => a.id === artifactId)).toBe(true)- })-- it("returns 400 without conversation_id", async () => {- const res = await tokenRequest(- `/api/artifacts?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(400)- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/artifacts?workspace_id=${seed.workspaceId}&conversation_id=${conversationId}`,- )- expect(res.status).toBe(401)- })-})diff --git a/src/web/src/test/e2e/auth.test.ts b/src/web/src/test/e2e/auth.test.tsindex f8a6a72bf..2aea3150b 100644--- a/src/web/src/test/e2e/auth.test.ts+++ b/src/web/src/test/e2e/auth.test.ts@@ -20,17 +20,16 @@ describe("auth", () => {expect(cookie).toContain("=")})- it("GET /api/me with session cookie returns user profile", async () => {+ it("GET /api/community/users/me/profile with session cookie returns user profile", async () => {const cookie = await signIn(testEmail, testPassword)- const res = await sessionRequest("/api/me", cookie)+ const res = await sessionRequest("/api/community/users/me/profile", cookie)expect(res.status).toBe(200)const data = await res.json() as Record<string, unknown>- expect(data.email).toBe(testEmail)expect(data.name).toBe(testName)})- it("GET /api/me without auth returns 401", async () => {- const res = await fetch(`${APP_URL}/api/me`)+ it("GET /api/community/users/me/profile without auth returns 401", async () => {+ const res = await fetch(`${APP_URL}/api/community/users/me/profile`)expect(res.status).toBe(401)})diff --git a/src/web/src/test/e2e/calendar-fire.test.ts b/src/web/src/test/e2e/calendar-fire.test.tsdeleted file mode 100644index efedf35e7..000000000--- a/src/web/src/test/e2e/calendar-fire.test.ts+++ /dev/null@@ -1,116 +0,0 @@-/**- * Cross-service E2E: Calendar event with past scheduled_at → sweep → task dispatched- * Verifies calendar event promotion creates a task with type=calendar_event.- * Refs: #190- *- * NOTE: The sweep route throttles calendar promotion (30s via KV). Tests are- * structured to insert all events before a single sweep call.- */-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sql, sqlQuery } from "@alook/test-utils"--let seed: TestSeed--const eventIds = {- basic: `ce_basic_${randomUUID().slice(0, 8)}`,- triggerCheck: `ce_trig_${randomUUID().slice(0, 8)}`,- recurring: `ce_recur_${randomUUID().slice(0, 8)}`,-}--beforeAll(async () => {- seed = seedTestData()-- const pastTime1 = new Date(Date.now() - 60_000).toISOString()- const pastTime2 = new Date(Date.now() - 120_000).toISOString()- const pastTime3 = new Date(Date.now() - 90_000).toISOString()- const now = new Date().toISOString()-- // Insert all events before sweep (throttle prevents multiple sweep calls)- sql(- `INSERT INTO calendar_event (id, agent_id, workspace_id, title, scheduled_at, created_at, updated_at) VALUES ('${eventIds.basic}', '${seed.agentId}', '${seed.workspaceId}', 'E2E sweep test event', '${pastTime1}', '${now}', '${now}')`,- )- sql(- `INSERT INTO calendar_event (id, agent_id, workspace_id, title, scheduled_at, created_at, updated_at) VALUES ('${eventIds.triggerCheck}', '${seed.agentId}', '${seed.workspaceId}', 'E2E trigger check', '${pastTime2}', '${now}', '${now}')`,- )- sql(- `INSERT INTO calendar_event (id, agent_id, workspace_id, title, scheduled_at, repeat_interval, created_at, updated_at) VALUES ('${eventIds.recurring}', '${seed.agentId}', '${seed.workspaceId}', 'E2E recurring', '${pastTime3}', '1day', '${now}', '${now}')`,- )-- // Small delay for WAL visibility- await new Promise((r) => setTimeout(r, 300))-- // Single sweep call processes all events- const sweepRes = await tokenRequest(- `/api/daemon/sweep`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId }),- },- )- expect(sweepRes.status).toBe(200)-- // Wait for processing- await new Promise((r) => setTimeout(r, 1500))-})-afterAll(() => cleanupTestData(seed))--describe("cross-service: calendar event fire → task dispatched", () => {- it("past calendar event → sweep → task created with type=calendar_event", () => {- const tasks = sqlQuery<Record<string, unknown>>(- `SELECT * FROM agent_task_queue WHERE agent_id = '${seed.agentId}' AND workspace_id = '${seed.workspaceId}' AND type = 'calendar_event' AND prompt = 'E2E sweep test event'`,- )- expect(tasks.length).toBeGreaterThan(0)- expect(tasks[0].type).toBe("calendar_event")- expect(tasks[0].prompt).toBe("E2E sweep test event")- expect(tasks[0].status).toMatch(/queued|dispatched/)- })-- it("calendar event last_triggered_at is updated after sweep", () => {- const rows = sqlQuery<{ last_triggered_at: string | null }>(- `SELECT last_triggered_at FROM calendar_event WHERE id = '${eventIds.triggerCheck}'`,- )- expect(rows).toHaveLength(1)- expect(rows[0].last_triggered_at).toBeTruthy()- })-- it("recurring event gets next scheduled_at advanced after sweep", () => {- const rows = sqlQuery<{ scheduled_at: string }>(- `SELECT scheduled_at FROM calendar_event WHERE id = '${eventIds.recurring}'`,- )- expect(rows).toHaveLength(1)- const newScheduled = new Date(rows[0].scheduled_at)- // After promotion, recurring event with 1day interval should advance to future- expect(newScheduled.getTime()).toBeGreaterThan(Date.now())- })-- it("already triggered event is not re-triggered on second sweep", async () => {- const countBefore = sqlQuery<{ cnt: number }>(- `SELECT COUNT(*) as cnt FROM agent_task_queue WHERE agent_id = '${seed.agentId}' AND type = 'calendar_event' AND prompt = 'E2E sweep test event'`,- )-- // Wait for throttle to expire (use a fresh workspace seed to bypass)- // Instead, insert a new event with last_triggered_at already set- const alreadyTriggeredId = `ce_done_${randomUUID().slice(0, 8)}`- const now = new Date().toISOString()- const pastTime = new Date(Date.now() - 60_000).toISOString()- sql(- `INSERT INTO calendar_event (id, agent_id, workspace_id, title, scheduled_at, last_triggered_at, created_at, updated_at) VALUES ('${alreadyTriggeredId}', '${seed.agentId}', '${seed.workspaceId}', 'E2E already-triggered', '${pastTime}', '${now}', '${now}', '${now}')`,- )-- // Verify it's not picked up by querying the due events condition directly- const dueRows = sqlQuery<Record<string, unknown>>(- `SELECT * FROM calendar_event WHERE id = '${alreadyTriggeredId}' AND (last_triggered_at IS NULL OR last_triggered_at < scheduled_at)`,- )- // Should NOT match — last_triggered_at > scheduled_at- expect(dueRows).toHaveLength(0)-- // Also verify the original event from test 1 wasn't duplicated- const countAfter = sqlQuery<{ cnt: number }>(- `SELECT COUNT(*) as cnt FROM agent_task_queue WHERE agent_id = '${seed.agentId}' AND type = 'calendar_event' AND prompt = 'E2E sweep test event'`,- )- expect(countAfter[0].cnt).toBe(countBefore[0].cnt)- })-})diff --git a/src/web/src/test/e2e/cli-update.test.ts b/src/web/src/test/e2e/cli-update.test.tsdeleted file mode 100644index 790530a1f..000000000--- a/src/web/src/test/e2e/cli-update.test.ts+++ /dev/null@@ -1,123 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest";-import { randomUUID } from "crypto";-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--let seed: TestSeed;--beforeAll(() => {- seed = seedTestData();-});-afterAll(() => cleanupTestData(seed));--describe("CLI auto-update e2e", () => {- const daemonId = `daemon_upd_${randomUUID().slice(0, 8)}`;- const daemonId2 = `daemon_upd2_${randomUUID().slice(0, 8)}`;-- beforeAll(async () => {- // Register two daemons to avoid 30s misc-throttle conflicts between tests- const res = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId,- device_name: "update-test-machine",- cli_version: "0.0.1",- runtimes: [- { provider: "claude", runtime_mode: "local", version: "4.0" },- ],- }),- });- expect(res.status).toBe(200);-- const res2 = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId2,- device_name: "update-test-machine-2",- cli_version: "0.0.1",- runtimes: [- { provider: "claude", runtime_mode: "local", version: "4.0" },- ],- }),- });- expect(res2.status).toBe(200);- });-- it("POST /api/runtimes/:id/update sets pendingUpdateVersion on machine", async () => {- sqlRun(- `UPDATE machine SET pending_update_version = ? WHERE daemon_id = ? AND workspace_id = ?`, '1.0.0', daemonId, seed.workspaceId- );-- const rows = sqlQuery<{ pending_update_version: string | null }>(- `SELECT pending_update_version FROM machine WHERE daemon_id = ? AND workspace_id = ?`, daemonId, seed.workspaceId- );- expect(rows[0]?.pending_update_version).toBe("1.0.0");- });-- it("poll returns pending_update when version is older", async () => {- const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- daemon_id: daemonId,- cli_version: "0.0.1",- }),- });- expect(res.status).toBe(200);- const data = (await res.json()) as { tasks: unknown[]; pending_update?: { version: string } };- expect(data.pending_update).toEqual({ version: "1.0.0" });-- // Version not satisfied → metadata cli_version must NOT be bumped- const metaRows = sqlQuery<{ cli_version: string | null }>(- `SELECT json_extract(metadata, '$.cli_version') AS cli_version FROM agent_runtime WHERE daemon_id = ? AND workspace_id = ?`, daemonId, seed.workspaceId- );- for (const r of metaRows) {- expect(r.cli_version).toBe("0.0.1");- }- });-- it("poll auto-clears pendingUpdateVersion when cli_version matches", async () => {- // Use a separate daemon to avoid 30s misc-throttle from previous poll- sqlRun(- `UPDATE machine SET pending_update_version = ? WHERE daemon_id = ? AND workspace_id = ?`, '1.0.0', daemonId2, seed.workspaceId- );-- const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- daemon_id: daemonId2,- cli_version: "1.0.0",- }),- });- expect(res.status).toBe(200);- const data = (await res.json()) as { tasks: unknown[]; pending_update?: unknown };- expect(data.pending_update).toBeUndefined();-- const rows = sqlQuery<{ pending_update_version: string | null }>(- `SELECT pending_update_version FROM machine WHERE daemon_id = ? AND workspace_id = ?`, daemonId2, seed.workspaceId- );- expect(rows[0]?.pending_update_version).toBeNull();-- // Runtime metadata cli_version is written back so the version gate clears- const metaRows = sqlQuery<{ cli_version: string | null }>(- `SELECT json_extract(metadata, '$.cli_version') AS cli_version FROM agent_runtime WHERE daemon_id = ? AND workspace_id = ?`, daemonId2, seed.workspaceId- );- expect(metaRows.length).toBeGreaterThan(0);- for (const r of metaRows) {- expect(r.cli_version).toBe("1.0.0");- }- });-- afterAll(() => {- try {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId);- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId);- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId2);- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId2);- } catch { /* ignore */ }- });-});diff --git a/src/web/src/test/e2e/conversation-init.test.ts b/src/web/src/test/e2e/conversation-init.test.tsdeleted file mode 100644index dd6ad9dd8..000000000--- a/src/web/src/test/e2e/conversation-init.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let conversationId: string--beforeAll(async () => {- seed = seedTestData()-- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const convData = await convRes.json() as { id: string }- conversationId = convData.id-- // Send a message to populate conversation- await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Init test message" }),- },- )-})--afterAll(() => cleanupTestData(seed))--describe("GET /api/conversations/[id]/init", () => {- it("returns full conversation initialization data", async () => {- const res = await tokenRequest(- `/api/conversations/${conversationId}/init?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.conversation).toBeTruthy()- expect(data.messages).toBeTruthy()- expect(Array.isArray(data.messages)).toBe(true)- expect(typeof data.has_more_messages).toBe("boolean")- expect(typeof data.has_more_conversations).toBe("boolean")- expect(typeof data.has_more_artifacts).toBe("boolean")- expect(Array.isArray(data.artifacts)).toBe(true)- expect(Array.isArray(data.flagged_message_ids)).toBe(true)- expect(typeof data.cache_valid).toBe("boolean")- expect(typeof data.message_count).toBe("number")- })-- it("returns cache_valid=true when newest_message_id matches", async () => {- // First get the init data to find the newest message id- const firstRes = await tokenRequest(- `/api/conversations/${conversationId}/init?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- const firstData = await firstRes.json() as { messages: Array<{ id: string }>; message_count: number }- const newestMsgId = firstData.messages[0]?.id- const msgCount = firstData.message_count-- if (newestMsgId) {- const res = await tokenRequest(- `/api/conversations/${conversationId}/init?workspace_id=${seed.workspaceId}&newest_message_id=${newestMsgId}&message_count=${msgCount}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { cache_valid: boolean; messages: unknown }- expect(data.cache_valid).toBe(true)- expect(data.messages).toBeNull()- }- })-- it("returns 404 for non-existent conversation", async () => {- const res = await tokenRequest(- `/api/conversations/conv_nonexistent_xyz/init?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(404)- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/conversations/${conversationId}/init?workspace_id=${seed.workspaceId}`,- )- expect(res.status).toBe(401)- })-})diff --git a/src/web/src/test/e2e/conversation.test.ts b/src/web/src/test/e2e/conversation.test.tsdeleted file mode 100644index 65759d52c..000000000--- a/src/web/src/test/e2e/conversation.test.ts+++ /dev/null@@ -1,131 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()-})-afterAll(() => cleanupTestData(seed))--describe("conversations", () => {- let conversationId: string-- it("POST /api/conversations creates a conversation", async () => {- const res = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBeTruthy()- expect(data.agent_id).toBe(seed.agentId)- conversationId = data.id as string- })-- it("GET /api/conversations lists conversations", async () => {- const res = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.some(c => c.id === conversationId)).toBe(true)- })-- it("GET /api/conversations/:id returns conversation", async () => {- const res = await tokenRequest(- `/api/conversations/${conversationId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBe(conversationId)- })-- it("POST /api/conversations/:id/messages creates a message and enqueues task", async () => {- const res = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Hello from e2e test" }),- },- )- // 201 on success, 500 if task enqueue fails (but message still created)- expect([201, 500]).toContain(res.status)- const data = await res.json() as Record<string, unknown>- const msg = data.message as Record<string, unknown>- expect(msg.content).toBe("Hello from e2e test")- expect(msg.role).toBe("user")- })-- it("GET /api/conversations/:id/messages lists messages", async () => {- const res = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const body = await res.json() as { messages: Array<Record<string, unknown>>; has_more: boolean }- expect(body.messages.length).toBeGreaterThanOrEqual(1)- expect(body.messages.some(m => m.content === "Hello from e2e test")).toBe(true)- })-- it("POST /api/conversations/:id/messages auto-titles conversation", async () => {- // Check the conversation now has a title- const res = await tokenRequest(- `/api/conversations/${conversationId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.title).toBeTruthy()- })-- it("DELETE /api/conversations/:id deletes conversation", async () => {- // Create a separate conversation to delete (keep the main one for other tests)- const createRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id } = await createRes.json() as { id: string }-- const deleteRes = await tokenRequest(- `/api/conversations/${id}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(deleteRes.status).toBe(204)-- // Verify it's gone- const getRes = await tokenRequest(- `/api/conversations/${id}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(getRes.status).toBe(404)- })-- it("POST /api/conversations rejects missing agent_id", async () => {- const res = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- },- )- expect(res.status).toBe(400)- })-})diff --git a/src/web/src/test/e2e/daemon-lifecycle.test.ts b/src/web/src/test/e2e/daemon-lifecycle.test.tsdeleted file mode 100644index c19a2bd61..000000000--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts+++ /dev/null@@ -1,171 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlQuery, sqlBatch } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()-})-afterAll(() => cleanupTestData(seed))--describe("daemon lifecycle", () => {- const daemonId = `daemon_e2e_${randomUUID().slice(0, 8)}`- let registeredRuntimeId: string-- it("POST /api/daemon/register creates runtimes and returns workspace_id", async () => {- const res = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId,- device_name: "e2e-machine",- cli_version: "0.1.0-test",- runtimes: [- {- provider: "claude",- runtime_mode: "local",- version: "4.0",- },- ],- }),- })- expect(res.status).toBe(200)- const data = await res.json() as { runtimes: Array<{ id: string }>; workspaceId: string }- expect(data.runtimes).toHaveLength(1)- expect(data.runtimes[0].id).toBeTruthy()- expect(data.workspaceId).toBe(seed.workspaceId)- registeredRuntimeId = data.runtimes[0].id- })-- it("POST /api/daemon/register sets machine last_seen_at (online)", async () => {- const rows = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`- )- expect(rows).toHaveLength(1)- expect(rows[0]?.last_seen_at).toBeTruthy()- })-- it("POST /api/daemon/register is idempotent (upserts)", async () => {- const res = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId,- device_name: "e2e-machine",- cli_version: "0.1.0-test",- runtimes: [- {- provider: "claude",- runtime_mode: "local",- version: "4.1",- },- ],- }),- })- expect(res.status).toBe(200)- const data = await res.json() as { runtimes: Array<{ id: string }> }- // Same runtime ID (upsert by workspace_id + daemon_id + provider)- expect(data.runtimes[0].id).toBe(registeredRuntimeId)- })-- it("register merges metadata (json_patch) instead of replacing", async () => {- // First register sets cli_version- const res1 = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId,- device_name: "e2e-machine",- cli_version: "0.2.0",- runtimes: [{ provider: "claude", runtime_mode: "local", version: "5.0" }],- }),- })- expect(res1.status).toBe(200)-- // Verify cli_version is stored- const rows1 = sqlQuery<{ metadata: string }>(- `SELECT metadata FROM agent_runtime WHERE id = '${registeredRuntimeId}'`- )- const meta1 = JSON.parse(rows1[0]!.metadata)- expect(meta1.cli_version).toBe("0.2.0")- expect(meta1.version).toBe("5.0")-- // Second register without cli_version (simulates activate path)- // We call register with empty cli_version — metadata should preserve cli_version- const res2 = await tokenRequest("/api/daemon/register", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: daemonId,- device_name: "e2e-machine",- cli_version: "",- runtimes: [{ provider: "claude", runtime_mode: "local", version: "5.1" }],- }),- })- expect(res2.status).toBe(200)-- // cli_version should still be preserved via json_patch merge- const rows2 = sqlQuery<{ metadata: string }>(- `SELECT metadata FROM agent_runtime WHERE id = '${registeredRuntimeId}'`- )- const meta2 = JSON.parse(rows2[0]!.metadata)- expect(meta2.cli_version).toBe("0.2.0")- expect(meta2.version).toBe("5.1")- })-- it("POST /api/daemon/tasks/poll updates last_seen_at", async () => {- const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: daemonId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { tasks: unknown[] }- expect(data.tasks).toEqual([])-- // Verify machine last_seen_at was set in DB- const rows = sqlQuery<{ last_seen_at: string }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`- )- expect(rows[0]?.last_seen_at).toBeTruthy()- })-- it("POST /api/daemon/tasks/poll rejects without machine token", async () => {- const APP_URL = process.env.APP_URL ?? "http://localhost:3000"- const res = await fetch(`${APP_URL}/api/daemon/tasks/poll`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: daemonId }),- })- expect(res.status).toBe(401)- })-- it("POST /api/daemon/deregister sets machine offline", async () => {- const res = await tokenRequest("/api/daemon/deregister", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: daemonId }),- })- expect(res.status).toBe(200)-- // Verify machine last_seen_at is null (offline)- const rows = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`- )- expect(rows[0]?.last_seen_at).toBeNull()- })-- afterAll(() => {- try {- sqlBatch([- `DELETE FROM agent_runtime WHERE daemon_id = '${daemonId}'`,- `DELETE FROM machine WHERE daemon_id = '${daemonId}'`,- ])- } catch { /* ignore */ }- })-})diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.tsindex 9f6668af6..0fdae2f23 100644--- a/src/web/src/test/e2e/device-code.test.ts+++ b/src/web/src/test/e2e/device-code.test.ts@@ -121,10 +121,10 @@ describe("device-code-flow", () => {const tokenData = await tokenRes.json() as Record<string, unknown>const accessToken = tokenData.access_token as string- const meRes = await tokenRequest("/api/me", accessToken)+ const meRes = await tokenRequest("/api/community/users/me/profile", accessToken)expect(meRes.status).toBe(200)const me = await meRes.json() as Record<string, unknown>- expect(me.email).toBe(testEmail)+ expect(me.name).toBe(testName)})it("POST /api/auth/device/deny denies authorization and token poll returns access_denied", async () => {@@ -174,119 +174,3 @@ describe("onboard.md", () => {expect(res.headers.get("content-type")).toContain("text/markdown")})})--describe("device-code-flow workspace reuse", () => {- const wsTestEmail = `e2e_dcws_${randomUUID().slice(0, 8)}@test.local`- const wsTestPassword = "TestPassword123!"- let wsCookie: string- let originalWorkspaceId: string-- beforeAll(async () => {- await signUp(wsTestEmail, wsTestPassword, "E2E WS User")- wsCookie = await signIn(wsTestEmail, wsTestPassword)-- // Create a workspace (simulates what the web app does on first visit)- const wsRes = await sessionRequest("/api/workspaces", wsCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Personal", slug: `personal-${randomUUID().slice(0, 8)}` }),- })- expect(wsRes.status).toBe(201)- const wsData = await wsRes.json() as Record<string, unknown>- originalWorkspaceId = wsData.id as string- })-- it("CLI login reuses existing workspace instead of creating a duplicate", async () => {- // Request device code- const codeRes = await fetch(`${APP_URL}/api/auth/device/code`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ client_id: TEST_CLIENT_ID }),- })- expect(codeRes.status).toBe(200)- const codeData = await codeRes.json() as Record<string, unknown>- const dc = codeData.device_code as string- const uc = codeData.user_code as string-- // Claim code to user session- await sessionRequest(`/api/auth/device?user_code=${uc}`, wsCookie)-- // Approve- const approveRes = await sessionRequest("/api/auth/device/approve", wsCookie, {- method: "POST",- headers: { "Content-Type": "application/json", Origin: APP_URL },- body: JSON.stringify({ userCode: uc }),- })- expect(approveRes.status).toBe(200)-- // Wait for polling interval- await new Promise(r => setTimeout(r, 5100))-- // Get token- const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- grant_type: "urn:ietf:params:oauth:grant-type:device_code",- device_code: dc,- client_id: TEST_CLIENT_ID,- }),- })- expect(tokenRes.status).toBe(200)- const tokenData = await tokenRes.json() as Record<string, unknown>- const accessToken = tokenData.access_token as string-- // CLI flow: get existing workspaces (use session cookie — mirrors real CLI which- // uses the session token via bearer() but cookie auth is equivalent here)- const wsListRes = await sessionRequest("/api/workspaces", wsCookie)- const wsList = await wsListRes.json() as { id: string }[]- expect(wsList.length).toBeGreaterThanOrEqual(1)- expect(wsList[0].id).toBe(originalWorkspaceId)-- // Create machine token tied to existing workspace (use Bearer session token)- const mtRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${originalWorkspaceId}`,- accessToken,- { method: "POST", headers: { "Content-Type": "application/json" } },- )- expect(mtRes.status).toBeLessThan(300)- const mtData = await mtRes.json() as Record<string, unknown>- const machineToken = mtData.token as string- expect(machineToken).toBeTruthy()-- // Activate with the machine token (creates machine + runtime, token becomes active)- const activateRes = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: machineToken,- hostname: "e2e-test-host",- runtimes: [{ type: "claude", version: "4.0.0" }],- }),- })- expect(activateRes.status).toBe(200)- const activateBody = await activateRes.json() as Record<string, unknown>- expect(activateBody.workspace_id).toBe(originalWorkspaceId)- expect(activateBody.daemon_id).toBe("e2e-test-host")-- // Verify user still has exactly 1 workspace (activate uses existing workspace from token)- const wsAfterRes = await sessionRequest("/api/workspaces", wsCookie)- const wsAfter = await wsAfterRes.json() as { id: string }[]- expect(wsAfter).toHaveLength(1)- expect(wsAfter[0].id).toBe(originalWorkspaceId)- })-- afterAll(() => {- try {- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, wsTestEmail)- sqlRun(`DELETE FROM machine_token WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, wsTestEmail)- sqlRun(`DELETE FROM agent_runtime WHERE machine_id IN (SELECT id FROM machine WHERE workspace_id = ?)`, originalWorkspaceId)- sqlRun(`DELETE FROM machine WHERE workspace_id = ?`, originalWorkspaceId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, originalWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, originalWorkspaceId)- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, wsTestEmail)- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, wsTestEmail)- sqlRun(`DELETE FROM "user" WHERE email = ?`, wsTestEmail)- } catch { /* ignore cleanup errors */ }- })-})diff --git a/src/web/src/test/e2e/dm-to-broadcast.test.ts b/src/web/src/test/e2e/dm-to-broadcast.test.tsdeleted file mode 100644index ca57feb95..000000000--- a/src/web/src/test/e2e/dm-to-broadcast.test.ts+++ /dev/null@@ -1,118 +0,0 @@-/**- * Cross-service E2E: User DM → Task → Daemon poll+start+complete → broadcast HTTP endpoint- * Verifies the full message-to-broadcast flow via server-side assertions only.- * Refs: #190- */-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { DEV_WS_DO_URL } from "@alook/shared"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let wsAvailable = false--async function checkWsAvailable(): Promise<boolean> {- try {- const res = await fetch(DEV_WS_DO_URL, { method: "GET" })- return res.status < 500- } catch {- return false- }-}--beforeAll(async () => {- seed = seedTestData()- wsAvailable = await checkWsAvailable()-})-afterAll(() => cleanupTestData(seed))--describe("cross-service: DM → task lifecycle → WS broadcast", () => {- let conversationId: string- let taskId: string-- it("user message creates a task", async () => {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- expect(convRes.ok).toBe(true)- const convData = await convRes.json() as { id: string }- conversationId = convData.id-- const msgRes = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "DM broadcast test" }),- },- )- expect(msgRes.ok).toBe(true)- const msgData = await msgRes.json() as { task?: { id: string } | null }- expect(msgData.task).toBeTruthy()- taskId = msgData.task!.id- })-- it("daemon polls and claims the task", async () => {- const pollRes = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 5 }),- },- )- expect(pollRes.status).toBe(200)- const pollData = await pollRes.json() as { tasks: Array<Record<string, unknown>> }- expect(pollData.tasks.length).toBeGreaterThanOrEqual(1)- const claimed = pollData.tasks.find(t => t.id === taskId)- expect(claimed).toBeTruthy()- expect(claimed!.status).toBe("dispatched")- })-- it("daemon starts the task", async () => {- const startRes = await tokenRequest(- `/api/daemon/tasks/${taskId}/start`,- seed.machineToken,- { method: "POST" },- )- expect(startRes.status).toBe(200)- const startData = await startRes.json() as { status: string }- expect(startData.status).toBe("running")- })-- it("daemon completes the task", async () => {- const completeRes = await tokenRequest(- `/api/daemon/tasks/${taskId}/complete`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "Task done", session_id: `sess_${randomUUID().slice(0, 8)}` }),- },- )- expect(completeRes.status).toBe(200)- const completeData = await completeRes.json() as { status: string }- expect(completeData.status).toBe("completed")- })-- it("broadcast HTTP endpoint delivers to connected sessions", async () => {- if (!wsAvailable) return-- const payload = { type: "task.completed", taskId: `test_${randomUUID().slice(0, 8)}`, conversationId }- const broadcastRes = await fetch(`${DEV_WS_DO_URL}/broadcast/user/${seed.userId}`, {- method: "POST",- body: JSON.stringify(payload),- })- expect(broadcastRes.status).toBe(200)- const broadcastData = await broadcastRes.json() as { sent: number }- expect(broadcastData.sent).toBeGreaterThanOrEqual(0)- })-})diff --git a/src/web/src/test/e2e/email.test.ts b/src/web/src/test/e2e/email.test.tsindex 404874466..0233b7fc3 100644--- a/src/web/src/test/e2e/email.test.ts+++ b/src/web/src/test/e2e/email.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery, postEmail, postEmailRaw } from "@alook/test-utils"+import { seedTestData, cleanupTestData, type TestSeed, sqlQuery, postEmail, postEmailRaw } from "@alook/test-utils"let seed: TestSeed@@ -117,235 +117,3 @@ describe("email threading (inbound)", () => {expect(rows[0].references).toBe("")})})--// ─── Folder filtering ───--describe("email folder filtering", () => {- it("GET /api/email?folder=untrust returns only non-whitelisted inbound emails", async () => {- const agentEmail = `${seed.agentEmailHandle}@alook.ai`- const now = new Date().toISOString()- const rejId = `erej_${randomUUID().slice(0, 8)}`- sqlRun(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, rejId, seed.agentId, seed.workspaceId, '[email protected]', agentEmail, 'Untrust folder test', 'emails/fake-rej/raw', 0, 0, '', '', '', now)-- const res = await tokenRequest(- `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=untrust`,- seed.machineToken,- )- expect(res.status).toBe(200)-- const emails = await res.json() as { is_whitelisted: boolean }[]- expect(emails.length).toBeGreaterThan(0)- for (const email of emails) {- expect(email.is_whitelisted).toBe(false)- }- })-- it("GET /api/email?folder=untrust excludes sent emails", async () => {- await tokenRequest(- `/api/email/send?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: seed.agentId,- to: "[email protected]",- subject: "E2E sent email",- htmlBody: "<p>Outbound</p>",- }),- },- )-- const res = await tokenRequest(- `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=untrust`,- seed.machineToken,- )- expect(res.status).toBe(200)-- const emails = await res.json() as { from_email: string; to_email: string }[]- const agentEmail = `${seed.agentEmailHandle}@alook.ai`- for (const email of emails) {- expect(email.from_email).not.toBe(agentEmail)- }- })-- it("GET /api/email?folder=inbox returns only whitelisted inbound emails", async () => {- const res = await tokenRequest(- `/api/email?workspace_id=${seed.workspaceId}&agentId=${seed.agentId}&folder=inbox`,- seed.machineToken,- )- expect(res.status).toBe(200)-- const emails = await res.json() as { direction: string; is_whitelisted: boolean }[]- for (const email of emails) {- expect(email.direction).toBe("inbound")- expect(email.is_whitelisted).toBe(true)- }- })-})--// ─── Send path ───--describe("email send (outbound)", () => {- it("POST /api/email/send → 200 with r2_key and DB record", async () => {- const res = await tokenRequest(- `/api/email/send?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: seed.agentId,- to: "[email protected]",- subject: "E2E send test",- htmlBody: "<p>Hello from e2e</p>",- }),- },- )- expect(res.status).toBe(200)-- const data = await res.json() as Record<string, unknown>- expect(data.r2_key).toBeTruthy()- expect(data.from_email).toBe(`${seed.agentEmailHandle}@alook.ai`)- expect(data.to_email).toBe("[email protected]")- expect(data.subject).toBe("E2E send test")- })-- it("POST /api/email/send with agent missing emailHandle → 400", async () => {- // Create a temporary agent without emailHandle- const tmpAgentId = `ag_tmp_${Date.now()}`- const now = new Date().toISOString()- sqlRun(`INSERT INTO agent (id, workspace_id, name, runtime_id, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, tmpAgentId, seed.workspaceId, 'No Handle Agent', seed.runtimeId, seed.userId, now, now)-- try {- const res = await tokenRequest(- `/api/email/send?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: tmpAgentId,- to: "[email protected]",- subject: "Should fail",- htmlBody: "<p>No handle</p>",- }),- },- )- expect(res.status).toBe(400)- } finally {- sqlRun(`DELETE FROM agent WHERE id = ?`, tmpAgentId)- }- })-- it("POST /api/email/send missing required fields → 400", async () => {- const res = await tokenRequest(- `/api/email/send?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agentId: seed.agentId }),- },- )- expect(res.status).toBe(400)- })-- it("POST /api/email/send with threading → stores message_id, in_reply_to, references", async () => {- const inReplyTo = `<parent-${randomUUID()}@e2e.test>`- const references = `<root-${randomUUID()}@e2e.test> ${inReplyTo}`-- const res = await tokenRequest(- `/api/email/send?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: seed.agentId,- to: "[email protected]",- subject: "E2E reply test",- htmlBody: "<p>Reply body</p>",- inReplyTo,- references,- }),- },- )- expect(res.status).toBe(200)-- const data = await res.json() as Record<string, unknown>- expect(data.message_id).toBeTruthy()- expect(typeof data.message_id).toBe("string")- expect((data.message_id as string).length).toBeGreaterThan(0)- expect(data.in_reply_to).toBe(inReplyTo)- expect(data.references).toBe(references)- })-})--// ─── Thread endpoint ───--describe("email thread", () => {- it("GET /api/email/[id]/thread returns parent chain", async () => {- const agentEmail = `${seed.agentEmailHandle}@alook.ai`- const now = new Date().toISOString()- const parentMsgId = `<thread-parent-${randomUUID()}@e2e.test>`- const childMsgId = `<thread-child-${randomUUID()}@e2e.test>`-- // Insert parent email directly- const parentId = `ep_${randomUUID().slice(0, 12)}`- sqlRun(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, parentId, seed.agentId, seed.workspaceId, '[email protected]', agentEmail, 'Thread parent', 'emails/fake/raw', 1, 0, parentMsgId, '', '', now)-- // Insert child email that replies to parent- const childId = `ec_${randomUUID().slice(0, 12)}`- sqlRun(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", direction, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, childId, seed.agentId, seed.workspaceId, agentEmail, '[email protected]', 'Re: Thread parent', 'emails/fake2/raw', 0, 0, childMsgId, parentMsgId, parentMsgId, 'outbound', now)-- const res = await tokenRequest(- `/api/email/${childId}/thread?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)-- const thread = await res.json() as { id: string; message_id: string }[]- expect(thread.length).toBe(1)- expect(thread[0].id).toBe(parentId)- expect(thread[0].message_id).toBe(parentMsgId)- })-- it("GET /api/email/[id]/thread walks chain and returns empty for root", async () => {- const agentEmail = `${seed.agentEmailHandle}@alook.ai`- const now = new Date().toISOString()-- // Build a chain of 5 emails via individual INSERTs to verify the chain walk works- // (MAX_DEPTH=50 is tested structurally — here we just verify the chain doesn't infinitely loop)- const ids: string[] = []- const mids: string[] = []- for (let i = 0; i < 5; i++) {- ids.push(`echain_${randomUUID().slice(0, 8)}`)- mids.push(`<chain-${i}-${randomUUID().slice(0, 8)}@e2e.test>`)- }-- for (let i = 0; i < 5; i++) {- const irt = i > 0 ? mids[i - 1] : ""- sqlRun(`INSERT INTO emails (id, agent_id, workspace_id, from_email, to_email, subject, r2_key, is_whitelisted, forwarded, message_id, in_reply_to, "references", created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, ids[i], seed.agentId, seed.workspaceId, '[email protected]', agentEmail, `Chain ${i}`, 'emails/fake-chain/raw', 1, 0, mids[i], irt, '', now)- }-- const res = await tokenRequest(- `/api/email/${ids[4]}/thread?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)-- const thread = await res.json() as { id: string }[]- expect(thread.length).toBe(4)- expect(thread[0].id).toBe(ids[0])-- // Root email (ids[0]) has no in_reply_to — thread should be empty- const rootRes = await tokenRequest(- `/api/email/${ids[0]}/thread?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(rootRes.status).toBe(200)- const rootThread = await rootRes.json() as unknown[]- expect(rootThread).toHaveLength(0)- })-})diff --git a/src/web/src/test/e2e/inbox.test.ts b/src/web/src/test/e2e/inbox.test.tsdeleted file mode 100644index 434b43657..000000000--- a/src/web/src/test/e2e/inbox.test.ts+++ /dev/null@@ -1,178 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"--let seed: TestSeed-let conversationId: string-let taskId: string--beforeAll(async () => {- seed = seedTestData()-- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const convData = await convRes.json() as { id: string }- conversationId = convData.id-- const msgRes = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Inbox test message" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- if (msgData.task) {- taskId = msgData.task.id- }-- // Poll, start, and complete the task so it shows up in inbox- await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- })- await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })-- // Post an assistant message so the inbox query can find it- await tokenRequest(- `/api/daemon/tasks/${taskId}/messages`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [{ seq: 1, type: "text", content: "Task done" }],- }),- },- )-- await tokenRequest(`/api/daemon/tasks/${taskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: "sess_inbox_1" }),- })-})--afterAll(() => {- sqlRun(`DELETE FROM conversation_read_state WHERE user_id = ?`, seed.userId)- cleanupTestData(seed)-})--describe("GET /api/inbox/count", () => {- it("returns unread count", async () => {- const res = await tokenRequest(- `/api/inbox/count?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { count: number }- expect(typeof data.count).toBe("number")- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/inbox/count?workspace_id=${seed.workspaceId}`,- )- expect(res.status).toBe(401)- })-})--describe("GET /api/inbox", () => {- it("returns inbox items list", async () => {- const res = await tokenRequest(- `/api/inbox?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { items: unknown[]; has_more: boolean }- expect(Array.isArray(data.items)).toBe(true)- expect(typeof data.has_more).toBe("boolean")- })-- it("respects limit parameter", async () => {- const res = await tokenRequest(- `/api/inbox?workspace_id=${seed.workspaceId}&limit=1`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as { items: unknown[] }- expect(data.items.length).toBeLessThanOrEqual(1)- })-- it("rejects invalid before timestamp", async () => {- const res = await tokenRequest(- `/api/inbox?workspace_id=${seed.workspaceId}&before=not-a-date`,- seed.machineToken,- )- expect(res.status).toBe(400)- })-})--describe("POST /api/inbox/read", () => {- it("marks a conversation as read", async () => {- const res = await tokenRequest(- `/api/inbox/read?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ conversationId }),- },- )- expect(res.status).toBe(204)- })-- it("returns 400 when conversationId is missing", async () => {- const res = await tokenRequest(- `/api/inbox/read?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- },- )- expect(res.status).toBe(400)- })-- it("returns 404 for non-existent conversation", async () => {- const res = await tokenRequest(- `/api/inbox/read?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ conversationId: "conv_nonexistent_xyz" }),- },- )- expect(res.status).toBe(404)- })-})--describe("POST /api/inbox/read-all", () => {- it("marks all conversations as read", async () => {- const res = await tokenRequest(- `/api/inbox/read-all?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(204)- })-- it("rejects unauthenticated request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/inbox/read-all?workspace_id=${seed.workspaceId}`,- { method: "POST" },- )- expect(res.status).toBe(401)- })-})diff --git a/src/web/src/test/e2e/machine-token.test.ts b/src/web/src/test/e2e/machine-token.test.tsdeleted file mode 100644index 059d91ab4..000000000--- a/src/web/src/test/e2e/machine-token.test.ts+++ /dev/null@@ -1,137 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, sessionRequest, tokenRequest, sqlRun, sqlQuery, fetchWithRetry } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()-})-afterAll(() => cleanupTestData(seed))--describe("machine tokens", () => {- it("GET /api/machine-tokens lists tokens (requires workspace header)", async () => {- const res = await tokenRequest(- `/api/machine-tokens?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(Array.isArray(data)).toBe(true)- expect(data.some(t => t.id === seed.machineTokenId)).toBe(true)- })-- it("POST /api/machine-tokens creates a new token", async () => {- const res = await tokenRequest(- `/api/machine-tokens?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "e2e-created" }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.token).toBeTruthy()- expect((data.token as string).startsWith("al_")).toBe(true)- expect(data.name).toBe("e2e-created")-- // Verify the new token works for auth- const meRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${seed.workspaceId}`,- data.token as string,- )- expect(meRes.status).toBe(200)-- // Cleanup: delete the created token- const deleteRes = await tokenRequest(- `/api/machine-tokens/${data.id}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(deleteRes.status).toBe(204)- })-- it("DELETE /api/machine-tokens/:id removes token", async () => {- // Create a token to delete- const createRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "to-delete" }),- },- )- const { id, token: newRawToken } = await createRes.json() as { id: string; token: string }-- const deleteRes = await tokenRequest(- `/api/machine-tokens/${id}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(deleteRes.status).toBe(204)-- // Verify deleted token no longer works- const verifyRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${seed.workspaceId}`,- newRawToken,- )- expect(verifyRes.status).toBe(401)- })-})--describe("machine token activation (decoupled — no workspace creation)", () => {- it("activation sets token to active status and creates machine/runtime rows", async () => {- const tokenId = `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}`- const rawToken = `al_${randomUUID().replace(/-/g, "")}`- const now = new Date().toISOString()- sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, tokenId, seed.userId, seed.workspaceId, rawToken, 'activate-test', 'pending', now)-- const APP_URL = process.env.APP_URL ?? "http://localhost:3000"- const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: rawToken,- hostname: "e2e-activate-machine",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(res.status).toBe(200)- const data = await res.json() as { daemon_id: string; workspace_id: string; runtimes: Array<{ id: string }> }-- expect(data.daemon_id).toBe("e2e-activate-machine")- expect(data.workspace_id).toBe(seed.workspaceId)- expect(data.runtimes.length).toBeGreaterThan(0)-- // Verify DB state- const rows = sqlQuery<{ status: string; hostname: string }>(- `SELECT status, hostname FROM machine_token WHERE id = ?`, tokenId,- )- expect(rows[0]!.status).toBe("active")- expect(rows[0]!.hostname).toBe("e2e-activate-machine")- })-- it("activation rejects already-used token with 409", async () => {- const tokenId = `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}`- const rawToken = `al_${randomUUID().replace(/-/g, "")}`- const now = new Date().toISOString()- sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, tokenId, seed.userId, seed.workspaceId, rawToken, 'active-token', 'active', now)-- const APP_URL = process.env.APP_URL ?? "http://localhost:3000"- const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: rawToken,- hostname: "e2e-rejected",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(res.status).toBe(409)- const data = await res.json() as { error: string }- expect(data.error).toBe("token already used")- })-})diff --git a/src/web/src/test/e2e/meeting-crud.test.ts b/src/web/src/test/e2e/meeting-crud.test.tsdeleted file mode 100644index de3e7bf9d..000000000--- a/src/web/src/test/e2e/meeting-crud.test.ts+++ /dev/null@@ -1,291 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun } from "@alook/test-utils"--let seed: TestSeed-let seedB: TestSeed--beforeAll(() => {- seed = seedTestData()- seedB = seedTestData()-}, 60_000)-afterAll(() => {- sqlRun(`DELETE FROM meeting_session WHERE workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM meeting_session WHERE workspace_id = ?`, seedB.workspaceId)- cleanupTestData(seed)- cleanupTestData(seedB)-}, 60_000)--function meetingReq(path: string, token: string, opts?: RequestInit) {- return tokenRequest(path, token, {- headers: { "Content-Type": "application/json" },- ...opts,- })-}--describe("meeting CRUD", () => {- let meetingId: string-- it("POST /api/agents/:id/meetings creates a scheduled meeting", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/abc-defg-hij",- title: "E2E Standup",- participants: ["[email protected]"],- scheduledAt: "2026-05-01T10:00:00Z",- }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBeTruthy()- expect((data.id as string).startsWith("ms_")).toBe(true)- expect(data.title).toBe("E2E Standup")- expect(data.meeting_url).toBe("https://meet.google.com/abc-defg-hij")- expect(data.status).toBe("scheduled")- expect(data.is_whitelisted).toBe(true)- meetingId = data.id as string- })-- it("POST /api/agents/:id/meetings returns 400 for missing meetingUrl", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({ title: "No URL" }),- },- )- expect(res.status).toBe(400)- })-- it("POST /api/agents/:id/meetings returns 400 for invalid Meet URL", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({ meetingUrl: "https://zoom.us/j/123456" }),- },- )- expect(res.status).toBe(400)- const data = await res.json() as Record<string, unknown>- expect(data.error).toContain("invalid")- })-- it("GET /api/agents/:id/meetings returns list with the created meeting", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(Array.isArray(data)).toBe(true)- expect(data.length).toBeGreaterThanOrEqual(1)- expect(data.some((m) => m.id === meetingId)).toBe(true)- })-- it("GET /api/agents/:id/meetings/:meetingId returns meeting detail", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${meetingId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBe(meetingId)- expect(data.title).toBe("E2E Standup")- expect(data.participants).toEqual(["[email protected]"])- })-- it("GET /api/agents/:id/meetings/:meetingId returns 404 for nonexistent", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/ms_nonexistent?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(404)- })-- it("DELETE /api/agents/:id/meetings/:meetingId removes meeting", async () => {- // Create a second meeting to delete- const createRes = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/del-eted-one",- title: "To Delete",- scheduledAt: "2026-05-02T10:00:00Z",- }),- },- )- const created = await createRes.json() as Record<string, unknown>- const deleteId = created.id as string-- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${deleteId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(200)-- // Verify gone- const getRes = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${deleteId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(getRes.status).toBe(404)- })-})--describe("meeting approve flow", () => {- let pendingId: string-- beforeAll(async () => {- // Create via API (so the record exists in miniflare's D1), then UPDATE status via sqlRun- // to simulate a non-whitelisted ICS meeting (no public API for creating pending meetings).- const createRes = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/pen-ding-one",- title: "Pending Meeting",- scheduledAt: "2026-05-03T10:00:00Z",- }),- },- )- expect(createRes.status).toBe(201)- const created = await createRes.json() as Record<string, unknown>- expect(created.id).toBeTruthy()- pendingId = created.id as string- // Mutate status to 'pending' to simulate a non-whitelisted ICS meeting- sqlRun(`UPDATE meeting_session SET status = 'pending', is_whitelisted = 0 WHERE id = ?`, pendingId)- }, 30_000)-- it("POST /approve transitions pending → scheduled", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${pendingId}/approve?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("scheduled")- })-- it("POST /approve on non-pending returns 400", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${pendingId}/approve?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(400)- const data = await res.json() as Record<string, unknown>- expect(data.error).toContain("pending")- })-})--describe("meeting stop on non-active", () => {- it("POST /stop returns 400 when meeting is scheduled (not active)", async () => {- // Create a scheduled meeting- const createRes = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/sch-edul-one",- title: "Scheduled Only",- scheduledAt: "2026-06-01T10:00:00Z",- }),- },- )- expect(createRes.status).toBe(201)- const created = await createRes.json() as Record<string, unknown>- expect(created.id).toBeTruthy()-- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings/${created.id}/stop?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(400)- const data = await res.json() as Record<string, unknown>- expect(data.error).toContain("not active")- })-})--describe("meeting workspace isolation", () => {- it("GET meetings from workspace B cannot see workspace A meetings", async () => {- const res = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seedB.workspaceId}`,- seedB.machineToken,- )- // Agent doesn't exist in workspace B, so should 404 or return empty- const status = res.status- if (status === 200) {- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toHaveLength(0)- } else {- expect(status).toBe(404)- }- })-- it("DELETE meeting from wrong workspace returns 404", async () => {- // Create in A- const createRes = await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/iso-late-one",- title: "Isolation Test",- scheduledAt: "2026-07-01T10:00:00Z",- }),- },- )- const created = await createRes.json() as Record<string, unknown>-- // Try delete from B- const res = await meetingReq(- `/api/agents/${seedB.agentId}/meetings/${created.id}?workspace_id=${seedB.workspaceId}`,- seedB.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(404)- })-})--describe("meeting in calendar API", () => {- it("GET /api/calendar includes meetings with scheduled_at", async () => {- // Create a meeting with scheduled_at in a known range- await meetingReq(- `/api/agents/${seed.agentId}/meetings?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- body: JSON.stringify({- meetingUrl: "https://meet.google.com/cal-test-one",- title: "Calendar Visible",- scheduledAt: "2026-05-15T14:00:00Z",- }),- },- )-- const res = await meetingReq(- `/api/calendar?workspace_id=${seed.workspaceId}&from=2026-05-01T00:00:00Z&to=2026-05-31T23:59:59Z`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- const meetingItems = data.filter((e) => (e as any)._type === "meeting")- expect(meetingItems.length).toBeGreaterThanOrEqual(1)- expect(meetingItems.some((m) => m.title === "Calendar Visible")).toBe(true)- })-})diff --git a/src/web/src/test/e2e/meeting-flow.test.ts b/src/web/src/test/e2e/meeting-flow.test.tsindex 401ddce05..bd01db949 100644--- a/src/web/src/test/e2e/meeting-flow.test.ts+++ b/src/web/src/test/e2e/meeting-flow.test.ts@@ -1,5 +1,4 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"let seed: TestSeed@@ -19,86 +18,6 @@ function req(path: string, opts?: RequestInit) {})}-describe("meeting claim via poll", () => {- // Use a separate daemon for the claim test to avoid 30s misc-throttle- const claimDaemonId = `daemon_claim_${randomUUID().slice(0, 8)}`-- beforeAll(async () => {- const res = await req("/api/daemon/register", {- method: "POST",- body: JSON.stringify({- workspace_id: seed.workspaceId,- daemon_id: claimDaemonId,- device_name: "claim-test-machine",- cli_version: "0.0.1",- runtimes: [- { provider: "claude", runtime_mode: "local", version: "4.0" },- ],- }),- })- expect(res.status).toBe(200)- })-- afterAll(() => {- try {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, claimDaemonId)- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, claimDaemonId)- } catch { /* ignore */ }- })-- it("poll returns no meetings when none are scheduled", async () => {- const res = await req("/api/daemon/tasks/poll", {- method: "POST",- body: JSON.stringify({ daemon_id: seed.daemonId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { meetings?: unknown[] }- expect(data.meetings).toBeUndefined()- })-- it("poll claims a scheduled meeting within 5-minute window", async () => {- const pastTime = new Date(Date.now() - 60_000).toISOString()- sqlRun(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, scheduled_at, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, 'ms_claim_test', seed.agentId, seed.workspaceId, 'Claim Test', 'https://meet.google.com/abc-defg-hij', 'scheduled', 1, '[]', pastTime, pastTime, pastTime)-- const res = await req("/api/daemon/tasks/poll", {- method: "POST",- body: JSON.stringify({ daemon_id: claimDaemonId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { meetings?: { id: string; meeting_url: string; agent_name: string }[] }- expect(data.meetings).toBeDefined()- expect(data.meetings!.length).toBe(1)- expect(data.meetings![0].id).toBe("ms_claim_test")- expect(data.meetings![0].meeting_url).toBe("https://meet.google.com/abc-defg-hij")- expect(data.meetings![0].agent_name).toBeDefined()- })-- it("does not re-claim already claimed meeting", async () => {- const res = await req("/api/daemon/tasks/poll", {- method: "POST",- body: JSON.stringify({ daemon_id: seed.daemonId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { meetings?: unknown[] }- expect(data.meetings).toBeUndefined()- })-- it("does not claim meetings far in the future", async () => {- const futureTime = new Date(Date.now() + 3600_000).toISOString()- sqlRun(`INSERT INTO meeting_session (id, agent_id, workspace_id, title, meeting_url, status, is_whitelisted, participants, scheduled_at, created_at, updated_at)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, 'ms_future_test', seed.agentId, seed.workspaceId, 'Future Test', 'https://meet.google.com/xyz-wxyz-abc', 'scheduled', 1, '[]', futureTime, futureTime, futureTime)-- const res = await req("/api/daemon/tasks/poll", {- method: "POST",- body: JSON.stringify({ daemon_id: seed.daemonId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { meetings?: unknown[] }- expect(data.meetings).toBeUndefined()- })-})-describe("meeting callback flow", () => {let callbackMeetingId: stringdiff --git a/src/web/src/test/e2e/multi-workspace-register.test.ts b/src/web/src/test/e2e/multi-workspace-register.test.tsdeleted file mode 100644index 1b3ad6525..000000000--- a/src/web/src/test/e2e/multi-workspace-register.test.ts+++ /dev/null@@ -1,161 +0,0 @@-/**- * Regression: Register daemon across multiple workspaces- * Bug pattern: Registering the same daemon_id in workspace B caused workspace A- * to go offline, breaking task routing for existing workspace.- * Refs: #194 (Priority 1)- */-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--let seedA: TestSeed-let seedB: TestSeed-const sharedDaemonId = `daemon_multi_${randomUUID().slice(0, 8)}`--beforeAll(() => {- seedA = seedTestData()- seedB = seedTestData()-})-afterAll(() => {- // Restore agent runtime_id to seed's original runtime before cleanup- // (test may have pointed it to the shared daemon's runtime)- sqlRun(`UPDATE agent SET runtime_id = ? WHERE id = ?`, seedA.runtimeId, seedA.agentId)- // Clean up tasks referencing the shared daemon's runtime- sqlRun(`DELETE FROM agent_task_queue WHERE workspace_id = ?`, seedA.workspaceId)- sqlRun(`DELETE FROM agent_task_queue WHERE workspace_id = ?`, seedB.workspaceId)- // Clean the shared daemon entries- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, sharedDaemonId)- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, sharedDaemonId)- cleanupTestData(seedA)- cleanupTestData(seedB)-})--describe("regression: multi-workspace daemon registration", () => {- it("register daemon in workspace A → machine is online", async () => {- const res = await tokenRequest("/api/daemon/register", seedA.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seedA.workspaceId,- daemon_id: sharedDaemonId,- device_name: "multi-ws-device",- cli_version: "1.0.0",- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],- }),- })- expect(res.status).toBe(200)-- const rows = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedA.workspaceId- )- expect(rows).toHaveLength(1)- expect(rows[0].last_seen_at).toBeTruthy()- })-- it("register same daemon in workspace B → workspace A still online", async () => {- const res = await tokenRequest("/api/daemon/register", seedB.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- workspace_id: seedB.workspaceId,- daemon_id: sharedDaemonId,- device_name: "multi-ws-device",- cli_version: "1.0.0",- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],- }),- })- expect(res.status).toBe(200)-- // Workspace A machine should still be online- const rowsA = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedA.workspaceId- )- expect(rowsA).toHaveLength(1)- expect(rowsA[0].last_seen_at).toBeTruthy()-- // Workspace B machine should also be online- const rowsB = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedB.workspaceId- )- expect(rowsB).toHaveLength(1)- expect(rowsB[0].last_seen_at).toBeTruthy()- })-- it("tasks route correctly to workspace A after workspace B registration", async () => {- // Get runtime ID for workspace A- const runtimesA = sqlQuery<{ id: string }>(- `SELECT id FROM agent_runtime WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedA.workspaceId- )- expect(runtimesA).toHaveLength(1)- const runtimeIdA = runtimesA[0].id-- // Update agent A to use this runtime- sqlRun(`UPDATE agent SET runtime_id = ? WHERE id = ?`, runtimeIdA, seedA.agentId)-- // Create a task in workspace A- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seedA.workspaceId}`,- seedA.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seedA.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seedA.workspaceId}`,- seedA.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Route to workspace A" }),- },- )- expect(msgRes.status).toBe(201)- const msgData = await msgRes.json() as { task?: { id: string } | null }- expect(msgData.task).toBeTruthy()-- // Poll from workspace A daemon to claim the task- const pollRes = await tokenRequest(`/api/daemon/tasks/poll`, seedA.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: sharedDaemonId, max_tasks: 5 }),- })- expect(pollRes.status).toBe(200)- const pollData = await pollRes.json() as { tasks: Array<Record<string, unknown>> }- expect(pollData.tasks.length).toBeGreaterThanOrEqual(1)- const claimed = pollData.tasks.find(t => t.id === msgData.task!.id)- expect(claimed).toBeTruthy()- expect(claimed!.prompt).toBe("Route to workspace A")-- // Cleanup: complete the task- await tokenRequest(`/api/daemon/tasks/${msgData.task!.id}/start`, seedA.machineToken, { method: "POST" })- await tokenRequest(`/api/daemon/tasks/${msgData.task!.id}/complete`, seedA.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: "sess_multi" }),- })- })-- it("deregister from workspace B does NOT affect workspace A", async () => {- await tokenRequest("/api/daemon/deregister", seedB.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: sharedDaemonId }),- })-- // Workspace B offline- const rowsB = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedB.workspaceId- )- expect(rowsB[0]?.last_seen_at).toBeNull()-- // Workspace A still online- const rowsA = sqlQuery<{ last_seen_at: string | null }>(- `SELECT last_seen_at FROM machine WHERE daemon_id = ? AND workspace_id = ?`, sharedDaemonId, seedA.workspaceId- )- expect(rowsA[0]?.last_seen_at).toBeTruthy()- })-})diff --git a/src/web/src/test/e2e/onboard-flow.test.ts b/src/web/src/test/e2e/onboard-flow.test.tsdeleted file mode 100644index f3fa91e8e..000000000--- a/src/web/src/test/e2e/onboard-flow.test.ts+++ /dev/null@@ -1,165 +0,0 @@-import { describe, it, expect, beforeAll } from "vitest"-import { randomUUID } from "crypto"-import { signUp, signIn, sessionRequest, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--const APP_URL = process.env.APP_URL ?? "http://localhost:3000"-const TEST_CLIENT_ID = "e2e-test-client"--async function deviceCodeLogin(sessionCookie: string): Promise<string> {- const codeRes = await fetch(`${APP_URL}/api/auth/device/code`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ client_id: TEST_CLIENT_ID }),- })- const codeData = await codeRes.json() as { device_code: string; user_code: string }-- await sessionRequest(`/api/auth/device?user_code=${codeData.user_code}`, sessionCookie)- await sessionRequest("/api/auth/device/approve", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json", Origin: APP_URL },- body: JSON.stringify({ userCode: codeData.user_code }),- })-- await new Promise(r => setTimeout(r, 5100))-- const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- grant_type: "urn:ietf:params:oauth:grant-type:device_code",- device_code: codeData.device_code,- client_id: TEST_CLIENT_ID,- }),- })- const tokenData = await tokenRes.json() as { access_token: string }- return tokenData.access_token-}--describe("onboard flow — simplified model", () => {-- // Scenario 1: New user → create workspace → get token → activate → runtimes available- describe("Scenario 1: New user complete onboard flow", () => {- const email = `e2e_onboard_new_${randomUUID().slice(0, 8)}@test.local`- const password = "TestPass123!"- let sessionCookie: string- let accessToken: string- let workspaceId: string- let machineToken: string-- beforeAll(async () => {- await signUp(email, password, "E2E New User")- sessionCookie = await signIn(email, password)- })-- it("login via device code auth stores session token", async () => {- accessToken = await deviceCodeLogin(sessionCookie)- expect(accessToken).toBeTruthy()- const meRes = await tokenRequest("/api/me", accessToken)- expect(meRes.status).toBe(200)- })-- it("new user has no workspaces initially", async () => {- const wsRes = await sessionRequest("/api/workspaces", sessionCookie)- const workspaces = await wsRes.json() as Array<{ id: string }>- expect(workspaces).toHaveLength(0)- })-- it("create workspace", async () => {- const res = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Personal", slug: `e2e-${randomUUID().slice(0, 8)}` }),- })- expect(res.status).toBe(201)- const body = await res.json() as { id: string }- workspaceId = body.id- expect(workspaceId).toBeTruthy()- })-- it("create machine token for workspace", async () => {- const res = await sessionRequest(- `/api/machine-tokens?workspace_id=${workspaceId}`,- sessionCookie,- { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },- )- expect(res.status).toBe(201)- const body = await res.json() as { token: string; status: string }- machineToken = body.token- expect(body.status).toBe("pending")- })-- it("activate creates machine + runtime rows", async () => {- const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: machineToken,- hostname: "E2EMachine.local",- runtimes: [{ type: "claude", version: "4.0.0" }],- }),- })- expect(res.status).toBe(200)- const body = await res.json() as { workspace_id: string; runtimes: Array<{ id: string }> }- expect(body.workspace_id).toBe(workspaceId)- expect(body.runtimes.length).toBeGreaterThan(0)- })-- it("runtimes are now available for the workspace", async () => {- const res = await sessionRequest(`/api/runtimes?workspace_id=${workspaceId}`, sessionCookie)- expect(res.status).toBe(200)- const runtimes = await res.json() as Array<{ id: string; status: string }>- expect(runtimes.length).toBeGreaterThan(0)- })- })-- // Scenario 2: Existing user, already has workspace with agents- describe("Scenario 2: Existing user adds new workspace", () => {- const email = `e2e_onboard_exist_${randomUUID().slice(0, 8)}@test.local`- const password = "TestPass123!"- let sessionCookie: string- let existingWorkspaceId: string- let newWorkspaceId: string-- beforeAll(async () => {- await signUp(email, password, "E2E Existing User")- sessionCookie = await signIn(email, password)-- const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Existing", slug: `e2e-exist-${randomUUID().slice(0, 8)}` }),- })- const ws = await wsRes.json() as { id: string }- existingWorkspaceId = ws.id- })-- it("can create a second workspace", async () => {- const res = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Second WS", slug: `e2e-new-${randomUUID().slice(0, 8)}` }),- })- expect(res.status).toBe(201)- const body = await res.json() as { id: string }- newWorkspaceId = body.id- })-- it("token for new workspace can be activated independently", async () => {- const tokenRes = await sessionRequest(- `/api/machine-tokens?workspace_id=${newWorkspaceId}`,- sessionCookie,- { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },- )- const { token } = await tokenRes.json() as { token: string }-- const activateRes = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ token, hostname: "Machine2.local", runtimes: [{ type: "claude", version: "4.0" }] }),- })- expect(activateRes.status).toBe(200)- const body = await activateRes.json() as { workspace_id: string }- expect(body.workspace_id).toBe(newWorkspaceId)- })- })-})diff --git a/src/web/src/test/e2e/skill-sync.test.ts b/src/web/src/test/e2e/skill-sync.test.tsdeleted file mode 100644index 78eb36dbd..000000000--- a/src/web/src/test/e2e/skill-sync.test.ts+++ /dev/null@@ -1,140 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlQuery, sqlRun } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => { seed = seedTestData() })-afterAll(() => {- sqlRun(`DELETE FROM agent_skill WHERE workspace_id = ?`, seed.workspaceId)- cleanupTestData(seed)-})--describe("POST /api/daemon/skills/sync", () => {- it("syncs global skills (scope=global)", async () => {- const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "global",- runtime: "claude",- skills: [- { name: "test-skill-1", description: "Test skill one" },- { name: "test-skill-2", description: "Test skill two" },- ],- }),- })- expect(res.status).toBe(200)- const data = await res.json()- expect(data.status).toBe("ok")-- const rows = sqlQuery<{ name: string; agent_id: string | null }>(- `SELECT name, agent_id FROM agent_skill WHERE workspace_id = ? AND runtime = ? AND agent_id IS NULL ORDER BY name`, seed.workspaceId, 'claude'- )- expect(rows).toHaveLength(2)- expect(rows[0]!.name).toBe("test-skill-1")- expect(rows[0]!.agent_id).toBeNull()- })-- it("syncs agent-scoped skills (scope=agent)", async () => {- const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "agent",- runtime: "claude",- agent_id: seed.agentId,- skills: [- { name: "agent-skill-1", description: "Agent specific" },- ],- }),- })- expect(res.status).toBe(200)-- const rows = sqlQuery<{ name: string; agent_id: string }>(- `SELECT name, agent_id FROM agent_skill WHERE workspace_id = ? AND agent_id = ?`, seed.workspaceId, seed.agentId- )- expect(rows).toHaveLength(1)- expect(rows[0]!.name).toBe("agent-skill-1")- expect(rows[0]!.agent_id).toBe(seed.agentId)- })-- it("re-sync replaces old skills (idempotent)", async () => {- const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "global",- runtime: "claude",- skills: [- { name: "updated-skill", description: "Replaced" },- ],- }),- })- expect(res.status).toBe(200)-- const rows = sqlQuery<{ name: string }>(- `SELECT name FROM agent_skill WHERE workspace_id = ? AND runtime = ? AND agent_id IS NULL`, seed.workspaceId, 'claude'- )- expect(rows).toHaveLength(1)- expect(rows[0]!.name).toBe("updated-skill")- })-- it("returns 400 when agent scope missing agent_id", async () => {- const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "agent",- runtime: "claude",- skills: [{ name: "x", description: "" }],- }),- })- expect(res.status).toBe(400)- })-- it("FK constraint: agent-scoped sync with invalid agent_id fails", async () => {- const res = await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "agent",- runtime: "claude",- agent_id: "ag_nonexistent_id_12345",- skills: [{ name: "bad-skill", description: "" }],- }),- })- expect(res.status).toBeGreaterThanOrEqual(400)- })-})--describe("GET /api/agents/[id]/skills", () => {- it("returns combined global + agent skills", async () => {- await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "global",- runtime: "claude",- skills: [{ name: "global-one", description: "G" }],- }),- })- await tokenRequest("/api/daemon/skills/sync", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- scope: "agent",- runtime: "claude",- agent_id: seed.agentId,- skills: [{ name: "agent-one", description: "A" }],- }),- })-- const rows = sqlQuery<{ name: string }>(- `SELECT name FROM agent_skill WHERE workspace_id = ? AND runtime = ? AND (agent_id IS NULL OR agent_id = ?) ORDER BY name`, seed.workspaceId, 'claude', seed.agentId- )- expect(rows.length).toBeGreaterThanOrEqual(2)- const names = rows.map(r => r.name)- expect(names).toContain("global-one")- expect(names).toContain("agent-one")- })-})diff --git a/src/web/src/test/e2e/task-lifecycle.test.ts b/src/web/src/test/e2e/task-lifecycle.test.tsdeleted file mode 100644index cb733ba45..000000000--- a/src/web/src/test/e2e/task-lifecycle.test.ts+++ /dev/null@@ -1,589 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let conversationId: string-let taskId: string--beforeAll(async () => {- seed = seedTestData()-- // Create a conversation- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const convData = await convRes.json() as { id: string }- conversationId = convData.id-- // Send a message to enqueue a task- const msgRes = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Run the e2e tests" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- if (msgData.task) {- taskId = msgData.task.id- }-})--afterAll(() => cleanupTestData(seed))--describe("task lifecycle", () => {- it("message enqueue creates a task", () => {- expect(taskId).toBeTruthy()- })-- it("POST /api/daemon/tasks/poll claims the task", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as { tasks: Array<Record<string, unknown>> }- expect(data.tasks).toHaveLength(1)- expect(data.tasks[0].id).toBe(taskId)- expect(data.tasks[0].status).toBe("dispatched")- expect(data.tasks[0].prompt).toBe("Run the e2e tests")- expect(data.tasks[0].context_key).toBe(conversationId)- // Poll response includes agent data- expect(data.tasks[0].agent).toBeTruthy()- const agent = data.tasks[0].agent as Record<string, unknown>- expect(agent.name).toBe("Test Agent")- })-- it("POST /api/daemon/tasks/:id/start marks task as running", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${taskId}/start`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("running")- expect(data.started_at).toBeTruthy()- })-- it("POST /api/daemon/tasks/:id/messages stores messages", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${taskId}/messages`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- messages: [- { seq: 1, type: "text", content: "Running tests..." },- { seq: 2, type: "tool", tool: "bash", content: "pnpm test", output: "All tests passed" },- ],- }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as { status: string }- expect(data.status).toBe("ok")- })-- it("GET /api/daemon/tasks/:id/messages returns stored messages", async () => {- let data: Array<Record<string, unknown>> = []- for (let attempt = 0; attempt < 5; attempt++) {- const res = await tokenRequest(- `/api/daemon/tasks/${taskId}/messages`,- seed.machineToken,- )- expect(res.status).toBe(200)- data = await res.json() as Array<Record<string, unknown>>- if (data.length >= 2) break- await new Promise(r => setTimeout(r, 200))- }- expect(data.length).toBeGreaterThanOrEqual(2)- expect(data.some(m => m.content === "Running tests...")).toBe(true)- expect(data.some(m => m.type === "tool")).toBe(true)- })-- it("POST /api/daemon/tasks/:id/complete marks task complete", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${taskId}/complete`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- output: "All tests passed",- session_id: "sess_test_123",- }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("completed")- expect(data.completed_at).toBeTruthy()- })-- it("GET /api/tasks/:id returns task (workspace auth)", async () => {- const res = await tokenRequest(- `/api/tasks/${taskId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBe(taskId)- expect(data.status).toBe("completed")- })-- it("poll returns empty tasks when nothing queued", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as { tasks: unknown[] }- expect(data.tasks).toEqual([])- })-})--describe("context_key resume contract", () => {- let conv2Id: string- let task2Id: string-- it("same conversation produces same context_key (DM resume)", async () => {- // Complete the first task from the main beforeAll- // (already completed above in the lifecycle tests)-- // Send another message in the SAME conversation- const msgRes = await tokenRequest(- `/api/conversations/${conversationId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Second message same conv" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- expect(msgData.task).toBeTruthy()- task2Id = msgData.task!.id-- // Poll to claim- const pollRes = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- const pollData = await pollRes.json() as { tasks: Array<Record<string, unknown>> }- expect(pollData.tasks).toHaveLength(1)- // Same conversation → same context_key- expect(pollData.tasks[0].context_key).toBe(conversationId)-- // Clean up: start + complete this task- await tokenRequest(`/api/daemon/tasks/${task2Id}/start`, seed.machineToken, { method: "POST" })- await tokenRequest(`/api/daemon/tasks/${task2Id}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: "sess_2" }),- })- })-- it("different conversation produces different context_key (DM reset)", async () => {- // Create a NEW conversation (simulates reset)- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const convData = await convRes.json() as { id: string }- conv2Id = convData.id-- const msgRes = await tokenRequest(- `/api/conversations/${conv2Id}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Message in new conv" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- expect(msgData.task).toBeTruthy()-- const pollRes = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- const pollData = await pollRes.json() as { tasks: Array<Record<string, unknown>> }- expect(pollData.tasks).toHaveLength(1)- // Different conversation → different context_key- expect(pollData.tasks[0].context_key).toBe(conv2Id)- expect(pollData.tasks[0].context_key).not.toBe(conversationId)-- // Clean up- const tid = pollData.tasks[0].id as string- await tokenRequest(`/api/daemon/tasks/${tid}/start`, seed.machineToken, { method: "POST" })- await tokenRequest(`/api/daemon/tasks/${tid}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: "sess_3" }),- })- })-- it("email notify with same thread root reuses same conversation via mapping", async () => {- const threadRoot = `<root-${Date.now()}@e2e.test>`-- // First email in thread- const res1 = await tokenRequest(- `/api/email/notify?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: seed.agentId,- workspaceId: seed.workspaceId,- r2Key: "emails/fake1/raw",- from: `${seed.userId}@test.local`,- subject: "Thread email 1",- isWhitelisted: true,- messageId: threadRoot,- inReplyTo: "",- references: "",- }),- },- )- expect(res1.status).toBe(200)-- // Poll to get first task- const poll1 = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- const poll1Data = await poll1.json() as { tasks: Array<Record<string, unknown>> }- expect(poll1Data.tasks).toHaveLength(1)- const emailConvId = poll1Data.tasks[0].context_key as string- // context_key is now a conversation ID (not email:threadRoot)- expect(emailConvId).toBeTruthy()- expect(emailConvId).toBe(poll1Data.tasks[0].conversation_id)-- // Complete it- const tid1 = poll1Data.tasks[0].id as string- await tokenRequest(`/api/daemon/tasks/${tid1}/start`, seed.machineToken, { method: "POST" })- await tokenRequest(`/api/daemon/tasks/${tid1}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "replied", session_id: "sess_email_1" }),- })-- // Second email in same thread (references contains thread root)- const res2 = await tokenRequest(- `/api/email/notify?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- agentId: seed.agentId,- workspaceId: seed.workspaceId,- r2Key: "emails/fake2/raw",- from: `${seed.userId}@test.local`,- subject: "Re: Thread email 1",- isWhitelisted: true,- messageId: `<reply-${Date.now()}@e2e.test>`,- inReplyTo: threadRoot,- references: `${threadRoot} <reply-${Date.now()}@e2e.test>`,- }),- },- )- expect(res2.status).toBe(200)-- // Poll second task- const poll2 = await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- const poll2Data = await poll2.json() as { tasks: Array<Record<string, unknown>> }- expect(poll2Data.tasks).toHaveLength(1)- // Same thread root → same conversation (via conversation_map lookup)- expect(poll2Data.tasks[0].context_key).toBe(emailConvId)- expect(poll2Data.tasks[0].conversation_id).toBe(emailConvId)-- // Clean up- const tid2 = poll2Data.tasks[0].id as string- await tokenRequest(`/api/daemon/tasks/${tid2}/start`, seed.machineToken, { method: "POST" })- await tokenRequest(`/api/daemon/tasks/${tid2}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "replied again", session_id: "sess_email_2" }),- })- })-})--describe("task failure and retry", () => {- let failTaskId: string-- beforeAll(async () => {- // Create another conversation + message to get a new task- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "This will fail" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- if (msgData.task) {- failTaskId = msgData.task.id- }-- // Claim and start the task via poll- await tokenRequest(- `/api/daemon/tasks/poll`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- },- )- await tokenRequest(- `/api/daemon/tasks/${failTaskId}/start`,- seed.machineToken,- { method: "POST" },- )- })-- it("POST /api/daemon/tasks/:id/fail marks task failed", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${failTaskId}/fail`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "Timeout exceeded" }),- },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("failed")- expect(data.error).toBe("Timeout exceeded")- })-- it("POST /api/tasks/:id/retry retries a failed task", async () => {- const res = await tokenRequest(- `/api/tasks/${failTaskId}/retry?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("queued")- expect(data.prompt).toBe("This will fail")- expect(data.id).not.toBe(failTaskId)- })-- it("original task is now superseded", async () => {- const res = await tokenRequest(- `/api/tasks/${failTaskId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("superseded")- })-- it("retrying a non-failed task returns 400", async () => {- // failTaskId is now superseded, not failed- const res = await tokenRequest(- `/api/tasks/${failTaskId}/retry?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(400)- const data = await res.json() as Record<string, unknown>- expect(data.error).toBe("only failed tasks can be retried")- })-})--describe("task progress reporting", () => {- let progressTaskId: string-- beforeAll(async () => {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Progress test" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- if (msgData.task) {- progressTaskId = msgData.task.id- }-- await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- })- await tokenRequest(`/api/daemon/tasks/${progressTaskId}/start`, seed.machineToken, { method: "POST" })- })-- it("POST /api/daemon/tasks/:id/progress returns ok", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${progressTaskId}/progress`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as { status: string }- expect(data.status).toBe("ok")- })-- it("rejects unauthenticated progress request", async () => {- const res = await fetch(- `${process.env.APP_URL || "http://localhost:3000"}/api/daemon/tasks/${progressTaskId}/progress`,- { method: "POST" },- )- expect(res.status).toBe(401)- })-- it("cleanup: complete progress task", async () => {- await tokenRequest(`/api/daemon/tasks/${progressTaskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: "sess_progress" }),- })- })-})--describe("task supersede", () => {- let supersedeTaskId: string-- beforeAll(async () => {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: "Supersede test" }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- if (msgData.task) {- supersedeTaskId = msgData.task.id- }-- // Keep polling until our specific task is dispatched- for (let attempt = 0; attempt < 5; attempt++) {- const pollRes = await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 10 }),- })- const pollData = await pollRes.json() as { tasks: Array<{ id: string }> }- if (pollData.tasks.some(t => t.id === supersedeTaskId)) break- await new Promise(r => setTimeout(r, 200))- }- await tokenRequest(`/api/daemon/tasks/${supersedeTaskId}/start`, seed.machineToken, { method: "POST" })- })-- it("POST /api/daemon/tasks/:id/supersede marks task as superseded", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${supersedeTaskId}/supersede`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.status).toBe("superseded")- expect(data.id).toBe(supersedeTaskId)- })-- it("superseding an already superseded task returns 400", async () => {- const res = await tokenRequest(- `/api/daemon/tasks/${supersedeTaskId}/supersede`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(400)- })-})diff --git a/src/web/src/test/e2e/task-state-transitions.test.ts b/src/web/src/test/e2e/task-state-transitions.test.tsdeleted file mode 100644index 412105982..000000000--- a/src/web/src/test/e2e/task-state-transitions.test.ts+++ /dev/null@@ -1,250 +0,0 @@-/**- * Regression: Task state transition validation- * Bug pattern: Invalid state transitions (e.g., failing a queued task, completing- * an already-completed task, starting a completed task) were not properly rejected.- * Refs: #194 (Priority 3)- */-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--describe("regression: invalid task state transitions return 400", () => {- let seed: TestSeed-- beforeAll(() => {- seed = seedTestData()- })- afterAll(() => cleanupTestData(seed))-- async function createAndEnqueueTask(): Promise<string> {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: `State test ${randomUUID().slice(0, 8)}` }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- return msgData.task!.id- }-- async function getTaskToRunning(): Promise<string> {- const taskId = await createAndEnqueueTask()- // Poll to dispatch- await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 10 }),- })- // Start- await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })- return taskId- }-- async function getTaskToCompleted(): Promise<string> {- const taskId = await getTaskToRunning()- await tokenRequest(`/api/daemon/tasks/${taskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "done", session_id: `sess_${randomUUID().slice(0, 8)}` }),- })- return taskId- }-- async function getTaskToFailed(): Promise<string> {- const taskId = await getTaskToRunning()- await tokenRequest(`/api/daemon/tasks/${taskId}/fail`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "intentional" }),- })- return taskId- }-- it("cannot fail a queued task (must be running first)", async () => {- const taskId = await createAndEnqueueTask()- // Force queued status in case push dispatched it- sqlRun(`UPDATE agent_task_queue SET status = ? WHERE id = ?`, 'queued', taskId)-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/fail`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "should not work" }),- })- expect(res.status).toBe(400)- })-- it("cannot complete a queued task", async () => {- const taskId = await createAndEnqueueTask()- sqlRun(`UPDATE agent_task_queue SET status = ? WHERE id = ?`, 'queued', taskId)-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "nope", session_id: "sess_x" }),- })- expect(res.status).toBe(400)- })-- it("cannot complete an already-completed task", async () => {- const taskId = await getTaskToCompleted()-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "again", session_id: "sess_y" }),- })- expect(res.status).toBe(400)- })-- it("cannot start a completed task", async () => {- const taskId = await getTaskToCompleted()-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })- expect(res.status).toBe(400)- })-- it("cannot start a failed task", async () => {- const taskId = await getTaskToFailed()-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })- expect(res.status).toBe(400)- })-- it("cannot fail an already-failed task", async () => {- const taskId = await getTaskToFailed()-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/fail`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "double fail" }),- })- expect(res.status).toBe(400)- })-- it("cannot fail an already-completed task", async () => {- const taskId = await getTaskToCompleted()-- const res = await tokenRequest(`/api/daemon/tasks/${taskId}/fail`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "too late" }),- })- expect(res.status).toBe(400)- })-})--describe("regression: valid task state transitions succeed", () => {- let seed: TestSeed-- beforeAll(() => {- seed = seedTestData()- })- afterAll(() => cleanupTestData(seed))-- it("dispatched → start → complete", async () => {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: `Valid start-complete ${randomUUID().slice(0, 8)}` }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- const taskId = msgData.task!.id-- // Poll to claim- const pollRes = await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- })- expect(pollRes.status).toBe(200)- const pollData = await pollRes.json() as { tasks: Array<{ id: string; status: string }> }- expect(pollData.tasks).toHaveLength(1)- expect(pollData.tasks[0].id).toBe(taskId)- expect(pollData.tasks[0].status).toBe("dispatched")-- const startRes = await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })- expect(startRes.status).toBe(200)-- const completeRes = await tokenRequest(`/api/daemon/tasks/${taskId}/complete`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ output: "success", session_id: `sess_${randomUUID().slice(0, 8)}` }),- })- expect(completeRes.status).toBe(200)- })-- it("dispatched → start → fail", async () => {- const convRes = await tokenRequest(- `/api/conversations?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ agent_id: seed.agentId }),- },- )- const { id: convId } = await convRes.json() as { id: string }-- const msgRes = await tokenRequest(- `/api/conversations/${convId}/messages?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ content: `Valid start-fail ${randomUUID().slice(0, 8)}` }),- },- )- const msgData = await msgRes.json() as { task?: { id: string } | null }- const taskId = msgData.task!.id-- // Poll to claim- const pollRes = await tokenRequest(`/api/daemon/tasks/poll`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: seed.daemonId, max_tasks: 1 }),- })- expect(pollRes.status).toBe(200)- const pollData = await pollRes.json() as { tasks: Array<{ id: string }> }- expect(pollData.tasks).toHaveLength(1)- expect(pollData.tasks[0].id).toBe(taskId)-- const startRes = await tokenRequest(`/api/daemon/tasks/${taskId}/start`, seed.machineToken, { method: "POST" })- expect(startRes.status).toBe(200)-- const failRes = await tokenRequest(`/api/daemon/tasks/${taskId}/fail`, seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ error: "expected failure" }),- })- expect(failRes.status).toBe(200)- })-})diff --git a/src/web/src/test/e2e/token-workspace-lifecycle.test.ts b/src/web/src/test/e2e/token-workspace-lifecycle.test.tsdeleted file mode 100644index 2871ee2be..000000000--- a/src/web/src/test/e2e/token-workspace-lifecycle.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import { describe, it, expect, beforeAll } from "vitest"-import { randomUUID } from "crypto"-import { signUp, signIn, sessionRequest, sqlRun, sqlQuery } from "@alook/test-utils"--const APP_URL = process.env.APP_URL ?? "http://localhost:3000"--describe("token/workspace lifecycle — simplified activate flow", () => {- const email = `e2e_token_${randomUUID().slice(0, 8)}@test.local`- const password = "TestPass123!"- let sessionCookie: string- let workspaceId: string- let firstToken: string-- beforeAll(async () => {- await signUp(email, password, "E2E Token User")- sessionCookie = await signIn(email, password)-- const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "TokenTest", slug: `e2e-tok-${randomUUID().slice(0, 8)}` }),- })- const ws = await wsRes.json() as { id: string }- workspaceId = ws.id- })-- describe("Token state transitions", () => {-- it("POST /machine-tokens creates a new token with status=pending", async () => {- const res = await sessionRequest(- `/api/machine-tokens?workspace_id=${workspaceId}`,- sessionCookie,- { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },- )- expect(res.status).toBe(201)- const body = await res.json() as { token: string; status: string }- expect(body.token).toMatch(/^al_/)- expect(body.status).toBe("pending")- firstToken = body.token- })-- it("calling create again returns the same pending token", async () => {- const res = await sessionRequest(- `/api/machine-tokens?workspace_id=${workspaceId}`,- sessionCookie,- { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },- )- expect(res.status).toBe(200)- const body = await res.json() as { token: string }- expect(body.token).toBe(firstToken)- })-- it("activate transitions to active and creates machine/runtime", async () => {- const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: firstToken,- hostname: "TestMachine.local",- runtimes: [{ type: "claude", version: "4.0.0" }],- }),- })- expect(res.status).toBe(200)- const body = await res.json() as { daemon_id: string; workspace_id: string; runtimes: Array<{ id: string }> }- expect(body.daemon_id).toBe("TestMachine.local")- expect(body.workspace_id).toBe(workspaceId)- expect(body.runtimes.length).toBeGreaterThan(0)- })-- it("activate rejects already-active token", async () => {- const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: firstToken,- hostname: "TestMachine.local",- runtimes: [{ type: "claude", version: "4.0.0" }],- }),- })- expect(res.status).toBe(409)- })-- it("activate rejects token without workspace_id", async () => {- const tokenVal = `al_${randomUUID().replace(/-/g, "")}`- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, NULL, ?, 'cli', 'pending', datetime('now'))`,- `mt_${randomUUID().slice(0, 21)}`, sqlQuery(`SELECT id FROM "user" WHERE email = ?`, email)[0]?.id, tokenVal,- )- const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ token: tokenVal, hostname: "host", runtimes: [{ type: "claude" }] }),- })- expect(res.status).toBe(422)- })- })-- describe("Status API", () => {- it("returns active status after activation", async () => {- const res = await sessionRequest("/api/machine-tokens/status", sessionCookie)- expect(res.status).toBe(200)- const body = await res.json() as { status: string; hostname?: string; daemon_online?: boolean }- expect(body.status).toBe("active")- expect(body.hostname).toBe("TestMachine.local")- })- })-})diff --git a/src/web/src/test/e2e/whitelist-crud.test.ts b/src/web/src/test/e2e/whitelist-crud.test.tsdeleted file mode 100644index 2145dcc38..000000000--- a/src/web/src/test/e2e/whitelist-crud.test.ts+++ /dev/null@@ -1,127 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let seedB: TestSeed--beforeAll(() => {- seed = seedTestData()- seedB = seedTestData()-}, 60_000)-afterAll(() => {- cleanupTestData(seed)- cleanupTestData(seedB)-}, 60_000)--describe("whitelist CRUD", () => {- let addedEntryId: string-- it("GET /api/agents/:id/whitelist returns seeded entry", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(Array.isArray(data)).toBe(true)- expect(data).toHaveLength(1)- expect(data[0].id).toBe(seed.whitelistId)- expect(data[0].email).toBe(`${seed.userId}@test.local`)- })-- it("POST /api/agents/:id/whitelist adds new email", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email: "[email protected]" }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.email).toBe("[email protected]")- expect(data.id).toBeTruthy()- addedEntryId = data.id as string- })-- it("GET /api/agents/:id/whitelist now returns both entries", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toHaveLength(2)- expect(data.some((e) => e.id === seed.whitelistId)).toBe(true)- expect(data.some((e) => e.id === addedEntryId)).toBe(true)- })-- it("DELETE /api/agents/:id/whitelist/:whitelistId removes entry", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist/${addedEntryId}?workspace_id=${seed.workspaceId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)- })-- it("GET /api/agents/:id/whitelist returns only seeded entry after delete", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data).toHaveLength(1)- expect(data[0].id).toBe(seed.whitelistId)- })-- it("POST /api/agents/:id/whitelist returns 409 for duplicate", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email: `${seed.userId}@test.local` }),- },- )- expect(res.status).toBe(409)- })-- it("POST /api/agents/:id/whitelist normalizes to lowercase", async () => {- const res = await tokenRequest(- `/api/agents/${seed.agentId}/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email: "[email protected]" }),- },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.email).toBe("[email protected]")- })-- it("GET /api/agents/:id/whitelist returns 404 for nonexistent agent", async () => {- const res = await tokenRequest(- `/api/agents/nonexistent/whitelist?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(res.status).toBe(404)- })-})--describe("whitelist workspace isolation", () => {- it("DELETE with valid whitelistId but wrong workspace returns 404", async () => {- const res = await tokenRequest(- `/api/agents/${seedB.agentId}/whitelist/${seed.whitelistId}?workspace_id=${seedB.workspaceId}`,- seedB.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(404)- })-})diff --git a/src/web/src/test/e2e/workspace-init.test.ts b/src/web/src/test/e2e/workspace-init.test.tsdeleted file mode 100644index 306a89374..000000000--- a/src/web/src/test/e2e/workspace-init.test.ts+++ /dev/null@@ -1,219 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--let seed: TestSeed-const createdAgentIds: string[] = []-let extraWorkspaceId: string | null = null--beforeAll(() => {- seed = seedTestData()-})--afterAll(() => {- for (const agentId of createdAgentIds) {- sqlRun(`DELETE FROM agent_task_queue WHERE agent_id = ?`, agentId)- sqlRun(`DELETE FROM message WHERE conversation_id IN (SELECT id FROM conversation WHERE agent_id = ?)`, agentId)- sqlRun(`DELETE FROM conversation WHERE agent_id = ?`, agentId)- sqlRun(`DELETE FROM agent_whitelist WHERE agent_id = ?`, agentId)- sqlRun(`DELETE FROM agent_link WHERE source_agent_id = ? OR target_agent_id = ?`, agentId, agentId)- sqlRun(`DELETE FROM agent_pin WHERE agent_id = ?`, agentId)- sqlRun(`DELETE FROM agent WHERE id = ?`, agentId)- }- if (extraWorkspaceId) {- sqlRun(`DELETE FROM agent_task_queue WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM conversation WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM agent_whitelist WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = ?)`, extraWorkspaceId)- sqlRun(`DELETE FROM agent_link WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM agent_pin WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM agent WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM agent_runtime WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, extraWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, extraWorkspaceId)- }- cleanupTestData(seed)-})--describe("workspace init flow", () => {- describe("template JSON endpoint", () => {- it("GET /templates/open-source-maintainer/json returns valid template JSON", async () => {- const APP_URL = process.env.APP_URL || "http://localhost:3000"- const res = await fetch(`${APP_URL}/templates/open-source-maintainer/json`)- expect(res.status).toBe(200)- expect(res.headers.get("content-type")).toContain("application/json")-- const data = await res.json() as Record<string, unknown>- expect(data.name).toBe("Open Source Maintainer")- expect(data.scenario).toBe("software-dev")- expect(Array.isArray(data.members)).toBe(true)-- const members = data.members as Array<Record<string, unknown>>- expect(members.length).toBeGreaterThanOrEqual(2)-- const leader = members.find(m => m.role === "leader")- expect(leader).toBeTruthy()- expect(leader!.instructions).toBeTruthy()- expect(typeof leader!.instructions).toBe("string")-- const specialist = members.find(m => m.role !== "leader")- expect(specialist).toBeTruthy()- expect(specialist!.relationship).toBeTruthy()- expect(typeof specialist!.relationship).toBe("string")- })-- it("GET /templates/nonexistent-slug/json returns 404", async () => {- const APP_URL = process.env.APP_URL || "http://localhost:3000"- const res = await fetch(`${APP_URL}/templates/nonexistent-slug/json`)- expect(res.status).toBe(404)- const data = await res.json() as Record<string, unknown>- expect(data.error).toBeTruthy()- })- })-- describe("studio creation (happy path)", () => {- it("POST /api/studios creates agents from template-style JSON without names", async () => {- const payload = {- name: "E2E Init Test",- scenario: "software-dev",- members: [- {- role: "leader",- runtime_id: seed.runtimeId,- description: "Test leader agent",- instructions: "You are the test leader",- },- {- role: "engineer",- runtime_id: seed.runtimeId,- description: "Test engineer agent",- instructions: "You are the test engineer",- relationship: "Delegate code tasks to this engineer\n\nReport back with implementation results",- },- ],- }-- const res = await tokenRequest(- `/api/studios?workspace_id=${seed.workspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload),- },- )- expect(res.status).toBe(201)-- const data = await res.json() as {- studio: { name: string }- workspace: { id: string; name: string }- agents: Array<{ id: string; name: string; email_handle: string | null }>- links: Array<{ id: string; source_agent_id: string; target_agent_id: string }>- }-- expect(data.studio.name).toBeTruthy()- expect(data.agents.length).toBe(2)-- // Names should be auto-generated (not empty)- for (const agent of data.agents) {- expect(agent.name).toBeTruthy()- expect(agent.name.length).toBeGreaterThan(0)- expect(agent.email_handle).toBeTruthy()- }-- createdAgentIds.push(...data.agents.map(a => a.id))-- // Verify agent links were created (index-based matching)- expect(data.links.length).toBeGreaterThanOrEqual(1)- const link = data.links[0]- const linkAgentIds = [link.source_agent_id, link.target_agent_id]- expect(linkAgentIds.length).toBe(2)- })- })-- describe("workspace with existing agents creates new workspace", () => {- it("POST /api/workspaces creates a new workspace when agents already exist", async () => {- // seed already has an agent in seed.workspaceId- // Verify existing agents- const listRes = await tokenRequest(- `/api/agents?workspace_id=${seed.workspaceId}`,- seed.machineToken,- )- expect(listRes.status).toBe(200)- const existingAgents = await listRes.json() as Array<{ id: string }>- expect(existingAgents.length).toBeGreaterThan(0)-- // Create a new workspace (simulates what CLI does when agents exist)- const wsRes = await tokenRequest(- `/api/workspaces`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "E2E New Workspace", slug: `e2e-new-ws-${Date.now()}` }),- },- )- expect(wsRes.status).toBe(201)- const newWs = await wsRes.json() as { id: string; name: string }- expect(newWs.id).toBeTruthy()- expect(newWs.name).toBe("E2E New Workspace")- extraWorkspaceId = newWs.id-- // Register a runtime in the new workspace (POST /api/workspaces already adds user as member)- const now = new Date().toISOString()- const rtId = `rt_e2e_${Date.now()}`- sqlRun(- `INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at, owner_id) VALUES (?, ?, ?, ?, ?, ?, ?)`,- seed.daemonId, extraWorkspaceId, "test-device", now, now, now, seed.userId,- )- sqlRun(- `INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,- rtId, extraWorkspaceId, seed.daemonId, "local", "claude", "online", "test-device", now, now,- )-- // Now create studio in the new workspace- const studioRes = await tokenRequest(- `/api/studios?workspace_id=${extraWorkspaceId}`,- seed.machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: "E2E Init In New WS",- members: [- {- role: "leader",- name: "New WS Leader",- runtime_id: rtId,- instructions: "You lead the new workspace",- },- ],- }),- },- )- expect(studioRes.status).toBe(201)- const studioData = await studioRes.json() as {- agents: Array<{ id: string; name: string }>- workspace: { id: string }- }- expect(studioData.agents.length).toBe(1)- expect(studioData.agents[0].name).toBe("New WS Leader")- expect(studioData.workspace.id).toBe(extraWorkspaceId)- })- })-- describe("agent links verification", () => {- it("verifies leader-specialist links contain correct relationship text", async () => {- // Query links directly from DB for the agents we created earlier- if (createdAgentIds.length < 2) return-- const links = sqlQuery(- `SELECT instruction FROM agent_link WHERE (source_agent_id = ? AND target_agent_id = ?) OR (source_agent_id = ? AND target_agent_id = ?)`,- createdAgentIds[0], createdAgentIds[1], createdAgentIds[1], createdAgentIds[0],- ) as Array<{ instruction: string }>-- expect(links.length).toBeGreaterThanOrEqual(1)- const linkText = links[0].instruction- expect(linkText).toContain("Delegate code tasks to this engineer")- expect(linkText).toContain("Report back with implementation results")- })- })-})diff --git a/src/web/src/test/e2e/workspace-invites.test.ts b/src/web/src/test/e2e/workspace-invites.test.tsdeleted file mode 100644index eda55fd4e..000000000--- a/src/web/src/test/e2e/workspace-invites.test.ts+++ /dev/null@@ -1,148 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, signUp, signIn, sessionRequest, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"--let seed: TestSeed--const inviteeEmail = `e2e_invitee_${randomUUID().slice(0, 8)}@test.local`-const inviteePassword = "TestPassword123!"-let inviteeCookie: string--beforeAll(async () => {- seed = seedTestData()- await signUp(inviteeEmail, inviteePassword, "Invitee User")- inviteeCookie = await signIn(inviteeEmail, inviteePassword)-}, 60_000)--afterAll(() => {- cleanupTestData(seed)- try {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, inviteeEmail)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, inviteeEmail)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, inviteeEmail)- sqlRun(`DELETE FROM "user" WHERE email = ?`, inviteeEmail)- } catch { /* ignore */ }-}, 60_000)--describe("workspace invite flow", () => {- let inviteToken: string- let inviteId: string-- it("POST /api/workspaces/:id/invites creates an invite (owner)", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/invites`,- seed.machineToken,- { method: "POST" },- )- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.token).toBeTruthy()- expect(data.id).toBeTruthy()- inviteToken = data.token as string- inviteId = data.id as string- })-- it("GET /api/workspaces/:id/invites lists active invites", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/invites`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.some(i => i.id === inviteId)).toBe(true)- })-- it("GET /api/invite/:token returns invite details", async () => {- const res = await sessionRequest(`/api/invite/${inviteToken}`, inviteeCookie)- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.workspace_id).toBe(seed.workspaceId)- expect(data.workspace_name).toBeTruthy()- })-- it("POST /api/invite/:token accepts invite and creates membership", async () => {- const res = await sessionRequest(`/api/invite/${inviteToken}`, inviteeCookie, {- method: "POST",- })- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.workspace_id).toBe(seed.workspaceId)- })-- it("POST /api/invite/:token again returns 410 (already used)", async () => {- const res = await sessionRequest(`/api/invite/${inviteToken}`, inviteeCookie, {- method: "POST",- })- expect(res.status).toBe(410)- })-- it("GET /api/workspaces/:id/members includes the new member", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/members`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.length).toBeGreaterThanOrEqual(2)- expect(data.some(m => m.email === inviteeEmail)).toBe(true)- })-- it("DELETE /api/workspaces/:id/invites/:inviteId on used invite", async () => {- const createRes = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/invites`,- seed.machineToken,- { method: "POST" },- )- const { id: newInviteId } = await createRes.json() as Record<string, unknown>-- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/invites/${newInviteId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)- })-- it("DELETE /api/workspaces/:id/invites/nonexistent returns 404", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/invites/nonexistent`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(404)- })-- it("invited member creating studio does NOT overwrite workspace slug", async () => {- const originalSlug = sqlQuery<{ slug: string }>(- `SELECT slug FROM workspace WHERE id = ?`,- seed.workspaceId,- )[0].slug-- // Create a runtime owned by the invitee so they can pass the member-isolation check- const inviteeUserId = sqlQuery<{ id: string }>(`SELECT id FROM "user" WHERE email = ?`, inviteeEmail)[0].id- const now = new Date().toISOString()- const inviteeDaemonId = `daemon_invitee_${Date.now()}`- const inviteeRtId = `rt_invitee_${Date.now()}`- sqlRun(`INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at, owner_id) VALUES (?, ?, ?, ?, ?, ?, ?)`, inviteeDaemonId, seed.workspaceId, "test", now, now, now, inviteeUserId)- sqlRun(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, inviteeRtId, seed.workspaceId, inviteeDaemonId, "local", "claude", "online", "test", now, now)-- const res = await sessionRequest(`/api/studios`, inviteeCookie, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Workspace-ID": seed.workspaceId,- },- body: JSON.stringify({- name: "Hijacked Studio Name",- members: [{ name: "Rogue", role: "leader", runtime_id: inviteeRtId }],- }),- })- expect(res.status).toBe(201)-- const currentSlug = sqlQuery<{ slug: string }>(- `SELECT slug FROM workspace WHERE id = ?`,- seed.workspaceId,- )[0].slug- expect(currentSlug).toBe(originalSlug)- })-})diff --git a/src/web/src/test/e2e/workspace-members.test.ts b/src/web/src/test/e2e/workspace-members.test.tsdeleted file mode 100644index 2401c9bca..000000000--- a/src/web/src/test/e2e/workspace-members.test.ts+++ /dev/null@@ -1,61 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { seedTestData, cleanupTestData, type TestSeed, seedSecondaryUser, cleanupSecondaryUser, type SecondaryUser, tokenRequest } from "@alook/test-utils"--let seed: TestSeed-let secondary: SecondaryUser--beforeAll(() => {- seed = seedTestData()- secondary = seedSecondaryUser(seed.workspaceId, "member")-}, 60_000)--afterAll(() => {- cleanupSecondaryUser(secondary)- cleanupTestData(seed)-}, 60_000)--describe("workspace member management", () => {- it("GET /api/workspaces/:id/members returns members with user info", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/members`,- seed.machineToken,- )- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.length).toBeGreaterThanOrEqual(2)-- const owner = data.find(m => m.user_id === seed.userId)- expect(owner).toBeTruthy()- expect(owner!.role).toBe("owner")-- const mem = data.find(m => m.user_id === secondary.userId)- expect(mem).toBeTruthy()- expect(mem!.role).toBe("member")- })-- it("DELETE /api/workspaces/:id/members/:memberId removes a member", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/members/${secondary.memberId}`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(204)-- // Verify member is gone- const listRes = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/members`,- seed.machineToken,- )- const data = await listRes.json() as Array<Record<string, unknown>>- expect(data.some(m => m.user_id === secondary.userId)).toBe(false)- })-- it("DELETE /api/workspaces/:id/members/nonexistent returns 404", async () => {- const res = await tokenRequest(- `/api/workspaces/${seed.workspaceId}/members/nonexistent`,- seed.machineToken,- { method: "DELETE" },- )- expect(res.status).toBe(404)- })-})diff --git a/src/web/src/test/e2e/workspace.test.ts b/src/web/src/test/e2e/workspace.test.tsdeleted file mode 100644index 291115a39..000000000--- a/src/web/src/test/e2e/workspace.test.ts+++ /dev/null@@ -1,168 +0,0 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"-import { randomUUID } from "crypto"-import { signUp, signIn, sessionRequest, sqlRun, sqlQuery } from "@alook/test-utils"--const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`-const testPassword = "TestPassword123!"-let cookie: string--beforeAll(async () => {- await signUp(testEmail, testPassword, "WS User")- cookie = await signIn(testEmail, testPassword)-})--afterAll(() => {- try {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM workspace WHERE id IN (SELECT workspace_id FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?))`, testEmail)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM "user" WHERE email = ?`, testEmail)- } catch { /* ignore */ }-})--describe("workspace", () => {- const slug = `e2e-ws-${randomUUID().slice(0, 8)}`- let workspaceId: string-- it("POST /api/workspaces creates a workspace", async () => {- const res = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "E2E Workspace", slug }),- })- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.name).toBe("E2E Workspace")- expect(data.slug).toBe(slug)- expect(data.id).toBeTruthy()- workspaceId = data.id as string- })-- it("POST /api/workspaces auto-suffixes duplicate slug", async () => {- const res = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Dup Workspace", slug }),- })- expect(res.status).toBe(201)- const data = await res.json() as Record<string, unknown>- expect(data.name).toBe("Dup Workspace")- // Slug should start with the original slug but have a suffix- expect(data.slug).not.toBe(slug)- expect((data.slug as string).startsWith(`${slug}-`)).toBe(true)- })-- it("GET /api/workspaces lists user's workspaces", async () => {- const res = await sessionRequest("/api/workspaces", cookie)- expect(res.status).toBe(200)- const data = await res.json() as Array<Record<string, unknown>>- expect(data.some(w => w.slug === slug)).toBe(true)- })-- it("GET /api/workspaces/:id returns workspace", async () => {- const res = await sessionRequest(`/api/workspaces/${workspaceId}`, cookie)- expect(res.status).toBe(200)- const data = await res.json() as Record<string, unknown>- expect(data.id).toBe(workspaceId)- expect(data.name).toBe("E2E Workspace")- })-- it("POST /api/workspaces rejects missing name", async () => {- const res = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ slug: "no-name" }),- })- expect(res.status).toBe(400)- })-})--describe("workspace isolation", () => {- const slugA = `e2e-iso-a-${randomUUID().slice(0, 8)}`- const slugB = `e2e-iso-b-${randomUUID().slice(0, 8)}`- let workspaceIdA: string- let workspaceIdB: string- const daemonId = `daemon_iso_${randomUUID().slice(0, 8)}`-- it("creates two separate workspaces", async () => {- // Create workspace A- const resA = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Workspace A", slug: slugA }),- })- expect(resA.status).toBe(201)- const dataA = await resA.json() as Record<string, unknown>- workspaceIdA = dataA.id as string-- // Create workspace B- const resB = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Workspace B", slug: slugB }),- })- expect(resB.status).toBe(201)- const dataB = await resB.json() as Record<string, unknown>- workspaceIdB = dataB.id as string-- expect(workspaceIdA).not.toBe(workspaceIdB)- })-- it("registering daemon to workspace A does not affect workspace B", async () => {- // Create machine token for workspace A- const tokenId = `mt_iso_${randomUUID().replace(/-/g, "").slice(0, 16)}`- const rawToken = `al_${randomUUID().replace(/-/g, "")}`- const now = new Date().toISOString()- sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, (SELECT id FROM "user" WHERE email = ?), ?, ?, ?, ?, ?)`, tokenId, testEmail, workspaceIdA, rawToken, 'iso-token', 'active', now)-- // Register daemon to workspace A- const APP_URL = process.env.APP_URL ?? "http://localhost:3000"- const res = await fetch(`${APP_URL}/api/daemon/register`, {- method: "POST",- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${rawToken}`,- },- body: JSON.stringify({- workspace_id: workspaceIdA,- daemon_id: daemonId,- device_name: "iso-machine",- cli_version: "0.1.0",- runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],- }),- })- expect(res.status).toBe(200)- const data = await res.json() as { runtimes: Array<{ id: string }>; workspaceId: string }- expect(data.workspaceId).toBe(workspaceIdA)- expect(data.runtimes).toHaveLength(1)-- // Workspace A should have the runtime- const runtimesA = sqlQuery<{ id: string }>(- `SELECT id FROM agent_runtime WHERE workspace_id = ? AND daemon_id = ?`, workspaceIdA, daemonId- )- expect(runtimesA.length).toBeGreaterThan(0)-- // Workspace B should have NO runtimes- const runtimesB = sqlQuery<{ id: string }>(- `SELECT id FROM agent_runtime WHERE workspace_id = ? AND daemon_id = ?`, workspaceIdB, daemonId- )- expect(runtimesB).toHaveLength(0)-- // Workspace B should have NO machine entry for this daemon- const machinesB = sqlQuery<{ daemon_id: string }>(- `SELECT daemon_id FROM machine WHERE workspace_id = ? AND daemon_id = ?`, workspaceIdB, daemonId- )- expect(machinesB).toHaveLength(0)- })-- afterAll(() => {- try {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = ?`, daemonId)- sqlRun(`DELETE FROM machine WHERE daemon_id = ?`, daemonId)- sqlRun(`DELETE FROM machine_token WHERE workspace_id IN (?, ?)`, workspaceIdA, workspaceIdB)- sqlRun(`DELETE FROM member WHERE workspace_id IN (?, ?)`, workspaceIdA, workspaceIdB)- sqlRun(`DELETE FROM workspace WHERE id IN (?, ?)`, workspaceIdA, workspaceIdB)- } catch { /* ignore */ }- })-})diff --git a/src/web/test-runtime/d1-bind-workspace-daemon.runtime.test.ts b/src/web/test-runtime/d1-bind-workspace-daemon.runtime.test.tsindex 03be99d0e..d7ad875de 100644--- a/src/web/test-runtime/d1-bind-workspace-daemon.runtime.test.ts+++ b/src/web/test-runtime/d1-bind-workspace-daemon.runtime.test.ts@@ -44,7 +44,7 @@ afterEach(async () => {});describe("workspace and daemon high-cardinality D1 queries", () => {- it("preserves global overview/task/trace ordering and fixed-bind claims at 125", async () => {+ it("preserves global task/trace ordering and fixed-bind claims at 125", async () => {const prefix = fixturePrefix("workspace");const userId = `${prefix}_user`;const workspaceId = `${prefix}_workspace`;@@ -89,12 +89,6 @@ describe("workspace and daemon high-cardinality D1 queries", () => {}));const db = createDb(runtimeEnv.DB);- const recent = await queries.overview.getRecentTerminalTasks(db, workspaceId, agentIds, 15);- expect(recent).toHaveLength(15);- expect(recent.map((task) => task.completedAt)).toEqual(- [...recent.map((task) => task.completedAt)].sort().reverse(),- );- expect(await queries.overview.getConversationCountsByAgent(db, workspaceId, agentIds)).toHaveLength(125);expect(await queries.task.listActiveTaskCountsByWorkspace(db, workspaceId, agentIds, userId)).toHaveLength(125);expect(await queries.task.listActiveTasksByWorkspace(db, workspaceId, agentIds, userId)).toHaveLength(50);expect(await queries.task.listPendingTasksByRuntimes(db, runtimeIds, workspaceId)).toHaveLength(125);diff --git a/src/web/test-runtime/d1-sql-correctness.runtime.test.ts b/src/web/test-runtime/d1-sql-correctness.runtime.test.tsindex c6fb8b95a..d0002d35e 100644--- a/src/web/test-runtime/d1-sql-correctness.runtime.test.ts+++ b/src/web/test-runtime/d1-sql-correctness.runtime.test.ts@@ -268,35 +268,6 @@ describe("whole-statement SQL correctness on native D1", () => {statementCount(record, 'thread_inbox_child_lookup', 13);});- it("selects newest scoped search rows before the global limit and escapes literal LIKE input", async () => {- const f = await seedCommunity("search");- await seedBatch(Array.from({ length: 60 }, (_, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle old', ?, ?, ?)").bind(`${f.prefix}_old_${i}`, f.sender, baseline, f.channels[0], i + 1)));- await seedBatch(f.channels.map((channel, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle new', ?, ?, ?)").bind(`${f.prefix}_new_${i}`, f.sender, `2026-09-02T00:00:${String(i).padStart(3, "0")}Z`, channel, i === 0 ? 61 : 1)));- const decoy = await seedCommunity("search_decoy", 1);- await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle hidden', '2099-01-01', ?, 1)", `${decoy.prefix}_msg`, decoy.sender, decoy.channels[0]);- await run("INSERT INTO community_category (id, server_id, name, private) VALUES (?, ?, 'Hidden', 1)", `${f.prefix}_hidden_category`, f.server);- await run("INSERT INTO community_channel (id, server_id, category_id, name, type, created_at) VALUES (?, ?, ?, 'hidden', 'text', ?)", `${f.prefix}_hidden`, f.server, `${f.prefix}_hidden_category`, baseline);- await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle private', '2099-01-01', ?, 1)", `${f.prefix}_hidden_msg`, f.sender, `${f.prefix}_hidden`);- const { db, record } = recordedDb("search");- const ids = f.channels.slice(0, 124);- const serverResult = await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: [...ids, ...ids], limit: 3 });- expect(serverResult.map(({ message }) => message.id)).toEqual([123, 122, 121].map((i) => `${f.prefix}_new_${i}`));- expect(await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: [] })).toEqual([]);- expect((await queries.communitySearch.searchMessagesInServer(db, { query: "needle", serverId: f.server, visibleChannelIds: f.channels })).map(({ message }) => message.id)).toEqual(Array.from({ length: 50 }, (_, i) => `${f.prefix}_new_${124 - i}`));- expect((await queries.communitySearch.searchMessages(db, { query: "needle", channelId: f.channels[0], limit: 1 }))[0].message.id).toBe(`${f.prefix}_new_0`);- statementCount(record, "json_each", 4);- const literal = String.raw`100%_\end`;- await run("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, ?, '2099-01-01', ?, 62)", `${f.prefix}_literal`, f.sender, literal, f.channels[0]);- expect((await queries.communitySearch.searchMessages(db, { query: literal, channelId: f.channels[0] })).map(({ message }) => message.id)).toEqual([`${f.prefix}_literal`]);- const dm = `${f.prefix}_dm`;- await run("INSERT INTO community_channel (id, type, created_at) VALUES (?, 'dm', ?)", dm, baseline);- await seedBatch([1, 2].map((seq) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'needle dm', ?, ?, ?)").bind(`${f.prefix}_dm_${seq}`, f.sender, seq === 1 ? baseline : later, dm, seq)));- expect((await queries.communitySearch.searchMessages(db, { query: "needle", channelId: dm, limit: 1 }))[0].message.id).toBe(`${f.prefix}_dm_2`);- const tied = [3, 4].map((seq) => `${f.prefix}_tie_${seq}`);- await seedBatch(tied.map((id, i) => runtimeEnv.DB.prepare("INSERT INTO community_message (id, author_id, content, created_at, channel_id, seq) VALUES (?, ?, 'tie', ?, ?, ?)").bind(id, f.sender, later, dm, i + 3)));- expect(new Set((await queries.communitySearch.searchMessages(db, { query: "tie", channelId: dm, limit: 2 })).map(({ message }) => message.id))).toEqual(new Set(tied));- });-it("creates exactly one complete graph with a single native seven-statement batch", async () => {const prefix = fixturePrefix("server_success");const owner = `${prefix}_owner`;