From 7a2521a06be825e71358082a87cc556eeb8cddff Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:45:27 +0100 Subject: [PATCH 1/7] test: cover linked thread history after reopening Co-authored-by: GPT 6.2 Sol --- .../src/state/peerLinks.test.ts | 175 +++++++++++++++++- 1 file changed, 172 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index c1e4ae8acd9f9..15a0c46ee2e4f 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,8 +1,177 @@ -import { EnvironmentId, type PeerLinkSummary } from "@t3tools/contracts"; +import { + EnvironmentId, + MessageId, + TurnItemId, + WS_METHODS, + type OrchestrationV2ProjectedTurnItem, + 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 { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; + +function messageRow(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: [], + }, + }; +} + +it.effect.each([ + [null, 8], + ["before-earlier", 7], +] as const)( + "keeps loaded messages across a linked-thread subscription reopen (next cursor %s)", + ([nextCursor, refreshedSequence]) => + Effect.gen(function* () { + const recent = messageRow("Recent message", 2); + const older = messageRow("Earlier message", 1); + const snapshot = ( + snapshotSequence: number, + historyCursor: string, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + 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 { + snapshotSequence: 7, + items: cursor === "before-recent" ? [older] : [], + nextCursor: cursor === "before-recent" ? nextCursor : null, + hasMoreHistory: cursor === "before-recent" && nextCursor !== null, + }; + }), + } 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 runtime = Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)); + const links = createPeerLinkEnvironmentAtoms(runtime); + const registry = yield* Effect.acquireRelease( + Effect.sync(() => AtomRegistry.make()), + (registry) => Effect.sync(() => registry.dispose()), + ); + const live = links.threadView(target); + const kept = links.lastThreadView(target); + const views = yield* Queue.unbounded(); + const open = () => + registry.subscribe(live, (result) => { + if (AsyncResult.isSuccess(result)) { + const view = registry.get(kept); + if (view?.thread.projection) Queue.offerUnsafe(views, view); + } + }); + 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(7, "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(7, "before-recent")); + const resumed = yield* Queue.take(views); + expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]); + expect(resumed.thread.historyCursor).toBe(nextCursor); + expect(requested).toEqual(["before-recent"]); + if (nextCursor !== null) { + resumed.loadEarlier(); + yield* Queue.take(views); // Loading. + expect((yield* Queue.take(views)).thread.historyCursor).toBeNull(); + expect(requested).toEqual(["before-recent", nextCursor]); + } + + yield* Queue.offer(reopened.items, snapshot(refreshedSequence, "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); From 509886e582f9276a2e5d1e97338c486679c86965 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:45:27 +0100 Subject: [PATCH 2/7] fix: keep paged linked thread history when reopening the same snapshot Co-authored-by: GPT 6.2 Sol --- packages/client-runtime/src/linkedThread.ts | 71 ++++++++++++++++--- .../client-runtime/src/state/peerLinks.ts | 29 ++++---- 2 files changed, 79 insertions(+), 21 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 15364cddf54ea..56d4a2ce33e05 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -16,6 +16,10 @@ import { deriveRunlessWorkStartedAt, deriveThreadStructureRuntime, } from "./state/threadExecution.ts"; +import { + mergeOlderHistoryIntoProjection, + mergeOlderSubagentsIntoProjection, +} from "./state/threadHistoryMerge.ts"; import { applyThreadHistoryPage, applyThreadStreamItem, @@ -218,6 +222,11 @@ export interface LinkedThreadView { /** 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 snapshotCursor: string; + readonly nextCursor: string | null; + } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ readonly loadEarlier: () => void; } @@ -233,7 +242,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,16 +257,20 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; + readonly readPrevious?: () => LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { const requests = yield* Queue.unbounded(); let requested = false; + let previous = source.readPrevious?.() ?? null; + let snapshotCursor: string | null = null; // Both halves below run one step at a time, so each reads the view the other left. let view: LinkedThreadView = { thread: initialThreadStreamState, error: null, history: { loading: false, failed: false }, + loadedHistory: null, loadEarlier: () => { if (requested || view.thread.historyCursor === null) return; requested = true; @@ -264,11 +281,43 @@ export const followLinkedThread = (source: { view = { ...view, ...patch }; return view; }; + const onItem = (item: OrchestrationV2ThreadStreamItem) => { + const thread = applyThreadStreamItem(view.thread, item); + if (item.kind !== "snapshot") return show({ thread, error: null }); + + const kept = view.thread.projection === null ? previous : view; + previous = null; + snapshotCursor = thread.historyCursor; + const loaded = kept?.loadedHistory; + // A different revision or window can invalidate both the old rows and their cursor. + if ( + kept?.thread.projection && + thread.projection && + kept.thread.sequence === thread.sequence && + loaded && + loaded.snapshotCursor === snapshotCursor + ) { + return show({ + thread: { + ...thread, + projection: mergeOlderSubagentsIntoProjection( + mergeOlderHistoryIntoProjection( + thread.projection, + kept.thread.projection.visibleTurnItems, + ), + kept.thread.projection.subagents, + ), + historyCursor: loaded.nextCursor, + }, + loadedHistory: loaded, + error: null, + }); + } + return show({ thread, loadedHistory: null, error: null }); + }; const attempt = (): Stream.Stream => source.items.pipe( - Stream.map((item) => - show({ thread: applyThreadStreamItem(view.thread, item), error: null }), - ), + Stream.map(onItem), Stream.catch((error) => isLinkedThreadUnreachable(error) ? Stream.make(show({ error })).pipe( @@ -292,11 +341,17 @@ export const followLinkedThread = (source: { Stream.fromEffect( source.historyPage(cursor).pipe( Effect.match({ - onSuccess: (page) => - show({ - thread: applyThreadHistoryPage(view.thread, cursor, page), + onSuccess: (page) => { + const thread = applyThreadHistoryPage(view.thread, cursor, page); + return show({ + thread, + loadedHistory: + thread !== view.thread && snapshotCursor !== null + ? { snapshotCursor, nextCursor: thread.historyCursor } + : view.loadedHistory, history: { loading: false, failed: false }, - }), + }); + }, onFailure: () => show({ history: { loading: false, failed: true } }), }), Effect.ensuring( diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 543fd55887139..781fcaf584dfb 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -19,7 +19,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 +54,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 +69,24 @@ 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, + followLinkedThread({ + items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), + historyPage: (cursor) => + request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), + readPrevious: () => 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; From c777388531e67d703dd5d0665d8f3b07be0fb6fd Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:50:55 +0100 Subject: [PATCH 3/7] refactor: pass the kept linked thread view as a value, not a thunk followLinkedThread reads it once at stream start, so a getter adds nothing. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/linkedThread.ts | 4 ++-- packages/client-runtime/src/state/peerLinks.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 56d4a2ce33e05..4da10e25bed3a 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -257,13 +257,13 @@ export const keepLinkedThreadView = ( export const followLinkedThread = (source: { readonly items: Stream.Stream; readonly historyPage: (cursor: string) => Effect.Effect; - readonly readPrevious?: () => LinkedThreadView | null; + readonly previous?: LinkedThreadView | null; }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { const requests = yield* Queue.unbounded(); let requested = false; - let previous = source.readPrevious?.() ?? null; + let previous = source.previous ?? null; let snapshotCursor: string | null = null; // Both halves below run one step at a time, so each reads the view the other left. let view: LinkedThreadView = { diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index 781fcaf584dfb..2fefb0453b9cf 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -79,7 +79,7 @@ export function createPeerLinkEnvironmentAtoms( items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), historyPage: (cursor) => request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), - readPrevious: () => registry.get(kept), + previous: registry.get(kept), }), ), ) From 8f9051f2b1391375e7c0ee3250b931d53c6fc4b0 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:02:21 +0100 Subject: [PATCH 4/7] fix: restore linked thread history across subscription updates Co-authored-by: GPT 6.2 Sol --- packages/client-runtime/src/linkedThread.ts | 133 +++++++++++----- .../src/state/peerLinks.test.ts | 147 ++++++++++++++++++ .../client-runtime/src/state/peerLinks.ts | 15 +- .../client-runtime/src/state/threadStream.ts | 18 ++- 4 files changed, 262 insertions(+), 51 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 4da10e25bed3a..91b73257734fd 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, @@ -7,6 +8,7 @@ import type { ThreadId, } from "@t3tools/contracts"; 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 { mFallback, msg } from "gt-i18n"; @@ -16,14 +18,11 @@ import { deriveRunlessWorkStartedAt, deriveThreadStructureRuntime, } from "./state/threadExecution.ts"; -import { - mergeOlderHistoryIntoProjection, - mergeOlderSubagentsIntoProjection, -} from "./state/threadHistoryMerge.ts"; import { applyThreadHistoryPage, applyThreadStreamItem, initialThreadStreamState, + prependThreadHistory, type ThreadStreamState, } from "./state/threadStream.ts"; @@ -216,6 +215,12 @@ 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; +interface LinkedHistoryWindow { + readonly sequence: number; + readonly cursor: string; + readonly oldest: Pick | null; +} + /** 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; @@ -224,7 +229,8 @@ export interface LinkedThreadView { readonly history: { readonly loading: boolean; readonly failed: boolean }; /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ readonly loadedHistory: { - readonly snapshotCursor: string; + readonly window: LinkedHistoryWindow; + readonly pages: number; readonly nextCursor: string | null; } | null; /** Loads the turns before the ones shown. Does nothing while a page loads or none is left. */ @@ -264,7 +270,7 @@ export const followLinkedThread = (source: { const requests = yield* Queue.unbounded(); let requested = false; let previous = source.previous ?? null; - let snapshotCursor: string | null = null; + let snapshotWindow: LinkedHistoryWindow | null = null; // Both halves below run one step at a time, so each reads the view the other left. let view: LinkedThreadView = { thread: initialThreadStreamState, @@ -272,7 +278,7 @@ export const followLinkedThread = (source: { history: { loading: false, failed: false }, loadedHistory: null, loadEarlier: () => { - if (requested || view.thread.historyCursor === null) return; + if (requested || snapshotWindow === null || view.thread.historyCursor === null) return; requested = true; Queue.offerUnsafe(requests, undefined); }, @@ -281,43 +287,78 @@ export const followLinkedThread = (source: { view = { ...view, ...patch }; return view; }; - const onItem = (item: OrchestrationV2ThreadStreamItem) => { - const thread = applyThreadStreamItem(view.thread, item); + // Only snapshots rebuild history. Live events keep the steady-state reducer path. + const onItem = Effect.fnUntraced(function* (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; - snapshotCursor = thread.historyCursor; const loaded = kept?.loadedHistory; - // A different revision or window can invalidate both the old rows and their cursor. - if ( - kept?.thread.projection && - thread.projection && - kept.thread.sequence === thread.sequence && - loaded && - loaded.snapshotCursor === snapshotCursor - ) { - return show({ - thread: { - ...thread, - projection: mergeOlderSubagentsIntoProjection( - mergeOlderHistoryIntoProjection( - thread.projection, - kept.thread.projection.visibleTurnItems, - ), - kept.thread.projection.subagents, - ), - historyCursor: loaded.nextCursor, - }, - loadedHistory: loaded, - error: null, - }); + const oldest = thread.projection?.visibleTurnItems[0]; + const window: LinkedHistoryWindow | null = + thread.historyCursor === null + ? null + : { + sequence: thread.sequence, + cursor: thread.historyCursor, + oldest: oldest + ? { sourceThreadId: oldest.sourceThreadId, sourceItemId: oldest.sourceItemId } + : null, + }; + snapshotWindow = null; + let pages = 0; + let failed = false; + if (window && kept?.thread.projection && loaded) { + const sameAnchor = + window.oldest !== null && + window.oldest.sourceThreadId === loaded.window.oldest?.sourceThreadId && + window.oldest.sourceItemId === loaded.window.oldest.sourceItemId; + // The cursor embeds the snapshot sequence even when its anchor stays put. + if ( + kept.thread.sequence === window.sequence && + (window.cursor === loaded.window.cursor || + (window.sequence > loaded.window.sequence && sameAnchor)) + ) { + thread = prependThreadHistory( + thread, + { + items: kept.thread.projection.visibleTurnItems, + subagents: kept.thread.projection.subagents, + }, + loaded.nextCursor, + ); + pages = loaded.pages; + } else if ( + window.sequence >= kept.thread.sequence && + window.sequence > loaded.window.sequence + ) { + // Re-read the prior page depth from the new window so removed rows stay removed. + while (pages < loaded.pages && thread.historyCursor !== null) { + const cursor = thread.historyCursor; + const page = yield* Effect.option(source.historyPage(cursor)); + if (Option.isNone(page) || page.value.snapshotSequence < window.sequence) { + failed = true; + break; + } + thread = applyThreadHistoryPage(thread, cursor, page.value); + pages += 1; + if (thread.historyCursor === cursor) break; + } + } } - return show({ thread, loadedHistory: null, error: null }); - }; - const attempt = (): Stream.Stream => + snapshotWindow = window; + return show({ + thread, + loadedHistory: + window && pages > 0 ? { window, pages, nextCursor: thread.historyCursor } : null, + history: { loading: false, failed }, + error: null, + }); + }); + const attempt = (): Stream.Stream => source.items.pipe( - Stream.map(onItem), + Stream.mapEffect(onItem), Stream.catch((error) => isLinkedThreadUnreachable(error) ? Stream.make(show({ error })).pipe( @@ -332,7 +373,8 @@ export const followLinkedThread = (source: { Stream.flatMap(() => Stream.suspend(() => { const cursor = view.thread.historyCursor; - if (cursor === null) { + const window = snapshotWindow; + if (cursor === null || window === null) { requested = false; return Stream.empty; } @@ -342,17 +384,25 @@ export const followLinkedThread = (source: { source.historyPage(cursor).pipe( Effect.match({ onSuccess: (page) => { + if (snapshotWindow !== window) return null; const thread = applyThreadHistoryPage(view.thread, cursor, page); return show({ thread, loadedHistory: - thread !== view.thread && snapshotCursor !== null - ? { snapshotCursor, nextCursor: thread.historyCursor } + thread !== view.thread + ? { + window, + pages: (view.loadedHistory?.pages ?? 0) + 1, + nextCursor: thread.historyCursor, + } : view.loadedHistory, history: { loading: false, failed: false }, }); }, - onFailure: () => show({ history: { loading: false, failed: true } }), + onFailure: () => + snapshotWindow === window + ? show({ history: { loading: false, failed: true } }) + : null, }), Effect.ensuring( Effect.sync(() => { @@ -365,6 +415,7 @@ export const followLinkedThread = (source: { ); }), ), + Stream.filter((view) => view !== null), ); return Stream.merge(attempt(), earlier, { haltStrategy: "left" }); }), diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 15a0c46ee2e4f..52dc39361baa2 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,5 +1,7 @@ +import * as NodeBuffer from "node:buffer"; import { EnvironmentId, + EventId, MessageId, TurnItemId, WS_METHODS, @@ -173,6 +175,151 @@ it.effect.each([ }).pipe(Effect.scoped), ); +it.effect.each([ + "live update", + "away update", + "window moves", + "history removed", + "route restart", +] as const)("shows the current linked history on reopen (%s)", (change) => + Effect.gen(function* () { + const recent = messageRow("Recent message", 3); + const older = messageRow("Earlier message", 2); + const oldest = messageRow("Oldest message", 1); + const latest = messageRow("Latest message", 4); + const cursorAt = (sequence: number, row: OrchestrationV2ProjectedTurnItem) => + NodeBuffer.Buffer.from( + JSON.stringify({ + v: 1, + seq: sequence, + st: row.sourceThreadId, + si: row.sourceItemId, + p: row.item.ordinal - 1, + }), + ).toString("base64url"); + const snapshot = ( + snapshotSequence: number, + title: string, + row = recent, + ): OrchestrationV2ThreadStreamItem => ({ + kind: "snapshot", + snapshotSequence, + projection: { + ...v2Projection, + thread: { ...v2Projection.thread, title }, + turnItems: [row.item], + visibleTurnItems: [row], + }, + historyCursor: cursorAt(snapshotSequence, row), + 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); + const revision = cursor === cursorAt(7, recent) ? 7 : 8; + return change === "history removed" && revision === 8 + ? { snapshotSequence: 8, items: [oldest], nextCursor: null, hasMoreHistory: false } + : { + snapshotSequence: revision, + items: cursor === cursorAt(8, latest) ? [older, recent] : [older], + nextCursor: cursorAt(revision, older), + hasMoreHistory: true, + }; + }), + } 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 route = yield* SubscriptionRef.make(0); + const environment = EnvironmentRegistry.of({ + followStream: (_id, stream) => + SubscriptionRef.changes(route).pipe( + Stream.switchMap(() => Stream.provideService(stream, EnvironmentSupervisor, supervisor)), + ), + } as Pick as EnvironmentRegistry["Service"]); + const runtime = Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)); + const links = createPeerLinkEnvironmentAtoms(runtime); + 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 unmount = open(); + const first = yield* Queue.take(subscriptions); + yield* Queue.offer(first.items, snapshot(7, "Original")); + (yield* Queue.take(views)).loadEarlier(); + yield* Queue.take(views); // Loading. + expect((yield* Queue.take(views)).thread.historyCursor).toBe(cursorAt(7, older)); + + if (change === "live update") { + yield* Queue.offer(first.items, { + kind: "event", + sequence: 8, + event: { + id: EventId.make("retitle"), + type: "thread.metadata-updated", + threadId: v2ThreadId, + occurredAt: v2Now, + payload: { ...v2Projection.thread, title: "Renamed" }, + }, + }); + expect((yield* Queue.take(views)).thread.sequence).toBe(8); + } + if (change === "route restart") { + yield* SubscriptionRef.set(route, 1); + } else { + unmount(); + yield* Deferred.await(first.stopped); + open(); + } + const reopened = yield* Queue.take(subscriptions); + const sequence = change === "route restart" ? 7 : 8; + const title = change === "route restart" ? "Original" : "Renamed"; + const moved = change === "window moves"; + yield* Queue.offer(reopened.items, snapshot(sequence, title, moved ? latest : recent)); + const resumed = yield* Queue.take(views); + const removed = change === "history removed"; + const refetched = removed || moved || change === "away update"; + expect(resumed.thread.projection?.thread.title).toBe(title); + expect(resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId)).toEqual([ + (removed ? oldest : older).sourceItemId, + recent.sourceItemId, + ...(moved ? [latest.sourceItemId] : []), + ]); + expect(resumed.thread.historyCursor).toBe(removed ? null : cursorAt(refetched ? 8 : 7, older)); + expect(requested).toEqual( + refetched + ? [cursorAt(7, recent), cursorAt(8, moved ? latest : recent)] + : [cursorAt(7, recent)], + ); + }).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 2fefb0453b9cf..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"; @@ -75,12 +76,14 @@ export function createPeerLinkEnvironmentAtoms( .atom(({ registry }) => followStreamInEnvironment( environmentId, - followLinkedThread({ - items: subscribe(WS_METHODS.peerLinksSubscribeThread, input), - historyPage: (cursor) => - request(WS_METHODS.peerLinksThreadHistoryPage, { ...input, cursor }), - previous: registry.get(kept), - }), + 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}`)); 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, }; } From b3a86bcba3e492cab03ffcd358b2f88aa5e4e3df Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:13:13 +0100 Subject: [PATCH 5/7] fix: restore linked history through the previously loaded boundary Co-authored-by: GPT 6.2 Sol --- packages/client-runtime/src/linkedThread.ts | 209 ++++++++++-------- .../src/state/peerLinks.test.ts | 170 ++++++++++---- 2 files changed, 247 insertions(+), 132 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 91b73257734fd..7402cb167f387 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -8,8 +8,8 @@ import type { ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; -import * as Option from "effect/Option"; 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"; @@ -215,10 +215,23 @@ 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; - readonly oldest: Pick | null; +} + +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. */ @@ -230,8 +243,9 @@ export interface LinkedThreadView { /** Pagination progress survives the temporary view that hides the cursor during reconnect. */ readonly loadedHistory: { readonly window: LinkedHistoryWindow; - readonly pages: number; 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; @@ -267,58 +281,47 @@ export const followLinkedThread = (source: { }): Stream.Stream => Stream.unwrap( Effect.gen(function* () { - const requests = yield* Queue.unbounded(); + const requests = yield* Queue.unbounded(); let requested = false; let previous = source.previous ?? null; let snapshotWindow: LinkedHistoryWindow | null = null; - // Both halves below run one step at a time, so each reads the view the other left. + 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 || snapshotWindow === null || 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; }; - // Only snapshots rebuild history. Live events keep the steady-state reducer path. - const onItem = Effect.fnUntraced(function* (item: OrchestrationV2ThreadStreamItem) { + + 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 oldest = thread.projection?.visibleTurnItems[0]; - const window: LinkedHistoryWindow | null = + const window = thread.historyCursor === null ? null - : { - sequence: thread.sequence, - cursor: thread.historyCursor, - oldest: oldest - ? { sourceThreadId: oldest.sourceThreadId, sourceItemId: oldest.sourceItemId } - : null, - }; - snapshotWindow = null; - let pages = 0; - let failed = false; + : { sequence: thread.sequence, cursor: thread.historyCursor }; + let loadedHistory: LinkedThreadView["loadedHistory"] = null; if (window && kept?.thread.projection && loaded) { - const sameAnchor = - window.oldest !== null && - window.oldest.sourceThreadId === loaded.window.oldest?.sourceThreadId && - window.oldest.sourceItemId === loaded.window.oldest.sourceItemId; - // The cursor embeds the snapshot sequence even when its anchor stays put. + // A live update can advance the revision and move the window without invalidating held rows. if ( kept.thread.sequence === window.sequence && - (window.cursor === loaded.window.cursor || - (window.sequence > loaded.window.sequence && sameAnchor)) + (window.sequence > loaded.window.sequence || window.cursor === loaded.window.cursor) ) { thread = prependThreadHistory( thread, @@ -328,40 +331,46 @@ export const followLinkedThread = (source: { }, loaded.nextCursor, ); - pages = loaded.pages; - } else if ( - window.sequence >= kept.thread.sequence && - window.sequence > loaded.window.sequence - ) { - // Re-read the prior page depth from the new window so removed rows stay removed. - while (pages < loaded.pages && thread.historyCursor !== null) { - const cursor = thread.historyCursor; - const page = yield* Effect.option(source.historyPage(cursor)); - if (Option.isNone(page) || page.value.snapshotSequence < window.sequence) { - failed = true; - break; - } - thread = applyThreadHistoryPage(thread, cursor, page.value); - pages += 1; - if (thread.historyCursor === cursor) break; + 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: - window && pages > 0 ? { window, pages, nextCursor: thread.historyCursor } : null, - history: { loading: false, failed }, + loadedHistory, + history: { loading: requested, failed: false }, error: null, }); - }); - const attempt = (): Stream.Stream => + }; + + const attempt = (): Stream.Stream< + | { readonly kind: "item"; readonly item: OrchestrationV2ThreadStreamItem } + | { readonly kind: "unreachable"; readonly error: E }, + E, + R + > => source.items.pipe( - Stream.mapEffect(onItem), + 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))), ), @@ -369,54 +378,66 @@ export const followLinkedThread = (source: { : Stream.fail(error), ), ); + const earlier = Stream.fromQueue(requests).pipe( - Stream.flatMap(() => - Stream.suspend(() => { - const cursor = view.thread.historyCursor; - const window = snapshotWindow; - if (cursor === null || window === 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) => { - if (snapshotWindow !== window) return null; - const thread = applyThreadHistoryPage(view.thread, cursor, page); - return show({ - thread, - loadedHistory: - thread !== view.thread - ? { - window, - pages: (view.loadedHistory?.pages ?? 0) + 1, - nextCursor: thread.historyCursor, - } - : view.loadedHistory, - history: { loading: false, failed: false }, - }); - }, - onFailure: () => - snapshotWindow === window - ? show({ history: { loading: false, failed: true } }) - : null, - }), - 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 })), ), ), ), ), - ); - }), ), - Stream.filter((view) => view !== null), ); - 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(page.success.items, 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/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 52dc39361baa2..73768ab579ab7 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,4 +1,3 @@ -import * as NodeBuffer from "node:buffer"; import { EnvironmentId, EventId, @@ -177,26 +176,29 @@ it.effect.each([ it.effect.each([ "live update", + "live window moves", "away update", "window moves", + "history request fails", + "history request waits", "history removed", "route restart", ] as const)("shows the current linked history on reopen (%s)", (change) => Effect.gen(function* () { - const recent = messageRow("Recent message", 3); const older = messageRow("Earlier message", 2); const oldest = messageRow("Oldest message", 1); - const latest = messageRow("Latest message", 4); - const cursorAt = (sequence: number, row: OrchestrationV2ProjectedTurnItem) => - NodeBuffer.Buffer.from( - JSON.stringify({ - v: 1, - seq: sequence, - st: row.sourceThreadId, - si: row.sourceItemId, - p: row.item.ordinal - 1, - }), - ).toString("base64url"); + // One new turn pushes the previous boundary past a full 20-turn page. + const between = + change === "window moves" + ? Array.from({ length: 19 }, (_, index) => messageRow(`Turn ${index + 3}`, index + 3)) + : []; + const recent = messageRow("Recent message", between.length + 3); + const latest = messageRow("Latest message", between.length + 4); + const originalCursor = "original-window"; + const refreshedCursor = "refreshed-window"; + const originalNext = "original-next"; + const refreshedNext = "refreshed-next"; + const restoredNext = "restored-next"; const snapshot = ( snapshotSequence: number, title: string, @@ -210,7 +212,7 @@ it.effect.each([ turnItems: [row.item], visibleTurnItems: [row], }, - historyCursor: cursorAt(snapshotSequence, row), + historyCursor: snapshotSequence === 7 ? originalCursor : refreshedCursor, hasMoreHistory: true, }); const subscriptions = yield* Queue.unbounded<{ @@ -218,6 +220,7 @@ it.effect.each([ stopped: Deferred.Deferred; }>(); const requested: string[] = []; + const releasePage = yield* Deferred.make(); const client = { [WS_METHODS.peerLinksSubscribeThread]: () => Stream.unwrap( @@ -230,17 +233,54 @@ it.effect.each([ }), ), [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) => - Effect.sync((): OrchestrationV2ThreadHistoryPage => { + Effect.gen(function* (): Effect.fn.Return { requested.push(cursor); - const revision = cursor === cursorAt(7, recent) ? 7 : 8; - return change === "history removed" && revision === 8 - ? { snapshotSequence: 8, items: [oldest], nextCursor: null, hasMoreHistory: false } - : { - snapshotSequence: revision, - items: cursor === cursorAt(8, latest) ? [older, recent] : [older], - nextCursor: cursorAt(revision, older), - hasMoreHistory: true, - }; + if (cursor === originalCursor) { + return { + snapshotSequence: 7, + items: [older, ...between], + nextCursor: originalNext, + hasMoreHistory: true, + }; + } + if ( + change === "history request fails" && + cursor === refreshedCursor && + requested.filter((request) => request === cursor).length === 1 + ) { + return yield* Effect.fail("history unavailable"); + } + if (change === "history request waits") yield* Deferred.await(releasePage); + if (change === "history removed") { + return { + snapshotSequence: 8, + items: [oldest], + nextCursor: null, + hasMoreHistory: false, + }; + } + if (change === "window moves" && cursor === refreshedCursor) { + return { + snapshotSequence: 8, + items: [...between, recent], + nextCursor: refreshedNext, + hasMoreHistory: true, + }; + } + if (cursor === refreshedNext) { + return { + snapshotSequence: 8, + items: [oldest, older], + nextCursor: null, + hasMoreHistory: false, + }; + } + return { + snapshotSequence: 8, + items: [older], + nextCursor: restoredNext, + hasMoreHistory: true, + }; }), } as unknown as RpcSession["client"]; const target = { @@ -269,12 +309,12 @@ it.effect.each([ registry.subscribe(links.threadView(target), (result) => { if (AsyncResult.isSuccess(result)) Queue.offerUnsafe(views, result.value); }); - const unmount = open(); + let unmount = open(); const first = yield* Queue.take(subscriptions); yield* Queue.offer(first.items, snapshot(7, "Original")); (yield* Queue.take(views)).loadEarlier(); yield* Queue.take(views); // Loading. - expect((yield* Queue.take(views)).thread.historyCursor).toBe(cursorAt(7, older)); + expect((yield* Queue.take(views)).thread.historyCursor).toBe(originalNext); if (change === "live update") { yield* Queue.offer(first.items, { @@ -290,33 +330,87 @@ it.effect.each([ }); expect((yield* Queue.take(views)).thread.sequence).toBe(8); } + if (change === "live window moves") { + yield* Queue.offer(first.items, { + kind: "event", + sequence: 8, + event: { + id: EventId.make("latest-item"), + type: "turn-item.updated", + threadId: v2ThreadId, + occurredAt: v2Now, + payload: latest.item, + }, + }); + expect( + (yield* Queue.take(views)).thread.projection?.visibleTurnItems.at(-1)?.sourceItemId, + ).toBe(latest.sourceItemId); + } if (change === "route restart") { yield* SubscriptionRef.set(route, 1); } else { unmount(); yield* Deferred.await(first.stopped); - open(); + unmount = open(); } - const reopened = yield* Queue.take(subscriptions); + let reopened = yield* Queue.take(subscriptions); const sequence = change === "route restart" ? 7 : 8; const title = change === "route restart" ? "Original" : "Renamed"; - const moved = change === "window moves"; - yield* Queue.offer(reopened.items, snapshot(sequence, title, moved ? latest : recent)); - const resumed = yield* Queue.take(views); + const moved = change === "window moves" || change === "live window moves"; const removed = change === "history removed"; - const refetched = removed || moved || change === "away update"; + const refetched = + removed || + change === "window moves" || + change === "away update" || + change === "history request fails" || + change === "history request waits"; + const incoming = snapshot(sequence, title, moved ? latest : recent); + yield* Queue.offer(reopened.items, incoming); + let resumed = yield* Queue.take(views); expect(resumed.thread.projection?.thread.title).toBe(title); + if (change === "history request waits") { + expect(resumed.history.loading).toBe(true); + yield* Queue.offer(reopened.items, { + kind: "event", + sequence: 9, + event: { + id: EventId.make("retitle-during-restore"), + type: "thread.metadata-updated", + threadId: v2ThreadId, + occurredAt: v2Now, + payload: { ...v2Projection.thread, title: "Renamed again" }, + }, + }); + expect((yield* Queue.take(views)).thread.projection?.thread.title).toBe("Renamed again"); + yield* Deferred.succeed(releasePage, undefined); + } + while (resumed.history.loading) resumed = yield* Queue.take(views); + if (change === "history request fails") { + expect(resumed.history.failed).toBe(true); + unmount(); + yield* Deferred.await(reopened.stopped); + open(); + reopened = yield* Queue.take(subscriptions); + yield* Queue.offer(reopened.items, incoming); + resumed = yield* Queue.take(views); + while (resumed.history.loading) resumed = yield* Queue.take(views); + } expect(resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId)).toEqual([ - (removed ? oldest : older).sourceItemId, + ...(removed || change === "window moves" ? [oldest.sourceItemId] : []), + ...(removed ? [] : [older.sourceItemId]), + ...between.map((row) => row.sourceItemId), recent.sourceItemId, ...(moved ? [latest.sourceItemId] : []), ]); - expect(resumed.thread.historyCursor).toBe(removed ? null : cursorAt(refetched ? 8 : 7, older)); - expect(requested).toEqual( - refetched - ? [cursorAt(7, recent), cursorAt(8, moved ? latest : recent)] - : [cursorAt(7, recent)], + expect(resumed.thread.historyCursor).toBe( + removed || change === "window moves" ? null : refetched ? restoredNext : originalNext, ); + expect(requested).toEqual([ + originalCursor, + ...(refetched ? [refreshedCursor] : []), + ...(change === "window moves" ? [refreshedNext] : []), + ...(change === "history request fails" ? [refreshedCursor] : []), + ]); }).pipe(Effect.scoped), ); From ca2905d924dd8a25c376c929b4c80f3f78d86dc4 Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:19:31 +0100 Subject: [PATCH 6/7] fix: keep rolled-back messages out of linked history backfill Co-authored-by: GPT 6.2 Sol --- packages/client-runtime/src/linkedThread.ts | 3 +- .../src/state/peerLinks.test.ts | 79 +++++++++++++++++-- .../src/state/threadHistoryMerge.ts | 5 ++ 3 files changed, 80 insertions(+), 7 deletions(-) diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 7402cb167f387..69b179e08f671 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -425,7 +425,8 @@ export const followLinkedThread = (source: { const nextCursor = thread.historyCursor; if ( restoreThrough !== null && - (nextCursor === null || includesHistoryAnchor(page.success.items, restoreThrough)) + (nextCursor === null || + includesHistoryAnchor(thread.projection?.visibleTurnItems ?? [], restoreThrough)) ) { restoreThrough = null; } diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 73768ab579ab7..84185cf271ef3 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -2,9 +2,12 @@ import { EnvironmentId, EventId, MessageId, + NodeId, + RunId, TurnItemId, WS_METHODS, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2Run, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, type PeerLinkSummary, @@ -181,11 +184,31 @@ it.effect.each([ "window moves", "history request fails", "history request waits", + "rollback during backfill", "history removed", "route restart", ] as const)("shows the current linked history on reopen (%s)", (change) => Effect.gen(function* () { - const older = messageRow("Earlier message", 2); + const rolledBack = change === "rollback during backfill"; + const earlier = messageRow("Earlier message", 2); + const run: OrchestrationV2Run = { + id: RunId.make("earlier-run"), + threadId: v2ThreadId, + ordinal: 1, + providerInstanceId: v2Projection.thread.providerInstanceId, + modelSelection: v2Projection.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("Earlier message"), + rootNodeId: NodeId.make("earlier-node"), + activeAttemptId: null, + status: "completed", + requestedAt: v2Now, + startedAt: v2Now, + completedAt: v2Now, + checkpointId: null, + contextHandoffId: null, + }; + const older = rolledBack ? { ...earlier, item: { ...earlier.item, runId: run.id } } : earlier; const oldest = messageRow("Oldest message", 1); // One new turn pushes the previous boundary past a full 20-turn page. const between = @@ -209,6 +232,7 @@ it.effect.each([ projection: { ...v2Projection, thread: { ...v2Projection.thread, title }, + runs: rolledBack ? [run] : [], turnItems: [row.item], visibleTurnItems: [row], }, @@ -220,6 +244,7 @@ it.effect.each([ stopped: Deferred.Deferred; }>(); const requested: string[] = []; + const pageStarted = yield* Deferred.make(); const releasePage = yield* Deferred.make(); const client = { [WS_METHODS.peerLinksSubscribeThread]: () => @@ -250,7 +275,18 @@ it.effect.each([ ) { return yield* Effect.fail("history unavailable"); } - if (change === "history request waits") yield* Deferred.await(releasePage); + if ((change === "history request waits" || rolledBack) && cursor === refreshedCursor) { + yield* Deferred.succeed(pageStarted, undefined); + yield* Deferred.await(releasePage); + } + if (rolledBack && cursor === restoredNext) { + return { + snapshotSequence: 9, + items: [oldest], + nextCursor: null, + hasMoreHistory: false, + }; + } if (change === "history removed") { return { snapshotSequence: 8, @@ -360,6 +396,7 @@ it.effect.each([ const removed = change === "history removed"; const refetched = removed || + rolledBack || change === "window moves" || change === "away update" || change === "history request fails" || @@ -384,7 +421,32 @@ it.effect.each([ expect((yield* Queue.take(views)).thread.projection?.thread.title).toBe("Renamed again"); yield* Deferred.succeed(releasePage, undefined); } - while (resumed.history.loading) resumed = yield* Queue.take(views); + if (rolledBack) { + yield* Deferred.await(pageStarted); + yield* Queue.offer(reopened.items, { + kind: "event", + sequence: 9, + event: { + id: EventId.make("rollback-during-backfill"), + type: "run.updated", + threadId: v2ThreadId, + runId: run.id, + occurredAt: v2Now, + payload: { ...run, status: "rolled_back" }, + }, + }); + resumed = yield* Queue.take(views); + expect(resumed.thread.sequence).toBe(9); + yield* Deferred.succeed(releasePage, undefined); + } + while (resumed.history.loading) { + resumed = yield* Queue.take(views); + if (rolledBack) { + expect( + resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId), + ).not.toContain(older.sourceItemId); + } + } if (change === "history request fails") { expect(resumed.history.failed).toBe(true); unmount(); @@ -396,19 +458,24 @@ it.effect.each([ while (resumed.history.loading) resumed = yield* Queue.take(views); } expect(resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId)).toEqual([ - ...(removed || change === "window moves" ? [oldest.sourceItemId] : []), - ...(removed ? [] : [older.sourceItemId]), + ...(removed || rolledBack || change === "window moves" ? [oldest.sourceItemId] : []), + ...(removed || rolledBack ? [] : [older.sourceItemId]), ...between.map((row) => row.sourceItemId), recent.sourceItemId, ...(moved ? [latest.sourceItemId] : []), ]); expect(resumed.thread.historyCursor).toBe( - removed || change === "window moves" ? null : refetched ? restoredNext : originalNext, + removed || rolledBack || change === "window moves" + ? null + : refetched + ? restoredNext + : originalNext, ); expect(requested).toEqual([ originalCursor, ...(refetched ? [refreshedCursor] : []), ...(change === "window moves" ? [refreshedNext] : []), + ...(rolledBack ? [restoredNext] : []), ...(change === "history request fails" ? [refreshedCursor] : []), ]); }).pipe(Effect.scoped), 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); From 2d39e57290abd62c71cdf354e8cd3fed9a648949 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 21 Nov 2026 20:43:45 +0000 Subject: [PATCH 7/7] test: cut linked history tests to one case per layer Co-Authored-By: Claude Opus 5.5 --- .../client-runtime/src/linkedThread.test.ts | 79 +++- .../src/state/orchestrationV2TestFixtures.ts | 37 ++ .../src/state/peerLinks.test.ts | 417 ++---------------- .../src/state/threadHistoryMerge.test.ts | 7 +- 4 files changed, 150 insertions(+), 390 deletions(-) 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/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 84185cf271ef3..75430e340fbff 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,13 +1,6 @@ import { EnvironmentId, - EventId, - MessageId, - NodeId, - RunId, - TurnItemId, WS_METHODS, - type OrchestrationV2ProjectedTurnItem, - type OrchestrationV2Run, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, type PeerLinkSummary, @@ -27,62 +20,20 @@ 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 { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.ts"; -function messageRow(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: [], - }, - }; -} - -it.effect.each([ - [null, 8], - ["before-earlier", 7], -] as const)( - "keeps loaded messages across a linked-thread subscription reopen (next cursor %s)", - ([nextCursor, refreshedSequence]) => +// 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 = messageRow("Recent message", 2); - const older = messageRow("Earlier message", 1); - const snapshot = ( - snapshotSequence: number, - historyCursor: string, - ): OrchestrationV2ThreadStreamItem => ({ + const recent = v2MessageRow("Recent message", 2); + const older = v2MessageRow("Earlier message", 1); + const snapshot = (historyCursor: string): OrchestrationV2ThreadStreamItem => ({ kind: "snapshot", - snapshotSequence, - projection: { - ...v2Projection, - turnItems: [recent.item], - visibleTurnItems: [recent], - }, + snapshotSequence: 7, + projection: { ...v2Projection, turnItems: [recent.item], visibleTurnItems: [recent] }, historyCursor, hasMoreHistory: true, }); @@ -105,12 +56,14 @@ it.effect.each([ [WS_METHODS.peerLinksThreadHistoryPage]: ({ cursor }: { cursor: string }) => Effect.sync((): OrchestrationV2ThreadHistoryPage => { requested.push(cursor); - return { - snapshotSequence: 7, - items: cursor === "before-recent" ? [older] : [], - nextCursor: cursor === "before-recent" ? nextCursor : null, - hasMoreHistory: cursor === "before-recent" && nextCursor !== null, - }; + 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 = { @@ -125,28 +78,24 @@ it.effect.each([ followStream: (_id, stream) => Stream.provideService(stream, EnvironmentSupervisor, supervisor), } as Pick as EnvironmentRegistry["Service"]); - const runtime = Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)); - const links = createPeerLinkEnvironmentAtoms(runtime); + const links = createPeerLinkEnvironmentAtoms( + Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)), + ); const registry = yield* Effect.acquireRelease( Effect.sync(() => AtomRegistry.make()), (registry) => Effect.sync(() => registry.dispose()), ); - const live = links.threadView(target); - const kept = links.lastThreadView(target); const views = yield* Queue.unbounded(); const open = () => - registry.subscribe(live, (result) => { - if (AsyncResult.isSuccess(result)) { - const view = registry.get(kept); - if (view?.thread.projection) Queue.offerUnsafe(views, view); - } + 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(7, "before-recent")); + 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([ @@ -158,329 +107,21 @@ it.effect.each([ open(); const reopened = yield* Queue.take(subscriptions); - yield* Queue.offer(reopened.items, snapshot(7, "before-recent")); + yield* Queue.offer(reopened.items, snapshot("before-recent")); const resumed = yield* Queue.take(views); expect(visibleMessages(resumed)).toEqual([older.sourceItemId, recent.sourceItemId]); - expect(resumed.thread.historyCursor).toBe(nextCursor); + // 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"]); - if (nextCursor !== null) { - resumed.loadEarlier(); - yield* Queue.take(views); // Loading. - expect((yield* Queue.take(views)).thread.historyCursor).toBeNull(); - expect(requested).toEqual(["before-recent", nextCursor]); - } - yield* Queue.offer(reopened.items, snapshot(refreshedSequence, "new-window")); + // 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), ); -it.effect.each([ - "live update", - "live window moves", - "away update", - "window moves", - "history request fails", - "history request waits", - "rollback during backfill", - "history removed", - "route restart", -] as const)("shows the current linked history on reopen (%s)", (change) => - Effect.gen(function* () { - const rolledBack = change === "rollback during backfill"; - const earlier = messageRow("Earlier message", 2); - const run: OrchestrationV2Run = { - id: RunId.make("earlier-run"), - threadId: v2ThreadId, - ordinal: 1, - providerInstanceId: v2Projection.thread.providerInstanceId, - modelSelection: v2Projection.thread.modelSelection, - providerThreadId: null, - userMessageId: MessageId.make("Earlier message"), - rootNodeId: NodeId.make("earlier-node"), - activeAttemptId: null, - status: "completed", - requestedAt: v2Now, - startedAt: v2Now, - completedAt: v2Now, - checkpointId: null, - contextHandoffId: null, - }; - const older = rolledBack ? { ...earlier, item: { ...earlier.item, runId: run.id } } : earlier; - const oldest = messageRow("Oldest message", 1); - // One new turn pushes the previous boundary past a full 20-turn page. - const between = - change === "window moves" - ? Array.from({ length: 19 }, (_, index) => messageRow(`Turn ${index + 3}`, index + 3)) - : []; - const recent = messageRow("Recent message", between.length + 3); - const latest = messageRow("Latest message", between.length + 4); - const originalCursor = "original-window"; - const refreshedCursor = "refreshed-window"; - const originalNext = "original-next"; - const refreshedNext = "refreshed-next"; - const restoredNext = "restored-next"; - const snapshot = ( - snapshotSequence: number, - title: string, - row = recent, - ): OrchestrationV2ThreadStreamItem => ({ - kind: "snapshot", - snapshotSequence, - projection: { - ...v2Projection, - thread: { ...v2Projection.thread, title }, - runs: rolledBack ? [run] : [], - turnItems: [row.item], - visibleTurnItems: [row], - }, - historyCursor: snapshotSequence === 7 ? originalCursor : refreshedCursor, - hasMoreHistory: true, - }); - const subscriptions = yield* Queue.unbounded<{ - items: Queue.Queue; - stopped: Deferred.Deferred; - }>(); - const requested: string[] = []; - const pageStarted = yield* Deferred.make(); - const releasePage = yield* Deferred.make(); - 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.gen(function* (): Effect.fn.Return { - requested.push(cursor); - if (cursor === originalCursor) { - return { - snapshotSequence: 7, - items: [older, ...between], - nextCursor: originalNext, - hasMoreHistory: true, - }; - } - if ( - change === "history request fails" && - cursor === refreshedCursor && - requested.filter((request) => request === cursor).length === 1 - ) { - return yield* Effect.fail("history unavailable"); - } - if ((change === "history request waits" || rolledBack) && cursor === refreshedCursor) { - yield* Deferred.succeed(pageStarted, undefined); - yield* Deferred.await(releasePage); - } - if (rolledBack && cursor === restoredNext) { - return { - snapshotSequence: 9, - items: [oldest], - nextCursor: null, - hasMoreHistory: false, - }; - } - if (change === "history removed") { - return { - snapshotSequence: 8, - items: [oldest], - nextCursor: null, - hasMoreHistory: false, - }; - } - if (change === "window moves" && cursor === refreshedCursor) { - return { - snapshotSequence: 8, - items: [...between, recent], - nextCursor: refreshedNext, - hasMoreHistory: true, - }; - } - if (cursor === refreshedNext) { - return { - snapshotSequence: 8, - items: [oldest, older], - nextCursor: null, - hasMoreHistory: false, - }; - } - return { - snapshotSequence: 8, - items: [older], - nextCursor: restoredNext, - hasMoreHistory: true, - }; - }), - } 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 route = yield* SubscriptionRef.make(0); - const environment = EnvironmentRegistry.of({ - followStream: (_id, stream) => - SubscriptionRef.changes(route).pipe( - Stream.switchMap(() => Stream.provideService(stream, EnvironmentSupervisor, supervisor)), - ), - } as Pick as EnvironmentRegistry["Service"]); - const runtime = Atom.runtime(Layer.succeed(EnvironmentRegistry, environment)); - const links = createPeerLinkEnvironmentAtoms(runtime); - 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); - }); - let unmount = open(); - const first = yield* Queue.take(subscriptions); - yield* Queue.offer(first.items, snapshot(7, "Original")); - (yield* Queue.take(views)).loadEarlier(); - yield* Queue.take(views); // Loading. - expect((yield* Queue.take(views)).thread.historyCursor).toBe(originalNext); - - if (change === "live update") { - yield* Queue.offer(first.items, { - kind: "event", - sequence: 8, - event: { - id: EventId.make("retitle"), - type: "thread.metadata-updated", - threadId: v2ThreadId, - occurredAt: v2Now, - payload: { ...v2Projection.thread, title: "Renamed" }, - }, - }); - expect((yield* Queue.take(views)).thread.sequence).toBe(8); - } - if (change === "live window moves") { - yield* Queue.offer(first.items, { - kind: "event", - sequence: 8, - event: { - id: EventId.make("latest-item"), - type: "turn-item.updated", - threadId: v2ThreadId, - occurredAt: v2Now, - payload: latest.item, - }, - }); - expect( - (yield* Queue.take(views)).thread.projection?.visibleTurnItems.at(-1)?.sourceItemId, - ).toBe(latest.sourceItemId); - } - if (change === "route restart") { - yield* SubscriptionRef.set(route, 1); - } else { - unmount(); - yield* Deferred.await(first.stopped); - unmount = open(); - } - let reopened = yield* Queue.take(subscriptions); - const sequence = change === "route restart" ? 7 : 8; - const title = change === "route restart" ? "Original" : "Renamed"; - const moved = change === "window moves" || change === "live window moves"; - const removed = change === "history removed"; - const refetched = - removed || - rolledBack || - change === "window moves" || - change === "away update" || - change === "history request fails" || - change === "history request waits"; - const incoming = snapshot(sequence, title, moved ? latest : recent); - yield* Queue.offer(reopened.items, incoming); - let resumed = yield* Queue.take(views); - expect(resumed.thread.projection?.thread.title).toBe(title); - if (change === "history request waits") { - expect(resumed.history.loading).toBe(true); - yield* Queue.offer(reopened.items, { - kind: "event", - sequence: 9, - event: { - id: EventId.make("retitle-during-restore"), - type: "thread.metadata-updated", - threadId: v2ThreadId, - occurredAt: v2Now, - payload: { ...v2Projection.thread, title: "Renamed again" }, - }, - }); - expect((yield* Queue.take(views)).thread.projection?.thread.title).toBe("Renamed again"); - yield* Deferred.succeed(releasePage, undefined); - } - if (rolledBack) { - yield* Deferred.await(pageStarted); - yield* Queue.offer(reopened.items, { - kind: "event", - sequence: 9, - event: { - id: EventId.make("rollback-during-backfill"), - type: "run.updated", - threadId: v2ThreadId, - runId: run.id, - occurredAt: v2Now, - payload: { ...run, status: "rolled_back" }, - }, - }); - resumed = yield* Queue.take(views); - expect(resumed.thread.sequence).toBe(9); - yield* Deferred.succeed(releasePage, undefined); - } - while (resumed.history.loading) { - resumed = yield* Queue.take(views); - if (rolledBack) { - expect( - resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId), - ).not.toContain(older.sourceItemId); - } - } - if (change === "history request fails") { - expect(resumed.history.failed).toBe(true); - unmount(); - yield* Deferred.await(reopened.stopped); - open(); - reopened = yield* Queue.take(subscriptions); - yield* Queue.offer(reopened.items, incoming); - resumed = yield* Queue.take(views); - while (resumed.history.loading) resumed = yield* Queue.take(views); - } - expect(resumed.thread.projection?.visibleTurnItems.map((row) => row.sourceItemId)).toEqual([ - ...(removed || rolledBack || change === "window moves" ? [oldest.sourceItemId] : []), - ...(removed || rolledBack ? [] : [older.sourceItemId]), - ...between.map((row) => row.sourceItemId), - recent.sourceItemId, - ...(moved ? [latest.sourceItemId] : []), - ]); - expect(resumed.thread.historyCursor).toBe( - removed || rolledBack || change === "window moves" - ? null - : refetched - ? restoredNext - : originalNext, - ); - expect(requested).toEqual([ - originalCursor, - ...(refetched ? [refreshedCursor] : []), - ...(change === "window moves" ? [refreshedNext] : []), - ...(rolledBack ? [restoredNext] : []), - ...(change === "history request fails" ? [refreshedCursor] : []), - ]); - }).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/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;