Open-source SEO, GEO, and marketing skills for AI agents.
feat(orchestration): task detail page + per-task specialist chat thread
Yuting Zhong47ecb5f692d0
diff --git a/src/app/(app)/tasks/[id]/page.tsx b/src/app/(app)/tasks/[id]/page.tsxnew file mode 100644index 00000000..adbcbae3--- /dev/null+++ b/src/app/(app)/tasks/[id]/page.tsx@@ -0,0 +1,174 @@+import Link from "next/link";+import { notFound } from "next/navigation";++import { AgentChat } from "@/components/agent-chat";+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 {+ buildPendingSessionKey,+ loadSessionHistory,+} from "@/server/openclaw/sessions";+import { buildTaskKickoffMessage } from "@/server/orchestration/task-kickoff";+import { generateTaskThreadId } from "@/server/orchestration/process-blocks";+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",+};++export default async function TaskDetailPage({+ params,+}: {+ params: Promise<{ id: string }>;+}) {+ const { id } = await params;+ const project = await getActiveProject();+ if (!project) {+ return (+ <div className="mx-auto max-w-md pt-12 text-sm text-muted-foreground">+ Select a project to view this task.+ </div>+ );+ }++ let 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.+ 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 (an empty list when this is the first visit).+ const history = loadSessionHistory(task.agent_id, threadId);+ const sessionKey = buildPendingSessionKey(task.agent_id, threadId);+ const autoKickoff = history.length === 0;+ 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={threadId}+ 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>+ </div>+ );+}diff --git a/src/app/(app)/tasks/page.tsx b/src/app/(app)/tasks/page.tsxindex bd8bd133..8459bc73 100644--- a/src/app/(app)/tasks/page.tsx+++ b/src/app/(app)/tasks/page.tsx@@ -1,3 +1,5 @@+import Link from "next/link";+import { Badge } from "@/components/ui/badge";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { getActiveProject } from "@/server/active-project";@@ -73,17 +75,26 @@ export default async function TasksPage() {</CardHeader><CardContent className="space-y-2">{items.map((t) => (- <div key={t.id} className="rounded-md border bg-card p-3 text-xs space-y-1">+ <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 gap-2"><Badge variant={STATUS_VARIANT[t.status]} className="text-[10px]">{t.agent_id}</Badge></div>- <p className="line-clamp-3 text-foreground">{t.brief}</p>+ <p className="font-medium text-foreground line-clamp-2">+ {t.title ?? t.brief}+ </p>+ {t.title && (+ <p className="line-clamp-2 text-muted-foreground">{t.brief}</p>+ )}<p className="text-[10px] text-muted-foreground">{new Date(t.updated_at).toLocaleString()}</p>- </div>+ </Link>))}</CardContent></Card>diff --git a/src/components/agent-chat.tsx b/src/components/agent-chat.tsxindex 4407cb25..abb7b849 100644--- a/src/components/agent-chat.tsx+++ b/src/components/agent-chat.tsx@@ -105,9 +105,19 @@ type Props = {* When true, the chat auto-sends a hidden kickoff on mount so the agent* produces its first turn without the user needing to type. Used after* onboarding when FIRST_TURN.md is sitting in the agent workspace and- * the agent system prompt is set up to read it and greet (D19).+ * the agent system prompt is set up to read it and greet (D19), and on+ * /tasks/[id] when the task's per-task thread is opened for the first+ * time and the brief is delivered via the kickoff message.*/autoKickoff?: boolean;+ /**+ * Override the default "(session start)" kickoff message. Used to+ * deliver per-task briefs to a specialist on first open of a task's+ * thread: the brief itself goes through the chat as a hidden message+ * so the agent has the full PRD before its first reply. Ignored unless+ * autoKickoff is also true.+ */+ kickoffMessage?: string;};export function AgentChat({@@ -119,6 +129,7 @@ export function AgentChat({templateKey: _templateKey,initialMessages = [],autoKickoff = false,+ kickoffMessage,}: Props) {const [messages, setMessages] = useState<Message[]>(initialMessages);const [input, setInput] = useState("");@@ -175,9 +186,10 @@ export function AgentChat({if (messages.length > 0) return;if (pending) return;KICKOFF_FIRED.add(sessionId);- // Short, neutral kickoff — the agent's FIRST_TURN.md instruction does the- // rest. Hidden so the user sees the greeting land on a clean canvas.- send("(session start)", { hidden: true });+ // Hidden kickoff — the agent's system prompt routes from here. Default+ // is "(session start)" which trips FIRST_TURN.md handling; for task+ // threads the caller passes a kickoffMessage carrying the task brief.+ send(kickoffMessage ?? "(session start)", { hidden: true });// Intentionally do not depend on `send` (stable enough across renders) or// `messages` (would re-fire as the greeting streams in).// eslint-disable-next-line react-hooks/exhaustive-depsdiff --git a/src/server/orchestration/task-kickoff.ts b/src/server/orchestration/task-kickoff.tsnew file mode 100644index 00000000..8c6cb79f--- /dev/null+++ b/src/server/orchestration/task-kickoff.ts@@ -0,0 +1,46 @@+import type { Task } from "@/types";++/**+ * Build the hidden kickoff message the assignee receives on first open of+ * a task's per-task chat thread. Carries the brief + operating+ * instructions — the agent has everything it needs to acknowledge and+ * start working without the user typing anything.+ *+ * Kept server-side (in orchestration/) because the format mirrors what+ * the agent's system prompt expects; changing one without the other+ * desyncs the contract.+ */+export function buildTaskKickoffMessage(task: Task): string {+ const lines: string[] = [+ "(task assignment)",+ "",+ `Task ID: ${task.id}`,+ `Title: ${task.title ?? "(untitled)"}`,+ "",+ "Brief:",+ task.brief,+ "",+ ];+ if (task.success_criteria) {+ lines.push("Success criteria:", task.success_criteria, "");+ }+ lines.push(+ "Acknowledge this task in 1-2 sentences (what you'll do + roughly how",+ "long), then start working. Use your tools (MCP, exec, etc.) to actually",+ "do the thing — don't just describe what you'd do.",+ "",+ "When the task is complete, emit at the END of your reply:",+ "",+ "<task_status>",+ `task_id: ${task.id}`,+ "status: done",+ "summary: <one line on what you did>",+ "</task_status>",+ "",+ "If you hit a real blocker, emit status: blocked + an <ask_user> or",+ "<add_comment> to the CMO. If you need user sign-off on a governed",+ "action (spend, content publish, bid change), use <request_approval>",+ "before executing.",+ );+ return lines.join("\n");+}