Open History to see the last commit
1import type { ThreadId } from "@t3tools/contracts";
2import * as SecureRandom from "effect/crypto/SecureRandom";
3import * as Effect from "effect/Effect";
4import * as Option from "effect/Option";
5import { Atom } from "effect/reactivity";
6import {
7 WS_METHODS,
8 type EnvironmentId,
9 type OrchestrationV2ShellSnapshot,
10} from "@t3tools/contracts";
11
12import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts";
13import * as DateTime from "effect/DateTime";
14
15import {
16 createAtomCommandScheduler,
17 createEnvironmentCommand,
18 createEnvironmentRpcCommand,
19} from "./runtime.ts";
20import {
21 type InterruptThreadTurnInput,
22 archiveThread,
23 closeGuestShare,
24 resolveGuestMessage,
25 cancelQueuedRun,
26 createThread,
27 deleteThread,
28 editQueuedRun,
29 interruptThreadTurn,
30 forkSideChat,
31 forkThreadFromRun,
32 markThreadUnread,
33 mergeThreadBack,
34 promoteQueuedRun,
35 resumeThreadQueue,
36 retryWorkspacePreparation,
37 linkThreadPullRequest,
38 respondToThreadApproval,
39 respondToThreadUserInput,
40 dismissThreadUserInput,
41 revertThreadCheckpoint,
42 setThreadInteractionMode,
43 setThreadRuntimeMode,
44 pinThread,
45 reorderPinnedThread,
46 reorderActiveThread,
47 setThreadAutoSettle,
48 settleThread,
49 snoozeThread,
50 startThreadTurn,
51 stopThreadSession,
52 unarchiveThread,
53 unlinkThreadPullRequest,
54 unpinThread,
55 unsettleThread,
56 unsnoozeThread,
57 updateThreadMetadata,
58 visitThread,
59 watchThreadPullRequest,
60} from "../operations/commands.ts";
61import type { EnvironmentRegistry } from "../connection/registry.ts";
62import * as EnvironmentSupervisor from "../connection/supervisor.ts";
63import * as ThreadHistoryController from "./threadHistoryController.ts";
64
65export type LoadEarlierThreadHistoryInput = {
66 readonly threadId: ThreadId;
67 readonly throughEntryId?: string;
68 readonly workAnchorId?: string;
69};
70
71export function createThreadEnvironmentAtoms<R, E>(
72 runtime: Atom.AtomRuntime<EnvironmentRegistry | SecureRandom.SecureRandom | R, E>,
73 snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom<OrchestrationV2ShellSnapshot | null>,
74) {
75 const scheduler = createAtomCommandScheduler();
76 const concurrency = {
77 mode: "serial" as const,
78 key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
79 JSON.stringify([environmentId, input.threadId]),
80 };
81 const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (
82 input: LoadEarlierThreadHistoryInput,
83 ) {
84 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
85 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
86 if (Option.isNone(controller)) {
87 return {
88 _tag: "noop",
89 } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
90 }
91 return yield* controller.value.loadEarlier(
92 supervisor.target.environmentId,
93 input.threadId,
94 input.throughEntryId,
95 input.workAnchorId,
96 );
97 });
98
99 // Runs whether or not the server accepted the interrupt, so a stale cached item still
100 // settles when Stop had nothing to interrupt; the interrupt's own failure still surfaces.
101 // The repair is detached: its lookups must not hold the thread's serial command key, and
102 // closing the thread cancels the repair, not the Stop that triggered it.
103 const interruptTurn = Effect.fn("ThreadCommands.interruptTurn")(function* (
104 input: InterruptThreadTurnInput,
105 ) {
106 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
107 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
108 return yield* interruptThreadTurn(input).pipe(
109 Effect.ensuring(
110 Option.match(controller, {
111 onNone: () => Effect.void,
112 onSome: (value) =>
113 value
114 .reconcilePendingWork(supervisor.target.environmentId, input.threadId)
115 .pipe(Effect.forkDetach, Effect.asVoid),
116 }),
117 ),
118 );
119 });
120
121 const commands = {
122 create: createEnvironmentCommand(runtime, {
123 label: "environment-data:commands:thread:create",
124 execute: createThread,
125 scheduler,
126 concurrency,
127 }),
128 delete: createEnvironmentCommand(runtime, {
129 label: "environment-data:commands:thread:delete",
130 execute: deleteThread,
131 scheduler,
132 concurrency,
133 }),
134 closeGuestShare: createEnvironmentCommand(runtime, {
135 label: "environment-data:commands:thread:close-guest-share",
136 execute: closeGuestShare,
137 scheduler,
138 concurrency,
139 }),
140 resolveGuestMessage: createEnvironmentCommand(runtime, {
141 label: "environment-data:commands:thread:resolve-guest-message",
142 execute: resolveGuestMessage,
143 scheduler,
144 concurrency,
145 }),
146 archive: createEnvironmentCommand(runtime, {
147 label: "environment-data:commands:thread:archive",
148 execute: archiveThread,
149 scheduler,
150 concurrency,
151 }),
152 unarchive: createEnvironmentCommand(runtime, {
153 label: "environment-data:commands:thread:unarchive",
154 execute: unarchiveThread,
155 scheduler,
156 concurrency,
157 }),
158 settle: createEnvironmentCommand(runtime, {
159 label: "environment-data:commands:thread:settle",
160 execute: settleThread,
161 scheduler,
162 concurrency,
163 }),
164 unsettle: createEnvironmentCommand(runtime, {
165 label: "environment-data:commands:thread:unsettle",
166 execute: unsettleThread,
167 scheduler,
168 concurrency,
169 }),
170 snooze: createEnvironmentCommand(runtime, {
171 label: "environment-data:commands:thread:snooze",
172 execute: snoozeThread,
173 scheduler,
174 concurrency,
175 }),
176 unsnooze: createEnvironmentCommand(runtime, {
177 label: "environment-data:commands:thread:unsnooze",
178 execute: unsnoozeThread,
179 scheduler,
180 concurrency,
181 }),
182 pin: createEnvironmentCommand(runtime, {
183 label: "environment-data:commands:thread:pin",
184 execute: pinThread,
185 scheduler,
186 concurrency,
187 }),
188 unpin: createEnvironmentCommand(runtime, {
189 label: "environment-data:commands:thread:unpin",
190 execute: unpinThread,
191 scheduler,
192 concurrency,
193 }),
194 reorderPin: createEnvironmentCommand(runtime, {
195 label: "environment-data:commands:thread:reorder-pin",
196 execute: reorderPinnedThread,
197 scheduler,
198 concurrency,
199 }),
200 setAutoSettle: createEnvironmentCommand(runtime, {
201 label: "environment-data:commands:thread:set-auto-settle",
202 execute: setThreadAutoSettle,
203 scheduler,
204 concurrency,
205 }),
206 reorderActive: createEnvironmentCommand(runtime, {
207 label: "environment-data:commands:thread:reorder-active",
208 execute: reorderActiveThread,
209 scheduler,
210 concurrency,
211 }),
212 visit: createEnvironmentCommand(runtime, {
213 label: "environment-data:commands:thread:visit",
214 execute: visitThread,
215 scheduler,
216 concurrency,
217 }),
218 markUnread: createEnvironmentCommand(runtime, {
219 label: "environment-data:commands:thread:mark-unread",
220 execute: markThreadUnread,
221 scheduler,
222 concurrency,
223 }),
224 updateMetadata: createEnvironmentCommand(runtime, {
225 label: "environment-data:commands:thread:update-metadata",
226 execute: updateThreadMetadata,
227 scheduler,
228 concurrency,
229 }),
230 linkPullRequest: createEnvironmentCommand(runtime, {
231 label: "environment-data:commands:thread:link-pull-request",
232 execute: linkThreadPullRequest,
233 scheduler,
234 concurrency,
235 }),
236 unlinkPullRequest: createEnvironmentCommand(runtime, {
237 label: "environment-data:commands:thread:unlink-pull-request",
238 execute: unlinkThreadPullRequest,
239 scheduler,
240 concurrency,
241 }),
242 watchPullRequest: createEnvironmentCommand(runtime, {
243 label: "environment-data:commands:thread:watch-pull-request",
244 execute: watchThreadPullRequest,
245 scheduler,
246 concurrency,
247 }),
248 setRuntimeMode: createEnvironmentCommand(runtime, {
249 label: "environment-data:commands:thread:set-runtime-mode",
250 execute: setThreadRuntimeMode,
251 scheduler,
252 concurrency,
253 }),
254 setInteractionMode: createEnvironmentCommand(runtime, {
255 label: "environment-data:commands:thread:set-interaction-mode",
256 execute: setThreadInteractionMode,
257 scheduler,
258 concurrency,
259 }),
260 startTurn: createEnvironmentCommand(runtime, {
261 label: "environment-data:commands:thread:start-turn",
262 execute: startThreadTurn,
263 scheduler,
264 concurrency,
265 }),
266 interruptTurn: createEnvironmentCommand(runtime, {
267 label: "environment-data:commands:thread:interrupt-turn",
268 execute: interruptTurn,
269 scheduler,
270 concurrency,
271 }),
272 respondToApproval: createEnvironmentCommand(runtime, {
273 label: "environment-data:commands:thread:respond-to-approval",
274 execute: respondToThreadApproval,
275 scheduler,
276 concurrency,
277 }),
278 respondToUserInput: createEnvironmentCommand(runtime, {
279 label: "environment-data:commands:thread:respond-to-user-input",
280 execute: respondToThreadUserInput,
281 scheduler,
282 concurrency,
283 }),
284 dismissUserInput: createEnvironmentCommand(runtime, {
285 label: "environment-data:commands:thread:dismiss-user-input",
286 execute: dismissThreadUserInput,
287 scheduler,
288 concurrency,
289 }),
290 revertCheckpoint: createEnvironmentCommand(runtime, {
291 label: "environment-data:commands:thread:revert-checkpoint",
292 execute: revertThreadCheckpoint,
293 scheduler,
294 concurrency,
295 }),
296 stopSession: createEnvironmentCommand(runtime, {
297 label: "environment-data:commands:thread:stop-session",
298 execute: stopThreadSession,
299 scheduler,
300 concurrency,
301 }),
302 forkFromRun: createEnvironmentCommand(runtime, {
303 label: "environment-data:commands:thread:fork-from-run",
304 execute: forkThreadFromRun,
305 scheduler,
306 concurrency: {
307 mode: "serial",
308 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
309 },
310 }),
311 forkSideChat: createEnvironmentCommand(runtime, {
312 label: "environment-data:commands:thread:fork-side-chat",
313 execute: forkSideChat,
314 scheduler,
315 concurrency: {
316 mode: "serial",
317 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
318 },
319 }),
320 mergeBack: createEnvironmentCommand(runtime, {
321 label: "environment-data:commands:thread:merge-back",
322 execute: mergeThreadBack,
323 scheduler,
324 concurrency: {
325 mode: "serial",
326 key: ({ environmentId, input }) =>
327 JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]),
328 },
329 }),
330 resumeThreadQueue: createEnvironmentCommand(runtime, {
331 label: "environment-data:commands:thread:resume-queue",
332 execute: resumeThreadQueue,
333 scheduler,
334 concurrency,
335 }),
336 promoteQueuedRun: createEnvironmentCommand(runtime, {
337 label: "environment-data:commands:thread:promote-queued-run",
338 execute: promoteQueuedRun,
339 scheduler,
340 concurrency,
341 }),
342 cancelQueuedRun: createEnvironmentCommand(runtime, {
343 label: "environment-data:commands:thread:cancel-queued-run",
344 execute: cancelQueuedRun,
345 scheduler,
346 concurrency,
347 }),
348 retryWorkspacePreparation: createEnvironmentCommand(runtime, {
349 label: "environment-data:commands:thread:retry-workspace-preparation",
350 execute: retryWorkspacePreparation,
351 scheduler,
352 concurrency,
353 }),
354 editQueuedRun: createEnvironmentCommand(runtime, {
355 label: "environment-data:commands:thread:edit-queued-run",
356 execute: editQueuedRun,
357 scheduler,
358 concurrency,
359 }),
360 loadEarlierHistory: createEnvironmentCommand(runtime, {
361 label: "environment-data:commands:thread:load-earlier-history",
362 execute: loadEarlierHistory,
363 scheduler,
364 concurrency: {
365 mode: "serial",
366 key: ({ environmentId, input }) =>
367 `history:${JSON.stringify([environmentId, input.threadId])}`,
368 },
369 }),
370 uploadFeedback: createEnvironmentRpcCommand(runtime, {
371 label: "environment-data:commands:thread:upload-feedback",
372 tag: WS_METHODS.providerUploadFeedback,
373 scheduler,
374 concurrency,
375 }),
376 };
377 const optimistic = createOptimisticThreadLifecycle(snapshotAtom);
378 return {
379 ...commands,
380 snapshotAtom: optimistic.snapshotAtom,
381 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
382 !accepted &&
383 (thread.pendingRuntimeRequest !== null ||
384 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status))
385 ? thread
386 : {
387 ...thread,
388 pendingRuntimeRequest: null,
389 settledOverride: "settled",
390 settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now,
391 unsettledAt: null,
392 activeOrderKey: null,
393 pinnedAt: null,
394 pinOrderKey: null,
395 snoozedAt: null,
396 snoozedUntil: null,
397 },
398 ),
399 unsettle: optimistic.wrap(commands.unsettle, (thread, input, now) => ({
400 ...thread,
401 settledOverride: input.reason === "user" ? "active" : null,
402 settledAt: null,
403 unsettledAt: thread.settledOverride === "active" ? (thread.unsettledAt ?? null) : now,
404 })),
405 snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
406 (!accepted &&
407 (thread.pendingRuntimeRequest !== null ||
408 ["preparing", "queued", "starting"].includes(thread.status))) ||
409 !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
410 ? thread
411 : {
412 ...thread,
413 pendingRuntimeRequest: null,
414 snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
415 snoozedAt: now,
416 },
417 ),
418 unsnooze: optimistic.wrap(commands.unsnooze, (thread) => ({
419 ...thread,
420 snoozedUntil: null,
421 snoozedAt: null,
422 })),
423 setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({
424 ...thread,
425 autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now),
426 })),
427 pin: optimistic.wrap(commands.pin, (thread, input, now) => ({
428 ...thread,
429 pinnedAt: thread.pinnedAt ?? now,
430 pinOrderKey: thread.pinnedAt == null ? (input.orderKey ?? null) : thread.pinOrderKey,
431 ...(thread.settledOverride === "settled"
432 ? {
433 settledOverride: "active" as const,
434 settledAt: null,
435 unsettledAt: now,
436 }
437 : {}),
438 snoozedUntil: null,
439 snoozedAt: null,
440 })),
441 unpin: optimistic.wrap(commands.unpin, (thread) => ({
442 ...thread,
443 pinnedAt: null,
444 pinOrderKey: null,
445 })),
446 reorderPin: optimistic.wrap(commands.reorderPin, (thread, input) => ({
447 ...thread,
448 pinOrderKey: input.orderKey,
449 })),
450 reorderActive: optimistic.wrap(commands.reorderActive, (thread, input) => ({
451 ...thread,
452 activeOrderKey: input.orderKey,
453 })),
454 };
455}