TypeScript
perf: make streaming projection and activity appends incremental (#9152)
Theo Brownec2283ce14628
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.tsindex 32551643b0d..080ea263e44 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts@@ -2422,44 +2422,35 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {json_object('requestId', 'user-input-active'),NULL,'2026-02-26T12:35:07.000Z'- ),- (- 'activity-user-input-active-failed',- 'thread-stale-user-input',- NULL,- 'error',- 'provider.user-input.respond.failed',- 'Provider user input response failed',- json_object(- 'requestId',- 'user-input-active',- 'detail',- 'Provider is temporarily unavailable'- ),- NULL,- '2026-02-26T12:35:08.000Z')`;+ // A user-input lifecycle activity is one of the events that still+ // refreshes the shell summary, so it forces the read under test.yield* appendAndProject({- type: "thread.message-sent",+ type: "thread.activity-appended",eventId: EventId.make("evt-stale-user-input-3"),aggregateKind: "thread",aggregateId: ThreadId.make("thread-stale-user-input"),- occurredAt: "2026-02-26T12:35:09.000Z",+ occurredAt: "2026-02-26T12:35:08.000Z",commandId: CommandId.make("cmd-stale-user-input-3"),causationEventId: null,correlationId: CorrelationId.make("cmd-stale-user-input-3"),metadata: {},payload: {threadId: ThreadId.make("thread-stale-user-input"),- messageId: MessageId.make("message-stale-user-input"),- role: "user",- text: "Continue",- turnId: null,- streaming: false,- createdAt: "2026-02-26T12:35:09.000Z",- updatedAt: "2026-02-26T12:35:09.000Z",+ activity: {+ id: EventId.make("activity-user-input-active-failed"),+ tone: "error",+ kind: "provider.user-input.respond.failed",+ summary: "Provider user input response failed",+ payload: {+ requestId: "user-input-active",+ detail: "Provider is temporarily unavailable",+ },+ turnId: null,+ createdAt: "2026-02-26T12:35:08.000Z",+ },},});@@ -2474,6 +2465,217 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {}),);+ it.effect("maintains shell summary fields across message and activity streams", () =>+ Effect.gen(function* () {+ const projectionPipeline = yield* OrchestrationProjectionPipeline;+ const eventStore = yield* OrchestrationEventStore;+ const sql = yield* SqlClient.SqlClient;+ const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>+ eventStore+ .append(event)+ .pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));++ yield* appendAndProject({+ type: "project.created",+ eventId: EventId.make("evt-shell-summary-1"),+ aggregateKind: "project",+ aggregateId: ProjectId.make("project-shell-summary"),+ occurredAt: "2026-03-01T08:00:00.000Z",+ commandId: CommandId.make("cmd-shell-summary-1"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-1"),+ metadata: {},+ payload: {+ projectId: ProjectId.make("project-shell-summary"),+ title: "Project Shell Summary",+ workspaceRoot: "/tmp/project-shell-summary",+ defaultModelSelection: null,+ scripts: [],+ createdAt: "2026-03-01T08:00:00.000Z",+ updatedAt: "2026-03-01T08:00:00.000Z",+ },+ });++ yield* appendAndProject({+ type: "thread.created",+ eventId: EventId.make("evt-shell-summary-2"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-shell-summary"),+ occurredAt: "2026-03-01T08:00:01.000Z",+ commandId: CommandId.make("cmd-shell-summary-2"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-2"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-shell-summary"),+ projectId: ProjectId.make("project-shell-summary"),+ title: "Thread Shell Summary",+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5-codex",+ },+ runtimeMode: "approval-required",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ createdAt: "2026-03-01T08:00:01.000Z",+ updatedAt: "2026-03-01T08:00:01.000Z",+ },+ });++ const readSummary = sql<{+ readonly latestUserMessageAt: string | null;+ readonly pendingUserInputCount: number;+ readonly updatedAt: string;+ }>`+ SELECT+ latest_user_message_at AS "latestUserMessageAt",+ pending_user_input_count AS "pendingUserInputCount",+ updated_at AS "updatedAt"+ FROM projection_threads+ WHERE thread_id = 'thread-shell-summary'+ `;++ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.make("evt-shell-summary-3"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-shell-summary"),+ occurredAt: "2026-03-01T08:00:02.000Z",+ commandId: CommandId.make("cmd-shell-summary-3"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-3"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-shell-summary"),+ messageId: MessageId.make("message-shell-summary-user"),+ role: "user",+ text: "please do the thing",+ turnId: TurnId.make("turn-shell-summary-1"),+ streaming: false,+ createdAt: "2026-03-01T08:00:02.000Z",+ updatedAt: "2026-03-01T08:00:02.000Z",+ },+ });++ assert.deepEqual(yield* readSummary, [+ {+ latestUserMessageAt: "2026-03-01T08:00:02.000Z",+ pendingUserInputCount: 0,+ updatedAt: "2026-03-01T08:00:02.000Z",+ },+ ]);++ // Streaming assistant deltas bump updatedAt but must not disturb+ // latestUserMessageAt or the pending counters.+ yield* appendAndProject({+ type: "thread.message-sent",+ eventId: EventId.make("evt-shell-summary-4"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-shell-summary"),+ occurredAt: "2026-03-01T08:00:03.000Z",+ commandId: CommandId.make("cmd-shell-summary-4"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-4"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-shell-summary"),+ messageId: MessageId.make("message-shell-summary-assistant"),+ role: "assistant",+ text: "working on it",+ turnId: TurnId.make("turn-shell-summary-1"),+ streaming: true,+ createdAt: "2026-03-01T08:00:03.000Z",+ updatedAt: "2026-03-01T08:00:03.000Z",+ },+ });++ assert.deepEqual(yield* readSummary, [+ {+ latestUserMessageAt: "2026-03-01T08:00:02.000Z",+ pendingUserInputCount: 0,+ updatedAt: "2026-03-01T08:00:03.000Z",+ },+ ]);++ // Ordinary tool activities bump updatedAt without touching the+ // user-input counter; user-input lifecycle activities update it.+ yield* appendAndProject({+ type: "thread.activity-appended",+ eventId: EventId.make("evt-shell-summary-5"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-shell-summary"),+ occurredAt: "2026-03-01T08:00:04.000Z",+ commandId: CommandId.make("cmd-shell-summary-5"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-5"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-shell-summary"),+ activity: {+ id: EventId.make("activity-shell-summary-command"),+ tone: "tool",+ kind: "command",+ summary: "Ran a command",+ payload: {},+ turnId: TurnId.make("turn-shell-summary-1"),+ createdAt: "2026-03-01T08:00:04.000Z",+ },+ },+ });++ assert.deepEqual(yield* readSummary, [+ {+ latestUserMessageAt: "2026-03-01T08:00:02.000Z",+ pendingUserInputCount: 0,+ updatedAt: "2026-03-01T08:00:04.000Z",+ },+ ]);++ yield* appendAndProject({+ type: "thread.activity-appended",+ eventId: EventId.make("evt-shell-summary-6"),+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-shell-summary"),+ occurredAt: "2026-03-01T08:00:05.000Z",+ commandId: CommandId.make("cmd-shell-summary-6"),+ causationEventId: null,+ correlationId: CorrelationId.make("cmd-shell-summary-6"),+ metadata: {},+ payload: {+ threadId: ThreadId.make("thread-shell-summary"),+ activity: {+ id: EventId.make("activity-shell-summary-user-input"),+ tone: "info",+ kind: "user-input.requested",+ summary: "User input requested",+ payload: {+ requestId: "user-input-request-shell-summary-1",+ questions: [+ {+ id: "confirm",+ header: "Confirm",+ question: "Proceed?",+ options: [{ label: "yes", description: "Proceed" }],+ },+ ],+ },+ turnId: TurnId.make("turn-shell-summary-1"),+ createdAt: "2026-03-01T08:00:05.000Z",+ },+ },+ });++ assert.deepEqual(yield* readSummary, [+ {+ latestUserMessageAt: "2026-03-01T08:00:02.000Z",+ pendingUserInputCount: 1,+ updatedAt: "2026-03-01T08:00:05.000Z",+ },+ ]);+ }),+ );+it.effect("ignores non-stale provider approval response failures", () =>Effect.gen(function* () {const projectionPipeline = yield* OrchestrationProjectionPipeline;diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.tsindex 22daeee6936..3d1dfd9c7e3 100644--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts@@ -130,12 +130,8 @@ function isStalePendingApprovalFailureDetail(detail: string | null): boolean {);}-// A refresh reads each persisted summary source, so skip events that cannot change the result.+// A refresh reads each persisted summary source, so skip activities that cannot change the result.function shouldRefreshThreadShellSummary(event: OrchestrationEvent): boolean {- if (event.type === "thread.message-sent") {- return event.payload.role === "user";- }-if (event.type !== "thread.activity-appended") {return true;}@@ -897,7 +893,29 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectireturn;}- case "thread.message-sent":+ // A message cannot change any summary field except latestUserMessageAt,+ // which is a monotonic maximum that folds in directly. The full refresh+ // would re-read every message body in the thread per user message.+ case "thread.message-sent": {+ const existingRow = yield* projectionThreadRepository.getById({+ threadId: event.payload.threadId,+ });+ if (Option.isNone(existingRow)) {+ return;+ }+ const previousLatest = existingRow.value.latestUserMessageAt;+ yield* projectionThreadRepository.upsert({+ ...existingRow.value,+ updatedAt: event.occurredAt,+ latestUserMessageAt:+ event.payload.role === "user" &&+ (previousLatest === null || event.payload.createdAt > previousLatest)+ ? event.payload.createdAt+ : previousLatest,+ });+ return;+ }+case "thread.proposed-plan-upserted":case "thread.activity-appended":case "thread.approval-response-requested":diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.tsindex 2042b2168c8..80a0a348fc3 100644--- a/packages/client-runtime/src/state/threadReducer.test.ts+++ b/packages/client-runtime/src/state/threadReducer.test.ts@@ -728,6 +728,184 @@ describe("applyThreadDetailEvent", () => {}});+ it("re-sorts when an activity arrives out of order", () => {+ const makeActivity = (id: string, sequence: number) => ({+ id: EventId.make(id),+ tone: "tool" as const,+ kind: "command",+ summary: `Ran command ${sequence}`,+ payload: {},+ turnId: TurnId.make("turn-1"),+ sequence,+ createdAt: "2026-04-01T11:00:00.000Z",+ });+ const result = applyThreadDetailEvent(+ {+ ...baseThread,+ activities: [makeActivity("activity-a", 1), makeActivity("activity-c", 3)],+ },+ {+ ...baseEventFields,+ sequence: 131,+ occurredAt: "2026-04-01T11:01:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.activity-appended",+ payload: {+ threadId: ThreadId.make("thread-1"),+ activity: makeActivity("activity-b", 2),+ },+ },+ );++ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.activities.map((activity) => activity.id)).toEqual([+ "activity-a",+ "activity-b",+ "activity-c",+ ]);+ }+ });++ it("repairs snapshot ordering before fast-path appends engage", () => {+ const makeActivity = (id: string, sequence: number | null) => ({+ id: EventId.make(id),+ tone: "tool" as const,+ kind: "command",+ summary: `Ran ${id}`,+ payload: {},+ turnId: TurnId.make("turn-1"),+ ...(sequence === null ? {} : { sequence }),+ createdAt: "2026-04-01T11:00:00.000Z",+ });+ // Snapshot loads deliver null-sequence rows first (DB order), which+ // activityOrder sorts last; an in-order live append must not freeze+ // that prefix.+ const result = applyThreadDetailEvent(+ {+ ...baseThread,+ activities: [makeActivity("activity-null", null), makeActivity("activity-a", 1)],+ },+ {+ ...baseEventFields,+ sequence: 135,+ occurredAt: "2026-04-01T11:01:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.activity-appended",+ payload: {+ threadId: ThreadId.make("thread-1"),+ activity: makeActivity("activity-b", 2),+ },+ },+ );++ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.activities.map((activity) => activity.id)).toEqual([+ "activity-a",+ "activity-b",+ "activity-null",+ ]);+ }+ });++ it("dedupes a re-delivery arriving right after an in-order append", () => {+ const makeActivity = (id: string, sequence: number, summary: string) => ({+ id: EventId.make(id),+ tone: "tool" as const,+ kind: "command",+ summary,+ payload: {},+ turnId: TurnId.make("turn-1"),+ sequence,+ createdAt: "2026-04-01T11:00:00.000Z",+ });+ const makeEvent = (sequence: number, activity: ReturnType<typeof makeActivity>) =>+ ({+ ...baseEventFields,+ sequence,+ occurredAt: "2026-04-01T11:01:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.activity-appended",+ payload: { threadId: ThreadId.make("thread-1"), activity },+ }) as const;+ const first = applyThreadDetailEvent(+ { ...baseThread, activities: [makeActivity("activity-a", 1, "first")] },+ makeEvent(133, makeActivity("activity-b", 2, "second")),+ );+ expect(first.kind).toBe("updated");+ if (first.kind !== "updated") {+ return;+ }+ const second = applyThreadDetailEvent(+ first.thread,+ makeEvent(134, makeActivity("activity-c", 3, "third")),+ );+ expect(second.kind).toBe("updated");+ if (second.kind !== "updated") {+ return;+ }+ const third = applyThreadDetailEvent(+ second.thread,+ makeEvent(135, makeActivity("activity-c", 4, "third (redelivered)")),+ );+ expect(third.kind).toBe("updated");+ if (third.kind === "updated") {+ expect(third.thread.activities.map((activity) => activity.id)).toEqual([+ "activity-a",+ "activity-b",+ "activity-c",+ ]);+ expect(third.thread.activities[2]?.summary).toBe("third (redelivered)");+ }+ });++ it("replaces a re-delivered activity instead of duplicating it", () => {+ const makeActivity = (id: string, sequence: number, summary: string) => ({+ id: EventId.make(id),+ tone: "tool" as const,+ kind: "command",+ summary,+ payload: {},+ turnId: TurnId.make("turn-1"),+ sequence,+ createdAt: "2026-04-01T11:00:00.000Z",+ });+ const result = applyThreadDetailEvent(+ {+ ...baseThread,+ activities: [+ makeActivity("activity-a", 1, "first"),+ makeActivity("activity-b", 2, "second"),+ ],+ },+ {+ ...baseEventFields,+ sequence: 132,+ occurredAt: "2026-04-01T11:01:00.000Z",+ aggregateKind: "thread",+ aggregateId: ThreadId.make("thread-1"),+ type: "thread.activity-appended",+ payload: {+ threadId: ThreadId.make("thread-1"),+ activity: makeActivity("activity-b", 2, "second (redelivered)"),+ },+ },+ );++ expect(result.kind).toBe("updated");+ if (result.kind === "updated") {+ expect(result.thread.activities.map((activity) => activity.id)).toEqual([+ "activity-a",+ "activity-b",+ ]);+ expect(result.thread.activities[1]?.summary).toBe("second (redelivered)");+ }+ });+it("replaces earlier resolvable context-window updates for the same turn", () => {const contextWindowActivity = (id: string, sequence: number, usedTokens: unknown) => ({id: EventId.make(id),diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex 10d5898c8fe..2a0d9de150a 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -35,6 +35,15 @@ const activityOrder = O.combineAll<OrchestrationThreadActivity>([O.mapInput(O.String, (a) => a.id),]);+// Per-array id index so the streaming append path can reject a re-delivered+// id without rescanning the history. Only arrays this reducer produced are+// indexed: presence also proves the array is activityOrder-sorted, which+// snapshot-loaded arrays (DB order, null sequences first) are not.+const activityIdIndex = new WeakMap<+ ReadonlyArray<OrchestrationThreadActivity>,+ Set<OrchestrationThreadActivity["id"]>+>();+/*** Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the* server's snapshot-side `dropStaleContextWindowActivities`): rows without a@@ -582,6 +591,31 @@ export function applyThreadDetailEvent(// thread.reverted that discards turns can still resolve a value from// the turns that survive.const supersedesContextWindow = isResolvableContextWindowActivity(activity);+ // Live streams append in order: an unseen id sorting at/after the tail+ // of a known-sorted array appends without re-filtering and re-sorting+ // the whole history on every event. The id set moves forward to the new+ // array; a superseded array falls back to the sorting path.+ const ids = activityIdIndex.get(thread.activities);+ const lastActivity = thread.activities.at(-1);+ if (+ !supersedesContextWindow &&+ ids !== undefined &&+ (lastActivity === undefined || activityOrder(lastActivity, activity) <= 0) &&+ !ids.has(activity.id)+ ) {+ const activities = Arr.append(thread.activities, activity);+ activityIdIndex.delete(thread.activities);+ ids.add(activity.id);+ activityIdIndex.set(activities, ids);+ return {+ kind: "updated",+ thread: {+ ...thread,+ activities,+ updatedAt: event.occurredAt,+ },+ };+ }const activities = pipe(thread.activities,Arr.filter(@@ -596,6 +630,7 @@ export function applyThreadDetailEvent(Arr.append(activity),Arr.sort(activityOrder),);+ activityIdIndex.set(activities, new Set(activities.map((entry) => entry.id)));return {kind: "updated",