From eec8d541329b28949404c4822d8bfa4aa28150f2 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 3 Dec 2026 13:04:50 -0800 Subject: [PATCH] perf(server,client-runtime): [NBR] stream wire-only text deltas to cut active turn bytes by 80%+ --- .../transferBudgetV2.integration.test.ts | 1 + .../src/orchestration-v2/ThreadStream.test.ts | 671 +++++++++++++++++- .../src/orchestration-v2/ThreadStream.ts | 498 ++++++++++++- .../orchestration-v2/WireProjection.test.ts | 40 ++ .../src/orchestration-v2/WireProjection.ts | 11 + apps/server/src/ws.test.ts | 166 +++++ apps/server/src/ws.ts | 13 +- .../state/orchestrationV2Projection.test.ts | 279 +++++++- .../src/state/orchestrationV2Projection.ts | 190 +++++ .../src/state/threadDetail.test.ts | 69 +- .../src/state/threadStream.test.ts | 308 ++++++++ .../client-runtime/src/state/threadStream.ts | 18 +- packages/client-runtime/src/state/threads.ts | 217 ++++-- .../contracts/src/orchestrationV2.test.ts | 63 ++ packages/contracts/src/orchestrationV2.ts | 42 ++ 15 files changed, 2525 insertions(+), 61 deletions(-) create mode 100644 packages/client-runtime/src/state/threadStream.test.ts diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index b0881cd3b12a9..0d84f5de3cbd5 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -121,6 +121,7 @@ const CLIENT_THREAD_SUBSCRIPTION = { acceptCompactTurnItems: true, acceptCompactIds: true, acceptDedupedBodies: true, + acceptTextDeltas: true, } satisfies Required>; type ShellResumeField = "afterSequence" | "httpSnapshotFallback" | "knownProjectIdentities"; const CLIENT_SHELL_SUBSCRIPTION = { diff --git a/apps/server/src/orchestration-v2/ThreadStream.test.ts b/apps/server/src/orchestration-v2/ThreadStream.test.ts index 5c9fd310e93ae..7789f2e9b6a20 100644 --- a/apps/server/src/orchestration-v2/ThreadStream.test.ts +++ b/apps/server/src/orchestration-v2/ThreadStream.test.ts @@ -2,21 +2,35 @@ import { ContextHandoffId, ContextTransferId, EventId, + MessageId, + NodeId, OrchestrationV2ThreadStreamItem, + PlanId, + ProjectId, + ProviderInstanceId, ProviderThreadId, RunId, ThreadId, TurnItemId, type OrchestrationV2ContextHandoff, + type OrchestrationV2ConversationMessage, + type OrchestrationV2DomainEvent, + type OrchestrationV2PlanArtifact, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; +import { + applyOrchestrationV2ProjectionEvent, + applyOrchestrationV2ThreadTextDelta, +} from "../../../../packages/client-runtime/src/state/orchestrationV2Projection.ts"; import { buildBoundedThreadStreamSnapshot, decideThreadResume, @@ -25,8 +39,9 @@ import { THREAD_RESUME_MAX_RAW_PAYLOAD_BYTES, THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, THREAD_RESUME_MAX_REPLAY_EVENTS, + withLiveTextDeltas, } from "./ThreadStream.ts"; -import { projectDomainEventForWire } from "./WireProjection.ts"; +import { makeLiveBodyDeduper, projectDomainEventForWire } from "./WireProjection.ts"; const NOW = DateTime.makeUnsafe("2026-09-08T00:00:00.000Z"); const THREAD_ID = ThreadId.make("thread-stream-test"); @@ -309,3 +324,655 @@ describe("compact bounded snapshots", () => { expect(boundedSnapshotProjection(decodedCompact)).toEqual(decodedFull.projection); }); }); + +describe("withLiveTextDeltas", () => { + const codec = Schema.toCodecJson(OrchestrationV2ThreadStreamItem); + const encodeStreamItem = Schema.encodeSync(codec); + const decodeStreamItem = Schema.decodeUnknownSync(codec); + const RUN_ID = RunId.make("run-delta-test"); + const NODE_ID = NodeId.make("node-delta-test"); + const MESSAGE_ID = MessageId.make("msg-delta-test"); + const REPLY_ITEM_ID = TurnItemId.make("item-reply-delta-test"); + const REASONING_ITEM_ID = TurnItemId.make("item-reasoning-delta-test"); + const TOOL_ITEM_ID = TurnItemId.make("item-tool-delta-test"); + const PLAN_ID = PlanId.make("plan-delta-test"); + const PLAN_ITEM_ID = TurnItemId.make("item-plan-delta-test"); + + const atMs = (offsetMs: number) => DateTime.makeUnsafe(DateTime.toEpochMillis(NOW) + offsetMs); + + const messagePayload = ( + text: string, + options: { + readonly id?: MessageId; + readonly streaming?: boolean; + readonly updatedAt?: DateTime.Utc; + readonly attachments?: OrchestrationV2ConversationMessage["attachments"]; + } = {}, + ): OrchestrationV2ConversationMessage => ({ + id: options.id ?? MESSAGE_ID, + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + role: "assistant", + text, + attachments: options.attachments ?? [], + streaming: options.streaming ?? true, + createdBy: "agent", + creationSource: "provider", + createdAt: NOW, + updatedAt: options.updatedAt ?? NOW, + }); + + const replyItemPayload = ( + text: string, + options: { + readonly id?: TurnItemId; + readonly messageId?: MessageId; + readonly streaming?: boolean; + readonly status?: OrchestrationV2TurnItem["status"]; + readonly updatedAt?: DateTime.Utc; + readonly completedAt?: DateTime.Utc | null; + readonly phase?: "commentary" | "partial_answer" | "final_answer"; + readonly ordinal?: number; + } = {}, + ): OrchestrationV2TurnItem => ({ + id: options.id ?? REPLY_ITEM_ID, + type: "assistant_message", + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: options.ordinal ?? 3, + status: options.status ?? "running", + title: null, + startedAt: NOW, + completedAt: options.completedAt ?? null, + updatedAt: options.updatedAt ?? NOW, + messageId: options.messageId ?? MESSAGE_ID, + text, + streaming: options.streaming ?? true, + ...(options.phase === undefined ? {} : { phase: options.phase }), + }); + + const reasoningItemPayload = ( + text: string, + options: { + readonly id?: TurnItemId; + readonly streaming?: boolean; + readonly status?: OrchestrationV2TurnItem["status"]; + readonly updatedAt?: DateTime.Utc; + readonly completedAt?: DateTime.Utc | null; + readonly ordinal?: number; + } = {}, + ): OrchestrationV2TurnItem => ({ + id: options.id ?? REASONING_ITEM_ID, + type: "reasoning", + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: options.ordinal ?? 1, + status: options.status ?? "running", + title: null, + startedAt: NOW, + completedAt: options.completedAt ?? null, + updatedAt: options.updatedAt ?? NOW, + text, + streaming: options.streaming ?? true, + }); + + const planPayload = ( + markdown: string, + status: OrchestrationV2PlanArtifact["status"] = "draft", + ): OrchestrationV2PlanArtifact => ({ + id: PLAN_ID, + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + status, + kind: "proposed_plan", + markdown, + }); + + const planItemPayload = ( + markdown: string, + options: { + readonly streaming?: boolean; + readonly status?: OrchestrationV2TurnItem["status"]; + readonly updatedAt?: DateTime.Utc; + readonly completedAt?: DateTime.Utc | null; + } = {}, + ): OrchestrationV2TurnItem => ({ + id: PLAN_ITEM_ID, + type: "proposed_plan", + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 4, + status: options.status ?? "running", + title: null, + startedAt: NOW, + completedAt: options.completedAt ?? null, + updatedAt: options.updatedAt ?? NOW, + planId: PLAN_ID, + markdown, + streaming: options.streaming ?? true, + }); + + const eventItem = ( + sequence: number, + event: Omit & { + readonly occurredAt?: DateTime.Utc; + }, + ): Extract => ({ + kind: "event", + sequence, + event: { + id: EventId.make(`event-${sequence}`), + threadId: THREAD_ID, + occurredAt: event.occurredAt ?? NOW, + ...event, + } as OrchestrationV2DomainEvent, + }); + + const chunkedStream = ( + batches: ReadonlyArray>, + ): Stream.Stream => + batches.reduce>( + (acc, batch) => Stream.concat(acc, Stream.fromIterable(batch)), + Stream.empty, + ); + + const wireRoundTrip = (items: ReadonlyArray) => { + let bytes = 0; + const decoded: Array = []; + for (const item of items) { + const json = JSON.stringify(encodeStreamItem(item)); + bytes += Buffer.byteLength(json, "utf8"); + decoded.push(decodeStreamItem(JSON.parse(json))); + } + return { decoded, bytes }; + }; + + const applyWireStream = ( + initial: OrchestrationV2ThreadProjection, + items: ReadonlyArray, + ): OrchestrationV2ThreadProjection => { + let projection = initial; + for (const item of items) { + if (item.kind === "snapshot") { + projection = boundedSnapshotProjection(item); + continue; + } + if (item.kind === "event") { + const next = applyOrchestrationV2ProjectionEvent(projection, item.event); + if (next === null) throw new Error("Unexpected null event projection"); + projection = next; + continue; + } + if (item.kind === "text-delta") { + const next = applyOrchestrationV2ThreadTextDelta(projection, item); + if (next === null) { + throw new Error(`Unexpected text-delta mismatch at sequence ${item.sequence}`); + } + projection = next; + } + } + return projection; + }; + + const emptyProjection = (): OrchestrationV2ThreadProjection => { + const providerInstanceId = ProviderInstanceId.make("codex"); + return { + thread: { + id: THREAD_ID, + projectId: ProjectId.make("project-stream-test"), + title: "Thread stream test", + providerInstanceId, + modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: THREAD_ID, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: NOW, + updatedAt: NOW, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: NOW, + }; + }; + + it.effect( + "cuts streaming turn bytes by >=80% while matching full-event client state exactly", + () => + Effect.gen(function* () { + const initial = emptyProjection(); + const batches: Array> = []; + let sequence = 1; + + // 15 chunks of streaming reasoning (~1.4 KB). + let reasoningText = ""; + for (let index = 0; index < 15; index += 1) { + const chunk = `Reasoning step ${index}: inspecting module boundaries and streaming delta invariants.\n`; + reasoningText += chunk; + const done = index === 14; + const at = atMs(index * 50); + batches.push([ + eventItem(sequence++, { + type: "turn-item.updated", + occurredAt: at, + payload: reasoningItemPayload(reasoningText, { + streaming: !done, + status: done ? "completed" : "running", + completedAt: done ? at : null, + updatedAt: at, + }), + }), + ]); + } + + // Interleaved tool call between reasoning and assistant reply. + const toolAt = atMs(800); + batches.push([ + eventItem(sequence++, { + type: "turn-item.updated", + occurredAt: toolAt, + payload: { + id: TOOL_ITEM_ID, + type: "command_execution", + threadId: THREAD_ID, + runId: RUN_ID, + nodeId: NODE_ID, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed", + title: "Check tests", + input: "vp test run", + exitCode: 0, + startedAt: toolAt, + completedAt: toolAt, + updatedAt: toolAt, + }, + }), + ]); + + // 50 chunks of paired assistant message + turn-item (>10 KB). + let replyText = ""; + for (let index = 0; index < 50; index += 1) { + const chunk = + `Paragraph ${index}: streaming incremental text deltas eliminates quadratic prefix ` + + `retransmissions across every coalesced frame and fuses mirrored assistant records ` + + `into one compact wire update without touching persistence.\n`; + replyText += chunk; + const done = index === 49; + const at = atMs(1_000 + index * 50); + batches.push([ + eventItem(sequence++, { + type: "message.updated", + occurredAt: at, + payload: messagePayload(replyText, { streaming: !done, updatedAt: at }), + }), + eventItem(sequence++, { + type: "turn-item.updated", + occurredAt: at, + payload: replyItemPayload(replyText, { + streaming: !done, + status: done ? "completed" : "running", + completedAt: done ? at : null, + updatedAt: at, + }), + }), + ]); + } + + // 10 chunks of paired proposed_plan updates, ending with status transition. + let planText = ""; + for (let index = 0; index < 10; index += 1) { + planText += `- Step ${index}: verify contract codec, server encoder, and client reducer alignment.\n`; + const done = index === 9; + const at = atMs(4_000 + index * 50); + batches.push([ + eventItem(sequence++, { + type: "plan.updated", + occurredAt: at, + payload: planPayload(planText, done ? "active" : "draft"), + }), + eventItem(sequence++, { + type: "turn-item.updated", + occurredAt: at, + payload: planItemPayload(planText, { + streaming: !done, + status: done ? "completed" : "running", + completedAt: done ? at : null, + updatedAt: at, + }), + }), + ]); + } + + expect(Buffer.byteLength(replyText, "utf8")).toBeGreaterThan(10_000); + expect(Buffer.byteLength(replyText + reasoningText + planText, "utf8")).toBeGreaterThan( + 12_000, + ); + + const legacyStream = chunkedStream(batches).pipe(Stream.map(makeLiveBodyDeduper())); + const deltaStream = chunkedStream(batches).pipe( + withLiveTextDeltas, + Stream.map(makeLiveBodyDeduper()), + ); + + const [legacyItems, deltaItems] = yield* Effect.all([ + Stream.runCollect(legacyStream), + Stream.runCollect(deltaStream), + ]); + + const legacyWire = wireRoundTrip(legacyItems); + const deltaWire = wireRoundTrip(deltaItems); + + const legacyProjection = applyWireStream(initial, legacyWire.decoded); + const deltaProjection = applyWireStream(initial, deltaWire.decoded); + + expect(deltaProjection).toEqual(legacyProjection); + expect(deltaWire.decoded.some((item) => item.kind === "text-delta")).toBe(true); + expect(legacyWire.decoded.every((item) => item.kind === "event")).toBe(true); + expect(deltaItems.length).toBeLessThan(legacyItems.length); + + const reduction = 1 - deltaWire.bytes / legacyWire.bytes; + expect(reduction).toBeGreaterThanOrEqual(0.8); + }), + ); + + it.effect( + "falls back cleanly on non-prefix edits, metadata changes, and non-completed terminal statuses", + () => + Effect.gen(function* () { + const initial = emptyProjection(); + const t1 = atMs(50); + const t2 = atMs(100); + const t3 = atMs(150); + const t4 = atMs(200); + const t5 = atMs(250); + const batches: Array> = [ + // Initial chunk. + [ + eventItem(1, { + type: "message.updated", + occurredAt: NOW, + payload: messagePayload("Hello"), + }), + eventItem(2, { + type: "turn-item.updated", + occurredAt: NOW, + payload: replyItemPayload("Hello", { phase: "commentary" }), + }), + ], + // Non-prefix rewrite (e.g. provider corrected earlier text). + [ + eventItem(3, { + type: "message.updated", + occurredAt: t1, + payload: messagePayload("Hi there", { updatedAt: t1 }), + }), + eventItem(4, { + type: "turn-item.updated", + occurredAt: t1, + payload: replyItemPayload("Hi there", { phase: "commentary", updatedAt: t1 }), + }), + ], + // Normal append resumes delta encoding after fallback, with distinct message/item timestamps. + [ + eventItem(5, { + type: "message.updated", + occurredAt: t2, + payload: messagePayload("Hi there!", { updatedAt: t1 }), + }), + eventItem(6, { + type: "turn-item.updated", + occurredAt: t3, + payload: replyItemPayload("Hi there!", { phase: "commentary", updatedAt: t2 }), + }), + ], + // Phase metadata change on turn-item forces turn-item fallback while message still deltas. + [ + eventItem(7, { + type: "message.updated", + occurredAt: t4, + payload: messagePayload("Hi there! More", { updatedAt: t4 }), + }), + eventItem(8, { + type: "turn-item.updated", + occurredAt: t4, + payload: replyItemPayload("Hi there! More", { phase: "final_answer", updatedAt: t4 }), + }), + ], + // Terminal interrupted status: message completes via done:true, turn-item falls back with deduped text. + [ + eventItem(9, { + type: "message.updated", + occurredAt: t5, + payload: messagePayload("Hi there! More", { streaming: false, updatedAt: t5 }), + }), + eventItem(10, { + type: "turn-item.updated", + occurredAt: t5, + payload: replyItemPayload("Hi there! More", { + phase: "final_answer", + streaming: false, + status: "interrupted", + completedAt: t5, + updatedAt: t5, + }), + }), + ], + ]; + + const [legacyItems, deltaItems] = yield* Effect.all([ + Stream.runCollect(chunkedStream(batches).pipe(Stream.map(makeLiveBodyDeduper()))), + Stream.runCollect( + chunkedStream(batches).pipe(withLiveTextDeltas, Stream.map(makeLiveBodyDeduper())), + ), + ]); + + const legacyWire = wireRoundTrip(legacyItems); + const deltaWire = wireRoundTrip(deltaItems); + expect(applyWireStream(initial, deltaWire.decoded)).toEqual( + applyWireStream(initial, legacyWire.decoded), + ); + + // Seq 3-4 fell back to full events; seq 5-6 fused into one text-delta; seq 9 used done:true; + // seq 10 fell back to a deduped full turn-item event. + expect( + deltaItems.map((item) => [item.kind, "sequence" in item ? item.sequence : null]), + ).toEqual([ + ["event", 1], + ["event", 2], + ["event", 3], + ["event", 4], + ["text-delta", 6], + ["text-delta", 7], + ["event", 8], + ["text-delta", 9], + ["event", 10], + ]); + const finalTurnItem = deltaItems.at(-1); + expect( + finalTurnItem?.kind === "event" && + finalTurnItem.event.type === "turn-item.updated" && + finalTurnItem.event.payload.type === "assistant_message" + ? finalTurnItem.event.payload.textOmitted + : undefined, + ).toBe(true); + }), + ); + + it.effect( + "seeds from compacted snapshots and resets tracked state across replacement snapshots", + () => + Effect.gen(function* () { + const initialMessage = messagePayload("Start", { streaming: true }); + const initialReply = replyItemPayload("Start", { streaming: true, ordinal: 1 }); + const initialReasoning = reasoningItemPayload("Step 1", { streaming: true, ordinal: 2 }); + const baseProjection: OrchestrationV2ThreadProjection = { + ...emptyProjection(), + messages: [initialMessage], + turnItems: [initialReply, initialReasoning], + visibleTurnItems: [initialReply, initialReasoning].map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: THREAD_ID, + sourceItemId: item.id, + item, + })), + }; + const firstSnapshot = buildBoundedThreadStreamSnapshot({ + snapshotSequence: 10, + projection: baseProjection, + compactTurnItems: true, + dedupeBodies: true, + compactIds: true, + }); + const resetSnapshot = buildBoundedThreadStreamSnapshot({ + snapshotSequence: 20, + projection: emptyProjection(), + compactTurnItems: true, + dedupeBodies: true, + compactIds: true, + }); + const t1 = atMs(50); + const t2 = atMs(100); + const batches: Array> = [ + [firstSnapshot], + [ + eventItem(11, { + type: "message.updated", + occurredAt: t1, + payload: messagePayload("Start + more", { updatedAt: t1 }), + }), + eventItem(12, { + type: "turn-item.updated", + occurredAt: t1, + payload: replyItemPayload("Start + more", { ordinal: 1, updatedAt: t1 }), + }), + ], + [ + eventItem(13, { + type: "turn-item.updated", + occurredAt: t1, + payload: reasoningItemPayload("Step 1 -> Step 2", { ordinal: 2, updatedAt: t1 }), + }), + ], + [resetSnapshot], + // After reset snapshot clears the tracker, same entity ids must ship full, never delta. + [ + eventItem(21, { + type: "message.updated", + occurredAt: t2, + payload: messagePayload("Start + more + after reset", { updatedAt: t2 }), + }), + ], + ]; + + const [legacyItems, deltaItems] = yield* Effect.all([ + Stream.runCollect(chunkedStream(batches).pipe(Stream.map(makeLiveBodyDeduper()))), + Stream.runCollect( + chunkedStream(batches).pipe(withLiveTextDeltas, Stream.map(makeLiveBodyDeduper())), + ), + ]); + + const legacyWire = wireRoundTrip(legacyItems); + const deltaWire = wireRoundTrip(deltaItems); + expect(applyWireStream(emptyProjection(), deltaWire.decoded)).toEqual( + applyWireStream(emptyProjection(), legacyWire.decoded), + ); + expect(deltaItems.map((item) => item.kind)).toEqual([ + "snapshot", + "text-delta", + "text-delta", + "snapshot", + "event", + ]); + }), + ); + + it.effect("evicts old streaming entries once bounded memory is exceeded", () => + Effect.gen(function* () { + const batches: Array> = []; + let sequence = 1; + for (let index = 0; index < 36; index += 1) { + batches.push([ + eventItem(sequence++, { + type: "turn-item.updated", + payload: reasoningItemPayload(`item-${index}`, { + id: TurnItemId.make(`reasoning-${index}`), + ordinal: index + 1, + }), + }), + ]); + } + // Item 0 was evicted from the 32-entry LRU -> must fall back to full event. + // Item 35 is still in the LRU -> emits text-delta. + batches.push([ + eventItem(sequence++, { + type: "turn-item.updated", + payload: reasoningItemPayload("item-0 appended", { + id: TurnItemId.make("reasoning-0"), + ordinal: 1, + }), + }), + eventItem(sequence++, { + type: "turn-item.updated", + payload: reasoningItemPayload("item-35 appended", { + id: TurnItemId.make("reasoning-35"), + ordinal: 36, + }), + }), + ]); + + const items = yield* Stream.runCollect(chunkedStream(batches).pipe(withLiveTextDeltas)); + const tail = items.slice(-2); + expect(tail.map((item) => item.kind)).toEqual(["event", "text-delta"]); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ThreadStream.ts b/apps/server/src/orchestration-v2/ThreadStream.ts index c16a1b9e095aa..d35e8703da12e 100644 --- a/apps/server/src/orchestration-v2/ThreadStream.ts +++ b/apps/server/src/orchestration-v2/ThreadStream.ts @@ -1,7 +1,19 @@ -import type { - OrchestrationV2ThreadProjection, - OrchestrationV2ThreadStreamItem, +import { + OrchestrationV2ConversationMessage, + OrchestrationV2PlanArtifact, + OrchestrationV2TurnItem, + type MessageId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadStreamItem, + type OrchestrationV2ThreadTextDelta, + type PlanId, + type TurnItemId, } from "@t3tools/contracts"; +import type * as Arr from "effect/Array"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as Stream from "effect/Stream"; import { omitLocalVisibleTurnItems } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; import { dedupeSnapshotBodies } from "@t3tools/shared/orchestrationV2DedupedBodies"; @@ -116,3 +128,483 @@ export function decideThreadResume(input: { throughSequence: input.highWater, }; } + +const LIVE_TEXT_DELTA_MEMORY = 32; + +const sameConversationMessage = Schema.toEquivalence(OrchestrationV2ConversationMessage); +const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem); +const samePlanArtifact = Schema.toEquivalence(OrchestrationV2PlanArtifact); + +type StreamableTextTurnItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "assistant_message" | "reasoning" | "proposed_plan" } +>; +type StreamableProposedPlan = Extract< + OrchestrationV2PlanArtifact, + { readonly kind: "proposed_plan" } +>; +type ThreadEventStreamItem = Extract; + +function rememberBounded(memory: Map, key: K, value: V): void { + memory.delete(key); + memory.set(key, value); + if (memory.size > LIVE_TEXT_DELTA_MEMORY) { + memory.delete(memory.keys().next().value as K); + } +} + +function sameInstant(left: DateTime.Utc, right: DateTime.Utc): boolean { + return DateTime.toEpochMillis(left) === DateTime.toEpochMillis(right); +} + +function sameNullableInstant(left: DateTime.Utc | null, right: DateTime.Utc | null): boolean { + return left === right || (left !== null && right !== null && sameInstant(left, right)); +} + +function isStreamableTextTurnItem(item: OrchestrationV2TurnItem): item is StreamableTextTurnItem { + return ( + item.type === "assistant_message" || item.type === "reasoning" || item.type === "proposed_plan" + ); +} + +function isStreamableProposedPlan( + plan: OrchestrationV2PlanArtifact, +): plan is StreamableProposedPlan { + return plan.kind === "proposed_plan" && (plan.status === "draft" || plan.status === "active"); +} + +function turnItemText(item: StreamableTextTurnItem): string { + return item.type === "proposed_plan" ? item.markdown : item.text; +} + +function sameTurnItemExceptStreamingFields( + previous: StreamableTextTurnItem, + next: StreamableTextTurnItem, +): boolean { + if (previous.type !== next.type || Object.keys(previous).length !== Object.keys(next).length) { + return false; + } + if (previous.type === "proposed_plan" && next.type === "proposed_plan") { + return sameTurnItem( + { + ...previous, + markdown: "", + updatedAt: previous.updatedAt, + streaming: next.streaming, + status: next.status, + completedAt: next.completedAt, + }, + { ...next, markdown: "", updatedAt: previous.updatedAt }, + ); + } + if (previous.type === "assistant_message" && next.type === "assistant_message") { + return sameTurnItem( + { + ...previous, + text: "", + updatedAt: previous.updatedAt, + streaming: next.streaming, + status: next.status, + completedAt: next.completedAt, + }, + { ...next, text: "", updatedAt: previous.updatedAt }, + ); + } + if (previous.type === "reasoning" && next.type === "reasoning") { + return sameTurnItem( + { + ...previous, + text: "", + updatedAt: previous.updatedAt, + streaming: next.streaming, + status: next.status, + completedAt: next.completedAt, + }, + { ...next, text: "", updatedAt: previous.updatedAt }, + ); + } + return false; +} + +function matchMessageDelta( + previous: OrchestrationV2ConversationMessage | undefined, + item: ThreadEventStreamItem & { + readonly event: Extract; + }, +) { + const next = item.event.payload; + if ( + previous === undefined || + !previous.streaming || + previous.id !== next.id || + previous.role !== next.role || + next.text.length < previous.text.length || + !next.text.startsWith(previous.text) || + Object.keys(previous).length !== Object.keys(next).length || + !sameConversationMessage( + { ...previous, text: "", updatedAt: previous.updatedAt, streaming: next.streaming }, + { ...next, text: "", updatedAt: previous.updatedAt }, + ) + ) { + return null; + } + return { + offset: previous.text.length, + chunk: next.text.slice(previous.text.length), + done: !next.streaming, + occurredAt: item.event.occurredAt, + updatedAt: next.updatedAt, + next, + } as const; +} + +function matchTurnItemDelta( + previous: StreamableTextTurnItem | undefined, + item: ThreadEventStreamItem & { + readonly event: Extract; + }, +) { + const next = item.event.payload; + if ( + previous === undefined || + !isStreamableTextTurnItem(next) || + previous.type !== next.type || + !previous.streaming || + previous.status !== "running" || + (next.type === "assistant_message" && next.textOmitted === true) + ) { + return null; + } + let done = false; + if (next.streaming) { + if (next.status !== "running" || !sameNullableInstant(next.completedAt, previous.completedAt)) { + return null; + } + } else { + if ( + next.status !== "completed" || + next.completedAt === null || + !sameInstant(next.completedAt, next.updatedAt) + ) { + return null; + } + done = true; + } + const previousText = turnItemText(previous); + const nextText = turnItemText(next); + if ( + nextText.length < previousText.length || + !nextText.startsWith(previousText) || + !sameTurnItemExceptStreamingFields(previous, next) + ) { + return null; + } + return { + offset: previousText.length, + chunk: nextText.slice(previousText.length), + done, + occurredAt: item.event.occurredAt, + updatedAt: next.updatedAt, + next, + } as const; +} + +function matchPlanDelta( + previous: StreamableProposedPlan | undefined, + item: ThreadEventStreamItem & { + readonly event: Extract; + }, +) { + const next = item.event.payload; + if ( + previous === undefined || + !isStreamableProposedPlan(next) || + previous.status !== next.status || + next.markdown.length < previous.markdown.length || + !next.markdown.startsWith(previous.markdown) || + Object.keys(previous).length !== Object.keys(next).length || + !samePlanArtifact({ ...previous, markdown: "" }, { ...next, markdown: "" }) + ) { + return null; + } + return { + offset: previous.markdown.length, + chunk: next.markdown.slice(previous.markdown.length), + occurredAt: item.event.occurredAt, + next, + } as const; +} + +function makeLiveTextDeltaBatchEncoder(): ( + items: Arr.NonEmptyReadonlyArray, +) => Arr.NonEmptyReadonlyArray { + const messages = new Map(); + const turnItems = new Map(); + const plans = new Map(); + + const clear = () => { + messages.clear(); + turnItems.clear(); + plans.clear(); + }; + + const recordMessage = (message: OrchestrationV2ConversationMessage) => { + if (message.streaming) rememberBounded(messages, message.id, message); + else messages.delete(message.id); + }; + + const recordTurnItem = (turnItem: OrchestrationV2TurnItem) => { + if ( + isStreamableTextTurnItem(turnItem) && + turnItem.streaming && + turnItem.status === "running" && + !(turnItem.type === "assistant_message" && turnItem.textOmitted === true) + ) { + rememberBounded(turnItems, turnItem.id, turnItem); + return; + } + turnItems.delete(turnItem.id); + }; + + const recordPlan = (plan: OrchestrationV2PlanArtifact) => { + if (isStreamableProposedPlan(plan)) rememberBounded(plans, plan.id, plan); + else plans.delete(plan.id); + }; + + const seedFromSnapshot = (snapshot: ThreadSnapshotStreamItem) => { + clear(); + const messageTextById = new Map( + snapshot.projection.messages.map((message) => [message.id, message.text] as const), + ); + for (const message of snapshot.projection.messages) { + if (message.streaming) rememberBounded(messages, message.id, message); + } + for (const plan of snapshot.projection.plans) { + if (isStreamableProposedPlan(plan)) rememberBounded(plans, plan.id, plan); + } + // Snapshots can omit local visible turnItems and blank mirrored message text; mirror what the client restores. + const seedTurnItem = (turnItem: OrchestrationV2TurnItem) => { + if ( + !isStreamableTextTurnItem(turnItem) || + !turnItem.streaming || + turnItem.status !== "running" + ) { + return; + } + if (turnItem.type === "assistant_message" && turnItem.textOmitted === true) { + const restoredText = messageTextById.get(turnItem.messageId); + if (restoredText === undefined) return; + const { textOmitted: _textOmitted, ...rest } = turnItem; + rememberBounded(turnItems, turnItem.id, { ...rest, text: restoredText }); + return; + } + rememberBounded(turnItems, turnItem.id, turnItem); + }; + for (const turnItem of snapshot.projection.turnItems) seedTurnItem(turnItem); + if (snapshot.turnItemsOmitLocalVisible === true) { + for (const row of snapshot.projection.visibleTurnItems) { + if (row.visibility === "local" || row.sourceThreadId === snapshot.projection.thread.id) { + seedTurnItem(row.item); + } + } + } + }; + + return (items) => { + const out: Array = []; + for (let index = 0; index < items.length; index += 1) { + const item = items[index]!; + if (item.kind === "snapshot") { + seedFromSnapshot(item); + out.push(item); + continue; + } + if (item.kind !== "event") { + out.push(item); + continue; + } + const { event } = item; + if (event.type === "thread.deleted") { + clear(); + out.push(item); + continue; + } + if (event.type === "message.updated") { + const matched = matchMessageDelta(messages.get(event.payload.id), { ...item, event }); + if (matched === null) { + recordMessage(event.payload); + out.push(item); + continue; + } + const nextItem = items[index + 1]; + if ( + nextItem !== undefined && + nextItem.kind === "event" && + nextItem.event.type === "turn-item.updated" && + nextItem.event.threadId === event.threadId && + nextItem.sequence >= item.sequence && + nextItem.event.payload.type === "assistant_message" && + nextItem.event.payload.messageId === event.payload.id + ) { + const mirror = matchTurnItemDelta(turnItems.get(nextItem.event.payload.id), { + ...nextItem, + event: nextItem.event, + }); + if ( + mirror !== null && + mirror.offset === matched.offset && + mirror.chunk === matched.chunk && + mirror.done === matched.done + ) { + recordMessage(matched.next); + recordTurnItem(mirror.next); + const occurredAt = mirror.occurredAt; + const delta: OrchestrationV2ThreadTextDelta = { + kind: "text-delta", + sequence: nextItem.sequence, + target: "message", + id: matched.next.id, + mirrorItemId: mirror.next.id, + offset: matched.offset, + chunk: matched.chunk, + occurredAt, + ...(sameInstant(matched.updatedAt, occurredAt) + ? {} + : { updatedAt: matched.updatedAt }), + ...(sameInstant(mirror.updatedAt, matched.updatedAt) + ? {} + : { mirrorUpdatedAt: mirror.updatedAt }), + ...(matched.done ? { done: true as const } : {}), + }; + out.push(delta); + index += 1; + continue; + } + } + recordMessage(matched.next); + const delta: OrchestrationV2ThreadTextDelta = { + kind: "text-delta", + sequence: item.sequence, + target: "message", + id: matched.next.id, + offset: matched.offset, + chunk: matched.chunk, + occurredAt: matched.occurredAt, + ...(sameInstant(matched.updatedAt, matched.occurredAt) + ? {} + : { updatedAt: matched.updatedAt }), + ...(matched.done ? { done: true as const } : {}), + }; + out.push(delta); + continue; + } + if (event.type === "plan.updated") { + const matched = matchPlanDelta(plans.get(event.payload.id), { ...item, event }); + if (matched === null) { + recordPlan(event.payload); + out.push(item); + continue; + } + const nextItem = items[index + 1]; + if ( + nextItem !== undefined && + nextItem.kind === "event" && + nextItem.event.type === "turn-item.updated" && + nextItem.event.threadId === event.threadId && + nextItem.sequence >= item.sequence && + nextItem.event.payload.type === "proposed_plan" && + nextItem.event.payload.planId === event.payload.id + ) { + const mirror = matchTurnItemDelta(turnItems.get(nextItem.event.payload.id), { + ...nextItem, + event: nextItem.event, + }); + if ( + mirror !== null && + !mirror.done && + mirror.offset === matched.offset && + mirror.chunk === matched.chunk + ) { + recordPlan(matched.next); + recordTurnItem(mirror.next); + const occurredAt = mirror.occurredAt; + const delta: OrchestrationV2ThreadTextDelta = { + kind: "text-delta", + sequence: nextItem.sequence, + target: "plan", + id: matched.next.id, + mirrorItemId: mirror.next.id, + offset: matched.offset, + chunk: matched.chunk, + occurredAt, + ...(sameInstant(mirror.updatedAt, occurredAt) + ? {} + : { mirrorUpdatedAt: mirror.updatedAt }), + }; + out.push(delta); + index += 1; + continue; + } + } + recordPlan(matched.next); + const delta: OrchestrationV2ThreadTextDelta = { + kind: "text-delta", + sequence: item.sequence, + target: "plan", + id: matched.next.id, + offset: matched.offset, + chunk: matched.chunk, + occurredAt: matched.occurredAt, + }; + out.push(delta); + continue; + } + if (event.type === "turn-item.updated") { + const matched = matchTurnItemDelta(turnItems.get(event.payload.id), { ...item, event }); + if (matched === null) { + recordTurnItem(event.payload); + out.push(item); + continue; + } + recordTurnItem(matched.next); + const delta: OrchestrationV2ThreadTextDelta = { + kind: "text-delta", + sequence: item.sequence, + target: "turn-item", + id: matched.next.id, + offset: matched.offset, + chunk: matched.chunk, + occurredAt: matched.occurredAt, + ...(sameInstant(matched.updatedAt, matched.occurredAt) + ? {} + : { updatedAt: matched.updatedAt }), + ...(matched.done ? { done: true as const } : {}), + }; + out.push(delta); + continue; + } + out.push(item); + } + return isNonEmpty(out) ? out : items; + }; +} + +function isNonEmpty(items: ReadonlyArray): items is Arr.NonEmptyReadonlyArray { + return items.length > 0; +} + +/** + * Per-subscriber wire encoder: replaces append-only streaming text/reasoning/plan updates with + * compact `text-delta` items and fuses adjacent mirrored record+turn-item updates into one frame. + */ +export function withLiveTextDeltas( + stream: Stream.Stream, +): Stream.Stream { + return Stream.fromPull( + Effect.gen(function* () { + const pull = yield* Stream.toPull(stream); + const encodeBatch = makeLiveTextDeltaBatchEncoder(); + return Effect.map(pull, encodeBatch); + }), + ).pipe(Stream.scoped); +} diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts index d4d361beeae83..bd6f9144ace81 100644 --- a/apps/server/src/orchestration-v2/WireProjection.test.ts +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -578,4 +578,44 @@ describe("live body deduper", () => { const first = reply(1, "a"); expect([first, message(2, "a")].map(makeLiveBodyDeduper())[0]).toBe(first); }); + + it("tracks message text-deltas so a subsequent fallback reply still omits duplicated text", () => { + const dedupe = makeLiveBodyDeduper(); + const delta: OrchestrationV2ThreadStreamItem = { + kind: "text-delta", + sequence: 2, + target: "message", + id: messageId, + offset: 3, + chunk: "lo!", + occurredAt: at, + done: true, + }; + const fallbackReply = reply(3, "Hello!"); + const delivered = [message(1, "Hel"), delta, fallbackReply].map(dedupe); + + expect(delivered[1]).toBe(delta); + expect(payloadOf(delivered[2]!)).toEqual({ + ...fallbackReply.event.payload, + text: "", + textOmitted: true, + }); + }); + + it("forgets tracked message text if a text-delta offset mismatches", () => { + const dedupe = makeLiveBodyDeduper(); + const mismatched: OrchestrationV2ThreadStreamItem = { + kind: "text-delta", + sequence: 2, + target: "message", + id: messageId, + offset: 99, + chunk: "!", + occurredAt: at, + }; + const fallbackReply = reply(3, "Hel!"); + const delivered = [message(1, "Hel"), mismatched, fallbackReply].map(dedupe); + + expect(delivered[2]).toBe(fallbackReply); + }); }); diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts index 1689789fbd1cf..90fa66409893a 100644 --- a/apps/server/src/orchestration-v2/WireProjection.ts +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -413,6 +413,17 @@ export function makeLiveBodyDeduper(): ( for (const subagent of records) rememberSubagent(subagent); return item; } + if (item.kind === "text-delta") { + if (item.target === "message") { + const previous = messageText.get(item.id); + if (previous !== undefined && previous.length === item.offset) { + remember(messageText, item.id, `${previous}${item.chunk}`); + } else { + messageText.delete(item.id); + } + } + return item; + } if (item.kind !== "event") return item; const { event } = item; switch (event.type) { diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 274afacedee68..fc749487230fa 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -2594,6 +2594,172 @@ it.effect("thread resume replays a deleted thread's deletion and nothing recorde }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); +it.effect("subscribeOrchestrationV2Thread emits text-deltas only when opted in", () => + Effect.gen(function* () { + const now = DateTime.makeUnsafe("2026-10-13T00:00:00.000Z"); + const later = DateTime.makeUnsafe("2026-10-13T00:00:01.000Z"); + const threadId = ThreadId.make("thread:text-deltas-opt-in"); + const messageId = MessageId.make("message:text-deltas"); + const itemId = TurnItemId.make("item:text-deltas"); + const stored = ( + sequence: number, + event: Omit, + ): OrchestrationV2StoredEvent => ({ + sequence, + commandId: null, + event: { + id: EventId.make(`delta:${sequence}`), + threadId, + ...event, + } as OrchestrationV2DomainEvent, + }); + const makeMessage = (text: string, streaming: boolean, updatedAt: DateTime.Utc) => ({ + id: messageId, + threadId, + runId: null, + nodeId: null, + role: "assistant" as const, + text, + attachments: [], + streaming, + createdBy: "agent" as const, + creationSource: "provider" as const, + createdAt: now, + updatedAt, + }); + const makeReplyItem = (text: string, streaming: boolean, updatedAt: DateTime.Utc) => ({ + id: itemId, + type: "assistant_message" as const, + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: streaming ? ("running" as const) : ("completed" as const), + title: null, + startedAt: now, + completedAt: streaming ? null : updatedAt, + updatedAt, + messageId, + text, + streaming, + }); + const makeToolItem = (id: string, ordinal: number) => ({ + id: TurnItemId.make(id), + type: "command_execution" as const, + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title: "Check", + input: "pwd", + exitCode: 0, + startedAt: now, + completedAt: now, + updatedAt: now, + }); + const liveEvents: ReadonlyArray = [ + stored(1, { + type: "message.updated", + occurredAt: now, + payload: makeMessage("Hel", true, now), + }), + stored(2, { + type: "turn-item.updated", + occurredAt: now, + payload: makeReplyItem("Hel", true, now), + }), + // Non-coalescible completed tool flushes each streaming pair immediately without timers. + stored(3, { + type: "turn-item.updated", + occurredAt: now, + payload: makeToolItem("item:tool-1", 2), + }), + stored(4, { + type: "message.updated", + occurredAt: later, + payload: makeMessage("Hello", true, later), + }), + stored(5, { + type: "turn-item.updated", + occurredAt: later, + payload: makeReplyItem("Hello", true, later), + }), + stored(6, { + type: "turn-item.updated", + occurredAt: later, + payload: makeToolItem("item:tool-2", 3), + }), + stored(7, { + type: "message.updated", + occurredAt: later, + payload: makeMessage("Hello!", false, later), + }), + stored(8, { + type: "turn-item.updated", + occurredAt: later, + payload: makeReplyItem("Hello!", false, later), + }), + ]; + const collect = (acceptTextDeltas: boolean) => + subscribeOrchestrationV2Thread({ + threadId, + afterSequence: 0, + acceptDedupedBodies: true, + ...(acceptTextDeltas ? { acceptTextDeltas: true } : {}), + }).pipe( + Effect.flatMap(Stream.runCollect), + Effect.map((items) => Array.from(items)), + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + streamStoredEventsFrom: () => Stream.fromIterable(liveEvents), + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + ); + + const legacyItems = yield* collect(false); + const deltaItems = yield* collect(true); + + assert.isTrue(legacyItems.every((item) => item.kind === "event")); + assert.deepEqual( + deltaItems.map((item) => [item.kind, "sequence" in item ? item.sequence : null]), + [ + ["event", 1], + ["event", 2], + ["event", 3], + ["text-delta", 5], + ["event", 6], + ["text-delta", 8], + ], + ); + const fused = deltaItems[3]; + assert.equal(fused?.kind, "text-delta"); + if (fused?.kind === "text-delta" && fused.target === "message") { + assert.equal(fused.id, messageId); + assert.equal(fused.mirrorItemId, itemId); + assert.equal(fused.offset, 3); + assert.equal(fused.chunk, "lo"); + assert.equal(fused.done, undefined); + } + const doneFused = deltaItems[5]; + assert.equal(doneFused?.kind, "text-delta"); + if (doneFused?.kind === "text-delta" && doneFused.target === "message") { + assert.equal(doneFused.id, messageId); + assert.equal(doneFused.mirrorItemId, itemId); + assert.equal(doneFused.offset, 5); + assert.equal(doneFused.chunk, "!"); + assert.equal(doneFused.done, true); + } + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +); + // A prune pass can delete replayed rows after the boundary check; the read must not be trusted. it.effect.each(["thread", "shell"] as const)( "%s resume loads a snapshot when pruning advances during the replay read", diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 02b556e4ae4f9..741add2056fab 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -176,6 +176,7 @@ import { isThreadReplayRawPayloadSafe, threadReplayEncodedBytes, THREAD_RESUME_MAX_REPLAY_EVENTS, + withLiveTextDeltas, } from "./orchestration-v2/ThreadStream.ts"; import { buildBoundedThreadProjection, @@ -960,12 +961,18 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs readonly acceptCompactTurnItems?: boolean; readonly acceptDedupedBodies?: boolean; readonly acceptCompactIds?: boolean; + readonly acceptTextDeltas?: boolean; }) { const threadManagement = yield* ThreadManagementService.ThreadManagementService; const dedupeBodies = input.acceptDedupedBodies === true; - // Replay, snapshot, and live tail share one deduper: it must see every delivered record. - const withLiveDedupe = (stream: Stream.Stream) => - dedupeBodies ? Stream.suspend(() => Stream.map(stream, makeLiveBodyDeduper())) : stream; + const textDeltas = input.acceptTextDeltas === true; + // Replay, snapshot, and live tail share one encoder and deduper: each must see every delivered record. + const withLiveDedupe = (stream: Stream.Stream) => { + const withDeltas = textDeltas ? withLiveTextDeltas(stream) : stream; + return dedupeBodies + ? Stream.suspend(() => Stream.map(withDeltas, makeLiveBodyDeduper())) + : withDeltas; + }; const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; yield* Effect.annotateCurrentSpan({ diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index aeda4ab915d11..884b34150fa84 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -1,12 +1,15 @@ import { describe, expect, it } from "vite-plus/test"; import { type ThreadPullRequestLink, + type OrchestrationV2ConversationMessage, type OrchestrationV2DomainEvent, + type OrchestrationV2PlanArtifact, type OrchestrationV2Run, type OrchestrationV2ProviderThread, type OrchestrationV2ThreadProjection, type OrchestrationV2TurnItem, MessageId, + PlanId, ProjectId, ProviderInstanceId, NodeId, @@ -18,7 +21,11 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + applyOrchestrationV2ThreadTextDelta, + getProjectionArrayReplacementIndex, +} from "./orchestrationV2Projection.ts"; const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); const threadId = ThreadId.make("thread-reducer"); @@ -917,3 +924,273 @@ describe("provider-thread.updated", () => { ]); }); }); + +describe("applyOrchestrationV2ThreadTextDelta", () => { + const later = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"); + const laterStill = DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"); + const messageId = MessageId.make("msg-delta"); + const replyId = TurnItemId.make("item-reply-delta"); + const reasoningId = TurnItemId.make("item-reasoning-delta"); + const planId = PlanId.make("plan-delta"); + const planItemId = TurnItemId.make("item-plan-delta"); + + const streamingMessage: OrchestrationV2ConversationMessage = { + id: messageId, + threadId, + runId, + nodeId: null, + role: "assistant", + text: "Hel", + attachments: [], + streaming: true, + createdBy: "agent", + creationSource: "provider", + createdAt: now, + updatedAt: now, + }; + const streamingReply: OrchestrationV2TurnItem = { + id: replyId, + type: "assistant_message", + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + messageId, + text: "Hel", + streaming: true, + }; + const streamingReasoning: OrchestrationV2TurnItem = { + id: reasoningId, + type: "reasoning", + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + text: "Think", + streaming: true, + deferredWork: { cursor: "work-1", itemCount: 5, lastOrdinal: 2 }, + }; + const streamingPlan: OrchestrationV2PlanArtifact = { + id: planId, + threadId, + runId, + nodeId: NodeId.make("node-plan"), + status: "draft", + kind: "proposed_plan", + markdown: "# Plan", + }; + const streamingPlanItem: OrchestrationV2TurnItem = { + id: planItemId, + type: "proposed_plan", + threadId, + runId, + nodeId: NodeId.make("node-plan"), + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 3, + status: "running", + title: null, + startedAt: now, + completedAt: null, + updatedAt: now, + planId, + markdown: "# Plan", + streaming: true, + }; + + const baseProjection: OrchestrationV2ThreadProjection = { + ...emptyProjection, + runs: [{ ...run, status: "running", completedAt: null }], + messages: [streamingMessage], + plans: [streamingPlan], + turnItems: [streamingReply, streamingReasoning, streamingPlanItem], + visibleTurnItems: [streamingReply, streamingReasoning, streamingPlanItem].map( + (item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + }), + ), + }; + + it("applies fused message+reply deltas, preserves O(1) array replacement hints, and completes on done", () => { + const mid = applyOrchestrationV2ThreadTextDelta(baseProjection, { + kind: "text-delta", + sequence: 10, + target: "message", + id: messageId, + mirrorItemId: replyId, + offset: 3, + chunk: "lo", + occurredAt: later, + updatedAt: now, + mirrorUpdatedAt: later, + }); + expect(mid).not.toBeNull(); + expect(mid?.updatedAt).toEqual(later); + expect(mid?.messages[0]).toMatchObject({ text: "Hello", streaming: true, updatedAt: now }); + expect(mid?.turnItems[0]).toMatchObject({ + text: "Hello", + streaming: true, + status: "running", + completedAt: null, + updatedAt: later, + }); + expect(mid?.visibleTurnItems[0]?.item).toBe(mid?.turnItems[0]); + expect(getProjectionArrayReplacementIndex(baseProjection.messages, mid!.messages)).toBe(0); + expect(getProjectionArrayReplacementIndex(baseProjection.turnItems, mid!.turnItems)).toBe(0); + expect( + getProjectionArrayReplacementIndex(baseProjection.visibleTurnItems, mid!.visibleTurnItems), + ).toBe(0); + + const finished = applyOrchestrationV2ThreadTextDelta(mid, { + kind: "text-delta", + sequence: 11, + target: "message", + id: messageId, + mirrorItemId: replyId, + offset: 5, + chunk: "!", + occurredAt: laterStill, + done: true, + }); + expect(finished?.messages[0]).toMatchObject({ + text: "Hello!", + streaming: false, + updatedAt: laterStill, + }); + expect(finished?.turnItems[0]).toMatchObject({ + text: "Hello!", + streaming: false, + status: "completed", + completedAt: laterStill, + updatedAt: laterStill, + }); + }); + + it("applies reasoning turn-item deltas while retaining deferredWork, and fused plan deltas", () => { + const afterReasoning = applyOrchestrationV2ThreadTextDelta(baseProjection, { + kind: "text-delta", + sequence: 12, + target: "turn-item", + id: reasoningId, + offset: 5, + chunk: "ing...", + occurredAt: later, + done: true, + }); + expect(afterReasoning?.turnItems[1]).toMatchObject({ + text: "Thinking...", + streaming: false, + status: "completed", + completedAt: later, + deferredWork: streamingReasoning.deferredWork, + }); + + const afterPlan = applyOrchestrationV2ThreadTextDelta(afterReasoning, { + kind: "text-delta", + sequence: 13, + target: "plan", + id: planId, + mirrorItemId: planItemId, + offset: 6, + chunk: "\n1. Ship", + occurredAt: laterStill, + }); + expect(afterPlan?.plans[0]).toMatchObject({ markdown: "# Plan\n1. Ship" }); + expect(afterPlan?.turnItems[2]).toMatchObject({ + markdown: "# Plan\n1. Ship", + updatedAt: laterStill, + }); + }); + + it("returns null without mutating when base record, offset, type, or link mismatches", () => { + expect( + applyOrchestrationV2ThreadTextDelta(null, { + kind: "text-delta", + sequence: 1, + target: "message", + id: messageId, + offset: 0, + chunk: "x", + occurredAt: later, + }), + ).toBeNull(); + // Wrong offset + expect( + applyOrchestrationV2ThreadTextDelta(baseProjection, { + kind: "text-delta", + sequence: 2, + target: "message", + id: messageId, + offset: 99, + chunk: "!", + occurredAt: later, + }), + ).toBeNull(); + // Unknown entity id + expect( + applyOrchestrationV2ThreadTextDelta(baseProjection, { + kind: "text-delta", + sequence: 3, + target: "turn-item", + id: TurnItemId.make("missing"), + offset: 0, + chunk: "!", + occurredAt: later, + }), + ).toBeNull(); + // Mirrored item points to wrong item type (reasoning instead of assistant_message) + expect( + applyOrchestrationV2ThreadTextDelta(baseProjection, { + kind: "text-delta", + sequence: 4, + target: "message", + id: messageId, + mirrorItemId: reasoningId, + offset: 3, + chunk: "!", + occurredAt: later, + }), + ).toBeNull(); + // Non-streaming message refuses delta + const finishedProjection: OrchestrationV2ThreadProjection = { + ...baseProjection, + messages: [{ ...streamingMessage, streaming: false }], + }; + expect( + applyOrchestrationV2ThreadTextDelta(finishedProjection, { + kind: "text-delta", + sequence: 5, + target: "message", + id: messageId, + offset: 3, + chunk: "!", + occurredAt: later, + }), + ).toBeNull(); + expect(baseProjection.messages[0]?.text).toBe("Hel"); + }); +}); diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 96d35a999b5e9..7fea3d9da6b67 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -4,11 +4,16 @@ import { isQueuedProviderThreadPlaceholder, } from "@t3tools/contracts"; import type { + MessageId, OrchestrationV2DomainEvent, OrchestrationV2Run, OrchestrationV2ThreadProjection, + OrchestrationV2ThreadTextDelta, OrchestrationV2TurnItem, + PlanId, + TurnItemId, } from "@t3tools/contracts"; +import type * as DateTime from "effect/DateTime"; import { restoreSubagentBodies, restoreTurnItemBodies, @@ -499,3 +504,188 @@ export function applyOrchestrationV2ProjectionEvent( return { ...base, contextTransfers: upsertEntity(base.contextTransfers, event.payload) }; } } + +function applyTurnItemTextDelta( + projection: OrchestrationV2ThreadProjection, + input: { + readonly id: TurnItemId; + readonly expectedType: "any" | "assistant_message" | "proposed_plan"; + readonly expectedRecordId?: MessageId | PlanId; + readonly offset: number; + readonly chunk: string; + readonly occurredAt: DateTime.Utc; + readonly updatedAt: DateTime.Utc; + readonly done?: true; + }, + options?: ApplyOrchestrationV2ProjectionEventOptions, +): OrchestrationV2ThreadProjection | null { + let itemIndex = projection.turnItems.length - 1; + while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== input.id) { + itemIndex -= 1; + } + if (itemIndex === -1) return null; + const existing = projection.turnItems[itemIndex]!; + if ( + existing.type !== "assistant_message" && + existing.type !== "reasoning" && + existing.type !== "proposed_plan" + ) { + return null; + } + if (input.expectedType !== "any" && existing.type !== input.expectedType) { + return null; + } + if ( + input.expectedType === "assistant_message" && + existing.type === "assistant_message" && + existing.messageId !== input.expectedRecordId + ) { + return null; + } + if ( + input.expectedType === "proposed_plan" && + existing.type === "proposed_plan" && + existing.planId !== input.expectedRecordId + ) { + return null; + } + if (!existing.streaming || existing.status !== "running") return null; + + const previousText = existing.type === "proposed_plan" ? existing.markdown : existing.text; + if (previousText.length !== input.offset) return null; + + const nextText = `${previousText}${input.chunk}`; + const nextStatus = input.done === true ? ("completed" as const) : existing.status; + const nextStreaming = input.done === true ? false : existing.streaming; + const nextCompletedAt = input.done === true ? input.updatedAt : existing.completedAt; + const nextItem: OrchestrationV2TurnItem = + existing.type === "proposed_plan" + ? { + ...existing, + status: nextStatus, + streaming: nextStreaming, + completedAt: nextCompletedAt, + markdown: nextText, + updatedAt: input.updatedAt, + } + : { + ...existing, + status: nextStatus, + streaming: nextStreaming, + completedAt: nextCompletedAt, + text: nextText, + updatedAt: input.updatedAt, + }; + + const partialTimeline = options?.partialTimeline === true; + const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal; + const turnItems = replaceProjectionArrayItem(projection.turnItems, itemIndex, nextItem); + const next = { ...projection, updatedAt: input.occurredAt, turnItems }; + return { + ...next, + visibleTurnItems: shouldShowLocalTurnItem(next, nextItem) + ? upsertVisibleTurnItem(next, nextItem, partialTimeline, latestLocalTurnOrdinal) + : removeVisibleItem(next.visibleTurnItems, nextItem.id), + }; +} + +/** Returns null when the delta's base record or offset does not match so callers can resync. */ +export function applyOrchestrationV2ThreadTextDelta( + projection: OrchestrationV2ThreadProjection | null, + delta: OrchestrationV2ThreadTextDelta, + options?: ApplyOrchestrationV2ProjectionEventOptions, +): OrchestrationV2ThreadProjection | null { + if (projection === null) return null; + switch (delta.target) { + case "message": { + let messageIndex = projection.messages.length - 1; + while (messageIndex >= 0 && projection.messages[messageIndex]!.id !== delta.id) { + messageIndex -= 1; + } + if (messageIndex === -1) return null; + const existing = projection.messages[messageIndex]!; + if (!existing.streaming || existing.text.length !== delta.offset) return null; + const messageUpdatedAt = delta.updatedAt ?? delta.occurredAt; + const nextMessage = { + ...existing, + text: `${existing.text}${delta.chunk}`, + updatedAt: messageUpdatedAt, + streaming: delta.done === true ? false : existing.streaming, + }; + const messages = replaceProjectionArrayItem(projection.messages, messageIndex, nextMessage); + const nextProjection: OrchestrationV2ThreadProjection = { + ...projection, + updatedAt: delta.occurredAt, + messages, + }; + if (delta.mirrorItemId === undefined) return nextProjection; + return applyTurnItemTextDelta( + nextProjection, + { + id: delta.mirrorItemId, + expectedType: "assistant_message", + expectedRecordId: delta.id, + offset: delta.offset, + chunk: delta.chunk, + occurredAt: delta.occurredAt, + updatedAt: delta.mirrorUpdatedAt ?? messageUpdatedAt, + ...(delta.done === true ? { done: true as const } : {}), + }, + options, + ); + } + case "turn-item": + return applyTurnItemTextDelta( + projection, + { + id: delta.id, + expectedType: "any", + offset: delta.offset, + chunk: delta.chunk, + occurredAt: delta.occurredAt, + updatedAt: delta.updatedAt ?? delta.occurredAt, + ...(delta.done === true ? { done: true as const } : {}), + }, + options, + ); + case "plan": { + let planIndex = projection.plans.length - 1; + while (planIndex >= 0 && projection.plans[planIndex]!.id !== delta.id) { + planIndex -= 1; + } + if (planIndex === -1) return null; + const existing = projection.plans[planIndex]!; + if ( + existing.kind !== "proposed_plan" || + (existing.status !== "draft" && existing.status !== "active") || + existing.markdown.length !== delta.offset + ) { + return null; + } + const nextPlan = { + ...existing, + markdown: `${existing.markdown}${delta.chunk}`, + }; + const plans = replaceProjectionArrayItem(projection.plans, planIndex, nextPlan); + const nextProjection: OrchestrationV2ThreadProjection = { + ...projection, + updatedAt: delta.occurredAt, + plans, + }; + if (delta.mirrorItemId === undefined) return nextProjection; + return applyTurnItemTextDelta( + nextProjection, + { + id: delta.mirrorItemId, + expectedType: "proposed_plan", + expectedRecordId: delta.id, + offset: delta.offset, + chunk: delta.chunk, + occurredAt: delta.occurredAt, + updatedAt: delta.mirrorUpdatedAt ?? delta.occurredAt, + }, + options, + ); + } + } +} diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts index f4a2ea4d5a751..4b220cb81e982 100644 --- a/packages/client-runtime/src/state/threadDetail.test.ts +++ b/packages/client-runtime/src/state/threadDetail.test.ts @@ -20,7 +20,10 @@ import * as Option from "effect/Option"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + applyOrchestrationV2ThreadTextDelta, +} from "./orchestrationV2Projection.ts"; import type { ThreadStructureVisibleTurnItem } from "./models.ts"; import { createEnvironmentThreadDetailAtoms, @@ -273,6 +276,70 @@ describe("timelineVisibleTurnItemsAtom", () => { expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ text: "Hello", streaming: false }); registry.dispose(); }); + + it("holds quiet and timeline atoms steady across text-delta chunks until done", () => { + const initial = withItem(assistant); + const stateAtom = Atom.make( + AsyncResult.success({ + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(initial), + }), + ); + const details = createEnvironmentThreadDetailAtoms(() => stateAtom); + const quietAtom = details.quietThreadAtom(ref); + const timelineAtom = details.timelineVisibleTurnItemsAtom(ref); + const textAtom = details.assistantMessageTextAtom(ref, assistant.id); + const registry = AtomRegistry.make(); + registry.mount(quietAtom); + registry.mount(timelineAtom); + registry.mount(textAtom); + + const firstQuiet = registry.get(quietAtom); + const firstTimeline = registry.get(timelineAtom); + const mid = applyOrchestrationV2ThreadTextDelta(initial, { + kind: "text-delta", + sequence: 2, + target: "message", + id: assistantMessage.id, + mirrorItemId: assistant.id, + offset: 3, + chunk: "lo world", + occurredAt: later, + }); + expect(mid).not.toBeNull(); + registry.set( + stateAtom, + AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(mid!) }), + ); + expect(registry.get(quietAtom)).toBe(firstQuiet); + expect(registry.get(timelineAtom)).toBe(firstTimeline); + expect(registry.get(textAtom)).toBe("Hello world"); + + const done = applyOrchestrationV2ThreadTextDelta(mid, { + kind: "text-delta", + sequence: 3, + target: "message", + id: assistantMessage.id, + mirrorItemId: assistant.id, + offset: 11, + chunk: "!", + occurredAt: later, + done: true, + }); + expect(done).not.toBeNull(); + registry.set( + stateAtom, + AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(done!) }), + ); + expect(registry.get(quietAtom)).not.toBe(firstQuiet); + expect(registry.get(timelineAtom)).not.toBe(firstTimeline); + expect(registry.get(timelineAtom)[0]?.item).toMatchObject({ + text: "Hello world!", + streaming: false, + status: "completed", + }); + registry.dispose(); + }); }); it("only compares replaced entries in a streamed reducer delta", () => { diff --git a/packages/client-runtime/src/state/threadStream.test.ts b/packages/client-runtime/src/state/threadStream.test.ts new file mode 100644 index 0000000000000..a59944efc18c6 --- /dev/null +++ b/packages/client-runtime/src/state/threadStream.test.ts @@ -0,0 +1,308 @@ +import { + EnvironmentId, + MessageId, + ORCHESTRATION_V2_WS_METHODS, + RunId, + TurnItemId, + type OrchestrationV2ConversationMessage, + type OrchestrationV2SubscribeThreadInput, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadStreamItem, + type OrchestrationV2TurnItem, + type ServerConfig, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type PreparedConnection, + type SupervisorConnectionState, +} from "../connection/model.ts"; +import * as EnvironmentSupervisor from "../connection/supervisor.ts"; +import * as Persistence from "../platform/persistence.ts"; +import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; +import type { RpcSession } from "../rpc/session.ts"; +import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import * as ThreadSnapshotLoader from "./threadSnapshotHttp.ts"; +import type { EnvironmentThreadState } from "./threadState.ts"; +import { applyThreadStreamItem, initialThreadStreamState } from "./threadStream.ts"; +import { makeEnvironmentThreadState } from "./threads.ts"; + +const LATER = DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"); +const MESSAGE_ID = MessageId.make("msg-stream-delta"); +const ITEM_ID = TurnItemId.make("item-stream-delta"); +const RUN_ID = RunId.make("run-stream-delta"); + +function streamingProjection(text: string, streaming = true): OrchestrationV2ThreadProjection { + const message: OrchestrationV2ConversationMessage = { + id: MESSAGE_ID, + threadId: v2ThreadId, + runId: RUN_ID, + nodeId: null, + role: "assistant", + text, + attachments: [], + streaming, + createdBy: "agent", + creationSource: "provider", + createdAt: v2Now, + updatedAt: v2Now, + }; + const item: OrchestrationV2TurnItem = { + id: ITEM_ID, + type: "assistant_message", + threadId: v2ThreadId, + runId: RUN_ID, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: streaming ? "running" : "completed", + title: null, + startedAt: v2Now, + completedAt: streaming ? null : LATER, + updatedAt: v2Now, + messageId: MESSAGE_ID, + text, + streaming, + }; + return { + ...v2Projection, + messages: [message], + turnItems: [item], + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: ITEM_ID, + item, + }, + ], + }; +} + +describe("applyThreadStreamItem text-delta", () => { + it("applies matching text-deltas and leaves state intact on mismatch", () => { + const seeded = applyThreadStreamItem(initialThreadStreamState, { + kind: "snapshot", + snapshotSequence: 10, + projection: streamingProjection("Hel"), + }); + const updated = applyThreadStreamItem(seeded, { + kind: "text-delta", + sequence: 11, + target: "message", + id: MESSAGE_ID, + mirrorItemId: ITEM_ID, + offset: 3, + chunk: "lo", + occurredAt: LATER, + }); + expect(updated.sequence).toBe(11); + expect(updated.projection?.messages[0]?.text).toBe("Hello"); + expect(updated.projection?.turnItems[0]).toMatchObject({ text: "Hello" }); + + // Mismatched offset must not corrupt text or advance sequence. + const mismatched = applyThreadStreamItem(updated, { + kind: "text-delta", + sequence: 12, + target: "message", + id: MESSAGE_ID, + mirrorItemId: ITEM_ID, + offset: 99, + chunk: "!", + occurredAt: LATER, + }); + expect(mismatched).toBe(updated); + }); +}); + +describe("makeEnvironmentThreadState text-delta resync", () => { + const TARGET = new PrimaryConnectionTarget({ + environmentId: EnvironmentId.make("env-text-delta"), + label: "Delta test", + httpBaseUrl: "https://delta.example.test", + wsBaseUrl: "wss://delta.example.test", + }); + const CONFIG = { + availableEditors: [], + issues: [], + keybindings: [], + keybindingsConfigPath: "", + observability: null, + providers: [], + settings: {}, + } as unknown as ServerConfig; + + it.effect("opts into acceptTextDeltas and forces a snapshot resync on offset mismatch", () => + Effect.gen(function* () { + const inputs: Array = []; + const firstStream = yield* Queue.unbounded(); + const secondStream = yield* Queue.unbounded(); + const secondSubscribed = yield* Deferred.make(); + let attempt = 0; + + const client = { + [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: ( + input: OrchestrationV2SubscribeThreadInput, + ) => { + inputs.push(input); + attempt += 1; + if (attempt === 1) return Stream.fromQueue(firstStream); + return Stream.unwrap( + Deferred.succeed(secondSubscribed, undefined).pipe( + Effect.as(Stream.fromQueue(secondStream)), + ), + ); + }, + } as unknown as WsRpcProtocolClient; + + const rpcSession: RpcSession = { + client, + initialConfig: Effect.succeed(CONFIG), + subscribeServerConfig: () => Stream.empty, + ready: Effect.void, + probe: Effect.void, + inboundFrames: Effect.succeed(0), + awaitingReply: Effect.succeed(false), + closed: Effect.never, + }; + + const supervisorState = yield* SubscriptionRef.make({ + ...AVAILABLE_CONNECTION_STATE, + desired: true, + network: "online", + phase: "connected", + }); + const activeSession = yield* SubscriptionRef.make>( + Option.some(rpcSession), + ); + const prepared = yield* SubscriptionRef.make>( + Option.none(), + ); + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: supervisorState, + session: activeSession, + prepared, + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + }); + + const cache = Persistence.EnvironmentCacheStore.of({ + loadShell: () => Effect.succeedNone, + saveShell: () => Effect.void, + loadThread: () => + Effect.succeedSome({ + snapshotSequence: 10, + projection: streamingProjection("Hel"), + }), + saveThread: () => Effect.void, + removeThread: () => Effect.void, + loadServerConfig: () => Effect.succeedNone, + saveServerConfig: () => Effect.void, + loadVcsRefs: () => Effect.succeedNone, + saveVcsRefs: () => Effect.void, + removeVcsRefs: () => Effect.void, + clearVcsRefs: () => Effect.void, + clear: () => Effect.void, + }); + + const snapshotLoader = ThreadSnapshotLoader.ThreadSnapshotLoader.of({ + load: () => Effect.succeed({ _tag: "unavailable" }), + }); + + const threadState = yield* makeEnvironmentThreadState(v2ThreadId).pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.provideService(Persistence.EnvironmentCacheStore, cache), + Effect.provideService(ThreadSnapshotLoader.ThreadSnapshotLoader, snapshotLoader), + ); + + const waitForState = (predicate: (value: EnvironmentThreadState) => boolean) => + SubscriptionRef.changes(threadState).pipe( + Stream.filter(predicate), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + + // First attempt resumes from cached seq 10, receives synchronized + valid text-delta. + yield* Queue.offerAll(firstStream, [ + { kind: "synchronized" }, + { + kind: "text-delta", + sequence: 11, + target: "message", + id: MESSAGE_ID, + mirrorItemId: ITEM_ID, + offset: 3, + chunk: "lo", + occurredAt: LATER, + }, + ]); + + const afterValid = yield* waitForState( + (value) => value.sequence === 11 && value.status === "live", + ); + expect(inputs[0]).toMatchObject({ + threadId: v2ThreadId, + afterSequence: 10, + acceptTextDeltas: true, + }); + expect(Option.getOrNull(afterValid.data)?.messages[0]?.text).toBe("Hello"); + expect(Option.getOrNull(afterValid.data)?.turnItems[0]).toMatchObject({ text: "Hello" }); + + // Send a mismatched offset delta: must NOT corrupt "Hello", must force a snapshot resubscribe. + yield* Queue.offer(firstStream, { + kind: "text-delta", + sequence: 12, + target: "message", + id: MESSAGE_ID, + mirrorItemId: ITEM_ID, + offset: 99, + chunk: "CORRUPT", + occurredAt: LATER, + }); + + yield* Deferred.await(secondSubscribed); + expect(inputs).toHaveLength(2); + expect(inputs[1]).toMatchObject({ threadId: v2ThreadId, acceptTextDeltas: true }); + expect("afterSequence" in inputs[1]!).toBe(false); + + const beforeHeal = yield* SubscriptionRef.get(threadState); + expect(Option.getOrNull(beforeHeal.data)?.messages[0]?.text).toBe("Hello"); + expect(beforeHeal.sequence).toBe(11); + + // Authoritative snapshot heals the thread cleanly back to live. + yield* Queue.offerAll(secondStream, [ + { + kind: "snapshot", + snapshotSequence: 15, + projection: streamingProjection("Hello recovered!", false), + }, + { kind: "synchronized" }, + ]); + + const healed = yield* waitForState( + (value) => value.sequence === 15 && value.status === "live", + ); + expect(Option.getOrNull(healed.data)?.messages[0]?.text).toBe("Hello recovered!"); + expect(Option.getOrNull(healed.data)?.turnItems[0]).toMatchObject({ + text: "Hello recovered!", + streaming: false, + status: "completed", + }); + }).pipe(Effect.scoped), + ); +}); diff --git a/packages/client-runtime/src/state/threadStream.ts b/packages/client-runtime/src/state/threadStream.ts index e03a1e610a094..41a981dde223e 100644 --- a/packages/client-runtime/src/state/threadStream.ts +++ b/packages/client-runtime/src/state/threadStream.ts @@ -5,7 +5,10 @@ import type { } from "@t3tools/contracts"; import { boundedSnapshotProjection } from "@t3tools/shared/orchestrationV2BoundedSnapshot"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + applyOrchestrationV2ThreadTextDelta, +} from "./orchestrationV2Projection.ts"; import { mergeOlderHistoryIntoProjection, mergeOlderSubagentsIntoProjection, @@ -54,6 +57,19 @@ export function applyThreadStreamItem( } if (item.kind === "synchronized" || item.sequence <= state.sequence) return state; if (item.kind === "unknown-event") return { ...state, sequence: item.sequence }; + if (item.kind === "text-delta") { + const projection = applyOrchestrationV2ThreadTextDelta( + state.projection, + item, + state.partial === null ? undefined : { partialTimeline: true, ...state.partial }, + ); + if (projection === null) return state; + return { + ...state, + projection, + sequence: item.sequence, + }; + } const projection = applyOrchestrationV2ProjectionEvent( state.projection, diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 59f2b00f6eaf8..34310a12429d4 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -8,6 +8,7 @@ import { type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadStreamItem, + type OrchestrationV2ThreadTextDelta, type OrchestrationV2TurnItem, type ThreadId as ThreadIdType, } from "@t3tools/contracts"; @@ -47,6 +48,7 @@ import { import { parseThreadKey, threadKey } from "./entities.ts"; import { applyOrchestrationV2ProjectionEvent, + applyOrchestrationV2ThreadTextDelta, restoreCachedProjectionVisibility, } from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; @@ -553,7 +555,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make type EventItem = Extract; type SequencedItem = Extract< OrchestrationV2ThreadStreamItem, - { kind: "event" | "unknown-event" } + { kind: "event" | "text-delta" | "unknown-event" } >; // Per-batch streaming spans add trace volume without a useful timing boundary. const applyEventsLocked = Effect.fnUntraced(function* ( @@ -562,56 +564,63 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make live: boolean, ) { const appliedSequence = yield* SubscriptionRef.get(lastSequence); - let sequence = appliedSequence; - const fresh: EventItem[] = []; + let seenSequence = appliedSequence; + const fresh: SequencedItem[] = []; for (const item of items) { - if (item.sequence <= sequence) continue; - sequence = item.sequence; - if (item.kind === "event") { - fresh.push(item); - continue; - } - yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe( - Effect.annotateLogs({ - environmentId, - threadId, - eventType: item.eventType.slice(0, 64), - sequence: item.sequence, - }), - ); - } - if (sequence === appliedSequence) return; - yield* SubscriptionRef.set(lastSequence, sequence); - if (fresh.length === 0) return; - - if (live) { - const receivedAtMs = yield* Clock.currentTimeMillis; - for (const item of fresh) { - observeServerTime( - environmentId, - DateTime.toEpochMillis(item.event.occurredAt), - receivedAtMs, + if (item.sequence <= seenSequence) continue; + seenSequence = item.sequence; + fresh.push(item); + if (item.kind === "unknown-event") { + yield* Effect.logDebug("Skipped a thread event type this client does not know.").pipe( + Effect.annotateLogs({ + environmentId, + threadId, + eventType: item.eventType.slice(0, 64), + sequence: item.sequence, + }), ); } } + if (fresh.length === 0) return false; const waiting = yield* Ref.get(awaitingCompletion); // Apply against the latest projection/history in one update so a concurrent // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale // get-then-set rebuild. - type EventApplyResult = + type EventApplyStep = | { readonly _tag: "noop" } | { readonly _tag: "delete" } + | { readonly _tag: "applied" }; + + type BatchApplyResult = + | { readonly _tag: "noop"; readonly sequence: number } + | { readonly _tag: "delete"; readonly sequence: number } + | { + readonly _tag: "resync"; + readonly sequence: number; + readonly mismatch: OrchestrationV2ThreadTextDelta; + } | { readonly _tag: "applied"; + readonly sequence: number; readonly projection: OrchestrationV2ThreadProjection; readonly history: ThreadHistoryMeta; }; + const partialFor = (current: EnvironmentThreadState) => + current.history.hasMoreHistory || + current.history.historyCursor !== null || + (current.history.gaps?.length ?? 0) > 0 + ? { + partialTimeline: true as const, + latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal, + } + : undefined; + const applyEvent = ( current: EnvironmentThreadState, item: EventItem, - ): readonly [EventApplyResult, EnvironmentThreadState] => { + ): readonly [EventApplyStep, EnvironmentThreadState] => { if (current.status === "deleted") { return [{ _tag: "noop" }, current]; } @@ -626,15 +635,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } // Expanded can remain true after the last page. Only unloaded history needs partial updates. - const partial = - current.history.hasMoreHistory || - current.history.historyCursor !== null || - (current.history.gaps?.length ?? 0) > 0 - ? { - partialTimeline: true as const, - latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal, - } - : undefined; + const partial = partialFor(current); const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial); if (next === null || next === current.data.value) { return [{ _tag: "noop" }, current]; @@ -656,28 +657,125 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make error: Option.none(), history, }; - return [{ _tag: "applied", projection: next, history: updated.history }, updated]; + return [{ _tag: "applied" }, updated]; }; const result = yield* SubscriptionRef.modify( state, - (current): readonly [EventApplyResult, EnvironmentThreadState] => { - let result: EventApplyResult = { _tag: "noop" }; + (current): readonly [BatchApplyResult, EnvironmentThreadState] => { + let committedSequence = appliedSequence; + let applied = false; + let deleted = false; + let mismatch: OrchestrationV2ThreadTextDelta | null = null; for (const item of fresh) { - const [applied, next] = applyEvent(current, item); + if (item.kind === "unknown-event") { + committedSequence = item.sequence; + continue; + } + if (item.kind === "text-delta") { + if (current.status === "deleted") { + committedSequence = item.sequence; + continue; + } + if (Option.isNone(current.data)) { + mismatch = item; + break; + } + const next = applyOrchestrationV2ThreadTextDelta( + current.data.value, + item, + partialFor(current), + ); + if (next === null) { + mismatch = item; + break; + } + current = { + ...current, + data: Option.some(next), + status: waiting ? "synchronizing" : "live", + error: Option.none(), + }; + committedSequence = item.sequence; + applied = true; + continue; + } + const [step, next] = applyEvent(current, item); current = next; - if (applied._tag !== "noop") result = applied; - if (applied._tag === "delete") break; + committedSequence = item.sequence; + if (step._tag === "delete") { + deleted = true; + break; + } + if (step._tag === "applied") { + applied = true; + } + } + if (mismatch !== null) { + return [ + { _tag: "resync", sequence: committedSequence, mismatch }, + applied ? { ...current, sequence: committedSequence } : current, + ]; + } + if (deleted) { + return [{ _tag: "delete", sequence: committedSequence }, current]; } // A batch that changed nothing keeps its state object, so readers do not re-render. - return [result, result._tag === "noop" ? current : { ...current, sequence }]; + if (applied && Option.isSome(current.data)) { + return [ + { + _tag: "applied", + sequence: committedSequence, + projection: current.data.value, + history: current.history, + }, + { ...current, sequence: committedSequence }, + ]; + } + return [{ _tag: "noop", sequence: committedSequence }, current]; }, ); + if (result.sequence > appliedSequence) { + yield* SubscriptionRef.set(lastSequence, result.sequence); + } + if (live && result.sequence > appliedSequence) { + const receivedAtMs = yield* Clock.currentTimeMillis; + for (const item of fresh) { + if (item.sequence > result.sequence) break; + if (item.kind === "event") { + observeServerTime( + environmentId, + DateTime.toEpochMillis(item.event.occurredAt), + receivedAtMs, + ); + } else if (item.kind === "text-delta") { + observeServerTime(environmentId, DateTime.toEpochMillis(item.occurredAt), receivedAtMs); + } + } + } + + if (result._tag === "resync") { + yield* Effect.logWarning( + "Thread text delta did not match local state; requesting a fresh snapshot.", + ).pipe( + Effect.annotateLogs({ + environmentId, + threadId, + sequence: result.mismatch.sequence, + target: result.mismatch.target, + entityId: result.mismatch.id, + offset: result.mismatch.offset, + }), + ); + yield* Ref.set(forceSnapshot, true); + yield* Queue.offer(resubscribes, undefined); + return true; + } if (result._tag === "delete") { httpMisses = 0; yield* setDeleted(); - return; + return false; } if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) { const snapshotSequence = yield* SubscriptionRef.get(lastSequence); @@ -690,6 +788,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ), ); } + return false; }); const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* ( @@ -765,9 +864,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make catchUp = []; let live = !(yield* Ref.get(awaitingCompletion)); let events: SequencedItem[] = []; + let resyncing = false; for (const item of items) { if ( item.kind === "unknown-event" || + item.kind === "text-delta" || (item.kind === "event" && item.event.type !== "thread.deleted") ) { events.push(item); @@ -776,12 +877,27 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make // Clearing the flag first lets the events before the marker publish // "live", so a catch-up ending in the marker is one state change. if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false); - yield* applyEventsLocked(events, live); + if (yield* applyEventsLocked(events, live)) { + resyncing = true; + events = []; + break; + } events = []; yield* applyItemLocked(item); if (item.kind === "synchronized") live = true; } - yield* applyEventsLocked(events, live); + if (!resyncing) { + resyncing = yield* applyEventsLocked(events, live); + } + if (resyncing) { + attempt = undefined; + yield* Ref.set(awaitingCompletion, true); + yield* SubscriptionRef.updateSome(state, (current) => + current.status === "live" + ? Option.some({ ...current, status: "synchronizing" as const }) + : Option.none(), + ); + } yield* remember; }), ); @@ -1226,6 +1342,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } : {}), acceptDedupedBodies: true as const, + acceptTextDeltas: true as const, }; attempt = input; return input; diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 79e7d81408bd5..bfeb87a5ccd3a 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -4,12 +4,15 @@ import * as Schema from "effect/Schema"; import { EnvironmentId, + MessageId, NodeId, + PlanId, RunAttemptId, RunId, ScheduledTaskId, ThreadId, TrimmedNonEmptyString, + TurnItemId, } from "./index.ts"; import { latestProviderTurnForAttempt, @@ -21,6 +24,7 @@ import { OrchestrationV2ProviderThreadJson, OrchestrationV2RpcSchemas, OrchestrationV2Subagent, + OrchestrationV2SubscribeThreadInput, OrchestrationV2ThreadShellJson, OrchestrationV2SubagentJson, OrchestrationV2ThreadHistoryPage, @@ -754,3 +758,62 @@ describe("withMessageSenderNote", () => { expect(withMessageSenderNote(message, text)).toBe(expected); }); }); + +describe("thread stream text-delta contract", () => { + const codec = Schema.toCodecJson(OrchestrationV2RpcSchemas.subscribeThread.output); + const encodeItem = Schema.encodeSync(codec); + const decodeItem = Schema.decodeUnknownSync(codec); + const decodeSubscribeInput = Schema.decodeUnknownSync(OrchestrationV2SubscribeThreadInput); + + it("round-trips message, turn-item, and plan text-delta frames", () => { + const later = DateTime.makeUnsafe("2026-04-20T00:00:01.000Z"); + const items = [ + { + kind: "text-delta" as const, + sequence: 10, + target: "message" as const, + id: MessageId.make("msg-1"), + mirrorItemId: TurnItemId.make("item-1"), + offset: 5, + chunk: " world", + occurredAt: later, + updatedAt: now, + mirrorUpdatedAt: later, + done: true as const, + }, + { + kind: "text-delta" as const, + sequence: 11, + target: "turn-item" as const, + id: TurnItemId.make("reasoning-1"), + offset: 12, + chunk: " next step", + occurredAt: later, + }, + { + kind: "text-delta" as const, + sequence: 12, + target: "plan" as const, + id: PlanId.make("plan-1"), + mirrorItemId: TurnItemId.make("plan-item-1"), + offset: 8, + chunk: "\n- step 2", + occurredAt: later, + }, + ]; + for (const item of items) { + const wire = JSON.parse(JSON.stringify(encodeItem(item))); + expect(decodeItem(wire)).toEqual(item); + } + }); + + it("accepts acceptTextDeltas as an additive opt-in on subscribeThread", () => { + expect(decodeSubscribeInput({ threadId: "thread-1" })).toEqual({ + threadId: ThreadId.make("thread-1"), + }); + expect(decodeSubscribeInput({ threadId: "thread-1", acceptTextDeltas: true })).toEqual({ + threadId: ThreadId.make("thread-1"), + acceptTextDeltas: true, + }); + }); +}); diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 68f90a24532f6..d16235ab71bea 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -4534,6 +4534,8 @@ export const OrchestrationV2SubscribeThreadInput = Schema.Struct({ /** The client restores `*Omitted` bodies from records it already holds. */ acceptDedupedBodies: Schema.optionalKey(Schema.Boolean), acceptCompactIds: Schema.optionalKey(Schema.Boolean), + /** The client applies incremental text-delta items for streaming text, reasoning, and plans. */ + acceptTextDeltas: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2SubscribeThreadInput.Type; @@ -4639,6 +4641,45 @@ const OrchestrationV2UnknownThreadStreamEvent = Schema.Struct({ ), ); +const OrchestrationV2ThreadTextDelta = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("text-delta"), + sequence: NonNegativeInt, + target: Schema.Literal("message"), + id: MessageId, + mirrorItemId: Schema.optionalKey(TurnItemId), + offset: NonNegativeInt, + chunk: Schema.String, + occurredAt: Schema.DateTimeUtc, + updatedAt: Schema.optionalKey(Schema.DateTimeUtc), + mirrorUpdatedAt: Schema.optionalKey(Schema.DateTimeUtc), + done: Schema.optionalKey(Schema.Literal(true)), + }), + Schema.Struct({ + kind: Schema.Literal("text-delta"), + sequence: NonNegativeInt, + target: Schema.Literal("turn-item"), + id: TurnItemId, + offset: NonNegativeInt, + chunk: Schema.String, + occurredAt: Schema.DateTimeUtc, + updatedAt: Schema.optionalKey(Schema.DateTimeUtc), + done: Schema.optionalKey(Schema.Literal(true)), + }), + Schema.Struct({ + kind: Schema.Literal("text-delta"), + sequence: NonNegativeInt, + target: Schema.Literal("plan"), + id: PlanId, + mirrorItemId: Schema.optionalKey(TurnItemId), + offset: NonNegativeInt, + chunk: Schema.String, + occurredAt: Schema.DateTimeUtc, + mirrorUpdatedAt: Schema.optionalKey(Schema.DateTimeUtc), + }), +]); +export type OrchestrationV2ThreadTextDelta = typeof OrchestrationV2ThreadTextDelta.Type; + export const OrchestrationV2ThreadStreamItem = withRecordIdTable( Schema.Union([ Schema.Struct({ @@ -4659,6 +4700,7 @@ export const OrchestrationV2ThreadStreamItem = withRecordIdTable( sequence: NonNegativeInt, event: OrchestrationV2DomainEvent, }), + ...OrchestrationV2ThreadTextDelta.members, OrchestrationV2UnknownThreadStreamEvent, ]), (item) => (item.kind === "snapshot" ? "projection" : undefined),