Skip to content

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

fix(tasks): stream kickoff via /api/chat instead of server-side drain

Yuting Zhong2f0a02e45a84
diff --git a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
index 306cc919..8970e345 100644
--- a/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
+++ b/src/app/(app)/[project]/agents/[agent]/tasks/page.tsx
@@ -10,7 +10,10 @@ import {
readTranscriptTail,
type TranscriptEvent,
} from "@/server/openclaw/transcript-tail";
-import { generateTaskThreadId } from "@/server/orchestration/task-kickoff";
+import {
+ buildTaskKickoffMessage,
+ generateTaskThreadId,
+} from "@/server/orchestration/task-kickoff";
import type { Approval, Task } from "@/types";
type Props = {
@@ -31,6 +34,14 @@ type SelectedBundle = {
* the audit trail for "what did I approve here?".
*/
approvals: Approval[];
+ /**
+ * Auto-kickoff payload for tasks that haven't started yet. The page
+ * builds the full assignment brief server-side so the client can just
+ * hand it to /api/chat — no business logic on the browser. `null` for
+ * any task already past `proposed` (kickoff already happened or never
+ * will).
+ */
+ kickoff: { taskId: string; message: string } | null;
};
export default async function AgentTasksPage({ params, searchParams }: Props) {
@@ -46,9 +57,12 @@ 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.
- // 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.
+ // For tasks still in `proposed`, we hand the client a kickoff payload it
+ // fires through /api/chat on mount — the SSE path streams gateway events
+ // live (JSONL polling alone misses the run because OpenClaw's codex
+ // mode flushes the transcript once per turn). For tasks already past
+ // proposed (delegated via MCP, restarted via Start all, or finished),
+ // this path is read-only.
let selected: SelectedBundle | null = null;
if (selectedTaskId) {
selected = await loadSelectedBundle(agentFullId, selectedTaskId);
@@ -97,6 +111,15 @@ async function loadSelectedBundle(
const { events, byteOffset } = readTranscriptTail(agentFullId, threadId, 0);
const approvals = listApprovalsForTask(task.id);
+ // Only minted for `proposed` tasks. The client uses this to fire the
+ // first turn via /api/chat (which streams gateway events live), and
+ // /api/chat atomically claims the task on the server before forwarding
+ // — so reloads / concurrent tabs can't double-fire the agent.
+ const kickoff =
+ task.status === "proposed"
+ ? { taskId: task.id, message: buildTaskKickoffMessage(task) }
+ : null;
+
return {
task,
threadId,
@@ -104,5 +127,6 @@ async function loadSelectedBundle(
initialEvents: events,
initialByteOffset: byteOffset,
approvals,
+ kickoff,
};
}
diff --git a/src/app/api/chat/route.test.ts b/src/app/api/chat/route.test.ts
index f7580a2b..24483d6c 100644
--- a/src/app/api/chat/route.test.ts
+++ b/src/app/api/chat/route.test.ts
@@ -33,6 +33,13 @@ vi.mock("@/server/openclaw/gateway-client", () => ({
streamChatViaGateway: (...args: unknown[]) => streamChatViaGatewayMock(...args),
}));
+const getTaskMock = vi.fn();
+const claimProposedTaskMock = vi.fn();
+vi.mock("@/server/db/tasks", () => ({
+ getTask: (...args: unknown[]) => getTaskMock(...args),
+ claimProposedTask: (...args: unknown[]) => claimProposedTaskMock(...args),
+}));
+
import { POST } from "./route";
function makeProject(overrides: Partial<Project> = {}): Project {
@@ -382,6 +389,107 @@ describe("POST /api/chat", () => {
// turn is streaming. The chat route is now pure pipe + perf instrumentation,
// so the only thing left to assert is that no `orchestration` SSE event is
// ever emitted (it's no longer part of the protocol).
+ // ── task_id: kickoff path ────────────────────────────────────────────
+ describe("task_id (task kickoff)", () => {
+ function setupAgent(slug = "acme", agentId = "acme-cmo") {
+ getActiveProjectMock.mockResolvedValue(makeProject({ slug }));
+ resolveAgentBySlugMock.mockResolvedValue({
+ agent_id: agentId,
+ display_name: "CMO",
+ slug: "cmo",
+ });
+ findSessionBySessionIdMock.mockReturnValue(null);
+ }
+
+ it("claims a proposed task and proceeds to stream when task_id matches", async () => {
+ setupAgent();
+ getTaskMock.mockReturnValueOnce({
+ id: "task-uuid",
+ display_id: "acme-1",
+ agent_id: "acme-cmo",
+ status: "proposed",
+ });
+ claimProposedTaskMock.mockReturnValueOnce({
+ id: "task-uuid",
+ status: "working",
+ });
+ streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
+
+ const res = await POST(
+ makeReq({
+ message: "(task assignment)",
+ sessionId: "s1",
+ task_id: "task-uuid",
+ }),
+ );
+ expect(res.status).toBe(200);
+ await readSse(res);
+ expect(claimProposedTaskMock).toHaveBeenCalledWith("task-uuid");
+ expect(streamChatViaGatewayMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("returns 409 when the task can't be claimed (already running/terminal)", async () => {
+ setupAgent();
+ getTaskMock.mockReturnValueOnce({
+ id: "task-uuid",
+ display_id: "acme-1",
+ agent_id: "acme-cmo",
+ status: "working",
+ });
+ claimProposedTaskMock.mockReturnValueOnce(null);
+
+ const res = await POST(
+ makeReq({ message: "hi", sessionId: "s1", task_id: "task-uuid" }),
+ );
+ expect(res.status).toBe(409);
+ const body = (await res.json()) as { status: string };
+ expect(body.status).toBe("working");
+ // Should NOT stream when claim failed — otherwise we'd double-fire the
+ // agent on a reload / concurrent tab.
+ expect(streamChatViaGatewayMock).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 when the task_id doesn't exist", async () => {
+ setupAgent();
+ getTaskMock.mockReturnValueOnce(null);
+ const res = await POST(
+ makeReq({ message: "hi", sessionId: "s1", task_id: "bogus" }),
+ );
+ expect(res.status).toBe(404);
+ expect(claimProposedTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("returns 400 when task belongs to a different agent", async () => {
+ setupAgent("acme", "acme-cmo");
+ getTaskMock.mockReturnValueOnce({
+ id: "task-uuid",
+ display_id: "acme-1",
+ agent_id: "acme-google-ads",
+ status: "proposed",
+ });
+ const res = await POST(
+ makeReq({
+ message: "hi",
+ sessionId: "s1",
+ agent: "cmo",
+ task_id: "task-uuid",
+ }),
+ );
+ expect(res.status).toBe(400);
+ expect(claimProposedTaskMock).not.toHaveBeenCalled();
+ });
+
+ it("skips claim entirely when no task_id is provided (normal chat)", async () => {
+ setupAgent();
+ streamChatViaGatewayMock.mockReturnValueOnce(makeAgentStream([]));
+ const res = await POST(makeReq({ message: "hi", sessionId: "s1" }));
+ expect(res.status).toBe(200);
+ await readSse(res);
+ expect(getTaskMock).not.toHaveBeenCalled();
+ expect(claimProposedTaskMock).not.toHaveBeenCalled();
+ });
+ });
+
it("never emits an `orchestration` SSE event (MCP-based now)", async () => {
getActiveProjectMock.mockResolvedValueOnce(makeProject({ slug: "acme" }));
resolveAgentBySlugMock.mockResolvedValueOnce({
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts
index f3ca2a25..b8e8ded3 100644
--- a/src/app/api/chat/route.ts
+++ b/src/app/api/chat/route.ts
@@ -7,6 +7,7 @@ import {
buildPendingSessionKey,
findSessionBySessionId,
} from "@/server/openclaw/sessions";
+import { claimProposedTask, getTask } from "@/server/db/tasks";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -58,6 +59,14 @@ type ChatPostBody = {
* sessionId-derived key for brand-new threads.
*/
sessionKey?: string;
+ /**
+ * When set, this turn is a task kickoff: atomically claim the task
+ * (proposed → working) before forwarding to the gateway. The claim is
+ * conditional on status='proposed', so concurrent kickoffs or reloads
+ * mid-run are rejected with 409 instead of double-firing the agent.
+ * Absent for normal user-typed messages.
+ */
+ task_id?: string;
};
export async function POST(request: Request) {
@@ -117,6 +126,43 @@ export async function POST(request: Request) {
}
perf.mark("session_resolved");
+ // Task-kickoff path: claim the proposed task before streaming so a single
+ // turn can't fire twice (page reload / two tabs / StrictMode double-mount).
+ // claimProposedTask is a conditional UPDATE keyed on status='proposed';
+ // any other state (working/done/failed/cancelled) returns null and we
+ // reject with 409. Callers (LiveTranscript auto-kickoff) treat 409 as a
+ // benign no-op — the task is already running or finished elsewhere.
+ const taskId = body.task_id?.trim();
+ if (taskId) {
+ const existing = getTask(taskId);
+ if (!existing) {
+ return NextResponse.json(
+ { error: `Unknown task_id '${taskId}'` },
+ { status: 404 },
+ );
+ }
+ if (existing.agent_id !== agentName) {
+ return NextResponse.json(
+ {
+ error: `Task ${existing.display_id} belongs to ${existing.agent_id}, not ${agentName}`,
+ },
+ { status: 400 },
+ );
+ }
+ const claimed = claimProposedTask(existing.id);
+ if (!claimed) {
+ return NextResponse.json(
+ {
+ error: "task already claimed",
+ status: existing.status,
+ task_id: existing.id,
+ },
+ { status: 409 },
+ );
+ }
+ }
+ perf.mark("task_claim_resolved");
+
const encoder = new TextEncoder();
const stream = new ReadableStream({
diff --git a/src/components/agent-task-workspace.test.tsx b/src/components/agent-task-workspace.test.tsx
index 5f9a5873..425e226f 100644
--- a/src/components/agent-task-workspace.test.tsx
+++ b/src/components/agent-task-workspace.test.tsx
@@ -262,7 +262,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0, approvals: [],
+ initialByteOffset: 0, approvals: [], kickoff: null,
},
})}
/>,
@@ -286,7 +286,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "agent:demo-google-ads:thr-1",
initialEvents: [],
- initialByteOffset: 0, approvals: [],
+ initialByteOffset: 0, approvals: [], kickoff: null,
},
})}
/>,
@@ -309,7 +309,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [],
+ initialByteOffset: 0, approvals: [], kickoff: null,
},
})}
/>,
@@ -330,7 +330,7 @@ describe("AgentTaskWorkspace selected-task panel", () => {
threadId: "thr-1",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [],
+ initialByteOffset: 0, approvals: [], kickoff: null,
},
})}
/>,
@@ -351,7 +351,7 @@ describe("AgentTaskWorkspace CancelTaskButton", () => {
threadId: "thr",
sessionKey: "k",
initialEvents: [],
- initialByteOffset: 0, approvals: [],
+ initialByteOffset: 0, approvals: [], kickoff: null,
},
})}
/>,
diff --git a/src/components/agent-task-workspace.tsx b/src/components/agent-task-workspace.tsx
index e7f9617f..0a444052 100644
--- a/src/components/agent-task-workspace.tsx
+++ b/src/components/agent-task-workspace.tsx
@@ -59,6 +59,12 @@ type SelectedTaskBundle = {
/** Approvals attached to this task, newest first. Rendered above the
* transcript so the user can act on a pending one without leaving the chat. */
approvals: Approval[];
+ /**
+ * Set when this task is still in `proposed` and the workspace should
+ * auto-fire the kickoff via /api/chat on mount. Null once the task has
+ * been claimed (working / done / etc.) so a reload doesn't re-send.
+ */
+ kickoff: { taskId: string; message: string } | null;
};
type Props = {
@@ -346,6 +352,9 @@ function SelectedTaskPanel({
composerDisabled={isInFlight}
blockedReason={blockedReason}
onPolled={onPolled}
+ autoKickoff={selected.kickoff !== null}
+ kickoffMessage={selected.kickoff?.message}
+ taskId={selected.kickoff?.taskId}
/>
</div>
</div>
diff --git a/src/components/live-transcript.test.tsx b/src/components/live-transcript.test.tsx
index e1c853a4..8cb8a206 100644
--- a/src/components/live-transcript.test.tsx
+++ b/src/components/live-transcript.test.tsx
@@ -636,6 +636,64 @@ describe("LiveTranscript autoKickoff", () => {
expect(screen.queryByText("kickoff!")).not.toBeInTheDocument();
});
+ it("forwards taskId in the /api/chat body when autoKickoff fires", async () => {
+ let observedBody: Record<string, unknown> | null = null;
+ const encoder = new TextEncoder();
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(encoder.encode("event: text\ndata: {\"chunk\":\"hi\"}\n\n"));
+ controller.close();
+ },
+ });
+ setFetch(async (url, init) => {
+ if (String(url).includes("/api/chat")) {
+ observedBody = JSON.parse((init?.body as string) ?? "{}");
+ return new Response(stream, { status: 200 });
+ }
+ return makeEmptyTranscriptResponse();
+ });
+ render(
+ <LiveTranscript
+ {...defaultProps({
+ autoKickoff: true,
+ kickoffMessage: "kickoff body",
+ taskId: "task-uuid-7",
+ threadId: "t-kickoff-with-task-id",
+ })}
+ />,
+ );
+ await waitFor(() => expect(observedBody).not.toBeNull());
+ expect(observedBody!.task_id).toBe("task-uuid-7");
+ });
+
+ it("treats a 409 from /api/chat as a benign no-op (no error toast, no thrown error)", async () => {
+ setFetch(async (url) => {
+ if (String(url).includes("/api/chat")) {
+ return new Response(
+ JSON.stringify({ error: "task already claimed", status: "working" }),
+ { status: 409 },
+ );
+ }
+ return makeEmptyTranscriptResponse();
+ });
+ render(
+ <LiveTranscript
+ {...defaultProps({
+ autoKickoff: true,
+ kickoffMessage: "kickoff body",
+ taskId: "task-uuid-8",
+ threadId: "t-kickoff-409",
+ })}
+ />,
+ );
+ // No error row should appear — 409 means "someone else claimed it"
+ // and is expected during reloads / concurrent tabs.
+ await new Promise((r) => setTimeout(r, 30));
+ expect(
+ screen.queryByText(/couldn[’']t reach/i),
+ ).not.toBeInTheDocument();
+ });
+
it("does not auto-kickoff a second time for the same threadId (module guard)", async () => {
// Re-uses the same threadId as the previous test which already added to KICKOFF_FIRED.
let chatCalled = false;
diff --git a/src/components/live-transcript.tsx b/src/components/live-transcript.tsx
index 3cc73b6f..58a80e4c 100644
--- a/src/components/live-transcript.tsx
+++ b/src/components/live-transcript.tsx
@@ -73,12 +73,22 @@ type Props = {
/**
* Auto-kickoff: when true AND the transcript is empty AND we're not
* already sending, fire a hidden first message so the agent runs
- * without the user typing. Used by /chat after onboarding (the
- * FIRST_TURN.md sentinel) so the CMO greets without a manual nudge.
+ * without the user typing. Used by the task workspace for tasks still
+ * in `proposed` so the user sees gateway events stream in immediately
+ * — JSONL polling alone can't (OpenClaw's codex-app-server mode flushes
+ * the file once per turn, not incrementally).
*/
autoKickoff?: boolean;
/** Override for the auto-kickoff message body. */
kickoffMessage?: string;
+ /**
+ * Task this turn belongs to. Forwarded to /api/chat so the server can
+ * atomically claim the task (proposed → working) before forwarding to
+ * the gateway. Without it, two tabs / a fast reload could race two
+ * kickoffs against each other and double-fire the agent. The server
+ * returns 409 when the claim fails; we treat that as a benign no-op.
+ */
+ taskId?: string;
};
/** Module-level guard so React StrictMode dev double-mounts don't double-fire. */
@@ -97,6 +107,7 @@ export function LiveTranscript({
onPolled,
autoKickoff = false,
kickoffMessage,
+ taskId,
}: Props) {
const router = useRouter();
const [events, setEvents] = useState<TranscriptEvent[]>(initialEvents);
@@ -302,6 +313,11 @@ export function LiveTranscript({
const ctrl = new AbortController();
abortRef.current = ctrl;
+ // Auto-kickoffs forward task_id so the server can atomically claim
+ // the task (proposed → working). User-typed messages skip it — the
+ // composer is already disabled while the task is in flight, so any
+ // message the user can actually send is post-claim.
+ const includeTaskId = opts.hidden && taskId;
try {
const res = await fetch("/api/chat", {
method: "POST",
@@ -312,9 +328,17 @@ export function LiveTranscript({
project: projectSlug,
sessionId: threadId,
sessionKey,
+ ...(includeTaskId ? { task_id: taskId } : {}),
}),
signal: ctrl.signal,
});
+ if (res.status === 409) {
+ // Task was already claimed elsewhere (concurrent tab, reload
+ // during a working turn). The agent is running on OpenClaw —
+ // JSONL polling will surface the output once the turn flushes.
+ // Bail silently; this is not a user-facing error.
+ return;
+ }
if (!res.ok || !res.body) {
throw new Error((await res.text()) || `HTTP ${res.status}`);
}
@@ -366,7 +390,7 @@ export function LiveTranscript({
abortRef.current = null;
}
},
- [agentSlug, input, pollOnce, projectSlug, router, sendingChat, sessionKey, threadId],
+ [agentSlug, input, pollOnce, projectSlug, router, sendingChat, sessionKey, taskId, threadId],
);
// ── Auto-kickoff for FIRST_TURN-style flows. ────────────────────────
diff --git a/src/server/onboarding/accounts.test.ts b/src/server/onboarding/accounts.test.ts
index 7095d70c..d547eabc 100644
--- a/src/server/onboarding/accounts.test.ts
+++ b/src/server/onboarding/accounts.test.ts
@@ -52,14 +52,6 @@ vi.mock("@/server/agent-templates", () => ({
agentNameFor: (slug: string, key: string) => `${slug}-${key.replace(/_/g, "-")}`,
}));
-// setOnboardingAccountAction lazy-imports startTaskIfProposed to kick off the
-// audit task at creation time. Stub it as a pass-through — the real kickoff
-// path would spin up the gateway client, which has no place in this test.
-const startTaskIfProposedMock = vi.fn((task: unknown) => task);
-vi.mock("@/server/orchestration/run-task", () => ({
- startTaskIfProposed: (task: unknown) => startTaskIfProposedMock(task),
-}));
-
import {
listGoogleAdsAccounts,
setOnboardingAccountAction,
diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.ts
index 3a19e168..f0c3f9ab 100644
--- a/src/server/onboarding/accounts.ts
+++ b/src/server/onboarding/accounts.ts
@@ -130,13 +130,14 @@ 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 and immediately
- * claims+kicks it off server-side via startTaskIfProposed.
+ * 3. Mints the CMO's first task with the audit brief in `proposed`
+ * state. The task workspace the user lands on auto-fires the
+ * kickoff via /api/chat, so the user sees streaming gateway events
+ * live — JSONL polling alone can't (OpenClaw's codex-app-server
+ * mode flushes the file once per turn, not incrementally).
*
* 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.
+ * watches the live audit stream the moment the page mounts.
*/
export async function setOnboardingAccountAction(
project_slug: string,
@@ -196,11 +197,11 @@ 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);
+ // Leave the task in `proposed`. The task workspace the caller redirects
+ // the user to will auto-fire the kickoff client-side via /api/chat so
+ // the user sees live gateway events stream in. /api/chat atomically
+ // claims the task before sending, so the resubmit branch (existing task
+ // already running/done) is a safe no-op there.
revalidatePath("/", "layout");
return { ok: true, project: updated, task_display_id: task.display_id };