@devries-cameron20 / t3code Mirror · read-only / commits / c50dd8e12d
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(server): agent continuations preserve the working timer start (#22947)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 00:40 UTC c50dd8e12d694110d7344707668b85b01583875f
2 files changed +265 -12
apps/server/src/orchestration-v2/Orchestrator.ts
+53 -12
@@ -508,23 +508,41 @@ function nextRunOrdinal(projection: Pick<OrchestrationV2ThreadProjection, "runs"
508 return projection.runs.reduce((max, run) => Math.max(max, run.ordinal), 0) + 1;
509 }
510
511 -/** Stamp at wake start; queued prompts lack start times and delegated results jump the queue. */
511 +/**
512 + * Stamp at wake start; queued prompts lack start times and delegated results jump the queue.
513 + * Auto-drained agent messages continue active work; explicit queue starts reset it.
514 + */
515 function wakeWorkStartedAt(
513 - runs: ReadonlyArray<OrchestrationV2Run>,
514 - trigger: {
516 + projection: Pick<OrchestrationV2ThreadProjection, "runs" | "subagents">,
517 + trigger: Pick<
518 + OrchestrationV2ConversationMessage,
519 + "createdBy" | "creationSource" | "senderThreadId"
520 + > & {
521 readonly notification?: unknown;
522 readonly delegatedCompletion?: unknown;
523 readonly restartContinuationOfRunId?: RunId | undefined;
524 },
525 + delivery: "immediate" | "automatic-queue" | "explicit-queue" = "immediate",
526 ): Pick<OrchestrationV2Run, "workStartedAt"> {
527 if (
528 trigger.notification === undefined &&
529 trigger.delegatedCompletion === undefined &&
523 - trigger.restartContinuationOfRunId === undefined
530 + trigger.restartContinuationOfRunId === undefined &&
531 + !(
532 + trigger.createdBy === "agent" &&
533 + trigger.creationSource === "mcp" &&
534 + trigger.senderThreadId !== undefined &&
535 + (delivery === "automatic-queue" ||
536 + (delivery === "immediate" &&
537 + projection.subagents.some(
538 + (subagent) =>
539 + subagent.origin === "app_owned" && subagent.childThreadId === trigger.senderThreadId,
540 + )))
541 + )
542 ) {
543 return {};
544 }
527 - const previous = runs
545 + const previous = projection.runs
546 .flatMap((run) => (run.startedAt === null ? [] : [{ run, startedAt: run.startedAt }]))
547 .toSorted(
548 (left, right) =>
@@ -2372,6 +2390,22 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2390 ),
2391 updatedAt: now,
2392 };
2393 + // Resume can clear the hold before the stopped run ends; its Stop marker still makes the drain explicit.
2394 + const endedRunId = options?.endedRunId;
2395 + const queueDelivery =
2396 + endedRunId === undefined ||
2397 + queuedRun.queueHeld === true ||
2398 + (yield* projectionStore
2399 + .getThreadRecords(threadId, ["turnItems"], {
2400 + turnItemTypes: ["run_interrupt_request"],
2401 + turnItemRunIds: [endedRunId],
2402 + })
2403 + .pipe(
2404 + Effect.map(({ turnItems }) => turnItems.length > 0),
2405 + Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
2406 + ))
2407 + ? "explicit-queue"
2408 + : "automatic-queue";
2409 const startingRun: OrchestrationV2Run = {
2410 ...queuedRun,
2411 providerThreadId: queuedProviderThread.id,
@@ -2380,11 +2414,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2414 queuePosition: null,
2415 startedAt: null,
2416 contextHandoffId: activeHandoff?.id ?? null,
2383 - ...wakeWorkStartedAt(projection.runs, {
2384 - notification: queuedMessage.notification,
2385 - delegatedCompletion: queuedMessage.delegatedCompletion,
2386 - restartContinuationOfRunId: queuedRun.restartContinuationOfRunId,
2387 - }),
2417 + ...wakeWorkStartedAt(
2418 + projection,
2419 + {
2420 + createdBy: queuedMessage.createdBy,
2421 + creationSource: queuedMessage.creationSource,
2422 + senderThreadId: queuedMessage.senderThreadId,
2423 + notification: queuedMessage.notification,
2424 + delegatedCompletion: queuedMessage.delegatedCompletion,
2425 + restartContinuationOfRunId: queuedRun.restartContinuationOfRunId,
2426 + },
2427 + queueDelivery,
2428 + ),
2429 };
2430 const userTurnItem: OrchestrationV2TurnItem = {
2431 ...(legacyQueuedTurnItem ?? {
@@ -6969,7 +7010,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7010 ? { workspacePreparation: dispatchMode.workspaceStrategy }
7011 : {}),
7012 ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
6972 - ...wakeWorkStartedAt(projection.runs, command),
7013 + ...wakeWorkStartedAt(projection, command),
7014 ...(freshContext ? { freshContext: true } : {}),
7015 };
7016 const attempt: OrchestrationV2RunAttempt = {
@@ -7755,7 +7796,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7796 ? {}
7797 : { usageLimitContinuationOfRunId: command.usageLimitContinuationOfRunId }),
7798 ...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
7758 - ...wakeWorkStartedAt(projection.runs, command),
7799 + ...wakeWorkStartedAt(projection, command),
7800 };
7801 const attempt: OrchestrationV2RunAttempt = {
7802 id: attemptId,
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+212
@@ -5512,6 +5512,218 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
5512 }),
5513 );
5514
5515 + it.effect.each([
5516 + { origin: "agent" as const, delivery: "queued" as const },
5517 + { origin: "agent" as const, delivery: "after-completion" as const },
5518 + { origin: "agent" as const, delivery: "held-resume" as const },
5519 + { origin: "agent" as const, delivery: "resume-before-stop-ends" as const },
5520 + { origin: "child" as const, delivery: "after-completion" as const },
5521 + { origin: "user" as const, delivery: "queued" as const },
5522 + ])(
5523 + "preserves queued agent and child updates but resets fresh requests (%j)",
5524 + ({ origin, delivery }) =>
5525 + Effect.gen(function* () {
5526 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5527 + const eventSink = yield* EventSink.EventSinkV2;
5528 + const threadId = ThreadId.make(`work-clock-${origin}-${delivery}`);
5529 + const originalMessageId = MessageId.make(`${threadId}-original`);
5530 + const followUpMessageId = MessageId.make(`${threadId}-follow-up`);
5531 + yield* orchestrator.dispatch({
5532 + type: "thread.create",
5533 + createdBy: "user",
5534 + creationSource: "web",
5535 + commandId: CommandId.make(`${threadId}-create`),
5536 + threadId,
5537 + projectId: ProjectId.make(`${threadId}-project`),
5538 + title: "Agent message work clock",
5539 + modelSelection,
5540 + runtimeMode: "full-access",
5541 + interactionMode: "default",
5542 + branch: null,
5543 + worktreePath: process.cwd(),
5544 + });
5545 + yield* orchestrator.dispatch({
5546 + type: "message.dispatch",
5547 + createdBy: "user",
5548 + creationSource: "web",
5549 + commandId: CommandId.make(`${threadId}-original`),
5550 + threadId,
5551 + messageId: originalMessageId,
5552 + text: "Original user work",
5553 + attachments: [],
5554 + modelSelection,
5555 + dispatchMode: { type: "start_immediately" },
5556 + });
5557 + const dispatchFollowUp = orchestrator.dispatch({
5558 + type: "message.dispatch",
5559 + createdBy: origin === "user" ? "user" : "agent",
5560 + creationSource: origin === "user" ? "web" : "mcp",
5561 + ...(origin === "user" ? {} : { senderThreadId: ThreadId.make("sending-agent") }),
5562 + commandId: CommandId.make(`${threadId}-follow-up`),
5563 + threadId,
5564 + messageId: followUpMessageId,
5565 + text: "Follow-up work",
5566 + attachments: [],
5567 + modelSelection,
5568 + dispatchMode: {
5569 + type: delivery === "after-completion" ? "start_immediately" : "queue_after_active",
5570 + },
5571 + });
5572 + const held = delivery === "held-resume" || delivery === "resume-before-stop-ends";
5573 + const drainsOnEnd = delivery === "queued" || delivery === "resume-before-stop-ends";
5574 + if (delivery === "queued" || held) yield* dispatchFollowUp;
5575 + const startedRunIds = yield* Queue.unbounded<RunId>();
5576 + const afterSequence = yield* orchestrator.getThreadEventSequence(threadId);
5577 + yield* eventSink.stream({ threadId, afterSequence }).pipe(
5578 + Stream.runForEach((stored) =>
5579 + stored.event.type === "run.updated" && stored.event.payload.status === "starting"
5580 + ? Queue.offer(startedRunIds, stored.event.payload.id)
5581 + : Effect.void,
5582 + ),
5583 + Effect.forkScoped,
5584 + );
5585 + yield* Effect.yieldNow;
5586 + const original = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
5587 + (run) => run.userMessageId === originalMessageId,
5588 + );
5589 + assert.isDefined(original);
5590 + if (origin === "child") {
5591 + assert.isNotNull(original.rootNodeId);
5592 + yield* eventSink.write({
5593 + events: [
5594 + {
5595 + id: EventId.make(`${threadId}-child`),
5596 + type: "subagent.updated",
5597 + threadId,
5598 + runId: original.id,
5599 + occurredAt: original.requestedAt,
5600 + payload: {
5601 + id: NodeId.make(`${threadId}-child`),
5602 + threadId,
5603 + runId: original.id,
5604 + parentNodeId: original.rootNodeId,
5605 + origin: "app_owned",
5606 + createdBy: "agent",
5607 + driver,
5608 + providerInstanceId: original.providerInstanceId,
5609 + providerThreadId: null,
5610 + childThreadId: ThreadId.make("sending-agent"),
5611 + nativeTaskRef: null,
5612 + prompt: "Delegated work",
5613 + title: null,
5614 + model: null,
5615 + status: "completed",
5616 + result: "Done",
5617 + startedAt: original.requestedAt,
5618 + completedAt: original.requestedAt,
5619 + updatedAt: original.requestedAt,
5620 + },
5621 + },
5622 + ],
5623 + });
5624 + }
5625 + if (held) {
5626 + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
5627 + (run) => run.userMessageId === followUpMessageId,
5628 + );
5629 + assert.isDefined(queued);
5630 + yield* eventSink.write({
5631 + events: [
5632 + {
5633 + id: EventId.make(`${threadId}-hold`),
5634 + type: "run.updated",
5635 + threadId,
5636 + occurredAt: original.requestedAt,
5637 + payload: { ...queued, queueHeld: true },
5638 + },
5639 + {
5640 + id: EventId.make(`${threadId}-interrupt-request`),
5641 + type: "turn-item.updated",
5642 + threadId,
5643 + runId: original.id,
5644 + occurredAt: original.requestedAt,
5645 + payload: {
5646 + id: TurnItemId.make(`${threadId}-interrupt-request`),
5647 + type: "run_interrupt_request",
5648 + threadId,
5649 + runId: original.id,
5650 + nodeId: original.rootNodeId,
5651 + providerThreadId: null,
5652 + providerTurnId: null,
5653 + nativeItemRef: null,
5654 + parentItemId: null,
5655 + ordinal: 90,
5656 + status: "completed",
5657 + title: "Interrupt requested",
5658 + startedAt: original.requestedAt,
5659 + completedAt: original.requestedAt,
5660 + updatedAt: original.requestedAt,
5661 + message: "Stopped by user",
5662 + },
5663 + },
5664 + ],
5665 + });
5666 + }
5667 + if (delivery === "resume-before-stop-ends") {
5668 + yield* orchestrator.dispatch({
5669 + type: "queue.resume",
5670 + commandId: CommandId.make(`${threadId}-resume`),
5671 + threadId,
5672 + });
5673 + }
5674 + const originalStart = DateTime.makeUnsafe("2026-10-21T14:20:17.457Z");
5675 + const completedAt = DateTime.makeUnsafe("2026-10-21T14:23:53.509Z");
5676 + yield* eventSink.write({
5677 + events: [
5678 + {
5679 + id: EventId.make(`${threadId}-completed`),
5680 + type: "run.updated",
5681 + threadId,
5682 + runId: original.id,
5683 + ...(original.rootNodeId === null ? {} : { nodeId: original.rootNodeId }),
5684 + providerInstanceId: original.providerInstanceId,
5685 + occurredAt: completedAt,
5686 + payload: {
5687 + ...original,
5688 + status: held ? "interrupted" : "completed",
5689 + startedAt: originalStart,
5690 + completedAt,
5691 + },
5692 + },
5693 + ],
5694 + });
5695 + if (delivery === "held-resume") {
5696 + yield* TestClock.adjust("3 hours");
5697 + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
5698 + (run) => run.userMessageId === followUpMessageId,
5699 + );
5700 + assert.isDefined(queued);
5701 + assert.equal(queued.status, "queued");
5702 + yield* orchestrator.dispatch({
5703 + type: "queue.resume",
5704 + commandId: CommandId.make(`${threadId}-resume`),
5705 + threadId,
5706 + });
5707 + } else if (delivery === "after-completion") yield* dispatchFollowUp;
5708 + const startedRunId = drainsOnEnd ? yield* Queue.take(startedRunIds) : null;
5709 + const followUp = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
5710 + (run) => run.userMessageId === followUpMessageId,
5711 + );
5712 + assert.isDefined(followUp);
5713 + if (drainsOnEnd) assert.equal(startedRunId, followUp.id);
5714 + assert.equal(followUp.status, "starting");
5715 + if (origin === "child" || (origin === "agent" && delivery === "queued")) {
5716 + assert.isDefined(followUp.workStartedAt);
5717 + assert.equal(
5718 + DateTime.toEpochMillis(followUp.workStartedAt),
5719 + DateTime.toEpochMillis(originalStart),
5720 + );
5721 + } else {
5722 + assert.isUndefined(followUp.workStartedAt);
5723 + }
5724 + }),
5725 + );
5726 +
5727 it.effect.each(["usage_limit", "provider_error"] as const)(
5728 "handles a queued message after a %s failure",
5729 (failureClass) =>