Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add message threads and rename /threads route to /traces

Gus947c5d9b7f64
diff --git a/src/cli/daemon/prompt.ts b/src/cli/daemon/prompt.ts
index eef45b025..718e79f5b 100644
--- a/src/cli/daemon/prompt.ts
+++ b/src/cli/daemon/prompt.ts
@@ -57,6 +57,13 @@ export function buildTaskObject(task: Task, attachments?: Attachment[]): Record<
if (ctx?.quoted_message) {
obj.quoted_message = ctx.quoted_message;
}
+ if (ctx?.conversation_history || ctx?.root_message) {
+ obj.thread_context = {
+ note: "The user started this thread by replying to the root_message below. The history is the conversation leading up to it.",
+ ...(ctx.root_message ? { root_message: ctx.root_message } : {}),
+ ...(ctx.conversation_history ? { history: ctx.conversation_history } : {}),
+ };
+ }
}
if (task.type === "email_notification") {
const ctx = task.context as Record<string, unknown> | undefined;
diff --git a/src/shared/src/db/queries/conversation.ts b/src/shared/src/db/queries/conversation.ts
index 21466062f..8c0db9fd4 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, ne, lt, sql, count as drizzleCount, inArray } from "drizzle-orm";
+import { eq, and, desc, ne, lt, sql, count as drizzleCount, inArray, isNull, isNotNull } from "drizzle-orm";
import { conversation, message } from "../schema";
import type { Database } from "../index";
import { TASK_TYPES, type TaskType } from "../../constants";
@@ -13,6 +13,8 @@ export async function createConversation(
title: string;
type?: TaskType;
channel?: string;
+ parentMessageId?: string;
+ threadTitle?: string;
}
) {
const rows = await db
@@ -24,6 +26,7 @@ export async function createConversation(
title: data.title,
type: data.type ?? TASK_TYPES.USER_DM_MESSAGE,
channel: data.channel ?? "default",
+ ...(data.parentMessageId ? { parentMessageId: data.parentMessageId, threadTitle: data.threadTitle ?? "" } : {}),
})
.returning();
return rows[0]!;
@@ -54,6 +57,7 @@ export async function listConversations(
const conditions = [
eq(conversation.workspaceId, workspaceId),
eq(conversation.userId, userId),
+ isNull(conversation.parentMessageId),
];
if (channel) {
conditions.push(eq(conversation.channel, channel));
@@ -76,6 +80,7 @@ export async function listConversationsByAgent(
eq(conversation.workspaceId, workspaceId),
eq(conversation.userId, userId),
eq(conversation.agentId, agentId),
+ isNull(conversation.parentMessageId),
];
if (channel) {
conditions.push(eq(conversation.channel, channel));
@@ -124,6 +129,7 @@ export async function getOrCreateAgentConversation(
eq(conversation.userId, userId),
eq(conversation.agentId, agentId),
eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE),
+ isNull(conversation.parentMessageId),
];
if (channel) {
conditions.push(eq(conversation.channel, channel));
@@ -177,6 +183,7 @@ export async function listPreviousConversations(
eq(conversation.agentId, agentId),
eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE),
ne(conversation.id, excludeId),
+ isNull(conversation.parentMessageId),
];
if (channel) {
conditions.push(eq(conversation.channel, channel));
@@ -193,6 +200,115 @@ export async function listPreviousConversations(
.limit(limit);
}
+export async function getThreadByParentMessage(
+ db: Database,
+ parentMessageId: string,
+ workspaceId: string
+) {
+ const rows = await db
+ .select()
+ .from(conversation)
+ .where(
+ and(
+ eq(conversation.parentMessageId, parentMessageId),
+ eq(conversation.workspaceId, workspaceId)
+ )
+ )
+ .limit(1);
+ return rows[0] ?? null;
+}
+
+export async function getThreadsByParentMessages(
+ db: Database,
+ workspaceId: string,
+ parentMessageIds: string[]
+) {
+ if (parentMessageIds.length === 0) return [];
+ return db
+ .select({
+ id: conversation.id,
+ parentMessageId: conversation.parentMessageId,
+ threadTitle: conversation.threadTitle,
+ createdAt: conversation.createdAt,
+ replyCount:
+ sql<number>`COUNT(CASE WHEN ${message.status} = 'active' THEN 1 END)`.mapWith(Number),
+ lastReplyAt:
+ sql<string>`MAX(${message.createdAt})`,
+ })
+ .from(conversation)
+ .leftJoin(message, eq(message.conversationId, conversation.id))
+ .where(
+ and(
+ inArray(conversation.parentMessageId, parentMessageIds),
+ eq(conversation.workspaceId, workspaceId)
+ )
+ )
+ .groupBy(conversation.id);
+}
+
+export async function getThreadsByConversation(
+ db: Database,
+ workspaceId: string,
+ conversationId: string
+) {
+ return db
+ .select({
+ id: conversation.id,
+ parentMessageId: conversation.parentMessageId,
+ threadTitle: conversation.threadTitle,
+ createdAt: conversation.createdAt,
+ replyCount:
+ sql<number>`COUNT(CASE WHEN ${message.status} = 'active' THEN 1 END)`.mapWith(Number),
+ lastReplyAt:
+ sql<string>`MAX(${message.createdAt})`,
+ })
+ .from(conversation)
+ .leftJoin(message, eq(message.conversationId, conversation.id))
+ .where(
+ and(
+ eq(conversation.workspaceId, workspaceId),
+ sql`${conversation.parentMessageId} IN (SELECT id FROM message WHERE conversation_id = ${conversationId} AND status = 'active')`
+ )
+ )
+ .groupBy(conversation.id);
+}
+
+export async function listThreadsByAgent(
+ db: Database,
+ workspaceId: string,
+ agentId: string,
+ opts?: { limit?: number; before?: string }
+) {
+ const conditions = [
+ eq(conversation.workspaceId, workspaceId),
+ eq(conversation.agentId, agentId),
+ isNotNull(conversation.parentMessageId),
+ ];
+ if (opts?.before) {
+ conditions.push(lt(conversation.createdAt, opts.before));
+ }
+ const limit = opts?.limit ?? 30;
+ return db
+ .select({
+ id: conversation.id,
+ parentMessageId: conversation.parentMessageId,
+ threadTitle: conversation.threadTitle,
+ createdAt: conversation.createdAt,
+ replyCount:
+ sql<number>`COUNT(CASE WHEN ${message.status} = 'active' THEN 1 END)`.mapWith(Number),
+ lastReplyAt:
+ sql<string>`MAX(${message.createdAt})`,
+ lastReplyPreview:
+ sql<string>`(SELECT SUBSTR(m2.content, 1, 60) FROM message m2 WHERE m2.conversation_id = ${conversation.id} AND m2.status = 'active' ORDER BY m2.created_at DESC LIMIT 1)`,
+ })
+ .from(conversation)
+ .leftJoin(message, eq(message.conversationId, conversation.id))
+ .where(and(...conditions))
+ .groupBy(conversation.id)
+ .orderBy(desc(sql`MAX(${message.createdAt})`))
+ .limit(limit);
+}
+
export async function hasPreviousConversations(
db: Database,
workspaceId: string,
@@ -207,6 +323,7 @@ export async function hasPreviousConversations(
eq(conversation.agentId, agentId),
eq(conversation.type, TASK_TYPES.USER_DM_MESSAGE),
ne(conversation.id, excludeId),
+ isNull(conversation.parentMessageId),
];
if (channel) {
conditions.push(eq(conversation.channel, channel));
diff --git a/src/shared/src/db/queries/message.ts b/src/shared/src/db/queries/message.ts
index d4d7be173..487fbec15 100644
--- a/src/shared/src/db/queries/message.ts
+++ b/src/shared/src/db/queries/message.ts
@@ -1,4 +1,4 @@
-import { eq, asc, desc, and, lt, gte, or, count } from "drizzle-orm";
+import { eq, asc, desc, and, lt, gte, or, count, sql } from "drizzle-orm";
import { message } from "../schema";
import type { Database } from "../index";
@@ -114,6 +114,31 @@ export async function updateMessageTaskId(db: Database, messageId: string, taskI
await db.update(message).set({ taskId }).where(eq(message.id, messageId));
}
+export async function listMessagesUpTo(
+ db: Database,
+ conversationId: string,
+ targetMessageId: string
+) {
+ const target = await db
+ .select({ createdAt: message.createdAt })
+ .from(message)
+ .where(eq(message.id, targetMessageId));
+ if (target.length === 0) return [];
+ const pivotTime = target[0]!.createdAt;
+ const rows = await db
+ .select()
+ .from(message)
+ .where(
+ and(
+ eq(message.conversationId, conversationId),
+ eq(message.status, "active"),
+ sql`(${message.createdAt} < ${pivotTime} OR ${message.id} = ${targetMessageId})`
+ )
+ )
+ .orderBy(asc(message.createdAt));
+ return rows;
+}
+
export async function listMessagesAroundTask(
db: Database,
conversationId: string,
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 31313ec87..126962be4 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -304,12 +304,15 @@ export const conversation = sqliteTable(
title: text("title").notNull().default(""),
type: text("type").notNull().default(TASK_TYPES.USER_DM_MESSAGE),
channel: text("channel").notNull().default("default"),
+ parentMessageId: text("parent_message_id"),
+ threadTitle: text("thread_title").notNull().default(""),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
},
(t) => [
index("idx_conversation_agent_lookup")
.on(t.workspaceId, t.agentId, t.userId, t.type, t.channel, t.createdAt),
index("idx_conversation_ws_user").on(t.workspaceId, t.userId, t.createdAt),
+ index("idx_conversation_thread").on(t.parentMessageId),
foreignKey({
columns: [t.agentId, t.workspaceId],
foreignColumns: [agent.id, agent.workspaceId],
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 0c181e7c5..49df0b9b2 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -167,6 +167,7 @@ export {
SkillSyncRequestSchema,
CreateStudioRequestSchema,
RecruitAgentRequestSchema,
+ CreateThreadRequestSchema,
DaemonPushMessageSchema,
} from "./schemas";
@@ -217,6 +218,7 @@ export type {
SkillSyncRequest,
CreateStudioRequest,
RecruitAgentRequest,
+ CreateThreadRequest,
DaemonPushMessageType,
} from "./schemas";
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 63e632961..c92518dd6 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -802,3 +802,10 @@ export const RecruitAgentRequestSchema = z.object({
context_key: z.string().optional(),
});
export type RecruitAgentRequest = z.infer<typeof RecruitAgentRequestSchema>;
+
+export const CreateThreadRequestSchema = z.object({
+ parent_message_id: z.string().min(1),
+ content: z.string().optional().default(""),
+ attachment_ids: z.array(z.string()).optional(),
+});
+export type CreateThreadRequest = z.infer<typeof CreateThreadRequestSchema>;
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index 60fce14fd..48f89daab 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -67,6 +67,8 @@ export interface Conversation {
title: string;
type: string;
channel: string;
+ parent_message_id?: string | null;
+ thread_title?: string;
created_at: string;
message_count?: number;
}
@@ -293,6 +295,8 @@ export type WsMessage =
| { type: "agent.created"; agentId: string; workspaceId: string; parentAgentId: string }
| { type: "issue.comment"; issueId: string; comment: IssueComment }
| { type: "workspace.files"; agentId: string; requestId: string; requestType: "tree" | "read"; result: WorkspaceFileResult }
+ | { type: "thread.created"; conversationId: string; threadConversationId: string; parentMessageId: string; threadTitle: string }
+ | { type: "thread.reply"; conversationId: string; threadConversationId: string; parentMessageId: string; replyCount: number }
export interface WorkspaceFileResult {
entries?: WorkspaceFileEntry[];
diff --git a/src/web/migrations/0039_add_thread_columns.sql b/src/web/migrations/0039_add_thread_columns.sql
new file mode 100644
index 000000000..acde2fd99
--- /dev/null
+++ b/src/web/migrations/0039_add_thread_columns.sql
@@ -0,0 +1,6 @@
+-- Add thread support: a thread is a conversation linked to a parent message
+ALTER TABLE conversation ADD COLUMN parent_message_id TEXT;
+ALTER TABLE conversation ADD COLUMN thread_title TEXT NOT NULL DEFAULT '';
+
+CREATE INDEX idx_conversation_thread ON conversation (parent_message_id)
+ WHERE parent_message_id IS NOT NULL;
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 3a93c9f3e..b253d9f46 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
@@ -184,11 +184,11 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
}`}>Files</span>
</Link>
<Link
- href={`/w/${slug}/threads?agentId=${agentId}`}
+ href={`/w/${slug}/traces?agentId=${agentId}`}
className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-foreground transition-all"
>
<GitBranch className="size-3 shrink-0" />
- <span className="max-w-0 opacity-0 group-hover:max-w-20 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Threads</span>
+ <span className="max-w-0 opacity-0 group-hover:max-w-20 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Traces</span>
</Link>
<div className="w-px h-4 bg-border mx-1" />
<button
@@ -253,7 +253,7 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
)}
<DropdownMenuItem
onClick={() =>
- router.push(`/w/${slug}/threads?agentId=${agentId}`)
+ router.push(`/w/${slug}/traces?agentId=${agentId}`)
}
>
<GitBranch className="size-3.5" />
diff --git a/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
similarity index 99%
rename from src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx
rename to src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
index cf9bf1c24..f2fa4469c 100644
--- a/src/web/src/app/(app)/w/[slug]/threads/[traceId]/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
@@ -194,7 +194,7 @@ export default function TraceDetailPage() {
<div className="flex flex-col h-full">
<div className="sticky top-0 z-10 flex items-center gap-2 px-4 py-2.5 border-b border-border/30">
<Link
- href={`/w/${slug}/threads`}
+ href={`/w/${slug}/traces`}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<ArrowLeft className="size-3.5" />
diff --git a/src/web/src/app/(app)/w/[slug]/threads/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/page.tsx
similarity index 99%
rename from src/web/src/app/(app)/w/[slug]/threads/page.tsx
rename to src/web/src/app/(app)/w/[slug]/traces/page.tsx
index ff420f9e2..0506a98a1 100644
--- a/src/web/src/app/(app)/w/[slug]/threads/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/traces/page.tsx
@@ -91,7 +91,7 @@ function TraceRow({ trace, slug }: { trace: TraceListItem; slug: string }) {
return (
<Link
- href={`/w/${slug}/threads/${trace.trace_id}`}
+ href={`/w/${slug}/traces/${trace.trace_id}`}
className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
>
<div className="flex items-center gap-2">
@@ -263,7 +263,7 @@ export default function TracesPage() {
} else {
newParams.delete(key);
}
- const pathname = `/w/${slug}/threads`;
+ const pathname = `/w/${slug}/traces`;
const qs = newParams.toString();
router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
},
diff --git a/src/web/src/app/api/agents/[id]/chat-init/route.ts b/src/web/src/app/api/agents/[id]/chat-init/route.ts
index 53fee17ca..7fee48554 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
@@ -77,12 +77,6 @@ export const POST = withAuth(async (req, ctx) => {
let taskMessages: unknown[] = [];
if (activeTask) {
try {
- // Errors-only: the chat no longer renders thinking/tool steps (replies
- // arrive via `send-dm`). We preload only `type:"error"` rows for the active
- // task so a live error survives a reload while the run is still active.
- // (A run that ended in error is settled to status:"failed" by the daemon and
- // re-surfaces via its persisted assistant error message, not through here.)
- // Filters type==="error" + scopes by workspace in SQL.
const tmsgs = await queries.taskMessage.listTaskErrorMessages(
db,
activeTask.id,
diff --git a/src/web/src/app/api/agents/[id]/threads/route.ts b/src/web/src/app/api/agents/[id]/threads/route.ts
new file mode 100644
index 000000000..0f58ebf7c
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/threads/route.ts
@@ -0,0 +1,44 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries } from "@alook/shared";
+import { getDb } from "@/lib/db";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError } from "@/lib/middleware/helpers";
+
+export const GET = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const agentId = ctx.params?.id;
+ if (!agentId) {
+ return writeError("agent id is required", 400);
+ }
+
+ const url = new URL(req.url);
+ const before = url.searchParams.get("before") || undefined;
+ const limitParam = url.searchParams.get("limit");
+ const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;
+
+ const threads = await queries.conversation.listThreadsByAgent(
+ db, ws.workspaceId, agentId, { limit: limit + 1, before }
+ );
+
+ const hasMore = threads.length > limit;
+ const items = threads.slice(0, limit);
+
+ return writeJSON({
+ threads: items.map(t => ({
+ id: t.id,
+ parent_message_id: t.parentMessageId,
+ thread_title: t.threadTitle ?? "",
+ reply_count: t.replyCount,
+ last_reply_at: t.lastReplyAt,
+ last_reply_preview: t.lastReplyPreview ?? "",
+ created_at: t.createdAt,
+ })),
+ has_more: hasMore,
+ });
+});
diff --git a/src/web/src/app/api/conversations/[id]/init/route.ts b/src/web/src/app/api/conversations/[id]/init/route.ts
index c81912c3e..a845d010d 100644
--- a/src/web/src/app/api/conversations/[id]/init/route.ts
+++ b/src/web/src/app/api/conversations/[id]/init/route.ts
@@ -70,12 +70,6 @@ export const GET = withAuth(async (req, ctx) => {
let taskMessages: unknown[] = [];
if (activeTask) {
try {
- // Errors-only: the chat no longer renders thinking/tool steps (replies
- // arrive via `send-dm`). We preload only `type:"error"` rows for the active
- // task so a live error survives a reload while the run is still active.
- // (A run that ended in error is settled to status:"failed" by the daemon and
- // re-surfaces via its persisted assistant error message, not through here.)
- // Filters type==="error" + scopes by workspace in SQL.
const tmsgs = await queries.taskMessage.listTaskErrorMessages(
db,
activeTask.id,
@@ -87,6 +81,15 @@ export const GET = withAuth(async (req, ctx) => {
}
}
+ // For thread conversations, fetch the root message from parent conversation
+ let rootMessage = null;
+ if (conversation.parentMessageId) {
+ try {
+ const rm = await queries.message.getMessage(db, conversation.parentMessageId);
+ if (rm) rootMessage = messageToResponse(rm);
+ } catch {}
+ }
+
return writeJSON({
conversation: conversationToResponse(conversation),
messages: cacheValid ? null : messages.map(messageToResponse),
@@ -99,5 +102,6 @@ export const GET = withAuth(async (req, ctx) => {
task_messages: taskMessages,
cache_valid: cacheValid,
message_count: serverMessageCount,
+ ...(rootMessage ? { root_message: rootMessage } : {}),
});
});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index dc9df6a9b..3d6749e09 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -157,6 +157,19 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
message: messageToResponse(message),
}).catch(() => {});
+ // If this is a thread conversation, broadcast thread.reply with actual count
+ if (conversation.parentMessageId) {
+ queries.message.getActiveMessageCount(db, id).then((count) => {
+ broadcastToUser(ctx.userId, {
+ type: "thread.reply",
+ conversationId: id,
+ threadConversationId: id,
+ parentMessageId: conversation.parentMessageId!,
+ replyCount: count,
+ }).catch(() => {});
+ }).catch(() => {});
+ }
+
// Auto-title: conditional WHERE title = '' ensures only the first message sets it
queries.conversation.updateConversationTitle(db, id, truncateTitle(content)).catch(() => {});
diff --git a/src/web/src/app/api/conversations/[id]/threads/route.ts b/src/web/src/app/api/conversations/[id]/threads/route.ts
new file mode 100644
index 000000000..f10e9fa03
--- /dev/null
+++ b/src/web/src/app/api/conversations/[id]/threads/route.ts
@@ -0,0 +1,211 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries, TASK_TYPES, truncateTitle, CreateThreadRequestSchema } from "@alook/shared";
+import { getDb } from "@/lib/db";
+import { nanoid } from "nanoid";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
+import { conversationToResponse, messageToResponse, taskToResponse } from "@/lib/api/responses";
+import { TaskService } from "@/lib/services/task";
+import { log } from "@/lib/logger";
+import { broadcastToUser } from "@/lib/broadcast";
+import { invalidate, cacheKeys } from "@/lib/cache";
+
+export const POST = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const conversationId = ctx.params?.id;
+ if (!conversationId) {
+ return writeError("conversation id is required", 400);
+ }
+
+ const [body, valErr] = await parseBody(req, CreateThreadRequestSchema);
+ if (valErr) return valErr;
+
+ const parentConv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
+ if (!parentConv) {
+ return writeError("conversation not found", 404);
+ }
+
+ const rootMessage = await queries.message.getMessage(db, body.parent_message_id);
+ if (!rootMessage || rootMessage.conversationId !== conversationId) {
+ return writeError("parent message not found in this conversation", 404);
+ }
+
+ // Idempotent: check if thread already exists for this parent_message_id
+ const existing = await queries.conversation.getThreadByParentMessage(
+ db, body.parent_message_id, ws.workspaceId
+ );
+ if (existing) {
+ // Thread already exists — create message in the existing thread and enqueue task
+ const threadMessage = await queries.message.createMessage(db, {
+ conversationId: existing.id,
+ role: "user",
+ content: body.content,
+ });
+
+ broadcastToUser(ctx.userId, {
+ type: "conversation.message",
+ conversationId: existing.id,
+ message: messageToResponse(threadMessage),
+ }).catch(() => {});
+
+ const taskService = new TaskService(db);
+ const traceId = "tr_" + nanoid();
+ try {
+ const task = await taskService.enqueueTask(
+ parentConv.agentId,
+ existing.id,
+ ws.workspaceId,
+ body.content,
+ TASK_TYPES.USER_DM_MESSAGE,
+ {
+ contextKey: existing.id,
+ context: { message_id: threadMessage.id },
+ traceId,
+ parentTaskId: null,
+ },
+ );
+ queries.message.updateMessageTaskId(db, threadMessage.id, task.id).catch(() => {});
+ return writeJSON({
+ conversation: conversationToResponse(existing),
+ message: messageToResponse(threadMessage),
+ task: taskToResponse(task),
+ }, 200);
+ } catch (err: unknown) {
+ log.error("enqueueTask error (thread)", { err });
+ return writeError("failed to enqueue task", 500);
+ }
+ }
+
+ // Create new thread conversation
+ const threadTitle = truncateTitle(rootMessage.content).slice(0, 80);
+ const threadConv = await queries.conversation.createConversation(db, {
+ workspaceId: ws.workspaceId,
+ agentId: parentConv.agentId,
+ userId: ctx.userId,
+ title: "",
+ type: TASK_TYPES.USER_DM_MESSAGE,
+ channel: parentConv.channel ?? "default",
+ parentMessageId: body.parent_message_id,
+ threadTitle,
+ });
+
+ broadcastToUser(ctx.userId, {
+ type: "thread.created",
+ conversationId,
+ threadConversationId: threadConv.id,
+ parentMessageId: body.parent_message_id,
+ threadTitle,
+ }).catch(() => {});
+
+ // If no content, return just the conversation (eager creation, no message/task)
+ if (!body.content) {
+ return writeJSON({ conversation: conversationToResponse(threadConv), message: null, task: null }, 201);
+ }
+
+ // Fetch parent conversation history up to and including root message
+ const historyMessages = await queries.message.listMessagesUpTo(
+ db, conversationId, body.parent_message_id
+ );
+ const rootMsg = historyMessages.find(m => m.id === body.parent_message_id);
+ const historyWithoutRoot = historyMessages
+ .filter(m => m.id !== body.parent_message_id)
+ .map(m => ({ role: m.role, content: m.content, created_at: m.createdAt }));
+ const rootMessageContext = rootMsg
+ ? { role: rootMsg.role, content: rootMsg.content }
+ : null;
+
+ // Create user message in thread
+ const threadMessage = await queries.message.createMessage(db, {
+ conversationId: threadConv.id,
+ role: "user",
+ content: body.content,
+ });
+
+ broadcastToUser(ctx.userId, {
+ type: "conversation.message",
+ conversationId: threadConv.id,
+ message: messageToResponse(threadMessage),
+ }).catch(() => {});
+
+ const taskContext: Record<string, unknown> = {
+ message_id: threadMessage.id,
+ conversation_history: historyWithoutRoot,
+ ...(rootMessageContext ? { root_message: rootMessageContext } : {}),
+ };
+
+ const traceId = "tr_" + nanoid();
+ const taskService = new TaskService(db);
+ try {
+ const task = await taskService.enqueueTask(
+ parentConv.agentId,
+ threadConv.id,
+ ws.workspaceId,
+ body.content,
+ TASK_TYPES.USER_DM_MESSAGE,
+ {
+ contextKey: threadConv.id,
+ context: taskContext,
+ traceId,
+ parentTaskId: null,
+ },
+ );
+
+ queries.message.updateMessageTaskId(db, threadMessage.id, task.id).catch(() => {});
+
+ const dateStr = new Date().toISOString().slice(0, 10);
+ invalidate(cacheKeys.overviewTaskStats(ws.workspaceId, dateStr)).catch(() => {});
+
+ return writeJSON({
+ conversation: conversationToResponse(threadConv),
+ message: messageToResponse(threadMessage),
+ task: taskToResponse(task),
+ }, 201);
+ } catch (err: unknown) {
+ log.error("enqueueTask error (thread create)", { err });
+ return writeError("failed to enqueue task", 500);
+ }
+});
+
+export const GET = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const conversationId = ctx.params?.id;
+ if (!conversationId) {
+ return writeError("conversation id is required", 400);
+ }
+
+ const conv = await queries.conversation.getConversation(db, conversationId, ws.workspaceId);
+ if (!conv) {
+ return writeError("conversation not found", 404);
+ }
+
+ try {
+ const threads = await queries.conversation.getThreadsByConversation(
+ db, ws.workspaceId, conversationId
+ );
+
+ const summaries = threads.map(t => ({
+ thread_id: t.id,
+ parent_message_id: t.parentMessageId,
+ thread_title: t.threadTitle,
+ reply_count: t.replyCount,
+ last_reply_at: t.lastReplyAt,
+ created_at: t.createdAt,
+ }));
+
+ return writeJSON({ thread_summaries: summaries });
+ } catch (err: unknown) {
+ log.error("getThreadsByConversation error", { err });
+ return writeError("failed to fetch thread summaries", 500);
+ }
+});
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index 6462555a6..e4d54e95f 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -17,11 +17,15 @@ import {
updateIssue,
getAgentSkills,
cancelActiveTask,
+ getThreadSummaries,
+ createThread,
+ conversationInit,
} from "@/lib/api";
import { useLatest } from "@/components/agent-chat/chat-message-utils";
import type {
Artifact,
Issue,
+ Message,
SkillEntry,
WsMessage,
} from "@alook/shared";
@@ -73,6 +77,8 @@ import {
} from "@/components/artifact-content-renderer";
import { ScrollToBottomButton } from "@/components/ui/scroll-to-bottom-button";
import { MessageItem, AgentRow } from "@/components/agent-chat/message-list";
+import { TimelineRail } from "@/components/agent-chat/timeline-rail";
+import { useAgentChatSheet } from "@/contexts/agent-chat-sheet-context";
import { PresenceLine } from "@/components/agent-chat/presence-line";
import { MenuToggleIcon } from "@/components/agent-chat/menu-toggle-icon";
import { parseAvatarUrl } from "@/components/avatar";
@@ -206,6 +212,11 @@ export function AgentChatView({
const { flaggedIds, setFlaggedIds, handleToggleFlag } =
useMessageFlags(workspaceId);
+ // Thread state
+ const { openAgentChat } = useAgentChatSheet();
+ const [threadSummaries, setThreadSummaries] = useState<Map<string, { thread_id: string; reply_count: number; last_reply_at: string | null; thread_title: string }>>(new Map());
+ const [threadRootMessage, setThreadRootMessage] = useState<Message | null>(null);
+
useEffect(() => {
setChannelAgentId(agentId);
}, [agentId, setChannelAgentId]);
@@ -296,6 +307,47 @@ export function AgentChatView({
[agentArtifacts],
);
+ // Fetch root message for thread conversations
+ useEffect(() => {
+ if (!conversation?.parent_message_id || !workspaceId) {
+ setThreadRootMessage(null);
+ return;
+ }
+ conversationInit(conversation.id, workspaceId)
+ .then((data) => {
+ if (data.root_message) setThreadRootMessage(data.root_message);
+ })
+ .catch(() => {});
+ }, [conversation?.id, conversation?.parent_message_id, workspaceId]);
+
+ const fetchThreadSummaries = useCallback(() => {
+ if (!conversation?.id || !workspaceId) return;
+ getThreadSummaries(conversation.id, workspaceId)
+ .then((data) => {
+ const map = new Map<string, { thread_id: string; reply_count: number; last_reply_at: string | null; thread_title: string }>();
+ for (const s of data.thread_summaries) {
+ map.set(s.parent_message_id, {
+ thread_id: s.thread_id,
+ reply_count: s.reply_count,
+ last_reply_at: s.last_reply_at,
+ thread_title: s.thread_title,
+ });
+ }
+ setThreadSummaries(map);
+ })
+ .catch(() => {});
+ }, [conversation?.id, workspaceId]);
+
+ useEffect(() => { fetchThreadSummaries(); }, [fetchThreadSummaries]);
+
+ useEffect(() => {
+ return subscribeWs((msg: WsMessage) => {
+ if (msg.type === "thread.created" || msg.type === "thread.reply") {
+ fetchThreadSummaries();
+ }
+ });
+ }, [subscribeWs, fetchThreadSummaries]);
+
const agentAvatarConfig = useMemo(
() => parseAvatarUrl(agents.find((a) => a.id === agentId)?.avatar_url ?? null),
[agents, agentId],
@@ -635,10 +687,14 @@ export function AgentChatView({
Quote
</button>
)}
+ {/* Main chat + optional thread panel side by side */}
+ <div className="flex flex-1 min-h-0">
+ {/* Chat column */}
+ <div className="flex flex-col flex-1 min-w-0">
{/* Messages */}
<div className="relative flex-1 min-h-0">
<div
- className="h-full overflow-y-auto overflow-x-hidden px-3 md:px-5 thin-scrollbar"
+ className={cn("h-full overflow-y-auto overflow-x-hidden px-3 md:px-5 thin-scrollbar", !conversation?.parent_message_id && threadSummaries.size > 0 && "pr-8")}
ref={scrollRef}
onScroll={handleScroll}
onClick={(e) => {
@@ -649,6 +705,29 @@ export function AgentChatView({
}}
>
<div className="mx-auto max-w-3xl pt-6 pb-15 min-w-0">
+ {/* Root message for thread conversations — rendered as a normal MessageItem with flagged emphasis + corner icon, no actions */}
+ {threadRootMessage && (
+ <div className="mb-2">
+ <MessageItem
+ msg={threadRootMessage}
+ agents={agents}
+ artifacts={[]}
+ activeTask={null}
+ taskMessages={[]}
+ connectionLost={false}
+ pendingFilesByMessage={new Map()}
+ onArtifactClick={() => {}}
+ onEmailClick={() => {}}
+ onIssueClick={() => {}}
+ onCalendarEventClick={() => {}}
+ mentionComponents={MENTION_COMPONENTS}
+ groupPosition="solo"
+ agentName={agentName}
+ agentAvatarConfig={agentAvatarConfig}
+ isThreadRoot
+ />
+ </div>
+ )}
{conversation && canLoadMore && !loadingMore && (
<div className="flex justify-center py-2">
<button
@@ -782,6 +861,19 @@ export function AgentChatView({
isSendFailed={failedSends.has(msg.id)}
onRetrySend={handleRetrySend}
onQuote={handleQuoteMessage}
+ onReplyInThread={conversation?.parent_message_id ? undefined : async (msgId) => {
+ const summary = threadSummaries.get(msgId);
+ if (summary?.thread_id) {
+ openAgentChat(agentId, { conversationId: summary.thread_id });
+ } else if (conversation) {
+ try {
+ const result = await createThread(conversation.id, msgId, "", workspaceId);
+ openAgentChat(agentId, { conversationId: result.conversation.id });
+ fetchThreadSummaries();
+ } catch {}
+ }
+ }}
+ threadSummary={conversation?.parent_message_id ? null : threadSummaries.get(msg.id) ?? null}
/>
</div>
);
@@ -809,6 +901,21 @@ export function AgentChatView({
</div>
</div>
<ScrollToBottomButton scrollRef={scrollRef} />
+ {/* Timeline rail — absolute overlay inside the messages area, scrollbar stays outermost */}
+ {!conversation?.parent_message_id && (
+ <div className="absolute right-1 top-0 bottom-0 z-10">
+ <div className="sticky top-4">
+ <TimelineRail
+ agentId={agentId}
+ workspaceId={workspaceId}
+ activeThreadMessageId={null}
+ onThreadClick={(_parentMsgId, threadConvId) => {
+ openAgentChat(agentId, { conversationId: threadConvId });
+ }}
+ />
+ </div>
+ </div>
+ )}
</div>
{/* Input */}
@@ -976,7 +1083,7 @@ export function AgentChatView({
<div className="flex items-center gap-2 px-3.5 pt-2.5 pb-1 border-b border-border/50">
<div className="flex-1 min-w-0 flex items-start gap-2">
<MessageSquareQuote className="size-3.5 shrink-0 mt-0.5 text-muted-foreground" />
- <p className="text-xs text-muted-foreground truncate">
+ <p className="text-xs text-muted-foreground truncate max-w-50">
{quotedMessage.excerpt}
</p>
</div>
@@ -1129,6 +1236,8 @@ export function AgentChatView({
</div>
</div>
</div>
+ </div>{/* end chat column */}
+ </div>{/* end flex row */}
<ArtifactSheet
open={artifactSheetOpen}
diff --git a/src/web/src/components/agent-chat/message-list.tsx b/src/web/src/components/agent-chat/message-list.tsx
index 8537a5994..2dc349f3e 100644
--- a/src/web/src/components/agent-chat/message-list.tsx
+++ b/src/web/src/components/agent-chat/message-list.tsx
@@ -11,7 +11,7 @@ import { highlightMentions } from "@/lib/highlight-mentions";
import { TaskStream } from "@/components/task-stream";
import { RuntimeErrorBlock } from "@/components/agent-chat/runtime-error-block";
import { AnimatedAvatar, type AvatarConfig } from "@/components/avatar";
-import { FileText, Flag, Copy, Check, MessageSquareQuote } from "lucide-react";
+import { FileText, Flag, Copy, Check, MessageSquareQuote, MessageSquare } from "lucide-react";
import { EmailCard } from "@/components/agent-chat/event-cards/email-card";
import { CalendarCard } from "@/components/agent-chat/event-cards/calendar-card";
import { IssueCard } from "@/components/agent-chat/event-cards/issue-card";
@@ -83,6 +83,9 @@ export interface MessageItemProps {
isSendFailed?: boolean;
onRetrySend?: (messageId: string) => void;
onQuote?: (messageId: string, excerpt: string) => void;
+ onReplyInThread?: (messageId: string) => void;
+ threadSummary?: { thread_id: string; reply_count: number; last_reply_at: string | null; thread_title: string } | null;
+ isThreadRoot?: boolean;
}
type EmailData = {
@@ -373,6 +376,17 @@ function FlagDot() {
);
}
+function ThreadRootDot() {
+ return (
+ <span
+ aria-hidden
+ className="absolute -left-1.5 -top-1.5 z-10 flex size-3.5 items-center justify-center rounded-full border-2 border-background bg-foreground text-background"
+ >
+ <MessageSquare className="size-2" />
+ </span>
+ );
+}
+
export const MessageItem = memo(function MessageItem({
msg,
agents,
@@ -398,6 +412,9 @@ export const MessageItem = memo(function MessageItem({
isSendFailed,
onRetrySend,
onQuote,
+ onReplyInThread,
+ threadSummary,
+ isThreadRoot,
}: MessageItemProps) {
const { copy, copied } = useCopyToClipboard();
@@ -466,7 +483,15 @@ export const MessageItem = memo(function MessageItem({
key: "quote",
label: "Quote",
icon: <MessageSquareQuote className="size-3.5" />,
- onClick: () => onQuote(msg.id, msg.content.slice(0, 100)),
+ onClick: () => onQuote(msg.id, msg.content.slice(0, 50)),
+ });
+ }
+ if (onReplyInThread && (msg.role === "assistant" || msg.role === "user")) {
+ messageActions.push({
+ key: "thread",
+ label: "Reply in thread",
+ icon: <MessageSquare className="size-3.5" />,
+ onClick: () => onReplyInThread(msg.id),
});
}
if (msg.role === "assistant" && onToggleFlag) {
@@ -545,7 +570,7 @@ export const MessageItem = memo(function MessageItem({
const target = document.querySelector(`[data-message-id="${CSS.escape(quoteId)}"]`);
target?.scrollIntoView({ behavior: "smooth", block: "center" });
}}
- className="max-w-[80%] mb-0.5 flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-left"
+ className="max-w-[50%] mb-0.5 flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-left"
>
<MessageSquareQuote className="size-3 shrink-0 text-muted-foreground" />
<span className="text-xs text-muted-foreground truncate">{quote.excerpt}</span>
@@ -590,6 +615,22 @@ export const MessageItem = memo(function MessageItem({
Not delivered · tap to retry
</button>
)}
+ {threadSummary && threadSummary.reply_count > 0 && (
+ <button
+ type="button"
+ onClick={() => onReplyInThread?.(msg.id)}
+ className="flex items-center gap-1.5 pt-1 cursor-pointer hover:opacity-75 transition-opacity"
+ >
+ <span className="text-[11px] font-semibold text-[oklch(0.72_0.19_145)]">
+ {threadSummary.reply_count} {threadSummary.reply_count === 1 ? "reply" : "replies"}
+ </span>
+ {threadSummary.last_reply_at && (
+ <span className="text-[10px] text-muted-foreground">
+ last reply {new Date(threadSummary.last_reply_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
+ </span>
+ )}
+ </button>
+ )}
</div>
);
})() : msg.role === "event" ? (() => {
@@ -676,16 +717,33 @@ export const MessageItem = memo(function MessageItem({
position={toBubblePosition(groupPosition)}
className={cn(
"markdown min-w-0 max-w-full",
- isFlagged && "shadow-[inset_2px_0_0_var(--foreground)]",
+ (isFlagged || isThreadRoot) && "shadow-[inset_2px_0_0_var(--foreground)]",
)}
>
<Streamdown plugins={{ mermaid, cjk, math }} controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }} allowedTags={MENTION_ALLOWED_TAGS} literalTagContent={MENTION_LITERAL_TAGS} components={mentionComponents}>{highlightMentions(msg.content, agents)}</Streamdown>
</MessageBubble>
- {isFlagged && <FlagDot />}
+ {isFlagged && !isThreadRoot && <FlagDot />}
+ {isThreadRoot && <ThreadRootDot />}
{toolbar}
{actionSheet}
</div>
)}
+ {threadSummary && threadSummary.reply_count > 0 && (
+ <button
+ type="button"
+ onClick={() => onReplyInThread?.(msg.id)}
+ className="flex items-center gap-1.5 pt-1 cursor-pointer hover:opacity-75 transition-opacity"
+ >
+ <span className="text-[11px] font-semibold text-[oklch(0.72_0.19_145)]">
+ {threadSummary.reply_count} {threadSummary.reply_count === 1 ? "reply" : "replies"}
+ </span>
+ {threadSummary.last_reply_at && (
+ <span className="text-[10px] text-muted-foreground">
+ last reply {new Date(threadSummary.last_reply_at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
+ </span>
+ )}
+ </button>
+ )}
</AgentRow>
</div>
) : null}
diff --git a/src/web/src/components/agent-chat/timeline-rail.tsx b/src/web/src/components/agent-chat/timeline-rail.tsx
new file mode 100644
index 000000000..84cee247c
--- /dev/null
+++ b/src/web/src/components/agent-chat/timeline-rail.tsx
@@ -0,0 +1,118 @@
+"use client";
+
+import React, { useState, useEffect, useCallback, useMemo } from "react";
+import { MessageSquare } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { listAgentThreads, type ThreadListItem } from "@/lib/api";
+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
+import type { WsMessage } from "@alook/shared";
+import { useAgentContext } from "@/contexts/agent-context";
+
+interface TimelineRailProps {
+ agentId: string;
+ workspaceId: string;
+ activeThreadMessageId: string | null;
+ onThreadClick: (parentMessageId: string, threadConvId: string) => void;
+}
+
+export function TimelineRail({
+ agentId,
+ workspaceId,
+ activeThreadMessageId,
+ onThreadClick,
+}: TimelineRailProps) {
+ const { subscribeWs } = useAgentContext();
+ const [threads, setThreads] = useState<ThreadListItem[]>([]);
+ const storageKey = `alook:timeline-rail:${workspaceId}:${agentId}`;
+ const [collapsed, setCollapsed] = useState(() => {
+ if (typeof window === "undefined") return false;
+ return localStorage.getItem(storageKey) === "collapsed";
+ });
+
+ useEffect(() => {
+ if (collapsed) localStorage.setItem(storageKey, "collapsed");
+ else localStorage.removeItem(storageKey);
+ }, [collapsed, storageKey]);
+
+ const fetchThreads = useCallback(() => {
+ listAgentThreads(agentId, workspaceId, { limit: 30 })
+ .then((data) => setThreads(data.threads))
+ .catch(() => {});
+ }, [agentId, workspaceId]);
+
+ useEffect(() => {
+ fetchThreads();
+ }, [fetchThreads]);
+
+ useEffect(() => {
+ return subscribeWs((msg: WsMessage) => {
+ if (msg.type === "thread.created" || msg.type === "thread.reply") {
+ fetchThreads();
+ }
+ });
+ }, [subscribeWs, fetchThreads]);
+
+ const showTickSet = useMemo(() => {
+ const set = new Set<number>();
+ let prev = "";
+ for (let i = 0; i < threads.length; i++) {
+ const dateKey = new Date(threads[i].last_reply_at ?? threads[i].created_at).toDateString();
+ if (i > 0 && dateKey !== prev) set.add(i);
+ prev = dateKey;
+ }
+ return set;
+ }, [threads]);
+
+ if (threads.length === 0) return null;
+
+ return (
+ <div className="w-11 shrink-0 flex flex-col items-center py-4">
+ {/* Toggle */}
+ <button
+ onClick={() => setCollapsed(!collapsed)}
+ className={cn(
+ "size-7 rounded-lg flex items-center justify-center cursor-pointer border-none bg-transparent mb-3 shrink-0 transition-all",
+ collapsed ? "text-muted-foreground" : "text-foreground opacity-80",
+ "hover:opacity-100 hover:bg-accent"
+ )}
+ >
+ <MessageSquare className="size-4" />
+ </button>
+
+ {collapsed ? null : (
+ <div className="flex flex-col items-center overflow-y-auto flex-1 thin-scrollbar">
+ {threads.map((t, i) => {
+ const showTick = showTickSet.has(i);
+ const isActive = t.parent_message_id === activeThreadMessageId;
+
+ return (
+ <React.Fragment key={t.id}>
+ {showTick && (
+ <div className="w-4 h-px bg-muted-foreground/20 my-2 rounded-full shrink-0" />
+ )}
+ <Tooltip>
+ <TooltipTrigger
+ onClick={() => onThreadClick(t.parent_message_id, t.id)}
+ className="size-7 flex items-center justify-center cursor-pointer my-0.5 shrink-0"
+ >
+ <div
+ className={cn(
+ "size-2.5 rounded-full transition-all",
+ isActive
+ ? "bg-foreground shadow-[0_0_0_3px_oklch(0.93_0.006_80/18%)]"
+ : "bg-muted-foreground opacity-25 hover:opacity-50 hover:scale-[1.15]"
+ )}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="left" className="max-w-50">
+ <p className="text-xs font-medium line-clamp-2">{t.thread_title || "Thread"}</p>
+ </TooltipContent>
+ </Tooltip>
+ </React.Fragment>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/web/src/components/canvas/active-tasks-float.tsx b/src/web/src/components/canvas/active-tasks-float.tsx
index e97114e5c..e1f5e1198 100644
--- a/src/web/src/components/canvas/active-tasks-float.tsx
+++ b/src/web/src/components/canvas/active-tasks-float.tsx
@@ -147,7 +147,7 @@ export function ActiveTasksFloat() {
))}
{taskCount > 8 && (
<Link
- href={`/w/${slug}/threads?status=active`}
+ href={`/w/${slug}/traces?status=active`}
className="block text-xs text-muted-foreground hover:text-foreground text-center py-1.5 transition-colors"
>
View all {taskCount} tasks
diff --git a/src/web/src/components/issues/issue-sheet.tsx b/src/web/src/components/issues/issue-sheet.tsx
index 84841bcd2..9058d7a98 100644
--- a/src/web/src/components/issues/issue-sheet.tsx
+++ b/src/web/src/components/issues/issue-sheet.tsx
@@ -610,7 +610,7 @@ export function IssueSheet({
{mode === "detail" && detail?.traceId && (
<PropertyRow icon={<GitBranch className="size-3.5" />}>
<Link
- href={`/w/${slug}/threads/${detail.traceId}`}
+ href={`/w/${slug}/traces/${detail.traceId}`}
className={cn(GHOST_CONTROL, "inline-flex items-center rounded-md")}
>
Thread
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 1fb91f722..7c2d4d0fc 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -298,6 +298,7 @@ export interface ConversationInitResponse {
task_messages: TaskMessageResponse[];
cache_valid: boolean;
message_count: number;
+ root_message?: Message | null;
}
export const conversationInit = (
@@ -1180,3 +1181,57 @@ export const getTrace = (traceId: string, workspaceId: string) =>
apiFetch<{ trace_id: string; channel: string; tasks: TraceTask[] }>(
`/api/traces/${traceId}${wsQuery(workspaceId)}`
);
+
+// ── Threads ──
+
+export interface ThreadSummary {
+ thread_id: string;
+ parent_message_id: string;
+ thread_title: string;
+ reply_count: number;
+ last_reply_at: string | null;
+ created_at: string;
+}
+
+export interface ThreadListItem {
+ id: string;
+ parent_message_id: string;
+ thread_title: string;
+ reply_count: number;
+ last_reply_at: string | null;
+ last_reply_preview: string;
+ created_at: string;
+}
+
+export const createThread = (
+ conversationId: string,
+ parentMessageId: string,
+ content: string,
+ workspaceId: string,
+) =>
+ apiFetch<{
+ conversation: Conversation;
+ message: Message;
+ task: TaskApi;
+ }>(`/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`, {
+ method: "POST",
+ body: JSON.stringify({ parent_message_id: parentMessageId, content }),
+ });
+
+export const getThreadSummaries = (conversationId: string, workspaceId: string) =>
+ apiFetch<{ thread_summaries: ThreadSummary[] }>(
+ `/api/conversations/${conversationId}/threads${wsQuery(workspaceId)}`
+ );
+
+export const listAgentThreads = (
+ agentId: string,
+ workspaceId: string,
+ opts?: { limit?: number; before?: string }
+) => {
+ const extra: Record<string, string> = {};
+ if (opts?.limit) extra.limit = String(opts.limit);
+ if (opts?.before) extra.before = opts.before;
+ return apiFetch<{ threads: ThreadListItem[]; has_more: boolean }>(
+ `/api/agents/${agentId}/threads${wsQuery(workspaceId, extra)}`
+ );
+};
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index 028b7e5b8..3170f8af8 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -124,6 +124,10 @@ export function conversationToResponse(c: any) {
channel: c.channel ?? "default",
created_at: formatTimestamp(c.createdAt),
};
+ if (c.parentMessageId) {
+ resp.parent_message_id = c.parentMessageId;
+ resp.thread_title = c.threadTitle ?? "";
+ }
if (c.messageCount !== undefined) {
resp.message_count = c.messageCount;
}