diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 53ec588af5867..3f8423b08f609 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -113,6 +113,8 @@ const CLIENT_HISTORY_OPT_INS = { compactIds: "1", deferWork: "1" } satisfies Req const CLIENT_SHELL_OPT_INS = { omitIdleSubagents: "1", omitOlderSettled: "1", + compactShell: "1", + compactIds: "1", } satisfies Required>; const CLIENT_THREAD_SUBSCRIPTION = { requestCompletionMarker: true, @@ -127,6 +129,9 @@ const CLIENT_SHELL_SUBSCRIPTION = { requestCompletionMarker: true, omitIdleSubagents: true, omitOlderSettled: true, + compactShell: true, + compactIds: true, + acceptShellDeltas: true, } satisfies Required>; const query = (optIns: Readonly>) => new URLSearchParams(optIns).toString(); const CLIENT_BOUNDED_QUERY = query(CLIENT_BOUNDED_OPT_INS); @@ -365,7 +370,7 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => assert.equal(decodedThread.projection.turnItems.length, TRANSFER_HISTORY_TURN_COUNT * 6); assert.notInclude(Buffer.from(threadSnapshot.decodedBody).toString(), "digest="); const shellSnapshot = yield* measureHttpGet({ - url: `${base}/api/orchestration/shell`, + url: `${base}/api/orchestration/shell?${CLIENT_SHELL_QUERY}`, headers: { [ORCHESTRATION_PROTOCOL_HEADER]: String(ORCHESTRATION_PROTOCOL_VERSION) }, }); assert.equal(shellSnapshot.status, 200); @@ -400,8 +405,26 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => // shells are skipped, so a turn split across batches may never yield an item at // the last sequence. Wait for the final shell instead. const finalShell = yield* projection.getThreadShell(THREAD_ID); - const shellTerminal = (item: StreamItem) => - item.kind === "thread.updated" && NodeUtil.isDeepStrictEqual(item.thread, finalShell); + if (finalShell === null) return yield* Effect.die("Expected final thread shell"); + const initialShell = decodedShell.threads[0]; + if (initialShell === undefined) return yield* Effect.die("Expected initial thread shell"); + const makeShellTerminal = () => { + let current = initialShell; + return (item: StreamItem) => { + if (item.kind === "thread.updated" && item.thread.id === THREAD_ID) { + current = item.thread; + } else if (item.kind === "thread.patched" && item.threadId === THREAD_ID) { + const patched: Record = { ...current }; + for (const [key, value] of Object.entries(item.patch)) { + if (value !== undefined) patched[key] = value; + } + current = patched as typeof current; + } else { + return false; + } + return NodeUtil.isDeepStrictEqual(current, finalShell); + }; + }; const liveTurn = yield* collectUntil(tq, threadTerminal); yield* collectUntil(ttq, threadTerminal); // A direct check, so live dedupe stays guarded however small the turn gets. @@ -414,7 +437,7 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => ); assert.equal(liveAnswer.length, 1); assert.equal(liveAnswer[0]!.textOmitted, true); - for (const queue of [sq, ssq]) yield* collectUntil(queue, shellTerminal); + for (const queue of [sq, ssq]) yield* collectUntil(queue, makeShellTerminal()); const measuredTurnWebSocket = difference(thread.recorder.totals(), threadBefore); const measuredTurnShellWebSocket = difference(shell.recorder.totals(), shellBefore); const measuredTurnSecondClientWebSocket = difference( diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index e06b7cba1e0f4..5bff709d0ba4c 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -5,7 +5,12 @@ import type { OrchestrationV2ShellStreamItem, OrchestrationV2ThreadShell, } from "@t3tools/contracts"; -import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; +import { + OrchestrationV2ShellStreamItem as ShellStreamItemSchema, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; import type * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -13,20 +18,24 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { activeShellRowsForSubscriber, + applyShellStreamWireOptions, bufferShellLiveStream, coalesceShellApplicationEvents, composeShellStreamWithEnrichment, dedupeShellEnrichment, + diffThreadShell, omitIdleSubagentShells, omitOlderSettledShells, shellStreamItemFromEnrichmentRefresh, shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, + shellStreamItemsFromResumeSnapshot, shouldPublishShellApplicationEvent, skipUnchangedThreadShells, toShellApplicationEvent, @@ -377,6 +386,54 @@ describe("shellStreamItemsFromInitialSnapshot", () => { }); expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length); }); + + it("omits duplicate project frames when resolved projects already carry repositoryIdentity", () => { + const identity = { + canonicalKey: "github.com/test/repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/test/repo.git", + }, + }; + const snapshot = { + ...emptyShellSnapshot, + projects: [ + { id: "project-a", workspaceRoot: "/workspace/a", repositoryIdentity: identity }, + { id: "project-b", workspaceRoot: "/workspace/b", repositoryIdentity: null }, + ], + threads: [shellFixture({})], + } as unknown as OrchestrationV2ShellSnapshot; + + expect( + shellStreamItemsFromInitialSnapshot({ + snapshot, + resolvedRepositoryIdentityRoots: ["/workspace/a"], + }), + ).toEqual([{ kind: "snapshot", snapshot }]); + + const mixed = shellStreamItemsFromInitialSnapshot({ + snapshot, + resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/b"], + }); + expect(mixed).toHaveLength(2); + expect(mixed[1]).toMatchObject({ + kind: "snapshot", + snapshot: { + projects: [{ id: "project-b", workspaceRoot: "/workspace/b", repositoryIdentity: null }], + threads: [], + archivedThreads: [], + }, + resolvedRepositoryIdentityRoots: ["/workspace/b"], + }); + + const resumed = shellStreamItemsFromResumeSnapshot({ + snapshot, + resolvedRepositoryIdentityRoots: ["/workspace/a"], + }); + expect(resumed).toHaveLength(1); + expect(resumed[0]?.resolvedRepositoryIdentityRoots).toEqual(["/workspace/a"]); + }); }); describe("composeShellStreamWithEnrichment", () => { @@ -743,3 +800,335 @@ describe("skipUnchangedThreadShells", () => { }), ); }); + +describe("diffThreadShell and applyShellStreamWireOptions", () => { + const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(ShellStreamItemSchema)); + const at = (ms: number) => DateTime.makeUnsafe(Date.parse("2026-10-01T00:00:00.000Z") + ms); + const fullShell = ( + id: string, + overrides: Partial = {}, + ): OrchestrationV2ThreadShell => ({ + createdBy: "user", + creationSource: "web", + id: ThreadId.make(id), + projectId: ProjectId.make("project-a"), + title: "Thread", + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + pullRequests: [], + lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + activeProviderThreadId: null, + latestRunId: null, + latestRunRequestedAt: null, + latestRunStartedAt: null, + latestRunCompletedAt: null, + latestRunStopRequested: false, + latestRunBackgroundWake: false, + activeRunId: null, + activityRunStartedAt: null, + activityRunStatus: null, + blockedOnThreadWait: false, + status: "running", + lastError: null, + lastErrorClass: null, + lastErrorCode: null, + usageLimitResetAt: null, + pendingRuntimeRequest: null, + pendingGuestMessageCount: 0, + latestVisibleMessage: null, + latestUserMessageAt: null, + latestUserAuthoredMessageAt: null, + hasActionableProposedPlan: false, + pendingBackgroundTasks: [], + providerInstanceHistory: [], + goal: null, + itemCount: 1, + visibleItemCount: 1, + createdAt: at(0), + updatedAt: at(0), + archivedAt: null, + settledOverride: null, + settledAt: null, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + limitRecovery: null, + pinnedAt: null, + autoSettleDisabledAt: null, + pinOrderKey: null, + lastVisitedAt: null, + opens: null, + titleRegeneration: null, + lastTitleRegeneration: null, + deletedAt: null, + ...overrides, + }); + + it("computes sparse diffs and returns null when keys become undefined or exceed the patch cap", () => { + const base = fullShell("a"); + expect(diffThreadShell(base, fullShell("a"))).toEqual({}); + expect( + diffThreadShell( + base, + fullShell("a", { itemCount: 2, visibleItemCount: 2, updatedAt: at(100) }), + ), + ).toEqual({ + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(100), + }); + + const withOrderKey = fullShell("a", { activeOrderKey: "a0" }); + expect(diffThreadShell(withOrderKey, base)).toBeNull(); + + const manyChanges = fullShell("a", { + title: "New", + runtimeMode: "approval-required", + interactionMode: "plan", + branch: "feat/x", + worktreePath: "/tmp/wt", + status: "completed", + latestRunStopRequested: true, + latestRunBackgroundWake: true, + blockedOnThreadWait: true, + hasActionableProposedPlan: true, + itemCount: 9, + visibleItemCount: 9, + updatedAt: at(500), + }); + expect(diffThreadShell(base, manyChanges)).toBeNull(); + }); + + type Step = { readonly advanceMs: number } | OrchestrationV2ShellStreamItem; + + const runWithOptions = ( + steps: ReadonlyArray, + options: { + readonly compactShell?: boolean; + readonly compactIds?: boolean; + readonly acceptShellDeltas?: boolean; + }, + ) => + applyShellStreamWireOptions( + Stream.fromIterable(steps).pipe( + Stream.mapEffect((step) => + "advanceMs" in step + ? TestClock.adjust(Duration.millis(step.advanceMs)).pipe(Effect.as(null)) + : Effect.succeed(step), + ), + Stream.filter((item): item is OrchestrationV2ShellStreamItem => item !== null), + ), + options, + ).pipe( + Stream.runCollect, + Effect.map((items) => Array.from(items)), + ); + + it.effect( + "emits thread.patched (>80% smaller), updatedAt-only patches, and cursor heartbeats after an authoritative snapshot", + () => + Effect.gen(function* () { + const a0 = fullShell("a"); + const a1 = fullShell("a", { itemCount: 2, visibleItemCount: 2, updatedAt: at(1_000) }); + const aUnchanged = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(2_000), + }); + const aFloorUpdatedAt = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(7_000), + }); + const aNoopAck = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(7_000), + }); + const aUpdatedAtAck = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(7_500), + }); + const aFloorIdentical = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + updatedAt: at(7_500), + }); + const aVisited = fullShell("a", { + itemCount: 2, + visibleItemCount: 2, + lastVisitedAt: at(8_000), + updatedAt: at(8_000), + }); + + const emitted = yield* runWithOptions( + [ + { + kind: "snapshot", + snapshot: { ...emptyShellSnapshot, snapshotSequence: 1, threads: [a0] }, + }, + { kind: "thread.updated", sequence: 2, location: "active", thread: a1 }, + { advanceMs: 1_000 }, + { kind: "thread.updated", sequence: 3, location: "active", thread: aUnchanged }, + { advanceMs: 5_000 }, + { kind: "thread.updated", sequence: 4, location: "active", thread: aFloorUpdatedAt }, + { + kind: "thread.updated", + sequence: 5, + location: "active", + thread: aNoopAck, + acknowledgesCommand: true, + } as OrchestrationV2ShellStreamItem, + { + kind: "thread.updated", + sequence: 6, + location: "active", + thread: aUpdatedAtAck, + acknowledgesCommand: true, + } as OrchestrationV2ShellStreamItem, + { advanceMs: 5_000 }, + { kind: "thread.updated", sequence: 7, location: "active", thread: aFloorIdentical }, + { kind: "thread.updated", sequence: 8, location: "active", thread: aVisited }, + ], + { compactShell: true, compactIds: true, acceptShellDeltas: true }, + ); + + expect(emitted).toEqual([ + { + kind: "snapshot", + snapshot: { ...emptyShellSnapshot, snapshotSequence: 1, threads: [a0] }, + compactShell: true, + idTable: true, + }, + { + kind: "thread.patched", + sequence: 2, + location: "active", + threadId: a0.id, + patch: { itemCount: 2, visibleItemCount: 2, updatedAt: at(1_000) }, + }, + { + kind: "thread.patched", + sequence: 4, + location: "active", + threadId: a0.id, + patch: { updatedAt: at(7_000) }, + }, + { kind: "cursor", sequence: 5 }, + { + kind: "thread.patched", + sequence: 6, + location: "active", + threadId: a0.id, + patch: { updatedAt: at(7_500) }, + }, + { kind: "cursor", sequence: 7 }, + { + kind: "thread.patched", + sequence: 8, + location: "active", + threadId: a0.id, + patch: { lastVisitedAt: at(8_000), updatedAt: at(8_000) }, + }, + ]); + + const fullLegacyBytes = JSON.stringify( + encodeStreamItem({ kind: "thread.updated", sequence: 2, location: "active", thread: a1 }), + ).length; + const patchBytes = JSON.stringify(encodeStreamItem(emitted[1]!)).length; + const updatedAtPatchBytes = JSON.stringify(encodeStreamItem(emitted[2]!)).length; + const cursorBytes = JSON.stringify(encodeStreamItem(emitted[3]!)).length; + expect(patchBytes).toBeLessThan(fullLegacyBytes * 0.2); + expect(updatedAtPatchBytes).toBeLessThan(fullLegacyBytes * 0.15); + expect(cursorBytes).toBeLessThan(50); + }), + ); + + it.effect("preserves project.updated updatedAt-only changes under compactShell", () => + Effect.gen(function* () { + const decodeStreamItem = Schema.decodeUnknownEffect( + Schema.toCodecJson(ShellStreamItemSchema), + ); + const project = { + id: ProjectId.make("project-a"), + title: "Project A", + workspaceRoot: "/workspace/a", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-01T00:05:00.000Z", + }; + const emitted = yield* runWithOptions([{ kind: "project.updated", sequence: 2, project }], { + compactShell: true, + acceptShellDeltas: true, + }); + const wire = JSON.parse(JSON.stringify(encodeStreamItem(emitted[0]!))) as Record< + string, + unknown + >; + expect(wire.compactShell).toBe(true); + expect(yield* decodeStreamItem(wire)).toEqual({ + kind: "project.updated", + sequence: 2, + project, + }); + }), + ); + + it.effect( + "falls back to compact thread.updated when untracked, removed, or archived, and preserves legacy streams", + () => + Effect.gen(function* () { + const a0 = fullShell("a"); + const a1 = fullShell("a", { title: "Updated" }); + const a2 = fullShell("a", { title: "Recreated" }); + const archived = fullShell("a", { title: "Recreated", archivedAt: at(1_000) }); + + const deltaItems = yield* runWithOptions( + [ + { kind: "thread.updated", sequence: 1, location: "active", thread: a0 }, + { kind: "thread.updated", sequence: 2, location: "active", thread: a1 }, + { kind: "thread.removed", sequence: 3, location: "active", threadId: a0.id }, + { kind: "thread.updated", sequence: 4, location: "active", thread: a2 }, + { kind: "thread.updated", sequence: 5, location: "archive", thread: archived }, + { kind: "thread.updated", sequence: 6, location: "active", thread: a2 }, + ], + { compactShell: true, acceptShellDeltas: true }, + ); + + expect(deltaItems.map((item) => item.kind)).toEqual([ + "thread.updated", + "thread.patched", + "thread.removed", + "thread.updated", + "thread.updated", + "thread.updated", + ]); + expect(deltaItems[0]).toMatchObject({ compactShell: true }); + expect(deltaItems[1]).toEqual({ + kind: "thread.patched", + sequence: 2, + location: "active", + threadId: a0.id, + patch: { title: "Updated" }, + }); + + const legacyInput: ReadonlyArray = [ + { + kind: "snapshot", + snapshot: { ...emptyShellSnapshot, snapshotSequence: 1, threads: [a0] }, + }, + { kind: "thread.updated", sequence: 2, location: "active", thread: a1 }, + ]; + const legacyItems = yield* runWithOptions(legacyInput, {}); + expect(legacyItems).toEqual(legacyInput); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 2cdf7ce48d02c..bda9c32f5b469 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -5,6 +5,7 @@ import type { OrchestrationV2OlderSettledThreads, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, + OrchestrationV2ThreadShellPatch, OrchestrationV2ThreadShellSnapshot, OrchestrationV2ShellStreamItem, OrchestrationV2StoredEvent, @@ -150,12 +151,16 @@ export const bufferShellLiveStream = ( source, (item) => { switch (item.kind) { + case "cursor": + return "cursor"; case "project.updated": return `project:${item.project.id}`; case "project.removed": return `project:${item.projectId}`; case "thread.updated": return `thread:${item.location}:${item.thread.id}`; + case "thread.patched": + return `thread:${item.location}:${item.threadId}`; case "thread.removed": return `thread:${item.location}:${item.threadId}`; } @@ -739,6 +744,23 @@ export function shellStreamItemFromEnrichmentRefresh(input: { }; } +function enrichmentSnapshotItem( + snapshot: OrchestrationV2ShellSnapshot, + roots: ReadonlyArray, +): Extract { + const uniqueRoots = [...new Set(roots)]; + return { + kind: "snapshot", + snapshot: { + ...snapshot, + projects: snapshot.projects.filter((project) => uniqueRoots.includes(project.workspaceRoot)), + threads: [], + archivedThreads: [], + }, + resolvedRepositoryIdentityRoots: uniqueRoots, + }; +} + export function shellStreamItemsFromInitialSnapshot(input: { readonly snapshot: OrchestrationV2ShellSnapshot; readonly resolvedRepositoryIdentityRoots: ReadonlyArray; @@ -750,35 +772,220 @@ export function shellStreamItemsFromInitialSnapshot(input: { if (input.resolvedRepositoryIdentityRoots.length === 0) { return [authoritative]; } - return [ - authoritative, - { - kind: "snapshot" as const, - snapshot: { - ...input.snapshot, - projects: input.snapshot.projects.filter((project) => - input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot), - ), - threads: [], - archivedThreads: [], - }, - resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)], - }, - ]; + // Authoritative snapshots already apply non-null repository identities; a marked follow-up + // is only needed so clients clear a stale cached identity on roots resolved to null. + const hasResolvedIdentity = (root: string) => { + let matched = false; + for (const project of input.snapshot.projects) { + if (project.workspaceRoot !== root) continue; + matched = true; + if (project.repositoryIdentity == null) return false; + } + return matched; + }; + const rootsToConfirmNull = [...new Set(input.resolvedRepositoryIdentityRoots)].filter( + (root) => !hasResolvedIdentity(root), + ); + if (rootsToConfirmNull.length === 0) { + return [authoritative]; + } + return [authoritative, enrichmentSnapshotItem(input.snapshot, rootsToConfirmNull)]; } export function shellStreamItemsFromResumeSnapshot(input: { readonly snapshot: OrchestrationV2ShellSnapshot; readonly resolvedRepositoryIdentityRoots: ReadonlyArray; }): ReadonlyArray> { - return shellStreamItemsFromInitialSnapshot(input).filter( - (item) => item.resolvedRepositoryIdentityRoots !== undefined, - ); + if (input.resolvedRepositoryIdentityRoots.length === 0) { + return []; + } + return [enrichmentSnapshotItem(input.snapshot, input.resolvedRepositoryIdentityRoots)]; } const sameThreadShell = Schema.toEquivalence(ThreadShellSchema); const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000; +const MAX_SHELL_PATCH_FIELDS = 12; +const MAX_TRACKED_SHELL_THREADS = 2_048; + +function shellValuesEqual(left: unknown, right: unknown): boolean { + if (Object.is(left, right)) return true; + if (left === null || right === null || typeof left !== "object" || typeof right !== "object") { + return false; + } + if (DateTime.isDateTime(left) && DateTime.isDateTime(right)) { + return DateTime.toEpochMillis(left) === DateTime.toEpochMillis(right); + } + if (Array.isArray(left) || Array.isArray(right)) { + if (!Array.isArray(left) || !Array.isArray(right) || left.length !== right.length) { + return false; + } + for (let index = 0; index < left.length; index++) { + if (!shellValuesEqual(left[index], right[index])) return false; + } + return true; + } + const leftObj = left as Readonly>; + const rightObj = right as Readonly>; + let leftCount = 0; + for (const key of Object.keys(leftObj)) { + if (leftObj[key] === undefined) continue; + leftCount++; + if (!shellValuesEqual(leftObj[key], rightObj[key])) return false; + } + let rightCount = 0; + for (const key of Object.keys(rightObj)) { + if (rightObj[key] !== undefined) rightCount++; + } + return leftCount === rightCount; +} + +/** + * Computes a sparse field patch between two versions of the same thread shell, or `null` when + * a key became undefined or too many fields changed (calling for a full `thread.updated` row). + */ +export function diffThreadShell( + previous: OrchestrationV2ThreadShell, + next: OrchestrationV2ThreadShell, +): OrchestrationV2ThreadShellPatch | null { + if (previous.id !== next.id) return null; + const prevRecord = previous as Readonly>; + const nextRecord = next as Readonly>; + for (const key of Object.keys(prevRecord)) { + if (key === "id") continue; + if (prevRecord[key] !== undefined && nextRecord[key] === undefined) return null; + } + const patch: Record = {}; + let changed = 0; + for (const key of Object.keys(nextRecord)) { + if (key === "id") continue; + const nextValue = nextRecord[key]; + if (nextValue === undefined) continue; + if (shellValuesEqual(prevRecord[key], nextValue)) continue; + changed++; + if (changed > MAX_SHELL_PATCH_FIELDS) return null; + patch[key] = nextValue; + } + return patch as OrchestrationV2ThreadShellPatch; +} + +interface TrackedShellEntry { + readonly thread: OrchestrationV2ThreadShell; + readonly sentAt: number; +} + +function rememberSentThread( + lastSent: Map, + thread: OrchestrationV2ThreadShell, + sentAt: number, +): void { + lastSent.delete(thread.id); + lastSent.set(thread.id, { thread, sentAt }); + if (lastSent.size > MAX_TRACKED_SHELL_THREADS) { + const oldest = lastSent.keys().next().value; + if (oldest !== undefined) lastSent.delete(oldest); + } +} + +interface ShellStreamWireOptions { + readonly compactShell?: boolean; + readonly compactIds?: boolean; + readonly acceptShellDeltas?: boolean; +} + +/** + * Applies opt-in wire compaction (`compactShell`, `compactIds`) and sparse delta delivery + * (`cursor` heartbeats and `thread.patched` diffs) after slow-client coalescing so buffered + * full rows never drop earlier patch fields. + */ +export function applyShellStreamWireOptions( + stream: Stream.Stream, + options: ShellStreamWireOptions, +): Stream.Stream { + const compactShell = options.compactShell === true; + const compactIds = options.compactIds === true; + const acceptShellDeltas = options.acceptShellDeltas === true; + if (!compactShell && !compactIds && !acceptShellDeltas) return stream; + return Stream.suspend(() => { + const lastSent = new Map(); + return stream.pipe( + Stream.mapEffect((item) => + Effect.map(Clock.currentTimeMillis, (now): OrchestrationV2ShellStreamItem | null => { + switch (item.kind) { + case "snapshot": { + if (acceptShellDeltas && item.resolvedRepositoryIdentityRoots === undefined) { + lastSent.clear(); + for (const thread of item.snapshot.threads) { + rememberSentThread(lastSent, thread, now); + } + } + return { + ...item, + ...(compactShell ? { compactShell: true as const } : {}), + ...(compactIds ? { idTable: true as const } : {}), + }; + } + case "project.updated": + return compactShell ? { ...item, compactShell: true as const } : item; + case "thread.removed": + lastSent.delete(item.threadId); + return item; + case "thread.updated": { + const acknowledgesCommand = + "acknowledgesCommand" in item && + (item as { readonly acknowledgesCommand?: true }).acknowledgesCommand === true; + const fullItem = { + kind: "thread.updated" as const, + sequence: item.sequence, + location: item.location, + thread: item.thread, + ...(compactShell ? { compactShell: true as const } : {}), + }; + if (item.location !== "active") { + lastSent.delete(item.thread.id); + return fullItem; + } + if (!acceptShellDeltas) { + return fullItem; + } + const previous = lastSent.get(item.thread.id); + if (previous !== undefined) { + if ( + !acknowledgesCommand && + now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS && + sameThreadShell( + { ...item.thread, updatedAt: previous.thread.updatedAt }, + previous.thread, + ) + ) { + return null; + } + const patch = diffThreadShell(previous.thread, item.thread); + if (patch !== null) { + rememberSentThread(lastSent, item.thread, now); + return Object.keys(patch).length === 0 + ? { kind: "cursor" as const, sequence: item.sequence } + : { + kind: "thread.patched" as const, + sequence: item.sequence, + location: item.location, + threadId: item.thread.id, + patch, + }; + } + } + rememberSentThread(lastSent, item.thread, now); + return fullItem; + } + default: + return item; + } + }), + ), + Stream.filter((item): item is OrchestrationV2ShellStreamItem => item !== null), + ); + }); +} /** Resend unchanged shells after UNCHANGED_THREAD_SHELL_RESEND_MS so skipped deltas cannot leave resume cursors behind. */ export function skipUnchangedThreadShells( diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts index d3b6c46e25a1d..2bdba3c91e75b 100644 --- a/apps/server/src/orchestration-v2/http.test.ts +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -10,6 +10,7 @@ import { ORCHESTRATION_PROTOCOL_VERSION_TEXT, OrchestrationV2AppThread, OrchestrationV2Run, + OrchestrationV2ShellHttpSnapshot, OrchestrationV2ThreadDetailSnapshot, OrchestrationV2TurnItem, OrchestrationV2ThreadTranscript, @@ -52,6 +53,9 @@ class TranscriptTestApi extends HttpApi.make("environment").add( const decodeTranscript = Schema.decodeUnknownEffect( Schema.toCodecJson(OrchestrationV2ThreadTranscript), ); +const decodeShellHttp = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot), +); const now = DateTime.makeUnsafe("2026-09-29T00:00:00.000Z"); const environmentId = EnvironmentId.make("source-بيئة"); @@ -481,5 +485,26 @@ it.effect("leaves older settled threads out of the HTTP shell only when asked", for (const cursor of [full.snapshotSequence + 1, "x"]) { expect((yield* shell(`?omitOlderSettled=1&resumeFrom=${cursor}`)).threads).toHaveLength(26); } + + const readText = (query: string) => + Effect.promise(async () => { + const response = await handler( + new Request(`http://localhost/api/orchestration/shell${query}`, { + headers: { [ORCHESTRATION_PROTOCOL_HEADER]: ORCHESTRATION_PROTOCOL_VERSION_TEXT }, + }), + ); + expect(response.status).toBe(200); + return await response.text(); + }); + const plainText = yield* readText("?omitOlderSettled=1"); + const compactText = yield* readText("?omitOlderSettled=1&compactShell=1&compactIds=1"); + const plainJson = JSON.parse(plainText) as Record; + const compactJson = JSON.parse(compactText) as Record; + expect(plainJson.compactShell).toBeUndefined(); + expect(plainJson.ids).toBeUndefined(); + expect(compactJson.compactShell).toBe(true); + expect(Array.isArray(compactJson.ids)).toBe(true); + expect(compactText.length).toBeLessThanOrEqual(plainText.length * 0.4); + expect(yield* decodeShellHttp(compactJson)).toEqual(yield* decodeShellHttp(plainJson)); }), ); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 92df7cc80157c..07ab5cca04c08 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -87,6 +87,8 @@ export const layer = HttpApiBuilder.group( function* (options: { readonly omitIdleSubagents: boolean; readonly omitOlderSettled: boolean; + readonly compactShell: boolean; + readonly compactIds: boolean; }) { const { snapshot } = yield* loadSubscriberShellSnapshot({ sql, @@ -101,7 +103,13 @@ export const layer = HttpApiBuilder.group( options, }); const projects = yield* enrichProjectShells(snapshot.projects); - return { ...snapshot, projects, projectIdentities: projectIdentitiesDigest(projects) }; + return { + ...snapshot, + projects, + projectIdentities: projectIdentitiesDigest(projects), + ...(options.compactShell ? { compactShell: true as const } : {}), + ...(options.compactIds ? { idTable: true as const } : {}), + }; }, ); @@ -110,6 +118,8 @@ export const layer = HttpApiBuilder.group( readonly omitIdleSubagents?: string; readonly omitOlderSettled?: string; readonly resumeFrom?: string; + readonly compactShell?: string; + readonly compactIds?: string; }) => { const resumeFrom = query.resumeFrom === undefined ? Number.NaN : Number(query.resumeFrom); return loadShellUnlessResumable({ @@ -118,6 +128,8 @@ export const layer = HttpApiBuilder.group( loadSnapshot: loadShellSnapshot({ omitIdleSubagents: query.omitIdleSubagents === "1", omitOlderSettled: query.omitOlderSettled === "1", + compactShell: query.compactShell === "1", + compactIds: query.compactIds === "1", }), }); }); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index b4938e1ba70d7..9364ed0ec257b 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -20,6 +20,9 @@ import { AuthTerminalOperateScope, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_QUERY_PARAM, + ORCHESTRATION_V2_WS_METHODS, + OrchestrationV2ThreadFamily, + OrchestrationV2WorktreeThreadIds, EnvironmentId, EventId, GitManagerError, @@ -61,6 +64,7 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Headers, HttpRouter, HttpServer } from "effect/http"; @@ -69,7 +73,7 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as VcsProcess from "./vcs/VcsProcess.ts"; import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.ts"; import * as Ws from "./ws.ts"; -import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc"; +import { RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc"; import * as RpcTest from "effect/rpc/RpcTest"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; @@ -3435,3 +3439,332 @@ it.effect("a session that can only read sees a workflow run but cannot steer it" assert.deepEqual(calls, []); }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), ); + +const omittableShellTags = [ + ORCHESTRATION_V2_WS_METHODS.getThreadFamily, + ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds, +] as const; +const omittableShellRpcs = WsRpcGroup.omit( + ...[...WsRpcGroup.requests.keys()].filter( + ( + tag, + ): tag is Exclude< + keyof typeof RpcAuthorization.RPC_REQUIRED_SCOPES, + (typeof omittableShellTags)[number] + > => !(omittableShellTags as ReadonlyArray).includes(tag), + ), +); +const omittableShellStores = Layer.mergeAll( + EventStore.layer, + OrchestrationEventStore.layer, + ProjectionStore.layer.pipe(Layer.provide(NodeCrypto.layer)), +).pipe(Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory))); +const decodeWireThreadFamily = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2ThreadFamily), +); +const decodeWireWorktreeThreadIds = Schema.decodeUnknownEffect( + Schema.toCodecJson(OrchestrationV2WorktreeThreadIds), +); + +const seedOmittableShellThread = Effect.fn("test.seedOmittableShellThread")(function* (input: { + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly instanceId: ProviderInstanceId; + readonly parentThreadId?: ThreadId | null; + readonly rootThreadId?: ThreadId; + readonly worktreePath?: string | null; + readonly archived?: boolean; + readonly deleted?: boolean; +}) { + const sink = yield* EventSink.EventSinkV2; + const now = DateTime.makeUnsafe("2026-10-23T00:00:00.000Z"); + const parentThreadId = input.parentThreadId ?? null; + const baseThread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: input.id, + projectId: input.projectId, + title: `Thread ${input.id}`, + providerInstanceId: input.instanceId, + modelSelection: { instanceId: input.instanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: input.worktreePath ?? null, + activeProviderThreadId: null, + lineage: { + parentThreadId, + relationshipToParent: parentThreadId === null ? null : "subagent", + rootThreadId: input.rootThreadId ?? input.id, + }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + deletedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + }; + const events: Array = [ + { + id: EventId.make(`${input.id}:created`), + type: "thread.created", + threadId: input.id, + occurredAt: now, + payload: baseThread, + }, + ]; + if (input.archived === true) { + events.push({ + id: EventId.make(`${input.id}:archived`), + type: "thread.archived", + threadId: input.id, + occurredAt: now, + payload: { ...baseThread, archivedAt: now }, + }); + } + if (input.deleted === true) { + events.push({ + id: EventId.make(`${input.id}:deleted`), + type: "thread.deleted", + threadId: input.id, + occurredAt: now, + payload: { ...baseThread, deletedAt: now }, + }); + } + yield* sink.write({ events }); +}); + +// Serves the omittable-shell RPCs through RpcServer JSON wire serialization against real SQLite stores. +const makeOmittableShellWireCaller = Effect.fn("test.makeOmittableShellWireCaller")(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; + const scopes = [AuthOrchestrationReadScope]; + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.fresh(layerConfigSources), + Layer.mock(ExternalLauncher.ExternalLauncher)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({}), + Layer.mock(UsageLimitSources.UsageLimitSources)({}), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({}), + Layer.mock(DirectEndpoints.DirectEndpoints)({}), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ namedProjectsRoot: "/unused" }), + Layer.mock(ThreadWorkspaceService.ThreadWorkspaceService)({}), + Layer.mock(ServerEnvironment.ServerEnvironment)({}), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({}), + Layer.mock(ThreadManagement.ThreadManagementService)({ + readShellSnapshot: (options) => { + const projectionError = (cause: unknown) => + new Orchestrator.OrchestratorProjectionError({ + threadId: ThreadId.make("thread:shell"), + cause, + }); + return projections + .readShellSnapshot(options) + .pipe(Effect.mapError(projectionError), Effect.map(Effect.mapError(projectionError))); + }, + }), + Layer.succeed(OrchestrationEventStore.OrchestrationEventStore, applicationEvents), + Layer.succeed(SqlClient.SqlClient, sql), + ); + const responses = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + const serialization = yield* RpcSerialization.RpcSerialization; + return { + disconnects: yield* Queue.unbounded(), + send: (_clientId, response) => Queue.offer(responses, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ).pipe(Effect.provide(RpcSerialization.layerJson)); + + yield* RpcServer.make(omittableShellRpcs, WS_RPC_SERVER_OPTIONS).pipe( + Effect.provide( + layerWsRpc( + { + sessionId: AuthSessionId.make("omittable-shell-test"), + subject: "omittable-shell-test", + method: "browser-session-cookie", + scopes, + }, + {}, + yield* ServerBrowser.ServerBrowser, + () => Effect.void, + { secretReferences: true }, + ).pipe(Layer.provide(services), Layer.merge(RpcAuthorization.layer(scopes))), + ), + Effect.provideService(RpcServer.Protocol, protocol), + Effect.forkScoped, + ); + + const write = yield* Deferred.await(receive); + let nextRequestId = 1; + return Effect.fn("test.callOmittableShellWire")(function* ( + tag: (typeof omittableShellTags)[number], + payload: unknown, + ) { + const id = String(nextRequestId++); + yield* write(0, { _tag: "Request", id, tag, payload, headers: [] }); + const response = yield* Queue.take(responses); + assert.strictEqual(response._tag, "Exit"); + if (response._tag !== "Exit") throw new Error(`Unexpected RPC response: ${response._tag}`); + assert.strictEqual(response.exit._tag, "Success"); + if (response.exit._tag !== "Success") { + throw new Error(`RPC ${tag} failed: ${JSON.stringify(response.exit)}`); + } + return response.exit.value; + }); +}); + +const layerOmittableShellTest = Layer.mergeAll( + EventSink.layer.pipe(Layer.provideMerge(Layer.fresh(omittableShellStores))), + Layer.mock(PreviewAutomationBroker.PreviewAutomationBroker)({}), + Layer.mock(ServerBrowser.ServerBrowser)({}), +); + +it.effect( + "getThreadFamily with compactShell and compactIds encodes active family threads compactly and excludes archived ones", + () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:family-compact"); + const instanceId = ProviderInstanceId.make("codex-family-instance"); + const rootId = ThreadId.make("thread:family-root"); + const activeChildId = ThreadId.make("thread:family-active-child"); + const archivedChildId = ThreadId.make("thread:family-archived-child"); + const unrelatedId = ThreadId.make("thread:unrelated-root"); + + yield* seedOmittableShellThread({ id: rootId, projectId, instanceId }); + yield* seedOmittableShellThread({ + id: activeChildId, + projectId, + instanceId, + parentThreadId: rootId, + rootThreadId: rootId, + }); + yield* seedOmittableShellThread({ + id: archivedChildId, + projectId, + instanceId, + parentThreadId: rootId, + rootThreadId: rootId, + archived: true, + }); + yield* seedOmittableShellThread({ id: unrelatedId, projectId, instanceId }); + + const call = yield* makeOmittableShellWireCaller(); + const plainWire = (yield* call(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, { + threadId: rootId, + })) as Record; + const compactWire = (yield* call(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, { + threadId: activeChildId, + compactShell: true, + compactIds: true, + })) as Record; + + assert.isUndefined(plainWire.compactShell); + assert.isUndefined(plainWire.ids); + assert.strictEqual(compactWire.compactShell, true); + assert.isTrue(Array.isArray(compactWire.ids)); + const ids = compactWire.ids as ReadonlyArray; + assert.isTrue(ids.includes(projectId)); + assert.isTrue(ids.includes(rootId)); + assert.isTrue(ids.includes(instanceId)); + assert.isTrue(ids.includes("gpt-5.4")); + const compactRows = compactWire.threads as ReadonlyArray>; + assert.strictEqual(compactRows.length, 2); + for (const row of compactRows) { + assert.isFalse("runtimeMode" in row); + assert.isFalse("interactionMode" in row); + assert.isFalse("providerInstanceId" in row); + assert.isFalse("archivedAt" in row); + assert.strictEqual(typeof row.projectId, "number"); + } + assert.isBelow(JSON.stringify(compactWire).length, JSON.stringify(plainWire).length); + + const plainDecoded = yield* decodeWireThreadFamily(plainWire); + const compactDecoded = yield* decodeWireThreadFamily(compactWire); + assert.deepEqual(compactDecoded, plainDecoded); + assert.deepEqual( + compactDecoded.threads.map((thread) => thread.id).toSorted(), + [activeChildId, rootId].toSorted(), + ); + }).pipe(Effect.provide(Layer.fresh(layerOmittableShellTest)), Effect.scoped), +); + +it.effect("getWorktreeThreadIds returns both active and archived threads owning a worktree", () => + Effect.gen(function* () { + const projectId = ProjectId.make("project:worktree-owners"); + const instanceId = ProviderInstanceId.make("codex-worktree-instance"); + const sharedWorktree = "/worktrees/shared-feature"; + const archivedOnlyWorktree = "/worktrees/archived-only"; + const activeOwnerId = ThreadId.make("thread:worktree-active"); + const archivedOwnerId = ThreadId.make("thread:worktree-archived"); + const archivedOnlyOwnerId = ThreadId.make("thread:worktree-archived-only"); + const deletedThreadId = ThreadId.make("thread:worktree-deleted"); + const otherWorktreeId = ThreadId.make("thread:worktree-other"); + + yield* seedOmittableShellThread({ + id: activeOwnerId, + projectId, + instanceId, + worktreePath: sharedWorktree, + }); + yield* seedOmittableShellThread({ + id: archivedOwnerId, + projectId, + instanceId, + worktreePath: sharedWorktree, + archived: true, + }); + yield* seedOmittableShellThread({ + id: archivedOnlyOwnerId, + projectId, + instanceId, + worktreePath: archivedOnlyWorktree, + archived: true, + }); + yield* seedOmittableShellThread({ + id: deletedThreadId, + projectId, + instanceId, + worktreePath: sharedWorktree, + deleted: true, + }); + yield* seedOmittableShellThread({ + id: otherWorktreeId, + projectId, + instanceId, + worktreePath: "/worktrees/other", + }); + + const call = yield* makeOmittableShellWireCaller(); + const sharedResult = yield* decodeWireWorktreeThreadIds( + yield* call(ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds, { + worktreePath: sharedWorktree, + }), + ); + assert.deepEqual( + sharedResult.threadIds.toSorted(), + [activeOwnerId, archivedOwnerId].toSorted(), + ); + + const archivedOnlyResult = yield* decodeWireWorktreeThreadIds( + yield* call(ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds, { + worktreePath: archivedOnlyWorktree, + }), + ); + assert.deepEqual(archivedOnlyResult.threadIds, [archivedOnlyOwnerId]); + }).pipe(Effect.provide(Layer.fresh(layerOmittableShellTest)), Effect.scoped), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 26131edc75e5c..73698c13bc75a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -79,6 +79,7 @@ import { OrchestrationV2GetThreadProjectionError, OrchestrationV2ThreadLaunchError, type OrchestrationProjectShell, + type OrchestrationV2GetArchivedShellSnapshotInput, type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellStreamItem, type OrchestrationV2ThreadStreamItem, @@ -147,6 +148,7 @@ import * as SecretRequests from "./secrets/SecretRequests.ts"; import * as FeedbackStore from "./feedback/FeedbackStore.ts"; import * as GuestShareService from "./guest/GuestShareService.ts"; import { + applyShellStreamWireOptions, bufferShellLiveStream, coalesceShellApplicationEvents, composeShellStreamWithEnrichment, @@ -1195,6 +1197,9 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc readonly requestCompletionMarker?: boolean; readonly omitIdleSubagents?: boolean; readonly omitOlderSettled?: boolean; + readonly compactShell?: boolean; + readonly compactIds?: boolean; + readonly acceptShellDeltas?: boolean; }) { const sql = yield* SqlClient.SqlClient; const threadManagement = yield* ThreadManagementService.ThreadManagementService; @@ -1313,13 +1318,14 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ); }); - const toShellStream = (stream: Stream.Stream) => - stream.pipe( + const toShellStream = (stream: Stream.Stream) => { + const projected = stream.pipe( Stream.groupedWithin(512, Duration.millis(50)), Stream.mapEffect((events) => projectShellItems(Array.from(events))), Stream.flatMap(Stream.fromIterable), - skipUnchangedThreadShells, ); + return input.acceptShellDeltas === true ? projected : skipUnchangedThreadShells(projected); + }; const liveFrom = (afterSequence: number) => bufferShellLiveStream( @@ -1471,8 +1477,11 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc ), ); - return stream.pipe( - dedupeShellEnrichment, + return applyShellStreamWireOptions(stream.pipe(dedupeShellEnrichment), { + compactShell: input.compactShell === true, + compactIds: input.compactIds === true, + acceptShellDeltas: input.acceptShellDeltas === true, + }).pipe( Stream.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ @@ -2037,25 +2046,26 @@ export const layerWsRpc = ( .refreshStatus(cwd) .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); - const getOrchestrationV2ArchivedShellSnapshot = Effect.gen(function* () { - const { threads, projects, snapshotSequence } = yield* loadShellSnapshotParts({ - sql, - readThreads: threadManagement.readShellSnapshot({ location: "archive" }), - listProjects: projectStore.listShells(), - latestSequence: applicationEvents.latestApplicationSequence, - }); - return { - schemaVersion: threads.schemaVersion, - snapshotSequence, - projects, - threads: threads.archivedThreads, - } as const; - }).pipe( - Effect.flatMap((snapshot) => - enrichProjectShells(snapshot.projects).pipe( - Effect.map(({ projects }) => ({ ...snapshot, projects })), - ), - ), + const getOrchestrationV2ArchivedShellSnapshot = Effect.fn( + "ws.orchestrationV2.getArchivedShellSnapshot", + )( + function* (input: OrchestrationV2GetArchivedShellSnapshotInput) { + const { threads, projects, snapshotSequence } = yield* loadShellSnapshotParts({ + sql, + readThreads: threadManagement.readShellSnapshot({ location: "archive" }), + listProjects: projectStore.listShells(), + latestSequence: applicationEvents.latestApplicationSequence, + }); + const enriched = yield* enrichProjectShells(projects); + return { + schemaVersion: threads.schemaVersion, + snapshotSequence, + projects: enriched.projects, + threads: threads.archivedThreads, + ...(input.compactShell === true ? { compactShell: true as const } : {}), + ...(input.compactIds === true ? { idTable: true as const } : {}), + } as const; + }, Effect.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ @@ -2225,12 +2235,18 @@ export const layerWsRpc = ( }), ), ), - [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) => - getOrchestrationV2ArchivedShellSnapshot, + [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (input) => + getOrchestrationV2ArchivedShellSnapshot(input), [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) => readOmittableShellRows( { location: "active", familyOf: input.threadId }, "Failed to load the thread family", + ).pipe( + Effect.map((family) => ({ + ...family, + ...(input.compactShell === true ? { compactShell: true as const } : {}), + ...(input.compactIds === true ? { idTable: true as const } : {}), + })), ), [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: (input) => threadManagement.getThreadLinkMetadata(input.threadIds).pipe( @@ -2260,6 +2276,11 @@ export const layerWsRpc = ( threadManagement.readShellSnapshot({ location: "active", threadIds }), latestSequence: applicationEvents.latestApplicationSequence, }).pipe( + Effect.map((page) => ({ + ...page, + ...(input.compactShell === true ? { compactShell: true as const } : {}), + ...(input.compactIds === true ? { idTable: true as const } : {}), + })), Effect.mapError( (cause) => new OrchestrationV2GetShellSnapshotError({ diff --git a/packages/client-runtime/src/state/olderSettledThreads.test.ts b/packages/client-runtime/src/state/olderSettledThreads.test.ts index 72e23c44d3f9c..b095cf0273e73 100644 --- a/packages/client-runtime/src/state/olderSettledThreads.test.ts +++ b/packages/client-runtime/src/state/olderSettledThreads.test.ts @@ -470,10 +470,12 @@ describe("createOlderSettledThreadAtoms", () => { expect(done.status).toBe("ready"); // The second page continues from the first page's last row. expect(requests).toEqual([ - { before: { settledAt: before }, limit: 25 }, + { before: { settledAt: before }, limit: 25, compactShell: true, compactIds: true }, { before: { settledAt: DateTime.formatIso(full[24]!.settledAt!), threadId: full[24]!.id }, limit: 25, + compactShell: true, + compactIds: true, }, ]); @@ -545,6 +547,8 @@ describe("createOlderSettledThreadAtoms", () => { expect((yield* Queue.take(requestLog)).input).toEqual({ before: { settledAt: before }, limit: 25, + compactShell: true, + compactIds: true, }); yield* Queue.offer( replies, @@ -560,6 +564,8 @@ describe("createOlderSettledThreadAtoms", () => { expect(second.input).toEqual({ before: { settledAt: DateTime.formatIso(full[24]!.settledAt!), threadId: full[24]!.id }, limit: 25, + compactShell: true, + compactIds: true, }); // Collapsing stops the pending read: nothing is left to run again on a reconnect. diff --git a/packages/client-runtime/src/state/olderSettledThreads.ts b/packages/client-runtime/src/state/olderSettledThreads.ts index 370ea11e890dd..b4954698bedf6 100644 --- a/packages/client-runtime/src/state/olderSettledThreads.ts +++ b/packages/client-runtime/src/state/olderSettledThreads.ts @@ -264,6 +264,8 @@ export function createOlderSettledThreadAtoms( before: input.before, ...(input.projectIds === null ? {} : { projectIds: input.projectIds }), limit: OLDER_SETTLED_PAGE_SIZE, + compactShell: true, + compactIds: true, }); }), }); diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 2c70c8d54027f..fd33506d87b6c 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -241,6 +241,12 @@ export function createOrchestrationEnvironmentAtoms( archivedShellSnapshot: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:archived-shell-snapshot", tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, + execute: (input) => + request(ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, { + compactShell: true, + compactIds: true, + ...input, + }), // The shell reports archiving a thread, and deleting or changing an archived one, as a removal, // and replaces `removedAt` on each one. refreshTrigger: ({ environmentId }) => { @@ -252,6 +258,12 @@ export function createOrchestrationEnvironmentAtoms( threadFamily: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:thread-family-for-delete", tag: ORCHESTRATION_V2_WS_METHODS.getThreadFamily, + execute: (input) => + request(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, { + compactShell: true, + compactIds: true, + ...input, + }), staleTimeMs: 0, idleTtlMs: 0, }), diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 1fdb4a5b6b0fa..def5bcc138bc1 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -1203,6 +1203,11 @@ describe("environment shell cold start", () => { environment: { serverVersion: "1.0.0" }, }; const FAMILY_FLAGS = { omitIdleSubagents: true, omitOlderSettled: true }; + const SHELL_WIRE_FLAGS = { + compactShell: true, + compactIds: true, + acceptShellDeltas: true, + }; const makeColdStart = Effect.fn("test.makeColdStartShell")(function* ( origin: Persistence.ShellCacheOrigin | undefined, @@ -1673,7 +1678,11 @@ describe("environment shell cold start", () => { yield* Deferred.await(claimed); yield* TestClock.adjust("30 millis"); const first = yield* Queue.take(h.subscriptions); - expect(first.input).toEqual({ ...FAMILY_FLAGS, requestCompletionMarker: true }); + expect(first.input).toEqual({ + ...FAMILY_FLAGS, + ...SHELL_WIRE_FLAGS, + requestCompletionMarker: true, + }); yield* Queue.offerAll(first.events, [ { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: HTTP_SEQUENCE + 1 } }, { kind: "synchronized" }, @@ -1939,7 +1948,11 @@ describe("environment shell cold start", () => { const wrongConfig = yield* Deferred.make(); const wrong = yield* makeOpeningHarness(Deferred.await(wrongConfig) as never); const wrongSub = yield* Queue.take(wrong.subscriptions); - expect(wrongSub.input).toEqual({ ...FAMILY_FLAGS, requestCompletionMarker: true }); + expect(wrongSub.input).toEqual({ + ...FAMILY_FLAGS, + ...SHELL_WIRE_FLAGS, + requestCompletionMarker: true, + }); yield* Queue.offerAll(wrongSub.events, [ { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: 99 } }, { kind: "synchronized" }, @@ -1976,7 +1989,7 @@ describe("environment shell cold start", () => { yield* TestClock.adjust("1 millis"); yield* Deferred.succeed(preMismatch.releaseLoad, undefined); const liveSub = yield* Queue.take(preMismatch.subscriptions); - expect(liveSub.input).toEqual({ requestCompletionMarker: true }); + expect(liveSub.input).toEqual({ ...SHELL_WIRE_FLAGS, requestCompletionMarker: true }); yield* Queue.offerAll(liveSub.events, [ { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: 42 } }, { kind: "synchronized" }, @@ -1994,7 +2007,11 @@ describe("environment shell cold start", () => { const lateMismatchConfig = yield* Deferred.make(); const lateMismatch = yield* makeOpeningHarness(Deferred.await(lateMismatchConfig) as never); const firstSub = yield* Queue.take(lateMismatch.subscriptions); - expect(firstSub.input).toEqual({ ...FAMILY_FLAGS, requestCompletionMarker: true }); + expect(firstSub.input).toEqual({ + ...FAMILY_FLAGS, + ...SHELL_WIRE_FLAGS, + requestCompletionMarker: true, + }); yield* Queue.offerAll(firstSub.events, [ { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: 55 } }, { kind: "synchronized" }, @@ -2013,7 +2030,7 @@ describe("environment shell cold start", () => { shellOlderSettled: false, } as never); const reloadedSub = yield* Queue.take(lateMismatch.subscriptions); - expect(reloadedSub.input).toEqual({ requestCompletionMarker: true }); + expect(reloadedSub.input).toEqual({ ...SHELL_WIRE_FLAGS, requestCompletionMarker: true }); yield* Queue.offerAll(reloadedSub.events, [ { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: 56 } }, { kind: "synchronized" }, @@ -2079,4 +2096,71 @@ describe("environment shell cold start", () => { expect((yield* SubscriptionRef.get(cancelled.shellState)).status).toBe("live"); }), ); + + it.effect( + "reloads a full HTTP snapshot after a missing active thread.patched while ignoring stale patches", + () => + Effect.gen(function* () { + const h = yield* makeColdStart(RECENT_ORIGIN); + const missingId = ThreadId.make("thread-missing"); + + const initial = yield* Queue.take(h.subscriptions); + expect(initial.input).toMatchObject({ + afterSequence: CACHED_SEQUENCE, + ...SHELL_WIRE_FLAGS, + }); + yield* Queue.offer(initial.events, { kind: "synchronized" }); + yield* h.liveAt(CACHED_SEQUENCE); + expect(yield* Ref.get(h.httpLoads)).toBe(0); + + // Stale patch for an absent thread must not trigger a reload; valid patches still apply. + yield* Queue.offerAll(initial.events, [ + { + kind: "thread.patched", + sequence: CACHED_SEQUENCE, + location: "active", + threadId: missingId, + patch: { title: "Stale ghost" }, + }, + { + kind: "thread.patched", + sequence: CACHED_SEQUENCE + 1, + location: "active", + threadId: v2ThreadShell.id, + patch: { title: "Patched title" }, + }, + ]); + const patchedState = yield* h.liveAt(CACHED_SEQUENCE + 1); + expect(Option.getOrThrow(patchedState.snapshot).threads[0]?.title).toBe("Patched title"); + expect(yield* Ref.get(h.httpLoads)).toBe(0); + expect(yield* Queue.size(h.subscriptions)).toBe(0); + + // Live patch for an absent active thread stops cursor advancement and forces a full reload. + yield* Queue.offerAll(initial.events, [ + { + kind: "thread.patched", + sequence: CACHED_SEQUENCE + 2, + location: "active", + threadId: missingId, + patch: { title: "Missing target" }, + }, + { kind: "cursor", sequence: CACHED_SEQUENCE + 3 }, + ]); + const reloaded = yield* Queue.take(h.subscriptions); + expect(reloaded.input).toEqual({ + afterSequence: HTTP_SEQUENCE, + knownProjectIdentities: "identities-1", + ...SHELL_WIRE_FLAGS, + requestCompletionMarker: true, + }); + expect(yield* Ref.get(h.httpLoads)).toBe(1); + expect(yield* Queue.take(h.loadOptions)).toEqual({ + omitIdleSubagents: false, + omitOlderSettled: false, + }); + yield* Queue.offer(reloaded.events, { kind: "synchronized" }); + const recovered = yield* h.liveAt(HTTP_SEQUENCE); + expect(recovered.generation).toBeGreaterThan(patchedState.generation); + }), + ); }); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 7bf424b0740ff..6accc2af474f2 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -40,7 +40,7 @@ import type { RpcSession } from "../rpc/session.ts"; import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts"; import type { DeferredShellSnapshot } from "./shellPullRequests.ts"; import { - applyShellStreamEvents, + applyShellStreamEventsWithStatus, type ShellStreamEvent, mergeShellSnapshotProjects, reuseUnchangedThreadShells, @@ -385,10 +385,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") const receivedAtMs = yield* Clock.currentTimeMillis; const flushDeltas = () => { if (deltas.length > 0 && Option.isSome(next.snapshot)) { + const applied = applyShellStreamEventsWithStatus(next.snapshot.value, deltas); + if (applied.missingPatchTarget) { + snapshotRequired = true; + } + const appliedSequence = applied.snapshot.snapshotSequence; let sequence = next.snapshot.value.snapshotSequence; let removedAt: Map | undefined; for (const delta of deltas) { - if (delta.sequence <= sequence) continue; + if (delta.sequence <= sequence || delta.sequence > appliedSequence) continue; switch (delta.kind) { case "thread.removed": removedAt ??= new Map(next.removedAt); @@ -404,6 +409,16 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") ); } break; + case "thread.patched": + if (!waiting && delta.patch.updatedAt !== undefined) { + observeServerTime( + environmentId, + DateTime.toEpochMillis(delta.patch.updatedAt), + receivedAtMs, + ); + } + break; + case "cursor": case "project.updated": case "project.removed": break; @@ -415,7 +430,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") next = { ...next, removedAt: removedAt ?? next.removedAt, - snapshot: Option.some(applyShellStreamEvents(next.snapshot.value, deltas)), + snapshot: Option.some(applied.snapshot), status: waiting ? "synchronizing" : "live", error: Option.none(), }; @@ -935,6 +950,9 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") const omission = { ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}), ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}), + compactShell: true as const, + compactIds: true as const, + acceptShellDeltas: true as const, }; if (Option.isNone(current.snapshot) || !(resumingHeldRows || loaded?.kind === "snapshot")) { return { ...omission, requestCompletionMarker: true as const }; diff --git a/packages/client-runtime/src/state/shellPullRequests.ts b/packages/client-runtime/src/state/shellPullRequests.ts index 97e4c7aaaa1e1..0e6c529e72328 100644 --- a/packages/client-runtime/src/state/shellPullRequests.ts +++ b/packages/client-runtime/src/state/shellPullRequests.ts @@ -1,5 +1,6 @@ import { - OrchestrationV2ShellSnapshot, + OrchestrationV2ShellHttpSnapshot, + type OrchestrationV2ShellSnapshot, type ThreadId, ThreadPullRequestLink, } from "@t3tools/contracts"; @@ -47,6 +48,7 @@ function deferPullRequests( rawLinks: ReadonlyArray, ): S & Required> { const threadIds = snapshot.threads.map((thread) => thread.id); + const retainedLinks = snapshot.threads.map((thread) => thread.pullRequests); // Schema decoding runs when called, so each thread's decode is built after a yield. const loadPullRequests = Effect.gen(function* () { const linksByThreadId = new Map>(); @@ -54,7 +56,11 @@ function deferPullRequests( let deadline = 0n; for (const [index, threadId] of threadIds.entries()) { const raw = rawLinks[index]; - if (raw === undefined) continue; + if (raw === undefined) { + const retained = retainedLinks[index]; + if (retained !== undefined) linksByThreadId.set(threadId, retained); + continue; + } const size = Array.isArray(raw) ? raw.length : 1; if (batchSize + size > LINKS_PER_BATCH || (yield* Clock.monotonicTimeNanos) >= deadline) { yield* yieldToHost; @@ -78,17 +84,24 @@ function deferPullRequests( } const decodeShellSnapshotJson = Schema.decodeUnknownEffect( - Schema.toCodecJson(OrchestrationV2ShellSnapshot), + Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot), ); export const decodeShellSnapshotDeferringPullRequests = Effect.fnUntraced(function* ( json: unknown, ) { const rawLinks = detachPullRequests(json); - const snapshot = yield* decodeShellSnapshotJson(json); - return rawLinks.some((links) => links !== undefined) - ? deferPullRequests(snapshot, rawLinks) - : snapshot; + const { projectIdentities: _projectIdentities, ...snapshot } = + yield* decodeShellSnapshotJson(json); + if (!rawLinks.some((links) => links !== undefined)) return snapshot; + // Compact wire decoding restores omitted `pullRequests` to `[]`; clear it only on rows + // whose links were detached above so `reuseUnchangedThreadShells` keeps prior links. + const deferredThreads = snapshot.threads.map((thread, index) => { + if (rawLinks[index] === undefined || thread.pullRequests === undefined) return thread; + const { pullRequests: _stripped, ...rest } = thread; + return rest; + }); + return deferPullRequests({ ...snapshot, threads: deferredThreads }, rawLinks); }); const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown)); diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index f98a14c3ed32d..d464bf61f18bd 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -1,10 +1,25 @@ -import { ProjectId, ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts"; -import { describe, expect, it } from "vite-plus/test"; - -import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; +import { describe, expect, it } from "@effect/vitest"; +import { + OrchestrationV2ShellHttpSnapshot, + ProjectId, + ProviderInstanceId, + ThreadId, + type ThreadPullRequestLink, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { v2Now, v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; +import { + decodeShellSnapshotDeferringPullRequests, + type DeferredShellSnapshot, +} from "./shellPullRequests.ts"; import { applyShellStreamEvent, applyShellStreamEvents, + applyShellStreamEventsWithStatus, + applyShellStreamThreadPatch, type ShellStreamEvent, mergeShellSnapshotProjects, reuseUnchangedThreadShells, @@ -429,4 +444,175 @@ describe("applyShellStreamEvents", () => { events.reduce(applyShellStreamEvent, v2ShellSnapshot), ); }); + + it("handles cursor heartbeats and sparse thread.patched deltas preserving untouched fields", () => { + const later = DateTime.makeUnsafe(DateTime.toEpochMillis(v2Now) + 5_000); + const tracked = { + ...a, + pendingBackgroundTasks: [], + providerInstanceHistory: [ProviderInstanceId.make("codex")], + }; + const seed = { + ...v2ShellSnapshot, + snapshotSequence: 4, + threads: [tracked, b], + archivedThreads: [archived], + }; + + const afterCursor = applyShellStreamEvent(seed, { kind: "cursor", sequence: 5 }); + expect(afterCursor.snapshotSequence).toBe(5); + expect(afterCursor.threads).toBe(seed.threads); + expect(afterCursor.projects).toBe(seed.projects); + expect(afterCursor.archivedThreads).toBe(seed.archivedThreads); + expect(applyShellStreamEvent(afterCursor, { kind: "cursor", sequence: 5 })).toBe(afterCursor); + + const noopPatched = applyShellStreamThreadPatch(tracked, { + title: tracked.title, + itemCount: tracked.itemCount, + }); + expect(noopPatched).toBe(tracked); + + const mixed: Array = [ + { kind: "cursor", sequence: 6 }, + { + kind: "thread.patched", + sequence: 7, + location: "active", + threadId: tracked.id, + patch: { itemCount: 3, visibleItemCount: 3, lastVisitedAt: later, updatedAt: later }, + }, + { + kind: "thread.patched", + sequence: 8, + location: "active", + threadId: tracked.id, + patch: { itemCount: 3 }, + }, + { + kind: "thread.patched", + sequence: 9, + location: "archive", + threadId: b.id, + patch: { archivedAt: later }, + }, + ]; + const batched = applyShellStreamEvents(seed, mixed); + const sequential = mixed.reduce(applyShellStreamEvent, seed); + expect(batched).toEqual(sequential); + expect(batched.snapshotSequence).toBe(9); + expect(batched.threads).toHaveLength(1); + expect(batched.threads[0]?.itemCount).toBe(3); + expect(batched.threads[0]?.visibleItemCount).toBe(3); + expect(batched.threads[0]?.lastVisitedAt).toEqual(later); + expect(batched.threads[0]?.providerInstanceHistory).toEqual([ProviderInstanceId.make("codex")]); + }); + + it("flags missing active thread.patched targets without advancing snapshotSequence past them", () => { + const seed = { ...v2ShellSnapshot, snapshotSequence: 4, threads: [a] }; + const missingId = ThreadId.make("missing-thread"); + + const single = applyShellStreamEventsWithStatus(seed, [ + { + kind: "thread.patched", + sequence: 5, + location: "active", + threadId: missingId, + patch: { title: "Ghost" }, + }, + ]); + expect(single.missingPatchTarget).toBe(true); + expect(single.snapshot).toBe(seed); + + const stale = applyShellStreamEventsWithStatus(seed, [ + { + kind: "thread.patched", + sequence: 4, + location: "active", + threadId: missingId, + patch: { title: "Stale" }, + }, + ]); + expect(stale.missingPatchTarget).toBe(false); + expect(stale.snapshot).toBe(seed); + + const multi = applyShellStreamEventsWithStatus(seed, [ + update(5, { ...a, title: "Applied before gap" }), + { + kind: "thread.patched", + sequence: 6, + location: "active", + threadId: missingId, + patch: { title: "Missing" }, + }, + { kind: "cursor", sequence: 7 }, + ]); + expect(multi.missingPatchTarget).toBe(true); + expect(multi.snapshot.snapshotSequence).toBe(5); + expect(multi.snapshot.threads[0]?.title).toBe("Applied before gap"); + }); +}); + +describe("decodeShellSnapshotDeferringPullRequests with compact wire", () => { + const encodeHttp = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot)); + const link: ThreadPullRequestLink = { + host: "github.com", + repository: "pingdotgg/t3code", + number: 99, + url: "https://github.com/pingdotgg/t3code/pull/99", + source: "agent", + linkedAt: "2026-06-20T00:00:00.000Z", + snapshot: null, + stack: null, + }; + + it.live( + "defers non-empty pullRequests while keeping empty compact pullRequests arrays intact", + () => + Effect.gen(function* () { + const plainId = ThreadId.make("thread-plain"); + const snapshot: OrchestrationV2ShellHttpSnapshot = { + ...v2ShellSnapshot, + snapshotSequence: 12, + threads: [ + { ...v2ThreadShell, pullRequests: [link] }, + { + ...v2ThreadShell, + id: plainId, + lineage: { ...v2ThreadShell.lineage, rootThreadId: plainId }, + pullRequests: [], + }, + ], + }; + const wire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true, idTable: true })), + ); + + const decoded: DeferredShellSnapshot = + yield* decodeShellSnapshotDeferringPullRequests(wire); + expect(decoded.threads[0]?.id).toBe(v2ThreadShell.id); + expect(decoded.threads[0]?.pullRequests).toBeUndefined(); + expect(decoded.threads[1]?.id).toBe(plainId); + expect(decoded.threads[1]?.pullRequests).toEqual([]); + expect(decoded.loadPullRequests).toBeDefined(); + + const filled = yield* decoded.loadPullRequests!; + expect(filled.get(v2ThreadShell.id)).toEqual([link]); + expect(filled.get(plainId)).toEqual([]); + + const noPrWire = JSON.parse( + JSON.stringify( + encodeHttp({ + ...v2ShellSnapshot, + threads: [{ ...v2ThreadShell, pullRequests: [] }], + compactShell: true, + idTable: true, + }), + ), + ); + const decodedNoPr: DeferredShellSnapshot = + yield* decodeShellSnapshotDeferringPullRequests(noPrWire); + expect(decodedNoPr.loadPullRequests).toBeUndefined(); + expect(decodedNoPr.threads[0]?.pullRequests).toEqual([]); + }), + ); }); diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 2ef7dea533f3c..f91d420c6ef5e 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -5,6 +5,7 @@ import { ThreadPullRequestLink, type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellStreamItem, + type OrchestrationV2ThreadShellPatch, } from "@t3tools/contracts"; import * as Schema from "effect/Schema"; @@ -129,6 +130,21 @@ export function mergeShellSnapshotProjects( return { ...next, projects: unchanged ? previous.projects : projects }; } +export function applyShellStreamThreadPatch( + existing: OrchestrationV2ThreadShell, + patch: OrchestrationV2ThreadShellPatch, +): OrchestrationV2ThreadShell { + let next: Record | undefined; + for (const [key, value] of Object.entries(patch)) { + if (value === undefined) continue; + next ??= { ...existing }; + next[key] = value; + } + if (next === undefined) return existing; + const patched = next as OrchestrationV2ThreadShell; + return sameThreadShell(existing, patched) ? existing : patched; +} + export function applyShellStreamEvent( snapshot: OrchestrationV2ShellSnapshot, event: ShellStreamEvent, @@ -136,6 +152,8 @@ export function applyShellStreamEvent( if (event.sequence <= snapshot.snapshotSequence) return snapshot; switch (event.kind) { + case "cursor": + return { ...snapshot, snapshotSequence: event.sequence }; case "project.updated": { // Enrichment is async. A project mutation can land with null // repositoryIdentity while an earlier snapshot already resolved it. @@ -178,6 +196,30 @@ export function applyShellStreamEvent( snapshotSequence: event.sequence, }; } + case "thread.patched": { + if (event.location !== "active") { + const withoutThread = (threads: OrchestrationV2ShellSnapshot["threads"]) => + threads.filter((thread) => thread.id !== event.threadId); + return { + ...snapshot, + threads: withoutThread(snapshot.threads), + archivedThreads: withoutThread(snapshot.archivedThreads), + snapshotSequence: event.sequence, + }; + } + const existing = snapshot.threads.find((thread) => thread.id === event.threadId); + if (existing === undefined) return snapshot; + const patched = applyShellStreamThreadPatch(existing, event.patch); + if (patched === existing) { + return { ...snapshot, snapshotSequence: event.sequence }; + } + return { + ...snapshot, + threads: upsertById(snapshot.threads, patched), + archivedThreads: snapshot.archivedThreads.filter((thread) => thread.id !== event.threadId), + snapshotSequence: event.sequence, + }; + } case "thread.removed": return { ...snapshot, @@ -219,20 +261,36 @@ export type ShellStreamEvent = Extract< { readonly sequence: number } >; -/** Apply ordered deltas with one index and at most one new array per collection. */ -export function applyShellStreamEvents( +/** Apply ordered deltas and report if a patch arrived for a thread absent from the local snapshot. */ +export function applyShellStreamEventsWithStatus( snapshot: OrchestrationV2ShellSnapshot, events: ReadonlyArray, -): OrchestrationV2ShellSnapshot { - // Avoid indexing the whole shell for the common single-event delivery. - if (events.length === 1) return applyShellStreamEvent(snapshot, events[0]!); +): { + readonly snapshot: OrchestrationV2ShellSnapshot; + readonly missingPatchTarget: boolean; +} { + if (events.length === 1) { + const event = events[0]!; + if ( + event.kind === "thread.patched" && + event.location === "active" && + event.sequence > snapshot.snapshotSequence && + !snapshot.threads.some((thread) => thread.id === event.threadId) + ) { + return { snapshot, missingPatchTarget: true }; + } + return { snapshot: applyShellStreamEvent(snapshot, event), missingPatchTarget: false }; + } const projects = batchRows(snapshot.projects); const threads = batchRows(snapshot.threads); const archivedThreads = batchRows(snapshot.archivedThreads); let sequence = snapshot.snapshotSequence; + let missingPatchTarget = false; for (const event of events) { if (event.sequence <= sequence) continue; switch (event.kind) { + case "cursor": + break; case "project.updated": projects.set(retainRepositoryIdentity(projects.get(event.project.id), event.project)); break; @@ -252,6 +310,22 @@ export function applyShellStreamEvents( archivedThreads.remove(id); break; } + case "thread.patched": { + const id = event.threadId; + if (event.location === "active") { + const previous = threads.get(id); + if (previous === undefined) { + missingPatchTarget = true; + break; + } + const patched = applyShellStreamThreadPatch(previous, event.patch); + if (patched !== previous) threads.set(patched); + } else { + threads.remove(id); + } + archivedThreads.remove(id); + break; + } case "thread.removed": threads.remove(event.threadId); archivedThreads.remove(event.threadId); @@ -259,14 +333,28 @@ export function applyShellStreamEvents( default: continue; } + if (missingPatchTarget) break; sequence = event.sequence; } - if (sequence === snapshot.snapshotSequence) return snapshot; + if (sequence === snapshot.snapshotSequence) { + return { snapshot, missingPatchTarget }; + } return { - ...snapshot, - snapshotSequence: sequence, - projects: projects.finish(), - threads: threads.finish(), - archivedThreads: archivedThreads.finish(), + snapshot: { + ...snapshot, + snapshotSequence: sequence, + projects: projects.finish(), + threads: threads.finish(), + archivedThreads: archivedThreads.finish(), + }, + missingPatchTarget, }; } + +/** Apply ordered deltas with one index and at most one new array per collection. */ +export function applyShellStreamEvents( + snapshot: OrchestrationV2ShellSnapshot, + events: ReadonlyArray, +): OrchestrationV2ShellSnapshot { + return applyShellStreamEventsWithStatus(snapshot, events).snapshot; +} diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.ts index e98846a0e3c73..bcb7864c154a9 100644 --- a/packages/client-runtime/src/state/shellSnapshotHttp.ts +++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts @@ -25,6 +25,8 @@ export interface ShellSnapshotOptions { readonly omitOlderSettled?: boolean; /** The cursor of held rows loaded with these omissions; the server may answer `resumable`. */ readonly resumeFrom?: number; + readonly compactShell?: boolean; + readonly compactIds?: boolean; } /** `projectIdentities` names the repository identities the snapshot carried. */ @@ -56,6 +58,8 @@ export const fetchEnvironmentShellSnapshot = Effect.fn( ...(input.omitIdleSubagents === true ? { omitIdleSubagents: "1" } : {}), ...(input.omitOlderSettled === true ? { omitOlderSettled: "1" } : {}), ...(input.resumeFrom === undefined ? {} : { resumeFrom: String(input.resumeFrom) }), + ...(input.compactShell === false ? {} : { compactShell: "1" }), + ...(input.compactIds === false ? {} : { compactIds: "1" }), }, }; return yield* executeAuthenticatedEnvironmentHttpRequest({ diff --git a/packages/client-runtime/src/state/threadFamilies.ts b/packages/client-runtime/src/state/threadFamilies.ts index 8adc131a954f1..548200f636cab 100644 --- a/packages/client-runtime/src/state/threadFamilies.ts +++ b/packages/client-runtime/src/state/threadFamilies.ts @@ -111,6 +111,8 @@ export function createThreadFamilyAtoms( if (config.shellThreadFamilies !== true) return EMPTY_FAMILY; return yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, { threadId: input.threadId, + compactShell: true, + compactIds: true, }); }), }); diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index fbbbfeab24045..a63ae18973779 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -746,6 +746,8 @@ export const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({ * `resumable` instead of a snapshot when the socket can replay from it. */ resumeFrom: Schema.optionalKey(Schema.String), + compactShell: Schema.optionalKey(Schema.String), + compactIds: Schema.optionalKey(Schema.String), }); export const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index de2020bc45705..059dd4caccd8e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1,5 +1,6 @@ import { OrchestrationMessageContext } from "./composerContext.ts"; import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; +import { withCompactShellWire } from "./orchestrationV2ShellWire.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -2613,6 +2614,84 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ }); export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type; +export const OrchestrationV2ThreadShellPatch = Schema.Struct({ + createdBy: Schema.optionalKey(OrchestrationV2ThreadShell.fields.createdBy), + creationSource: Schema.optionalKey(OrchestrationV2ThreadShell.fields.creationSource), + projectId: Schema.optionalKey(OrchestrationV2ThreadShell.fields.projectId), + title: Schema.optionalKey(OrchestrationV2ThreadShell.fields.title), + providerInstanceId: Schema.optionalKey(OrchestrationV2ThreadShell.fields.providerInstanceId), + modelSelection: Schema.optionalKey(OrchestrationV2ThreadShell.fields.modelSelection), + runtimeMode: Schema.optionalKey(OrchestrationV2ThreadShell.fields.runtimeMode), + interactionMode: Schema.optionalKey(OrchestrationV2ThreadShell.fields.interactionMode), + branch: Schema.optionalKey(OrchestrationV2ThreadShell.fields.branch), + worktreePath: Schema.optionalKey(OrchestrationV2ThreadShell.fields.worktreePath), + linkedPullRequest: OrchestrationV2ThreadShell.fields.linkedPullRequest, + pullRequests: OrchestrationV2ThreadShell.fields.pullRequests, + branchPullRequest: OrchestrationV2ThreadShell.fields.branchPullRequest, + issues: OrchestrationV2ThreadShell.fields.issues, + lineage: Schema.optionalKey(OrchestrationV2ThreadShell.fields.lineage), + forkedFrom: Schema.optionalKey(OrchestrationV2ThreadShell.fields.forkedFrom), + activeProviderThreadId: Schema.optionalKey( + OrchestrationV2ThreadShell.fields.activeProviderThreadId, + ), + historyOrigin: OrchestrationV2ThreadShell.fields.historyOrigin, + linkOrigin: OrchestrationV2ThreadShell.fields.linkOrigin, + delegatedFrom: OrchestrationV2ThreadShell.fields.delegatedFrom, + workflowRun: OrchestrationV2ThreadShell.fields.workflowRun, + handoff: OrchestrationV2ThreadShell.fields.handoff, + latestRunId: Schema.optionalKey(OrchestrationV2ThreadShell.fields.latestRunId), + latestRunRequestedAt: OrchestrationV2ThreadShell.fields.latestRunRequestedAt, + latestRunStartedAt: OrchestrationV2ThreadShell.fields.latestRunStartedAt, + latestRunCompletedAt: OrchestrationV2ThreadShell.fields.latestRunCompletedAt, + latestRunStopRequested: OrchestrationV2ThreadShell.fields.latestRunStopRequested, + latestRunBackgroundWake: OrchestrationV2ThreadShell.fields.latestRunBackgroundWake, + activeRunId: Schema.optionalKey(OrchestrationV2ThreadShell.fields.activeRunId), + activityRunStartedAt: OrchestrationV2ThreadShell.fields.activityRunStartedAt, + activityRunStatus: OrchestrationV2ThreadShell.fields.activityRunStatus, + blockedOnThreadWait: OrchestrationV2ThreadShell.fields.blockedOnThreadWait, + status: Schema.optionalKey(OrchestrationV2ThreadShell.fields.status), + lastError: OrchestrationV2ThreadShell.fields.lastError, + lastErrorClass: OrchestrationV2ThreadShell.fields.lastErrorClass, + lastErrorCode: OrchestrationV2ThreadShell.fields.lastErrorCode, + usageLimitResetAt: OrchestrationV2ThreadShell.fields.usageLimitResetAt, + pendingRuntimeRequest: Schema.optionalKey( + OrchestrationV2ThreadShell.fields.pendingRuntimeRequest, + ), + pendingGuestMessageCount: OrchestrationV2ThreadShell.fields.pendingGuestMessageCount, + latestVisibleMessage: Schema.optionalKey(OrchestrationV2ThreadShell.fields.latestVisibleMessage), + latestUserMessageAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.latestUserMessageAt), + latestUserAuthoredMessageAt: OrchestrationV2ThreadShell.fields.latestUserAuthoredMessageAt, + hasActionableProposedPlan: Schema.optionalKey( + OrchestrationV2ThreadShell.fields.hasActionableProposedPlan, + ), + pendingBackgroundTasks: Schema.optionalKey(Schema.Array(OrchestrationV2PendingBackgroundTask)), + providerInstanceHistory: Schema.optionalKey(Schema.Array(ProviderInstanceId)), + goal: OrchestrationV2ThreadShell.fields.goal, + itemCount: Schema.optionalKey(OrchestrationV2ThreadShell.fields.itemCount), + visibleItemCount: Schema.optionalKey(OrchestrationV2ThreadShell.fields.visibleItemCount), + createdAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.createdAt), + updatedAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.updatedAt), + archivedAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.archivedAt), + settledOverride: Schema.optionalKey(OrchestrationV2ThreadShell.fields.settledOverride), + settledAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.settledAt), + unsettledAt: OrchestrationV2ThreadShell.fields.unsettledAt, + snoozedUntil: OrchestrationV2ThreadShell.fields.snoozedUntil, + snoozedAt: OrchestrationV2ThreadShell.fields.snoozedAt, + limitRecovery: OrchestrationV2ThreadShell.fields.limitRecovery, + pinnedAt: OrchestrationV2ThreadShell.fields.pinnedAt, + autoSettleDisabledAt: OrchestrationV2ThreadShell.fields.autoSettleDisabledAt, + pinOrderKey: OrchestrationV2ThreadShell.fields.pinOrderKey, + activeOrderKey: OrchestrationV2ThreadShell.fields.activeOrderKey, + tags: OrchestrationV2ThreadShell.fields.tags, + toolOverrides: OrchestrationV2ThreadShell.fields.toolOverrides, + lastVisitedAt: OrchestrationV2ThreadShell.fields.lastVisitedAt, + opens: OrchestrationV2ThreadShell.fields.opens, + titleRegeneration: OrchestrationV2ThreadShell.fields.titleRegeneration, + lastTitleRegeneration: OrchestrationV2ThreadShell.fields.lastTitleRegeneration, + deletedAt: Schema.optionalKey(OrchestrationV2ThreadShell.fields.deletedAt), +} satisfies Record, unknown>); +export type OrchestrationV2ThreadShellPatch = typeof OrchestrationV2ThreadShellPatch.Type; + const LIVE_SHELL_STATUSES: ReadonlySet = new Set([ "queued", "preparing", @@ -2694,11 +2773,27 @@ export const OrchestrationV2ShellSnapshot = Schema.Struct({ }); export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type; +/** + * Server-side only: set it on a response for a client that opted in, and the + * `withRecordIdTable` / `withCompactShellWire` codecs emit the compact wire form. + */ +const IdTableMarker = Schema.optionalKey(Schema.Literal(true)); +const CompactShellMarker = Schema.optionalKey(Schema.Literal(true)); + /** The HTTP shell snapshot. `projectIdentities` names its repository identities; see `knownProjectIdentities`. */ -export const OrchestrationV2ShellHttpSnapshot = Schema.Struct({ - ...OrchestrationV2ShellSnapshot.fields, - projectIdentities: Schema.optionalKey(Schema.String), -}); +export const OrchestrationV2ShellHttpSnapshot = withCompactShellWire( + Schema.Struct({ + ...OrchestrationV2ShellSnapshot.fields, + projectIdentities: Schema.optionalKey(Schema.String), + compactShell: CompactShellMarker, + idTable: IdTableMarker, + }), + () => ({ + kind: "snapshot", + key: null, + emptyArrays: ["projects", "threads", "archivedThreads"], + }), +); export type OrchestrationV2ShellHttpSnapshot = typeof OrchestrationV2ShellHttpSnapshot.Type; /** @@ -2710,45 +2805,78 @@ export const OrchestrationV2ShellResumable = Schema.Struct({ }); export type OrchestrationV2ShellResumable = typeof OrchestrationV2ShellResumable.Type; -export const OrchestrationV2ShellStreamItem = Schema.Union([ - Schema.Struct({ - kind: Schema.Literal("synchronized"), - }), - /** - * The only item of a resume the server cannot replay when the client asked for - * `httpSnapshotFallback`: load the HTTP snapshot and subscribe again from its cursor. - */ - Schema.Struct({ - kind: Schema.Literal("snapshot-required"), - }), - Schema.Struct({ - kind: Schema.Literal("snapshot"), - snapshot: OrchestrationV2ShellSnapshot, - resolvedRepositoryIdentityRoots: Schema.optionalKey(Schema.Array(Schema.String)), - }), - Schema.Struct({ - kind: Schema.Literal("project.updated"), - sequence: NonNegativeInt, - project: OrchestrationProjectShell, - }), - Schema.Struct({ - kind: Schema.Literal("project.removed"), - sequence: NonNegativeInt, - projectId: ProjectId, - }), - Schema.Struct({ - kind: Schema.Literal("thread.updated"), - sequence: NonNegativeInt, - location: Schema.Literals(["active", "archive"]), - thread: OrchestrationV2ThreadShell, - }), - Schema.Struct({ - kind: Schema.Literal("thread.removed"), - sequence: NonNegativeInt, - location: Schema.Literals(["active", "archive"]), - threadId: ThreadId, - }), -]); +export const OrchestrationV2ShellStreamItem = withCompactShellWire( + Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("synchronized"), + }), + /** + * The only item of a resume the server cannot replay when the client asked for + * `httpSnapshotFallback`: load the HTTP snapshot and subscribe again from its cursor. + */ + Schema.Struct({ + kind: Schema.Literal("snapshot-required"), + }), + Schema.Struct({ + kind: Schema.Literal("cursor"), + sequence: NonNegativeInt, + }), + Schema.Struct({ + kind: Schema.Literal("snapshot"), + snapshot: OrchestrationV2ShellSnapshot, + resolvedRepositoryIdentityRoots: Schema.optionalKey(Schema.Array(Schema.String)), + compactShell: CompactShellMarker, + idTable: IdTableMarker, + }), + Schema.Struct({ + kind: Schema.Literal("project.updated"), + sequence: NonNegativeInt, + project: OrchestrationProjectShell, + compactShell: CompactShellMarker, + }), + Schema.Struct({ + kind: Schema.Literal("project.removed"), + sequence: NonNegativeInt, + projectId: ProjectId, + }), + Schema.Struct({ + kind: Schema.Literal("thread.updated"), + sequence: NonNegativeInt, + location: Schema.Literals(["active", "archive"]), + thread: OrchestrationV2ThreadShell, + compactShell: CompactShellMarker, + }), + Schema.Struct({ + kind: Schema.Literal("thread.patched"), + sequence: NonNegativeInt, + location: Schema.Literals(["active", "archive"]), + threadId: ThreadId, + patch: OrchestrationV2ThreadShellPatch, + }), + Schema.Struct({ + kind: Schema.Literal("thread.removed"), + sequence: NonNegativeInt, + location: Schema.Literals(["active", "archive"]), + threadId: ThreadId, + }), + ]), + (item) => { + switch (item.kind) { + case "snapshot": + return { + kind: "snapshot", + key: "snapshot", + emptyArrays: ["projects", "threads", "archivedThreads"], + }; + case "thread.updated": + return { kind: "thread", key: "thread" }; + case "project.updated": + return { kind: "project", key: "project" }; + default: + return undefined; + } + }, +); export type OrchestrationV2ShellStreamItem = typeof OrchestrationV2ShellStreamItem.Type; export const OrchestrationV2StoredEvent = Schema.Struct({ @@ -4354,12 +4482,28 @@ export const OrchestrationV2PromptSuggestion = Schema.NullOr( ); export type OrchestrationV2PromptSuggestion = typeof OrchestrationV2PromptSuggestion.Type; -export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({ - schemaVersion: PositiveInt, - snapshotSequence: NonNegativeInt, - projects: Schema.Array(OrchestrationProjectShell), - threads: Schema.Array(OrchestrationV2ThreadShell), +export const OrchestrationV2GetArchivedShellSnapshotInput = Schema.Struct({ + compactShell: Schema.optionalKey(Schema.Boolean), + compactIds: Schema.optionalKey(Schema.Boolean), }); +export type OrchestrationV2GetArchivedShellSnapshotInput = + typeof OrchestrationV2GetArchivedShellSnapshotInput.Type; + +export const OrchestrationV2ArchivedShellSnapshot = withCompactShellWire( + Schema.Struct({ + schemaVersion: PositiveInt, + snapshotSequence: NonNegativeInt, + projects: Schema.Array(OrchestrationProjectShell), + threads: Schema.Array(OrchestrationV2ThreadShell), + compactShell: CompactShellMarker, + idTable: IdTableMarker, + }), + () => ({ + kind: "snapshot", + key: null, + emptyArrays: ["projects", "threads"], + }), +); export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2ArchivedShellSnapshot.Type; export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ @@ -4428,11 +4572,19 @@ export const OrchestrationV2SubscribeShellInput = Schema.Struct({ * `getOlderSettledThreads`. Send only to servers that advertise `shellOlderSettled`. */ omitOlderSettled: Schema.optionalKey(Schema.Boolean), + /** Encodes shell rows without default/derived fields on snapshots and thread/project updates. */ + compactShell: Schema.optionalKey(Schema.Boolean), + /** Interns repeated shell IDs, paths, and model identifiers in snapshot responses. */ + compactIds: Schema.optionalKey(Schema.Boolean), + /** Accepts `cursor` sequence heartbeats and sparse `thread.patched` deltas on the stream. */ + acceptShellDeltas: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2SubscribeShellInput = typeof OrchestrationV2SubscribeShellInput.Type; export const OrchestrationV2GetThreadFamilyInput = Schema.Struct({ threadId: ThreadId, + compactShell: Schema.optionalKey(Schema.Boolean), + compactIds: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2GetThreadFamilyInput = typeof OrchestrationV2GetThreadFamilyInput.Type; @@ -4441,10 +4593,19 @@ export type OrchestrationV2GetThreadFamilyInput = typeof OrchestrationV2GetThrea * forks, and their whole subagent trees, in any run state. An unknown thread has an empty family; * a deleted one still names its root. */ -export const OrchestrationV2ThreadFamily = Schema.Struct({ - snapshotSequence: NonNegativeInt, - threads: Schema.Array(OrchestrationV2ThreadShell), -}); +export const OrchestrationV2ThreadFamily = withCompactShellWire( + Schema.Struct({ + snapshotSequence: NonNegativeInt, + threads: Schema.Array(OrchestrationV2ThreadShell), + compactShell: CompactShellMarker, + idTable: IdTableMarker, + }), + () => ({ + kind: "snapshot", + key: null, + emptyArrays: ["threads"], + }), +); export type OrchestrationV2ThreadFamily = typeof OrchestrationV2ThreadFamily.Type; export const OrchestrationV2GetThreadTitlesInput = Schema.Struct({ @@ -4503,6 +4664,8 @@ export const OrchestrationV2GetOlderSettledThreadsInput = Schema.Struct({ projectIds: Schema.optionalKey(Schema.Array(ProjectId)), /** 0 reads only the counts. */ limit: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 50 })), + compactShell: Schema.optionalKey(Schema.Boolean), + compactIds: Schema.optionalKey(Schema.Boolean), }); export type OrchestrationV2GetOlderSettledThreadsInput = typeof OrchestrationV2GetOlderSettledThreadsInput.Type; @@ -4512,11 +4675,20 @@ export type OrchestrationV2GetOlderSettledThreadsInput = * `limit: 0` read fills `counts` instead: the older settled threads below the cursor per project, * as `OrchestrationV2OlderSettledThreads.counts` count them. A cursor without an id is strict. */ -export const OrchestrationV2OlderSettledThreadsPage = Schema.Struct({ - snapshotSequence: NonNegativeInt, - threads: Schema.Array(OrchestrationV2ThreadShell), - counts: Schema.Array(OrchestrationV2OlderSettledCount), -}); +export const OrchestrationV2OlderSettledThreadsPage = withCompactShellWire( + Schema.Struct({ + snapshotSequence: NonNegativeInt, + threads: Schema.Array(OrchestrationV2ThreadShell), + counts: Schema.Array(OrchestrationV2OlderSettledCount), + compactShell: CompactShellMarker, + idTable: IdTableMarker, + }), + () => ({ + kind: "snapshot", + key: null, + emptyArrays: ["threads", "counts"], + }), +); export type OrchestrationV2OlderSettledThreadsPage = typeof OrchestrationV2OlderSettledThreadsPage.Type; @@ -4539,12 +4711,6 @@ export const OrchestrationV2SubscribeThreadInput = Schema.Struct({ }); export type OrchestrationV2SubscribeThreadInput = typeof OrchestrationV2SubscribeThreadInput.Type; -/** - * Server-side only: set it on a response for a client that opted in, and the - * `withRecordIdTable` codec sends that response with an ID table. - */ -const IdTableMarker = Schema.optionalKey(Schema.Literal(true)); - export const OrchestrationV2ThreadDetailSnapshot = Schema.Struct({ snapshotSequence: NonNegativeInt, projection: OrchestrationV2ThreadProjection, @@ -4982,7 +5148,7 @@ export const OrchestrationV2RpcSchemas = { output: OrchestrationGetFullThreadDiffResult, }, getArchivedShellSnapshot: { - input: Schema.Struct({}), + input: OrchestrationV2GetArchivedShellSnapshotInput, output: OrchestrationV2ArchivedShellSnapshot, }, getThreadFamily: { diff --git a/packages/contracts/src/orchestrationV2ShellWire.test.ts b/packages/contracts/src/orchestrationV2ShellWire.test.ts new file mode 100644 index 0000000000000..9c23a65f5f195 --- /dev/null +++ b/packages/contracts/src/orchestrationV2ShellWire.test.ts @@ -0,0 +1,501 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; + +import { ProjectId, RunId, ThreadId } from "./baseSchemas.ts"; +import { OrchestrationProjectShell } from "./orchestrationProject.ts"; +import { + OrchestrationV2ArchivedShellSnapshot, + OrchestrationV2GetArchivedShellSnapshotInput, + OrchestrationV2OlderSettledThreadsPage, + OrchestrationV2ShellHttpSnapshot, + OrchestrationV2ShellStreamItem, + OrchestrationV2ThreadFamily, + OrchestrationV2ThreadShell, + OrchestrationV2ThreadShellPatch, +} from "./orchestrationV2.ts"; +import { PROJECT_SHELL_WIRE_POLICY, THREAD_SHELL_WIRE_POLICY } from "./orchestrationV2ShellWire.ts"; +import { ProviderInstanceId } from "./providerInstance.ts"; + +const encodeHttp = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot)); +const decodeHttp = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot)); +const encodeStreamItem = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ShellStreamItem)); +const decodeStreamItem = Schema.decodeUnknownSync( + Schema.toCodecJson(OrchestrationV2ShellStreamItem), +); +const encodeArchived = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ArchivedShellSnapshot)); +const decodeArchived = Schema.decodeUnknownSync( + Schema.toCodecJson(OrchestrationV2ArchivedShellSnapshot), +); +const encodeFamily = Schema.encodeSync(Schema.toCodecJson(OrchestrationV2ThreadFamily)); +const decodeFamily = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2ThreadFamily)); +const encodeOlderPage = Schema.encodeSync( + Schema.toCodecJson(OrchestrationV2OlderSettledThreadsPage), +); +const decodeOlderPage = Schema.decodeUnknownSync( + Schema.toCodecJson(OrchestrationV2OlderSettledThreadsPage), +); +const decodePatch = Schema.decodeUnknownSync(Schema.toCodecJson(OrchestrationV2ThreadShellPatch)); +const decodeArchivedInput = Schema.decodeUnknownSync(OrchestrationV2GetArchivedShellSnapshotInput); + +const t0 = DateTime.makeUnsafe("2026-10-01T00:00:00.000Z"); +const t1 = DateTime.makeUnsafe("2026-10-02T12:30:00.000Z"); +const projectA = ProjectId.make("project:alpha-workspace"); +const projectB = ProjectId.make("project:beta-workspace"); +const codexInstance = ProviderInstanceId.make("codex-default-instance"); +const claudeInstance = ProviderInstanceId.make("claudeAgent-default-instance"); + +function makeProjectShell( + id: ProjectId, + overrides: Partial = {}, +): OrchestrationProjectShell { + return { + id, + title: "Project", + workspaceRoot: "/Users/dev/workspaces/monorepo-project", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-10-01T00:00:00.000Z", + updatedAt: "2026-10-01T00:00:00.000Z", + ...overrides, + }; +} + +function makeFullThreadShell( + id: string, + overrides: Partial = {}, +): OrchestrationV2ThreadShell { + const threadId = ThreadId.make(id); + return { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: projectA, + title: `Thread ${id}`, + providerInstanceId: codexInstance, + modelSelection: { instanceId: codexInstance, model: "gpt-5.4-codex" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + pullRequests: [], + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + activeProviderThreadId: null, + latestRunId: null, + latestRunRequestedAt: null, + latestRunStartedAt: null, + latestRunCompletedAt: null, + latestRunStopRequested: false, + latestRunBackgroundWake: false, + activeRunId: null, + activityRunStartedAt: null, + activityRunStatus: null, + blockedOnThreadWait: false, + status: "idle", + lastError: null, + lastErrorClass: null, + lastErrorCode: null, + usageLimitResetAt: null, + pendingRuntimeRequest: null, + pendingGuestMessageCount: 0, + latestVisibleMessage: null, + latestUserMessageAt: null, + latestUserAuthoredMessageAt: null, + hasActionableProposedPlan: false, + pendingBackgroundTasks: [], + providerInstanceHistory: [], + goal: null, + itemCount: 0, + visibleItemCount: 0, + createdAt: t0, + updatedAt: t0, + archivedAt: null, + settledOverride: null, + settledAt: null, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + limitRecovery: null, + pinnedAt: null, + autoSettleDisabledAt: null, + pinOrderKey: null, + lastVisitedAt: null, + opens: null, + titleRegeneration: null, + lastTitleRegeneration: null, + deletedAt: null, + ...overrides, + }; +} + +describe("compact shell wire codec", () => { + it("compacts and interns a 27-thread HTTP shell snapshot with >=65% byte savings and exact parity", () => { + const parentId = ThreadId.make("thread:root-active"); + const richSubagent = makeFullThreadShell("thread:subagent-rich", { + projectId: projectB, + createdBy: "agent", + creationSource: "mcp", + providerInstanceId: claudeInstance, + modelSelection: { instanceId: codexInstance, model: "gpt-5.4-codex" }, + runtimeMode: "approval-required", + interactionMode: "plan", + branch: "feature/compact-shell", + worktreePath: "/Users/dev/worktrees/compact-shell", + pullRequests: [ + { + host: "github.com", + repository: "pingdotgg/t3code", + number: 42, + url: "https://github.com/pingdotgg/t3code/pull/42", + source: "agent", + linkedAt: "2026-10-02T00:00:00.000Z", + snapshot: null, + stack: null, + }, + ], + lineage: { + parentThreadId: parentId, + relationshipToParent: "subagent", + rootThreadId: parentId, + }, + latestRunId: RunId.make("run:latest-1"), + activeRunId: RunId.make("run:latest-1"), + status: "running", + activityRunStatus: "running", + activityRunStartedAt: t1, + latestRunStopRequested: true, + blockedOnThreadWait: true, + pendingGuestMessageCount: 2, + hasActionableProposedPlan: true, + providerInstanceHistory: [codexInstance, claudeInstance], + itemCount: 12, + visibleItemCount: 18, + updatedAt: t1, + pinnedAt: t1, + lastVisitedAt: t1, + }); + const settledThreads = Array.from({ length: 25 }, (_, index) => { + const settledAt = DateTime.makeUnsafe(DateTime.toEpochMillis(t0) + (index + 1) * 60_000); + return makeFullThreadShell(`thread:settled-${String(index).padStart(2, "0")}`, { + status: "completed", + itemCount: 8, + visibleItemCount: 8, + settledOverride: "settled", + settledAt, + updatedAt: settledAt, + }); + }); + const snapshot: OrchestrationV2ShellHttpSnapshot = { + schemaVersion: 1, + snapshotSequence: 420, + projects: [ + makeProjectShell(projectA), + makeProjectShell(projectB, { + title: "Beta", + workspaceRoot: "/Users/dev/workspaces/beta-project", + defaultModelSelection: { instanceId: codexInstance, model: "gpt-5.4-codex" }, + updatedAt: "2026-10-02T00:00:00.000Z", + }), + ], + threads: [makeFullThreadShell(parentId), richSubagent, ...settledThreads], + archivedThreads: [], + olderSettled: { + before: "2026-10-01T00:01:00.000Z", + asOfSequence: 420, + counts: [{ projectId: projectA, count: 80 }], + }, + projectIdentities: "digest-abc", + }; + + const plainJson = JSON.stringify(encodeHttp(snapshot)); + const compactWire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true, idTable: true })), + ) as Record; + const compactJson = JSON.stringify(compactWire); + + expect(compactWire.compactShell).toBe(true); + expect(Array.isArray(compactWire.ids)).toBe(true); + expect(compactWire.archivedThreads).toBeUndefined(); + expect(compactJson.length).toBeLessThanOrEqual(plainJson.length * 0.35); + + const decoded = decodeHttp(compactWire); + expect(decoded).toEqual(snapshot); + expect(decodeHttp(compactWire)).toEqual(snapshot); + + const plainParsed = JSON.parse(plainJson) as Record; + expect(plainParsed.compactShell).toBeUndefined(); + expect(plainParsed.ids).toBeUndefined(); + expect(decodeHttp(plainParsed)).toEqual(snapshot); + }); + + it("round-trips shell stream items and keeps thread.patched sparse without array defaults", () => { + const thread = makeFullThreadShell("thread:stream-1", { + itemCount: 4, + visibleItemCount: 4, + updatedAt: t1, + }); + const project = makeProjectShell(projectA); + + const streamSnapshot = { + kind: "snapshot", + snapshot: { + schemaVersion: 1, + snapshotSequence: 12, + projects: [project], + threads: [thread, makeFullThreadShell("thread:stream-2")], + archivedThreads: [], + }, + } as const satisfies OrchestrationV2ShellStreamItem; + const encodedSnapshot = JSON.parse( + JSON.stringify(encodeStreamItem({ ...streamSnapshot, compactShell: true, idTable: true })), + ); + expect(decodeStreamItem(encodedSnapshot)).toEqual(streamSnapshot); + + const threadUpdated = { + kind: "thread.updated", + sequence: 13, + location: "active", + thread, + } as const satisfies OrchestrationV2ShellStreamItem; + const plainUpdated = JSON.stringify(encodeStreamItem(threadUpdated)); + const compactUpdated = JSON.parse( + JSON.stringify(encodeStreamItem({ ...threadUpdated, compactShell: true })), + ); + expect(JSON.stringify(compactUpdated).length).toBeLessThan(plainUpdated.length * 0.45); + expect(decodeStreamItem(compactUpdated)).toEqual(threadUpdated); + + const projectUpdated = { + kind: "project.updated", + sequence: 14, + project, + } as const satisfies OrchestrationV2ShellStreamItem; + const compactProject = JSON.parse( + JSON.stringify(encodeStreamItem({ ...projectUpdated, compactShell: true })), + ); + expect(decodeStreamItem(compactProject)).toEqual(projectUpdated); + + const cursor = { + kind: "cursor", + sequence: 15, + } as const satisfies OrchestrationV2ShellStreamItem; + const cursorWire = JSON.parse(JSON.stringify(encodeStreamItem(cursor))); + expect(JSON.stringify(cursorWire).length).toBeLessThan(50); + expect(decodeStreamItem(cursorWire)).toEqual(cursor); + + const patched = { + kind: "thread.patched", + sequence: 16, + location: "active", + threadId: thread.id, + patch: { + itemCount: 5, + visibleItemCount: 5, + updatedAt: t1, + }, + } as const satisfies OrchestrationV2ShellStreamItem; + const patchedWire = JSON.parse(JSON.stringify(encodeStreamItem(patched))); + const decodedPatched = decodeStreamItem(patchedWire); + expect(decodedPatched).toEqual(patched); + if (decodedPatched.kind === "thread.patched") { + expect("pendingBackgroundTasks" in decodedPatched.patch).toBe(false); + expect("providerInstanceHistory" in decodedPatched.patch).toBe(false); + } + + const decodedDirectPatch = decodePatch({ title: "Renamed" }); + expect(decodedDirectPatch).toEqual({ title: "Renamed" }); + expect("pendingBackgroundTasks" in decodedDirectPatch).toBe(false); + expect("providerInstanceHistory" in decodedDirectPatch).toBe(false); + }); + + it("round-trips archived snapshots, thread families, and older settled pages including empty arrays", () => { + const thread = makeFullThreadShell("thread:other"); + const archived = { + schemaVersion: 1, + snapshotSequence: 9, + projects: [makeProjectShell(projectA)], + threads: [thread], + }; + expect( + decodeArchived( + JSON.parse( + JSON.stringify(encodeArchived({ ...archived, compactShell: true, idTable: true })), + ), + ), + ).toEqual(archived); + const emptyArchived = { schemaVersion: 1, snapshotSequence: 9, projects: [], threads: [] }; + const emptyArchivedWire = JSON.parse( + JSON.stringify(encodeArchived({ ...emptyArchived, compactShell: true, idTable: true })), + ) as Record; + expect(emptyArchivedWire.projects).toBeUndefined(); + expect(emptyArchivedWire.threads).toBeUndefined(); + expect(decodeArchived(emptyArchivedWire)).toEqual(emptyArchived); + + const family = { snapshotSequence: 9, threads: [thread, makeFullThreadShell("thread:child")] }; + expect( + decodeFamily( + JSON.parse(JSON.stringify(encodeFamily({ ...family, compactShell: true, idTable: true }))), + ), + ).toEqual(family); + const emptyFamily = { snapshotSequence: 9, threads: [] }; + expect( + decodeFamily( + JSON.parse(JSON.stringify(encodeFamily({ ...emptyFamily, compactShell: true }))), + ), + ).toEqual(emptyFamily); + + const olderPage = { + snapshotSequence: 9, + threads: [thread], + counts: [{ projectId: projectA, count: 3 }], + }; + expect( + decodeOlderPage( + JSON.parse( + JSON.stringify(encodeOlderPage({ ...olderPage, compactShell: true, idTable: true })), + ), + ), + ).toEqual(olderPage); + const emptyOlderPage = { snapshotSequence: 9, threads: [], counts: [] }; + expect( + decodeOlderPage( + JSON.parse(JSON.stringify(encodeOlderPage({ ...emptyOlderPage, compactShell: true }))), + ), + ).toEqual(emptyOlderPage); + + expect(decodeArchivedInput({})).toEqual({}); + expect(decodeArchivedInput({ compactShell: true, compactIds: true })).toEqual({ + compactShell: true, + compactIds: true, + }); + }); + + it("rejects out-of-bounds idTable indices", () => { + const snapshot: OrchestrationV2ShellHttpSnapshot = { + schemaVersion: 1, + snapshotSequence: 1, + projects: [makeProjectShell(projectA)], + threads: [makeFullThreadShell("thread:a"), makeFullThreadShell("thread:b")], + archivedThreads: [], + }; + const wire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true, idTable: true })), + ) as { threads: Array>; ids: Array }; + wire.threads[0]!.projectId = wire.ids.length + 5; + + expect(() => decodeHttp(wire)).toThrow(); + }); + + it("keeps wire policy maps and thread patch fields exhaustive against shell schemas", () => { + const threadSchemaKeys = Object.keys(OrchestrationV2ThreadShell.fields).toSorted(); + expect(Object.keys(THREAD_SHELL_WIRE_POLICY).toSorted()).toEqual(threadSchemaKeys); + expect(Object.keys(OrchestrationV2ThreadShellPatch.fields).toSorted()).toEqual( + threadSchemaKeys.filter((key) => key !== "id"), + ); + expect(Object.keys(PROJECT_SHELL_WIRE_POLICY).toSorted()).toEqual( + Object.keys(OrchestrationProjectShell.fields).toSorted(), + ); + + // Expanding a minimal compact wire payload must satisfy the full schemas and re-compact cleanly. + const minimalWire = { + schemaVersion: 1, + snapshotSequence: 1, + compactShell: true, + projects: [ + { + id: projectA, + title: "Minimal", + workspaceRoot: "/workspace/minimal", + createdAt: "2026-10-01T00:00:00.000Z", + }, + ], + threads: [ + { + id: ThreadId.make("thread:minimal"), + projectId: projectA, + title: "Minimal thread", + modelSelection: { instanceId: codexInstance, model: "gpt-5.4-codex" }, + createdAt: "2026-10-01T00:00:00.000Z", + }, + ], + }; + const decoded = decodeHttp(minimalWire); + expect(decoded.projects[0]?.defaultModelSelection).toBeNull(); + expect(decoded.projects[0]?.scripts).toEqual([]); + expect(decoded.projects[0]?.updatedAt).toBe("2026-10-01T00:00:00.000Z"); + expect(decoded.threads[0]?.providerInstanceId).toBe(codexInstance); + expect(decoded.threads[0]?.lineage).toEqual({ + parentThreadId: null, + relationshipToParent: null, + rootThreadId: ThreadId.make("thread:minimal"), + }); + const reencoded = JSON.parse( + JSON.stringify(encodeHttp({ ...decoded, compactShell: true })), + ) as { + readonly projects: ReadonlyArray>; + readonly threads: ReadonlyArray>; + }; + expect(Object.keys(reencoded.projects[0]!).toSorted()).toEqual([ + "createdAt", + "id", + "title", + "workspaceRoot", + ]); + expect(Object.keys(reencoded.threads[0]!).toSorted()).toEqual([ + "createdAt", + "id", + "modelSelection", + "projectId", + "title", + ]); + }); + + it("preserves optional lineage flags and rejects unknown compactShell versions or non-string ids", () => { + const sideChatThread = makeFullThreadShell("thread:side-chat", { + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: ThreadId.make("thread:side-chat"), + sideChat: true, + }, + }); + const workflowThread = makeFullThreadShell("thread:workflow-step", { + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: ThreadId.make("thread:workflow-step"), + workflowStep: true, + }, + }); + const snapshot: OrchestrationV2ShellHttpSnapshot = { + schemaVersion: 1, + snapshotSequence: 3, + projects: [makeProjectShell(projectA)], + threads: [sideChatThread, workflowThread], + archivedThreads: [], + }; + const wire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true, idTable: true })), + ) as Record; + expect(decodeHttp(wire)).toEqual(snapshot); + + // Unsupported future compactShell marker must fail schema decoding rather than silently mis-expanding. + const futureWire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true })), + ) as Record; + futureWire.compactShell = 2; + expect(() => decodeHttp(futureWire)).toThrow(); + + // Non-string entries in ids must not resolve into string fields. + const badIdsWire = JSON.parse( + JSON.stringify(encodeHttp({ ...snapshot, compactShell: true, idTable: true })), + ) as { ids: Array }; + badIdsWire.ids[0] = 999; + expect(() => decodeHttp(badIdsWire)).toThrow(); + }); +}); diff --git a/packages/contracts/src/orchestrationV2ShellWire.ts b/packages/contracts/src/orchestrationV2ShellWire.ts new file mode 100644 index 0000000000000..272bce88bc703 --- /dev/null +++ b/packages/contracts/src/orchestrationV2ShellWire.ts @@ -0,0 +1,650 @@ +import * as Schema from "effect/Schema"; +import * as SchemaGetter from "effect/SchemaGetter"; + +import type { OrchestrationProjectShell } from "./orchestrationProject.ts"; +import type { + OrchestrationV2AppThreadLineage, + OrchestrationV2ThreadShell, +} from "./orchestrationV2.ts"; + +/** + * Opt-in v1 shell wire compaction: omits documented default/derived fields and interns repeated + * strings in `ids`. Changing an existing field's rule needs a new opt-in (`compactShell=2` / WS flag). + */ +type JsonObject = { [key: string]: unknown }; + +type ThreadShellEncoded = typeof OrchestrationV2ThreadShell.Encoded; +type ProjectShellEncoded = typeof OrchestrationProjectShell.Encoded; +type ThreadLineageEncoded = typeof OrchestrationV2AppThreadLineage.Encoded; + +type ScalarDefault = string | number | boolean; +type ThreadShellDerivedKey = "providerInstanceId" | "visibleItemCount" | "updatedAt" | "lineage"; +type ProjectShellDerivedKey = "updatedAt"; + +type ShellFieldPolicy = + | "keep" + | (null extends V ? "null" : never) + | (readonly [] extends V ? "empty-array" : never) + | (Extract extends never + ? never + : { readonly default: Extract }) + | (Derived extends true ? "derived" : never); + +type ShellWirePolicy = { + readonly [K in keyof T]-?: ShellFieldPolicy; +}; + +type StringFieldKey = { + readonly [K in keyof T]-?: string extends Extract ? K : never; +}[keyof T]; + +type ShellWireTarget = + | { + readonly kind: "snapshot"; + readonly key: string | null; + readonly emptyArrays: ReadonlyArray; + } + | { readonly kind: "thread"; readonly key: string } + | { readonly kind: "project"; readonly key: string }; + +const isObject = (value: unknown): value is JsonObject => + typeof value === "object" && value !== null && !Array.isArray(value); + +// Exhaustive against OrchestrationV2ThreadShell.Encoded; matches ProjectionStore.shellFromState defaults. +export const THREAD_SHELL_WIRE_POLICY = { + createdBy: { default: "user" }, + creationSource: { default: "web" }, + id: "keep", + projectId: "keep", + title: "keep", + providerInstanceId: "derived", + modelSelection: "keep", + runtimeMode: { default: "full-access" }, + interactionMode: { default: "default" }, + branch: "null", + worktreePath: "null", + linkedPullRequest: "keep", + pullRequests: "empty-array", + branchPullRequest: "keep", + issues: "keep", + lineage: "derived", + forkedFrom: "null", + activeProviderThreadId: "null", + historyOrigin: "keep", + linkOrigin: "keep", + delegatedFrom: "keep", + workflowRun: "keep", + handoff: "keep", + latestRunId: "null", + latestRunRequestedAt: "null", + latestRunStartedAt: "null", + latestRunCompletedAt: "null", + latestRunStopRequested: { default: false }, + latestRunBackgroundWake: { default: false }, + activeRunId: "null", + activityRunStartedAt: "null", + activityRunStatus: "null", + blockedOnThreadWait: { default: false }, + status: { default: "idle" }, + lastError: "null", + lastErrorClass: "null", + lastErrorCode: "null", + usageLimitResetAt: "null", + pendingRuntimeRequest: "null", + pendingGuestMessageCount: { default: 0 }, + latestVisibleMessage: "null", + latestUserMessageAt: "null", + latestUserAuthoredMessageAt: "null", + hasActionableProposedPlan: { default: false }, + pendingBackgroundTasks: "empty-array", + providerInstanceHistory: "empty-array", + goal: "null", + itemCount: { default: 0 }, + visibleItemCount: "derived", + createdAt: "keep", + updatedAt: "derived", + archivedAt: "null", + settledOverride: "null", + settledAt: "null", + unsettledAt: "null", + snoozedUntil: "null", + snoozedAt: "null", + limitRecovery: "null", + pinnedAt: "null", + autoSettleDisabledAt: "null", + pinOrderKey: "null", + activeOrderKey: "keep", + tags: "keep", + toolOverrides: "keep", + lastVisitedAt: "null", + opens: "null", + titleRegeneration: "null", + lastTitleRegeneration: "null", + deletedAt: "null", +} as const satisfies ShellWirePolicy; + +export const PROJECT_SHELL_WIRE_POLICY = { + id: "keep", + title: "keep", + hasCustomTitle: "keep", + workspaceRoot: "keep", + repositoryIdentity: "keep", + defaultModelSelection: "null", + defaultThreadEnvMode: "keep", + autoPull: "keep", + faviconPath: "keep", + projectIcon: "keep", + scripts: "empty-array", + trackedFolders: "keep", + pinnedAt: "keep", + archivedAt: "keep", + createdAt: "keep", + updatedAt: "derived", +} as const satisfies ShellWirePolicy; + +type PolicyEntry = + | "keep" + | "null" + | "empty-array" + | "derived" + | { readonly default: ScalarDefault }; + +interface CompiledShellDefaults { + readonly nullKeys: ReadonlyArray; + readonly valueDefaults: ReadonlyArray; + readonly emptyArrayKeys: ReadonlyArray; +} + +function compilePolicyDefaults( + policy: Readonly>, +): CompiledShellDefaults { + const nullKeys: Array = []; + const valueDefaults: Array = []; + const emptyArrayKeys: Array = []; + for (const [key, entry] of Object.entries(policy)) { + if (entry === "null") { + nullKeys.push(key); + } else if (entry === "empty-array") { + emptyArrayKeys.push(key); + } else if (typeof entry === "object") { + valueDefaults.push([key, entry.default]); + } + } + return { nullKeys, valueDefaults, emptyArrayKeys }; +} + +const THREAD_SHELL_DEFAULTS = compilePolicyDefaults(THREAD_SHELL_WIRE_POLICY); +const PROJECT_SHELL_DEFAULTS = compilePolicyDefaults(PROJECT_SHELL_WIRE_POLICY); +const LINEAGE_NULL_KEYS: ReadonlyArray = [ + "parentThreadId", + "relationshipToParent", +]; + +function compactByDefaults(out: JsonObject, defaults: CompiledShellDefaults): void { + for (const key of defaults.nullKeys) { + if (out[key] === null) delete out[key]; + } + for (const [key, fallback] of defaults.valueDefaults) { + if (out[key] === fallback) delete out[key]; + } + for (const key of defaults.emptyArrayKeys) { + const value = out[key]; + if (Array.isArray(value) && value.length === 0) delete out[key]; + } +} + +function expandByDefaults(row: JsonObject, defaults: CompiledShellDefaults): void { + for (const key of defaults.nullKeys) { + if (!(key in row)) row[key] = null; + } + for (const [key, fallback] of defaults.valueDefaults) { + if (!(key in row)) row[key] = fallback; + } + for (const key of defaults.emptyArrayKeys) { + if (!(key in row)) row[key] = []; + } +} + +function compactThreadShell(row: JsonObject): JsonObject { + const out: JsonObject = { ...row }; + const itemCount = typeof row.itemCount === "number" ? row.itemCount : 0; + const updatedAtBaseline = typeof row.settledAt === "string" ? row.settledAt : row.createdAt; + + compactByDefaults(out, THREAD_SHELL_DEFAULTS); + if ( + isObject(out.modelSelection) && + typeof out.modelSelection.instanceId === "string" && + out.providerInstanceId === out.modelSelection.instanceId + ) { + delete out.providerInstanceId; + } + if (out.visibleItemCount === itemCount) { + delete out.visibleItemCount; + } + if (typeof updatedAtBaseline === "string" && out.updatedAt === updatedAtBaseline) { + delete out.updatedAt; + } + if (isObject(out.lineage)) { + const lineage: JsonObject = { ...out.lineage }; + for (const key of LINEAGE_NULL_KEYS) { + if (lineage[key] === null) delete lineage[key]; + } + if (lineage.rootThreadId === out.id) delete lineage.rootThreadId; + if (Object.keys(lineage).some((key) => lineage[key] !== undefined)) { + out.lineage = lineage; + } else { + delete out.lineage; + } + } + return out; +} + +function expandThreadShell(row: JsonObject): void { + expandByDefaults(row, THREAD_SHELL_DEFAULTS); + if ( + !("providerInstanceId" in row) && + isObject(row.modelSelection) && + typeof row.modelSelection.instanceId === "string" + ) { + row.providerInstanceId = row.modelSelection.instanceId; + } + if (!("visibleItemCount" in row) && typeof row.itemCount === "number") { + row.visibleItemCount = row.itemCount; + } + if (!("updatedAt" in row)) { + const baseline = typeof row.settledAt === "string" ? row.settledAt : row.createdAt; + if (typeof baseline === "string") row.updatedAt = baseline; + } + if (!("lineage" in row)) { + if (typeof row.id === "string") { + row.lineage = { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: row.id, + }; + } + } else if (isObject(row.lineage)) { + for (const key of LINEAGE_NULL_KEYS) { + if (!(key in row.lineage)) row.lineage[key] = null; + } + if (!("rootThreadId" in row.lineage) && typeof row.id === "string") { + row.lineage.rootThreadId = row.id; + } + } +} + +function compactProjectShell(row: JsonObject): JsonObject { + const out: JsonObject = { ...row }; + compactByDefaults(out, PROJECT_SHELL_DEFAULTS); + if (typeof out.createdAt === "string" && out.updatedAt === out.createdAt) { + delete out.updatedAt; + } + return out; +} + +function expandProjectShell(row: JsonObject): void { + expandByDefaults(row, PROJECT_SHELL_DEFAULTS); + if (!("updatedAt" in row) && typeof row.createdAt === "string") { + row.updatedAt = row.createdAt; + } +} + +function compactSnapshotContainer( + container: JsonObject, + emptyArrays: ReadonlyArray, +): JsonObject { + const out: JsonObject = { ...container }; + if (Array.isArray(out.projects)) { + out.projects = out.projects.map((project) => + isObject(project) ? compactProjectShell(project) : project, + ); + } + if (Array.isArray(out.threads)) { + out.threads = out.threads.map((thread) => + isObject(thread) ? compactThreadShell(thread) : thread, + ); + } + if (Array.isArray(out.archivedThreads)) { + out.archivedThreads = out.archivedThreads.map((thread) => + isObject(thread) ? compactThreadShell(thread) : thread, + ); + } + for (const key of emptyArrays) { + const value = out[key]; + if (Array.isArray(value) && value.length === 0) delete out[key]; + } + return out; +} + +function expandSnapshotContainer(container: JsonObject, emptyArrays: ReadonlyArray): void { + for (const key of emptyArrays) { + if (!(key in container)) container[key] = []; + } + if (Array.isArray(container.projects)) { + for (const project of container.projects) { + if (isObject(project)) expandProjectShell(project); + } + } + if (Array.isArray(container.threads)) { + for (const thread of container.threads) { + if (isObject(thread)) expandThreadShell(thread); + } + } + if (Array.isArray(container.archivedThreads)) { + for (const thread of container.archivedThreads) { + if (isObject(thread)) expandThreadShell(thread); + } + } +} + +const PROJECT_INTERN_KEYS: ReadonlyArray> = [ + "id", + "workspaceRoot", +]; +const THREAD_INTERN_KEYS: ReadonlyArray> = [ + "id", + "projectId", + "providerInstanceId", + "branch", + "worktreePath", + "activeProviderThreadId", + "latestRunId", + "activeRunId", +]; + +function collectStrings(container: JsonObject, counts: Map): void { + const observe = (value: unknown) => { + if (typeof value === "string" && value.length >= 2) { + counts.set(value, (counts.get(value) ?? 0) + 1); + } + }; + const observeModelSelection = (selection: unknown) => { + if (!isObject(selection)) return; + observe(selection.instanceId); + observe(selection.model); + }; + const observeProject = (project: JsonObject) => { + for (const key of PROJECT_INTERN_KEYS) observe(project[key]); + observeModelSelection(project.defaultModelSelection); + }; + const observeThread = (thread: JsonObject) => { + for (const key of THREAD_INTERN_KEYS) observe(thread[key]); + observeModelSelection(thread.modelSelection); + if (isObject(thread.lineage)) { + observe(thread.lineage.parentThreadId); + observe(thread.lineage.rootThreadId); + } + if (Array.isArray(thread.providerInstanceHistory)) { + for (const entry of thread.providerInstanceHistory) observe(entry); + } + }; + const observeCounts = (entries: unknown) => { + if (!Array.isArray(entries)) return; + for (const entry of entries) { + if (isObject(entry)) observe(entry.projectId); + } + }; + + if (Array.isArray(container.projects)) { + for (const project of container.projects) if (isObject(project)) observeProject(project); + } + if (Array.isArray(container.threads)) { + for (const thread of container.threads) if (isObject(thread)) observeThread(thread); + } + if (Array.isArray(container.archivedThreads)) { + for (const thread of container.archivedThreads) if (isObject(thread)) observeThread(thread); + } + if (isObject(container.olderSettled)) { + observeCounts(container.olderSettled.counts); + } + observeCounts(container.counts); +} + +function internSnapshotStrings(container: JsonObject): { + readonly container: JsonObject; + readonly ids: Array; +} { + const counts = new Map(); + collectStrings(container, counts); + + const ids: Array = []; + const index = new Map(); + const ref = (value: unknown) => { + if (typeof value !== "string" || (counts.get(value) ?? 0) < 2) return value; + let position = index.get(value); + if (position === undefined) { + position = ids.length; + ids.push(value); + index.set(value, position); + } + return position; + }; + const internModelSelection = (selection: unknown) => { + if (!isObject(selection)) return selection; + const instanceId = ref(selection.instanceId); + const model = ref(selection.model); + if (instanceId === selection.instanceId && model === selection.model) return selection; + return { ...selection, instanceId, model }; + }; + const internProject = (project: JsonObject): JsonObject => { + const out: JsonObject = { ...project }; + for (const key of PROJECT_INTERN_KEYS) { + if (key in out) out[key] = ref(out[key]); + } + if ("defaultModelSelection" in out) { + out.defaultModelSelection = internModelSelection(out.defaultModelSelection); + } + return out; + }; + const internThread = (thread: JsonObject): JsonObject => { + const out: JsonObject = { ...thread }; + for (const key of THREAD_INTERN_KEYS) { + if (key in out) out[key] = ref(out[key]); + } + if ("modelSelection" in out) { + out.modelSelection = internModelSelection(out.modelSelection); + } + if (isObject(out.lineage)) { + const lineage: JsonObject = { ...out.lineage }; + if ("parentThreadId" in lineage) lineage.parentThreadId = ref(lineage.parentThreadId); + if ("rootThreadId" in lineage) lineage.rootThreadId = ref(lineage.rootThreadId); + out.lineage = lineage; + } + if (Array.isArray(out.providerInstanceHistory)) { + out.providerInstanceHistory = out.providerInstanceHistory.map(ref); + } + return out; + }; + const internCounts = (entries: ReadonlyArray) => + entries.map((entry) => + isObject(entry) && "projectId" in entry + ? { ...entry, projectId: ref(entry.projectId) } + : entry, + ); + + const out: JsonObject = { ...container }; + if (Array.isArray(out.projects)) { + out.projects = out.projects.map((project) => + isObject(project) ? internProject(project) : project, + ); + } + if (Array.isArray(out.threads)) { + out.threads = out.threads.map((thread) => (isObject(thread) ? internThread(thread) : thread)); + } + if (Array.isArray(out.archivedThreads)) { + out.archivedThreads = out.archivedThreads.map((thread) => + isObject(thread) ? internThread(thread) : thread, + ); + } + if (isObject(out.olderSettled) && Array.isArray(out.olderSettled.counts)) { + out.olderSettled = { + ...out.olderSettled, + counts: internCounts(out.olderSettled.counts), + }; + } + if (Array.isArray(out.counts)) { + out.counts = internCounts(out.counts); + } + return { container: out, ids }; +} + +function expandSnapshotStrings(container: JsonObject, ids: ReadonlyArray): void { + const resolve = (value: unknown): unknown => { + if (typeof value !== "number") return value; + return Number.isInteger(value) && + value >= 0 && + value < ids.length && + typeof ids[value] === "string" + ? ids[value] + : value; + }; + const expandModelSelection = (selection: unknown) => { + if (!isObject(selection)) return; + if ("instanceId" in selection) selection.instanceId = resolve(selection.instanceId); + if ("model" in selection) selection.model = resolve(selection.model); + }; + const expandProject = (project: JsonObject) => { + for (const key of PROJECT_INTERN_KEYS) { + if (key in project) project[key] = resolve(project[key]); + } + expandModelSelection(project.defaultModelSelection); + }; + const expandThread = (thread: JsonObject) => { + for (const key of THREAD_INTERN_KEYS) { + if (key in thread) thread[key] = resolve(thread[key]); + } + expandModelSelection(thread.modelSelection); + if (isObject(thread.lineage)) { + if ("parentThreadId" in thread.lineage) { + thread.lineage.parentThreadId = resolve(thread.lineage.parentThreadId); + } + if ("rootThreadId" in thread.lineage) { + thread.lineage.rootThreadId = resolve(thread.lineage.rootThreadId); + } + } + if (Array.isArray(thread.providerInstanceHistory)) { + for (let i = 0; i < thread.providerInstanceHistory.length; i++) { + thread.providerInstanceHistory[i] = resolve(thread.providerInstanceHistory[i]); + } + } + }; + const expandCounts = (entries: unknown) => { + if (!Array.isArray(entries)) return; + for (const entry of entries) { + if (isObject(entry) && "projectId" in entry) entry.projectId = resolve(entry.projectId); + } + }; + + if (Array.isArray(container.projects)) { + for (const project of container.projects) if (isObject(project)) expandProject(project); + } + if (Array.isArray(container.threads)) { + for (const thread of container.threads) if (isObject(thread)) expandThread(thread); + } + if (Array.isArray(container.archivedThreads)) { + for (const thread of container.archivedThreads) if (isObject(thread)) expandThread(thread); + } + if (isObject(container.olderSettled)) { + expandCounts(container.olderSettled.counts); + } + expandCounts(container.counts); +} + +// `toCodecJson` turns `Schema.Unknown` into a recursive JSON check of the whole +// tree. The input is parsed JSON and the inner codec validates it anyway. +const ParsedJson = Schema.declare((_: unknown): _ is unknown => true, { + toCodecJson: () => undefined, +}); + +/** + * Adds opt-in compact shell row encoding (omitting default/derived fields) and + * frequency-gated string interning (`ids`) to shell snapshot and stream schemas. + */ +export const withCompactShellWire = ( + schema: S, + target: (value: JsonObject) => ShellWireTarget | undefined, +) => { + const codec = Schema.toCodecJson(schema); + type Encoded = typeof codec.Encoded; + return ParsedJson.pipe( + Schema.decodeTo(codec, { + decode: SchemaGetter.transform((raw: unknown): Encoded => { + if (!isObject(raw)) return raw as Encoded; + const hasIds = Array.isArray(raw.ids); + const hasCompact = raw.compactShell === true; + if (!hasIds && !hasCompact) return raw as Encoded; + const spec = target(raw); + if (hasIds) { + const ids: ReadonlyArray = raw.ids as ReadonlyArray; + delete raw.ids; + if (spec?.kind === "snapshot") { + const container = spec.key === null ? raw : raw[spec.key]; + if (isObject(container)) expandSnapshotStrings(container, ids); + } + } + if (hasCompact) { + delete raw.compactShell; + if (spec?.kind === "snapshot") { + const container = spec.key === null ? raw : raw[spec.key]; + if (isObject(container)) expandSnapshotContainer(container, spec.emptyArrays); + } else if (spec?.kind === "thread") { + const row = raw[spec.key]; + if (isObject(row)) expandThreadShell(row); + } else if (spec?.kind === "project") { + const row = raw[spec.key]; + if (isObject(row)) expandProjectShell(row); + } + } + return raw as Encoded; + }), + encode: SchemaGetter.transform((encoded: Encoded): unknown => { + if (!isObject(encoded)) return encoded; + const wantCompact = encoded.compactShell === true; + const wantIds = encoded.idTable === true; + if (!wantCompact && !wantIds) return encoded; + const { compactShell: _compactShell, idTable: _idTable, ...rest } = encoded; + const spec = target(rest); + if (spec === undefined) return rest; + + let out: JsonObject = rest; + if (wantCompact) { + if (spec.kind === "snapshot") { + if (spec.key === null) { + out = compactSnapshotContainer(out, spec.emptyArrays); + } else { + const container = out[spec.key]; + if (isObject(container)) { + out = { + ...out, + [spec.key]: compactSnapshotContainer(container, spec.emptyArrays), + }; + } + } + } else if (spec.kind === "thread") { + const row = out[spec.key]; + if (isObject(row)) out = { ...out, [spec.key]: compactThreadShell(row) }; + } else if (spec.kind === "project") { + const row = out[spec.key]; + if (isObject(row)) out = { ...out, [spec.key]: compactProjectShell(row) }; + } + out = { ...out, compactShell: true }; + } + + if (wantIds && spec.kind === "snapshot") { + const container = spec.key === null ? out : out[spec.key]; + if (isObject(container)) { + const interned = internSnapshotStrings(container); + if (interned.ids.length > 0) { + out = + spec.key === null + ? { ...interned.container, ids: interned.ids } + : { ...out, [spec.key]: interned.container, ids: interned.ids }; + } + } + } + + return out; + }), + }), + ); +};