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 inbox for unread root task responses
Gus6c763bc9d764
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex f27751938..ee09decca 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -25,4 +25,5 @@ export * as channel from "./queries/channel";export * as workspaceFileRequest from "./queries/workspace-file-request";export * as conversationMap from "./queries/conversation-map";export * as agentLink from "./queries/agent-link";+export * as inbox from "./queries/inbox";export * as issue from "./queries/issue";diff --git a/src/shared/src/db/queries/inbox.ts b/src/shared/src/db/queries/inbox.tsnew file mode 100644index 000000000..b7b7b544e--- /dev/null+++ b/src/shared/src/db/queries/inbox.ts@@ -0,0 +1,142 @@+import { sql } from "drizzle-orm";+import { nanoid } from "nanoid";+import type { Database } from "../index";++export async function listUnreadConversations(+ db: Database,+ userId: string,+ workspaceId: string,+ opts?: { limit?: number; before?: string }+) {+ const limit = opts?.limit ?? 30;+ const beforeClause = opts?.before+ ? sql`AND m_latest.created_at < ${opts.before}`+ : sql``;++ const rows = await db.all<{+ id: string;+ agent_id: string;+ title: string;+ channel: string;+ latest_response: string;+ latest_response_at: string;+ root_prompt: string | null;+ agent_name: string | null;+ agent_avatar_url: string | null;+ root_task_status: string | null;+ }>(sql`+ WITH root_tasks AS (+ SELECT t.conversation_id, t.prompt, t.status, t.created_at,+ ROW_NUMBER() OVER (PARTITION BY t.conversation_id ORDER BY t.created_at DESC) AS rn+ FROM agent_task_queue t+ WHERE t.parent_task_id IS NULL+ AND t.trace_id IS NOT NULL+ AND t.type != 'kill_task'+ AND t.status IN ('completed', 'failed')+ )+ SELECT c.id,+ c.agent_id,+ c.title,+ c.channel,+ m_latest.content AS latest_response,+ m_latest.created_at AS latest_response_at,+ rt.prompt AS root_prompt,+ a.name AS agent_name,+ a.avatar_url AS agent_avatar_url,+ rt.status AS root_task_status+ FROM conversation c+ INNER JOIN message m_latest+ ON m_latest.conversation_id = c.id+ AND m_latest.role = 'assistant'+ AND m_latest.status = 'active'+ AND m_latest.id = (+ SELECT id FROM message+ WHERE conversation_id = c.id+ AND role = 'assistant'+ AND status = 'active'+ ORDER BY created_at DESC LIMIT 1+ )+ INNER JOIN root_tasks rt+ ON rt.conversation_id = c.id AND rt.rn = 1+ LEFT JOIN conversation_read_state crs+ ON crs.conversation_id = c.id AND crs.user_id = ${userId}+ LEFT JOIN agent a+ ON a.id = c.agent_id AND a.workspace_id = c.workspace_id+ WHERE c.user_id = ${userId}+ AND c.workspace_id = ${workspaceId}+ AND m_latest.created_at > COALESCE(crs.last_read_at, '1970-01-01T00:00:00.000Z')+ ${beforeClause}+ ORDER BY m_latest.created_at DESC+ LIMIT ${limit + 1}+ `);++ const hasMore = rows.length > limit;+ const items = rows.slice(0, limit);++ return { items, hasMore };+}++export async function getUnreadCount(+ db: Database,+ userId: string,+ workspaceId: string,+) {+ const rows = await db.all<{ count: number }>(sql`+ SELECT COUNT(*) AS count+ FROM conversation c+ WHERE c.user_id = ${userId}+ AND c.workspace_id = ${workspaceId}+ AND EXISTS (+ SELECT 1 FROM agent_task_queue t+ WHERE t.conversation_id = c.id+ AND t.parent_task_id IS NULL+ AND t.trace_id IS NOT NULL+ AND t.type != 'kill_task'+ AND t.status IN ('completed', 'failed')+ )+ AND EXISTS (+ SELECT 1 FROM message m+ WHERE m.conversation_id = c.id+ AND m.role = 'assistant'+ AND m.status = 'active'+ AND m.created_at > COALESCE(+ (SELECT last_read_at FROM conversation_read_state+ WHERE conversation_id = c.id AND user_id = ${userId}),+ '1970-01-01T00:00:00.000Z'+ )+ )+ `);++ return rows[0]?.count ?? 0;+}++export async function markConversationRead(+ db: Database,+ userId: string,+ conversationId: string,+) {+ const now = new Date().toISOString();+ await db.run(sql`+ INSERT INTO conversation_read_state (id, conversation_id, user_id, last_read_at, created_at)+ VALUES (${nanoid()}, ${conversationId}, ${userId}, ${now}, ${now})+ ON CONFLICT (conversation_id, user_id)+ DO UPDATE SET last_read_at = ${now}+ `);+}++export async function markAllConversationsRead(+ db: Database,+ userId: string,+ workspaceId: string,+) {+ const now = new Date().toISOString();+ await db.run(sql`+ INSERT INTO conversation_read_state (id, conversation_id, user_id, last_read_at, created_at)+ SELECT lower(hex(randomblob(11))), c.id, ${userId}, ${now}, ${now}+ FROM conversation c+ WHERE c.user_id = ${userId}+ AND c.workspace_id = ${workspaceId}+ ON CONFLICT (conversation_id, user_id)+ DO UPDATE SET last_read_at = ${now}+ `);+}diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex fe2ce2610..b9e533da9 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -656,6 +656,25 @@ export const agentLink = sqliteTable(]);+export const conversationReadState = sqliteTable(+ "conversation_read_state",+ {+ id: text("id").primaryKey().$defaultFn(() => nanoid()),+ conversationId: text("conversation_id")+ .notNull()+ .references(() => conversation.id, { onDelete: "cascade" }),+ userId: text("user_id")+ .notNull()+ .references(() => user.id, { onDelete: "cascade" }),+ lastReadAt: text("last_read_at").notNull().default("1970-01-01T00:00:00.000Z"),+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ (t) => [+ unique("conversation_read_state_conv_user").on(t.conversationId, t.userId),+ index("idx_conversation_read_state_user").on(t.userId),+ ]+);+export const workspaceFileRequest = sqliteTable("workspace_file_request",{diff --git a/src/web/migrations/0023_add_conversation_read_state.sql b/src/web/migrations/0023_add_conversation_read_state.sqlnew file mode 100644index 000000000..f6876a2e7--- /dev/null+++ b/src/web/migrations/0023_add_conversation_read_state.sql@@ -0,0 +1,18 @@+CREATE TABLE IF NOT EXISTS conversation_read_state (+ id TEXT PRIMARY KEY,+ conversation_id TEXT NOT NULL REFERENCES conversation(id) ON DELETE CASCADE,+ user_id TEXT NOT NULL REFERENCES "user"(id) ON DELETE CASCADE,+ last_read_at TEXT NOT NULL DEFAULT '1970-01-01T00:00:00.000Z',+ created_at TEXT NOT NULL DEFAULT (datetime('now')),+ UNIQUE(conversation_id, user_id)+);++CREATE INDEX IF NOT EXISTS idx_conversation_read_state_user+ ON conversation_read_state(user_id);++-- Performance indexes for inbox queries+CREATE INDEX IF NOT EXISTS idx_message_conv_role_status_created+ ON message(conversation_id, role, status, created_at);++CREATE INDEX IF NOT EXISTS idx_conversation_user_workspace+ ON conversation(user_id, workspace_id);diff --git a/src/web/src/app/(app)/w/[slug]/inbox/page.tsx b/src/web/src/app/(app)/w/[slug]/inbox/page.tsxnew file mode 100644index 000000000..8b6092c37--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/inbox/page.tsx@@ -0,0 +1,245 @@+"use client";++import { useState, useEffect, useCallback, useRef } from "react";+import Link from "next/link";+import { useWorkspace } from "@/contexts/workspace-context";+import { useAgentContext } from "@/contexts/agent-context";+import { listInboxItems, markAllInboxRead, type InboxItem } from "@/lib/api";+import { useInboxCount } from "@/contexts/inbox-count-context";+import { Skeleton } from "@/components/ui/skeleton";+import { Inbox } from "lucide-react";+import { AvatarRenderer, parseAvatarUrl } from "@/components/avatar";+import type { WsMessage } from "@alook/shared";++const INBOX_LIMIT = 30;++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 StatusDot({ status }: { status: string | null }) {+ const colorClass =+ status === "completed"+ ? "bg-[oklch(0.72_0.19_145)]"+ : status === "failed"+ ? "bg-destructive"+ : "bg-muted-foreground/40";+ return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;+}++function AgentAvatar({ name, avatarUrl, size = 32 }: { name?: string | null; 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-xs font-medium shrink-0"+ style={{ width: size, height: size }}+ >+ {(name ?? "?").charAt(0).toUpperCase()}+ </span>+ );+}++function InboxRow({ item, slug, onClick }: { item: InboxItem; slug: string; onClick?: () => void }) {+ const statusLabel = item.root_task_status === "failed" ? "Failed" : "Completed";++ return (+ <Link+ href={`/w/${slug}/agents/${item.agent_id}?conv=${item.id}`}+ onClick={onClick}+ 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={item.agent_name} avatarUrl={item.agent_avatar_url} />+ <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">+ {item.root_prompt ?? item.title}+ </span>+ <span className="text-xs text-muted-foreground shrink-0 ml-2" title={new Date(item.latest_response_at).toLocaleString()}>+ {relativeTime(item.latest_response_at)}+ </span>+ </div>+ <div className="flex items-center gap-1.5 mt-0.5">+ {item.agent_name && (+ <>+ <span className="text-xs font-medium text-muted-foreground">{item.agent_name}</span>+ <span className="text-muted-foreground/40">·</span>+ </>+ )}+ <StatusDot status={item.root_task_status} />+ <span className="text-xs text-muted-foreground">{statusLabel}</span>+ </div>+ <p className="text-xs text-muted-foreground/70 mt-1 line-clamp-1">+ {item.latest_response}+ </p>+ </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="size-8 rounded-full shrink-0" />+ <div className="flex-1">+ <Skeleton className="h-3.5 rounded" style={{ width: promptWidth }} />+ <div className="flex items-center gap-1.5 mt-1.5">+ <Skeleton className="h-2.5 w-16 rounded" />+ <Skeleton className="h-2.5 w-8 rounded" />+ </div>+ <Skeleton className="h-2.5 w-3/4 rounded mt-1.5" />+ </div>+ </div>+ </div>+ );+}++export default function InboxPage() {+ const { slug, workspaceId } = useWorkspace();+ const { subscribeWs } = useAgentContext();+ const { refresh: refreshInboxCount, decrement: decrementInboxCount } = useInboxCount();++ const [items, setItems] = useState<InboxItem[]>([]);+ 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 loadInitial = useCallback(async () => {+ setLoading(true);+ try {+ const result = await listInboxItems(workspaceId, { limit: INBOX_LIMIT });+ setItems(result.items);+ setHasMore(result.has_more);+ } catch {+ // silently fail+ } finally {+ setLoading(false);+ }+ }, [workspaceId]);++ useEffect(() => {+ loadInitial();+ refreshInboxCount();+ }, [loadInitial, refreshInboxCount]);++ useEffect(() => {+ return subscribeWs((msg: WsMessage) => {+ if (msg.type === "task.updated" && (msg.status === "completed" || msg.status === "failed")) {+ loadInitial();+ }+ });+ }, [subscribeWs, loadInitial]);++ const loadMore = useCallback(async () => {+ if (isFetchingRef.current || !hasMore || items.length === 0) return;+ isFetchingRef.current = true;+ setLoadingMore(true);+ try {+ const oldest = items[items.length - 1];+ const result = await listInboxItems(workspaceId, {+ limit: INBOX_LIMIT,+ before: oldest.latest_response_at,+ });+ if (result.items.length === 0) {+ setHasMore(false);+ return;+ }+ setHasMore(result.has_more);+ setItems((prev) => {+ const existingIds = new Set(prev.map((i) => i.id));+ const unique = result.items.filter((i) => !existingIds.has(i.id));+ return [...prev, ...unique];+ });+ } finally {+ isFetchingRef.current = false;+ setLoadingMore(false);+ }+ }, [workspaceId, items, hasMore]);++ const handleScroll = useCallback(() => {+ const el = scrollRef.current;+ if (!el) return;+ const nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 200;+ if (!loadingMore && hasMore && nearBottom) {+ loadMore();+ }+ }, [loadMore, loadingMore, hasMore]);++ const handleMarkAllRead = useCallback(async () => {+ setItems([]);+ setHasMore(false);+ try {+ await markAllInboxRead(workspaceId);+ refreshInboxCount();+ } catch {+ loadInitial();+ }+ }, [workspaceId, loadInitial, refreshInboxCount]);++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3">+ <div className="flex items-center gap-3 min-w-0">+ <h1 className="text-sm font-medium">Inbox</h1>+ <p className="text-xs text-muted-foreground hidden md:block">+ Unread responses from your agents.+ </p>+ </div>+ <div className="flex items-center gap-2">+ {!loading && items.length > 0 && (+ <button+ type="button"+ onClick={handleMarkAllRead}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ Mark all as read+ </button>+ )}+ </div>+ </div>++ <div+ ref={scrollRef}+ onScroll={handleScroll}+ className="flex-1 overflow-y-auto"+ >+ {loading ? (+ <>+ <SkeletonRow promptWidth="60%" />+ <SkeletonRow promptWidth="45%" />+ <SkeletonRow promptWidth="70%" />+ <SkeletonRow promptWidth="55%" />+ </>+ ) : items.length === 0 ? (+ <div className="flex flex-col items-center justify-center h-full text-muted-foreground gap-3 py-20">+ <Inbox className="size-10 opacity-30" />+ <p className="text-sm">No unread messages</p>+ </div>+ ) : (+ <>+ {items.map((item) => (+ <InboxRow key={item.id} item={item} slug={slug} onClick={decrementInboxCount} />+ ))}+ {loadingMore && <SkeletonRow promptWidth="50%" />}+ </>+ )}+ </div>+ </div>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/layout.tsx b/src/web/src/app/(app)/w/[slug]/layout.tsxindex 675d61b23..73e0d7493 100644--- a/src/web/src/app/(app)/w/[slug]/layout.tsx+++ b/src/web/src/app/(app)/w/[slug]/layout.tsx@@ -6,6 +6,7 @@ import { getSession } from "@/lib/session"import { WorkspaceProvider } from "@/contexts/workspace-context"import { AgentProvider } from "@/contexts/agent-context"import { ChannelProvider } from "@/contexts/channel-context"+import { InboxCountProvider } from "@/contexts/inbox-count-context"import { WorkspaceShell } from "@/components/workspace-shell"export default async function WorkspaceLayout({@@ -35,9 +36,11 @@ export default async function WorkspaceLayout({return (<WorkspaceProvider workspaceId={ws.id} slug={slug}><AgentProvider workspaceId={ws.id}>- <ChannelProvider workspaceId={ws.id}>- <WorkspaceShell>{children}</WorkspaceShell>- </ChannelProvider>+ <InboxCountProvider>+ <ChannelProvider workspaceId={ws.id}>+ <WorkspaceShell>{children}</WorkspaceShell>+ </ChannelProvider>+ </InboxCountProvider></AgentProvider></WorkspaceProvider>)diff --git a/src/web/src/app/(app)/w/[slug]/threads/page.tsx b/src/web/src/app/(app)/w/[slug]/threads/page.tsxindex 156f1713f..3fcfb91b1 100644--- a/src/web/src/app/(app)/w/[slug]/threads/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/threads/page.tsx@@ -263,7 +263,26 @@ export default function TracesPage() {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">+ <div className="flex items-center justify-between border-b border-border/50 px-3 md:px-5 py-2.5 gap-3">+ <div className="flex items-center gap-3 min-w-0">+ <h1 className="text-sm font-medium">Threads</h1>+ <p className="text-xs text-muted-foreground hidden md:block">+ Execution traces across your agents.+ </p>+ </div>+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={loadInitial}+ className="p-1.5 text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ title="Refresh"+ >+ <RefreshCw className="size-3.5" />+ </button>+ </div>+ </div>++ <div className="flex items-center gap-2 px-4 py-2"><Select value={statusFilter} onValueChange={(v) => updateFilter("status", 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" />@@ -307,19 +326,8 @@ export default function TracesPage() {))}</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>- <p className="px-4 pb-1 text-xs text-muted-foreground/50">Showing tasks that involve multiple agents</p>-<divref={scrollRef}className="flex-1 overflow-y-auto thin-scrollbar"diff --git a/src/web/src/app/api/inbox/count/route.ts b/src/web/src/app/api/inbox/count/route.tsnew file mode 100644index 000000000..49a998daa--- /dev/null+++ b/src/web/src/app/api/inbox/count/route.ts@@ -0,0 +1,19 @@+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 count = await queries.inbox.getUnreadCount(db, ctx.userId, ws.workspaceId);++ return writeJSON({ count });+});diff --git a/src/web/src/app/api/inbox/read-all/route.ts b/src/web/src/app/api/inbox/read-all/route.tsnew file mode 100644index 000000000..9b64e2014--- /dev/null+++ b/src/web/src/app/api/inbox/read-all/route.ts@@ -0,0 +1,18 @@+import { NextRequest, NextResponse } 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";++export const POST = withAuth(async (req: NextRequest, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ await queries.inbox.markAllConversationsRead(db, ctx.userId, ws.workspaceId);++ return new NextResponse(null, { status: 204 });+});diff --git a/src/web/src/app/api/inbox/read/route.ts b/src/web/src/app/api/inbox/read/route.tsnew file mode 100644index 000000000..ce623534e--- /dev/null+++ b/src/web/src/app/api/inbox/read/route.ts@@ -0,0 +1,33 @@+import { NextRequest, NextResponse } 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";++export const POST = withAuth(async (req: NextRequest, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ let body: { conversationId?: string };+ try {+ body = await req.json();+ } catch {+ return NextResponse.json({ error: "invalid JSON body" }, { status: 400 });+ }+ if (!body.conversationId) {+ return NextResponse.json({ error: "conversationId is required" }, { status: 400 });+ }++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const conv = await queries.conversation.getConversation(db, body.conversationId, ws.workspaceId);+ if (!conv || conv.userId !== ctx.userId) {+ return NextResponse.json({ error: "conversation not found" }, { status: 404 });+ }++ await queries.inbox.markConversationRead(db, ctx.userId, body.conversationId);++ return new NextResponse(null, { status: 204 });+});diff --git a/src/web/src/app/api/inbox/route.ts b/src/web/src/app/api/inbox/route.tsnew file mode 100644index 000000000..b5b3ef6b8--- /dev/null+++ b/src/web/src/app/api/inbox/route.ts@@ -0,0 +1,27 @@+import { NextRequest, NextResponse } 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 limitParam = req.nextUrl.searchParams.get("limit");+ const limit = limitParam ? Math.min(Math.max(parseInt(limitParam, 10) || 30, 1), 100) : 30;+ const before = req.nextUrl.searchParams.get("before") ?? undefined;++ if (before && isNaN(Date.parse(before))) {+ return NextResponse.json({ error: "invalid before timestamp" }, { status: 400 });+ }++ const result = await queries.inbox.listUnreadConversations(db, ctx.userId, ws.workspaceId, { limit, before });++ return writeJSON({ items: result.items, has_more: result.hasMore });+});diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex a9d185346..c55d26250 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -24,10 +24,12 @@ import {cancelActiveTask,getActiveTask,retryTask,+ markInboxRead,} from "@/lib/api";import type { PreviousConversation } from "@/lib/api";import type { Artifact, Conversation, Message, TaskApi as Task, TaskMessage, WsMessage } from "@alook/shared";import { useAgentContext } from "@/contexts/agent-context";+import { useInboxCount } from "@/contexts/inbox-count-context";import { useChannel } from "@/contexts/channel-context";import { toast } from "sonner";import { cn } from "@/lib/utils";@@ -324,6 +326,7 @@ export function AgentChatView() {const searchParams = useSearchParams();const { workspaceId } = useWorkspace();const { agents, activeTaskCounts, subscribeWs } = useAgentContext();+ const { refresh: refreshInboxCount } = useInboxCount();const { activeChannel, loading: channelLoading } = useChannel();const agentId = params.id as string;const scrollToTaskId = searchParams.get("task");@@ -526,6 +529,16 @@ export function AgentChatView() {return () => { ignore = true; };}, [agentId, workspaceId, targetConvId, scrollToTaskId, activeChannel, channelLoading]);+ const markedReadRef = useRef<string | null>(null);+ useEffect(() => {+ if (!conversation?.id || !workspaceId) return;+ if (markedReadRef.current === conversation.id) return;+ markedReadRef.current = conversation.id;+ markInboxRead(conversation.id, workspaceId)+ .then(() => refreshInboxCount())+ .catch(() => {});+ }, [conversation?.id, workspaceId, refreshInboxCount]);+// Scroll to bottom on initial load (skip if scroll-to-task is active)useEffect(() => {if (!loading && messages.length > 0 && !initialScrollDone.current) {diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsxindex 3f4699902..b04fa3320 100644--- a/src/web/src/components/app-sidebar.tsx+++ b/src/web/src/components/app-sidebar.tsx@@ -5,9 +5,10 @@ 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 { useInboxCount } from "@/contexts/inbox-count-context";import { Logo } from "@/components/logo";import { cn } from "@/lib/utils";-import { Monitor, SunMoon, Plus, CalendarDays, GitBranch, Settings, PinIcon, PinOffIcon, ArrowLeftRight, Home, CircleDot } from "lucide-react";+import { Monitor, SunMoon, Plus, CalendarDays, GitBranch, Settings, PinIcon, PinOffIcon, ArrowLeftRight, Home, CircleDot, Inbox } from "lucide-react";import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import { useTheme } from "next-themes";@@ -133,6 +134,7 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {const { resolvedTheme, setTheme } = useTheme();const { activeTaskCounts: taskCounts } = useAgentContext();+ const { count: inboxCount } = useInboxCount();const pinned = agents.filter((a) => pins.has(a.id))@@ -175,6 +177,7 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {const isRuntimes = pathname === `${prefix}/runtimes`;const isCalendar = pathname === `${prefix}/calendar`;const isTraces = pathname.startsWith(`${prefix}/threads`);+ const isInbox = pathname.startsWith(`${prefix}/inbox`);const isIssues = pathname.startsWith(`${prefix}/issues`);const isSettings = pathname === `${prefix}/settings`;const isCreateAgent = pathname === `${prefix}/agents/new`;@@ -266,17 +269,22 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {<TooltipTrigger render={<buttontype="button"- onClick={() => { router.push(`${prefix}/calendar`); onNavigate?.(); }}+ onClick={() => { router.push(`${prefix}/inbox`); onNavigate?.(); }}className={cn(- "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",+ "relative 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"+ isInbox && "bg-accent text-foreground")}/>}>- <CalendarDays className="size-4" />+ <Inbox className="size-4" />+ {inboxCount > 0 && (+ <span className="absolute top-1 right-1 flex items-center justify-center min-w-3.5 h-3.5 rounded-full bg-primary text-primary-foreground text-[9px] font-bold px-0.5">+ {inboxCount > 99 ? "99+" : inboxCount}+ </span>+ )}</TooltipTrigger>- <TooltipContent side="right">Calendar</TooltipContent>+ <TooltipContent side="right">Inbox</TooltipContent></Tooltip><Tooltip>@@ -296,6 +304,23 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {<TooltipContent side="right">Issues</TooltipContent></Tooltip>+ <Tooltip>+ <TooltipTrigger render={+ <button+ type="button"+ 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"+ )}+ />+ }>+ <CalendarDays className="size-4" />+ </TooltipTrigger>+ <TooltipContent side="right">Calendar</TooltipContent>+ </Tooltip>+<Tooltip><TooltipTrigger render={<buttondiff --git a/src/web/src/contexts/inbox-count-context.tsx b/src/web/src/contexts/inbox-count-context.tsxnew file mode 100644index 000000000..de398476f--- /dev/null+++ b/src/web/src/contexts/inbox-count-context.tsx@@ -0,0 +1,63 @@+"use client";++import {+ createContext,+ useContext,+ useState,+ useEffect,+ useCallback,+ type ReactNode,+} from "react";+import { getInboxCount } from "@/lib/api";+import { useAgentContext } from "@/contexts/agent-context";+import { useWorkspace } from "@/contexts/workspace-context";+import type { WsMessage } from "@alook/shared";++interface InboxCountContextValue {+ count: number;+ refresh: () => void;+ decrement: () => void;+}++const InboxCountContext = createContext<InboxCountContextValue | null>(null);++export function useInboxCount() {+ const ctx = useContext(InboxCountContext);+ if (!ctx) throw new Error("useInboxCount must be used within InboxCountProvider");+ return ctx;+}++export function InboxCountProvider({ children }: { children: ReactNode }) {+ const { workspaceId } = useWorkspace();+ const { subscribeWs } = useAgentContext();+ const [count, setCount] = useState(0);++ const refresh = useCallback(() => {+ getInboxCount(workspaceId).then((r) => setCount(r.count)).catch(() => {});+ }, [workspaceId]);++ const decrement = useCallback(() => {+ setCount((c) => Math.max(0, c - 1));+ }, []);++ useEffect(() => { refresh(); }, [refresh]);++ useEffect(() => {+ return subscribeWs((msg: WsMessage) => {+ if (msg.type === "task.updated" && (msg.status === "completed" || msg.status === "failed")) {+ refresh();+ }+ });+ }, [subscribeWs, refresh]);++ useEffect(() => {+ const id = setInterval(refresh, 30_000);+ return () => clearInterval(id);+ }, [refresh]);++ return (+ <InboxCountContext.Provider value={{ count, refresh, decrement }}>+ {children}+ </InboxCountContext.Provider>+ );+}diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 357724ff2..b3cf8c253 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -1040,6 +1040,46 @@ export const deleteMeeting = (agentId: string, meetingId: string, workspaceId: smethod: "DELETE",});+// Inbox+export interface InboxItem {+ id: string;+ agent_id: string;+ title: string;+ channel: string;+ latest_response: string;+ latest_response_at: string;+ root_prompt: string | null;+ agent_name: string | null;+ agent_avatar_url: string | null;+ root_task_status: string | null;+}++export const listInboxItems = (+ 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<{ items: InboxItem[]; has_more: boolean }>(+ `/api/inbox${wsQuery(workspaceId, extra)}`+ );+};++export const getInboxCount = (workspaceId: string) =>+ apiFetch<{ count: number }>(`/api/inbox/count${wsQuery(workspaceId)}`);++export const markInboxRead = (conversationId: string, workspaceId: string) =>+ apiFetch<void>(`/api/inbox/read${wsQuery(workspaceId)}`, {+ method: "POST",+ body: JSON.stringify({ conversationId }),+ });++export const markAllInboxRead = (workspaceId: string) =>+ apiFetch<void>(`/api/inbox/read-all${wsQuery(workspaceId)}`, {+ method: "POST",+ });+// Tracesexport interface TraceListItem {trace_id: string;