Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(orchestration): agent Tasks tab with Start-All button

Yuting Zhonge8ed990615d6
diff --git a/src/app/(app)/agents/[agent]/tasks/page.tsx b/src/app/(app)/agents/[agent]/tasks/page.tsx
new file mode 100644
index 00000000..15b57e39
--- /dev/null
+++ b/src/app/(app)/agents/[agent]/tasks/page.tsx
@@ -0,0 +1,141 @@
+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 { 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",
+};
+
+export default async function AgentTasksPage({
+ params,
+}: {
+ params: Promise<{ agent: string }>;
+}) {
+ const { agent: agentSlug } = await params;
+ const project = await getActiveProject();
+ if (!project) {
+ return (
+ <div className="mx-auto max-w-md p-6 pt-12 text-sm text-muted-foreground">
+ Select a project to view this agent&rsquo;s tasks.
+ </div>
+ );
+ }
+
+ const resolved = await resolveAgentBySlug(project.slug, agentSlug);
+ if (!resolved) notFound();
+
+ const agentFullId = resolved.agent_id;
+ 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} &middot; 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>
+ );
+}
diff --git a/src/components/agent-tabs.tsx b/src/components/agent-tabs.tsx
index 8da8da94..57a31422 100644
--- a/src/components/agent-tabs.tsx
+++ b/src/components/agent-tabs.tsx
@@ -2,7 +2,7 @@
import Link from "next/link";
import { usePathname } from "next/navigation";
-import { MessageSquare, FileText, Sparkles, Clock, Settings } from "lucide-react";
+import { MessageSquare, FileText, Sparkles, Clock, Settings, ListChecks } from "lucide-react";
import { cn } from "@/lib/utils";
type Tab = {
@@ -13,6 +13,7 @@ type Tab = {
const TABS: Tab[] = [
{ key: "chat", label: "Chat", icon: MessageSquare },
+ { key: "tasks", label: "Tasks", icon: ListChecks },
{ key: "files", label: "Files", icon: FileText },
{ key: "skills", label: "Skills", icon: Sparkles },
{ key: "cron", label: "Cron", icon: Clock },
diff --git a/src/components/start-all-tasks-button.tsx b/src/components/start-all-tasks-button.tsx
new file mode 100644
index 00000000..13cb635e
--- /dev/null
+++ b/src/components/start-all-tasks-button.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { Loader2, Play } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { startAllProposedTasksAction } from "@/server/actions/tasks";
+
+/**
+ * Kicks off every proposed task for an agent in one click. Server action
+ * marks tasks running and fires background kickoffs; this button then
+ * starts a short polling loop (router.refresh every 3s for 2 minutes) so
+ * the user sees status flip from proposed → running → succeeded as each
+ * agent run finishes, without staring at a stale page.
+ */
+export function StartAllTasksButton({
+ agentId,
+ proposedCount,
+}: {
+ agentId: string;
+ proposedCount: number;
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const [polling, setPolling] = useState(false);
+
+ async function onClick() {
+ startTransition(async () => {
+ const result = await startAllProposedTasksAction(agentId);
+ if (!result.ok) {
+ toast.error(result.error);
+ return;
+ }
+ if (result.data.started === 0) {
+ toast.info("No proposed tasks to start.");
+ return;
+ }
+ toast.success(
+ `Started ${result.data.started} task${result.data.started === 1 ? "" : "s"}.`,
+ );
+ router.refresh();
+ // Poll for ~2 minutes so the page reflects status flips without the
+ // user needing to refresh manually. Long enough for most tasks (3 ×
+ // 30-60s each) but bounded so we don't burn cycles forever.
+ setPolling(true);
+ const intervalId = setInterval(() => router.refresh(), 3_000);
+ const timeoutId = setTimeout(() => {
+ clearInterval(intervalId);
+ setPolling(false);
+ }, 120_000);
+ // Belt + suspenders cleanup if component unmounts (rare here).
+ void timeoutId;
+ });
+ }
+
+ const disabled = pending || polling || proposedCount === 0;
+ const label = polling
+ ? "Working…"
+ : pending
+ ? "Starting…"
+ : `Start all ${proposedCount} task${proposedCount === 1 ? "" : "s"}`;
+
+ return (
+ <Button onClick={onClick} disabled={disabled} size="sm">
+ {pending || polling ? (
+ <Loader2 className="mr-1.5 size-3.5 animate-spin" />
+ ) : (
+ <Play className="mr-1.5 size-3.5" />
+ )}
+ {label}
+ </Button>
+ );
+}
diff --git a/src/server/actions/tasks.ts b/src/server/actions/tasks.ts
new file mode 100644
index 00000000..0a3b2e03
--- /dev/null
+++ b/src/server/actions/tasks.ts
@@ -0,0 +1,69 @@
+"use server";
+
+import { revalidatePath } from "next/cache";
+
+import { getActiveProject } from "@/server/active-project";
+import { listTasksByAgent, updateTask } from "@/server/db/tasks";
+import { runTaskKickoffServerSide } from "@/server/orchestration/run-task";
+
+export type StartAllResult =
+ | { ok: true; data: { started: number; task_ids: string[] } }
+ | { ok: false; error: string };
+
+/**
+ * Start all proposed tasks for an agent. Marks each as running, then fires
+ * a server-side kickoff per task (fire-and-forget). The kickoffs run the
+ * agent against each task in parallel using the shared OpenClaw gateway;
+ * the action returns as soon as kickoffs are scheduled so the UI can
+ * refresh without blocking on agent completion.
+ *
+ * Polling: the page is server-rendered, so the caller should run
+ * router.refresh() periodically to see status flip from proposed →
+ * running → succeeded as each kickoff finishes.
+ */
+export async function startAllProposedTasksAction(
+ agentId: string,
+): Promise<StartAllResult> {
+ if (!agentId.trim()) return { ok: false, error: "agentId is required" };
+ const project = await getActiveProject();
+ if (!project) return { ok: false, error: "No active project." };
+
+ const proposed = listTasksByAgent(agentId, "proposed");
+ if (proposed.length === 0) {
+ return { ok: true, data: { started: 0, task_ids: [] } };
+ }
+
+ // Guard: every task we touch must belong to the active project. Defends
+ // against the assignee belonging to a project the user no longer has
+ // active (cookie drift).
+ const validTasks = proposed.filter((t) => t.project_slug === project.slug);
+ if (validTasks.length === 0) {
+ return {
+ ok: false,
+ error: `Agent ${agentId} has no proposed tasks in the active project.`,
+ };
+ }
+
+ // Flip status to running BEFORE firing the kickoffs so the UI immediately
+ // reflects intent — the user sees "running" cards while the agent works.
+ for (const task of validTasks) {
+ updateTask(task.id, { status: "running" });
+ }
+
+ // Fire-and-forget per task. The server stays alive long enough to drain
+ // each gateway stream because Node keeps event-loop work running even
+ // after the action's response is sent. In production we'd want
+ // `unstable_after` for stronger guarantees; V1 dev mode is fine.
+ for (const task of validTasks) {
+ void runTaskKickoffServerSide({ ...task, status: "running" }).catch((err) =>
+ console.error(`[start-all] kickoff failed for ${task.id}:`, err),
+ );
+ }
+
+ revalidatePath(`/agents`, "layout");
+ revalidatePath(`/tasks`, "layout");
+ return {
+ ok: true,
+ data: { started: validTasks.length, task_ids: validTasks.map((t) => t.id) },
+ };
+}
diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.ts
index e47882cc..64e7244c 100644
--- a/src/server/db/tasks.ts
+++ b/src/server/db/tasks.ts
@@ -94,6 +94,23 @@ export function listTasks(project_slug: string, status?: TaskStatus): Task[] {
.all(project_slug) as Task[];
}
+/**
+ * Per-agent task list — what's on this agent's plate. Used by the
+ * /agents/[agent]/tasks page so the assignee can see its queue without
+ * filtering the project-wide kanban manually.
+ */
+export function listTasksByAgent(agent_id: string, status?: TaskStatus): Task[] {
+ const db = getDb();
+ if (status) {
+ return db
+ .prepare("SELECT * FROM tasks WHERE agent_id = ? AND status = ? ORDER BY created_at DESC")
+ .all(agent_id, status) as Task[];
+ }
+ return db
+ .prepare("SELECT * FROM tasks WHERE agent_id = ? ORDER BY created_at DESC")
+ .all(agent_id) as Task[];
+}
+
export type UpdateTaskInput = {
status?: TaskStatus;
result?: unknown;
diff --git a/src/server/orchestration/run-task.ts b/src/server/orchestration/run-task.ts
new file mode 100644
index 00000000..cc947bbb
--- /dev/null
+++ b/src/server/orchestration/run-task.ts
@@ -0,0 +1,71 @@
+import {
+ buildPendingSessionKey,
+} from "@/server/openclaw/sessions";
+import { streamChatViaGateway } from "@/server/openclaw/gateway-client";
+import { setTaskThreadIfMissing, updateTask } from "@/server/db/tasks";
+import type { Task } from "@/types";
+
+import { generateTaskThreadId, processOrchestrationBlocks } from "./process-blocks";
+import { buildTaskKickoffMessage } from "./task-kickoff";
+
+/**
+ * Server-side kickoff for a task. Consumes the full gateway stream (no SSE
+ * pipe to a client) and applies orchestration blocks the assignee emits.
+ * Used by the "Start all" button on the agent Tasks tab so the agent
+ * starts working immediately without the user opening each task's
+ * detail page.
+ *
+ * Returns when the agent has finished its turn AND orchestration blocks
+ * have been processed. Errors are logged + the task is marked failed.
+ */
+export async function runTaskKickoffServerSide(task: Task): Promise<void> {
+ // Lazily mint the thread on first kickoff if the task didn't have one
+ // (e.g., user never opened /tasks/[id]). Stable forever after.
+ let finalTask = task;
+ if (!finalTask.thread_id) {
+ const updated = setTaskThreadIfMissing(task.id, generateTaskThreadId());
+ if (updated) finalTask = updated;
+ if (!finalTask.thread_id) {
+ throw new Error(`Failed to assign thread_id for task ${task.id}`);
+ }
+ }
+
+ const sessionKey = buildPendingSessionKey(finalTask.agent_id, finalTask.thread_id);
+ const kickoffMessage = buildTaskKickoffMessage(finalTask);
+
+ let buffer = "";
+ try {
+ for await (const evt of streamChatViaGateway({
+ sessionKey,
+ sessionId: finalTask.thread_id,
+ message: kickoffMessage,
+ })) {
+ if (evt.kind === "delta") buffer += evt.text;
+ if (evt.kind === "error") {
+ throw new Error(evt.message);
+ }
+ }
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ console.error(`[run-task] kickoff failed for ${finalTask.id}:`, err);
+ updateTask(finalTask.id, {
+ status: "failed",
+ error_message: message,
+ });
+ return;
+ }
+
+ if (buffer.trim().length > 0) {
+ try {
+ await processOrchestrationBlocks(buffer, {
+ project_slug: finalTask.project_slug,
+ agent_id: finalTask.agent_id,
+ });
+ } catch (err) {
+ console.error(
+ `[run-task] orchestration processing failed for ${finalTask.id}:`,
+ err,
+ );
+ }
+ }
+}