TypeScript
fix(server): held assistant drafts keep their position when flushed at turn end (#19023)
fixfona917d843b3ae
diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 0e68d9f562e..7e88b49789d 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -49,14 +49,20 @@ import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";import * as RunExecutionService from "./RunExecutionService.ts";import * as RunFinalizationService from "./RunFinalizationService.ts";+import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";const driver = ProviderDriverKind.make("codex");+const layerTurnItemPositionsTest = Layer.mock(TurnItemPositionStore.TurnItemPositionStoreV2)({+ allocate: () => Effect.succeed(1),+});+const layerRunExecutionTest = RunExecutionService.layer.pipe(Layer.provide(Layer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({}),IdAllocator.layer,Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({@@ -752,6 +758,7 @@ it.effect("passes the thread's MCP app context to the provider under a safe key"Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({}),IdAllocator.layer,Layer.mock(ProviderEventIngestor.ProviderEventIngestorV2)({@@ -779,6 +786,7 @@ it.effect("fails the run when its ownership check cannot be read before callingLayer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({writeIfRunCurrent: (input) =>Ref.update(writes, (current) => [...current, ...input.events]).pipe(@@ -1059,6 +1067,7 @@ it.effect("starts the provider when checkpoint baseline capture fails", () =>}),),}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({writeWithEffects: (input) =>Ref.update(writes, (current) => [@@ -1171,6 +1180,7 @@ it.effect.each(["failure", "interruption", "stale-attempt", "start-guard"] as cocaptureBaseline: () =>scenario === "start-guard" ? Effect.void : Effect.die("not reached"),}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({writeIfRunCurrent: (input) =>Effect.gen(function* () {@@ -1337,6 +1347,7 @@ it.effect("ingests new member threads of an owned child after the root turn termLayer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -1566,6 +1577,7 @@ it.effect("ends a nested native subagent and its thread when the root run is intLayer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -1923,6 +1935,7 @@ it.effect(Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -2136,6 +2149,7 @@ it.effect("drops late root provider-thread writes from a superseded attempt", ()Layer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -2337,6 +2351,7 @@ it.effect(Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -2506,6 +2521,7 @@ it.effect(Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -2668,6 +2684,7 @@ it.effect(Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -3108,6 +3125,7 @@ it.effect(Layer.mock(CheckpointService.CheckpointServiceV2)({captureBaseline: () => Effect.void,}),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>@@ -3885,6 +3903,7 @@ function captureRootRunTermination(input: {forThread: () => input.appContext ?? Effect.succeed([]),}),Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: (payload) =>Effect.gen(function* () {@@ -4370,6 +4389,7 @@ function runBackgroundItemScenario(Layer.mergeAll(McpAppModelContext.layerEmpty,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),+ layerTurnItemPositionsTest,Layer.mock(EventSink.EventSinkV2)({write: () => Effect.succeed([]),writeWithEffects: (input) =>diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 61ab0a3f095..eb0f28310de 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -49,6 +49,7 @@ import {makeProviderFailureTurnItem,} from "@t3tools/provider-core/server/failure";import * as RunFinalizationService from "./RunFinalizationService.ts";+import * as TurnItemPositionStore from "./TurnItemPositionStore.ts";export interface ProviderEventRoutingState {readonly ownedThreadIds: ReadonlySet<ThreadId>;@@ -564,6 +565,7 @@ export const layer: Layer.Layer<| ProviderEventIngestor.ProviderEventIngestorV2| ServerSettings.ServerSettingsService| McpAppModelContext.McpAppModelContext+ | TurnItemPositionStore.TurnItemPositionStoreV2> = Layer.effect(RunExecutionServiceV2,Effect.gen(function* () {@@ -573,6 +575,7 @@ export const layer: Layer.Layer<const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2;const serverSettings = yield* ServerSettings.ServerSettingsService;const mcpAppModelContext = yield* McpAppModelContext.McpAppModelContext;+ const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;const writeFinalRunEvents = (input: {@@ -1195,6 +1198,9 @@ export const layer: Layer.Layer<return true;});const filterAssistantEvent = makeAssistantStreamingFilter(responseStreamingMode);+ // Held text writes nothing, so its item would take a position only+ // when finally written, behind every item that began after it.+ const reservedHeldTurnItemIds = new Set<TurnItemId>();const providerEventFiber = yield* eventSubscription.events.pipe(Stream.filterEffect((event) =>Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),@@ -1250,6 +1256,19 @@ export const layer: Layer.Layer<) {yield* Ref.set(providerThreadOwnerLost, true);}+ } else if (+ event.type === "turn_item.updated" &&+ (event.turnItem.type === "assistant_message" ||+ event.turnItem.type === "reasoning") &&+ event.turnItem.streaming &&+ !reservedHeldTurnItemIds.has(event.turnItem.id)+ ) {+ yield* turnItemPositions.allocate({+ threadId: event.turnItem.threadId,+ turnItemId: event.turnItem.id,+ runId: event.turnItem.runId,+ });+ reservedHeldTurnItemIds.add(event.turnItem.id);}if (event.type === "provider_thread.updated") {if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) {diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.tsindex 63b80412491..fca2d937212 100644--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts@@ -10,6 +10,7 @@ import {ProviderThreadId,ProviderTurnId,ThreadId,+ TurnItemId,type ModelSelection,type OrchestrationV2DomainEvent,} from "@t3tools/contracts";@@ -700,3 +701,120 @@ it.effect("starts a steer that missed the turn on the saved next-turn selection"}),),);++// A draft that never reaches a paragraph boundary is held back while it+// streams. Codex only flushes it at turn end, after the final answer is written,+// so the draft must already own its place from before the steer.+it.effect("keeps a held commentary draft before the steer when turn end flushes it", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { events, started, layer, startFirstTurn } =+ yield* nextTurnSelectionHarness("steering-held-draft");+ yield* Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ const threadId = yield* startFirstTurn;+ const first = started[0]!;+ const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!;+ const now = yield* DateTime.now;+ const assistantItem = (id: string, text: string, streaming: boolean) =>+ ({+ type: "turn_item.updated",+ driver,+ turnItem: {+ id: TurnItemId.make(id),+ threadId,+ runId: first.runId,+ nodeId: first.rootNodeId,+ providerThreadId: turn.providerThreadId,+ providerTurnId: turn.id,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 0,+ status: streaming ? "running" : "completed",+ title: null,+ startedAt: now,+ completedAt: streaming ? null : now,+ updatedAt: now,+ type: "assistant_message",+ messageId: MessageId.make(`message:${id}`),+ text,+ streaming,+ },+ }) satisfies ProviderAdapter.ProviderAdapterV2Event;+ const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>+ orchestrator.streamDomainEvents.pipe(+ Stream.filter(predicate),+ Stream.take(1),+ Stream.runDrain,+ Effect.forkScoped,+ );++ // The cut-off draft starts first; the commentary after it is written,+ // so the draft has been seen by the time the steer arrives.+ yield* Queue.offer(events, assistantItem("draft", "Let me look at the", true));+ const commentaryWritten = yield* watch(+ (event) => event.type === "turn-item.updated" && event.payload.id === "commentary",+ );+ yield* Queue.offer(events, assistantItem("commentary", "Checking the popover.", false));+ yield* Fiber.join(commentaryWritten);++ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make("steer"),+ threadId,+ messageId: MessageId.make("message:steer"),+ text: "fix the popover",+ attachments: [],+ dispatchMode: { type: "steer_active", targetRunId: first.runId },+ createdBy: "user",+ creationSource: "web",+ });+ yield* worker.drain();++ const settled = yield* watch(+ (event) =>+ event.type === "run.updated" &&+ event.payload.id === first.runId &&+ event.payload.status === "waiting",+ );+ yield* Queue.offer(events, assistantItem("answer", "All fixed.", false));+ yield* Queue.offer(events, assistantItem("draft", "Let me look at the", false));+ yield* Queue.offer(events, {+ type: "provider_turn.updated",+ driver,+ providerTurn: { ...turn, status: "completed", completedAt: yield* DateTime.now },+ });+ yield* Queue.offer(events, {+ type: "turn.terminal",+ driver,+ providerThreadId: turn.providerThreadId,+ providerTurnId: turn.id,+ runOrdinal: first.runOrdinal,+ status: "completed",+ failure: null,+ threadDisposition: "reusable",+ });+ yield* Fiber.join(settled);+ yield* worker.drain();++ const items = (yield* orchestrator.getThreadProjection(threadId)).turnItems+ .toSorted((left, right) => left.ordinal - right.ordinal)+ .flatMap((item) =>+ item.type === "user_message"+ ? [String(item.messageId)]+ : item.type === "assistant_message"+ ? [String(item.id)]+ : [],+ );+ assert.deepEqual(items, [+ "message:first",+ "draft",+ "commentary",+ "message:steer",+ "answer",+ ]);+ }).pipe(Effect.provide(layer));+ }),+ ),+);diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.tsindex 52e9adf1870..aa44a6171e5 100644--- a/apps/server/src/orchestration-v2/runtimeLayer.ts+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts@@ -155,6 +155,7 @@ const layerRunExecutionServiceProvided = RunExecutionService.layer.pipe(layerEventSinkProvided,IdAllocator.layer,layerProviderEventIngestorProvided,+ TurnItemPositionStore.layer,),),);diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.tsindex b6327f3a069..0342a3ccc9d 100644--- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts+++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts@@ -385,6 +385,7 @@ export function layerWithRegistry<Error>(IdAllocator.layer,layerProviderEventIngestorProvided,layerServerSettings,+ layerStores,),),);diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_tool_call/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_tool_call/output.tsindex 06172b6b2a5..f2f03c22dd4 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_tool_call/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_tool_call/output.ts@@ -22,13 +22,14 @@ export function assertOpenCode2ToolCallOutput(assertSemanticProjectionIntegrity(projection);assertVisibleTurnItemsMirrorLocalTurnItems(projection);// Buffered delivery keeps streaming text out of the read model until- // `text.ended`, which OpenCode sends after both tool calls started.+ // `text.ended`, which OpenCode sends after both tool calls started. The text+ // keeps the position it took when it began, ahead of the tool calls.assertTurnItemTypeSequence(projection, ["user_message",+ "assistant_message","dynamic_tool","command_execution","assistant_message",- "assistant_message","checkpoint",]);assertUserMessagesInclude(projection, [OPENCODE2_TOOL_CALL_PROMPT]);