Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add agent tracing

Gus199550474edc
diff --git a/src/cli/commands/email.ts b/src/cli/commands/email.ts
index 7d49e4ecf..fda059891 100644
--- a/src/cli/commands/email.ts
+++ b/src/cli/commands/email.ts
@@ -405,6 +405,8 @@ export function emailCommand(): Command {
}
const conversationId = process.env.ALOOK_CONVERSATION_ID;
+ const traceId = process.env.ALOOK_TRACE_ID;
+ const sourceTaskId = process.env.ALOOK_TASK_ID;
const res = await client.postJSON<SendResponse>("/api/email/send", {
agentId: opts.agent_id,
to: opts.to,
@@ -414,6 +416,8 @@ export function emailCommand(): Command {
...(inReplyTo ? { inReplyTo, references } : {}),
...(opts.from ? { from: opts.from } : {}),
...(conversationId ? { conversationId } : {}),
+ ...(traceId ? { traceId } : {}),
+ ...(sourceTaskId ? { sourceTaskId } : {}),
});
console.log(`Sent email to ${res.to_email} (id: ${res.id})`);
} catch (err) {
@@ -565,6 +569,8 @@ export function emailCommand(): Command {
// 8. Send
const conversationId = process.env.ALOOK_CONVERSATION_ID;
+ const traceId = process.env.ALOOK_TRACE_ID;
+ const sourceTaskId = process.env.ALOOK_TASK_ID;
const res = await client.postJSON<SendResponse>("/api/email/send", {
agentId: opts.agent_id,
to: opts.to,
@@ -573,6 +579,8 @@ export function emailCommand(): Command {
attachments,
...(opts.from ? { from: opts.from } : {}),
...(conversationId ? { conversationId } : {}),
+ ...(traceId ? { traceId } : {}),
+ ...(sourceTaskId ? { sourceTaskId } : {}),
});
console.log(`Forwarded email to ${res.to_email} (id: ${res.id})`);
} catch (err) {
diff --git a/src/cli/daemon/execenv/__tests__/index.test.ts b/src/cli/daemon/execenv/__tests__/index.test.ts
index 179b6dd6c..c0a578fec 100644
--- a/src/cli/daemon/execenv/__tests__/index.test.ts
+++ b/src/cli/daemon/execenv/__tests__/index.test.ts
@@ -103,6 +103,7 @@ describe("prepare", () => {
ALOOK_AGENT_ID: "a1",
ALOOK_TASK_ID: "t1",
ALOOK_CONVERSATION_ID: "c1",
+ ALOOK_TRACE_ID: "",
ALOOK_HEALTH_PORT: expect.any(String),
});
});
diff --git a/src/cli/daemon/execenv/index.ts b/src/cli/daemon/execenv/index.ts
index 61f8ef405..6bc28a090 100644
--- a/src/cli/daemon/execenv/index.ts
+++ b/src/cli/daemon/execenv/index.ts
@@ -31,6 +31,7 @@ export function prepare(
ALOOK_AGENT_ID: task.agentId,
ALOOK_TASK_ID: task.id,
ALOOK_CONVERSATION_ID: task.conversationId,
+ ALOOK_TRACE_ID: task.traceId ?? "",
ALOOK_HEALTH_PORT: process.env.ALOOK_HEALTH_PORT || "19514",
};
diff --git a/src/cli/daemon/types.ts b/src/cli/daemon/types.ts
index 56c65a9cc..0841feeb5 100644
--- a/src/cli/daemon/types.ts
+++ b/src/cli/daemon/types.ts
@@ -20,6 +20,8 @@ export interface Task {
sender?: TaskSender;
repos?: RepoData[];
createdAt: string;
+ traceId: string | null;
+ parentTaskId: string | null;
}
export interface Attachment {
@@ -152,5 +154,7 @@ export function fromApiTask(api: import("@alook/shared").TaskApi): Task {
: undefined,
repos: undefined,
createdAt: api.created_at,
+ traceId: api.trace_id ?? null,
+ parentTaskId: api.parent_task_id ?? null,
};
}
diff --git a/src/shared/src/constants.ts b/src/shared/src/constants.ts
index feb323e83..cefa23eb3 100644
--- a/src/shared/src/constants.ts
+++ b/src/shared/src/constants.ts
@@ -60,6 +60,7 @@ export const POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS) || 3_000;
export const OFFLINE_THRESHOLD_MS = Number(process.env.OFFLINE_THRESHOLD_MS) || 9_000;
export const EVENT_POLL_INTERVAL_MS = Number(process.env.EVENT_POLL_INTERVAL_MS) || 2_000;
export const AGENT_HANDLE_MIN_LENGTH = 4;
+export const MAX_TASKS_PER_TRACE = 256;
export const MeetingStatus = {
PENDING: "pending",
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index 8e2491a9e..91feefb55 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -16,6 +16,8 @@ export async function createTask(
contextKey?: string | null;
priority?: number;
context?: Record<string, unknown>;
+ traceId?: string | null;
+ parentTaskId?: string | null;
}
) {
const rows = await db
@@ -30,11 +32,34 @@ export async function createTask(
contextKey: data.contextKey ?? null,
priority: data.priority ?? 0,
context: data.context ?? undefined,
+ traceId: data.traceId ?? null,
+ parentTaskId: data.parentTaskId ?? null,
})
.returning();
return rows[0]!;
}
+export async function countTasksByTrace(db: Database, traceId: string) {
+ const rows = await db
+ .select({ value: count() })
+ .from(agentTaskQueue)
+ .where(eq(agentTaskQueue.traceId, traceId));
+ return Number(rows[0]?.value ?? 0);
+}
+
+export async function getLatestTaskForConversation(db: Database, conversationId: string) {
+ const rows = await db
+ .select({
+ id: agentTaskQueue.id,
+ traceId: agentTaskQueue.traceId,
+ })
+ .from(agentTaskQueue)
+ .where(eq(agentTaskQueue.conversationId, conversationId))
+ .orderBy(desc(agentTaskQueue.createdAt))
+ .limit(1);
+ return rows[0] ?? null;
+}
+
export async function getTask(db: Database, id: string, workspaceId?: string) {
const conditions = [eq(agentTaskQueue.id, id)];
if (workspaceId) conditions.push(eq(agentTaskQueue.workspaceId, workspaceId));
@@ -624,3 +649,138 @@ export async function listTaskHistory(
return { tasks: tasks.reverse(), hasMore };
}
+
+export async function listTraces(
+ db: Database,
+ workspaceId: string,
+ opts?: { status?: string; limit?: number; before?: string }
+) {
+ const limit = opts?.limit ?? 30;
+ // When filtering by computed status, overfetch roots to compensate
+ const rootFetchLimit = opts?.status ? limit * 10 : limit;
+
+ const conditions = [
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ sql`${agentTaskQueue.traceId} IS NOT NULL`,
+ sql`${agentTaskQueue.parentTaskId} IS NULL`,
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),
+ ];
+ if (opts?.before) {
+ conditions.push(lt(agentTaskQueue.createdAt, opts.before));
+ }
+
+ const rootTasks = await db
+ .select({
+ id: agentTaskQueue.id,
+ traceId: agentTaskQueue.traceId,
+ agentId: agentTaskQueue.agentId,
+ prompt: agentTaskQueue.prompt,
+ createdAt: agentTaskQueue.createdAt,
+ })
+ .from(agentTaskQueue)
+ .where(and(...conditions))
+ .orderBy(desc(agentTaskQueue.createdAt))
+ .limit(rootFetchLimit + 1);
+
+ if (rootTasks.length === 0) return { traces: [], hasMore: false };
+
+ const moreRootsExist = rootTasks.length > rootFetchLimit;
+ const roots = rootTasks.slice(0, rootFetchLimit);
+ const traceIds = roots.map(r => r.traceId).filter((id): id is string => !!id);
+ if (traceIds.length === 0) return { traces: [], hasMore: false };
+
+ const allTasks = await db
+ .select({
+ traceId: agentTaskQueue.traceId,
+ agentId: agentTaskQueue.agentId,
+ status: agentTaskQueue.status,
+ completedAt: agentTaskQueue.completedAt,
+ })
+ .from(agentTaskQueue)
+ .where(
+ and(
+ inArray(agentTaskQueue.traceId, traceIds),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),
+ )
+ );
+
+ const tasksByTrace = new Map<string, typeof allTasks>();
+ for (const t of allTasks) {
+ if (!t.traceId) continue;
+ const arr = tasksByTrace.get(t.traceId) ?? [];
+ arr.push(t);
+ tasksByTrace.set(t.traceId, arr);
+ }
+
+ const traces: {
+ traceId: string;
+ rootPrompt: string;
+ rootAgentId: string;
+ helperAgentIds: string[];
+ status: string;
+ taskCount: number;
+ startedAt: string;
+ completedAt: string | null;
+ }[] = [];
+
+ for (const root of roots) {
+ const tasks = tasksByTrace.get(root.traceId!) ?? [];
+ const helperIds = [...new Set(tasks.map(t => t.agentId).filter(id => id !== root.agentId))];
+
+ const hasActive = tasks.some(t => ["queued", "dispatched", "running"].includes(t.status));
+ const hasFailed = tasks.some(t => t.status === "failed");
+ let traceStatus: string;
+ if (hasActive) traceStatus = "active";
+ else if (hasFailed) traceStatus = "failed";
+ else traceStatus = "completed";
+
+ if (opts?.status && traceStatus !== opts.status) continue;
+
+ const allTerminal = tasks.every(t => ["completed", "failed", "cancelled", "superseded"].includes(t.status));
+ const completedAt = allTerminal
+ ? tasks.reduce((max, t) => (t.completedAt && t.completedAt > (max ?? "")) ? t.completedAt : max, null as string | null)
+ : null;
+
+ traces.push({
+ traceId: root.traceId!,
+ rootPrompt: root.prompt,
+ rootAgentId: root.agentId,
+ helperAgentIds: helperIds,
+ status: traceStatus,
+ taskCount: tasks.length,
+ startedAt: root.createdAt,
+ completedAt,
+ });
+ }
+
+ const hasMore = moreRootsExist || traces.length > limit;
+ return { traces: traces.slice(0, limit), hasMore };
+}
+
+export async function getTraceTree(
+ db: Database,
+ traceId: string,
+ workspaceId: string
+) {
+ return db
+ .select({
+ id: agentTaskQueue.id,
+ agentId: agentTaskQueue.agentId,
+ parentTaskId: agentTaskQueue.parentTaskId,
+ prompt: agentTaskQueue.prompt,
+ status: agentTaskQueue.status,
+ type: agentTaskQueue.type,
+ conversationId: agentTaskQueue.conversationId,
+ createdAt: agentTaskQueue.createdAt,
+ completedAt: agentTaskQueue.completedAt,
+ })
+ .from(agentTaskQueue)
+ .where(
+ and(
+ eq(agentTaskQueue.traceId, traceId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)
+ )
+ )
+ .orderBy(asc(agentTaskQueue.createdAt));
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 4f5b887fe..0d91bcae2 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -355,6 +355,8 @@ export const agentTaskQueue = sqliteTable(
startedAt: text("started_at"),
completedAt: text("completed_at"),
error: text("error"),
+ traceId: text("trace_id"),
+ parentTaskId: text("parent_task_id"),
},
(t) => [
index("idx_task_queue_pending")
@@ -367,6 +369,8 @@ export const agentTaskQueue = sqliteTable(
.on(t.agentId, t.workspaceId, t.createdAt),
index("idx_task_queue_conversation_status")
.on(t.conversationId, t.status),
+ index("idx_task_queue_trace").on(t.traceId),
+ index("idx_task_queue_parent").on(t.parentTaskId),
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 67857ad50..b207ae24b 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -70,6 +70,7 @@ export {
OFFLINE_THRESHOLD_MS,
EVENT_POLL_INTERVAL_MS,
AGENT_HANDLE_MIN_LENGTH,
+ MAX_TASKS_PER_TRACE,
DEV_WEB_URL,
DEV_WS_DO_URL,
DEV_EMAIL_WORKER_URL,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 9ec0686d8..4c144939a 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -38,6 +38,8 @@ export const ClaimedTaskRowSchema = z.object({
startedAt: z.coerce.date().nullable(),
completedAt: z.coerce.date().nullable(),
error: z.string().nullable(),
+ traceId: z.string().nullable().optional(),
+ parentTaskId: z.string().nullable().optional(),
});
export type ClaimedTaskRow = z.infer<typeof ClaimedTaskRowSchema>;
@@ -86,6 +88,8 @@ export const TaskApiBaseSchema = z.object({
type: z.string(),
context_key: z.string().nullable().optional(),
context: z.unknown().nullable().optional(),
+ trace_id: z.string().nullable().optional(),
+ parent_task_id: z.string().nullable().optional(),
});
export type TaskApiBase = z.infer<typeof TaskApiBaseSchema>;
@@ -452,6 +456,8 @@ export const SendEmailRequestSchema = z.object({
customAccountId: z.string().optional(),
from: z.string().email().optional(),
conversationId: z.string().optional(),
+ traceId: z.string().optional(),
+ sourceTaskId: z.string().optional(),
});
export type SendEmailRequest = z.infer<typeof SendEmailRequestSchema>;
@@ -484,6 +490,8 @@ export const EmailNotifyRequestSchema = z.object({
references: z.string().optional().default(""),
meetingInfo: MeetingInfoSchema.nullable().optional(),
attachments: z.string().optional(),
+ traceId: z.string().optional(),
+ sourceTaskId: z.string().optional(),
});
export type EmailNotifyRequest = z.infer<typeof EmailNotifyRequestSchema>;
diff --git a/src/web/migrations/0021_add_trace_columns.sql b/src/web/migrations/0021_add_trace_columns.sql
new file mode 100644
index 000000000..6458e0fb7
--- /dev/null
+++ b/src/web/migrations/0021_add_trace_columns.sql
@@ -0,0 +1,4 @@
+ALTER TABLE agent_task_queue ADD COLUMN trace_id TEXT;
+ALTER TABLE agent_task_queue ADD COLUMN parent_task_id TEXT;
+CREATE INDEX IF NOT EXISTS idx_task_queue_trace ON agent_task_queue(trace_id);
+CREATE INDEX IF NOT EXISTS idx_task_queue_parent ON agent_task_queue(parent_task_id);
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 3ccd040e1..fbca66d4a 100644
--- a/src/web/src/app/(app)/w/[slug]/settings/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/settings/page.tsx
@@ -12,7 +12,7 @@ import { UsagesTab } from "./usages-tab";
const TABS = [
{ id: "general", label: "General" },
- { id: "instruction", label: "Instruction" },
+ { id: "instruction", label: "Global Instruction" },
{ id: "notifications", label: "Notifications" },
{ id: "members", label: "Members" },
{ id: "usages", label: "Usages" },
diff --git a/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
new file mode 100644
index 000000000..e0008e986
--- /dev/null
+++ b/src/web/src/app/(app)/w/[slug]/traces/[traceId]/page.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { useParams } from "next/navigation";
+import Link from "next/link";
+import { useWorkspace } from "@/contexts/workspace-context";
+import { getTrace, type TraceTask } from "@/lib/api";
+import { Skeleton } from "@/components/ui/skeleton";
+import { ArrowLeft } from "lucide-react";
+import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
+
+function relativeTime(dateStr: string): string {
+ const date = new Date(dateStr);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMin = Math.floor(diffMs / 60000);
+ if (diffMin < 1) return "just now";
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffHrs = Math.floor(diffMin / 60);
+ if (diffHrs < 24) return `${diffHrs}h ago`;
+ const diffDays = Math.floor(diffHrs / 24);
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+function formatDuration(createdAt: string, completedAt: string | null): string | null {
+ if (!completedAt) return null;
+ const ms = new Date(completedAt).getTime() - new Date(createdAt).getTime();
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
+ if (totalSeconds >= 3600) {
+ const h = Math.floor(totalSeconds / 3600);
+ const m = Math.floor((totalSeconds % 3600) / 60);
+ return `${h}h ${m}m`;
+ }
+ if (totalSeconds >= 60) {
+ const m = Math.floor(totalSeconds / 60);
+ const s = totalSeconds % 60;
+ return `${m}m ${s}s`;
+ }
+ return `${totalSeconds}s`;
+}
+
+function StatusDot({ status }: { status: string }) {
+ const colorClass =
+ status === "completed"
+ ? "bg-[oklch(0.72_0.19_145)]"
+ : status === "failed"
+ ? "bg-destructive"
+ : status === "running"
+ ? "bg-primary animate-pulse"
+ : "bg-muted-foreground/40";
+ return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
+}
+
+const STATUS_LABELS: Record<string, string> = {
+ queued: "Queued",
+ dispatched: "Queued",
+ running: "Running",
+ completed: "Completed",
+ failed: "Failed",
+ cancelled: "Cancelled",
+ superseded: "Cancelled",
+};
+
+function AgentAvatar({ name, avatarUrl, size = 14 }: { name?: string; avatarUrl?: string | null; size?: number }) {
+ const config = parseAvatarUrl(avatarUrl);
+ if (config) return <AvatarRenderer config={config} size={size} className="rounded-full shrink-0" />;
+ return (
+ <span
+ className="flex items-center justify-center rounded-full bg-secondary text-[8px] font-medium shrink-0"
+ style={{ width: size, height: size }}
+ >
+ {(name ?? "?").charAt(0).toUpperCase()}
+ </span>
+ );
+}
+
+interface TreeNode extends TraceTask {
+ children: TreeNode[];
+ depth: number;
+}
+
+function buildTree(tasks: TraceTask[]): TreeNode[] {
+ const nodeMap = new Map<string, TreeNode>();
+ for (const t of tasks) {
+ nodeMap.set(t.id, { ...t, children: [], depth: 0 });
+ }
+
+ const roots: TreeNode[] = [];
+ for (const node of nodeMap.values()) {
+ if (node.parent_task_id && nodeMap.has(node.parent_task_id)) {
+ const parent = nodeMap.get(node.parent_task_id)!;
+ parent.children.push(node);
+ } else {
+ roots.push(node);
+ }
+ }
+
+ function setDepth(node: TreeNode, depth: number) {
+ node.depth = depth;
+ for (const child of node.children) {
+ setDepth(child, depth + 1);
+ }
+ }
+ for (const root of roots) setDepth(root, 0);
+
+ return roots;
+}
+
+function flattenTree(nodes: TreeNode[]): TreeNode[] {
+ const result: TreeNode[] = [];
+ function walk(node: TreeNode) {
+ result.push(node);
+ for (const child of node.children) walk(child);
+ }
+ for (const n of nodes) walk(n);
+ return result;
+}
+
+function TaskNode({ node, slug }: { node: TreeNode; slug: string }) {
+ const duration = formatDuration(node.created_at, node.completed_at);
+
+ return (
+ <Link
+ href={`/w/${slug}/agents/${node.agent_id}?task=${node.id}&conv=${node.conversation_id}`}
+ className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
+ style={{ paddingLeft: `${1 + node.depth * 1.5}rem` }}
+ >
+ <div className="flex items-center gap-2">
+ <AgentAvatar name={node.agent?.name} avatarUrl={node.agent?.avatarUrl} size={32} />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="text-sm text-foreground truncate flex-1 min-w-0">
+ {node.prompt}
+ </span>
+ <span className="text-xs text-muted-foreground shrink-0 ml-2" title={new Date(node.created_at).toLocaleString()}>
+ {relativeTime(node.created_at)}
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {node.agent?.name && (
+ <>
+ <span className="text-xs font-medium text-muted-foreground">{node.agent.name}</span>
+ <span className="text-muted-foreground/40">&middot;</span>
+ </>
+ )}
+ <StatusDot status={node.status} />
+ <span className="text-xs text-muted-foreground">{STATUS_LABELS[node.status] ?? node.status}</span>
+ {duration && (
+ <>
+ <span className="text-muted-foreground/40">&middot;</span>
+ <span className="text-xs text-muted-foreground">{duration}</span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ </Link>
+ );
+}
+
+export default function TraceDetailPage() {
+ const params = useParams();
+ const { slug, workspaceId } = useWorkspace();
+ const traceId = params.traceId as string;
+
+ const [tasks, setTasks] = useState<TraceTask[]>([]);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ setLoading(true);
+ getTrace(traceId, workspaceId)
+ .then((data) => setTasks(data.tasks))
+ .catch(() => {})
+ .finally(() => setLoading(false));
+ }, [traceId, workspaceId]);
+
+ const tree = buildTree(tasks);
+ const flat = flattenTree(tree);
+
+ return (
+ <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}/traces`}
+ className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
+ >
+ <ArrowLeft className="size-3.5" />
+ Traces
+ </Link>
+ </div>
+
+ <div className="flex-1 overflow-y-auto thin-scrollbar">
+ {loading ? (
+ <div className="flex flex-col">
+ {[40, 55, 48].map((w, i) => (
+ <div key={i} className="px-4 py-3 border-b border-border/30">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-3.5 w-4 rounded-full shrink-0" />
+ <Skeleton className="h-3.5 rounded" style={{ width: `${w}%` }} />
+ <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
+ </div>
+ <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">
+ <Skeleton className="h-2.5 w-20 rounded-full" />
+ </div>
+ </div>
+ ))}
+ </div>
+ ) : flat.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-full">
+ <p className="text-sm text-muted-foreground">Trace not found</p>
+ </div>
+ ) : (
+ <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
+ {flat.map((node) => (
+ <TaskNode key={node.id} node={node} slug={slug} />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/web/src/app/(app)/w/[slug]/traces/page.tsx b/src/web/src/app/(app)/w/[slug]/traces/page.tsx
new file mode 100644
index 000000000..8b085f426
--- /dev/null
+++ b/src/web/src/app/(app)/w/[slug]/traces/page.tsx
@@ -0,0 +1,309 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import Link from "next/link";
+import { useWorkspace } from "@/contexts/workspace-context";
+import { listTraces, type TraceListItem } from "@/lib/api";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+} from "@/components/ui/select";
+import { GitBranch, RefreshCw } from "lucide-react";
+import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";
+
+const TRACE_LIMIT = 30;
+
+const STATUS_OPTIONS = [
+ { label: "All", value: "" },
+ { label: "Active", value: "active" },
+ { label: "Completed", value: "completed" },
+ { label: "Failed", value: "failed" },
+];
+
+function relativeTime(dateStr: string): string {
+ const date = new Date(dateStr);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMin = Math.floor(diffMs / 60000);
+ if (diffMin < 1) return "just now";
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffHrs = Math.floor(diffMin / 60);
+ if (diffHrs < 24) return `${diffHrs}h ago`;
+ const diffDays = Math.floor(diffHrs / 24);
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+function formatDuration(startedAt: string, completedAt: string | null): string | null {
+ if (!completedAt) return null;
+ const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
+ if (totalSeconds >= 3600) {
+ const h = Math.floor(totalSeconds / 3600);
+ const m = Math.floor((totalSeconds % 3600) / 60);
+ return `${h}h ${m}m`;
+ }
+ if (totalSeconds >= 60) {
+ const m = Math.floor(totalSeconds / 60);
+ const s = totalSeconds % 60;
+ return `${m}m ${s}s`;
+ }
+ return `${totalSeconds}s`;
+}
+
+function StatusDot({ status }: { status: string }) {
+ const colorClass =
+ status === "completed"
+ ? "bg-[oklch(0.72_0.19_145)]"
+ : status === "failed"
+ ? "bg-destructive"
+ : status === "active"
+ ? "bg-primary animate-pulse"
+ : "bg-muted-foreground/40";
+ return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
+}
+
+function AgentAvatar({ name, avatarUrl, size = 14 }: { name?: string; avatarUrl?: string | null; size?: number }) {
+ const config = parseAvatarUrl(avatarUrl);
+ if (config) return <AvatarRenderer config={config} size={size} className="rounded-full shrink-0" />;
+ return (
+ <span
+ className="flex items-center justify-center rounded-full bg-secondary text-[8px] font-medium shrink-0"
+ style={{ width: size, height: size }}
+ >
+ {(name ?? "?").charAt(0).toUpperCase()}
+ </span>
+ );
+}
+
+function TraceRow({ trace, slug }: { trace: TraceListItem; slug: string }) {
+ const duration = formatDuration(trace.started_at, trace.completed_at);
+ const statusLabel = trace.status === "active" ? "Active" : trace.status === "failed" ? "Failed" : "Completed";
+
+ return (
+ <Link
+ 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">
+ <AgentAvatar name={trace.root_agent?.name} avatarUrl={trace.root_agent?.avatarUrl} size={32} />
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2 min-w-0">
+ <span className="text-sm text-foreground truncate flex-1 min-w-0">
+ {trace.root_prompt}
+ </span>
+ <span className="text-xs text-muted-foreground shrink-0 ml-2" title={new Date(trace.started_at).toLocaleString()}>
+ {relativeTime(trace.started_at)}
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {trace.root_agent?.name && (
+ <>
+ <span className="text-xs font-medium text-muted-foreground">{trace.root_agent.name}</span>
+ <span className="text-muted-foreground/40">&middot;</span>
+ </>
+ )}
+ <StatusDot status={trace.status} />
+ <span className="text-xs text-muted-foreground">{statusLabel}</span>
+ {duration && (
+ <>
+ <span className="text-muted-foreground/40">&middot;</span>
+ <span className="text-xs text-muted-foreground">{duration}</span>
+ </>
+ )}
+ {trace.helper_agents.length > 0 && (
+ <>
+ <span className="text-muted-foreground/40">&middot;</span>
+ <span className="flex items-center">
+ {trace.helper_agents.map((h, i) => (
+ <span key={h.id} className={i > 0 ? "-ml-1" : ""}>
+ <AgentAvatar name={h.name} avatarUrl={h.avatarUrl} />
+ </span>
+ ))}
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+ </div>
+ </Link>
+ );
+}
+
+function SkeletonRow({ promptWidth }: { promptWidth: string }) {
+ return (
+ <div className="px-4 py-3 border-b border-border/30">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-3.5 w-4 rounded-full shrink-0" />
+ <Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} />
+ <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
+ </div>
+ <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">
+ <Skeleton className="h-2.5 w-20 rounded-full" />
+ <Skeleton className="h-2.5 w-8 rounded" />
+ </div>
+ </div>
+ );
+}
+
+export default function TracesPage() {
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const { slug, workspaceId } = useWorkspace();
+
+ const [traces, setTraces] = useState<TraceListItem[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [hasMore, setHasMore] = useState(false);
+ const [loadingMore, setLoadingMore] = useState(false);
+
+ const scrollRef = useRef<HTMLDivElement>(null);
+ const isFetchingRef = useRef(false);
+
+ const statusFilter = searchParams.get("status") ?? "";
+
+ const loadInitial = useCallback(async () => {
+ setLoading(true);
+ try {
+ const result = await listTraces(workspaceId, {
+ limit: TRACE_LIMIT,
+ status: statusFilter || undefined,
+ });
+ const seen = new Set<string>();
+ const deduped = result.traces.filter((t) => {
+ if (seen.has(t.trace_id)) return false;
+ seen.add(t.trace_id);
+ return true;
+ });
+ setTraces(deduped);
+ setHasMore(result.has_more);
+ } catch {
+ // silently fail
+ } finally {
+ setLoading(false);
+ }
+ }, [workspaceId, statusFilter]);
+
+ useEffect(() => {
+ loadInitial();
+ }, [loadInitial]);
+
+ const loadOlderTraces = useCallback(async () => {
+ if (isFetchingRef.current || !hasMore || traces.length === 0) return;
+ isFetchingRef.current = true;
+ setLoadingMore(true);
+ try {
+ const oldest = traces[traces.length - 1];
+ const result = await listTraces(workspaceId, {
+ limit: TRACE_LIMIT,
+ before: oldest.started_at,
+ status: statusFilter || undefined,
+ });
+ if (result.traces.length === 0) {
+ setHasMore(false);
+ return;
+ }
+ setHasMore(result.has_more);
+ setTraces((prev) => {
+ const existingIds = new Set(prev.map((t) => t.trace_id));
+ const unique = result.traces.filter((t) => !existingIds.has(t.trace_id));
+ return [...prev, ...unique];
+ });
+ } finally {
+ isFetchingRef.current = false;
+ setLoadingMore(false);
+ }
+ }, [workspaceId, traces, hasMore, statusFilter]);
+
+ const handleScroll = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 200;
+ if (!loadingMore && hasMore && nearBottom) {
+ loadOlderTraces();
+ }
+ }, [loadOlderTraces, loadingMore, hasMore]);
+
+ const updateFilter = useCallback(
+ (value: string) => {
+ const newParams = new URLSearchParams(searchParams.toString());
+ if (value) {
+ newParams.set("status", value);
+ } else {
+ newParams.delete("status");
+ }
+ const pathname = `/w/${slug}/traces`;
+ const qs = newParams.toString();
+ router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
+ },
+ [router, slug, searchParams]
+ );
+
+ return (
+ <div className="flex flex-col h-full">
+ <div className="sticky top-0 z-10 flex items-center gap-2 px-4 py-2.5">
+ <Select value={statusFilter} onValueChange={(v) => updateFilter(v ?? "")}>
+ <SelectTrigger className="w-35 border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
+ <SelectValue placeholder="Status: All" />
+ </SelectTrigger>
+ <SelectPopup>
+ {STATUS_OPTIONS.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label === "All" ? "Status: All" : opt.label}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+
+ <button
+ type="button"
+ onClick={loadInitial}
+ className="ml-auto p-1.5 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"
+ title="Refresh"
+ >
+ <RefreshCw className="size-3.5" />
+ </button>
+ </div>
+
+ <div
+ ref={scrollRef}
+ className="flex-1 overflow-y-auto thin-scrollbar"
+ onScroll={handleScroll}
+ >
+ {loading ? (
+ <div className="flex flex-col">
+ <SkeletonRow promptWidth="40%" />
+ <SkeletonRow promptWidth="55%" />
+ <SkeletonRow promptWidth="48%" />
+ </div>
+ ) : traces.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
+ <GitBranch className="size-8 text-muted-foreground mb-3" />
+ <p className="text-sm text-muted-foreground">No traces yet</p>
+ {statusFilter && (
+ <p className="text-xs text-muted-foreground/60 mt-1">
+ Try changing your filter
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
+ {traces.map((trace) => (
+ <TraceRow key={trace.trace_id} trace={trace} slug={slug} />
+ ))}
+ {loadingMore && (
+ <>
+ <SkeletonRow promptWidth="48%" />
+ <SkeletonRow promptWidth="40%" />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
index 62757253b..4cfe0f01b 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts
@@ -183,7 +183,7 @@ describe("POST /api/conversations/[id]/messages", () => {
expect(res.status).toBe(201);
expect(body.message).toEqual({ id: "m1", content: "Hi there" });
expect(body.task).toEqual({ id: "t1", status: "pending" });
- expect(mockEnqueueTask).toHaveBeenCalledWith("a1", "c1", "w1", "Hi there", "user_dm_message", { contextKey: "c1" });
+ expect(mockEnqueueTask).toHaveBeenCalledWith("a1", "c1", "w1", "Hi there", "user_dm_message", expect.objectContaining({ contextKey: "c1", traceId: expect.stringMatching(/^tr_/), parentTaskId: null }));
});
it("auto-titles conversation with truncated first message", async () => {
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 25ff40fe4..6f1759780 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -187,6 +187,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
...(artifactIds.length > 0 ? { attachment_ids: artifactIds } : {}),
...mentionContext,
};
+ const traceId = "tr_" + nanoid();
const taskService = new TaskService(db);
try {
const task = await taskService.enqueueTask(
@@ -198,6 +199,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
{
contextKey,
context: Object.keys(taskContext).length > 0 ? taskContext : undefined,
+ traceId,
+ parentTaskId: null,
},
);
broadcastToUser(ctx.userId, { type: "task.updated", taskId: task.id, agentId: task.agentId, status: "queued" }).catch(() => {});
diff --git a/src/web/src/app/api/email/notify/route.test.ts b/src/web/src/app/api/email/notify/route.test.ts
index 0c8fd250e..a99e72b17 100644
--- a/src/web/src/app/api/email/notify/route.test.ts
+++ b/src/web/src/app/api/email/notify/route.test.ts
@@ -133,7 +133,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_new", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_new", context: { conversationType: "email_notification" } },
+ expect.objectContaining({ contextKey: "conv_new", context: { conversationType: "email_notification" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -152,7 +152,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_existing", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_existing", context: { conversationType: "email_notification" } },
+ expect.objectContaining({ contextKey: "conv_existing", context: { conversationType: "email_notification" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -172,7 +172,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_dm", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } } },
+ expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message", dmUser: { name: "Alice", email: "[email protected]" } }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
@@ -190,7 +190,7 @@ describe("POST /api/email/notify", () => {
"a1", "conv_dm", "ws1",
expect.any(String),
"email_notification",
- { contextKey: "conv_dm", context: { conversationType: "user_dm_message" } },
+ expect.objectContaining({ contextKey: "conv_dm", context: { conversationType: "user_dm_message" }, traceId: expect.stringMatching(/^tr_/), parentTaskId: null }),
);
});
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index e79d9f78d..5f6b81bd0 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -1,6 +1,7 @@
import { NextRequest } from "next/server"
import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, TASK_TYPES, MeetingStatus, extractThreadId, buildEmailMapKey, EmailNotifyRequestSchema } from "@alook/shared"
+import { nanoid } from "nanoid"
import { getDb } from "@/lib/db"
import { writeJSON, parseBody } from "@/lib/middleware/helpers"
import { TaskService } from "@/lib/services/task"
@@ -113,7 +114,9 @@ export async function POST(req: NextRequest) {
const taskService = new TaskService(db)
const context: Record<string, unknown> = { conversationType };
if (dmUser) context.dmUser = dmUser;
- const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context })
+ const traceId = body.traceId || ("tr_" + nanoid());
+ const parentTaskId = body.traceId ? (body.sourceTaskId || null) : null;
+ const task = await taskService.enqueueTask(agent.id, conversationId, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey: conversationId, context, traceId, parentTaskId })
if (conversationType === TASK_TYPES.USER_DM_MESSAGE) {
broadcastToUser(agent.ownerId, {
diff --git a/src/web/src/app/api/email/send/route.ts b/src/web/src/app/api/email/send/route.ts
index c76107d0f..ee5d2d8f3 100644
--- a/src/web/src/app/api/email/send/route.ts
+++ b/src/web/src/app/api/email/send/route.ts
@@ -140,6 +140,8 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
messageId,
inReplyTo: body.inReplyTo ?? "",
references: body.references ?? "",
+ ...(body.traceId ? { traceId: body.traceId } : {}),
+ ...(body.sourceTaskId ? { sourceTaskId: body.sourceTaskId } : {}),
});
const notifyInit = { method: "POST", headers: { "Content-Type": "application/json" }, body: notifyPayload };
let notifyRes: Response;
diff --git a/src/web/src/app/api/traces/[traceId]/route.ts b/src/web/src/app/api/traces/[traceId]/route.ts
new file mode 100644
index 000000000..acc1b19b1
--- /dev/null
+++ b/src/web/src/app/api/traces/[traceId]/route.ts
@@ -0,0 +1,41 @@
+import { NextRequest } from "next/server";
+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: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const traceId = ctx.params?.traceId;
+ if (!traceId || typeof traceId !== "string" || !traceId.startsWith("tr_") || traceId.length > 30) {
+ return writeError("invalid traceId", 400);
+ }
+
+ const tasks = await queries.task.getTraceTree(db, traceId, ws.workspaceId);
+ if (tasks.length === 0) return writeError("trace not found", 404);
+
+ const agents = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);
+ const agentMap = new Map(agents.map(a => [a.id, { name: a.name, email_handle: a.emailHandle, avatarUrl: a.avatarUrl }]));
+
+ const traceTasks = tasks.map(t => ({
+ id: t.id,
+ agent_id: t.agentId,
+ agent: agentMap.get(t.agentId) ?? null,
+ parent_task_id: t.parentTaskId,
+ prompt: t.prompt,
+ status: t.status,
+ type: t.type,
+ conversation_id: t.conversationId,
+ created_at: t.createdAt,
+ completed_at: t.completedAt,
+ }));
+
+ return writeJSON({ trace_id: traceId, tasks: traceTasks });
+});
diff --git a/src/web/src/app/api/traces/route.ts b/src/web/src/app/api/traces/route.ts
new file mode 100644
index 000000000..fb1f07641
--- /dev/null
+++ b/src/web/src/app/api/traces/route.ts
@@ -0,0 +1,40 @@
+import { NextRequest } from "next/server";
+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 } from "@/lib/middleware/helpers";
+
+export const GET = withAuth(async (req: NextRequest, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = getDb((env as Env).DB);
+
+ const statusRaw = req.nextUrl.searchParams.get("status");
+ const status = statusRaw && ["active", "completed", "failed"].includes(statusRaw) ? statusRaw : undefined;
+ const before = req.nextUrl.searchParams.get("before") ?? undefined;
+ const limitParam = req.nextUrl.searchParams.get("limit");
+ const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : undefined;
+
+ const result = await queries.task.listTraces(db, ws.workspaceId, { status, limit, before });
+
+ const agents = await queries.agent.listAgents(db, ws.workspaceId, ctx.userId);
+ const agentMap = new Map(agents.map(a => [a.id, { name: a.name, avatarUrl: a.avatarUrl }]));
+
+ const traces = result.traces.map(t => ({
+ trace_id: t.traceId,
+ root_prompt: t.rootPrompt,
+ root_agent_id: t.rootAgentId,
+ root_agent: agentMap.get(t.rootAgentId) ?? null,
+ helper_agents: t.helperAgentIds.map(id => ({ id, ...agentMap.get(id) })),
+ status: t.status,
+ task_count: t.taskCount,
+ started_at: t.startedAt,
+ completed_at: t.completedAt,
+ }));
+
+ return writeJSON({ traces, has_more: result.hasMore });
+});
diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsx
index 16d43181c..fd7a3fcb8 100644
--- a/src/web/src/components/app-sidebar.tsx
+++ b/src/web/src/components/app-sidebar.tsx
@@ -7,7 +7,7 @@ import { useWorkspace } from "@/contexts/workspace-context";
import type { Agent } from "@alook/shared";
import { Logo } from "@/components/logo";
import { cn } from "@/lib/utils";
-import { Monitor, SunMoon, Plus, LayoutGrid, CalendarDays, Settings, PinIcon, PinOffIcon } from "lucide-react";
+import { Monitor, SunMoon, Plus, CalendarDays, GitBranch, Settings, PinIcon, PinOffIcon, ArrowLeftRight } from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { useTheme } from "next-themes";
@@ -174,6 +174,7 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
const isHome = pathname === `${prefix}/home`;
const isRuntimes = pathname === `${prefix}/runtimes`;
const isCalendar = pathname === `${prefix}/calendar`;
+ const isTraces = pathname.startsWith(`${prefix}/traces`);
const isSettings = pathname === `${prefix}/settings`;
const isCreateAgent = pathname === `${prefix}/agents/new`;
@@ -293,47 +294,64 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
<TooltipTrigger render={
<button
type="button"
- onClick={() => { router.push("/workspaces"); onNavigate?.(); }}
- className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
+ onClick={() => { router.push(`${prefix}/calendar`); onNavigate?.(); }}
+ className={cn(
+ "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
+ "text-muted-foreground hover:text-foreground hover:bg-accent",
+ isCalendar && "bg-accent text-foreground"
+ )}
/>
}>
- <LayoutGrid className="size-4" />
+ <CalendarDays className="size-4" />
</TooltipTrigger>
- <TooltipContent side="right">Workspaces</TooltipContent>
+ <TooltipContent side="right">Calendar</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger render={
<button
type="button"
- onClick={() => { router.push(`${prefix}/runtimes`); onNavigate?.(); }}
+ onClick={() => { router.push(`${prefix}/traces`); onNavigate?.(); }}
className={cn(
"flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
"text-muted-foreground hover:text-foreground hover:bg-accent",
- isRuntimes && "bg-accent text-foreground"
+ isTraces && "bg-accent text-foreground"
)}
/>
}>
- <Monitor className="size-4" />
+ <GitBranch className="size-4" />
</TooltipTrigger>
- <TooltipContent side="right">Runtimes</TooltipContent>
+ <TooltipContent side="right">Traces</TooltipContent>
</Tooltip>
<Tooltip>
<TooltipTrigger render={
<button
type="button"
- onClick={() => { router.push(`${prefix}/calendar`); onNavigate?.(); }}
+ onClick={() => { router.push(`${prefix}/runtimes`); onNavigate?.(); }}
className={cn(
"flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",
"text-muted-foreground hover:text-foreground hover:bg-accent",
- isCalendar && "bg-accent text-foreground"
+ isRuntimes && "bg-accent text-foreground"
)}
/>
}>
- <CalendarDays className="size-4" />
+ <Monitor className="size-4" />
</TooltipTrigger>
- <TooltipContent side="right">Calendar</TooltipContent>
+ <TooltipContent side="right">Runtimes</TooltipContent>
+ </Tooltip>
+
+ <Tooltip>
+ <TooltipTrigger render={
+ <button
+ type="button"
+ onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
+ className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
+ />
+ }>
+ <SunMoon className="size-4" />
+ </TooltipTrigger>
+ <TooltipContent side="right">Toggle theme</TooltipContent>
</Tooltip>
<Tooltip>
@@ -357,13 +375,13 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {
<TooltipTrigger render={
<button
type="button"
- onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
+ onClick={() => { router.push("/workspaces"); onNavigate?.(); }}
className="flex items-center justify-center size-10 rounded-xl text-muted-foreground hover:text-foreground hover:bg-accent transition-colors duration-200 cursor-pointer"
/>
}>
- <SunMoon className="size-4" />
+ <ArrowLeftRight className="size-4" />
</TooltipTrigger>
- <TooltipContent side="right">Toggle theme</TooltipContent>
+ <TooltipContent side="right">Switch workspace</TooltipContent>
</Tooltip>
<NavUser />
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 5528565b1..0b0ceee44 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -896,3 +896,47 @@ export const deleteMeeting = (agentId: string, meetingId: string, workspaceId: s
apiFetch<void>(`/api/agents/${agentId}/meetings/${meetingId}${wsQuery(workspaceId)}`, {
method: "DELETE",
});
+
+// Traces
+export interface TraceListItem {
+ trace_id: string;
+ root_prompt: string;
+ root_agent_id: string;
+ root_agent: { name: string; avatarUrl: string | null } | null;
+ helper_agents: { id: string; name?: string; avatarUrl?: string | null }[];
+ status: string;
+ task_count: number;
+ started_at: string;
+ completed_at: string | null;
+}
+
+export interface TraceTask {
+ id: string;
+ agent_id: string;
+ agent: { name: string; email_handle: string | null; avatarUrl: string | null } | null;
+ parent_task_id: string | null;
+ prompt: string;
+ status: string;
+ type: string;
+ conversation_id: string;
+ created_at: string;
+ completed_at: string | null;
+}
+
+export const listTraces = (
+ workspaceId: string,
+ opts?: { status?: string; limit?: number; before?: string }
+) => {
+ const extra: Record<string, string> = {};
+ if (opts?.limit) extra.limit = String(opts.limit);
+ if (opts?.before) extra.before = opts.before;
+ if (opts?.status) extra.status = opts.status;
+ return apiFetch<{ traces: TraceListItem[]; has_more: boolean }>(
+ `/api/traces${wsQuery(workspaceId, extra)}`
+ );
+};
+
+export const getTrace = (traceId: string, workspaceId: string) =>
+ apiFetch<{ trace_id: string; tasks: TraceTask[] }>(
+ `/api/traces/${traceId}${wsQuery(workspaceId)}`
+ );
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index 3050312be..1f10bf5c1 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -89,6 +89,8 @@ export function taskToResponse(t: {
result?: unknown;
error?: string | null;
createdAt: Date | string;
+ traceId?: string | null;
+ parentTaskId?: string | null;
}) {
return TaskApiBaseSchema.parse({
id: t.id,
@@ -108,6 +110,8 @@ export function taskToResponse(t: {
result: t.result ?? null,
error: t.error || null,
created_at: formatTimestamp(t.createdAt),
+ trace_id: t.traceId ?? null,
+ parent_task_id: t.parentTaskId ?? null,
});
}
diff --git a/src/web/src/lib/services/calendar.ts b/src/web/src/lib/services/calendar.ts
index 5a419594e..4f9425e66 100644
--- a/src/web/src/lib/services/calendar.ts
+++ b/src/web/src/lib/services/calendar.ts
@@ -1,5 +1,6 @@
import type { Database } from "@alook/shared";
import { queries, TASK_TYPES } from "@alook/shared";
+import { nanoid } from "nanoid";
import { log } from "@/lib/logger";
const {
@@ -89,6 +90,8 @@ export async function promoteDueCalendarEventsForWorkspace(
prompt: ev.title,
type: TASK_TYPES.CALENDAR_EVENT,
priority: 0,
+ traceId: "tr_" + nanoid(),
+ parentTaskId: null,
});
if (ev.repeatInterval) {
diff --git a/src/web/src/lib/services/task.test.ts b/src/web/src/lib/services/task.test.ts
index cd3142cd4..b97078d74 100644
--- a/src/web/src/lib/services/task.test.ts
+++ b/src/web/src/lib/services/task.test.ts
@@ -9,6 +9,7 @@ vi.mock("@alook/shared", () => ({
CALENDAR_EVENT: "calendar_event",
KILL_TASK: "kill_task",
},
+ MAX_TASKS_PER_TRACE: 256,
queries: {
task: {
createTask: vi.fn(),
@@ -20,6 +21,8 @@ vi.mock("@alook/shared", () => ({
markFailedAsSuperseded: vi.fn(),
getTask: vi.fn(),
countRunningTasks: vi.fn(),
+ countTasksByTrace: vi.fn().mockResolvedValue(0),
+ getLatestTaskForConversation: vi.fn().mockResolvedValue(null),
listPendingTasksByRuntimes: vi.fn(),
claimKillTasks: vi.fn().mockResolvedValue([]),
getActiveTaskByConversation: vi.fn(),
@@ -116,6 +119,9 @@ describe("TaskService", () => {
type: "user_dm_message",
contextKey: null,
priority: 0,
+ context: undefined,
+ traceId: null,
+ parentTaskId: null,
});
expect(result).toEqual({ id: "t1" });
});
diff --git a/src/web/src/lib/services/task.ts b/src/web/src/lib/services/task.ts
index c7e5f8cb5..f41895054 100644
--- a/src/web/src/lib/services/task.ts
+++ b/src/web/src/lib/services/task.ts
@@ -1,5 +1,5 @@
import type { Database } from "@alook/shared";
-import { queries, TASK_TYPES } from "@alook/shared";
+import { queries, TASK_TYPES, MAX_TASKS_PER_TRACE } from "@alook/shared";
import { log } from "@/lib/logger";
import { broadcastToUser } from "@/lib/broadcast";
import { messageToResponse, taskToResponse } from "@/lib/api/responses";
@@ -18,7 +18,7 @@ export class TaskService {
workspaceId: string,
prompt: string,
type: string = TASK_TYPES.USER_DM_MESSAGE,
- opts?: { contextKey?: string | null; context?: Record<string, unknown> },
+ opts?: { contextKey?: string | null; context?: Record<string, unknown>; traceId?: string | null; parentTaskId?: string | null },
) {
const agent = await agentQueries.getAgent(this.db, agentId, workspaceId);
if (!agent) {
@@ -28,6 +28,13 @@ export class TaskService {
throw new Error("agent has no runtime");
}
+ if (opts?.traceId && opts.parentTaskId) {
+ const traceCount = await taskQueries.countTasksByTrace(this.db, opts.traceId);
+ if (traceCount >= MAX_TASKS_PER_TRACE) {
+ throw new Error(`Trace limit reached (${MAX_TASKS_PER_TRACE} tasks). This may indicate an infinite loop between agents.`);
+ }
+ }
+
return taskQueries.createTask(this.db, {
agentId,
runtimeId: agent.runtimeId,
@@ -38,6 +45,8 @@ export class TaskService {
contextKey: opts?.contextKey ?? null,
priority: 0,
context: opts?.context,
+ traceId: opts?.traceId ?? null,
+ parentTaskId: opts?.parentTaskId ?? null,
});
}
@@ -206,6 +215,8 @@ export class TaskService {
{
contextKey: original.contextKey ?? null,
context: original.context as Record<string, unknown> | undefined,
+ traceId: original.traceId ?? null,
+ parentTaskId: original.parentTaskId ?? null,
},
);
@@ -267,6 +278,8 @@ export class TaskService {
try {
const contextKey = conversationId;
const attachmentIds = activated.attachmentIds ? JSON.parse(activated.attachmentIds) as string[] : [];
+ const latestTask = await taskQueries.getLatestTaskForConversation(this.db, conversationId);
+ const traceId = latestTask?.traceId ?? null;
const task = await this.enqueueTask(
conversation.agentId,
conversationId,
@@ -276,6 +289,8 @@ export class TaskService {
{
contextKey,
context: attachmentIds.length > 0 ? { attachment_ids: attachmentIds } : undefined,
+ traceId,
+ parentTaskId: null,
},
);