Open History to see the last commit
1import type {
2 ApplicationStoredEvent,
3 OrchestrationProjectShell,
4 OrchestrationV2ArchivedShellStreamItem,
5 OrchestrationV2ShellSnapshot,
6 OrchestrationV2ThreadShell,
7 OrchestrationV2ThreadShellSnapshot,
8 OrchestrationV2ShellStreamItem,
9 OrchestrationV2StoredEvent,
10} from "@t3tools/contracts";
11import {
12 OrchestrationProjectShell as ProjectShellSchema,
13 OrchestrationV2ThreadShell as ThreadShellSchema,
14} from "@t3tools/contracts";
15import * as Clock from "effect/Clock";
16import * as Effect from "effect/Effect";
17import * as Schema from "effect/Schema";
18import * as Stream from "effect/Stream";
19
20/** Build the regular navigation shell without duplicating the archive dataset. */
21export function buildActiveShellSnapshot(input: {
22 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
23 readonly threads: OrchestrationV2ThreadShellSnapshot;
24 readonly snapshotSequence: number;
25}): OrchestrationV2ShellSnapshot {
26 return {
27 schemaVersion: input.threads.schemaVersion,
28 snapshotSequence: input.snapshotSequence,
29 projects: input.projects,
30 threads: input.threads.threads,
31 archivedThreads: [],
32 };
33}
34
35export type ShellApplicationEvent =
36 | Pick<
37 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
38 "aggregateKind" | "aggregateId" | "type" | "sequence"
39 >
40 | {
41 readonly sequence: number;
42 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
43 };
44
45/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
46export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
47 return "aggregateKind" in stored
48 ? {
49 aggregateKind: stored.aggregateKind,
50 aggregateId: stored.aggregateId,
51 type: stored.type,
52 sequence: stored.sequence,
53 }
54 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
55}
56
57/** Keep only the newest shell-relevant event per project/thread aggregate. */
58export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
59 events: ReadonlyArray<A>,
60): ReadonlyArray<A> {
61 const latestByAggregate = new Map<string, A>();
62 for (const stored of events) {
63 const key =
64 "aggregateKind" in stored
65 ? `project:${stored.aggregateId}`
66 : `thread:${stored.event.threadId}`;
67 latestByAggregate.set(key, stored);
68 }
69 return Array.from(latestByAggregate.values()).sort(
70 (left, right) => left.sequence - right.sequence,
71 );
72}
73
74/**
75 * Emit the initial shell prefix strictly first, then merge the post-prefix
76 * tail with enrichment refreshes. Prevents a newer marked enrichment from
77 * landing before the unmarked authoritative initial snapshot.
78 */
79export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
80 readonly initial: Stream.Stream<A, E, R>;
81 readonly tail: Stream.Stream<A2, E2, R2>;
82 readonly enrichment: Stream.Stream<A3, E3, R3>;
83}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
84 return Stream.concat(input.initial, Stream.merge(input.tail, input.enrichment));
85}
86
87const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
88
89/** Drop repeated metadata refreshes within one subscription, preserving resolution progress. */
90export function dedupeShellEnrichment<E, R>(
91 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
92): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
93 return Stream.suspend(() => {
94 let previous:
95 | {
96 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
97 readonly roots: ReadonlySet<string>;
98 }
99 | undefined;
100 return stream.pipe(
101 Stream.filter((item) => {
102 if (item.kind !== "snapshot") {
103 // A project delta may change which projects/identities a later refresh repairs.
104 if (item.kind === "project.updated" || item.kind === "project.removed")
105 previous = undefined;
106 return true;
107 }
108 if (
109 item.resolvedRepositoryIdentityRoots === undefined ||
110 item.snapshot.threads.length > 0 ||
111 item.snapshot.archivedThreads.length > 0
112 ) {
113 previous = undefined;
114 return true;
115 }
116 const roots = new Set(item.resolvedRepositoryIdentityRoots);
117 const prior = previous;
118 if (
119 prior !== undefined &&
120 roots.size === prior.roots.size &&
121 [...roots].every((root) => prior.roots.has(root)) &&
122 sameProjects(prior.projects, item.snapshot.projects)
123 )
124 return false;
125 previous = { projects: item.snapshot.projects, roots };
126 return true;
127 }),
128 );
129 });
130}
131
132/** Build a shell snapshot stream item for a batched enrichment completion. */
133export function shellStreamItemFromEnrichmentRefresh(input: {
134 readonly snapshot: OrchestrationV2ShellSnapshot;
135 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
136}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
137 const resolvedRepositoryIdentityRoots = [
138 ...new Set(input.changes.map((change) => change.workspaceRoot)),
139 ];
140 return {
141 kind: "snapshot",
142 snapshot: {
143 ...input.snapshot,
144 projects: input.snapshot.projects.filter((project) =>
145 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
146 ),
147 threads: [],
148 archivedThreads: [],
149 },
150 resolvedRepositoryIdentityRoots,
151 };
152}
153
154/**
155 * Initial subscribe frames: always emit the unmarked authoritative snapshot,
156 * then a same-sequence enrichment frame only when some roots already resolved.
157 */
158export function shellStreamItemsFromInitialSnapshot(input: {
159 readonly snapshot: OrchestrationV2ShellSnapshot;
160 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
161}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
162 const authoritative = {
163 kind: "snapshot" as const,
164 snapshot: input.snapshot,
165 };
166 if (input.resolvedRepositoryIdentityRoots.length === 0) {
167 return [authoritative];
168 }
169 return [
170 authoritative,
171 {
172 kind: "snapshot" as const,
173 snapshot: {
174 ...input.snapshot,
175 projects: input.snapshot.projects.filter((project) =>
176 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
177 ),
178 threads: [],
179 archivedThreads: [],
180 },
181 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
182 },
183 ];
184}
185
186/** Resume after HTTP/cache hydration with metadata only, never another full shell body. */
187export function shellStreamItemsFromResumeSnapshot(input: {
188 readonly snapshot: OrchestrationV2ShellSnapshot;
189 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
190}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
191 return shellStreamItemsFromInitialSnapshot(input).filter(
192 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
193 );
194}
195
196const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
197
198/** How long an unchanged thread shell may go unsent on a live subscription. */
199const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
200
201/**
202 * Drop live `thread.updated` deltas whose shell matches the last one this
203 * subscription sent, apart from `updatedAt`. Every thread event bumps
204 * `updatedAt`, so tool output and streaming text alone used to send the full,
205 * otherwise unchanged shell once per batch.
206 *
207 * A skipped delta leaves the client cursor behind, and a resume replays the
208 * events after that cursor. So an unchanged shell is still sent once its last
209 * send is `UNCHANGED_THREAD_SHELL_RESEND_MS` old. That bounds both the replay
210 * and how stale the client's `updatedAt` can get.
211 */
212export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
213 stream: Stream.Stream<A, E, R>,
214): Stream.Stream<A, E, R> {
215 return Stream.suspend(() => {
216 const lastSent = new Map<
217 OrchestrationV2ThreadShell["id"],
218 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
219 >();
220 return stream.pipe(
221 Stream.filterEffect((item) =>
222 Effect.map(Clock.currentTimeMillis, (now) => {
223 if (item.kind === "thread.removed") {
224 lastSent.delete(item.threadId);
225 return true;
226 }
227 if (item.kind !== "thread.updated") return true;
228 const previous = lastSent.get(item.thread.id);
229 if (
230 previous !== undefined &&
231 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
232 sameThreadShell(
233 { ...item.thread, updatedAt: previous.thread.updatedAt },
234 previous.thread,
235 )
236 ) {
237 return false;
238 }
239 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
240 return true;
241 }),
242 ),
243 );
244 });
245}
246
247/** Keep only the newest stored event per thread within a coalescing window. */
248export function coalesceStoredThreadEvents(
249 events: ReadonlyArray<OrchestrationV2StoredEvent>,
250): ReadonlyArray<OrchestrationV2StoredEvent> {
251 const latestByThreadId = new Map<string, OrchestrationV2StoredEvent>();
252 for (const stored of events) {
253 latestByThreadId.set(stored.event.threadId, stored);
254 }
255 return Array.from(latestByThreadId.values()).sort(
256 (left, right) => left.sequence - right.sequence,
257 );
258}
259
260/**
261 * Converts a committed event and the affected thread's current shell into one
262 * delta. `shell` is null when the thread is deleted or unknown.
263 */
264export function shellStreamItemFromThreadShell(input: {
265 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
266 readonly shell: OrchestrationV2ThreadShell | null;
267}): Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
268 if (input.shell !== null) {
269 if (input.shell.archivedAt !== null) {
270 return {
271 kind: "thread.removed",
272 sequence: input.stored.sequence,
273 location: "active",
274 threadId: input.shell.id,
275 };
276 }
277 return {
278 kind: "thread.updated",
279 sequence: input.stored.sequence,
280 location: "active",
281 thread: input.shell,
282 };
283 }
284
285 return {
286 kind: "thread.removed",
287 sequence: input.stored.sequence,
288 location: "active",
289 threadId: input.stored.event.threadId,
290 };
291}
292
293/** Converts a committed event into an archive-only delta when it changes archive membership. */
294export function archivedShellStreamItemFromThreadShell(input: {
295 readonly stored: OrchestrationV2StoredEvent;
296 readonly shell: OrchestrationV2ThreadShell | null;
297}): Exclude<OrchestrationV2ArchivedShellStreamItem, { readonly kind: "snapshot" }> | null {
298 if (input.shell !== null && input.shell.archivedAt !== null) {
299 return {
300 kind: "thread.updated",
301 sequence: input.stored.sequence,
302 thread: input.shell,
303 };
304 }
305 if (
306 input.stored.event.type === "thread.unarchived" ||
307 (input.stored.event.type === "thread.deleted" && input.stored.event.payload.archivedAt !== null)
308 ) {
309 return {
310 kind: "thread.removed",
311 sequence: input.stored.sequence,
312 threadId: input.stored.event.threadId,
313 };
314 }
315 return null;
316}