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