From 4ef3b9d525170a612056411d046646221b8916ae Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:36:28 -0500 Subject: [PATCH 1/4] fix(server): Stop ends the agents' check-backs Pressing Stop interrupted the turn but left check-backs a Claude agent set (ScheduleWakeup, CronCreate) alive in its runtime, so a recurring one kept waking the agent and spending usage after the user stopped it. The Stop decision now also requests a check-back cancel for every agent in the thread that holds one, room agents included. The existing cancel path stops that agent's runtime, the only way to drop a schedule, along with background work it left running. Jobs saved to the project count too: they would fire in that runtime; they stay listed and come back the next time the agent runs. thread_stop on a child, local or on a linked computer, now treats a check-back as work to stop instead of answering not_running. --- apps/server/src/guide/topics.ts | 4 +- apps/server/src/links/LinkRequests.ts | 5 +- apps/server/src/mcp/threadToolHandlers.ts | 5 +- apps/server/src/mcp/threadTools.ts | 2 +- .../Layers/ProviderCommandReactor.test.ts | 55 +++++++++++++++++++ apps/server/src/orchestration/decider.ts | 25 ++++++++- docs/design/child-threads.md | 4 +- packages/shared/src/checkBacks.ts | 14 +++++ 8 files changed, 106 insertions(+), 8 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 3dbeb8dd0..e34af8b97 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -111,7 +111,7 @@ Whether the thread's agent may bring in another model on its own is {place:threa Once a thread it started has finished, the agent can wrap it up itself (thread_wrap), so you don't have to. It moves to Wrapped as with your own Wrap up, and its answer counts as seen. You can reopen it, and it comes back by itself when it gets new work. A thread still working or waiting for you isn't wrapped up. -A thread that keeps working after its answer went back (a check-back woke it, or a reviewer it asked replied) doesn't wake the parent. Its latest reply is passed to the parent's agent at that agent's next turn, and the thread then wraps up by itself. A thread the agent stops with thread_stop wraps up by itself too. +A thread that keeps working after its answer went back (a check-back woke it, or a reviewer it asked replied) doesn't wake the parent. Its latest reply is passed to the parent's agent at that agent's next turn, and the thread then wraps up by itself. A thread the agent stops with thread_stop wraps up by itself too, and its check-backs end, as with your Stop. {place:threads.agentThreads} decides this: Off, Ask me first (a card in the chat lists the threads and you decide), or Automatic. The same setting covers agents creating or changing scheduled tasks. There's no limit on how many threads an agent starts or how many messages it sends them, so an agent can keep a team of threads going for hours without you writing. Stop on the parent stops its agent and its threads' answers coming back, but the threads keep working; "Stop N working threads" in the parent's menu stops them too. @@ -227,7 +227,7 @@ Tasks run while Threadlines is running on that computer. A time missed while it Agents can list, create and change scheduled tasks when {place:threads.agentThreads} isn't Off; with Ask me first, a card asks you before a change takes effect. A task an agent sets up on a model already in the room runs at the reasoning you set for that agent, unless the agent or you name another level. -Below the tasks, Check-backs lists the threads an agent set itself to come back to, soonest first, with when and why. A row opens its thread, and Cancel ends the check-back (it stops that agent's session; one saved to the project has no Cancel). A thread with a check-back can still wrap up: in Wrapped its row shows a clock with the time left, and it comes back to the list when the agent does.`, +Below the tasks, Check-backs lists the threads an agent set itself to come back to, soonest first, with when and why. A row opens its thread, and Cancel ends the check-back (it stops that agent's session; one saved to the project has no Cancel). Stop in the thread ends every check-back its agents set, by stopping each such agent's session, so work it left running in the background stops too. One saved to the project goes quiet but stays listed, and comes back the next time that agent runs; ask the agent to delete it to end it for good. A thread with a check-back can still wrap up: in Wrapped its row shows a clock with the time left, and it comes back to the list when the agent does.`, }, { id: "outside-agents", diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index 4968193a9..e7b12f2f4 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -59,6 +59,7 @@ import { type ThreadRemoteOrigin, TurnId, } from "@threadlines/contracts"; +import { hasLiveCheckBack } from "@threadlines/shared/checkBacks"; import { sameRemoteThreadFiling } from "@threadlines/shared/childThreads"; import { remoteThreadFilingOf } from "@threadlines/shared/threadFiling"; import * as Cause from "effect/Cause"; @@ -1217,7 +1218,6 @@ const make = Effect.gen(function* () { }), ); - /** Whether a thread still has anything going: a turn, a session at work, queued messages. */ /** * Whether a thread's agent is at work: a turn, a session at work, a * background task. (Unlike isWorking, messages queued for later don't @@ -1235,6 +1235,8 @@ const make = Effect.gen(function* () { ); }; + /** Whether a thread still has anything going: a turn, a session at work, a + * check-back that would wake it later, queued messages. */ const isWorking = (thread: OrchestrationThread) => { const session = thread.session; return ( @@ -1244,6 +1246,7 @@ const make = Effect.gen(function* () { session.status === "running" || session.status === "starting" || (session.pendingBackgroundTaskCount ?? 0) > 0)) || + hasLiveCheckBack(thread) || (thread.queuedFollowUps ?? []).length > 0 ); }; diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index 543a6a7d9..2d3d297b3 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -50,6 +50,7 @@ import { TurnId, } from "@threadlines/contracts"; import { placeMarkdownLink } from "@threadlines/shared/appPlaces"; +import { hasLiveCheckBack } from "@threadlines/shared/checkBacks"; import { areFilesystemPathsEqual } from "@threadlines/shared/path"; import { saferRuntimeMode } from "@threadlines/shared/runtimeMode"; import { @@ -329,9 +330,11 @@ const remoteLabel = (thread: OrchestrationThread, environmentId: string) => ?.remote?.label ?? "the other computer"; -/** Whether a child has anything to stop: work in flight, or work its parent still waits on. */ +/** Whether a child has anything to stop: work in flight, a check-back that + * would wake it later, or work its parent still waits on. */ const childHasWork = (child: OrchestrationThread, parent: OrchestrationThread) => child.latestTurn?.state === "running" || + hasLiveCheckBack(child) || (child.session !== null && (child.session.activeTurnId !== null || child.session.status === "running" || diff --git a/apps/server/src/mcp/threadTools.ts b/apps/server/src/mcp/threadTools.ts index d92e8ba72..5f5253008 100644 --- a/apps/server/src/mcp/threadTools.ts +++ b/apps/server/src/mcp/threadTools.ts @@ -363,7 +363,7 @@ export const ThreadStopTool = loadedOnDemand( drivesThreads( Tool.make("thread_stop", { description: - "Stop one of your threads: its turn, its background work and its session. What you asked of it ends without an answer, and messages you queued for it are taken back. A later message starts it again. Only threads you started whose replies still come back to you.", + "Stop one of your threads: its turn, its background work, its check-backs and its session. What you asked of it ends without an answer, and messages you queued for it are taken back. A later message starts it again. Only threads you started whose replies still come back to you.", parameters: Schema.Struct({ threadId: ThreadIdParameter }), success: ThreadStopResult, }).annotate(Tool.Title, "Stop a thread"), diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 3ced4bd35..a15853b3b 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -4816,6 +4816,61 @@ describe("ProviderCommandReactor", () => { ]); }); + it("ends every room agent's check-backs on Stop, background work and saved jobs included", async () => { + const { harness, threadId, astraId, dispatch, now } = + await startRoomWithMessageQueuedForAstra(); + const astraKey = participantSessionKey(threadId, astraId); + const primary = harness.runtimeSessions.find((session) => session.threadId === threadId); + if (!primary) throw new Error("expected the primary runtime"); + // Astra runs a dev server it left behind and set itself a job saved to + // the project; the thread's own agent set a repeating check-back. + harness.runtimeSessions.push({ ...primary, threadId: astraKey, pendingBackgroundTaskCount: 1 }); + const checkBack = ( + id: string, + participantId: ThreadParticipantId | null, + durable: boolean, + ) => ({ + id, + participantId, + scheduledFor: "2026-01-01T01:00:00.000Z", + exact: false, + recurring: true, + durable, + }); + await dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make("cmd-primary-check-backs"), + threadId, + participantId: null, + checkBacks: [checkBack("loop-1", null, false)], + createdAt: now, + }); + await dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make("cmd-astra-saved-check-back"), + threadId, + participantId: astraId, + checkBacks: [checkBack("cron-saved", astraId, true)], + createdAt: now, + }); + + await dispatch({ + type: "thread.turn.interrupt", + commandId: CommandId.make("cmd-stop-with-check-backs"), + threadId, + createdAt: now, + }); + await waitFor(() => harness.stopSession.mock.calls.length >= 2); + await harness.drain(); + + expect(harness.interruptTurn.mock.calls.length).toBe(1); + // Each agent's runtime stops, the one running a dev server included. + expect(harness.stopSession.mock.calls.map(([input]) => input)).toEqual( + expect.arrayContaining([{ threadId }, { threadId: astraKey }]), + ); + expect(harness.stopSession.mock.calls.length).toBe(2); + }); + it("clears a stale check-back list but keeps the jobs saved to disk", async () => { const { harness, threadId, astraId, dispatch, now } = await startRoomWithMessageQueuedForAstra(); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 5ad269701..efa9f4d69 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -1193,6 +1193,27 @@ function holdCommandOutputOnStop( })); } +/** + * Stop: every agent in the thread that set itself a check-back has it + * cancelled, so a stopped agent never wakes itself up later. Nothing drops a + * schedule from a live runtime, so each such agent's runtime stops, with any + * background work it left running (the user asked to stop). Jobs saved to the + * project count too: they would fire in that runtime, and they come back + * from disk the next time the agent runs. + */ +function endCheckBacksOnStop( + thread: OrchestrationThread, + base: () => Omit, + createdAt: string, +): ReadonlyArray { + const agents = new Set((thread.checkBacks ?? []).map((checkBack) => checkBack.participantId)); + return [...agents].map((participantId) => ({ + ...base(), + type: "thread.check-back-cancel-requested" as const, + payload: { threadId: thread.id, participantId, stopBackgroundWork: true, createdAt }, + })); +} + /** * Clears the lead pointer of every project that names one of `threadIds` * (docs/design/lead-chat.md: archive and delete end a lead in the same @@ -4720,11 +4741,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }); // In a room, Stop also ends the agents' chain of requests; with child // threads, it ends what this thread was owed by its children, and a - // parent's requests still queued here are taken back. + // parent's requests still queued here are taken back. Every agent's + // check-backs end with it. const chainStop = [ ...decideAgentChainStop(thread, base, command.createdAt), ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), + ...endCheckBacksOnStop(thread, base, command.createdAt), // Stop is the user's say: a goal paused for a wait stays as Stop // leaves it, never resumed when the waits Stop ends are over. ...goalTakenByUser(thread, command), diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 144da30af..5d46b6bd3 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -28,7 +28,7 @@ T3 Code shipped the same idea in "orchestrator v2" (`delegate_task`, `create_thr - **Children inherit the parent's interaction mode** (plan stays plan) as well as its runtime mode. - **Batching several answers into one parent turn is dropped.** It needed multi-message turns, and it only saves a turn when answers land while the parent is busy. - **Cancelling stops queued answers too,** not just open requests. A final check before send catches answers already being prepared. -- **`thread_stop` stops the child's whole session,** background agents included. +- **`thread_stop` stops the child's whole session,** background agents and check-backs included. - **Requests and reports are marked separately,** and each gets its own preamble. - **Room specifics:** the requester leaving cancels its child traffic, and notes are delivered per recipient. - **Put back** is refused when it would create depth two. @@ -143,7 +143,7 @@ Side runtimes never get these tools: `roomToolsFor(side)` excludes them and the | `thread_list` | `scope?: "mine" \| "project" = "mine"` | The caller's children (attached and separated), or the project's non-archived threads (newest first, max 30). For each: id, title, status word, branch, model, attached, startedBy. | | `thread_read` | `threadId`, `after?`, `limit? = 20` | Same project only. Recent user and assistant messages (each clipped at 4,000 chars, with a flag), status, and a `next` cursor. | | `thread_send` | `threadId`, `message` | The caller's attached children only. If the child is idle, starts a turn. If busy, queues behind its current turn. The answer comes back like a start. Returns `sent`, `queued` or `not_yours`. | -| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. Returns `stopped` or `not_running`. | +| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. A child idle but for a check-back that would wake it (`hasLiveCheckBack` in `@threadlines/shared/checkBacks`) counts as running, so the stop ends it. Returns `stopped` or `not_running`. | | `thread_wrap` | `threadIds: 1..20` | The caller's attached children only, and only finished ones. Wraps each up as the user's Wrap up does (`thread.done-override.set` with `byParentAgent`) and marks it seen; a child on a linked computer is wrapped on the parent's record (`thread.remote-child.done-override.set`) and sent on. Returns `ok` with one outcome per thread: `wrapped`, `working`, `not_yours`, `refused` or `failed`. See "Wrapped up by the parent's agent". | - **Reasoning.** A child's reasoning is settled when it is asked for (`settleChildReasoning` in childThreadAgents.ts) and saved in its launch, so replay and approval use exactly what the card showed. In order: a level named in `agent.reasoning` (id or picker label; `"default"` for the provider's own); a reasoning option passed in `agent.options`, refused if the model doesn't offer it; the level of the first agent on the same provider kind and model among the caller, the room's other agents still in it, and the user's default for new threads. The first matching agent decides: one that names no level leaves it to the provider, and a level the model doesn't offer (another computer's catalog can differ) is refused with the model's levels rather than quietly dropped. Only the reasoning follows, never other options (a fast service tier is the user's to choose); Claude's retired `ultracode` effort follows as Extra High, without the Ultracode switch it implied. Matching is by provider kind and model, so it works across computers too. The approval card shows the level beside the model. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index d744f4257..a499715a2 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -90,3 +90,17 @@ export function runtimeCheckBackOwed( (checkBack.exact ? CHECK_BACK_EXACT_GRACE_MS : CHECK_BACK_SCHEDULE_GRACE_MS); return Number.isFinite(due) && nowMs < due; } + +/** + * Whether one of the thread's agents can still wake itself up: a check-back + * that lives in its runtime, or one saved to the project while the thread's + * session is up (it fires there too). A stop counts it as work to stop. + */ +export function hasLiveCheckBack(thread: { + readonly checkBacks?: ReadonlyArray | undefined; + readonly session?: { readonly status: string } | null | undefined; +}): boolean { + const checkBacks = thread.checkBacks ?? []; + const sessionUp = thread.session != null && thread.session.status !== "stopped"; + return checkBacks.some((checkBack) => !checkBack.durable) || (sessionUp && checkBacks.length > 0); +} From c97e9392dc3bfd54caa26b7b04b347cf61563314 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:58:08 -0500 Subject: [PATCH 2/4] fix(server): Stop sees check-backs set during the turn it stops Claude reports its check-back list only when a turn ends, and a stopped turn may never get there, so Stop missed a check-back set earlier in that same turn. The adapter now publishes the list as soon as ScheduleWakeup, CronCreate or CronDelete returns; Claude's report at the turn's end replaces it whole. thread_stop now counts any check-back, including one saved to the project: in a room, the thread's single session doesn't show whether another agent's runtime is still up. For a child on a linked computer, the stop goes even when the child reads as idle, since only that computer can see its check-backs, and it stops the child only if something is still going. --- apps/server/src/mcp/threadToolHandlers.ts | 20 ++--- .../provider/Drivers/ClaudeCheckBacks.test.ts | 43 +++++++++ .../src/provider/Drivers/ClaudeCheckBacks.ts | 90 +++++++++++++++++++ .../src/provider/Layers/ClaudeAdapter.test.ts | 14 ++- .../src/provider/Layers/ClaudeAdapter.ts | 21 ++++- docs/design/child-threads.md | 18 ++-- packages/shared/src/checkBacks.ts | 12 ++- 7 files changed, 182 insertions(+), 36 deletions(-) diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index 2d3d297b3..46bd7635d 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -2218,17 +2218,11 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { const open = thread.childRequests.open.filter( (request) => request.childThreadId === child.threadId, ); - if ( - open.length === 0 && - child.cachedStatus !== "working" && - child.cachedStatus !== "waiting" - ) { - return { - outcome: "not_running", - detail: "It isn't working on anything, and nothing you asked of it is waiting.", - threadId: child.threadId, - } satisfies ThreadStopResult; - } + // A quiet child may still have a check-back there, which this computer + // can't see: the stop goes anyway, and that computer stops it only if + // it has something going (stopIfWorking in LinkRequests.ts). + const quiet = + open.length === 0 && child.cachedStatus !== "working" && child.cachedStatus !== "waiting"; const key = [ scope.threadId, scope.participantId ?? "primary", @@ -2252,7 +2246,9 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { } return { outcome: "stopped", - detail: `Stopped. ${child.label} is told to stop it; nothing more comes back from it for what you asked. A later thread_send starts it again.`, + detail: quiet + ? `${child.label} is told to stop it if it still has anything going there, such as a check-back. A later thread_send starts it again.` + : `Stopped. ${child.label} is told to stop it; nothing more comes back from it for what you asked. A later thread_send starts it again.`, threadId: child.threadId, } satisfies ThreadStopResult; }), diff --git a/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts b/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts index 3c3663be0..5230b1a59 100644 --- a/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeCheckBacks.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from "vite-plus/test"; import { claudeCheckBackTrigger, + claudeCheckBacksAfterScheduleTool, claudeCheckBacksFromSessionCrons, makeClaudeCheckBackState, recordClaudeScheduleTool, @@ -10,6 +11,48 @@ import { const at = (iso: string) => Date.parse(iso); describe("Claude check-backs", () => { + it("lists a check-back as soon as its tool returns, before the turn's report", () => { + const state = makeClaudeCheckBackState(); + const now = at("2026-10-20T15:27:30Z"); + const after = (call: { toolName: string; input: unknown; result: unknown }) => + claudeCheckBacksAfterScheduleTool(state, call, now, "UTC"); + const cron = { + toolName: "CronCreate", + input: { cron: "*/5 * * * *", prompt: "Look at the deploy", recurring: true }, + result: { id: "job-1", humanSchedule: "every 5 minutes", recurring: true }, + }; + expect(after(cron)).toEqual([ + { + id: "job-1", + scheduledFor: "2026-10-20T15:30:00.000Z", + exact: false, + recurring: true, + schedule: "every 5 minutes", + description: "Look at the deploy", + prompt: "Look at the deploy", + cron: "*/5 * * * *", + durable: false, + }, + ]); + // The same job again changes nothing. + expect(after(cron)).toBeUndefined(); + const wakeup = after({ + toolName: "ScheduleWakeup", + input: { delaySeconds: 900, reason: "Waiting for CI", prompt: "Check CI" }, + result: { scheduledFor: at("2026-10-20T15:42:00Z") }, + }); + expect(wakeup?.map((checkBack) => [checkBack.scheduledFor, checkBack.exact])).toEqual([ + ["2026-10-20T15:30:00.000Z", false], + ["2026-10-20T15:42:00.000Z", true], + ]); + expect( + after({ toolName: "CronDelete", input: { id: "job-1" }, result: undefined })?.map( + (checkBack) => checkBack.description, + ), + ).toEqual(["Waiting for CI"]); + expect(after({ toolName: "ScheduleWakeup", input: {}, result: { stopped: true } })).toEqual([]); + }); + it("states a wake-up's exact time and reason, and a cron job's wording and next run", () => { const state = makeClaudeCheckBackState(); recordClaudeScheduleTool(state, { diff --git a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts index 1d61e52cf..66752395f 100644 --- a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts +++ b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts @@ -151,6 +151,96 @@ export function recordClaudeScheduleTool( } } +/** + * The session's list right after a scheduling tool call took effect, before + * Claude reports its own at the turn's end. A turn the user stops may never + * get that far, and Stop reads the published list to know which agents still + * have a check-back to end. Claude's next report replaces this list whole. + * Undefined when the call changed nothing. + */ +export function claudeCheckBacksAfterScheduleTool( + state: ClaudeCheckBackState, + call: { readonly toolName: string; readonly input: unknown; readonly result: unknown }, + nowMs: number, + timeZone: string | undefined, +): ReadonlyArray | undefined { + const input = asRecord(call.input) ?? {}; + // A delete's input names its job; the other tools' results say what they set. + const result = asRecord(call.result) ?? {}; + const without = (drop: (checkBack: RuntimeCheckBack) => boolean) => { + const kept = state.current.filter((checkBack) => !drop(checkBack)); + return kept.length === state.current.length ? undefined : kept; + }; + const withAdded = (checkBack: RuntimeCheckBack) => + [...state.current, checkBack].toSorted((left, right) => + left.scheduledFor.localeCompare(right.scheduledFor), + ); + let next: ReadonlyArray | undefined; + if (call.toolName === "ScheduleWakeup") { + if (result.stopped === true) { + // Wake-ups are the only exact-time jobs. + next = without((checkBack) => checkBack.exact); + } else { + const prompt = asString(input.prompt); + const scheduledForMs = result.scheduledFor; + if (!prompt || typeof scheduledForMs !== "number" || !Number.isFinite(scheduledForMs)) { + return undefined; + } + const scheduledFor = new Date(scheduledForMs).toISOString(); + if ( + state.current.some( + (checkBack) => checkBack.exact && checkBack.scheduledFor === scheduledFor, + ) + ) { + return undefined; + } + const description = clip(asString(input.reason) ?? prompt); + const kept = keptPrompt(prompt); + next = withAdded({ + // Claude names the job only in its report; until then the time does. + id: `wakeup:${scheduledForMs}`, + scheduledFor, + exact: true, + recurring: false, + ...(description ? { description } : {}), + ...(kept ? { prompt: kept } : {}), + durable: false, + }); + } + } else if (call.toolName === "CronCreate") { + const id = asString(result.id); + const prompt = asString(input.prompt); + const cron = asString(input.cron)?.trim(); + if (!id || !prompt || !cron || state.current.some((checkBack) => checkBack.id === id)) { + return undefined; + } + const fire = nextCronMatch(cron, new Date(nowMs), timeZone); + if (!fire) return undefined; + const recurring = result.recurring === true; + const schedule = recurring ? asString(result.humanSchedule) : undefined; + const description = clip(prompt); + const kept = keptPrompt(prompt); + next = withAdded({ + id, + scheduledFor: fire.toISOString(), + exact: false, + recurring, + ...(schedule ? { schedule } : {}), + ...(description ? { description } : {}), + ...(kept ? { prompt: kept } : {}), + cron, + durable: result.durable === true, + }); + } else if (call.toolName === "CronDelete") { + const id = asString(input.id); + if (!id) return undefined; + next = without((checkBack) => checkBack.id === id); + } + if (next === undefined) return undefined; + state.current = next; + return next; +} + /** * When a reported job fires next. A wake-up's stated time is exact. A cron * job's is worked out from its schedule in Claude's time zone, once: a diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 9699ac197..aa1780091 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -1935,7 +1935,12 @@ describe("ClaudeAdapterLive", () => { }, }, } as unknown as SDKMessage); - const created = yield* nextEvent("item.completed"); + // Listed as soon as the tool returns, before the turn's own report. + const toolReturned = yield* Stream.filter( + adapter.streamEvents, + (event) => + event.type === "item.completed" || event.type === "session.check-backs.updated", + ).pipe(Stream.take(2), Stream.runCollect, Effect.forkChild); harness.query.emit({ type: "user", session_id: "sdk-session-check-back", @@ -1952,7 +1957,9 @@ describe("ClaudeAdapterLive", () => { durable: false, }, } as unknown as SDKMessage); - const createdItem = yield* Fiber.join(created); + const returned = yield* Fiber.join(toolReturned); + const update = returned.find((event) => event.type === "session.check-backs.updated"); + const createdItem = returned.find((event) => event.type === "item.completed"); // Scheduling a check-back is a tool call, not a file change. assert.equal( createdItem?.type === "item.completed" ? createdItem.payload.itemType : null, @@ -1969,14 +1976,13 @@ describe("ClaudeAdapterLive", () => { } as unknown as SDKMessage); yield* Fiber.join(turnDone); - const reported = yield* nextEvent("session.check-backs.updated"); + // Claude's report at the turn's end says the same. yield* runHook("Stop", { hook_event_name: "Stop", session_crons: [ { id: "job-1", schedule: "*/5 * * * *", recurring: true, prompt: "Look at the deploy" }, ], }); - const update = yield* Fiber.join(reported); assert.equal(update?.type, "session.check-backs.updated"); if (update?.type !== "session.check-backs.updated") return; assert.deepEqual( diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 1c7e5099f..ef722a7f9 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -202,6 +202,7 @@ import { } from "../Drivers/ClaudeGoals.ts"; import { claudeCheckBackTrigger, + claudeCheckBacksAfterScheduleTool, claudeCheckBacksFromSessionCrons, isClaudeCheckBackTool, makeClaudeCheckBackState, @@ -6411,17 +6412,29 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const [index, tool] = toolEntry; // A check-back's exact time, reason and job id are only in the - // scheduling tool's own result (one tool_result per such message). + // scheduling tool's own result (one tool_result per such message). The + // change is published at once: Stop must see it if the turn never + // reaches Claude's own report at its end. if ( - (tool.toolName === "ScheduleWakeup" || tool.toolName === "CronCreate") && + (tool.toolName === "ScheduleWakeup" || + tool.toolName === "CronCreate" || + tool.toolName === "CronDelete") && toolResults.length === 1 && !toolResult.isError ) { - recordClaudeScheduleTool(context.checkBacks, { + const call = { toolName: tool.toolName, input: tool.input, result: (message as { readonly tool_use_result?: unknown }).tool_use_result, - }); + }; + recordClaudeScheduleTool(context.checkBacks, call); + const checkBacks = claudeCheckBacksAfterScheduleTool( + context.checkBacks, + call, + Date.now(), + nonEmptyString(claudeEnvironment.TZ), + ); + if (checkBacks !== undefined) yield* emitCheckBacksUpdated(context, checkBacks); } if (tool.itemType === "collab_agent_tool_call") { // Background agents settle after this tool_result; keep the launch so diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 5d46b6bd3..03b60c00f 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -136,15 +136,15 @@ hasAgentRecords || agentInvitesMode !== "off" || agentThreadsMode !== "off"; Side runtimes never get these tools: `roomToolsFor(side)` excludes them and the handler re-checks `scope.side === undefined`. Every tool answers with an `outcome` literal and never blocks on child work. -| Tool | Input | Behavior | -| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `thread_agents` | none | Ready provider instances and models a child can run on, each model with its reasoning levels. Also `yours` (the caller's model and reasoning) and, in a room, `room` (the other agents still in it, each with the reasoning the user set). Respects `agentThreads`, not invites. Excludes per-use-billed sign-ins, as invites do (`PER_USE_AUTH_TYPES`), and providers that cannot honor the caller's interaction mode. | -| `thread_start` | `threads: 1..5 × { title, prompt, agent?: { instanceId, model, reasoning?, options? }, runSetup?: boolean = true }`, `reportBack?: boolean = true` | Starts threads in the caller's project, each in its own new worktree off the caller's current branch (see Workspaces). `agent` defaults to the caller's model and reasoning. The description steers the agent to its own model or one already in the room unless the user asked otherwise. A named agent's reasoning is settled as described under Reasoning. `reportBack: false` starts them already separated, so nothing comes back. Returns `started` with `[{ threadId, title, model, reasoning? }]`, `asked_user`, `off`, `not_allowed`, `unavailable_agent`, or `refused` (a reasoning level the model doesn't have). | -| `thread_list` | `scope?: "mine" \| "project" = "mine"` | The caller's children (attached and separated), or the project's non-archived threads (newest first, max 30). For each: id, title, status word, branch, model, attached, startedBy. | -| `thread_read` | `threadId`, `after?`, `limit? = 20` | Same project only. Recent user and assistant messages (each clipped at 4,000 chars, with a flag), status, and a `next` cursor. | -| `thread_send` | `threadId`, `message` | The caller's attached children only. If the child is idle, starts a turn. If busy, queues behind its current turn. The answer comes back like a start. Returns `sent`, `queued` or `not_yours`. | -| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. A child idle but for a check-back that would wake it (`hasLiveCheckBack` in `@threadlines/shared/checkBacks`) counts as running, so the stop ends it. Returns `stopped` or `not_running`. | -| `thread_wrap` | `threadIds: 1..20` | The caller's attached children only, and only finished ones. Wraps each up as the user's Wrap up does (`thread.done-override.set` with `byParentAgent`) and marks it seen; a child on a linked computer is wrapped on the parent's record (`thread.remote-child.done-override.set`) and sent on. Returns `ok` with one outcome per thread: `wrapped`, `working`, `not_yours`, `refused` or `failed`. See "Wrapped up by the parent's agent". | +| Tool | Input | Behavior | +| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `thread_agents` | none | Ready provider instances and models a child can run on, each model with its reasoning levels. Also `yours` (the caller's model and reasoning) and, in a room, `room` (the other agents still in it, each with the reasoning the user set). Respects `agentThreads`, not invites. Excludes per-use-billed sign-ins, as invites do (`PER_USE_AUTH_TYPES`), and providers that cannot honor the caller's interaction mode. | +| `thread_start` | `threads: 1..5 × { title, prompt, agent?: { instanceId, model, reasoning?, options? }, runSetup?: boolean = true }`, `reportBack?: boolean = true` | Starts threads in the caller's project, each in its own new worktree off the caller's current branch (see Workspaces). `agent` defaults to the caller's model and reasoning. The description steers the agent to its own model or one already in the room unless the user asked otherwise. A named agent's reasoning is settled as described under Reasoning. `reportBack: false` starts them already separated, so nothing comes back. Returns `started` with `[{ threadId, title, model, reasoning? }]`, `asked_user`, `off`, `not_allowed`, `unavailable_agent`, or `refused` (a reasoning level the model doesn't have). | +| `thread_list` | `scope?: "mine" \| "project" = "mine"` | The caller's children (attached and separated), or the project's non-archived threads (newest first, max 30). For each: id, title, status word, branch, model, attached, startedBy. | +| `thread_read` | `threadId`, `after?`, `limit? = 20` | Same project only. Recent user and assistant messages (each clipped at 4,000 chars, with a flag), status, and a `next` cursor. | +| `thread_send` | `threadId`, `message` | The caller's attached children only. If the child is idle, starts a turn. If busy, queues behind its current turn. The answer comes back like a start. Returns `sent`, `queued` or `not_yours`. | +| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. A child idle but for a check-back that would wake it (`hasLiveCheckBack` in `@threadlines/shared/checkBacks`) counts as running, so the stop ends it. A child on a linked computer is sent the stop even when it reads as idle, since this computer can't see its check-backs; that computer stops it only if it has something going (`stopIfWorking`). Returns `stopped` or `not_running`. | +| `thread_wrap` | `threadIds: 1..20` | The caller's attached children only, and only finished ones. Wraps each up as the user's Wrap up does (`thread.done-override.set` with `byParentAgent`) and marks it seen; a child on a linked computer is wrapped on the parent's record (`thread.remote-child.done-override.set`) and sent on. Returns `ok` with one outcome per thread: `wrapped`, `working`, `not_yours`, `refused` or `failed`. See "Wrapped up by the parent's agent". | - **Reasoning.** A child's reasoning is settled when it is asked for (`settleChildReasoning` in childThreadAgents.ts) and saved in its launch, so replay and approval use exactly what the card showed. In order: a level named in `agent.reasoning` (id or picker label; `"default"` for the provider's own); a reasoning option passed in `agent.options`, refused if the model doesn't offer it; the level of the first agent on the same provider kind and model among the caller, the room's other agents still in it, and the user's default for new threads. The first matching agent decides: one that names no level leaves it to the provider, and a level the model doesn't offer (another computer's catalog can differ) is refused with the model's levels rather than quietly dropped. Only the reasoning follows, never other options (a fast service tier is the user's to choose); Claude's retired `ultracode` effort follows as Extra High, without the Ultracode switch it implied. Matching is by provider kind and model, so it works across computers too. The approval card shows the level beside the model. - **Depth 1.** A thread that is currently an attached child gets `not_allowed` from `thread_start`, `thread_send`, `thread_stop` and `thread_wrap`. It can still read and list. A separated child counts as top-level. diff --git a/packages/shared/src/checkBacks.ts b/packages/shared/src/checkBacks.ts index a499715a2..8b069a412 100644 --- a/packages/shared/src/checkBacks.ts +++ b/packages/shared/src/checkBacks.ts @@ -92,15 +92,13 @@ export function runtimeCheckBackOwed( } /** - * Whether one of the thread's agents can still wake itself up: a check-back - * that lives in its runtime, or one saved to the project while the thread's - * session is up (it fires there too). A stop counts it as work to stop. + * Whether one of the thread's agents can still wake itself up. A job saved + * to the project counts too: in a room, the thread's session says nothing of + * the other agents' runtimes, where it may still fire. A stop counts it as + * work to stop. */ export function hasLiveCheckBack(thread: { readonly checkBacks?: ReadonlyArray | undefined; - readonly session?: { readonly status: string } | null | undefined; }): boolean { - const checkBacks = thread.checkBacks ?? []; - const sessionUp = thread.session != null && thread.session.status !== "stopped"; - return checkBacks.some((checkBack) => !checkBack.durable) || (sessionUp && checkBacks.length > 0); + return (thread.checkBacks ?? []).length > 0; } From a3e0fc43ff1b22cb484272624194b63aca08c113 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:08:44 -0500 Subject: [PATCH 3/4] fix(server): close the gaps a second review found in Stop ending check-backs - A check-back the stopped turn set, reported just after Stop read the list, is cancelled by ingestion while the session's Stop is pending. - A fresh Claude runtime's updates before its first report are partial: ingestion keeps the saved jobs already listed instead of dropping them. - The cancel stops a runtime only if its provider sets check-backs, so a saved Claude job on an agent now running Codex can't stop Codex. - Removing a link stops a thread it started that has only a check-back. - thread_stop no longer sends a stop to a quiet child on a linked computer: it could kill a turn started there before a delayed stop lands. A check-back-only linked child is a documented limit. --- apps/server/src/links/LinkRequests.ts | 3 +- apps/server/src/mcp/threadToolHandlers.ts | 22 ++++-- .../Layers/ProviderCommandReactor.test.ts | 45 +++++++++++- .../Layers/ProviderCommandReactor.ts | 14 +++- .../Layers/ProviderRuntimeIngestion.test.ts | 73 +++++++++++++++++++ .../Layers/ProviderRuntimeIngestion.ts | 43 +++++++++-- .../src/provider/Drivers/ClaudeCheckBacks.ts | 12 ++- .../src/provider/Layers/ClaudeAdapter.ts | 15 +++- docs/design/child-threads.md | 18 ++--- packages/contracts/src/providerRuntime.ts | 5 +- 10 files changed, 218 insertions(+), 32 deletions(-) diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts index e7b12f2f4..94e01de50 100644 --- a/apps/server/src/links/LinkRequests.ts +++ b/apps/server/src/links/LinkRequests.ts @@ -1780,7 +1780,8 @@ const make = Effect.gen(function* () { const thread = yield* readThreadOrFail(threadId); if (thread === undefined || thread.deletedAt !== null) return; if (thread.remoteOrigin?.linkDeviceId !== deviceId) return; - if (!isRunning(thread)) return; + // A check-back would wake it later with nobody there to hear back. + if (!isRunning(thread) && !hasLiveCheckBack(thread)) return; // A turn asked for once the link was off is this computer's user's. const turnsBefore = options?.turnsBefore; const requestedAt = thread.latestTurn?.requestedAt; diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index 46bd7635d..004259121 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -2218,11 +2218,19 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { const open = thread.childRequests.open.filter( (request) => request.childThreadId === child.threadId, ); - // A quiet child may still have a check-back there, which this computer - // can't see: the stop goes anyway, and that computer stops it only if - // it has something going (stopIfWorking in LinkRequests.ts). - const quiet = - open.length === 0 && child.cachedStatus !== "working" && child.cachedStatus !== "waiting"; + // A check-back there doesn't show in its status here, so a quiet child + // with one is not reached (a known limit, docs/design/child-threads.md). + if ( + open.length === 0 && + child.cachedStatus !== "working" && + child.cachedStatus !== "waiting" + ) { + return { + outcome: "not_running", + detail: "It isn't working on anything, and nothing you asked of it is waiting.", + threadId: child.threadId, + } satisfies ThreadStopResult; + } const key = [ scope.threadId, scope.participantId ?? "primary", @@ -2246,9 +2254,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { } return { outcome: "stopped", - detail: quiet - ? `${child.label} is told to stop it if it still has anything going there, such as a check-back. A later thread_send starts it again.` - : `Stopped. ${child.label} is told to stop it; nothing more comes back from it for what you asked. A later thread_send starts it again.`, + detail: `Stopped. ${child.label} is told to stop it; nothing more comes back from it for what you asked. A later thread_send starts it again.`, threadId: child.threadId, } satisfies ThreadStopResult; }), diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index a15853b3b..76b88c720 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -207,6 +207,8 @@ describe("ProviderCommandReactor", () => { readonly sessionModelSwitch?: "unsupported" | "in-session"; readonly nativeThreadFork?: "supported" | "unsupported"; readonly activeTurnSteering?: "supported" | "unsupported"; + /** Whether the agents' provider sets check-backs (it does unless told). */ + readonly checkBacks?: "supported" | "unsupported"; /** Fail session starts that request a native fork, to exercise the * context-seed fallback path. */ readonly failNativeForkStart?: boolean; @@ -580,6 +582,7 @@ describe("ProviderCommandReactor", () => { Effect.succeed({ sessionModelSwitch: input?.sessionModelSwitch ?? "in-session", activeTurnSteering: input?.activeTurnSteering ?? "supported", + checkBacks: input?.checkBacks ?? "supported", ...(input?.nativeThreadFork !== undefined ? { nativeThreadFork: input.nativeThreadFork } : {}), @@ -2777,8 +2780,10 @@ describe("ProviderCommandReactor", () => { * waits in the queue. `settle` ends the turn with the given background * counts. */ - async function startRoomWithMessageQueuedForAstra() { - const harness = await createHarness(); + async function startRoomWithMessageQueuedForAstra( + harnessInput?: Parameters[0], + ) { + const harness = await createHarness(harnessInput); const now = "2026-01-01T00:00:00.000Z"; const threadId = ThreadId.make("thread-1"); const astraId = ThreadParticipantId.make("7a0b1c2d-3e4f-4a5b-8c6d-7e8f9a0b1c2d"); @@ -4871,6 +4876,42 @@ describe("ProviderCommandReactor", () => { expect(harness.stopSession.mock.calls.length).toBe(2); }); + it("leaves a runtime whose provider sets no check-backs running on Stop", async () => { + // The agent switched from Claude: its job saved to the project is still + // listed, but the runtime now running (with a dev server) can't fire it. + const { harness, threadId, dispatch, now } = await startRoomWithMessageQueuedForAstra({ + checkBacks: "unsupported", + }); + const saved = { + id: "cron-saved", + participantId: null, + scheduledFor: "2026-01-01T01:00:00.000Z", + exact: false, + recurring: true, + durable: true, + }; + await dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make("cmd-saved-claude-check-back"), + threadId, + participantId: null, + checkBacks: [saved], + createdAt: now, + }); + await dispatch({ + type: "thread.turn.interrupt", + commandId: CommandId.make("cmd-stop-other-provider"), + threadId, + createdAt: now, + }); + await waitFor(() => harness.interruptTurn.mock.calls.length > 0); + await harness.drain(); + + expect(harness.stopSession.mock.calls.length).toBe(0); + const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); + expect(thread?.checkBacks).toEqual([saved]); + }); + it("clears a stale check-back list but keeps the jobs saved to disk", async () => { const { harness, threadId, astraId, dispatch, now } = await startRoomWithMessageQueuedForAstra(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index e94a543fe..9ec25d344 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -5066,9 +5066,17 @@ const make = Effect.gen(function* () { yield* note("Check-back not cancelled: couldn't reach the agent's session", "error"); return; } - if (runtime === undefined) { - // Nothing is running to come back: the list was stale. Jobs saved to - // disk outlive the session, so they stay. + // A runtime whose provider sets no check-backs (the agent switched from + // Claude, say) holds none of them, so it is left running. + const holdsCheckBacks = + runtime?.providerInstanceId === undefined || + (yield* providerService.getCapabilities(runtime.providerInstanceId).pipe( + Effect.map((capabilities) => capabilities.checkBacks === "supported"), + Effect.orElseSucceed(() => true), + )); + if (runtime === undefined || !holdsCheckBacks) { + // Nothing is running that could come back: the list was stale. Jobs + // saved to disk outlive the session, so they stay. const thread = yield* resolveThread(threadId); const kept = (thread?.checkBacks ?? []).filter( (checkBack) => checkBack.participantId === participantId && checkBack.durable, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 48de77782..150266202 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -1310,6 +1310,79 @@ describe("ProviderRuntimeIngestion", () => { ).toEqual(["check-back.skipped"]); }); + it("ends a check-back the stopped turn set, and keeps saved jobs a partial list lacks", async () => { + const harness = await createHarness(); + const now = "2026-01-01T00:00:00.000Z"; + const threadId = asThreadId("thread-1"); + const dispatch = (command: Parameters[0]) => + Effect.runPromise(harness.engine.dispatch(command)); + const saved = { + id: "cron-saved", + participantId: null, + scheduledFor: "2026-01-02T09:00:00.000Z", + exact: false, + recurring: true, + durable: true, + }; + await dispatch({ + type: "thread.check-backs.set", + commandId: CommandId.make("cmd-saved-job"), + threadId, + participantId: null, + checkBacks: [saved], + createdAt: now, + }); + await dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-claude-working"), + threadId, + session: { + threadId, + status: "running", + providerName: "claudeAgent", + runtimeMode: "approval-required", + activeTurnId: asTurnId("turn-1"), + updatedAt: now, + lastError: null, + }, + createdAt: now, + }); + await dispatch({ + type: "thread.turn.interrupt", + commandId: CommandId.make("cmd-stop"), + threadId, + createdAt: now, + }); + const cancelsSoFar = async () => + (await Effect.runPromise(Stream.runCollect(harness.engine.readEvents(0)))).filter( + (event) => event.type === "thread.check-back-cancel-requested", + ).length; + const cancelsAtStop = await cancelsSoFar(); + + // A fresh runtime's first word, from the turn just stopped: a new job, + // before Claude reported the saved one it restored. + const wakeup = { + id: "wakeup:1", + scheduledFor: "2026-01-01T00:15:00.000Z", + exact: true, + recurring: false, + durable: false, + }; + harness.emit({ + type: "session.check-backs.updated", + eventId: asEventId("evt-check-backs-after-stop"), + provider: ProviderDriverKind.make("claudeAgent"), + threadId, + createdAt: now, + payload: { checkBacks: [wakeup], partial: true }, + }); + await harness.drain(); + + const thread = (await harness.readModel()).threads.find((entry) => entry.id === threadId); + expect(thread?.checkBacks).toEqual([{ ...wakeup, participantId: null }, saved]); + expect(await cancelsSoFar()).toBe(cancelsAtStop + 1); + }); + it("maps turn started/completed events into thread session updates", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index dbe3b4490..2fa3744ce 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -2948,19 +2948,52 @@ const make = Effect.gen(function* () { const current = (thread.checkBacks ?? []).filter( (checkBack) => checkBack.participantId === participantId, ); - if (!sameCheckBacks(current, event.payload.checkBacks)) { + const reported = event.payload.checkBacks.map((checkBack) => ({ + ...checkBack, + participantId, + })); + // A runtime that hasn't reported its own list yet may not know the jobs + // saved to the project it restored: the ones listed stay. + const next = event.payload.partial + ? [ + ...reported, + ...current.filter( + (listed) => + listed.durable && !reported.some((checkBack) => checkBack.id === listed.id), + ), + ].toSorted((left, right) => left.scheduledFor.localeCompare(right.scheduledFor)) + : reported; + if (!sameCheckBacks(current, next)) { yield* orchestrationEngine.dispatch({ type: "thread.check-backs.set", commandId: providerCommandId(event, "check-backs-set"), threadId: thread.id, participantId, - checkBacks: event.payload.checkBacks.map((checkBack) => ({ - ...checkBack, - participantId, - })), + checkBacks: next, createdAt: event.createdAt, }); } + // A check-back set by the turn the user just stopped, reported after + // Stop read the list: it ends as Stop's own would have. + const session = thread.session; + const added = next.some((checkBack) => !current.some((listed) => listed.id === checkBack.id)); + if ( + added && + session !== null && + (session.stopRequestedTurnId ?? null) !== null && + sessionSlotParticipantId(session) === participantId + ) { + yield* orchestrationEngine + .dispatch({ + type: "thread.check-back.cancel", + commandId: providerCommandId(event, "check-back-cancel-after-stop"), + threadId: thread.id, + participantId, + stopBackgroundWork: true, + createdAt: event.createdAt, + }) + .pipe(Effect.ignoreCause({ log: true })); + } // A move's stop ends them on purpose: it carries them (docs/design/fleet.md, Part 3e, (b)). const movingTo = (thread.pendingMove ?? thread.move ?? null)?.target.label; for (const [index, ended] of (event.payload.ended ?? []).entries()) { diff --git a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts index 66752395f..92d9eb23c 100644 --- a/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts +++ b/apps/server/src/provider/Drivers/ClaudeCheckBacks.ts @@ -52,10 +52,20 @@ export interface ClaudeCheckBackState { readonly prompts: Map; /** The list as last reported to orchestration. */ current: ReadonlyArray; + /** Whether Claude has reported its own list in this session. Until then + * the list may lack jobs saved to the project that the CLI restored. */ + reported: boolean; } export function makeClaudeCheckBackState(): ClaudeCheckBackState { - return { wakeups: [], crons: new Map(), nextFire: new Map(), prompts: new Map(), current: [] }; + return { + wakeups: [], + crons: new Map(), + nextFire: new Map(), + prompts: new Map(), + current: [], + reported: false, + }; } /** Longest reason or prompt a check-back carries. */ diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index ef722a7f9..294299256 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -5284,7 +5284,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( provider: PROVIDER, createdAt: stamp.createdAt, threadId: context.session.threadId, - payload: { checkBacks, ...(ended && ended.length > 0 ? { ended } : {}) }, + payload: { + checkBacks, + ...(ended && ended.length > 0 ? { ended } : {}), + ...(context.checkBacks.reported ? {} : { partial: true }), + }, providerRefs: nativeProviderRefs(context), }); }); @@ -8937,6 +8941,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const context = yield* Ref.get(contextRef); const sessionCrons = (hookInput as { session_crons?: unknown }).session_crons; if (!context || context.stopped || !Array.isArray(sessionCrons)) return {}; + const firstReport = !context.checkBacks.reported; + context.checkBacks.reported = true; const checkBacks = claudeCheckBacksFromSessionCrons( context.checkBacks, sessionCrons.flatMap((cron) => { @@ -8957,7 +8963,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( Date.now(), nonEmptyString(claudeEnvironment.TZ), ); - if (!sameCheckBacks(context.checkBacks.current, checkBacks)) { + // The first report is whole: after a partial list it is sent even + // when it reads the same, to settle the saved jobs that list kept. + if ( + (firstReport && context.checkBacks.current.length > 0) || + !sameCheckBacks(context.checkBacks.current, checkBacks) + ) { context.checkBacks.current = checkBacks; yield* emitCheckBacksUpdated(context, checkBacks); } diff --git a/docs/design/child-threads.md b/docs/design/child-threads.md index 03b60c00f..7518f29cc 100644 --- a/docs/design/child-threads.md +++ b/docs/design/child-threads.md @@ -136,15 +136,15 @@ hasAgentRecords || agentInvitesMode !== "off" || agentThreadsMode !== "off"; Side runtimes never get these tools: `roomToolsFor(side)` excludes them and the handler re-checks `scope.side === undefined`. Every tool answers with an `outcome` literal and never blocks on child work. -| Tool | Input | Behavior | -| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `thread_agents` | none | Ready provider instances and models a child can run on, each model with its reasoning levels. Also `yours` (the caller's model and reasoning) and, in a room, `room` (the other agents still in it, each with the reasoning the user set). Respects `agentThreads`, not invites. Excludes per-use-billed sign-ins, as invites do (`PER_USE_AUTH_TYPES`), and providers that cannot honor the caller's interaction mode. | -| `thread_start` | `threads: 1..5 × { title, prompt, agent?: { instanceId, model, reasoning?, options? }, runSetup?: boolean = true }`, `reportBack?: boolean = true` | Starts threads in the caller's project, each in its own new worktree off the caller's current branch (see Workspaces). `agent` defaults to the caller's model and reasoning. The description steers the agent to its own model or one already in the room unless the user asked otherwise. A named agent's reasoning is settled as described under Reasoning. `reportBack: false` starts them already separated, so nothing comes back. Returns `started` with `[{ threadId, title, model, reasoning? }]`, `asked_user`, `off`, `not_allowed`, `unavailable_agent`, or `refused` (a reasoning level the model doesn't have). | -| `thread_list` | `scope?: "mine" \| "project" = "mine"` | The caller's children (attached and separated), or the project's non-archived threads (newest first, max 30). For each: id, title, status word, branch, model, attached, startedBy. | -| `thread_read` | `threadId`, `after?`, `limit? = 20` | Same project only. Recent user and assistant messages (each clipped at 4,000 chars, with a flag), status, and a `next` cursor. | -| `thread_send` | `threadId`, `message` | The caller's attached children only. If the child is idle, starts a turn. If busy, queues behind its current turn. The answer comes back like a start. Returns `sent`, `queued` or `not_yours`. | -| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. A child idle but for a check-back that would wake it (`hasLiveCheckBack` in `@threadlines/shared/checkBacks`) counts as running, so the stop ends it. A child on a linked computer is sent the stop even when it reads as idle, since this computer can't see its check-backs; that computer stops it only if it has something going (`stopIfWorking`). Returns `stopped` or `not_running`. | -| `thread_wrap` | `threadIds: 1..20` | The caller's attached children only, and only finished ones. Wraps each up as the user's Wrap up does (`thread.done-override.set` with `byParentAgent`) and marks it seen; a child on a linked computer is wrapped on the parent's record (`thread.remote-child.done-override.set`) and sent on. Returns `ok` with one outcome per thread: `wrapped`, `working`, `not_yours`, `refused` or `failed`. See "Wrapped up by the parent's agent". | +| Tool | Input | Behavior | +| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `thread_agents` | none | Ready provider instances and models a child can run on, each model with its reasoning levels. Also `yours` (the caller's model and reasoning) and, in a room, `room` (the other agents still in it, each with the reasoning the user set). Respects `agentThreads`, not invites. Excludes per-use-billed sign-ins, as invites do (`PER_USE_AUTH_TYPES`), and providers that cannot honor the caller's interaction mode. | +| `thread_start` | `threads: 1..5 × { title, prompt, agent?: { instanceId, model, reasoning?, options? }, runSetup?: boolean = true }`, `reportBack?: boolean = true` | Starts threads in the caller's project, each in its own new worktree off the caller's current branch (see Workspaces). `agent` defaults to the caller's model and reasoning. The description steers the agent to its own model or one already in the room unless the user asked otherwise. A named agent's reasoning is settled as described under Reasoning. `reportBack: false` starts them already separated, so nothing comes back. Returns `started` with `[{ threadId, title, model, reasoning? }]`, `asked_user`, `off`, `not_allowed`, `unavailable_agent`, or `refused` (a reasoning level the model doesn't have). | +| `thread_list` | `scope?: "mine" \| "project" = "mine"` | The caller's children (attached and separated), or the project's non-archived threads (newest first, max 30). For each: id, title, status word, branch, model, attached, startedBy. | +| `thread_read` | `threadId`, `after?`, `limit? = 20` | Same project only. Recent user and assistant messages (each clipped at 4,000 chars, with a flag), status, and a `next` cursor. | +| `thread_send` | `threadId`, `message` | The caller's attached children only. If the child is idle, starts a turn. If busy, queues behind its current turn. The answer comes back like a start. Returns `sent`, `queued` or `not_yours`. | +| `thread_stop` | `threadId` | The caller's attached children only. Stops the child's whole session: the turn, background agents and workflows (`thread.session.stop`; the next message resumes it). The parent's requests for that child settle `stopped` without waking it. The parent's messages still queued in the child are taken back. A child idle but for a check-back that would wake it (`hasLiveCheckBack` in `@threadlines/shared/checkBacks`) counts as running, so the stop ends it. A child on a linked computer is reached only when its last status says working or waiting, or a request to it is open: its status doesn't carry check-backs, so a quiet one that only has a check-back answers `not_running` and keeps it (known limit). When the stop does go, that computer also ends its check-backs (`stopIfWorking`). Returns `stopped` or `not_running`. | +| `thread_wrap` | `threadIds: 1..20` | The caller's attached children only, and only finished ones. Wraps each up as the user's Wrap up does (`thread.done-override.set` with `byParentAgent`) and marks it seen; a child on a linked computer is wrapped on the parent's record (`thread.remote-child.done-override.set`) and sent on. Returns `ok` with one outcome per thread: `wrapped`, `working`, `not_yours`, `refused` or `failed`. See "Wrapped up by the parent's agent". | - **Reasoning.** A child's reasoning is settled when it is asked for (`settleChildReasoning` in childThreadAgents.ts) and saved in its launch, so replay and approval use exactly what the card showed. In order: a level named in `agent.reasoning` (id or picker label; `"default"` for the provider's own); a reasoning option passed in `agent.options`, refused if the model doesn't offer it; the level of the first agent on the same provider kind and model among the caller, the room's other agents still in it, and the user's default for new threads. The first matching agent decides: one that names no level leaves it to the provider, and a level the model doesn't offer (another computer's catalog can differ) is refused with the model's levels rather than quietly dropped. Only the reasoning follows, never other options (a fast service tier is the user's to choose); Claude's retired `ultracode` effort follows as Extra High, without the Ultracode switch it implied. Matching is by provider kind and model, so it works across computers too. The approval card shows the level beside the model. - **Depth 1.** A thread that is currently an attached child gets `not_allowed` from `thread_start`, `thread_send`, `thread_stop` and `thread_wrap`. It can still read and list. A separated child counts as top-level. diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.ts index fc8f986a9..c77323735 100644 --- a/packages/contracts/src/providerRuntime.ts +++ b/packages/contracts/src/providerRuntime.ts @@ -566,11 +566,14 @@ export type RuntimeCheckBack = typeof RuntimeCheckBack.Type; /** * The session's pending check-backs, whole (an authoritative level signal). * `ended`: ones that will not fire because the runtime stopped while they - * were pending. + * were pending. `partial`: the runtime hasn't reported its own list yet, so + * jobs saved to the project that it restored may be missing; ones already + * listed as saved are kept. */ const SessionCheckBacksUpdatedPayload = Schema.Struct({ checkBacks: Schema.Array(RuntimeCheckBack), ended: Schema.optional(Schema.Array(RuntimeCheckBack)), + partial: Schema.optional(Schema.Boolean), }); export type SessionCheckBacksUpdatedPayload = typeof SessionCheckBacksUpdatedPayload.Type; From 50c2016b27a879d7791d02a0a5106976002c3c62 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:42:25 -0500 Subject: [PATCH 4/4] test(server): update the tool size budget for the longer thread_stop description thread_stop now says a quiet child with only a check-back counts as running and is stopped, and what happens for a child on a linked computer. That is 17 bytes, worth it so the agent knows a stop ends the child's check-backs. --- apps/server/src/provider/agentContextBudget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 710c1675a..575ee04bd 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -17,5 +17,5 @@ "show_page" ], "upFrontToolDefinitionBytes": 18074, - "onDemandToolDefinitionBytes": 50661 + "onDemandToolDefinitionBytes": 50678 }