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

threadCommands.ts

498 lines16.6 KB

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