Open-source SEO, GEO, and marketing skills for AI agents.
fix(tasks): clicking a succeeded task no longer re-triggers the agent
Yuting Zhong7da1348d1a15
diff --git a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsxindex 5ac7755c..7e865800 100644--- a/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx+++ b/src/app/(app)/agents/[agent]/chat/[thread]/page.tsx@@ -8,13 +8,12 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/comimport { getActiveProject } from "@/server/active-project";import { resolveAgentBySlug } from "@/server/agent-meta";import {- buildPendingSessionKey,findSessionBySessionId,listSessionsForAgent,- loadSessionHistory,} from "@/server/openclaw/sessions";import { storedMcpKey } from "@/server/mcp-catalog";import { getMcpStatus } from "@/server/mcp-state";+import { loadThreadHistory } from "@/server/orchestration/thread-history";import { AgentChat } from "@/components/agent-chat";import { GoogleAdsMcpBanner } from "@/components/google-ads-mcp-banner";import { McpFlashBanner } from "@/components/mcp-flash-banner";@@ -73,13 +72,10 @@ export default async function AgentChatThreadPage({const allSessions = listSessionsForAgent(agentFullId);const existing = findSessionBySessionId(agentFullId, threadId);- // Either we have a known session (use its registered sessionKey) or this is- // a brand-new thread the user just navigated into; use a self-named key so- // OpenClaw can create the entry on the first turn.- const sessionKey = existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);- // History lives in a JSONL file named after OpenClaw's internal sessionId,- // which is distinct from the URL thread id (the label half of the sessionKey).- const history = existing ? loadSessionHistory(agentFullId, existing.sessionId) : [];+ // Both surfaces (this page + /tasks/[id]) load history via the shared+ // helper that resolves the URL threadId to OpenClaw's internal sessionId+ // before reading the transcript JSONL. See thread-history.ts.+ const { sessionKey, history } = loadThreadHistory(agentFullId, threadId);// For the dropdown: surface the pending thread at the top so the user sees// it's "selected" even before sending the first message.diff --git a/src/app/(app)/tasks/[id]/page.tsx b/src/app/(app)/tasks/[id]/page.tsxindex adbcbae3..88d709c0 100644--- a/src/app/(app)/tasks/[id]/page.tsx+++ b/src/app/(app)/tasks/[id]/page.tsx@@ -9,12 +9,9 @@ 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 { loadThreadHistory, shouldAutoKickoffTask } from "@/server/orchestration/thread-history";import type { TaskStatus } from "@/types";const STATUS_VARIANT: Record<@@ -63,10 +60,14 @@ export default async function TaskDetailPage({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;+ // Per-task chat history. loadThreadHistory resolves threadId → OpenClaw+ // sessionId before reading the JSONL — direct loadSessionHistory(threadId)+ // returns [] because the file is keyed by OpenClaw's internal sessionId,+ // not by the URL label. That bug caused succeeded tasks to re-trigger+ // when reopened. shouldAutoKickoffTask adds a defense-in-depth status+ // gate so any non-proposed task is safe even if history loading regresses.+ const { sessionKey, history } = loadThreadHistory(task.agent_id, threadId);+ const autoKickoff = shouldAutoKickoffTask(task, history);const kickoffMessage = autoKickoff ? buildTaskKickoffMessage(task) : undefined;// Comments + status updates on this task (rendered as an activity list abovediff --git a/src/server/orchestration/thread-history.test.ts b/src/server/orchestration/thread-history.test.tsnew file mode 100644index 00000000..e769f5ed--- /dev/null+++ b/src/server/orchestration/thread-history.test.ts@@ -0,0 +1,119 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { Task } from "@/types";++const findSessionBySessionIdMock = vi.fn();+const loadSessionHistoryMock = vi.fn();+vi.mock("@/server/openclaw/sessions", () => ({+ findSessionBySessionId: (agentFullId: string, threadId: string) =>+ findSessionBySessionIdMock(agentFullId, threadId),+ loadSessionHistory: (agentFullId: string, sessionId: string) =>+ loadSessionHistoryMock(agentFullId, sessionId),+ buildPendingSessionKey: (agentFullId: string, threadId: string) =>+ `agent:${agentFullId}:${threadId}`,+}));++import { loadThreadHistory, shouldAutoKickoffTask } from "./thread-history";++const baseTask: Task = {+ id: "task-1",+ project_slug: "demo",+ agent_id: "demo-google-ads",+ title: "Install conv tracking",+ brief: "Do it.",+ success_criteria: null,+ deadline_iso: null,+ status: "proposed",+ result_json: null,+ error_message: null,+ thread_id: "thread-abc",+ assigner_agent_id: "demo-cmo",+ created_at: "now",+ updated_at: "now",+};++describe("loadThreadHistory", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("resolves threadId → OpenClaw sessionId, then loads history with sessionId (not threadId)", () => {+ // URL threadId is "thread-abc" but OpenClaw's internal sessionId for+ // that thread is "internal-xyz" — distinct values. Previous bug: we+ // called loadSessionHistory(threadId), got an empty file, kickoff+ // re-fired. Fix: resolve via findSessionBySessionId first.+ findSessionBySessionIdMock.mockReturnValueOnce({+ sessionId: "internal-xyz",+ label: "thread-abc",+ sessionKey: "agent:demo-google-ads:thread-abc",+ lastInteractionAt: 1,+ pending: false,+ });+ loadSessionHistoryMock.mockReturnValueOnce([+ { id: "0", role: "user", body: "(task assignment) ...", timestamp: 1 },+ { id: "1", role: "assistant", body: "On it.", timestamp: 2 },+ ]);++ const out = loadThreadHistory("demo-google-ads", "thread-abc");++ expect(loadSessionHistoryMock).toHaveBeenCalledWith(+ "demo-google-ads",+ "internal-xyz",+ );+ expect(loadSessionHistoryMock).not.toHaveBeenCalledWith(+ "demo-google-ads",+ "thread-abc",+ );+ expect(out.sessionKey).toBe("agent:demo-google-ads:thread-abc");+ expect(out.history).toHaveLength(2);+ });++ it("returns pending sessionKey + empty history when threadId is unknown to OpenClaw", () => {+ // First open of a freshly-minted thread — OpenClaw hasn't seen it+ // yet, so findSessionBySessionId returns null. Caller should treat+ // as pending (no history, sessionKey is a fresh pending one).+ findSessionBySessionIdMock.mockReturnValueOnce(null);+ const out = loadThreadHistory("demo-google-ads", "fresh-thread");+ expect(out.history).toEqual([]);+ expect(out.sessionKey).toBe("agent:demo-google-ads:fresh-thread");+ expect(loadSessionHistoryMock).not.toHaveBeenCalled();+ });+});++describe("shouldAutoKickoffTask", () => {+ it("fires for proposed task with empty history (happy path)", () => {+ expect(shouldAutoKickoffTask({ ...baseTask, status: "proposed" }, [])).toBe(true);+ });++ it("does NOT fire for proposed task with existing history (resume case)", () => {+ expect(+ shouldAutoKickoffTask({ ...baseTask, status: "proposed" }, [+ { id: "0", role: "user", body: "...", timestamp: 1 },+ ]),+ ).toBe(false);+ });++ it("does NOT fire for succeeded task even with empty history (REGRESSION — task re-trigger bug)", () => {+ // The bug the user reported: clicking a succeeded task re-triggered+ // the agent. Root cause was loadThreadHistory returning [] (separate+ // bug, fixed above). This guard is defense-in-depth so even if+ // history loading regresses again, a succeeded task never re-runs.+ expect(shouldAutoKickoffTask({ ...baseTask, status: "succeeded" }, [])).toBe(false);+ });++ it("does NOT fire for running task (agent is already at work — or stalled, user retries explicitly)", () => {+ expect(shouldAutoKickoffTask({ ...baseTask, status: "running" }, [])).toBe(false);+ });++ it("does NOT fire for failed task (no implicit auto-retry; user must explicitly restart)", () => {+ expect(shouldAutoKickoffTask({ ...baseTask, status: "failed" }, [])).toBe(false);+ });++ it("does NOT fire for cancelled task", () => {+ expect(shouldAutoKickoffTask({ ...baseTask, status: "cancelled" }, [])).toBe(false);+ });++ it("does NOT fire for approved task (in v1.1 the post-approval kickoff will be triggered explicitly)", () => {+ expect(shouldAutoKickoffTask({ ...baseTask, status: "approved" }, [])).toBe(false);+ });+});diff --git a/src/server/orchestration/thread-history.ts b/src/server/orchestration/thread-history.tsnew file mode 100644index 00000000..79261742--- /dev/null+++ b/src/server/orchestration/thread-history.ts@@ -0,0 +1,55 @@+import {+ buildPendingSessionKey,+ findSessionBySessionId,+ loadSessionHistory,+ type ChatMessage,+} from "@/server/openclaw/sessions";++/**+ * Resolve `threadId → (sessionKey, history)` for an agent.+ *+ * Why this helper exists: the URL threadId we mint is the LABEL half of+ * OpenClaw's sessionKey (`agent:<agent>:<label>`), NOT OpenClaw's internal+ * `sessionId` (a different UUID OpenClaw assigns when it writes the+ * transcript JSONL on first turn). loadSessionHistory takes that internal+ * sessionId. Passing the URL threadId directly silently returns [] for any+ * existing thread — which then trips autoKickoff and re-runs the agent.+ *+ * Both the agent's per-thread chat page and the per-task chat thread on+ * /tasks/[id] use this helper so the discrepancy can't bite again.+ */+export function loadThreadHistory(+ agentFullId: string,+ threadId: string,+): { sessionKey: string; history: ChatMessage[] } {+ const existing = findSessionBySessionId(agentFullId, threadId);+ const sessionKey =+ existing?.sessionKey ?? buildPendingSessionKey(agentFullId, threadId);+ const history = existing+ ? loadSessionHistory(agentFullId, existing.sessionId)+ : [];+ return { sessionKey, history };+}++import type { Task } from "@/types";++/**+ * Defense-in-depth guard for the per-task auto-kickoff. We only fire the+ * hidden kickoff when:+ * 1. The task is still proposed (hasn't started yet), AND+ * 2. The thread has no history (the agent hasn't sent any reply).+ *+ * The status guard is the load-bearing one — even if history loading+ * regresses (the bug that caused this helper to exist), a succeeded task+ * still never auto-re-fires. The history guard catches the rarer case of+ * a proposed task whose first kickoff already wrote a partial reply+ * before crashing.+ */+export function shouldAutoKickoffTask(+ task: Task,+ history: ChatMessage[],+): boolean {+ if (task.status !== "proposed") return false;+ if (history.length > 0) return false;+ return true;+}