Open-source SEO, GEO, and marketing skills for AI agents.
feat(agents): paperclip-style task workspace with live transcript
Yuting Zhongdda1e8e2e18f
diff --git a/src/app/(app)/agents/[agent]/page.tsx b/src/app/(app)/agents/[agent]/page.tsxindex bca1d7ca..7843847b 100644--- a/src/app/(app)/agents/[agent]/page.tsx+++ b/src/app/(app)/agents/[agent]/page.tsx@@ -6,5 +6,5 @@ export default async function AgentIndexPage({params: Promise<{ agent: string }>;}) {const { agent } = await params;- redirect(`/agents/${agent}/chat`);+ redirect(`/agents/${agent}/tasks`);}diff --git a/src/app/(app)/agents/[agent]/tasks/page.tsx b/src/app/(app)/agents/[agent]/tasks/page.tsxindex 15b57e39..ccf19be6 100644--- a/src/app/(app)/agents/[agent]/tasks/page.tsx+++ b/src/app/(app)/agents/[agent]/tasks/page.tsx@@ -1,40 +1,37 @@-import Link from "next/link";import { notFound } from "next/navigation";-import { Badge } from "@/components/ui/badge";-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";-import { StartAllTasksButton } from "@/components/start-all-tasks-button";+import { AgentTaskWorkspace } from "@/components/agent-task-workspace";import { getActiveProject } from "@/server/active-project";import { resolveAgentBySlug } from "@/server/agent-meta";-import { listTasksByAgent } from "@/server/db/tasks";-import type { Task, TaskStatus } from "@/types";--const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [- { status: "proposed", label: "Proposed" },- { status: "running", label: "In progress" },- { status: "succeeded", label: "Done" },- { status: "failed", label: "Failed" },- { status: "cancelled", label: "Cancelled" },-];--const STATUS_VARIANT: Record<- TaskStatus,- "default" | "secondary" | "outline" | "destructive"-> = {- proposed: "outline",- approved: "secondary",- running: "default",- succeeded: "secondary",- failed: "destructive",- cancelled: "outline",-};+import { getTask, listTasksByAgent, setTaskThreadIfMissing } from "@/server/db/tasks";+import { buildPendingSessionKey, findSessionBySessionId } from "@/server/openclaw/sessions";+import {+ readTranscriptTail,+ type TranscriptEvent,+} from "@/server/openclaw/transcript-tail";+import { generateTaskThreadId } from "@/server/orchestration/process-blocks";+import { startTaskIfProposed } from "@/server/orchestration/run-task";+import type { Task } from "@/types";-export default async function AgentTasksPage({- params,-}: {+type Props = {params: Promise<{ agent: string }>;-}) {- const { agent: agentSlug } = await params;+ searchParams: Promise<{ task?: string }>;+};++type SelectedBundle = {+ task: Task;+ threadId: string;+ sessionKey: string;+ initialEvents: TranscriptEvent[];+ initialByteOffset: number;+};++export default async function AgentTasksPage({ params, searchParams }: Props) {+ const [{ agent: agentSlug }, { task: selectedTaskId }] = await Promise.all([+ params,+ searchParams,+ ]);+const project = await getActiveProject();if (!project) {return (@@ -48,94 +45,66 @@ export default async function AgentTasksPage({if (!resolved) notFound();const agentFullId = resolved.agent_id;++ // Load the selected task's brief + transcript bundle if `?task=` is set.+ // This may auto-claim a proposed task → running, so it runs BEFORE the+ // task list is read — otherwise the list shows the pre-claim status+ // and the selected task appears under the wrong group.+ let selected: SelectedBundle | null = null;+ if (selectedTaskId) {+ selected = await loadSelectedBundle(agentFullId, selectedTaskId);+ // Guard: drop selection if it's not on this agent (cross-agent links etc).+ if (selected && selected.task.agent_id !== agentFullId) selected = null;+ }+const tasks = listTasksByAgent(agentFullId);const proposedCount = tasks.filter((t) => t.status === "proposed").length;- const byStatus = new Map<TaskStatus, Task[]>();- for (const t of tasks) {- const list = byStatus.get(t.status) ?? [];- list.push(t);- byStatus.set(t.status, list);- }return (- <div className="mx-auto max-w-5xl space-y-6 p-6">- <header className="flex items-end justify-between gap-4">- <div>- <h1 className="text-2xl font-semibold tracking-tight">- {resolved.display_name} · Tasks- </h1>- <p className="text-sm text-muted-foreground">- {tasks.length === 0- ? "Nothing assigned yet."- : `${tasks.length} total · ${proposedCount} ready to start`}- </p>- </div>- {proposedCount > 0 && (- <StartAllTasksButton agentId={agentFullId} proposedCount={proposedCount} />- )}- </header>-- {tasks.length === 0 ? (- <Card>- <CardContent className="py-12 text-center text-sm text-muted-foreground">- No tasks assigned to {resolved.display_name} yet. The CMO will create- tasks here when it delegates work.- </CardContent>- </Card>- ) : (- <div className="grid gap-4 md:grid-cols-3">- {STATUS_GROUPS.map((group) => {- const items = byStatus.get(group.status) ?? [];- if (items.length === 0) return null;- return (- <Card key={group.status}>- <CardHeader className="pb-2">- <CardTitle className="flex items-center justify-between text-sm font-medium">- {group.label}- <span className="text-xs text-muted-foreground tabular-nums">- {items.length}- </span>- </CardTitle>- </CardHeader>- <CardContent className="space-y-2">- {items.map((t) => (- <Link- key={t.id}- href={`/tasks/${t.id}`}- className="block rounded-md border bg-card p-3 text-xs space-y-1 transition-colors hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-foreground/30"- >- <div className="flex items-center justify-between gap-2">- <Badge- variant={STATUS_VARIANT[t.status]}- className="text-[10px]"- >- {t.status}- </Badge>- <span className="text-[10px] text-muted-foreground tabular-nums">- {new Date(t.updated_at).toLocaleTimeString()}- </span>- </div>- <p className="line-clamp-2 font-medium text-foreground">- {t.title ?? t.brief}- </p>- {t.title && (- <p className="line-clamp-2 text-muted-foreground">- {t.brief}- </p>- )}- {t.status === "failed" && t.error_message && (- <p className="line-clamp-2 text-destructive">- {t.error_message}- </p>- )}- </Link>- ))}- </CardContent>- </Card>- );- })}- </div>- )}- </div>+ <AgentTaskWorkspace+ agentSlug={agentSlug}+ agentFullId={agentFullId}+ agentDisplayName={resolved.display_name}+ tasks={tasks}+ selected={selected}+ proposedCount={proposedCount}+ />);}++async function loadSelectedBundle(+ agentFullId: string,+ taskId: string,+): Promise<SelectedBundle | null> {+ let task = getTask(taskId);+ if (!task) return null;++ // Lazily mint a per-task chat thread on first open. Stable forever after.+ if (!task.thread_id) {+ const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());+ if (updated) task = updated;+ }+ if (!task.thread_id) return null;+ const threadId = task.thread_id;++ // Atomically transition proposed → running and fire the kickoff. No-op+ // when the task isn't proposed, so reloading the page doesn't restart.+ task = startTaskIfProposed(task);++ // Resolve canonical sessionKey for /api/chat composer sends (when task+ // is done and user wants to keep chatting). The pending key is a safe+ // fallback for brand-new threads.+ const session = findSessionBySessionId(agentFullId, threadId);+ const sessionKey =+ session?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);++ const { events, byteOffset } = readTranscriptTail(agentFullId, threadId, 0);++ return {+ task,+ threadId,+ sessionKey,+ initialEvents: events,+ initialByteOffset: byteOffset,+ };+}diff --git a/src/app/(app)/tasks/[id]/page.tsx b/src/app/(app)/tasks/[id]/page.tsxindex e1e17b43..b5422b1e 100644--- a/src/app/(app)/tasks/[id]/page.tsx+++ b/src/app/(app)/tasks/[id]/page.tsx@@ -1,32 +1,16 @@-import Link from "next/link";-import { notFound } from "next/navigation";+import { notFound, redirect } from "next/navigation";-import { AgentChat } from "@/components/agent-chat";-import { TaskLivePoller } from "@/components/task-live-poller";-import { Badge } from "@/components/ui/badge";-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";-import { getActiveProject } from "@/server/active-project";import { readAgentMeta } from "@/server/agent-meta";-import { templateForKey, urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templates";-import { listAgentActions } from "@/server/db/agent-actions";-import { getTask, setTaskThreadIfMissing } from "@/server/db/tasks";-import { buildTaskKickoffMessage } from "@/server/orchestration/task-kickoff";-import { generateTaskThreadId } from "@/server/orchestration/process-blocks";-import { loadThreadHistory, shouldAutoKickoffTask } from "@/server/orchestration/thread-history";-import type { TaskStatus } from "@/types";--const STATUS_VARIANT: Record<- TaskStatus,- "default" | "secondary" | "outline" | "destructive"-> = {- proposed: "outline",- approved: "secondary",- running: "default",- succeeded: "secondary",- failed: "destructive",- cancelled: "outline",-};-+import { getActiveProject } from "@/server/active-project";+import { getTask } from "@/server/db/tasks";+import { urlSlugForTemplate, type AgentTemplateKey } from "@/server/agent-templates";++/**+ * Deep-link destination for task IDs. The canonical view lives in the agent+ * workspace, so we resolve the task's owning agent and redirect there with+ * the task pre-selected. Keeps existing orchestration-summary links + emails+ * + bookmarks working through the rework.+ */export default async function TaskDetailPage({params,}: {@@ -42,140 +26,14 @@ export default async function TaskDetailPage({);}- let task = getTask(id);+ const task = getTask(id);if (!task || task.project_slug !== project.slug) notFound();- // Lazily mint a per-task chat thread on first open. Stable forever after- // so the assignee's transcript for THIS task persists across visits.- if (!task.thread_id) {- const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());- if (updated) task = updated;- }- const threadId = task.thread_id!;-- // Resolve the assignee's template + display info. The brief might predate- // an agent rename / template rework, so be defensive.+ // Resolve the assignee's URL slug. Templates predate cloned agents — fall+ // back to the template default if no per-agent slug is stored.const meta = await readAgentMeta(task.agent_id);const templateKey = (meta?.template_key as AgentTemplateKey | undefined) ?? "google_ads";- const template = templateForKey(templateKey);const agentSlug = meta?.slug ?? urlSlugForTemplate(templateKey);- const agentDisplayName = meta?.display_name ?? template?.display_name ?? "Specialist";-- // Per-task chat history. loadThreadHistory resolves threadId → OpenClaw- // sessionId before reading the JSONL — direct loadSessionHistory(threadId)- // returns [] because the file is keyed by OpenClaw's internal sessionId,- // not by the URL label. That bug caused succeeded tasks to re-trigger- // when reopened. shouldAutoKickoffTask adds a defense-in-depth status- // gate so any non-proposed task is safe even if history loading regresses.- const { sessionKey, history } = loadThreadHistory(task.agent_id, threadId);- const autoKickoff = shouldAutoKickoffTask(task, history);- const kickoffMessage = autoKickoff ? buildTaskKickoffMessage(task) : undefined;- // Comments + status updates on this task (rendered as an activity list above- // the chat). Pulls from agent_actions filtered by task_id payload field.- const activity = listAgentActions(project.slug, 50).filter((a) => {- if (!a.payload_json) return false;- try {- const payload = JSON.parse(a.payload_json) as { task_id?: string };- return payload.task_id === task!.id;- } catch {- return false;- }- });-- return (- <div className="flex h-full flex-col">- <div className="border-b bg-background/95 px-6 py-4">- <div className="mx-auto max-w-3xl space-y-3">- <div className="flex items-center justify-between gap-3">- <div className="min-w-0">- <div className="text-xs text-muted-foreground">- <Link href="/tasks" className="hover:text-foreground hover:underline">- Tasks- </Link>{" "}- / <span className="font-mono">{task.id.slice(0, 8)}</span>- </div>- <h1 className="text-xl font-semibold tracking-tight truncate">- {task.title ?? "(untitled task)"}- </h1>- </div>- <div className="flex shrink-0 items-center gap-2">- <Badge variant={STATUS_VARIANT[task.status]}>{task.status}</Badge>- <Badge variant="outline" className="font-mono text-[10px]">- → {agentDisplayName}- </Badge>- </div>- </div>-- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Brief</CardTitle>- <CardDescription className="text-[10px]">- Created {new Date(task.created_at).toLocaleString()}- {task.assigner_agent_id ? ` by ${task.assigner_agent_id}` : ""}- </CardDescription>- </CardHeader>- <CardContent className="space-y-2 pt-0 text-sm whitespace-pre-wrap">- {task.brief}- {task.success_criteria && (- <div className="mt-3 border-t pt-2 text-xs text-muted-foreground">- <span className="font-medium">Success criteria:</span>{" "}- {task.success_criteria}- </div>- )}- </CardContent>- </Card>-- {activity.length > 0 && (- <Card>- <CardHeader className="pb-2">- <CardTitle className="text-sm">Task activity</CardTitle>- <CardDescription className="text-[10px]">- {activity.length} event{activity.length === 1 ? "" : "s"} on this- task- </CardDescription>- </CardHeader>- <CardContent className="space-y-1.5 pt-0 text-xs">- {activity.slice(0, 8).map((a) => (- <div key={a.id} className="flex items-baseline gap-2">- <Badge variant="outline" className="font-mono text-[9px]">- {a.action_type}- </Badge>- <span className="flex-1 truncate">{a.summary}</span>- <span className="text-[10px] text-muted-foreground tabular-nums">- {new Date(a.occurred_at).toLocaleTimeString()}- </span>- </div>- ))}- </CardContent>- </Card>- )}- </div>- </div>-- <div className="min-h-0 flex-1 border-t">- <AgentChat- // Key includes task.status so flipping running → succeeded remounts- // AgentChat exactly once, pulling in the agent's final reply from- // JSONL. The threadId stays stable so the dedup'd kickoff guard in- // KICKOFF_FIRED still prevents a re-trigger.- key={`${threadId}:${task.status}`}- projectSlug={project.slug}- agentSlug={agentSlug}- agentDisplayName={agentDisplayName}- sessionId={threadId}- sessionKey={sessionKey}- templateKey={templateKey}- initialMessages={history.map((m) => ({- id: m.id,- role: m.role,- body: m.body,- }))}- autoKickoff={autoKickoff}- kickoffMessage={kickoffMessage}- />- </div>- <TaskLivePoller status={task.status} />- </div>- );+ redirect(`/agents/${agentSlug}/tasks?task=${task.id}`);}diff --git a/src/app/api/agents/[agent]/tasks/[id]/transcript/route.ts b/src/app/api/agents/[agent]/tasks/[id]/transcript/route.tsnew file mode 100644index 00000000..fe43d52b--- /dev/null+++ b/src/app/api/agents/[agent]/tasks/[id]/transcript/route.ts@@ -0,0 +1,81 @@+import { NextResponse } from "next/server";+import { getActiveProject } from "@/server/active-project";+import { resolveAgentBySlug } from "@/server/agent-meta";+import { getTask } from "@/server/db/tasks";+import { readTranscriptTail } from "@/server/openclaw/transcript-tail";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++/**+ * Returns the slice of the on-disk JSONL transcript that lives after the+ * client's last seen byte offset. The client appends `events` to its local+ * buffer and sends the returned `byteOffset` back on the next poll.+ *+ * `done: true` tells the client to stop polling — set when the task has+ * reached a terminal status. A null `byteOffset` means OpenClaw hasn't+ * written a transcript file yet (proposed task whose kickoff hasn't landed).+ */+export async function GET(+ request: Request,+ context: { params: Promise<{ agent: string; id: string }> },+) {+ const { agent: agentSlug, id: taskId } = await context.params;++ const project = await getActiveProject();+ if (!project) {+ return NextResponse.json({ error: "no active project" }, { status: 400 });+ }++ const resolved = await resolveAgentBySlug(project.slug, agentSlug);+ if (!resolved) {+ return NextResponse.json({ error: "unknown agent" }, { status: 404 });+ }++ const task = getTask(taskId);+ if (!task || task.project_slug !== project.slug) {+ return NextResponse.json({ error: "task not found" }, { status: 404 });+ }+ // Cross-agent task access guard — the URL agent must own this task.+ if (task.agent_id !== resolved.agent_id) {+ return NextResponse.json({ error: "task not on this agent" }, { status: 404 });+ }+ if (!task.thread_id) {+ // Thread isn't minted yet (task just created, never opened). Nothing on+ // disk to tail. Client will retry on the next poll tick.+ return NextResponse.json({+ events: [],+ byteOffset: 0,+ file_size: 0,+ done: false,+ status: task.status,+ });+ }++ const url = new URL(request.url);+ const offsetParam = url.searchParams.get("offset");+ const byteOffset = offsetParam ? Number(offsetParam) : 0;+ const validOffset = Number.isFinite(byteOffset) && byteOffset >= 0 ? byteOffset : 0;++ const { events, byteOffset: newOffset, fileSize } = readTranscriptTail(+ resolved.agent_id,+ task.thread_id,+ validOffset,+ );++ const terminal =+ task.status === "succeeded" ||+ task.status === "failed" ||+ task.status === "cancelled";++ return NextResponse.json({+ events,+ byteOffset: newOffset,+ file_size: fileSize,+ // Only stop polling AFTER the task is terminal AND we've drained the+ // file. Otherwise the last few events written between status-flip and+ // our read can get dropped.+ done: terminal && newOffset >= fileSize,+ status: task.status,+ });+}diff --git a/src/components/agent-nav.tsx b/src/components/agent-nav.tsxindex c51e7688..751b50ec 100644--- a/src/components/agent-nav.tsx+++ b/src/components/agent-nav.tsx@@ -8,6 +8,7 @@ import {SidebarMenuButton,SidebarMenuItem,} from "@/components/ui/sidebar";+import { RunningDot } from "@/components/running-dot";import type { AgentTemplateKey } from "@/server/agent-templates";type AgentNavEntry = {@@ -22,6 +23,12 @@ type AgentNavEntry = {type Props = {agents: AgentNavEntry[];+ /**+ * agent_id → in-flight task count. Drives the live-dot + count badge on+ * each row. Stale by up to the server-component refresh interval; that's+ * fine for an "I have work" hint.+ */+ inFlightCounts?: Record<string, number>;};const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {@@ -30,23 +37,37 @@ const TEMPLATE_ICONS: Record<AgentTemplateKey, LucideIcon> = {seo: Search,};-export function AgentNav({ agents }: Props) {+export function AgentNav({ agents, inFlightCounts = {} }: Props) {const pathname = usePathname();return (<SidebarMenu>{agents.map((a) => {- const href = `/agents/${a.slug}/chat`;+ // Specialists land on Tasks; CMO lands on Chat. The CMO doesn't own+ // tasks (it delegates them) so Tasks would be empty for it.+ const href =+ a.template_key === "cmo"+ ? `/agents/${a.slug}/chat`+ : `/agents/${a.slug}/tasks`;const agentBase = `/agents/${a.slug}`;const isActive =pathname === agentBase || pathname?.startsWith(`${agentBase}/`);const Icon = a.template_key ? TEMPLATE_ICONS[a.template_key] ?? Bot : Bot;+ const liveCount = inFlightCounts[a.key] ?? 0;return (<SidebarMenuItem key={a.key}><SidebarMenuButton asChild isActive={isActive}><Link href={href}><Icon /><span>{a.display_name}</span>+ {liveCount > 0 && (+ <span className="ml-auto inline-flex items-center gap-1.5">+ <RunningDot size="sm" aria-label={`${liveCount} running`} />+ <span className="text-[10px] font-medium tabular-nums text-sky-600 dark:text-sky-400">+ {liveCount}+ </span>+ </span>+ )}</Link></SidebarMenuButton></SidebarMenuItem>diff --git a/src/components/agent-tabs.tsx b/src/components/agent-tabs.tsxindex 57a31422..25bf820d 100644--- a/src/components/agent-tabs.tsx+++ b/src/components/agent-tabs.tsx@@ -11,9 +11,12 @@ type Tab = {icon: React.ComponentType<{ className?: string }>;};+// Tasks is the default landing surface for specialists (and the workspace+// where the live transcript lives), so it leads. Chat is still available as+// a free-form thread when the user wants to talk outside the task model.const TABS: Tab[] = [- { key: "chat", label: "Chat", icon: MessageSquare },{ key: "tasks", label: "Tasks", icon: ListChecks },+ { key: "chat", label: "Chat", icon: MessageSquare },{ key: "files", label: "Files", icon: FileText },{ key: "skills", label: "Skills", icon: Sparkles },{ key: "cron", label: "Cron", icon: Clock },diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsxnew file mode 100644index 00000000..2e95b292--- /dev/null+++ b/src/components/agent-task-workspace.tsx@@ -0,0 +1,348 @@+"use client";++import { useMemo } from "react";+import Link from "next/link";+import { useRouter, useSearchParams } from "next/navigation";+import { CheckCircle2, Circle, CircleDot, Loader2, XCircle } from "lucide-react";++import { Badge } from "@/components/ui/badge";+import { LiveTranscript } from "@/components/live-transcript";+import { RunningDot } from "@/components/running-dot";+import { StartAllTasksButton } from "@/components/start-all-tasks-button";+import { cn } from "@/lib/utils";+import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";+import type { Task, TaskStatus } from "@/types";++const STATUS_GROUPS: Array<{ status: TaskStatus; label: string }> = [+ { status: "running", label: "Running" },+ { status: "proposed", label: "Proposed" },+ { status: "approved", label: "Approved" },+ { status: "succeeded", label: "Done" },+ { status: "failed", label: "Failed" },+ { status: "cancelled", label: "Cancelled" },+];++const STATUS_VARIANT: Record<+ TaskStatus,+ "default" | "secondary" | "outline" | "destructive"+> = {+ proposed: "outline",+ approved: "secondary",+ running: "default",+ succeeded: "secondary",+ failed: "destructive",+ cancelled: "outline",+};++type SelectedTaskBundle = {+ task: Task;+ threadId: string;+ sessionKey: string;+ initialEvents: TranscriptEvent[];+ initialByteOffset: number;+};++type Props = {+ agentSlug: string;+ agentFullId: string;+ agentDisplayName: string;+ tasks: Task[];+ selected: SelectedTaskBundle | null;+ proposedCount: number;+};++export function AgentTaskWorkspace({+ agentSlug,+ agentFullId,+ agentDisplayName,+ tasks,+ selected,+ proposedCount,+}: Props) {+ const router = useRouter();+ const search = useSearchParams();+ const selectedId = search.get("task");++ const grouped = useMemo(() => {+ const map = new Map<TaskStatus, Task[]>();+ for (const t of tasks) {+ const list = map.get(t.status) ?? [];+ list.push(t);+ map.set(t.status, list);+ }+ return map;+ }, [tasks]);++ const totalCount = tasks.length;+ const inFlightCount =+ (grouped.get("running")?.length ?? 0) ++ (grouped.get("proposed")?.length ?? 0) ++ (grouped.get("approved")?.length ?? 0);++ function selectTask(id: string) {+ const params = new URLSearchParams(search?.toString() ?? "");+ params.set("task", id);+ router.replace(`?${params.toString()}`, { scroll: false });+ }++ return (+ <div className="flex h-full min-h-0">+ {/* ── Left pane: task list ─────────────────────────────────────── */}+ <aside className="flex w-80 shrink-0 flex-col border-r bg-muted/20">+ <div className="border-b px-4 py-3">+ <div className="flex items-baseline justify-between gap-2">+ <h2 className="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {agentDisplayName} · Tasks+ </h2>+ <span className="text-[10px] tabular-nums text-muted-foreground">+ {totalCount}+ </span>+ </div>+ <p className="mt-1 text-[11px] text-muted-foreground">+ {inFlightCount > 0 ? (+ <span className="inline-flex items-center gap-1.5">+ <RunningDot size="sm" aria-label="" />+ <span className="tabular-nums">{inFlightCount}</span> in flight+ </span>+ ) : totalCount === 0 ? (+ "Nothing assigned yet."+ ) : (+ "All quiet."+ )}+ </p>+ {proposedCount > 0 && (+ <div className="mt-2">+ <StartAllTasksButton+ agentId={agentFullId}+ proposedCount={proposedCount}+ />+ </div>+ )}+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto py-1">+ {totalCount === 0 ? (+ <div className="px-4 py-8 text-center text-xs text-muted-foreground">+ The CMO will delegate tasks here.+ </div>+ ) : (+ STATUS_GROUPS.map((group) => {+ const items = grouped.get(group.status);+ if (!items || items.length === 0) return null;+ return (+ <div key={group.status} className="py-1">+ <div className="flex items-center justify-between px-4 py-1.5">+ <span className="text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground">+ {group.label}+ </span>+ <span className="text-[10px] tabular-nums text-muted-foreground">+ {items.length}+ </span>+ </div>+ <ul>+ {items.map((t) => (+ <li key={t.id}>+ <TaskRow+ task={t}+ selected={t.id === selectedId}+ onSelect={() => selectTask(t.id)}+ />+ </li>+ ))}+ </ul>+ </div>+ );+ })+ )}+ </div>+ </aside>++ {/* ── Right pane: brief header + live transcript ───────────────── */}+ <section className="flex min-w-0 flex-1 flex-col">+ {selected ? (+ <>+ <header className="border-b bg-background/60 backdrop-blur">+ <div className="mx-auto w-full max-w-3xl px-6 py-3">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2 text-[10px] uppercase tracking-[0.18em] text-muted-foreground">+ <Link href="/tasks" className="hover:text-foreground">+ Tasks+ </Link>+ <span>/</span>+ <span className="font-mono">+ {selected.task.id.slice(0, 8)}+ </span>+ </div>+ <h1 className="mt-0.5 text-base font-semibold tracking-tight truncate">+ {selected.task.title ?? "(untitled task)"}+ </h1>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ {(selected.task.status === "running" ||+ selected.task.status === "proposed" ||+ selected.task.status === "approved") && (+ <RunningDot size="md" />+ )}+ <Badge+ variant={STATUS_VARIANT[selected.task.status]}+ className="text-[10px]"+ >+ {selected.task.status}+ </Badge>+ </div>+ </div>+ <details className="group mt-2">+ <summary className="flex cursor-pointer select-none items-center gap-2 text-[10px] font-semibold uppercase tracking-[0.18em] text-muted-foreground hover:text-foreground">+ <span className="transition-transform group-open:rotate-90">›</span>+ Brief+ </summary>+ <div className="mt-2 space-y-2 pl-3 text-sm whitespace-pre-wrap text-muted-foreground">+ {selected.task.brief}+ {selected.task.success_criteria && (+ <div className="mt-2 border-l-2 border-muted pl-3 text-xs">+ <span className="font-medium text-foreground">+ Success criteria:+ </span>{" "}+ {selected.task.success_criteria}+ </div>+ )}+ </div>+ </details>+ </div>+ </header>++ <div className="min-h-0 flex-1">+ <LiveTranscript+ key={selected.task.id}+ agentSlug={agentSlug}+ agentDisplayName={agentDisplayName}+ taskId={selected.task.id}+ taskStatus={selected.task.status}+ initialEvents={selected.initialEvents}+ initialByteOffset={selected.initialByteOffset}+ sessionId={selected.threadId}+ sessionKey={selected.sessionKey}+ />+ </div>+ </>+ ) : (+ <EmptyRightPane+ agentDisplayName={agentDisplayName}+ hasTasks={totalCount > 0}+ />+ )}+ </section>+ </div>+ );+}++function TaskRow({+ task,+ selected,+ onSelect,+}: {+ task: Task;+ selected: boolean;+ onSelect: () => void;+}) {+ const isRunning = task.status === "running";+ const isInFlight =+ task.status === "running" ||+ task.status === "proposed" ||+ task.status === "approved";+ return (+ <button+ type="button"+ onClick={onSelect}+ aria-current={selected ? "true" : undefined}+ className={cn(+ "group block w-full px-4 py-2.5 text-left transition-colors",+ "hover:bg-accent/40 focus-visible:outline-none focus-visible:bg-accent/40",+ selected && "bg-accent/80 hover:bg-accent/80",+ )}+ >+ <div className="flex items-center gap-2.5">+ <span className="flex size-3.5 shrink-0 items-center justify-center">+ {isRunning ? (+ <RunningDot size="md" aria-label="Running" />+ ) : (+ <StatusGlyph status={task.status} />+ )}+ </span>+ <span+ className={cn(+ "flex-1 truncate text-xs",+ selected ? "font-medium text-foreground" : "text-foreground/90",+ !isInFlight && task.status !== "running" && "text-muted-foreground",+ )}+ >+ {task.title ?? task.brief.slice(0, 80)}+ </span>+ <span className="shrink-0 text-[10px] tabular-nums text-muted-foreground">+ {formatRelative(task.updated_at)}+ </span>+ </div>+ {task.status === "failed" && task.error_message && (+ <div className="ml-6 mt-1 line-clamp-1 text-[10px] text-destructive/80">+ {task.error_message}+ </div>+ )}+ </button>+ );+}++function StatusGlyph({ status }: { status: TaskStatus }) {+ switch (status) {+ case "succeeded":+ return <CheckCircle2 className="size-3.5 text-emerald-600" />;+ case "failed":+ return <XCircle className="size-3.5 text-destructive" />;+ case "cancelled":+ return <Circle className="size-3.5 text-muted-foreground" />;+ case "approved":+ return <CircleDot className="size-3.5 text-sky-600" />;+ case "running":+ return <Loader2 className="size-3.5 animate-spin text-sky-600" />;+ case "proposed":+ default:+ return <Circle className="size-3.5 text-muted-foreground" />;+ }+}++function EmptyRightPane({+ agentDisplayName,+ hasTasks,+}: {+ agentDisplayName: string;+ hasTasks: boolean;+}) {+ return (+ <div className="flex h-full flex-col items-center justify-center px-6 text-center">+ <div className="space-y-2 max-w-sm">+ <h3 className="text-sm font-medium">+ {hasTasks ? "Select a task" : `${agentDisplayName} has no tasks yet`}+ </h3>+ <p className="text-xs text-muted-foreground">+ {hasTasks+ ? "Pick one from the left to see its brief and live transcript."+ : "When the CMO delegates work to this specialist, tasks will land here. Open the CMO and ask it to plan the next move."}+ </p>+ </div>+ </div>+ );+}++function formatRelative(iso: string): string {+ const t = Date.parse(iso);+ if (!Number.isFinite(t)) return "";+ const delta = Date.now() - t;+ const sec = Math.round(delta / 1000);+ if (sec < 60) return `${sec}s`;+ const min = Math.round(sec / 60);+ if (min < 60) return `${min}m`;+ const hr = Math.round(min / 60);+ if (hr < 24) return `${hr}h`;+ const day = Math.round(hr / 24);+ return `${day}d`;+}diff --git a/src/components/app-sidebar.tsx b/src/components/app-sidebar.tsxindex 2f6d51eb..ef1044d6 100644--- a/src/components/app-sidebar.tsx+++ b/src/components/app-sidebar.tsx@@ -27,6 +27,7 @@ import { listProjects } from "@/server/db/projects";import { getActiveProject } from "@/server/active-project";import { pendingApprovalCount } from "@/server/db/approvals";import { listProjectAgents } from "@/server/agent-meta";+import { inFlightCountsByAgent } from "@/server/db/tasks";import { ProjectSwitcher } from "./project-switcher";import { PairedOpenclawPill } from "./paired-openclaw-pill";import { AgentNav } from "./agent-nav";@@ -55,6 +56,12 @@ export async function AppSidebar() {const active = await getActiveProject();const approvalsBadge = active ? pendingApprovalCount(active.slug) : 0;const agentEntries = active ? await listProjectAgents(active.slug) : [];+ const inFlightCounts: Record<string, number> = {};+ if (active) {+ for (const [agentId, count] of inFlightCountsByAgent(active.slug)) {+ inFlightCounts[agentId] = count;+ }+ }return (<Sidebar collapsible="icon">@@ -92,6 +99,7 @@ export async function AppSidebar() {description: a.description,template_key: a.template_key,}))}+ inFlightCounts={inFlightCounts}/></SidebarGroupContent></SidebarGroup>diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsxnew file mode 100644index 00000000..2b7ecc5a--- /dev/null+++ b/src/components/live-transcript.tsx@@ -0,0 +1,507 @@+"use client";++import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { useRouter } from "next/navigation";+import {+ AlertCircle,+ CheckCircle2,+ Edit3,+ FileText,+ Globe,+ Loader2,+ Send,+ StopCircle,+ Terminal,+ Wrench,+ type LucideIcon,+} from "lucide-react";+import { toast } from "sonner";++import { Button } from "@/components/ui/button";+import { Markdown } from "@/components/markdown";+import { RunningDot } from "@/components/running-dot";+import { cn } from "@/lib/utils";+import { stripOrchestrationBlocks } from "@/server/orchestration/blocks";+import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";+import type { TaskStatus } from "@/types";++const POLL_INTERVAL_MS = 1_500;+const POLL_MAX_DURATION_MS = 10 * 60 * 1000;++const IN_FLIGHT_STATUSES: TaskStatus[] = ["proposed", "approved", "running"];++type Props = {+ agentSlug: string;+ agentDisplayName: string;+ taskId: string;+ taskStatus: TaskStatus;+ /** Server-rendered initial slice of the transcript. */+ initialEvents: TranscriptEvent[];+ /** Byte offset *after* `initialEvents` — polls start from here. */+ initialByteOffset: number;+ /** sessionId / sessionKey for the per-task chat thread, used by /api/chat. */+ sessionId: string;+ sessionKey: string;+};++export function LiveTranscript({+ agentSlug,+ agentDisplayName,+ taskId,+ taskStatus,+ initialEvents,+ initialByteOffset,+ sessionId,+ sessionKey,+}: Props) {+ const router = useRouter();+ const [events, setEvents] = useState<TranscriptEvent[]>(initialEvents);+ const [byteOffset, setByteOffset] = useState(initialByteOffset);+ const [status, setStatus] = useState<TaskStatus>(taskStatus);+ const [input, setInput] = useState("");+ const [sendingChat, setSendingChat] = useState(false);++ const scrollRef = useRef<HTMLDivElement>(null);+ const bottomSentinelRef = useRef<HTMLDivElement>(null);+ const stickyBottomRef = useRef(true);+ const startedAtRef = useRef<number | null>(null);++ const isInFlight = IN_FLIGHT_STATUSES.includes(status);++ // ── Auto-scroll: only when the user is already near the bottom. ─────+ function onScroll() {+ const el = scrollRef.current;+ if (!el) return;+ const remaining = el.scrollHeight - (el.scrollTop + el.clientHeight);+ stickyBottomRef.current = remaining < 96;+ }+ useLayoutEffect(() => {+ if (!stickyBottomRef.current) return;+ const el = scrollRef.current;+ if (!el) return;+ el.scrollTop = el.scrollHeight;+ }, [events, sendingChat]);++ // ── Live tail polling. Stops once the server reports `done: true`. ──+ const pollOnce = useCallback(async () => {+ try {+ const url = `/api/agents/${agentSlug}/tasks/${taskId}/transcript?offset=${byteOffset}`;+ const res = await fetch(url, { cache: "no-store" });+ if (!res.ok) return { stop: false };+ const data = (await res.json()) as {+ events: TranscriptEvent[];+ byteOffset: number;+ done: boolean;+ status: TaskStatus;+ };+ if (data.events.length > 0) {+ setEvents((prev) => [...prev, ...data.events]);+ }+ if (data.byteOffset !== byteOffset) setByteOffset(data.byteOffset);+ if (data.status !== status) {+ setStatus(data.status);+ // Status flipped — refresh the rest of the page (task list pills,+ // status badge in the brief header). Cheaper than a full reload.+ router.refresh();+ }+ return { stop: data.done };+ } catch {+ return { stop: false };+ }+ }, [agentSlug, byteOffset, router, status, taskId]);++ useEffect(() => {+ if (!isInFlight) return;+ if (startedAtRef.current === null) startedAtRef.current = Date.now();+ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | null = null;++ const tick = async () => {+ if (cancelled) return;+ const elapsed = Date.now() - (startedAtRef.current ?? Date.now());+ if (elapsed > POLL_MAX_DURATION_MS) return;+ const { stop } = await pollOnce();+ if (cancelled || stop) return;+ timer = setTimeout(tick, POLL_INTERVAL_MS);+ };++ timer = setTimeout(tick, POLL_INTERVAL_MS);+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [isInFlight, pollOnce]);++ // ── Pair tool_call with its eventual tool_result so they render as ONE row.+ const rendered = useMemo(() => collapseToolPairs(events), [events]);++ // ── Composer: enabled only when the task isn't actively in flight. ──+ async function send() {+ const text = input.trim();+ if (!text || sendingChat) return;+ setInput("");+ setSendingChat(true);+ try {+ // Pipe through /api/chat exactly like AgentChat does — the response+ // streams to the JSONL we're already tailing, so the new turn lands+ // automatically once polling resumes (which we kick off below by+ // letting the task status flip back to running via the server).+ const res = await fetch("/api/chat", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ message: text,+ agent: agentSlug,+ sessionId,+ sessionKey,+ }),+ });+ if (!res.ok || !res.body) {+ const err = await res.text();+ throw new Error(err || `HTTP ${res.status}`);+ }+ // Drain the SSE stream so the gateway run completes; we don't need+ // to render its events here (the JSONL tail will pick everything up+ // on the next poll). We just have to consume the body so the agent+ // turn doesn't stall on backpressure.+ const reader = res.body.getReader();+ while (true) {+ const { done } = await reader.read();+ if (done) break;+ }+ // After the turn closes, prompt a re-poll so the new transcript bytes+ // show up immediately instead of waiting for the next tick.+ void pollOnce();+ } catch (err) {+ toast.error(err instanceof Error ? err.message : "Send failed");+ } finally {+ setSendingChat(false);+ }+ }++ return (+ <div className="flex h-full flex-col">+ <div+ ref={scrollRef}+ onScroll={onScroll}+ className="min-h-0 flex-1 overflow-y-auto"+ role="log"+ aria-live="polite"+ >+ <div className="mx-auto w-full max-w-3xl px-6 py-6">+ {rendered.length === 0 ? (+ <TranscriptEmptyState+ status={status}+ agentDisplayName={agentDisplayName}+ />+ ) : (+ <ol className="space-y-4">+ {rendered.map((item) => (+ <li key={item.key}>+ <RenderItem+ item={item}+ agentDisplayName={agentDisplayName}+ />+ </li>+ ))}+ </ol>+ )}+ {isInFlight && <ThinkingPulse agentDisplayName={agentDisplayName} />}+ <div ref={bottomSentinelRef} />+ </div>+ </div>++ <div className="border-t bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80">+ <div className="mx-auto w-full max-w-3xl px-6 py-3">+ <form+ className="flex items-end gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ void send();+ }}+ >+ <textarea+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ void send();+ }+ }}+ disabled={isInFlight || sendingChat}+ placeholder={+ isInFlight+ ? `${agentDisplayName} is working — the transcript updates live`+ : `Message ${agentDisplayName}…`+ }+ rows={1}+ className="flex min-h-[40px] flex-1 resize-none rounded-xl border bg-background px-3.5 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"+ />+ <Button+ type="submit"+ size="sm"+ disabled={isInFlight || sendingChat || !input.trim()}+ className="h-10 rounded-xl"+ >+ {sendingChat ? (+ <StopCircle className="size-4" />+ ) : (+ <Send className="size-4" />+ )}+ <span className="sr-only">Send</span>+ </Button>+ </form>+ <p className="pt-1.5 text-center text-[10px] text-muted-foreground">+ {isInFlight ? (+ <span className="inline-flex items-center gap-1.5">+ <RunningDot size="sm" aria-label="" />+ Live · polling every {Math.round(POLL_INTERVAL_MS / 1000)}s+ </span>+ ) : (+ <>Enter to send · Shift+Enter for newline</>+ )}+ </p>+ </div>+ </div>+ </div>+ );+}++// ── Rendering helpers ──────────────────────────────────────────────────++type RenderedItem =+ | { kind: "user_message"; key: string; body: string }+ | { kind: "assistant_text"; key: string; body: string }+ | {+ kind: "tool";+ key: string;+ name: string;+ label: string | null;+ result: string | null;+ ok: boolean;+ done: boolean;+ }+ | { kind: "system_unknown"; key: string; raw_type: string };++/**+ * The on-disk JSONL writes `toolCall` and `toolResult` as separate parts.+ * Pair them up so the UI shows a single row that flips from spinner to+ * check (mirrors AgentChat's StepList behavior).+ */+function collapseToolPairs(events: TranscriptEvent[]): RenderedItem[] {+ const out: RenderedItem[] = [];+ const callIndex = new Map<string, number>();+ for (const e of events) {+ if (e.kind === "tool_call") {+ callIndex.set(e.tool_call_id, out.length);+ out.push({+ kind: "tool",+ key: e.id,+ name: e.name,+ label: e.label,+ result: null,+ ok: true,+ done: false,+ });+ continue;+ }+ if (e.kind === "tool_result") {+ const idx = callIndex.get(e.tool_call_id);+ if (idx != null) {+ const prev = out[idx];+ if (prev && prev.kind === "tool") {+ out[idx] = {+ ...prev,+ result: e.summary,+ ok: e.ok,+ done: true,+ };+ continue;+ }+ }+ // Orphan result (no matching call earlier in the buffer) — render+ // standalone so the user still sees something.+ out.push({+ kind: "tool",+ key: e.id,+ name: e.name,+ label: null,+ result: e.summary,+ ok: e.ok,+ done: true,+ });+ continue;+ }+ if (e.kind === "user_message") {+ out.push({ kind: "user_message", key: e.id, body: e.body });+ continue;+ }+ if (e.kind === "assistant_text") {+ out.push({ kind: "assistant_text", key: e.id, body: e.body });+ continue;+ }+ if (e.kind === "unknown") {+ out.push({ kind: "system_unknown", key: e.id, raw_type: e.raw_type });+ continue;+ }+ }+ return out;+}++function RenderItem({+ item,+ agentDisplayName: _agentDisplayName,+}: {+ item: RenderedItem;+ agentDisplayName: string;+}) {+ if (item.kind === "user_message") {+ // Kickoff messages (the task brief + operating protocol that+ // buildTaskKickoffMessage produces, or FIRST_TURN session opens) are+ // technically user-role rows in OpenClaw, but they're system-injected+ // not user-typed. Collapse them so the transcript reads as "agent+ // acknowledged + did the work", not "USER DUMPED 30 LINES OF XML".+ const isKickoff =+ item.body.startsWith("(task assignment)") ||+ item.body.startsWith("(session start)") ||+ item.body.startsWith("TASK_BRIEF") ||+ item.body.startsWith("FIRST_TURN");+ if (isKickoff) {+ return <KickoffBlock body={item.body} />;+ }+ return (+ <div className="flex justify-end">+ <div className="max-w-[85%] rounded-2xl bg-muted px-4 py-2 text-sm leading-relaxed whitespace-pre-wrap break-words">+ {item.body}+ </div>+ </div>+ );+ }+ if (item.kind === "assistant_text") {+ // Same orchestration-tag stripping the live chat applies — keeps the+ // raw <task_status>…</task_status>, <create_task>…</create_task> XML+ // out of the user-facing transcript. The structured outcome already+ // lives in the task DB row.+ const cleanBody = stripOrchestrationBlocks(item.body);+ if (cleanBody.trim() === "") return null;+ return (+ <div className="text-sm leading-relaxed">+ <Markdown>{cleanBody}</Markdown>+ </div>+ );+ }+ if (item.kind === "tool") {+ return <ToolRow item={item} />;+ }+ // Unknown / system rows render as a thin divider so the eye can scan past.+ return null;+}++function KickoffBlock({ body }: { body: string }) {+ // Show the task brief as a collapsed system block — full text visible but+ // visually demoted so it doesn't dominate the transcript.+ return (+ <details className="group rounded-md border border-dashed border-muted-foreground/30 bg-muted/20 px-3 py-2 text-xs">+ <summary className="flex cursor-pointer items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-muted-foreground select-none">+ <span aria-hidden>›</span>+ Task brief sent to agent+ </summary>+ <pre className="mt-2 whitespace-pre-wrap break-words font-mono text-[11px] text-muted-foreground">+ {body}+ </pre>+ </details>+ );+}++function ToolRow({+ item,+}: {+ item: Extract<RenderedItem, { kind: "tool" }>;+}) {+ const Icon = iconForTool(item.name);+ const StatusIcon = item.done+ ? item.ok+ ? CheckCircle2+ : AlertCircle+ : Loader2;+ const statusClass = item.done+ ? item.ok+ ? "text-emerald-600"+ : "text-destructive"+ : "text-muted-foreground motion-safe:animate-spin";+ return (+ <div className="space-y-1 rounded-md border bg-muted/30 px-3 py-2">+ <div className="flex items-center gap-2 text-xs">+ <StatusIcon className={cn("size-3.5 shrink-0", statusClass)} />+ <Icon className="size-3.5 shrink-0 text-muted-foreground" />+ <span className="font-mono text-[11px] font-medium text-foreground">+ {item.name}+ </span>+ {item.label && (+ <span className="truncate font-mono text-[11px] text-muted-foreground">+ {item.label}+ </span>+ )}+ </div>+ {item.done && item.result && (+ <div className="pl-6 font-mono text-[11px] text-muted-foreground/90">+ <span className="text-[10px] uppercase tracking-[0.18em]">+ {item.ok ? "→ result" : "→ error"}+ </span>{" "}+ <span className="break-words">{item.result}</span>+ </div>+ )}+ </div>+ );+}++function ThinkingPulse({ agentDisplayName }: { agentDisplayName: string }) {+ return (+ <div className="mt-4 flex items-center gap-2 text-xs italic text-muted-foreground">+ <RunningDot size="sm" aria-label="" />+ {agentDisplayName} is working…+ </div>+ );+}++function TranscriptEmptyState({+ status,+ agentDisplayName,+}: {+ status: TaskStatus;+ agentDisplayName: string;+}) {+ if (status === "proposed") {+ return (+ <div className="py-12 text-center text-sm text-muted-foreground">+ Waiting for {agentDisplayName} to pick this up. Hit{" "}+ <span className="font-mono text-xs">Start all</span> on the agent tasks+ page, or open this task to kick it off.+ </div>+ );+ }+ return (+ <div className="py-12 text-center text-sm text-muted-foreground">+ No transcript yet. Send a message below to start the conversation.+ </div>+ );+}++function iconForTool(name: string): LucideIcon {+ const n = name.toLowerCase();+ if (n === "exec" || n === "shell" || n === "bash" || n.includes("bash"))+ return Terminal;+ if (n === "read" || n === "cat" || n === "open" || n.includes("read"))+ return FileText;+ if (n === "write" || n === "edit" || n === "patch") return Edit3;+ if (n === "fetch" || n.includes("http") || n.includes("web")) return Globe;+ return Wrench;+}diff --git a/src/components/running-dot.tsx b/src/components/running-dot.tsxnew file mode 100644index 00000000..e179c749--- /dev/null+++ b/src/components/running-dot.tsx@@ -0,0 +1,38 @@+import { cn } from "@/lib/utils";++/**+ * Pulsing dot that signals "in flight, watch this." Sky/blue tone is reserved+ * for liveness so it doesn't collide with success/destructive badges.+ *+ * Size: `sm` for inline-with-text, `md` for status rails in lists.+ */+export function RunningDot({+ size = "sm",+ className,+ "aria-label": ariaLabel = "Running",+}: {+ size?: "sm" | "md";+ className?: string;+ "aria-label"?: string;+}) {+ const px = size === "md" ? "h-2.5 w-2.5" : "h-2 w-2";+ return (+ <span+ role="status"+ aria-label={ariaLabel}+ className={cn("relative inline-flex", px, className)}+ >+ <span+ aria-hidden+ className={cn(+ "absolute inset-0 inline-flex rounded-full bg-sky-400 opacity-60",+ "motion-safe:animate-ping",+ )}+ />+ <span+ aria-hidden+ className={cn("relative inline-flex rounded-full bg-sky-500", px)}+ />+ </span>+ );+}diff --git a/src/components/task-live-poller.test.tsx b/src/components/task-live-poller.test.tsxdeleted file mode 100644index 270bebb1..00000000--- a/src/components/task-live-poller.test.tsx+++ /dev/null@@ -1,79 +0,0 @@-// @vitest-environment jsdom-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, render } from "@testing-library/react";--const refreshMock = vi.fn();-vi.mock("next/navigation", () => ({- useRouter: () => ({ refresh: refreshMock }),-}));--import { TaskLivePoller } from "./task-live-poller";--describe("TaskLivePoller", () => {- beforeEach(() => {- vi.useFakeTimers();- refreshMock.mockClear();- });-- afterEach(() => {- cleanup();- vi.useRealTimers();- });-- it("polls router.refresh while status is running", () => {- render(<TaskLivePoller status="running" />);- expect(refreshMock).not.toHaveBeenCalled();- vi.advanceTimersByTime(3_000);- expect(refreshMock).toHaveBeenCalledTimes(1);- vi.advanceTimersByTime(3_000);- expect(refreshMock).toHaveBeenCalledTimes(2);- vi.advanceTimersByTime(6_000);- expect(refreshMock).toHaveBeenCalledTimes(4);- });-- it("polls while status is proposed (kickoff in flight)", () => {- render(<TaskLivePoller status="proposed" />);- vi.advanceTimersByTime(3_000);- expect(refreshMock).toHaveBeenCalledTimes(1);- });-- it("does NOT poll once status is succeeded", () => {- render(<TaskLivePoller status="succeeded" />);- vi.advanceTimersByTime(15_000);- expect(refreshMock).not.toHaveBeenCalled();- });-- it("does NOT poll for failed task", () => {- render(<TaskLivePoller status="failed" />);- vi.advanceTimersByTime(15_000);- expect(refreshMock).not.toHaveBeenCalled();- });-- it("does NOT poll for cancelled task", () => {- render(<TaskLivePoller status="cancelled" />);- vi.advanceTimersByTime(15_000);- expect(refreshMock).not.toHaveBeenCalled();- });-- it("stops polling after the 10-minute cap so a stuck agent doesn't burn cycles forever", () => {- render(<TaskLivePoller status="running" />);- // 10 minutes = 600,000 ms = 200 ticks at 3s- vi.advanceTimersByTime(11 * 60 * 1000);- const callsAtCap = refreshMock.mock.calls.length;- // Advance another minute — count should not grow.- vi.advanceTimersByTime(60_000);- expect(refreshMock).toHaveBeenCalledTimes(callsAtCap);- // And the cap kicks in around 200 calls, not a 100x runaway.- expect(callsAtCap).toBeLessThan(220);- });-- it("tears down the interval when the component unmounts", () => {- const { unmount } = render(<TaskLivePoller status="running" />);- vi.advanceTimersByTime(3_000);- expect(refreshMock).toHaveBeenCalledTimes(1);- unmount();- vi.advanceTimersByTime(30_000);- // No further refreshes after unmount.- expect(refreshMock).toHaveBeenCalledTimes(1);- });-});diff --git a/src/components/task-live-poller.tsx b/src/components/task-live-poller.tsxdeleted file mode 100644index 77e70224..00000000--- a/src/components/task-live-poller.tsx+++ /dev/null@@ -1,49 +0,0 @@-"use client";--import { useEffect, useRef } from "react";-import { useRouter } from "next/navigation";--import type { TaskStatus } from "@/types";--/**- * While the task is in flight (status: running or proposed-with-thread),- * refresh the page every few seconds so the user sees the agent's- * progress (status flips, activity log, persisted transcript) without- * having to hit the reload button. Server components re-render on- * router.refresh; the AgentChat client component is keyed on the- * statusKey prop so it remounts exactly once when status flips to a- * terminal state — that pulls in the agent's final reply from JSONL.- *- * Cap polling at 10 minutes per mount so we don't burn cycles if the- * agent gets stuck. The page can be reloaded manually after that.- */-const POLL_INTERVAL_MS = 3_000;-const POLL_MAX_DURATION_MS = 10 * 60 * 1000;--const POLL_STATUSES: TaskStatus[] = ["running", "proposed", "approved"];--export function TaskLivePoller({ status }: { status: TaskStatus }) {- const router = useRouter();- const startedAtRef = useRef<number | null>(null);-- useEffect(() => {- // Only poll while the task is in an in-flight state. As soon as it- // flips to done/failed/cancelled, the effect's cleanup tears down- // the interval.- if (!POLL_STATUSES.includes(status)) return;- if (startedAtRef.current === null) startedAtRef.current = Date.now();-- const interval = setInterval(() => {- const elapsed = Date.now() - (startedAtRef.current ?? Date.now());- if (elapsed > POLL_MAX_DURATION_MS) {- clearInterval(interval);- return;- }- router.refresh();- }, POLL_INTERVAL_MS);-- return () => clearInterval(interval);- }, [status, router]);-- return null;-}diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.tsindex 64e7244c..2231ab33 100644--- a/src/server/db/tasks.ts+++ b/src/server/db/tasks.ts@@ -111,6 +111,29 @@ export function listTasksByAgent(agent_id: string, status?: TaskStatus): Task[].all(agent_id) as Task[];}+/**+ * Map of `agent_id → in-flight task count` for a single project. Drives the+ * sidebar's per-agent live-task badge. "In flight" means proposed (kickoff+ * pending), approved, or running. Terminal states (succeeded/failed/cancelled)+ * never count.+ */+export function inFlightCountsByAgent(+ project_slug: string,+): Map<string, number> {+ const db = getDb();+ const rows = db+ .prepare(+ `SELECT agent_id, COUNT(*) as count+ FROM tasks+ WHERE project_slug = ? AND status IN ('proposed', 'approved', 'running')+ GROUP BY agent_id`,+ )+ .all(project_slug) as Array<{ agent_id: string; count: number }>;+ const map = new Map<string, number>();+ for (const r of rows) map.set(r.agent_id, r.count);+ return map;+}+export type UpdateTaskInput = {status?: TaskStatus;result?: unknown;diff --git a/src/server/openclaw/transcript-tail.ts b/src/server/openclaw/transcript-tail.tsnew file mode 100644index 00000000..b9154aa7--- /dev/null+++ b/src/server/openclaw/transcript-tail.ts@@ -0,0 +1,289 @@+import { existsSync, readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";+import { findSessionBySessionId } from "@/server/openclaw/sessions";++const OPENCLAW_HOME = process.env.OPENCLAW_HOME ?? join(homedir(), ".openclaw");++export type TranscriptEvent =+ | { kind: "user_message"; id: string; ts: number; body: string }+ | {+ kind: "assistant_text";+ id: string;+ ts: number;+ body: string;+ }+ | {+ kind: "tool_call";+ id: string;+ ts: number;+ tool_call_id: string;+ name: string;+ label: string | null;+ }+ | {+ kind: "tool_result";+ id: string;+ ts: number;+ tool_call_id: string;+ name: string;+ summary: string | null;+ ok: boolean;+ }+ | { kind: "unknown"; id: string; ts: number; raw_type: string };++type RawMessageContentPart =+ | { type: "text"; text?: string }+ | {+ type: "toolCall";+ id?: string;+ name?: string;+ arguments?: Record<string, unknown>;+ input?: Record<string, unknown>;+ }+ | {+ type: "toolResult";+ toolCallId?: string;+ tool_call_id?: string;+ name?: string;+ content?: unknown;+ output?: unknown;+ isError?: boolean;+ is_error?: boolean;+ }+ | string;++type RawMessage = {+ role?: string;+ content?: string | RawMessageContentPart[];+ timestamp?: number;+};++type RawEntry = {+ type?: string;+ id?: string;+ timestamp?: string | number;+ message?: RawMessage;+};++function sessionJsonlPath(agentFullId: string, sessionId: string): string {+ return join(+ OPENCLAW_HOME,+ "agents",+ agentFullId,+ "sessions",+ `${sessionId}.jsonl`,+ );+}++/** Resolve URL threadId (label) → on-disk transcript file path. */+export function resolveTranscriptPath(+ agentFullId: string,+ threadId: string,+): string | null {+ const session = findSessionBySessionId(agentFullId, threadId);+ if (!session) return null;+ const path = sessionJsonlPath(agentFullId, session.sessionId);+ if (!existsSync(path)) return null;+ return path;+}++/**+ * Read the JSONL transcript from `byteOffset` to EOF, parse new lines into+ * structured events the client can render. Returns the new byte offset so the+ * caller can stitch incremental polls together without re-reading prior bytes.+ *+ * Returns `{ events: [], byteOffset, fileSize }` when the file doesn't exist+ * yet or no new bytes are available — caller treats it as a no-op.+ */+export function readTranscriptTail(+ agentFullId: string,+ threadId: string,+ byteOffset: number,+): { events: TranscriptEvent[]; byteOffset: number; fileSize: number } {+ const path = resolveTranscriptPath(agentFullId, threadId);+ if (!path) return { events: [], byteOffset, fileSize: 0 };++ let size: number;+ try {+ size = statSync(path).size;+ } catch {+ return { events: [], byteOffset, fileSize: 0 };+ }++ // Defensive: if the file got truncated/rotated, reset to 0.+ if (byteOffset > size) byteOffset = 0;+ if (byteOffset === size) return { events: [], byteOffset, fileSize: size };++ let raw: string;+ try {+ const buf = readFileSync(path);+ raw = buf.slice(byteOffset).toString("utf8");+ } catch {+ return { events: [], byteOffset, fileSize: size };+ }++ // Only consume up to the last newline; whatever's after is a partial line+ // the writer is still flushing. Leave its bytes unconsumed by reporting an+ // offset that points right after the last complete line.+ const lastNl = raw.lastIndexOf("\n");+ const consumable = lastNl < 0 ? "" : raw.slice(0, lastNl + 1);+ const newByteOffset = byteOffset + Buffer.byteLength(consumable, "utf8");++ const events: TranscriptEvent[] = [];+ let lineIdx = 0;+ for (const line of consumable.split("\n")) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ let entry: RawEntry;+ try {+ entry = JSON.parse(trimmed) as RawEntry;+ } catch {+ continue;+ }+ const baseId = `${entry.id ?? "anon"}-${lineIdx++}`;+ const ts =+ typeof entry.timestamp === "string"+ ? Date.parse(entry.timestamp)+ : typeof entry.timestamp === "number"+ ? entry.timestamp+ : 0;++ if (entry.type !== "message") {+ // Session metadata, model-config rows, etc. Surface as a faint+ // "unknown" event the client can hide unless verbose mode is on.+ events.push({ kind: "unknown", id: baseId, ts, raw_type: entry.type ?? "?" });+ continue;+ }+ const msg = entry.message;+ if (!msg) continue;++ if (msg.role === "user") {+ const body = extractUserText(msg.content);+ if (!body) continue;+ events.push({ kind: "user_message", id: baseId, ts, body });+ continue;+ }+ if (msg.role !== "assistant") continue;++ // Assistant: content is an array of parts. Each part becomes one event.+ const parts = Array.isArray(msg.content) ? msg.content : [];+ let partIdx = 0;+ for (const part of parts) {+ const partId = `${baseId}:${partIdx++}`;+ if (typeof part === "string") {+ if (part.trim()) {+ events.push({ kind: "assistant_text", id: partId, ts, body: part });+ }+ continue;+ }+ if (part?.type === "text") {+ const text = (part.text ?? "").trim();+ if (text) {+ events.push({ kind: "assistant_text", id: partId, ts, body: text });+ }+ continue;+ }+ if (part?.type === "toolCall") {+ const callId = part.id ?? partId;+ const name = part.name ?? "tool";+ const label = formatToolLabel(name, part.arguments ?? part.input);+ events.push({+ kind: "tool_call",+ id: partId,+ ts,+ tool_call_id: callId,+ name,+ label,+ });+ continue;+ }+ if (part?.type === "toolResult") {+ const callId = part.toolCallId ?? part.tool_call_id ?? partId;+ const name = part.name ?? "tool";+ const ok = !(part.isError ?? part.is_error ?? false);+ const summary = summarizeToolResult(part.content ?? part.output);+ events.push({+ kind: "tool_result",+ id: partId,+ ts,+ tool_call_id: callId,+ name,+ summary,+ ok,+ });+ continue;+ }+ }+ }++ return { events, byteOffset: newByteOffset, fileSize: size };+}++function extractUserText(content: RawMessage["content"]): string {+ if (typeof content === "string") return stripUserTimestampPrefix(content);+ if (!Array.isArray(content)) return "";+ const out: string[] = [];+ for (const c of content) {+ if (typeof c === "string") out.push(c);+ else if (c?.type === "text" && typeof c.text === "string") out.push(c.text);+ }+ return stripUserTimestampPrefix(out.join("\n").trim());+}++function stripUserTimestampPrefix(s: string): string {+ return s.replace(+ /^\[[A-Z][a-z]{2} \d{4}-\d{2}-\d{2} \d{2}:\d{2} [A-Z]{2,5}\] ?/,+ "",+ );+}++function formatToolLabel(+ name: string,+ args: Record<string, unknown> | undefined,+): string | null {+ if (!args) return null;+ // Pick the most informative single field from common tool shapes.+ if (typeof args.command === "string") return shortenLine(args.command);+ if (typeof args.path === "string") return args.path;+ if (typeof args.file_path === "string") return args.file_path;+ if (typeof args.url === "string") return args.url;+ if (typeof args.query === "string") return shortenLine(args.query);+ if (typeof args.pattern === "string") return args.pattern;+ // MCP tools tend to use namespaced names; fall back to a JSON preview.+ try {+ return shortenLine(JSON.stringify(args));+ } catch {+ return null;+ }+}++function summarizeToolResult(content: unknown): string | null {+ if (content == null) return null;+ if (typeof content === "string") return shortenLine(content);+ if (Array.isArray(content)) {+ const text = content+ .map((c) => {+ if (typeof c === "string") return c;+ if (c && typeof c === "object" && "text" in c)+ return String((c as { text?: string }).text ?? "");+ return "";+ })+ .filter(Boolean)+ .join("\n");+ return shortenLine(text);+ }+ if (typeof content === "object") {+ try {+ return shortenLine(JSON.stringify(content));+ } catch {+ return null;+ }+ }+ return null;+}++function shortenLine(s: string, max = 140): string {+ const flat = s.replace(/\s+/g, " ").trim();+ return flat.length > max ? flat.slice(0, max - 1) + "…" : flat;+}diff --git a/src/server/orchestration/run-task.ts b/src/server/orchestration/run-task.tsindex cc947bbb..78864467 100644--- a/src/server/orchestration/run-task.ts+++ b/src/server/orchestration/run-task.ts@@ -8,6 +8,28 @@ import type { Task } from "@/types";import { generateTaskThreadId, processOrchestrationBlocks } from "./process-blocks";import { buildTaskKickoffMessage } from "./task-kickoff";+/**+ * Idempotent "claim and kickoff" — flips a proposed task to running and+ * fires the server-side kickoff. No-op when the task isn't proposed (already+ * started, already done, etc.). Used by the agent workspace so opening a+ * proposed task auto-starts it the same way "Start all" does for batches,+ * without bouncing through the chat client.+ *+ * Returns the post-transition task (still proposed if no claim happened, or+ * running on success). The kickoff itself runs fire-and-forget — callers+ * shouldn't await it; the workspace's live transcript polling will reveal+ * progress.+ */+export function startTaskIfProposed(task: Task): Task {+ if (task.status !== "proposed") return task;+ const claimed = updateTask(task.id, { status: "running" });+ if (!claimed) return task;+ void runTaskKickoffServerSide(claimed).catch((err) => {+ console.error("[start-task] kickoff failed:", err);+ });+ return claimed;+}+/*** Server-side kickoff for a task. Consumes the full gateway stream (no SSE* pipe to a client) and applies orchestration blocks the assignee emits.diff --git a/src/server/orchestration/thread-history.test.ts b/src/server/orchestration/thread-history.test.tsindex e769f5ed..3a9171bf 100644--- a/src/server/orchestration/thread-history.test.ts+++ b/src/server/orchestration/thread-history.test.ts@@ -1,7 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import type { Task } from "@/types";-const findSessionBySessionIdMock = vi.fn();const loadSessionHistoryMock = vi.fn();vi.mock("@/server/openclaw/sessions", () => ({@@ -13,24 +11,7 @@ vi.mock("@/server/openclaw/sessions", () => ({`agent:${agentFullId}:${threadId}`,}));-import { loadThreadHistory, shouldAutoKickoffTask } from "./thread-history";--const baseTask: Task = {- id: "task-1",- project_slug: "demo",- agent_id: "demo-google-ads",- title: "Install conv tracking",- brief: "Do it.",- success_criteria: null,- deadline_iso: null,- status: "proposed",- result_json: null,- error_message: null,- thread_id: "thread-abc",- assigner_agent_id: "demo-cmo",- created_at: "now",- updated_at: "now",-};+import { loadThreadHistory } from "./thread-history";describe("loadThreadHistory", () => {beforeEach(() => {@@ -79,41 +60,3 @@ describe("loadThreadHistory", () => {expect(loadSessionHistoryMock).not.toHaveBeenCalled();});});--describe("shouldAutoKickoffTask", () => {- it("fires for proposed task with empty history (happy path)", () => {- expect(shouldAutoKickoffTask({ ...baseTask, status: "proposed" }, [])).toBe(true);- });-- it("does NOT fire for proposed task with existing history (resume case)", () => {- expect(- shouldAutoKickoffTask({ ...baseTask, status: "proposed" }, [- { id: "0", role: "user", body: "...", timestamp: 1 },- ]),- ).toBe(false);- });-- it("does NOT fire for succeeded task even with empty history (REGRESSION — task re-trigger bug)", () => {- // The bug the user reported: clicking a succeeded task re-triggered- // the agent. Root cause was loadThreadHistory returning [] (separate- // bug, fixed above). This guard is defense-in-depth so even if- // history loading regresses again, a succeeded task never re-runs.- expect(shouldAutoKickoffTask({ ...baseTask, status: "succeeded" }, [])).toBe(false);- });-- it("does NOT fire for running task (agent is already at work — or stalled, user retries explicitly)", () => {- expect(shouldAutoKickoffTask({ ...baseTask, status: "running" }, [])).toBe(false);- });-- it("does NOT fire for failed task (no implicit auto-retry; user must explicitly restart)", () => {- expect(shouldAutoKickoffTask({ ...baseTask, status: "failed" }, [])).toBe(false);- });-- it("does NOT fire for cancelled task", () => {- expect(shouldAutoKickoffTask({ ...baseTask, status: "cancelled" }, [])).toBe(false);- });-- it("does NOT fire for approved task (in v1.1 the post-approval kickoff will be triggered explicitly)", () => {- expect(shouldAutoKickoffTask({ ...baseTask, status: "approved" }, [])).toBe(false);- });-});diff --git a/src/server/orchestration/thread-history.ts b/src/server/orchestration/thread-history.tsindex 79261742..77fc2adf 100644--- a/src/server/orchestration/thread-history.ts+++ b/src/server/orchestration/thread-history.ts@@ -31,25 +31,3 @@ export function loadThreadHistory(return { sessionKey, history };}-import type { Task } from "@/types";--/**- * Defense-in-depth guard for the per-task auto-kickoff. We only fire the- * hidden kickoff when:- * 1. The task is still proposed (hasn't started yet), AND- * 2. The thread has no history (the agent hasn't sent any reply).- *- * The status guard is the load-bearing one — even if history loading- * regresses (the bug that caused this helper to exist), a succeeded task- * still never auto-re-fires. The history guard catches the rarer case of- * a proposed task whose first kickoff already wrote a partial reply- * before crashing.- */-export function shouldAutoKickoffTask(- task: Task,- history: ChatMessage[],-): boolean {- if (task.status !== "proposed") return false;- if (history.length > 0) return false;- return true;-}