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

threadDetail.ts

179 lines7.4 KB

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 snoozedUntil: shell.snoozedUntil,
64 snoozedAt: shell.snoozedAt,
65 // The shell carries only a wait summary; the detail stream owns the full
66 // queued prompt. A null summary clears it; a live summary keeps whatever
67 // the detail subscription last reported, but only when its messageId still
68 // matches — a lagging detail can hold a cancelled wait while the shell
69 // already points at a replacement, and cancelling by the stale id would be
70 // rejected by the server.
71 pendingProviderTurn:
72 shell.pendingProviderTurn == null ||
73 detail.pendingProviderTurn?.message.messageId !== shell.pendingProviderTurn.messageId
74 ? null
75 : detail.pendingProviderTurn,
76 pinnedAt: shell.pinnedAt,
77 pinOrderKey: shell.pinOrderKey,
78 session: shell.session,
79 };
81​
82export function createEnvironmentThreadDetailAtoms<E>(
83 threadStateAtom: (
84 environmentId: ScopedThreadRef["environmentId"],
85 threadId: ScopedThreadRef["threadId"],
86 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>,
87) {
88 const threadStateValueAtomFamily = Atom.family((key: string) => {
89 const ref = parseThreadKey(key);
90 return Atom.make((get) =>
91 Option.getOrElse(
92 AsyncResult.value(get(threadStateAtom(ref.environmentId, ref.threadId))),
93 () => EMPTY_ENVIRONMENT_THREAD_STATE,
94 ),
95 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-state-value:${key}`));
96 });
97​
98 const threadDetailAtomFamily = Atom.family((key: string) => {
99 const ref = parseThreadKey(key);
100 let previousSource: OrchestrationThread | null = null;
101 let previousValue: EnvironmentThread | null = null;
102 return Atom.make((get) => {
103 const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
104 if (source === previousSource) {
105 return previousValue;
106 }
107 previousSource = source;
108 previousValue = source === null ? null : scopeThread(ref.environmentId, source);
109 return previousValue;
110 }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-detail:${key}`));
111 });
112​
113 const threadStatusAtomFamily = Atom.family((key: string) =>
114 Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
115 Atom.setIdleTTL(0),
116 Atom.withLabel(`environment-thread-status:${key}`),
117 ),
118 );
119​
120 const threadErrorAtomFamily = Atom.family((key: string) =>
121 Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
122 Atom.setIdleTTL(0),
123 Atom.withLabel(`environment-thread-error:${key}`),
124 ),
125 );
126​
127 const threadMessagesAtomFamily = Atom.family((key: string) =>
128 Atom.make(
129 (get): ReadonlyArray<OrchestrationMessage> =>
130 get(threadDetailAtomFamily(key))?.messages ?? EMPTY_MESSAGES,
131 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-messages:${key}`)),
132 );
133​
134 const threadActivitiesAtomFamily = Atom.family((key: string) =>
135 Atom.make(
136 (get): ReadonlyArray<OrchestrationThreadActivity> =>
137 get(threadDetailAtomFamily(key))?.activities ?? EMPTY_ACTIVITIES,
138 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-activities:${key}`)),
139 );
140​
141 const threadProposedPlansAtomFamily = Atom.family((key: string) =>
142 Atom.make(
143 (get): ReadonlyArray<OrchestrationProposedPlan> =>
144 get(threadDetailAtomFamily(key))?.proposedPlans ?? EMPTY_PROPOSED_PLANS,
145 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-proposed-plans:${key}`)),
146 );
147​
148 const threadCheckpointsAtomFamily = Atom.family((key: string) =>
149 Atom.make(
150 (get): ReadonlyArray<OrchestrationCheckpointSummary> =>
151 get(threadDetailAtomFamily(key))?.checkpoints ?? EMPTY_CHECKPOINTS,
152 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoints:${key}`)),
153 );
154​
155 const threadSessionAtomFamily = Atom.family((key: string) =>
156 Atom.make(
157 (get): OrchestrationSession | null => get(threadDetailAtomFamily(key))?.session ?? null,
158 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-session:${key}`)),
159 );
160​
161 const threadLatestTurnAtomFamily = Atom.family((key: string) =>
162 Atom.make(
163 (get): OrchestrationLatestTurn | null => get(threadDetailAtomFamily(key))?.latestTurn ?? null,
164 ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-latest-turn:${key}`)),
165 );
166​
167 return {
168 stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
169 detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)),
170 statusAtom: (ref: ScopedThreadRef) => threadStatusAtomFamily(threadKey(ref)),
171 errorAtom: (ref: ScopedThreadRef) => threadErrorAtomFamily(threadKey(ref)),
172 messagesAtom: (ref: ScopedThreadRef) => threadMessagesAtomFamily(threadKey(ref)),
173 activitiesAtom: (ref: ScopedThreadRef) => threadActivitiesAtomFamily(threadKey(ref)),
174 proposedPlansAtom: (ref: ScopedThreadRef) => threadProposedPlansAtomFamily(threadKey(ref)),
175 checkpointsAtom: (ref: ScopedThreadRef) => threadCheckpointsAtomFamily(threadKey(ref)),
176 sessionAtom: (ref: ScopedThreadRef) => threadSessionAtomFamily(threadKey(ref)),
177 latestTurnAtom: (ref: ScopedThreadRef) => threadLatestTurnAtomFamily(threadKey(ref)),
178 };