Skip to content

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

fix(chat): stop button aborts the running harness turn server-side

Yuting Zhong87cc98542e04
diff --git a/notfair/src/app/api/chat/route.ts b/notfair/src/app/api/chat/route.ts
index 368f5322..862d629a 100644
--- a/notfair/src/app/api/chat/route.ts
+++ b/notfair/src/app/api/chat/route.ts
@@ -9,6 +9,10 @@ import {
appendTranscriptEvent,
touchSession,
} from "@/server/sessions";
+import {
+ registerLiveTurn,
+ releaseLiveTurn,
+} from "@/server/sessions/live-turns";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -104,9 +108,11 @@ export async function POST(request: Request) {
}
};
- // Disconnect != cancel: the harness keeps running and persisting events
- // to the transcript. The user sees them on next attach.
- const noAbort = new AbortController();
+ // Disconnect != cancel: the harness keeps running and persisting
+ // events to the transcript; the user sees them on next attach. Only
+ // the explicit stop endpoint (POST /api/chat/stop) aborts this
+ // controller, which SIGTERMs the harness subprocess.
+ const ctrl = registerLiveTurn(session.id);
try {
send("meta", {
@@ -125,7 +131,7 @@ export async function POST(request: Request) {
threadId: session.id,
harnessSessionId: session.harness_session_id,
model,
- signal: noAbort.signal,
+ signal: ctrl.signal,
})) {
if (evt.kind === "session") {
// Remember the harness's own session id so the next turn can
@@ -134,6 +140,10 @@ export async function POST(request: Request) {
touchSession(session.id, evt.harnessSessionId);
continue;
}
+ // A user-requested stop SIGTERMs the harness, which surfaces as a
+ // nonzero-exit error from the adapter. That's the stop working,
+ // not a failure — swallow it; the clean marker lands below.
+ if (evt.kind === "error" && ctrl.signal.aborted) continue;
try {
appendTranscriptEvent(session.id, evt.kind, evt);
} catch (err) {
@@ -156,6 +166,19 @@ export async function POST(request: Request) {
}
}
+ if (ctrl.signal.aborted) {
+ // Honest marker: the turn ended because the user stopped it, not
+ // because the agent finished. The done lifecycle ends the
+ // transcript's "still thinking" state for late attachers.
+ appendTranscriptEvent(session.id, "error", {
+ kind: "error",
+ message: "Stopped by user.",
+ });
+ appendTranscriptEvent(session.id, "lifecycle", {
+ kind: "lifecycle",
+ phase: "done",
+ });
+ }
touchSession(session.id);
send("done", {});
@@ -163,6 +186,7 @@ export async function POST(request: Request) {
const message = err instanceof Error ? err.message : String(err);
send("error", { message });
} finally {
+ releaseLiveTurn(session.id, ctrl);
try {
controller.close();
} catch {
diff --git a/notfair/src/app/api/chat/stop/route.ts b/notfair/src/app/api/chat/stop/route.ts
new file mode 100644
index 00000000..94fbc9b3
--- /dev/null
+++ b/notfair/src/app/api/chat/stop/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from "next/server";
+import { getActiveProject } from "@/server/active-project";
+import { getProject } from "@/server/db/projects";
+import { resolveAgentBySlug } from "@/server/agent-meta";
+import { findSession } from "@/server/sessions";
+import { stopLiveTurn } from "@/server/sessions/live-turns";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+type StopPostBody = {
+ agent?: string;
+ project?: string;
+ thread?: string;
+};
+
+/**
+ * The user's explicit stop click. Aborts the thread's in-flight chat turn
+ * server-side (SIGTERM to the harness subprocess) — unlike a client
+ * disconnect, which deliberately never cancels a running turn.
+ */
+export async function POST(request: Request) {
+ let body: StopPostBody;
+ try {
+ body = (await request.json()) as StopPostBody;
+ } catch {
+ return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
+ }
+
+ const project = body.project ? getProject(body.project) : await getActiveProject();
+ if (!project) {
+ return NextResponse.json({ error: "No active project." }, { status: 400 });
+ }
+ const requestedSlug = (body.agent ?? "").trim();
+ if (!requestedSlug) {
+ return NextResponse.json({ error: "agent is required" }, { status: 400 });
+ }
+ const resolved = await resolveAgentBySlug(project.slug, requestedSlug);
+ if (!resolved) {
+ return NextResponse.json(
+ { error: `Unknown agent: '${requestedSlug}'` },
+ { status: 404 },
+ );
+ }
+
+ const label = body.thread?.trim() || "main";
+ const session = findSession(project.slug, resolved.agent_id, label);
+ const stopped = session ? stopLiveTurn(session.id) : false;
+ return NextResponse.json({ stopped });
+}
diff --git a/notfair/src/components/live-transcript.tsx b/notfair/src/components/live-transcript.tsx
index e14e1c1e..03e4d6a6 100644
--- a/notfair/src/components/live-transcript.tsx
+++ b/notfair/src/components/live-transcript.tsx
@@ -262,6 +262,24 @@ export function LiveTranscript({
const scrollRef = useRef<HTMLDivElement>(null);
const stickyBottomRef = useRef(true);
const abortRef = useRef<AbortController | null>(null);
+
+ // The stop click must reach the server: aborting the local fetch alone
+ // never stops the harness turn (disconnect != cancel), so the transcript
+ // would keep streaming the still-running reply via the poll.
+ const stopTurn = useCallback(() => {
+ abortRef.current?.abort();
+ void fetch("/api/chat/stop", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ project: projectSlug,
+ agent: agentSlug,
+ thread: threadId,
+ }),
+ }).catch(() => {
+ // Best-effort: the local abort already froze the composer's stream.
+ });
+ }, [agentSlug, projectSlug, threadId]);
/**
* Ids of every transcript event we've already committed to state. Acts as
* a dedupe set for poll-result merging: two `pollOnce` calls can fire
@@ -473,7 +491,7 @@ export function LiveTranscript({
);
return;
case "stop":
- abortRef.current?.abort();
+ stopTurn();
return;
case "set-model": {
// Same store the selector next to Send uses.
@@ -820,7 +838,7 @@ export function LiveTranscript({
type="button"
variant="outline"
size="icon"
- onClick={() => abortRef.current?.abort()}
+ onClick={stopTurn}
className="size-9 rounded-full"
aria-label="Stop"
>
diff --git a/notfair/src/server/sessions/index.ts b/notfair/src/server/sessions/index.ts
index 08ea7bbd..c92f5312 100644
--- a/notfair/src/server/sessions/index.ts
+++ b/notfair/src/server/sessions/index.ts
@@ -114,6 +114,20 @@ export function deleteSession(id: string): void {
getDb().prepare("DELETE FROM sessions WHERE id = ?").run(id);
}
+/** The session for a (project, agent, label) triple, if one exists. */
+export function findSession(
+ project_slug: string,
+ agent_id: string,
+ label: string,
+): Session | null {
+ const row = getDb()
+ .prepare(
+ "SELECT * FROM sessions WHERE project_slug = ? AND agent_id = ? AND label = ?",
+ )
+ .get(project_slug, agent_id, label) as SessionRow | undefined;
+ return row ? rowToSession(row) : null;
+}
+
export function getSession(id: string): Session | null {
const row = getDb()
.prepare("SELECT * FROM sessions WHERE id = ?")
diff --git a/notfair/src/server/sessions/live-turns.test.ts b/notfair/src/server/sessions/live-turns.test.ts
new file mode 100644
index 00000000..4a3c3f78
--- /dev/null
+++ b/notfair/src/server/sessions/live-turns.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import {
+ registerLiveTurn,
+ releaseLiveTurn,
+ stopLiveTurn,
+} from "./live-turns";
+
+describe("live chat turn registry", () => {
+ it("stops a registered turn by aborting its controller", () => {
+ const ctrl = registerLiveTurn("s1");
+ expect(ctrl.signal.aborted).toBe(false);
+ expect(stopLiveTurn("s1")).toBe(true);
+ expect(ctrl.signal.aborted).toBe(true);
+ releaseLiveTurn("s1", ctrl);
+ });
+
+ it("reports nothing to stop for an idle session", () => {
+ expect(stopLiveTurn("nope")).toBe(false);
+ });
+
+ it("release is a no-op after the slot was re-registered by a newer turn", () => {
+ const old = registerLiveTurn("s2");
+ const fresh = registerLiveTurn("s2");
+ releaseLiveTurn("s2", old); // stale release must not evict the live turn
+ expect(stopLiveTurn("s2")).toBe(true);
+ expect(fresh.signal.aborted).toBe(true);
+ expect(old.signal.aborted).toBe(false);
+ releaseLiveTurn("s2", fresh);
+ });
+
+ it("a released turn can no longer be stopped", () => {
+ const ctrl = registerLiveTurn("s3");
+ releaseLiveTurn("s3", ctrl);
+ expect(stopLiveTurn("s3")).toBe(false);
+ });
+});
diff --git a/notfair/src/server/sessions/live-turns.ts b/notfair/src/server/sessions/live-turns.ts
new file mode 100644
index 00000000..560e5cfb
--- /dev/null
+++ b/notfair/src/server/sessions/live-turns.ts
@@ -0,0 +1,29 @@
+/**
+ * In-process registry of live chat turns, keyed by session id. The chat
+ * route registers each turn's AbortController here so the stop endpoint
+ * can kill the harness subprocess on the user's explicit request —
+ * distinct from a mere client disconnect, which never cancels the turn.
+ * Single-process local app: module state is the source of truth (same
+ * pattern as the tick runner's re-entrancy guard).
+ */
+
+const liveTurns = new Map<string, AbortController>();
+
+export function registerLiveTurn(sessionId: string): AbortController {
+ const ctrl = new AbortController();
+ liveTurns.set(sessionId, ctrl);
+ return ctrl;
+}
+
+/** Release only if this controller still owns the slot (races are benign). */
+export function releaseLiveTurn(sessionId: string, ctrl: AbortController): void {
+ if (liveTurns.get(sessionId) === ctrl) liveTurns.delete(sessionId);
+}
+
+/** Abort a session's live turn. Returns whether one was running. */
+export function stopLiveTurn(sessionId: string): boolean {
+ const ctrl = liveTurns.get(sessionId);
+ if (!ctrl) return false;
+ ctrl.abort();
+ return true;
+}