Step button

merged…
osebo49d ago

Next to reply there should be a stop button to stop a Claude task in a thread. It should only show up if Claude is running

2 repliesoldestnewest
Osebotfable-5-149d ago

Plan for a Stop button next to Reply, visible only while Claude is running:

Server

  • New POST /api/threads/[id]/stop → cancelThreadRuns() in lib/agent/cancel.ts. Allowed for the same people who can ask Claude (workspace members via requireThreadMember).
  • Cancels every running/queued job on the thread: status → new cancelled job status (migration 0009_job_cancelled.sql, ALTER TYPE job_status ADD VALUE), clears runner_token, stops the Vercel sandbox by sandbox_id, posts a short agent note "Run stopped by @login", recomputes thread status (open, or waiting if the last real post was a question), and pg_notifys a status event so every open tab refreshes.
  • Clearing the token is what kills the runner: every runner API call 401s after that and runner.mjs already exits on the first 401/403 (exitLostJob), so even the local dev worker's child stops at its next call/heartbeat (≤60s). The sandbox is stopped outright.
  • Two races to close: finishJob becomes a no-op for jobs that aren't running/queued (so a cancelled launch that then errors can't flip the thread to "failed"), and launchJob re-checks the job after Sandbox.create and stops the fresh sandbox if the job was cancelled meanwhile.

UI

  • components/stop-run.tsx: two-tap button (like delete/visibility — "Stop" → red "Really stop?" for 4s → fires), rendered by the collapsed composer right next to Reply. Only rendered when thread.status === "running" and the viewer is a member.
Osebotfable-5-149d agothreadide@d2d52b0

Done on thread/8a6f80d2 (commit d2d52b0, pushed; no PR opened — say the word if you want one).

What you get

A Stop button next to Reply in the compose dock, rendered only while the thread status is running and you're a workspace member (same gate as asking Claude). It's two-tap like delete: first tap arms it (turns red, "Really stop?", disarms after 4s), second tap fires. Screenshot attached (phone mockup; desktop is the same row, just not stretched).

How a stop actually stops the run

POST /api/threads/[id]/stop → lib/agent/cancel.ts cancelThreadRuns():

  1. One UPDATE flips every queued/running job on the thread to the new job status cancelled (migration drizzle/0009_job_cancelled.sql) and clears runner_token. From then on every runner callback 401s, and runner.mjs already exits on its first 401/403 (exitLostJob from the liveness PR) — so the agent can't post or finish after a stop, in sandbox and local-worker mode. The local worker's own "is this job still mine?" check means it won't finishJob it either.
  2. The Vercel sandbox is stopped by sandbox_id immediately (no waiting for the next heartbeat / billable idle).
  3. An agent note "Run stopped by @login." is posted (kind progress: not emailed, not embedded).
  4. Thread status goes back to open — or waiting_on_human if the latest non-progress post is still an unanswered Claude question — and the existing DB triggers push the SSE status event so open tabs refresh and the button disappears. Merge-status sync runs too, so a previously-merged thread gets that back.

Two races closed while I was in there:

  • finishJob() is now a no-op unless the job is still running/queued. Without that, stopping during the clone/install phase made the launch's catch block post "The run crashed before finishing." and mark the thread failed, overwriting the stop.
  • launchJob() re-checks the job right after Sandbox.create (UPDATE … WHERE status='running') and stops the brand-new sandbox if the job was cancelled in the gap before it had a sandbox_id.

Caveats worth knowing

  • Commits the agent already pushed to the thread branch stay there, but no PR is opened for them at stop time (we don't know the commit shas without the runner's report). The next run on the thread resumes that branch and finishJob opens PRs then.
  • Guests can't stop (needs a session + membership). Non-member viewers never see the button.
  • Migration applies on the next production deploy via npm run build (ADD VALUE IF NOT EXISTS, same pattern as merged in 0004).
  • Verified with tsc --noEmit; the UI shot is a static mockup against the real globals.css (app can't run in the sandbox).
Compose dock while Claude runs (390px mockup): Reply · Stop · Top; right frame shows the armed "Really stop?" state after the first tap
Compose dock while Claude runs (390px mockup): Reply · Stop · Top; right frame shows the armed "Really stop?" state after the first tap
Diff · 11 files
diff --git a/app/api/threads/[id]/stop/route.ts b/app/api/threads/[id]/stop/route.ts
new file mode 100644
--- /dev/null
+++ threadide/app/api/threads/[id]/stop/route.ts
@@ -0,0 +1,19 @@
+import { NextResponse } from "next/server";
+import { cancelThreadRuns } from "@/lib/agent/cancel";
+import { guarded, requireThreadMember, requireUserApi } from "@/lib/session";
+
+type Params = { params: Promise<{ id: string }> };
+
+/**
+ * Stop Claude on this thread: cancels every queued/running job, kills its sandbox and reopens the
+ * thread. Same gate as asking Claude in the first place — workspace members (requireThreadMember).
+ * 409 when nothing is running, so a stale Stop button explains itself instead of silently succeeding.
+ */
+export const POST = guarded(async (_req: Request, { params }: Params) => {
+  const user = await requireUserApi();
+  const { id } = await params;
+  await requireThreadMember(id, user);
+  const { cancelled } = await cancelThreadRuns(id, user);
+  if (cancelled === 0) return NextResponse.json({ error: "Claude isn't running on this thread" }, { status: 409 });
+  return NextResponse.json({ ok: true, cancelled });
+});
diff --git a/app/globals.css b/app/globals.css
--- threadide/app/globals.css
+++ threadide/app/globals.css
@@ -438,7 +438,7 @@
 .compose-collapsed { display: flex; align-items: center; gap: 12px; font-size: 13px; }
 @media (max-width: 560px) {
   .compose-collapsed > button { flex: 1 1 auto; }
-  .compose-collapsed > button.jump-top { flex: none; }
+  .compose-collapsed > button.jump-top, .compose-collapsed > button.stop-run { flex: none; }
 }
@@ -446,6 +446,12 @@
 button.jump-top:hover:not(:disabled) { background: var(--accent); color: var(--on-accent); opacity: 1; }
+/* Stop button (components/stop-run.tsx): same outlined shape as Top, with a square "stop" glyph drawn in CSS
+   (no Unicode glyphs — font metrics differ per OS). Armed state turns red so the second tap is a conscious one. */
+button.stop-run { display: inline-flex; align-items: center; gap: 7px; background: none; color: var(--text); border: 1px solid var(--text); padding: 7px 14px; flex: none; }
+button.stop-run .stop-icon { width: 9px; height: 9px; background: currentColor; border-radius: 1px; }
+button.stop-run:hover:not(:disabled) { background: var(--accent); color: var(--on-accent); opacity: 1; }
+button.stop-run.armed, button.stop-run.armed:hover:not(:disabled) { color: #fff; background: var(--danger, #dc2626); border-color: var(--danger, #dc2626); }
diff --git a/app/threads/[id]/page.tsx b/app/threads/[id]/page.tsx
--- threadide/app/threads/[id]/page.tsx
+++ threadide/app/threads/[id]/page.tsx
@@ -146,7 +146,7 @@
-            <Composer threadId={thread.id} disabled={live} canAskClaude={canAskClaude} guest={!user} />
+            <Composer threadId={thread.id} disabled={live} canAskClaude={canAskClaude} guest={!user} canStop={live && canRunPosts} />
diff --git a/components/composer.tsx b/components/composer.tsx
--- threadide/components/composer.tsx
+++ threadide/components/composer.tsx
@@ -4,6 +4,7 @@
 import { JumpToTop } from "./jump-to-top";
+import { StopRunButton } from "./stop-run";
@@ -12,8 +13,21 @@
+ * canStop=true (thread is running and the viewer is a member): a Stop button sits next to Reply.
  */
-export function Composer({ threadId, disabled, canAskClaude = true, guest = false }: { threadId: string; disabled?: boolean; canAskClaude?: boolean; guest?: boolean }) {
+export function Composer({
+  threadId,
+  disabled,
+  canAskClaude = true,
+  guest = false,
+  canStop = false,
+}: {
+  threadId: string;
+  disabled?: boolean;
+  canAskClaude?: boolean;
+  guest?: boolean;
+  canStop?: boolean;
+}) {
@@ -116,6 +130,7 @@
           <button type="button" onClick={() => setOpen(true)}>
             Reply
           </button>
+          {canStop && <StopRunButton threadId={threadId} />}
           <JumpToTop />
diff --git a/components/stop-run.tsx b/components/stop-run.tsx
new file mode 100644
--- /dev/null
+++ threadide/components/stop-run.tsx
@@ -0,0 +1,40 @@
+"use client";
+import { useRouter } from "next/navigation";
+import { useState } from "react";
+import { failureMessage } from "@/lib/client-errors";
+
+/**
+ * Stop the run on this thread. Two-tap like delete: a stray tap must not kill a 20-minute run.
+ * Rendered only while the thread is `running` (the server page decides), next to Reply.
+ */
+export function StopRunButton({ threadId }: { threadId: string }) {
+  const router = useRouter();
+  const [armed, setArmed] = useState(false);
+  const [busy, setBusy] = useState(false);
+  const [error, setError] = useState<string | null>(null);
+
+  async function onClick() {
+    if (!armed) {
+      setArmed(true);
+      setTimeout(() => setArmed(false), 4000);
+      return;
+    }
+    setBusy(true);
+    setError(null);
+    const res = await fetch(`/api/threads/${threadId}/stop`, { method: "POST" });
+    setBusy(false);
+    setArmed(false);
+    if (res.ok || res.status === 409) router.refresh(); // 409 = already finished; the refresh drops the button
+    else setError(await failureMessage(res));
+  }
+
+  return (
+    <>
+      <button type="button" className={`stop-run${armed ? " armed" : ""}`} disabled={busy} onClick={onClick} title="Stop Claude's current run on this thread" aria-live="polite">
+        <span className="stop-icon" aria-hidden />
+        {busy ? "Stopping…" : armed ? "Really stop?" : "Stop"}
+      </button>
+      {error && <span className="danger-text">{error}</span>}
+    </>
+  );
+}
diff --git a/db/schema.ts b/db/schema.ts
--- threadide/db/schema.ts
+++ threadide/db/schema.ts
@@ -44,7 +44,8 @@
-export const jobStatus = pgEnum("job_status", ["queued", "running", "succeeded", "failed"]);
+// "cancelled" = a member pressed Stop (lib/agent/cancel.ts) while the job was queued/running.
+export const jobStatus = pgEnum("job_status", ["queued", "running", "succeeded", "failed", "cancelled"]);
diff --git a/drizzle/0009_job_cancelled.sql b/drizzle/0009_job_cancelled.sql
new file mode 100644
--- /dev/null
+++ threadide/drizzle/0009_job_cancelled.sql
@@ -0,0 +1,3 @@
+-- "cancelled" = a workspace member pressed Stop in the thread while the job was queued or running
+-- (lib/agent/cancel.ts). Distinct from "failed" so a deliberate stop never reads as a crash.
+ALTER TYPE "job_status" ADD VALUE IF NOT EXISTS 'cancelled';
diff --git a/lib/agent/cancel.ts b/lib/agent/cancel.ts
new file mode 100644
--- /dev/null
+++ threadide/lib/agent/cancel.ts
@@ -0,0 +1,68 @@
+/**
+ * Stop button: cancel every queued/running job on a thread.
+ *
+ * Mechanics. Flipping the job to `cancelled` and clearing runner_token is what actually stops the
+ * runner: lib/job-auth.ts authJob only accepts running jobs with a matching token, so the runner's
+ * next callback (a post, a heartbeat within 60s, /finish) gets a 401 and runner.mjs exitLostJob()
+ * exits on the spot. In sandbox mode we don't wait for that: the sandbox is stopped by id right
+ * here. The local dev worker's child exits the same way (401 → exit 2) and the worker then sees the
+ * job is no longer running+its token, so it doesn't finishJob() it either.
+ *
+ * Commits the agent already pushed stay on the thread branch (git uses its own token), but no PR
+ * is opened for them — the next run on the thread picks the branch up and finishJob opens PRs then.
+ */
+import { and, eq, inArray, ne } from "drizzle-orm";
+import { db, schema } from "@/db";
+import { addAgentPost, setThreadStatus } from "@/lib/data";
+import { syncThreadMergeStatus } from "@/lib/merge";
+
+const { jobs, posts, threads } = schema;
+
+export async function cancelThreadRuns(threadId: string, by: { login: string }) {
+  const thread = await db.query.threads.findFirst({ where: eq(threads.id, threadId) });
+  if (!thread) return { cancelled: 0 };
+
+  // One statement claims the jobs, so a runner's concurrent /finish (which also requires
+  // status=running) and this cancel can't both "win" the same job.
+  const cancelled = await db
+    .update(jobs)
+    .set({ status: "cancelled", runnerToken: null, finishedAt: new Date(), error: `stopped by ${by.login}` })
+    .where(and(eq(jobs.threadId, threadId), inArray(jobs.status, ["queued", "running"])))
+    .returning({ id: jobs.id, sandboxId: jobs.sandboxId });
+  if (cancelled.length === 0) return { cancelled: 0 };
+
+  // Billable minutes otherwise: the sandbox would idle until SANDBOX_TIMEOUT_MS.
+  for (const j of cancelled) if (j.sandboxId) void stopSandbox(j.sandboxId);
+
+  // Leave a trace in the thread. `progress` on purpose: not emailed, not embedded for retrieval.
+  await addAgentPost({
+    threadId,
+    workspaceId: thread.workspaceId,
+    kind: "progress",
+    body: `Run stopped by @${by.login}.`,
+    meta: { jobId: cancelled[0].id },
+  });
+
+  // Status as finishJob computes it, minus the note we just added: an unanswered question from an
+  // earlier run still waits on the human; anything else is simply open again.
+  const last = await db.query.posts.findFirst({
+    where: and(eq(posts.threadId, threadId), ne(posts.kind, "progress")),
+    orderBy: (p, { desc }) => desc(p.createdAt),
+  });
+  const status = last?.kind === "question_back" && last.author === "agent" ? "waiting_on_human" : "open";
+  await setThreadStatus(threadId, status); // threads_status_notify trigger → SSE "status" → tabs refresh
+  // A thread that was "merged" lost that when the run started; give it back if GitHub still agrees.
+  await syncThreadMergeStatus({ ...thread, status, prsCheckedAt: null }, 0).catch((e) => console.warn("[merge] sync skipped:", e instanceof Error ? e.message : e));
+
+  return { cancelled: cancelled.length };
+}
+
+async function stopSandbox(name: string) {
+  try {
+    const { Sandbox } = await import("@vercel/sandbox");
+    const sb = await Sandbox.get({ name });
+    await sb.stop();
+  } catch {
+    /* already gone; the sandbox timeout cleans up */
+  }
+}
diff --git a/lib/agent/finish.ts b/lib/agent/finish.ts
--- threadide/lib/agent/finish.ts
+++ threadide/lib/agent/finish.ts
@@ -27,6 +27,10 @@
   if (!job) return;
+  // Already closed out — by the runner's own /finish, stale recovery, or Stop (lib/agent/cancel.ts).
+  // A cancelled launch still errors its way into the catch block in launch.ts; without this guard
+  // that late failure would overwrite "stopped by X" with a "run crashed" post and a failed thread.
+  if (job.status !== "running" && job.status !== "queued") return;
   // Tear the sandbox down. It would time out on its own, but that's billable minutes.
diff --git a/lib/agent/launch.ts b/lib/agent/launch.ts
--- threadide/lib/agent/launch.ts
+++ threadide/lib/agent/launch.ts
@@ -8,7 +8,7 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
@@ -77,7 +77,13 @@
-    await db.update(jobs).set({ sandboxId: sandbox.name }).where(eq(jobs.id, jobId));
+    // Record the sandbox only if the job is still ours: Stop (lib/agent/cancel.ts) may have
+    // cancelled it during Sandbox.create, before there was a sandbox_id for it to kill.
+    const claimed = await db.update(jobs).set({ sandboxId: sandbox.name }).where(and(eq(jobs.id, jobId), eq(jobs.status, "running"))).returning({ id: jobs.id });
+    if (claimed.length === 0) {
+      await sandbox.stop().catch(() => {});
+      return;
+    }