diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index d936fa7726df2..218c3219ffbd0 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -266,11 +266,15 @@ function upsertVisibleTurnItem( // items never received stay absent. function restoreQueuedUserItems( projection: OrchestrationV2ThreadProjection, - runId: OrchestrationV2Run["id"], + runId?: OrchestrationV2Run["id"], ): OrchestrationV2ThreadProjection["visibleTurnItems"] { let visibleTurnItems = projection.visibleTurnItems; for (const item of projection.turnItems) { - if (item.runId !== runId || item.type !== "user_message" || item.inputIntent !== "queued_turn") + if ( + (runId !== undefined && item.runId !== runId) || + item.type !== "user_message" || + item.inputIntent !== "queued_turn" + ) continue; if (!shouldShowLocalTurnItem(projection, item)) continue; visibleTurnItems = upsertVisibleTurnItem( @@ -283,6 +287,20 @@ function restoreQueuedUserItems( return visibleTurnItems; } +// Older caches can retain delivered queued input hidden by the former visibility rule. +// Request cards retained outside the window must not be pulled into the timeline. +export function restoreCachedProjectionVisibility( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + const visibleTurnItems = restoreQueuedUserItems({ + ...projection, + visibleTurnItems: activeVisibleTurnItems(projection), + }); + return visibleTurnItems === projection.visibleTurnItems + ? projection + : { ...projection, visibleTurnItems }; +} + export function applyOrchestrationV2ProjectionEvent( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index d14b8a66c40cd..9dc93757b2269 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -49,7 +49,7 @@ import { decodeOrDiscardOrchestrationCache, } from "../platform/orchestrationCache.ts"; import * as RpcSession from "../rpc/session.ts"; -import { v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { v2MessageRow, v2Now, v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; import { onThreadRequestsResolved, type ThreadRequestsResolved } from "./threadRequests.ts"; import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -423,6 +423,74 @@ const deleted = (sequence = 3): OrchestrationV2ThreadStreamItem => { }; describe("EnvironmentThreads", () => { + it.effect.each(["disk", "retained"] as const)( + "shows a delivered queued message that an older %s cache hid", + (cacheKind) => + Effect.gen(function* () { + // The former rule hid the queued message of a started run that a restart cancelled. + const runId = RunId.make("run-cancelled-after-start"); + const later = v2MessageRow("Later input", 2); + const delivered = { + ...v2MessageRow("Delivered before restart", 1).item, + runId, + inputIntent: "queued_turn", + } as OrchestrationV2TurnItem; + const projection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + runs: [ + { + id: runId, + threadId: THREAD_ID, + ordinal: 1, + providerInstanceId: BASE_PROJECTION.thread.providerInstanceId, + modelSelection: BASE_PROJECTION.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("Delivered before restart"), + rootNodeId: null, + activeAttemptId: null, + status: "cancelled", + requestedAt: v2Now, + startedAt: v2Now, + completedAt: v2Now, + checkpointId: null, + contextHandoffId: null, + }, + ], + turnItems: [delivered, later.item], + visibleTurnItems: [later], + }; + const h = yield* makeHarness({ + loadCached: Effect.succeedSome({ + snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, + projection, + }), + ...(cacheKind === "retained" + ? { + resumeCache: { + owner: undefined, + snapshot: { + state: { + ...EMPTY_ENVIRONMENT_THREAD_STATE, + data: Option.some(projection), + status: "live", + }, + sequence: CACHED_SNAPSHOT_SEQUENCE, + persisted: true, + }, + }, + } + : {}), + completionMarker: true, + }); + yield* Queue.offer(h.inputs, synchronized()); + const state = yield* awaitThreadState(h.observed, (value) => value.status === "live"); + expect( + Option.getOrThrow(state.data).visibleTurnItems.map((row) => row.sourceItemId), + ).toEqual([delivered.id, later.sourceItemId]); + expect(yield* Ref.get(h.loaderCalls)).toBe(0); + }), + ); + it.effect.each([ ["disk", false], ["retained", false], diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index c0921417ba5cf..19af253a6398e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -44,7 +44,10 @@ import { subscriptionRetryDelay, } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; -import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; +import { + applyOrchestrationV2ProjectionEvent, + restoreCachedProjectionVisibility, +} from "./orchestrationV2Projection.ts"; import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; import * as ThreadHistoryController from "./threadHistoryController.ts"; @@ -221,6 +224,7 @@ function matchesThreadSnapshot( function cachedThreadState(value: EnvironmentThreadState): EnvironmentThreadState { return { ...value, + data: Option.map(value.data, restoreCachedProjectionVisibility), status: value.status === "deleted" || (value.status === "live" && Option.isSome(value.data)) ? value.status @@ -290,7 +294,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make loaded, (snapshot) => !hasMissingPendingQuestionCard(snapshot.projection), ); - const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); + const cachedThread = Option.map(cached, (snapshot) => + restoreCachedProjectionVisibility(snapshot.projection), + ); // Seed the resume cursor from the cached snapshot so a warm cache can catch up // via `afterSequence` instead of re-downloading the full thread body. const initialSequence =