Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shellReducer.ts

164 lines6.1 KB

1import {
2 OrchestrationV2ThreadShell,
3 type OrchestrationProjectShell,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6} from "@t3tools/contracts";
7import * as Schema from "effect/Schema";
8​
9const sameThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
10​
11function upsertById<T extends { readonly id: unknown }>(
12 items: ReadonlyArray<T>,
13 item: T,
14): ReadonlyArray<T> {
15 const index = items.findIndex((candidate) => candidate.id === item.id);
16 if (index === -1) return [...items, item];
17 return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate));
19​
20function retainRepositoryIdentity(
21 previous: OrchestrationProjectShell | undefined,
22 next: OrchestrationProjectShell,
23): OrchestrationProjectShell {
24 if (
25 next.repositoryIdentity == null &&
26 previous?.repositoryIdentity != null &&
27 previous.workspaceRoot === next.workspaceRoot
28 ) {
29 return { ...next, repositoryIdentity: previous.repositoryIdentity };
30 }
31 return next;
33​
34export interface MergeShellSnapshotOptions {
35 /**
36 * Metadata-only enrichment refresh: structure and sequence never change;
37 * listed roots accept identity exactly (including null).
38 * Omit this options object for authoritative HTTP/initial WebSocket snapshots.
39 */
40 readonly resolvedRepositoryIdentityRoots: ReadonlyArray<string>;
42​
43/**
44 * Merge an incoming full shell snapshot into prior client state.
45 *
46 * Authoritative snapshots (no options) replace structure and sequence even when
47 * lower than cache, while retaining a prior non-null identity when the candidate
48 * is still unresolved/null for the same root.
49 *
50 * Enrichment snapshots (options present) only patch repository identity for
51 * matching current projects. They never replace projects, threads, archives,
52 * or sequence, regardless of the incoming snapshot sequence.
53 */
54export function mergeShellSnapshotProjects(
55 previous: OrchestrationV2ShellSnapshot | null | undefined,
56 next: OrchestrationV2ShellSnapshot,
57 options?: MergeShellSnapshotOptions,
58): OrchestrationV2ShellSnapshot {
59 if (previous === null || previous === undefined) {
60 return next;
61 }
62​
63 const isEnrichment = options !== undefined;
64 const resolvedRootSet = isEnrichment ? new Set(options.resolvedRepositoryIdentityRoots) : null;
65​
66 if (isEnrichment) {
67 const nextById = new Map(next.projects.map((project) => [project.id, project] as const));
68 return {
69 ...previous,
70 projects: previous.projects.map((project) => {
71 const candidate = nextById.get(project.id);
72 if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) {
73 return project;
74 }
75 if (resolvedRootSet?.has(project.workspaceRoot) === true) {
76 return { ...project, repositoryIdentity: candidate.repositoryIdentity };
77 }
78 if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) {
79 return { ...project, repositoryIdentity: candidate.repositoryIdentity };
80 }
81 return project;
82 }),
83 };
84 }
85​
86 const previousById = new Map(previous.projects.map((project) => [project.id, project] as const));
87 return {
88 ...next,
89 projects: next.projects.map((project) => {
90 const prior = previousById.get(project.id);
91 if (resolvedRootSet?.has(project.workspaceRoot) === true) {
92 return project;
93 }
94 return retainRepositoryIdentity(prior, project);
95 }),
96 };
98​
99/** Applies one committed V2 shell delta while preserving active/archive exclusivity. */
100export function applyShellStreamEvent(
101 snapshot: OrchestrationV2ShellSnapshot,
102 event: Exclude<
103 OrchestrationV2ShellStreamItem,
104 { readonly kind: "snapshot" } | { readonly kind: "synchronized" }
105 >,
106): OrchestrationV2ShellSnapshot {
107 if (event.sequence <= snapshot.snapshotSequence) return snapshot;
108​
109 switch (event.kind) {
110 case "project.updated": {
111 // Enrichment is async. A project mutation can land with null
112 // repositoryIdentity while an earlier snapshot already resolved it.
113 // Keep the prior identity for the same workspace root so multi-env
114 // grouping does not split until a full snapshot refresh arrives.
115 const previous = snapshot.projects.find((project) => project.id === event.project.id);
116 const project = retainRepositoryIdentity(previous, event.project);
117 return {
118 ...snapshot,
119 projects: upsertById(snapshot.projects, project),
120 snapshotSequence: event.sequence,
121 };
122 }
123 case "project.removed":
124 return {
125 ...snapshot,
126 projects: snapshot.projects.filter((project) => project.id !== event.projectId),
127 snapshotSequence: event.sequence,
128 };
129 case "thread.updated": {
130 // An unchanged shell keeps its object and the list, so subscribers that
131 // compare by reference skip the update. Only the cursor moves.
132 const existing =
133 event.location === "active"
134 ? snapshot.threads.find((thread) => thread.id === event.thread.id)
135 : undefined;
136 if (existing !== undefined && sameThreadShell(existing, event.thread)) {
137 return { ...snapshot, snapshotSequence: event.sequence };
138 }
139 const withoutThread = (threads: OrchestrationV2ShellSnapshot["threads"]) =>
140 threads.filter((thread) => thread.id !== event.thread.id);
141 return {
142 ...snapshot,
143 threads:
144 event.location === "active"
145 ? upsertById(snapshot.threads, event.thread)
146 : withoutThread(snapshot.threads),
147 // The archive has its own bounded query/subscription. Older servers may
148 // still send archive-located deltas here; remove them from the normal
149 // shell instead of growing its persisted cache again.
150 archivedThreads: withoutThread(snapshot.archivedThreads),
151 snapshotSequence: event.sequence,
152 };
153 }
154 case "thread.removed":
155 return {
156 ...snapshot,
157 threads: snapshot.threads.filter((thread) => thread.id !== event.threadId),
158 archivedThreads: snapshot.archivedThreads.filter((thread) => thread.id !== event.threadId),
159 snapshotSequence: event.sequence,
160 };
161 default:
162 return snapshot;
163 }