Open History to see the last commit
1import type {
2 ApplicationStoredEvent,
3 OrchestrationProjectShell,
4 OrchestrationV2OlderSettledCount,
5 OrchestrationV2OlderSettledThreads,
6 OrchestrationV2ShellSnapshot,
7 OrchestrationV2ThreadShell,
8 OrchestrationV2ThreadShellSnapshot,
9 OrchestrationV2ShellStreamItem,
10 OrchestrationV2StoredEvent,
11 ProjectId,
12 ThreadId,
13} from "@t3tools/contracts";
14import {
15 isListedThreadLineage,
16 isLiveSubagentShell,
17 isOlderSettledThreadShell,
18 OrchestrationProjectShell as ProjectShellSchema,
19 OrchestrationV2ThreadShell as ThreadShellSchema,
20} from "@t3tools/contracts";
21import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
22import type * as Arr from "effect/Array";
23import type * as Cause from "effect/Cause";
24import * as Clock from "effect/Clock";
25import * as DateTime from "effect/DateTime";
26import * as Deferred from "effect/Deferred";
27import * as Effect from "effect/Effect";
28import * as Exit from "effect/Exit";
29import * as Queue from "effect/Queue";
30import * as Schema from "effect/Schema";
31import type * as SqlClient from "effect/sql/SqlClient";
32import * as Stream from "effect/Stream";
33
34import { bufferLatestLiveStream } from "./LiveStreamBudget.ts";
35import type { ActiveShellIndexEntry } from "./ProjectionStore.ts";
36
37type ShellDelta = Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;
38
39/** Snapshots, synchronization, and enrichment markers must bypass full-state coalescing. */
40export const bufferShellLiveStream = <E, R>(
41 source: Stream.Stream<ShellDelta, E, R>,
42 limits?: { readonly maxItems?: number; readonly maxSerializedBytes?: number },
43) =>
44 bufferLatestLiveStream(
45 source,
46 (item) => {
47 switch (item.kind) {
48 case "project.updated":
49 return `project:${item.project.id}`;
50 case "project.removed":
51 return `project:${item.projectId}`;
52 case "thread.updated":
53 return `thread:${item.location}:${item.thread.id}`;
54 case "thread.removed":
55 return `thread:${item.location}:${item.threadId}`;
56 }
57 },
58 limits,
59 );
60
61function buildActiveShellSnapshot(input: {
62 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
63 readonly threads: OrchestrationV2ThreadShellSnapshot;
64 readonly snapshotSequence: number;
65}): OrchestrationV2ShellSnapshot {
66 return {
67 schemaVersion: input.threads.schemaVersion,
68 snapshotSequence: input.snapshotSequence,
69 projects: input.projects,
70 threads: input.threads.threads,
71 archivedThreads: [],
72 };
73}
74
75type ShellTrimRow = Pick<
76 OrchestrationV2ThreadShell,
77 "id" | "projectId" | "lineage" | "settledOverride" | "settledAt"
78>;
79
80/**
81 * What a subscriber's trims read across every active row. Computed from full shells or from the
82 * store's index, so a snapshot read only for the rows it sends trims the same way.
83 */
84interface ShellTrimFacts {
85 readonly subagentParentIds: ReadonlySet<string>;
86 readonly subagentThreadIds: Set<string>;
87 /** Undefined when no thread is settled, so none is older. */
88 readonly olderSettledBeforeMs: number | undefined;
89 readonly olderSettledCounts: ReadonlyArray<OrchestrationV2OlderSettledCount>;
90}
91
92const NEWEST_SETTLED_KEPT = 25;
93
94function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {
95 const subagentParentIds = new Set<string>();
96 const subagentThreadIds = new Set<string>();
97 const settledTimes: Array<number> = [];
98 for (const row of rows) {
99 if (row.lineage.relationshipToParent === "subagent") {
100 subagentThreadIds.add(row.id);
101 if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId);
102 } else if (
103 isListedThreadLineage(row.lineage) &&
104 row.settledOverride === "settled" &&
105 row.settledAt !== null
106 ) {
107 settledTimes.push(DateTime.toEpochMillis(row.settledAt));
108 }
109 }
110 settledTimes.sort((left, right) => right - left);
111 // With fewer than 25, the oldest one is the cut, so nothing is older.
112 const olderSettledBeforeMs = settledTimes[NEWEST_SETTLED_KEPT - 1] ?? settledTimes.at(-1);
113 const counts = new Map<ProjectId, number>();
114 if (olderSettledBeforeMs !== undefined) {
115 for (const row of rows) {
116 if (isOlderSettledThreadShell(row, olderSettledBeforeMs)) {
117 counts.set(row.projectId, (counts.get(row.projectId) ?? 0) + 1);
118 }
119 }
120 }
121 return {
122 subagentParentIds,
123 subagentThreadIds,
124 olderSettledBeforeMs,
125 olderSettledCounts: Array.from(counts, ([projectId, count]) => ({ projectId, count })),
126 };
127}
128
129function hiddenChildAncestorIds(
130 threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>,
131) {
132 const ancestorIds = new Set<string>();
133 for (const thread of threads) {
134 if (isListedThreadLineage(thread.lineage)) continue;
135 if (thread.lineage.parentThreadId !== null) ancestorIds.add(thread.lineage.parentThreadId);
136 ancestorIds.add(thread.lineage.rootThreadId);
137 }
138 return ancestorIds;
139}
140
141function omitIdleSubagentShellsWith(
142 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
143 facts: Pick<ShellTrimFacts, "subagentParentIds">,
144): ReadonlyArray<OrchestrationV2ThreadShell> {
145 return threads.filter(
146 (thread) =>
147 thread.lineage.relationshipToParent !== "subagent" ||
148 isLiveSubagentShell(thread) ||
149 facts.subagentParentIds.has(thread.id),
150 );
151}
152
153function omitOlderSettledShellsWith(
154 input: {
155 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
156 readonly snapshotSequence: number;
157 readonly now: DateTime.Utc;
158 },
159 facts: Pick<ShellTrimFacts, "olderSettledBeforeMs" | "olderSettledCounts">,
160): {
161 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
162 readonly olderSettled: OrchestrationV2OlderSettledThreads;
163} {
164 const nowMs = DateTime.toEpochMillis(input.now);
165 const beforeMs = facts.olderSettledBeforeMs ?? nowMs;
166 const ancestorIds = hiddenChildAncestorIds(input.threads);
167 const threads = input.threads.filter(
168 (thread) =>
169 !isOlderSettledThreadShell(thread, beforeMs) ||
170 thread.pinnedAt != null ||
171 (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) ||
172 isLiveSubagentShell(thread) ||
173 ancestorIds.has(thread.id),
174 );
175 return {
176 threads,
177 olderSettled: {
178 before: DateTime.formatIso(DateTime.makeUnsafe(beforeMs)),
179 asOfSequence: input.snapshotSequence,
180 counts: facts.olderSettledCounts,
181 },
182 };
183}
184
185/**
186 * Idle subagent children have no sidebar row, so clients that opt in read them from their thread
187 * family instead. A child stays while it is live or the parent of another child, so the request
188 * and working walks over shell rows never meet a gap in a nested chain.
189 */
190export function omitIdleSubagentShells(
191 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
192): ReadonlyArray<OrchestrationV2ThreadShell> {
193 return omitIdleSubagentShellsWith(threads, shellTrimFacts(threads));
194}
195
196/**
197 * The active rows a shell subscriber gets, and the subagent ids whose transcript events its stream
198 * drops. The ids come from every row, so an omitted child that wakes keeps that filter.
199 */
200export function activeShellRowsForSubscriber(
201 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
202 omitIdleSubagents: boolean,
203): {
204 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
205 readonly subagentThreadIds: Set<string>;
206} {
207 const facts = shellTrimFacts(threads);
208 return {
209 threads: omitIdleSubagents ? omitIdleSubagentShellsWith(threads, facts) : threads,
210 subagentThreadIds: facts.subagentThreadIds,
211 };
212}
213
214/**
215 * Opted-in snapshots keep the 25 newest settled top-level threads (and ties) and count the rest per
216 * project in `olderSettled`; clients page them with `getOlderSettledThreads`. Older rows stay while
217 * pinned, snoozed, live, or above a kept subagent or side chat, so walks over shell rows still find
218 * them.
219 */
220export function omitOlderSettledShells(input: {
221 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
222 readonly snapshotSequence: number;
223 readonly now: DateTime.Utc;
224}): {
225 readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;
226 readonly olderSettled: OrchestrationV2OlderSettledThreads;
227} {
228 return omitOlderSettledShellsWith(input, shellTrimFacts(input.threads));
229}
230
231interface ShellSubscriberOptions {
232 readonly omitIdleSubagents: boolean;
233 readonly omitOlderSettled: boolean;
234}
235
236function trimShellSnapshot(
237 base: OrchestrationV2ShellSnapshot,
238 facts: ShellTrimFacts,
239 options: ShellSubscriberOptions & { readonly now: DateTime.Utc },
240): OrchestrationV2ShellSnapshot {
241 const threads = options.omitIdleSubagents
242 ? omitIdleSubagentShellsWith(base.threads, facts)
243 : base.threads;
244 if (!options.omitOlderSettled) return { ...base, threads };
245 const older = omitOlderSettledShellsWith(
246 { threads, snapshotSequence: base.snapshotSequence, now: options.now },
247 facts,
248 );
249 return { ...base, threads: older.threads, olderSettled: older.olderSettled };
250}
251
252/**
253 * The threads whose shells a trimmed snapshot can contain: a superset of what the trims keep, so
254 * trimming the shells read for these ids gives the snapshot trimming every shell would.
255 */
256function shellSubscriberThreadIds(
257 index: ReadonlyArray<ActiveShellIndexEntry>,
258 options: ShellSubscriberOptions,
259): ReadonlyArray<ThreadId> {
260 const facts = shellTrimFacts(index);
261 const subagents = index.filter(
262 (entry) =>
263 entry.lineage.relationshipToParent === "subagent" &&
264 (!options.omitIdleSubagents || entry.mayBeLive || facts.subagentParentIds.has(entry.id)),
265 );
266 const ancestorIds = hiddenChildAncestorIds([
267 ...subagents,
268 ...index.filter((entry) => entry.lineage.sideChat === true),
269 ]);
270 const keptSubagentIds = new Set(subagents.map((entry) => entry.id));
271 const beforeMs = facts.olderSettledBeforeMs;
272 return index.flatMap((entry) =>
273 entry.lineage.relationshipToParent === "subagent"
274 ? keptSubagentIds.has(entry.id)
275 ? [entry.id]
276 : []
277 : !options.omitOlderSettled ||
278 beforeMs === undefined ||
279 !isOlderSettledThreadShell(entry, beforeMs) ||
280 entry.pinnedAt != null ||
281 entry.snoozedUntil != null ||
282 entry.mayBeLive ||
283 ancestorIds.has(entry.id)
284 ? [entry.id]
285 : [],
286 );
287}
288
289/**
290 * A subscriber's active shell snapshot, read like `loadShellSnapshotParts`. With an opt-in, the
291 * store's index decides which shells to read, so threads the trims drop are never built.
292 */
293export const loadSubscriberShellSnapshot = Effect.fn("ShellStream.loadSubscriberShellSnapshot")(
294 function* <E1, E2, E3, E4, E5>(input: {
295 readonly sql: SqlClient.SqlClient;
296 readonly listShellIndex: Effect.Effect<ReadonlyArray<ActiveShellIndexEntry>, E1>;
297 readonly readThreads: (
298 threadIds: ReadonlyArray<ThreadId> | undefined,
299 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E3>, E2>;
300 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E4>;
301 readonly latestSequence: Effect.Effect<number, E5>;
302 readonly options: ShellSubscriberOptions;
303 }) {
304 const trims = input.options.omitIdleSubagents || input.options.omitOlderSettled;
305 const read = yield* input.sql
306 .withTransaction(
307 Effect.gen(function* () {
308 const index = trims ? yield* input.listShellIndex : null;
309 return {
310 index,
311 decodeThreads: yield* input.readThreads(
312 index === null ? undefined : shellSubscriberThreadIds(index, input.options),
313 ),
314 projects: yield* input.listProjects,
315 snapshotSequence: yield* input.latestSequence,
316 };
317 }),
318 )
319 .pipe(NodeSqliteClient.readOnly);
320 const base = buildActiveShellSnapshot({
321 projects: read.projects,
322 threads: yield* read.decodeThreads,
323 snapshotSequence: read.snapshotSequence,
324 });
325 const facts = shellTrimFacts(read.index ?? base.threads);
326 return {
327 snapshot: trimShellSnapshot(base, facts, { ...input.options, now: yield* DateTime.now }),
328 subagentThreadIds: facts.subagentThreadIds,
329 };
330 },
331);
332
333/**
334 * One transaction covers the reads so they agree; the threads are decoded after it commits,
335 * because the server shares one SQLite connection and decoding a large shell takes longer than
336 * reading it.
337 */
338export const loadShellSnapshotParts = Effect.fn("ShellStream.loadShellSnapshotParts")(function* <
339 E1,
340 E2,
341 E3,
342 E4,
343>(input: {
344 readonly sql: SqlClient.SqlClient;
345 readonly readThreads: Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E2>, E1>;
346 readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E3>;
347 readonly latestSequence: Effect.Effect<number, E4>;
348}) {
349 const read = yield* input.sql
350 .withTransaction(
351 Effect.all({
352 decodeThreads: input.readThreads,
353 projects: input.listProjects,
354 snapshotSequence: input.latestSequence,
355 }),
356 )
357 .pipe(NodeSqliteClient.readOnly);
358 return {
359 projects: read.projects,
360 threads: yield* read.decodeThreads,
361 snapshotSequence: read.snapshotSequence,
362 };
363});
364
365/** A page of older settled threads, read and decoded like `loadShellSnapshotParts`. */
366export const loadOlderSettledThreadsPage = Effect.fn("ShellStream.loadOlderSettledThreadsPage")(
367 function* <E1, E2, E3, E4>(input: {
368 readonly sql: SqlClient.SqlClient;
369 readonly listThreads: Effect.Effect<
370 {
371 readonly threadIds: ReadonlyArray<ThreadId>;
372 readonly counts: ReadonlyArray<OrchestrationV2OlderSettledCount>;
373 },
374 E1
375 >;
376 readonly readThreads: (
377 threadIds: ReadonlyArray<ThreadId>,
378 ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E3>, E2>;
379 readonly latestSequence: Effect.Effect<number, E4>;
380 }) {
381 const read = yield* input.sql
382 .withTransaction(
383 Effect.gen(function* () {
384 const listed = yield* input.listThreads;
385 return {
386 listed,
387 decodeThreads:
388 listed.threadIds.length === 0 ? null : yield* input.readThreads(listed.threadIds),
389 snapshotSequence: yield* input.latestSequence,
390 };
391 }),
392 )
393 .pipe(NodeSqliteClient.readOnly);
394 const threads = read.decodeThreads === null ? [] : (yield* read.decodeThreads).threads;
395 const order = new Map(read.listed.threadIds.map((threadId, index) => [threadId, index]));
396 return {
397 snapshotSequence: read.snapshotSequence,
398 threads: threads.toSorted((left, right) => order.get(left.id)! - order.get(right.id)!),
399 counts: read.listed.counts,
400 };
401 },
402);
403
404export type ShellApplicationEvent =
405 | Pick<
406 Extract<ApplicationStoredEvent, { readonly aggregateKind: "project" }>,
407 "aggregateKind" | "aggregateId" | "type" | "sequence"
408 >
409 | {
410 readonly sequence: number;
411 readonly event: Pick<OrchestrationV2StoredEvent["event"], "threadId">;
412 };
413
414/** Focused subagents receive these updates through their thread subscription. */
415export function shouldPublishShellApplicationEvent(
416 stored: ApplicationStoredEvent,
417 subagentThreadIds: Set<string>,
418): boolean {
419 if ("aggregateKind" in stored) return true;
420 const { event } = stored;
421 if (event.type === "thread.created") {
422 if (event.payload.lineage.relationshipToParent === "subagent") {
423 subagentThreadIds.add(event.threadId);
424 }
425 return true;
426 }
427 if (event.type === "thread.deleted") {
428 // Replay and the live tail overlap; keep known IDs so late events stay filtered.
429 return true;
430 }
431 return !(
432 subagentThreadIds.has(event.threadId) &&
433 (event.type === "node.updated" ||
434 event.type === "turn-item.updated" ||
435 event.type === "provider-turn.updated" ||
436 event.type === "message.updated")
437 );
438}
439
440/** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */
441export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent {
442 return "aggregateKind" in stored
443 ? {
444 aggregateKind: stored.aggregateKind,
445 aggregateId: stored.aggregateId,
446 type: stored.type,
447 sequence: stored.sequence,
448 }
449 : { sequence: stored.sequence, event: { threadId: stored.event.threadId } };
450}
451
452export function coalesceShellApplicationEvents<A extends ShellApplicationEvent>(
453 events: ReadonlyArray<A>,
454): ReadonlyArray<A> {
455 const latestByAggregate = new Map<string, A>();
456 for (const stored of events) {
457 const key =
458 "aggregateKind" in stored
459 ? `project:${stored.aggregateId}`
460 : `thread:${stored.event.threadId}`;
461 latestByAggregate.set(key, stored);
462 }
463 return Array.from(latestByAggregate.values()).sort(
464 (left, right) => left.sequence - right.sequence,
465 );
466}
467
468/** Emit the authoritative initial snapshot before marked enrichment. */
469export function composeShellStreamWithEnrichment<A, E, R, A2, E2, R2, A3, E3, R3>(input: {
470 readonly initial: Stream.Stream<A, E, R>;
471 readonly tail: Stream.Stream<A2, E2, R2>;
472 readonly enrichment: Stream.Stream<A3, E3, R3>;
473}): Stream.Stream<A | A2 | A3, E | E2 | E3, R | R2 | R3> {
474 const merged = Stream.fromPull(
475 Effect.gen(function* () {
476 const output = yield* Queue.bounded<
477 {
478 readonly items: Arr.NonEmptyReadonlyArray<A2 | A3>;
479 readonly acknowledged?: Deferred.Deferred<void>;
480 },
481 E2 | E3 | Cause.Done
482 >(0);
483 yield* Effect.addFinalizer(() => Queue.shutdown(output));
484 let remaining = 2;
485 const drain = (effect: Effect.Effect<void, E2 | E3, R2 | R3>) =>
486 effect.pipe(
487 Effect.exit,
488 Effect.flatMap((exit) =>
489 Exit.isFailure(exit)
490 ? Queue.failCause(output, exit.cause)
491 : --remaining === 0
492 ? Queue.end(output)
493 : Effect.void,
494 ),
495 Effect.forkScoped,
496 );
497 yield* drain(
498 input.tail.pipe(
499 Stream.runForEachArray((items) =>
500 Effect.gen(function* () {
501 const acknowledged = yield* Deferred.make<void>();
502 yield* Queue.offer(output, { items, acknowledged });
503 yield* Deferred.await(acknowledged);
504 }),
505 ),
506 ),
507 );
508 // Keep draining the sliding enrichment subscription after each handoff,
509 // as Stream.merge does, while only the budgeted tail waits for an ACK.
510 yield* drain(
511 input.enrichment.pipe(Stream.runForEachArray((items) => Queue.offer(output, { items }))),
512 );
513 let previous: Deferred.Deferred<void> | undefined;
514 // Stream.merge pulls ahead after handing off each batch. Wait for the next
515 // downstream pull so shell delivery keeps that batch charged until its RPC ACK.
516 return Effect.gen(function* () {
517 if (previous) yield* Deferred.succeed(previous, undefined);
518 const next = yield* Queue.take(output);
519 previous = next.acknowledged;
520 return next.items;
521 });
522 }),
523 ).pipe(Stream.scoped);
524 return Stream.concat(input.initial, merged);
525}
526
527const sameProjects = Schema.toEquivalence(Schema.Array(ProjectShellSchema));
528
529export function dedupeShellEnrichment<E, R>(
530 stream: Stream.Stream<OrchestrationV2ShellStreamItem, E, R>,
531): Stream.Stream<OrchestrationV2ShellStreamItem, E, R> {
532 return Stream.suspend(() => {
533 let previous:
534 | {
535 readonly projects: ReadonlyArray<OrchestrationProjectShell>;
536 readonly roots: ReadonlySet<string>;
537 }
538 | undefined;
539 return stream.pipe(
540 Stream.filter((item) => {
541 if (item.kind !== "snapshot") {
542 if (item.kind === "project.updated" || item.kind === "project.removed")
543 previous = undefined;
544 return true;
545 }
546 if (
547 item.resolvedRepositoryIdentityRoots === undefined ||
548 item.snapshot.threads.length > 0 ||
549 item.snapshot.archivedThreads.length > 0
550 ) {
551 previous = undefined;
552 return true;
553 }
554 const roots = new Set(item.resolvedRepositoryIdentityRoots);
555 const prior = previous;
556 if (
557 prior !== undefined &&
558 roots.size === prior.roots.size &&
559 [...roots].every((root) => prior.roots.has(root)) &&
560 sameProjects(prior.projects, item.snapshot.projects)
561 )
562 return false;
563 previous = { projects: item.snapshot.projects, roots };
564 return true;
565 }),
566 );
567 });
568}
569
570export function shellStreamItemFromEnrichmentRefresh(input: {
571 readonly snapshot: OrchestrationV2ShellSnapshot;
572 readonly changes: ReadonlyArray<{ readonly workspaceRoot: string }>;
573}): Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }> {
574 const resolvedRepositoryIdentityRoots = [
575 ...new Set(input.changes.map((change) => change.workspaceRoot)),
576 ];
577 return {
578 kind: "snapshot",
579 snapshot: {
580 ...input.snapshot,
581 projects: input.snapshot.projects.filter((project) =>
582 resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
583 ),
584 threads: [],
585 archivedThreads: [],
586 },
587 resolvedRepositoryIdentityRoots,
588 };
589}
590
591export function shellStreamItemsFromInitialSnapshot(input: {
592 readonly snapshot: OrchestrationV2ShellSnapshot;
593 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
594}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
595 const authoritative = {
596 kind: "snapshot" as const,
597 snapshot: input.snapshot,
598 };
599 if (input.resolvedRepositoryIdentityRoots.length === 0) {
600 return [authoritative];
601 }
602 return [
603 authoritative,
604 {
605 kind: "snapshot" as const,
606 snapshot: {
607 ...input.snapshot,
608 projects: input.snapshot.projects.filter((project) =>
609 input.resolvedRepositoryIdentityRoots.includes(project.workspaceRoot),
610 ),
611 threads: [],
612 archivedThreads: [],
613 },
614 resolvedRepositoryIdentityRoots: [...new Set(input.resolvedRepositoryIdentityRoots)],
615 },
616 ];
617}
618
619export function shellStreamItemsFromResumeSnapshot(input: {
620 readonly snapshot: OrchestrationV2ShellSnapshot;
621 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
622}): ReadonlyArray<Extract<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>> {
623 return shellStreamItemsFromInitialSnapshot(input).filter(
624 (item) => item.resolvedRepositoryIdentityRoots !== undefined,
625 );
626}
627
628const sameThreadShell = Schema.toEquivalence(ThreadShellSchema);
629
630const UNCHANGED_THREAD_SHELL_RESEND_MS = 5_000;
631
632/** Resend unchanged shells after UNCHANGED_THREAD_SHELL_RESEND_MS so skipped deltas cannot leave resume cursors behind. */
633export function skipUnchangedThreadShells<A extends OrchestrationV2ShellStreamItem, E, R>(
634 stream: Stream.Stream<A, E, R>,
635): Stream.Stream<A, E, R> {
636 return Stream.suspend(() => {
637 const lastSent = new Map<
638 OrchestrationV2ThreadShell["id"],
639 { readonly thread: OrchestrationV2ThreadShell; readonly sentAt: number }
640 >();
641 return stream.pipe(
642 Stream.filterEffect((item) =>
643 Effect.map(Clock.currentTimeMillis, (now) => {
644 if (item.kind === "thread.removed") {
645 lastSent.delete(item.threadId);
646 return true;
647 }
648 if (item.kind !== "thread.updated") return true;
649 const previous = lastSent.get(item.thread.id);
650 if (
651 previous !== undefined &&
652 now - previous.sentAt < UNCHANGED_THREAD_SHELL_RESEND_MS &&
653 sameThreadShell(
654 { ...item.thread, updatedAt: previous.thread.updatedAt },
655 previous.thread,
656 )
657 ) {
658 return false;
659 }
660 lastSent.set(item.thread.id, { thread: item.thread, sentAt: now });
661 return true;
662 }),
663 ),
664 );
665 });
666}
667
668export function shellStreamItemFromThreadShell(input: {
669 readonly stored: Extract<ShellApplicationEvent, { readonly event: unknown }>;
670 readonly shell: OrchestrationV2ThreadShell | null;
671}): Extract<
672 OrchestrationV2ShellStreamItem,
673 { readonly kind: "thread.updated" | "thread.removed" }
674> {
675 if (input.shell !== null) {
676 if (input.shell.archivedAt !== null) {
677 return {
678 kind: "thread.removed",
679 sequence: input.stored.sequence,
680 location: "active",
681 threadId: input.shell.id,
682 };
683 }
684 return {
685 kind: "thread.updated",
686 sequence: input.stored.sequence,
687 location: "active",
688 thread: input.shell,
689 };
690 }
691
692 return {
693 kind: "thread.removed",
694 sequence: input.stored.sequence,
695 location: "active",
696 threadId: input.stored.event.threadId,
697 };
698}