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(web): add workspace overview dashboard as home page
Gener77062669b86c
diff --git a/src/shared/src/db/queries-index.ts b/src/shared/src/db/queries-index.tsindex e0ae603ec..949935833 100644--- a/src/shared/src/db/queries-index.ts+++ b/src/shared/src/db/queries-index.ts@@ -18,3 +18,4 @@ export * as emailAccount from "./queries/email-account";export * as workspaceInvite from "./queries/workspace-invite";export * as agentAccess from "./queries/agent-access";export * as agentPin from "./queries/agent-pin";+export * as overview from "./queries/overview";diff --git a/src/shared/src/db/queries/overview.ts b/src/shared/src/db/queries/overview.tsnew file mode 100644index 000000000..c75509150--- /dev/null+++ b/src/shared/src/db/queries/overview.ts@@ -0,0 +1,166 @@+import { eq, and, count, desc, inArray, gte, ne, lt, sql } from "drizzle-orm";+import { emails, agentEmailAccount, agentTaskQueue, conversation } from "../schema";+import type { Database } from "../index";+import { TASK_TYPES } from "../../constants";++export async function getEmailStatsByWorkspace(db: Database, workspaceId: string) {+ const rows = await db+ .select({+ direction: emails.direction,+ cnt: count(),+ })+ .from(emails)+ .where(eq(emails.workspaceId, workspaceId))+ .groupBy(emails.direction);++ const unreadRows = await db+ .select({ cnt: count() })+ .from(emails)+ .where(+ and(+ eq(emails.workspaceId, workspaceId),+ eq(emails.status, "unread"),+ eq(emails.direction, "inbound")+ )+ );++ const rejectedRows = await db+ .select({ cnt: count() })+ .from(emails)+ .where(+ and(+ eq(emails.workspaceId, workspaceId),+ eq(emails.isWhitelisted, false),+ eq(emails.direction, "inbound")+ )+ );++ let inbound = 0;+ let outbound = 0;+ for (const r of rows) {+ if (r.direction === "inbound") inbound = Number(r.cnt);+ if (r.direction === "outbound") outbound = Number(r.cnt);+ }++ return {+ inbound,+ outbound,+ unread: Number(unreadRows[0]?.cnt ?? 0),+ rejected: Number(rejectedRows[0]?.cnt ?? 0),+ };+}++export async function getEmailAccountsByWorkspace(db: Database, workspaceId: string) {+ return db+ .select({+ id: agentEmailAccount.id,+ agentId: agentEmailAccount.agentId,+ emailAddress: agentEmailAccount.emailAddress,+ status: agentEmailAccount.status,+ errorMessage: agentEmailAccount.errorMessage,+ lastSyncedAt: agentEmailAccount.lastSyncedAt,+ })+ .from(agentEmailAccount)+ .where(eq(agentEmailAccount.workspaceId, workspaceId));+}++export async function getTaskStatsByWorkspace(+ db: Database,+ workspaceId: string,+ todayStart: string+) {+ const terminalRows = await db+ .select({+ status: agentTaskQueue.status,+ cnt: count(),+ })+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),+ gte(agentTaskQueue.completedAt, todayStart),+ inArray(agentTaskQueue.status, ["completed", "failed", "cancelled"])+ )+ )+ .groupBy(agentTaskQueue.status);++ const queuedRows = await db+ .select({ cnt: count() })+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ eq(agentTaskQueue.status, "queued"),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK)+ )+ );++ const staleThreshold = new Date(Date.now() - 3600 * 1000).toISOString();+ const staleRows = await db+ .select({ cnt: count() })+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ eq(agentTaskQueue.status, "running"),+ lt(agentTaskQueue.startedAt, staleThreshold)+ )+ );++ let completed = 0;+ let failed = 0;+ let cancelled = 0;+ for (const r of terminalRows) {+ if (r.status === "completed") completed = Number(r.cnt);+ if (r.status === "failed") failed = Number(r.cnt);+ if (r.status === "cancelled") cancelled = Number(r.cnt);+ }++ return {+ completed,+ failed,+ cancelled,+ queued: Number(queuedRows[0]?.cnt ?? 0),+ stale: Number(staleRows[0]?.cnt ?? 0),+ };+}++export async function getRecentTerminalTasks(+ db: Database,+ workspaceId: string,+ limit = 15+) {+ return db+ .select({+ id: agentTaskQueue.id,+ agentId: agentTaskQueue.agentId,+ type: agentTaskQueue.type,+ status: agentTaskQueue.status,+ prompt: agentTaskQueue.prompt,+ createdAt: agentTaskQueue.createdAt,+ completedAt: agentTaskQueue.completedAt,+ error: agentTaskQueue.error,+ })+ .from(agentTaskQueue)+ .where(+ and(+ eq(agentTaskQueue.workspaceId, workspaceId),+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),+ inArray(agentTaskQueue.status, ["completed", "failed", "cancelled"])+ )+ )+ .orderBy(desc(agentTaskQueue.completedAt))+ .limit(limit);+}++export async function getConversationCountsByAgent(db: Database, workspaceId: string) {+ return db+ .select({+ agentId: conversation.agentId,+ cnt: count(),+ })+ .from(conversation)+ .where(eq(conversation.workspaceId, workspaceId))+ .groupBy(conversation.agentId);+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsxnew file mode 100644index 000000000..e37a22a7c--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/agent-overview.tsx@@ -0,0 +1,116 @@+"use client";++import { useRouter } from "next/navigation";+import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";+import { useWorkspace } from "@/contexts/workspace-context";+import { MessageSquare, Mail, Plus } from "lucide-react";+import type { Agent, AgentRuntime } from "@alook/shared";+import type { WorkspaceOverview } from "@/lib/api";++interface AgentOverviewProps {+ agents: Agent[];+ runtimes: AgentRuntime[];+ activeTaskCounts: Record<string, number>;+ overview: WorkspaceOverview;+}++export function AgentOverview({ agents, runtimes, activeTaskCounts, overview }: AgentOverviewProps) {+ const router = useRouter();+ const { slug } = useWorkspace();++ if (agents.length === 0) return null;++ return (+ <Card>+ <CardHeader>+ <CardTitle>Agents</CardTitle>+ <CardAction>+ <button+ type="button"+ onClick={() => router.push(`/w/${slug}/agents/new`)}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ <Plus className="size-4" />+ </button>+ </CardAction>+ </CardHeader>+ <CardContent className="p-0">+ <div className="divide-y divide-border/50">+ {agents.map((agent) => {+ const rt = runtimes.find((r) => r.id === agent.runtime_id);+ const isOnline = rt?.status === "online";+ const tasks = activeTaskCounts[agent.id] ?? 0;+ const convos = overview.conversation_counts[agent.id] ?? 0;++ return (+ <button+ key={agent.id}+ type="button"+ onClick={() => router.push(`/w/${slug}/agents/${agent.id}`)}+ className="flex w-full items-center gap-3 px-4 py-2.5 text-left hover:bg-accent/50 transition-colors cursor-pointer"+ >+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-secondary text-secondary-foreground text-sm font-medium">+ {agent.name.charAt(0).toUpperCase()}+ </div>++ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-medium truncate">{agent.name}</span>+ <Tooltip>+ <TooltipTrigger render={+ <span+ className={`size-2 rounded-full shrink-0 ${isOnline ? "bg-emerald-500" : "bg-muted-foreground/30"}`}+ />+ } />+ <TooltipContent side="top">{isOnline ? "Online" : "Offline"}</TooltipContent>+ </Tooltip>+ {agent.visibility === "public" && (+ <Badge variant="secondary" className="text-[10px] px-1.5 py-0">+ public+ </Badge>+ )}+ </div>+ </div>++ <div className="flex items-center gap-4 text-xs text-muted-foreground shrink-0">+ {tasks > 0 && (+ <Tooltip>+ <TooltipTrigger render={+ <span className="flex items-center gap-1 text-primary font-medium">+ <span className="size-1.5 rounded-full bg-primary animate-pulse" />+ {tasks} active+ </span>+ } />+ <TooltipContent side="top">{tasks} active task{tasks > 1 ? "s" : ""}</TooltipContent>+ </Tooltip>+ )}+ <Tooltip>+ <TooltipTrigger render={+ <span className="flex items-center gap-1">+ <MessageSquare className="size-3" />+ {convos}+ </span>+ } />+ <TooltipContent side="top">{convos} conversation{convos !== 1 ? "s" : ""}</TooltipContent>+ </Tooltip>+ {agent.email_handle && (+ <Tooltip>+ <TooltipTrigger render={+ <span className="flex items-center">+ <Mail className="size-3" />+ </span>+ } />+ <TooltipContent side="top">{agent.email_handle}</TooltipContent>+ </Tooltip>+ )}+ </div>+ </button>+ );+ })}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsxnew file mode 100644index 000000000..12940e6aa--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/calendar-overview.tsx@@ -0,0 +1,90 @@+"use client";++import { useRouter } from "next/navigation";+import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";+import { useWorkspace } from "@/contexts/workspace-context";+import { CalendarDays, ArrowUpRight } from "lucide-react";+import type { WorkspaceOverview } from "@/lib/api";+import type { Agent } from "@alook/shared";++interface CalendarOverviewProps {+ overview: WorkspaceOverview;+ agents: Agent[];+}++export function CalendarOverview({ overview, agents }: CalendarOverviewProps) {+ const router = useRouter();+ const { slug } = useWorkspace();+ const { calendar_events } = overview;+ const agentMap = new Map(agents.map((a) => [a.id, a.name]));++ const now = new Date();+ const todayEnd = new Date(now);+ todayEnd.setHours(23, 59, 59, 999);++ const todayEvents = calendar_events.filter(+ (e) => new Date(e.scheduled_at) <= todayEnd+ );++ const recurring = calendar_events.filter((e) => e.repeat_interval);+ const oneOff = calendar_events.filter((e) => !e.repeat_interval);++ const upcoming = [...calendar_events]+ .sort((a, b) => new Date(a.scheduled_at).getTime() - new Date(b.scheduled_at).getTime())+ .slice(0, 5);++ return (+ <Card>+ <CardHeader>+ <CardTitle>Calendar</CardTitle>+ <CardAction>+ <button+ type="button"+ onClick={() => router.push(`/w/${slug}/calendar`)}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ <ArrowUpRight className="size-4" />+ </button>+ </CardAction>+ </CardHeader>+ <CardContent className="space-y-3">+ <div className="grid grid-cols-3 gap-3">+ <div>+ <p className="text-xl font-semibold">{todayEvents.length}</p>+ <p className="text-xs text-muted-foreground">Today</p>+ </div>+ <div>+ <p className="text-xl font-semibold">{recurring.length}</p>+ <p className="text-xs text-muted-foreground">Recurring</p>+ </div>+ <div>+ <p className="text-xl font-semibold">{oneOff.length}</p>+ <p className="text-xs text-muted-foreground">One-off</p>+ </div>+ </div>++ {upcoming.length > 0 && (+ <div className="space-y-1.5 pt-2 border-t border-border/50">+ <p className="text-xs font-medium text-muted-foreground">Upcoming This Week</p>+ {upcoming.map((e) => (+ <div key={e.id} className="flex items-center gap-2 text-xs">+ <CalendarDays className="size-3 shrink-0 text-muted-foreground" />+ <span className="truncate flex-1">{e.title}</span>+ <span className="text-muted-foreground shrink-0">+ {agentMap.get(e.agent_id) ?? "—"}+ </span>+ <span className="text-muted-foreground shrink-0">+ {new Date(e.scheduled_at).toLocaleDateString(undefined, { weekday: "short", hour: "2-digit", minute: "2-digit" })}+ </span>+ </div>+ ))}+ </div>+ )}++ {calendar_events.length === 0 && (+ <p className="text-sm text-muted-foreground">No events this week.</p>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsxnew file mode 100644index 000000000..fa8fbbef0--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/email-summary.tsx@@ -0,0 +1,72 @@+"use client";++import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";+import type { WorkspaceOverview } from "@/lib/api";+import type { Agent } from "@alook/shared";++interface EmailSummaryProps {+ overview: WorkspaceOverview;+ agents: Agent[];+}++export function EmailSummary({ overview, agents }: EmailSummaryProps) {+ const { inbound, outbound, unread, rejected } = overview.email_stats;++ const agentMap = new Map(agents.map((a) => [a.id, a.name]));++ return (+ <Card>+ <CardHeader>+ <CardTitle>Email Summary</CardTitle>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <div>+ <p className="text-xl font-semibold">{inbound}</p>+ <p className="text-xs text-muted-foreground">Received</p>+ </div>+ <div>+ <p className="text-xl font-semibold">{outbound}</p>+ <p className="text-xs text-muted-foreground">Sent</p>+ </div>+ <div>+ <p className={`text-xl font-semibold ${unread > 0 ? "text-primary" : ""}`}>{unread}</p>+ <p className="text-xs text-muted-foreground">Unread</p>+ </div>+ <div>+ <p className={`text-xl font-semibold ${rejected > 0 ? "text-amber-500" : ""}`}>{rejected}</p>+ <p className="text-xs text-muted-foreground">Rejected</p>+ </div>+ </div>++ {overview.email_accounts.length > 0 && (+ <div className="space-y-2 pt-2 border-t border-border/50">+ <p className="text-xs font-medium text-muted-foreground">Custom Mailboxes</p>+ {overview.email_accounts.map((acc) => (+ <div key={acc.id} className="flex items-center justify-between gap-2 text-xs">+ <div className="flex items-center gap-2 min-w-0">+ <Tooltip>+ <TooltipTrigger render={+ <span+ className={`size-1.5 shrink-0 rounded-full ${acc.status === "active" ? "bg-emerald-500" : "bg-destructive"}`}+ />+ } />+ <TooltipContent side="top">+ {acc.status === "active" ? "Active" : `Error: ${acc.error_message || "inactive"}`}+ </TooltipContent>+ </Tooltip>+ <span className="truncate">{acc.email_address}</span>+ </div>+ <span className="text-muted-foreground shrink-0">+ {agentMap.get(acc.agent_id) ?? "—"}+ </span>+ </div>+ ))}+ </div>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsxnew file mode 100644index 000000000..872a85cdd--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/quick-stats.tsx@@ -0,0 +1,92 @@+"use client";++import { Card, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Bot, Mail, Send, Users, Monitor, Zap } from "lucide-react";+import type { Agent, AgentRuntime } from "@alook/shared";+import type { WorkspaceOverview } from "@/lib/api";++interface QuickStatsProps {+ agents: Agent[];+ runtimes: AgentRuntime[];+ activeTaskCounts: Record<string, number>;+ overview: WorkspaceOverview;+}++function StatCard({+ icon: Icon,+ label,+ value,+ sub,+}: {+ icon: React.ElementType;+ label: string;+ value: number | string;+ sub?: string;+}) {+ return (+ <Card size="sm">+ <CardContent className="flex items-center gap-3">+ <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">+ <Icon className="size-4" />+ </div>+ <div className="flex-1 min-w-0">+ <div className="flex items-center justify-between gap-1">+ <p className="text-2xl font-semibold leading-none tracking-tight">{value}</p>+ {sub && <Badge variant="secondary" className="text-[10px] px-1.5 h-4 font-normal">{sub}</Badge>}+ </div>+ <p className="mt-1 text-xs text-muted-foreground truncate">{label}</p>+ </div>+ </CardContent>+ </Card>+ );+}++export function QuickStatsRow({ agents, runtimes, activeTaskCounts, overview }: QuickStatsProps) {+ const onlineRuntimes = runtimes.filter((r) => r.status === "online").length;+ const totalActiveTasks = Object.values(activeTaskCounts).reduce((a, b) => a + b, 0);+ const onlineAgents = agents.filter((a) => {+ const rt = runtimes.find((r) => r.id === a.runtime_id);+ return rt?.status === "online";+ }).length;++ return (+ <div className="grid gap-3 grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">+ <StatCard+ icon={Bot}+ label="Agents"+ value={agents.length}+ sub={`${onlineAgents} online`}+ />+ <StatCard+ icon={Mail}+ label="Custom Emails"+ value={overview.email_accounts.length}+ />+ <StatCard+ icon={Send}+ label="Emails Sent"+ value={overview.email_stats.outbound}+ sub={`${overview.email_stats.unread} unread`}+ />+ <StatCard+ icon={Users}+ label="Members"+ value={overview.members.length}+ sub={overview.pending_invites > 0 ? `${overview.pending_invites} pending` : undefined}+ />+ <StatCard+ icon={Monitor}+ label="Machines"+ value={`${onlineRuntimes}/${new Set(runtimes.map((r) => r.daemon_id)).size}`}+ sub="online"+ />+ <StatCard+ icon={Zap}+ label="Active Tasks"+ value={totalActiveTasks}+ sub={overview.task_stats.queued > 0 ? `${overview.task_stats.queued} queued` : undefined}+ />+ </div>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsxnew file mode 100644index 000000000..f7a1e150b--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/recent-activity.tsx@@ -0,0 +1,98 @@+"use client";++import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";+import { MessageSquare, Mail, CalendarDays } from "lucide-react";+import type { WorkspaceOverview } from "@/lib/api";+import type { Agent } from "@alook/shared";++interface RecentActivityProps {+ overview: WorkspaceOverview;+ agents: Agent[];+}++const TYPE_CONFIG: Record<string, { icon: React.ElementType; label: string }> = {+ user_dm_message: { icon: MessageSquare, label: "Chat message" },+ email_notification: { icon: Mail, label: "Email task" },+ calendar_event: { icon: CalendarDays, label: "Calendar event" },+};++function timeAgo(dateStr: string | null): string {+ if (!dateStr) return "";+ const diff = Date.now() - new Date(dateStr).getTime();+ const mins = Math.floor(diff / 60000);+ if (mins < 1) return "just now";+ if (mins < 60) return `${mins}m ago`;+ const hours = Math.floor(mins / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.floor(hours / 24);+ return `${days}d ago`;+}++export function RecentActivity({ overview, agents }: RecentActivityProps) {+ const { recent_tasks } = overview;+ const agentMap = new Map(agents.map((a) => [a.id, a.name]));++ if (recent_tasks.length === 0) {+ return (+ <Card>+ <CardHeader>+ <CardTitle>Recent Activity</CardTitle>+ </CardHeader>+ <CardContent>+ <p className="text-sm text-muted-foreground">No recent activity.</p>+ </CardContent>+ </Card>+ );+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>Recent Activity</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <div className="divide-y divide-border/50">+ {recent_tasks.map((task) => {+ const config = TYPE_CONFIG[task.type] ?? TYPE_CONFIG.user_dm_message;+ const Icon = config.icon;+ return (+ <div key={task.id} className="flex items-center gap-3 px-4 py-2.5">+ <Tooltip>+ <TooltipTrigger render={+ <span className="flex items-center">+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ </span>+ } />+ <TooltipContent side="top">{config.label}</TooltipContent>+ </Tooltip>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-xs font-medium shrink-0">+ {agentMap.get(task.agent_id) ?? "Unknown"}+ </span>+ <span className="text-xs text-muted-foreground truncate">+ {task.prompt.slice(0, 80)}{task.prompt.length > 80 ? "..." : ""}+ </span>+ </div>+ </div>+ <div className="flex items-center gap-2 shrink-0">+ <Badge+ variant={task.status === "completed" ? "secondary" : "destructive"}+ className="text-[10px] px-1.5 py-0"+ >+ {task.status}+ </Badge>+ <span className="text-[10px] text-muted-foreground w-14 text-right">+ {timeAgo(task.completed_at)}+ </span>+ </div>+ </div>+ );+ })}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsxnew file mode 100644index 000000000..534aeee6f--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/runtime-health.tsx@@ -0,0 +1,127 @@+"use client";++import { useRouter } from "next/navigation";+import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";+import { useWorkspace } from "@/contexts/workspace-context";+import { ArrowUpRight } from "lucide-react";+import type { Agent, AgentRuntime } from "@alook/shared";++interface RuntimeHealthProps {+ runtimes: AgentRuntime[];+ agents: Agent[];+}++function timeAgo(dateStr: string | null): string {+ if (!dateStr) return "never";+ const diff = Date.now() - new Date(dateStr).getTime();+ const secs = Math.floor(diff / 1000);+ if (secs < 60) return `${secs}s ago`;+ const mins = Math.floor(secs / 60);+ if (mins < 60) return `${mins}m ago`;+ const hours = Math.floor(mins / 60);+ if (hours < 24) return `${hours}h ago`;+ return `${Math.floor(hours / 24)}d ago`;+}++export function RuntimeHealth({ runtimes, agents }: RuntimeHealthProps) {+ const router = useRouter();+ const { slug } = useWorkspace();+ const machineMap = new Map<string, { runtimes: AgentRuntime[]; deviceInfo: string }>();+ for (const rt of runtimes) {+ const key = rt.daemon_id ?? rt.id;+ if (!machineMap.has(key)) {+ machineMap.set(key, { runtimes: [], deviceInfo: rt.device_info ?? "" });+ }+ machineMap.get(key)!.runtimes.push(rt);+ }++ const machines = [...machineMap.entries()];++ if (machines.length === 0) {+ return (+ <Card>+ <CardHeader>+ <CardTitle>Machines</CardTitle>+ <CardAction>+ <button+ type="button"+ onClick={() => router.push(`/w/${slug}/runtimes`)}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ <ArrowUpRight className="size-4" />+ </button>+ </CardAction>+ </CardHeader>+ <CardContent>+ <p className="text-sm text-muted-foreground">No machines connected.</p>+ </CardContent>+ </Card>+ );+ }++ return (+ <Card>+ <CardHeader>+ <CardTitle>Machines</CardTitle>+ </CardHeader>+ <CardContent className="space-y-3">+ {machines.map(([daemonId, machine]) => {+ const isOnline = machine.runtimes.some((r) => r.status === "online");+ const lastSeen = machine.runtimes+ .map((r) => r.last_seen_at)+ .filter(Boolean)+ .sort()+ .reverse()[0];+ const boundAgents = agents.filter((a) =>+ machine.runtimes.some((r) => r.id === a.runtime_id)+ );+ const hasPendingUpdate = machine.runtimes.some(+ (r) => r.pending_update_version+ );+ const updateVersion = machine.runtimes.find((r) => r.pending_update_version)?.pending_update_version;++ return (+ <div key={daemonId} className="flex items-start gap-3 text-xs">+ <Tooltip>+ <TooltipTrigger render={+ <span+ className={`mt-1 size-2 shrink-0 rounded-full ${isOnline ? "bg-emerald-500" : "bg-muted-foreground/30"}`}+ />+ } />+ <TooltipContent side="top">{isOnline ? "Online" : "Offline"}</TooltipContent>+ </Tooltip>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="font-medium truncate">+ {machine.deviceInfo || daemonId.slice(0, 12)}+ </span>+ {hasPendingUpdate && (+ <Tooltip>+ <TooltipTrigger render={+ <span>+ <Badge variant="outline" className="text-[10px] px-1.5 py-0 text-amber-500 border-amber-500/30">+ update+ </Badge>+ </span>+ } />+ <TooltipContent side="top">Pending update to v{updateVersion}</TooltipContent>+ </Tooltip>+ )}+ </div>+ <div className="text-muted-foreground mt-0.5">+ {boundAgents.length > 0+ ? boundAgents.map((a) => a.name).join(", ")+ : "No agents"}+ {" · "}+ {timeAgo(lastSeen ?? null)}+ </div>+ </div>+ </div>+ );+ })}+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsxnew file mode 100644index 000000000..9e78227c3--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/task-health.tsx@@ -0,0 +1,41 @@+"use client";++import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";+import type { WorkspaceOverview } from "@/lib/api";++interface TaskHealthProps {+ overview: WorkspaceOverview;+}++export function TaskHealth({ overview }: TaskHealthProps) {+ const { completed, failed, cancelled, queued, stale } = overview.task_stats;+ const total = completed + failed;+ const failRate = total > 0 ? ((failed / total) * 100).toFixed(1) : "0";++ return (+ <Card>+ <CardHeader>+ <CardTitle>Task Health (Today)</CardTitle>+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-2 gap-3">+ <Stat label="Completed" value={completed} />+ <Stat label="Failed" value={failed} className={failed > 0 ? "text-destructive" : undefined} />+ <Stat label="Cancelled" value={cancelled} />+ <Stat label="Failure Rate" value={`${failRate}%`} className={Number(failRate) > 10 ? "text-destructive" : undefined} />+ <Stat label="Queue Backlog" value={queued} className={queued > 10 ? "text-amber-500" : undefined} />+ <Stat label="Stale Tasks" value={stale} className={stale > 0 ? "text-destructive" : undefined} />+ </div>+ </CardContent>+ </Card>+ );+}++function Stat({ label, value, className }: { label: string; value: string | number; className?: string }) {+ return (+ <div>+ <p className={`text-xl font-semibold ${className ?? ""}`}>{value}</p>+ <p className="text-xs text-muted-foreground">{label}</p>+ </div>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsxnew file mode 100644index 000000000..37424d122--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/home/_components/team-access.tsx@@ -0,0 +1,77 @@+"use client";++import { useRouter } from "next/navigation";+import { Card, CardHeader, CardTitle, CardAction, CardContent } from "@/components/ui/card";+import { Badge } from "@/components/ui/badge";+import { useWorkspace } from "@/contexts/workspace-context";+import { ArrowUpRight } from "lucide-react";+import type { WorkspaceOverview } from "@/lib/api";++interface TeamAccessProps {+ overview: WorkspaceOverview;+}++export function TeamAccess({ overview }: TeamAccessProps) {+ const router = useRouter();+ const { slug } = useWorkspace();+ const { members, pending_invites } = overview;++ return (+ <Card>+ <CardHeader>+ <CardAction>+ <button+ type="button"+ onClick={() => router.push(`/w/${slug}/settings`)}+ className="text-muted-foreground hover:text-foreground transition-colors cursor-pointer"+ >+ <ArrowUpRight className="size-4" />+ </button>+ </CardAction>+ <CardTitle>+ Team+ {pending_invites > 0 && (+ <span className="ml-2 text-xs text-muted-foreground font-normal">+ ({pending_invites} pending invite{pending_invites > 1 ? "s" : ""})+ </span>+ )}+ </CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <div className="divide-y divide-border/50">+ {members.map((m) => (+ <div key={m.id} className="flex items-center gap-3 px-4 py-2.5">+ {m.image ? (+ <img+ src={m.image}+ alt={m.name}+ className="size-7 rounded-full shrink-0"+ />+ ) : (+ <div className="flex size-7 shrink-0 items-center justify-center rounded-full bg-secondary text-xs font-medium">+ {(m.name || m.email).charAt(0).toUpperCase()}+ </div>+ )}+ <div className="flex-1 min-w-0">+ <span className="text-sm font-medium truncate block">+ {m.name || m.email}+ </span>+ {m.name && (+ <span className="text-xs text-muted-foreground truncate block">+ {m.email}+ </span>+ )}+ </div>+ <Badge+ variant={m.role === "owner" ? "default" : "secondary"}+ className="text-[10px] px-1.5 py-0 shrink-0"+ >+ {m.role}+ </Badge>+ </div>+ ))}+ </div>+ </CardContent>+ </Card>+ );+}diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex d753a3b5a..f9b174122 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -1,28 +1,43 @@"use client";-import { useEffect, useRef } from "react";+import { useEffect, useState } from "react";import { useRouter } from "next/navigation";import { useAgentContext } from "@/contexts/agent-context";import { useWorkspace } from "@/contexts/workspace-context";import { Button } from "@/components/ui/button";+import { Skeleton } from "@/components/ui/skeleton";import { Loader2 } from "lucide-react";+import { getWorkspaceOverview, type WorkspaceOverview } from "@/lib/api";+import { QuickStatsRow } from "./_components/quick-stats";+import { AgentOverview } from "./_components/agent-overview";+import { TaskHealth } from "./_components/task-health";+import { EmailSummary } from "./_components/email-summary";+import { RecentActivity } from "./_components/recent-activity";+import { CalendarOverview } from "./_components/calendar-overview";+import { RuntimeHealth } from "./_components/runtime-health";+import { TeamAccess } from "./_components/team-access";export default function HomePage() {const router = useRouter();- const { agents, runtimes, loading } = useAgentContext();- const { slug } = useWorkspace();- const redirectedRef = useRef(false);+ const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();+ const { slug, workspaceId } = useWorkspace();+ const [overview, setOverview] = useState<WorkspaceOverview | null>(null);+ const [overviewLoading, setOverviewLoading] = useState(false);- // Auto-redirect to first agent's detail pageuseEffect(() => {- if (loading || redirectedRef.current) return;- if (agents.length === 0) return;-- redirectedRef.current = true;- const sorted = [...agents].sort((a, b) => a.name.localeCompare(b.name));- const first = sorted[0];- router.replace(`/w/${slug}/agents/${first.id}`);- }, [agents, loading, router, slug]);+ if (loading || agents.length === 0) return;+ let cancelled = false;+ setOverviewLoading(true);+ getWorkspaceOverview(workspaceId)+ .then((data) => {+ if (!cancelled) setOverview(data);+ })+ .catch(() => {})+ .finally(() => {+ if (!cancelled) setOverviewLoading(false);+ });+ return () => { cancelled = true; };+ }, [loading, agents.length, workspaceId]);if (loading) {return (@@ -32,55 +47,95 @@ export default function HomePage() {);}- // Redirecting to first agent chat- if (agents.length > 0) {+ if (agents.length === 0) {+ const hasOnline = runtimes.some((r) => r.status === "online");return (<div className="flex flex-1 items-center justify-center">- <Loader2 className="size-5 animate-spin text-muted-foreground" />+ <div className="text-center animate-[fade-up_400ms_ease-out_both]">+ {runtimes.length === 0 ? (+ <>+ <p className="text-muted-foreground text-sm">Connect a machine to run your agents.</p>+ <Button+ size="sm"+ className="mt-4 glow-border"+ onClick={() => router.push(`/w/${slug}/runtimes?connect`)}+ >+ Connect Machine+ </Button>+ </>+ ) : !hasOnline ? (+ <>+ <p className="text-muted-foreground text-sm">Start the daemon on your machine to bring it online.</p>+ <Button+ size="sm"+ className="mt-4 glow-border"+ onClick={() => router.push(`/w/${slug}/runtimes`)}+ >+ Bring Machine Online+ </Button>+ </>+ ) : (+ <>+ <p className="text-muted-foreground text-sm">Your machine is ready. Create your first agent to get started.</p>+ <Button+ size="sm"+ className="mt-4 glow-border"+ onClick={() => router.push(`/w/${slug}/agents/new`)}+ >+ Create Agent+ </Button>+ </>+ )}+ </div></div>);}- // Empty state — no agents- const hasOnline = runtimes.some((r) => r.status === "online");+ if (overviewLoading || !overview) {+ return (+ <div className="flex-1 overflow-y-auto">+ <div className="p-4 lg:p-6 space-y-4">+ <div className="grid gap-3 grid-cols-2 sm:grid-cols-3 lg:grid-cols-6">+ {Array.from({ length: 6 }).map((_, i) => (+ <Skeleton key={i} className="h-20 rounded-xl" />+ ))}+ </div>+ <Skeleton className="h-48 rounded-xl" />+ <div className="grid gap-4 lg:grid-cols-2">+ <Skeleton className="h-44 rounded-xl" />+ <Skeleton className="h-44 rounded-xl" />+ </div>+ <Skeleton className="h-48 rounded-xl" />+ </div>+ </div>+ );+ }return (- <div className="flex flex-1 items-center justify-center">- <div className="text-center animate-[fade-up_400ms_ease-out_both]">- {runtimes.length === 0 ? (- <>- <p className="text-muted-foreground text-sm">Connect a machine to run your agents.</p>- <Button- size="sm"- className="mt-4 glow-border"- onClick={() => router.push(`/w/${slug}/runtimes?connect`)}- >- Connect Machine- </Button>- </>- ) : !hasOnline ? (- <>- <p className="text-muted-foreground text-sm">Start the daemon on your machine to bring it online.</p>- <Button- size="sm"- className="mt-4 glow-border"- onClick={() => router.push(`/w/${slug}/runtimes`)}- >- Bring Machine Online- </Button>- </>- ) : (- <>- <p className="text-muted-foreground text-sm">Your machine is ready. Create your first agent to get started.</p>- <Button- size="sm"- className="mt-4 glow-border"- onClick={() => router.push(`/w/${slug}/agents/new`)}- >- Create Agent- </Button>- </>- )}+ <div className="flex-1 overflow-y-auto">+ <div className="p-4 lg:p-6 space-y-4">+ <QuickStatsRow+ agents={agents}+ runtimes={runtimes}+ activeTaskCounts={activeTaskCounts}+ overview={overview}+ />+ <AgentOverview+ agents={agents}+ runtimes={runtimes}+ activeTaskCounts={activeTaskCounts}+ overview={overview}+ />+ <div className="grid gap-4 lg:grid-cols-2">+ <TaskHealth overview={overview} />+ <EmailSummary overview={overview} agents={agents} />+ </div>+ <RecentActivity overview={overview} agents={agents} />+ <div className="grid gap-4 lg:grid-cols-2">+ <CalendarOverview overview={overview} agents={agents} />+ <RuntimeHealth runtimes={runtimes} agents={agents} />+ </div>+ <TeamAccess overview={overview} /></div></div>);diff --git a/src/web/src/app/api/workspaces/[id]/overview/route.ts b/src/web/src/app/api/workspaces/[id]/overview/route.tsnew file mode 100644index 000000000..54f0a2245--- /dev/null+++ b/src/web/src/app/api/workspaces/[id]/overview/route.ts@@ -0,0 +1,94 @@+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, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = getDb((env as Env).DB);++ const todayStart = new Date();+ todayStart.setHours(0, 0, 0, 0);+ const todayISO = todayStart.toISOString();++ const weekEnd = new Date(todayStart);+ weekEnd.setDate(weekEnd.getDate() + 7);+ const weekEndISO = weekEnd.toISOString();++ const [+ emailStats,+ emailAccounts,+ taskStats,+ recentTasks,+ conversationCounts,+ members,+ invites,+ calendarEvents,+ ] = await Promise.all([+ queries.overview.getEmailStatsByWorkspace(db, ws.workspaceId),+ queries.overview.getEmailAccountsByWorkspace(db, ws.workspaceId),+ queries.overview.getTaskStatsByWorkspace(db, ws.workspaceId, todayISO),+ queries.overview.getRecentTerminalTasks(db, ws.workspaceId, 15),+ queries.overview.getConversationCountsByAgent(db, ws.workspaceId),+ queries.member.listMembers(db, ws.workspaceId),+ queries.workspaceInvite.listActiveInvites(db, ws.workspaceId),+ queries.calendarEvent.listCalendarEvents(db, ws.workspaceId, {+ from: todayISO,+ to: weekEndISO,+ }),+ ]);++ const conversationCountMap: Record<string, number> = {};+ for (const row of conversationCounts) {+ conversationCountMap[row.agentId] = Number(row.cnt);+ }++ return writeJSON({+ email_stats: emailStats,+ email_accounts: emailAccounts.map((a) => ({+ id: a.id,+ agent_id: a.agentId,+ email_address: a.emailAddress,+ status: a.status,+ error_message: a.errorMessage,+ last_synced_at: a.lastSyncedAt,+ })),+ task_stats: taskStats,+ recent_tasks: recentTasks.map((t) => ({+ id: t.id,+ agent_id: t.agentId,+ type: t.type,+ status: t.status,+ prompt: t.prompt,+ created_at: t.createdAt,+ completed_at: t.completedAt,+ error: t.error,+ })),+ conversation_counts: conversationCountMap,+ members: members.map((m) => ({+ id: m.id,+ user_id: m.userId,+ role: m.role,+ name: m.userName,+ email: m.userEmail,+ image: m.userImage,+ created_at: m.createdAt,+ })),+ pending_invites: invites.length,+ calendar_events: calendarEvents.map((e) => ({+ id: e.id,+ agent_id: e.agentId,+ title: e.title,+ description: e.description,+ scheduled_at: e.scheduledAt,+ repeat_interval: e.repeatInterval,+ repeat_stop_at: e.repeatStopAt,+ last_triggered_at: e.lastTriggeredAt,+ })),+ });+});diff --git a/src/web/src/components/app-sidebar.tsx b/src/web/src/components/app-sidebar.tsxindex ecab6efda..95860ab58 100644--- a/src/web/src/components/app-sidebar.tsx+++ b/src/web/src/components/app-sidebar.tsx@@ -95,9 +95,12 @@ export function AppSidebar({ onNavigate }: { onNavigate?: () => void } = {}) {return (<nav className="flex h-full w-14 flex-col items-center py-2 gap-0.5">- {/* Top — logo */}+ {/* Top — logo as Home link */}<div className="pb-2 border-b border-border/50 mb-1">- <div className="flex shrink-0 items-center justify-center size-10">+ <div+ className="flex shrink-0 items-center justify-center size-10 cursor-pointer [&>button]:pointer-events-none"+ onClick={() => { router.push(`${prefix}/home`); onNavigate?.(); }}+ ><Logo size="sm" iconOnly /></div></div>diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 31a8bad3d..1703da3a9 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -601,6 +601,63 @@ export const createInvite = (workspaceId: string) =>export const revokeInvite = (workspaceId: string, inviteId: string) =>apiFetch<void>(`/api/workspaces/${workspaceId}/invites/${inviteId}${wsQuery(workspaceId)}`, { method: "DELETE" });+// --- Workspace overview ---++export interface OverviewEmailAccount {+ id: string;+ agent_id: string;+ email_address: string;+ status: string;+ error_message: string;+ last_synced_at: string | null;+}++export interface OverviewRecentTask {+ id: string;+ agent_id: string;+ type: string;+ status: string;+ prompt: string;+ created_at: string;+ completed_at: string | null;+ error: string | null;+}++export interface OverviewCalendarEvent {+ id: string;+ agent_id: string;+ title: string;+ description: string | null;+ scheduled_at: string;+ repeat_interval: string | null;+ repeat_stop_at: string | null;+ last_triggered_at: string | null;+}++export interface OverviewMember {+ id: string;+ user_id: string;+ role: string;+ name: string;+ email: string;+ image: string | null;+ created_at: string;+}++export interface WorkspaceOverview {+ email_stats: { inbound: number; outbound: number; unread: number; rejected: number };+ email_accounts: OverviewEmailAccount[];+ task_stats: { completed: number; failed: number; cancelled: number; queued: number; stale: number };+ recent_tasks: OverviewRecentTask[];+ conversation_counts: Record<string, number>;+ members: OverviewMember[];+ pending_invites: number;+ calendar_events: OverviewCalendarEvent[];+}++export const getWorkspaceOverview = (workspaceId: string) =>+ apiFetch<WorkspaceOverview>(`/api/workspaces/${workspaceId}/overview${wsQuery(workspaceId)}`);+// --- Invite accept ---export interface InviteInfo {