diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 3023485b4..c0bfda765 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -308,7 +308,7 @@ When Claude Code refuses to start (a settings file that is not valid JSON, a bad If Codex's sign-in goes stale in a chat before it has started on your message, Threadlines restarts Codex and sends the message again, once, with a note in the chat. If that fails too, the chat asks you to sign in. -When a Claude or Codex usage limit stops a thread, the notice above the composer says which limit and when it resets. Its Continue at reset switch sends "Continue where you left off." a minute after the reset, from the computer the thread runs on (a Mac that wakes only briefly for upkeep waits until it's fully awake), or within a few minutes of the limit resetting early because the user spent a limit reset, and {place:threads.continueAfterUsageLimits} turns it on for every limit. If you added another account of the same agent that still has room, the notice offers it by name. Threadlines never switches accounts on its own.`, +When a Claude or Codex usage limit stops a thread, the notice above the composer says which limit and when it resets. Its Continue at reset switch sends "Continue where you left off." a minute after the reset, from the computer the thread runs on (a Mac that wakes only briefly for upkeep waits until it's fully awake), or within a few minutes of the limit resetting early because the user spent a limit reset, and {place:threads.continueAfterUsageLimits} turns it on for every limit. With it on, a thread another thread's agent started on this computer also waits for the reset instead of failing, and its answer goes back once it continues; so does a thread hearing back from one it started. Stop ends the wait, and a turn you stopped never comes back by itself. If you added another account of the same agent that still has room, the notice offers it by name. Threadlines never switches accounts on its own.`, }, { id: "plugins-skills-instructions", diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts index 906a1bc37..7a0c722ff 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.test.ts @@ -384,6 +384,140 @@ describe("ChildThreadReactor", () => { ), ); + describe("a child errored on a usage limit (docs/design/lead-chat.md, ruling 3)", () => { + const erroredTurn = TurnId.make("child-turn-1"); + const asked = { + id: CHILD_MESSAGE, + role: "user" as const, + text: "Write it.", + fromThread: { threadId: PARENT, requestId: REQUEST, kind: "request" as const }, + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }; + const errored = (overrides: Partial = {}) => + thread(CHILD, { + messages: [asked], + latestTurn: { + turnId: erroredTurn, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + session: { + threadId: CHILD, + status: "error", + providerName: "codex", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: "You've hit your usage limit", + updatedAt: now, + }, + ...overrides, + }); + const sessionChanged = (harness: Harness) => + PubSub.publish(harness.events, { + type: "thread.session-set", + payload: { threadId: CHILD }, + } as unknown as OrchestrationEvent); + + it.effect("waits for a late turn end that arms the wait, and then holds the request", () => + withReactor([parentWith([]), errored()], {}, (harness) => + Effect.gen(function* () { + // The request opens after startup, so no restart pass settles it. + harness.threads.set(PARENT, parentWith([request()])); + yield* sessionChanged(harness); + yield* settle; + // Past today's 5 s: its turn hasn't ended, so nothing settles yet. + yield* TestClock.adjust(Duration.seconds(6)); + yield* settle; + expect(settles(harness)).toEqual([]); + // The turn's end arrives with the reset: the wait is armed. + harness.threads.set( + CHILD, + errored({ + latestTurn: { + turnId: erroredTurn, + state: "error", + requestedAt: now, + startedAt: now, + completedAt: now, + assistantMessageId: null, + }, + session: { + threadId: CHILD, + status: "error", + providerName: "codex", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: "You've hit your usage limit", + continueAtReset: { resetsAt: now, at: now }, + updatedAt: now, + }, + }), + ); + yield* TestClock.adjust(Duration.seconds(15)); + yield* settle; + expect(settles(harness)).toEqual([]); + }), + ), + ); + + it.effect("settles the request failed at the bound when the turn's end never comes", () => + withReactor([parentWith([]), errored()], {}, (harness) => + Effect.gen(function* () { + // The request opens after startup, so no restart pass settles it. + harness.threads.set(PARENT, parentWith([request()])); + yield* sessionChanged(harness); + yield* settle; + yield* TestClock.adjust(Duration.seconds(19)); + yield* settle; + expect(settles(harness)).toEqual([]); + yield* TestClock.adjust(Duration.seconds(2)); + yield* settle; + expect(settles(harness)).toMatchObject([{ outcome: "failed" }]); + }), + ), + ); + + it.effect("keeps a held request across a restart", () => + withReactor( + [ + parentWith([request()]), + errored({ + latestTurn: { + turnId: erroredTurn, + state: "error", + requestedAt: now, + startedAt: now, + completedAt: now, + assistantMessageId: null, + }, + session: { + threadId: CHILD, + status: "error", + providerName: "codex", + runtimeMode: "auto-accept-edits", + activeTurnId: null, + lastError: "You've hit your usage limit", + continueAtReset: { resetsAt: now, at: now }, + updatedAt: now, + }, + }), + ], + {}, + (harness) => + Effect.gen(function* () { + yield* settle; + expect(settles(harness)).toEqual([]); + }), + ), + ); + }); + it.effect("starts a child with no more access than its parent has now", () => withReactor( [ diff --git a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts index a03e3c0c6..34b5b9497 100644 --- a/apps/server/src/orchestration/Layers/ChildThreadReactor.ts +++ b/apps/server/src/orchestration/Layers/ChildThreadReactor.ts @@ -33,6 +33,7 @@ import { childDeliveryAfterRestart, childDeliveryForQuietCandidate, finishedTurnAfterRestart, + isHeldByContinueAtReset, isQuietCandidate, } from "../childThreadDelivery.ts"; import { @@ -58,6 +59,16 @@ const QUIET_GRACE = Duration.seconds(15); */ const STOP_GRACE = Duration.seconds(5); +/** + * How long an errored child whose answering turn hasn't ended yet gets for + * that end before its request is settled from the error. A provider can + * report the session's error first and the turn's end, with a usage limit's + * reset time, later: Codex refreshes usage first and gives up on that after + * 15 s (freshProviderSnapshot). The turn's end decides whether the request + * waits to continue at the reset (docs/design/lead-chat.md, ruling 3). + */ +const LATE_TURN_END_GRACE = Duration.seconds(20); + type ReactorEvent = Extract< OrchestrationEvent, { type: "thread.child-request-submitted" | "thread.child-request-updated" | "thread.session-set" } @@ -282,6 +293,19 @@ export const makeChildThreadReactor = Effect.gen(function* () { if ((status === "stopped" || status === "error") && !stopChecks.has(childId)) { stopChecks.add(childId); yield* Effect.sleep(STOP_GRACE).pipe( + // An error whose turn hasn't ended yet: its end may still come, + // with the reset time, up to the bound; then the error settles it. + Effect.andThen( + status === "error" + ? readThread(childId).pipe( + Effect.flatMap((latest) => + latest?.latestTurn?.state === "running" + ? Effect.sleep(Duration.subtract(LATE_TURN_END_GRACE, STOP_GRACE)) + : Effect.void, + ), + ) + : Effect.void, + ), Effect.andThen(settleStoppedAnswers(parent.id, childId, status)), Effect.ensuring(Effect.sync(() => stopChecks.delete(childId))), Effect.forkDetach, @@ -325,7 +349,9 @@ export const makeChildThreadReactor = Effect.gen(function* () { for (const request of parent.childRequests.open) { if ( request.childThreadId !== childId || - (request.status !== "running" && request.status !== "awaiting_background") + (request.status !== "running" && request.status !== "awaiting_background") || + // Waiting to continue at a usage limit's reset: the continue answers it. + isHeldByContinueAtReset(child, request) ) { continue; } @@ -406,6 +432,11 @@ export const makeChildThreadReactor = Effect.gen(function* () { }); continue; } + // Still waiting to continue at a usage limit's reset (the wait is + // kept across a restart): the continue answers it. + if (isHeldByContinueAtReset(child, request)) { + continue; + } const childTurns = yield* turns .listByThreadId({ threadId: child.id }) .pipe(Effect.orElseSucceed(() => [] as const)); diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 142322932..7b7bc6a3d 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -2156,6 +2156,18 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti yield* projectionThreadSessionRepository.setContinueAtReset(event.payload); return; } + // Stop names the turn it is for: no usage limit brings that turn back. + if ( + (event.type === "thread.turn-interrupt-requested" || + event.type === "thread.session-stop-requested") && + event.payload.stopsTurnId !== undefined + ) { + yield* projectionThreadSessionRepository.setStopRequested({ + threadId: event.payload.threadId, + turnId: event.payload.stopsTurnId, + }); + return; + } if (event.type !== "thread.session-set") { return; } @@ -2183,6 +2195,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti lastErrorDismissedAt: event.payload.session.lastErrorDismissedAt ?? null, lastErrorUsageLimit: event.payload.session.lastErrorUsageLimit ?? null, continueAtReset: event.payload.session.continueAtReset ?? null, + stopRequestedTurnId: event.payload.session.stopRequestedTurnId ?? null, updatedAt: event.payload.session.updatedAt, }); }); diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index 33a9945b6..1c4e72762 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -575,6 +575,7 @@ function mapSessionRow( ...(row.lastErrorDismissedAt ? { lastErrorDismissedAt: row.lastErrorDismissedAt } : {}), ...(row.lastErrorUsageLimit ? { lastErrorUsageLimit: row.lastErrorUsageLimit } : {}), ...(row.continueAtReset ? { continueAtReset: row.continueAtReset } : {}), + ...(row.stopRequestedTurnId ? { stopRequestedTurnId: row.stopRequestedTurnId } : {}), updatedAt: row.updatedAt, }; } @@ -1399,6 +1400,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { last_error_dismissed_at AS "lastErrorDismissedAt", last_error_usage_limit AS "lastErrorUsageLimit", continue_at_reset AS "continueAtReset", + stop_requested_turn_id AS "stopRequestedTurnId", updated_at AS "updatedAt" FROM projection_thread_sessions ORDER BY thread_id ASC @@ -1454,6 +1456,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sessions.last_error_dismissed_at AS "lastErrorDismissedAt", sessions.last_error_usage_limit AS "lastErrorUsageLimit", sessions.continue_at_reset AS "continueAtReset", + sessions.stop_requested_turn_id AS "stopRequestedTurnId", sessions.updated_at AS "updatedAt" FROM projection_thread_sessions sessions INNER JOIN projection_threads threads @@ -1489,6 +1492,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { sessions.last_error_dismissed_at AS "lastErrorDismissedAt", sessions.last_error_usage_limit AS "lastErrorUsageLimit", sessions.continue_at_reset AS "continueAtReset", + sessions.stop_requested_turn_id AS "stopRequestedTurnId", sessions.updated_at AS "updatedAt" FROM projection_thread_sessions sessions INNER JOIN projection_threads threads @@ -2403,6 +2407,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { last_error_dismissed_at AS "lastErrorDismissedAt", last_error_usage_limit AS "lastErrorUsageLimit", continue_at_reset AS "continueAtReset", + stop_requested_turn_id AS "stopRequestedTurnId", updated_at AS "updatedAt" FROM projection_thread_sessions WHERE thread_id = ${threadId} @@ -3876,6 +3881,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { last_error_dismissed_at AS "lastErrorDismissedAt", last_error_usage_limit AS "lastErrorUsageLimit", continue_at_reset AS "continueAtReset", + stop_requested_turn_id AS "stopRequestedTurnId", + stop_requested_turn_id AS "stopRequestedTurnId", updated_at AS "updatedAt" FROM projection_thread_sessions WHERE ${sql.in("thread_id", threadIds)} diff --git a/apps/server/src/orchestration/childThreadDelivery.ts b/apps/server/src/orchestration/childThreadDelivery.ts index 766340246..3f188bf5c 100644 --- a/apps/server/src/orchestration/childThreadDelivery.ts +++ b/apps/server/src/orchestration/childThreadDelivery.ts @@ -18,6 +18,7 @@ import { } from "@threadlines/contracts"; import { childReportMessageId, childReportText } from "./childThreadDecisions.ts"; +import { turnStartingMessage } from "./continueTurns.ts"; /** What the delivery rules read of a request, wherever it is kept. */ export type ChildDeliveryRequest = Pick< @@ -157,6 +158,11 @@ export function childDeliveryForTurnEnd(input: { ); } if (end.outcome === "failed") { + // A usage limit paused it: the request waits for the continue at the + // reset, which answers it (docs/design/lead-chat.md, "Usage limits"). + if (isHeldByContinueAtReset(child, request)) { + return null; + } const error = end.error ?? "Its turn did not finish."; return settle( request, @@ -174,6 +180,63 @@ export function childDeliveryForTurnEnd(input: { ); } +/** + * Whether a parent's request is held open by the child's wait to continue + * after a usage limit (docs/design/lead-chat.md, "Usage limits"): the child + * waits to continue at the reset, and the request is `running` and answered + * by the turn that stopped on the limit. Only such a request is held: one + * waiting on background work (`awaiting_background`) follows its own path. + */ +export function isHeldByContinueAtReset( + child: OrchestrationThread, + request: ChildDeliveryRequest, +): boolean { + const session = child.session; + return ( + session !== null && + (session.continueAtReset ?? null) !== null && + request.status === "running" && + request.childMessageId === failedTurnMessage(child)?.id + ); +} + +/** + * The message that started the child's last turn, not counting messages still + * waiting in its queue: an agent's message is written into the chat when it + * is queued, so the newest user message may not have run yet. + */ +export function failedTurnMessage(child: OrchestrationThread) { + const session = child.session; + if (session === null) return undefined; + const queued = new Set((child.queuedFollowUps ?? []).map((entry) => entry.messageId)); + if (queued.size === 0) return turnStartingMessage(child, session); + return turnStartingMessage( + { ...child, messages: child.messages.filter((message) => !queued.has(message.id)) }, + session, + ); +} + +/** + * A held request whose wait ended without its continue: it settles as it + * would have when its turn stopped, with why it did not go on. + */ +export function heldRequestEnded( + child: OrchestrationThread, + request: ChildDeliveryRequest, + outcome: "failed" | "stopped", + why: string, +): Extract { + const text = + outcome === "stopped" + ? `The user stopped '${child.title}' while it waited for a usage limit to reset.` + : `'${child.title}' stopped on a usage limit and won't continue: ${why}`; + const delivery = settle(request, outcome, `${text}${partialAnswer(child, request)}`, null); + return { + ...(delivery as Extract), + ...(outcome === "failed" ? { error: why } : {}), + }; +} + /** * A child whose turn ended while it waited on background work has gone quiet * with nothing left running and no follow-up turn: its answer so far stands. diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 8aad8d2cd..52f4e0506 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -113,7 +113,12 @@ import { settleParentRequestsForUnqueued, withinModeCeiling, } from "./childThreadDecisions.ts"; -import { childDeliveryForQuietCandidate } from "./childThreadDelivery.ts"; +import { + childDeliveryForQuietCandidate, + failedTurnMessage, + heldRequestEnded, + isHeldByContinueAtReset, +} from "./childThreadDelivery.ts"; import { turnLiftsMoveFence } from "./linkFence.ts"; import { projectEvent } from "./projector.ts"; import { checkoutSelectedEvents, leavesLentWorktree, movesCheckout } from "./threadCheckout.ts"; @@ -588,18 +593,47 @@ function refuseSkippedSetup( * it) is carried the same way. The wait to continue after it goes as soon as * a turn starts; only the decider arms it (`withArmedContinueAtReset`, * `thread.continue-at-reset.*`), so a writer's copy is ignored too. + * + * The turn the user asked to stop (`stopRequestedTurnId`, set by the Stop + * events) is kept until another turn starts, whatever the writer sent. */ function withLastErrorState( next: OrchestrationSession, prior: OrchestrationSession | null | undefined, at: string, usageLimit?: OrchestrationSessionUsageLimit, +): OrchestrationSession { + const stopped = carriedStopRequest(next, prior); + const withStop = (session: OrchestrationSession): OrchestrationSession => + stopped === null ? session : { ...session, stopRequestedTurnId: stopped }; + return withStop(withLastErrorStamps(next, prior, at, usageLimit)); +} + +/** + * The stopped turn a session update keeps: until a turn starts (the session + * is starting, or running another turn than the one stopped). + */ +function carriedStopRequest( + next: OrchestrationSession, + prior: OrchestrationSession | null | undefined, +) { + const stopped = prior?.stopRequestedTurnId ?? null; + if (stopped === null || next.status === "starting") return null; + return next.activeTurnId !== null && next.activeTurnId !== stopped ? null : stopped; +} + +function withLastErrorStamps( + next: OrchestrationSession, + prior: OrchestrationSession | null | undefined, + at: string, + usageLimit?: OrchestrationSessionUsageLimit, ): OrchestrationSession { const { lastErrorAt: sentAt, lastErrorDismissedAt: _sentDismissedAt, lastErrorUsageLimit: _sentUsageLimit, continueAtReset: _sentContinueAtReset, + stopRequestedTurnId: _sentStopRequestedTurnId, ...session } = next; if (next.lastError === null) { @@ -716,11 +750,16 @@ function continueAtResetWaiting( * on a failure: always when the stopped turn was itself a continue (the user * asked this thread to keep going), and with the setting on when the user * asked for it (typed it, moved it to another account, or it is a turn a - * restart cut off that Threadlines continued). A turn a scheduled - * run, another thread or a room agent started waits for the user: continuing - * it would not finish the run or answer the request. + * restart cut off that Threadlines continued). With the setting on, also a + * turn answering its parent's request on this computer, whose request then + * waits for the continue, and a report turn in a thread no parent waits on + * (docs/design/lead-chat.md, "Usage limits"). A turn a scheduled run, a + * linked computer, an outside agent or a room agent started waits for the + * user: continuing it would not finish the run or answer the request. + * Never for a turn the user asked to stop. */ function withArmedContinueAtReset( + readModel: OrchestrationReadModel, thread: OrchestrationThread, session: OrchestrationSession, prior: OrchestrationSession | null, @@ -729,6 +768,8 @@ function withArmedContinueAtReset( const resetsAt = session.lastErrorUsageLimit?.resetsAt ?? null; // The user asked to move this thread: that wins over an automatic retry here. if ((thread.pendingMove ?? null) !== null) return session; + // The user stopped this turn: a limit landing after Stop never brings it back. + if ((session.stopRequestedTurnId ?? null) !== null) return session; if ( resetsAt === null || session.continueAtReset != null || @@ -749,10 +790,71 @@ function withArmedContinueAtReset( if (startedBy === undefined) return session; const continuing = startedBy.trigger === "usageLimitReset"; const fromUser = !continuing && userAskedForTurn(startedBy); - if (!continuing && !(settingOn && fromUser)) return session; + // Read past messages still queued: an agent's is written when it queues. + const ran = failedTurnMessage({ ...thread, session }) ?? startedBy; + const forAnotherThread = + !continuing && + ran.trigger === undefined && + (answersHeldableRequest(readModel, thread, session, ran) || + reportsToTopLevel(thread, session, ran)); + if (!continuing && !(settingOn && (fromUser || forAnotherThread))) return session; return { ...session, continueAtReset: continueAtResetFor(resetsAt) }; } +/** + * The turn answers its parent's request on this computer, still `running`: + * the request can wait for the continue. Not a lead chat's pass (nothing is + * owed for one), a linked computer's request, a room agent's turn, or a + * child stopped on a Codex goal the limit paused (its continue sends no + * message to answer with). + */ +function answersHeldableRequest( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + session: OrchestrationSession, + startedBy: OrchestrationMessage, +): boolean { + const origin = startedBy.fromThread; + if ( + origin === undefined || + origin.kind !== "request" || + origin.environmentId !== undefined || + origin.ceiling !== undefined || + !isAttachedChild(thread) || + thread.parentThreadId !== origin.threadId || + (thread.remoteOrigin ?? null) !== null || + sessionSlotParticipantId(session) !== null || + thread.goal?.status === "usageLimited" + ) { + return false; + } + const parent = readModel.threads.find((entry) => entry.id === origin.threadId); + return ( + parent?.childRequests.open.some( + (request) => + request.requestId === origin.requestId && + request.childThreadId === thread.id && + request.remote === undefined && + request.status === "running" && + request.childMessageId === startedBy.id, + ) === true + ); +} + +/** A report from one of its threads, heard in a thread no parent waits on. */ +function reportsToTopLevel( + thread: OrchestrationThread, + session: OrchestrationSession, + startedBy: OrchestrationMessage, +): boolean { + return ( + startedBy.fromThread?.kind === "report" && + !isAttachedChild(thread) && + (thread.remoteOrigin ?? null) === null && + sessionSlotParticipantId(session) === null + ); +} + /** * Whether a thread already has the user's work in it: a user message, or a * turn running or about to. A thread made without a message (the goal flow's, @@ -1038,6 +1140,97 @@ function leadClearEvents( })); } +/** The parent's requests a child's wait to continue holds open (`isHeldByContinueAtReset`). */ +function heldRequestsOf( + readModel: OrchestrationReadModel, + child: OrchestrationThread, +): { + readonly parent: OrchestrationThread; + readonly held: OrchestrationThread["childRequests"]["open"]; +} | null { + if (!isAttachedChild(child) || child.parentThreadId === null) return null; + const parent = readModel.threads.find((entry) => entry.id === child.parentThreadId); + if (parent === undefined) return null; + const held = parent.childRequests.open.filter( + (request) => + request.childThreadId === child.id && + request.remote === undefined && + isHeldByContinueAtReset(child, request), + ); + return held.length === 0 ? null : { parent, held }; +} + +/** + * A child's wait to continue after a usage limit ends without its continue + * (Stop, the switch turned off, the user or another message starting a turn, + * a new failure): the request it held settles in the same decision + * (docs/design/lead-chat.md, "Rulings after the third review", 6). + */ +const decideHeldRequestsEnd = Effect.fn("decideHeldRequestsEnd")(function* (input: { + readonly readModel: OrchestrationReadModel; + readonly child: OrchestrationThread; + readonly outcome: "failed" | "stopped"; + readonly why: string; + readonly createdAt: string; +}) { + const found = heldRequestsOf(input.readModel, input.child); + if (found === null) return [] as ReadonlyArray; + return yield* decideCommandSequence({ + readModel: input.readModel, + commands: found.held.map((request): OrchestrationCommand => ({ + ...heldRequestEnded(input.child, request, input.outcome, input.why), + threadId: found.parent.id, + createdAt: input.createdAt, + })), + }); +}); + +/** + * Stop on a thread waiting to continue after a usage limit: the wait ends and + * the request it held settles, in the Stop's own decision. + */ +const decideWaitEndOnStop = Effect.fn("decideWaitEndOnStop")(function* ( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + commandId: OrchestrationCommand["commandId"], + createdAt: string, +) { + const session = thread.session; + const lastErrorAt = session?.lastErrorAt ?? null; + if (session === null || (session.continueAtReset ?? null) === null || lastErrorAt === null) { + return [] as ReadonlyArray; + } + const settled = yield* decideHeldRequestsEnd({ + readModel, + child: thread, + outcome: "stopped", + why: "the user stopped it", + createdAt, + }); + return [ + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: thread.id, + occurredAt: createdAt, + commandId, + }), + type: "thread.continue-at-reset-set" as const, + payload: { threadId: thread.id, lastErrorAt, continueAtReset: null, updatedAt: createdAt }, + }, + ...settled, + ]; +}); + +/** The turn a Stop is for: the one running now, if any. */ +function turnBeingStopped(thread: OrchestrationThread): TurnId | undefined { + return ( + thread.session?.activeTurnId ?? + (thread.latestTurn?.state === "running" ? thread.latestTurn.turnId : undefined) ?? + undefined + ); +} + export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({ command, readModel, @@ -3520,6 +3713,20 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, ] : []; + // A turn starting while the thread waited to continue after a usage + // limit ends that wait; the request it held won't get its continue. + // (The continue itself, which the fire starts, answers it instead.) + const waitEnded = + command.trigger !== "usageLimitReset" && + (targetThread.session?.continueAtReset ?? null) !== null + ? yield* decideHeldRequestsEnd({ + readModel, + child: targetThread, + outcome: "failed", + why: "another message started its turn before the reset.", + createdAt: command.createdAt, + }) + : []; return [ userMessageEvent, ...(titleSeedEvent ? [titleSeedEvent] : []), @@ -3527,6 +3734,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" turnStartRequestedEvent, ...requestRunningEvents, ...passStartedEvents, + ...waitEnded, // The user wrote: agents may make requests again. (A queued message // sent later drops these; it counted when the user queued it.) An // agent's message, another thread's or an outside agent's, is not @@ -3711,6 +3919,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" createdAt: command.createdAt, }, }; + // A request a wait to continue held stays open through a retry: the + // retry sends the very message it is bound to, so its turn answers it. // Retrying is the user acting: agents may make requests again. return [ retrySessionEvent, @@ -4273,16 +4483,26 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), ]; + const stopsTurnId = command.turnId ?? turnBeingStopped(thread); const interruptEvent: PlannedOrchestrationEvent = { ...base(), type: "thread.turn-interrupt-requested", payload: { threadId: command.threadId, ...(command.turnId !== undefined ? { turnId: command.turnId } : {}), + ...(stopsTurnId !== undefined ? { stopsTurnId } : {}), createdAt: command.createdAt, }, }; - return chainStop.length > 0 ? [interruptEvent, ...chainStop] : interruptEvent; + const waitEnd = yield* decideWaitEndOnStop( + readModel, + thread, + command.commandId, + command.createdAt, + ); + return chainStop.length > 0 || waitEnd.length > 0 + ? [interruptEvent, ...chainStop, ...waitEnd] + : interruptEvent; } case "thread.realtime.start": { @@ -4592,15 +4812,25 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...childStopEvents(readModel, thread, command, command.createdAt), ...holdCommandOutputOnStop(thread, base, command.createdAt), ]; + const stopsTurnId = turnBeingStopped(thread); const stopEvent: PlannedOrchestrationEvent = { ...base(), type: "thread.session-stop-requested", payload: { threadId: command.threadId, + ...(stopsTurnId !== undefined ? { stopsTurnId } : {}), createdAt: command.createdAt, }, }; - return chainStop.length > 0 ? [stopEvent, ...chainStop] : stopEvent; + const waitEnd = yield* decideWaitEndOnStop( + readModel, + thread, + command.commandId, + command.createdAt, + ); + return chainStop.length > 0 || waitEnd.length > 0 + ? [stopEvent, ...chainStop, ...waitEnd] + : stopEvent; } case "thread.session.set": { @@ -4626,6 +4856,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" payload: { threadId: command.threadId, session: withArmedContinueAtReset( + readModel, thread, withLastErrorState( command.session, @@ -4661,11 +4892,25 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" (command.session.status === "stopped" || !checkoutDiffers); const stoppedCheckoutMove = command.session.status === "stopped" && checkoutDiffers && thread.effectiveCwd !== null; + // The update ended a wait to continue without its continue (a new + // failure, the session moving on): the request it held settles now. + const waitEnded = + (thread.session?.continueAtReset ?? null) !== null && + (sessionSetEvent.payload.session.continueAtReset ?? null) === null + ? yield* decideHeldRequestsEnd({ + readModel, + child: thread, + outcome: "failed", + why: command.session.lastError ?? "it moved on before the reset.", + createdAt: command.createdAt, + }) + : []; if (!selectionSettled && !stoppedCheckoutMove) { - return sessionSetEvent; + return waitEnded.length === 0 ? sessionSetEvent : [sessionSetEvent, ...waitEnded]; } return [ sessionSetEvent, + ...waitEnded, { ...withEventBase({ aggregateKind: "thread", @@ -4751,7 +4996,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" continueAtReset = session.continueAtReset ?? continueAtResetFor(resetsAt, command.createdAt); } - return { + const setEvent: PlannedOrchestrationEvent = { ...withEventBase({ aggregateKind: "thread", aggregateId: command.threadId, @@ -4766,6 +5011,18 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" updatedAt: command.createdAt, }, }; + // Turned off while it waited: the request it held won't be answered. + const ended = + continueAtReset === null && (session.continueAtReset ?? null) !== null + ? yield* decideHeldRequestsEnd({ + readModel, + child: thread, + outcome: "failed", + why: "Continue at reset was turned off for it.", + createdAt: command.createdAt, + }) + : []; + return ended.length === 0 ? setEvent : [setEvent, ...ended]; } case "thread.continue-at-reset.postpone": { @@ -4815,7 +5072,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: "Only a waiting continue message is left unsent.", }); } - return { + const skipped: PlannedOrchestrationEvent = { ...withEventBase({ aggregateKind: "thread", aggregateId: command.threadId, @@ -4829,6 +5086,34 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" skippedAt: command.createdAt, }, }; + // A request bound to that continue will never get its answer from it: + // the user took over before it could continue. + const parent = + isAttachedChild(thread) && thread.parentThreadId !== null + ? readModel.threads.find((entry) => entry.id === thread.parentThreadId) + : undefined; + const bound = (parent?.childRequests.open ?? []).filter( + (request) => + request.childThreadId === thread.id && + request.remote === undefined && + request.status === "running" && + request.childMessageId === command.messageId, + ); + if (parent === undefined || bound.length === 0) return skipped; + const ended = yield* decideCommandSequence({ + readModel, + commands: bound.map((request): OrchestrationCommand => ({ + ...heldRequestEnded( + thread, + request, + "failed", + "the user took over before it could continue.", + ), + threadId: parent.id, + createdAt: command.createdAt, + })), + }); + return [skipped, ...ended]; } // One decision checks the wait and starts the turn, so a message the user @@ -4906,7 +5191,40 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" commands: [continueCommand], readModel, }); - return [cleared, ...continued]; + // A Codex goal picks up by itself and sends no message to answer with: + // the request the wait held won't get an answer from it. + if (continueCommand.type !== "thread.turn.start") { + const ended = yield* decideHeldRequestsEnd({ + readModel, + child: thread, + outcome: "failed", + why: "it went back to its goal, which answers no request.", + createdAt: command.createdAt, + }); + return [cleared, ...continued, ...ended]; + } + // The request this wait held is now answered by the continue's turn. + const held = heldRequestsOf(readModel, thread); + const rebound: PlannedOrchestrationEvent[] = + held === null + ? [] + : held.held.map((request) => ({ + ...withEventBase({ + aggregateKind: "thread", + aggregateId: held.parent.id, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.child-request-updated" as const, + payload: { + threadId: held.parent.id, + requestId: request.requestId, + status: "running" as const, + childMessageId: command.messageId, + updatedAt: command.createdAt, + }, + })); + return [cleared, ...continued, ...rebound]; } // One decision reads the thread as the restart left it and either diff --git a/apps/server/src/orchestration/decider.turnRetry.test.ts b/apps/server/src/orchestration/decider.turnRetry.test.ts index 1321e4203..6dba990dc 100644 --- a/apps/server/src/orchestration/decider.turnRetry.test.ts +++ b/apps/server/src/orchestration/decider.turnRetry.test.ts @@ -1,4 +1,6 @@ import { + ChildRequestBatchId, + ChildRequestId, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, MessageId, @@ -16,6 +18,7 @@ import { import * as Effect from "effect/Effect"; import { describe, expect, it } from "vite-plus/test"; +import { childDeliveryForTurnEnd, isHeldByContinueAtReset } from "./childThreadDelivery.ts"; import { decideOrchestrationCommand } from "./decider.ts"; import { projectEvent } from "./projector.ts"; @@ -717,3 +720,404 @@ describe("decider continue at reset", () => { expect(archived.session?.continueAtReset).toBeUndefined(); }); }); + +// docs/design/lead-chat.md, "Usage limits: pause, not failure" and its rulings. +describe("a usage limit pauses a thread an agent started", () => { + const parentId = ThreadId.make("thread-parent"); + const childId = ThreadId.make("thread-child"); + const requestId = ChildRequestId.make("request-1"); + const askId = MessageId.make("message-ask"); + const turnId = TurnId.make("turn-child-1"); + const limitText = "You've hit your session limit"; + const resetsAt = "2026-01-01T05:00:00.000Z"; + const running: OrchestrationSession = { + ...failedSession, + threadId: childId, + status: "running", + activeTurnId: turnId, + lastError: null, + }; + + function model( + overrides: { + readonly requestStatus?: "running" | "awaiting_background"; + readonly typed?: boolean; + } = {}, + ): OrchestrationReadModel { + const parent = makeThread({ + id: parentId, + title: "Parent", + session: null, + messages: [], + latestTurn: null, + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + open: [ + { + requestId, + batchId: ChildRequestBatchId.make("batch-1"), + kind: "send", + from: { participantId: null }, + callerTurnId: TurnId.make("parent-turn"), + deliveryEpoch: 0, + status: overrides.requestStatus ?? "running", + childThreadId: childId, + childMessageId: askId, + ...(overrides.requestStatus === "awaiting_background" + ? { candidateTurnId: turnId } + : {}), + createdAt: now, + }, + ], + }, + }); + const child = makeThread({ + id: childId, + title: "Child", + parentThreadId: parentId, + attachedToParent: true, + session: running, + latestTurn: { + turnId, + state: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + assistantMessageId: null, + }, + messages: [ + { + id: askId, + role: "user", + text: "Write the changelog.", + ...(overrides.typed + ? { composer: "typed" as const } + : { fromThread: { threadId: parentId, requestId, kind: "request" as const } }), + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }); + return { ...makeReadModel(parent), threads: [parent, child] }; + } + + const run = async (readModel: OrchestrationReadModel, command: OrchestrationCommand) => { + const decided = await Effect.runPromise(decideOrchestrationCommand({ command, readModel })); + const events = Array.isArray(decided) ? decided : [decided]; + let projected = readModel; + for (const event of events) { + projected = await Effect.runPromise( + projectEvent(projected, { ...event, sequence: projected.snapshotSequence + 1 }), + ); + projected = { ...projected, snapshotSequence: projected.snapshotSequence + 1 }; + } + return { events, readModel: projected }; + }; + const threadIn = (readModel: OrchestrationReadModel, id: ThreadId) => + readModel.threads.find((entry) => entry.id === id)!; + const openRequests = (readModel: OrchestrationReadModel) => + threadIn(readModel, parentId).childRequests.open; + const limitHit = (settingOn: boolean, at = "2026-01-01T00:00:04.000Z") => + ({ + type: "thread.session.set", + commandId: CommandId.make(`cmd-limit-${at}`), + threadId: childId, + session: { + ...running, + status: "error", + activeTurnId: null, + lastError: limitText, + updatedAt: at, + }, + usageLimit: { window: "session", resetsAt }, + continueAfterUsageLimits: settingOn, + createdAt: at, + }) as const; + const turnEnded = (readModel: OrchestrationReadModel, pendingMessageId: MessageId) => + childDeliveryForTurnEnd({ + owned: openRequests(readModel), + child: threadIn(readModel, childId), + end: { turnId, outcome: "failed", error: limitText }, + pendingMessageId, + awaitedBackgroundTaskCount: 0, + }); + + it("holds the request through the wait and answers it with the continue", async () => { + const off = await run(model(), limitHit(false)); + expect(threadIn(off.readModel, childId).session?.continueAtReset).toBeUndefined(); + expect(turnEnded(off.readModel, askId)?.type).toBe("thread.child-request.settle"); + + const armed = await run(model(), limitHit(true)); + expect(threadIn(armed.readModel, childId).session?.continueAtReset).toBeDefined(); + // The failed turn's end does not settle it: it waits for the continue. + expect(turnEnded(armed.readModel, askId)).toBeNull(); + + const lastErrorAt = threadIn(armed.readModel, childId).session?.lastErrorAt ?? ""; + const continueId = MessageId.make("message-continue"); + const fired = await run(armed.readModel, { + type: "thread.continue-at-reset.fire", + commandId: CommandId.make("cmd-fire"), + threadId: childId, + lastErrorAt, + messageId: continueId, + createdAt: "2026-01-01T05:01:30.000Z", + }); + expect(openRequests(fired.readModel)).toMatchObject([ + { requestId, status: "running", childMessageId: continueId }, + ]); + // The continue's turn answers it through the normal path. + const answered = childDeliveryForTurnEnd({ + owned: openRequests(fired.readModel), + child: threadIn(fired.readModel, childId), + end: { turnId: TurnId.make("turn-continue"), outcome: "completed" }, + pendingMessageId: continueId, + awaitedBackgroundTaskCount: 0, + }); + expect(answered).toMatchObject({ type: "thread.child-request.settle", outcome: "answered" }); + }); + + it("never arms for a turn the user stopped, whoever started it", async () => { + for (const typed of [false, true]) { + const stopped = await run(model({ typed }), { + type: "thread.turn.interrupt", + commandId: CommandId.make(`cmd-stop-${typed}`), + threadId: childId, + createdAt: "2026-01-01T00:00:03.000Z", + }); + expect(threadIn(stopped.readModel, childId).session?.stopRequestedTurnId).toBe(turnId); + const limited = await run(stopped.readModel, limitHit(true)); + expect(threadIn(limited.readModel, childId).session?.continueAtReset).toBeUndefined(); + } + }); + + it("settles the held request when Stop or the user's own turn ends the wait", async () => { + const armed = (await run(model(), limitHit(true))).readModel; + const stopped = await run(armed, { + type: "thread.session.stop", + commandId: CommandId.make("cmd-session-stop"), + threadId: childId, + createdAt: "2026-01-01T00:01:00.000Z", + }); + expect(threadIn(stopped.readModel, childId).session?.continueAtReset).toBeUndefined(); + expect(openRequests(stopped.readModel)).toEqual([]); + expect( + stopped.events.some( + (event) => + event.type === "thread.child-request-settled" && + (event.payload as { outcome?: string }).outcome === "stopped", + ), + ).toBe(true); + + const userWrote = await run(armed, { + type: "thread.turn.start", + commandId: CommandId.make("cmd-user-turn"), + threadId: childId, + message: { + messageId: MessageId.make("message-user-own"), + role: "user", + text: "Do something else.", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: "2026-01-01T00:01:00.000Z", + }); + expect(openRequests(userWrote.readModel)).toEqual([]); + expect( + userWrote.events.some( + (event) => + event.type === "thread.child-request-settled" && + (event.payload as { outcome?: string }).outcome === "failed", + ), + ).toBe(true); + }); + + it("fails the request when its continue is overtaken and never runs", async () => { + const armed = (await run(model(), limitHit(true))).readModel; + const lastErrorAt = threadIn(armed, childId).session?.lastErrorAt ?? ""; + const continueId = MessageId.make("message-continue"); + const fired = ( + await run(armed, { + type: "thread.continue-at-reset.fire", + commandId: CommandId.make("cmd-fire"), + threadId: childId, + lastErrorAt, + messageId: continueId, + createdAt: "2026-01-01T05:01:30.000Z", + }) + ).readModel; + const skipped = await run(fired, { + type: "thread.continue-at-reset.skip", + commandId: CommandId.make("cmd-skip"), + threadId: childId, + messageId: continueId, + createdAt: "2026-01-01T05:01:31.000Z", + }); + expect(openRequests(skipped.readModel)).toEqual([]); + }); + + it("arms for a report heard in a top-level thread, never for a goal the limit paused", async () => { + const reporting = makeThread({ + session: { ...failedSession, status: "running", activeTurnId: turnId, lastError: null }, + messages: [ + { + id: MessageId.make("message-report"), + role: "user", + text: "The changelog is written.", + fromThread: { threadId: childId, requestId, kind: "report" }, + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }); + const reported = await run(makeReadModel(reporting), { + ...limitHit(true), + threadId, + session: { ...limitHit(true).session, threadId }, + }); + expect(threadIn(reported.readModel, threadId).session?.continueAtReset).toBeDefined(); + + const goalPaused = model(); + const onGoal = { + ...goalPaused, + threads: goalPaused.threads.map((entry) => + entry.id === childId + ? { + ...entry, + goal: { + objective: "Ship it", + status: "usageLimited" as const, + createdAt: now, + updatedAt: now, + } as never, + } + : entry, + ), + }; + const limited = await run(onGoal, limitHit(true)); + expect(threadIn(limited.readModel, childId).session?.continueAtReset).toBeUndefined(); + }); + + it("keeps the hold past a later message queued in the child, and settles it when that runs", async () => { + const armed = (await run(model(), limitHit(true))).readModel; + // The parent asks again while the child waits: its message is written when queued. + const secondId = MessageId.make("message-ask-2"); + const queued: OrchestrationReadModel = { + ...armed, + threads: armed.threads.map((entry) => + entry.id === parentId + ? { + ...entry, + childRequests: { + ...entry.childRequests, + open: [ + ...entry.childRequests.open, + { + ...entry.childRequests.open[0]!, + requestId: ChildRequestId.make("request-2"), + status: "queued" as const, + childMessageId: secondId, + }, + ], + }, + } + : entry.id === childId + ? { + ...entry, + messages: [ + ...entry.messages, + { + id: secondId, + role: "user" as const, + text: "Also the release notes.", + fromThread: { + threadId: parentId, + requestId: ChildRequestId.make("request-2"), + kind: "request" as const, + }, + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + queuedFollowUps: [ + { + messageId: secondId, + text: "Also the release notes.", + attachments: [], + fromThread: { + threadId: parentId, + requestId: ChildRequestId.make("request-2"), + kind: "request" as const, + }, + runtimeMode: "full-access" as const, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + createdAt: now, + }, + ], + } + : entry, + ), + }; + expect(isHeldByContinueAtReset(threadIn(queued, childId), openRequests(queued)[0]!)).toBe(true); + const sent = await run(queued, { + type: "thread.follow-up.send-queued", + commandId: CommandId.make("cmd-send-second"), + threadId: childId, + messageId: secondId, + createdAt: "2026-01-01T00:02:00.000Z", + }); + expect(openRequests(sent.readModel).some((entry) => entry.requestId === requestId)).toBe(false); + }); + + it("fails the held request when the wait ends by resuming a Codex goal", async () => { + const armed = (await run(model(), limitHit(true))).readModel; + const onGoal = { + ...armed, + threads: armed.threads.map((entry) => + entry.id === childId + ? ({ + ...entry, + goal: { + objective: "Ship it", + status: "usageLimited", + createdAt: now, + updatedAt: now, + }, + } as never) + : entry, + ), + }; + const lastErrorAt = threadIn(onGoal, childId).session?.lastErrorAt ?? ""; + const fired = await run(onGoal, { + type: "thread.continue-at-reset.fire", + commandId: CommandId.make("cmd-fire-goal"), + threadId: childId, + lastErrorAt, + messageId: MessageId.make("message-continue-goal"), + createdAt: "2026-01-01T05:01:30.000Z", + }); + expect(openRequests(fired.readModel)).toEqual([]); + }); + + it("leaves a request waiting on background work on today's path", async () => { + const armed = await run(model({ requestStatus: "awaiting_background" }), limitHit(true)); + // Nothing armed for it, and the follow-up's failure settles it as before. + expect(threadIn(armed.readModel, childId).session?.continueAtReset).toBeUndefined(); + expect(turnEnded(armed.readModel, null as unknown as MessageId)).toBeNull(); + expect( + childDeliveryForTurnEnd({ + owned: openRequests(armed.readModel), + child: threadIn(armed.readModel, childId), + end: { turnId: TurnId.make("turn-follow-up"), outcome: "failed", error: limitText }, + pendingMessageId: null, + awaitedBackgroundTaskCount: 0, + }), + ).toMatchObject({ type: "thread.child-request.settle", outcome: "failed" }); + }); +}); diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 6461e6bd8..79ceabf5a 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -109,6 +109,8 @@ import { ThreadChildRequestUpdatedPayload, ThreadChildRequestsResetPayload, ThreadLeadPassRecordedPayload, + ThreadSessionStopRequestedPayload, + ThreadTurnInterruptRequestedPayload, ThreadHandedBackPayload, ThreadRemoteCancelQueuedPayload, ThreadRemoteCancelsDeliveredPayload, @@ -1627,6 +1629,32 @@ export function projectEvent( ); // Waiting to continue is not work on the thread either. + // Stop names the turn it is for: no usage limit brings that turn back + // (OrchestrationSession.stopRequestedTurnId). + case "thread.turn-interrupt-requested": + case "thread.session-stop-requested": + return decodeForEvent( + event.type === "thread.turn-interrupt-requested" + ? ThreadTurnInterruptRequestedPayload + : ThreadSessionStopRequestedPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => { + const session = nextBase.threads.find((entry) => entry.id === payload.threadId)?.session; + if (session == null || payload.stopsTurnId === undefined) { + return nextBase; + } + return { + ...nextBase, + threads: updateThread(nextBase.threads, payload.threadId, { + session: { ...session, stopRequestedTurnId: payload.stopsTurnId }, + }), + }; + }), + ); + case "thread.continue-at-reset-set": return decodeForEvent( ThreadContinueAtResetSetPayload, diff --git a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts index 395411066..8c16eaf78 100644 --- a/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Layers/ProjectionThreadSessions.ts @@ -22,6 +22,7 @@ import { GetProjectionThreadSessionInput, ProjectionThreadContinueAtReset, SetProjectionThreadSessionContinueAtResetInput, + SetProjectionThreadSessionStopRequestedInput, } from "../Services/ProjectionThreadSessions.ts"; const ProjectionThreadSessionDbRow = ProjectionThreadSession.mapFields( @@ -70,6 +71,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { last_error_dismissed_at, last_error_usage_limit, continue_at_reset, + stop_requested_turn_id, updated_at ) VALUES ( @@ -106,6 +108,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { ${row.lastErrorDismissedAt ?? null}, ${row.lastErrorUsageLimit == null ? null : JSON.stringify(row.lastErrorUsageLimit)}, ${row.continueAtReset == null ? null : JSON.stringify(row.continueAtReset)}, + ${row.stopRequestedTurnId ?? null}, ${row.updatedAt} ) ON CONFLICT (thread_id) @@ -128,6 +131,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { last_error_dismissed_at = excluded.last_error_dismissed_at, last_error_usage_limit = excluded.last_error_usage_limit, continue_at_reset = excluded.continue_at_reset, + stop_requested_turn_id = excluded.stop_requested_turn_id, updated_at = excluded.updated_at `, }); @@ -157,6 +161,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { last_error_dismissed_at AS "lastErrorDismissedAt", last_error_usage_limit AS "lastErrorUsageLimit", continue_at_reset AS "continueAtReset", + stop_requested_turn_id AS "stopRequestedTurnId", updated_at AS "updatedAt" FROM projection_thread_sessions WHERE thread_id = ${threadId} @@ -186,6 +191,16 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { `, }); + const setProjectionThreadSessionStopRequested = SqlSchema.void({ + Request: SetProjectionThreadSessionStopRequestedInput, + execute: ({ threadId, turnId }) => + sql` + UPDATE projection_thread_sessions + SET stop_requested_turn_id = ${turnId} + WHERE thread_id = ${threadId} + `, + }); + const listProjectionThreadContinueAtReset = SqlSchema.findAll({ Request: Schema.Void, Result: ProjectionThreadContinueAtResetDbRow, @@ -239,6 +254,13 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { ), ); + const setStopRequested: ProjectionThreadSessionRepositoryShape["setStopRequested"] = (input) => + setProjectionThreadSessionStopRequested(input).pipe( + Effect.mapError( + toPersistenceSqlError("ProjectionThreadSessionRepository.setStopRequested:query"), + ), + ); + const listContinueAtReset: ProjectionThreadSessionRepositoryShape["listContinueAtReset"] = () => listProjectionThreadContinueAtReset(undefined).pipe( Effect.mapError( @@ -258,6 +280,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () { getByThreadId, dismissError, setContinueAtReset, + setStopRequested, listContinueAtReset, deleteByThreadId, } satisfies ProjectionThreadSessionRepositoryShape; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 2c157f546..71f250b87 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -137,6 +137,7 @@ import Migration0114 from "./Migrations/114_LinkMoveAbortCode.ts"; import Migration0115 from "./Migrations/115_ThreadNativeSession.ts"; import Migration0116 from "./Migrations/116_ProjectLeadThread.ts"; import Migration0117 from "./Migrations/117_ThreadMoveCarry.ts"; +import Migration0118 from "./Migrations/118_SessionStopRequestedTurn.ts"; /** * Migration loader with all migrations defined inline. @@ -266,6 +267,7 @@ export const migrationEntries = [ [115, "ThreadNativeSession", Migration0115], [116, "ProjectLeadThread", Migration0116], [117, "ThreadMoveCarry", Migration0117], + [118, "SessionStopRequestedTurn", Migration0118], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/118_SessionStopRequestedTurn.ts b/apps/server/src/persistence/Migrations/118_SessionStopRequestedTurn.ts new file mode 100644 index 000000000..b2c1abe69 --- /dev/null +++ b/apps/server/src/persistence/Migrations/118_SessionStopRequestedTurn.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * The turn the user asked to stop (`OrchestrationSession.stopRequestedTurnId`, + * docs/design/lead-chat.md, "Rulings after the third review"): a usage limit + * failure that lands after Stop never arms "Continue at reset" for it. + * + * A new nullable column; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // A development database may have it already, from when this was 117. + const columns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(projection_thread_sessions) + `; + if (!columns.some((column) => column.name === "stop_requested_turn_id")) { + yield* sql`ALTER TABLE projection_thread_sessions ADD COLUMN stop_requested_turn_id TEXT`; + } +}); diff --git a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts index 75b8012fb..4ca73bf12 100644 --- a/apps/server/src/persistence/Services/ProjectionThreadSessions.ts +++ b/apps/server/src/persistence/Services/ProjectionThreadSessions.ts @@ -59,10 +59,19 @@ export const ProjectionThreadSession = Schema.Struct({ lastErrorUsageLimit: Schema.optional(Schema.NullOr(OrchestrationSessionUsageLimit)), /** See OrchestrationSession.continueAtReset. Absent on write clears it. */ continueAtReset: Schema.optional(Schema.NullOr(OrchestrationContinueAtReset)), + /** See OrchestrationSession.stopRequestedTurnId. Absent on write clears it. */ + stopRequestedTurnId: Schema.optional(Schema.NullOr(TurnId)), updatedAt: IsoDateTime, }); export type ProjectionThreadSession = typeof ProjectionThreadSession.Type; +export const SetProjectionThreadSessionStopRequestedInput = Schema.Struct({ + threadId: ThreadId, + turnId: TurnId, +}); +export type SetProjectionThreadSessionStopRequestedInput = + typeof SetProjectionThreadSessionStopRequestedInput.Type; + export const GetProjectionThreadSessionInput = Schema.Struct({ threadId: ThreadId, }); @@ -132,6 +141,11 @@ export interface ProjectionThreadSessionRepositoryShape { input: SetProjectionThreadSessionContinueAtResetInput, ) => Effect.Effect; + /** Record the turn the user asked to stop (OrchestrationSession.stopRequestedTurnId). */ + readonly setStopRequested: ( + input: SetProjectionThreadSessionStopRequestedInput, + ) => Effect.Effect; + /** Every thread waiting to continue after a usage limit. */ readonly listContinueAtReset: () => Effect.Effect< ReadonlyArray, diff --git a/apps/web/src/components/settings/ThreadsSettings.tsx b/apps/web/src/components/settings/ThreadsSettings.tsx index bd8c915b2..f17b2d0bd 100644 --- a/apps/web/src/components/settings/ThreadsSettings.tsx +++ b/apps/web/src/components/settings/ThreadsSettings.tsx @@ -740,7 +740,7 @@ export function ContinueAfterUsageLimitsRow() { return ( settings.continueAfterUsageLimits), widensAgents: true, diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index c657845c8..3a2142e93 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -24,6 +24,7 @@ import { type RemoteThreadFiling, type RoomAgentRef, type LocalChildStart, + type MessageId, type ProviderInteractionMode, type RuntimeMode, type ThreadId, @@ -636,12 +637,14 @@ export const childRequestStateOn = { readonly status: ChildRequestStatus; readonly candidateTurnId?: TurnId | undefined; readonly remote?: RemoteChildRequest | undefined; + readonly childMessageId?: MessageId | undefined; }, ): OrchestrationChildRequestState => { const changes = (entry: OrchestrationChildRequest) => entry.requestId === update.requestId && (entry.status !== update.status || entry.candidateTurnId !== update.candidateTurnId || + (update.childMessageId !== undefined && entry.childMessageId !== update.childMessageId) || (update.remote !== undefined && !sameRemoteRequest(entry.remote, update.remote))); return state.open.some(changes) ? { @@ -656,6 +659,9 @@ export const childRequestStateOn = { ? { candidateTurnId: update.candidateTurnId } : {}), ...(update.remote !== undefined ? { remote: update.remote } : {}), + ...(update.childMessageId !== undefined + ? { childMessageId: update.childMessageId } + : {}), }; }), }