Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add preview card
Gus20b28fb22be2
diff --git a/src/shared/src/db/queries/task-message.ts b/src/shared/src/db/queries/task-message.tsindex 4f30e1dbf..6fbcf2964 100644--- a/src/shared/src/db/queries/task-message.ts+++ b/src/shared/src/db/queries/task-message.ts@@ -1,4 +1,4 @@-import { eq, and, gt, asc } from "drizzle-orm";+import { eq, and, gt, asc, count, inArray, notInArray } from "drizzle-orm";import { taskMessage, agentTaskQueue } from "../schema";import type { Database } from "../index";@@ -73,3 +73,37 @@ export async function listTaskMessagesSince(export async function deleteTaskMessages(db: Database, taskId: string) {await db.delete(taskMessage).where(eq(taskMessage.taskId, taskId));}++const HIDDEN_STEP_TYPES = ["status", "log", "tool-result", "text"];+const CHUNK_SIZE = 50;++export async function countTaskMessagesByTaskIds(+ db: Database,+ taskIds: string[],+ workspaceId: string+): Promise<Array<{ taskId: string; count: number }>> {+ if (taskIds.length === 0) return [];++ const results: Array<{ taskId: string; count: number }> = [];+ for (let i = 0; i < taskIds.length; i += CHUNK_SIZE) {+ const chunk = taskIds.slice(i, i + CHUNK_SIZE);+ const rows = await db+ .select({+ taskId: taskMessage.taskId,+ count: count(taskMessage.id),+ })+ .from(taskMessage)+ .innerJoin(agentTaskQueue, eq(taskMessage.taskId, agentTaskQueue.id))+ .where(+ and(+ inArray(taskMessage.taskId, chunk),+ eq(agentTaskQueue.workspaceId, workspaceId),+ notInArray(taskMessage.type, HIDDEN_STEP_TYPES)+ )+ )+ .groupBy(taskMessage.taskId);+ results.push(...rows.map((r) => ({ taskId: r.taskId, count: r.count })));+ }++ return results;+}diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 7c7eb26f7..5facc145f 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -31,6 +31,7 @@ export interface Agent {status: string;max_concurrent_tasks: number;email_handle: string | null;+ avatar_url: string | null;visibility: string;owner_id: string | null;created_at: string;diff --git a/src/shared/test/queries/task-message.test.ts b/src/shared/test/queries/task-message.test.tsnew file mode 100644index 000000000..6e57b2068--- /dev/null+++ b/src/shared/test/queries/task-message.test.ts@@ -0,0 +1,36 @@+import { describe, it, expect } from "vitest";+import * as taskMessageQueries from "../../src/db/queries/task-message";++describe("task-message query module exports", () => {+ it("exports createTaskMessage", () => {+ expect(typeof taskMessageQueries.createTaskMessage).toBe("function");+ });++ it("exports listTaskMessages", () => {+ expect(typeof taskMessageQueries.listTaskMessages).toBe("function");+ });++ it("exports listTaskMessagesSince", () => {+ expect(typeof taskMessageQueries.listTaskMessagesSince).toBe("function");+ });++ it("exports deleteTaskMessages", () => {+ expect(typeof taskMessageQueries.deleteTaskMessages).toBe("function");+ });++ it("exports countTaskMessagesByTaskIds", () => {+ expect(typeof taskMessageQueries.countTaskMessagesByTaskIds).toBe("function");+ });+});++describe("countTaskMessagesByTaskIds", () => {+ it("accepts (db, taskIds, workspaceId)", () => {+ expect(taskMessageQueries.countTaskMessagesByTaskIds.length).toBe(3);+ });++ it("returns empty array for empty taskIds input", async () => {+ const mockDb = {} as Parameters<typeof taskMessageQueries.countTaskMessagesByTaskIds>[0];+ const result = await taskMessageQueries.countTaskMessagesByTaskIds(mockDb, [], "ws-1");+ expect(result).toEqual([]);+ });+});diff --git a/src/web/src/app/api/tasks/step-counts/route.test.ts b/src/web/src/app/api/tasks/step-counts/route.test.tsnew file mode 100644index 000000000..9a2cdf079--- /dev/null+++ b/src/web/src/app/api/tasks/step-counts/route.test.ts@@ -0,0 +1,129 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockCountTaskMessagesByTaskIds = vi.fn();++vi.mock("@/lib/middleware/helpers", () => ({+ writeJSON: (data: any, status = 200) =>+ new Response(JSON.stringify(data), {+ status,+ headers: { "content-type": "application/json" },+ }),+ writeError: (message: string, status: number) =>+ new Response(JSON.stringify({ error: message }), {+ status,+ headers: { "content-type": "application/json" },+ }),+}));+vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ taskMessage: {+ countTaskMessagesByTaskIds: (...args: any[]) =>+ mockCountTaskMessagesByTaskIds(...args),+ },+ },+}));+vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any) => {+ return handler(req, { userId: "u1", email: "[email protected]" });+ }),+}));+vi.mock("@/lib/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),+}));++import { POST } from "./route";++function makeReq(body: unknown, qs = "workspace_id=w1") {+ return new NextRequest(`http://localhost/api/tasks/step-counts?${qs}`, {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "content-type": "application/json" },+ });+}++describe("POST /api/tasks/step-counts", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns counts keyed by task ID", async () => {+ mockCountTaskMessagesByTaskIds.mockResolvedValue([+ { taskId: "t1", count: 5 },+ { taskId: "t2", count: 12 },+ ]);++ const res = await POST(makeReq({ task_ids: ["t1", "t2"] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({ t1: 5, t2: 12 });+ expect(mockCountTaskMessagesByTaskIds).toHaveBeenCalledWith(+ {},+ ["t1", "t2"],+ "w1"+ );+ });++ it("returns empty object when no task_ids provided", async () => {+ const res = await POST(makeReq({ task_ids: [] }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body).toEqual({});+ expect(mockCountTaskMessagesByTaskIds).not.toHaveBeenCalled();+ });++ it("returns 400 when task_ids is missing", async () => {+ const res = await POST(makeReq({}));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task_ids is required");+ });++ it("returns 400 when task_ids is not an array", async () => {+ const res = await POST(makeReq({ task_ids: "not-array" }));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task_ids must be an array of strings");+ });++ it("returns 400 when task_ids contains non-strings", async () => {+ const res = await POST(makeReq({ task_ids: [1, 2] }));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task_ids must be an array of strings");+ });++ it("rejects arrays exceeding 100 entries", async () => {+ const bigArray = Array.from({ length: 101 }, (_, i) => `t${i}`);+ const res = await POST(makeReq({ task_ids: bigArray }));+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("task_ids exceeds maximum of 100 entries");+ });++ it("returns 400 for invalid JSON body", async () => {+ const req = new NextRequest(+ "http://localhost/api/tasks/step-counts?workspace_id=w1",+ {+ method: "POST",+ body: "not json",+ headers: { "content-type": "application/json" },+ }+ );+ const res = await POST(req);+ const body = await res.json();++ expect(res.status).toBe(400);+ expect(body.error).toBe("invalid request body");+ });+});diff --git a/src/web/src/app/api/tasks/step-counts/route.ts b/src/web/src/app/api/tasks/step-counts/route.tsnew file mode 100644index 000000000..cd09970ec--- /dev/null+++ b/src/web/src/app/api/tasks/step-counts/route.ts@@ -0,0 +1,51 @@+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 POST = withAuth(async (req, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ let body: unknown;+ try {+ body = await req.json();+ } catch {+ return writeError("invalid request body", 400);+ }++ if (!body || typeof body !== "object" || !("task_ids" in body)) {+ return writeError("task_ids is required", 400);+ }++ const { task_ids } = body as { task_ids: unknown };+ if (!Array.isArray(task_ids) || !task_ids.every((id) => typeof id === "string")) {+ return writeError("task_ids must be an array of strings", 400);+ }++ if (task_ids.length > 100) {+ return writeError("task_ids exceeds maximum of 100 entries", 400);+ }++ if (task_ids.length === 0) {+ return writeJSON({});+ }++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const rows = await queries.taskMessage.countTaskMessagesByTaskIds(+ db,+ task_ids,+ ws.workspaceId+ );++ const result: Record<string, number> = {};+ for (const row of rows) {+ result[row.taskId] = row.count;+ }++ return writeJSON(result);+});diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex 7a4ee4249..cbf0af1ef 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -15,6 +15,7 @@ import {sendMessage,getTask,getTaskMessages,+ getTaskStepCounts,listArtifacts,listBufferedMessages,createBufferedMessage,@@ -40,15 +41,37 @@ import { ArtifactSheet, formatSize } from "@/components/agent-chat/artifact-sheeimport { isPreviewable, getArtifactUrl } from "@/components/artifact-content-renderer";import { Streamdown } from "streamdown";import { FollowUpBuffer } from "@/components/agent-chat/follow-up-buffer";+import { HistoricalTaskSteps } from "@/components/agent-chat/historical-task-steps";+import { AgentPreviewCard } from "@/components/agent-preview-card";+import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";const MESSAGE_LIMIT = 20;const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10 MB-const MENTION_ALLOWED_TAGS = { mention: [] as string[] };+const MENTION_ALLOWED_TAGS = { mention: ["data-agent-id"] };const MENTION_LITERAL_TAGS = ["mention"];-const MentionHighlight = ({ children }: { children?: React.ReactNode }) => (- <span className="mention-highlight">{children}</span>-);+function MentionHighlight(props: Record<string, unknown> & { children?: React.ReactNode }) {+ const { children, ...rest } = props;+ const { agents } = useAgentContext();+ const agentId = (rest["data-agent-id"] ?? rest.dataAgentId) as string | undefined;+ let agent = agentId ? agents.find((a) => a.id === agentId) : undefined;+ if (!agent && typeof children === "string") {+ agent = agents.find((a) => a.name.toLowerCase() === children.toLowerCase());+ }+ if (agent) {+ return (+ <Popover>+ <PopoverTrigger openOnHover delay={300} nativeButton={false} render={<span className="mention-highlight cursor-pointer" />}>+ {children}+ </PopoverTrigger>+ <PopoverContent side="top" className="w-70">+ <AgentPreviewCard agent={agent} />+ </PopoverContent>+ </Popover>+ );+ }+ return <span className="mention-highlight">{children}</span>;+}const MENTION_COMPONENTS = { mention: MentionHighlight };/** Sort messages by (created_at, id) ascending — guarantees chronological order. */@@ -214,6 +237,7 @@ export function AgentChatView() {const [previousConversations, setPreviousConversations] = useState<PreviousConversation[]>([]);const [hasMoreConversations, setHasMoreConversations] = useState(false);const [napMarkers, setNapMarkers] = useState<NapMarker[]>([]);+ const [stepCounts, setStepCounts] = useState<Record<string, number>>({});const pendingFilesMapRef = useRef<Map<string, File[]>>(new Map());@@ -289,6 +313,7 @@ export function AgentChatView() {setTaskMessages([]);setBufferedMessages([]);setNapMarkers([]);+ setStepCounts({});setPreviousConversations([]);setHasMoreConversations(false);oldestConvIdRef.current = null;@@ -306,6 +331,12 @@ export function AgentChatView() {setMessages(msgs);setHasMore(msgs.length >= MESSAGE_LIMIT);setArtifacts(arts);+ const taskIds = [...new Set(msgs.filter((m) => m.role === "assistant" && m.task_id).map((m) => m.task_id!))];+ if (taskIds.length > 0) {+ getTaskStepCounts(taskIds, workspaceId)+ .then(setStepCounts)+ .catch(() => {});+ }} catch {const data = await chatInit(agentId, workspaceId, activeChannel);setConversation(data.conversation);@@ -1108,6 +1139,15 @@ export function AgentChatView() {msg.task_id === activeTask.id &&taskMessages.length > 0;+ const historicalStepCount =+ !hasTaskStream &&+ targetConvId &&+ msg.role === "assistant" &&+ msg.task_id &&+ stepCounts[msg.task_id] > 0+ ? stepCounts[msg.task_id]+ : 0;+return (<React.Fragment key={msg.id}>{hasTaskStream && (@@ -1118,6 +1158,13 @@ export function AgentChatView() {onRetry={handleRetryTask}/>)}+ {historicalStepCount > 0 && msg.task_id && (+ <HistoricalTaskSteps+ taskId={msg.task_id}+ stepCount={historicalStepCount}+ workspaceId={workspaceId}+ />+ )}{msg.role === "user" ? (() => {const isLastUser = messages.length > 0 && messages[messages.length - 1].id === msg.id;const awaitingRun = isLastUser && !!activeTask && activeTask.status !== "running" && !["completed", "failed", "cancelled", "superseded"].includes(activeTask.status);@@ -1220,7 +1267,7 @@ export function AgentChatView() {input.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"),agents,)- .replace(/<mention>/g, '<span class="mention-highlight">')+ .replace(/<mention[^>]*>/g, '<span class="mention-highlight">').replace(/<\/mention>/g, "</span>"): "",}}diff --git a/src/web/src/components/agent-chat/historical-task-steps.tsx b/src/web/src/components/agent-chat/historical-task-steps.tsxnew file mode 100644index 000000000..9acb0bb10--- /dev/null+++ b/src/web/src/components/agent-chat/historical-task-steps.tsx@@ -0,0 +1,62 @@+"use client";++import { useState, useCallback } from "react";+import { TaskStream } from "@/components/task-stream";+import { getTaskMessages } from "@/lib/api";+import type { TaskMessage, TaskApi } from "@alook/shared";++const COMPLETED_STUB: TaskApi = {+ id: "",+ agent_id: "",+ runtime_id: "",+ conversation_id: "",+ workspace_id: "",+ prompt: "",+ status: "completed",+ priority: 0,+ dispatched_at: null,+ started_at: null,+ completed_at: null,+ result: null,+ error: null,+ created_at: "",+ type: "",+};++export function HistoricalTaskSteps({+ taskId,+ stepCount,+ workspaceId,+}: {+ taskId: string;+ stepCount: number;+ workspaceId: string;+}) {+ const [messages, setMessages] = useState<TaskMessage[]>([]);+ const [loading, setLoading] = useState(false);+ const [fetched, setFetched] = useState(false);++ const handleExpand = useCallback(async () => {+ if (fetched || loading) return;+ setLoading(true);+ try {+ const msgs = await getTaskMessages(taskId, workspaceId);+ setMessages(msgs);+ } catch {+ setMessages([]);+ } finally {+ setLoading(false);+ setFetched(true);+ }+ }, [fetched, loading, taskId, workspaceId]);++ return (+ <TaskStream+ task={COMPLETED_STUB}+ messages={messages}+ stepCountHint={stepCount}+ onExpandSteps={handleExpand}+ stepsLoading={loading}+ />+ );+}diff --git a/src/web/src/components/agent-preview-card.tsx b/src/web/src/components/agent-preview-card.tsxnew file mode 100644index 000000000..c65e8d5b8--- /dev/null+++ b/src/web/src/components/agent-preview-card.tsx@@ -0,0 +1,63 @@+"use client";++import { useCallback, useState } from "react";+import type { Agent } from "@alook/shared";+import { Check, Copy } from "lucide-react";+import { toast } from "sonner";++export function AgentPreviewCard({ agent }: { agent: Agent }) {+ const [copied, setCopied] = useState(false);+ const email = agent.email_handle ? `${agent.email_handle}@alook.ai` : null;++ const handleCopy = useCallback(async () => {+ if (!email) return;+ try {+ await navigator.clipboard.writeText(email);+ setCopied(true);+ toast.success("Email copied to clipboard");+ setTimeout(() => setCopied(false), 2000);+ } catch {+ toast.error("Failed to copy email");+ }+ }, [email]);++ return (+ <div className="flex flex-col gap-2.5 p-1">+ <div className="flex items-start gap-3">+ {agent.avatar_url ? (+ <img+ src={agent.avatar_url}+ alt={agent.name}+ className="size-10 rounded-xl object-cover shrink-0"+ />+ ) : (+ <div className="flex items-center justify-center size-10 rounded-xl bg-secondary text-secondary-foreground text-sm font-medium shrink-0">+ {agent.name.charAt(0).toUpperCase()}+ </div>+ )}+ <div className="min-w-0 flex-1">+ <p className="text-sm font-medium truncate">{agent.name}</p>+ {email && (+ <div className="flex items-center gap-1 mt-0.5">+ <span className="text-xs text-muted-foreground truncate">{email}</span>+ <button+ type="button"+ onClick={handleCopy}+ className="shrink-0 p-0.5 rounded-sm text-muted-foreground/60 hover:text-foreground transition-colors cursor-pointer"+ >+ {copied ? (+ <Check className="size-3 text-green-500" />+ ) : (+ <Copy className="size-3" />+ )}+ </button>+ </div>+ )}+ </div>+ </div>+ {agent.description && (+ <p className="text-xs text-muted-foreground line-clamp-2">{agent.description}</p>+ )}+ </div>+ );+}diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsxindex 44112aea0..c840d6f34 100644--- a/src/web/src/components/app-sidebar.tsx+++ b/src/web/src/components/app-sidebar.tsx@@ -1,8 +1,10 @@"use client";+import { useState } from "react";import { useRouter, usePathname, useSearchParams } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";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";@@ -16,6 +18,81 @@ import {ContextMenuContent,ContextMenuItem,} from "@/components/ui/context-menu";+import { AgentPreviewCard } from "@/components/agent-preview-card";+import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";++function AgentSidebarButton({+ agent,+ isActive,+ isPinned,+ taskCount,+ onClick,+ onPin,+ onUnpin,+}: {+ agent: Agent;+ isActive: boolean;+ isPinned: boolean;+ taskCount: number;+ onClick: () => void;+ onPin: () => void;+ onUnpin: () => void;+}) {+ const [previewOpen, setPreviewOpen] = useState(false);+ return (+ <Popover+ open={previewOpen}+ onOpenChange={(open, event) => {+ if (open && event.reason === "trigger-press") return;+ setPreviewOpen(open);+ }}+ >+ <ContextMenu>+ <PopoverTrigger+ openOnHover+ delay={10}+ render={+ <ContextMenuTrigger+ render={+ <button+ type="button"+ onClick={() => { setPreviewOpen(false); onClick(); }}+ className={cn(+ "relative flex shrink-0 items-center justify-center size-10 rounded-xl text-sm font-medium transition-colors duration-200 cursor-pointer",+ isActive+ ? "bg-primary text-primary-foreground shadow-sm"+ : "bg-secondary text-secondary-foreground hover:bg-accent"+ )}+ />+ }+ />+ }+ >+ {agent.name.charAt(0).toUpperCase()}+ {taskCount > 0 && (+ <span className="absolute bottom-0 right-0 size-2 rounded-full bg-status-online animate-pulse ring-2 ring-background" />+ )}+ </PopoverTrigger>+ <ContextMenuContent>+ {isPinned ? (+ <ContextMenuItem onClick={onUnpin}>+ <PinOffIcon className="size-3.5 mr-1.5" />+ Unpin+ </ContextMenuItem>+ ) : (+ <ContextMenuItem onClick={onPin}>+ <PinIcon className="size-3.5 mr-1.5" />+ Pin to top+ </ContextMenuItem>+ )}+ </ContextMenuContent>+ </ContextMenu>+ <PopoverContent side="right" className="w-70">+ <AgentPreviewCard agent={agent} />+ </PopoverContent>+ </Popover>+ );+}export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {const router = useRouter();@@ -51,53 +128,18 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {onNavigate?.();};- const renderAgentButton = (agent: typeof agents[number]) => {- const isActive = activeAgentId === agent.id;- const isPinned = pins.has(agent.id);- return (- <Tooltip key={agent.id}>- <ContextMenu>- <TooltipTrigger- render={- <ContextMenuTrigger- render={- <button- type="button"- onClick={() => handleAgentClick(agent.id)}- className={cn(- "relative flex shrink-0 items-center justify-center size-10 rounded-xl text-sm font-medium transition-colors duration-200 cursor-pointer",- isActive- ? "bg-primary text-primary-foreground shadow-sm"- : "bg-secondary text-secondary-foreground hover:bg-accent"- )}- />- }- />- }- >- {agent.name.charAt(0).toUpperCase()}- {(taskCounts[agent.id] ?? 0) > 0 && (- <span className="absolute bottom-0 right-0 size-2 rounded-full bg-status-online animate-pulse ring-2 ring-background" />- )}- </TooltipTrigger>- <ContextMenuContent>- {isPinned ? (- <ContextMenuItem onClick={() => handleUnpinAgent(agent.id)}>- <PinOffIcon className="size-3.5 mr-1.5" />- Unpin- </ContextMenuItem>- ) : (- <ContextMenuItem onClick={() => handlePinAgent(agent.id)}>- <PinIcon className="size-3.5 mr-1.5" />- Pin to top- </ContextMenuItem>- )}- </ContextMenuContent>- </ContextMenu>- <TooltipContent side="right">{agent.name} (right-click for options)</TooltipContent>- </Tooltip>- );- };+ const renderAgentButton = (agent: typeof agents[number]) => (+ <AgentSidebarButton+ key={agent.id}+ agent={agent}+ isActive={activeAgentId === agent.id}+ isPinned={pins.has(agent.id)}+ taskCount={taskCounts[agent.id] ?? 0}+ onClick={() => handleAgentClick(agent.id)}+ onPin={() => handlePinAgent(agent.id)}+ onUnpin={() => handleUnpinAgent(agent.id)}+ />+ );return (<nav className="flex h-full w-14 flex-col items-center pt-1 pb-2 gap-0.5">diff --git a/src/web/src/components/task-stream.tsx b/src/web/src/components/task-stream.tsxindex 20d47b0ff..754f45d9f 100644--- a/src/web/src/components/task-stream.tsx+++ b/src/web/src/components/task-stream.tsx@@ -277,11 +277,17 @@ export function TaskStream({messages,connectionLost,onRetry,+ stepCountHint,+ onExpandSteps,+ stepsLoading,}: {task: Task;messages: TaskMessage[];connectionLost?: boolean;onRetry?: () => void;+ stepCountHint?: number;+ onExpandSteps?: () => void;+ stepsLoading?: boolean;}) {const [retrying, setRetrying] = useState(false);const allItems = useMemo(() => groupMessages(messages), [messages]);@@ -291,6 +297,7 @@ export function TaskStream({const textItems = allItems.filter((i): i is TextItem => i.kind === "text");const toolScrollRef = useRef<HTMLDivElement>(null);+ const expandedRef = useRef(false);// Auto-scroll tool area to bottom while runninguseEffect(() => {@@ -299,6 +306,16 @@ export function TaskStream({}}, [toolItems.length, isRunning]);+ const displayStepCount = toolItems.length > 0 ? toolItems.length : stepCountHint ?? 0;+ const showStepsSection = toolItems.length > 0 || (stepCountHint && stepCountHint > 0);++ const handleStepsToggle = (e: React.SyntheticEvent<HTMLDetailsElement>) => {+ if ((e.currentTarget as HTMLDetailsElement).open && !expandedRef.current && onExpandSteps) {+ expandedRef.current = true;+ onExpandSteps();+ }+ };+return (<div className="space-y-3">{/* Status badge */}@@ -330,8 +347,8 @@ export function TaskStream({</div>{/* Tool stream zone — foldable, height-limited, scrollable */}- {toolItems.length > 0 && (- <details className="group/stream pl-1">+ {showStepsSection && (+ <details className="group/stream pl-1" onToggle={handleStepsToggle}><summaryclassName={cn("flex items-center gap-1.5 py-1 cursor-pointer select-none",@@ -341,12 +358,18 @@ export function TaskStream({)}><ChevronRight className={cn("size-3 shrink-0 text-muted-foreground/60 transition-transform duration-150 group-open/stream:rotate-90", isRunning && "animate-pulse text-primary")} />- <span><AnimatedNumber value={toolItems.length} /> {toolItems.length === 1 ? "step" : "steps"}</span>+ <span><AnimatedNumber value={displayStepCount} /> {displayStepCount === 1 ? "step" : "steps"}</span></summary><divref={toolScrollRef}className="mt-1 max-h-80 overflow-y-auto overflow-x-hidden thin-scrollbar space-y-0.5 pl-1">+ {stepsLoading && toolItems.length === 0 && (+ <div className="flex items-center gap-2 py-2 text-xs text-muted-foreground">+ <Loader2 className="size-3 animate-spin" />+ <span>Loading steps...</span>+ </div>+ )}{toolItems.map((item) => {switch (item.kind) {case "tool-call":diff --git a/src/web/src/components/ui/popover.tsx b/src/web/src/components/ui/popover.tsxindex 8e99c6576..0b437c7b2 100644--- a/src/web/src/components/ui/popover.tsx+++ b/src/web/src/components/ui/popover.tsx@@ -16,10 +16,12 @@ function PopoverTrigger({ ...props }: PopoverPrimitive.Trigger.Props) {function PopoverContent({className,children,+ side,sideOffset = 6,align = "start",...props}: PopoverPrimitive.Popup.Props & {+ side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start"sideOffset?: numberalign?: "start" | "center" | "end"}) {@@ -32,6 +34,7 @@ function PopoverContent({return (<PopoverPrimitive.Portal container={container}><PopoverPrimitive.Positioner+ side={side}sideOffset={sideOffset}align={align}style={{ zIndex: 60 }}diff --git a/src/web/src/lib/api.test.ts b/src/web/src/lib/api.test.tsindex d8f328600..bb37523d5 100644--- a/src/web/src/lib/api.test.ts+++ b/src/web/src/lib/api.test.ts@@ -197,3 +197,42 @@ describe("apiFetch", () => {}});});++describe("getTaskStepCounts", () => {+ it("sends POST with task_ids and workspace_id", async () => {+ const counts = { "t1": 5, "t2": 12 };+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => counts,+ });++ const { getTaskStepCounts } = await getApiFetch();+ const result = await getTaskStepCounts(["t1", "t2"], "ws-1");+ expect(result).toEqual(counts);++ expect(mockFetch).toHaveBeenCalledWith(+ expect.stringContaining("/api/tasks/step-counts"),+ expect.objectContaining({+ method: "POST",+ headers: expect.objectContaining({ "Content-Type": "application/json" }),+ body: JSON.stringify({ task_ids: ["t1", "t2"] }),+ })+ );++ const calledUrl = mockFetch.mock.calls[0][0] as string;+ expect(calledUrl).toContain("workspace_id=ws-1");+ });++ it("returns empty object for empty task_ids", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: true,+ status: 200,+ json: async () => ({}),+ });++ const { getTaskStepCounts } = await getApiFetch();+ const result = await getTaskStepCounts([], "ws-1");+ expect(result).toEqual({});+ });+});diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex b11fd59cd..7dae46486 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -469,6 +469,15 @@ export const retryTask = (id: string, workspaceId: string) =>method: "POST",});+export const getTaskStepCounts = (taskIds: string[], workspaceId: string) =>+ apiFetch<Record<string, number>>(+ `/api/tasks/step-counts${wsQuery(workspaceId)}`,+ {+ method: "POST",+ body: JSON.stringify({ task_ids: taskIds }),+ }+ );+// Emailsexport const listEmails = (agentId: string, workspaceId: string, folder?: string, address?: string) =>apiFetch<Email[]>(`/api/email${wsQuery(workspaceId, { agentId, ...(folder ? { folder } : {}), ...(address ? { address } : {}) })}`);diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex 880705d0e..1196fdd11 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -325,11 +325,29 @@ describe("AgentResponse shape", () => {maxConcurrentTasks: 3, ...baseFields(),});expect(Object.keys(res).sort()).toEqual([- "created_at", "description", "email_handle", "id", "instructions", "max_concurrent_tasks",+ "avatar_url", "created_at", "description", "email_handle", "id", "instructions", "max_concurrent_tasks","name", "owner_id", "runtime_config", "runtime_id", "runtime_mode", "status","updated_at", "visibility", "workspace_id",]);});++ it("includes avatar_url as null when not provided", () => {+ const res = agentToResponse({+ id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",+ instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",+ maxConcurrentTasks: 1, ...baseFields(),+ });+ expect(res.avatar_url).toBeNull();+ });++ it("includes avatar_url when provided", () => {+ const res = agentToResponse({+ id: "a1", workspaceId: "w1", runtimeId: "r1", name: "A", description: "d",+ instructions: "i", runtimeMode: "auto", runtimeConfig: {}, status: "active",+ maxConcurrentTasks: 1, avatarUrl: "https://example.com/avatar.png", ...baseFields(),+ });+ expect(res.avatar_url).toBe("https://example.com/avatar.png");+ });});describe("ConversationResponse shape", () => {diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex b39f6c827..1ea7913c5 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -42,6 +42,7 @@ export function agentToResponse(a: any) {status: a.status,max_concurrent_tasks: a.maxConcurrentTasks,email_handle: a.emailHandle || null,+ avatar_url: a.avatarUrl || null,visibility: a.visibility ?? "private",owner_id: a.ownerId ?? null,created_at: formatTimestamp(a.createdAt),diff --git a/src/web/src/lib/highlight-mentions.test.ts b/src/web/src/lib/highlight-mentions.test.tsindex 792e6007d..31659601c 100644--- a/src/web/src/lib/highlight-mentions.test.ts+++ b/src/web/src/lib/highlight-mentions.test.ts@@ -14,6 +14,7 @@ const agent = (name: string, email_handle: string | null = null): Agent => ({status: "active",max_concurrent_tasks: 1,email_handle,+ avatar_url: null,visibility: "public",owner_id: null,created_at: "2024-01-01T00:00:00Z",@@ -21,14 +22,14 @@ const agent = (name: string, email_handle: string | null = null): Agent => ({})describe("highlightMentions", () => {- it("wraps basic @AgentName", () => {+ it("wraps basic @AgentName with data-agent-id", () => {const result = highlightMentions("Hey @TestBot do this", [agent("TestBot", "testbot")])- expect(result).toBe("Hey @<mention>TestBot</mention> do this")+ expect(result).toBe('Hey @<mention data-agent-id="ag_testbot">TestBot</mention> do this')})it("wraps only name portion of enriched form", () => {const result = highlightMentions("Hey @TestBot ([email protected]) do this", [agent("TestBot", "testbot")])- expect(result).toBe("Hey @<mention>TestBot</mention> ([email protected]) do this")+ expect(result).toBe('Hey @<mention data-agent-id="ag_testbot">TestBot</mention> ([email protected]) do this')})it("leaves non-matching @ as plain text", () => {@@ -36,9 +37,9 @@ describe("highlightMentions", () => {expect(result).toBe("send to [email protected]")})- it("wraps multiple mentions", () => {+ it("wraps multiple mentions with correct agent ids", () => {const result = highlightMentions("@Alpha and @Beta", [agent("Alpha", "alpha"), agent("Beta", "beta")])- expect(result).toBe("@<mention>Alpha</mention> and @<mention>Beta</mention>")+ expect(result).toBe('@<mention data-agent-id="ag_alpha">Alpha</mention> and @<mention data-agent-id="ag_beta">Beta</mention>')})it("does not wrap unknown agent names", () => {@@ -55,4 +56,17 @@ describe("highlightMentions", () => {const result = highlightMentions("Hey @TestBot", [])expect(result).toBe("Hey @TestBot")})++ it("includes data-agent-id attribute on mention tags", () => {+ const result = highlightMentions("Hello @TestBot", [agent("TestBot")])+ expect(result).toContain('data-agent-id="ag_testbot"')+ })++ it("includes correct agent id for each mention when multiple agents are mentioned", () => {+ const agents = [agent("Alice", "alice"), agent("Bob", "bob")]+ const result = highlightMentions("@Alice talk to @Bob", agents)+ expect(result).toContain('data-agent-id="ag_alice"')+ expect(result).toContain('data-agent-id="ag_bob"')+ expect(result).toBe('@<mention data-agent-id="ag_alice">Alice</mention> talk to @<mention data-agent-id="ag_bob">Bob</mention>')+ })})diff --git a/src/web/src/lib/highlight-mentions.ts b/src/web/src/lib/highlight-mentions.tsindex dc1728d98..504d02808 100644--- a/src/web/src/lib/highlight-mentions.ts+++ b/src/web/src/lib/highlight-mentions.ts@@ -23,6 +23,7 @@ export function highlightMentions(content: string, agents: Agent[]): string {start: numberend: numbername: string+ agentId: string}const matches: Match[] = []@@ -52,8 +53,7 @@ export function highlightMentions(content: string, agents: Agent[]): string {const overlaps = matches.some(m => i >= m.start && i < m.end)if (overlaps) break- // Only wrap the @Name part in <mention>, leave the (email) outside- matches.push({ start: i, end: nameEnd, name: agent.name })+ matches.push({ start: i, end: nameEnd, name: agent.name, agentId: agent.id })break}}@@ -63,7 +63,7 @@ export function highlightMentions(content: string, agents: Agent[]): string {for (let i = matches.length - 1; i >= 0; i--) {const m = matches[i]const name = result.slice(m.start + 1, m.end)- result = result.slice(0, m.start) + `@<mention>${name}</mention>` + result.slice(m.end)+ result = result.slice(0, m.start) + `@<mention data-agent-id="${m.agentId}">${name}</mention>` + result.slice(m.end)}return result