diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 8b2d4e105e5b1..2004f514df4a4 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -20,7 +20,7 @@ import { LINKED_THREAD_RETRY_MS, type LinkedThreadView, } from "./linkedThread.ts"; -import { v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection } from "./state/orchestrationV2TestFixtures.ts"; const snapshot = ( snapshotSequence: number, @@ -163,6 +163,83 @@ it.effect("loads the turns before a snapshot's window once per request", () => }).pipe(Effect.scoped), ); +it.effect("brings back the turns a closed view had loaded when it opens again", () => + Effect.gen(function* () { + const older = v2MessageRow("Older", 1); + const recent = v2MessageRow("Recent", 2); + const latest = v2MessageRow("Latest", 3); + const window = ( + snapshotSequence: number, + historyCursor: string, + row: typeof recent, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: { ...v2Projection, turnItems: [row.item], visibleTurnItems: [row] }, + historyCursor, + hasMoreHistory: true, + }); + const pages: Record> = { + "before-recent": { items: [older], nextCursor: "before-older" }, + "before-latest": { items: [recent], nextCursor: "before-recent" }, + }; + const asked: string[] = []; + const follow = ( + items: ReadonlyArray, + previous: LinkedThreadView | null, + ) => + Effect.gen(function* () { + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.fromIterable(items).pipe(Stream.concat(Stream.never)), + historyPage: (cursor) => + Effect.sync(() => { + asked.push(cursor); + return { ...pages[cursor]!, snapshotSequence: 3, hasMoreHistory: true }; + }), + previous, + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + return views; + }); + const settled = Effect.fnUntraced(function* (views: Queue.Queue) { + let view = yield* Queue.take(views); + while (view.history.loading) view = yield* Queue.take(views); + return view; + }); + const rows = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const first = yield* follow([window(1, "before-recent", recent), retitled(2, "Renamed")], null); + (yield* Queue.take(first)).loadEarlier(); + yield* Queue.take(first); // Loading. + yield* Queue.take(first); // The earlier page. + const closed = yield* Queue.take(first); + expect([rows(closed), closed.thread.sequence]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + 2, + ]); + + // Nothing changed while the view was closed: the rows it held are shown as they were. + const same = yield* settled(yield* follow([window(2, "before-recent", recent)], closed)); + expect([rows(same), same.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent"]); + + // The thread moved on: pages are read again until the oldest row it showed is back. + const moved = yield* settled(yield* follow([window(3, "before-latest", latest)], closed)); + expect([rows(moved), moved.thread.historyCursor]).toEqual([ + [older.sourceItemId, recent.sourceItemId, latest.sourceItemId], + "before-older", + ]); + expect(asked).toEqual(["before-recent", "before-latest", "before-recent"]); + }).pipe(Effect.scoped), +); + describe("connectLinkedEnvironment", () => { const lan = "http://192.168.1.20:3773"; const tailnet = "https://vm.tail.ts.net"; diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..69b179e08f671 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -1,5 +1,6 @@ import type { EnvironmentId, + OrchestrationV2ProjectedTurnItem, OrchestrationV2ThreadHistoryPage, OrchestrationV2ThreadProjection, OrchestrationV2ThreadStreamItem, @@ -8,6 +9,7 @@ import type { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Queue from "effect/Queue"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; @@ -20,6 +22,7 @@ import { applyThreadHistoryPage, applyThreadStreamItem, initialThreadStreamState, + prependThreadHistory, type ThreadStreamState, } from "./state/threadStream.ts"; @@ -212,12 +215,38 @@ export function isLinkedThreadWorking(projection: OrchestrationV2ThreadProjectio /** How long a view waits before asking again for a thread whose environment did not answer. */ export const LINKED_THREAD_RETRY_MS = 15_000; +type HistoryAnchor = Pick; + +interface LinkedHistoryWindow { + readonly sequence: number; + readonly cursor: string; +} + +interface LinkedHistoryRequest { + readonly window: LinkedHistoryWindow; + readonly cursor: string; +} + +function includesHistoryAnchor(rows: ReadonlyArray, anchor: HistoryAnchor): boolean { + return rows.some( + (row) => + row.sourceThreadId === anchor.sourceThreadId && row.sourceItemId === anchor.sourceItemId, + ); +} + /** A linked thread as its view holds it: the thread's own stream, reduced as any thread's is. */ export interface LinkedThreadView { readonly thread: ThreadStreamState; /** Why the stream stopped, while the view waits to ask again; the next item clears it. */ readonly error: unknown; readonly history: { readonly loading: boolean; readonly failed: boolean }; + /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ + readonly loadedHistory: { + readonly window: LinkedHistoryWindow; + readonly nextCursor: string | null; + /** The oldest row still to recover, even if a read fails or the view closes during backfill. */ + readonly restoreThrough: HistoryAnchor | null; + } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ readonly loadEarlier: () => void; } @@ -233,7 +262,11 @@ export const keepLinkedThreadView = ( ): LinkedThreadView => next.thread.projection !== null || kept === null || kept.thread.projection === null ? next - : { ...next, thread: { ...kept.thread, historyCursor: null } }; + : { + ...next, + thread: { ...kept.thread, historyCursor: null }, + loadedHistory: kept.loadedHistory, + }; /** * Follows a linked environment's thread for as long as something consumes the result. The thread @@ -244,34 +277,100 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; + readonly previous?: LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { - const requests = yield* Queue.unbounded(); + const requests = yield* Queue.unbounded(); let requested = false; - // Both halves below run one step at a time, so each reads the view the other left. + let previous = source.previous ?? null; + let snapshotWindow: LinkedHistoryWindow | null = null; + const requestPage = (window: LinkedHistoryWindow, cursor: string) => { + requested = true; + Queue.offerUnsafe(requests, { window, cursor }); + }; let view: LinkedThreadView = { thread: initialThreadStreamState, error: null, history: { loading: false, failed: false }, + loadedHistory: null, loadEarlier: () => { - if (requested || view.thread.historyCursor === null) return; - requested = true; - Queue.offerUnsafe(requests, undefined); + const cursor = view.thread.historyCursor; + if (requested || snapshotWindow === null || cursor === null) return; + requestPage(snapshotWindow, cursor); }, }; const show = (patch: Partial) => { view = { ...view, ...patch }; return view; }; - const attempt = (): Stream.Stream => + + const onItem = (item: OrchestrationV2ThreadStreamItem) => { + let thread = applyThreadStreamItem(view.thread, item); + if (item.kind !== "snapshot") return show({ thread, error: null }); + + const kept = view.thread.projection === null ? previous : view; + previous = null; + const loaded = kept?.loadedHistory; + const window = + thread.historyCursor === null + ? null + : { sequence: thread.sequence, cursor: thread.historyCursor }; + let loadedHistory: LinkedThreadView["loadedHistory"] = null; + if (window && kept?.thread.projection && loaded) { + // A live update can advance the revision and move the window without invalidating held rows. + if ( + kept.thread.sequence === window.sequence && + (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor) + ) { + thread = prependThreadHistory( + thread, + { + items: kept.thread.projection.visibleTurnItems, + subagents: kept.thread.projection.subagents, + }, + loaded.nextCursor, + ); + loadedHistory = { ...loaded, window }; + } else if (window.sequence > kept.thread.sequence) { + const oldest = loaded.restoreThrough ?? kept.thread.projection.visibleTurnItems[0]; + if (oldest && !includesHistoryAnchor(item.projection.visibleTurnItems, oldest)) { + const { sourceThreadId, sourceItemId } = oldest; + loadedHistory = { + window, + nextCursor: window.cursor, + restoreThrough: { sourceThreadId, sourceItemId }, + }; + } + } + } + + snapshotWindow = window; + requested = false; + if (window && thread.historyCursor !== null && loadedHistory?.restoreThrough) { + requestPage(window, thread.historyCursor); + } else { + Queue.offerUnsafe(requests, null); + } + return show({ + thread, + loadedHistory, + history: { loading: requested, failed: false }, + error: null, + }); + }; + + const attempt = (): Stream.Stream< + | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem } + | { readonly kind: "unreachable"; readonly error: E }, + E, + R + > => source.items.pipe( - Stream.map((item) => - show({ thread: applyThreadStreamItem(view.thread, item), error: null }), - ), + Stream.map((item) => ({ kind: "item" as const, item })), Stream.catch((error) => isLinkedThreadUnreachable(error) - ? Stream.make(show({ error })).pipe( + ? Stream.make({ kind: "unreachable" as const, error }).pipe( Stream.concat( Stream.unwrap(Effect.sleep(LINKED_THREAD_RETRY_MS).pipe(Effect.map(attempt))), ), @@ -279,38 +378,67 @@ export const followLinkedThread = (source: { : Stream.fail(error), ), ); + const earlier = Stream.fromQueue(requests).pipe( - Stream.flatMap(() => - Stream.suspend(() => { - const cursor = view.thread.historyCursor; - if (cursor === null) { - requested = false; - return Stream.empty; - } - return Stream.make(show({ history: { loading: true, failed: false } })).pipe( - Stream.concat( - Stream.fromEffect( - source.historyPage(cursor).pipe( - Effect.match({ - onSuccess: (page) => - show({ - thread: applyThreadHistoryPage(view.thread, cursor, page), - history: { loading: false, failed: false }, - }), - onFailure: () => show({ history: { loading: false, failed: true } }), - }), - Effect.ensuring( - Effect.sync(() => { - requested = false; - }), + Stream.switchMap((request) => + request === null + ? Stream.empty + : Stream.make({ kind: "loading" as const, request }).pipe( + Stream.concat( + Stream.fromEffect( + source.historyPage(request.cursor).pipe( + Effect.result, + Effect.map((page) => ({ kind: "page" as const, request, page })), ), ), ), ), - ); - }), ), ); - return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); + + // Reduce snapshots, live items and history results in publication order. + return Stream.merge(attempt(), earlier, { haltStrategy: "left" }).pipe( + Stream.filterMap((update) => { + if (update.kind === "item") return Result.succeed(onItem(update.item)); + if (update.kind === "unreachable") return Result.succeed(show({ error: update.error })); + const { window, cursor } = update.request; + if (snapshotWindow !== window || view.thread.historyCursor !== cursor) { + return Result.failVoid; + } + if (update.kind === "loading") { + return view.history.loading + ? Result.failVoid + : Result.succeed(show({ history: { loading: true, failed: false } })); + } + requested = false; + const page = update.page; + if ( + Result.isFailure(page) || + page.success.snapshotSequence < window.sequence || + (page.success.hasMoreHistory && page.success.nextCursor === cursor) + ) { + return Result.succeed(show({ history: { loading: false, failed: true } })); + } + + const thread = applyThreadHistoryPage(view.thread, cursor, page.success); + let restoreThrough = view.loadedHistory?.restoreThrough ?? null; + const nextCursor = thread.historyCursor; + if ( + restoreThrough !== null && + (nextCursor === null || + includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough)) + ) { + restoreThrough = null; + } + if (restoreThrough !== null && nextCursor !== null) requestPage(window, nextCursor); + return Result.succeed( + show({ + thread, + loadedHistory: { window, nextCursor, restoreThrough }, + history: { loading: requested, failed: false }, + }), + ); + }), + ); }), ); diff --git a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts index 550dc389a86bf..cf1ec01a4fc65 100644 --- a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts +++ b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts @@ -1,8 +1,11 @@ import { + MessageId, ProjectId, ProviderInstanceId, ThreadId, + TurnItemId, type OrchestrationProjectShell, + type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, @@ -101,6 +104,40 @@ export const v2Projection: OrchestrationV2ThreadProjection = { updatedAt: v2Now, }; +/** A completed user message row of `v2ThreadId`, identified by its text. */ +export function v2MessageRow(text: string, ordinal: number): OrchestrationV2ProjectedTurnItem { + const itemId = TurnItemId.make(text); + return { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: itemId, + item: { + id: itemId, + threadId: v2ThreadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: v2Now, + completedAt: v2Now, + updatedAt: v2Now, + type: "user_message", + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(text), + inputIntent: "turn_start", + text, + attachments: [], + }, + }; +} + export const v2ShellSnapshot: OrchestrationV2ShellSnapshot = { schemaVersion: 1, snapshotSequence: 0, diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index c1e4ae8acd9f9..75430e340fbff 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,8 +1,126 @@ -import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import { + EnvironmentId, + WS_METHODS, + type OrchestrationV2ThreadHistoryPage, + type OrchestrationV2ThreadStreamItem, + type PeerLinkSummary, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; -import { describe, expect, it } from "vite-plus/test"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +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 { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; -import { linkThroughRoutes } from "./peerLinks.ts"; +import { EnvironmentRegistry } from "../connection/registry.ts"; +import { EnvironmentSupervisor } from "../connection/supervisor.ts"; +import type { LinkedThreadView } from "../linkedThread.ts"; +import type { RpcSession } from "../rpc/session.ts"; +import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; + +// regression: #40544 earlier messages vanished when a linked thread's view opened again +it.effect( + "keeps loaded messages when a linked thread's view opens again on the same snapshot", + () => + Effect.gen(function* () { + const recent = v2MessageRow("Recent message", 2); + const older = v2MessageRow("Earlier message", 1); + const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence: 7, + projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] }, + historyCursor, + hasMoreHistory: true, + }); + const subscriptions = yield* Queue.unbounded<{ + items: Queue.Queue; + stopped: Deferred.Deferred; + }>(); + const requested: string[] = []; + const client = { + [WS_METHODS.peerLinksSubscribeThread]: () => + Stream.unwrap( + Effect.gen(function* () { + const items = yield* Queue.unbounded(); + const stopped = yield* Deferred.make(); + yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); + yield* Queue.offer(subscriptions, { items, stopped }); + return Stream.fromQueue(items); + }), + ), + [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) => + Effect.sync((): OrchestrationV2ThreadHistoryPage => { + requested.push(cursor); + return cursor === "before-recent" + ? { + snapshotSequence: 7, + items: [older], + nextCursor: "before-earlier", + hasMoreHistory: true, + } + : { snapshotSequence: 7, items: [], nextCursor: null, hasMoreHistory: false }; + }), + } as unknown as RpcSession["client"]; + const target = { + environmentId: EnvironmentId.make("via"), + input: { environmentId: EnvironmentId.make("linked"), threadId: v2ThreadId }, + }; + const supervisor = EnvironmentSupervisor.of({ + target: { environmentId: target.environmentId, label: "Via" }, + session: yield* SubscriptionRef.make(Option.some({ client })), + } as unknown as EnvironmentSupervisor["Service"]); + const environment = EnvironmentRegistry.of({ + followStream: (_id, stream) => + Stream.provideService(stream, EnvironmentSupervisor, supervisor), + } as Pick as EnvironmentRegistry["Service"]); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); + const registry = yield* Effect.acquireRelease( + Effect.sync(() => AtomRegistry.make()), + (registry) => Effect.sync(() => registry.dispose()), + ); + const views = yield* Queue.unbounded(); + const open = () => + registry.subscribe(links.threadView(target), (result) => { + if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value); + }); + const visibleMessages = (view: LinkedThreadView) => + view.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId); + + const unmount = open(); + const first = yield* Queue.take(subscriptions); + yield* Queue.offer(first.items, snapshot("before-recent")); + (yield* Queue.take(views)).loadEarlier(); + yield* Queue.take(views); // Loading. + expect(visibleMessages(yield* Queue.take(views))).toEqual([ + older.sourceItemId, + recent.sourceItemId, + ]); + unmount(); + yield* Deferred.await(first.stopped); + + open(); + const reopened = yield* Queue.take(subscriptions); + yield* Queue.offer(reopened.items, snapshot("before-recent")); + const resumed = yield* Queue.take(views); + expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]); + // Paging goes on from where the closed view stopped, without reading the same page again. + expect(resumed.thread.historyCursor).toBe("before-earlier"); + expect(requested).toEqual(["before-recent"]); + + // A snapshot of another window replaces the rows held for the old one. + yield* Queue.offer(reopened.items, snapshot("new-window")); + const refreshed = yield* Queue.take(views); + expect(visibleMessages(refreshed)).toEqual([recent.sourceItemId]); + expect(refreshed.thread.historyCursor).toBe("new-window"); + }).pipe(Effect.scoped), +); const now = DateTime.makeUnsafe("2026-11-20T00:00:00.000Z"); const id = (value: string) => EnvironmentId.make(value); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 543fd55887139..fd9d269bfd726 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -7,6 +7,7 @@ import { import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Stream from "effect/Stream"; import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity"; import type { EnvironmentRegistry } from "../connection/registry.ts"; @@ -19,7 +20,7 @@ import { request, subscribe } from "../rpc/client.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily, - createEnvironmentSubscriptionAtomFamily, + followStreamInEnvironment, } from "./runtime.ts"; /** The environment a client reads through, and the linked environment's thread it reads. */ @@ -54,16 +55,6 @@ export function createPeerLinkEnvironmentAtoms( registry.refresh(list({ environmentId, input: {} })); registry.refresh(names({ environmentId, input: {} })); }); - const threadStream = createEnvironmentSubscriptionAtomFamily(runtime, { - label: "environment-data:peer-links:thread-stream", - idleTtlMs: 0, - subscribe: (input: PeerLinkThreadInput) => - followLinkedThread({ - items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), - historyPage: (cursor) => - request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), - }), - }); /** * What a view of the thread last showed. It outlives the subscription for a while, so coming * back to the view shows the thread at once while the stream starts again. @@ -79,11 +70,26 @@ export function createPeerLinkEnvironmentAtoms( * last reader, which closes the stream at the linked environment too. */ const threadView = Atom.family((key: string) => { - const stream = threadStream(JSON.parse(key) as LinkedThreadViewTarget); + const { environmentId, input } = JSON.parse(key) as LinkedThreadViewTarget; + const kept = lastThreadView(key); + const stream = runtime + .atom(({ registry }) => + followStreamInEnvironment( + environmentId, + Stream.suspend(() => + followLinkedThread({ + items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), + historyPage: (cursor) => + request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), + previous: registry.get(kept), + }), + ), + ), + ) + .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); return Atom.make((get) => { const live = get(stream); if (AsyncResult.isSuccess(live)) { - const kept = lastThreadView(key); get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); } return live; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.ts index 9647f5e4ffc2c..e92852ee36db1 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.test.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts @@ -345,8 +345,11 @@ describe("threadHistoryMerge", () => { visibleTurnItems: [{ ...recent, position: 0 }], }; + // A row of the run that was never in the window, such as one paged in after a rollback. + const ran = { ...row(1), item: { ...row(1).item, runId } }; const merged = mergeOlderHistoryIntoProjection(coldOpen, [ { ...row(0), position: 0 }, + ran, { position: 1, visibility: "local", @@ -357,7 +360,9 @@ describe("threadHistoryMerge", () => { ]); expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual( - status === "rolled_back" ? ["item-0", "item-5"] : ["item-0", "item-question", "item-5"], + status === "rolled_back" + ? ["item-0", "item-5"] + : ["item-0", "item-1", "item-question", "item-5"], ); expect(merged.turnItems).toContain(card); const pending = derivePendingThreadRequests(merged).userInputs; diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts index 4af17f76e031c..a455d64a4726f 100644 --- a/packages/client-runtime/src/state/threadHistoryMerge.ts +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -102,6 +102,9 @@ export function mergeOlderHistoryIntoProjection( const currentByKey = new Map( projection.visibleTurnItems.map((row) => [projectedItemKey(row), row]), ); + const rolledBackRuns = new Set( + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), + ); const turnItemById = new Map(projection.turnItems.map((item) => [String(item.id), item])); const pageKeys = new Set(); const page: OrchestrationV2ProjectedTurnItem[] = []; @@ -140,6 +143,8 @@ export function mergeOlderHistoryIntoProjection( continue; row = { ...row, item: currentItem }; } + // A rollback can arrive before a history page for rows outside the loaded window. + if (row.item.runId !== null && rolledBackRuns.has(row.item.runId)) continue; } pageKeys.add(key); page.push(row); diff --git a/packages/client-runtime/src/state/threadStream.ts b/packages/client-runtime/src/state/threadStream.ts index b723a99885aad..e03a1e610a094 100644 --- a/packages/client-runtime/src/state/threadStream.ts +++ b/packages/client-runtime/src/state/threadStream.ts @@ -82,13 +82,23 @@ export function applyThreadHistoryPage( page: OrchestrationV2ThreadHistoryPage, ): ThreadStreamState { // A snapshot since the request replaced the thread and its cursor. - if (state.projection === null || state.historyCursor !== cursor) return state; + if (state.historyCursor !== cursor) return state; + return prependThreadHistory(state, page, page.hasMoreHistory ? page.nextCursor : null); +} + +/** Adds older timeline rows and their subagent records, with the cursor that follows them. */ +export function prependThreadHistory( + state: ThreadStreamState, + history: Pick, + nextCursor: string | null, +): ThreadStreamState { + if (state.projection === null) return state; return { ...state, projection: mergeOlderSubagentsIntoProjection( - mergeOlderHistoryIntoProjection(state.projection, page.items), - page.subagents, + mergeOlderHistoryIntoProjection(state.projection, history.items), + history.subagents, ), - historyCursor: page.hasMoreHistory ? page.nextCursor : null, + historyCursor: nextCursor, }; }