Open-source SEO, GEO, and marketing skills for AI agents.
feat(tasks): auto-start delegated tasks + cancel + working pulse
Yuting Zhong68f5ec7591b9
diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.locknew file mode 100644index 00000000..a4869c86--- /dev/null+++ b/.claude/scheduled_tasks.lock@@ -0,0 +1 @@+{"sessionId":"e8325c83-a66d-464a-90bf-308fee3cc0bd","pid":24772,"procStart":"Sun May 17 21:33:18 2026","acquiredAt":1779257395997}\ No newline at end of filediff --git a/next-env.d.ts b/next-env.d.tsindex 9edff1c7..c4b7818f 100644--- a/next-env.d.ts+++ b/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsxindex d0e9468b..91c13d1b 100644--- a/src/components/agent-task-workspace.tsx+++ b/src/components/agent-task-workspace.tsx@@ -1,14 +1,24 @@"use client";-import { useCallback, useMemo } from "react";+import { useCallback, useMemo, useState, useTransition } from "react";import Link from "next/link";import { useRouter, useSearchParams } from "next/navigation";-import { CheckCircle2, Circle, CircleDot, Loader2, XCircle } from "lucide-react";+import {+ CheckCircle2,+ Circle,+ CircleDot,+ Loader2,+ StopCircle,+ XCircle,+} from "lucide-react";+import { toast } from "sonner";import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";import { LiveTranscript } from "@/components/live-transcript";import { RunningDot } from "@/components/running-dot";import { StartAllTasksButton } from "@/components/start-all-tasks-button";+import { cancelTaskAction } from "@/server/actions/tasks";import { cn } from "@/lib/utils";import type { TranscriptEvent } from "@/server/openclaw/transcript-tail";import type { Task, TaskStatus } from "@/types";@@ -184,7 +194,12 @@ export function AgentTaskWorkspace({{(selected.task.status === "running" ||selected.task.status === "proposed" ||selected.task.status === "approved") && (- <RunningDot size="md" />+ <>+ <RunningDot size="md" />+ <CancelTaskButton+ taskDisplayId={selected.task.display_id}+ />+ </>)}<Badgevariant={STATUS_VARIANT[selected.task.status]}@@ -244,9 +259,18 @@ function SelectedTaskPanel({// the status badge in this panel's header + the task list grouping// catch up to the JSONL — the LiveTranscript handles its own rendering// updates, this hook just rebroadcasts to the rest of the page.+ //+ // Double-refresh: when the agent emits its final reply (with the+ // <task_status>done</task_status> block), the JSONL bytes can land+ // BEFORE processOrchestrationBlocks runs the DB status flip. The+ // 600ms delayed refresh catches that follow-up DB write so the badge+ // updates without the user having to manually reload.const onPolled = useCallback(({ newEvents }: { newEvents: number; fileSize: number }) => {- if (newEvents > 0) router.refresh();+ if (newEvents > 0) {+ router.refresh();+ setTimeout(() => router.refresh(), 600);+ }// Return true to stop polling once the task is terminal AND the// poll returned nothing new (transcript fully drained).if (!isInFlight && newEvents === 0) return true;@@ -269,6 +293,49 @@ function SelectedTaskPanel({);}+function CancelTaskButton({ taskDisplayId }: { taskDisplayId: string }) {+ const router = useRouter();+ const [pending, startTransition] = useTransition();+ const [confirming, setConfirming] = useState(false);+ function onClick() {+ if (!confirming) {+ setConfirming(true);+ // Auto-clear the confirm prompt after a few seconds so the button+ // doesn't sit in a scary "click again to cancel" state forever.+ setTimeout(() => setConfirming(false), 3000);+ return;+ }+ startTransition(async () => {+ const r = await cancelTaskAction(taskDisplayId);+ if (!r.ok) {+ toast.error(r.error);+ setConfirming(false);+ return;+ }+ toast.success("Task cancelled.");+ setConfirming(false);+ router.refresh();+ });+ }+ return (+ <Button+ type="button"+ variant={confirming ? "destructive" : "outline"}+ size="sm"+ disabled={pending}+ onClick={onClick}+ className="h-7 px-2 text-[11px]"+ >+ {pending ? (+ <Loader2 className="size-3 animate-spin" />+ ) : (+ <StopCircle className="size-3" />+ )}+ {confirming ? "Click again to cancel" : "Cancel"}+ </Button>+ );+}+function TaskRow({task,selected,diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsxindex aaaa7573..f6246768 100644--- a/src/components/live-transcript.tsx+++ b/src/components/live-transcript.tsx@@ -186,6 +186,11 @@ export function LiveTranscript({}}, [agentSlug, byteOffset, onPolled, threadId]);+ // Poll faster while the parent says the task is in flight — typical+ // first-task experience is "land on workspace, watch the audit run."+ // 2s feels laggy when nothing's on screen; 800ms keeps the pulse fresh.+ const pollIntervalMs = composerDisabled ? 800 : POLL_INTERVAL_MS;+// Background polling: runs while mounted, paused during an active send so// we don't double-render content we're already streaming via SSE.useEffect(() => {@@ -197,14 +202,14 @@ export function LiveTranscript({if (cancelled) return;await pollOnce();if (cancelled) return;- timer = setTimeout(tick, POLL_INTERVAL_MS);+ timer = setTimeout(tick, pollIntervalMs);};- timer = setTimeout(tick, POLL_INTERVAL_MS);+ timer = setTimeout(tick, pollIntervalMs);return () => {cancelled = true;if (timer) clearTimeout(timer);};- }, [pollOnce, sendingChat, stopPolling]);+ }, [pollIntervalMs, pollOnce, sendingChat, stopPolling]);// ── Send: optimistic user message + SSE-driven streaming reply. ─────const send = useCallback(@@ -330,7 +335,16 @@ export function LiveTranscript({}, [autoKickoff, threadId]);const rendered = useMemo(() => collapseEvents(events), [events]);- const showThinking = sendingChat && pendingAssistant === "" && pendingTools.length === 0;+ // Pulse the "thinking" indicator any time the agent could plausibly be+ // working: the user just sent (sendingChat) OR the parent told us this is+ // an in-flight task (composerDisabled) with no streaming output yet to+ // show. Without the second branch, server-side kickoffs land the user on+ // a silent page until the first poll picks up bytes — that's the "did my+ // task even get delivered?" gap the user flagged.+ const showThinking =+ pendingAssistant === "" &&+ pendingTools.length === 0 &&+ (sendingChat || composerDisabled);return (<div className="flex h-full flex-col">@@ -342,7 +356,10 @@ export function LiveTranscript({aria-live="polite"><div className="mx-auto w-full max-w-3xl px-6 py-6">- {rendered.length === 0 && !pendingUserMsg && !sendingChat ? (+ {rendered.length === 0 &&+ !pendingUserMsg &&+ !sendingChat &&+ !composerDisabled ? (<TranscriptEmptyState agentDisplayName={agentDisplayName} />) : (<ol className="space-y-4">@@ -717,10 +734,19 @@ function AssistantText({ body }: { body: string }) {}function KickoffBlock({ body }: { body: string }) {+ // Open by default so the user sees the brief was actually delivered — the+ // moment the page loads, this is the only proof the agent received its+ // assignment. Users can collapse it once they've read it; the chevron+ // makes that affordance obvious.return (- <details className="group rounded-md border border-dashed border-muted-foreground/30 bg-muted/20 px-3 py-2 text-xs">+ <details+ open+ 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>+ <span aria-hidden className="transition-transform group-open:rotate-90">+ ›+ </span>Task brief sent to agent</summary><pre className="mt-2 whitespace-pre-wrap break-words font-mono text-[11px] text-muted-foreground">diff --git a/src/server/actions/tasks.ts b/src/server/actions/tasks.tsindex 0a3b2e03..fac838da 100644--- a/src/server/actions/tasks.ts+++ b/src/server/actions/tasks.ts@@ -3,7 +3,7 @@import { revalidatePath } from "next/cache";import { getActiveProject } from "@/server/active-project";-import { listTasksByAgent, updateTask } from "@/server/db/tasks";+import { getTask, listTasksByAgent, updateTask } from "@/server/db/tasks";import { runTaskKickoffServerSide } from "@/server/orchestration/run-task";export type StartAllResult =@@ -67,3 +67,40 @@ export async function startAllProposedTasksAction(data: { started: validTasks.length, task_ids: validTasks.map((t) => t.id) },};}++export type CancelTaskResult =+ | { ok: true }+ | { ok: false; error: string };++/**+ * Mark a task as cancelled. The agent run on OpenClaw is fire-and-forget+ * and may still complete in the background; processOrchestrationBlocks+ * guards against overwriting a terminal status, so a late "done" from+ * the agent won't flip cancelled → succeeded. Accepts either the PK+ * UUID or the display_id (`<slug>-<n>`).+ */+export async function cancelTaskAction(+ idOrDisplayId: string,+): Promise<CancelTaskResult> {+ const project = await getActiveProject();+ if (!project) return { ok: false, error: "No active project." };+ const task = getTask(idOrDisplayId);+ if (!task) return { ok: false, error: "Task not found." };+ if (task.project_slug !== project.slug) {+ return { ok: false, error: "Task isn't in the active project." };+ }+ if (+ task.status === "succeeded" ||+ task.status === "failed" ||+ task.status === "cancelled"+ ) {+ return { ok: false, error: `Task is already ${task.status}.` };+ }+ updateTask(task.id, {+ status: "cancelled",+ error_message: "Cancelled by user",+ });+ revalidatePath(`/agents`, "layout");+ revalidatePath(`/tasks`, "layout");+ return { ok: true };+}diff --git a/src/server/onboarding/accounts.test.ts b/src/server/onboarding/accounts.test.tsindex 16483f9b..74c774ba 100644--- a/src/server/onboarding/accounts.test.ts+++ b/src/server/onboarding/accounts.test.ts@@ -24,7 +24,7 @@ vi.mock("next/cache", () => ({// Dynamic imports inside setOnboardingAccountAction need mocks too — it// auto-creates the CMO's onboarding task as the final step of the action.const createTaskMock = vi.fn();-const listTasksMock = vi.fn(() => [] as unknown[]);+const listTasksMock = vi.fn<(slug: string) => unknown[]>(() => []);vi.mock("@/server/db/tasks", () => ({createTask: (input: unknown) => {createTaskMock(input);@@ -46,7 +46,7 @@ vi.mock("@/server/db/tasks", () => ({updated_at: "now",};},- listTasks: (...args: unknown[]) => listTasksMock(...args),+ listTasks: (slug: string) => listTasksMock(slug),}));vi.mock("@/server/agent-templates", () => ({agentNameFor: (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,diff --git a/src/server/orchestration/process-blocks.ts b/src/server/orchestration/process-blocks.tsindex 9936f4b0..394293c2 100644--- a/src/server/orchestration/process-blocks.ts+++ b/src/server/orchestration/process-blocks.ts@@ -158,7 +158,15 @@ async function applyCreateTaskBlock(payload: { task_id: task.id, assignee: assigneeAgentId },});- return task;+ // Auto-start the delegated task. When the CMO emits <create_task>, the+ // user expects work to be in flight immediately — not parked as+ // "proposed" until someone clicks Start. The kickoff is fire-and-forget;+ // status flips proposed → running so the sidebar badge + workspace task+ // list reflect activity on the very next poll cycle.+ // Lazy import to avoid pulling the orchestration → run-task → gateway+ // chain into modules that just want createTask.+ const { startTaskIfProposed } = await import("./run-task");+ return startTaskIfProposed(task);}function applyTaskStatusBlock(@@ -179,6 +187,16 @@ function applyTaskStatusBlock(`Only the assignee (${task.agent_id}) can update task '${block.task_id}'; got update from '${ctx.agent_id}'`,);}+ // Already terminal? Skip — user cancellations + earlier failure updates+ // shouldn't get overwritten by a late "done" from an agent that kept+ // running for a bit after the user moved on.+ if (+ task.status === "cancelled" ||+ task.status === "failed" ||+ task.status === "succeeded"+ ) {+ return { task_id: block.task_id, status: task.status };+ }// Map the agent's status vocabulary to our TaskStatus enum.const newStatus =