Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add agent activity

Gus3f6d6f764155
diff --git a/DESIGN.md b/DESIGN.md
index 6e2f52b32..cdcf54977 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -1,7 +1,7 @@
## Design Context
### Users
-Power users and tasteful hackers who want always-on AI agents with a minimalist, collaborative approach. They value control over their infrastructure, appreciate good tooling, and have strong aesthetic sensibilities. They use Alook in focused work sessions — managing agents, reviewing task output, and iterating on instructions.
+Power users and tasteful hackers who want Your Personal Colleagues with a minimalist, collaborative approach. They value control over their infrastructure, appreciate good tooling, and have strong aesthetic sensibilities. They use Alook in focused work sessions — managing agents, reviewing task output, and iterating on instructions.
### Brand Personality
**Warm, precise, and utilitarian.** Alook feels like a well-crafted tool made by someone who cares — not cold and corporate, not flashy and consumer. It earns trust through restraint and clarity. Every element has a reason.
diff --git a/src/cli/package.json b/src/cli/package.json
index 38d1acaf4..d78a4ce70 100644
--- a/src/cli/package.json
+++ b/src/cli/package.json
@@ -1,7 +1,7 @@
{
"name": "@alook/cli",
"version": "0.0.21",
- "description": "Alook CLI — register and run always-on AI coding agents.",
+ "description": "Alook CLI — Enable Your Person Colleague",
"license": "Apache-2.0",
"homepage": "https://github.com/alookai/alook#readme",
"repository": {
@@ -54,4 +54,4 @@
"typescript": "^6.0.3",
"vitest": "^4.1.5"
}
-}
+}
\ No newline at end of file
diff --git a/src/shared/src/db/queries/message.ts b/src/shared/src/db/queries/message.ts
index ed773aa36..8acb40010 100644
--- a/src/shared/src/db/queries/message.ts
+++ b/src/shared/src/db/queries/message.ts
@@ -1,4 +1,4 @@
-import { eq, asc, desc, and, lt, or, count } from "drizzle-orm";
+import { eq, asc, desc, and, lt, or, count, sql } from "drizzle-orm";
import { message } from "../schema";
import type { Database } from "../index";
@@ -183,3 +183,55 @@ export async function countBufferedMessages(db: Database, conversationId: string
);
return rows[0]?.count ?? 0;
}
+
+export async function listMessagesAroundTask(
+ db: Database,
+ conversationId: string,
+ taskId: string,
+ limit = 15
+) {
+ const target = await db
+ .select({ createdAt: message.createdAt })
+ .from(message)
+ .where(
+ and(
+ eq(message.conversationId, conversationId),
+ eq(message.taskId, taskId),
+ eq(message.status, "active")
+ )
+ )
+ .orderBy(asc(message.createdAt))
+ .limit(1);
+
+ if (target.length === 0) return [];
+
+ const pivot = target[0]!.createdAt;
+
+ const before = await db
+ .select()
+ .from(message)
+ .where(
+ and(
+ eq(message.conversationId, conversationId),
+ eq(message.status, "active"),
+ lt(message.createdAt, pivot)
+ )
+ )
+ .orderBy(desc(message.createdAt))
+ .limit(limit);
+
+ const atAndAfter = await db
+ .select()
+ .from(message)
+ .where(
+ and(
+ eq(message.conversationId, conversationId),
+ eq(message.status, "active"),
+ sql`${message.createdAt} >= ${pivot}`
+ )
+ )
+ .orderBy(asc(message.createdAt))
+ .limit(limit + 1);
+
+ return [...before.reverse(), ...atAndAfter];
+}
diff --git a/src/shared/src/db/queries/task.ts b/src/shared/src/db/queries/task.ts
index c5a249a94..ffdaec8e1 100644
--- a/src/shared/src/db/queries/task.ts
+++ b/src/shared/src/db/queries/task.ts
@@ -1,4 +1,4 @@
-import { eq, and, desc, asc, inArray, notInArray, ne, count, lt, sql } from "drizzle-orm";
+import { eq, and, desc, asc, inArray, notInArray, ne, count, lt, or, sql } from "drizzle-orm";
import { agentTaskQueue, taskMessage } from "../schema";
import type { Database } from "../index";
import { ClaimedTaskRowSchema } from "../../schemas";
@@ -354,6 +354,24 @@ export async function deleteTasksByConversation(
.returning({ id: agentTaskQueue.id });
}
+export async function cancelActiveTasksByConversation(
+ db: Database,
+ conversationId: string,
+ workspaceId: string
+) {
+ return db
+ .update(agentTaskQueue)
+ .set({ status: "cancelled", completedAt: new Date().toISOString() })
+ .where(
+ and(
+ eq(agentTaskQueue.conversationId, conversationId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ inArray(agentTaskQueue.status, ["queued", "dispatched", "running"])
+ )
+ )
+ .returning({ id: agentTaskQueue.id });
+}
+
export async function countRunningTasks(db: Database, agentId: string, workspaceId: string, excludeTaskId?: string) {
const conditions = [
eq(agentTaskQueue.agentId, agentId),
@@ -527,3 +545,67 @@ export async function failStaleRunningTasks(db: Database, workspaceId: string, s
.returning({ agentId: agentTaskQueue.agentId, workspaceId: agentTaskQueue.workspaceId, conversationId: agentTaskQueue.conversationId });
return rows;
}
+
+const DEFAULT_HISTORY_LIMIT = 30;
+
+export async function listTaskHistory(
+ db: Database,
+ agentId: string,
+ workspaceId: string,
+ opts?: {
+ limit?: number;
+ before?: string;
+ beforeId?: string;
+ status?: string[];
+ type?: string[];
+ }
+) {
+ const limit = opts?.limit ?? DEFAULT_HISTORY_LIMIT;
+ const conditions = [
+ eq(agentTaskQueue.agentId, agentId),
+ eq(agentTaskQueue.workspaceId, workspaceId),
+ ne(agentTaskQueue.type, TASK_TYPES.KILL_TASK),
+ ];
+
+ if (opts?.status && opts.status.length > 0) {
+ conditions.push(inArray(agentTaskQueue.status, opts.status));
+ }
+
+ if (opts?.type && opts.type.length > 0) {
+ conditions.push(inArray(agentTaskQueue.type, opts.type));
+ }
+
+ if (opts?.before) {
+ const cursorCondition = opts.beforeId
+ ? or(
+ lt(agentTaskQueue.createdAt, opts.before),
+ and(eq(agentTaskQueue.createdAt, opts.before), lt(agentTaskQueue.id, opts.beforeId))
+ )
+ : lt(agentTaskQueue.createdAt, opts.before);
+ conditions.push(cursorCondition!);
+ }
+
+ const rows = await db
+ .select({
+ id: agentTaskQueue.id,
+ agentId: agentTaskQueue.agentId,
+ conversationId: agentTaskQueue.conversationId,
+ workspaceId: agentTaskQueue.workspaceId,
+ prompt: agentTaskQueue.prompt,
+ type: agentTaskQueue.type,
+ status: agentTaskQueue.status,
+ createdAt: agentTaskQueue.createdAt,
+ startedAt: agentTaskQueue.startedAt,
+ completedAt: agentTaskQueue.completedAt,
+ error: agentTaskQueue.error,
+ })
+ .from(agentTaskQueue)
+ .where(and(...conditions))
+ .orderBy(desc(agentTaskQueue.createdAt), desc(agentTaskQueue.id))
+ .limit(limit + 1);
+
+ const hasMore = rows.length > limit;
+ const tasks = hasMore ? rows.slice(0, limit) : rows;
+
+ return { tasks: tasks.reverse(), hasMore };
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 4a90bc9f2..2d9d1d994 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -323,6 +323,8 @@ export const agentTaskQueue = sqliteTable(
index("idx_task_queue_workspace_active")
.on(t.workspaceId, t.status, t.agentId)
.where(sql`status IN ('queued', 'dispatched', 'running')`),
+ index("idx_task_queue_agent_history")
+ .on(t.agentId, t.workspaceId, t.createdAt),
foreignKey({
columns: [t.agentId, t.workspaceId],
foreignColumns: [agent.id, agent.workspaceId],
diff --git a/src/web/migrations/0012_task_queue_agent_history_index.sql b/src/web/migrations/0012_task_queue_agent_history_index.sql
new file mode 100644
index 000000000..7f06050ad
--- /dev/null
+++ b/src/web/migrations/0012_task_queue_agent_history_index.sql
@@ -0,0 +1 @@
+CREATE INDEX idx_task_queue_agent_history ON agent_task_queue (agent_id, workspace_id, created_at);
diff --git a/src/web/public/manifest.json b/src/web/public/manifest.json
index 7a9e22e21..550ffaef4 100644
--- a/src/web/public/manifest.json
+++ b/src/web/public/manifest.json
@@ -1,5 +1,5 @@
{
- "name": "Alook — Always-on AI Agents",
+ "name": "Alook — Personal Colleagues",
"short_name": "Alook",
"description": "Your AI agents, always on. Give them an email, let them work for you around the clock.",
"start_url": "/",
@@ -13,4 +13,4 @@
"type": "image/svg+xml"
}
]
-}
+}
\ No newline at end of file
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
new file mode 100644
index 000000000..89f7d7316
--- /dev/null
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/activity/page.tsx
@@ -0,0 +1,354 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { useParams, useRouter, useSearchParams } from "next/navigation";
+import Link from "next/link";
+import { useWorkspace } from "@/contexts/workspace-context";
+import { listAgentActivity, type ActivityTask } from "@/lib/api";
+import { Skeleton } from "@/components/ui/skeleton";
+import {
+ Select,
+ SelectTrigger,
+ SelectValue,
+ SelectPopup,
+ SelectItem,
+} from "@/components/ui/select";
+import {
+ MessageSquare,
+ Mail,
+ CalendarDays,
+ CircleDot,
+ History,
+} from "lucide-react";
+
+const ACTIVITY_LIMIT = 30;
+
+const STATUS_OPTIONS = [
+ { label: "All", value: "" },
+ { label: "Queued", value: "queued,dispatched" },
+ { label: "Running", value: "running" },
+ { label: "Completed", value: "completed" },
+ { label: "Failed", value: "failed" },
+ { label: "Cancelled", value: "cancelled,superseded" },
+];
+
+const TYPE_OPTIONS = [
+ { label: "All", value: "" },
+ { label: "Message", value: "user_dm_message" },
+ { label: "Email", value: "email_notification" },
+ { label: "Calendar", value: "calendar_event" },
+];
+
+function relativeTime(dateStr: string): string {
+ const date = new Date(dateStr);
+ const now = new Date();
+ const diffMs = now.getTime() - date.getTime();
+ const diffMin = Math.floor(diffMs / 60000);
+ if (diffMin < 1) return "just now";
+ if (diffMin < 60) return `${diffMin}m ago`;
+ const diffHrs = Math.floor(diffMin / 60);
+ if (diffHrs < 24) return `${diffHrs}h ago`;
+ const diffDays = Math.floor(diffHrs / 24);
+ if (diffDays < 7) return `${diffDays}d ago`;
+ return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
+}
+
+function formatDuration(startedAt: string | null, completedAt: string | null): string | null {
+ if (!startedAt || !completedAt) return null;
+ const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000));
+ if (totalSeconds >= 3600) {
+ const h = Math.floor(totalSeconds / 3600);
+ const m = Math.floor((totalSeconds % 3600) / 60);
+ return `${h}h ${m}m`;
+ }
+ if (totalSeconds >= 60) {
+ const m = Math.floor(totalSeconds / 60);
+ const s = totalSeconds % 60;
+ return `${m}m ${s}s`;
+ }
+ return `${totalSeconds}s`;
+}
+
+const TYPE_ICONS: Record<string, typeof MessageSquare> = {
+ user_dm_message: MessageSquare,
+ email_notification: Mail,
+ calendar_event: CalendarDays,
+};
+
+const STATUS_LABELS: Record<string, string> = {
+ queued: "Queued",
+ dispatched: "Queued",
+ running: "Running",
+ completed: "Completed",
+ failed: "Failed",
+ cancelled: "Cancelled",
+ superseded: "Cancelled",
+};
+
+const TERMINAL_STATUSES = new Set(["completed", "failed", "cancelled", "superseded"]);
+
+function StatusDot({ status }: { status: string }) {
+ const colorClass =
+ status === "completed"
+ ? "bg-[oklch(0.72_0.19_145)]"
+ : status === "failed"
+ ? "bg-destructive"
+ : status === "running"
+ ? "bg-primary animate-pulse"
+ : "bg-muted-foreground/40";
+
+ return <span className={`size-1.5 rounded-full shrink-0 ${colorClass}`} />;
+}
+
+function ActivityRow({ task, slug, agentId }: { task: ActivityTask; slug: string; agentId: string }) {
+ const Icon = TYPE_ICONS[task.type] ?? CircleDot;
+ const duration = TERMINAL_STATUSES.has(task.status)
+ ? formatDuration(task.started_at, task.completed_at)
+ : null;
+
+ return (
+ <Link
+ href={`/w/${slug}/agents/${agentId}?task=${task.id}&conv=${task.conversation_id}`}
+ className="block px-4 py-3 border-b border-border/30 hover:bg-accent/30 transition-colors duration-150 cursor-pointer"
+ >
+ <div className="flex items-center gap-2 min-w-0">
+ <Icon className="shrink-0 size-3.5 text-muted-foreground" />
+ <span className="text-sm text-foreground truncate flex-1 min-w-0">
+ {task.prompt}
+ </span>
+ <span
+ className="text-xs text-muted-foreground shrink-0 ml-2"
+ title={new Date(task.created_at).toLocaleString()}
+ >
+ {relativeTime(task.created_at)}
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">
+ <StatusDot status={task.status} />
+ <span className="text-xs text-muted-foreground">
+ {STATUS_LABELS[task.status] ?? task.status}
+ </span>
+ {duration && (
+ <>
+ <span className="text-muted-foreground/40">·</span>
+ <span className="text-xs text-muted-foreground">{duration}</span>
+ </>
+ )}
+ {task.status === "failed" && task.error && (
+ <>
+ <span className="text-muted-foreground/40">—</span>
+ <span className="text-xs text-destructive truncate max-w-[200px]">
+ {task.error}
+ </span>
+ </>
+ )}
+ </div>
+ </Link>
+ );
+}
+
+function SkeletonRow({ promptWidth }: { promptWidth: string }) {
+ return (
+ <div className="px-4 py-3 border-b border-border/30">
+ <div className="flex items-center gap-2">
+ <Skeleton className="h-3.5 w-4 rounded shrink-0" />
+ <Skeleton className={`h-3.5 rounded`} style={{ width: promptWidth }} />
+ <Skeleton className="h-2.5 w-10 rounded shrink-0 ml-auto" />
+ </div>
+ <div className="flex items-center gap-1.5 mt-1 ml-[calc(0.875rem+0.5rem)]">
+ <Skeleton className="h-2.5 w-20 rounded-full" />
+ <Skeleton className="h-2.5 w-8 rounded" />
+ </div>
+ </div>
+ );
+}
+
+export default function AgentActivityPage() {
+ const params = useParams();
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const agentId = params.id as string;
+ const { slug, workspaceId } = useWorkspace();
+
+ const [tasks, setTasks] = useState<ActivityTask[]>([]);
+ 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 initialScrollDone = useRef(false);
+
+ const statusFilter = searchParams.get("status") ?? "";
+ const typeFilter = searchParams.get("type") ?? "";
+
+ const loadInitial = useCallback(async () => {
+ setLoading(true);
+ try {
+ const result = await listAgentActivity(agentId, workspaceId, {
+ limit: ACTIVITY_LIMIT,
+ status: statusFilter || undefined,
+ type: typeFilter || undefined,
+ });
+ setTasks(result.tasks);
+ setHasMore(result.has_more);
+ initialScrollDone.current = false;
+ } catch {
+ // error handled silently
+ } finally {
+ setLoading(false);
+ }
+ }, [agentId, workspaceId, statusFilter, typeFilter]);
+
+ useEffect(() => {
+ loadInitial();
+ }, [loadInitial]);
+
+ useEffect(() => {
+ if (!loading && !initialScrollDone.current && scrollRef.current) {
+ scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
+ initialScrollDone.current = true;
+ }
+ }, [loading, tasks]);
+
+ const loadOlderTasks = useCallback(async () => {
+ if (isFetchingRef.current || !hasMore || tasks.length === 0) return;
+ isFetchingRef.current = true;
+ setLoadingMore(true);
+
+ const el = scrollRef.current;
+ const prevScrollHeight = el?.scrollHeight ?? 0;
+
+ try {
+ const oldest = tasks[0];
+ const result = await listAgentActivity(agentId, workspaceId, {
+ limit: ACTIVITY_LIMIT,
+ before: oldest.created_at,
+ beforeId: oldest.id,
+ status: statusFilter || undefined,
+ type: typeFilter || undefined,
+ });
+
+ if (result.tasks.length === 0) {
+ setHasMore(false);
+ return;
+ }
+
+ setHasMore(result.has_more);
+ setTasks((prev) => {
+ const existingIds = new Set(prev.map((t) => t.id));
+ const unique = result.tasks.filter((t) => !existingIds.has(t.id));
+ return [...unique, ...prev];
+ });
+
+ requestAnimationFrame(() => {
+ if (el) {
+ const newScrollHeight = el.scrollHeight;
+ el.scrollTop = newScrollHeight - prevScrollHeight;
+ }
+ });
+ } finally {
+ isFetchingRef.current = false;
+ setLoadingMore(false);
+ }
+ }, [agentId, workspaceId, tasks, hasMore, statusFilter, typeFilter]);
+
+ const handleScroll = useCallback(() => {
+ const el = scrollRef.current;
+ if (!el) return;
+ if (!loadingMore && hasMore && el.scrollTop < 80) {
+ loadOlderTasks();
+ }
+ }, [loadOlderTasks, loadingMore, hasMore]);
+
+ const updateFilter = useCallback(
+ (key: string, value: string) => {
+ const newParams = new URLSearchParams(searchParams.toString());
+ if (value) {
+ newParams.set(key, value);
+ } else {
+ newParams.delete(key);
+ }
+ const pathname = `/w/${slug}/agents/${agentId}/activity`;
+ const qs = newParams.toString();
+ router.replace(qs ? `${pathname}?${qs}` : pathname, { scroll: false });
+ },
+ [router, slug, agentId, searchParams]
+ );
+
+ return (
+ <>
+ {/* Filter bar */}
+ <div className="sticky top-0 z-10 flex items-center gap-2 px-4 py-2.5">
+ <Select value={statusFilter} onValueChange={(v) => updateFilter("status", v ?? "")}>
+ <SelectTrigger className="w-[140px] border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
+ <SelectValue placeholder="Status: All" />
+ </SelectTrigger>
+ <SelectPopup>
+ {STATUS_OPTIONS.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label === "All" ? "Status: All" : opt.label}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+
+ <Select value={typeFilter} onValueChange={(v) => updateFilter("type", v ?? "")}>
+ <SelectTrigger className="w-[130px] border-none bg-transparent shadow-none text-xs text-muted-foreground hover:bg-muted hover:text-foreground transition-colors">
+ <SelectValue placeholder="Type: All" />
+ </SelectTrigger>
+ <SelectPopup>
+ {TYPE_OPTIONS.map((opt) => (
+ <SelectItem key={opt.value} value={opt.value}>
+ {opt.label === "All" ? "Type: All" : opt.label}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ </div>
+
+ {/* Scroll container */}
+ <div
+ ref={scrollRef}
+ className="flex-1 overflow-y-auto thin-scrollbar"
+ onScroll={handleScroll}
+ >
+ {loading ? (
+ <div className="flex flex-col">
+ <SkeletonRow promptWidth="40%" />
+ <SkeletonRow promptWidth="55%" />
+ <SkeletonRow promptWidth="48%" />
+ </div>
+ ) : tasks.length === 0 ? (
+ <div className="flex flex-col items-center justify-center h-full animate-[fade-up_400ms_ease-out_both]">
+ <History className="size-8 text-muted-foreground mb-3" />
+ <p className="text-sm text-muted-foreground">No activity yet</p>
+ {(statusFilter || typeFilter) && (
+ <p className="text-xs text-muted-foreground/60 mt-1">
+ Try changing your filters
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="flex flex-col animate-[fade-up_400ms_ease-out_both]">
+ {loadingMore && (
+ <>
+ <SkeletonRow promptWidth="48%" />
+ <SkeletonRow promptWidth="40%" />
+ </>
+ )}
+ {tasks.map((task) => (
+ <ActivityRow
+ key={task.id}
+ task={task}
+ slug={slug}
+ agentId={agentId}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
index 12502a445..d87bc9f43 100644
--- a/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
+++ b/src/web/src/app/(app)/w/[slug]/agents/[id]/layout.tsx
@@ -1,7 +1,7 @@
"use client";
import { useState, useEffect, type ReactNode } from "react";
-import { useParams, useRouter, usePathname } from "next/navigation";
+import { useParams, useRouter, usePathname, useSearchParams } from "next/navigation";
import Link from "next/link";
import { useAgentContext } from "@/contexts/agent-context";
import { useWorkspace } from "@/contexts/workspace-context";
@@ -10,7 +10,7 @@ import { ConfirmDialog } from "@/components/ui/confirm-dialog";
import { AgentEditForm } from "@/components/agent-edit-form";
import { Skeleton } from "@/components/ui/skeleton";
import { AgentStatusBadge } from "@/components/agent-status-badge";
-import { CalendarDays, Mail, MessageSquare, MoreHorizontal, Pencil, Trash2, X } from "lucide-react";
+import { CalendarDays, History, Mail, MessageSquare, MoreHorizontal, Pencil, Trash2, X } from "lucide-react";
import { MobileSidebarLogo } from "@/components/mobile-sidebar-logo";
import {
DropdownMenu,
@@ -26,8 +26,15 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
const router = useRouter();
const pathname = usePathname();
const { slug } = useWorkspace();
+ const searchParams = useSearchParams();
const agentId = params.id as string;
- const isOnEmail = pathname.includes(`/agents/${agentId}/email`);
+ const isActivityView = !!searchParams.get("conv");
+ const currentTab = pathname.includes("/activity") || isActivityView
+ ? "activity"
+ : pathname.includes("/email")
+ ? "email"
+ : "chat";
+ const tabLabels: Record<string, string> = { email: "Email", activity: "Activity" };
const { agents, runtimes, handleDeleteAgent, handleUpdateAgent } = useAgentContext();
const agent = agents.find((a) => a.id === agentId);
@@ -75,7 +82,7 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
<Skeleton className="h-3.5 w-24" />
)}
<span className="text-xs text-muted-foreground">
- / {editing ? "Settings" : isOnEmail ? "Email" : "Chat"}
+ / {editing ? "Settings" : tabLabels[currentTab] ?? "Chat"}
</span>
</div>
{agent ? (
@@ -94,47 +101,75 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
<>
{/* Desktop: inline buttons */}
<div className="hidden sm:flex items-center gap-0.5">
- {isOnEmail ? (
- <Link
- href={`/w/${slug}/agents/${agentId}`}
- className="inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 gap-1 px-2 hover:bg-muted hover:text-foreground transition-all"
- >
- <MessageSquare className="size-3" />
- Chat
- </Link>
- ) : (
- <Link
- href={`/w/${slug}/agents/${agentId}/email`}
- className="inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 gap-1 px-2 hover:bg-muted hover:text-foreground transition-all"
- >
- <Mail className="size-3" />
- Email
- </Link>
- )}
+ <Link
+ href={`/w/${slug}/agents/${agentId}`}
+ className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
+ currentTab === "chat"
+ ? "text-foreground bg-muted"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ }`}
+ >
+ <MessageSquare className="size-3 shrink-0" />
+ <span className={`overflow-hidden transition-all duration-500 ease-out ${
+ currentTab === "chat"
+ ? "max-w-16 opacity-100 ml-1"
+ : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
+ }`}>Chat</span>
+ </Link>
+ <Link
+ href={`/w/${slug}/agents/${agentId}/email`}
+ className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
+ currentTab === "email"
+ ? "text-foreground bg-muted"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ }`}
+ >
+ <Mail className="size-3 shrink-0" />
+ <span className={`overflow-hidden transition-all duration-500 ease-out ${
+ currentTab === "email"
+ ? "max-w-16 opacity-100 ml-1"
+ : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
+ }`}>Email</span>
+ </Link>
+ <Link
+ href={`/w/${slug}/agents/${agentId}/activity`}
+ className={`group inline-flex items-center rounded-lg text-xs h-7 px-2 transition-all ${
+ currentTab === "activity"
+ ? "text-foreground bg-muted"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ }`}
+ >
+ <History className="size-3 shrink-0" />
+ <span className={`overflow-hidden transition-all duration-500 ease-out ${
+ currentTab === "activity"
+ ? "max-w-16 opacity-100 ml-1"
+ : "max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300"
+ }`}>Activity</span>
+ </Link>
<Link
href={`/w/${slug}/calendar?agents=${agentId}`}
- className="inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 gap-1 px-2 hover:bg-muted hover:text-foreground transition-all"
+ className="group inline-flex items-center rounded-lg text-xs text-muted-foreground h-7 px-2 hover:bg-muted hover:text-foreground transition-all"
>
- <CalendarDays className="size-3" />
- Calendar
+ <CalendarDays className="size-3 shrink-0" />
+ <span className="max-w-0 opacity-0 group-hover:max-w-20 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Calendar</span>
</Link>
<Button
variant="ghost"
size="sm"
- className="text-xs text-muted-foreground h-7 gap-1 px-2"
+ className="group text-xs text-muted-foreground h-7 px-2"
onClick={() => setEditing(true)}
>
- <Pencil className="size-3" />
- Edit
+ <Pencil className="size-3 shrink-0" />
+ <span className="max-w-0 opacity-0 group-hover:max-w-12 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Edit</span>
</Button>
<Button
variant="ghost"
size="sm"
- className="text-xs text-muted-foreground h-7 px-2 hover:text-destructive"
+ className="group text-xs text-muted-foreground h-7 px-2 hover:text-destructive"
onClick={() => setAgentConfirmOpen(true)}
>
- <Trash2 className="size-3" />
- Remove
+ <Trash2 className="size-3 shrink-0" />
+ <span className="max-w-0 opacity-0 group-hover:max-w-16 group-hover:opacity-100 group-hover:ml-1 group-hover:delay-300 overflow-hidden transition-all duration-500 ease-out">Remove</span>
</Button>
</div>
@@ -147,21 +182,27 @@ export default function AgentDetailLayout({ children }: { children: ReactNode })
<MoreHorizontal className="size-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={6}>
- <DropdownMenuItem
- onClick={() =>
- router.push(
- isOnEmail
- ? `/w/${slug}/agents/${agentId}`
- : `/w/${slug}/agents/${agentId}/email`
- )
- }
- >
- {isOnEmail ? (
- <><MessageSquare className="size-3.5" /> Chat</>
- ) : (
- <><Mail className="size-3.5" /> Email</>
- )}
- </DropdownMenuItem>
+ {currentTab !== "chat" && (
+ <DropdownMenuItem
+ onClick={() => router.push(`/w/${slug}/agents/${agentId}`)}
+ >
+ <MessageSquare className="size-3.5" /> Chat
+ </DropdownMenuItem>
+ )}
+ {currentTab !== "email" && (
+ <DropdownMenuItem
+ onClick={() => router.push(`/w/${slug}/agents/${agentId}/email`)}
+ >
+ <Mail className="size-3.5" /> Email
+ </DropdownMenuItem>
+ )}
+ {currentTab !== "activity" && (
+ <DropdownMenuItem
+ onClick={() => router.push(`/w/${slug}/agents/${agentId}/activity`)}
+ >
+ <History className="size-3.5" /> Activity
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem
onClick={() =>
router.push(`/w/${slug}/calendar?agents=${agentId}`)
diff --git a/src/web/src/app/(auth)/layout.tsx b/src/web/src/app/(auth)/layout.tsx
index b016873a4..d0bc16488 100644
--- a/src/web/src/app/(auth)/layout.tsx
+++ b/src/web/src/app/(auth)/layout.tsx
@@ -4,7 +4,7 @@ import { getSession } from "@/lib/session";
export const metadata: Metadata = {
title: "Sign In",
- description: "Sign in to manage your always-on AI agents on Alook.",
+ description: "Sign in to manage your Your Personal Colleagues on Alook.",
openGraph: {
images: [{ url: "/api/og?title=Sign In", width: 1200, height: 630 }],
},
diff --git a/src/web/src/app/api/agents/[id]/activity/route.test.ts b/src/web/src/app/api/agents/[id]/activity/route.test.ts
new file mode 100644
index 000000000..a02d3ef6e
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/activity/route.test.ts
@@ -0,0 +1,228 @@
+import { NextRequest } from "next/server";
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+const mockGetAgent = vi.fn();
+const mockListTaskHistory = vi.fn();
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", async () => {
+ const actual = await vi.importActual("@alook/shared");
+ return {
+ ...actual,
+ createDb: vi.fn(() => ({})),
+ queries: {
+ agent: {
+ getAgent: (...args: unknown[]) => mockGetAgent(...args),
+ },
+ task: {
+ listTaskHistory: (...args: unknown[]) => mockListTaskHistory(...args),
+ },
+ },
+ };
+});
+
+vi.mock("@/lib/middleware/auth", () => ({
+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;
+ return handler(req, { userId: "u1", email: "[email protected]", params });
+ }),
+}));
+
+vi.mock("@/lib/middleware/workspace", () => ({
+ withWorkspaceMember: vi.fn(async () => ({ workspaceId: "w1" })),
+}));
+
+vi.mock("@/lib/api/responses", () => ({
+ taskToActivityResponse: vi.fn((t: any) => ({
+ id: t.id,
+ conversation_id: t.conversationId,
+ type: t.type,
+ status: t.status,
+ prompt: t.prompt?.slice(0, 120),
+ created_at: t.createdAt,
+ started_at: t.startedAt,
+ completed_at: t.completedAt,
+ error: t.error || null,
+ })),
+}));
+
+import { GET } from "./route";
+
+beforeEach(() => vi.clearAllMocks());
+
+const makeTask = (overrides: Record<string, unknown> = {}) => ({
+ id: "t1",
+ agentId: "a1",
+ conversationId: "c1",
+ workspaceId: "w1",
+ prompt: "Do something",
+ type: "user_dm_message",
+ status: "completed",
+ createdAt: "2025-01-01T00:00:00.000Z",
+ startedAt: "2025-01-01T00:00:01.000Z",
+ completedAt: "2025-01-01T00:00:10.000Z",
+ error: null,
+ ...overrides,
+});
+
+describe("GET /api/agents/[id]/activity", () => {
+ it("returns 404 for non-existent agent", async () => {
+ mockGetAgent.mockResolvedValue(null);
+
+ const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await GET(req, ctx);
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toBe("agent not found");
+ });
+
+ it("returns tasks with has_more", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({
+ tasks: [makeTask()],
+ hasMore: true,
+ });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await GET(req, ctx);
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.tasks).toHaveLength(1);
+ expect(body.has_more).toBe(true);
+ expect(body.tasks[0].id).toBe("t1");
+ });
+
+ it("parses comma-separated status params", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/agents/a1/activity?workspace_id=w1&status=queued,dispatched"
+ );
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ await GET(req, ctx);
+
+ expect(mockListTaskHistory).toHaveBeenCalledWith(
+ expect.anything(),
+ "a1",
+ "w1",
+ expect.objectContaining({ status: ["queued", "dispatched"] })
+ );
+ });
+
+ it("parses comma-separated type params", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/agents/a1/activity?workspace_id=w1&type=user_dm_message,email_notification"
+ );
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ await GET(req, ctx);
+
+ expect(mockListTaskHistory).toHaveBeenCalledWith(
+ expect.anything(),
+ "a1",
+ "w1",
+ expect.objectContaining({ type: ["user_dm_message", "email_notification"] })
+ );
+ });
+
+ it("clamps limit to 1-100 range", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/agents/a1/activity?workspace_id=w1&limit=999"
+ );
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ await GET(req, ctx);
+
+ expect(mockListTaskHistory).toHaveBeenCalledWith(
+ expect.anything(),
+ "a1",
+ "w1",
+ expect.objectContaining({ limit: 100 })
+ );
+ });
+
+ it("clamps limit minimum to 1", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/agents/a1/activity?workspace_id=w1&limit=0"
+ );
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ await GET(req, ctx);
+
+ expect(mockListTaskHistory).toHaveBeenCalledWith(
+ expect.anything(),
+ "a1",
+ "w1",
+ expect.objectContaining({ limit: 1 })
+ );
+ });
+
+ it("passes before and before_id cursor params", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({ tasks: [], hasMore: false });
+
+ const req = new NextRequest(
+ "http://localhost/api/agents/a1/activity?workspace_id=w1&before=2025-01-01T00:00:00.000Z&before_id=t5"
+ );
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ await GET(req, ctx);
+
+ expect(mockListTaskHistory).toHaveBeenCalledWith(
+ expect.anything(),
+ "a1",
+ "w1",
+ expect.objectContaining({
+ before: "2025-01-01T00:00:00.000Z",
+ beforeId: "t5",
+ })
+ );
+ });
+
+ it("returns has_more false when no more tasks", async () => {
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({
+ tasks: [makeTask()],
+ hasMore: false,
+ });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await GET(req, ctx);
+ const body = await res.json();
+
+ expect(body.has_more).toBe(false);
+ });
+
+ it("taskToActivityResponse truncates prompt and omits result/context", async () => {
+ const longPrompt = "x".repeat(200);
+ mockGetAgent.mockResolvedValue({ id: "a1" });
+ mockListTaskHistory.mockResolvedValue({
+ tasks: [makeTask({ prompt: longPrompt })],
+ hasMore: false,
+ });
+
+ const req = new NextRequest("http://localhost/api/agents/a1/activity?workspace_id=w1");
+ const ctx = { params: Promise.resolve({ id: "a1" }) };
+ const res = await GET(req, ctx);
+ const body = await res.json();
+
+ expect(body.tasks[0].prompt.length).toBeLessThanOrEqual(120);
+ expect(body.tasks[0]).not.toHaveProperty("result");
+ expect(body.tasks[0]).not.toHaveProperty("context");
+ });
+});
diff --git a/src/web/src/app/api/agents/[id]/activity/route.ts b/src/web/src/app/api/agents/[id]/activity/route.ts
new file mode 100644
index 000000000..d4412f38f
--- /dev/null
+++ b/src/web/src/app/api/agents/[id]/activity/route.ts
@@ -0,0 +1,46 @@
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { createDb, queries } from "@alook/shared";
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError } from "@/lib/middleware/helpers";
+import { taskToActivityResponse } from "@/lib/api/responses";
+
+export const GET = withAuth(async (req, ctx) => {
+ const ws = await withWorkspaceMember(req, ctx);
+ if (ws instanceof Response) return ws;
+
+ const { env } = getCloudflareContext();
+ const db = createDb((env as Env).DB);
+
+ const id = ctx.params?.id;
+ if (!id) return writeError("agent id is required", 400);
+
+ const agent = await queries.agent.getAgent(db, id, ws.workspaceId, ctx.userId);
+ if (!agent) return writeError("agent not found", 404);
+
+ const url = new URL(req.url);
+ const limitParam = url.searchParams.get("limit");
+ const before = url.searchParams.get("before") || undefined;
+ const beforeId = url.searchParams.get("before_id") || undefined;
+ const statusParam = url.searchParams.get("status");
+ const typeParam = url.searchParams.get("type");
+
+ const parsedLimit = limitParam ? parseInt(limitParam, 10) : NaN;
+ const limit = Number.isNaN(parsedLimit) ? 30 : Math.min(Math.max(parsedLimit, 1), 100);
+
+ const status = statusParam ? statusParam.split(",").filter(Boolean) : undefined;
+ const type = typeParam ? typeParam.split(",").filter(Boolean) : undefined;
+
+ const result = await queries.task.listTaskHistory(db, id, ws.workspaceId, {
+ limit,
+ before,
+ beforeId,
+ status,
+ type,
+ });
+
+ return writeJSON({
+ tasks: result.tasks.map(taskToActivityResponse),
+ has_more: result.hasMore,
+ });
+});
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.ts b/src/web/src/app/api/conversations/[id]/messages/route.ts
index eecd6c734..7f8fb9314 100644
--- a/src/web/src/app/api/conversations/[id]/messages/route.ts
+++ b/src/web/src/app/api/conversations/[id]/messages/route.ts
@@ -45,6 +45,13 @@ export const GET = withAuth(async (req, ctx) => {
}
const url = new URL(req.url);
+ const aroundTask = url.searchParams.get("around_task");
+
+ if (aroundTask) {
+ const messages = await queries.message.listMessagesAroundTask(db, id, aroundTask);
+ return writeJSON(messages.map(messageToResponse));
+ }
+
const limitParam = url.searchParams.get("limit");
const before = url.searchParams.get("before") || undefined;
const beforeId = url.searchParams.get("before_id") || undefined;
diff --git a/src/web/src/app/api/email/notify/route.ts b/src/web/src/app/api/email/notify/route.ts
index ccea73a19..bd4b617eb 100644
--- a/src/web/src/app/api/email/notify/route.ts
+++ b/src/web/src/app/api/email/notify/route.ts
@@ -38,10 +38,16 @@ export async function POST(req: NextRequest) {
title: `Email: ${body.subject}`.slice(0, 50),
type: TASK_TYPES.EMAIL_NOTIFICATION,
})
+ const prompt = `New email from ${body.from}: ${body.subject}`;
+ await queries.message.createMessage(db, {
+ conversationId: conv.id,
+ role: "user",
+ content: prompt,
+ })
const threadId = extractThreadId(body.references, body.inReplyTo, body.messageId);
const contextKey = buildContextKey(TASK_TYPES.EMAIL_NOTIFICATION, { threadId });
const taskService = new TaskService(db)
- await taskService.enqueueTask(agent.id, conv.id, agent.workspaceId, `New email from ${body.from}: ${body.subject}`, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey })
+ await taskService.enqueueTask(agent.id, conv.id, agent.workspaceId, prompt, TASK_TYPES.EMAIL_NOTIFICATION, { contextKey })
}
// Notify UI for all emails (whitelisted or not)
diff --git a/src/web/src/app/api/og/route.tsx b/src/web/src/app/api/og/route.tsx
index bdd87544c..4be8a4586 100644
--- a/src/web/src/app/api/og/route.tsx
+++ b/src/web/src/app/api/og/route.tsx
@@ -129,7 +129,7 @@ function TypewriterIllustration() {
export async function GET(request: NextRequest) {
try {
const { searchParams } = request.nextUrl;
- const title = searchParams.get("title") || "Always-on AI Agents";
+ const title = searchParams.get("title") || "Your Personal Colleagues";
const fontData = await loadFont();
@@ -186,15 +186,15 @@ export async function GET(request: NextRequest) {
height: 630,
...(fontData
? {
- fonts: [
- {
- name: "DM Sans",
- data: fontData,
- weight: 600,
- style: "normal" as const,
- },
- ],
- }
+ fonts: [
+ {
+ name: "DM Sans",
+ data: fontData,
+ weight: 600,
+ style: "normal" as const,
+ },
+ ],
+ }
: {}),
},
);
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 150b7ce51..0bfd5a11a 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -1194,3 +1194,13 @@
width: max-content !important;
min-width: 100%;
}
+
+/* ── Task highlight (activity page scroll-to-task) ── */
+.task-highlight {
+ background-color: oklch(0.8 0.04 80 / 0.4);
+ border-radius: 0.75rem;
+ transition: background-color 1.5s ease-out;
+}
+:is(.dark) .task-highlight {
+ background-color: oklch(0.4 0.04 80 / 0.3);
+}
diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsx
index 6f7c28daa..9e55f893b 100644
--- a/src/web/src/app/layout.tsx
+++ b/src/web/src/app/layout.tsx
@@ -55,7 +55,7 @@ const SITE_URL = "https://alook.ai";
export const metadata: Metadata = {
metadataBase: new URL(SITE_URL),
title: {
- default: "Alook — Always-on AI Agents",
+ default: "Alook — Personal Colleagues",
template: "%s — Alook",
},
description:
@@ -75,25 +75,25 @@ export const metadata: Metadata = {
openGraph: {
type: "website",
siteName: "Alook",
- title: "Alook — Always-on AI Agents",
+ title: "Alook — Personal Colleague",
description:
"Your AI agents, always on. Give them an email, let them work for you around the clock.",
url: SITE_URL,
images: [
{
- url: "/api/og?title=Always-on AI Agents",
+ url: "/api/og?title=Your Personal Colleagues",
width: 1200,
height: 630,
- alt: "Alook — Always-on AI Agents",
+ alt: "Alook — Your Personal Colleagues",
},
],
},
twitter: {
card: "summary_large_image",
- title: "Alook — Always-on AI Agents",
+ title: "Alook — Your Personal Colleagues",
description:
"Your AI agents, always on. Give them an email, let them work for you around the clock.",
- images: ["/api/og?title=Always-on AI Agents"],
+ images: ["/api/og?title=Your Personal Colleagues"],
},
alternates: {
canonical: SITE_URL,
diff --git a/src/web/src/app/page.tsx b/src/web/src/app/page.tsx
index 693dc3898..0e36f8e2a 100644
--- a/src/web/src/app/page.tsx
+++ b/src/web/src/app/page.tsx
@@ -4,7 +4,7 @@ import { HomePage } from "@/components/home/home-page";
import { WorkspaceRedirect } from "@/components/workspace-redirect";
export const metadata: Metadata = {
- title: "Alook — Always-on AI Agents",
+ title: "Alook — Your Personal Colleagues",
description:
"Your AI agents, always on. Give them an email, let them work for you around the clock.",
alternates: { canonical: "https://alook.ai" },
@@ -35,7 +35,7 @@ const faqJsonLd = {
name: "Is Alook free to use?",
acceptedAnswer: {
"@type": "Answer",
- text: "Yes, Alook offers a free tier to get started with always-on AI agents.",
+ text: "Yes, Alook offers a free tier to get started with Your Personal Colleagues.",
},
},
],
diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsx
index ab2a61e52..be94ecaa5 100644
--- a/src/web/src/components/agent-chat/agent-chat-view.tsx
+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx
@@ -1,18 +1,19 @@
"use client";
import React, { useEffect, useState, useRef, useCallback, useMemo } from "react";
-import { useParams } from "next/navigation";
+import { useParams, useSearchParams } from "next/navigation";
import { useWorkspace } from "@/contexts/workspace-context";
import { Button } from "@/components/ui/button";
import { TaskStream } from "@/components/task-stream";
import {
chatInit,
- getOrCreateAgentConversation,
+ createConversation,
+ getConversation,
listMessages,
+ listMessagesAroundTask,
sendMessage,
getTask,
getTaskMessages,
- deleteConversation,
listArtifacts,
listBufferedMessages,
createBufferedMessage,
@@ -156,9 +157,12 @@ function PendingFileChips({
export function AgentChatView() {
const params = useParams();
+ const searchParams = useSearchParams();
const { workspaceId } = useWorkspace();
const { agents, activeTaskCounts, subscribeWs } = useAgentContext();
const agentId = params.id as string;
+ const scrollToTaskId = searchParams.get("task");
+ const targetConvId = searchParams.get("conv");
const [conversation, setConversation] = useState<Conversation | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
@@ -240,21 +244,42 @@ export function AgentChatView() {
useEffect(() => {
async function load() {
try {
- const data = await chatInit(agentId, workspaceId);
- setConversation(data.conversation);
- setMessages(data.messages);
- setHasMore(data.has_more_messages);
- setArtifacts(data.artifacts);
- setBufferedMessages(data.buffered_messages);
-
- if (data.active_task) {
- setActiveTask(data.active_task);
- if (data.task_messages.length > 0) {
- setTaskMessages(data.task_messages);
- lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));
+ if (targetConvId && scrollToTaskId) {
+ try {
+ const [conv, msgs, arts] = await Promise.all([
+ getConversation(targetConvId, workspaceId),
+ listMessages(targetConvId, workspaceId),
+ listArtifacts(targetConvId, workspaceId).catch(() => [] as Artifact[]),
+ ]);
+ setConversation(conv);
+ setMessages(msgs);
+ setHasMore(msgs.length >= MESSAGE_LIMIT);
+ setArtifacts(arts);
+ } catch {
+ const data = await chatInit(agentId, workspaceId);
+ setConversation(data.conversation);
+ setMessages(data.messages);
+ setHasMore(data.has_more_messages);
+ setArtifacts(data.artifacts);
+ setBufferedMessages(data.buffered_messages);
}
- if (!["completed", "failed", "cancelled", "superseded"].includes(data.active_task.status)) {
- startPollingRef.current(data.active_task.id, data.conversation.id, lastSeqRef.current);
+ } else {
+ const data = await chatInit(agentId, workspaceId);
+ setConversation(data.conversation);
+ setMessages(data.messages);
+ setHasMore(data.has_more_messages);
+ setArtifacts(data.artifacts);
+ setBufferedMessages(data.buffered_messages);
+
+ if (data.active_task) {
+ setActiveTask(data.active_task);
+ if (data.task_messages.length > 0) {
+ setTaskMessages(data.task_messages);
+ lastSeqRef.current = Math.max(...data.task_messages.map((m) => m.seq));
+ }
+ if (!["completed", "failed", "cancelled", "superseded"].includes(data.active_task.status)) {
+ startPollingRef.current(data.active_task.id, data.conversation.id, lastSeqRef.current);
+ }
}
}
} catch {
@@ -264,17 +289,44 @@ export function AgentChatView() {
}
}
load();
- }, [agentId, workspaceId]);
+ }, [agentId, workspaceId, targetConvId, scrollToTaskId]);
- // Scroll to bottom on initial load
+ // Scroll to bottom on initial load (skip if scroll-to-task is active)
useEffect(() => {
if (!loading && messages.length > 0 && !initialScrollDone.current) {
initialScrollDone.current = true;
- setTimeout(() => {
- scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
- }, 50);
+ if (!scrollToTaskId) {
+ setTimeout(() => {
+ scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
+ }, 50);
+ }
}
- }, [loading, messages.length]);
+ }, [loading, messages.length, scrollToTaskId]);
+
+ // Scroll to task when ?task= param is present
+ useEffect(() => {
+ if (!scrollToTaskId || loading || !conversation) return;
+ const tryScroll = () => {
+ const el = document.querySelector(`[data-task-id="${CSS.escape(scrollToTaskId)}"]`);
+ if (!el) return false;
+ el.scrollIntoView({ behavior: "smooth", block: "center" });
+ el.classList.add("task-highlight");
+ setTimeout(() => el.classList.remove("task-highlight"), 1500);
+ return true;
+ };
+ setTimeout(async () => {
+ if (tryScroll()) return;
+ try {
+ const around = await listMessagesAroundTask(conversation.id, workspaceId, scrollToTaskId);
+ if (around.length > 0) {
+ setMessages((prev) => mergeMessages(prev, around));
+ requestAnimationFrame(() => {
+ setTimeout(() => tryScroll(), 100);
+ });
+ }
+ } catch {}
+ }, 100);
+ }, [scrollToTaskId, loading, conversation, workspaceId]);
// Auto-scroll when task badge appears or new task steps arrive
const taskStatus = activeTask?.status;
@@ -727,8 +779,7 @@ export function AgentChatView() {
clearInterval(pollRef.current);
pollRef.current = null;
}
- await deleteConversation(conversation.id, workspaceId);
- const newConv = await getOrCreateAgentConversation(agentId, workspaceId);
+ const newConv = await createConversation(agentId, workspaceId);
setConversation(newConv);
setMessages([]);
setActiveTask(null);
@@ -921,7 +972,7 @@ export function AgentChatView() {
</div>
);
})() : !hasTaskStream ? (
- <div className="flex justify-start">
+ <div className="flex justify-start" {...(msg.task_id ? { "data-task-id": msg.task_id } : {})}>
<div className="markdown max-w-full min-w-0 px-1 py-1 text-base text-foreground">
<Streamdown controls={{ code: { copy: true, download: false }, table: { copy: true, download: false, fullscreen: true } }} linkSafety={{ enabled: false }}>{msg.content}</Streamdown>
</div>
@@ -943,7 +994,7 @@ export function AgentChatView() {
</div>
{/* Follow-up buffer indicator */}
- <FollowUpBuffer
+ {!targetConvId && <FollowUpBuffer
bufferedMessages={bufferedMessages}
onDelete={(messageId) => {
const prev = bufferedMessages;
@@ -953,10 +1004,10 @@ export function AgentChatView() {
toast.error("Failed to delete follow-up");
});
}}
- />
+ />}
- {/* Input */}
- <div className="px-5 py-3">
+ {/* Input — hidden when viewing a specific conversation from activity */}
+ {!targetConvId && <div className="px-5 py-3">
<div className="mx-auto max-w-2xl relative">
<div
className={cn(
@@ -1139,7 +1190,7 @@ export function AgentChatView() {
</div>
</div>
</div>
- </div>
+ </div>}
<Dialog open={resetConfirmOpen} onOpenChange={setResetConfirmOpen}>
<DialogContent showCloseButton={false}>
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index 1703da3a9..e9bea78f0 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -202,6 +202,15 @@ export const listMessages = (
);
};
+export const listMessagesAroundTask = (
+ conversationId: string,
+ workspaceId: string,
+ taskId: string
+) =>
+ apiFetch<Message[]>(
+ `/api/conversations/${conversationId}/messages${wsQuery(workspaceId, { around_task: taskId })}`
+ );
+
export const sendMessage = async (
conversationId: string,
content: string,
@@ -369,6 +378,35 @@ export interface ActiveTask {
export const listAgentActiveTasks = (agentId: string, workspaceId: string) =>
apiFetch<{ tasks: ActiveTask[] }>(`/api/agents/${agentId}/active-tasks${wsQuery(workspaceId)}`);
+// Activity
+export interface ActivityTask {
+ id: string;
+ conversation_id: string;
+ type: string;
+ status: string;
+ prompt: string;
+ created_at: string;
+ started_at: string | null;
+ completed_at: string | null;
+ error: string | null;
+}
+
+export const listAgentActivity = (
+ agentId: string,
+ workspaceId: string,
+ opts?: { limit?: number; before?: string; beforeId?: string; status?: string; type?: string }
+) => {
+ const extra: Record<string, string> = {};
+ if (opts?.limit) extra.limit = String(opts.limit);
+ if (opts?.before) extra.before = opts.before;
+ if (opts?.beforeId) extra.before_id = opts.beforeId;
+ if (opts?.status) extra.status = opts.status;
+ if (opts?.type) extra.type = opts.type;
+ return apiFetch<{ tasks: ActivityTask[]; has_more: boolean }>(
+ `/api/agents/${agentId}/activity${wsQuery(workspaceId, extra)}`
+ );
+};
+
// Tasks (polling)
export const getTask = (id: string, workspaceId: string) =>
apiFetch<TaskApi>(`/api/tasks/${id}${wsQuery(workspaceId)}`);
diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.ts
index aeb517003..530802dac 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -208,6 +208,31 @@ export function calendarEventToResponse(e: any) {
};
}
+export function taskToActivityResponse(t: {
+ id: string;
+ conversationId: string;
+ type: string;
+ status: string;
+ prompt: string;
+ createdAt: Date | string;
+ startedAt: Date | string | null;
+ completedAt: Date | string | null;
+ error?: string | null;
+}) {
+ const prompt = t.prompt.length > 120 ? t.prompt.slice(0, 120) : t.prompt;
+ return {
+ id: t.id,
+ conversation_id: t.conversationId,
+ type: t.type ?? TASK_TYPES.USER_DM_MESSAGE,
+ status: t.status,
+ prompt,
+ created_at: formatTimestamp(t.createdAt),
+ started_at: formatTimestampNullable(t.startedAt),
+ completed_at: formatTimestampNullable(t.completedAt),
+ error: t.error || null,
+ };
+}
+
export function memberToResponse(m: {
id: string;
userId: string;
diff --git a/src/web/src/lib/services/calendar.test.ts b/src/web/src/lib/services/calendar.test.ts
index 50457aa3e..ac529516f 100644
--- a/src/web/src/lib/services/calendar.test.ts
+++ b/src/web/src/lib/services/calendar.test.ts
@@ -15,6 +15,7 @@ const mockRevert = vi.fn();
const mockUpdateSchedule = vi.fn();
const mockGetAgent = vi.fn();
const mockCreateConv = vi.fn();
+const mockCreateMessage = vi.fn();
const mockCreateTask = vi.fn();
vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
@@ -28,6 +29,9 @@ vi.mock("@alook/shared", async () => {
conversation: {
createConversation: (...args: unknown[]) => mockCreateConv(...args),
},
+ message: {
+ createMessage: (...args: unknown[]) => mockCreateMessage(...args),
+ },
task: { createTask: (...args: unknown[]) => mockCreateTask(...args) },
calendarEvent: {
listDueCalendarEvents: (...args: unknown[]) => mockListDue(...args),
diff --git a/src/web/src/lib/services/calendar.ts b/src/web/src/lib/services/calendar.ts
index 422f388dd..ea3dfc694 100644
--- a/src/web/src/lib/services/calendar.ts
+++ b/src/web/src/lib/services/calendar.ts
@@ -75,6 +75,12 @@ export async function promoteDueCalendarEventsForWorkspace(
type: TASK_TYPES.CALENDAR_EVENT,
});
+ await queries.message.createMessage(db, {
+ conversationId: conv.id,
+ role: "user",
+ content: ev.title,
+ });
+
await queries.task.createTask(db, {
agentId: ev.agentId,
runtimeId: agent.runtimeId,