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