diff --git a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts index 8c56f5217b..ba883b6f6a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts @@ -778,6 +778,17 @@ interface ActiveCursorSubagent { resultProjected: boolean; } +interface ActiveCursorTextSegment { + readonly nativeItemId: string; + readonly startedAt: DateTime.Utc; + text: string; +} + +interface ActiveCursorTextStream { + current: ActiveCursorTextSegment | null; + nextSegment: number; +} + interface ActiveCursorTurn { readonly input: ProviderAdapterV2TurnInput; readonly run: CursorAgentSdkRun; @@ -786,14 +797,8 @@ interface ActiveCursorTurn { readonly completed: Deferred.Deferred; readonly tools: Map; readonly subagents: Map; - readonly assistant: { - readonly nativeItemId: string; - text: string; - }; - readonly reasoning: { - readonly nativeItemId: string; - text: string; - }; + readonly assistant: ActiveCursorTextStream; + readonly reasoning: ActiveCursorTextStream; interrupted: boolean; finalized: boolean; } @@ -900,26 +905,27 @@ export function makeCursorAdapterV2( context: ActiveCursorTurn, completed: boolean, ) { - if (context.assistant.text.length === 0) { + const segment = context.assistant.current; + if (segment === null || segment.text.length === 0) { return; } const now = yield* DateTime.now; - const ordinal = yield* resolveItemOrdinal(context, context.assistant.nativeItemId); + const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ provider: CURSOR_PROVIDER, - nativeItemId: context.assistant.nativeItemId, + nativeItemId: segment.nativeItemId, }); const messageId = idAllocator.derive.messageFromProviderItem({ provider: CURSOR_PROVIDER, - nativeItemId: context.assistant.nativeItemId, + nativeItemId: segment.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ provider: CURSOR_PROVIDER, - nativeItemId: context.assistant.nativeItemId, + nativeItemId: segment.nativeItemId, }); const nativeItemRef = { provider: CURSOR_PROVIDER, - nativeId: context.assistant.nativeItemId, + nativeId: segment.nativeItemId, strength: "weak" as const, }; yield* emitProviderEvent({ @@ -939,7 +945,7 @@ export function makeCursorAdapterV2( nativeItemRef, runtimeRequestId: null, checkpointScopeId: null, - startedAt: context.startedAt, + startedAt: segment.startedAt, completedAt: completed ? now : null, }, }); @@ -952,10 +958,10 @@ export function makeCursorAdapterV2( runId: context.input.runId, nodeId, role: "assistant", - text: context.assistant.text, + text: segment.text, attachments: [], streaming: !completed, - createdAt: context.startedAt, + createdAt: segment.startedAt, updatedAt: now, }, }); @@ -974,12 +980,12 @@ export function makeCursorAdapterV2( ordinal, status: completed ? "completed" : "running", title: null, - startedAt: context.startedAt, + startedAt: segment.startedAt, completedAt: completed ? now : null, updatedAt: now, type: "assistant_message", messageId, - text: context.assistant.text, + text: segment.text, streaming: !completed, }, }); @@ -989,22 +995,23 @@ export function makeCursorAdapterV2( context: ActiveCursorTurn, completed: boolean, ) { - if (context.reasoning.text.length === 0) { + const segment = context.reasoning.current; + if (segment === null || segment.text.length === 0) { return; } const now = yield* DateTime.now; - const ordinal = yield* resolveItemOrdinal(context, context.reasoning.nativeItemId); + const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ provider: CURSOR_PROVIDER, - nativeItemId: context.reasoning.nativeItemId, + nativeItemId: segment.nativeItemId, }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ provider: CURSOR_PROVIDER, - nativeItemId: context.reasoning.nativeItemId, + nativeItemId: segment.nativeItemId, }); const nativeItemRef = { provider: CURSOR_PROVIDER, - nativeId: context.reasoning.nativeItemId, + nativeId: segment.nativeItemId, strength: "weak" as const, }; yield* emitProviderEvent({ @@ -1024,7 +1031,7 @@ export function makeCursorAdapterV2( nativeItemRef, runtimeRequestId: null, checkpointScopeId: null, - startedAt: context.startedAt, + startedAt: segment.startedAt, completedAt: completed ? now : null, }, }); @@ -1043,16 +1050,49 @@ export function makeCursorAdapterV2( ordinal, status: completed ? "completed" : "running", title: null, - startedAt: context.startedAt, + startedAt: segment.startedAt, completedAt: completed ? now : null, updatedAt: now, type: "reasoning", - text: context.reasoning.text, + text: segment.text, streaming: !completed, }, }); }); + const appendTextSegment = Effect.fnUntraced(function* (input: { + readonly context: ActiveCursorTurn; + readonly stream: ActiveCursorTextStream; + readonly kind: "assistant" | "reasoning"; + readonly text: string; + }) { + if (input.stream.current === null) { + input.stream.nextSegment += 1; + input.stream.current = { + nativeItemId: `${input.kind}:${input.context.run.runId}:${input.stream.nextSegment}`, + startedAt: yield* DateTime.now, + text: "", + }; + } + input.stream.current.text += input.text; + }); + + const completeAssistant = Effect.fnUntraced(function* (context: ActiveCursorTurn) { + if (context.assistant.current === null) { + return; + } + yield* emitAssistant(context, true); + context.assistant.current = null; + }); + + const completeReasoning = Effect.fnUntraced(function* (context: ActiveCursorTurn) { + if (context.reasoning.current === null) { + return; + } + yield* emitReasoning(context, true); + context.reasoning.current = null; + }); + const emitToolArtifacts = Effect.fnUntraced(function* (input: { readonly active: ActiveCursorToolCall; readonly completed: boolean; @@ -1759,21 +1799,40 @@ export function makeCursorAdapterV2( } switch (update.type) { case "text-delta": - context.assistant.text += update.text; + yield* completeReasoning(context); + yield* appendTextSegment({ + context, + stream: context.assistant, + kind: "assistant", + text: update.text, + }); yield* emitAssistant(context, false); return; case "thinking-delta": - context.reasoning.text += update.text; + yield* completeAssistant(context); + yield* appendTextSegment({ + context, + stream: context.reasoning, + kind: "reasoning", + text: update.text, + }); yield* emitReasoning(context, false); return; case "thinking-completed": - yield* emitReasoning(context, true); + yield* completeReasoning(context); return; case "tool-call-started": case "partial-tool-call": case "tool-call-completed": + yield* completeAssistant(context); + yield* completeReasoning(context); yield* handleToolUpdate(context, update); return; + case "step-completed": + case "turn-ended": + yield* completeAssistant(context); + yield* completeReasoning(context); + return; case "shell-output-delta": { const shell = Array.from(context.tools.values()) .toReversed() @@ -1826,8 +1885,8 @@ export function makeCursorAdapterV2( yield* emitToolArtifacts({ active: tool, completed: true }); } input.context.tools.clear(); - yield* emitReasoning(input.context, true); - yield* emitAssistant(input.context, true); + yield* completeReasoning(input.context); + yield* completeAssistant(input.context); yield* emitProviderEvent({ type: "provider_turn.updated", provider: CURSOR_PROVIDER, @@ -2022,12 +2081,12 @@ export function makeCursorAdapterV2( tools: new Map(), subagents: new Map(), assistant: { - nativeItemId: `assistant:${sdkRun.runId}`, - text: "", + current: null, + nextSegment: 0, }, reasoning: { - nativeItemId: `reasoning:${sdkRun.runId}`, - text: "", + current: null, + nextSegment: 0, }, interrupted: false, finalized: false, @@ -2061,11 +2120,16 @@ export function makeCursorAdapterV2( Effect.gen(function* () { if ( context !== null && - context.assistant.text.length === 0 && + context.assistant.nextSegment === 0 && result.result !== undefined && result.result.length > 0 ) { - context.assistant.text = result.result; + yield* appendTextSegment({ + context, + stream: context.assistant, + kind: "assistant", + text: result.result, + }); } if (context !== null) { yield* finalizeTurn({ diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2d1901eda1..b0a8ea58a5 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -29,6 +29,10 @@ import { ThreadId, TurnItemId, } from "@t3tools/contracts"; +import { + isOrchestrationV2SupersededInterrupt, + isOrchestrationV2TurnItemVisible, +} from "@t3tools/shared/orchestrationV2Timeline"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -167,10 +171,10 @@ export function applyToProjection( }); case "run-attempt.created": case "run-attempt.updated": - return { + return withLocalVisibleTurnItems({ ...base, attempts: upsertById(base.attempts, event.payload), - }; + }); case "node.updated": return { ...base, @@ -423,18 +427,17 @@ function sortMessagesByTurnItemOrder( }); } -function rolledBackRunIds(projection: OrchestrationV2ThreadProjection): ReadonlySet { - return new Set( - projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), - ); -} - function activeLocalTurnItems( projection: OrchestrationV2ThreadProjection, ): Array { - const rolledBack = rolledBackRunIds(projection); return projection.turnItems - .filter((item) => item.runId === null || !rolledBack.has(item.runId)) + .filter((item) => + isOrchestrationV2TurnItemVisible({ + item, + runs: projection.runs, + attempts: projection.attempts, + }), + ) .map((item, position) => ({ position, visibility: "local" as const, @@ -524,6 +527,14 @@ function visibleTurnItemsThroughRun(input: { })); const localPrefix = inheritedVisibleTurnItemsFromLocalItems( input.sourceProjection.turnItems.filter((item) => { + if ( + isOrchestrationV2SupersededInterrupt({ + item, + attempts: input.sourceProjection.attempts, + }) + ) { + return false; + } if (item.runId === null) { return false; } diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 651e405bab..fd7119fb7b 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -21,10 +21,12 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import { ServerSettingsService } from "../serverSettings.ts"; import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { EventSinkV2 } from "./EventSink.ts"; import { IdAllocatorV2, type IdAllocatorV2Shape } from "./IdAllocator.ts"; import type { + ProviderAdapterV2Event, ProviderAdapterV2RuntimePolicy, ProviderAdapterV2SessionRuntime, ProviderAdapterV2TurnMessage, @@ -97,13 +99,37 @@ export class RunExecutionServiceV2 extends Context.Service< RunExecutionServiceV2Shape >()("t3/orchestration-v2/RunExecutionService/RunExecutionServiceV2") {} +export function shouldDeliverProviderEvent( + event: ProviderAdapterV2Event, + assistantStreamingEnabled: boolean, +): boolean { + if (assistantStreamingEnabled) { + return true; + } + + switch (event.type) { + case "node.updated": + return event.node.kind !== "assistant_message" || event.node.status !== "running"; + case "message.updated": + return event.message.role !== "assistant" || !event.message.streaming; + case "turn_item.updated": + return event.turnItem.type !== "assistant_message" || !event.turnItem.streaming; + default: + return true; + } +} + /** * IMPLEMENTATIONS */ export const layer: Layer.Layer< RunExecutionServiceV2, never, - CheckpointServiceV2 | EventSinkV2 | IdAllocatorV2 | ProviderEventIngestorV2 + | CheckpointServiceV2 + | EventSinkV2 + | IdAllocatorV2 + | ProviderEventIngestorV2 + | ServerSettingsService > = Layer.effect( RunExecutionServiceV2, Effect.gen(function* () { @@ -111,6 +137,7 @@ export const layer: Layer.Layer< const eventSink = yield* EventSinkV2; const idAllocator = yield* IdAllocatorV2; const providerEventIngestor = yield* ProviderEventIngestorV2; + const serverSettings = yield* ServerSettingsService; const writeFinalRunEvents = (input: { readonly run: OrchestrationV2Run; @@ -286,6 +313,17 @@ export const layer: Layer.Layer< return RunExecutionServiceV2.of({ startRootRun: (input) => Effect.gen(function* () { + const assistantStreamingEnabled = yield* serverSettings.getSettings.pipe( + Effect.map((settings) => settings.enableAssistantStreaming), + Effect.mapError( + (cause) => + new RunExecutionStartError({ + commandId: input.commandId, + runId: input.run.id, + cause, + }), + ), + ); const terminalStatus = yield* Ref.make event.type === "turn.terminal"), Stream.runForEach((event) => Effect.gen(function* () { - yield* providerEventIngestor.ingestNormalized({ - providerSessionId: input.providerSessionId, - threadId: input.run.threadId, - runId: input.run.id, - nodeId: input.rootNode.id, - event, - }); + if (shouldDeliverProviderEvent(event, assistantStreamingEnabled)) { + yield* providerEventIngestor.ingestNormalized({ + providerSessionId: input.providerSessionId, + threadId: input.run.threadId, + runId: input.run.id, + nodeId: input.rootNode.id, + event, + }); + } if (event.type === "provider_thread.updated") { if (event.providerThread.id === input.providerThread.id) { yield* Ref.set(latestProviderThread, event.providerThread); diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts index 9c2251e22a..457c68d7c6 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts @@ -1,6 +1,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; -import type { ProviderReplayTranscript } from "@t3tools/contracts"; +import type { OrchestrationV2DomainEvent, ProviderReplayTranscript } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -33,6 +33,19 @@ function normalizeTestError(cause: unknown): Error { return cause instanceof Error ? cause : new Error(String(cause)); } +function isStreamingAssistantEvent(event: OrchestrationV2DomainEvent): boolean { + switch (event.type) { + case "node.updated": + return event.payload.kind === "assistant_message" && event.payload.status === "running"; + case "message.updated": + return event.payload.role === "assistant" && event.payload.streaming; + case "turn-item.updated": + return event.payload.type === "assistant_message" && event.payload.streaming; + default: + return false; + } +} + const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < Transcript extends ProviderReplayTranscript, Error, @@ -41,6 +54,7 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < readonly buildInput: () => OrchestratorFixtureInput; readonly provider: ProviderOrchestratorReplayVariant; readonly harness: OrchestratorV2ProviderReplayHarness; + readonly enableAssistantStreaming?: boolean; }) { const rawTranscript = yield* readTranscript(input.provider.transcriptFile); const transcript = yield* input.harness.decodeTranscript(rawTranscript); @@ -62,23 +76,31 @@ const runFixtureProvider = Effect.fn("runOrchestratorReplayFixture")(function* < }, }; - const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness).pipe( - provideDeterministicTestRuntime, - ); + const result = yield* runOrchestratorV2ProviderReplayScenario(scenario, input.harness, { + enableAssistantStreaming: input.enableAssistantStreaming ?? false, + }).pipe(provideDeterministicTestRuntime); input.provider.assertOutput(result, transcript); + if (input.enableAssistantStreaming !== true) { + assert.isFalse( + result.domainEvents.some(isStreamingAssistantEvent), + "buffered delivery must not persist streaming assistant artifacts", + ); + } const projectionThreadId = materialized.projectionThreadIds[0]; assert.isDefined(projectionThreadId); const projection = result.projections.get(projectionThreadId); assert.isDefined(projection); const latestRun = projection.runs.at(-1); assert.deepEqual(latestRun?.modelSelection, input.provider.modelSelection); + return result; }); function runFixtureProviderWithRegisteredHarness(input: { readonly fixtureName: string; readonly buildInput: () => OrchestratorFixtureInput; readonly provider: ProviderOrchestratorReplayVariant; + readonly enableAssistantStreaming?: boolean; }) { switch (input.provider.provider) { case "codex": @@ -133,4 +155,30 @@ describe("orchestrator replay fixtures", () => { }), ); } + + const simpleFixture = ORCHESTRATOR_REPLAY_FIXTURES.find((fixture) => fixture.name === "simple"); + const simpleCursorProvider = simpleFixture?.providers.find( + (provider) => provider.provider === "cursor", + ); + if (simpleFixture !== undefined && simpleCursorProvider !== undefined) { + it.effect("streams Cursor assistant artifacts only when streaming is enabled", () => + Effect.gen(function* () { + const result = yield* runFixtureProviderWithRegisteredHarness({ + fixtureName: "simple-cursor-streaming", + buildInput: simpleFixture.buildInput, + provider: simpleCursorProvider, + enableAssistantStreaming: true, + }); + + assert.deepEqual( + Array.from( + new Set( + result.domainEvents.filter(isStreamingAssistantEvent).map((event) => event.type), + ), + ).toSorted(), + ["message.updated", "node.updated", "turn-item.updated"], + ); + }), + ); + } }); diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 35239fb14a..4a4e9968cd 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -13,6 +13,9 @@ import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore. import { ServerConfig, type ServerConfigShape } from "../../config.ts"; import { GitCoreLive } from "../../git/Layers/GitCore.ts"; import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; +import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts"; +import * as VcsProcess from "../../vcs/VcsProcess.ts"; import { layer as checkpointServiceLayer } from "../CheckpointService.ts"; import { layer as commandPolicyLayer } from "../CommandPolicy.ts"; import { layer as commandReceiptStoreLayer } from "../CommandReceiptStore.ts"; @@ -150,6 +153,7 @@ export function runOrchestratorV2ProviderReplayScenario< SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; + readonly enableAssistantStreaming?: boolean; } = {}, ): Effect.Effect< OrchestratorV2ScenarioResult, @@ -177,6 +181,7 @@ export function makeOrchestratorV2ProviderReplayLayer< SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; + readonly enableAssistantStreaming?: boolean; } = {}, ): Layer.Layer { const registryLayer = harness.makeProviderAdapterRegistryLayer(scenario.transcript); @@ -191,6 +196,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( SqlClient.SqlClient, MigrationError | PlatformError.PlatformError | SqlError >; + readonly enableAssistantStreaming?: boolean; } = {}, ): Layer.Layer { const serverConfigLayer = Layer.effect( @@ -204,6 +210,9 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( Layer.provide(runtimePolicyLayer), ); const databaseLayer = options.databaseLayer ?? SqlitePersistenceMemory; + const serverSettingsLayer = ServerSettingsService.layerTest({ + enableAssistantStreaming: options.enableAssistantStreaming ?? false, + }).pipe(Layer.orDie); const storesLayer = Layer.merge(eventStoreLayer, projectionStoreLayer).pipe( Layer.provide(databaseLayer), ); @@ -245,6 +254,7 @@ export function makeOrchestratorV2ReplayLayerWithRegistry( eventSinkProvided, idAllocatorLayer, providerEventIngestorProvided, + serverSettingsLayer, ), ), ); diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/cursor_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/cursor_output.ts index f2af8bacb1..b4482f762d 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/cursor_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/cursor_output.ts @@ -10,7 +10,6 @@ import { assertTurnItemTypes, assertUserMessageInputIntents, assertUserMessagesInclude, - assertVisibleTurnItemsMirrorLocalTurnItems, MESSAGE_STEERING_INITIAL_PROMPT, MESSAGE_STEERING_STEER_PROMPT, projectionFor, @@ -25,8 +24,7 @@ export function assertCursorMessageSteeringOutput( const projection = projectionFor(result, transcript.scenario); assertSemanticProjectionIntegrity(projection); - assertVisibleTurnItemsMirrorLocalTurnItems(projection); - assertTurnItemTypes(projection, ["user_message", "assistant_message"]); + assertTurnItemTypes(projection, ["user_message", "run_interrupt_result", "assistant_message"]); assertRuntimeRequestCounts(projection, { total: 0 }); assertUserMessagesInclude(projection, [ MESSAGE_STEERING_INITIAL_PROMPT, @@ -49,4 +47,9 @@ export function assertCursorMessageSteeringOutput( ); assert.equal(projection.runs[0]?.activeAttemptId, projection.attempts[1]?.id); assert.equal(projection.runs[0]?.rootNodeId, projection.attempts[1]?.rootNodeId); + assert.notInclude( + projection.visibleTurnItems.map((row) => row.item.type), + "run_interrupt_result", + "restart steering must keep its internal interruption out of visible chat history", + ); } diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts index f4c3ee92b7..d882367591 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent/cursor_output.ts @@ -36,6 +36,23 @@ export function assertCursorSubagentOutput( assertAssistantTextIncludes(projection, "cursor-read-only-fixture"); assertAssistantTextIncludes(projection, "ES2022"); + const lifecycleItems = projection.turnItems.filter( + (item) => + item.type === "reasoning" || item.type === "assistant_message" || item.type === "subagent", + ); + assert.deepEqual( + lifecycleItems.map((item) => item.type), + ["reasoning", "assistant_message", "subagent", "subagent", "assistant_message"], + "Cursor progress, subagents, and the final response must retain provider order", + ); + const assistantMessages = lifecycleItems.filter((item) => item.type === "assistant_message"); + assert.lengthOf(assistantMessages, 2); + assert.equal( + assistantMessages[0]?.text, + "Spawning two subagents in parallel to read `package.json` and `tsconfig.json`.\n", + ); + assert.include(assistantMessages[1]?.text ?? "", "Both subagents finished."); + assert.lengthOf(projection.subagents, 2); assert.lengthOf(result.shellSnapshot.threads, 3); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/cursor_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/cursor_output.ts index 061d1797d4..219f51f3ad 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/cursor_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/todo_list/cursor_output.ts @@ -35,6 +35,24 @@ export function assertTodoListCursorOutput( assertUserMessagesInclude(projection, [TODO_LIST_PROMPT]); assertAssistantTextIncludes(projection, "todo list fixture complete"); + const conversationalItems = projection.turnItems.filter( + (item) => item.type === "assistant_message" || item.type === "reasoning", + ); + assert.deepEqual( + conversationalItems.map((item) => item.type), + ["assistant_message", "reasoning", "reasoning", "assistant_message", "assistant_message"], + "separate Cursor reasoning and assistant segments must not be concatenated", + ); + const assistantMessages = conversationalItems.filter((item) => item.type === "assistant_message"); + assert.lengthOf(assistantMessages, 3); + assert.include(assistantMessages[0]?.text ?? "", "I'll use the update_plan tool"); + assert.include(assistantMessages[1]?.text ?? "", "No `update_plan` tool is available"); + assert.equal(assistantMessages[2]?.text, "todo list fixture complete"); + assert.lengthOf( + conversationalItems.filter((item) => item.type === "reasoning"), + 2, + ); + const todoLists = projection.plans.filter((plan) => plan.kind === "todo_list"); assert.isAtLeast(todoLists.length, 1); assert.deepEqual( diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_output.ts index c1463ba10a..f909d33360 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_output.ts @@ -28,8 +28,19 @@ export function assertToolCallReadOnlyCursorOutput( assertAssistantTextIncludes(projection, "read only tool fixture complete"); assertRuntimeRequestCounts(projection, { total: 0 }); + const assistantMessages = projection.turnItems.filter( + (item) => item.type === "assistant_message", + ); + assert.deepEqual( + assistantMessages.map((item) => item.text), + ["Reading both files now.\n", "read only tool fixture complete"], + "Cursor progress text and the final response must be separate messages", + ); + const fileSearches = projection.turnItems.filter((item) => item.type === "file_search"); assert.lengthOf(fileSearches, 2); + assert.isBelow(assistantMessages[0]?.ordinal ?? Infinity, fileSearches[0]?.ordinal ?? -Infinity); + assert.isBelow(fileSearches[1]?.ordinal ?? Infinity, assistantMessages[1]?.ordinal ?? -Infinity); assert.isTrue( fileSearches.some((item) => JSON.stringify(item.results ?? []).includes("cursor-read-only-fixture"), diff --git a/apps/web/src/lib/orchestrationV2Timeline.test.ts b/apps/web/src/lib/orchestrationV2Timeline.test.ts index 91fd9888d3..c94a3816a8 100644 --- a/apps/web/src/lib/orchestrationV2Timeline.test.ts +++ b/apps/web/src/lib/orchestrationV2Timeline.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it } from "vite-plus/test"; -import { removeAndRenumberTimelineItem } from "./orchestrationV2Timeline"; +import { + removeAndRenumberTimelineItem, + upsertTimelineItemAtStablePosition, +} from "./orchestrationV2Timeline"; describe("removeAndRenumberTimelineItem", () => { it("closes the position gap before a streamed item is reinserted", () => { @@ -20,3 +23,32 @@ describe("removeAndRenumberTimelineItem", () => { expect(new Set(remaining.map((row) => row.position)).size).toBe(remaining.length); }); }); + +describe("upsertTimelineItemAtStablePosition", () => { + it("replaces a streaming item without moving it behind newer items", () => { + const updated = upsertTimelineItemAtStablePosition( + [ + { position: 0, sourceItemId: "reasoning", text: "partial" }, + { position: 1, sourceItemId: "subagent", text: "running" }, + ], + { position: 2, sourceItemId: "reasoning", text: "completed" }, + ); + + expect(updated).toEqual([ + { position: 0, sourceItemId: "reasoning", text: "completed" }, + { position: 1, sourceItemId: "subagent", text: "running" }, + ]); + }); + + it("appends a genuinely new item at the next position", () => { + const updated = upsertTimelineItemAtStablePosition( + [{ position: 0, sourceItemId: "reasoning" }], + { position: 99, sourceItemId: "assistant" }, + ); + + expect(updated).toEqual([ + { position: 0, sourceItemId: "reasoning" }, + { position: 1, sourceItemId: "assistant" }, + ]); + }); +}); diff --git a/apps/web/src/lib/orchestrationV2Timeline.ts b/apps/web/src/lib/orchestrationV2Timeline.ts index 0c6091da3c..8be8b77b8c 100644 --- a/apps/web/src/lib/orchestrationV2Timeline.ts +++ b/apps/web/src/lib/orchestrationV2Timeline.ts @@ -6,3 +6,17 @@ export function removeAndRenumberTimelineItem< .filter((row) => row.sourceItemId !== sourceItemId) .map((row, position) => ({ ...row, position })); } + +export function upsertTimelineItemAtStablePosition< + Id, + Row extends { readonly position: number; readonly sourceItemId: Id }, +>(rows: ReadonlyArray, item: Row): Array { + const existingIndex = rows.findIndex((row) => row.sourceItemId === item.sourceItemId); + if (existingIndex === -1) { + return [...rows, { ...item, position: rows.length }]; + } + + return rows.map((row, index) => + index === existingIndex ? { ...item, position: row.position } : row, + ); +} diff --git a/apps/web/src/routes/debug.orchestration-v2.tsx b/apps/web/src/routes/debug.orchestration-v2.tsx index 92baf99106..141d55cba0 100644 --- a/apps/web/src/routes/debug.orchestration-v2.tsx +++ b/apps/web/src/routes/debug.orchestration-v2.tsx @@ -21,6 +21,7 @@ import { type ThreadId, } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; +import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline"; import { createFileRoute } from "@tanstack/react-router"; import { GitMergeIcon } from "lucide-react"; import type { CSSProperties, DragEvent, ReactNode } from "react"; @@ -29,7 +30,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ProviderModelPicker } from "../components/chat/ProviderModelPicker"; import { getPrimaryEnvironmentConnection } from "../environments/runtime"; import { useSettings } from "../hooks/useSettings"; -import { removeAndRenumberTimelineItem } from "../lib/orchestrationV2Timeline"; +import { + removeAndRenumberTimelineItem, + upsertTimelineItemAtStablePosition, +} from "../lib/orchestrationV2Timeline"; import { newCommandId, newMessageId, newProjectId, newThreadId } from "../lib/utils"; import { type AppModelOption, getAppModelOptionsForInstance } from "../modelSelection"; import { @@ -473,48 +477,31 @@ function upsertVisibleTurnItem( projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem, ): OrchestrationV2ThreadProjection["visibleTurnItems"] { - const existingIndex = projection.visibleTurnItems.findIndex( - (row) => row.sourceItemId === item.id, - ); - if (existingIndex === -1) { - return [ - ...projection.visibleTurnItems, - { - position: projection.visibleTurnItems.length, - visibility: "local", - sourceThreadId: item.threadId, - sourceItemId: item.id, - item, - }, - ]; - } - return projection.visibleTurnItems.map((row, index) => - index === existingIndex ? { ...row, item } : row, - ); -} - -function rolledBackRunIds(projection: OrchestrationV2ThreadProjection): ReadonlySet { - return new Set( - projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), - ); + return upsertTimelineItemAtStablePosition(projection.visibleTurnItems, { + position: projection.visibleTurnItems.length, + visibility: "local" as const, + sourceThreadId: item.threadId, + sourceItemId: item.id, + item, + }); } function shouldShowLocalTurnItem( projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem, ): boolean { - return item.runId === null || !rolledBackRunIds(projection).has(item.runId); + return isOrchestrationV2TurnItemVisible({ + item, + runs: projection.runs, + attempts: projection.attempts, + }); } function activeVisibleTurnItems( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadProjection["visibleTurnItems"] { - const rolledBack = rolledBackRunIds(projection); return projection.visibleTurnItems - .filter( - (row) => - row.visibility !== "local" || row.item.runId === null || !rolledBack.has(row.item.runId), - ) + .filter((row) => row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item)) .map((row, position) => ({ position, visibility: row.visibility, @@ -552,11 +539,16 @@ function applyStreamEventToProjection( }; } case "run-attempt.created": - case "run-attempt.updated": - return { + case "run-attempt.updated": { + const nextProjection = { ...base, attempts: upsertProjectionEntity(base.attempts, event.payload), }; + return { + ...nextProjection, + visibleTurnItems: activeVisibleTurnItems(nextProjection), + }; + } case "node.updated": return { ...base, @@ -602,18 +594,15 @@ function applyStreamEventToProjection( ...base, turnItems: upsertProjectionEntity(base.turnItems, event.payload), }; - const withoutStaleItem = { + const visibleProjection = { ...nextProjection, - visibleTurnItems: removeAndRenumberTimelineItem( - activeVisibleTurnItems(nextProjection), - event.payload.id, - ), + visibleTurnItems: activeVisibleTurnItems(nextProjection), }; return { ...nextProjection, visibleTurnItems: shouldShowLocalTurnItem(nextProjection, event.payload) - ? upsertVisibleTurnItem(withoutStaleItem, event.payload) - : withoutStaleItem.visibleTurnItems, + ? upsertVisibleTurnItem(visibleProjection, event.payload) + : removeAndRenumberTimelineItem(visibleProjection.visibleTurnItems, event.payload.id), }; } case "checkpoint-scope.created": @@ -2893,6 +2882,16 @@ function buildChatScenes( activeRunIds: ReadonlySet, ): ReadonlyArray { const scenes: Array = []; + const finalAssistantItemIdByRun = new Map(); + for (const row of rows) { + if ( + row.kind !== "fork-marker" && + row.item.type === "assistant_message" && + row.item.runId !== null + ) { + finalAssistantItemIdByRun.set(row.item.runId, row.item.id); + } + } let currentLog: Array = []; let currentLogKey: string | null = null; let workStartMs: number | null = null; @@ -2944,7 +2943,13 @@ function buildChatScenes( // belongs to is still active, the turn isn't over (more work may follow) // and the live WorkingIndicator is what should be visible instead. const runStillActive = item.runId !== null && activeRunIds.has(item.runId); - const turnSettled = !item.streaming && item.status === "completed" && !runStillActive; + const isFinalAssistantMessage = + item.runId === null || finalAssistantItemIdByRun.get(item.runId) === item.id; + const turnSettled = + isFinalAssistantMessage && + !item.streaming && + item.status === "completed" && + !runStillActive; if (pendingResponse && turnSettled) { const assistantStart = itemStartMs(item); const duration = diff --git a/packages/shared/package.json b/packages/shared/package.json index 8cdae3e516..bdd402063e 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -99,6 +99,10 @@ "types": "./src/orchestrationTiming.ts", "import": "./src/orchestrationTiming.ts" }, + "./orchestrationV2Timeline": { + "types": "./src/orchestrationV2Timeline.ts", + "import": "./src/orchestrationV2Timeline.ts" + }, "./remote": { "types": "./src/remote.ts", "import": "./src/remote.ts" diff --git a/packages/shared/src/orchestrationV2Timeline.test.ts b/packages/shared/src/orchestrationV2Timeline.test.ts new file mode 100644 index 0000000000..829b0f6f4d --- /dev/null +++ b/packages/shared/src/orchestrationV2Timeline.test.ts @@ -0,0 +1,46 @@ +import { NodeId, RunId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { isOrchestrationV2TurnItemVisible } from "./orchestrationV2Timeline.ts"; + +const runId = RunId.make("run:timeline-visibility"); +const nodeId = NodeId.make("node:timeline-visibility"); + +describe("isOrchestrationV2TurnItemVisible", () => { + it("hides interruption results from superseded attempts", () => { + expect( + isOrchestrationV2TurnItemVisible({ + item: { type: "run_interrupt_result", runId, nodeId }, + runs: [{ id: runId, status: "running" }], + attempts: [{ runId, rootNodeId: nodeId, status: "superseded" }], + }), + ).toBe(false); + }); + + it("keeps interruption results from terminal attempts", () => { + expect( + isOrchestrationV2TurnItemVisible({ + item: { type: "run_interrupt_result", runId, nodeId }, + runs: [{ id: runId, status: "interrupted" }], + attempts: [{ runId, rootNodeId: nodeId, status: "interrupted" }], + }), + ).toBe(true); + }); + + it("does not hide an interruption because another attempt was superseded", () => { + expect( + isOrchestrationV2TurnItemVisible({ + item: { type: "run_interrupt_result", runId, nodeId }, + runs: [{ id: runId, status: "interrupted" }], + attempts: [ + { + runId, + rootNodeId: NodeId.make("node:timeline-visibility:older"), + status: "superseded", + }, + { runId, rootNodeId: nodeId, status: "interrupted" }, + ], + }), + ).toBe(true); + }); +}); diff --git a/packages/shared/src/orchestrationV2Timeline.ts b/packages/shared/src/orchestrationV2Timeline.ts new file mode 100644 index 0000000000..7eed78db8f --- /dev/null +++ b/packages/shared/src/orchestrationV2Timeline.ts @@ -0,0 +1,42 @@ +import type { + OrchestrationV2Run, + OrchestrationV2RunAttempt, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; + +type TimelineRun = Pick; +type TimelineRunAttempt = Pick; +type TimelineTurnItem = Pick; + +export function isOrchestrationV2SupersededInterrupt(input: { + readonly item: TimelineTurnItem; + readonly attempts: ReadonlyArray; +}): boolean { + const { item } = input; + if (item.type !== "run_interrupt_result" || item.runId === null || item.nodeId === null) { + return false; + } + + return input.attempts.some( + (attempt) => + attempt.runId === item.runId && + attempt.rootNodeId === item.nodeId && + attempt.status === "superseded", + ); +} + +export function isOrchestrationV2TurnItemVisible(input: { + readonly item: TimelineTurnItem; + readonly runs: ReadonlyArray; + readonly attempts: ReadonlyArray; +}): boolean { + const { item } = input; + if ( + item.runId !== null && + input.runs.some((run) => run.id === item.runId && run.status === "rolled_back") + ) { + return false; + } + + return !isOrchestrationV2SupersededInterrupt({ item, attempts: input.attempts }); +}