Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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",
Expand Down
8 changes: 6 additions & 2 deletions apps/server/src/links/LinkRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand All @@ -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 (
Expand All @@ -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
);
};
Expand Down Expand Up @@ -1777,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;
Expand Down
7 changes: 6 additions & 1 deletion apps/server/src/mcp/threadToolHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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" ||
Expand Down Expand Up @@ -2215,6 +2218,8 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
const open = thread.childRequests.open.filter(
(request) => request.childThreadId === child.threadId,
);
// 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" &&
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/threadTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down
100 changes: 98 additions & 2 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 }
: {}),
Expand Down Expand Up @@ -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<typeof createHarness>[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");
Expand Down Expand Up @@ -4816,6 +4821,97 @@ 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("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();
Expand Down
14 changes: 11 additions & 3 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof harness.engine.dispatch>[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";
Expand Down
43 changes: 38 additions & 5 deletions apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
Loading
Loading