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