Open-source SEO, GEO, and marketing skills for AI agents.
fix(onboarding): land Skip path on first task and keep the kickoff alive
Yuting Zhongfbedb6e7c921
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.tsindex f923e346..c23281cd 100644--- a/src/app/api/chat/route.ts+++ b/src/app/api/chat/route.ts@@ -11,7 +11,7 @@ import {openShadowWriter,shadowStreamEvent,} from "@/server/openclaw/shadow-transcript";-import { claimProposedTask, getTask } from "@/server/db/tasks";+import { claimProposedTask, getTask, updateTask } from "@/server/db/tasks";export const dynamic = "force-dynamic";export const runtime = "nodejs";@@ -258,6 +258,21 @@ export async function POST(request: Request) {send("lifecycle", { phase: evt.phase });} else if (evt.kind === "error") {send("error", { message: evt.message });+ // When this turn is a task kickoff (we atomically claimed+ // proposed → working above), a gateway error means the agent+ // never actually ran. Without this rollback the task is+ // stranded in `working` forever — the UI shows a permanent+ // "Starting" with no events. Mark it failed so the error+ // surfaces in the task row and the user can decide to retry.+ if (taskId) {+ console.error(+ `[api/chat] kickoff gateway error for task ${taskId} (agent=${agentName}): ${evt.message}`,+ );+ updateTask(taskId, {+ status: "failed",+ error_message: evt.message,+ });+ }}// "final" implicitly ends the loop after; no separate signal needed.}@@ -274,9 +289,19 @@ export async function POST(request: Request) {send("perf", { marks: perf.summary() });send("done", {});} catch (err) {- send("error", {- message: err instanceof Error ? err.message : String(err),- });+ const message = err instanceof Error ? err.message : String(err);+ send("error", { message });+ // Same kickoff-stranding fix as the in-stream error branch above:+ // if we claimed the task at the top of the handler, the gateway+ // tearing down before any progress means the agent never ran.+ // Mark it failed so the UI surfaces the error instead of sitting+ // on "Starting" forever.+ if (taskId) {+ console.error(+ `[api/chat] kickoff threw for task ${taskId} (agent=${agentName}): ${message}`,+ );+ updateTask(taskId, { status: "failed", error_message: message });+ }} finally {// Close the shadow if it's still open (error path). Idempotent// close — calling twice when the success path already closed isdiff --git a/src/components/onboarding-flow.test.tsx b/src/components/onboarding-flow.test.tsxindex 6d1f8075..f42d6a09 100644--- a/src/components/onboarding-flow.test.tsx+++ b/src/components/onboarding-flow.test.tsx@@ -7,6 +7,7 @@ const {startMcpConnect,listGoogleAdsAccounts,setOnboardingAccountAction,+ getOnboardingTaskForSkipAction,routerPush,routerReplace,toastFns,@@ -16,6 +17,7 @@ const {startMcpConnect: vi.fn(),listGoogleAdsAccounts: vi.fn(),setOnboardingAccountAction: vi.fn(),+ getOnboardingTaskForSkipAction: vi.fn(),routerPush: vi.fn(),routerReplace: vi.fn(),toastFns: {@@ -38,6 +40,8 @@ vi.mock("@/server/onboarding/accounts", () => ({listGoogleAdsAccounts: (...args: unknown[]) => listGoogleAdsAccounts(...args),setOnboardingAccountAction: (...args: unknown[]) =>setOnboardingAccountAction(...args),+ getOnboardingTaskForSkipAction: (...args: unknown[]) =>+ getOnboardingTaskForSkipAction(...args),}));vi.mock("next/navigation", () => ({@@ -80,6 +84,7 @@ beforeEach(() => {startMcpConnect.mockReset();listGoogleAdsAccounts.mockReset();setOnboardingAccountAction.mockReset();+ getOnboardingTaskForSkipAction.mockReset();routerPush.mockReset();routerReplace.mockReset();toastFns.success.mockReset();@@ -238,15 +243,33 @@ describe("OnboardingFlow — ConnectStep", () => {);});- it("pushes the project home when the user clicks Skip", () => {+ it("redirects to the CMO onboarding task when the user clicks Skip", async () => {+ getOnboardingTaskForSkipAction.mockResolvedValue({+ ok: true,+ task_display_id: "acme-1",+ cmo_agent_slug: "cmo-greg",+ });+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));+ await waitFor(() =>+ expect(routerReplace).toHaveBeenCalledWith(+ "/acme/agents/cmo-greg/tasks?task=acme-1",+ ),+ );+ });++ it("toasts when the skip lookup fails", async () => {+ getOnboardingTaskForSkipAction.mockResolvedValue({+ ok: false,+ error: "Onboarding task not found.",+ });setStep("connect", "acme");render(<OnboardingFlow />);fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));- // After the agent-identity refactor, CMO URL slugs encode the user-- // chosen name (`cmo-<name>`), so we can't hardcode `/agents/cmo/tasks`- // here. Sending the user to the project home is correct — the sidebar- // surfaces the named CMO from there.- expect(routerPush).toHaveBeenCalledWith("/acme");+ await waitFor(() =>+ expect(toastFns.error).toHaveBeenCalledWith("Onboarding task not found."),+ );});});diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex b9c8ba77..a9800423 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -17,6 +17,7 @@ import { createProjectForOnboardingAction } from "@/server/actions/projects";import {listGoogleAdsAccounts,setOnboardingAccountAction,+ getOnboardingTaskForSkipAction,type GoogleAdsAccount,} from "@/server/onboarding/accounts";@@ -271,10 +272,6 @@ function ConnectStep({ slug }: { slug: string }) {const router = useRouter();const [busy, setBusy] = useState(false);const connectionsHref = projectHref(slug, "/connections");- // Project home — sidebar leads the user to the CMO from there.- // (We can't hardcode /agents/<role-name>/tasks because the URL slug is- // user-customizable as <role>-<name>.)- const projectHome = projectHref(slug, "");async function onConnect() {setBusy(true);@@ -296,11 +293,31 @@ function ConnectStep({ slug }: { slug: string }) {}}- function onSkip() {- // Without Google Ads connected, there's nothing for the CMO to audit- // yet — drop the user on the CMO's task tab so they can see "no tasks- // assigned, connect Google Ads to start".- router.push(projectHome);+ async function onSkip() {+ // Drop the user on the CMO's PROJECT.md onboarding task — the same+ // workspace the connect path lands on. The kickoff already fired+ // server-side in createProjectForOnboardingAction, so this is just a+ // navigation: the user sees streaming events (or, if the kickoff+ // errored, the failed-task error message — much better than the+ // earlier "land on project home and figure it out" fallback).+ setBusy(true);+ try {+ const result = await getOnboardingTaskForSkipAction(slug);+ if (!result.ok) {+ toast.error(result.error);+ setBusy(false);+ return;+ }+ router.replace(+ projectHref(+ slug,+ `/agents/${result.cmo_agent_slug}/tasks?task=${encodeURIComponent(result.task_display_id)}`,+ ),+ );+ } catch (err) {+ toast.error(err instanceof Error ? err.message : String(err));+ setBusy(false);+ }}return (diff --git a/src/server/agent-templates.test.ts b/src/server/agent-templates.test.tsindex cff4a7be..cfe1b07c 100644--- a/src/server/agent-templates.test.ts+++ b/src/server/agent-templates.test.ts@@ -16,8 +16,13 @@ vi.mock("@/server/openclaw/cli", () => ({openclaw: vi.fn(async (args: string[]) => {// ensureProjectAgents calls `openclaw agents list` to check existence,// and `openclaw agents add` to provision. Stub both as no-ops returning- // an empty agent list so every template is treated as "new".+ // an empty agent list so every template is treated as "new". Track+ // the added ids so the gateway-list mock below can pretend the+ // gateway already knows about them (closes the test-time race).if (args[0] === "agents" && args[1] === "list") return "";+ if (args[0] === "agents" && args[1] === "add" && typeof args[2] === "string") {+ seenAgentIds.add(args[2]);+ }return undefined;}),OpenClawError: class extends Error {},@@ -41,6 +46,20 @@ vi.mock("@/server/agent-meta", () => ({writeAgentMeta: vi.fn(async () => {}),}));+// Provisioning now waits for the gateway's runtime agents list to include+// the newly-created ids before returning (closes the post-`openclaw agents+// add` race that stranded onboarding kickoffs). Use a permissive mock that+// claims every requested id is already present — the wait drops out on its+// first iteration so provisioning returns synchronously like before.+const seenAgentIds = new Set<string>();+vi.mock("@/server/openclaw/gateway-rpc", () => ({+ listAllAgents: vi.fn(async () => ({+ defaultId: "main",+ mainKey: "main",+ agents: [...seenAgentIds].map((id) => ({ id })),+ })),+}));+import { ensureProjectAgents, agentNameFor } from "./agent-templates";import { getOrchestrationSkill } from "./skills/orchestration-skill";diff --git a/src/server/agent-templates.ts b/src/server/agent-templates.tsindex e05c1994..b14a8973 100644--- a/src/server/agent-templates.ts+++ b/src/server/agent-templates.ts@@ -2,6 +2,7 @@ import { mkdir, writeFile } from "node:fs/promises";import { homedir } from "node:os";import { join } from "node:path";import { openclaw } from "@/server/openclaw/cli";+import { listAllAgents } from "@/server/openclaw/gateway-rpc";import { readAgentMeta, writeAgentMeta } from "@/server/agent-meta";import {cleanupLegacyOrchestrationRows,@@ -374,6 +375,19 @@ export async function ensureProjectAgents(}}+ // After provisioning, the openclaw config file has the new agent rows+ // but the gateway daemon's pinned runtime snapshot lags by a beat —+ // sending chat.send during that window hits an INVALID_REQUEST+ // "Agent '<id>' no longer exists in configuration". Wait until the+ // gateway's agents.list reports every newly-created id so the kickoff+ // path immediately after this (createProjectForOnboardingAction's+ // startTaskIfProposed) finds a warm gateway. Best-effort: a timeout+ // here doesn't block provisioning — runTaskKickoffServerSide also has+ // retry-on-this-error as a second line of defense.+ if (created.length > 0) {+ await waitForGatewayToSeeAgents(created);+ }+// Register the orchestration MCP server with OpenClaw — once, globally.// Tools are project-scoped via a required `project_slug` argument on every// call, so a single registration serves every project + every agent in@@ -399,6 +413,40 @@ export async function ensureProjectAgents(return { created, existed, failed };}+/**+ * Poll the gateway's `agents.list` until every newly-provisioned id shows+ * up (or the timeout expires). Closes the post-`openclaw agents add` race+ * where the runtime config snapshot hasn't caught up to the on-disk+ * config file yet, so chat.send hits "Agent '<id>' no longer exists in+ * configuration".+ */+async function waitForGatewayToSeeAgents(+ expected: string[],+ opts: { timeoutMs?: number; intervalMs?: number } = {},+): Promise<void> {+ const timeoutMs = opts.timeoutMs ?? 15_000;+ const intervalMs = opts.intervalMs ?? 500;+ const deadline = Date.now() + timeoutMs;+ const want = new Set(expected);+ while (Date.now() < deadline) {+ try {+ const list = await listAllAgents();+ const seen = new Set(list.agents.map((a) => a.id));+ if ([...want].every((id) => seen.has(id))) return;+ } catch (err) {+ // Transient — gateway may be momentarily unreachable during config+ // rewrites. Fall through to the sleep + retry.+ console.warn(+ `[provision] gateway agents.list probe failed: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ await new Promise((r) => setTimeout(r, intervalMs));+ }+ console.warn(+ `[provision] gateway didn't surface all new agents within ${timeoutMs}ms; kickoffs will rely on the retry-on-stale-snapshot path`,+ );+}+function workspaceDirFor(name: string): string {const dataDir = process.env.NOTFAIR_CMO_DATA_DIR ?? join(homedir(), ".notfair-cmo");return join(dataDir, "agents", name);diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.tsindex 2006a146..2c85d1e7 100644--- a/src/server/onboarding/accounts.ts+++ b/src/server/onboarding/accounts.ts@@ -248,3 +248,50 @@ export async function setOnboardingAccountAction(cmo_agent_slug: cmo.slug,};}++export type SkipAccountResult =+ | { ok: true; task_display_id: string; cmo_agent_slug: string }+ | { ok: false; error: string };++/**+ * Skip-Google-Ads variant of the onboarding finish. Resolves the CMO agent+ * and its already-created "Learn the project and write PROJECT.md" task so+ * the client can land the user on the same task workspace the connect path+ * lands on. No account is persisted, no audit task is minted — the audit+ * task is only meaningful once Google Ads is wired up, and the user can+ * always reach the connect screen later from /connections.+ *+ * The PROJECT.md kickoff was already fired server-side by+ * createProjectForOnboardingAction (post-provisioning .then). All we do+ * here is forward the slugs the client needs to navigate.+ */+export async function getOnboardingTaskForSkipAction(+ project_slug: string,+): Promise<SkipAccountResult> {+ if (!project_slug.trim()) {+ return { ok: false, error: "Missing project slug." };+ }+ const project = getProject(project_slug);+ if (!project) return { ok: false, error: "Project not found." };++ const { listTasks } = await import("@/server/db/tasks");+ const { listProjectAgents } = await import("@/server/agent-meta");+ const projectAgents = await listProjectAgents(project_slug);+ const cmo = projectAgents.find((a) => a.template_key === "cmo");+ if (!cmo) {+ return { ok: false, error: "CMO agent has not been provisioned yet." };+ }+ const onboardingTask = listTasks(project_slug).find(+ (t) =>+ t.agent_id === cmo.agent_id &&+ t.title === "Learn the project and write PROJECT.md",+ );+ if (!onboardingTask) {+ return { ok: false, error: "Onboarding task not found." };+ }+ return {+ ok: true,+ task_display_id: onboardingTask.display_id,+ cmo_agent_slug: cmo.slug,+ };+}diff --git a/src/server/orchestration/run-task.ts b/src/server/orchestration/run-task.tsindex 5685418d..1762ebb2 100644--- a/src/server/orchestration/run-task.ts+++ b/src/server/orchestration/run-task.ts@@ -74,31 +74,69 @@ export async function runTaskKickoffServerSide(task: Task): Promise<void> {// post-process the buffer for pseudo-XML blocks — any side effects// (task_status, comments, approvals) happen via the agent calling// notfair-orchestration MCP tools mid-stream.- try {- for await (const evt of streamChatViaGateway({- sessionKey,- sessionId: finalTask.thread_id,- message: kickoffMessage,- })) {- // Best-effort forward to the shadow; a shadow-write failure must- // not abort the actual gateway stream.- try {- await shadowStreamEvent(shadow, evt);- } catch (err) {- console.error("[run-task] shadow write failed:", err);+ console.log(+ `[run-task] kickoff start task=${finalTask.id} agent=${finalTask.agent_id} thread=${finalTask.thread_id}`,+ );+ // Retry on the post-provisioning race: `openclaw agents add` updates the+ // config file but the gateway's pinned runtime snapshot needs a moment+ // before it sees the new agent. Until that catches up, chat.send fails+ // with INVALID_REQUEST "Agent '<id>' no longer exists in configuration".+ // 2s/4s/8s backoff covers a ~14s race window we've observed in dev.+ const RETRY_DELAYS_MS = [2_000, 4_000, 8_000];+ let lastError: unknown = null;+ let streamed = false;+ for (let attempt = 0; attempt <= RETRY_DELAYS_MS.length; attempt += 1) {+ try {+ for await (const evt of streamChatViaGateway({+ sessionKey,+ sessionId: finalTask.thread_id,+ message: kickoffMessage,+ })) {+ try {+ await shadowStreamEvent(shadow, evt);+ } catch (err) {+ console.error("[run-task] shadow write failed:", err);+ }+ if (evt.kind === "error") {+ throw new Error(evt.message);+ }}- if (evt.kind === "error") {- throw new Error(evt.message);+ streamed = true;+ break;+ } catch (err) {+ lastError = err;+ const message = err instanceof Error ? err.message : String(err);+ if (!isAgentNotInConfigError(message) || attempt >= RETRY_DELAYS_MS.length) {+ break;}+ const delay = RETRY_DELAYS_MS[attempt]!;+ console.warn(+ `[run-task] gateway snapshot stale for ${finalTask.agent_id}; retrying in ${delay}ms (attempt ${attempt + 1}/${RETRY_DELAYS_MS.length})`,+ );+ await new Promise((r) => setTimeout(r, delay));}+ }+ if (streamed) {await shadow.close();- } catch (err) {- await shadow.close().catch(() => undefined);- 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,- });+ console.log(`[run-task] kickoff stream done task=${finalTask.id}`);+ return;}+ await shadow.close().catch(() => undefined);+ const message = lastError instanceof Error ? lastError.message : String(lastError);+ console.error(+ `[run-task] kickoff failed task=${finalTask.id} agent=${finalTask.agent_id}: ${message}`,+ );+ updateTask(finalTask.id, {+ status: "failed",+ error_message: message,+ });+}++/**+ * Matches the gateway's "Agent '<id>' no longer exists in configuration"+ * INVALID_REQUEST. Surfaced when the gateway hasn't refreshed its agents+ * snapshot yet after a fresh `openclaw agents add`. Idempotently retryable.+ */+function isAgentNotInConfigError(message: string): boolean {+ return message.includes("no longer exists in configuration");}