Open History to see the last commit
1import { CommandId, type ModelSelection, 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 { AsyncResult, Atom, type AtomRegistry } 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 type AtomCommand,
17 createAtomCommandScheduler,
18 createEnvironmentCommand,
19 createEnvironmentRpcCommand,
20 environmentConnectionAtom,
21 mapAtomCommandResult,
22} from "./runtime.ts";
23import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts";
24import {
25 type InterruptThreadTurnInput,
26 type UpdateThreadMetadataInput,
27 archiveThread,
28 closeGuestShare,
29 resolveGuestMessage,
30 cancelQueuedRun,
31 createThread,
32 deleteThread,
33 editQueuedRun,
34 interruptThreadTurn,
35 forkSideChat,
36 forkThreadFromRun,
37 markThreadUnread,
38 mergeThreadBack,
39 promoteQueuedRun,
40 resumeThreadQueue,
41 retryWorkspacePreparation,
42 linkThreadPullRequest,
43 linkThreadIssue,
44 respondToThreadApproval,
45 respondToThreadUserInput,
46 dismissThreadUserInput,
47 revertThreadCheckpoint,
48 setThreadInteractionMode,
49 setThreadRuntimeMode,
50 pinThread,
51 reorderPinnedThread,
52 reorderActiveThread,
53 setThreadAutoSettle,
54 settleThread,
55 snoozeThread,
56 startThreadTurn,
57 stopThreadSession,
58 unarchiveThread,
59 unlinkThreadPullRequest,
60 unlinkThreadIssue,
61 unpinThread,
62 unsettleThread,
63 unsnoozeThread,
64 updateThreadMetadata,
65 visitThread,
66 watchThreadPullRequest,
67} from "../operations/commands.ts";
68import { connectionProjectionPhase } from "../connection/model.ts";
69import type { EnvironmentRegistry } from "../connection/registry.ts";
70import * as EnvironmentSupervisor from "../connection/supervisor.ts";
71import * as ThreadHistoryController from "./threadHistoryController.ts";
72
73export type LoadEarlierThreadHistoryInput = {
74 readonly threadId: ThreadId;
75 readonly throughEntryId?: string;
76 readonly workAnchorId?: string;
77};
78
79export function createThreadEnvironmentAtoms<R, E>(
80 runtime: Atom.AtomRuntime<EnvironmentRegistry | SecureRandom.SecureRandom | R, E>,
81 snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom<OrchestrationV2ShellSnapshot | null>,
82) {
83 const scheduler = createAtomCommandScheduler();
84 const concurrency = {
85 mode: "serial" as const,
86 key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
87 JSON.stringify([environmentId, input.threadId]),
88 };
89 const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (
90 input: LoadEarlierThreadHistoryInput,
91 ) {
92 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
93 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
94 if (Option.isNone(controller)) {
95 return {
96 _tag: "noop",
97 } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
98 }
99 return yield* controller.value.loadEarlier(
100 supervisor.target.environmentId,
101 input.threadId,
102 input.throughEntryId,
103 input.workAnchorId,
104 );
105 });
106
107 // Runs whether or not the server accepted the interrupt, so a stale cached item still
108 // settles when Stop had nothing to interrupt; the interrupt's own failure still surfaces.
109 // The repair is detached: its lookups must not hold the thread's serial command key, and
110 // closing the thread cancels the repair, not the Stop that triggered it.
111 const interruptTurn = Effect.fn("ThreadCommands.interruptTurn")(function* (
112 input: InterruptThreadTurnInput,
113 ) {
114 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
115 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
116 return yield* interruptThreadTurn(input).pipe(
117 Effect.ensuring(
118 Option.match(controller, {
119 onNone: () => Effect.void,
120 onSome: (value) =>
121 value
122 .reconcilePendingWork(supervisor.target.environmentId, input.threadId)
123 .pipe(Effect.forkDetach, Effect.asVoid),
124 }),
125 ),
126 );
127 });
128
129 const armTitleRegeneration = Effect.fn("ThreadCommands.armTitleRegeneration")(function* (input: {
130 readonly threadId: ThreadId;
131 }) {
132 const random = yield* SecureRandom.SecureRandom;
133 const requestId = CommandId.make(yield* random.uuidV4());
134 const result = yield* updateThreadMetadata({
135 threadId: input.threadId,
136 regenerateTitle: true,
137 commandId: requestId,
138 });
139 return { requestId, sequence: result.sequence };
140 });
141
142 // Counts the commands that move or remove a thread's row. A list that holds its rows while
143 // environments synchronize (`stepSteadyShells`) shows the user's own change at once.
144 const rowActionsAtom = Atom.family((_environmentId: EnvironmentId) =>
145 Atom.make(0).pipe(Atom.keepAlive),
146 );
147 const rowAction = <W extends { readonly environmentId: EnvironmentId }, A, E>(
148 command: AtomCommand<W, A, E>,
149 ): AtomCommand<W, A, E> => ({
150 label: command.label,
151 run: (registry, target) => {
152 registry.update(rowActionsAtom(target.environmentId), (count) => count + 1);
153 return command.run(registry, target);
154 },
155 });
156
157 const sent = {
158 armTitleRegeneration: createEnvironmentCommand(runtime, {
159 label: "environment-data:commands:thread:regenerate-title",
160 execute: armTitleRegeneration,
161 scheduler,
162 concurrency,
163 }),
164
165 create: createEnvironmentCommand(runtime, {
166 label: "environment-data:commands:thread:create",
167 execute: createThread,
168 scheduler,
169 concurrency,
170 }),
171 delete: createEnvironmentCommand(runtime, {
172 label: "environment-data:commands:thread:delete",
173 execute: deleteThread,
174 scheduler,
175 concurrency,
176 }),
177 closeGuestShare: createEnvironmentCommand(runtime, {
178 label: "environment-data:commands:thread:close-guest-share",
179 execute: closeGuestShare,
180 scheduler,
181 concurrency,
182 }),
183 resolveGuestMessage: createEnvironmentCommand(runtime, {
184 label: "environment-data:commands:thread:resolve-guest-message",
185 execute: resolveGuestMessage,
186 scheduler,
187 concurrency,
188 }),
189 archive: createEnvironmentCommand(runtime, {
190 label: "environment-data:commands:thread:archive",
191 execute: archiveThread,
192 scheduler,
193 concurrency,
194 }),
195 unarchive: createEnvironmentCommand(runtime, {
196 label: "environment-data:commands:thread:unarchive",
197 execute: unarchiveThread,
198 scheduler,
199 concurrency,
200 }),
201 settle: createEnvironmentCommand(runtime, {
202 label: "environment-data:commands:thread:settle",
203 execute: settleThread,
204 scheduler,
205 concurrency,
206 }),
207 unsettle: createEnvironmentCommand(runtime, {
208 label: "environment-data:commands:thread:unsettle",
209 execute: unsettleThread,
210 scheduler,
211 concurrency,
212 }),
213 snooze: createEnvironmentCommand(runtime, {
214 label: "environment-data:commands:thread:snooze",
215 execute: snoozeThread,
216 scheduler,
217 concurrency,
218 }),
219 unsnooze: createEnvironmentCommand(runtime, {
220 label: "environment-data:commands:thread:unsnooze",
221 execute: unsnoozeThread,
222 scheduler,
223 concurrency,
224 }),
225 pin: createEnvironmentCommand(runtime, {
226 label: "environment-data:commands:thread:pin",
227 execute: pinThread,
228 scheduler,
229 concurrency,
230 }),
231 unpin: createEnvironmentCommand(runtime, {
232 label: "environment-data:commands:thread:unpin",
233 execute: unpinThread,
234 scheduler,
235 concurrency,
236 }),
237 reorderPin: createEnvironmentCommand(runtime, {
238 label: "environment-data:commands:thread:reorder-pin",
239 execute: reorderPinnedThread,
240 scheduler,
241 concurrency,
242 }),
243 setAutoSettle: createEnvironmentCommand(runtime, {
244 label: "environment-data:commands:thread:set-auto-settle",
245 execute: setThreadAutoSettle,
246 scheduler,
247 concurrency,
248 }),
249 reorderActive: createEnvironmentCommand(runtime, {
250 label: "environment-data:commands:thread:reorder-active",
251 execute: reorderActiveThread,
252 scheduler,
253 concurrency,
254 }),
255 visit: createEnvironmentCommand(runtime, {
256 label: "environment-data:commands:thread:visit",
257 execute: visitThread,
258 scheduler,
259 concurrency,
260 }),
261 markUnread: createEnvironmentCommand(runtime, {
262 label: "environment-data:commands:thread:mark-unread",
263 execute: markThreadUnread,
264 scheduler,
265 concurrency,
266 }),
267 updateMetadata: createEnvironmentCommand(runtime, {
268 label: "environment-data:commands:thread:update-metadata",
269 execute: updateThreadMetadata,
270 scheduler,
271 concurrency,
272 }),
273 linkPullRequest: createEnvironmentCommand(runtime, {
274 label: "environment-data:commands:thread:link-pull-request",
275 execute: linkThreadPullRequest,
276 scheduler,
277 concurrency,
278 }),
279 unlinkPullRequest: createEnvironmentCommand(runtime, {
280 label: "environment-data:commands:thread:unlink-pull-request",
281 execute: unlinkThreadPullRequest,
282 scheduler,
283 concurrency,
284 }),
285 watchPullRequest: createEnvironmentCommand(runtime, {
286 label: "environment-data:commands:thread:watch-pull-request",
287 execute: watchThreadPullRequest,
288 scheduler,
289 concurrency,
290 }),
291 setModelSelection: createEnvironmentCommand(runtime, {
292 label: "environment-data:commands:thread:set-model-selection",
293 execute: (input: UpdateThreadMetadataInput & { readonly modelSelection: ModelSelection }) =>
294 updateThreadMetadata(input),
295 scheduler,
296 concurrency,
297 }),
298 linkIssue: createEnvironmentCommand(runtime, {
299 label: "environment-data:commands:thread:link-issue",
300 execute: linkThreadIssue,
301 scheduler,
302 concurrency,
303 }),
304 unlinkIssue: createEnvironmentCommand(runtime, {
305 label: "environment-data:commands:thread:unlink-issue",
306 execute: unlinkThreadIssue,
307 scheduler,
308 concurrency,
309 }),
310 setRuntimeMode: createEnvironmentCommand(runtime, {
311 label: "environment-data:commands:thread:set-runtime-mode",
312 execute: setThreadRuntimeMode,
313 scheduler,
314 concurrency,
315 }),
316 setInteractionMode: createEnvironmentCommand(runtime, {
317 label: "environment-data:commands:thread:set-interaction-mode",
318 execute: setThreadInteractionMode,
319 scheduler,
320 concurrency,
321 }),
322 startTurn: createEnvironmentCommand(runtime, {
323 label: "environment-data:commands:thread:start-turn",
324 execute: startThreadTurn,
325 scheduler,
326 concurrency,
327 }),
328 interruptTurn: createEnvironmentCommand(runtime, {
329 label: "environment-data:commands:thread:interrupt-turn",
330 execute: interruptTurn,
331 scheduler,
332 concurrency,
333 }),
334 respondToApproval: createEnvironmentCommand(runtime, {
335 label: "environment-data:commands:thread:respond-to-approval",
336 execute: respondToThreadApproval,
337 scheduler,
338 concurrency,
339 }),
340 respondToUserInput: createEnvironmentCommand(runtime, {
341 label: "environment-data:commands:thread:respond-to-user-input",
342 execute: respondToThreadUserInput,
343 scheduler,
344 concurrency,
345 }),
346 dismissUserInput: createEnvironmentCommand(runtime, {
347 label: "environment-data:commands:thread:dismiss-user-input",
348 execute: dismissThreadUserInput,
349 scheduler,
350 concurrency,
351 }),
352 revertCheckpoint: createEnvironmentCommand(runtime, {
353 label: "environment-data:commands:thread:revert-checkpoint",
354 execute: revertThreadCheckpoint,
355 scheduler,
356 concurrency,
357 }),
358 stopSession: createEnvironmentCommand(runtime, {
359 label: "environment-data:commands:thread:stop-session",
360 execute: stopThreadSession,
361 scheduler,
362 concurrency,
363 }),
364 forkFromRun: createEnvironmentCommand(runtime, {
365 label: "environment-data:commands:thread:fork-from-run",
366 execute: forkThreadFromRun,
367 scheduler,
368 concurrency: {
369 mode: "serial",
370 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
371 },
372 }),
373 forkSideChat: createEnvironmentCommand(runtime, {
374 label: "environment-data:commands:thread:fork-side-chat",
375 execute: forkSideChat,
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: mergeThreadBack,
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: resumeThreadQueue,
395 scheduler,
396 concurrency,
397 }),
398 promoteQueuedRun: createEnvironmentCommand(runtime, {
399 label: "environment-data:commands:thread:promote-queued-run",
400 execute: promoteQueuedRun,
401 scheduler,
402 concurrency,
403 }),
404 cancelQueuedRun: createEnvironmentCommand(runtime, {
405 label: "environment-data:commands:thread:cancel-queued-run",
406 execute: cancelQueuedRun,
407 scheduler,
408 concurrency,
409 }),
410 retryWorkspacePreparation: createEnvironmentCommand(runtime, {
411 label: "environment-data:commands:thread:retry-workspace-preparation",
412 execute: retryWorkspacePreparation,
413 scheduler,
414 concurrency,
415 }),
416 editQueuedRun: createEnvironmentCommand(runtime, {
417 label: "environment-data:commands:thread:edit-queued-run",
418 execute: editQueuedRun,
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 }) =>
429 `history:${JSON.stringify([environmentId, input.threadId])}`,
430 },
431 }),
432 uploadFeedback: createEnvironmentRpcCommand(runtime, {
433 label: "environment-data:commands:thread:upload-feedback",
434 tag: WS_METHODS.providerUploadFeedback,
435 scheduler,
436 concurrency,
437 }),
438 };
439 const commands = {
440 ...sent,
441 delete: rowAction(sent.delete),
442 archive: rowAction(sent.archive),
443 unarchive: rowAction(sent.unarchive),
444 settle: rowAction(sent.settle),
445 unsettle: rowAction(sent.unsettle),
446 snooze: rowAction(sent.snooze),
447 unsnooze: rowAction(sent.unsnooze),
448 pin: rowAction(sent.pin),
449 unpin: rowAction(sent.unpin),
450 };
451 const optimistic = createOptimisticThreadLifecycle(snapshotAtom);
452 const disconnectedAtom = Atom.family((environmentId: EnvironmentId) =>
453 Atom.make((get) => {
454 const connection = AsyncResult.getOrElse(
455 get(environmentConnectionAtom(runtime, environmentId)),
456 () => null,
457 );
458 return connection !== null && connectionProjectionPhase(connection[0]) === "disconnected";
459 }),
460 );
461 const regenerateTitle = {
462 label: commands.armTitleRegeneration.label,
463 run: async (
464 registry: AtomRegistry.AtomRegistry,
465 target: { readonly environmentId: EnvironmentId; readonly input: { threadId: ThreadId } },
466 ) => {
467 const armed = await commands.armTitleRegeneration.run(registry, target);
468 const outcome =
469 armed._tag === "Success"
470 ? await waitForTitleRegenerationOutcome(
471 registry,
472 {
473 snapshot: snapshotAtom(target.environmentId),
474 disconnected: disconnectedAtom(target.environmentId),
475 },
476 { threadId: target.input.threadId, ...armed.value },
477 )
478 : null;
479 return mapAtomCommandResult(armed, () => outcome);
480 },
481 };
482 return {
483 ...commands,
484 regenerateTitle,
485 rowActionsAtom,
486 snapshotAtom: optimistic.snapshotAtom,
487 pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
488 settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
489 !accepted &&
490 (thread.pendingRuntimeRequest !== null ||
491 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status))
492 ? thread
493 : {
494 ...thread,
495 pendingRuntimeRequest: null,
496 settledOverride: "settled",
497 settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now,
498 unsettledAt: null,
499 activeOrderKey: null,
500 pinnedAt: null,
501 pinOrderKey: null,
502 snoozedAt: null,
503 snoozedUntil: null,
504 },
505 ),
506 unsettle: optimistic.wrap(commands.unsettle, (thread, input, now) => ({
507 ...thread,
508 settledOverride: input.reason === "user" ? "active" : null,
509 settledAt: null,
510 unsettledAt:
511 thread.settledOverride === "active"
512 ? (thread.unsettledAt ?? null)
513 : input.restoreUnsettledAt === undefined
514 ? now
515 : input.restoreUnsettledAt === null
516 ? null
517 : DateTime.makeUnsafe(input.restoreUnsettledAt),
518 })),
519 snooze: optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
520 (!accepted &&
521 ((thread.pendingRuntimeRequest !== null &&
522 thread.pendingRuntimeRequest.kind !== "user_input") ||
523 ["preparing", "queued", "starting"].includes(thread.status))) ||
524 !(Date.parse(input.snoozedUntil) > DateTime.toEpochMillis(now))
525 ? thread
526 : {
527 ...thread,
528 snoozedUntil: DateTime.makeUnsafe(input.snoozedUntil),
529 snoozedAt: now,
530 },
531 ),
532 unsnooze: optimistic.wrap(commands.unsnooze, (thread) => ({
533 ...thread,
534 snoozedUntil: null,
535 snoozedAt: null,
536 })),
537 setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({
538 ...thread,
539 autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now),
540 })),
541 pin: optimistic.wrap(commands.pin, (thread, input, now) => ({
542 ...thread,
543 pinnedAt: thread.pinnedAt ?? now,
544 pinOrderKey: thread.pinnedAt == null ? (input.orderKey ?? null) : thread.pinOrderKey,
545 ...(thread.settledOverride === "settled"
546 ? {
547 settledOverride: "active" as const,
548 settledAt: null,
549 unsettledAt: now,
550 }
551 : {}),
552 snoozedUntil: null,
553 snoozedAt: null,
554 })),
555 unpin: optimistic.wrap(commands.unpin, (thread) => ({
556 ...thread,
557 pinnedAt: null,
558 pinOrderKey: null,
559 })),
560 reorderPin: optimistic.wrap(commands.reorderPin, (thread, input) => ({
561 ...thread,
562 pinOrderKey: input.orderKey,
563 })),
564 reorderActive: optimistic.wrap(commands.reorderActive, (thread, input) => ({
565 ...thread,
566 activeOrderKey: input.orderKey,
567 })),
568 // Shown at once, so a composer that releases its accepted pick keeps showing it.
569 setModelSelection: optimistic.wrap(commands.setModelSelection, (thread, input) => ({
570 ...thread,
571 modelSelection: input.modelSelection,
572 })),
573 };
574}