Open-source SEO, GEO, and marketing skills for AI agents.
refactor(tasks): atomic claim everywhere + kick off at creation
Yuting Zhong0f8f3e11dd87
diff --git a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsxindex 82398e57..ca913753 100644--- a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx+++ b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx@@ -10,7 +10,6 @@ import {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";type Props = {@@ -39,9 +38,9 @@ export default async function AgentTasksPage({ params, searchParams }: Props) {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.+ // Tasks are kicked off at creation time (onboarding action + the CMO's+ // <create_task> handler both call startTaskIfProposed), so this path is+ // read-only — it never mutates task status.let selected: SelectedBundle | null = null;if (selectedTaskId) {selected = await loadSelectedBundle(agentFullId, selectedTaskId);@@ -80,10 +79,6 @@ async function loadSelectedBundle(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.diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex 20a83ee7..91749373 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -181,7 +181,7 @@ function ConnectStep({ slug }: { slug: string }) {onClick={onSkip}variant="ghost"disabled={busy}- aria-label="Skip Google Ads connection for now and go to chat"+ aria-label="Skip Google Ads connection for now and go to CMO tasks">Skip for now</Button>diff --git a/src/server/actions/tasks.ts b/src/server/actions/tasks.tsindex fac838da..1a79842f 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 { getTask, listTasksByAgent, updateTask } from "@/server/db/tasks";+import { claimProposedTask, getTask, listTasksByAgent, updateTask } from "@/server/db/tasks";import { runTaskKickoffServerSide } from "@/server/orchestration/run-task";export type StartAllResult =@@ -44,18 +44,19 @@ export async function startAllProposedTasksAction(};}- // 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" });- }+ // Atomic claim per task — conditional UPDATE so a task that raced into+ // running/terminal between the SELECT and now is silently skipped instead+ // of getting its terminal status overwritten with `running`.+ const claimedTasks = validTasks+ .map((t) => claimProposedTask(t.id))+ .filter((t): t is NonNullable<typeof t> => t !== null);- // 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+ // Fire-and-forget per claimed 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) =>+ for (const task of claimedTasks) {+ void runTaskKickoffServerSide(task).catch((err) =>console.error(`[start-all] kickoff failed for ${task.id}:`, err),);}@@ -64,7 +65,7 @@ export async function startAllProposedTasksAction(revalidatePath(`/tasks`, "layout");return {ok: true,- data: { started: validTasks.length, task_ids: validTasks.map((t) => t.id) },+ data: { started: claimedTasks.length, task_ids: claimedTasks.map((t) => t.id) },};}diff --git a/src/server/db/tasks.ts b/src/server/db/tasks.tsindex ccf6f291..fdd8b3b8 100644--- a/src/server/db/tasks.ts+++ b/src/server/db/tasks.ts@@ -187,3 +187,24 @@ export function updateTask(id: string, update: UpdateTaskInput): Task | null {return getTask(id);}++/**+ * Atomically flip a task from `proposed` to `running` and return the post-flip+ * row, or null when no claim happened (already started, already terminal, row+ * missing). The conditional WHERE clause is the whole point — callers+ * (kickoff entry points, "Start all" batch) can never accidentally regress a+ * `succeeded`/`failed`/`cancelled` row back to `running` by passing in a+ * stale in-memory task snapshot. better-sqlite3 is synchronous, so the+ * read-back here cannot race with a concurrent writer in this process.+ */+export function claimProposedTask(id: string): Task | null {+ const db = getDb();+ const now = new Date().toISOString();+ const info = db+ .prepare(+ "UPDATE tasks SET status = 'running', updated_at = ? WHERE id = ? AND status = 'proposed'",+ )+ .run(now, id);+ if (info.changes === 0) return null;+ return getTask(id);+}diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.tsindex bc44ebf0..3a19e168 100644--- a/src/server/onboarding/accounts.ts+++ b/src/server/onboarding/accounts.ts@@ -130,12 +130,13 @@ export type SetAccountResult =* 1. Validates the account_id against the MCP's reachable list* (anti-tamper for the form submit).* 2. Persists it on the project row.- * 3. Mints the CMO's first task with the audit brief.+ * 3. Mints the CMO's first task with the audit brief and immediately+ * claims+kicks it off server-side via startTaskIfProposed.*- * The caller redirects to /agents/cmo/tasks?task=<display_id>; the- * workspace's startTaskIfProposed fires the kickoff so the agent does the- * audit live in the standard task UX. Replaces the one-off audit.ts- * pipeline that used to drive its own SSE stream + FIRST_TURN.md sentinel.+ * The caller redirects to /agents/cmo/tasks?task=<display_id> so the user+ * watches the in-flight audit in the standard task UX. Replaces the one-off+ * audit.ts pipeline that used to drive its own SSE stream + FIRST_TURN.md+ * sentinel.*/export async function setOnboardingAccountAction(project_slug: string,@@ -195,6 +196,12 @@ export async function setOnboardingAccountAction(});}+ // Claim + kick off the audit task server-side. startTaskIfProposed uses an+ // atomic conditional UPDATE so the resubmit branch (existing task) is a+ // no-op when the audit is already running or done.+ const { startTaskIfProposed } = await import("@/server/orchestration/run-task");+ task = startTaskIfProposed(task);+revalidatePath("/", "layout");return { ok: true, project: updated, task_display_id: task.display_id };}diff --git a/src/server/orchestration/run-task.ts b/src/server/orchestration/run-task.tsindex 78864467..26788abe 100644--- a/src/server/orchestration/run-task.ts+++ b/src/server/orchestration/run-task.ts@@ -2,27 +2,27 @@ import {buildPendingSessionKey,} from "@/server/openclaw/sessions";import { streamChatViaGateway } from "@/server/openclaw/gateway-client";-import { setTaskThreadIfMissing, updateTask } from "@/server/db/tasks";+import { claimProposedTask, setTaskThreadIfMissing, updateTask } from "@/server/db/tasks";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.+ * Idempotent "claim and kickoff" — atomically flips a proposed task to+ * running and fires the server-side kickoff. No-op when the row is already+ * running, terminal, or missing. Used by `<create_task>` handling and the+ * onboarding audit-task path; both callers operate on freshly-created tasks.*- * 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.+ * The claim is a conditional SQL UPDATE (`WHERE status = 'proposed'`), so+ * even if a stale in-memory `task` snapshot is passed in, the DB cannot+ * regress a terminal row back to running.+ *+ * Returns the post-transition task (running on success, the input task+ * otherwise). The kickoff runs fire-and-forget — callers shouldn't await it.*/export function startTaskIfProposed(task: Task): Task {- if (task.status !== "proposed") return task;- const claimed = updateTask(task.id, { status: "running" });+ const claimed = claimProposedTask(task.id);if (!claimed) return task;void runTaskKickoffServerSide(claimed).catch((err) => {console.error("[start-task] kickoff failed:", err);