Open History to see the last commit
1import type {
2 OrchestrationCheckpointSummary,
3 OrchestrationLatestTurn,
4 OrchestrationMessage,
5 OrchestrationProposedPlan,
6 OrchestrationSession,
7 OrchestrationThread,
8 OrchestrationThreadActivity,
9 ScopedThreadRef,
10} from "@t3tools/contracts";
11import * as Option from "effect/Option";
12import { AsyncResult, Atom } from "effect/unstable/reactivity";
13
14import type { EnvironmentThread, EnvironmentThreadShell } from "./models.ts";
15import { scopeThread } from "./models.ts";
16import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
17import { parseThreadKey, threadKey } from "./entities.ts";
18import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
19
20const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);
21const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);
22const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);
23const EMPTY_CHECKPOINTS: ReadonlyArray<OrchestrationCheckpointSummary> = Object.freeze([]);
24
25/**
26 * Combine detail-only collections with the shell's authoritative thread metadata.
27 *
28 * Shell and detail subscriptions are intentionally independent. A cached detail can
29 * therefore briefly outlive a newer shell snapshot after reconnecting. Workspace
30 * consumers must use the shell branch/worktree/project fields so they do not target
31 * a stale checkout while retaining messages, activities, plans, and checkpoints
32 * from the detail subscription.
33 */
34export function mergeEnvironmentThread(
35 detail: EnvironmentThread | null,
36 shell: EnvironmentThreadShell | null,
37): EnvironmentThread | null {
38 if (detail === null || shell === null) {
39 return detail;
40 }
41 if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) {
42 return detail;
43 }
44
45 return {
46 ...detail,
47 environmentId: shell.environmentId,
48 id: shell.id,
49 projectId: shell.projectId,
50 title: shell.title,
51 modelSelection: shell.modelSelection,
52 runtimeMode: shell.runtimeMode,
53 interactionMode: shell.interactionMode,
54 branch: shell.branch,
55 worktreePath: shell.worktreePath,
56 latestTurn: shell.latestTurn,
57 createdAt: shell.createdAt,
58 updatedAt: shell.updatedAt,
59 archivedAt: shell.archivedAt,
60 settledOverride: shell.settledOverride,
61 settledAt: shell.settledAt,
62 snoozedUntil: shell.snoozedUntil,
63 snoozedAt: shell.snoozedAt,
64 session: shell.session,
65 };
66}
67
68export function createEnvironmentThreadDetailAtoms<E>(
69 threadStateAtom: (
70 environmentId: ScopedThreadRef["environmentId"],
71 threadId: ScopedThreadRef["threadId"],
72 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
73) {
74 const threadStateValueAtomFamily = Atom.family((key: string) => {
75 const ref = parseThreadKey(key);
76 return Atom.make((get) =>
77 Option.getOrElse(
78 AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))),
79 () => EMPTY_ENVIRONMENT_THREAD_STATE,
80 ),
81 ).pipe(
82 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
83 Atom.withLabel(`environment-thread-state-value:${key}`),
84 );
85 });
86
87 const threadDetailAtomFamily = Atom.family((key: string) => {
88 const ref = parseThreadKey(key);
89 let previousSource: OrchestrationThread | null = null;
90 let previousValue: EnvironmentThread | null = null;
91 return Atom.make((get) => {
92 const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
93 if (source === previousSource) {
94 return previousValue;
95 }
96 previousSource = source;
97 previousValue = source === null ? null : scopeThread(ref.environmentId, source);
98 return previousValue;
99 }).pipe(
100 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
101 Atom.withLabel(`environment-thread-detail:${key}`),
102 );
103 });
104
105 const threadStatusAtomFamily = Atom.family((key: string) =>
106 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
107 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
108 Atom.withLabel(`environment-thread-status:${key}`),
109 ),
110 );
111
112 const threadErrorAtomFamily = Atom.family((key: string) =>
113 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
114 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
115 Atom.withLabel(`environment-thread-error:${key}`),
116 ),
117 );
118
119 const threadMessagesAtomFamily = Atom.family((key: string) =>
120 Atom.make(
121 (get): ReadonlyArray<OrchestrationMessage> =>
122 get(threadDetailAtomFamily(key))?.messages ?? EMPTY_MESSAGES,
123 ).pipe(
124 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
125 Atom.withLabel(`environment-thread-messages:${key}`),
126 ),
127 );
128
129 const threadActivitiesAtomFamily = Atom.family((key: string) =>
130 Atom.make(
131 (get): ReadonlyArray<OrchestrationThreadActivity> =>
132 get(threadDetailAtomFamily(key))?.activities ?? EMPTY_ACTIVITIES,
133 ).pipe(
134 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
135 Atom.withLabel(`environment-thread-activities:${key}`),
136 ),
137 );
138
139 const threadProposedPlansAtomFamily = Atom.family((key: string) =>
140 Atom.make(
141 (get): ReadonlyArray<OrchestrationProposedPlan> =>
142 get(threadDetailAtomFamily(key))?.proposedPlans ?? EMPTY_PROPOSED_PLANS,
143 ).pipe(
144 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
145 Atom.withLabel(`environment-thread-proposed-plans:${key}`),
146 ),
147 );
148
149 const threadCheckpointsAtomFamily = Atom.family((key: string) =>
150 Atom.make(
151 (get): ReadonlyArray<OrchestrationCheckpointSummary> =>
152 get(threadDetailAtomFamily(key))?.checkpoints ?? EMPTY_CHECKPOINTS,
153 ).pipe(
154 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
155 Atom.withLabel(`environment-thread-checkpoints:${key}`),
156 ),
157 );
158
159 const threadSessionAtomFamily = Atom.family((key: string) =>
160 Atom.make(
161 (get): OrchestrationSession | null => get(threadDetailAtomFamily(key))?.session ?? null,
162 ).pipe(
163 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
164 Atom.withLabel(`environment-thread-session:${key}`),
165 ),
166 );
167
168 const threadLatestTurnAtomFamily = Atom.family((key: string) =>
169 Atom.make(
170 (get): OrchestrationLatestTurn | null => get(threadDetailAtomFamily(key))?.latestTurn ?? null,
171 ).pipe(
172 Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
173 Atom.withLabel(`environment-thread-latest-turn:${key}`),
174 ),
175 );
176
177 return {
178 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
179 detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)),
180 statusAtom: (ref: ScopedThreadRef) => threadStatusAtomFamily(threadKey(ref)),
181 errorAtom: (ref: ScopedThreadRef) => threadErrorAtomFamily(threadKey(ref)),
182 messagesAtom: (ref: ScopedThreadRef) => threadMessagesAtomFamily(threadKey(ref)),
183 activitiesAtom: (ref: ScopedThreadRef) => threadActivitiesAtomFamily(threadKey(ref)),
184 proposedPlansAtom: (ref: ScopedThreadRef) => threadProposedPlansAtomFamily(threadKey(ref)),
185 checkpointsAtom: (ref: ScopedThreadRef) => threadCheckpointsAtomFamily(threadKey(ref)),
186 sessionAtom: (ref: ScopedThreadRef) => threadSessionAtomFamily(threadKey(ref)),
187 latestTurnAtom: (ref: ScopedThreadRef) => threadLatestTurnAtomFamily(threadKey(ref)),
188 };
189}