From 9bee0e9476bba8a757976c7f005eb2dacc2f0caa Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 03:29:18 -0500 Subject: [PATCH 1/7] fix(server): a queued message being edited waits until the edit ends A queued message that a client is editing gets a short hold. Once it is next, the queue waits there until the edit is saved, cancelled, or the hold lapses after two minutes without a renewal. A turn that fails during the edit still holds the queue, and a steer waiting for its turn waits for the edit too. --- .../src/orchestration-v2/EffectOutbox.ts | 24 +- .../src/orchestration-v2/EffectWorker.ts | 20 ++ .../FoundationPersistence.test.ts | 18 ++ .../src/orchestration-v2/Orchestrator.ts | 253 ++++++++++++++++-- .../SteeringCompletion.integration.test.ts | 103 +++++++ .../src/orchestration-v2/ThreadStop.test.ts | 140 +++++++++- .../src/orchestration-v2/runtimeLayer.test.ts | 112 ++++++++ .../testkit/OrchestratorScenario.ts | 1 + packages/contracts/src/orchestrationV2.ts | 22 ++ 9 files changed, 654 insertions(+), 39 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b495293bc2228..4a7502a85d81e 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -138,6 +138,11 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ type: Schema.Literal("delegated-tasks.stop"), reason: Schema.optional(Schema.String), }), + Schema.Struct({ + type: Schema.Literal("queued-run.hold.expire"), + runId: RunId, + heldUntil: Schema.DateTimeUtcFromString, + }), ]); export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; @@ -152,6 +157,7 @@ export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ "attachment.cleanup", "thread-title.generate", "delegated-tasks.stop", + "queued-run.hold.expire", ] as const satisfies ReadonlyArray; export const PROCESS_BOUND_EFFECT_TYPES = [ @@ -339,6 +345,10 @@ export const layer: Layer.Layer = La available, Array.from({ length: Math.min(64, Math.max(0, Math.floor(count))) }, () => undefined), ).pipe(Effect.asVoid); + const effectLane = (alias: "candidate" | "active") => + sql.literal( + `CASE WHEN ${alias}.effect_type IN ('thread-title.generate', 'queued-run.hold.expire') THEN ${alias}.effect_type ELSE '' END`, + ); // Retry backoff must block later effects so turns cannot race a pending rollback. const claimableCandidatePredicate = ( availableBefore?: string, @@ -368,17 +378,9 @@ export const layer: Layer.Layer = La } ) ) - AND ( - ( - candidate.effect_type = 'thread-title.generate' - AND active.effect_type = 'thread-title.generate' - ) - OR - ( - candidate.effect_type != 'thread-title.generate' - AND active.effect_type != 'thread-title.generate' - ) - ) + -- Titles and edit-hold timers wait only on their own kind: a timer due in + -- minutes would otherwise hold back the thread's turns until it fires. + AND ${effectLane("candidate")} = ${effectLane("active")} ) AND ${ maxRunningTitleGenerations === undefined diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 6c805cfc4592f..735ade1b1a288 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -713,6 +713,26 @@ export const layerExecutor: Layer.Layer< }), ), ); + case "queued-run.hold.expire": + return threads + .dispatch({ + type: "queued-run.hold.expire", + commandId: CommandId.make(`${effect.id}:expire`), + threadId: effect.threadId, + runId: effect.request.runId, + heldUntil: effect.request.heldUntil, + }) + .pipe( + Effect.asVoid, + Effect.mapError( + (cause) => + new OrchestrationEffectExecutionError({ + effectId: effect.id, + effectType: effect.request.type, + cause, + }), + ), + ); } }), }); diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 5e208fc7fd658..f06813b5c4ba3 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -2776,7 +2776,20 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { const providerEffectId = "effect:foundation-title-effect-lane:b-provider"; const nextTitleEffectId = "effect:foundation-title-effect-lane:c-title"; const nextCriticalEffectId = "effect:foundation-title-effect-lane:d-critical"; + // An edit-hold timer due in minutes must not hold back either lane. + const heldUntil = DateTime.add(yield* DateTime.now, { minutes: 5 }); yield* outbox.enqueue([ + { + id: "effect:foundation-title-effect-lane:0-edit-hold", + commandId, + threadId, + request: { + type: "queued-run.hold.expire", + runId: RunId.make("run:foundation-title-effect-lane"), + heldUntil, + }, + availableAt: heldUntil, + }, { id: titleEffectId, commandId, @@ -2864,6 +2877,11 @@ it.layer(layerTest)("orchestration V2 foundation persistence", (it) => { workerId: "title-lane-worker", }); } + yield* outbox.cancelUnsettled({ + threadId, + effectTypes: ["queued-run.hold.expire"], + reason: "Test cleanup.", + }); }), ); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 995ff63b25747..3428076cffa42 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -24,6 +24,7 @@ import { } from "../sourceControl/threadPullRequests.ts"; import { ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE, + QUEUED_RUN_EDIT_HOLD_MS, type ChatAttachment, CommandId, type GuestMessageId, @@ -692,6 +693,8 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId { case "queued-run.reorder": case "queued-run.cancel": case "queued-run.edit": + case "queued-run.hold": + case "queued-run.hold.expire": case "runtime-request.respond": case "runtime-request.delivery.fail": case "thread.user-input.dismiss": @@ -1034,12 +1037,44 @@ function worktreeSetupPending( ); } -function nextQueuedRun( +function queueHead( projection: Pick, ): OrchestrationV2Run | undefined { return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } +function nextQueuedRun( + projection: Pick, +): OrchestrationV2Run | undefined { + const head = queueHead(projection); + return head?.editHeldUntil === undefined ? head : undefined; +} + +// Each can change which queued message is next, or end the edit the queue waits on. +const QUEUE_CHANGING_COMMAND_TYPES = [ + "queue.resume", + "queued-run.start", + "queued-run.reorder", + "queued-run.cancel", + "queued-run.edit", + "queued-run.hold", + "queued-run.hold.expire", +] as const satisfies ReadonlyArray; + +function startsQueueAfterCommit( + command: OrchestrationV2ServerCommand, +): command is Extract< + OrchestrationV2ServerCommand, + { readonly type: (typeof QUEUE_CHANGING_COMMAND_TYPES)[number] } +> { + return (QUEUE_CHANGING_COMMAND_TYPES as ReadonlyArray).includes(command.type); +} + +function withoutEditHold(run: OrchestrationV2Run): OrchestrationV2Run { + const { editHeldUntil: _editHeldUntil, ...rest } = run; + return rest; +} + // Delegated completions, monitor notifications and queued messages that name no model never choose a // model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. function followsCurrentConversation( @@ -2516,9 +2551,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (yield* cancelStaleQuestionWakes(projection)) { projection = yield* readCommandProjection(threadId); } + // The head is read past an edit hold so a failure below still holds the queue. let storedQueuedRun = options?.queuedRunId === undefined - ? nextQueuedRun(projection) + ? queueHead(projection) : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); @@ -2530,7 +2566,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now), ); projection = yield* readCommandProjection(threadId); - storedQueuedRun = nextQueuedRun(projection); + storedQueuedRun = queueHead(projection); } // A wake that outlived some of its pull requests tells only the current ones. const currentWake = @@ -2562,7 +2598,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); const modelSelection = queuedRunModelSelection(projection, storedQueuedRun); const queuedRun = { - ...storedQueuedRun, + ...withoutEditHold(storedQueuedRun), modelSelection, providerInstanceId: modelSelection.instanceId, }; @@ -2645,6 +2681,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); return wakes.length > 0; } + if (options?.queuedRunId === undefined && storedQueuedRun.editHeldUntil !== undefined) { + return; + } // Move queued ordinals after runs that started while they waited to preserve transcript and checkpoint order. // Started runs have prompts; cancelled queued messages do not. const newerRunIds = projection.runs @@ -7908,7 +7947,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.steerFollowUpOfRunId === undefined ? undefined : projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); - const queueBehindRun = activeRun ?? worktreeMissingRun ?? steerFollowUpSource; + // Subagent results are delivered before the queue, so they do not wait on an edit. + const idleQueueHead = + activeRun === undefined && delegatedCompletion === undefined + ? queueHead(projection) + : undefined; + const editPausedRun = idleQueueHead?.editHeldUntil === undefined ? undefined : idleQueueHead; + const queueBehindRun = activeRun ?? worktreeMissingRun ?? steerFollowUpSource ?? editPausedRun; const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection); const startsOrQueuesRun = dispatchMode.type === "defer_start" || @@ -12246,22 +12291,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); }); - const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* ( - command: Extract, - events: Ref.Ref>, - effects: Ref.Ref>, + const requireEditableQueuedRun = Effect.fn("Orchestrator.requireEditableQueuedRun")(function* ( + command: Extract< + OrchestrationV2Command, + { readonly type: "queued-run.edit" | "queued-run.hold" } + >, + projection: Pick, ) { - if (command.text.trim().length === 0) { - return yield* new OrchestratorDispatchError({ - commandId: command.commandId, - commandType: command.type, - cause: `Queued run ${command.runId} cannot be edited to an empty message.`, - }); - } - const projection = yield* loadProjectionForCommand(command, ["runs", "messages", "turnItems"], { - turnItemTypes: ["user_message"], - messageRoles: ["user"], - }); const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId); if (queuedRun === undefined || queuedRun.status !== "queued") { return yield* new OrchestratorDispatchError({ @@ -12298,6 +12334,26 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A guest's message cannot be edited. Cancel it instead.", }); } + return { queuedRun, queuedMessage }; + }); + + const dispatchQueuedRunEdit = Effect.fn("Orchestrator.dispatchQueuedRunEdit")(function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + if (command.text.trim().length === 0) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Queued run ${command.runId} cannot be edited to an empty message.`, + }); + } + const projection = yield* loadProjectionForCommand(command, ["runs", "messages", "turnItems"], { + turnItemTypes: ["user_message"], + messageRoles: ["user"], + }); + const { queuedRun, queuedMessage } = yield* requireEditableQueuedRun(command, projection); yield* ensureGoalCommandSupported( command, { text: command.text, attachments: command.attachments ?? queuedMessage.attachments }, @@ -12398,15 +12454,111 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ]); } + if (queuedRun.editHeldUntil !== undefined) { + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: withoutEditHold(queuedRun), + }); + } }); + const editHoldExpiryEffect = ( + command: { readonly commandId: CommandId; readonly threadId: ThreadId }, + runId: RunId, + heldUntil: DateTime.Utc, + ): PendingOrchestrationEffectV2 => ({ + id: `effect:queued-run.hold.expire:${runId}:${DateTime.toEpochMillis(heldUntil)}`, + commandId: command.commandId, + threadId: command.threadId, + request: { type: "queued-run.hold.expire", runId, heldUntil }, + availableAt: heldUntil, + }); + + const dispatchQueuedRunHold = Effect.fn("Orchestrator.dispatchQueuedRunHold")(function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const projection = yield* loadProjectionForCommand(command, ["runs", "messages"], { + messageRoles: ["user"], + }); + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + if (!command.held) { + // The message may have started or been cancelled while the edit was open. + const run = projection.runs.find((candidate) => candidate.id === command.runId); + if (run?.status !== "queued" || run.editHeldUntil === undefined) return; + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: withoutEditHold(run), + }); + return; + } + const { queuedRun } = yield* requireEditableQueuedRun(command, projection); + const heldUntil = DateTime.add(now, { milliseconds: QUEUED_RUN_EDIT_HOLD_MS }); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { ...queuedRun, editHeldUntil: heldUntil }, + }); + // A renewal only moves the deadline; the pending timer follows it when it fires. + if (queuedRun.editHeldUntil === undefined) { + yield* Ref.update(effects, (existing) => [ + ...existing, + editHoldExpiryEffect(command, queuedRun.id, heldUntil), + ]); + } + }); + + const dispatchQueuedRunHoldExpire = Effect.fn("Orchestrator.dispatchQueuedRunHoldExpire")( + function* ( + command: Extract, + events: Ref.Ref>, + effects: Ref.Ref>, + ) { + const projection = yield* loadProjectionForCommand(command, ["runs"]); + const run = projection.runs.find((candidate) => candidate.id === command.runId); + if (run?.status !== "queued" || run.editHeldUntil === undefined) return; + if (DateTime.isGreaterThan(run.editHeldUntil, command.heldUntil)) { + const renewedUntil = run.editHeldUntil; + yield* Ref.update(effects, (existing) => [ + ...existing, + editHoldExpiryEffect(command, run.id, renewedUntil), + ]); + return; + } + yield* emit( + events, + command, + )({ + type: "run.updated", + threadId: command.threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: yield* DateTime.now, + payload: withoutEditHold(run), + }); + }, + ); + const subagentCount = (threadId: ThreadId) => projectionStore .getSubagentCount(threadId) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); const loadProjectionForCommand = ( - command: OrchestrationV2Command, + command: OrchestrationV2ServerCommand, fields: ReadonlyArray, filter?: ProjectionRecordFilter, ) => @@ -16036,6 +16188,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "run.output.submit": yield* dispatchRunOutputSubmit(command, events); break; + case "queued-run.hold": + yield* dispatchQueuedRunHold(command, events, effects); + break; + case "queued-run.hold.expire": + yield* dispatchQueuedRunHoldExpire(command, events, effects); + break; case "checkpoint.rollback": yield* dispatchCheckpointRollback(command, events, effects); break; @@ -16135,10 +16293,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); - if (command.type === "queue.resume" || command.type === "queued-run.start") { + if (startsQueueAfterCommit(command)) { yield* mapDispatchError(command)( startNextQueuedRun(command.threadId, { - userStarted: true, + userStarted: command.type === "queue.resume" || command.type === "queued-run.start", ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), }), ); @@ -16150,6 +16308,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies OrchestratorV2DispatchResult; }); + // A deferred steer skips its turn's start while the message is being edited. + const deliverSteerAfterEdit = Effect.fn("Orchestrator.deliverSteerAfterEdit")( + function* (threadId: ThreadId, runId: RunId, commandId: CommandId) { + const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runStatuses: ["queued", "running"], + }); + const queued = runs.find((run) => run.id === runId); + if ( + queued?.status !== "queued" || + queued.editHeldUntil !== undefined || + queued.steerWhenReadyRunId === undefined + ) { + return; + } + const target = runs.find((run) => run.id === queued.steerWhenReadyRunId); + if (target?.status !== "running") return; + yield* dispatchWithReceiptEffect({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(`command:deferred-steer:${queued.id}:${commandId}`), + threadId, + queuedRunId: queued.id, + targetRunId: target.id, + }); + }, + Effect.catchCause((cause) => + Effect.logWarning("Failed to deliver a steer after its edit", { cause }), + ), + ); + /** `sideChatIds` are the live side chats a delete, archive, or unarchive cascades to, read under their locks. */ const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* ( command: OrchestrationV2ServerCommand, @@ -16223,6 +16410,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "subagent.stop" || // Closing a share again, or after it ended, is not an error. command.type === "thread.guest-share.close" || + // Nor is ending an edit hold that already ended, or a timer that finds it renewed. + command.type === "queued-run.hold.expire" || + (command.type === "queued-run.hold" && !command.held) || (command.type === "thread.delete" && command.onlyIfUnused === true), (_planned) => new OrchestratorDispatchError({ @@ -16388,17 +16578,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } if ( - command.type === "queue.resume" || - command.type === "queued-run.start" || + startsQueueAfterCommit(command) || (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined) ) { yield* mapDispatchError(command)( startNextQueuedRun(command.threadId, { - userStarted: command.type !== "thread.runtime-mode.set", + userStarted: command.type === "queue.resume" || command.type === "queued-run.start", ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), }), ); } + if ( + command.type === "queued-run.edit" || + command.type === "queued-run.hold.expire" || + (command.type === "queued-run.hold" && !command.held) + ) { + yield* deliverSteerAfterEdit(command.threadId, command.runId, command.commandId); + } if ( command.type === "notification.delivery.accept" || // A steer restart that settled a wake can reserve the next one for its siblings. @@ -16681,7 +16877,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (run === undefined) return; const pending = projection.runs .filter( - (queued) => queued.status === "queued" && queued.steerWhenReadyRunId === run.id, + (queued) => + queued.status === "queued" && + queued.steerWhenReadyRunId === run.id && + queued.editHeldUntil === undefined, ) .toSorted( (left, right) => diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 04257d91bc9a7..27cd4a92fe0d7 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1122,6 +1122,109 @@ it.effect.each( }), ); +it.effect("a deferred steer waits for its edit and then steers the edited text", () => + Effect.gen(function* () { + const { steered, layer, startFirstTurn, events } = yield* nextTurnSelectionHarness( + "deferred-steer-edit-hold", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sink = yield* EventSink.EventSinkV2; + const threadId = yield* startFirstTurn; + const before = yield* orchestrator.getThreadProjection(threadId); + const run = before.runs[0]!; + const turn = before.providerTurns[0]!; + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make("setup-run"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...run, status: "preparing" }, + }, + { + id: EventId.make("setup-turn"), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + const steerAfterSetup = (text: string) => + Effect.gen(function* () { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(text), + threadId, + messageId: MessageId.make(`message:${text}`), + text, + attachments: [], + deliveryIntent: "steer", + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + return (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), + )!; + }); + const edited = yield* steerAfterSetup("being edited"); + const other = yield* steerAfterSetup("not edited"); + yield* orchestrator.dispatch({ + type: "queued-run.hold", + commandId: CommandId.make("hold-steer"), + threadId, + runId: edited.id, + held: true, + }); + const otherPromoted = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === other.id && + event.payload.status === "cancelled", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* worker.drain(); + yield* sink.write({ + events: [ + { + id: EventId.make("ready-run"), + type: "run.updated", + threadId, + occurredAt: now, + payload: run, + }, + ], + }); + yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); + // Both steers wait on this turn, so the later one landing means the held one was passed over. + yield* Fiber.join(otherPromoted); + yield* worker.drain(); + assert.deepEqual(steered, ["not edited"]); + + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("save-steer"), + threadId, + runId: edited.id, + text: "edited before steering", + }); + yield* worker.drain(); + assert.deepEqual(steered, ["not edited", "edited before steering"]); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.equal(after.runs.find((candidate) => candidate.id === edited.id)?.status, "cancelled"); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("force sends multiple queued messages and can force send a requeued message again", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index fc52191d32b29..71036cd2672c2 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -158,7 +158,10 @@ const threadState = (threadId: ThreadId) => const orchestrator = yield* Orchestrator.OrchestratorV2; const projection = yield* orchestrator.getThreadProjection(threadId); return { - runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`), + runs: projection.runs.map( + (run) => + `${run.status}${run.queueHeld === true ? ":held" : ""}${run.editHeldUntil === undefined ? "" : ":editing"}`, + ), watched: (projection.thread.pullRequests ?? []) .filter((link) => link.watch !== undefined) .map((link) => link.number), @@ -800,6 +803,141 @@ it.effect("a message the user sends after Stop releases the held queue; an agent }).pipe(Effect.provide(layerTest)), ); +const completeRun = (threadId: ThreadId, index: number) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[index]!; + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make(`event:${run.id}:completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", completedAt: now }, + }); + yield* orchestrator.resumeQueuedRuns; + }); + +const holdForEdit = (threadId: ThreadId, runIndex: number, commandId: string, held: boolean) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[runIndex]!; + yield* orchestrator.dispatch({ + type: "queued-run.hold", + commandId: CommandId.make(commandId), + threadId, + runId: run.id, + held, + }); + }); + +it.effect("the queue waits at a message being edited once it is next", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("thread:edit-hold"); + yield* createWatchingThread(threadId, 40); + yield* send(threadId, "active", "start_immediately"); + yield* send(threadId, "ahead", "queue_after_active"); + yield* send(threadId, "edited", "queue_after_active"); + yield* holdForEdit(threadId, 2, "hold-edited", true); + + yield* completeRun(threadId, 0); + assert.deepEqual((yield* threadState(threadId)).runs, [ + "completed", + "starting", + "queued:editing", + ]); + + // Anything sent while the queue waits, even to an idle thread, waits behind the edit. + yield* completeRun(threadId, 1); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("edit-hold:agent-send"), + threadId, + messageId: MessageId.make(`message:${threadId}:agent`), + text: "agent nudge", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make("edit-hold:resume"), + threadId, + }); + assert.deepEqual((yield* threadState(threadId)).runs, [ + "completed", + "completed", + "queued:editing", + "queued", + ]); + + const edited = (yield* orchestrator.getThreadProjection(threadId)).runs[2]!; + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit-hold:save"), + threadId, + runId: edited.id, + text: "edited and saved", + }); + const saved = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual((yield* threadState(threadId)).runs, [ + "completed", + "completed", + "starting", + "queued", + ]); + assert.equal( + saved.messages.find((message) => message.id === edited.userMessageId)?.text, + "edited and saved", + ); + }).pipe(Effect.provide(layerTest)), +); + +it.effect.each(["expires", "is released"] as const)( + "an edit hold starts the queue when it %s", + (ending) => + Effect.gen(function* () { + const threadId = ThreadId.make(`thread:edit-hold-${ending.replaceAll(" ", "-")}`); + const sql = yield* SqlClient.SqlClient; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const fireDueHoldTimer = Effect.gen(function* () { + yield* sql`DELETE FROM orchestration_v2_effect_outbox WHERE effect_type != 'queued-run.hold.expire'`; + yield* worker.drain(1); + }); + yield* createWatchingThread(threadId, 41); + yield* send(threadId, "active", "start_immediately"); + yield* send(threadId, "edited", "queue_after_active"); + yield* holdForEdit(threadId, 1, `${threadId}:hold`, true); + yield* completeRun(threadId, 0); + + // Renewing keeps the hold past the first expiry. + yield* TestClock.adjust("3 minutes"); + yield* holdForEdit(threadId, 1, `${threadId}:renew`, true); + yield* TestClock.adjust("2 minutes"); + yield* fireDueHoldTimer; + assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "queued:editing"]); + + if (ending === "is released") { + yield* holdForEdit(threadId, 1, `${threadId}:release`, false); + assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "starting"]); + } + yield* TestClock.adjust("3 minutes"); + yield* fireDueHoldTimer; + assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "starting"]); + const timers = yield* sql<{ readonly status: string }>` + SELECT status FROM orchestration_v2_effect_outbox + WHERE effect_type = 'queued-run.hold.expire' ORDER BY available_at`; + assert.deepEqual( + timers.map((timer) => timer.status), + ["succeeded", "succeeded"], + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect( "an agent's auto send queues behind a run that is still stopping instead of steering it", () => diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b5072355659ef..8c806441b3d8a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -11585,6 +11585,118 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("a provider failure during an edit holds the queue past the save", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("queue-hold-edit-after-failure"); + const send = (key: string, dispatchMode: "start_immediately" | "queue_after_active") => + orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:message:${key}`), + threadId, + messageId: MessageId.make(`${threadId}:${key}`), + text: key, + attachments: [], + modelSelection, + dispatchMode: { type: dispatchMode }, + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`${threadId}:create`), + threadId, + projectId: ProjectId.make(`${threadId}:project`), + title: "Edit behind a failed run", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* send("active", "start_immediately"); + yield* send("edited", "queue_after_active"); + const [active, edited] = (yield* orchestrator.getThreadProjection(threadId)).runs; + yield* orchestrator.dispatch({ + type: "queued-run.hold", + commandId: CommandId.make(`${threadId}:hold`), + threadId, + runId: edited!.id, + held: true, + }); + const afterSequence = yield* orchestrator.getThreadEventSequence(threadId); + const failureHold = yield* eventSink.stream({ threadId, afterSequence }).pipe( + Stream.filter( + (stored) => + stored.event.type === "run.updated" && + stored.event.payload.id === edited!.id && + stored.event.payload.queueHeld === true, + ), + Stream.runHead, + Effect.forkScoped, + ); + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:active:error`), + type: "turn-item.updated", + threadId, + runId: active!.id, + nodeId: active!.rootNodeId!, + providerInstanceId: active!.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:active:error`), + type: "error", + threadId, + runId: active!.id, + nodeId: active!.rootNodeId, + providerThreadId: active!.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Provider failure", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error", + message: "Provider request failed with HTTP 502", + code: null, + retryable: null, + }, + }, + }, + { + id: EventId.make(`${threadId}:active:failed`), + type: "run.updated", + threadId, + runId: active!.id, + providerInstanceId: active!.providerInstanceId, + occurredAt: now, + payload: { ...active!, status: "failed", startedAt: now, completedAt: now }, + }, + ], + }); + assert.isTrue(Option.isSome(yield* Fiber.join(failureHold))); + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make(`${threadId}:save`), + threadId, + runId: edited!.id, + text: "edited", + }); + const saved = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; + assert.deepInclude(saved, { status: "queued", queueHeld: true }); + }), + ); + it.effect("edits and removes queued runs", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index 15ac7ecb8d3fe..896ecc2d247a5 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -184,6 +184,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray ( startedAt: Schema.NullOr(Schema.DateTimeUtcFromString), completedAt: Schema.NullOr(Schema.DateTimeUtcFromString), workStartedAt: Schema.optional(Schema.DateTimeUtcFromString), + editHeldUntil: Schema.optional(Schema.DateTimeUtcFromString), })); export type OrchestrationV2RunJson = typeof OrchestrationV2RunJson.Type; @@ -3665,6 +3668,14 @@ export const OrchestrationV2Command = Schema.Union([ // Replaces all attachments; absent preserves them for older clients editing text. attachments: Schema.optional(Schema.Array(ChatAttachment)), }), + /** Starts or renews (`held: true`) or ends an edit hold; it lapses after QUEUED_RUN_EDIT_HOLD_MS. */ + Schema.Struct({ + type: Schema.Literal("queued-run.hold"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + held: Schema.Boolean, + }), Schema.Struct({ type: Schema.Literal("runtime-request.respond"), commandId: CommandId, @@ -3765,8 +3776,19 @@ export const OrchestrationV2Command = Schema.Union([ ]); export type OrchestrationV2Command = typeof OrchestrationV2Command.Type; +// Clients renew well inside the hold, since a hidden browser tab may run its timers only once a minute. +export const QUEUED_RUN_EDIT_HOLD_MS = 2 * 60_000; +export const QUEUED_RUN_EDIT_HOLD_RENEW_MS = 30_000; + // Excluded from dispatchCommand so only the server can send these. const OrchestrationV2InternalCommand = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("queued-run.hold.expire"), + commandId: CommandId, + threadId: ThreadId, + runId: RunId, + heldUntil: Schema.DateTimeUtc, + }), // The server issues this after checking the value against the run's declared schema. Schema.Struct({ type: Schema.Literal("run.output.submit"), From 6cd61c628b551d0cb0640dc69370ed357c91e4f8 Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 03:29:34 -0500 Subject: [PATCH 2/7] fix(web,mobile): editing a queued message holds the queue until you save or cancel Opening a queued message for editing asks the server to hold it, renews the hold every 30 seconds, and releases it on cancel or when another message is opened. A server without the hold rejects it and editing works as before. --- .../features/threads/ThreadQueueControl.tsx | 8 +++ apps/mobile/src/state/queued-run-edit.test.ts | 14 ++--- apps/mobile/src/state/queued-run-edit.ts | 4 +- .../chat/useQueuedRunEdit.browser.test.tsx | 11 +++- .../src/components/chat/useQueuedRunEdit.ts | 10 ++++ .../client-runtime/src/operations/commands.ts | 17 ++++++ .../client-runtime/src/queuedRunEdit.test.ts | 53 ++++++++++++++++--- packages/client-runtime/src/queuedRunEdit.ts | 51 ++++++++++++++++-- .../src/state/threadCommands.ts | 7 +++ 9 files changed, 153 insertions(+), 22 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 4f5b799f82879..869b19a4193d6 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -146,6 +146,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { ); const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message"); const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "remove queued message"); + const holdQueuedRun = useAtomCommand(threadEnvironment.holdQueuedRun, { + label: "hold queued message", + reportFailure: false, + reportDefect: false, + }); const resume = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue"); const resumeHeldQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, { label: "resume queue", @@ -192,6 +197,9 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { (get) => get(environmentThreadDetails.quietThreadAtom(target))?.projection.runs ?? null, ), }), + (held) => { + void holdQueuedRun({ ...target, input: { threadId: target.threadId, runId, held } }); + }, ); navigation.goBack(); return; diff --git a/apps/mobile/src/state/queued-run-edit.test.ts b/apps/mobile/src/state/queued-run-edit.test.ts index 8a6176c1140c0..0f3578c91852e 100644 --- a/apps/mobile/src/state/queued-run-edit.test.ts +++ b/apps/mobile/src/state/queued-run-edit.test.ts @@ -127,7 +127,7 @@ describe("beginQueuedRunEdit", () => { const runs = Atom.make | null>( [{ id: original.runId, status: "queued" }], ); - beginQueuedRunEdit(threadKey, original, runs); + beginQueuedRunEdit(threadKey, original, runs, () => {}); const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, original.runId)); expect(draft.text).toBe(prefix.trimEnd()); expect( @@ -146,7 +146,7 @@ describe("beginQueuedRunEdit", () => { const runs = Atom.make | null>([ { id: runId, status: "queued" }, ]); - beginQueuedRunEdit(threadKey, edit([]), runs); + beginQueuedRunEdit(threadKey, edit([]), runs, () => {}); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); @@ -163,7 +163,7 @@ describe("beginQueuedRunEdit", () => { const runs = Atom.make | null>([ { id: runId, status: "queued" }, ]); - beginQueuedRunEdit(threadKey, edit([image("removed")]), runs); + beginQueuedRunEdit(threadKey, edit([image("removed")]), runs, () => {}); removeQueuedRunEditAttachment(threadKey, "removed"); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); @@ -184,7 +184,7 @@ describe("beginQueuedRunEdit", () => { const runs = Atom.make | null>([ { id: runId, status: "queued" }, ]); - beginQueuedRunEdit(threadKey, edit([]), runs); + beginQueuedRunEdit(threadKey, edit([]), runs, () => {}); setComposerDraftText(queuedEditDraftKey(threadKey, runId), "revised"); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); @@ -205,7 +205,7 @@ describe("beginQueuedRunEdit", () => { { id: runId, status: "queued" }, ]); setComposerDraftText(threadKey, "other work"); - beginQueuedRunEdit(threadKey, edit([]), runs); + beginQueuedRunEdit(threadKey, edit([]), runs, () => {}); setComposerDraftText(queuedEditDraftKey(threadKey, runId), "changed"); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); @@ -223,7 +223,7 @@ describe("beginQueuedRunEdit", () => { const runs = Atom.make | null>([ { id: runId, status: "queued" }, ]); - beginQueuedRunEdit(threadKey, edit([]), runs); + beginQueuedRunEdit(threadKey, edit([]), runs, () => {}); setComposerDraftText(queuedEditDraftKey(threadKey, runId), ""); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); @@ -242,7 +242,7 @@ describe("beginQueuedRunEdit", () => { { id: runId, status: "queued" }, ]); setComposerDraftText(threadKey, "other work"); - beginQueuedRunEdit(threadKey, edit([image("kept")]), runs); + beginQueuedRunEdit(threadKey, edit([image("kept")]), runs, () => {}); removeQueuedRunEditAttachment(threadKey, "kept"); appAtomRegistry.set(runs, [{ id: runId, status: "running" }]); diff --git a/apps/mobile/src/state/queued-run-edit.ts b/apps/mobile/src/state/queued-run-edit.ts index 3c046f847f29f..17f5ffaf7de03 100644 --- a/apps/mobile/src/state/queued-run-edit.ts +++ b/apps/mobile/src/state/queued-run-edit.ts @@ -11,6 +11,7 @@ import { stripAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerCont import { makeQueuedRunEditStore, resolveQueuedEditExit, + type HoldQueuedRun, type QueuedRunsAtom, } from "@t3tools/client-runtime/queued-run-edit"; @@ -113,6 +114,7 @@ export function beginQueuedRunEdit( threadKey: string, edit: QueuedRunEdit, runs: QueuedRunsAtom, + hold: HoldQueuedRun, ): void { const previous = getQueuedRunEdit(threadKey); if (previous !== null && previous.runId !== edit.runId) { @@ -128,7 +130,7 @@ export function beginQueuedRunEdit( queuedRunEdits.begin( threadKey, { ...edit, originalText }, - { runs, onRunLeftQueue: exitQueuedRunEdit }, + { runs, onRunLeftQueue: exitQueuedRunEdit, hold }, ); } diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..81b55058b1022 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -42,6 +42,8 @@ const mocks = await vi.hoisted(async () => { editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(), promoteQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), promoteCommand: {}, + holdQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" }>>(), + holdCommand: {}, // The projection's runs per thread, written by each test to stand in for the server. threadRuns: Atom.family((_key: string) => Atom.make | null>(null).pipe(Atom.keepAlive), @@ -51,7 +53,11 @@ const mocks = await vi.hoisted(async () => { vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => - command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, + command === mocks.promoteCommand + ? mocks.promoteQueuedRun + : command === mocks.holdCommand + ? mocks.holdQueuedRun + : mocks.editQueuedRun, })); vi.mock("../../hooks/useSettings", () => ({ @@ -68,6 +74,7 @@ vi.mock("../../state/threads", async () => { snapshotAtom: () => Atom.make(null), editQueuedRun: {}, promoteQueuedRun: mocks.promoteCommand, + holdQueuedRun: mocks.holdCommand, }, environmentThreadDetails: { statusAtom: () => Atom.make("ready"), @@ -178,6 +185,8 @@ function view( function setup() { mocks.editQueuedRun.mockReset(); mocks.promoteQueuedRun.mockReset(); + mocks.holdQueuedRun.mockReset(); + mocks.holdQueuedRun.mockResolvedValue({ _tag: "Success" }); useAttachmentUploadStore.setState({ uploadsByImageId: {} }); useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} }); setRuns(THREAD_A, "queued"); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 61907b93cfb22..006c3ed517562 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -224,6 +224,10 @@ export function useQueuedRunEdit(input: { } = input; const editQueuedRunCommand = useEditQueuedRunCommand(); const promoteQueuedRun = useAtomCommand(threadEnvironment.promoteQueuedRun); + const holdQueuedRun = useAtomCommand(threadEnvironment.holdQueuedRun, { + reportFailure: false, + reportDefect: false, + }); const editKey = scopedThreadKey(routeThreadRef); const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null; const editing = activeThreadId === null ? null : storedEdit; @@ -294,6 +298,12 @@ export function useQueuedRunEdit(input: { context, }, { + hold: (held) => { + void holdQueuedRun({ + environmentId, + input: { threadId: activeThreadId, runId: request.runId, held }, + }); + }, runs: makeQueuedRunsAtom({ threadId: activeThreadId, snapshot: threadEnvironment.snapshotAtom(environmentId), diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..e1f1e4cfaf9b4 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -276,6 +276,11 @@ export interface CancelQueuedRunInput extends ThreadCommandInput { readonly runId: RunId; } +export interface HoldQueuedRunInput extends ThreadCommandInput { + readonly runId: RunId; + readonly held: boolean; +} + export interface RetryWorkspacePreparationInput extends ThreadCommandInput { readonly runId: RunId; } @@ -1188,6 +1193,18 @@ export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")( }); }); +export const holdQueuedRun = Effect.fn("EnvironmentCommands.holdQueuedRun")(function* ( + input: HoldQueuedRunInput, +) { + return yield* dispatch({ + type: "queued-run.hold", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + runId: input.runId, + held: input.held, + }); +}); + export const retryWorkspacePreparation = Effect.fn("EnvironmentCommands.retryWorkspacePreparation")( function* (input: RetryWorkspacePreparationInput) { return yield* dispatch({ diff --git a/packages/client-runtime/src/queuedRunEdit.test.ts b/packages/client-runtime/src/queuedRunEdit.test.ts index 6d71f3ec11f9c..36d922de4080c 100644 --- a/packages/client-runtime/src/queuedRunEdit.test.ts +++ b/packages/client-runtime/src/queuedRunEdit.test.ts @@ -1,6 +1,6 @@ -import { RunId } from "@t3tools/contracts"; +import { QUEUED_RUN_EDIT_HOLD_RENEW_MS, RunId } from "@t3tools/contracts"; import { Atom, AtomRegistry } from "effect/reactivity"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { makeQueuedRunEditStore, @@ -21,13 +21,18 @@ function setup(initialRuns: ReadonlyArray | null = queued()) { label: "test-queued-run-edits", }); const exits: Array<{ threadKey: string; text: string }> = []; - const begin = () => + const holds: Array = []; + const begin = (runId = RUN) => store.begin( "env:thread", - { runId: RUN, text: "draft" }, - { runs, onRunLeftQueue: (threadKey, edit) => exits.push({ threadKey, text: edit.text }) }, + { runId, text: "draft" }, + { + runs, + onRunLeftQueue: (threadKey, edit) => exits.push({ threadKey, text: edit.text }), + hold: (held) => holds.push(`${runId}:${held ? "hold" : "release"}`), + }, ); - return { registry, runs, store, exits, begin }; + return { registry, runs, store, exits, holds, begin }; } describe("resolveQueuedEditExit", () => { @@ -51,6 +56,34 @@ describe("queuedRunEditBlockedReason", () => { }); describe("makeQueuedRunEditStore", () => { + it("holds the queue while editing and releases it only when the edit is abandoned", () => { + vi.useFakeTimers(); + try { + const { registry, runs, store, holds, begin } = setup(); + begin(); + vi.advanceTimersByTime(QUEUED_RUN_EDIT_HOLD_RENEW_MS); + expect(holds).toEqual(["run-1:hold", "run-1:hold"]); + + // Switching messages releases the first; cancelling releases the second. + const other = RunId.make("run-2"); + registry.set(runs, [...queued(), { id: other, status: "queued" }]); + begin(other); + store.end("env:thread"); + expect(holds.slice(2)).toEqual(["run-1:release", "run-2:hold", "run-2:release"]); + + // A save or a started run already ended the hold on the server. + holds.length = 0; + begin(); + store.startSave("env:thread")?.(true); + begin(); + registry.set(runs, []); + vi.advanceTimersByTime(QUEUED_RUN_EDIT_HOLD_RENEW_MS * 2); + expect(holds).toEqual(["run-1:hold", "run-1:hold"]); + } finally { + vi.useRealTimers(); + } + }); + it("fires once when the edited run leaves the queue, with the latest edit", () => { const { registry, runs, store, exits, begin } = setup(); begin(); @@ -189,7 +222,7 @@ describe("makeQueuedRunEditStore", () => { label: "test-queued-run-edits", }); const begin = () => - store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: () => {} }); + store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: () => {}, hold: () => {} }); begin(); expect(mounted).toBe(1); @@ -241,7 +274,11 @@ describe("makeQueuedRunsAtom", () => { label: "test-queued-run-edits", }); const exits: Array = []; - store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: (key) => exits.push(key) }); + store.begin( + "env:thread", + { runId: RUN }, + { runs, onRunLeftQueue: (key) => exits.push(key), hold: () => {} }, + ); return { registry, snapshot, diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.ts index 45805c3ff74d0..7c535e21a3e6c 100644 --- a/packages/client-runtime/src/queuedRunEdit.ts +++ b/packages/client-runtime/src/queuedRunEdit.ts @@ -1,3 +1,4 @@ +// @effect-diagnostics globalTimers:off - The edit store renews its hold from plain client state, outside an Effect runtime. import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; /** @@ -6,7 +7,7 @@ import type { MFunctionType } from "gt-i18n/types"; * once, when the projection reports it, wherever the user is in the app. It also * owns the edit's save, because a save outlives the view that started it. */ -import type { RunId } from "@t3tools/contracts"; +import { QUEUED_RUN_EDIT_HOLD_RENEW_MS, type RunId } from "@t3tools/contracts"; import { Atom, type AtomRegistry } from "effect/reactivity"; export interface QueuedRunStatus { @@ -86,6 +87,19 @@ interface ExitWatch { cancel: (() => void) | null; } +/** + * Asks the server to hold (true) or release (false) the queue at the edited + * message. Failures are ignored: an older server, or a run that already + * started, leaves the edit unheld and the exit watch recovers it. + */ +export type HoldQueuedRun = (held: boolean) => void; + +interface EditHold { + readonly runId: RunId; + readonly hold: HoldQueuedRun; + readonly renew: ReturnType; +} + /** * Settles a save from `startSave`. False, changing nothing, when the edit was * ended or begun again meanwhile. Success ends the edit; failure resumes its @@ -108,6 +122,25 @@ export function makeQueuedRunEditStore(opti ); // Each begin creates a new watch, so the watch is the edit's identity. const watches = new Map>(); + const holds = new Map(); + + const startHold = (threadKey: string, runId: RunId, hold: HoldQueuedRun) => { + hold(true); + holds.set(threadKey, { + runId, + hold, + renew: setInterval(() => hold(true), QUEUED_RUN_EDIT_HOLD_RENEW_MS), + }); + }; + + // The server drops the hold itself once the run starts or a save lands. + const stopHold = (threadKey: string, release: boolean) => { + const current = holds.get(threadKey); + if (current === undefined) return; + clearInterval(current.renew); + holds.delete(threadKey); + if (release) current.hold(false); + }; const setSaving = (threadKey: string, saving: boolean) => { const current = registry.get(savingAtom); @@ -144,6 +177,7 @@ export function makeQueuedRunEditStore(opti if (!runLeftQueue(runs, watch.runId)) return; unsubscribe(watch); watches.delete(threadKey); + stopHold(threadKey, false); const edit = get(threadKey); if (edit === null || edit.runId !== watch.runId) return; write(threadKey, null); @@ -166,9 +200,10 @@ export function makeQueuedRunEditStore(opti savingAtom, get, /** - * Starts an edit, replacing any edit already open on the thread. When the - * run leaves the queue the edit is removed and `onRunLeftQueue` receives - * it; if the run already left, that happens immediately. + * Starts an edit, replacing any edit already open on the thread. The queue + * is held at the run until the edit ends. When the run leaves the queue the + * edit is removed and `onRunLeftQueue` receives it; if the run already + * left, that happens immediately. */ begin( threadKey: string, @@ -176,12 +211,16 @@ export function makeQueuedRunEditStore(opti watch: { readonly runs: QueuedRunsAtom; readonly onRunLeftQueue: (threadKey: string, edit: E) => void; + readonly hold: HoldQueuedRun; }, ) { stopWatch(threadKey); + stopHold(threadKey, holds.get(threadKey)?.runId !== edit.runId); write(threadKey, edit); - const next: ExitWatch = { ...watch, runId: edit.runId, cancel: null }; + const { hold, ...exit } = watch; + const next: ExitWatch = { ...exit, runId: edit.runId, cancel: null }; watches.set(threadKey, next); + startHold(threadKey, edit.runId, hold); subscribe(threadKey, next); }, update(threadKey: string, f: (edit: E) => E) { @@ -190,6 +229,7 @@ export function makeQueuedRunEditStore(opti }, end(threadKey: string) { stopWatch(threadKey); + stopHold(threadKey, true); write(threadKey, null); }, /** @@ -212,6 +252,7 @@ export function makeQueuedRunEditStore(opti if (watches.get(threadKey) !== watch) return false; if (succeeded) { stopWatch(threadKey); + stopHold(threadKey, false); write(threadKey, null); return true; } diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 98d88407b85b4..0e1de5a7acc1a 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -27,6 +27,7 @@ import { closeGuestShare, resolveGuestMessage, cancelQueuedRun, + holdQueuedRun, createThread, deleteThread, editQueuedRun, @@ -438,6 +439,12 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency, }), + holdQueuedRun: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:hold-queued-run", + execute: holdQueuedRun, + scheduler, + concurrency, + }), retryWorkspacePreparation: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:retry-workspace-preparation", execute: retryWorkspacePreparation, From 1172481d7504472da97c8c57c8059d02e5a7da12 Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 03:43:31 -0500 Subject: [PATCH 3/7] fix(server): edit holds keep failure holds, subagent results, and a saved command's place Starts that an edit triggers check the latest turn for a failure, as the run-end handler would, so a save that beats that handler cannot start queued work after a failed turn. Subagent results pass a message that is being edited. Saving a deferred steer as a slash command no longer restores its steer target in a second run update. --- .../src/orchestration-v2/Orchestrator.ts | 66 +++--- .../orchestration-v2/QueuedRunOrder.test.ts | 28 ++- .../src/orchestration-v2/QueuedRunOrder.ts | 17 ++ .../SteeringCompletion.integration.test.ts | 207 +++++++++--------- .../src/orchestration-v2/ThreadStop.test.ts | 74 ++++++- 5 files changed, 249 insertions(+), 143 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3428076cffa42..8fb5a60dc60e0 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -203,7 +203,12 @@ import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; import * as RunExecutionService from "./RunExecutionService.ts"; import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts"; import { ProviderSwitchServiceV2 } from "./ProviderSwitchService.ts"; -import { isAutomaticCompletionRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; +import { + isAutomaticCompletionRun, + nextQueuedRun, + queueHead, + queuedRunsInDeliveryOrder, +} from "./QueuedRunOrder.ts"; import { isRuntimePolicyAboveCeilingError, RuntimePolicyV2 } from "./RuntimePolicy.ts"; import { endOrphanedNativeSubagent, @@ -1037,19 +1042,6 @@ function worktreeSetupPending( ); } -function queueHead( - projection: Pick, -): OrchestrationV2Run | undefined { - return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); -} - -function nextQueuedRun( - projection: Pick, -): OrchestrationV2Run | undefined { - const head = queueHead(projection); - return head?.editHeldUntil === undefined ? head : undefined; -} - // Each can change which queued message is next, or end the edit the queue waits on. const QUEUE_CHANGING_COMMAND_TYPES = [ "queue.resume", @@ -1070,6 +1062,13 @@ function startsQueueAfterCommit( return (QUEUE_CHANGING_COMMAND_TYPES as ReadonlyArray).includes(command.type); } +// Only Resume and Send now are a person choosing to go on; the rest still honor a turn that just failed. +function queueStartAfterCommit(command: OrchestrationV2ServerCommand) { + if (command.type === "queued-run.start") return { userStarted: true, queuedRunId: command.runId }; + if (command.type === "queue.resume") return { userStarted: true }; + return startsQueueAfterCommit(command) ? { latestRunEnded: true } : {}; +} + function withoutEditHold(run: OrchestrationV2Run): OrchestrationV2Run { const { editHeldUntil: _editHeldUntil, ...rest } = run; return rest; @@ -2551,10 +2550,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (yield* cancelStaleQuestionWakes(projection)) { projection = yield* readCommandProjection(threadId); } - // The head is read past an edit hold so a failure below still holds the queue. + // An edit-held head with nothing to pass it is still read, so a failure below holds the queue. let storedQueuedRun = options?.queuedRunId === undefined - ? queueHead(projection) + ? (nextQueuedRun(projection) ?? queueHead(projection)) : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); @@ -2566,7 +2565,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now), ); projection = yield* readCommandProjection(threadId); - storedQueuedRun = queueHead(projection); + storedQueuedRun = nextQueuedRun(projection) ?? queueHead(projection); } // A wake that outlived some of its pull requests tells only the current ones. const currentWake = @@ -12414,14 +12413,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } // A command cannot steer, so an edit into one keeps it queued where it is. - if ( + const losesSteer = queuedRun.steerWhenReadyRunId !== undefined && isSlashCommand({ text: command.text, attachments: command.attachments ?? queuedMessage.attachments, - }) - ) { - const { steerWhenReadyRunId: _, ...queued } = queuedRun; + }); + if (losesSteer || queuedRun.editHeldUntil !== undefined) { + const { steerWhenReadyRunId, ...unsteered } = withoutEditHold(queuedRun); yield* emitEvent({ type: "run.updated", threadId: command.threadId, @@ -12429,7 +12428,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), providerInstanceId: queuedRun.providerInstanceId, occurredAt: now, - payload: queued, + payload: + losesSteer || steerWhenReadyRunId === undefined + ? unsteered + : { ...unsteered, steerWhenReadyRunId }, }); } // Thread deletion only cleans files the thread still references. @@ -12454,16 +12456,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ]); } - if (queuedRun.editHeldUntil !== undefined) { - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: queuedRun.id, - providerInstanceId: queuedRun.providerInstanceId, - occurredAt: now, - payload: withoutEditHold(queuedRun), - }); - } }); const editHoldExpiryEffect = ( @@ -16295,10 +16287,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if (startsQueueAfterCommit(command)) { yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, { - userStarted: command.type === "queue.resume" || command.type === "queued-run.start", - ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), - }), + startNextQueuedRun(command.threadId, queueStartAfterCommit(command)), ); } return { @@ -16582,10 +16571,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined) ) { yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, { - userStarted: command.type === "queue.resume" || command.type === "queued-run.start", - ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), - }), + startNextQueuedRun(command.threadId, queueStartAfterCommit(command)), ); } if ( diff --git a/apps/server/src/orchestration-v2/QueuedRunOrder.test.ts b/apps/server/src/orchestration-v2/QueuedRunOrder.test.ts index 9e12153771fab..9dcf09218063a 100644 --- a/apps/server/src/orchestration-v2/QueuedRunOrder.test.ts +++ b/apps/server/src/orchestration-v2/QueuedRunOrder.test.ts @@ -1,7 +1,7 @@ import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; -import { queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; +import { nextQueuedRun, queuedRunsInDeliveryOrder } from "./QueuedRunOrder.ts"; const at = (time: string) => DateTime.makeUnsafe(`2026-01-01T${time}Z`); const delegatedCompletion = { @@ -62,4 +62,30 @@ describe("queued run delivery order", () => { "run:later-completion", ]); }); + + it("passes a message being edited only for a subagent result", () => { + const run = (key: string, time: string, extra: object = {}) => ({ + id: `run:${key}`, + ordinal: 1, + requestedAt: at(time), + status: "queued", + userMessageId: `message:${key}`, + ...extra, + }); + const edited = run("edited", "10:00:00", { editHeldUntil: at("10:05:00") }); + const projection = (...runs: ReadonlyArray) => + ({ + messages: [ + { id: "message:edited" }, + { id: "message:later" }, + { id: "message:completion", delegatedCompletion }, + ], + runs, + }) as never; + + expect(nextQueuedRun(projection(edited, run("later", "10:01:00")))).toBeUndefined(); + expect(nextQueuedRun(projection(edited, run("completion", "10:02:00")))?.id).toBe( + "run:completion", + ); + }); }); diff --git a/apps/server/src/orchestration-v2/QueuedRunOrder.ts b/apps/server/src/orchestration-v2/QueuedRunOrder.ts index 1635f4ab51674..a707a82116716 100644 --- a/apps/server/src/orchestration-v2/QueuedRunOrder.ts +++ b/apps/server/src/orchestration-v2/QueuedRunOrder.ts @@ -49,3 +49,20 @@ export function queuedRunsInDeliveryOrder( } } } + +/** The first queued run no Stop or failure holds, whether or not it is being edited. */ +export function queueHead( + projection: Pick, +): OrchestrationV2Run | undefined { + return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); +} + +/** The run to start next. An edit holds the queue at its message, but subagent results still go out. */ +export function nextQueuedRun( + projection: Pick, +): OrchestrationV2Run | undefined { + const unheld = queuedRunsInDeliveryOrder(projection).filter((run) => run.queueHeld !== true); + const head = unheld[0]; + if (head?.editHeldUntil === undefined) return head; + return unheld.find((run) => isAutomaticCompletionRun(projection, run)); +} diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 27cd4a92fe0d7..ab865d3c46e2b 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1122,107 +1122,118 @@ it.effect.each( }), ); -it.effect("a deferred steer waits for its edit and then steers the edited text", () => - Effect.gen(function* () { - const { steered, layer, startFirstTurn, events } = yield* nextTurnSelectionHarness( - "deferred-steer-edit-hold", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const sink = yield* EventSink.EventSinkV2; - const threadId = yield* startFirstTurn; - const before = yield* orchestrator.getThreadProjection(threadId); - const run = before.runs[0]!; - const turn = before.providerTurns[0]!; - const now = yield* DateTime.now; - yield* sink.write({ - events: [ - { - id: EventId.make("setup-run"), - type: "run.updated", - threadId, - occurredAt: now, - payload: { ...run, status: "preparing" }, - }, - { - id: EventId.make("setup-turn"), - type: "provider-turn.updated", - threadId, - occurredAt: now, - payload: { ...turn, status: "pending" }, - }, - ], - }); - const steerAfterSetup = (text: string) => - Effect.gen(function* () { - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(text), - threadId, - messageId: MessageId.make(`message:${text}`), - text, - attachments: [], - deliveryIntent: "steer", - dispatchMode: { type: "queue_after_active" }, - createdBy: "user", - creationSource: "web", +// A command cannot steer, so a deferred steer saved as one stays queued instead. +it.effect.each(["edited before steering", "/context all"])( + "a deferred steer waits for its edit, then is saved as %s", + (savedText) => + Effect.gen(function* () { + const { steered, layer, startFirstTurn, events } = yield* nextTurnSelectionHarness( + `deferred-steer-edit-hold-${savedText.startsWith("/") ? "command" : "text"}`, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const sink = yield* EventSink.EventSinkV2; + const threadId = yield* startFirstTurn; + const before = yield* orchestrator.getThreadProjection(threadId); + const run = before.runs[0]!; + const turn = before.providerTurns[0]!; + const now = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make("setup-run"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...run, status: "preparing" }, + }, + { + id: EventId.make("setup-turn"), + type: "provider-turn.updated", + threadId, + occurredAt: now, + payload: { ...turn, status: "pending" }, + }, + ], + }); + const steerAfterSetup = (text: string) => + Effect.gen(function* () { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(text), + threadId, + messageId: MessageId.make(`message:${text}`), + text, + attachments: [], + deliveryIntent: "steer", + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + return (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), + )!; }); - return (yield* orchestrator.getThreadProjection(threadId)).runs.find( - (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), - )!; + const edited = yield* steerAfterSetup("being edited"); + const other = yield* steerAfterSetup("not edited"); + yield* orchestrator.dispatch({ + type: "queued-run.hold", + commandId: CommandId.make("hold-steer"), + threadId, + runId: edited.id, + held: true, }); - const edited = yield* steerAfterSetup("being edited"); - const other = yield* steerAfterSetup("not edited"); - yield* orchestrator.dispatch({ - type: "queued-run.hold", - commandId: CommandId.make("hold-steer"), - threadId, - runId: edited.id, - held: true, - }); - const otherPromoted = yield* orchestrator.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - event.payload.id === other.id && - event.payload.status === "cancelled", - ), - Stream.take(1), - Stream.runDrain, - Effect.forkScoped, - ); - yield* worker.drain(); - yield* sink.write({ - events: [ - { - id: EventId.make("ready-run"), - type: "run.updated", - threadId, - occurredAt: now, - payload: run, - }, - ], - }); - yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); - // Both steers wait on this turn, so the later one landing means the held one was passed over. - yield* Fiber.join(otherPromoted); - yield* worker.drain(); - assert.deepEqual(steered, ["not edited"]); + const otherPromoted = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + event.payload.id === other.id && + event.payload.status === "cancelled", + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + yield* worker.drain(); + yield* sink.write({ + events: [ + { + id: EventId.make("ready-run"), + type: "run.updated", + threadId, + occurredAt: now, + payload: run, + }, + ], + }); + yield* Queue.offer(events, { type: "provider_turn.updated", driver, providerTurn: turn }); + // Both steers wait on this turn, so the later one landing means the held one was passed over. + yield* Fiber.join(otherPromoted); + yield* worker.drain(); + assert.deepEqual(steered, ["not edited"]); - yield* orchestrator.dispatch({ - type: "queued-run.edit", - commandId: CommandId.make("save-steer"), - threadId, - runId: edited.id, - text: "edited before steering", - }); - yield* worker.drain(); - assert.deepEqual(steered, ["not edited", "edited before steering"]); - const after = yield* orchestrator.getThreadProjection(threadId); - assert.equal(after.runs.find((candidate) => candidate.id === edited.id)?.status, "cancelled"); - }).pipe(Effect.provide(layer)); - }), + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("save-steer"), + threadId, + runId: edited.id, + text: savedText, + }); + yield* worker.drain(); + const saved = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === edited.id, + ); + if (savedText.startsWith("/")) { + assert.deepEqual(steered, ["not edited"]); + assert.equal(saved?.status, "queued"); + assert.isUndefined(saved?.steerWhenReadyRunId); + } else { + assert.deepEqual(steered, ["not edited", savedText]); + assert.equal(saved?.status, "cancelled"); + } + }).pipe(Effect.provide(layer)); + }), ); it.effect("force sends multiple queued messages and can force send a requeued message again", () => diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 71036cd2672c2..93cd7782e8591 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -12,12 +12,14 @@ import { ProviderSessionId, ProviderThreadId, ProviderTurnId, + QUEUED_RUN_EDIT_HOLD_MS, RuntimeRequestId, ScheduledTaskId, ThreadId, TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; @@ -897,6 +899,69 @@ it.effect("the queue waits at a message being edited once it is next", () => }).pipe(Effect.provide(layerTest)), ); +// The run-end reaction that holds the queue has not run yet when the save lands. +it.effect("saving an edit right after a provider failure leaves the queue held", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:edit-hold-after-failure"); + yield* createWatchingThread(threadId, 42); + yield* send(threadId, "active", "start_immediately"); + yield* send(threadId, "edited", "queue_after_active"); + yield* holdForEdit(threadId, 1, "edit-after-failure:hold", true); + const [active, edited] = (yield* orchestrator.getThreadProjection(threadId)).runs; + const now = yield* DateTime.now; + yield* projections.apply({ + id: EventId.make("event:edit-after-failure:error"), + type: "turn-item.updated", + threadId, + runId: active!.id, + nodeId: active!.rootNodeId!, + occurredAt: now, + payload: { + id: TurnItemId.make("turn-item:edit-after-failure:error"), + type: "error", + threadId, + runId: active!.id, + nodeId: active!.rootNodeId, + providerThreadId: active!.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Provider failure", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "provider_error", + message: "Provider request failed with HTTP 502", + code: null, + retryable: null, + }, + }, + }); + yield* projections.apply({ + id: EventId.make("event:edit-after-failure:failed"), + type: "run.updated", + threadId, + runId: active!.id, + occurredAt: now, + payload: { ...active!, status: "failed", startedAt: now, completedAt: now }, + }); + + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("edit-after-failure:save"), + threadId, + runId: edited!.id, + text: "edited after the failure", + }); + assert.deepEqual((yield* threadState(threadId)).runs, ["failed", "queued:held"]); + }).pipe(Effect.provide(layerTest)), +); + it.effect.each(["expires", "is released"] as const)( "an edit hold starts the queue when it %s", (ending) => @@ -914,10 +979,11 @@ it.effect.each(["expires", "is released"] as const)( yield* holdForEdit(threadId, 1, `${threadId}:hold`, true); yield* completeRun(threadId, 0); - // Renewing keeps the hold past the first expiry. - yield* TestClock.adjust("3 minutes"); + // A renewal halfway through keeps the hold when the first deadline comes. + const halfHold = Duration.millis(QUEUED_RUN_EDIT_HOLD_MS / 2); + yield* TestClock.adjust(halfHold); yield* holdForEdit(threadId, 1, `${threadId}:renew`, true); - yield* TestClock.adjust("2 minutes"); + yield* TestClock.adjust(halfHold); yield* fireDueHoldTimer; assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "queued:editing"]); @@ -925,7 +991,7 @@ it.effect.each(["expires", "is released"] as const)( yield* holdForEdit(threadId, 1, `${threadId}:release`, false); assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "starting"]); } - yield* TestClock.adjust("3 minutes"); + yield* TestClock.adjust(halfHold); yield* fireDueHoldTimer; assert.deepEqual((yield* threadState(threadId)).runs, ["completed", "starting"]); const timers = yield* sql<{ readonly status: string }>` From 35790402270b0cf6ac3cbe6d34b628d75b3a40bb Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 03:43:45 -0500 Subject: [PATCH 4/7] fix(client-runtime): pause edit hold renewals during a save A renewal sent while a save is in flight runs after it and would hold the saved message again. --- packages/client-runtime/src/queuedRunEdit.test.ts | 11 +++++++++-- packages/client-runtime/src/queuedRunEdit.ts | 15 +++++++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/client-runtime/src/queuedRunEdit.test.ts b/packages/client-runtime/src/queuedRunEdit.test.ts index 36d922de4080c..07029ea49aebb 100644 --- a/packages/client-runtime/src/queuedRunEdit.test.ts +++ b/packages/client-runtime/src/queuedRunEdit.test.ts @@ -71,14 +71,21 @@ describe("makeQueuedRunEditStore", () => { store.end("env:thread"); expect(holds.slice(2)).toEqual(["run-1:release", "run-2:hold", "run-2:release"]); - // A save or a started run already ended the hold on the server. + // Renewals pause during a save and resume if it fails. holds.length = 0; begin(); + const finishSave = store.startSave("env:thread"); + vi.advanceTimersByTime(QUEUED_RUN_EDIT_HOLD_RENEW_MS * 2); + finishSave?.(false); + expect(holds).toEqual(["run-1:hold", "run-1:hold"]); + + // A save or a started run already ended the hold on the server. + holds.length = 0; store.startSave("env:thread")?.(true); begin(); registry.set(runs, []); vi.advanceTimersByTime(QUEUED_RUN_EDIT_HOLD_RENEW_MS * 2); - expect(holds).toEqual(["run-1:hold", "run-1:hold"]); + expect(holds).toEqual(["run-1:hold"]); } finally { vi.useRealTimers(); } diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.ts index 7c535e21a3e6c..c227585a73947 100644 --- a/packages/client-runtime/src/queuedRunEdit.ts +++ b/packages/client-runtime/src/queuedRunEdit.ts @@ -97,7 +97,7 @@ export type HoldQueuedRun = (held: boolean) => void; interface EditHold { readonly runId: RunId; readonly hold: HoldQueuedRun; - readonly renew: ReturnType; + renew: ReturnType | null; } /** @@ -133,11 +133,19 @@ export function makeQueuedRunEditStore(opti }); }; + // A renewal sent during a save would run after it and hold the saved message again. + const pauseHold = (threadKey: string) => { + const current = holds.get(threadKey); + if (current?.renew == null) return; + clearInterval(current.renew); + current.renew = null; + }; + // The server drops the hold itself once the run starts or a save lands. const stopHold = (threadKey: string, release: boolean) => { const current = holds.get(threadKey); if (current === undefined) return; - clearInterval(current.renew); + if (current.renew !== null) clearInterval(current.renew); holds.delete(threadKey); if (release) current.hold(false); }; @@ -243,6 +251,7 @@ export function makeQueuedRunEditStore(opti if (watch === undefined || threadKey in registry.get(savingAtom)) return null; setSaving(threadKey, true); unsubscribe(watch); + pauseHold(threadKey); let settled = false; return (succeeded) => { if (!settled) { @@ -256,6 +265,8 @@ export function makeQueuedRunEditStore(opti write(threadKey, null); return true; } + const paused = holds.get(threadKey); + if (paused !== undefined) startHold(threadKey, paused.runId, paused.hold); subscribe(threadKey, watch); return watches.get(threadKey) === watch; }; From 7aa929fa59213c01facb401d32e3fd4092e9f6e8 Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 03:56:38 -0500 Subject: [PATCH 5/7] refactor(server): drop a failure check the edit-triggered starts already make Starts that an edit triggers check the latest turn for a failure, so the queue no longer needs to read past an edit hold at turn end to apply it. Also drops comments that restated the code. --- .../src/orchestration-v2/Orchestrator.ts | 10 +- .../src/orchestration-v2/QueuedRunOrder.ts | 1 - .../SteeringCompletion.integration.test.ts | 1 - .../src/orchestration-v2/ThreadStop.test.ts | 4 +- .../src/orchestration-v2/runtimeLayer.test.ts | 112 ------------------ .../client-runtime/src/queuedRunEdit.test.ts | 2 - packages/client-runtime/src/queuedRunEdit.ts | 6 +- 7 files changed, 4 insertions(+), 132 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8fb5a60dc60e0..71ddc6009d26e 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1042,7 +1042,6 @@ function worktreeSetupPending( ); } -// Each can change which queued message is next, or end the edit the queue waits on. const QUEUE_CHANGING_COMMAND_TYPES = [ "queue.resume", "queued-run.start", @@ -2550,10 +2549,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (yield* cancelStaleQuestionWakes(projection)) { projection = yield* readCommandProjection(threadId); } - // An edit-held head with nothing to pass it is still read, so a failure below holds the queue. let storedQueuedRun = options?.queuedRunId === undefined - ? (nextQueuedRun(projection) ?? queueHead(projection)) + ? nextQueuedRun(projection) : projection.runs.find( (run) => run.id === options.queuedRunId && run.status === "queued", ); @@ -2565,7 +2563,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio queuedRunCancellationEvents(projection, storedQueuedRun, yield* DateTime.now), ); projection = yield* readCommandProjection(threadId); - storedQueuedRun = nextQueuedRun(projection) ?? queueHead(projection); + storedQueuedRun = nextQueuedRun(projection); } // A wake that outlived some of its pull requests tells only the current ones. const currentWake = @@ -2680,9 +2678,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); return wakes.length > 0; } - if (options?.queuedRunId === undefined && storedQueuedRun.editHeldUntil !== undefined) { - return; - } // Move queued ordinals after runs that started while they waited to preserve transcript and checkpoint order. // Started runs have prompts; cancelled queued messages do not. const newerRunIds = projection.runs @@ -12481,7 +12476,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const emitEvent = emit(events, command); if (!command.held) { - // The message may have started or been cancelled while the edit was open. const run = projection.runs.find((candidate) => candidate.id === command.runId); if (run?.status !== "queued" || run.editHeldUntil === undefined) return; yield* emitEvent({ diff --git a/apps/server/src/orchestration-v2/QueuedRunOrder.ts b/apps/server/src/orchestration-v2/QueuedRunOrder.ts index a707a82116716..0c1bf50cc221a 100644 --- a/apps/server/src/orchestration-v2/QueuedRunOrder.ts +++ b/apps/server/src/orchestration-v2/QueuedRunOrder.ts @@ -50,7 +50,6 @@ export function queuedRunsInDeliveryOrder( } } -/** The first queued run no Stop or failure holds, whether or not it is being edited. */ export function queueHead( projection: Pick, ): OrchestrationV2Run | undefined { diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index ab865d3c46e2b..711c4fb44c0b9 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1122,7 +1122,6 @@ it.effect.each( }), ); -// A command cannot steer, so a deferred steer saved as one stays queued instead. it.effect.each(["edited before steering", "/context all"])( "a deferred steer waits for its edit, then is saved as %s", (savedText) => diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts index 93cd7782e8591..cf05ba3ef9a28 100644 --- a/apps/server/src/orchestration-v2/ThreadStop.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts @@ -899,8 +899,7 @@ it.effect("the queue waits at a message being edited once it is next", () => }).pipe(Effect.provide(layerTest)), ); -// The run-end reaction that holds the queue has not run yet when the save lands. -it.effect("saving an edit right after a provider failure leaves the queue held", () => +it.effect("saving an edit after a provider failure leaves the queue held", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -979,7 +978,6 @@ it.effect.each(["expires", "is released"] as const)( yield* holdForEdit(threadId, 1, `${threadId}:hold`, true); yield* completeRun(threadId, 0); - // A renewal halfway through keeps the hold when the first deadline comes. const halfHold = Duration.millis(QUEUED_RUN_EDIT_HOLD_MS / 2); yield* TestClock.adjust(halfHold); yield* holdForEdit(threadId, 1, `${threadId}:renew`, true); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8c806441b3d8a..b5072355659ef 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -11585,118 +11585,6 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); - it.effect("a provider failure during an edit holds the queue past the save", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const eventSink = yield* EventSink.EventSinkV2; - const threadId = ThreadId.make("queue-hold-edit-after-failure"); - const send = (key: string, dispatchMode: "start_immediately" | "queue_after_active") => - orchestrator.dispatch({ - type: "message.dispatch", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`${threadId}:message:${key}`), - threadId, - messageId: MessageId.make(`${threadId}:${key}`), - text: key, - attachments: [], - modelSelection, - dispatchMode: { type: dispatchMode }, - }); - yield* orchestrator.dispatch({ - type: "thread.create", - createdBy: "user", - creationSource: "web", - commandId: CommandId.make(`${threadId}:create`), - threadId, - projectId: ProjectId.make(`${threadId}:project`), - title: "Edit behind a failed run", - modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: process.cwd(), - }); - yield* send("active", "start_immediately"); - yield* send("edited", "queue_after_active"); - const [active, edited] = (yield* orchestrator.getThreadProjection(threadId)).runs; - yield* orchestrator.dispatch({ - type: "queued-run.hold", - commandId: CommandId.make(`${threadId}:hold`), - threadId, - runId: edited!.id, - held: true, - }); - const afterSequence = yield* orchestrator.getThreadEventSequence(threadId); - const failureHold = yield* eventSink.stream({ threadId, afterSequence }).pipe( - Stream.filter( - (stored) => - stored.event.type === "run.updated" && - stored.event.payload.id === edited!.id && - stored.event.payload.queueHeld === true, - ), - Stream.runHead, - Effect.forkScoped, - ); - const now = yield* DateTime.now; - yield* eventSink.write({ - events: [ - { - id: EventId.make(`${threadId}:active:error`), - type: "turn-item.updated", - threadId, - runId: active!.id, - nodeId: active!.rootNodeId!, - providerInstanceId: active!.providerInstanceId, - occurredAt: now, - payload: { - id: TurnItemId.make(`${threadId}:active:error`), - type: "error", - threadId, - runId: active!.id, - nodeId: active!.rootNodeId, - providerThreadId: active!.providerThreadId, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 2, - status: "failed", - title: "Provider failure", - startedAt: now, - completedAt: now, - updatedAt: now, - failure: { - class: "provider_error", - message: "Provider request failed with HTTP 502", - code: null, - retryable: null, - }, - }, - }, - { - id: EventId.make(`${threadId}:active:failed`), - type: "run.updated", - threadId, - runId: active!.id, - providerInstanceId: active!.providerInstanceId, - occurredAt: now, - payload: { ...active!, status: "failed", startedAt: now, completedAt: now }, - }, - ], - }); - assert.isTrue(Option.isSome(yield* Fiber.join(failureHold))); - yield* orchestrator.dispatch({ - type: "queued-run.edit", - commandId: CommandId.make(`${threadId}:save`), - threadId, - runId: edited!.id, - text: "edited", - }); - const saved = (yield* orchestrator.getThreadProjection(threadId)).runs[1]!; - assert.deepInclude(saved, { status: "queued", queueHeld: true }); - }), - ); - it.effect("edits and removes queued runs", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/packages/client-runtime/src/queuedRunEdit.test.ts b/packages/client-runtime/src/queuedRunEdit.test.ts index 07029ea49aebb..49dd388097a7b 100644 --- a/packages/client-runtime/src/queuedRunEdit.test.ts +++ b/packages/client-runtime/src/queuedRunEdit.test.ts @@ -64,14 +64,12 @@ describe("makeQueuedRunEditStore", () => { vi.advanceTimersByTime(QUEUED_RUN_EDIT_HOLD_RENEW_MS); expect(holds).toEqual(["run-1:hold", "run-1:hold"]); - // Switching messages releases the first; cancelling releases the second. const other = RunId.make("run-2"); registry.set(runs, [...queued(), { id: other, status: "queued" }]); begin(other); store.end("env:thread"); expect(holds.slice(2)).toEqual(["run-1:release", "run-2:hold", "run-2:release"]); - // Renewals pause during a save and resume if it fails. holds.length = 0; begin(); const finishSave = store.startSave("env:thread"); diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.ts index c227585a73947..243e7ea66bb91 100644 --- a/packages/client-runtime/src/queuedRunEdit.ts +++ b/packages/client-runtime/src/queuedRunEdit.ts @@ -87,11 +87,7 @@ interface ExitWatch { cancel: (() => void) | null; } -/** - * Asks the server to hold (true) or release (false) the queue at the edited - * message. Failures are ignored: an older server, or a run that already - * started, leaves the edit unheld and the exit watch recovers it. - */ +/** Failures are ignored: an older server, or a run that already started, leaves the edit unheld. */ export type HoldQueuedRun = (held: boolean) => void; interface EditHold { From e6e2c97d0d98056b59cd96390db59a538082a1a6 Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 15:52:25 -0500 Subject: [PATCH 6/7] perf(server): edit holds write less and share the deferred-steer delivery A renewal writes only once less than half the hold remains, so clients get one run update a minute instead of two. Taking a hold no longer tries to start the queue, and a timer that finds its hold renewed skips the post-commit work. Hold commands read only their run. Steers that waited for an edit go through the same promotion as other deferred steers, and a replayed command now delivers them too. --- .../src/orchestration-v2/EffectOutbox.ts | 10 +- .../src/orchestration-v2/Orchestrator.ts | 229 +++++++++--------- 2 files changed, 124 insertions(+), 115 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 4a7502a85d81e..77e5432a92029 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -146,6 +146,12 @@ export const OrchestrationEffectRequestV2 = Schema.Union([ ]); export type OrchestrationEffectRequestV2 = typeof OrchestrationEffectRequestV2.Type; +// These wait only on their own kind, so one due in minutes cannot hold back a thread's turns. +const OWN_LANE_EFFECT_TYPES = [ + "thread-title.generate", + "queued-run.hold.expire", +] as const satisfies ReadonlyArray; + export const REPLAY_SAFE_EFFECT_TYPES_AFTER_PROCESS_LOSS = [ "provider-runtime.continue", "provider-session.detach", @@ -347,7 +353,7 @@ export const layer: Layer.Layer = La ).pipe(Effect.asVoid); const effectLane = (alias: "candidate" | "active") => sql.literal( - `CASE WHEN ${alias}.effect_type IN ('thread-title.generate', 'queued-run.hold.expire') THEN ${alias}.effect_type ELSE '' END`, + `CASE WHEN ${alias}.effect_type IN (${OWN_LANE_EFFECT_TYPES.map((type) => `'${type}'`).join(", ")}) THEN ${alias}.effect_type ELSE '' END`, ); // Retry backoff must block later effects so turns cannot race a pending rollback. const claimableCandidatePredicate = ( @@ -378,8 +384,6 @@ export const layer: Layer.Layer = La } ) ) - -- Titles and edit-hold timers wait only on their own kind: a timer due in - -- minutes would otherwise hold back the thread's turns until it fires. AND ${effectLane("candidate")} = ${effectLane("active")} ) AND ${ diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 71ddc6009d26e..41374e2e50aa4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1065,7 +1065,7 @@ function startsQueueAfterCommit( function queueStartAfterCommit(command: OrchestrationV2ServerCommand) { if (command.type === "queued-run.start") return { userStarted: true, queuedRunId: command.runId }; if (command.type === "queue.resume") return { userStarted: true }; - return startsQueueAfterCommit(command) ? { latestRunEnded: true } : {}; + return { latestRunEnded: true }; } function withoutEditHold(run: OrchestrationV2Run): OrchestrationV2Run { @@ -12415,19 +12415,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio attachments: command.attachments ?? queuedMessage.attachments, }); if (losesSteer || queuedRun.editHeldUntil !== undefined) { - const { steerWhenReadyRunId, ...unsteered } = withoutEditHold(queuedRun); - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: queuedRun.id, - ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), - providerInstanceId: queuedRun.providerInstanceId, - occurredAt: now, - payload: - losesSteer || steerWhenReadyRunId === undefined - ? unsteered - : { ...unsteered, steerWhenReadyRunId }, - }); + const unheld = withoutEditHold(queuedRun); + const { steerWhenReadyRunId: _, ...unsteered } = unheld; + yield* emitRunUpdate(events, command, losesSteer ? unsteered : unheld, now); } // Thread deletion only cleans files the thread still references. const keptAttachmentIds = new Set( @@ -12465,39 +12455,53 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio availableAt: heldUntil, }); + const emitRunUpdate = ( + events: Ref.Ref>, + command: OrchestrationV2ServerCommand & { readonly threadId: ThreadId }, + run: OrchestrationV2Run, + occurredAt: DateTime.Utc, + ) => + emit( + events, + command, + )({ + type: "run.updated", + threadId: command.threadId, + runId: run.id, + ...(run.rootNodeId === null ? {} : { nodeId: run.rootNodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt, + payload: run, + }); + const dispatchQueuedRunHold = Effect.fn("Orchestrator.dispatchQueuedRunHold")(function* ( command: Extract, events: Ref.Ref>, effects: Ref.Ref>, ) { const projection = yield* loadProjectionForCommand(command, ["runs", "messages"], { + runIds: [command.runId], + messageRunIds: [command.runId], messageRoles: ["user"], }); const now = yield* DateTime.now; - const emitEvent = emit(events, command); if (!command.held) { const run = projection.runs.find((candidate) => candidate.id === command.runId); if (run?.status !== "queued" || run.editHeldUntil === undefined) return; - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: run.id, - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: withoutEditHold(run), - }); + yield* emitRunUpdate(events, command, withoutEditHold(run), now); return; } const { queuedRun } = yield* requireEditableQueuedRun(command, projection); + // Renewals arrive every 30s; writing only past half the hold halves the events clients receive. + if ( + queuedRun.editHeldUntil !== undefined && + DateTime.toEpochMillis(queuedRun.editHeldUntil) - DateTime.toEpochMillis(now) > + QUEUED_RUN_EDIT_HOLD_MS / 2 + ) { + return; + } const heldUntil = DateTime.add(now, { milliseconds: QUEUED_RUN_EDIT_HOLD_MS }); - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: queuedRun.id, - providerInstanceId: queuedRun.providerInstanceId, - occurredAt: now, - payload: { ...queuedRun, editHeldUntil: heldUntil }, - }); + yield* emitRunUpdate(events, command, { ...queuedRun, editHeldUntil: heldUntil }, now); // A renewal only moves the deadline; the pending timer follows it when it fires. if (queuedRun.editHeldUntil === undefined) { yield* Ref.update(effects, (existing) => [ @@ -12513,7 +12517,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events: Ref.Ref>, effects: Ref.Ref>, ) { - const projection = yield* loadProjectionForCommand(command, ["runs"]); + const projection = yield* loadProjectionForCommand(command, ["runs"], { + runIds: [command.runId], + }); const run = projection.runs.find((candidate) => candidate.id === command.runId); if (run?.status !== "queued" || run.editHeldUntil === undefined) return; if (DateTime.isGreaterThan(run.editHeldUntil, command.heldUntil)) { @@ -12524,17 +12530,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ]); return; } - yield* emit( - events, - command, - )({ - type: "run.updated", - threadId: command.threadId, - runId: run.id, - providerInstanceId: run.providerInstanceId, - occurredAt: yield* DateTime.now, - payload: withoutEditHold(run), - }); + yield* emitRunUpdate(events, command, withoutEditHold(run), yield* DateTime.now); }, ); @@ -16279,11 +16275,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); - if (startsQueueAfterCommit(command)) { - yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, queueStartAfterCommit(command)), - ); - } + yield* afterQueueChange(command, storedEvents.length > 0); return { sequence: receipt.resultSequence, storedEvents, @@ -16291,29 +16283,77 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies OrchestratorV2DispatchResult; }); - // A deferred steer skips its turn's start while the message is being edited. - const deliverSteerAfterEdit = Effect.fn("Orchestrator.deliverSteerAfterEdit")( - function* (threadId: ThreadId, runId: RunId, commandId: CommandId) { - const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"], { - runStatuses: ["queued", "running"], - }); - const queued = runs.find((run) => run.id === runId); - if ( - queued?.status !== "queued" || - queued.editHeldUntil !== undefined || - queued.steerWhenReadyRunId === undefined - ) { - return; - } - const target = runs.find((run) => run.id === queued.steerWhenReadyRunId); - if (target?.status !== "running") return; + /** Promotes the steers waiting on `targetRunId`, except those being edited. */ + const promoteReadySteers = Effect.fn("Orchestrator.promoteReadySteers")(function* ( + threadId: ThreadId, + runs: ReadonlyArray, + targetRunId: RunId, + commandIdSuffix: string, + ) { + const pending = runs + .filter( + (queued) => + queued.status === "queued" && + queued.steerWhenReadyRunId === targetRunId && + queued.editHeldUntil === undefined, + ) + .toSorted( + (left, right) => + (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal), + ); + for (const queued of pending) { yield* dispatchWithReceiptEffect({ type: "queued-message.promote-to-steer", - commandId: CommandId.make(`command:deferred-steer:${queued.id}:${commandId}`), + commandId: CommandId.make(`command:deferred-steer:${queued.id}:${commandIdSuffix}`), threadId, queuedRunId: queued.id, - targetRunId: target.id, + targetRunId, + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to deliver a deferred steer", { + threadId, + runId: queued.id, + cause, + }), + ), + ); + } + }); + + /** Starts the queue after a command that changed it, and delivers a steer whose edit ended. */ + const afterQueueChange = Effect.fn("Orchestrator.afterQueueChange")(function* ( + command: OrchestrationV2ServerCommand, + producedEvents: boolean, + ) { + if (!startsQueueAfterCommit(command)) return; + // Taking a hold never frees the queue, and a renewal or an ended hold changes nothing. + if (command.type === "queued-run.hold" || command.type === "queued-run.hold.expire") { + if (!producedEvents || (command.type === "queued-run.hold" && command.held)) return; + } + yield* mapDispatchError(command)( + startNextQueuedRun(command.threadId, queueStartAfterCommit(command)), + ); + if ( + command.type !== "queued-run.edit" && + command.type !== "queued-run.hold" && + command.type !== "queued-run.hold.expire" + ) { + return; + } + yield* deliverSteerAfterEdit(command.threadId, command.runId, command.commandId); + }); + + // A deferred steer skips its turn's start while it is being edited. + const deliverSteerAfterEdit = Effect.fn("Orchestrator.deliverSteerAfterEdit")( + function* (threadId: ThreadId, runId: RunId, commandId: CommandId) { + const { runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"], { + runStatuses: ["queued", "running"], }); + const edited = runs.find((run) => run.id === runId); + const target = runs.find( + (run) => run.id === edited?.steerWhenReadyRunId && run.status === "running", + ); + if (target !== undefined) yield* promoteReadySteers(threadId, runs, target.id, commandId); }, Effect.catchCause((cause) => Effect.logWarning("Failed to deliver a steer after its edit", { cause }), @@ -16393,9 +16433,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.type === "subagent.stop" || // Closing a share again, or after it ended, is not an error. command.type === "thread.guest-share.close" || - // Nor is ending an edit hold that already ended, or a timer that finds it renewed. + // Nor is an early renewal, ending a hold that already ended, or a timer that finds it renewed. command.type === "queued-run.hold.expire" || - (command.type === "queued-run.hold" && !command.held) || + command.type === "queued-run.hold" || (command.type === "thread.delete" && command.onlyIfUnused === true), (_planned) => new OrchestratorDispatchError({ @@ -16560,21 +16600,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandThreadId: commandThreadId(command), }); } - if ( - startsQueueAfterCommit(command) || - (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined) - ) { - yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, queueStartAfterCommit(command)), - ); - } - if ( - command.type === "queued-run.edit" || - command.type === "queued-run.hold.expire" || - (command.type === "queued-run.hold" && !command.held) - ) { - yield* deliverSteerAfterEdit(command.threadId, command.runId, command.commandId); + if (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined) { + yield* mapDispatchError(command)(startNextQueuedRun(command.threadId)); } + yield* afterQueueChange(command, committed.storedEvents.length > 0); if ( command.type === "notification.delivery.accept" || // A steer restart that settled a wake can reserve the next one for its siblings. @@ -16855,36 +16884,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio candidate.activeAttemptId === turn.runAttemptId && candidate.status === "running", ); if (run === undefined) return; - const pending = projection.runs - .filter( - (queued) => - queued.status === "queued" && - queued.steerWhenReadyRunId === run.id && - queued.editHeldUntil === undefined, - ) - .toSorted( - (left, right) => - (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal), - ); - for (const queued of pending) { - yield* dispatchWithReceiptEffect({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make( - `command:deferred-steer:${queued.id}:${run.id}:${turn.runAttemptId}`, - ), - threadId, - queuedRunId: queued.id, - targetRunId: run.id, - }).pipe( - Effect.catchCause((cause) => - Effect.logWarning("Failed to deliver a deferred steer", { - threadId, - runId: queued.id, - cause, - }), - ), - ); - } + yield* promoteReadySteers( + threadId, + projection.runs, + run.id, + `${run.id}:${turn.runAttemptId}`, + ); }, (effect, stored) => threadDispatch.withLock(stored.event.threadId, effect), Effect.catchCause((cause) => From 0d6e883a04d777a0a47d8ec42dfc56961f2b25c6 Mon Sep 17 00:00:00 2001 From: jagrat7 Date: Mon, 23 Nov 2026 15:52:37 -0500 Subject: [PATCH 7/7] refactor(client-runtime): keep an edit's hold on its exit watch The hold, its renewal, and the watch always started and stopped together, so they now live in one record. --- .../chat/useQueuedRunEdit.browser.test.tsx | 9 ++- packages/client-runtime/src/queuedRunEdit.ts | 65 +++++-------------- 2 files changed, 20 insertions(+), 54 deletions(-) diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index 81b55058b1022..06b08f874a7de 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -53,11 +53,10 @@ const mocks = await vi.hoisted(async () => { vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => - command === mocks.promoteCommand - ? mocks.promoteQueuedRun - : command === mocks.holdCommand - ? mocks.holdQueuedRun - : mocks.editQueuedRun, + new Map([ + [mocks.promoteCommand, mocks.promoteQueuedRun], + [mocks.holdCommand, mocks.holdQueuedRun], + ]).get(command) ?? mocks.editQueuedRun, })); vi.mock("../../hooks/useSettings", () => ({ diff --git a/packages/client-runtime/src/queuedRunEdit.ts b/packages/client-runtime/src/queuedRunEdit.ts index 243e7ea66bb91..a77ef518156a9 100644 --- a/packages/client-runtime/src/queuedRunEdit.ts +++ b/packages/client-runtime/src/queuedRunEdit.ts @@ -80,19 +80,15 @@ export function queuedRunEditBlockedReason( : null; } -interface ExitWatch { - readonly runs: QueuedRunsAtom; - readonly runId: RunId; - readonly onRunLeftQueue: (threadKey: string, edit: E) => void; - cancel: (() => void) | null; -} - /** Failures are ignored: an older server, or a run that already started, leaves the edit unheld. */ export type HoldQueuedRun = (held: boolean) => void; -interface EditHold { +interface ExitWatch { + readonly runs: QueuedRunsAtom; readonly runId: RunId; + readonly onRunLeftQueue: (threadKey: string, edit: E) => void; readonly hold: HoldQueuedRun; + cancel: (() => void) | null; renew: ReturnType | null; } @@ -118,33 +114,6 @@ export function makeQueuedRunEditStore(opti ); // Each begin creates a new watch, so the watch is the edit's identity. const watches = new Map>(); - const holds = new Map(); - - const startHold = (threadKey: string, runId: RunId, hold: HoldQueuedRun) => { - hold(true); - holds.set(threadKey, { - runId, - hold, - renew: setInterval(() => hold(true), QUEUED_RUN_EDIT_HOLD_RENEW_MS), - }); - }; - - // A renewal sent during a save would run after it and hold the saved message again. - const pauseHold = (threadKey: string) => { - const current = holds.get(threadKey); - if (current?.renew == null) return; - clearInterval(current.renew); - current.renew = null; - }; - - // The server drops the hold itself once the run starts or a save lands. - const stopHold = (threadKey: string, release: boolean) => { - const current = holds.get(threadKey); - if (current === undefined) return; - if (current.renew !== null) clearInterval(current.renew); - holds.delete(threadKey); - if (release) current.hold(false); - }; const setSaving = (threadKey: string, saving: boolean) => { const current = registry.get(savingAtom); @@ -170,18 +139,22 @@ export function makeQueuedRunEditStore(opti registry.set(atom, { ...current, [threadKey]: edit }); }; + // Renewal pauses with the watch: one sent during a save would land after it and hold the saved message again. const unsubscribe = (watch: ExitWatch) => { watch.cancel?.(); watch.cancel = null; + if (watch.renew !== null) clearInterval(watch.renew); + watch.renew = null; }; const subscribe = (threadKey: string, watch: ExitWatch) => { + watch.hold(true); + watch.renew = setInterval(() => watch.hold(true), QUEUED_RUN_EDIT_HOLD_RENEW_MS); const check = (runs: ReadonlyArray | null) => { if (watches.get(threadKey) !== watch || watch.cancel === null) return; if (!runLeftQueue(runs, watch.runId)) return; unsubscribe(watch); watches.delete(threadKey); - stopHold(threadKey, false); const edit = get(threadKey); if (edit === null || edit.runId !== watch.runId) return; write(threadKey, null); @@ -191,11 +164,13 @@ export function makeQueuedRunEditStore(opti check(registry.get(watch.runs)); }; - const stopWatch = (threadKey: string) => { + // The server drops the hold itself once the run starts or a save lands, so only an abandoned edit releases it. + const stopWatch = (threadKey: string, release: boolean) => { const watch = watches.get(threadKey); if (watch === undefined) return; unsubscribe(watch); watches.delete(threadKey); + if (release) watch.hold(false); }; return { @@ -218,13 +193,10 @@ export function makeQueuedRunEditStore(opti readonly hold: HoldQueuedRun; }, ) { - stopWatch(threadKey); - stopHold(threadKey, holds.get(threadKey)?.runId !== edit.runId); + stopWatch(threadKey, watches.get(threadKey)?.runId !== edit.runId); write(threadKey, edit); - const { hold, ...exit } = watch; - const next: ExitWatch = { ...exit, runId: edit.runId, cancel: null }; + const next: ExitWatch = { ...watch, runId: edit.runId, cancel: null, renew: null }; watches.set(threadKey, next); - startHold(threadKey, edit.runId, hold); subscribe(threadKey, next); }, update(threadKey: string, f: (edit: E) => E) { @@ -232,8 +204,7 @@ export function makeQueuedRunEditStore(opti if (edit !== null) write(threadKey, f(edit)); }, end(threadKey: string) { - stopWatch(threadKey); - stopHold(threadKey, true); + stopWatch(threadKey, true); write(threadKey, null); }, /** @@ -247,7 +218,6 @@ export function makeQueuedRunEditStore(opti if (watch === undefined || threadKey in registry.get(savingAtom)) return null; setSaving(threadKey, true); unsubscribe(watch); - pauseHold(threadKey); let settled = false; return (succeeded) => { if (!settled) { @@ -256,13 +226,10 @@ export function makeQueuedRunEditStore(opti } if (watches.get(threadKey) !== watch) return false; if (succeeded) { - stopWatch(threadKey); - stopHold(threadKey, false); + stopWatch(threadKey, false); write(threadKey, null); return true; } - const paused = holds.get(threadKey); - if (paused !== undefined) startHold(threadKey, paused.runId, paused.hold); subscribe(threadKey, watch); return watches.get(threadKey) === watch; };