@devries-cameron20 / t3code Mirror · read-only / commits / a917d843b3
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 23, 04:15 UTC

fix(server): held assistant drafts keep their position when flushed at turn end (#19023)

fixfon committed Oct 18, 2026 at 22:21 UTC a917d843b3ae4fdc06d61805929d4a74c41ecaf4
6 files changed +162 -2
apps/server/src/orchestration-v2/RunExecutionService.test.ts
+20
@@ -49,14 +49,20 @@ import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";
49 import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
50 import * as RunExecutionService from "./RunExecutionService.ts";
51 import * as RunFinalizationService from "./RunFinalizationService.ts";
52 +import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
53
54 const driver = ProviderDriverKind.make("codex");
55
56 +const layerTurnItemPositionsTest = Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({
57 + allocate: () => Effect.succeed(1),
58 +});
59 +
60 const layerRunExecutionTest = RunExecutionService.layer.pipe(
61 Layer.provide(
62 Layer.mergeAll(
63 McpAppModelContext.layerEmpty,
64 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
65 + layerTurnItemPositionsTest,
66 Layer.mock(EventSink.EventSinkV2)({}),
67 IdAllocator.layer,
68 Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
@@ -752,6 +758,7 @@ it.effect("passes the thread's MCP app context to the provider under a safe key"
758 Layer.mock(CheckpointService.CheckpointServiceV2)({
759 captureBaseline: () => Effect.void,
760 }),
761 + layerTurnItemPositionsTest,
762 Layer.mock(EventSink.EventSinkV2)({}),
763 IdAllocator.layer,
764 Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({
@@ -779,6 +786,7 @@ it.effect("fails the run when its ownership check cannot be read before calling
786 Layer.mergeAll(
787 McpAppModelContext.layerEmpty,
788 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
789 + layerTurnItemPositionsTest,
790 Layer.mock(EventSink.EventSinkV2)({
791 writeIfRunCurrent: (input) =>
792 Ref.update(writes, (current) => [...current, ...input.events]).pipe(
@@ -1059,6 +1067,7 @@ it.effect("starts the provider when checkpoint baseline capture fails", () =>
1067 }),
1068 ),
1069 }),
1070 + layerTurnItemPositionsTest,
1071 Layer.mock(EventSink.EventSinkV2)({
1072 writeWithEffects: (input) =>
1073 Ref.update(writes, (current) => [
@@ -1171,6 +1180,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as co
1180 captureBaseline: () =>
1181 scenario === "start-guard" ? Effect.void : Effect.die("not reached"),
1182 }),
1183 + layerTurnItemPositionsTest,
1184 Layer.mock(EventSink.EventSinkV2)({
1185 writeIfRunCurrent: (input) =>
1186 Effect.gen(function* () {
@@ -1337,6 +1347,7 @@ it.effect("ingests new member threads of an owned child after the root turn term
1347 Layer.mergeAll(
1348 McpAppModelContext.layerEmpty,
1349 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
1350 + layerTurnItemPositionsTest,
1351 Layer.mock(EventSink.EventSinkV2)({
1352 write: () => Effect.succeed([]),
1353 writeWithEffects: (input) =>
@@ -1566,6 +1577,7 @@ it.effect("ends a nested native subagent and its thread when the root run is int
1577 Layer.mergeAll(
1578 McpAppModelContext.layerEmpty,
1579 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
1580 + layerTurnItemPositionsTest,
1581 Layer.mock(EventSink.EventSinkV2)({
1582 write: () => Effect.succeed([]),
1583 writeWithEffects: (input) =>
@@ -1923,6 +1935,7 @@ it.effect(
1935 Layer.mock(CheckpointService.CheckpointServiceV2)({
1936 captureBaseline: () => Effect.void,
1937 }),
1938 + layerTurnItemPositionsTest,
1939 Layer.mock(EventSink.EventSinkV2)({
1940 write: () => Effect.succeed([]),
1941 writeWithEffects: (input) =>
@@ -2136,6 +2149,7 @@ it.effect("drops late root provider-thread writes from a superseded attempt", ()
2149 Layer.mergeAll(
2150 McpAppModelContext.layerEmpty,
2151 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
2152 + layerTurnItemPositionsTest,
2153 Layer.mock(EventSink.EventSinkV2)({
2154 write: () => Effect.succeed([]),
2155 writeWithEffects: (input) =>
@@ -2337,6 +2351,7 @@ it.effect(
2351 Layer.mock(CheckpointService.CheckpointServiceV2)({
2352 captureBaseline: () => Effect.void,
2353 }),
2354 + layerTurnItemPositionsTest,
2355 Layer.mock(EventSink.EventSinkV2)({
2356 write: () => Effect.succeed([]),
2357 writeWithEffects: (input) =>
@@ -2506,6 +2521,7 @@ it.effect(
2521 Layer.mock(CheckpointService.CheckpointServiceV2)({
2522 captureBaseline: () => Effect.void,
2523 }),
2524 + layerTurnItemPositionsTest,
2525 Layer.mock(EventSink.EventSinkV2)({
2526 write: () => Effect.succeed([]),
2527 writeWithEffects: (input) =>
@@ -2668,6 +2684,7 @@ it.effect(
2684 Layer.mock(CheckpointService.CheckpointServiceV2)({
2685 captureBaseline: () => Effect.void,
2686 }),
2687 + layerTurnItemPositionsTest,
2688 Layer.mock(EventSink.EventSinkV2)({
2689 write: () => Effect.succeed([]),
2690 writeWithEffects: (input) =>
@@ -3108,6 +3125,7 @@ it.effect(
3125 Layer.mock(CheckpointService.CheckpointServiceV2)({
3126 captureBaseline: () => Effect.void,
3127 }),
3128 + layerTurnItemPositionsTest,
3129 Layer.mock(EventSink.EventSinkV2)({
3130 write: () => Effect.succeed([]),
3131 writeWithEffects: (input) =>
@@ -3885,6 +3903,7 @@ function captureRootRunTermination(input: {
3903 forThread: () => input.appContext ?? Effect.succeed([]),
3904 }),
3905 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
3906 + layerTurnItemPositionsTest,
3907 Layer.mock(EventSink.EventSinkV2)({
3908 write: (payload) =>
3909 Effect.gen(function* () {
@@ -4370,6 +4389,7 @@ function runBackgroundItemScenario(
4389 Layer.mergeAll(
4390 McpAppModelContext.layerEmpty,
4391 Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),
4392 + layerTurnItemPositionsTest,
4393 Layer.mock(EventSink.EventSinkV2)({
4394 write: () => Effect.succeed([]),
4395 writeWithEffects: (input) =>
apps/server/src/orchestration-v2/RunExecutionService.ts
+19
@@ -49,6 +49,7 @@ import {
49 makeProviderFailureTurnItem,
50 } from "@t3tools/provider-core/server/failure";
51 import * as RunFinalizationService from "./RunFinalizationService.ts";
52 +import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";
53
54 export interface ProviderEventRoutingState {
55 readonly ownedThreadIds: ReadonlySet<ThreadId>;
@@ -564,6 +565,7 @@ export const layer: Layer.Layer<
565 | ProviderEventIngestor.ProviderEventIngestorV2
566 | ServerSettings.ServerSettingsService
567 | McpAppModelContext.McpAppModelContext
568 + | TurnItemPositionStore.TurnItemPositionStoreV2
569 > = Layer.effect(
570 RunExecutionServiceV2,
571 Effect.gen(function* () {
@@ -573,6 +575,7 @@ export const layer: Layer.Layer<
575 const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;
576 const serverSettings = yield* ServerSettings.ServerSettingsService;
577 const mcpAppModelContext = yield* McpAppModelContext.McpAppModelContext;
578 + const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;
579 const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;
580
581 const writeFinalRunEvents = (input: {
@@ -1195,6 +1198,9 @@ export const layer: Layer.Layer<
1198 return true;
1199 });
1200 const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);
1201 + // Held text writes nothing, so its item would take a position only
1202 + // when finally written, behind every item that began after it.
1203 + const reservedHeldTurnItemIds = new Set<TurnItemId>();
1204 const providerEventFiber = yield* eventSubscription.events.pipe(
1205 Stream.filterEffect((event) =>
1206 Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
@@ -1250,6 +1256,19 @@ export const layer: Layer.Layer<
1256 ) {
1257 yield* Ref.set(providerThreadOwnerLost, true);
1258 }
1259 + } else if (
1260 + event.type === "turn_item.updated" &&
1261 + (event.turnItem.type === "assistant_message" ||
1262 + event.turnItem.type === "reasoning") &&
1263 + event.turnItem.streaming &&
1264 + !reservedHeldTurnItemIds.has(event.turnItem.id)
1265 + ) {
1266 + yield* turnItemPositions.allocate({
1267 + threadId: event.turnItem.threadId,
1268 + turnItemId: event.turnItem.id,
1269 + runId: event.turnItem.runId,
1270 + });
1271 + reservedHeldTurnItemIds.add(event.turnItem.id);
1272 }
1273 if (event.type === "provider_thread.updated") {
1274 if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+118
@@ -10,6 +10,7 @@ import {
10 ProviderThreadId,
11 ProviderTurnId,
12 ThreadId,
13 + TurnItemId,
14 type ModelSelection,
15 type OrchestrationV2DomainEvent,
16 } from "@t3tools/contracts";
@@ -700,3 +701,120 @@ it.effect("starts a steer that missed the turn on the saved next-turn selection"
701 }),
702 ),
703 );
704 +
705 +// A draft that never reaches a paragraph boundary is held back while it
706 +// streams. Codex only flushes it at turn end, after the final answer is written,
707 +// so the draft must already own its place from before the steer.
708 +it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>
709 + Effect.scoped(
710 + Effect.gen(function* () {
711 + const { events, started, layer, startFirstTurn } =
712 + yield* nextTurnSelectionHarness("steering-held-draft");
713 + yield* Effect.gen(function* () {
714 + const orchestrator = yield* Orchestrator.OrchestratorV2;
715 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
716 + const threadId = yield* startFirstTurn;
717 + const first = started[0]!;
718 + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;
719 + const now = yield* DateTime.now;
720 + const assistantItem = (id: string, text: string, streaming: boolean) =>
721 + ({
722 + type: "turn_item.updated",
723 + driver,
724 + turnItem: {
725 + id: TurnItemId.make(id),
726 + threadId,
727 + runId: first.runId,
728 + nodeId: first.rootNodeId,
729 + providerThreadId: turn.providerThreadId,
730 + providerTurnId: turn.id,
731 + nativeItemRef: null,
732 + parentItemId: null,
733 + ordinal: 0,
734 + status: streaming ? "running" : "completed",
735 + title: null,
736 + startedAt: now,
737 + completedAt: streaming ? null : now,
738 + updatedAt: now,
739 + type: "assistant_message",
740 + messageId: MessageId.make(`message:${id}`),
741 + text,
742 + streaming,
743 + },
744 + }) satisfies ProviderAdapter.ProviderAdapterV2Event;
745 + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
746 + orchestrator.streamDomainEvents.pipe(
747 + Stream.filter(predicate),
748 + Stream.take(1),
749 + Stream.runDrain,
750 + Effect.forkScoped,
751 + );
752 +
753 + // The cut-off draft starts first; the commentary after it is written,
754 + // so the draft has been seen by the time the steer arrives.
755 + yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));
756 + const commentaryWritten = yield* watch(
757 + (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",
758 + );
759 + yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));
760 + yield* Fiber.join(commentaryWritten);
761 +
762 + yield* orchestrator.dispatch({
763 + type: "message.dispatch",
764 + commandId: CommandId.make("steer"),
765 + threadId,
766 + messageId: MessageId.make("message:steer"),
767 + text: "fix the popover",
768 + attachments: [],
769 + dispatchMode: { type: "steer_active", targetRunId: first.runId },
770 + createdBy: "user",
771 + creationSource: "web",
772 + });
773 + yield* worker.drain();
774 +
775 + const settled = yield* watch(
776 + (event) =>
777 + event.type === "run.updated" &&
778 + event.payload.id === first.runId &&
779 + event.payload.status === "waiting",
780 + );
781 + yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));
782 + yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));
783 + yield* Queue.offer(events, {
784 + type: "provider_turn.updated",
785 + driver,
786 + providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },
787 + });
788 + yield* Queue.offer(events, {
789 + type: "turn.terminal",
790 + driver,
791 + providerThreadId: turn.providerThreadId,
792 + providerTurnId: turn.id,
793 + runOrdinal: first.runOrdinal,
794 + status: "completed",
795 + failure: null,
796 + threadDisposition: "reusable",
797 + });
798 + yield* Fiber.join(settled);
799 + yield* worker.drain();
800 +
801 + const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems
802 + .toSorted((left, right) => left.ordinal - right.ordinal)
803 + .flatMap((item) =>
804 + item.type === "user_message"
805 + ? [String(item.messageId)]
806 + : item.type === "assistant_message"
807 + ? [String(item.id)]
808 + : [],
809 + );
810 + assert.deepEqual(items, [
811 + "message:first",
812 + "draft",
813 + "commentary",
814 + "message:steer",
815 + "answer",
816 + ]);
817 + }).pipe(Effect.provide(layer));
818 + }),
819 + ),
820 +);
apps/server/src/orchestration-v2/runtimeLayer.ts
+1
@@ -155,6 +155,7 @@ const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe(
155 layerEventSinkProvided,
156 IdAllocator.layer,
157 layerProviderEventIngestorProvided,
158 + TurnItemPositionStore.layer,
159 ),
160 ),
161 );
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+1
@@ -385,6 +385,7 @@ export function layerWithRegistry<Error>(
385 IdAllocator.layer,
386 layerProviderEventIngestorProvided,
387 layerServerSettings,
388 + layerStores,
389 ),
390 ),
391 );
apps/server/src/orchestration-v2/testkit/fixtures/opencode2_tool_call/output.ts
+3 -2
@@ -22,13 +22,14 @@ export function assertOpenCode2ToolCallOutput(
22 assertSemanticProjectionIntegrity(projection);
23 assertVisibleTurnItemsMirrorLocalTurnItems(projection);
24 // Buffered delivery keeps streaming text out of the read model until
25 - // `text.ended`, which OpenCode sends after both tool calls started.
25 + // `text.ended`, which OpenCode sends after both tool calls started. The text
26 + // keeps the position it took when it began, ahead of the tool calls.
27 assertTurnItemTypeSequence(projection, [
28 "user_message",
29 + "assistant_message",
30 "dynamic_tool",
31 "command_execution",
32 "assistant_message",
31 - "assistant_message",
33 "checkpoint",
34 ]);
35 assertUserMessagesInclude(projection, [OPENCODE2_TOOL_CALL_PROMPT]);