Skip to content

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

fix(chat): agent keeps running across client disconnect + live poll on return

Yuting Zhongdafd30f2783f
diff --git a/src/app/(app)/tasks/[id]/page.tsx b/src/app/(app)/tasks/[id]/page.tsx
index 88d709c0..e1e17b43 100644
--- a/src/app/(app)/tasks/[id]/page.tsx
+++ b/src/app/(app)/tasks/[id]/page.tsx
@@ -2,6 +2,7 @@ import Link from "next/link";
import { notFound } from "next/navigation";
import { AgentChat } from "@/components/agent-chat";
+import { TaskLivePoller } from "@/components/task-live-poller";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { getActiveProject } from "@/server/active-project";
@@ -154,7 +155,11 @@ export default async function TaskDetailPage({
<div className="min-h-0 flex-1 border-t">
<AgentChat
- key={threadId}
+ // Key includes task.status so flipping running → succeeded remounts
+ // AgentChat exactly once, pulling in the agent's final reply from
+ // JSONL. The threadId stays stable so the dedup'd kickoff guard in
+ // KICKOFF_FIRED still prevents a re-trigger.
+ key={`${threadId}:${task.status}`}
projectSlug={project.slug}
agentSlug={agentSlug}
agentDisplayName={agentDisplayName}
@@ -170,6 +175,7 @@ export default async function TaskDetailPage({
kickoffMessage={kickoffMessage}
/>
</div>
+ <TaskLivePoller status={task.status} />
</div>
);
}
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts
index 5ae9c580..5a7a56be 100644
--- a/src/app/api/chat/route.ts
+++ b/src/app/api/chat/route.ts
@@ -110,14 +110,34 @@ export async function POST(request: Request) {
const stream = new ReadableStream({
async start(controller) {
+ // Track whether the SSE client is still connected. Once they navigate
+ // away or close the tab, controller.enqueue throws — we flip this flag
+ // and silently drop further sends. The agent run on OpenClaw keeps
+ // going, the assistantBuffer keeps accumulating, and orchestration
+ // still runs at the end. Persistence (JSONL) happens server-side
+ // regardless, so when the user returns, loadThreadHistory shows the
+ // full response.
+ let clientOpen = true;
const send = (event: string, data: unknown) => {
- controller.enqueue(
- encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
- );
+ if (!clientOpen) return;
+ try {
+ controller.enqueue(
+ encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`),
+ );
+ } catch {
+ clientOpen = false;
+ }
};
- const abortCtl = new AbortController();
- request.signal?.addEventListener("abort", () => abortCtl.abort(), { once: true });
+ // Deliberately do NOT propagate request.signal to the gateway abort
+ // signal. The user expectation: "if I switch agents or close the tab,
+ // the agent should keep responding; when I switch back, show the
+ // result." Honoring disconnect-as-cancel kills mid-flight agent runs
+ // and breaks that promise. The Stop button is now a future-TODO
+ // (separate POST /api/chat/stop endpoint) — there isn't a way to
+ // explicitly cancel a run today, only the implicit disconnect path
+ // which we no longer treat as cancel.
+ const noAbort = new AbortController(); // never aborted; just satisfies the signal param
let firstSseDeltaSent = false;
let assistantBuffer = "";
@@ -133,7 +153,7 @@ export async function POST(request: Request) {
sessionKey,
sessionId,
message: body.message,
- signal: abortCtl.signal,
+ signal: noAbort.signal,
perf,
})) {
if (evt.kind === "delta") {
@@ -207,7 +227,12 @@ export async function POST(request: Request) {
message: err instanceof Error ? err.message : String(err),
});
} finally {
- controller.close();
+ try {
+ controller.close();
+ } catch {
+ // Controller may already be closed if the client disconnected
+ // mid-stream — silent because the agent run continued + persisted.
+ }
}
},
});
diff --git a/src/components/task-live-poller.test.tsx b/src/components/task-live-poller.test.tsx
new file mode 100644
index 00000000..270bebb1
--- /dev/null
+++ b/src/components/task-live-poller.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render } from "@testing-library/react";
+
+const refreshMock = vi.fn();
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ refresh: refreshMock }),
+}));
+
+import { TaskLivePoller } from "./task-live-poller";
+
+describe("TaskLivePoller", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ refreshMock.mockClear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+ });
+
+ it("polls router.refresh while status is running", () => {
+ render(<TaskLivePoller status="running" />);
+ expect(refreshMock).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(3_000);
+ expect(refreshMock).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(3_000);
+ expect(refreshMock).toHaveBeenCalledTimes(2);
+ vi.advanceTimersByTime(6_000);
+ expect(refreshMock).toHaveBeenCalledTimes(4);
+ });
+
+ it("polls while status is proposed (kickoff in flight)", () => {
+ render(<TaskLivePoller status="proposed" />);
+ vi.advanceTimersByTime(3_000);
+ expect(refreshMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("does NOT poll once status is succeeded", () => {
+ render(<TaskLivePoller status="succeeded" />);
+ vi.advanceTimersByTime(15_000);
+ expect(refreshMock).not.toHaveBeenCalled();
+ });
+
+ it("does NOT poll for failed task", () => {
+ render(<TaskLivePoller status="failed" />);
+ vi.advanceTimersByTime(15_000);
+ expect(refreshMock).not.toHaveBeenCalled();
+ });
+
+ it("does NOT poll for cancelled task", () => {
+ render(<TaskLivePoller status="cancelled" />);
+ vi.advanceTimersByTime(15_000);
+ expect(refreshMock).not.toHaveBeenCalled();
+ });
+
+ it("stops polling after the 10-minute cap so a stuck agent doesn't burn cycles forever", () => {
+ render(<TaskLivePoller status="running" />);
+ // 10 minutes = 600,000 ms = 200 ticks at 3s
+ vi.advanceTimersByTime(11 * 60 * 1000);
+ const callsAtCap = refreshMock.mock.calls.length;
+ // Advance another minute — count should not grow.
+ vi.advanceTimersByTime(60_000);
+ expect(refreshMock).toHaveBeenCalledTimes(callsAtCap);
+ // And the cap kicks in around 200 calls, not a 100x runaway.
+ expect(callsAtCap).toBeLessThan(220);
+ });
+
+ it("tears down the interval when the component unmounts", () => {
+ const { unmount } = render(<TaskLivePoller status="running" />);
+ vi.advanceTimersByTime(3_000);
+ expect(refreshMock).toHaveBeenCalledTimes(1);
+ unmount();
+ vi.advanceTimersByTime(30_000);
+ // No further refreshes after unmount.
+ expect(refreshMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/components/task-live-poller.tsx b/src/components/task-live-poller.tsx
new file mode 100644
index 00000000..77e70224
--- /dev/null
+++ b/src/components/task-live-poller.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useEffect, useRef } from "react";
+import { useRouter } from "next/navigation";
+
+import type { TaskStatus } from "@/types";
+
+/**
+ * While the task is in flight (status: running or proposed-with-thread),
+ * refresh the page every few seconds so the user sees the agent's
+ * progress (status flips, activity log, persisted transcript) without
+ * having to hit the reload button. Server components re-render on
+ * router.refresh; the AgentChat client component is keyed on the
+ * statusKey prop so it remounts exactly once when status flips to a
+ * terminal state — that pulls in the agent's final reply from JSONL.
+ *
+ * Cap polling at 10 minutes per mount so we don't burn cycles if the
+ * agent gets stuck. The page can be reloaded manually after that.
+ */
+const POLL_INTERVAL_MS = 3_000;
+const POLL_MAX_DURATION_MS = 10 * 60 * 1000;
+
+const POLL_STATUSES: TaskStatus[] = ["running", "proposed", "approved"];
+
+export function TaskLivePoller({ status }: { status: TaskStatus }) {
+ const router = useRouter();
+ const startedAtRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ // Only poll while the task is in an in-flight state. As soon as it
+ // flips to done/failed/cancelled, the effect's cleanup tears down
+ // the interval.
+ if (!POLL_STATUSES.includes(status)) return;
+ if (startedAtRef.current === null) startedAtRef.current = Date.now();
+
+ const interval = setInterval(() => {
+ const elapsed = Date.now() - (startedAtRef.current ?? Date.now());
+ if (elapsed > POLL_MAX_DURATION_MS) {
+ clearInterval(interval);
+ return;
+ }
+ router.refresh();
+ }, POLL_INTERVAL_MS);
+
+ return () => clearInterval(interval);
+ }, [status, router]);
+
+ return null;
+}