Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add channel uiux

Gus8264ceedb6d5
diff --git a/src/shared/src/db/queries/channel.ts b/src/shared/src/db/queries/channel.ts
index 8f22ea1a2..850911058 100644
--- a/src/shared/src/db/queries/channel.ts
+++ b/src/shared/src/db/queries/channel.ts
@@ -1,5 +1,5 @@
import { eq, and } from "drizzle-orm";
-import { channel } from "../schema";
+import { channel, conversation } from "../schema";
import type { Database } from "../index";
export async function createChannel(
@@ -36,3 +36,68 @@ export async function getChannelByName(
);
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 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 };
+}
diff --git a/src/shared/src/db/queries/conversation.ts b/src/shared/src/db/queries/conversation.ts
index c0df2cf2d..f1f2bfada 100644
--- a/src/shared/src/db/queries/conversation.ts
+++ b/src/shared/src/db/queries/conversation.ts
@@ -1,4 +1,4 @@
-import { eq, and, desc, count } from "drizzle-orm";
+import { eq, and, desc, count, ne, lt } from "drizzle-orm";
import { conversation, message } from "../schema";
import type { Database } from "../index";
import { TASK_TYPES, type TaskType } from "../../constants";
@@ -40,17 +40,20 @@ export async function getConversation(db: Database, id: string, workspaceId: str
export async function listConversations(
db: Database,
workspaceId: string,
- userId: string
+ userId: string,
+ channel?: string
) {
+ const conditions = [
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.userId, userId),
+ ];
+ if (channel) {
+ conditions.push(eq(conversation.channel, channel));
+ }
return db
.select()
.from(conversation)
- .where(
- and(
- eq(conversation.workspaceId, workspaceId),
- eq(conversation.userId, userId)
- )
- )
+ .where(and(...conditions))
.orderBy(desc(conversation.createdAt));
}
@@ -58,8 +61,17 @@ export async function listConversationsByAgent(
db: Database,
workspaceId: string,
userId: string,
- agentId: string
+ agentId: string,
+ channel?: string
) {
+ const conditions = [
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.userId, userId),
+ eq(conversation.agentId, agentId),
+ ];
+ if (channel) {
+ conditions.push(eq(conversation.channel, channel));
+ }
return db
.select({
id: conversation.id,
@@ -67,18 +79,13 @@ export async function listConversationsByAgent(
agentId: conversation.agentId,
userId: conversation.userId,
title: conversation.title,
+ channel: conversation.channel,
createdAt: conversation.createdAt,
messageCount: count(message.id).mapWith(Number),
})
.from(conversation)
.leftJoin(message, and(eq(message.conversationId, conversation.id), eq(message.status, "active")))
- .where(
- and(
- eq(conversation.workspaceId, workspaceId),
- eq(conversation.userId, userId),
- eq(conversation.agentId, agentId)
- )
- )
+ .where(and(...conditions))
.groupBy(conversation.id)
.orderBy(desc(conversation.createdAt));
}
@@ -100,22 +107,23 @@ export async function getOrCreateAgentConversation(
db: Database,
workspaceId: string,
userId: string,
- agentId: string
+ agentId: string,
+ channel?: string
) {
- // Find the most recent user-DM conversation for this user+agent+workspace.
- // Email- and calendar-originated conversations share the same table but must
- // not surface as the agent's default chat — they have their own entry points.
+ const conditions = [
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.userId, userId),
+ eq(conversation.agentId, agentId),
+ eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE),
+ ];
+ if (channel) {
+ conditions.push(eq(conversation.channel, channel));
+ }
+
const rows = await db
.select()
.from(conversation)
- .where(
- and(
- eq(conversation.workspaceId, workspaceId),
- eq(conversation.userId, userId),
- eq(conversation.agentId, agentId),
- eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE)
- )
- )
+ .where(and(...conditions))
.orderBy(desc(conversation.createdAt))
.limit(1);
@@ -123,7 +131,6 @@ export async function getOrCreateAgentConversation(
return rows[0]!;
}
- // No conversation exists — create one
const created = await db
.insert(conversation)
.values({
@@ -132,6 +139,7 @@ export async function getOrCreateAgentConversation(
userId,
title: "",
type: TASK_TYPES.USER_DM_MESSAGE,
+ channel: channel ?? "default",
})
.returning();
return created[0]!;
@@ -144,3 +152,34 @@ export async function deleteConversation(db: Database, id: string, workspaceId:
.returning();
return rows[0] ?? null;
}
+
+export async function listPreviousConversations(
+ db: Database,
+ workspaceId: string,
+ userId: string,
+ agentId: string,
+ excludeId: string,
+ channel?: string,
+ opts?: { limit?: number; before?: string }
+) {
+ const conditions = [
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.userId, userId),
+ eq(conversation.agentId, agentId),
+ eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE),
+ ne(conversation.id, excludeId),
+ ];
+ if (channel) {
+ conditions.push(eq(conversation.channel, channel));
+ }
+ if (opts?.before) {
+ conditions.push(lt(conversation.createdAt, opts.before));
+ }
+ const limit = opts?.limit ?? 10;
+ return db
+ .select({ id: conversation.id, createdAt: conversation.createdAt })
+ .from(conversation)
+ .where(and(...conditions))
+ .orderBy(desc(conversation.createdAt))
+ .limit(limit);
+}
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index f1da9e36f..efb674a55 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -364,6 +364,7 @@ export type UpdateAgentRequest = z.infer<typeof UpdateAgentRequestSchema>;
export const CreateConversationRequestSchema = z.object({
agent_id: z.string().min(1, "agent_id is required"),
+ channel: z.string().optional(),
});
export type CreateConversationRequest = z.infer<
typeof CreateConversationRequestSchema
diff --git a/src/shared/test/queries/channel.test.ts b/src/shared/test/queries/channel.test.ts
new file mode 100644
index 000000000..97c1a79ea
--- /dev/null
+++ b/src/shared/test/queries/channel.test.ts
@@ -0,0 +1,54 @@
+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");
+ });
+});
+
+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);
+ });
+});
diff --git a/src/shared/test/queries/conversation.test.ts b/src/shared/test/queries/conversation.test.ts
new file mode 100644
index 000000000..b47b7266b
--- /dev/null
+++ b/src/shared/test/queries/conversation.test.ts
@@ -0,0 +1,50 @@
+import { describe, it, expect } from "vitest";
+import * as conversationQueries from "../../src/db/queries/conversation";
+
+describe("conversation query module exports", () => {
+ it("exports createConversation", () => {
+ expect(typeof conversationQueries.createConversation).toBe("function");
+ });
+
+ it("exports getConversation", () => {
+ expect(typeof conversationQueries.getConversation).toBe("function");
+ });
+
+ it("exports listConversations", () => {
+ expect(typeof conversationQueries.listConversations).toBe("function");
+ });
+
+ it("exports listConversationsByAgent", () => {
+ expect(typeof conversationQueries.listConversationsByAgent).toBe("function");
+ });
+
+ it("exports getOrCreateAgentConversation", () => {
+ expect(typeof conversationQueries.getOrCreateAgentConversation).toBe("function");
+ });
+
+ it("exports deleteConversation", () => {
+ expect(typeof conversationQueries.deleteConversation).toBe("function");
+ });
+
+ it("exports listPreviousConversations", () => {
+ expect(typeof conversationQueries.listPreviousConversations).toBe("function");
+ });
+});
+
+describe("conversation query function signatures (with optional channel param)", () => {
+ it("listConversations accepts at least 3 params (db, workspaceId, userId) plus optional channel", () => {
+ expect(conversationQueries.listConversations.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it("listConversationsByAgent accepts at least 4 params plus optional channel", () => {
+ expect(conversationQueries.listConversationsByAgent.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it("getOrCreateAgentConversation accepts at least 4 params plus optional channel", () => {
+ expect(conversationQueries.getOrCreateAgentConversation.length).toBeGreaterThanOrEqual(4);
+ });
+
+ it("listPreviousConversations accepts at least 5 params (db, workspaceId, userId, agentId, excludeId)", () => {
+ expect(conversationQueries.listPreviousConversations.length).toBeGreaterThanOrEqual(5);
+ });
+});
diff --git a/src/shared/test/schemas/conversation.test.ts b/src/shared/test/schemas/conversation.test.ts
new file mode 100644
index 000000000..a5e632dfd
--- /dev/null
+++ b/src/shared/test/schemas/conversation.test.ts
@@ -0,0 +1,35 @@
+import { describe, it, expect } from "vitest";
+import { CreateConversationRequestSchema } from "../../src/schemas";
+
+describe("CreateConversationRequestSchema", () => {
+ it("accepts valid body with agent_id only", () => {
+ const result = CreateConversationRequestSchema.safeParse({ agent_id: "ag_1" });
+ expect(result.success).toBe(true);
+ });
+
+ it("accepts valid body with agent_id and channel", () => {
+ const result = CreateConversationRequestSchema.safeParse({ agent_id: "ag_1", channel: "work" });
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.channel).toBe("work");
+ }
+ });
+
+ it("channel is optional", () => {
+ const result = CreateConversationRequestSchema.safeParse({ agent_id: "ag_1" });
+ expect(result.success).toBe(true);
+ if (result.success) {
+ expect(result.data.channel).toBeUndefined();
+ }
+ });
+
+ it("rejects empty agent_id", () => {
+ const result = CreateConversationRequestSchema.safeParse({ agent_id: "" });
+ expect(result.success).toBe(false);
+ });
+
+ it("rejects missing agent_id", () => {
+ const result = CreateConversationRequestSchema.safeParse({});
+ expect(result.success).toBe(false);
+ });
+});
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
index bdf968c35..ecaf0c6e2 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
@@ -60,7 +60,6 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
{/* Top navbar */}
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5">
<div className="flex items-center gap-2 min-w-0">
- <MobileSidebarLogo />
{agent ? (
<AgentStatusBadge
isOnline={isOnline}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx
index ef1c5934a..5dd74fc09 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/new/page.tsx
@@ -7,7 +7,7 @@ import { useWorkspace } from "@/contexts/workspace-context";
import { AgentCreateForm } from "@/components/agent-create-form";
import { fetchModelOptions, createEmailAccount } from "@/lib/api";
import { toast } from "sonner";
-import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
+
export default function CreateAgentPage() {
const router = useRouter();
@@ -28,7 +28,6 @@ export default function CreateAgentPage() {
return (
<>
<div className="flex items-center gap-2 border-b border-border/50 px-3 md:px-5 py-2.5">
- <MobileSidebarLogo />
<h1 className="text-sm font-medium">Create Agent</h1>
</div>
diff --git a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
index 033c0a4fe..e1fb28388 100644
--- a/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/calendar/page.tsx
@@ -8,7 +8,7 @@ import { useAgentContext } from "@/contexts/agent-context";
import { useWorkspace } from "@/contexts/workspace-context";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
-import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
+
import {
listCalendarEvents,
createCalendarEvent,
@@ -493,7 +493,6 @@ export default function CalendarPage() {
<>
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3">
<div className="flex items-center gap-3 min-w-0">
- <MobileSidebarLogo />
<h1 className="text-sm font-medium">Calendar</h1>
<p className="text-xs text-muted-foreground hidden md:block">
Schedule recurring and one-time tasks for your agents.
diff --git a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx b/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx
index a1249cfa5..e423db0bf 100644
--- a/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/help/email-setup/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
+
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
const PROVIDERS = [
@@ -121,7 +121,6 @@ export default function EmailSetupHelpPage() {
<>
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3">
<div className="flex items-center gap-3 min-w-0">
- <MobileSidebarLogo />
<h1 className="text-sm font-medium">Email Setup Guide</h1>
<p className="text-xs text-muted-foreground hidden md:block">
How to get IMAP/SMTP credentials for your email provider
diff --git a/src/web/src/app/(app)/w/[slug]/layout.tsx b/src/web/src/app/(app)/w/[slug]/layout.tsx
index e006eadeb..675d61b23 100644
--- a/src/web/src/app/(app)/w/[slug]/layout.tsx
+++ b/src/web/src/app/(app)/w/[slug]/layout.tsx
@@ -5,6 +5,7 @@ import { getDb } from "@/lib/db"
import { getSession } from "@/lib/session"
import { WorkspaceProvider } from "@/contexts/workspace-context"
import { AgentProvider } from "@/contexts/agent-context"
+import { ChannelProvider } from "@/contexts/channel-context"
import { WorkspaceShell } from "@/components/workspace-shell"
export default async function WorkspaceLayout({
@@ -34,7 +35,9 @@ export default async function WorkspaceLayout({
return (
<WorkspaceProvider workspaceId={ws.id} slug={slug}>
<AgentProvider workspaceId={ws.id}>
- <WorkspaceShell>{children}</WorkspaceShell>
+ <ChannelProvider workspaceId={ws.id}>
+ <WorkspaceShell>{children}</WorkspaceShell>
+ </ChannelProvider>
</AgentProvider>
</WorkspaceProvider>
)
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
index ff072a865..2db0d5413 100644
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
@@ -23,7 +23,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { toast } from "sonner";
import { Skeleton } from "@/components/ui/skeleton";
import { Monitor, Plus } from "lucide-react";
-import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
+
import type { AgentRuntime as Runtime } from "@alook/shared";
import { semverGte } from "@alook/shared";
import { CLI_CMD } from "@/lib/utils";
@@ -294,7 +294,7 @@ export default function RuntimesPage() {
{/* Skeleton title bar */}
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5">
<div className="flex items-center gap-3">
- <MobileSidebarLogo />
+
<Skeleton className="h-4 w-16" />
<Skeleton className="h-3 w-52" />
</div>
@@ -334,7 +334,6 @@ export default function RuntimesPage() {
{/* Title bar */}
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5">
<div className="flex items-center gap-3">
- <MobileSidebarLogo />
<h1 className="text-sm font-medium">Runtimes</h1>
<p className="text-xs text-muted-foreground">
Your machines and their agent runtimes.
diff --git a/src/web/src/app/(app)/w/[slug]/settings/page.tsx b/src/web/src/app/(app)/w/[slug]/settings/page.tsx
index 3022f6379..3ccd040e1 100644
--- a/src/web/src/app/(app)/w/[slug]/settings/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/settings/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
-import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
+
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";
import { GeneralTab } from "./general-tab";
@@ -27,7 +27,6 @@ export default function SettingsPage() {
<>
<div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3">
<div className="flex items-center gap-3 min-w-0">
- <MobileSidebarLogo />
<h1 className="text-sm font-medium">Settings</h1>
</div>
</div>
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.ts
index 93258502d..ec5a41e87 100644
--- 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.ts
@@ -6,6 +6,7 @@ vi.mock("@opennextjs/cloudflare", () => ({
const mockGetAgent = vi.fn();
const mockGetOrCreateAgentConversation = vi.fn();
+const mockListPreviousConversations = vi.fn();
const mockListMessages = vi.fn();
const mockListArtifactsByConversation = vi.fn();
const mockListBufferedMessages = vi.fn();
@@ -33,6 +34,8 @@ vi.mock("@alook/shared", () => ({
conversation: {
getOrCreateAgentConversation: (...args: unknown[]) =>
mockGetOrCreateAgentConversation(...args),
+ listPreviousConversations: (...args: unknown[]) =>
+ mockListPreviousConversations(...args),
},
message: {
listMessages: (...args: unknown[]) => mockListMessages(...args),
@@ -119,6 +122,7 @@ const CONV = {
function setupDefaults() {
mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent" });
mockGetOrCreateAgentConversation.mockResolvedValue(CONV);
+ mockListPreviousConversations.mockResolvedValue([]);
mockListMessages.mockResolvedValue([]);
mockListArtifactsByConversation.mockResolvedValue([]);
mockListBufferedMessages.mockResolvedValue([]);
@@ -148,6 +152,7 @@ describe("POST /api/agents/[id]/chat-init", () => {
mockGetAgent.mockResolvedValue({ id: "a1", name: "Agent" });
mockGetOrCreateAgentConversation.mockResolvedValue(CONV);
+ mockListPreviousConversations.mockResolvedValue([]);
mockListMessages.mockResolvedValue([msg]);
mockListArtifactsByConversation.mockResolvedValue([artifact]);
mockListBufferedMessages.mockResolvedValue([]);
@@ -166,6 +171,8 @@ describe("POST /api/agents/[id]/chat-init", () => {
expect(body.active_task).toBeNull();
expect(body.task_messages).toEqual([]);
expect(body.has_more_messages).toBe(false);
+ expect(body.previous_conversations).toEqual([]);
+ expect(body.has_more_conversations).toBe(false);
});
it("returns 404 for non-existent agent", async () => {
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.ts
index 094b704a3..d054f41f8 100644
--- a/src/web/src/app/api/agents/[id]/chat-init/route.ts
+++ b/src/web/src/app/api/agents/[id]/chat-init/route.ts
@@ -12,6 +12,7 @@ import {
} from "@/lib/api/responses";
const MESSAGE_LIMIT = 20;
+const PREV_CONV_LIMIT = 10;
export const POST = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
@@ -30,21 +31,34 @@ export const POST = withAuth(async (req, ctx) => {
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, bufferedResult, activeTaskResult] =
+ const [messagesResult, artifactsResult, bufferedResult, activeTaskResult, prevConvsResult] =
await Promise.allSettled([
queries.message.listMessages(db, convId, { limit: MESSAGE_LIMIT }),
queries.artifact.listArtifactsByConversation(db, convId, ws.workspaceId),
queries.message.listBufferedMessages(db, convId),
queries.task.getActiveTaskByConversation(db, convId, ws.workspaceId),
+ queries.conversation.listPreviousConversations(
+ db, ws.workspaceId, ctx.userId, id, convId, channel,
+ { limit: PREV_CONV_LIMIT },
+ ),
]);
const messages =
@@ -57,6 +71,8 @@ export const POST = withAuth(async (req, ctx) => {
activeTaskResult.status === "fulfilled"
? activeTaskResult.value
: null;
+ const prevConvs =
+ prevConvsResult.status === "fulfilled" ? prevConvsResult.value : [];
let taskMessages: unknown[] = [];
if (
@@ -82,5 +98,10 @@ export const POST = withAuth(async (req, ctx) => {
active_task: activeTask ? taskToResponse(activeTask) : null,
task_messages: taskMessages,
has_more_messages: messages.length >= MESSAGE_LIMIT,
+ previous_conversations: prevConvs.map((c) => ({
+ id: c.id,
+ created_at: c.createdAt,
+ })),
+ has_more_conversations: prevConvs.length >= PREV_CONV_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.ts
index 0d2c68b27..16979b8d3 100644
--- a/src/web/src/app/api/agents/[id]/conversation/route.test.ts
+++ b/src/web/src/app/api/agents/[id]/conversation/route.test.ts
@@ -74,7 +74,8 @@ describe("POST /api/agents/[id]/conversation", () => {
{},
"w1",
"u1",
- "a1"
+ "a1",
+ undefined
);
});
diff --git a/src/web/src/app/api/agents/[id]/conversation/route.ts b/src/web/src/app/api/agents/[id]/conversation/route.ts
index a85e3e195..d5bd09092 100644
--- a/src/web/src/app/api/agents/[id]/conversation/route.ts
+++ b/src/web/src/app/api/agents/[id]/conversation/route.ts
@@ -23,11 +23,20 @@ export const POST = withAuth(async (req, ctx) => {
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
+ id,
+ channel
);
return writeJSON(conversationToResponse(conversation));
diff --git a/src/web/src/app/api/agents/[id]/conversations/route.ts b/src/web/src/app/api/agents/[id]/conversations/route.ts
index 108591645..14c4bb242 100644
--- a/src/web/src/app/api/agents/[id]/conversations/route.ts
+++ b/src/web/src/app/api/agents/[id]/conversations/route.ts
@@ -23,11 +23,29 @@ export const GET = withAuth(async (req, ctx) => {
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
+ id,
+ channel
);
return writeJSON(conversations.map(conversationToResponse));
diff --git a/src/web/src/app/api/channels/[id]/route.test.ts b/src/web/src/app/api/channels/[id]/route.test.ts
new file mode 100644
index 000000000..a997dd139
--- /dev/null
+++ b/src/web/src/app/api/channels/[id]/route.test.ts
@@ -0,0 +1,216 @@
+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, { 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.ts
new file mode 100644
index 000000000..197ee378f
--- /dev/null
+++ b/src/web/src/app/api/channels/[id]/route.ts
@@ -0,0 +1,70 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+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 { env } = getCloudflareContext();
+ const db = getDb((env as 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 { env } = getCloudflareContext();
+ const db = getDb((env as 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/route.test.ts b/src/web/src/app/api/channels/route.test.ts
new file mode 100644
index 000000000..d74796a48
--- /dev/null
+++ b/src/web/src/app/api/channels/route.test.ts
@@ -0,0 +1,244 @@
+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,
+ 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, { 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[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.ts
new file mode 100644
index 000000000..a9706a47f
--- /dev/null
+++ b/src/web/src/app/api/channels/route.ts
@@ -0,0 +1,78 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+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 { env } = getCloudflareContext();
+ const db = getDb((env as 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",
+ 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 { env } = getCloudflareContext();
+ const db = getDb((env as 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/conversations/route.test.ts b/src/web/src/app/api/conversations/route.test.ts
index 718970f4b..899ee0e54 100644
--- a/src/web/src/app/api/conversations/route.test.ts
+++ b/src/web/src/app/api/conversations/route.test.ts
@@ -56,7 +56,7 @@ describe("GET /api/conversations", () => {
{ id: "c1", title: "Hello" },
{ id: "c2", title: "World" },
]);
- expect(mockListConversations).toHaveBeenCalledWith({}, "w1", "u1");
+ expect(mockListConversations).toHaveBeenCalledWith({}, "w1", "u1", undefined);
});
});
@@ -83,6 +83,7 @@ describe("POST /api/conversations", () => {
agentId: "a1",
userId: "u1",
title: "",
+ channel: undefined,
});
});
diff --git a/src/web/src/app/api/conversations/route.ts b/src/web/src/app/api/conversations/route.ts
index 889a44ac8..2d0f828ae 100644
--- a/src/web/src/app/api/conversations/route.ts
+++ b/src/web/src/app/api/conversations/route.ts
@@ -14,10 +14,13 @@ export const GET = withAuth(async (req, ctx) => {
const { env } = getCloudflareContext()
const db = getDb((env as Env).DB)
+ const channel = new URL(req.url).searchParams.get("channel") || undefined;
+
const conversations = await queries.conversation.listConversations(
db,
ws.workspaceId,
- ctx.userId
+ ctx.userId,
+ channel
);
return writeJSON(conversations.map(conversationToResponse));
});
@@ -37,6 +40,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
agentId: body.agent_id,
userId: ctx.userId,
title: "",
+ channel: body.channel,
});
return writeJSON(conversationToResponse(conversation), 201);
diff --git a/src/web/src/components/agent-chat/agent-chat-view.test.ts b/src/web/src/components/agent-chat/agent-chat-view.test.ts
index 2ebc821d5..5b5b23bbc 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.test.ts
+++ b/src/web/src/components/agent-chat/agent-chat-view.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from "vitest";
-import type { Message } from "@alook/shared";
-import { sortMessages, mergeMessages } from "./agent-chat-view";
+import type { Message, Artifact } from "@alook/shared";
+import { sortMessages, mergeMessages, buildTimeline } from "./agent-chat-view";
+import type { NapMarker } from "./agent-chat-view";
function msg(id: string, created_at: string, role: "user" | "assistant" = "user", content = ""): Message {
return { id, conversation_id: "conv1", role, content, task_id: null, created_at };
@@ -194,3 +195,96 @@ describe("mergeMessages", () => {
expect(result.map((m) => m.id)).toEqual(["m1", "m2", "m3", "m4", "m5", "m6"]);
});
});
+
+function artifact(id: string, created_at: string): Artifact {
+ return {
+ id,
+ conversation_id: "conv1",
+ filename: "file.txt",
+ content_type: "text/plain",
+ size: 100,
+ source: "agent",
+ r2_key: `key-${id}`,
+ created_at,
+ };
+}
+
+function nap(id: string, created_at: string, agentName = "Luna"): NapMarker {
+ return { id, created_at, agentName };
+}
+
+describe("buildTimeline", () => {
+ it("interleaves messages, artifacts, and nap markers chronologically", () => {
+ const msgs = [
+ msg("m1", "2024-01-01T00:00:00Z"),
+ msg("m3", "2024-01-03T00:00:00Z"),
+ ];
+ const arts = [artifact("a1", "2024-01-02T00:00:00Z")];
+ const naps: NapMarker[] = [];
+
+ const result = buildTimeline(msgs, arts, naps);
+ expect(result.map((i) => i.data.id)).toEqual(["m1", "a1", "m3"]);
+ });
+
+ it("places nap marker after messages at the same timestamp", () => {
+ const msgs = [
+ msg("m1", "2024-01-01T00:00:00Z"),
+ msg("m2", "2024-01-03T00:00:00Z"),
+ ];
+ const napTs = "2024-01-02T00:00:00Z";
+ const naps = [nap("nap-1", napTs)];
+
+ const result = buildTimeline(msgs, [], naps);
+ expect(result.map((i) => i.kind)).toEqual(["message", "nap", "message"]);
+ });
+
+ it("nap marker sorts after messages with the same created_at", () => {
+ const ts = "2024-01-02T00:00:00Z";
+ const msgs = [msg("m1", ts)];
+ const naps = [nap("nap-1", ts)];
+
+ const result = buildTimeline(msgs, [], naps);
+ expect(result[0].kind).toBe("message");
+ expect(result[1].kind).toBe("nap");
+ });
+
+ it("renders multiple nap markers between multiple conversations", () => {
+ const msgs = [
+ msg("m1", "2024-01-01T00:00:00Z"),
+ msg("m2", "2024-01-03T00:00:00Z"),
+ msg("m3", "2024-01-05T00:00:00Z"),
+ ];
+ const naps = [
+ nap("nap-1", "2024-01-02T00:00:00Z"),
+ nap("nap-2", "2024-01-04T00:00:00Z"),
+ ];
+
+ const result = buildTimeline(msgs, [], naps);
+ expect(result.map((i) => i.kind)).toEqual([
+ "message", "nap", "message", "nap", "message",
+ ]);
+ expect(result.map((i) => i.data.id)).toEqual([
+ "m1", "nap-1", "m2", "nap-2", "m3",
+ ]);
+ });
+
+ it("handles empty messages with nap markers only", () => {
+ const naps = [nap("nap-1", "2024-01-01T00:00:00Z")];
+ const result = buildTimeline([], [], naps);
+ expect(result).toHaveLength(1);
+ expect(result[0].kind).toBe("nap");
+ });
+
+ it("preserves agent name on nap markers", () => {
+ const naps = [nap("nap-1", "2024-01-01T00:00:00Z", "TestBot")];
+ const result = buildTimeline([], [], naps);
+ expect(result[0].kind).toBe("nap");
+ if (result[0].kind === "nap") {
+ expect(result[0].data.agentName).toBe("TestBot");
+ }
+ });
+
+ it("returns empty timeline when all inputs are empty", () => {
+ expect(buildTimeline([], [], [])).toEqual([]);
+ });
+});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 4aa5b2f35..7d48e9d9f 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -11,6 +11,7 @@ import {
getConversation,
listMessages,
listMessagesAroundTask,
+ listPreviousConversations,
sendMessage,
getTask,
getTaskMessages,
@@ -22,27 +23,21 @@ import {
getActiveTask,
retryTask,
} from "@/lib/api";
+import type { PreviousConversation } from "@/lib/api";
import type { Artifact, Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";
import { useAgentContext } from "@/contexts/agent-context";
+import { useChannel } from "@/contexts/channel-context";
import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
-import { ArrowUp, Box, FileText, Loader2, Mail, Mic, Paperclip, RotateCcw, Square, X } from "lucide-react";
+import { ArrowUp, BedDouble, Box, FileText, Loader2, Mail, Mic, Paperclip, Square, X } from "lucide-react";
import { useSpeechRecognition } from "@/hooks/use-speech-recognition";
import { useMentionPopup } from "@/hooks/use-mention-popup";
import { MentionPopup } from "@/components/agent-chat/mention-popup";
import { highlightMentions } from "@/lib/highlight-mentions";
import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheet";
import { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
import { Streamdown } from "streamdown";
import { FollowUpBuffer } from "@/components/agent-chat/follow-up-buffer";
@@ -73,23 +68,43 @@ export function mergeMessages(existing: Message[], incoming: Message[]): Message
return sortMessages([...merged.values()]);
}
+export type NapMarker = { agentName: string; created_at: string; id: string };
+
type TimelineItem =
| { kind: "message"; data: Message }
- | { kind: "artifact"; data: Artifact };
+ | { kind: "artifact"; data: Artifact }
+ | { kind: "nap"; data: NapMarker };
-function buildTimeline(messages: Message[], artifacts: Artifact[]): TimelineItem[] {
+export function buildTimeline(messages: Message[], artifacts: Artifact[], napMarkers: NapMarker[]): TimelineItem[] {
const items: TimelineItem[] = [
...messages.map((m): TimelineItem => ({ kind: "message", data: m })),
...artifacts.map((a): TimelineItem => ({ kind: "artifact", data: a })),
+ ...napMarkers.map((n): TimelineItem => ({ kind: "nap", data: n })),
];
return items.sort((a, b) => {
const cmp = a.data.created_at.localeCompare(b.data.created_at);
if (cmp !== 0) return cmp;
+ if (a.kind === "nap" || b.kind === "nap") {
+ if (a.kind === "nap" && b.kind !== "nap") return 1;
+ if (a.kind !== "nap" && b.kind === "nap") return -1;
+ }
if (a.kind !== b.kind) return a.kind === "message" ? -1 : 1;
return a.data.id.localeCompare(b.data.id);
});
}
+function NapSeparator({ agentName }: { agentName: string }) {
+ return (
+ <div className="flex items-center gap-3 py-4 select-none" aria-hidden>
+ <div className="flex-1 border-t border-border/40" />
+ <span className="text-xs text-muted-foreground/60 whitespace-nowrap">
+ {agentName} took a nap 💤
+ </span>
+ <div className="flex-1 border-t border-border/40" />
+ </div>
+ );
+}
+
function ArtifactCard({ artifact, onClick }: { artifact: Artifact; onClick: (a: Artifact) => void }) {
return (
<button
@@ -171,6 +186,7 @@ export function AgentChatView() {
const searchParams = useSearchParams();
const { workspaceId } = useWorkspace();
const { agents, activeTaskCounts, subscribeWs } = useAgentContext();
+ const { activeChannel } = useChannel();
const agentId = params.id as string;
const scrollToTaskId = searchParams.get("task");
const targetConvId = searchParams.get("conv");
@@ -195,6 +211,9 @@ export function AgentChatView() {
const [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [bufferedMessages, setBufferedMessages] = useState<Message[]>([]);
const [caretIndex, setCaretIndex] = useState<number | null>(null);
+ const [previousConversations, setPreviousConversations] = useState<PreviousConversation[]>([]);
+ const [hasMoreConversations, setHasMoreConversations] = useState(false);
+ const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);
const pendingFilesMapRef = useRef<Map<string, File[]>>(new Map());
@@ -205,7 +224,7 @@ export function AgentChatView() {
const agentArtifacts = useMemo(() => artifacts.filter((a) => a.source === "agent"), [artifacts]);
- const timeline = useMemo(() => buildTimeline(messages, agentArtifacts), [messages, agentArtifacts]);
+ const timeline = useMemo(() => buildTimeline(messages, agentArtifacts, napMarkers), [messages, agentArtifacts, napMarkers]);
const handleArtifactClick = useCallback((artifact: Artifact) => {
if (isPreviewable(artifact)) {
@@ -264,6 +283,16 @@ export function AgentChatView() {
}, []);
useEffect(() => {
+ setLoading(true);
+ initialScrollDone.current = false;
+ setActiveTask(null);
+ setTaskMessages([]);
+ setBufferedMessages([]);
+ setNapMarkers([]);
+ setPreviousConversations([]);
+ setHasMoreConversations(false);
+ oldestConvIdRef.current = null;
+ oldestConvCreatedAtRef.current = null;
async function load() {
try {
if (targetConvId && scrollToTaskId) {
@@ -278,20 +307,24 @@ export function AgentChatView() {
setHasMore(msgs.length >= MESSAGE_LIMIT);
setArtifacts(arts);
} catch {
- const data = await chatInit(agentId, workspaceId);
+ const data = await chatInit(agentId, workspaceId, activeChannel);
setConversation(data.conversation);
setMessages(data.messages);
setHasMore(data.has_more_messages);
setArtifacts(data.artifacts);
setBufferedMessages(data.buffered_messages);
+ setPreviousConversations(data.previous_conversations);
+ setHasMoreConversations(data.has_more_conversations);
}
} else {
- const data = await chatInit(agentId, workspaceId);
+ const data = await chatInit(agentId, workspaceId, activeChannel);
setConversation(data.conversation);
setMessages(data.messages);
setHasMore(data.has_more_messages);
setArtifacts(data.artifacts);
setBufferedMessages(data.buffered_messages);
+ setPreviousConversations(data.previous_conversations);
+ setHasMoreConversations(data.has_more_conversations);
if (data.active_task) {
setActiveTask(data.active_task);
@@ -311,7 +344,7 @@ export function AgentChatView() {
}
}
load();
- }, [agentId, workspaceId, targetConvId, scrollToTaskId]);
+ }, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel]);
// Scroll to bottom on initial load (skip if scroll-to-task is active)
useEffect(() => {
@@ -346,7 +379,7 @@ export function AgentChatView() {
setTimeout(() => tryScroll(), 100);
});
}
- } catch {}
+ } catch { }
}, 100);
}, [scrollToTaskId, loading, conversation, workspaceId]);
@@ -359,10 +392,59 @@ export function AgentChatView() {
}
}, [taskMessages.length, taskStatus, scrollToBottom]);
+ const agentName = useMemo(() => agents.find((a) => a.id === agentId)?.name ?? "Agent", [agents, agentId]);
+
+ const messagesRef = useRef(messages);
+ messagesRef.current = messages;
+ const hasMoreRef = useRef(hasMore);
+ hasMoreRef.current = hasMore;
+ const prevConvsRef = useRef(previousConversations);
+ prevConvsRef.current = previousConversations;
+ const hasMoreConvsRef = useRef(hasMoreConversations);
+ hasMoreConvsRef.current = hasMoreConversations;
+ const agentNameRef = useRef(agentName);
+ agentNameRef.current = agentName;
+ const activeChannelRef = useRef(activeChannel);
+ activeChannelRef.current = activeChannel;
+
+ const oldestConvIdRef = useRef<string | null>(null);
+ const oldestConvCreatedAtRef = useRef<string | null>(null);
+
const loadOlderMessages = useCallback(async () => {
- if (!conversation || loadingMoreRef.current || !hasMore) return;
- const oldest = messages[0];
- if (!oldest) return;
+ if (!conversation || loadingMoreRef.current) return;
+
+ const currentMessages = messagesRef.current;
+ const currentHasMore = hasMoreRef.current;
+ const currentHasMoreConvs = hasMoreConvsRef.current;
+ const currentAgentName = agentNameRef.current;
+ const currentChannel = activeChannelRef.current;
+
+ const oldest = currentMessages[0];
+ const paginatingConvId = oldestConvIdRef.current ?? conversation.id;
+ const canLoadMoreInConv = currentHasMore && oldest;
+ let prevConvsList = prevConvsRef.current;
+
+ if (!canLoadMoreInConv && prevConvsList.length === 0 && currentHasMoreConvs) {
+ const oldestConv = oldestConvCreatedAtRef.current
+ ? { id: oldestConvIdRef.current!, created_at: oldestConvCreatedAtRef.current }
+ : { id: conversation.id, created_at: conversation.created_at };
+ try {
+ const result = await listPreviousConversations(agentId, workspaceId, {
+ exclude: conversation.id,
+ before: oldestConv.created_at,
+ channel: currentChannel,
+ });
+ prevConvsList = result.conversations;
+ setPreviousConversations(result.conversations);
+ setHasMoreConversations(result.has_more);
+ } catch {
+ setHasMoreConversations(false);
+ }
+ }
+
+ const canLoadPrevConv = prevConvsList.length > 0;
+
+ if (!canLoadMoreInConv && !canLoadPrevConv) return;
loadingMoreRef.current = true;
setLoadingMore(true);
@@ -370,23 +452,69 @@ export function AgentChatView() {
const prevScrollHeight = el?.scrollHeight ?? 0;
try {
- const older = await listMessages(conversation.id, workspaceId, {
- limit: MESSAGE_LIMIT,
- before: oldest.created_at,
- beforeId: oldest.id,
- });
- if (older.length === 0) {
- setHasMore(false);
- return;
+ if (canLoadMoreInConv) {
+ const older = await listMessages(paginatingConvId, workspaceId, {
+ limit: MESSAGE_LIMIT,
+ before: oldest!.created_at,
+ beforeId: oldest!.id,
+ });
+ if (older.length === 0) {
+ setHasMore(false);
+ } else {
+ setHasMore(older.length >= MESSAGE_LIMIT);
+ setMessages((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const unique = older.filter((m) => !existingIds.has(m.id));
+ return [...unique, ...prev];
+ });
+ }
+ } else if (canLoadPrevConv) {
+ let consumed = 0;
+ let loadedOlder: Message[] = [];
+
+ while (consumed < prevConvsList.length) {
+ const prevConv = prevConvsList[consumed]!;
+ consumed++;
+ const older = await listMessages(prevConv.id, workspaceId, {
+ limit: MESSAGE_LIMIT,
+ });
+
+ if (older.length === 0) {
+ oldestConvIdRef.current = prevConv.id;
+ oldestConvCreatedAtRef.current = prevConv.created_at;
+ continue;
+ }
+
+ const napTs = oldestConvCreatedAtRef.current ?? conversation.created_at;
+ const napId = `nap-${prevConv.id}`;
+ setNapMarkers((prev) =>
+ prev.some((m) => m.id === napId)
+ ? prev
+ : [...prev, { agentName: currentAgentName, created_at: napTs, id: napId }],
+ );
+
+ loadedOlder = older;
+ setHasMore(older.length >= MESSAGE_LIMIT);
+ oldestConvIdRef.current = prevConv.id;
+ oldestConvCreatedAtRef.current = prevConv.created_at;
+ break;
+ }
+
+ if (consumed > 0) {
+ setPreviousConversations((prev) => prev.slice(consumed));
+ }
+
+ if (loadedOlder.length > 0) {
+ setMessages((prev) => {
+ const existingIds = new Set(prev.map((m) => m.id));
+ const unique = loadedOlder.filter((m) => !existingIds.has(m.id));
+ return [...unique, ...prev];
+ });
+ } else {
+ setHasMore(false);
+ }
}
- setHasMore(older.length >= MESSAGE_LIMIT);
- setMessages((prev) => {
- const existingIds = new Set(prev.map((m) => m.id));
- const unique = older.filter((m) => !existingIds.has(m.id));
- return [...unique, ...prev];
- });
- // Restore scroll position so content doesn't jump
requestAnimationFrame(() => {
if (el) {
const newScrollHeight = el.scrollHeight;
@@ -399,11 +527,12 @@ export function AgentChatView() {
loadingMoreRef.current = false;
setLoadingMore(false);
}
- }, [conversation, workspaceId, messages, hasMore]);
+ }, [conversation, workspaceId, agentId]);
// Auto-load older messages when content doesn't overflow (scroll can't trigger)
+ const canLoadMore = hasMore || previousConversations.length > 0 || hasMoreConversations;
useEffect(() => {
- if (loading || !hasMore || loadingMoreRef.current) return;
+ if (loading || !canLoadMore || loadingMoreRef.current) return;
const el = scrollRef.current;
if (!el) return;
const raf = requestAnimationFrame(() => {
@@ -412,17 +541,17 @@ export function AgentChatView() {
}
});
return () => cancelAnimationFrame(raf);
- }, [loading, hasMore, messages.length, loadOlderMessages]);
+ }, [loading, canLoadMore, messages.length, loadOlderMessages]);
const handleScroll = useCallback(() => {
const el = scrollRef.current;
if (!el) return;
isNearBottom.current =
el.scrollHeight - el.scrollTop - el.clientHeight < 100;
- if (!loadingMore && hasMore && el.scrollTop < 80) {
+ if (!loadingMore && canLoadMore && el.scrollTop < 80) {
loadOlderMessages();
}
- }, [loadOlderMessages, loadingMore, hasMore]);
+ }, [loadOlderMessages, loadingMore, canLoadMore]);
const startPolling = useCallback(
(taskId: string, conversationId: string, initialSeq?: number) => {
@@ -465,7 +594,7 @@ export function AgentChatView() {
// Stale poll — still merge messages but don't touch activeTask or polling
listMessages(conversationId, workspaceId)
.then((latest) => setMessages((prev) => mergeMessages(prev, latest)))
- .catch(() => {});
+ .catch(() => { });
return;
}
@@ -511,7 +640,7 @@ export function AgentChatView() {
setTaskMessages([]);
startPollingRef.current(nextTask.id, conversationId);
}
- } catch {}
+ } catch { }
}, 1000);
} else if (!isStale) {
setActiveTask(task);
@@ -570,7 +699,7 @@ export function AgentChatView() {
// Fetch all messages so the completed task's agent response is included
listMessages(msg.conversationId, workspaceId)
.then((latest) => setMessages((prev) => mergeMessages(prev, latest)))
- .catch(() => {});
+ .catch(() => { });
const task = msg.task as Task;
setActiveTask(task);
setTaskMessages([]);
@@ -768,7 +897,7 @@ export function AgentChatView() {
if (message.attachment_ids && message.attachment_ids.length > 0) {
listArtifacts(conversation.id, workspaceId)
.then((arts) => setArtifacts(arts))
- .catch(() => {});
+ .catch(() => { });
}
setActiveTask(task);
setTaskMessages([]);
@@ -795,23 +924,34 @@ export function AgentChatView() {
startPolling(newTask.id, conversation.id);
}, [activeTask, conversation, workspaceId, startPolling]);
- const [resetConfirmOpen, setResetConfirmOpen] = useState(false);
- const [resetting, setResetting] = useState(false);
- const [resetDontAsk, setResetDontAsk] = useState(false);
+ const [napping, setNapping] = useState(false);
- const RESET_SKIP_KEY = "chat-reset-skip-confirm";
+ const currentConvHasMessages = useMemo(
+ () => !!conversation && messages.some((m) => m.conversation_id === conversation.id),
+ [conversation, messages],
+ );
- const executeReset = async () => {
- if (!conversation) return;
- setResetting(true);
+ const handleNap = async () => {
+ if (!conversation || !currentConvHasMessages || napping) return;
+ setNapping(true);
try {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
- const newConv = await createConversation(agentId, workspaceId);
+ const newConv = await createConversation(agentId, workspaceId, activeChannel);
+
+ setNapMarkers((prev) => [
+ ...prev,
+ { agentName, created_at: newConv.created_at, id: `nap-${conversation.id}` },
+ ]);
+
+ setPreviousConversations((prev) => [
+ { id: conversation.id, created_at: conversation.created_at },
+ ...prev,
+ ]);
+
setConversation(newConv);
- setMessages([]);
setActiveTask(null);
setTaskMessages([]);
setArtifacts([]);
@@ -821,23 +961,14 @@ export function AgentChatView() {
lastSeqRef.current = 0;
setConnectionLost(false);
setHasMore(false);
- initialScrollDone.current = false;
+ oldestConvIdRef.current = null;
+ oldestConvCreatedAtRef.current = null;
+
+ scrollToBottom();
} catch {
- toast.error("Failed to reset conversation");
+ toast.error("Failed to start new conversation");
} finally {
- setResetting(false);
- setResetConfirmOpen(false);
- }
- };
-
- const handleReset = () => {
- if (!conversation || messages.length === 0) return;
- const skip = typeof window !== "undefined" && localStorage.getItem(RESET_SKIP_KEY) === "true";
- if (skip) {
- executeReset();
- } else {
- setResetDontAsk(false);
- setResetConfirmOpen(true);
+ setNapping(false);
}
};
@@ -953,6 +1084,10 @@ export function AgentChatView() {
})()}
{timeline.map((item) => {
+ if (item.kind === "nap") {
+ return <NapSeparator key={item.data.id} agentName={agentName} />;
+ }
+
if (item.kind === "artifact") {
return (
<ArtifactCard
@@ -1072,11 +1207,11 @@ export function AgentChatView() {
dangerouslySetInnerHTML={{
__html: input
? highlightMentions(
- input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"),
- agents,
- )
- .replace(/<mention>/g, '<span class="mention-highlight">')
- .replace(/<\/mention>/g, "</span>")
+ input.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"),
+ agents,
+ )
+ .replace(/<mention>/g, '<span class="mention-highlight">')
+ .replace(/<\/mention>/g, "</span>")
: "",
}}
/>
@@ -1130,22 +1265,26 @@ export function AgentChatView() {
<div className="flex items-center justify-between px-2 pb-2 pt-0.5">
<div className="flex items-center gap-1">
<Tooltip>
- <TooltipTrigger render={
- <Button
- variant="ghost"
- size="icon-sm"
- onClick={handleReset}
- disabled={resetting || !conversation || messages.length === 0}
- className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
- />
- }>
- {resetting ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : (
- <RotateCcw className="size-3.5" />
- )}
- </TooltipTrigger>
- <TooltipContent side="top">New conversation</TooltipContent>
+ <TooltipTrigger render={(props) => (
+ <span {...props} className={cn("inline-flex", props.className)}>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={handleNap}
+ disabled={napping || !conversation || !currentConvHasMessages}
+ className="rounded-lg text-muted-foreground/60 hover:text-foreground transition-colors duration-200"
+ >
+ {napping ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <BedDouble className="size-3.5" />
+ )}
+ </Button>
+ </span>
+ )} />
+ <TooltipContent side="top">
+ {currentConvHasMessages ? "Take a nap" : `${agentName} is well-rested and ready to go`}
+ </TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger render={
@@ -1255,48 +1394,6 @@ export function AgentChatView() {
</div>
</div>}
- <Dialog open={resetConfirmOpen} onOpenChange={setResetConfirmOpen}>
- <DialogContent showCloseButton={false}>
- <DialogHeader>
- <DialogTitle>Start new conversation?</DialogTitle>
- <DialogDescription>
- This will clear the current conversation and start fresh. The agent won&apos;t remember context from this chat.
- </DialogDescription>
- </DialogHeader>
- <label className="flex items-center gap-2 text-sm text-muted-foreground cursor-pointer select-none">
- <input
- type="checkbox"
- checked={resetDontAsk}
- onChange={(e) => setResetDontAsk(e.target.checked)}
- className="rounded"
- />
- Don&apos;t ask me next time
- </label>
- <DialogFooter>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setResetConfirmOpen(false)}
- disabled={resetting}
- >
- Cancel
- </Button>
- <Button
- size="sm"
- onClick={() => {
- if (resetDontAsk) {
- localStorage.setItem(RESET_SKIP_KEY, "true");
- }
- executeReset();
- }}
- disabled={resetting}
- >
- {resetting ? "Resetting..." : "Reset"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
-
<ArtifactSheet
open={artifactSheetOpen}
onOpenChange={(v) => {
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index 95860ab58..5992576da 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -94,11 +94,11 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
};
return (
- <nav className="flex h-full w-14 flex-col items-center py-2 gap-0.5">
+ <nav className="flex h-full w-14 flex-col items-center pt-1 pb-2 gap-0.5">
{/* Top — logo as Home link */}
- <div className="pb-2 border-b border-border/50 mb-1">
+ <div className="pb-1.5 border-b border-border/50 mb-1">
<div
- className="flex shrink-0 items-center justify-center size-10 cursor-pointer [&>button]:pointer-events-none"
+ className="flex shrink-0 items-center justify-center size-8 cursor-pointer [&>button]:pointer-events-none"
onClick={() => { router.push(`${prefix}/home`); onNavigate?.(); }}
>
<Logo size="sm" iconOnly />
diff --git a/src/web/src/components/channel-bar.tsx b/src/web/src/components/channel-bar.tsx
new file mode 100644
index 000000000..30e470837
--- /dev/null
+++ b/src/web/src/components/channel-bar.tsx
@@ -0,0 +1,307 @@
+"use client";
+
+import { useState, useRef, useEffect, useCallback } from "react";
+import Image from "next/image";
+import { Plus, Pencil, Trash2 } from "lucide-react";
+import { useChannel } from "@/contexts/channel-context";
+import { useSidebarTrigger } from "@/components/workspace-shell";
+import { cn } from "@/lib/utils";
+import {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSeparator,
+ ContextMenuTrigger,
+} from "@/components/ui/context-menu";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Button } from "@/components/ui/button";
+import { toast } from "sonner";
+
+export function ChannelBar({ isMobile = false }: { isMobile?: boolean }) {
+ const {
+ channels,
+ activeChannel,
+ loading,
+ setActiveChannel,
+ createChannel,
+ renameChannel,
+ deleteChannel,
+ } = useChannel();
+
+ const [creating, setCreating] = useState(false);
+ const [renamingId, setRenamingId] = useState<string | null>(null);
+ const [deletingId, setDeletingId] = useState<string | null>(null);
+
+ if (loading) {
+ return (
+ <div className="h-8 flex items-center gap-1.5 px-2 mb-1 shrink-0">
+ {isMobile && <BarLogo />}
+ <div className="h-5 w-14 rounded-md bg-muted animate-pulse" />
+ <div className="h-5 w-12 rounded-md bg-muted animate-pulse" />
+ <div className="h-5 w-16 rounded-md bg-muted animate-pulse" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-8 flex items-center gap-1.5 px-2 mb-1 overflow-x-auto thin-scrollbar shrink-0">
+ {isMobile && <BarLogo />}
+ {channels.map((ch) =>
+ renamingId === ch.id ? (
+ <RenameInput
+ key={ch.id}
+ currentName={ch.name}
+ onSave={async (name) => {
+ try {
+ await renameChannel(ch.id, name);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to rename");
+ }
+ setRenamingId(null);
+ }}
+ onCancel={() => setRenamingId(null)}
+ />
+ ) : (
+ <ChannelPill
+ key={ch.id}
+ id={ch.id}
+ name={ch.name}
+ active={ch.name === activeChannel}
+ deleting={deletingId === ch.id}
+ onSelect={() => setActiveChannel(ch.name)}
+ onRename={() => setRenamingId(ch.id)}
+ onDeleteRequest={() => setDeletingId(ch.id)}
+ onDeleteCancel={() => setDeletingId(null)}
+ onDeleteConfirm={async () => {
+ try {
+ await deleteChannel(ch.id);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to delete");
+ }
+ setDeletingId(null);
+ }}
+ />
+ )
+ )}
+
+ {creating ? (
+ <CreateInput
+ onSave={async (name) => {
+ try {
+ await createChannel(name);
+ setActiveChannel(name);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : "Failed to create");
+ }
+ setCreating(false);
+ }}
+ onCancel={() => setCreating(false)}
+ />
+ ) : (
+ <button
+ onClick={() => setCreating(true)}
+ className="h-5 w-5 rounded-md border border-dashed border-muted-foreground/30 text-muted-foreground hover:border-foreground/50 hover:text-foreground hover:bg-accent transition-colors duration-200 inline-flex items-center justify-center cursor-pointer shrink-0"
+ >
+ <Plus className="size-3" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+function ChannelPill({
+ id,
+ name,
+ active,
+ deleting,
+ onSelect,
+ onRename,
+ onDeleteRequest,
+ onDeleteCancel,
+ onDeleteConfirm,
+}: {
+ id: string;
+ name: string;
+ active: boolean;
+ deleting: boolean;
+ onSelect: () => void;
+ onRename: () => void;
+ onDeleteRequest: () => void;
+ onDeleteCancel: () => void;
+ onDeleteConfirm: () => void;
+}) {
+ const isDefault = name === "default";
+
+ const pillClasses = cn(
+ "h-5 px-1.5 rounded-md text-[11px] font-medium inline-flex items-center gap-1 cursor-pointer select-none transition-colors duration-200 shrink-0",
+ "active:translate-y-px focus-visible:ring-2 focus-visible:ring-ring/50 outline-none",
+ active
+ ? "bg-secondary text-foreground shadow-sm ring-1 ring-foreground/5"
+ : "text-muted-foreground hover:text-foreground hover:bg-accent"
+ );
+
+ if (isDefault) {
+ return (
+ <button onClick={onSelect} className={pillClasses}>
+ {name}
+ </button>
+ );
+ }
+
+ return (
+ <Popover open={deleting} onOpenChange={(open) => { if (!open) onDeleteCancel(); }}>
+ <ContextMenu>
+ <ContextMenuTrigger className="inline-flex">
+ <PopoverTrigger
+ render={
+ <button onClick={onSelect} className={pillClasses} />
+ }
+ >
+ {name}
+ </PopoverTrigger>
+ </ContextMenuTrigger>
+ <ContextMenuContent>
+ <ContextMenuItem onClick={onRename}>
+ <Pencil className="size-3.5 mr-2" />
+ Rename
+ </ContextMenuItem>
+ <ContextMenuSeparator />
+ <ContextMenuItem
+ onClick={onDeleteRequest}
+ className="text-destructive focus:text-destructive"
+ >
+ <Trash2 className="size-3.5 mr-2" />
+ Delete
+ </ContextMenuItem>
+ </ContextMenuContent>
+ </ContextMenu>
+ <PopoverContent className="w-auto p-3" align="start">
+ <p className="text-sm mb-3">
+ Delete &ldquo;{name}&rdquo;? Its conversations will be removed.
+ </p>
+ <div className="flex gap-2 justify-end">
+ <Button variant="ghost" size="sm" onClick={onDeleteCancel}>
+ Cancel
+ </Button>
+ <Button variant="destructive" size="sm" onClick={onDeleteConfirm}>
+ Delete
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+function CreateInput({
+ onSave,
+ onCancel,
+}: {
+ onSave: (name: string) => void;
+ onCancel: () => void;
+}) {
+ const ref = useRef<HTMLInputElement>(null);
+ const savedRef = useRef(false);
+ const [value, setValue] = useState("");
+
+ useEffect(() => {
+ ref.current?.focus();
+ }, []);
+
+ const handleSubmit = useCallback(() => {
+ const trimmed = value.trim();
+ if (trimmed) {
+ savedRef.current = true;
+ onSave(trimmed);
+ } else {
+ onCancel();
+ }
+ }, [value, onSave, onCancel]);
+
+ return (
+ <input
+ ref={ref}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleSubmit();
+ if (e.key === "Escape") onCancel();
+ }}
+ onBlur={() => { if (!savedRef.current) onCancel(); }}
+ placeholder="name..."
+ className="h-5 w-24 px-1.5 rounded-md text-[11px] bg-transparent border border-input focus:border-ring focus:ring-2 focus:ring-ring/50 placeholder:text-muted-foreground/50 outline-none shrink-0"
+ />
+ );
+}
+
+function RenameInput({
+ currentName,
+ onSave,
+ onCancel,
+}: {
+ currentName: string;
+ onSave: (name: string) => void;
+ onCancel: () => void;
+}) {
+ const ref = useRef<HTMLInputElement>(null);
+ const savedRef = useRef(false);
+ const [value, setValue] = useState(currentName);
+
+ useEffect(() => {
+ ref.current?.focus();
+ ref.current?.select();
+ }, []);
+
+ const handleSubmit = useCallback(() => {
+ const trimmed = value.trim();
+ if (trimmed && trimmed !== currentName) {
+ savedRef.current = true;
+ onSave(trimmed);
+ } else {
+ onCancel();
+ }
+ }, [value, currentName, onSave, onCancel]);
+
+ return (
+ <input
+ ref={ref}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleSubmit();
+ if (e.key === "Escape") onCancel();
+ }}
+ onBlur={() => { if (!savedRef.current) onCancel(); }}
+ className="h-5 w-24 px-1.5 rounded-md text-[11px] bg-transparent border border-input focus:border-ring focus:ring-2 focus:ring-ring/50 outline-none shrink-0"
+ />
+ );
+}
+
+function BarLogo() {
+ const openSidebar = useSidebarTrigger();
+ const [mounted, setMounted] = useState(false);
+ useEffect(() => { setMounted(true); }, []);
+
+ if (!openSidebar) return null;
+
+ const img = mounted ? (
+ <>
+ <Image src="/alook.svg" alt="Alook" width={20} height={20} className="dark:hidden" />
+ <Image src="/alook-dark.svg" alt="Alook" width={20} height={20} className="hidden dark:block" />
+ </>
+ ) : (
+ <span className="size-5" />
+ );
+
+ return (
+ <button
+ onClick={openSidebar}
+ className="shrink-0 cursor-pointer transition-opacity hover:opacity-70 mr-1"
+ >
+ {img}
+ </button>
+ );
+}
diff --git a/src/web/src/components/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsx
index c0aa796cf..486e16c31 100644
--- a/src/web/src/components/workspace-shell.tsx
+++ b/src/web/src/components/workspace-shell.tsx
@@ -2,6 +2,7 @@
import { createContext, useContext, type ReactNode, useState } from "react";
import { AppSidebar } from "@/components/app-sidebar";
+import { ChannelBar } from "@/components/channel-bar";
import { GradientBackground } from "@/components/gradient-background";
import { useIsMobile } from "@/hooks/use-mobile";
import {
@@ -24,8 +25,9 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {
<SidebarTriggerContext.Provider value={() => setSidebarOpen(true)}>
<div className="flex flex-col h-dvh overflow-hidden relative">
<GradientBackground />
- <div className="flex-1 min-h-0 px-2 pb-2 pt-2">
- <main className="h-full rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">
+ <div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col">
+ <ChannelBar isMobile />
+ <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">
{children}
</main>
</div>
@@ -43,8 +45,9 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {
<div className="flex h-dvh overflow-hidden relative">
<GradientBackground />
<AppSidebar />
- <div className="flex-1 min-w-0 p-2 pl-0">
- <main className="h-full rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">
+ <div className="flex-1 flex flex-col min-w-0 pt-1 pr-2 pb-2">
+ <ChannelBar />
+ <main className="flex-1 min-h-0 rounded-xl bg-card/80 backdrop-blur-xl shadow-lg ring-1 ring-border/40 overflow-hidden flex flex-col">
{children}
</main>
</div>
diff --git a/src/web/src/contexts/channel-context.tsx b/src/web/src/contexts/channel-context.tsx
new file mode 100644
index 000000000..32c9dc909
--- /dev/null
+++ b/src/web/src/contexts/channel-context.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import {
+ createContext,
+ useContext,
+ useState,
+ useEffect,
+ useCallback,
+ type ReactNode,
+} from "react";
+import type { Channel } from "@alook/shared";
+import {
+ listChannels,
+ createChannelApi,
+ renameChannelApi,
+ deleteChannelApi,
+} from "@/lib/api";
+
+interface ChannelContextValue {
+ channels: Channel[];
+ activeChannel: string;
+ loading: boolean;
+ setActiveChannel: (name: string) => void;
+ createChannel: (name: string) => Promise<Channel>;
+ renameChannel: (id: string, name: string) => Promise<void>;
+ deleteChannel: (id: string) => Promise<void>;
+ refresh: () => Promise<void>;
+}
+
+const ChannelContext = createContext<ChannelContextValue | null>(null);
+
+function storageKey(workspaceId: string) {
+ return `alook:channel:${workspaceId}`;
+}
+
+export function ChannelProvider({
+ workspaceId,
+ children,
+}: {
+ workspaceId: string;
+ children: ReactNode;
+}) {
+ const [channels, setChannels] = useState<Channel[]>([]);
+ const [activeChannel, setActiveChannelState] = useState<string>("default");
+ const [loading, setLoading] = useState(true);
+
+ const fetchChannels = useCallback(async () => {
+ try {
+ const list = await listChannels(workspaceId);
+ setChannels(list);
+ } catch {
+ // fallback — at minimum show default
+ setChannels([]);
+ }
+ }, [workspaceId]);
+
+ useEffect(() => {
+ const stored =
+ typeof window !== "undefined"
+ ? localStorage.getItem(storageKey(workspaceId))
+ : null;
+ if (stored) {
+ setActiveChannelState(stored);
+ }
+ fetchChannels().finally(() => setLoading(false));
+ }, [workspaceId, fetchChannels]);
+
+ const setActiveChannel = useCallback(
+ (name: string) => {
+ setActiveChannelState(name);
+ if (typeof window !== "undefined") {
+ localStorage.setItem(storageKey(workspaceId), name);
+ }
+ },
+ [workspaceId]
+ );
+
+ const createChannel = useCallback(
+ async (name: string) => {
+ const created = await createChannelApi(workspaceId, name);
+ await fetchChannels();
+ return created;
+ },
+ [workspaceId, fetchChannels]
+ );
+
+ const renameChannel = useCallback(
+ async (id: string, name: string) => {
+ const ch = channels.find((c) => c.id === id);
+ await renameChannelApi(id, workspaceId, name);
+ if (ch && ch.name === activeChannel) {
+ setActiveChannel(name);
+ }
+ await fetchChannels();
+ },
+ [workspaceId, channels, activeChannel, setActiveChannel, fetchChannels]
+ );
+
+ const deleteChannel = useCallback(
+ async (id: string) => {
+ const ch = channels.find((c) => c.id === id);
+ await deleteChannelApi(id, workspaceId);
+ if (ch && ch.name === activeChannel) {
+ setActiveChannel("default");
+ }
+ await fetchChannels();
+ },
+ [workspaceId, channels, activeChannel, setActiveChannel, fetchChannels]
+ );
+
+ return (
+ <ChannelContext.Provider
+ value={{
+ channels,
+ activeChannel,
+ loading,
+ setActiveChannel,
+ createChannel,
+ renameChannel,
+ deleteChannel,
+ refresh: fetchChannels,
+ }}
+ >
+ {children}
+ </ChannelContext.Provider>
+ );
+}
+
+export function useChannel() {
+ const ctx = useContext(ChannelContext);
+ if (!ctx) {
+ throw new Error("useChannel must be used within a ChannelProvider");
+ }
+ return ctx;
+}
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 174f5c1a0..82220c88b 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -4,6 +4,7 @@ import type {
AgentRuntime,
Artifact,
CalendarEvent,
+ Channel,
Conversation,
CreateAgentRequest,
CreateCalendarEventRequest,
@@ -150,27 +151,54 @@ export const triggerRuntimeRescan = (runtimeId: string, workspaceId: string) =>
export const fetchLatestCliVersion = () =>
apiFetch<{ version: string }>("/api/cli/latest-version");
+// Channels
+export const listChannels = (workspaceId: string) =>
+ apiFetch<Channel[]>(`/api/channels${wsQuery(workspaceId)}`);
+
+export const createChannelApi = (workspaceId: string, name: string) =>
+ apiFetch<Channel>(`/api/channels${wsQuery(workspaceId)}`, {
+ method: "POST",
+ body: JSON.stringify({ name }),
+ });
+
+export const renameChannelApi = (id: string, workspaceId: string, name: string) =>
+ apiFetch<Channel>(`/api/channels/${id}${wsQuery(workspaceId)}`, {
+ method: "PATCH",
+ body: JSON.stringify({ name }),
+ });
+
+export const deleteChannelApi = (id: string, workspaceId: string) =>
+ apiFetch<{ ok: boolean }>(`/api/channels/${id}${wsQuery(workspaceId)}`, {
+ method: "DELETE",
+ });
+
// Conversations
-export const listConversations = (workspaceId: string) =>
- apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId)}`);
+export const listConversations = (workspaceId: string, channel?: string) =>
+ apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);
-export const createConversation = (agentId: string, workspaceId: string) =>
+export const createConversation = (agentId: string, workspaceId: string, channel?: string) =>
apiFetch<Conversation>(`/api/conversations${wsQuery(workspaceId)}`, {
method: "POST",
- body: JSON.stringify({ agent_id: agentId }),
+ body: JSON.stringify({ agent_id: agentId, ...(channel ? { channel } : {}) }),
});
export const getConversation = (id: string, workspaceId: string) =>
apiFetch<Conversation>(`/api/conversations/${id}${wsQuery(workspaceId)}`);
-export const listAgentConversations = (agentId: string, workspaceId: string) =>
- apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations${wsQuery(workspaceId)}`);
+export const listAgentConversations = (agentId: string, workspaceId: string, channel?: string) =>
+ apiFetch<Conversation[]>(`/api/agents/${agentId}/conversations${wsQuery(workspaceId, channel ? { channel } : undefined)}`);
-export const getOrCreateAgentConversation = (agentId: string, workspaceId: string) =>
+export const getOrCreateAgentConversation = (agentId: string, workspaceId: string, channel?: string) =>
apiFetch<Conversation>(`/api/agents/${agentId}/conversation${wsQuery(workspaceId)}`, {
method: "POST",
+ body: JSON.stringify({ ...(channel ? { channel } : {}) }),
});
+export interface PreviousConversation {
+ id: string;
+ created_at: string;
+}
+
export interface ChatInitResponse {
conversation: Conversation;
messages: Message[];
@@ -179,11 +207,27 @@ export interface ChatInitResponse {
active_task: TaskApi | null;
task_messages: TaskMessage[];
has_more_messages: boolean;
+ previous_conversations: PreviousConversation[];
+ has_more_conversations: boolean;
}
-export const chatInit = (agentId: string, workspaceId: string) =>
+export const listPreviousConversations = (
+ agentId: string,
+ workspaceId: string,
+ opts: { exclude: string; before: string; channel?: string; limit?: number },
+) => {
+ const extra: Record<string, string> = { exclude: opts.exclude, before: opts.before };
+ if (opts.channel) extra.channel = opts.channel;
+ if (opts.limit) extra.limit = String(opts.limit);
+ return apiFetch<{ conversations: PreviousConversation[]; has_more: boolean }>(
+ `/api/agents/${agentId}/conversations${wsQuery(workspaceId, extra)}`,
+ );
+};
+
+export const chatInit = (agentId: string, workspaceId: string, channel?: string) =>
apiFetch<ChatInitResponse>(`/api/agents/${agentId}/chat-init${wsQuery(workspaceId)}`, {
method: "POST",
+ body: JSON.stringify({ ...(channel ? { channel } : {}) }),
});
export const deleteConversation = (id: string, workspaceId: string) =>
diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.ts
index 9c0c871f8..29d80147f 100644
--- a/src/web/src/lib/api/responses.test.ts
+++ b/src/web/src/lib/api/responses.test.ts
@@ -5,6 +5,7 @@ import {
agentToResponse,
taskToResponse,
conversationToResponse,
+ channelToResponse,
messageToResponse,
runtimeToResponse,
machineTokenToResponse,
@@ -338,9 +339,9 @@ describe("AgentResponse shape", () => {
});
describe("ConversationResponse shape", () => {
- it("has expected keys: id, agent_id, title, type, created_at", () => {
- const res = conversationToResponse({ id: "c1", agentId: "a1", title: "Chat", type: "user_dm_message", createdAt: ts });
- expect(Object.keys(res).sort()).toEqual(["agent_id", "created_at", "id", "title", "type"]);
+ 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", () => {
@@ -348,6 +349,16 @@ describe("ConversationResponse shape", () => {
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 });
@@ -356,6 +367,23 @@ describe("ConversationResponse shape", () => {
});
});
+describe("channelToResponse", () => {
+ it("maps DB fields to API response format", () => {
+ const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "work", createdAt: ts });
+ expect(res).toEqual({
+ id: "ch_1",
+ workspace_id: "w1",
+ name: "work",
+ created_at: tsFormatted,
+ });
+ });
+
+ it("has expected keys: id, workspace_id, name, created_at", () => {
+ const res = channelToResponse({ id: "ch_1", workspaceId: "w1", name: "personal", createdAt: ts });
+ expect(Object.keys(res).sort()).toEqual(["created_at", "id", "name", "workspace_id"]);
+ });
+});
+
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 });
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index a220da4de..567b79480 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -116,6 +116,7 @@ export function conversationToResponse(c: any) {
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.messageCount !== undefined) {
@@ -124,6 +125,15 @@ export function conversationToResponse(c: any) {
return resp;
}
+export function channelToResponse(c: any) {
+ return {
+ id: c.id,
+ workspace_id: c.workspaceId,
+ name: c.name,
+ created_at: formatTimestamp(c.createdAt),
+ };
+}
+
export function messageToResponse(m: any) {
const resp: any = {
id: m.id,