diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7dc93dc5c196e..906804d0844e2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3493,15 +3493,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // the server or scheduled tasks, so a later completed run releases those unless it was stopped. const releaseUnattendedHolds = Effect.fn("Orchestrator.releaseUnattendedHolds")(function* ( threadId: ThreadId, - completedRunId: RunId, + completedRun: OrchestrationV2Run, ) { + const completedRunId = completedRun.id; const held = yield* projectionStore.getHeldQueuedRuns(threadId); if (held.length === 0) return; const projection = yield* projectionStore.getThreadRecords( threadId, ["runs", "messages", "turnItems"], { - messageIds: held.map((run) => run.userMessageId), + messageIds: [...held.map((run) => run.userMessageId), completedRun.userMessageId], turnItemTypes: ["run_interrupt_request"], turnItemRunIds: [completedRunId], }, @@ -3520,8 +3521,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .filter((message) => message.createdBy !== "user" || message.scheduledTaskId !== undefined) .map((message) => message.id), ); + // A restart that cut a compaction records the holds it added; redoing it releases those. + // Retried or re-cut continuations chain back to the run that recorded them. + const restartHeld = new Set(); + const isCompaction = messages.some( + (message) => message.id === completedRun.userMessageId && isCompactionCommandMessage(message), + ); + let id = isCompaction ? completedRun.restartContinuationOfRunId : undefined; + for (let hops = 0; id !== undefined && hops < projection.runs.length; hops++) { + const source = projection.runs.find((run) => run.id === id); + for (const heldId of source?.restartHeldRunIds ?? []) restartHeld.add(heldId); + id = source?.restartContinuationOfRunId; + } const now = yield* DateTime.now; - const released = held.filter((run) => unattended.has(run.userMessageId)); + const released = held.filter( + (run) => unattended.has(run.userMessageId) || restartHeld.has(run.id), + ); if (released.length === 0) return; yield* writeSystemEvents( released.map((run) => ({ @@ -7447,8 +7462,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // The service checked idleness before this command; a run or a delegated result that landed // since makes the thread busy, and that turn refreshes the cache anyway. + // A restart's queued runs are held, so they will not refresh the cache. if ( command.idleCompaction === "beforeCacheExpires" && + command.restartContinuationOfRunId === undefined && projection.runs.some( (run) => run.status === "queued" || @@ -16911,10 +16928,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* threadDispatch .withLock( threadId, - (run.status === "completed" - ? releaseUnattendedHolds(threadId, run.id) - : Effect.void - ).pipe( + (run.status === "completed" ? releaseUnattendedHolds(threadId, run) : Effect.void).pipe( Effect.andThen( requeueUnreadSteers(threadId, [run.id]).pipe( Effect.catchCause((cause) => diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index 1f1a2f9aac264..27bbb72fe3e6b 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -867,6 +867,8 @@ it.effect( providerThreadId, providerInstanceId: ProviderInstanceId.make("codex"), }, + { id: RunId.make("run_recovery_queued"), status: "queued", ordinal: 2 }, + { id: RunId.make("run_recovery_held"), status: "queued", ordinal: 3, queueHeld: true }, ], attempts: [ { @@ -903,6 +905,8 @@ it.effect( Layer.mock(ProjectionStore.ProjectionStoreV2)({ getRecoveryThreadIds: () => Effect.succeed([threadId]), getRuntimeRecoveryProjection: () => Effect.succeed(projection), + getMessagesById: () => Effect.succeed(new Map()), + getThreadRecords: () => Effect.succeed(projection), }), Layer.mock(EventSink.EventSinkV2)({ commitCommand: (input) => { @@ -943,6 +947,7 @@ it.effect( "status" in event.payload ? event.payload.status : null, ]), [ + ["run.updated", "queued"], ["run.updated", "cancelled"], ["run-attempt.updated", "cancelled"], ["node.updated", "cancelled"], @@ -957,6 +962,13 @@ it.effect( ["provider-session.updated", "stopped"], ], ); + // Only the hold this restart added is recorded on the run it cut. + const cutRun = events.find( + (event) => event.type === "run.updated" && event.payload.status === "cancelled", + ); + assert.deepEqual(cutRun?.type === "run.updated" ? cutRun.payload.restartHeldRunIds : null, [ + RunId.make("run_recovery_queued"), + ]); const messageEvent = events.find((event) => event.type === "message.updated"); assert.isFalse(messageEvent?.type === "message.updated" && messageEvent.payload.streaming); const stoppedSession = events.find((event) => event.type === "provider-session.updated"); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 02cb33b849ae2..a552330a5d952 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -4,6 +4,7 @@ import { isProviderNativeSubagentThread, type OrchestrationV2DomainEvent, type ProviderThreadId, + type RunId, type RunAttemptId, type OrchestrationV2RestartCancelledBackgroundWork, type OrchestrationV2Subagent, @@ -567,12 +568,14 @@ export const make = Effect.gen(function* () { ...retryableRuns, ...queuedRunsInDeliveryOrder({ runs: queuedRuns, messages: queuedMessages }), ]; + const restartHeldRunIds: Array = []; for (const [index, run] of heldRuns.entries()) { if (bufferedMessageIds.has(run.userMessageId)) { runs.push(run); continue; } if (run.queueHeld === true && retryableRuns.length === 0) continue; + if (run.queueHeld !== true) restartHeldRunIds.push(run.id); events.push({ id: yield* allocateEventId(), type: "run.updated", @@ -682,7 +685,13 @@ export const make = Effect.gen(function* () { runId: run.id, providerInstanceId: run.providerInstanceId, occurredAt: now, - payload: { ...run, status: "cancelled", queuePosition: null, completedAt: now }, + payload: { + ...run, + status: "cancelled", + queuePosition: null, + completedAt: now, + ...(restartHeldRunIds.length > 0 ? { restartHeldRunIds } : {}), + }, }); for (const attempt of projection.attempts.filter( (candidate) => diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 77af7d2680e05..111e9d1389428 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -1230,14 +1230,29 @@ it.effect("does not continue a run the user asked to stop before the restart", ( }), ); -it.effect("does not continue a cut /compact or /logout turn", () => +it.effect("compacts again after a cut /compact turn, and does not continue a cut /logout", () => Effect.gen(function* () { - for (const text of ["/compact", " /LOGOUT "]) { - const texts = yield* continuationTexts({ + for (const [text, creationSource, expected] of [ + [" /Compact ", "mcp", ["user:/compact"]], + // Servers before `idleCompaction` marked their own compaction this way. + ["/compact", "server", ["agent:/compact"]], + [" /LOGOUT ", "mcp", []], + ] as const) { + const sent = yield* continuationDispatches({ ...cutMidTurn(), - messages: [{ id: MessageId.make("message:user"), text, attachments: [] }], + messages: [ + { + id: MessageId.make("message:user"), + role: "user", + createdBy: "agent", + creationSource, + text, + attachments: [], + }, + ], } as unknown as OrchestrationV2ThreadProjection); - assert.deepEqual(texts, [], text); + const texts = sent.map((command) => `${command.createdBy}:${command.text}`); + assert.deepEqual(texts, [...expected], text); } const texts = yield* continuationTexts({ ...cutMidTurn(), diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 21d70c62f920e..7deafec0d6712 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -2,6 +2,9 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { CommandId, + IDLE_COMPACTION_TEXT, + idleCompactionOf, + isCompactionCommandMessage, isOrchestrationV2WorkActive, latestProviderTurnForAttempt, MessageId, @@ -311,7 +314,13 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta const sourceMessage = (yield* threads.getThreadRecords(input.threadId, ["messages"], { messageIds: [source.userMessageId], })).messages.find((message) => message.id === source.userMessageId); - if (sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) return; + // Compaction changes nothing a repeat could double, so a cut one runs again. + const recompact = + sourceMessage !== undefined && + isCompactionCommandMessage(sourceMessage) && + !isRestartNoteSource(source, projection.providerTurns); + if (!recompact && sourceMessage !== undefined && isNativeMaintenanceCommand(sourceMessage)) + return; const note = restartContinuationNote( source, projection.runs, @@ -334,22 +343,30 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta commandId: CommandId.make(`command:restart-continuation:${input.sourceRunId}`), threadId: input.threadId, messageId, - text, - notification: { - source: { kind: "system" }, - outcome: "updated", - summary: - input.cause === "provider_exit" - ? "The agent runtime exited and stopped background work" - : note.settled - ? "T3 Code restarted and stopped background work" - : "T3 Code restarted and resumed this turn", - detail: text, - }, + text: recompact ? IDLE_COMPACTION_TEXT : text, + idleCompaction: recompact ? sourceMessage.idleCompaction : undefined, + notification: recompact + ? undefined + : { + source: { kind: "system" }, + outcome: "updated", + summary: + input.cause === "provider_exit" + ? "The agent runtime exited and stopped background work" + : note.settled + ? "T3 Code restarted and stopped background work" + : "T3 Code restarted and resumed this turn", + detail: text, + }, attachments: [], modelSelection: source.modelSelection, dispatchMode: { type: "start_immediately" }, - createdBy: "agent", + // Agent + server with no idleCompaction reads as an automatic idle compaction. + createdBy: !recompact + ? "agent" + : idleCompactionOf(sourceMessage) === undefined + ? "user" + : sourceMessage.createdBy, creationSource: "server", restartContinuationOfRunId: input.sourceRunId, }) diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 0eb5d0e4b463a..7698a053e3aa8 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -9386,8 +9386,14 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { branch: null, worktreePath: process.cwd(), }); - const send = (key: string, createdBy: "user" | "agent", start: boolean) => + const send = ( + key: string, + createdBy: "user" | "agent", + start: boolean, + extra: { idleCompaction?: "beforeCacheExpires"; restartContinuationOfRunId?: RunId } = {}, + ) => orchestrator.dispatch({ + ...extra, type: "message.dispatch", createdBy, creationSource: createdBy === "user" ? "web" : "server", @@ -9436,7 +9442,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }); const end = ( key: string, - status: "completed" | "failed", + status: "completed" | "failed" | "cancelled", revision = "", patch: Partial = {}, ) => @@ -9586,6 +9592,33 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("a compaction resumed after a restart releases only what that restart held", () => + Effect.gen(function* () { + const threadId = ThreadId.make("runtime-layer-held-queue-resumed-compaction"); + const { send, runFor, end, startedRunIds, awaitHeld } = yield* queueTestThread(threadId); + yield* send("failed", "agent", true); + yield* send("earlier", "user", false); + yield* send("later", "user", false); + yield* end("failed", "failed"); + yield* awaitHeld("later"); + yield* send("cut", "agent", true); + yield* end("cut", "cancelled", "", { restartHeldRunIds: [(yield* runFor("later")).id] }); + // A second restart cuts the first continuation, which adds no holds of its own. + yield* send(" /compact", "agent", true); + yield* end(" /compact", "cancelled", "", { + restartContinuationOfRunId: (yield* runFor("cut")).id, + }); + // Queued runs are held, so an idle compaction does not wait for them. + yield* send("/compact", "agent", true, { + idleCompaction: "beforeCacheExpires", + restartContinuationOfRunId: (yield* runFor(" /compact")).id, + }); + yield* end("/compact", "completed"); + assert.equal(yield* Queue.take(startedRunIds), (yield* runFor("later")).id); + assert.isTrue((yield* runFor("earlier")).queueHeld); + }), + ); + it.effect("keeps held agent messages while the thread's worktree setup is unresolved", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/docs/user/composer.md b/docs/user/composer.md index 53017052a2a01..27cfe04f5bb5b 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -287,6 +287,7 @@ the provider, Resume sends that request again. Sending a new message also resumes the queue, unless it steers a turn that is already running. You can edit or remove held messages without starting them. +A `/compact` cut by a restart runs again, and messages queued behind it send when it finishes. The pencil on a queued message opens it in the composer for editing. The original message stays in the queue until you save, and it is highlighted while you edit. The message's diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index dfde87c009f66..68c7c795246e0 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -843,6 +843,8 @@ export const OrchestrationV2Run = Schema.Struct({ restartCancelledBackgroundWork: Schema.optional( Schema.Array(OrchestrationV2RestartCancelledBackgroundWork), ), + /** Queued runs a restart held when it cut this run, as opposed to holds already in place. */ + restartHeldRunIds: Schema.optional(Schema.Array(RunId)), sourcePlanRef: Schema.optional( Schema.Struct({ threadId: ThreadId,