diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index b589c114b9..7fb82706b1 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -1,6 +1,9 @@ import { Connection } from "@t3tools/client-runtime/connection"; import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell"; -import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads"; +import { + boundedThreadSnapshotLoaderLayer, + threadHistoryControllerLayer, +} from "@t3tools/client-runtime/state/threads"; import * as Layer from "effect/Layer"; import { Atom } from "effect/unstable/reactivity"; @@ -15,7 +18,11 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe( Layer.provide(runtimeContextLayer), ); -const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer); +const snapshotLoaderLayer = Layer.mergeAll( + boundedThreadSnapshotLoaderLayer, + shellSnapshotLoaderLayer, + threadHistoryControllerLayer, +); type ConnectionLayerSource = | typeof Connection.layer diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 0f5f699c69..22bfba4c35 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -79,7 +79,7 @@ import { COMPOSER_EXPANDED_CHROME, ThreadComposer, } from "./ThreadComposer"; -import { ThreadFeed } from "./ThreadFeed"; +import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed"; import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner"; import { ThreadQueueControl } from "./ThreadQueueControl"; import type { ThreadContentPresentation } from "./threadContentPresentation"; @@ -104,6 +104,8 @@ export interface ThreadDetailScreenProps { readonly connectionStateLabel: EnvironmentConnectionPhase; /** Message sync status for the selected thread (drives the composer status pill). */ readonly threadSyncStatus?: EnvironmentThreadStatus; + /** Progressive history controls for oversized mobile thread opens. */ + readonly historyControls?: ThreadFeedHistoryControls; readonly activeThreadBusy: boolean; readonly canStopThread: boolean; readonly environmentId: EnvironmentId; @@ -637,6 +639,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread contentTopInset={0} contentBottomInset={estimatedOverlayHeight} contentMaxWidth={contentMaxWidth} + historyControls={props.historyControls} topAccessory={ void; +} + export interface ThreadFeedProps { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; @@ -188,6 +180,7 @@ export interface ThreadFeedProps { readonly contentInsetEndAdjustment: SharedValue; readonly contentTopInset?: number; readonly contentBottomInset?: number; + readonly historyControls?: ThreadFeedHistoryControls; readonly topAccessory?: ReactNode; readonly contentMaxWidth?: number; readonly layoutVariant?: LayoutVariant; @@ -1454,6 +1447,41 @@ function compactFileName(filePath: string): string { return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized; } +function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) { + const mutedColor = useThemeColor("--color-icon-subtle"); + const accentColor = useThemeColor("--color-primary"); + if (!props.hasMoreHistory && props.error === null) { + return null; + } + return ( + + {props.hasMoreHistory ? ( + + {props.loading ? ( + + ) : ( + + )} + + {props.loading ? "Loading earlier activity…" : "Load earlier activity"} + + + ) : null} + {props.error !== null ? ( + + {props.error} + + ) : null} + + ); +} + function ThreadFeedPlaceholder(props: { readonly bottomInset: number; readonly detail: string; @@ -1633,11 +1661,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }, [props.onHeaderMaterialVisibilityChange], ); - // True while the viewport sits within ~one screen of the list end — the - // only region where layout shifts should animate. Starts true because the - // list opens pinned to the end. - const nearListEnd = useSharedValue(true); - const handleScroll = useCallback( (event: NativeSyntheticEvent) => { // anchorTopInset, not topContentInset: under automatic insets the list @@ -1645,9 +1668,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // UIKit's adjustedContentInset, so topContentInset is 0 here). Add the // header height back or the material toggles a full header too late. reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6); - const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent; - nearListEnd.value = - contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height; // LegendList recomputes its inset-aware end distance before invoking // this handler, so getState() is current. Only the actual end re-arms // follow: its broader maintain-scroll threshold is large enough for a @@ -1663,13 +1683,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }); } }, - [ - reportHeaderMaterialVisibility, - anchorTopInset, - nearListEnd, - props.listRef, - transitionEndFollow, - ], + [reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow], ); const clearUserScrollSettle = useCallback(() => { if (userScrollSettleTimerRef.current !== null) { @@ -1741,33 +1755,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } }, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]); - // Gated variant of the 180ms feed layout slide. Instant while browsing - // history: maintainVisibleContentPosition compensates the scroll offset in - // the same frame a row's measured size lands, so an instant reposition is - // invisible — animating it is exactly what made cold upward scrolls slide - // and jump. Near the end the slide stays on: streaming growth and sends - // shift rows at rest, where the animation is the thing preventing a hard - // visual snap. - const feedItemLayoutTransition = useMemo(() => { - return (values: LayoutAnimationsValues) => { - "worklet"; - const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0; - return { - initialValues: { - originX: values.currentOriginX, - originY: values.currentOriginY, - width: values.currentWidth, - height: values.currentHeight, - }, - animations: { - originX: withTiming(values.targetOriginX, { duration }), - originY: withTiming(values.targetOriginY, { duration }), - width: withTiming(values.targetWidth, { duration }), - height: withTiming(values.targetHeight, { duration }), - }, - }; - }; - }, [nearListEnd]); const handleViewportLayout = useCallback((event: LayoutChangeEvent) => { const nextWidth = Math.round(event.nativeEvent.layout.width); const nextHeight = Math.round(event.nativeEvent.layout.height); @@ -2098,7 +2085,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } : { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })} {...(anchoredEndSpace ? { anchoredEndSpace } : {})} - itemLayoutAnimation={feedItemLayoutTransition} // Patched LegendList prop (patches/@legendapp__list@3.2.0.patch): // lets its scroll math clamp programmatic scrolls to -headerInset // instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short @@ -2180,6 +2166,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ListHeaderComponent={ <> {usesNativeAutomaticInsets ? null : } + {props.historyControls ? ( + + ) : null} {props.topAccessory} } diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 713f4b3ace..3af9ecf8dc 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -196,6 +196,30 @@ function ThreadRouteContent( const gitActions = useSelectedThreadGitActions(); const requests = useSelectedThreadRequests(); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt"); + const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, { + label: "load earlier thread history", + reportFailure: false, + }); + const historyControls = useMemo(() => { + const history = selectedThreadDetailState.history; + if (!selectedThread) { + return undefined; + } + if (!history.hasMoreHistory && history.error === null) { + return undefined; + } + return { + hasMoreHistory: history.hasMoreHistory, + loading: history.loading, + error: history.error, + onLoadEarlier: () => { + void loadEarlierHistory({ + environmentId: selectedThread.environmentId, + input: { threadId: selectedThread.id }, + }); + }, + }; + }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]); const navigation = useNavigation(); const params = props.route.params; const environmentIdRaw = firstRouteParam(params.environmentId); @@ -761,6 +785,7 @@ function ThreadRouteContent( draftAttachments={composer.draftAttachments} connectionStateLabel={routeConnectionState} threadSyncStatus={selectedThreadDetailState.status} + historyControls={historyControls} activeThreadBusy={composer.activeThreadBusy} canStopThread={composer.interruptibleRunId !== null} environmentId={selectedThread.environmentId} diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index dcef23ce8c..37437c0380 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -239,6 +239,7 @@ export function useThreadOutboxDrain(): void { runtimeMode: settings.runtimeMode, interactionMode: settings.interactionMode, createdAt: queuedMessage.createdAt, + dispatchMode: "start", }, }); return completeDelivery(deliveryResult); diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index 8972a97b8c..b51614b129 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -5,6 +5,7 @@ import type { OrchestrationV2StoredEvent, OrchestrationV2ThreadShell, } from "@t3tools/contracts"; +import { ThreadId } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Stream from "effect/Stream"; @@ -16,6 +17,7 @@ import { shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, + shellStreamItemsFromResumeSnapshot, } from "./ShellStream.ts"; function project(sequence: number, id: string): ApplicationStoredEvent { @@ -198,6 +200,35 @@ describe("shellStreamItemFromEnrichmentRefresh", () => { }); describe("shellStreamItemsFromInitialSnapshot", () => { + it("keeps thread rows out of the metadata-only enrichment frame", () => { + const snapshot = { + ...emptyShellSnapshot, + projects: [ + { id: "project-a", workspaceRoot: "/workspace/a" }, + { id: "project-b", workspaceRoot: "/workspace/b" }, + ], + threads: [shellFixture({})], + archivedThreads: [shellFixture({ id: ThreadId.make("thread-archived"), archivedAt: null })], + } as unknown as OrchestrationV2ShellSnapshot; + + const items = shellStreamItemsFromInitialSnapshot({ + snapshot, + resolvedRepositoryIdentityRoots: ["/workspace/a"], + }); + + expect(items[0]).toEqual({ kind: "snapshot", snapshot }); + expect(items[1]).toMatchObject({ + kind: "snapshot", + snapshot: { + projects: [{ id: "project-a", workspaceRoot: "/workspace/a" }], + threads: [], + archivedThreads: [], + }, + resolvedRepositoryIdentityRoots: ["/workspace/a"], + }); + expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length); + }); + it("emits unmarked authoritative then same-sequence marked enrichment when roots resolved", () => { const snapshot = { ...emptyShellSnapshot, @@ -229,6 +260,20 @@ describe("shellStreamItemsFromInitialSnapshot", () => { }); }); +describe("shellStreamItemsFromResumeSnapshot", () => { + it("never repeats the authoritative shell snapshot", () => { + expect( + shellStreamItemsFromResumeSnapshot({ + snapshot: { + ...emptyShellSnapshot, + threads: [shellFixture({})], + }, + resolvedRepositoryIdentityRoots: [], + }), + ).toEqual([]); + }); +}); + describe("composeShellStreamWithEnrichment", () => { it.effect( "emits every initial item before enrichment even when enrichment is already ready", diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 744a8720fe..942b909d7c 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -43,12 +43,20 @@ export function shellStreamItemFromEnrichmentRefresh(input: { readonly snapshot: OrchestrationV2ShellSnapshot; readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>; }): Extract { + const resolvedRepositoryIdentityRoots = [ + ...new Set(input.changes.map((change) => change.workspaceRoot)), + ]; return { kind: "snapshot", - snapshot: input.snapshot, - resolvedRepositoryIdentityRoots: [ - ...new Set(input.changes.map((change) => change.workspaceRoot)), - ], + snapshot: { + ...input.snapshot, + projects: input.snapshot.projects.filter((project) => + resolvedRepositoryIdentityRoots.includes(project.workspaceRoot), + ), + threads: [], + archivedThreads: [], + }, + resolvedRepositoryIdentityRoots, }; } @@ -71,12 +79,29 @@ export function shellStreamItemsFromInitialSnapshot(input: { authoritative, { kind: "snapshot" as const, - snapshot: input.snapshot, + snapshot: { + ...input.snapshot, + projects: input.snapshot.projects.filter((project) => + input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot), + ), + threads: [], + archivedThreads: [], + }, resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)], }, ]; } +/** Resume after HTTP/cache hydration with metadata only, never another full shell body. */ +export function shellStreamItemsFromResumeSnapshot(input: { + readonly snapshot: OrchestrationV2ShellSnapshot; + readonly resolvedRepositoryIdentityRoots: ReadonlyArray; +}): ReadonlyArray> { + return shellStreamItemsFromInitialSnapshot(input).filter( + (item) => item.resolvedRepositoryIdentityRoots !== undefined, + ); +} + /** Keep only the newest stored event per thread within a coalescing window. */ export function coalesceStoredThreadEvents( events: ReadonlyArray, diff --git a/apps/server/src/orchestration-v2/ThreadStream.test.ts b/apps/server/src/orchestration-v2/ThreadStream.test.ts new file mode 100644 index 0000000000..b5e9b8d58e --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadStream.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + decideThreadResume, + threadReplayEncodedBytes, + THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, + THREAD_RESUME_MAX_REPLAY_EVENTS, +} from "./ThreadStream.ts"; + +describe("decideThreadResume", () => { + it("replays when the gap is zero", () => { + expect( + decideThreadResume({ + afterSequence: 10, + highWater: 10, + replayEventCount: 0, + replayEncodedBytes: 0, + }), + ).toEqual({ mode: "replay", afterSequence: 10, throughSequence: 10 }); + }); + + it("replays when the event count is within the bound", () => { + expect( + decideThreadResume({ + afterSequence: 10, + highWater: 20_000, + replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS, + replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES, + }), + ).toEqual({ + mode: "replay", + afterSequence: 10, + throughSequence: 20_000, + }); + }); + + it("falls back to a snapshot when the event count exceeds the bound", () => { + expect( + decideThreadResume({ + afterSequence: 10, + highWater: 20_000, + replayEventCount: THREAD_RESUME_MAX_REPLAY_EVENTS + 1, + replayEncodedBytes: 1, + }), + ).toEqual({ mode: "snapshot" }); + }); + + it("falls back to a snapshot when encoded replay bytes exceed the bound", () => { + expect( + decideThreadResume({ + afterSequence: 10, + highWater: 11, + replayEventCount: 1, + replayEncodedBytes: THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + 1, + }), + ).toEqual({ mode: "snapshot" }); + }); + + it("falls back to a snapshot when the client cursor is ahead of the store", () => { + expect( + decideThreadResume({ + afterSequence: 50, + highWater: 40, + replayEventCount: 0, + replayEncodedBytes: 0, + }), + ).toEqual({ mode: "snapshot" }); + }); + + it("counts UTF-8 bytes across projected stream items", () => { + expect(threadReplayEncodedBytes([{ value: "a" }, { value: "🦊" }])).toBe( + Buffer.byteLength('{"value":"a"}', "utf8") + Buffer.byteLength('{"value":"🦊"}', "utf8"), + ); + }); +}); diff --git a/apps/server/src/orchestration-v2/ThreadStream.ts b/apps/server/src/orchestration-v2/ThreadStream.ts new file mode 100644 index 0000000000..6172898867 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadStream.ts @@ -0,0 +1,51 @@ +/** Maximum number of reducer applications allowed during a thread resume. */ +export const THREAD_RESUME_MAX_REPLAY_EVENTS = 128; + +/** Maximum encoded event JSON allowed during a thread resume. */ +export const THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES = 1_048_576; + +/** Encoded payload cost after events have been projected for the wire. */ +export function threadReplayEncodedBytes(items: ReadonlyArray): number { + let total = 0; + for (const item of items) { + const encoded = JSON.stringify(item); + total += Buffer.byteLength(encoded ?? "", "utf8"); + } + return total; +} + +export type ThreadResumePlan = + | { + readonly mode: "replay"; + readonly afterSequence: number; + readonly throughSequence: number; + } + | { readonly mode: "snapshot" }; + +/** + * Decide whether a thread subscription should replay the event gap after the + * client's cursor or send a fresh snapshot instead. + * + * A client cursor above the high water mark is stale or invalid. Event count + * limits reducer churn while encoded bytes limit a small number of large + * updates. Either excess is cheaper to replace with one current snapshot. + */ +export function decideThreadResume(input: { + readonly afterSequence: number; + readonly highWater: number; + readonly replayEventCount: number; + readonly replayEncodedBytes: number; +}): ThreadResumePlan { + if ( + input.afterSequence > input.highWater || + input.replayEventCount > THREAD_RESUME_MAX_REPLAY_EVENTS || + input.replayEncodedBytes > THREAD_RESUME_MAX_REPLAY_ENCODED_BYTES + ) { + return { mode: "snapshot" }; + } + return { + mode: "replay", + afterSequence: input.afterSequence, + throughSequence: input.highWater, + }; +} diff --git a/apps/server/src/orchestration-v2/WireProjection.test.ts b/apps/server/src/orchestration-v2/WireProjection.test.ts new file mode 100644 index 0000000000..8c1cbc1bf8 --- /dev/null +++ b/apps/server/src/orchestration-v2/WireProjection.test.ts @@ -0,0 +1,50 @@ +import { ThreadId, TurnItemId, type OrchestrationV2TurnItem } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { projectTurnItemForWire } from "./WireProjection.ts"; + +const base = { + id: TurnItemId.make("tool-1"), + type: "dynamic_tool" as const, + threadId: ThreadId.make("thread-1"), + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed" as const, + title: "MCP tool", + toolName: "mcp__github__fetch_pr", + input: { pr: 42 }, + startedAt: DateTime.makeUnsafe("2026-08-13T00:00:00.000Z"), + completedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"), + updatedAt: DateTime.makeUnsafe("2026-08-13T00:00:01.000Z"), +}; + +describe("orchestration V2 wire projection", () => { + it("summarizes oversized dynamic tool results without mutating persistence data", () => { + const output = { content: [{ type: "text", text: "first line\n" + "x".repeat(100_000) }] }; + const item = { ...base, output } satisfies OrchestrationV2TurnItem; + const projected = projectTurnItemForWire(item); + + expect(item.output).toBe(output); + expect(projected).not.toBe(item); + expect(JSON.stringify(projected).length).toBeLessThan(2_000); + expect(projected.type === "dynamic_tool" ? projected.output : null).toMatchObject({ + truncated: true, + }); + }); + + it("keeps small dynamic tool values intact", () => { + const item = { ...base, output: { ok: true } } satisfies OrchestrationV2TurnItem; + expect(projectTurnItemForWire(item)).toEqual(item); + }); + + it("keeps undefined dynamic input intact", () => { + const item = { ...base, input: undefined } satisfies OrchestrationV2TurnItem; + expect(projectTurnItemForWire(item)).toEqual(item); + }); +}); diff --git a/apps/server/src/orchestration-v2/WireProjection.ts b/apps/server/src/orchestration-v2/WireProjection.ts new file mode 100644 index 0000000000..eaa0a7898d --- /dev/null +++ b/apps/server/src/orchestration-v2/WireProjection.ts @@ -0,0 +1,108 @@ +import type { + OrchestrationV2DomainEvent, + OrchestrationV2ThreadProjection, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; + +const MAX_DETAIL_STRING_BYTES = 32_768; +const MAX_DYNAMIC_VALUE_BYTES = 16_384; + +function encodedBytes(value: unknown): number { + try { + const serialized = JSON.stringify(value); + return Buffer.byteLength(serialized ?? String(value), "utf8"); + } catch { + return Number.POSITIVE_INFINITY; + } +} + +function truncateDetail(value: string | undefined): string | undefined { + if (value === undefined || Buffer.byteLength(value, "utf8") <= MAX_DETAIL_STRING_BYTES) { + return value; + } + const prefix = Buffer.from(value, "utf8") + .subarray(0, MAX_DETAIL_STRING_BYTES) + .toString("utf8") + .replace(/\uFFFD$/u, ""); + return `${prefix}\n… output truncated for transport`; +} + +function summarizeDynamicValue(value: unknown): unknown { + if (encodedBytes(value) <= MAX_DYNAMIC_VALUE_BYTES) { + return value; + } + let serialized: string; + try { + serialized = typeof value === "string" ? value : (JSON.stringify(value) ?? String(value)); + } catch { + serialized = "Unserializable tool output"; + } + const firstLine = + serialized + .split(/\r?\n/u) + .map((line) => line.replace(/\s+/gu, " ").trim()) + .find((line) => line.length > 0) ?? "Large tool output"; + return { + summary: firstLine.length <= 160 ? firstLine : `${firstLine.slice(0, 159).trimEnd()}…`, + truncated: true, + }; +} + +export function projectTurnItemForWire(item: OrchestrationV2TurnItem): OrchestrationV2TurnItem { + switch (item.type) { + case "command_execution": + return { ...item, output: truncateDetail(item.output) }; + case "file_change": + return { + ...item, + diffStr: truncateDetail(item.diffStr), + oldStr: truncateDetail(item.oldStr), + newStr: truncateDetail(item.newStr), + }; + case "subagent": + return { + ...item, + prompt: truncateDetail(item.prompt) ?? "", + progress: truncateDetail(item.progress), + result: item.result === null ? null : (truncateDetail(item.result) ?? null), + }; + case "dynamic_tool": + return { + ...item, + input: summarizeDynamicValue(item.input), + ...(item.output === undefined ? {} : { output: summarizeDynamicValue(item.output) }), + }; + default: + return item; + } +} + +export function projectThreadProjectionForWire( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2ThreadProjection { + const projectedById = new Map(); + const project = (item: OrchestrationV2TurnItem) => { + const key = `${item.threadId}:${item.id}`; + const existing = projectedById.get(key); + if (existing !== undefined) return existing; + const projected = projectTurnItemForWire(item); + projectedById.set(key, projected); + return projected; + }; + return { + ...projection, + turnItems: projection.turnItems.map(project), + visibleTurnItems: projection.visibleTurnItems.map((row) => ({ + ...row, + item: project(row.item), + })), + }; +} + +export function projectDomainEventForWire( + event: OrchestrationV2DomainEvent, +): OrchestrationV2DomainEvent { + return event.type === "turn-item.updated" + ? { ...event, payload: projectTurnItemForWire(event.payload) } + : event; +} diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index ef4ebd9fa1..045afefd53 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -11,13 +11,20 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import { annotateEnvironmentRequest, failEnvironmentInternal, + failEnvironmentInvalidRequest, failEnvironmentNotFound, requireEnvironmentScope, } from "../auth/http.ts"; import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import * as OrchestrationEventStore from "../persistence/Services/OrchestrationEventStore.ts"; import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts"; +import { + buildBoundedThreadProjection, + InvalidThreadHistoryCursorError, + selectHistoryPageFromCursor, +} from "./threadHistoryPaging.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; +import { projectThreadProjectionForWire } from "./WireProjection.ts"; function isThreadNotFound(error: unknown): boolean { return ( @@ -27,9 +34,25 @@ function isThreadNotFound(error: unknown): boolean { ); } +function selectHistoryPageFromCursorOrError( + input: Parameters[0], +): + | { readonly _tag: "ok"; readonly page: ReturnType } + | { readonly _tag: "invalid_cursor" } + | { readonly _tag: "error"; readonly cause: unknown } { + try { + return { _tag: "ok", page: selectHistoryPageFromCursor(input) }; + } catch (cause) { + if (cause instanceof InvalidThreadHistoryCursorError) { + return { _tag: "invalid_cursor" }; + } + return { _tag: "error", cause }; + } +} + /** * Serves orchestration V2 snapshots over HTTP so clients can load the - * (potentially large) shell and thread projections off the socket — gzip + * (potentially large) shell and thread projections off the socket; gzip * compressible and cacheable — and then resume the WebSocket subscription via * `afterSequence`. */ @@ -80,6 +103,29 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group( return { ...base, projects }; }); + const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* ( + threadId: Parameters[0], + failureReason: + | "orchestration_thread_snapshot_failed" + | "orchestration_thread_bounded_snapshot_failed" + | "orchestration_thread_history_failed", + ) { + return yield* threadManagement.getThreadSnapshot(threadId).pipe( + Effect.map((snapshot) => ({ + ...snapshot, + projection: projectThreadProjectionForWire(snapshot.projection), + })), + Effect.catch( + Effect.fnUntraced(function* (error) { + if (isThreadNotFound(error)) { + return yield* failEnvironmentNotFound("thread_not_found"); + } + return yield* failEnvironmentInternal(failureReason, error); + }), + ), + ); + }); + return handlers .handle( "shellSnapshot", @@ -98,24 +144,68 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group( Effect.fn("environment.orchestration.threadSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); yield* requireEnvironmentScope(AuthOrchestrationReadScope); - const snapshot = yield* threadManagement.getThreadSnapshot(args.params.threadId).pipe( - Effect.catch( - Effect.fnUntraced(function* (error) { - if (isThreadNotFound(error)) { - return yield* failEnvironmentNotFound("thread_not_found"); - } - return yield* failEnvironmentInternal( - "orchestration_thread_snapshot_failed", - error, - ); - }), - ), + const snapshot = yield* loadThreadSnapshot( + args.params.threadId, + "orchestration_thread_snapshot_failed", ); return { snapshotSequence: snapshot.snapshotSequence, projection: snapshot.projection, }; }), + ) + .handle( + "threadBoundedSnapshot", + Effect.fn("environment.orchestration.threadBoundedSnapshot")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const snapshot = yield* loadThreadSnapshot( + args.params.threadId, + "orchestration_thread_bounded_snapshot_failed", + ); + const bounded = buildBoundedThreadProjection({ + projection: snapshot.projection, + snapshotSequence: snapshot.snapshotSequence, + }); + return { + snapshotSequence: snapshot.snapshotSequence, + projection: bounded.projection, + historyCursor: bounded.historyCursor, + hasMoreHistory: bounded.hasMoreHistory, + latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal, + }; + }), + ) + .handle( + "threadHistoryPage", + Effect.fn("environment.orchestration.threadHistoryPage")(function* (args) { + yield* annotateEnvironmentRequest(args.endpoint.name); + yield* requireEnvironmentScope(AuthOrchestrationReadScope); + const snapshot = yield* loadThreadSnapshot( + args.params.threadId, + "orchestration_thread_history_failed", + ); + const pageOrError = selectHistoryPageFromCursorOrError({ + items: snapshot.projection.visibleTurnItems, + cursor: args.query.cursor, + snapshotSequence: snapshot.snapshotSequence, + }); + if (pageOrError._tag === "invalid_cursor") { + return yield* failEnvironmentInvalidRequest("invalid_history_cursor"); + } + if (pageOrError._tag === "error") { + return yield* failEnvironmentInternal( + "orchestration_thread_history_failed", + pageOrError.cause, + ); + } + return { + snapshotSequence: snapshot.snapshotSequence, + items: pageOrError.page.items, + nextCursor: pageOrError.page.nextCursor, + hasMoreHistory: pageOrError.page.hasMoreHistory, + }; + }), ); }), ); diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts new file mode 100644 index 0000000000..d5921d979e --- /dev/null +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -0,0 +1,473 @@ +import { + MessageId, + NodeId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { + buildBoundedThreadProjection, + boundedTimelineEncodedBytes, + computeLatestLocalTurnOrdinal, + decodeThreadHistoryCursor, + encodeThreadHistoryCursor, + InvalidThreadHistoryCursorError, + projectedRowBoundedSnapshotEncodedBytes, + projectedRowEncodedBytes, + selectHistoryPageFromCursor, + selectRecentTimelineWindow, + THREAD_HISTORY_CURSOR_MAX_LENGTH, + THREAD_HISTORY_PAGE_POLICY, +} from "./threadHistoryPaging.ts"; + +const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +const THREAD = ThreadId.make("thread-1"); +const RUN = RunId.make("run-interrupt-1"); +const NODE = NodeId.make("node-interrupt-1"); + +function makeRow( + index: number, + options?: { readonly outputBytes?: number }, +): OrchestrationV2ProjectedTurnItem { + const id = TurnItemId.make(`item-${index}`); + const output = + options?.outputBytes !== undefined ? "x".repeat(options.outputBytes) : `output-${index}`; + return { + position: index, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: id, + item: { + id, + type: "command_execution", + threadId: THREAD, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: index + 1, + status: "completed", + title: `Command ${index}`, + input: `cmd-${index}`, + output, + exitCode: 0, + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + }, + }; +} + +function interruptItem( + id: string, + type: "run_interrupt_request" | "run_interrupt_result", + ordinal: number, +): OrchestrationV2TurnItem { + return { + id: TurnItemId.make(id), + type, + threadId: THREAD, + runId: RUN, + nodeId: NODE, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: type, + message: type === "run_interrupt_request" ? "Stopping" : "Stopped", + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + } as OrchestrationV2TurnItem; +} + +function interruptRow( + index: number, + type: "run_interrupt_request" | "run_interrupt_result", +): OrchestrationV2ProjectedTurnItem { + const item = interruptItem( + type === "run_interrupt_request" ? "interrupt-req" : "interrupt-res", + type, + index + 1, + ); + return { + position: index, + visibility: "local", + sourceThreadId: THREAD, + sourceItemId: item.id, + item, + }; +} + +function makeProjection(visibleTurnItems: OrchestrationV2ProjectedTurnItem[]) { + return { + thread: { + id: THREAD, + projectId: "project-1", + title: "Thread", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: THREAD, + }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: NOW, + updatedAt: NOW, + archivedAt: null, + deletedAt: null, + settledOverride: null, + settledAt: null, + }, + runs: [{ id: "run-1" }], + attempts: [{ id: "attempt-1" }], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [{ id: "req-1" }], + messages: [], + plans: [], + turnItems: visibleTurnItems.map((row) => row.item), + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems, + updatedAt: NOW, + } as unknown as Parameters[0]["projection"]; +} + +describe("threadHistoryPaging", () => { + it("encodes opaque cursors with stable source identity", () => { + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 9, + sourceThreadId: THREAD, + sourceItemId: TurnItemId.make("item-3"), + position: 3, + }); + expect(cursor.includes("{")).toBe(false); + expect(decodeThreadHistoryCursor(cursor)).toEqual({ + v: 1, + seq: 9, + st: "thread-1", + si: "item-3", + p: 3, + }); + }); + + it("rejects malformed cursors", () => { + expect(() => decodeThreadHistoryCursor("not-valid")).toThrow(InvalidThreadHistoryCursorError); + expect(() => + decodeThreadHistoryCursor(Buffer.from("{}", "utf8").toString("base64url")), + ).toThrow(InvalidThreadHistoryCursorError); + }); + + it("rejects cursors longer than the maximum length before decoding", () => { + const oversized = "A".repeat(THREAD_HISTORY_CURSOR_MAX_LENGTH + 1); + expect(() => decodeThreadHistoryCursor(oversized)).toThrow(InvalidThreadHistoryCursorError); + }); + + it("selects a recent window by item count", () => { + const items = Array.from({ length: 120 }, (_, index) => makeRow(index)); + const page = selectRecentTimelineWindow({ + items, + snapshotSequence: 4, + policy: { maxItems: 10, maxEncodedBytes: 10_000_000 }, + }); + expect(page.items).toHaveLength(10); + expect(page.items[0]?.sourceItemId).toBe("item-110"); + expect(page.items[9]?.sourceItemId).toBe("item-119"); + expect(page.hasMoreHistory).toBe(true); + expect(page.nextCursor).not.toBeNull(); + const cursor = decodeThreadHistoryCursor(page.nextCursor!); + expect(cursor.si).toBe("item-110"); + expect(cursor.seq).toBe(4); + }); + + it("always includes at least one pathological oversized item", () => { + const items = [makeRow(0, { outputBytes: 2_000_000 }), makeRow(1, { outputBytes: 10 })]; + const page = selectRecentTimelineWindow({ + items, + snapshotSequence: 1, + policy: { maxItems: 50, maxEncodedBytes: 1_024 }, + }); + expect(page.items).toHaveLength(1); + expect(page.items[0]?.sourceItemId).toBe("item-1"); + expect(page.hasMoreHistory).toBe(true); + + const older = selectHistoryPageFromCursor({ + items, + cursor: page.nextCursor!, + snapshotSequence: 1, + policy: { maxItems: 50, maxEncodedBytes: 1_024 }, + }); + expect(older.items).toHaveLength(1); + expect(older.items[0]?.sourceItemId).toBe("item-0"); + expect(older.hasMoreHistory).toBe(false); + expect(older.nextCursor).toBeNull(); + }); + + it("recovers identity-miss cursors when position is past a shrunken timeline", () => { + const items = Array.from({ length: 5 }, (_, index) => makeRow(index)); + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 3, + sourceThreadId: THREAD, + sourceItemId: TurnItemId.make("item-deleted-long-ago"), + position: 40, + }); + const page = selectHistoryPageFromCursor({ + items, + cursor, + snapshotSequence: 3, + policy: { maxItems: 2, maxEncodedBytes: 10_000_000 }, + }); + // Clamp exclusive end to items.length and page backward so the client can + // dedupe and advance rather than permanently 400 on a dead cursor. + expect(page.items.map((row) => row.sourceItemId)).toEqual(["item-3", "item-4"]); + expect(page.hasMoreHistory).toBe(true); + expect(page.nextCursor).not.toBeNull(); + }); + + it("keeps cursor resolution stable when newer items append", () => { + const initial = Array.from({ length: 20 }, (_, index) => makeRow(index)); + const recent = selectRecentTimelineWindow({ + items: initial, + snapshotSequence: 2, + policy: { maxItems: 5, maxEncodedBytes: 10_000_000 }, + }); + const cursor = recent.nextCursor!; + const grown = [...initial, makeRow(20), makeRow(21)]; + const older = selectHistoryPageFromCursor({ + items: grown, + cursor, + snapshotSequence: 5, + policy: { maxItems: 5, maxEncodedBytes: 10_000_000 }, + }); + expect(older.items.map((row) => row.sourceItemId)).toEqual([ + "item-10", + "item-11", + "item-12", + "item-13", + "item-14", + ]); + expect(older.hasMoreHistory).toBe(true); + }); + + it("builds a bounded projection that preserves non-timeline control state", () => { + const full = makeProjection(Array.from({ length: 40 }, (_, index) => makeRow(index))); + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 7, + policy: { maxItems: 5, maxEncodedBytes: 10_000_000 }, + }); + expect(bounded.projection.runs).toEqual(full.runs); + expect(bounded.projection.runtimeRequests).toEqual(full.runtimeRequests); + expect(bounded.projection.attempts).toEqual(full.attempts); + expect(bounded.projection.visibleTurnItems).toHaveLength(5); + expect(bounded.projection.turnItems).toHaveLength(5); + expect(bounded.hasMoreHistory).toBe(true); + expect(bounded.historyCursor).not.toBeNull(); + expect(bounded.projection.visibleTurnItems.map((row) => row.position)).toEqual([0, 1, 2, 3, 4]); + // Watermark comes from the full projection, not the trimmed window. + expect(bounded.latestLocalTurnOrdinal).toBe(40); + expect(computeLatestLocalTurnOrdinal(full.turnItems)).toBe(40); + }); + + it("carries a full-projection watermark when the bounded window is inherited-only", () => { + const localOlder = makeRow(0); + const localMid = makeRow(1); + const inherited = { + ...makeRow(2), + visibility: "inherited" as const, + sourceThreadId: ThreadId.make("parent-thread"), + item: { + ...makeRow(2).item, + threadId: ThreadId.make("parent-thread"), + }, + }; + // Full projection still has local turnItems even if the recent window is + // only the inherited row (e.g. after aggressive byte budget on a large + // local item that is not selected into the recent page). Use a synthetic + // projection with local turnItems and inherited-only visible window. + const full = makeProjection([localOlder, localMid, inherited]); + // Force an inherited-only visible window by rebuilding with only inherited + // visible rows while retaining full local turnItems for the watermark. + const inheritedOnly = { + ...full, + visibleTurnItems: [inherited], + turnItems: [localOlder.item, localMid.item], + }; + const bounded = buildBoundedThreadProjection({ + projection: inheritedOnly, + snapshotSequence: 2, + policy: { maxItems: 1, maxEncodedBytes: 10_000_000 }, + }); + expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([ + String(inherited.sourceItemId), + ]); + expect(bounded.latestLocalTurnOrdinal).toBe(2); + expect(computeLatestLocalTurnOrdinal([])).toBeNull(); + }); + + it("retains an out-of-window run_interrupt_request needed by a visible result", () => { + // Older request sits outside a 1-row recent window; result is visible alone. + const request = interruptRow(0, "run_interrupt_request"); + const filler = makeRow(1); + const result = interruptRow(2, "run_interrupt_result"); + const full = makeProjection([request, filler, result]); + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 3, + policy: { maxItems: 1, maxEncodedBytes: 10_000_000 }, + }); + + expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([ + "interrupt-res", + ]); + expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([ + "interrupt-req", + "interrupt-res", + ]); + expect(bounded.hasMoreHistory).toBe(true); + }); + + it("retains all run_interrupt_request items even when no result is in the initial window", () => { + // Cold open: recent window is only filler. Request and result both live on + // older pages, but the request must still ride in turnItems so a later + // history page can introduce the result safely under live attempt updates. + const request = interruptRow(0, "run_interrupt_request"); + const result = interruptRow(1, "run_interrupt_result"); + const recent = makeRow(2); + const full = makeProjection([request, result, recent]); + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 4, + policy: { maxItems: 1, maxEncodedBytes: 10_000_000 }, + }); + + expect(bounded.projection.visibleTurnItems.map((row) => String(row.sourceItemId))).toEqual([ + "item-2", + ]); + expect(bounded.projection.turnItems.map((item) => String(item.id)).sort()).toEqual([ + "interrupt-req", + "item-2", + ]); + expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_request")).toBe( + true, + ); + expect(bounded.projection.turnItems.some((item) => item.type === "run_interrupt_result")).toBe( + false, + ); + }); + + it("charges local row.item duplication when measuring bounded timeline bytes", () => { + const rows = Array.from({ length: 8 }, (_, index) => makeRow(index, { outputBytes: 2_000 })); + const full = makeProjection(rows); + const maxEncodedBytes = 12_000; + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 1, + policy: { maxItems: 50, maxEncodedBytes }, + }); + + const contribution = boundedTimelineEncodedBytes({ + visibleTurnItems: bounded.projection.visibleTurnItems, + turnItems: bounded.projection.turnItems, + }); + expect(contribution).toBeLessThanOrEqual(maxEncodedBytes); + expect(bounded.projection.visibleTurnItems.length).toBeGreaterThan(0); + expect(bounded.projection.visibleTurnItems.length).toBeLessThan(rows.length); + + // History pages only charge the projected row once (no turnItems copy). + const historyPage = selectRecentTimelineWindow({ + items: rows, + snapshotSequence: 1, + policy: { maxItems: 50, maxEncodedBytes }, + }); + const historyBytes = historyPage.items.reduce( + (sum, row) => sum + projectedRowEncodedBytes(row), + 0, + ); + expect(historyBytes).toBeLessThanOrEqual(maxEncodedBytes); + expect(historyPage.items.length).toBeGreaterThan(bounded.projection.visibleTurnItems.length); + + // Dual-cost for one local row exceeds the plain row cost. + const sample = rows[0]!; + expect(projectedRowBoundedSnapshotEncodedBytes(sample, THREAD)).toBeGreaterThan( + projectedRowEncodedBytes(sample), + ); + }); + + it("allows a single pathological bounded row to exceed the configured cap", () => { + const huge = makeRow(0, { outputBytes: 50_000 }); + const full = makeProjection([huge]); + const maxEncodedBytes = 1_000; + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 1, + policy: { maxItems: 10, maxEncodedBytes }, + }); + expect(bounded.projection.visibleTurnItems).toHaveLength(1); + const contribution = boundedTimelineEncodedBytes({ + visibleTurnItems: bounded.projection.visibleTurnItems, + turnItems: bounded.projection.turnItems, + }); + expect(contribution).toBeGreaterThan(maxEncodedBytes); + }); + + it("exposes conservative default page budgets", () => { + expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeGreaterThanOrEqual(50); + expect(THREAD_HISTORY_PAGE_POLICY.maxItems).toBeLessThanOrEqual(100); + expect(THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes).toBe(1_048_576); + }); + + it("does not carry the full duplicated message table into a bounded snapshot", () => { + const projection = makeProjection(Array.from({ length: 120 }, (_, index) => makeRow(index))); + const full = { + ...projection, + messages: Array.from({ length: 2_000 }, (_, index) => ({ + id: MessageId.make(`message-${index}`), + threadId: THREAD, + runId: RunId.make(`old-run-${index}`), + nodeId: null, + role: "assistant" as const, + text: "x".repeat(1_000), + attachments: [], + streaming: false, + createdBy: "agent" as const, + creationSource: "provider" as const, + createdAt: NOW, + updatedAt: NOW, + })), + } as typeof projection; + + const bounded = buildBoundedThreadProjection({ + projection: full, + snapshotSequence: 9, + }); + + expect(bounded.projection.messages).toEqual([]); + expect(Buffer.byteLength(JSON.stringify(bounded.projection), "utf8")).toBeLessThan( + THREAD_HISTORY_PAGE_POLICY.maxEncodedBytes + 100_000, + ); + }); +}); diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts new file mode 100644 index 0000000000..652de1d318 --- /dev/null +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -0,0 +1,442 @@ +import type { + OrchestrationV2ProjectedTurnItem, + OrchestrationV2ThreadProjection, + OrchestrationV2TurnItem, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; + +/** + * Centralized page budgets for progressive client hydration. Sized for relay + * cold opens: dozens of rows and about 1 MiB of encoded JSON per page. + */ +export const THREAD_HISTORY_PAGE_POLICY = { + maxItems: 75, + maxEncodedBytes: 1_048_576, +} as const; + +/** Reject absurd cursors before base64 work or JSON parse. */ +export const THREAD_HISTORY_CURSOR_MAX_LENGTH = 4_096; + +export type ThreadHistoryPagePolicy = { + readonly maxItems: number; + readonly maxEncodedBytes: number; +}; + +export type ThreadHistoryCursorPayload = { + readonly v: 1; + readonly seq: number; + readonly st: string; + readonly si: string; + readonly p: number; +}; + +export type SelectTimelinePageResult = { + readonly items: ReadonlyArray; + readonly nextCursor: string | null; + readonly hasMoreHistory: boolean; +}; + +export type BoundedProjectionResult = { + readonly projection: OrchestrationV2ThreadProjection; + readonly historyCursor: string | null; + readonly hasMoreHistory: boolean; + /** Max ordinal across the authoritative full projection's local turnItems. */ + readonly latestLocalTurnOrdinal: number | null; +}; + +export class InvalidThreadHistoryCursorError extends Error { + readonly _tag = "InvalidThreadHistoryCursorError"; + constructor(message = "Invalid thread history cursor.") { + super(message); + this.name = "InvalidThreadHistoryCursorError"; + } +} + +function bytesOfJson(value: unknown): number { + return Buffer.byteLength(JSON.stringify(value), "utf8"); +} + +/** Ordinary history-page cost: one projected row (item is nested once). */ +export function projectedRowEncodedBytes(row: OrchestrationV2ProjectedTurnItem): number { + return bytesOfJson(row); +} + +/** + * Bounded-snapshot cost: local rows also land in `projection.turnItems`, so + * charge the nested item a second time. Inherited rows only appear in the + * visible list. + */ +export function projectedRowBoundedSnapshotEncodedBytes( + row: OrchestrationV2ProjectedTurnItem, + threadId: ThreadId | string, +): number { + const rowBytes = projectedRowEncodedBytes(row); + if (row.visibility === "local" || String(row.sourceThreadId) === String(threadId)) { + return rowBytes + bytesOfJson(row.item); + } + return rowBytes; +} + +function renumberPositions( + items: ReadonlyArray, +): OrchestrationV2ProjectedTurnItem[] { + return items.map((row, position) => (row.position === position ? row : { ...row, position })); +} + +function encodeCursorPayload(payload: ThreadHistoryCursorPayload): string { + return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url"); +} + +export function encodeThreadHistoryCursor(input: { + readonly snapshotSequence: number; + readonly sourceThreadId: ThreadId | string; + readonly sourceItemId: TurnItemId | string; + readonly position: number; +}): string { + return encodeCursorPayload({ + v: 1, + seq: input.snapshotSequence, + st: String(input.sourceThreadId), + si: String(input.sourceItemId), + p: input.position, + }); +} + +export function decodeThreadHistoryCursor(cursor: string): ThreadHistoryCursorPayload { + if (cursor.length === 0 || cursor.length > THREAD_HISTORY_CURSOR_MAX_LENGTH) { + throw new InvalidThreadHistoryCursorError(); + } + let parsed: unknown; + try { + const json = Buffer.from(cursor, "base64url").toString("utf8"); + parsed = JSON.parse(json) as unknown; + } catch { + throw new InvalidThreadHistoryCursorError(); + } + if ( + typeof parsed !== "object" || + parsed === null || + !("v" in parsed) || + (parsed as { v: unknown }).v !== 1 || + !("seq" in parsed) || + typeof (parsed as { seq: unknown }).seq !== "number" || + !Number.isInteger((parsed as { seq: number }).seq) || + (parsed as { seq: number }).seq < 0 || + !("st" in parsed) || + typeof (parsed as { st: unknown }).st !== "string" || + (parsed as { st: string }).st.length === 0 || + !("si" in parsed) || + typeof (parsed as { si: unknown }).si !== "string" || + (parsed as { si: string }).si.length === 0 || + !("p" in parsed) || + typeof (parsed as { p: unknown }).p !== "number" || + !Number.isInteger((parsed as { p: number }).p) || + (parsed as { p: number }).p < 0 + ) { + throw new InvalidThreadHistoryCursorError(); + } + return parsed as ThreadHistoryCursorPayload; +} + +/** + * Walk a chronological timeline from `startIndex` backward, collecting rows + * under count and byte budgets. Always includes at least one row when available + * so a single oversized item cannot deadlock pagination. + */ +export function selectOlderTimelinePage(input: { + readonly items: ReadonlyArray; + readonly exclusiveEndIndex: number; + readonly snapshotSequence: number; + readonly policy?: ThreadHistoryPagePolicy | undefined; + readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined; +}): SelectTimelinePageResult { + const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY; + const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes; + const end = Math.min(Math.max(input.exclusiveEndIndex, 0), input.items.length); + if (end <= 0) { + return { items: [], nextCursor: null, hasMoreHistory: false }; + } + + const selected: OrchestrationV2ProjectedTurnItem[] = []; + let encodedBytes = 0; + for (let index = end - 1; index >= 0; index -= 1) { + const row = input.items[index]!; + const rowBytes = rowCost(row); + if ( + selected.length > 0 && + (selected.length >= policy.maxItems || encodedBytes + rowBytes > policy.maxEncodedBytes) + ) { + break; + } + selected.push(row); + encodedBytes += rowBytes; + } + selected.reverse(); + + const oldest = selected[0]; + const oldestIndex = oldest + ? input.items.findIndex( + (row) => + row.sourceThreadId === oldest.sourceThreadId && row.sourceItemId === oldest.sourceItemId, + ) + : -1; + const hasMoreHistory = oldestIndex > 0; + const nextCursor = + hasMoreHistory && oldest + ? encodeThreadHistoryCursor({ + snapshotSequence: input.snapshotSequence, + sourceThreadId: oldest.sourceThreadId, + sourceItemId: oldest.sourceItemId, + position: oldest.position, + }) + : null; + + return { + items: renumberPositions(selected), + nextCursor, + hasMoreHistory, + }; +} + +export function selectRecentTimelineWindow(input: { + readonly items: ReadonlyArray; + readonly snapshotSequence: number; + readonly policy?: ThreadHistoryPagePolicy | undefined; + readonly rowEncodedBytes?: ((row: OrchestrationV2ProjectedTurnItem) => number) | undefined; +}): SelectTimelinePageResult { + return selectOlderTimelinePage({ + items: input.items, + exclusiveEndIndex: input.items.length, + snapshotSequence: input.snapshotSequence, + ...(input.policy === undefined ? {} : { policy: input.policy }), + ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }), + }); +} + +function findCursorIndex( + items: ReadonlyArray, + cursor: ThreadHistoryCursorPayload, +): number { + const byIdentity = items.findIndex( + (row) => String(row.sourceThreadId) === cursor.st && String(row.sourceItemId) === cursor.si, + ); + if (byIdentity !== -1) { + return byIdentity; + } + // Identity miss can happen if the cursor item was deleted; fall back to the + // recorded position clamped into the current timeline so pagination can + // continue from a stable-ish anchor rather than failing hard. Clamp to + // items.length (exclusive end) so a shrunken timeline never 400s forever. + // decodeThreadHistoryCursor already guarantees p is a non-negative integer. + return Math.min(cursor.p, items.length); +} + +export function selectHistoryPageFromCursor(input: { + readonly items: ReadonlyArray; + readonly cursor: string; + readonly snapshotSequence: number; + readonly policy?: ThreadHistoryPagePolicy | undefined; +}): SelectTimelinePageResult { + const decoded = decodeThreadHistoryCursor(input.cursor); + const anchorIndex = findCursorIndex(input.items, decoded); + return selectOlderTimelinePage({ + items: input.items, + exclusiveEndIndex: anchorIndex, + snapshotSequence: input.snapshotSequence, + ...(input.policy === undefined ? {} : { policy: input.policy }), + }); +} + +function isLocalProjectedRow( + projection: OrchestrationV2ThreadProjection, + row: OrchestrationV2ProjectedTurnItem, +): boolean { + return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id); +} + +/** + * Visibility for superseded `run_interrupt_result` rows depends on a matching + * `run_interrupt_request` in `turnItems`. Keep every small request item from the + * full projection even when it sits outside the recent visible window, so a + * later history page that introduces the matching result still has the request + * available for live attempt/run reducers. + */ +export function retainedInterruptRequestTurnItems( + projection: OrchestrationV2ThreadProjection, + visible: ReadonlyArray, +): OrchestrationV2TurnItem[] { + const visibleLocalIds = new Set(); + for (const row of visible) { + if (isLocalProjectedRow(projection, row)) { + visibleLocalIds.add(String(row.sourceItemId)); + } + } + + const retained: OrchestrationV2TurnItem[] = []; + for (const item of projection.turnItems) { + if (item.type !== "run_interrupt_request") { + continue; + } + // Already covered by local turnItems for the visible window. + if (visibleLocalIds.has(String(item.id))) { + continue; + } + retained.push(item); + } + return retained; +} + +function localTurnItemsForVisibleWindow( + projection: OrchestrationV2ThreadProjection, + visible: ReadonlyArray, +): OrchestrationV2TurnItem[] { + const localIds = new Set(); + for (const row of visible) { + if (isLocalProjectedRow(projection, row)) { + localIds.add(String(row.sourceItemId)); + } + } + if (localIds.size === 0) { + return []; + } + return projection.turnItems.filter((item) => localIds.has(String(item.id))); +} + +function messagesForBoundedProjection( + projection: OrchestrationV2ThreadProjection, + turnItems: ReadonlyArray, +): OrchestrationV2ThreadProjection["messages"] { + const retainedMessageIds = new Set(); + for (const item of turnItems) { + if ("messageId" in item) { + retainedMessageIds.add(String(item.messageId)); + } + } + + const latestRun = projection.runs.reduce<(typeof projection.runs)[number] | null>( + (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest), + null, + ); + const retainedRunIds = new Set(); + for (const run of projection.runs) { + if ( + run.id === latestRun?.id || + run.status === "preparing" || + run.status === "starting" || + run.status === "running" || + run.status === "waiting" || + run.status === "queued" + ) { + retainedRunIds.add(String(run.id)); + retainedMessageIds.add(String(run.userMessageId)); + } + } + + return projection.messages.filter( + (message) => + retainedMessageIds.has(String(message.id)) || + (message.runId !== null && retainedRunIds.has(String(message.runId))) || + message.delegatedCompletion !== undefined, + ); +} + +/** + * Max local turn ordinal over the authoritative full projection turnItems. + * Used as a cheap partial-timeline watermark so old missing turn-item updates + * cannot append newest when the bounded window has no local rows. + */ +export function computeLatestLocalTurnOrdinal( + turnItems: ReadonlyArray<{ readonly ordinal: number }>, +): number | null { + let latest: number | null = null; + for (const item of turnItems) { + if (latest === null || item.ordinal > latest) { + latest = item.ordinal; + } + } + return latest; +} + +/** + * Encoded timeline contribution for a bounded snapshot: visible rows plus the + * duplicated local turnItems and any retained interrupt-request dependencies. + */ +export function boundedTimelineEncodedBytes(input: { + readonly visibleTurnItems: ReadonlyArray; + readonly turnItems: ReadonlyArray; +}): number { + let total = 0; + for (const row of input.visibleTurnItems) { + total += projectedRowEncodedBytes(row); + } + for (const item of input.turnItems) { + total += bytesOfJson(item); + } + return total; +} + +/** + * Builds a partial thread projection with full control-plane arrays and a + * bounded recent timeline window plus matching local turnItems. + */ +export function buildBoundedThreadProjection(input: { + readonly projection: OrchestrationV2ThreadProjection; + readonly snapshotSequence: number; + readonly policy?: ThreadHistoryPagePolicy | undefined; +}): BoundedProjectionResult { + const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY; + const threadId = input.projection.thread.id; + + // Reserve bytes for small interrupt-request dependencies that may sit outside + // the recent window but are required for visibility of results inside it. + const dependencyReserve = (() => { + // Upper bound: all request items in the full projection. Window selection + // uses this reserve so the final contribution stays under the cap. + let reserve = 0; + for (const item of input.projection.turnItems) { + if (item.type === "run_interrupt_request") { + reserve += bytesOfJson(item); + } + } + return reserve; + })(); + const windowBudget = Math.max(0, policy.maxEncodedBytes - dependencyReserve); + const windowPolicy: ThreadHistoryPagePolicy = { + maxItems: policy.maxItems, + // Zero still admits the first row via the at-least-one rule. + maxEncodedBytes: windowBudget, + }; + + const window = selectRecentTimelineWindow({ + items: input.projection.visibleTurnItems, + snapshotSequence: input.snapshotSequence, + policy: windowPolicy, + rowEncodedBytes: (row) => projectedRowBoundedSnapshotEncodedBytes(row, threadId), + }); + const visibleTurnItems = renumberPositions(window.items); + const windowTurnItems = localTurnItemsForVisibleWindow(input.projection, visibleTurnItems); + const dependencyTurnItems = retainedInterruptRequestTurnItems(input.projection, visibleTurnItems); + const turnItemById = new Map(); + for (const item of windowTurnItems) { + turnItemById.set(String(item.id), item); + } + for (const item of dependencyTurnItems) { + turnItemById.set(String(item.id), item); + } + const turnItems = [...turnItemById.values()]; + + return { + projection: { + ...input.projection, + messages: messagesForBoundedProjection(input.projection, turnItems), + turnItems, + visibleTurnItems, + }, + historyCursor: window.nextCursor, + hasMoreHistory: window.hasMoreHistory, + // Always from the full projection so inherited-only windows still carry a + // watermark for partial live reducers. + latestLocalTurnOrdinal: computeLatestLocalTurnOrdinal(input.projection.turnItems), + }; +} diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c57ebd44eb..3daaa28a84 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -82,7 +82,17 @@ import { shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, + shellStreamItemsFromResumeSnapshot, } from "./orchestration-v2/ShellStream.ts"; +import { + decideThreadResume, + threadReplayEncodedBytes, + THREAD_RESUME_MAX_REPLAY_EVENTS, +} from "./orchestration-v2/ThreadStream.ts"; +import { + projectDomainEventForWire, + projectThreadProjectionForWire, +} from "./orchestration-v2/WireProjection.ts"; import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import * as OrchestrationEventStore from "./persistence/Services/OrchestrationEventStore.ts"; import { userFacingDispatchErrorMessage } from "./orchestration-v2/UserFacingErrors.ts"; @@ -615,7 +625,7 @@ const makeWsRpcLayer = ( Stream.map((stored) => ({ kind: "event" as const, sequence: stored.sequence, - event: stored.event, + event: projectDomainEventForWire(stored.event), })), Stream.mapError( (cause) => @@ -627,20 +637,23 @@ const makeWsRpcLayer = ( ), ); - const replayThrough = (afterSequence: number, throughSequence: number) => + const loadReplayThrough = (afterSequence: number, throughSequence: number) => applicationEvents .readAgentEvents({ threadId: input.threadId, afterSequence, throughSequence, + limit: THREAD_RESUME_MAX_REPLAY_EVENTS + 1, }) .pipe( Stream.map((stored) => ({ kind: "event" as const, sequence: stored.sequence, - event: stored.event, + event: projectDomainEventForWire(stored.event), })), - Stream.mapError( + Stream.runCollect, + Effect.map((items) => Array.from(items)), + Effect.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ threadId: input.threadId, @@ -655,6 +668,34 @@ const makeWsRpcLayer = ( ? Stream.make({ kind: "synchronized" as const }) : Stream.empty; + const snapshotThenLive = Effect.fn("ws.orchestrationV2.threadSnapshotThenLive")( + function* () { + const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetThreadProjectionError({ + threadId: input.threadId, + message: `Failed to load orchestration V2 thread ${input.threadId}`, + cause, + }), + ), + ); + const { snapshotSequence } = snapshot; + const projection = projectThreadProjectionForWire(snapshot.projection); + return Stream.concat( + Stream.concat( + Stream.make({ + kind: "snapshot" as const, + snapshotSequence, + projection, + }), + completionMarker, + ), + eventStreamFrom(snapshotSequence), + ); + }, + ); + // When the client already holds the projection (cached, or loaded over // HTTP) it passes that snapshot's sequence, and we resume by replaying // persisted events after it instead of re-sending the (potentially @@ -673,35 +714,23 @@ const makeWsRpcLayer = ( }), ), ); + const replay = yield* loadReplayThrough(input.afterSequence, highWater); + const plan = decideThreadResume({ + afterSequence: input.afterSequence, + highWater, + replayEventCount: replay.length, + replayEncodedBytes: threadReplayEncodedBytes(replay), + }); + if (plan.mode === "snapshot") { + return yield* snapshotThenLive(); + } return Stream.concat( - Stream.concat(replayThrough(input.afterSequence, highWater), completionMarker), + Stream.concat(Stream.fromIterable(replay), completionMarker), eventStreamFrom(highWater), ); } - const snapshot = yield* threadManagement.getThreadSnapshot(input.threadId).pipe( - Effect.mapError( - (cause) => - new OrchestrationV2GetThreadProjectionError({ - threadId: input.threadId, - message: `Failed to load orchestration V2 thread ${input.threadId}`, - cause, - }), - ), - ); - const { projection, snapshotSequence } = snapshot; - - return Stream.concat( - Stream.concat( - Stream.make({ - kind: "snapshot" as const, - snapshotSequence, - projection, - }), - completionMarker, - ), - eventStreamFrom(snapshotSequence), - ); + return yield* snapshotThenLive(); }, ); @@ -808,7 +837,7 @@ const makeWsRpcLayer = ( // completions that race HTTP snapshot fetch still push a refresh. // When the client already holds a shell snapshot (cached, or loaded // over HTTP) it passes that snapshot's sequence. We still emit one - // enriched snapshot up front: getAvailable may have been cold on the + // compact metadata refresh up front: getAvailable may have been cold on the // HTTP path (null identity), and enrichment PubSub events published // before this subscribe attached are dropped. Rehydrating here fills // repositoryIdentity for cross-environment project grouping even on @@ -834,6 +863,16 @@ const makeWsRpcLayer = ( resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, }), ); + const initialEnrichmentItems = (loaded: { + readonly snapshot: OrchestrationV2ShellSnapshot; + readonly resolvedRepositoryIdentityRoots: ReadonlyArray; + }) => + Stream.fromIterable( + shellStreamItemsFromResumeSnapshot({ + snapshot: loaded.snapshot, + resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, + }), + ); // Initial unmarked (+ optional same-load marked) always drains first. // Enrichment merges only with the post-prefix tail so a ready marked // refresh cannot interleave before the authoritative initial frame. @@ -868,7 +907,7 @@ const makeWsRpcLayer = ( }), ); return composeShellStreamWithEnrichment({ - initial, + initial: initialEnrichmentItems(loaded), tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)), enrichment: enrichmentRefreshes, }); @@ -1118,6 +1157,7 @@ const makeWsRpcLayer = ( observeRpcEffect( ORCHESTRATION_V2_WS_METHODS.getThreadProjection, threadManagement.getThreadProjection(input.threadId).pipe( + Effect.map(projectThreadProjectionForWire), Effect.mapError( (cause) => new OrchestrationV2GetThreadProjectionError({ @@ -1168,6 +1208,10 @@ const makeWsRpcLayer = ( }), ) .pipe( + Effect.map((result) => ({ + ...result, + projection: projectThreadProjectionForWire(result.projection), + })), Effect.mapError( (cause) => new OrchestrationV2ThreadLaunchError({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6d9c15ab99..0d86465008 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -34,6 +34,7 @@ import { deriveThreadRuntime, } from "@t3tools/client-runtime/state/thread-execution"; import { resolveThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows"; +import { shouldShowLoadEarlierControl } from "@t3tools/client-runtime/state/threads"; import { resolveThreadLastVisitedAt } from "./Sidebar.logic"; import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { @@ -235,6 +236,7 @@ import { useProject, useProjects, useThreadProjection, + useThreadHistory, useThreadShell, useThreadRefs, useThreadVisibleTurnItems, @@ -245,7 +247,7 @@ import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; -import { MessagesTimeline } from "./chat/MessagesTimeline"; +import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline"; import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic"; import { ChatHeader } from "./chat/ChatHeader"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; @@ -1228,6 +1230,10 @@ function ChatViewContent(props: ChatViewProps) { const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, { reportFailure: false, }); + const loadEarlierThreadHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, { + label: "load earlier thread history", + reportFailure: false, + }); const respondToThreadApproval = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false, }); @@ -1277,6 +1283,23 @@ function ChatViewContent(props: ChatViewProps) { [serverProjection?.subagents], ); const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadDetailRef); + const serverThreadHistory = useThreadHistory(routeThreadDetailRef); + const threadHistoryControls = useMemo(() => { + if (routeThreadDetailRef === null || !shouldShowLoadEarlierControl(serverThreadHistory)) { + return undefined; + } + return { + hasMoreHistory: serverThreadHistory.hasMoreHistory, + loading: serverThreadHistory.loading, + error: serverThreadHistory.error, + onLoadEarlier: () => { + void loadEarlierThreadHistory({ + environmentId: routeThreadDetailRef.environmentId, + input: { threadId: routeThreadDetailRef.threadId }, + }); + }, + }; + }, [loadEarlierThreadHistory, routeThreadDetailRef, serverThreadHistory]); const committedServerMessageIds = useMemo( () => deriveCommittedServerUserMessageIds(serverVisibleTurnItems), [serverVisibleTurnItems], @@ -6422,6 +6445,9 @@ function ChatViewContent(props: ChatViewProps) { onManualNavigation={cancelTimelineLiveFollowForUserNavigation} hideEmptyPlaceholder={isDraftHeroState} topFadeEnabled={!hasTimelineTopBanner} + {...(threadHistoryControls === undefined + ? {} + : { historyControls: threadHistoryControls })} /> {/* scroll to end pill — shown when user has scrolled away from the live edge */} diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index 503d9ea9e8..1892d0b8be 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -231,6 +231,45 @@ function buildUserTimelineEntry(text: string) { } describe("MessagesTimeline", () => { + it("renders progressive history controls ahead of the bounded timeline", () => { + const markup = renderToStaticMarkup( + {}, + }} + />, + ); + + expect(markup).toContain('aria-label="Load earlier activity"'); + expect(markup).toContain("Load earlier activity"); + expect(markup).toContain("Earlier activity could not be loaded."); + expect(markup.indexOf("Load earlier activity")).toBeLessThan(markup.indexOf("Recent activity")); + }); + + it("keeps an empty bounded timeline actionable while earlier history loads", () => { + const markup = renderToStaticMarkup( + {}, + }} + />, + ); + + expect(markup).toContain("Loading earlier activity…"); + expect(markup).toContain("disabled"); + expect(markup).not.toContain("Send a message to start the conversation."); + }); + it("uses the larger leading inset only when the top fade is enabled", () => { const timelineEntries = [buildUserTimelineEntry("Hello")]; diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 4443465af3..ff129f1882 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -193,6 +193,13 @@ const EMPTY_TIMELINE_RUNS: ReadonlyArray = []; // Props (public API) // --------------------------------------------------------------------------- +export interface MessagesTimelineHistoryControls { + readonly hasMoreHistory: boolean; + readonly loading: boolean; + readonly error: string | null; + readonly onLoadEarlier: () => void; +} + interface MessagesTimelineProps { isWorking: boolean; activeTurnInProgress: boolean; @@ -247,6 +254,7 @@ interface MessagesTimelineProps { onManualNavigation: () => void; hideEmptyPlaceholder?: boolean; topFadeEnabled?: boolean; + historyControls?: MessagesTimelineHistoryControls; } // --------------------------------------------------------------------------- @@ -289,6 +297,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onManualNavigation, hideEmptyPlaceholder = false, topFadeEnabled = false, + historyControls, }: MessagesTimelineProps) { const [expandedRunIds, setExpandedRunIds] = useState>(new Set()); const [expandedAttemptIds, setExpandedAttemptIds] = useState>( @@ -582,10 +591,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }), [activeTurnInProgress, isRevertingCheckpoint, isWorking, latestRun?.runId], ); - const listHeader = useMemo( - () => + const listHeader = useMemo(() => { + const leadingContent = parentThreadLink === null ? ( - TIMELINE_LIST_HEADER + topFadeEnabled ? ( + TIMELINE_LIST_FADE_HEADER + ) : ( + TIMELINE_LIST_HEADER + ) ) : (
@@ -598,9 +611,15 @@ export const MessagesTimeline = memo(function MessagesTimeline({ />
- ), - [onOpenThread, parentThreadLink], - ); + ); + return ( + <> + {parentThreadLink === null ? leadingContent : null} + {historyControls ? : null} + {parentThreadLink !== null ? leadingContent : null} + + ); + }, [historyControls, onOpenThread, parentThreadLink, topFadeEnabled]); // Stable renderItem — no closure deps. Row components read shared state // from TimelineRowCtx, which propagates through LegendList's memo. @@ -615,7 +634,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({ [], ); - if (rows.length === 0 && !isWorking && parentThreadLink === null) { + if ( + rows.length === 0 && + !isWorking && + parentThreadLink === null && + historyControls === undefined + ) { if (hideEmptyPlaceholder) { return null; } @@ -657,9 +681,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ "messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain px-3 [overflow-anchor:none] sm:px-5", topFadeEnabled && "chat-timeline-scroll-fade", )} - ListHeaderComponent={ - topFadeEnabled && parentThreadLink === null ? TIMELINE_LIST_FADE_HEADER : listHeader - } + ListHeaderComponent={listHeader} ListFooterComponent={TIMELINE_LIST_FOOTER} /> +
+ {props.hasMoreHistory ? ( + + ) : null} + {props.error !== null ? ( +

+ {props.error} +

+ ) : null} +
+ + ); +} + function keyExtractor(item: MessagesTimelineRow) { return item.id; } diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts index b63d019990..6fc111e777 100644 --- a/apps/web/src/connection/runtime.ts +++ b/apps/web/src/connection/runtime.ts @@ -1,6 +1,9 @@ import { Connection } from "@t3tools/client-runtime/connection"; import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell"; -import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads"; +import { + boundedThreadSnapshotLoaderLayer, + threadHistoryControllerLayer, +} from "@t3tools/client-runtime/state/threads"; import { pullRequestDiffLoaderLayer } from "@t3tools/client-runtime/state/pull-requests"; import * as Layer from "effect/Layer"; import { Atom } from "effect/unstable/reactivity"; @@ -17,8 +20,9 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe( ); const snapshotLoaderLayer = Layer.mergeAll( - threadSnapshotLoaderLayer, + boundedThreadSnapshotLoaderLayer, shellSnapshotLoaderLayer, + threadHistoryControllerLayer, pullRequestDiffLoaderLayer, ); diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index e5a83827f4..3471499435 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -4,7 +4,11 @@ import type { EnvironmentThread, EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; -import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads"; +import { + EMPTY_THREAD_HISTORY_META, + type EnvironmentThreadStatus, + type ThreadHistoryMeta, +} from "@t3tools/client-runtime/state/threads"; import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts"; import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; @@ -40,6 +44,9 @@ const EMPTY_THREAD_STATUS_ATOM = Atom.make("empty").pip const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe( Atom.withLabel("web-thread-visible-turn-items:empty"), ); +const EMPTY_THREAD_HISTORY_ATOM = Atom.make(EMPTY_THREAD_HISTORY_META).pipe( + Atom.withLabel("web-thread-history:empty"), +); export const activeEnvironmentIdAtom = Atom.make(null).pipe( Atom.keepAlive, @@ -130,6 +137,12 @@ export function useThreadStatus(ref: ScopedThreadRef | null): EnvironmentThreadS ); } +export function useThreadHistory(ref: ScopedThreadRef | null): ThreadHistoryMeta { + return useAtomValue( + ref === null ? EMPTY_THREAD_HISTORY_ATOM : environmentThreadDetails.historyAtom(ref), + ); +} + export function resolveThreadDetailRef( ref: ScopedThreadRef | null, options: { diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md new file mode 100644 index 0000000000..01799be8b0 --- /dev/null +++ b/docs/internals/performance-regressions.md @@ -0,0 +1,30 @@ +# Performance regression checks + +The v2 transport has a focused regression command: + +```bash +vp run test:perf:v2-wire +``` + +It exercises the real v2 projection and client reducers. This matters because the older +built-app benchmark fixtures seed v1 orchestration events; running those fixtures against a v2 +client can produce reassuring timings while missing the active transport path. + +The v2 checks pin these invariants: + +- Client cold opens use a recent timeline window capped at 75 rows and about 1 MiB of encoded + timeline data. +- The bounded snapshot does not retain the full duplicate conversation-message table. +- Older activity is fetched in bounded HTTP pages and merged without disturbing the live scroll + window. +- Resume catch-up replays at most 128 thread events and 1 MiB of projected event JSON before + replacing stale state with a current snapshot. +- Oversized dynamic-tool results and detail strings are reduced only at the wire boundary; the + persisted event remains complete. +- Shell resume sends deltas plus compact repository-enrichment metadata, not another full project + and thread snapshot. +- Known idle sends and interrupts do not fetch a full thread projection before dispatch. + +When changing projection schemas, paging, shell synchronization, or thread state, run this command +alongside the focused package typechecks and a real-client pass on every affected surface. Payload +budgets belong in these tests rather than logs or one-off recordings so regressions fail locally. diff --git a/package.json b/package.json index 3fc66d0dd0..a71c964085 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "lint": "vp lint --report-unused-disable-directives", "lint:mobile": "node scripts/mobile-native-static-check.ts", "test": "vp run -r test", + "test:perf:v2-wire": "vp test run apps/server/src/orchestration-v2/WireProjection.test.ts apps/server/src/orchestration-v2/threadHistoryPaging.test.ts apps/server/src/orchestration-v2/ThreadStream.test.ts apps/server/src/orchestration-v2/ShellStream.test.ts packages/contracts/src/environmentHttp.test.ts packages/contracts/src/orchestrationV2.test.ts packages/client-runtime/src/operations/commands.test.ts packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts packages/client-runtime/src/state/threadHistoryController.test.ts packages/client-runtime/src/state/threadHistoryMerge.test.ts packages/client-runtime/src/state/threadDetail.test.ts packages/client-runtime/src/state/threads-sync.test.ts packages/client-runtime/src/state/shellReducer.test.ts", "test:resource-monitor": "cargo test --locked --manifest-path native/resource-monitor/Cargo.toml", "test:desktop-smoke": "vp run --filter @t3tools/desktop smoke-test", "fmt": "vp fmt", diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index 0e52e44410..dbef2ac8af 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -38,6 +38,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, createProject, + interruptThreadTurn, forkThreadFromRun, mergeThreadBack, cancelQueuedRun, @@ -71,6 +72,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct readonly projects: ProjectMutation[]; readonly launches?: OrchestrationV2ThreadLaunchInput[]; readonly projection?: OrchestrationV2ThreadProjection; + readonly projectionRequests?: ThreadId[]; }) { const client = { [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => @@ -78,8 +80,13 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct input.commands.push(command); return { sequence: input.commands.length }; }), - [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () => - Effect.succeed(input.projection ?? v2Projection), + [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (requestInput: { + readonly threadId: ThreadId; + }) => + Effect.sync(() => { + input.projectionRequests?.push(requestInput.threadId); + return input.projection ?? v2Projection; + }), [ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) => Effect.sync(() => { input.launches?.push(launchInput); @@ -510,4 +517,67 @@ describe("V2 environment commands", () => { ]); }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), ); + + it.effect("dispatches an explicit idle start without fetching the full projection", () => + Effect.gen(function* () { + const commands: OrchestrationV2Command[] = []; + const projectionRequests: ThreadId[] = []; + const supervisor = yield* makeSupervisor({ + commands, + projects: [], + projectionRequests, + }); + + yield* startThreadTurn({ + commandId: CommandId.make("direct-start"), + threadId: v2ThreadId, + message: { + messageId: MessageId.make("direct-start-message"), + role: "user", + text: "continue", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + dispatchMode: "start", + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(projectionRequests).toEqual([]); + expect(commands).toMatchObject([ + { + type: "message.dispatch", + threadId: v2ThreadId, + dispatchMode: { type: "start_immediately" }, + }, + ]); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + + it.effect("interrupts a known run without fetching the full projection", () => + Effect.gen(function* () { + const commands: OrchestrationV2Command[] = []; + const projectionRequests: ThreadId[] = []; + const supervisor = yield* makeSupervisor({ + commands, + projects: [], + projectionRequests, + }); + + yield* interruptThreadTurn({ + commandId: CommandId.make("direct-interrupt"), + threadId: v2ThreadId, + runId: RunId.make("active-run"), + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(projectionRequests).toEqual([]); + expect(commands).toEqual([ + { + type: "run.interrupt", + commandId: "direct-interrupt", + threadId: v2ThreadId, + runId: "active-run", + }, + ]); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); }); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index c3753998ff..763a72ba19 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -153,7 +153,7 @@ export interface StartThreadTurnInput extends ThreadCommandInput { readonly interactionMode: ProviderInteractionMode; readonly bootstrap?: StartThreadBootstrap; readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId }; - readonly dispatchMode?: "auto" | "queue" | "steer" | "restart"; + readonly dispatchMode?: "auto" | "queue" | "steer" | "restart" | "start"; } export interface InterruptThreadTurnInput extends ThreadCommandInput { @@ -589,6 +589,25 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( }); } + const requestedMode = input.dispatchMode ?? "auto"; + if (requestedMode === "start") { + return yield* dispatch({ + type: "message.dispatch", + commandId, + createdBy: "user", + creationSource: input.creationSource ?? "web", + threadId: input.threadId, + messageId: input.message.messageId, + text: input.message.text, + attachments, + ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), + ...(input.sourceProposedPlan === undefined + ? {} + : { sourcePlanRef: input.sourceProposedPlan }), + dispatchMode: { type: "start_immediately" }, + }); + } + const projection = yield* getProjection(input.threadId); const activeRun = projection.runs.findLast( (run) => @@ -597,7 +616,6 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( run.status === "running" || run.status === "waiting", ); - const requestedMode = input.dispatchMode ?? "auto"; const activeProviderThread = activeRun === undefined ? undefined @@ -647,17 +665,17 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* ( input: InterruptThreadTurnInput, ) { - const projection = yield* getProjection(input.threadId); - const runId = - input.runId ?? - (input.turnId as RunId | undefined) ?? - projection.runs.findLast( + let runId = input.runId ?? (input.turnId as RunId | undefined); + if (runId === undefined) { + const projection = yield* getProjection(input.threadId); + runId = projection.runs.findLast( (run) => run.status === "preparing" || run.status === "starting" || run.status === "running" || run.status === "waiting", )?.id; + } if (runId === undefined) return { sequence: 0 }; return yield* dispatch({ type: "run.interrupt", diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts new file mode 100644 index 0000000000..1ac5b7e6b5 --- /dev/null +++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.test.ts @@ -0,0 +1,214 @@ +import { ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { PrimaryConnectionTarget, type PreparedConnection } from "../connection/model.ts"; +import { remoteHttpClientLayer } from "../rpc/http.ts"; +import { boundedThreadSnapshotLoaderLayer } from "./boundedThreadSnapshotHttp.ts"; +import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts"; + +const TARGET = new PrimaryConnectionTarget({ + environmentId: "environment-bounded" as never, + label: "Bounded", + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", +}); + +const PREPARED: PreparedConnection = { + environmentId: TARGET.environmentId, + label: TARGET.label, + httpBaseUrl: TARGET.httpBaseUrl, + socketUrl: TARGET.wsBaseUrl, + httpAuthorization: null, + target: TARGET, +}; + +const THREAD_ID = ThreadId.make("thread-bounded"); +const NOW = "2026-06-20T00:00:00.000Z"; + +const FULL_SNAPSHOT_BODY = { + snapshotSequence: 9, + projection: { + thread: { + createdBy: "user", + creationSource: "web", + id: String(THREAD_ID), + projectId: "project-1", + title: "Full fallback thread", + providerInstanceId: "codex", + modelSelection: { instanceId: "codex", model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: String(THREAD_ID), + }, + forkedFrom: null, + createdAt: NOW, + updatedAt: NOW, + archivedAt: null, + deletedAt: null, + settledOverride: null, + settledAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: NOW, + }, +}; + +describe("boundedThreadSnapshotLoader", () => { + it.effect("falls back to full HTTP snapshot when bounded returns a plain route 404", () => { + const fetchFn = ((input: RequestInfo | URL) => { + const url = String(input); + if (url.includes(`/api/orchestration/threads/${THREAD_ID}/bounded`)) { + // Generic HTML/route 404: not a structured thread_not_found payload. + return Promise.resolve( + new Response("Not Found", { + status: 404, + headers: { "content-type": "text/plain" }, + }), + ); + } + expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}`); + expect(url.includes("/bounded")).toBe(false); + return Promise.resolve( + new Response(JSON.stringify(FULL_SNAPSHOT_BODY), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ); + }) satisfies typeof fetch; + + return Effect.gen(function* () { + const loader = yield* ThreadSnapshotLoader; + const result = yield* loader.load(PREPARED, THREAD_ID); + expect(result._tag).toBe("present"); + if (result._tag === "present") { + expect(result.snapshot.snapshotSequence).toBe(9); + expect(result.snapshot.projection.thread.title).toBe("Full fallback thread"); + expect(result.history).toBeUndefined(); + } + }).pipe( + Effect.provide( + Layer.provide(boundedThreadSnapshotLoaderLayer, remoteHttpClientLayer(fetchFn)), + ), + ); + }); + + it.effect("treats structured EnvironmentResourceNotFoundError from bounded as missing", () => { + const fetchFn = ((input: RequestInfo | URL) => { + const url = String(input); + expect(url).toContain(`/api/orchestration/threads/${THREAD_ID}/bounded`); + return Promise.resolve( + Response.json( + { + _tag: "EnvironmentResourceNotFoundError", + code: "not_found", + reason: "thread_not_found", + traceId: "trace-bounded-missing", + }, + { status: 404 }, + ), + ); + }) satisfies typeof fetch; + + return Effect.gen(function* () { + const loader = yield* ThreadSnapshotLoader; + const result = yield* loader.load(PREPARED, THREAD_ID); + expect(result).toEqual({ _tag: "missing" }); + }).pipe( + Effect.provide( + Layer.provide(boundedThreadSnapshotLoaderLayer, remoteHttpClientLayer(fetchFn)), + ), + ); + }); + + it.effect("treats structured missing from full fallback as missing", () => { + let fullCalls = 0; + const fetchFn = ((input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/bounded")) { + return Promise.resolve( + new Response("Not Found", { + status: 404, + headers: { "content-type": "text/plain" }, + }), + ); + } + fullCalls += 1; + return Promise.resolve( + Response.json( + { + _tag: "EnvironmentResourceNotFoundError", + code: "not_found", + reason: "thread_not_found", + traceId: "trace-full-missing", + }, + { status: 404 }, + ), + ); + }) satisfies typeof fetch; + + return Effect.gen(function* () { + const loader = yield* ThreadSnapshotLoader; + const result = yield* loader.load(PREPARED, THREAD_ID); + expect(result).toEqual({ _tag: "missing" }); + expect(fullCalls).toBe(1); + }).pipe( + Effect.provide( + Layer.provide(boundedThreadSnapshotLoaderLayer, remoteHttpClientLayer(fetchFn)), + ), + ); + }); + + it.effect( + "uses socket fallback directly when the bounded endpoint has a transient failure", + () => { + let fullCalls = 0; + const fetchFn = ((input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/bounded")) { + return Promise.resolve(new Response("Service Unavailable", { status: 503 })); + } + fullCalls += 1; + return Promise.resolve( + new Response(JSON.stringify(FULL_SNAPSHOT_BODY), { + status: 200, + headers: { "content-type": "application/json" }, + }), + ); + }) satisfies typeof fetch; + + return Effect.gen(function* () { + const loader = yield* ThreadSnapshotLoader; + const result = yield* loader.load(PREPARED, THREAD_ID); + expect(result).toEqual({ _tag: "unavailable" }); + expect(fullCalls).toBe(0); + }).pipe( + Effect.provide( + Layer.provide(boundedThreadSnapshotLoaderLayer, remoteHttpClientLayer(fetchFn)), + ), + ); + }, + ); +}); diff --git a/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts new file mode 100644 index 0000000000..a36eb16eb5 --- /dev/null +++ b/packages/client-runtime/src/state/boundedThreadSnapshotHttp.ts @@ -0,0 +1,156 @@ +import type { ThreadId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { HttpClient } from "effect/unstable/http"; + +import type { PreparedConnection } from "../connection/model.ts"; +import { environmentEndpointUrl } from "../environment/endpoint.ts"; +import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts"; +import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts"; +import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts"; +import { + fetchEnvironmentThreadSnapshot, + ThreadSnapshotLoader, + type ThreadSnapshotLoadResult, +} from "./threadSnapshotHttp.ts"; + +// Same cold-open budget as the full snapshot path; bounded payloads should fit. +const DEFAULT_BOUNDED_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000; + +/** Load a bounded recent-window thread snapshot over HTTP. */ +export const fetchEnvironmentBoundedThreadSnapshot = Effect.fn( + "clientRuntime.state.fetchEnvironmentBoundedThreadSnapshot", +)(function* (input: { + readonly prepared: PreparedConnection; + readonly threadId: ThreadId; + readonly signer: Option.Option; + readonly timeoutMs?: number; +}) { + const requestUrl = environmentEndpointUrl( + input.prepared.httpBaseUrl, + `/api/orchestration/threads/${input.threadId}/bounded`, + ); + const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl); + const headers = yield* buildEnvironmentAuthHeaders( + input.prepared.httpAuthorization, + "GET", + requestUrl, + input.signer, + ); + return yield* executeEnvironmentHttpRequest( + requestUrl, + input.timeoutMs ?? DEFAULT_BOUNDED_THREAD_SNAPSHOT_TIMEOUT_MS, + withEnvironmentCredentials( + input.prepared.httpAuthorization, + client.orchestration.threadBoundedSnapshot({ + params: { threadId: input.threadId }, + headers, + }), + ), + ); +}); + +/** + * Shared ThreadSnapshotLoader for clients that render progressive history. + * Seeds from the bounded HTTP snapshot when available. Older servers that lack + * the bounded route (plain/generic 404) fall back to the existing full HTTP + * thread snapshot. Structured EnvironmentResourceNotFoundError from either + * endpoint still means missing. Transient failures report `unavailable` so the + * socket path remains a last resort for connectivity issues. + */ +export const boundedThreadSnapshotLoaderLayer: Layer.Layer< + ThreadSnapshotLoader, + never, + HttpClient.HttpClient +> = Layer.effect( + ThreadSnapshotLoader, + Effect.gen(function* () { + const httpClient = yield* HttpClient.HttpClient; + const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner); + return ThreadSnapshotLoader.of({ + load: (prepared: PreparedConnection, threadId: ThreadId) => { + const loadFullFallback = fetchEnvironmentThreadSnapshot({ + prepared, + threadId, + signer, + }).pipe( + Effect.map( + (snapshot): ThreadSnapshotLoadResult => ({ + _tag: "present", + snapshot, + }), + ), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.catchTags({ + EnvironmentResourceNotFoundError: () => + Effect.logDebug( + "Full thread snapshot not found over HTTP after bounded fallback; treating the thread as deleted.", + ).pipe( + Effect.annotateLogs({ threadId }), + Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult), + ), + }), + Effect.catchCause((cause) => + Effect.logWarning( + "Could not load the full thread snapshot over HTTP after bounded fallback; using the socket snapshot instead.", + ).pipe( + Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }), + Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult), + ), + ), + ); + + return fetchEnvironmentBoundedThreadSnapshot({ prepared, threadId, signer }).pipe( + Effect.map( + (bounded): ThreadSnapshotLoadResult => ({ + _tag: "present", + snapshot: { + snapshotSequence: bounded.snapshotSequence, + projection: bounded.projection, + latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal, + }, + history: { + historyCursor: bounded.historyCursor, + hasMoreHistory: bounded.hasMoreHistory, + latestLocalTurnOrdinal: bounded.latestLocalTurnOrdinal, + }, + }), + ), + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.catchTags({ + EnvironmentResourceNotFoundError: () => + Effect.logDebug( + "Bounded thread snapshot not found over HTTP; treating the thread as deleted.", + ).pipe( + Effect.annotateLogs({ threadId }), + Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult), + ), + RemoteEnvironmentAuthInvalidJsonError: (error) => + Effect.logDebug( + "Bounded thread snapshot returned an invalid response; trying the full HTTP thread snapshot for an older server.", + ).pipe( + Effect.annotateLogs({ threadId, cause: error.message }), + Effect.andThen(loadFullFallback), + ), + RemoteEnvironmentAuthUndeclaredStatusError: (error) => + error.status === 404 + ? Effect.logDebug( + "Bounded thread snapshot route was not found; trying the full HTTP thread snapshot for an older server.", + ).pipe(Effect.annotateLogs({ threadId }), Effect.andThen(loadFullFallback)) + : Effect.fail(error), + }), + Effect.catchCause((cause) => + Effect.logWarning( + "Could not load the bounded thread snapshot over HTTP; using the socket snapshot instead.", + ).pipe( + Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }), + Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult), + ), + ), + ); + }, + }); + }), +); diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 98144197a4..ddbda4a209 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -5,6 +5,11 @@ import type { } from "@t3tools/contracts"; import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline"; +export type ApplyOrchestrationV2ProjectionEventOptions = { + readonly partialTimeline?: boolean; + readonly latestLocalTurnOrdinal?: number | null; +}; + function upsertEntity( items: ReadonlyArray, item: T, @@ -60,9 +65,43 @@ function activeVisibleTurnItems( return next === null ? rows : renumberVisibleItems(next); } +function oldestLocalTurnOrdinal( + rows: OrchestrationV2ThreadProjection["visibleTurnItems"], +): number | null { + let oldest: number | null = null; + for (const row of rows) { + if (row.visibility !== "local") continue; + if (oldest === null || row.item.ordinal < oldest) { + oldest = row.item.ordinal; + } + } + return oldest; +} + +function shouldDropMissingPartialTurnItem( + projection: OrchestrationV2ThreadProjection, + item: OrchestrationV2TurnItem, + latestLocalTurnOrdinal: number | null | undefined, +): boolean { + if (projection.visibleTurnItems.some((row) => row.sourceItemId === item.id)) { + return false; + } + if ( + latestLocalTurnOrdinal !== null && + latestLocalTurnOrdinal !== undefined && + item.ordinal <= latestLocalTurnOrdinal + ) { + return true; + } + const oldest = oldestLocalTurnOrdinal(projection.visibleTurnItems); + return oldest !== null && item.ordinal < oldest; +} + function upsertVisibleTurnItem( projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem, + partialTimeline: boolean, + latestLocalTurnOrdinal: number | null | undefined, ): OrchestrationV2ThreadProjection["visibleTurnItems"] { const rows = projection.visibleTurnItems; const index = rows.findIndex((row) => row.sourceItemId === item.id); @@ -83,6 +122,13 @@ function upsertVisibleTurnItem( ) { return rows; } + if ( + index === -1 && + partialTimeline && + shouldDropMissingPartialTurnItem(projection, item, latestLocalTurnOrdinal) + ) { + return rows; + } const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)]; const insertionIndex = updated.findIndex( (row) => @@ -99,9 +145,12 @@ function upsertVisibleTurnItem( export function applyOrchestrationV2ProjectionEvent( projection: OrchestrationV2ThreadProjection | null, event: OrchestrationV2DomainEvent, + options?: ApplyOrchestrationV2ProjectionEventOptions, ): OrchestrationV2ThreadProjection | null { if (projection === null || event.threadId !== projection.thread.id) return projection; + const partialTimeline = options?.partialTimeline === true; + const latestLocalTurnOrdinal = options?.latestLocalTurnOrdinal; const base = { ...projection, updatedAt: event.occurredAt }; switch (event.type) { case "thread.created": @@ -163,12 +212,19 @@ export function applyOrchestrationV2ProjectionEvent( case "plan.updated": return { ...base, plans: upsertEntity(base.plans, event.payload) }; case "turn-item.updated": { + if ( + partialTimeline && + !projection.turnItems.some((candidate) => candidate.id === event.payload.id) && + shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal) + ) { + return projection; + } const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) }; const visible = { ...next, visibleTurnItems: activeVisibleTurnItems(next) }; return { ...next, visibleTurnItems: shouldShowLocalTurnItem(next, event.payload) - ? upsertVisibleTurnItem(visible, event.payload) + ? upsertVisibleTurnItem(visible, event.payload, partialTimeline, latestLocalTurnOrdinal) : removeVisibleItem(visible.visibleTurnItems, event.payload.id), }; } diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index 3593494a2a..8aa8fd1772 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -214,6 +214,30 @@ describe("applyShellStreamEvent", () => { expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity); }); + it("treats higher-sequence compact enrichment as metadata-only", () => { + const previous = { + ...v2ShellSnapshot, + snapshotSequence: 5, + projects: [{ ...v2Project, repositoryIdentity: null }], + threads: [{ ...v2ThreadShell, title: "Newest title" }], + }; + const next = mergeShellSnapshotProjects( + previous, + { + ...v2ShellSnapshot, + snapshotSequence: 8, + projects: [{ ...v2Project, repositoryIdentity }], + threads: [], + archivedThreads: [], + }, + { resolvedRepositoryIdentityRoots: [v2Project.workspaceRoot] }, + ); + + expect(next.snapshotSequence).toBe(5); + expect(next.threads[0]?.title).toBe("Newest title"); + expect(next.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity); + }); + it("lower-sequence enrichment cannot resurrect empty structural state", () => { const previous = { ...v2ShellSnapshot, diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 71de63333d..c5d0e0631f 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -29,8 +29,8 @@ function retainRepositoryIdentity( export interface MergeShellSnapshotOptions { /** - * Enrichment refresh: structure and sequence must not roll back when at or - * below cache; listed roots accept identity exactly (including null). + * Metadata-only enrichment refresh: structure and sequence never change; + * listed roots accept identity exactly (including null). * Omit this options object for authoritative HTTP/initial WebSocket snapshots. */ readonly resolvedRepositoryIdentityRoots: ReadonlyArray; @@ -43,9 +43,9 @@ export interface MergeShellSnapshotOptions { * lower than cache, while retaining a prior non-null identity when the candidate * is still unresolved/null for the same root. * - * Enrichment snapshots (options present) never resurrect or roll back - * projects/threads/archives/sequence when at or below cache; they only patch - * repository identity for matching current projects. + * Enrichment snapshots (options present) only patch repository identity for + * matching current projects. They never replace projects, threads, archives, + * or sequence, regardless of the incoming snapshot sequence. */ export function mergeShellSnapshotProjects( previous: OrchestrationV2ShellSnapshot | null | undefined, @@ -59,7 +59,7 @@ export function mergeShellSnapshotProjects( const isEnrichment = options !== undefined; const resolvedRootSet = isEnrichment ? new Set(options.resolvedRepositoryIdentityRoots) : null; - if (isEnrichment && next.snapshotSequence <= previous.snapshotSequence) { + if (isEnrichment) { const nextById = new Map(next.projects.map((project) => [project.id, project] as const)); return { ...previous, diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index ffbd5243d9..4f06b010ef 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -1,4 +1,7 @@ +import type { ThreadId } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import { Atom } from "effect/unstable/reactivity"; import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts"; @@ -61,6 +64,15 @@ import { visitThread, } from "../operations/commands.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { EnvironmentSupervisor } from "../connection/supervisor.ts"; +import { + ThreadHistoryController, + type ThreadHistoryLoadEarlierResult, +} from "./threadHistoryController.ts"; + +export type LoadEarlierThreadHistoryInput = { + readonly threadId: ThreadId; +}; export type { ArchiveThreadInput, @@ -279,5 +291,25 @@ export function createThreadEnvironmentAtoms( scheduler, concurrency, }), + loadEarlierHistory: createEnvironmentCommand(runtime, { + label: "environment-data:commands:thread:load-earlier-history", + execute: (input: LoadEarlierThreadHistoryInput) => + Effect.gen(function* () { + const supervisor = yield* EnvironmentSupervisor; + const controller = yield* Effect.serviceOption(ThreadHistoryController); + if (Option.isNone(controller)) { + return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult; + } + return yield* controller.value.loadEarlier( + supervisor.target.environmentId, + input.threadId, + ); + }), + scheduler, + concurrency: { + mode: "serial", + key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]), + }, + }), }; } diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts index fcbdc85d53..7b0d275388 100644 --- a/packages/client-runtime/src/state/threadDetail.test.ts +++ b/packages/client-runtime/src/state/threadDetail.test.ts @@ -4,6 +4,7 @@ import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; import { describe, expect, it } from "vite-plus/test"; import { v2Projection } from "./orchestrationV2TestFixtures.ts"; +import { EMPTY_THREAD_HISTORY_META } from "./threadHistoryMerge.ts"; import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts"; import type { EnvironmentThreadState } from "./threads.ts"; @@ -12,13 +13,22 @@ const ref: ScopedThreadRef = { threadId: ThreadId.make(v2Projection.thread.id), }; +function threadState( + partial: Pick & + Partial>, +): EnvironmentThreadState { + return { ...partial, history: partial.history ?? EMPTY_THREAD_HISTORY_META }; +} + describe("createEnvironmentThreadDetailAtoms", () => { it("adds environment scope while preserving the pristine projection", () => { - const initial: AsyncResult.AsyncResult = AsyncResult.success({ - data: Option.some(v2Projection), - status: "cached", - error: Option.none(), - }); + const initial: AsyncResult.AsyncResult = AsyncResult.success( + threadState({ + data: Option.some(v2Projection), + status: "cached", + error: Option.none(), + }), + ); const sourceAtom = Atom.make(initial); const details = createEnvironmentThreadDetailAtoms(() => sourceAtom); const registry = AtomRegistry.make(); @@ -28,46 +38,61 @@ describe("createEnvironmentThreadDetailAtoms", () => { expect(thread?.projection).toBe(v2Projection); expect(registry.get(details.visibleTurnItemsAtom(ref))).toBe(v2Projection.visibleTurnItems); expect(registry.get(details.statusAtom(ref))).toBe("cached"); + expect(registry.get(details.historyAtom(ref))).toBe(EMPTY_THREAD_HISTORY_META); registry.set( sourceAtom, - AsyncResult.success({ - data: Option.some(v2Projection), - status: "synchronizing", - error: Option.none(), - }), + AsyncResult.success( + threadState({ + data: Option.some(v2Projection), + status: "synchronizing", + error: Option.none(), + }), + ), ); expect(registry.get(details.threadAtom(ref))).toBe(thread); expect(registry.get(details.statusAtom(ref))).toBe("synchronizing"); + const progressiveHistory = { + ...EMPTY_THREAD_HISTORY_META, + historyCursor: "cursor-1", + hasMoreHistory: true, + }; registry.set( sourceAtom, - AsyncResult.success({ - data: Option.some(v2Projection), - status: "live", - error: Option.some("Stream interrupted."), - }), + AsyncResult.success( + threadState({ + data: Option.some(v2Projection), + status: "live", + error: Option.some("Stream interrupted."), + history: progressiveHistory, + }), + ), ); expect(registry.get(details.threadAtom(ref))).toBe(thread); expect(registry.get(details.visibleTurnItemsAtom(ref))).toBe(v2Projection.visibleTurnItems); expect(registry.get(details.statusAtom(ref))).toBe("live"); expect(registry.get(details.errorAtom(ref))).toBe("Stream interrupted."); + expect(registry.get(details.historyAtom(ref))).toBe(progressiveHistory); registry.set( sourceAtom, - AsyncResult.success({ - data: Option.none(), - status: "deleted", - error: Option.none(), - }), + AsyncResult.success( + threadState({ + data: Option.none(), + status: "deleted", + error: Option.none(), + }), + ), ); expect(registry.get(details.threadAtom(ref))).toBeNull(); expect(registry.get(details.visibleTurnItemsAtom(ref))).toEqual([]); expect(registry.get(details.statusAtom(ref))).toBe("deleted"); expect(registry.get(details.errorAtom(ref))).toBeNull(); + expect(registry.get(details.historyAtom(ref))).toBe(EMPTY_THREAD_HISTORY_META); registry.dispose(); }); }); diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index 4b9a6e309c..e596dccaca 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -66,6 +66,12 @@ export function createEnvironmentThreadDetailAtoms( Atom.withLabel(`environment-thread-error:${key}`), ), ); + const historyAtomFamily = Atom.family((key: string) => + Atom.make((get) => get(threadStateValueAtomFamily(key)).history).pipe( + Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), + Atom.withLabel(`environment-thread-history:${key}`), + ), + ); return { stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)), @@ -73,5 +79,6 @@ export function createEnvironmentThreadDetailAtoms( visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)), statusAtom: (ref: ScopedThreadRef) => statusAtomFamily(threadKey(ref)), errorAtom: (ref: ScopedThreadRef) => errorAtomFamily(threadKey(ref)), + historyAtom: (ref: ScopedThreadRef) => historyAtomFamily(threadKey(ref)), }; } diff --git a/packages/client-runtime/src/state/threadHistoryController.test.ts b/packages/client-runtime/src/state/threadHistoryController.test.ts new file mode 100644 index 0000000000..642dc25e8d --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryController.test.ts @@ -0,0 +1,66 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import { + ThreadHistoryController, + threadHistoryControllerLayer, + type ThreadHistoryHandler, + type ThreadHistoryLoadEarlierResult, +} from "./threadHistoryController.ts"; + +const ENV = "env-history" as EnvironmentId; +const THREAD = "thread-history" as ThreadId; + +function handler( + tag: string, +): ThreadHistoryHandler & { readonly tag: string; readonly calls: number } { + const state = { tag, calls: 0 }; + return { + get tag() { + return state.tag; + }, + get calls() { + return state.calls; + }, + loadEarlier: () => { + state.calls += 1; + return Effect.succeed({ _tag: "loaded" } satisfies ThreadHistoryLoadEarlierResult); + }, + }; +} + +describe("ThreadHistoryController", () => { + it.effect("does not let an older finalizer delete a newer registration", () => + Effect.gen(function* () { + const controller = yield* ThreadHistoryController; + const older = handler("older"); + const newer = handler("newer"); + + const olderRegistration = yield* controller.register(ENV, THREAD, older); + const newerRegistration = yield* controller.register(ENV, THREAD, newer); + + // Older fiber finalizes after the newer handler is already registered. + yield* controller.unregister(olderRegistration); + + const result = yield* controller.loadEarlier(ENV, THREAD); + expect(result).toEqual({ _tag: "loaded" }); + expect(newer.calls).toBe(1); + expect(older.calls).toBe(0); + + yield* controller.unregister(newerRegistration); + expect(yield* controller.loadEarlier(ENV, THREAD)).toEqual({ _tag: "noop" }); + }).pipe(Effect.provide(threadHistoryControllerLayer)), + ); + + it.effect("unregister removes only its own matching registration", () => + Effect.gen(function* () { + const controller = yield* ThreadHistoryController; + const first = handler("first"); + const registration = yield* controller.register(ENV, THREAD, first); + yield* controller.unregister(registration); + expect(yield* controller.loadEarlier(ENV, THREAD)).toEqual({ _tag: "noop" }); + }).pipe(Effect.provide(Layer.fresh(threadHistoryControllerLayer))), + ); +}); diff --git a/packages/client-runtime/src/state/threadHistoryController.ts b/packages/client-runtime/src/state/threadHistoryController.ts new file mode 100644 index 0000000000..4fde44b108 --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryController.ts @@ -0,0 +1,93 @@ +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; + +import { threadKey } from "./entities.ts"; + +export type ThreadHistoryLoadEarlierResult = + | { readonly _tag: "loaded" } + | { readonly _tag: "noop" } + | { readonly _tag: "busy" } + | { readonly _tag: "error"; readonly message: string }; + +export type ThreadHistoryHandler = { + readonly loadEarlier: () => Effect.Effect; +}; + +/** + * Opaque registration token returned by `register`. Finalizers must pass the + * same token so an older fiber cannot delete a newer handler for the key. + */ +export type ThreadHistoryRegistration = { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly handler: ThreadHistoryHandler; +}; + +/** + * Per-thread registration for progressive history loads. Thread state fibers + * register while active; mobile UI dispatches through `loadEarlier`. + */ +export class ThreadHistoryController extends Context.Service< + ThreadHistoryController, + { + readonly register: ( + environmentId: EnvironmentId, + threadId: ThreadId, + handler: ThreadHistoryHandler, + ) => Effect.Effect; + readonly unregister: (registration: ThreadHistoryRegistration) => Effect.Effect; + readonly loadEarlier: ( + environmentId: EnvironmentId, + threadId: ThreadId, + ) => Effect.Effect; + } +>()("@t3tools/client-runtime/state/threadHistoryController") {} + +export const threadHistoryControllerLayer: Layer.Layer = Layer.effect( + ThreadHistoryController, + Effect.gen(function* () { + const handlers = yield* Ref.make(new Map()); + return ThreadHistoryController.of({ + register: (environmentId, threadId, handler) => + Ref.update(handlers, (current) => { + const next = new Map(current); + next.set(threadKey({ environmentId, threadId }), handler); + return next; + }).pipe( + Effect.as({ + environmentId, + threadId, + handler, + } satisfies ThreadHistoryRegistration), + ), + unregister: (registration) => + Ref.update(handlers, (current) => { + const key = threadKey({ + environmentId: registration.environmentId, + threadId: registration.threadId, + }); + // Only remove when this registration still owns the slot. An older + // fiber finalizer must not delete a newer handler for the same key. + if (current.get(key) !== registration.handler) { + return current; + } + const next = new Map(current); + next.delete(key); + return next; + }), + loadEarlier: (environmentId, threadId) => + Ref.get(handlers).pipe( + Effect.flatMap((current) => { + const handler = current.get(threadKey({ environmentId, threadId })); + if (handler === undefined) { + return Effect.succeed({ _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult); + } + return handler.loadEarlier(); + }), + ), + }); + }), +); diff --git a/packages/client-runtime/src/state/threadHistoryHttp.ts b/packages/client-runtime/src/state/threadHistoryHttp.ts new file mode 100644 index 0000000000..3deadd94b9 --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryHttp.ts @@ -0,0 +1,45 @@ +import type { ThreadId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { PreparedConnection } from "../connection/model.ts"; +import { environmentEndpointUrl } from "../environment/endpoint.ts"; +import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts"; +import { executeEnvironmentHttpRequest, makeEnvironmentHttpApiClient } from "../rpc/http.ts"; +import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./environmentHttpAuth.ts"; + +const DEFAULT_THREAD_HISTORY_TIMEOUT_MS = 6_000; + +export const fetchEnvironmentThreadHistoryPage = Effect.fn( + "clientRuntime.state.fetchEnvironmentThreadHistoryPage", +)(function* (input: { + readonly prepared: PreparedConnection; + readonly threadId: ThreadId; + readonly cursor: string; + readonly signer: Option.Option; + readonly timeoutMs?: number; +}) { + const requestUrl = environmentEndpointUrl( + input.prepared.httpBaseUrl, + `/api/orchestration/threads/${input.threadId}/history`, + ); + const client = yield* makeEnvironmentHttpApiClient(input.prepared.httpBaseUrl); + const headers = yield* buildEnvironmentAuthHeaders( + input.prepared.httpAuthorization, + "GET", + requestUrl, + input.signer, + ); + return yield* executeEnvironmentHttpRequest( + requestUrl, + input.timeoutMs ?? DEFAULT_THREAD_HISTORY_TIMEOUT_MS, + withEnvironmentCredentials( + input.prepared.httpAuthorization, + client.orchestration.threadHistoryPage({ + params: { threadId: input.threadId }, + query: { cursor: input.cursor }, + headers, + }), + ), + ); +}); diff --git a/packages/client-runtime/src/state/threadHistoryMerge.test.ts b/packages/client-runtime/src/state/threadHistoryMerge.test.ts new file mode 100644 index 0000000000..0952e3eedd --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryMerge.test.ts @@ -0,0 +1,416 @@ +import type { OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { + applyHistoryPageMeta, + clearActiveHistoryLoading, + isActiveHistoryRequestCursor, + mergeOlderHistoryIntoProjection, + shouldShowLoadEarlierControl, +} from "./threadHistoryMerge.ts"; +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; + +const NOW = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); + +function row(index: number): OrchestrationV2ProjectedTurnItem { + const id = `item-${index}` as never; + return { + position: index, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: id, + item: { + id, + type: "command_execution", + threadId: v2ThreadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: index + 1, + status: "completed", + title: `Command ${index}`, + input: `cmd-${index}`, + output: `out-${index}`, + exitCode: 0, + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + }, + }; +} + +describe("threadHistoryMerge", () => { + it("prepends older rows and dedupes by source identity", () => { + const recent = [row(2), row(3)]; + const projection = { + ...v2Projection, + turnItems: recent.map((entry) => entry.item), + visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })), + }; + const older = [row(0), row(1), row(2)]; + const merged = mergeOlderHistoryIntoProjection(projection, older); + expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([ + "item-0", + "item-1", + "item-2", + "item-3", + ]); + expect(merged.visibleTurnItems.map((entry) => entry.position)).toEqual([0, 1, 2, 3]); + expect(merged.turnItems.map((item) => item.id)).toEqual([ + "item-2", + "item-3", + "item-0", + "item-1", + ]); + }); + + it("retains live rows that arrived after the older page was fetched", () => { + const live = [row(5), row(6)]; + const projection = { + ...v2Projection, + turnItems: live.map((entry) => entry.item), + visibleTurnItems: live.map((entry, position) => ({ ...entry, position })), + }; + const older = [row(3), row(4)]; + const merged = mergeOlderHistoryIntoProjection(projection, older); + expect(merged.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([ + "item-3", + "item-4", + "item-5", + "item-6", + ]); + }); + + it("does not resurrect a local item hidden while an older page was in flight", () => { + const stalePageRow = row(1); + const currentItem = { + ...stalePageRow.item, + output: "newer live output", + updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:01.000Z"), + }; + const projection = { + ...v2Projection, + turnItems: [currentItem], + visibleTurnItems: [], + }; + + const merged = mergeOlderHistoryIntoProjection(projection, [stalePageRow]); + + expect(merged).toBe(projection); + expect(merged.turnItems).toEqual([currentItem]); + expect(merged.visibleTurnItems).toEqual([]); + }); + + it("marks history expanded after a successful page", () => { + const next = applyHistoryPageMeta( + { + historyCursor: "cursor-a", + hasMoreHistory: true, + loading: true, + error: null, + expanded: false, + latestLocalTurnOrdinal: 42, + }, + { nextCursor: "cursor-b", hasMoreHistory: true }, + ); + expect(next).toEqual({ + historyCursor: "cursor-b", + hasMoreHistory: true, + loading: false, + error: null, + expanded: true, + latestLocalTurnOrdinal: 42, + }); + }); + + it("only applies history responses for the active request cursor", () => { + expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-a" })).toBe(true); + expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: "cursor-b" })).toBe(false); + expect(isActiveHistoryRequestCursor("cursor-a", { historyCursor: null })).toBe(false); + }); + + it("clears loading on interrupt only for the active request cursor", () => { + const loading = { + historyCursor: "cursor-a", + hasMoreHistory: true, + loading: true, + error: null, + expanded: false, + latestLocalTurnOrdinal: 10, + }; + expect(clearActiveHistoryLoading("cursor-a", loading)).toEqual({ + ...loading, + loading: false, + }); + // Stale cursor must not mutate replacement progressive meta. + expect( + clearActiveHistoryLoading("cursor-a", { ...loading, historyCursor: "cursor-b" }), + ).toEqual({ ...loading, historyCursor: "cursor-b" }); + // Already idle: identity-preserving no-op shape. + const idle = { ...loading, loading: false }; + expect(clearActiveHistoryLoading("cursor-a", idle)).toBe(idle); + }); + + it("shows the load-earlier control when history remains or a local error is set", () => { + expect( + shouldShowLoadEarlierControl({ + historyCursor: "c", + hasMoreHistory: true, + loading: false, + error: null, + expanded: false, + latestLocalTurnOrdinal: null, + }), + ).toBe(true); + expect( + shouldShowLoadEarlierControl({ + historyCursor: null, + hasMoreHistory: false, + loading: false, + error: "Could not load earlier activity.", + expanded: true, + latestLocalTurnOrdinal: null, + }), + ).toBe(true); + expect( + shouldShowLoadEarlierControl({ + historyCursor: null, + hasMoreHistory: false, + loading: false, + error: null, + expanded: false, + latestLocalTurnOrdinal: null, + }), + ).toBe(false); + }); + + it("retains merged older rows when a live turn-item update arrives", () => { + const recent = [row(2), row(3)]; + const projection = { + ...v2Projection, + turnItems: recent.map((entry) => entry.item), + visibleTurnItems: recent.map((entry, position) => ({ ...entry, position })), + }; + const merged = mergeOlderHistoryIntoProjection(projection, [row(0), row(1)]); + const liveItem = { + ...row(3).item, + output: "streamed", + }; + const next = applyOrchestrationV2ProjectionEvent(merged, { + id: "event-live-item" as never, + type: "turn-item.updated", + threadId: v2ThreadId, + occurredAt: NOW, + payload: liveItem, + } as never); + expect(next?.visibleTurnItems.map((entry) => entry.sourceItemId)).toEqual([ + "item-0", + "item-1", + "item-2", + "item-3", + ]); + expect(next?.visibleTurnItems[3]?.item).toEqual(liveItem); + }); + + it("keeps a history-page interrupt result visible when its request was retained at cold open", () => { + // Cold bounded window: only a recent filler. Request was retained in + // turnItems (not visible). Result arrives later via load-earlier merge. + const runId = "run-interrupt-cold" as never; + const nodeId = "node-interrupt-cold" as never; + const recent = row(5); + const requestItem = { + id: "item-interrupt-request" as never, + type: "run_interrupt_request" as const, + threadId: v2ThreadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed" as const, + title: null, + message: "Stopping", + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + }; + const resultItem = { + id: "item-interrupt-result" as never, + type: "run_interrupt_result" as const, + threadId: v2ThreadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed" as const, + title: null, + message: "Stopped", + startedAt: NOW, + completedAt: NOW, + updatedAt: NOW, + }; + const resultRow = { + position: 0, + visibility: "local" as const, + sourceThreadId: v2ThreadId, + sourceItemId: resultItem.id, + item: resultItem, + }; + const coldOpen = { + ...v2Projection, + runs: [ + { + id: runId, + threadId: v2ThreadId, + ordinal: 1, + providerInstanceId: "codex" as never, + modelSelection: { instanceId: "codex" as never, model: "gpt-5" }, + providerThreadId: null, + userMessageId: "message-1" as never, + rootNodeId: nodeId, + activeAttemptId: null, + status: "running" as const, + requestedAt: NOW, + startedAt: NOW, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + ], + attempts: [ + { + id: "attempt-1" as never, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId: "codex" as never, + providerThreadId: "provider-thread-1" as never, + providerTurnId: null, + reason: "initial" as const, + status: "running" as const, + startedAt: NOW, + completedAt: null, + }, + ], + // Request retained from full projection; no result yet in the window. + turnItems: [requestItem, recent.item], + visibleTurnItems: [{ ...recent, position: 0 }], + }; + + const requestMerged = mergeOlderHistoryIntoProjection(coldOpen, [ + { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: requestItem.id, + item: requestItem, + }, + ]); + expect(requestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([ + "item-interrupt-request", + "item-5", + ]); + + const rolledBackRequestMerged = mergeOlderHistoryIntoProjection( + { + ...coldOpen, + runs: coldOpen.runs.map((run) => ({ + ...run, + status: "rolled_back" as const, + completedAt: NOW, + })), + }, + [ + { + position: 0, + visibility: "local", + sourceThreadId: v2ThreadId, + sourceItemId: requestItem.id, + item: requestItem, + }, + ], + ); + expect( + rolledBackRequestMerged.visibleTurnItems.map((entry) => String(entry.sourceItemId)), + ).toEqual(["item-5"]); + + const merged = mergeOlderHistoryIntoProjection(coldOpen, [resultRow]); + expect(merged.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([ + "item-interrupt-result", + "item-5", + ]); + expect(merged.turnItems.some((item) => item.type === "run_interrupt_request")).toBe(true); + expect(merged.turnItems.some((item) => item.type === "run_interrupt_result")).toBe(true); + + const attemptSuperseded = applyOrchestrationV2ProjectionEvent( + merged, + { + id: "event-attempt-superseded" as never, + type: "run-attempt.updated", + threadId: v2ThreadId, + runId, + occurredAt: NOW, + payload: { + id: "attempt-1" as never, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId: "codex" as never, + providerThreadId: "provider-thread-1" as never, + providerTurnId: null, + reason: "initial", + status: "superseded", + startedAt: NOW, + completedAt: NOW, + }, + } as never, + { partialTimeline: true }, + ); + + expect(attemptSuperseded?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual([ + "item-interrupt-result", + "item-5", + ]); + + // Without the cold-open retained request, the same update would hide the result. + const withoutRequest = { + ...merged, + turnItems: merged.turnItems.filter((item) => item.type !== "run_interrupt_request"), + }; + const hidden = applyOrchestrationV2ProjectionEvent( + withoutRequest, + { + id: "event-attempt-superseded-missing" as never, + type: "run-attempt.updated", + threadId: v2ThreadId, + runId, + occurredAt: NOW, + payload: { + id: "attempt-1" as never, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId: "codex" as never, + providerThreadId: "provider-thread-1" as never, + providerTurnId: null, + reason: "initial", + status: "superseded", + startedAt: NOW, + completedAt: NOW, + }, + } as never, + { partialTimeline: true }, + ); + expect(hidden?.visibleTurnItems.map((entry) => String(entry.sourceItemId))).toEqual(["item-5"]); + }); +}); diff --git a/packages/client-runtime/src/state/threadHistoryMerge.ts b/packages/client-runtime/src/state/threadHistoryMerge.ts new file mode 100644 index 0000000000..6210686ec0 --- /dev/null +++ b/packages/client-runtime/src/state/threadHistoryMerge.ts @@ -0,0 +1,156 @@ +import type { + OrchestrationV2ProjectedTurnItem, + OrchestrationV2ThreadProjection, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { isOrchestrationV2TurnItemVisible } from "@t3tools/shared/orchestrationV2Timeline"; + +export type ThreadHistoryMeta = { + readonly historyCursor: string | null; + readonly hasMoreHistory: boolean; + readonly loading: boolean; + readonly error: string | null; + /** True after at least one older page was merged; skip monolithic cache growth. */ + readonly expanded: boolean; + /** + * Max local turn ordinal known for partial progressive windows. Null when + * unknown (legacy cache) or when history meta is cleared for a full snapshot. + */ + readonly latestLocalTurnOrdinal: number | null; +}; + +export const EMPTY_THREAD_HISTORY_META: ThreadHistoryMeta = { + historyCursor: null, + hasMoreHistory: false, + loading: false, + error: null, + expanded: false, + latestLocalTurnOrdinal: null, +}; + +/** Whether a history-page response still matches the cursor that started it. */ +export function isActiveHistoryRequestCursor( + requestCursor: string, + history: { readonly historyCursor: string | null }, +): boolean { + return history.historyCursor === requestCursor; +} + +/** + * Clear history loading after an interrupted load-earlier only when the + * request cursor is still active. Does not touch stream/status/error. + */ +export function clearActiveHistoryLoading( + requestCursor: string, + history: ThreadHistoryMeta, +): ThreadHistoryMeta { + if (!isActiveHistoryRequestCursor(requestCursor, history) || !history.loading) { + return history; + } + return { ...history, loading: false }; +} + +function projectedItemKey(row: OrchestrationV2ProjectedTurnItem): string { + return `${row.sourceThreadId}:${row.sourceItemId}`; +} + +function renumberVisible( + rows: ReadonlyArray, +): OrchestrationV2ProjectedTurnItem[] { + return rows.map((row, position) => (row.position === position ? row : { ...row, position })); +} + +/** + * Merge an older history page into the live projection. Dedupes by + * sourceThreadId + sourceItemId, keeps chronological order (older first), and + * preserves newer live rows already present in state. + */ +export function mergeOlderHistoryIntoProjection( + projection: OrchestrationV2ThreadProjection, + olderItems: ReadonlyArray, +): OrchestrationV2ThreadProjection { + if (olderItems.length === 0) { + return projection; + } + + const existingKeys = new Set(projection.visibleTurnItems.map(projectedItemKey)); + const turnItemById = new Map(); + for (const item of projection.turnItems) { + turnItemById.set(String(item.id), item); + } + const prepended: OrchestrationV2ProjectedTurnItem[] = []; + for (const pageRow of olderItems) { + let row = pageRow; + const key = projectedItemKey(row); + if (existingKeys.has(key)) { + continue; + } + if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) { + const currentItem = turnItemById.get(String(row.sourceItemId)); + if (currentItem !== undefined) { + // A live event may have hidden this item while the page was in flight. + // Do not resurrect the stale page copy. Retained interrupt requests are + // the exception: they intentionally exist outside the bounded visible + // window and should become visible when their history page arrives. + if (currentItem.type !== "run_interrupt_request") { + continue; + } + if ( + !isOrchestrationV2TurnItemVisible({ + item: currentItem, + runs: projection.runs, + attempts: projection.attempts, + items: projection.turnItems, + }) + ) { + continue; + } + row = { ...row, item: currentItem }; + } + } + existingKeys.add(key); + prepended.push(row); + } + if (prepended.length === 0) { + return projection; + } + + const visibleTurnItems = renumberVisible([...prepended, ...projection.visibleTurnItems]); + + for (const row of prepended) { + if (row.visibility === "local" || row.sourceThreadId === projection.thread.id) { + if (!turnItemById.has(String(row.sourceItemId))) { + turnItemById.set(String(row.sourceItemId), row.item); + } + } + } + + return { + ...projection, + turnItems: [...turnItemById.values()], + visibleTurnItems, + }; +} + +export function applyHistoryPageMeta( + current: ThreadHistoryMeta, + page: { + readonly nextCursor: string | null; + readonly hasMoreHistory: boolean; + }, +): ThreadHistoryMeta { + return { + historyCursor: page.nextCursor, + hasMoreHistory: page.hasMoreHistory, + loading: false, + error: null, + expanded: true, + // Preserve the partial-timeline watermark across load-earlier pages. + latestLocalTurnOrdinal: current.latestLocalTurnOrdinal, + }; +} + +/** Whether a client timeline should render its load-earlier control. */ +export function shouldShowLoadEarlierControl(history: ThreadHistoryMeta): boolean { + return history.hasMoreHistory || history.error !== null; +} diff --git a/packages/client-runtime/src/state/threadSnapshotHttp.ts b/packages/client-runtime/src/state/threadSnapshotHttp.ts index e539617c4f..c379dc3b2a 100644 --- a/packages/client-runtime/src/state/threadSnapshotHttp.ts +++ b/packages/client-runtime/src/state/threadSnapshotHttp.ts @@ -21,6 +21,30 @@ import { buildEnvironmentAuthHeaders, withEnvironmentCredentials } from "./envir // delays the transition to live data on the first open, not the initial paint. const DEFAULT_THREAD_SNAPSHOT_TIMEOUT_MS = 6_000; +/** Progressive history metadata returned by a bounded snapshot loader. */ +export type ThreadSnapshotHistoryMeta = { + readonly historyCursor: string | null; + readonly hasMoreHistory: boolean; + /** Max local turn ordinal from the full projection; optional on older servers. */ + readonly latestLocalTurnOrdinal?: number | null; +}; + +/** + * Outcome of an HTTP thread-detail snapshot load. + * + * - `present`: snapshot body is available (seed projection, resume via socket). + * - `missing`: server definitively reported the thread does not exist (404). + * - `unavailable`: transport/timeout/5xx/etc.; fall back to the socket path. + */ +export type ThreadSnapshotLoadResult = + | { + readonly _tag: "present"; + readonly snapshot: OrchestrationV2ThreadDetailSnapshot; + readonly history?: ThreadSnapshotHistoryMeta; + } + | { readonly _tag: "missing" } + | { readonly _tag: "unavailable" }; + /** * Load a thread's detail snapshot over HTTP instead of embedding it in the * WebSocket subscription's first frame. The response is gzip-compressible by @@ -61,10 +85,12 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn( export type FetchEnvironmentThreadSnapshotError = RemoteEnvironmentRequestError; /** - * Loads a thread's detail snapshot over HTTP, returning `Option.none()` when it - * cannot be loaded (so the caller falls back to the socket-embedded snapshot). - * Decouples the thread state machine from the underlying HTTP + DPoP details and - * keeps them out of test contexts. + * Loads a thread's detail snapshot over HTTP. + * + * Distinguishes a definitive missing thread (HTTP 404) from transient snapshot + * unavailability so the thread state machine can mark the thread deleted without + * opening a socket subscription, while still falling back to the socket when the + * HTTP path is merely unavailable. */ export class ThreadSnapshotLoader extends Context.Service< ThreadSnapshotLoader, @@ -72,7 +98,7 @@ export class ThreadSnapshotLoader extends Context.Service< readonly load: ( prepared: PreparedConnection, threadId: ThreadId, - ) => Effect.Effect>; + ) => Effect.Effect; } >()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {} @@ -91,19 +117,22 @@ export const threadSnapshotLoaderLayer: Layer.Layer< return ThreadSnapshotLoader.of({ load: (prepared: PreparedConnection, threadId: ThreadId) => fetchEnvironmentThreadSnapshot({ prepared, threadId, signer }).pipe( - Effect.map(Option.some), + Effect.map( + (snapshot): ThreadSnapshotLoadResult => ({ + _tag: "present", + snapshot, + }), + ), Effect.provideService(HttpClient.HttpClient, httpClient), - // A genuinely missing thread (404) is expected — the socket - // subscription is the source of truth for thread existence and will - // surface the deletion — so don't treat it as an error worth warning - // about; just defer to the socket path. + // A genuinely missing thread (404) is definitive: do not fall back to + // the socket or retry. Callers mark the thread deleted and clear cache. Effect.catchTags({ EnvironmentResourceNotFoundError: () => Effect.logDebug( - "Thread snapshot not found over HTTP; deferring to the socket subscription.", + "Thread snapshot not found over HTTP; treating the thread as deleted.", ).pipe( Effect.annotateLogs({ threadId }), - Effect.as(Option.none()), + Effect.as({ _tag: "missing" } satisfies ThreadSnapshotLoadResult), ), }), Effect.catchCause((cause) => @@ -111,7 +140,7 @@ export const threadSnapshotLoaderLayer: Layer.Layer< "Could not load the thread snapshot over HTTP; using the socket snapshot instead.", ).pipe( Effect.annotateLogs({ threadId, cause: Cause.pretty(cause) }), - Effect.as(Option.none()), + Effect.as({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult), ), ), ), diff --git a/packages/client-runtime/src/state/threadState.ts b/packages/client-runtime/src/state/threadState.ts index 5ef18259b7..d534f50ce9 100644 --- a/packages/client-runtime/src/state/threadState.ts +++ b/packages/client-runtime/src/state/threadState.ts @@ -1,16 +1,25 @@ import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import * as Option from "effect/Option"; +import { EMPTY_THREAD_HISTORY_META, type ThreadHistoryMeta } from "./threadHistoryMerge.ts"; + export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted"; export interface EnvironmentThreadState { readonly data: Option.Option; readonly status: EnvironmentThreadStatus; readonly error: Option.Option; + /** + * Progressive history cursor for bounded hydration. Absent/cleared on full + * snapshot paths. Errors here are thread/history-local and must not be + * promoted into the environment disconnect path. + */ + readonly history: ThreadHistoryMeta; } export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = { data: Option.none(), status: "empty", error: Option.none(), + history: EMPTY_THREAD_HISTORY_META, }; diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 1992da2f6c..fcb7edc4b6 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -3,9 +3,11 @@ import { EventId, ORCHESTRATION_V2_WS_METHODS, ThreadId, + TurnItemId, type OrchestrationV2ThreadDetailSnapshot, type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadStreamItem, + type OrchestrationV2TurnItem, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as DateTime from "effect/DateTime"; @@ -34,6 +36,7 @@ import { makeEnvironmentThreadState, ThreadSnapshotLoader, type EnvironmentThreadState, + type ThreadSnapshotLoadResult, } from "./threads.ts"; const TARGET = new PrimaryConnectionTarget({ @@ -87,7 +90,12 @@ function awaitThreadState( const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: { readonly cached?: OrchestrationV2ThreadProjection; - readonly httpSnapshot?: Option.Option; + readonly cachedHistory?: { + readonly historyCursor: string | null; + readonly hasMoreHistory: boolean; + readonly latestLocalTurnOrdinal?: number | null; + }; + readonly httpSnapshot?: ThreadSnapshotLoadResult; readonly completionMarker?: boolean; }) { const inputs = yield* Queue.unbounded(); @@ -136,8 +144,9 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o Ref.update(loaderCalls, (count) => count + 1).pipe( Effect.as( threadId === THREAD_ID - ? (options?.httpSnapshot ?? Option.none()) - : Option.none(), + ? (options?.httpSnapshot ?? + ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult)) + : ({ _tag: "unavailable" } satisfies ThreadSnapshotLoadResult), ), ), }); @@ -159,6 +168,17 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o ? Option.some({ snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, projection: options.cached, + ...(options.cachedHistory === undefined + ? {} + : { + historyCursor: options.cachedHistory.historyCursor, + hasMoreHistory: options.cachedHistory.hasMoreHistory, + ...(options.cachedHistory.latestLocalTurnOrdinal === undefined + ? {} + : { + latestLocalTurnOrdinal: options.cachedHistory.latestLocalTurnOrdinal, + }), + }), }) : Option.none(), ), @@ -316,7 +336,10 @@ describe("EnvironmentThreads", () => { thread: { ...BASE_PROJECTION.thread, title: "HTTP title" }, }; const harness = yield* makeHarness({ - httpSnapshot: Option.some({ snapshotSequence: 1, projection: httpProjection }), + httpSnapshot: { + _tag: "present", + snapshot: { snapshotSequence: 1, projection: httpProjection }, + }, }); // No socket snapshot is pushed; only a live event arrives over the socket. // It can only be applied if the HTTP snapshot already seeded the thread. @@ -338,6 +361,580 @@ describe("EnvironmentThreads", () => { }), ); + it.effect("installs bounded snapshot history meta and resumes via afterSequence", () => + Effect.gen(function* () { + const httpProjection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Bounded title" }, + }; + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { snapshotSequence: 11, projection: httpProjection }, + history: { + historyCursor: "opaque-cursor", + hasMoreHistory: true, + }, + }, + }); + yield* Queue.offer(harness.inputs, titleUpdated("Live after bounded", 12)); + + const state = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Live after bounded" && + value.history.hasMoreHistory, + ); + + expect(state.history).toMatchObject({ + historyCursor: "opaque-cursor", + hasMoreHistory: true, + loading: false, + error: null, + expanded: false, + }); + expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(11); + // Bounded HTTP success must not require a socket snapshot frame. + expect(Option.getOrThrow(state.data).thread.title).toBe("Live after bounded"); + }), + ); + + it.effect("persists progressive history meta with a settled bounded snapshot", () => + Effect.gen(function* () { + const httpProjection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Bounded cache title" }, + }; + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { snapshotSequence: 4, projection: httpProjection }, + history: { + historyCursor: "cursor-oldest", + hasMoreHistory: true, + }, + }, + }); + // Bounded install alone (settled) must enqueue progressive meta with the + // projection. Never persist the partial window as a complete full snapshot. + yield* awaitThreadState( + harness.observed, + (value) => + Option.isSome(value.data) && + value.data.value.thread.title === "Bounded cache title" && + value.history.historyCursor === "cursor-oldest", + ); + yield* TestClock.adjust("500 millis"); + yield* Effect.yieldNow; + + const savedAll = yield* Ref.get(harness.savedThreads); + expect(savedAll.length).toBeGreaterThanOrEqual(1); + const first = savedAll[0]; + expect(first?.snapshotSequence).toBe(4); + expect(first?.projection.thread.title).toBe("Bounded cache title"); + expect(first?.historyCursor).toBe("cursor-oldest"); + expect(first?.hasMoreHistory).toBe(true); + // No earlier complete-looking entry without progressive meta. + expect( + savedAll.some( + (entry) => + entry.projection.thread.title === "Bounded cache title" && + entry.historyCursor === undefined && + entry.hasMoreHistory === undefined, + ), + ).toBe(false); + + // A later live update still carries the progressive cursor. + yield* Queue.offer(harness.inputs, titleUpdated("Settled bounded", 5)); + yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Settled bounded", + ); + yield* TestClock.adjust("500 millis"); + yield* Effect.yieldNow; + + const saved = (yield* Ref.get(harness.savedThreads)).at(-1); + expect(saved?.snapshotSequence).toBe(5); + expect(saved?.projection.thread.title).toBe("Settled bounded"); + expect(saved?.historyCursor).toBe("cursor-oldest"); + expect(saved?.hasMoreHistory).toBe(true); + }), + ); + + it.effect("warm resume restores progressive history meta and skips HTTP", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + cached: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Cached bounded" }, + }, + cachedHistory: { + historyCursor: "warm-cursor", + hasMoreHistory: true, + }, + }); + + // Apply a live event so the subscription is known to have resumed from cache. + yield* Queue.offer( + harness.inputs, + titleUpdated("Cached bounded live", CACHED_SNAPSHOT_SEQUENCE + 1), + ); + const state = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Cached bounded live" && + value.history.hasMoreHistory, + ); + + expect(state.history).toMatchObject({ + historyCursor: "warm-cursor", + hasMoreHistory: true, + expanded: false, + }); + // Warm progressive cache must not re-download; resume via afterSequence. + expect(yield* Ref.get(harness.loaderCalls)).toBe(0); + expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE); + }), + ); + + it.effect("legacy warm cache without history meta stays complete (no false load-earlier)", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ cached: BASE_PROJECTION }); + const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data)); + expect(state.history).toMatchObject({ + historyCursor: null, + hasMoreHistory: false, + expanded: false, + }); + expect(yield* Ref.get(harness.loaderCalls)).toBe(0); + }), + ); + + it.effect("socket snapshot clears progressive history meta left from a bounded window", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + cached: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Warm progressive" }, + }, + cachedHistory: { + historyCursor: "stale-cursor", + hasMoreHistory: true, + }, + }); + + yield* Queue.offer( + harness.inputs, + snapshot( + { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Full socket snapshot" }, + }, + CACHED_SNAPSHOT_SEQUENCE + 1, + ), + ); + + const state = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Full socket snapshot" && + value.history.historyCursor === null && + value.history.hasMoreHistory === false, + ); + + expect(state.history).toMatchObject({ + historyCursor: null, + hasMoreHistory: false, + expanded: false, + loading: false, + error: null, + }); + + // Settled full snapshot persistence must not keep the stale cursor. + yield* TestClock.adjust("500 millis"); + yield* Effect.yieldNow; + const saved = (yield* Ref.get(harness.savedThreads)).at(-1); + expect(saved?.projection.thread.title).toBe("Full socket snapshot"); + expect(saved?.historyCursor).toBeUndefined(); + expect(saved?.hasMoreHistory).toBeUndefined(); + }), + ); + + it.effect("live events preserve progressive history meta under atomic setThread", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { + snapshotSequence: 8, + projection: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Bounded seed" }, + }, + }, + history: { + historyCursor: "keep-me", + hasMoreHistory: true, + }, + }, + }); + + yield* Queue.offer(harness.inputs, titleUpdated("Live preserves meta", 9)); + const state = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Live preserves meta", + ); + + expect(state.history).toMatchObject({ + historyCursor: "keep-me", + hasMoreHistory: true, + expanded: false, + }); + }), + ); + + it.effect("bounded HTTP install sets projection and progressive meta atomically", () => + Effect.gen(function* () { + // One setThread with explicit history (not applyItem reset + later meta). + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { + snapshotSequence: 2, + projection: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Bounded atomic install" }, + }, + }, + history: { + historyCursor: "post-install-cursor", + hasMoreHistory: true, + }, + }, + }); + + const state = yield* awaitThreadState( + harness.observed, + (value) => + Option.isSome(value.data) && + value.data.value.thread.title === "Bounded atomic install" && + value.history.historyCursor === "post-install-cursor" && + value.history.hasMoreHistory === true, + ); + + expect(state.history).toMatchObject({ + historyCursor: "post-install-cursor", + hasMoreHistory: true, + loading: false, + error: null, + expanded: false, + }); + expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(2); + }), + ); + + it.effect("dropped partial-timeline turn item is a true applyItem no-op", () => + Effect.gen(function* () { + const recent = { + id: TurnItemId.make("item-window"), + threadId: THREAD_ID, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 10, + status: "completed" as const, + title: null, + startedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + completedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + type: "command_execution" as const, + input: "pwd", + output: "ok", + exitCode: 0, + } satisfies OrchestrationV2TurnItem; + const recentRow = { + position: 0, + visibility: "local" as const, + sourceThreadId: THREAD_ID, + sourceItemId: recent.id, + item: recent, + }; + const boundedProjection: OrchestrationV2ThreadProjection = { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Partial noop" }, + turnItems: [recent], + visibleTurnItems: [recentRow], + }; + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { + snapshotSequence: 5, + projection: boundedProjection, + latestLocalTurnOrdinal: 10, + }, + history: { + historyCursor: "partial-cursor", + hasMoreHistory: true, + latestLocalTurnOrdinal: 10, + }, + }, + }); + + const seeded = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Partial noop" && + value.history.historyCursor === "partial-cursor", + ); + const seededProjection = Option.getOrThrow(seeded.data); + yield* TestClock.adjust("500 millis"); + yield* Effect.yieldNow; + const savedBefore = (yield* Ref.get(harness.savedThreads)).length; + + const older = { + ...recent, + id: TurnItemId.make("item-old-outside"), + ordinal: 3, + output: "must-not-append", + } satisfies OrchestrationV2TurnItem; + yield* Queue.offer(harness.inputs, { + kind: "event", + sequence: 6, + event: { + id: EventId.make("event-old-partial"), + type: "turn-item.updated", + threadId: THREAD_ID, + occurredAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"), + payload: older, + }, + }); + + // Allow the event to be processed without requiring a state transition. + for (let attempt = 0; attempt < 30; attempt += 1) { + yield* Effect.yieldNow; + } + // Drive a later unrelated title update so we know the stream continued. + yield* Queue.offer(harness.inputs, titleUpdated("After dropped event", 7)); + const after = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "After dropped event", + ); + + // The dropped event must not have appended the old item. + expect(Option.getOrThrow(after.data).turnItems.map((item) => String(item.id))).toEqual([ + String(recent.id), + ]); + // Watermark unchanged (only advanced on successful newer turn-item applies). + expect(after.history.latestLocalTurnOrdinal).toBe(10); + // No persistence enqueue from the dropped event itself. + const savedAfterDrop = (yield* Ref.get(harness.savedThreads)).length; + expect(savedAfterDrop).toBe(savedBefore); + // Seeded projection reference path: event path kept partial meta intact. + expect(after.history.historyCursor).toBe("partial-cursor"); + expect(after.history.hasMoreHistory).toBe(true); + // Title event applied; drop itself did not clear progressive meta. + expect(seededProjection.turnItems.map((item) => String(item.id))).toEqual([ + String(recent.id), + ]); + }), + ); + + it.effect("installs and advances latestLocalTurnOrdinal for partial progressive windows", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + httpSnapshot: { + _tag: "present", + snapshot: { + snapshotSequence: 3, + projection: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Watermark seed" }, + }, + latestLocalTurnOrdinal: 15, + }, + history: { + historyCursor: "wm-cursor", + hasMoreHistory: true, + latestLocalTurnOrdinal: 15, + }, + }, + }); + + const seeded = yield* awaitThreadState( + harness.observed, + (value) => + Option.isSome(value.data) && + value.data.value.thread.title === "Watermark seed" && + value.history.latestLocalTurnOrdinal === 15, + ); + expect(seeded.history.latestLocalTurnOrdinal).toBe(15); + + yield* TestClock.adjust("500 millis"); + yield* Effect.yieldNow; + const savedSeed = (yield* Ref.get(harness.savedThreads)).at(-1); + expect(savedSeed?.latestLocalTurnOrdinal).toBe(15); + + const newer = { + id: TurnItemId.make("item-newer-live"), + threadId: THREAD_ID, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 22, + status: "completed" as const, + title: null, + startedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + completedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + updatedAt: DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"), + type: "command_execution" as const, + input: "echo newer", + output: "newer", + exitCode: 0, + } satisfies OrchestrationV2TurnItem; + + yield* Queue.offer(harness.inputs, { + kind: "event", + sequence: 4, + event: { + id: EventId.make("event-newer-item"), + type: "turn-item.updated", + threadId: THREAD_ID, + occurredAt: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"), + payload: newer, + }, + }); + + const advanced = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.history.latestLocalTurnOrdinal === 22 && + value.data.value.turnItems.some((item) => String(item.id) === String(newer.id)), + ); + expect(advanced.history.latestLocalTurnOrdinal).toBe(22); + expect(advanced.history.historyCursor).toBe("wm-cursor"); + }), + ); + + it.effect("warm resume restores latestLocalTurnOrdinal from progressive cache", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + cached: { + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Warm watermark" }, + }, + cachedHistory: { + historyCursor: "warm-wm-cursor", + hasMoreHistory: true, + latestLocalTurnOrdinal: 33, + }, + }); + + const state = yield* awaitThreadState( + harness.observed, + (value) => + Option.isSome(value.data) && + value.data.value.thread.title === "Warm watermark" && + value.history.latestLocalTurnOrdinal === 33, + ); + expect(state.history).toMatchObject({ + historyCursor: "warm-wm-cursor", + hasMoreHistory: true, + latestLocalTurnOrdinal: 33, + expanded: false, + }); + expect(yield* Ref.get(harness.loaderCalls)).toBe(0); + }), + ); + + it.effect("marks a cold definitive HTTP miss deleted without socket subscribe or retry", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + httpSnapshot: { _tag: "missing" }, + }); + + const state = yield* awaitThreadState( + harness.observed, + (value) => value.status === "deleted", + ); + + expect(Option.isNone(state.data)).toBe(true); + expect(Option.isNone(state.error)).toBe(true); + expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1); + expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]); + expect(yield* Ref.get(harness.subscriptionCount)).toBe(0); + + // A definitive miss must not schedule the expected-failure retry path. + yield* TestClock.adjust("1 second"); + for (let attempt = 0; attempt < 20; attempt += 1) { + yield* Effect.yieldNow; + } + yield* harness.replaceSession; + yield* Queue.offer(harness.wakeups, "application-active"); + for (let attempt = 0; attempt < 20; attempt += 1) { + yield* Effect.yieldNow; + } + expect(yield* Ref.get(harness.subscriptionCount)).toBe(0); + expect(yield* Ref.get(harness.retryCount)).toBe(0); + expect(yield* Ref.get(harness.loaderCalls)).toBe(1); + expect((yield* Ref.get(harness.latest)).status).toBe("deleted"); + }), + ); + + it.effect("falls back to the socket when the HTTP snapshot is only unavailable", () => + Effect.gen(function* () { + const harness = yield* makeHarness({ + httpSnapshot: { _tag: "unavailable" }, + }); + + yield* Queue.offer( + harness.inputs, + snapshot({ + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Socket title" }, + }), + ); + + const state = yield* awaitThreadState( + harness.observed, + (value) => + value.status === "live" && + Option.isSome(value.data) && + value.data.value.thread.title === "Socket title", + ); + + expect(Option.getOrThrow(state.data).thread.title).toBe("Socket title"); + expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1); + expect(yield* Ref.get(harness.subscriptionCount)).toBe(1); + expect(yield* Ref.get(harness.removedThreads)).toEqual([]); + }), + ); + it.effect("ignores replayed thread events at or below the snapshot sequence", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 1058ac6bd9..ff35dc017c 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -11,8 +11,10 @@ import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; +import * as Result from "effect/Result"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import { HttpClient } from "effect/unstable/http"; import { Atom } from "effect/unstable/reactivity"; import { EnvironmentRegistry } from "../connection/registry.ts"; @@ -20,12 +22,26 @@ import { connectionProjectionPhase } from "../connection/model.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import * as ConnectionWakeups from "../connection/wakeups.ts"; import { EnvironmentCacheStore } from "../platform/persistence.ts"; +import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts"; import { subscribeDynamic } from "../rpc/client.ts"; -import { ThreadSnapshotLoader } from "./threadSnapshotHttp.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; -import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; +import { + ThreadHistoryController, + type ThreadHistoryLoadEarlierResult, +} from "./threadHistoryController.ts"; +import { fetchEnvironmentThreadHistoryPage } from "./threadHistoryHttp.ts"; +import { + applyHistoryPageMeta, + clearActiveHistoryLoading, + EMPTY_THREAD_HISTORY_META, + isActiveHistoryRequestCursor, + mergeOlderHistoryIntoProjection, + type ThreadHistoryMeta, +} from "./threadHistoryMerge.ts"; +import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts"; +import { ThreadSnapshotLoader, type ThreadSnapshotLoadResult } from "./threadSnapshotHttp.ts"; import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState, @@ -45,7 +61,57 @@ function formatThreadError(cause: Cause.Cause): string { : "Could not synchronize the thread."; } -function shouldPersistThread(thread: OrchestrationV2ThreadProjection): boolean { +function formatHistoryError(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + return "Could not load earlier activity."; +} + +function historyMetaFromCachedSnapshot( + snapshot: OrchestrationV2ThreadDetailSnapshot, +): ThreadHistoryMeta { + const historyCursor = snapshot.historyCursor ?? null; + const hasMoreHistory = snapshot.hasMoreHistory ?? false; + return { + historyCursor, + hasMoreHistory, + loading: false, + error: null, + // Cache never stores expanded progressive history (load-earlier growth). + expanded: false, + latestLocalTurnOrdinal: snapshot.latestLocalTurnOrdinal ?? null, + }; +} + +function snapshotToPersist( + snapshotSequence: number, + projection: OrchestrationV2ThreadProjection, + history: ThreadHistoryMeta, +): OrchestrationV2ThreadDetailSnapshot { + // Persist progressive meta with the bounded window so warm resume restores the + // history cursor instead of looking like a complete full-projection cache hit. + if (history.hasMoreHistory || history.historyCursor !== null) { + return { + snapshotSequence, + projection, + historyCursor: history.historyCursor, + hasMoreHistory: history.hasMoreHistory, + latestLocalTurnOrdinal: history.latestLocalTurnOrdinal, + }; + } + return { snapshotSequence, projection }; +} + +function shouldPersistThread( + thread: OrchestrationV2ThreadProjection, + history: ThreadHistoryMeta, +): boolean { + // After the user loads older pages the in-memory timeline can grow large. + // Keep those expanded projections out of the monolithic cache. + if (history.expanded) { + return false; + } return !thread.runs.some( (run) => run.status === "preparing" || run.status === "starting" || run.status === "running", ); @@ -57,6 +123,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make const supervisor = yield* EnvironmentSupervisor; const cache = yield* EnvironmentCacheStore; const snapshotLoader = yield* ThreadSnapshotLoader; + const historyController = yield* Effect.serviceOption(ThreadHistoryController); + const httpClient = yield* Effect.serviceOption(HttpClient.HttpClient); + const dpopSigner = yield* Effect.serviceOption(ManagedRelayDpopSigner); const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups); const environmentId = supervisor.target.environmentId; const cached = yield* cache.loadThread(environmentId, threadId).pipe( @@ -72,10 +141,15 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ), ); const cachedThread = Option.map(cached, (snapshot) => snapshot.projection); + const cachedHistory = Option.match(cached, { + onNone: () => EMPTY_THREAD_HISTORY_META, + onSome: historyMetaFromCachedSnapshot, + }); const state = yield* SubscriptionRef.make({ data: cachedThread, status: statusWithoutLiveData(cachedThread), error: Option.none(), + history: cachedHistory, }); // 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. @@ -146,28 +220,57 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* ( thread: OrchestrationV2ThreadProjection, + options?: { + /** Socket/full snapshots: drop progressive meta with the new timeline. */ + readonly resetHistory?: boolean; + /** + * Explicit progressive meta installed atomically with the projection + * (bounded HTTP). Wins over resetHistory when both are supplied. + */ + readonly history?: ThreadHistoryMeta; + }, ) { const waiting = yield* Ref.get(awaitingCompletion); - yield* SubscriptionRef.set(state, { - data: Option.some(thread), - status: waiting ? "synchronizing" : "live", - error: Option.none(), + // Atomic with concurrent history meta updates: never get-then-set the whole + // state when only the projection changes. Bounded installs pass history so + // projection + cursor persist together in one enqueue. + const next = yield* SubscriptionRef.updateAndGet(state, (previous) => { + const history = + options?.history !== undefined + ? options.history + : options?.resetHistory === true + ? EMPTY_THREAD_HISTORY_META + : previous.history; + return { + ...previous, + data: Option.some(thread), + status: waiting ? ("synchronizing" as const) : ("live" as const), + error: Option.none(), + history, + }; }); // Active projections can update many times per second and retain large tool // payloads. Persist once the run settles so cache encoding stays off the - // streaming path. - if (shouldPersistThread(thread)) { + // streaming path. Progressive meta rides along when the window is incomplete. + if (shouldPersistThread(thread, next.history)) { const snapshotSequence = yield* SubscriptionRef.get(lastSequence); - yield* Queue.offer(persistence, { snapshotSequence, projection: thread }); + yield* Queue.offer(persistence, snapshotToPersist(snapshotSequence, thread, next.history)); } }); + const patchHistoryMeta = (patch: (history: ThreadHistoryMeta) => ThreadHistoryMeta) => + SubscriptionRef.update(state, (current) => ({ + ...current, + history: patch(current.history), + })); + const setDeleted = Effect.fn("EnvironmentThreadState.setDeleted")(function* () { yield* Ref.set(awaitingCompletion, false); yield* SubscriptionRef.set(state, { data: Option.none(), status: "deleted", error: Option.none(), + history: EMPTY_THREAD_HISTORY_META, }); yield* cache.removeThread(environmentId, threadId).pipe( Effect.catch((error) => @@ -197,7 +300,10 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make if (item.kind === "snapshot") { yield* SubscriptionRef.set(lastSequence, item.snapshotSequence); - yield* setThread(item.projection); + // True socket/full snapshots replace the full timeline; progressive cursor + // state from a prior bounded window must not stick around. Bounded HTTP + // installs call setThread with explicit history and never route here. + yield* setThread(item.projection, { resetHistory: true }); return; } @@ -207,23 +313,230 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } yield* SubscriptionRef.set(lastSequence, item.sequence); - const current = yield* SubscriptionRef.get(state); - if (Option.isNone(current.data)) { - if (item.event.type === "thread.deleted") { - yield* setDeleted(); - } - return; - } - if (item.event.type === "thread.deleted") { + const waiting = yield* Ref.get(awaitingCompletion); + // Apply against the latest projection/history in one update so a concurrent + // loadEarlier merge (or history-meta patch) cannot be clobbered by a stale + // get-then-set rebuild. + type EventApplyResult = + | { readonly _tag: "noop" } + | { readonly _tag: "delete" } + | { + readonly _tag: "applied"; + readonly projection: OrchestrationV2ThreadProjection; + readonly history: ThreadHistoryMeta; + }; + + const result = yield* SubscriptionRef.modify( + state, + (current): readonly [EventApplyResult, EnvironmentThreadState] => { + if (current.status === "deleted") { + return [{ _tag: "noop" }, current]; + } + if (Option.isNone(current.data)) { + return [ + item.event.type === "thread.deleted" ? { _tag: "delete" } : { _tag: "noop" }, + current, + ]; + } + if (item.event.type === "thread.deleted") { + return [{ _tag: "delete" }, current]; + } + + // Incomplete progressive windows only (hasMore or open cursor). Do not + // use expanded: it remains true after the last page as a cache marker. + // Full/web and fully-loaded timelines keep default append-on-miss. + const partial = + current.history.hasMoreHistory || current.history.historyCursor !== null + ? { + partialTimeline: true as const, + latestLocalTurnOrdinal: current.history.latestLocalTurnOrdinal, + } + : undefined; + const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event, partial); + // True no-op when the reducer deliberately returns the current projection + // reference (e.g. dropped old partial-timeline turn-item). Do not clear + // stream error/status or enqueue persistence. + if (next === null || next === current.data.value) { + return [{ _tag: "noop" }, current]; + } + + let history = current.history; + if (partial !== undefined && item.event.type === "turn-item.updated") { + const ordinal = item.event.payload.ordinal; + const watermark = history.latestLocalTurnOrdinal; + if (watermark === null || ordinal > watermark) { + history = { ...history, latestLocalTurnOrdinal: ordinal }; + } + } + + const updated: EnvironmentThreadState = { + ...current, + data: Option.some(next), + status: waiting ? "synchronizing" : "live", + error: Option.none(), + history, + }; + return [{ _tag: "applied", projection: next, history: updated.history }, updated]; + }, + ); + + if (result._tag === "delete") { yield* setDeleted(); return; } - const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event); - if (next !== null) { - yield* setThread(next); + if (result._tag === "applied" && shouldPersistThread(result.projection, result.history)) { + const snapshotSequence = yield* SubscriptionRef.get(lastSequence); + yield* Queue.offer( + persistence, + snapshotToPersist(snapshotSequence, result.projection, result.history), + ); } }); + const loadEarlier = Effect.fn("EnvironmentThreadState.loadEarlier")(function* () { + const current = yield* SubscriptionRef.get(state); + if ( + current.status === "deleted" || + Option.isNone(current.data) || + !current.history.hasMoreHistory || + current.history.historyCursor === null + ) { + return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult; + } + if (current.history.loading) { + return { _tag: "busy" } satisfies ThreadHistoryLoadEarlierResult; + } + + // Capture the cursor that initiated this request. Completions/failures must + // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight. + const requestCursor = current.history.historyCursor; + yield* patchHistoryMeta((history) => + isActiveHistoryRequestCursor(requestCursor, history) + ? { ...history, loading: true, error: null } + : history, + ); + + const runLoad = Effect.gen(function* () { + const preparedOption = yield* SubscriptionRef.get(supervisor.prepared); + if (Option.isNone(preparedOption) || Option.isNone(httpClient)) { + const message = "Environment is not connected."; + const stillCurrent = yield* SubscriptionRef.modify( + state, + (latest): readonly [boolean, EnvironmentThreadState] => { + if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) { + return [false, latest]; + } + return [ + true, + { + ...latest, + history: { ...latest.history, loading: false, error: message }, + }, + ]; + }, + ); + if (!stillCurrent) { + return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult; + } + return { + _tag: "error", + message, + } satisfies ThreadHistoryLoadEarlierResult; + } + + const pageResult = yield* fetchEnvironmentThreadHistoryPage({ + prepared: preparedOption.value, + threadId, + cursor: requestCursor, + signer: dpopSigner, + }).pipe(Effect.provideService(HttpClient.HttpClient, httpClient.value), Effect.result); + + if (Result.isFailure(pageResult)) { + const message = formatHistoryError(pageResult.failure); + // Only mark error when this request's cursor is still active. Leave + // stream/status/error alone so concurrent live updates stay intact. + const stillCurrent = yield* SubscriptionRef.modify( + state, + (latest): readonly [boolean, EnvironmentThreadState] => { + if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) { + return [false, latest]; + } + return [ + true, + { + ...latest, + history: { ...latest.history, loading: false, error: message }, + }, + ]; + }, + ); + if (!stillCurrent) { + return { _tag: "noop" } satisfies ThreadHistoryLoadEarlierResult; + } + return { _tag: "error", message } satisfies ThreadHistoryLoadEarlierResult; + } + + const page = pageResult.success; + const waiting = yield* Ref.get(awaitingCompletion); + // Single atomic merge against whatever is current after the await so a + // concurrent applyItem cannot be clobbered by a stale get/set pair. + return yield* SubscriptionRef.modify( + state, + (latest): readonly [ThreadHistoryLoadEarlierResult, EnvironmentThreadState] => { + // Stale page: socket/full snapshot or newer bounded install changed the + // progressive cursor while this request was in flight. Never mutate the + // replacement meta (including deleted/empty installs). + if (!isActiveHistoryRequestCursor(requestCursor, latest.history)) { + return [{ _tag: "noop" }, latest]; + } + if (Option.isNone(latest.data) || latest.status === "deleted") { + return [ + { _tag: "noop" }, + { + ...latest, + history: EMPTY_THREAD_HISTORY_META, + }, + ]; + } + + const merged = mergeOlderHistoryIntoProjection(latest.data.value, page.items); + const history = applyHistoryPageMeta(latest.history, page); + return [ + { _tag: "loaded" }, + { + ...latest, + data: Option.some(merged), + status: waiting + ? ("synchronizing" as const) + : latest.status === "live" + ? ("live" as const) + : latest.status, + history, + }, + ]; + }, + ); + }); + + // On Effect interruption only: clear loading when this request cursor is + // still active. Never mutate stream status/error from the interrupt path. + return yield* runLoad.pipe( + Effect.onInterrupt(() => + SubscriptionRef.update(state, (latest) => ({ + ...latest, + history: clearActiveHistoryLoading(requestCursor, latest.history), + })), + ), + ); + }); + + if (Option.isSome(historyController)) { + const registration = yield* historyController.value.register(environmentId, threadId, { + loadEarlier: () => loadEarlier(), + }); + yield* Effect.addFinalizer(() => historyController.value.unregister(registration)); + } + yield* SubscriptionRef.changes(supervisor.state).pipe( Stream.runForEach((connectionState) => { switch (connectionProjectionPhase(connectionState)) { @@ -249,6 +562,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make subscribeDynamic( ORCHESTRATION_V2_WS_METHODS.subscribeThread, Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) { + let current = yield* SubscriptionRef.get(state); + // A prior definitive miss (or delete event) already cleared this thread. + // Park the subscription attempt without opening the socket so we do not + // retry forever against a known-missing id. + if (current.status === "deleted") { + return yield* Effect.never; + } + const supportsCompletionMarker = yield* session.initialConfig.pipe( Effect.map((config) => config.threadResumeCompletionMarker === true), Effect.orElseSucceed(() => false), @@ -256,8 +577,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* Ref.set(awaitingCompletion, supportsCompletionMarker); yield* setSynchronizing; - let current = yield* SubscriptionRef.get(state); - if (Option.isNone(current.data) && current.status !== "deleted") { + if (Option.isNone(current.data)) { const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( Effect.flatMap( Option.match({ @@ -272,14 +592,41 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }), ), ); - const httpSnapshot = yield* snapshotLoader.load(prepared, threadId); - if (Option.isSome(httpSnapshot)) { - yield* applyItem({ - kind: "snapshot", - snapshotSequence: httpSnapshot.value.snapshotSequence, - projection: httpSnapshot.value.projection, - }); - current = yield* SubscriptionRef.get(state); + const httpResult: ThreadSnapshotLoadResult = yield* snapshotLoader.load( + prepared, + threadId, + ); + switch (httpResult._tag) { + case "present": { + // Atomic projection + progressive meta so a settled bounded window + // never persists as a complete full-timeline cache entry. Socket + // snapshots still go through applyItem (resetHistory). + yield* SubscriptionRef.set(lastSequence, httpResult.snapshot.snapshotSequence); + const history: ThreadHistoryMeta = + httpResult.history !== undefined + ? { + historyCursor: httpResult.history.historyCursor, + hasMoreHistory: httpResult.history.hasMoreHistory, + loading: false, + error: null, + expanded: false, + latestLocalTurnOrdinal: httpResult.history.latestLocalTurnOrdinal ?? null, + } + : EMPTY_THREAD_HISTORY_META; + yield* setThread(httpResult.snapshot.projection, { history }); + current = yield* SubscriptionRef.get(state); + break; + } + case "missing": { + // Definitive HTTP 404: clear any stale cache and do not open or + // retry a socket subscription for this attempt. + yield* setDeleted(); + return yield* Effect.never; + } + case "unavailable": { + // Transient HTTP failure: fall through to the socket path. + break; + } } } @@ -313,8 +660,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make Option.match(current.data, { onNone: () => Effect.void, onSome: (projection) => - shouldPersistThread(projection) - ? persist({ snapshotSequence, projection }) + shouldPersistThread(projection, current.history) + ? persist(snapshotToPersist(snapshotSequence, projection, current.history)) : Effect.void, }), ), @@ -357,6 +704,9 @@ export function createEnvironmentThreadStateAtoms( export * from "./archivedThreads.ts"; export * from "./checkpointDiff.ts"; +export * from "./boundedThreadSnapshotHttp.ts"; +export * from "./threadHistoryController.ts"; +export * from "./threadHistoryMerge.ts"; export * from "./threadSnapshotHttp.ts"; export * from "./composerPathSearch.ts"; export * from "./threadCommands.ts"; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 14a582aa41..ce319d25e6 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -28,7 +28,9 @@ import { AuthSessionId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts import { ExecutionEnvironmentDescriptor } from "./environment.ts"; import { OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadBoundedSnapshot, OrchestrationV2ThreadDetailSnapshot, + OrchestrationV2ThreadHistoryPage, } from "./orchestrationV2.ts"; import { Project, ProjectMutation, ProjectSnapshot } from "./project.ts"; import { @@ -60,6 +62,7 @@ export const EnvironmentRequestInvalidReason = Schema.Literals([ "invalid_scope", "scope_not_granted", "invalid_command", + "invalid_history_cursor", ]); export type EnvironmentRequestInvalidReason = typeof EnvironmentRequestInvalidReason.Type; @@ -89,6 +92,8 @@ export const EnvironmentInternalErrorReason = Schema.Literals([ "project_mutation_failed", "orchestration_snapshot_failed", "orchestration_thread_snapshot_failed", + "orchestration_thread_bounded_snapshot_failed", + "orchestration_thread_history_failed", "internal_error", ]); export type EnvironmentInternalErrorReason = typeof EnvironmentInternalErrorReason.Type; @@ -490,6 +495,17 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ threadId: ThreadId, }); +const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ + cursor: TrimmedNonEmptyString, +}); + +const EnvironmentOrchestrationThreadHistoryErrors = [ + EnvironmentRequestInvalidError, + EnvironmentScopeRequiredError, + EnvironmentResourceNotFoundError, + EnvironmentInternalError, +] as const; + export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration") .add( HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", { @@ -505,6 +521,23 @@ export class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestr success: OrchestrationV2ThreadDetailSnapshot, error: EnvironmentOrchestrationThreadSnapshotErrors, }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.get("threadBoundedSnapshot", "/api/orchestration/threads/:threadId/bounded", { + headers: OptionalBearerHeaders, + params: EnvironmentOrchestrationThreadSnapshotParams, + success: OrchestrationV2ThreadBoundedSnapshot, + error: EnvironmentOrchestrationThreadSnapshotErrors, + }).middleware(EnvironmentAuthenticatedAuth), + ) + .add( + HttpApiEndpoint.get("threadHistoryPage", "/api/orchestration/threads/:threadId/history", { + headers: OptionalBearerHeaders, + params: EnvironmentOrchestrationThreadSnapshotParams, + query: EnvironmentOrchestrationThreadHistoryQuery, + success: OrchestrationV2ThreadHistoryPage, + error: EnvironmentOrchestrationThreadHistoryErrors, + }).middleware(EnvironmentAuthenticatedAuth), ) {} export class EnvironmentProjectsHttpApi extends HttpApiGroup.make("projects") diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 90b7f90949..68dffeb4c6 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2384,9 +2384,49 @@ export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2Subscrib export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({ snapshotSequence: NonNegativeInt, projection: OrchestrationV2ThreadProjection, + /** + * Progressive history metadata. Omitted on full-projection caches and older + * clients. When present with hasMoreHistory/cursor, the projection is a + * bounded window and must not be treated as a complete timeline. + */ + historyCursor: Schema.optionalKey(Schema.NullOr(TrimmedNonEmptyString)), + hasMoreHistory: Schema.optionalKey(Schema.Boolean), + /** + * Max local turn ordinal from the authoritative full projection at snapshot + * time. Optional for backward-compatible warm cache entries. + */ + latestLocalTurnOrdinal: Schema.optionalKey(Schema.NullOr(NonNegativeInt)), }); export type OrchestrationV2ThreadDetailSnapshot = typeof OrchestrationV2ThreadDetailSnapshot.Type; +/** + * Progressive cold open: full control-plane projection arrays with only a + * recent window of timeline rows. `historyCursor` is opaque; clients must not + * parse it. Resume live events with `afterSequence = snapshotSequence`. + */ +export const OrchestrationV2ThreadBoundedSnapshot = Schema.Struct({ + snapshotSequence: NonNegativeInt, + projection: OrchestrationV2ThreadProjection, + historyCursor: Schema.NullOr(TrimmedNonEmptyString), + hasMoreHistory: Schema.Boolean, + /** + * Max local turn ordinal over the authoritative full projection turnItems. + * Clients use this as a partial-timeline watermark when the bounded window + * has no local rows (inherited-only). + */ + latestLocalTurnOrdinal: Schema.NullOr(NonNegativeInt), +}); +export type OrchestrationV2ThreadBoundedSnapshot = typeof OrchestrationV2ThreadBoundedSnapshot.Type; + +/** Older timeline page for progressive history. Rows are chronological. */ +export const OrchestrationV2ThreadHistoryPage = Schema.Struct({ + snapshotSequence: NonNegativeInt, + items: Schema.Array(OrchestrationV2ProjectedTurnItem), + nextCursor: Schema.NullOr(TrimmedNonEmptyString), + hasMoreHistory: Schema.Boolean, +}); +export type OrchestrationV2ThreadHistoryPage = typeof OrchestrationV2ThreadHistoryPage.Type; + export const OrchestrationV2ThreadStreamItem = Schema.Union([ Schema.Struct({ kind: Schema.Literal("synchronized"),