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/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index b495293bc2228..77e5432a92029 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -138,9 +138,20 @@ 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; +// 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", @@ -152,6 +163,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 +351,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 (${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 = ( availableBefore?: string, @@ -368,17 +384,7 @@ 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' - ) - ) + 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..41374e2e50aa4 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, @@ -202,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, @@ -692,6 +698,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,10 +1042,35 @@ function worktreeSetupPending( ); } -function nextQueuedRun( - projection: Pick, -): OrchestrationV2Run | undefined { - return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); +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); +} + +// 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 { latestRunEnded: true }; +} + +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 @@ -2562,7 +2595,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); const modelSelection = queuedRunModelSelection(projection, storedQueuedRun); const queuedRun = { - ...storedQueuedRun, + ...withoutEditHold(storedQueuedRun), modelSelection, providerInstanceId: modelSelection.instanceId, }; @@ -7908,7 +7941,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 +12285,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 +12328,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 }, @@ -12358,23 +12408,16 @@ 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; - yield* emitEvent({ - type: "run.updated", - threadId: command.threadId, - runId: queuedRun.id, - ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), - providerInstanceId: queuedRun.providerInstanceId, - occurredAt: now, - payload: queued, }); + if (losesSteer || queuedRun.editHeldUntil !== undefined) { + 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( @@ -12400,13 +12443,104 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + 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 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; + if (!command.held) { + const run = projection.runs.find((candidate) => candidate.id === command.runId); + if (run?.status !== "queued" || run.editHeldUntil === undefined) return; + 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* 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) => [ + ...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"], { + 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)) { + const renewedUntil = run.editHeldUntil; + yield* Ref.update(effects, (existing) => [ + ...existing, + editHoldExpiryEffect(command, run.id, renewedUntil), + ]); + return; + } + yield* emitRunUpdate(events, command, withoutEditHold(run), yield* DateTime.now); + }, + ); + 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 +16170,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,14 +16275,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); - if (command.type === "queue.resume" || command.type === "queued-run.start") { - yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, { - userStarted: true, - ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), - }), - ); - } + yield* afterQueueChange(command, storedEvents.length > 0); return { sequence: receipt.resultSequence, storedEvents, @@ -16150,6 +16283,83 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies OrchestratorV2DispatchResult; }); + /** 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}:${commandIdSuffix}`), + threadId, + queuedRunId: queued.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 }), + ), + ); + /** `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 +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 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.type === "thread.delete" && command.onlyIfUnused === true), (_planned) => new OrchestratorDispatchError({ @@ -16387,18 +16600,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio commandThreadId: commandThreadId(command), }); } - if ( - command.type === "queue.resume" || - command.type === "queued-run.start" || - (command.type === "thread.runtime-mode.set" && runtimeModeCeiling !== undefined) - ) { - yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, { - userStarted: command.type !== "thread.runtime-mode.set", - ...(command.type === "queued-run.start" ? { queuedRunId: command.runId } : {}), - }), - ); + 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. @@ -16679,33 +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, - ) - .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) => 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..0c1bf50cc221a 100644 --- a/apps/server/src/orchestration-v2/QueuedRunOrder.ts +++ b/apps/server/src/orchestration-v2/QueuedRunOrder.ts @@ -49,3 +49,19 @@ export function queuedRunsInDeliveryOrder( } } } + +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 04257d91bc9a7..711c4fb44c0b9 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1122,6 +1122,119 @@ it.effect.each( }), ); +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}`), + )!; + }); + 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: 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", () => 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..cf05ba3ef9a28 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"; @@ -158,7 +160,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 +805,203 @@ 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("saving an edit 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) => + 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); + + const halfHold = Duration.millis(QUEUED_RUN_EDIT_HOLD_MS / 2); + yield* TestClock.adjust(halfHold); + yield* holdForEdit(threadId, 1, `${threadId}:renew`, true); + yield* TestClock.adjust(halfHold); + 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(halfHold); + 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/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 { 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,10 @@ const mocks = await vi.hoisted(async () => { vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => - command === mocks.promoteCommand ? mocks.promoteQueuedRun : mocks.editQueuedRun, + new Map([ + [mocks.promoteCommand, mocks.promoteQueuedRun], + [mocks.holdCommand, mocks.holdQueuedRun], + ]).get(command) ?? mocks.editQueuedRun, })); vi.mock("../../hooks/useSettings", () => ({ @@ -68,6 +73,7 @@ vi.mock("../../state/threads", async () => { snapshotAtom: () => Atom.make(null), editQueuedRun: {}, promoteQueuedRun: mocks.promoteCommand, + holdQueuedRun: mocks.holdCommand, }, environmentThreadDetails: { statusAtom: () => Atom.make("ready"), @@ -178,6 +184,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..49dd388097a7b 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,39 @@ 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"]); + + 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"]); + + 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"]); + } 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 +227,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 +279,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..a77ef518156a9 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 { @@ -79,11 +80,16 @@ export function queuedRunEditBlockedReason( : null; } +/** Failures are ignored: an older server, or a run that already started, leaves the edit unheld. */ +export type HoldQueuedRun = (held: boolean) => void; + interface ExitWatch { readonly runs: QueuedRunsAtom; readonly runId: RunId; readonly onRunLeftQueue: (threadKey: string, edit: E) => void; + readonly hold: HoldQueuedRun; cancel: (() => void) | null; + renew: ReturnType | null; } /** @@ -133,12 +139,17 @@ 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; @@ -153,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 { @@ -166,9 +179,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,11 +190,12 @@ export function makeQueuedRunEditStore(opti watch: { readonly runs: QueuedRunsAtom; readonly onRunLeftQueue: (threadKey: string, edit: E) => void; + readonly hold: HoldQueuedRun; }, ) { - stopWatch(threadKey); + stopWatch(threadKey, watches.get(threadKey)?.runId !== edit.runId); write(threadKey, edit); - const next: ExitWatch = { ...watch, runId: edit.runId, cancel: null }; + const next: ExitWatch = { ...watch, runId: edit.runId, cancel: null, renew: null }; watches.set(threadKey, next); subscribe(threadKey, next); }, @@ -189,7 +204,7 @@ export function makeQueuedRunEditStore(opti if (edit !== null) write(threadKey, f(edit)); }, end(threadKey: string) { - stopWatch(threadKey); + stopWatch(threadKey, true); write(threadKey, null); }, /** @@ -211,7 +226,7 @@ export function makeQueuedRunEditStore(opti } if (watches.get(threadKey) !== watch) return false; if (succeeded) { - stopWatch(threadKey); + stopWatch(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, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 8b05c12e17871..ba45fd26b58aa 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -804,6 +804,8 @@ export const OrchestrationV2Run = Schema.Struct({ queuePosition: Schema.optional(Schema.NullOr(PositiveInt)), queueHeld: Schema.optional(Schema.Boolean), steerWhenReadyRunId: Schema.optional(RunId), + /** A client is editing this message: the queue waits here once it is next, until this time. */ + editHeldUntil: Schema.optional(Schema.DateTimeUtc), requestedAt: Schema.DateTimeUtc, startedAt: Schema.NullOr(Schema.DateTimeUtc), completedAt: Schema.NullOr(Schema.DateTimeUtc), @@ -2618,6 +2620,7 @@ export const OrchestrationV2RunJson = OrchestrationV2Run.mapFields((fields) => ( 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"),