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 ORCHESTRATION_V2_WS_METHODS,
8 WS_METHODS,
9 type EnvironmentId,
10 type OrchestrationV2ShellSnapshot,
11 type OrchestrationV2ThreadShell,
12} from "@t3tools/contracts";
13
14import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts";
15import {
16 type EnvironmentShellState,
17 type EnvironmentShellStatus,
18 shellCommandHistoryInvalidated,
19} from "./shell.ts";
20import { createThreadTriageOutbox } from "./threadTriageOutbox.ts";
21import * as DateTime from "effect/DateTime";
22
23import {
24 type AtomCommand,
25 createAtomCommandScheduler,
26 createEnvironmentCommand,
27 createEnvironmentRpcCommand,
28 environmentConnectionAtom,
29} from "./runtime.ts";
30import { waitForTitleRegenerationOutcome } from "./threadTitleRegeneration.ts";
31import {
32 type InterruptThreadTurnInput,
33 type UpdateThreadMetadataInput,
34 archiveThread,
35 closeGuestShare,
36 resolveGuestMessage,
37 cancelQueuedRun,
38 createThread,
39 deleteThread,
40 editQueuedRun,
41 interruptThreadTurn,
42 forkSideChat,
43 forkThreadFromRun,
44 markThreadUnread,
45 mergeThreadBack,
46 promoteQueuedRun,
47 resumeThreadQueue,
48 retryWorkspacePreparation,
49 linkThreadPullRequest,
50 linkThreadIssue,
51 respondToThreadApproval,
52 respondToThreadUserInput,
53 dismissThreadUserInput,
54 revertThreadCheckpoint,
55 setThreadInteractionMode,
56 setThreadRuntimeMode,
57 setThreadToolOverrides,
58 pinThread,
59 reorderPinnedThread,
60 reorderActiveThread,
61 setThreadAutoSettle,
62 settleThread,
63 snoozeThread,
64 startThreadTurn,
65 stopThreadSession,
66 unarchiveThread,
67 unlinkThreadPullRequest,
68 unlinkThreadIssue,
69 unpinThread,
70 unsettleThread,
71 unsnoozeThread,
72 updateThreadMetadata,
73 withCommandDispatch,
74 visitThread,
75 watchThreadPullRequest,
76} from "../operations/commands.ts";
77import { connectionProjectionPhase } from "../connection/model.ts";
78import type { EnvironmentRegistry } from "../connection/registry.ts";
79import * as EnvironmentSupervisor from "../connection/supervisor.ts";
80import * as ThreadHistoryController from "./threadHistoryController.ts";
81
82export type LoadEarlierThreadHistoryInput = {
83 readonly threadId: ThreadId;
84 readonly throughEntryId?: string;
85 readonly workAnchorId?: string;
86};
87
88function applySettle(
89 thread: OrchestrationV2ThreadShell,
90 now: DateTime.Utc,
91 accepted: boolean,
92): OrchestrationV2ThreadShell {
93 return !accepted &&
94 (thread.pendingRuntimeRequest !== null ||
95 ["preparing", "queued", "starting", "running", "waiting"].includes(thread.status))
96 ? thread
97 : {
98 ...thread,
99 pendingRuntimeRequest: null,
100 settledOverride: "settled",
101 settledAt: thread.settledOverride === "settled" ? (thread.settledAt ?? now) : now,
102 unsettledAt: null,
103 activeOrderKey: null,
104 pinnedAt: null,
105 pinOrderKey: null,
106 snoozedAt: null,
107 snoozedUntil: null,
108 };
109}
110
111function applySnooze(
112 thread: OrchestrationV2ThreadShell,
113 snoozedUntil: string,
114 now: DateTime.Utc,
115 accepted: boolean,
116): OrchestrationV2ThreadShell {
117 return (!accepted &&
118 ((thread.pendingRuntimeRequest !== null &&
119 thread.pendingRuntimeRequest.kind !== "user_input") ||
120 ["preparing", "queued", "starting"].includes(thread.status))) ||
121 !(Date.parse(snoozedUntil) > DateTime.toEpochMillis(now))
122 ? thread
123 : {
124 ...thread,
125 snoozedUntil: DateTime.makeUnsafe(snoozedUntil),
126 snoozedAt: now,
127 };
128}
129
130export function createThreadEnvironmentAtoms<R, E>(
131 runtime: Atom.AtomRuntime<EnvironmentRegistry | SecureRandom.SecureRandom | R, E>,
132 snapshotAtom: (environmentId: EnvironmentId) => Atom.Atom<OrchestrationV2ShellSnapshot | null>,
133 /** Offline settle and snooze are sent once this reports a synchronized shell. */
134 shellStatusAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellStatus>,
135 commandHistoryAtom: (
136 environmentId: EnvironmentId,
137 ) => Atom.Atom<EnvironmentShellState["commandHistory"]>,
138) {
139 const scheduler = createAtomCommandScheduler();
140 const concurrency = {
141 mode: "serial" as const,
142 key: ({ environmentId, input }: { environmentId: string; input: { threadId: string } }) =>
143 JSON.stringify([environmentId, input.threadId]),
144 };
145 const loadEarlierHistory = Effect.fn("ThreadCommands.loadEarlierHistory")(function* (
146 input: LoadEarlierThreadHistoryInput,
147 ) {
148 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
149 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
150 if (Option.isNone(controller)) {
151 return {
152 _tag: "noop",
153 } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;
154 }
155 return yield* controller.value.loadEarlier(
156 supervisor.target.environmentId,
157 input.threadId,
158 input.throughEntryId,
159 input.workAnchorId,
160 );
161 });
162
163 // Runs whether or not the server accepted the interrupt, so a stale cached item still
164 // settles when Stop had nothing to interrupt; the interrupt's own failure still surfaces.
165 // The repair is detached: its lookups must not hold the thread's serial command key, and
166 // closing the thread cancels the repair, not the Stop that triggered it.
167 const interruptTurn = Effect.fn("ThreadCommands.interruptTurn")(function* (
168 input: InterruptThreadTurnInput,
169 ) {
170 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
171 const controller = yield* Effect.serviceOption(ThreadHistoryController.ThreadHistoryController);
172 return yield* interruptThreadTurn(input).pipe(
173 Effect.ensuring(
174 Option.match(controller, {
175 onNone: () => Effect.void,
176 onSome: (value) =>
177 value
178 .reconcilePendingWork(supervisor.target.environmentId, input.threadId)
179 .pipe(Effect.forkDetach, Effect.asVoid),
180 }),
181 ),
182 );
183 });
184
185 const armTitleRegeneration = Effect.fn("ThreadCommands.armTitleRegeneration")(function* (input: {
186 readonly threadId: ThreadId;
187 }) {
188 const random = yield* SecureRandom.SecureRandom;
189 const requestId = CommandId.make(yield* random.uuidV4());
190 const result = yield* updateThreadMetadata({
191 threadId: input.threadId,
192 regenerateTitle: true,
193 commandId: requestId,
194 });
195 return { requestId, sequence: result.sequence };
196 });
197
198 // Counts the commands that move or remove a thread's row. A list that holds its rows while
199 // environments synchronize (`stepSteadyShells`) shows the user's own change at once.
200 const rowActionsAtom = Atom.family((_environmentId: EnvironmentId) =>
201 Atom.make(0).pipe(Atom.keepAlive),
202 );
203 const rowAction = <W extends { readonly environmentId: EnvironmentId }, A, E>(
204 command: AtomCommand<W, A, E>,
205 ): AtomCommand<W, A, E> => ({
206 label: command.label,
207 run: (registry, target) =>
208 Effect.suspend(() => {
209 registry.update(rowActionsAtom(target.environmentId), (count) => count + 1);
210 return command.run(registry, target);
211 }),
212 });
213
214 // The environment's time of the last sign-in to a server in a thread, until the app reloads.
215 const mcpSignedInAtFamily = Atom.family((_key: string) =>
216 Atom.make<number | null>(null).pipe(Atom.keepAlive),
217 );
218 const mcpSignInKey = (
219 environmentId: EnvironmentId,
220 input: { readonly threadId: ThreadId; readonly server: string },
221 ) => JSON.stringify([environmentId, input.threadId, input.server]);
222 const markMcpSignedIn = (
223 registry: AtomRegistry.AtomRegistry,
224 environmentId: EnvironmentId,
225 input: { readonly threadId: ThreadId; readonly server: string },
226 signedInAt: string,
227 ) =>
228 registry.update(mcpSignedInAtFamily(mcpSignInKey(environmentId, input)), (current) =>
229 Math.max(current ?? 0, Date.parse(signedInAt)),
230 );
231 const mcpNoticeSignedInFamily = Atom.family((key: string) => {
232 const [signInKey, noticeAt] = JSON.parse(key) as [string, number];
233 // A notice newer than the sign-in means the server needs one again.
234 return Atom.make((get) => {
235 const signedInAt = get(mcpSignedInAtFamily(signInKey));
236 return signedInAt !== null && noticeAt <= signedInAt;
237 });
238 });
239 /** Whether a sign-in notice, by its environment time, came before the server was signed in. */
240 const mcpSignedInAtom = (
241 environmentId: EnvironmentId,
242 input: { readonly threadId: ThreadId; readonly server: string; readonly noticeAt: number },
243 ) =>
244 mcpNoticeSignedInFamily(JSON.stringify([mcpSignInKey(environmentId, input), input.noticeAt]));
245 const withShellReceipt =
246 <I, A, E, R2>(execute: (input: I) => Effect.Effect<A, E, R2>) =>
247 (input: I, registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentId) =>
248 withCommandDispatch(execute(input), (session) => ({
249 session,
250 history: registry.get(commandHistoryAtom(environmentId)),
251 }));
252
253 const sent = {
254 armTitleRegeneration: createEnvironmentCommand(runtime, {
255 label: "environment-data:commands:thread:regenerate-title",
256 execute: withShellReceipt(armTitleRegeneration),
257 scheduler,
258 concurrency,
259 }),
260
261 create: createEnvironmentCommand(runtime, {
262 label: "environment-data:commands:thread:create",
263 execute: createThread,
264 scheduler,
265 concurrency,
266 }),
267 delete: createEnvironmentCommand(runtime, {
268 label: "environment-data:commands:thread:delete",
269 execute: deleteThread,
270 scheduler,
271 concurrency,
272 }),
273 closeGuestShare: createEnvironmentCommand(runtime, {
274 label: "environment-data:commands:thread:close-guest-share",
275 execute: closeGuestShare,
276 scheduler,
277 concurrency,
278 }),
279 resolveGuestMessage: createEnvironmentCommand(runtime, {
280 label: "environment-data:commands:thread:resolve-guest-message",
281 execute: resolveGuestMessage,
282 scheduler,
283 concurrency,
284 }),
285 archive: createEnvironmentCommand(runtime, {
286 label: "environment-data:commands:thread:archive",
287 execute: archiveThread,
288 scheduler,
289 concurrency,
290 }),
291 unarchive: createEnvironmentCommand(runtime, {
292 label: "environment-data:commands:thread:unarchive",
293 execute: unarchiveThread,
294 scheduler,
295 concurrency,
296 }),
297 settle: createEnvironmentCommand(runtime, {
298 label: "environment-data:commands:thread:settle",
299 execute: withShellReceipt(settleThread),
300 scheduler,
301 concurrency,
302 }),
303 unsettle: createEnvironmentCommand(runtime, {
304 label: "environment-data:commands:thread:unsettle",
305 execute: withShellReceipt(unsettleThread),
306 scheduler,
307 concurrency,
308 }),
309 snooze: createEnvironmentCommand(runtime, {
310 label: "environment-data:commands:thread:snooze",
311 execute: withShellReceipt(snoozeThread),
312 scheduler,
313 concurrency,
314 }),
315 unsnooze: createEnvironmentCommand(runtime, {
316 label: "environment-data:commands:thread:unsnooze",
317 execute: withShellReceipt(unsnoozeThread),
318 scheduler,
319 concurrency,
320 }),
321 pin: createEnvironmentCommand(runtime, {
322 label: "environment-data:commands:thread:pin",
323 execute: withShellReceipt(pinThread),
324 scheduler,
325 concurrency,
326 }),
327 unpin: createEnvironmentCommand(runtime, {
328 label: "environment-data:commands:thread:unpin",
329 execute: withShellReceipt(unpinThread),
330 scheduler,
331 concurrency,
332 }),
333 reorderPin: createEnvironmentCommand(runtime, {
334 label: "environment-data:commands:thread:reorder-pin",
335 execute: withShellReceipt(reorderPinnedThread),
336 scheduler,
337 concurrency,
338 }),
339 setAutoSettle: createEnvironmentCommand(runtime, {
340 label: "environment-data:commands:thread:set-auto-settle",
341 execute: withShellReceipt(setThreadAutoSettle),
342 scheduler,
343 concurrency,
344 }),
345 reorderActive: createEnvironmentCommand(runtime, {
346 label: "environment-data:commands:thread:reorder-active",
347 execute: withShellReceipt(reorderActiveThread),
348 scheduler,
349 concurrency,
350 }),
351 visit: createEnvironmentCommand(runtime, {
352 label: "environment-data:commands:thread:visit",
353 execute: visitThread,
354 scheduler,
355 concurrency,
356 }),
357 markUnread: createEnvironmentCommand(runtime, {
358 label: "environment-data:commands:thread:mark-unread",
359 execute: markThreadUnread,
360 scheduler,
361 concurrency,
362 }),
363 updateMetadata: createEnvironmentCommand(runtime, {
364 label: "environment-data:commands:thread:update-metadata",
365 execute: updateThreadMetadata,
366 scheduler,
367 concurrency,
368 }),
369 linkPullRequest: createEnvironmentCommand(runtime, {
370 label: "environment-data:commands:thread:link-pull-request",
371 execute: linkThreadPullRequest,
372 scheduler,
373 concurrency,
374 }),
375 unlinkPullRequest: createEnvironmentCommand(runtime, {
376 label: "environment-data:commands:thread:unlink-pull-request",
377 execute: unlinkThreadPullRequest,
378 scheduler,
379 concurrency,
380 }),
381 watchPullRequest: createEnvironmentCommand(runtime, {
382 label: "environment-data:commands:thread:watch-pull-request",
383 execute: watchThreadPullRequest,
384 scheduler,
385 concurrency,
386 }),
387 setModelSelection: createEnvironmentCommand(runtime, {
388 label: "environment-data:commands:thread:set-model-selection",
389 execute: withShellReceipt(
390 (input: UpdateThreadMetadataInput & { readonly modelSelection: ModelSelection }) =>
391 updateThreadMetadata(input),
392 ),
393 scheduler,
394 concurrency,
395 }),
396 linkIssue: createEnvironmentCommand(runtime, {
397 label: "environment-data:commands:thread:link-issue",
398 execute: linkThreadIssue,
399 scheduler,
400 concurrency,
401 }),
402 unlinkIssue: createEnvironmentCommand(runtime, {
403 label: "environment-data:commands:thread:unlink-issue",
404 execute: unlinkThreadIssue,
405 scheduler,
406 concurrency,
407 }),
408 setRuntimeMode: createEnvironmentCommand(runtime, {
409 label: "environment-data:commands:thread:set-runtime-mode",
410 execute: setThreadRuntimeMode,
411 scheduler,
412 concurrency,
413 }),
414 setInteractionMode: createEnvironmentCommand(runtime, {
415 label: "environment-data:commands:thread:set-interaction-mode",
416 execute: setThreadInteractionMode,
417 scheduler,
418 concurrency,
419 }),
420 setToolOverrides: createEnvironmentCommand(runtime, {
421 label: "environment-data:commands:thread:set-tool-overrides",
422 execute: setThreadToolOverrides,
423 scheduler,
424 concurrency,
425 }),
426 startTurn: createEnvironmentCommand(runtime, {
427 label: "environment-data:commands:thread:start-turn",
428 execute: startThreadTurn,
429 scheduler,
430 concurrency,
431 }),
432 interruptTurn: createEnvironmentCommand(runtime, {
433 label: "environment-data:commands:thread:interrupt-turn",
434 execute: interruptTurn,
435 scheduler,
436 concurrency,
437 }),
438 respondToApproval: createEnvironmentCommand(runtime, {
439 label: "environment-data:commands:thread:respond-to-approval",
440 execute: respondToThreadApproval,
441 scheduler,
442 concurrency,
443 }),
444 respondToUserInput: createEnvironmentCommand(runtime, {
445 label: "environment-data:commands:thread:respond-to-user-input",
446 execute: respondToThreadUserInput,
447 scheduler,
448 concurrency,
449 }),
450 dismissUserInput: createEnvironmentCommand(runtime, {
451 label: "environment-data:commands:thread:dismiss-user-input",
452 execute: dismissThreadUserInput,
453 scheduler,
454 concurrency,
455 }),
456 revertCheckpoint: createEnvironmentCommand(runtime, {
457 label: "environment-data:commands:thread:revert-checkpoint",
458 execute: revertThreadCheckpoint,
459 scheduler,
460 concurrency,
461 }),
462 stopSession: createEnvironmentCommand(runtime, {
463 label: "environment-data:commands:thread:stop-session",
464 execute: stopThreadSession,
465 scheduler,
466 concurrency,
467 }),
468 forkFromRun: createEnvironmentCommand(runtime, {
469 label: "environment-data:commands:thread:fork-from-run",
470 execute: forkThreadFromRun,
471 scheduler,
472 concurrency: {
473 mode: "serial",
474 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
475 },
476 }),
477 forkSideChat: createEnvironmentCommand(runtime, {
478 label: "environment-data:commands:thread:fork-side-chat",
479 execute: forkSideChat,
480 scheduler,
481 concurrency: {
482 mode: "serial",
483 key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
484 },
485 }),
486 mergeBack: createEnvironmentCommand(runtime, {
487 label: "environment-data:commands:thread:merge-back",
488 execute: mergeThreadBack,
489 scheduler,
490 concurrency: {
491 mode: "serial",
492 key: ({ environmentId, input }) =>
493 JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]),
494 },
495 }),
496 resumeThreadQueue: createEnvironmentCommand(runtime, {
497 label: "environment-data:commands:thread:resume-queue",
498 execute: resumeThreadQueue,
499 scheduler,
500 concurrency,
501 }),
502 promoteQueuedRun: createEnvironmentCommand(runtime, {
503 label: "environment-data:commands:thread:promote-queued-run",
504 execute: promoteQueuedRun,
505 scheduler,
506 concurrency,
507 }),
508 cancelQueuedRun: createEnvironmentCommand(runtime, {
509 label: "environment-data:commands:thread:cancel-queued-run",
510 execute: cancelQueuedRun,
511 scheduler,
512 concurrency,
513 }),
514 retryWorkspacePreparation: createEnvironmentCommand(runtime, {
515 label: "environment-data:commands:thread:retry-workspace-preparation",
516 execute: retryWorkspacePreparation,
517 scheduler,
518 concurrency,
519 }),
520 editQueuedRun: createEnvironmentCommand(runtime, {
521 label: "environment-data:commands:thread:edit-queued-run",
522 execute: editQueuedRun,
523 scheduler,
524 concurrency,
525 }),
526 loadEarlierHistory: createEnvironmentCommand(runtime, {
527 label: "environment-data:commands:thread:load-earlier-history",
528 execute: loadEarlierHistory,
529 scheduler,
530 concurrency: {
531 mode: "serial",
532 key: ({ environmentId, input }) =>
533 `history:${JSON.stringify([environmentId, input.threadId])}`,
534 },
535 }),
536 uploadFeedback: createEnvironmentRpcCommand(runtime, {
537 label: "environment-data:commands:thread:upload-feedback",
538 tag: WS_METHODS.providerUploadFeedback,
539 scheduler,
540 concurrency,
541 }),
542 // Outside the thread's queue: finishing can wait on the agent, and messages must not.
543 mcpSignInStart: createEnvironmentRpcCommand(runtime, {
544 label: "environment-data:commands:thread:mcp-sign-in-start",
545 tag: WS_METHODS.providerMcpSignInStart,
546 onSuccess: ({ environmentId, input }, registry, result) =>
547 Effect.sync(() => {
548 if (result.signedInAt !== null) {
549 markMcpSignedIn(registry, environmentId, input, result.signedInAt);
550 }
551 }),
552 }),
553 mcpSignInComplete: createEnvironmentRpcCommand(runtime, {
554 label: "environment-data:commands:thread:mcp-sign-in-complete",
555 tag: WS_METHODS.providerMcpSignInComplete,
556 onSuccess: ({ environmentId, input }, registry, result) =>
557 Effect.sync(() => markMcpSignedIn(registry, environmentId, input, result.signedInAt)),
558 }),
559 };
560 const commands = {
561 ...sent,
562 delete: rowAction(sent.delete),
563 archive: rowAction(sent.archive),
564 unarchive: rowAction(sent.unarchive),
565 settle: rowAction(sent.settle),
566 unsettle: rowAction(sent.unsettle),
567 snooze: rowAction(sent.snooze),
568 unsnooze: rowAction(sent.unsnooze),
569 pin: rowAction(sent.pin),
570 unpin: rowAction(sent.unpin),
571 };
572 const triage = createThreadTriageOutbox({
573 runtime,
574 sourceSnapshotAtom: snapshotAtom,
575 shellStatusAtom,
576 apply: (thread, action, queuedAt) =>
577 action.type === "settle"
578 ? applySettle(thread, queuedAt, false)
579 : applySnooze(thread, action.snoozedUntil, queuedAt, false),
580 send: (registry, { environmentId, threadId, commandId, action }) =>
581 action.type === "settle"
582 ? settle.run(registry, { environmentId, input: { threadId, commandId } })
583 : snooze.run(registry, {
584 environmentId,
585 input: { threadId, commandId, snoozedUntil: action.snoozedUntil },
586 }),
587 readFamily: createEnvironmentRpcCommand(runtime, {
588 label: "environment-data:commands:thread:read-family",
589 tag: ORCHESTRATION_V2_WS_METHODS.getThreadFamily,
590 }),
591 });
592 const optimistic = createOptimisticThreadLifecycle(triage.snapshotAtom, commandHistoryAtom);
593 const settle = optimistic.wrap(commands.settle, (thread, _input, now, accepted) =>
594 applySettle(thread, now, accepted),
595 );
596 const snooze = optimistic.wrap(commands.snooze, (thread, input, now, accepted) =>
597 applySnooze(thread, input.snoozedUntil, now, accepted),
598 );
599 const disconnectedAtom = Atom.family((environmentId: EnvironmentId) =>
600 Atom.make((get) => {
601 const connection = AsyncResult.getOrElse(
602 get(environmentConnectionAtom(runtime, environmentId)),
603 () => null,
604 );
605 return connection !== null && connectionProjectionPhase(connection[0]) === "disconnected";
606 }),
607 );
608 const regenerateTitle = {
609 label: commands.armTitleRegeneration.label,
610 run: (
611 registry: AtomRegistry.AtomRegistry,
612 target: { readonly environmentId: EnvironmentId; readonly input: { threadId: ThreadId } },
613 ) =>
614 commands.armTitleRegeneration.run(registry, target).pipe(
615 Effect.flatMap(({ dispatched, value }) =>
616 waitForTitleRegenerationOutcome(
617 registry,
618 {
619 snapshot: snapshotAtom(target.environmentId),
620 disconnected: disconnectedAtom(target.environmentId),
621 historyInvalidated: Atom.make((get) =>
622 shellCommandHistoryInvalidated(
623 dispatched,
624 get(commandHistoryAtom(target.environmentId)),
625 ),
626 ),
627 },
628 { threadId: target.input.threadId, ...value },
629 ),
630 ),
631 ),
632 };
633 return {
634 ...commands,
635 regenerateTitle,
636 rowActionsAtom,
637 mcpSignedInAtom,
638 snapshotAtom: optimistic.snapshotAtom,
639 pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom,
640 pendingSyncAtom: triage.pendingSyncAtom,
641 // Queued inside the optimistic update, so it stays shown until the queued entry replaces it.
642 settle: optimistic.wrap(
643 triage.queueWhenOffline(commands.settle, () => ({ type: "settle" as const })),
644 (thread, _input, now, accepted) => applySettle(thread, now, accepted),
645 ),
646 unsettle: triage.cancelQueued(
647 optimistic.wrap(commands.unsettle, (thread, input, now) => ({
648 ...thread,
649 settledOverride: input.reason === "user" ? "active" : null,
650 settledAt: null,
651 unsettledAt:
652 thread.settledOverride === "active"
653 ? (thread.unsettledAt ?? null)
654 : input.restoreUnsettledAt === undefined
655 ? now
656 : input.restoreUnsettledAt === null
657 ? null
658 : DateTime.makeUnsafe(input.restoreUnsettledAt),
659 })),
660 "settle",
661 ),
662 snooze: optimistic.wrap(
663 triage.queueWhenOffline(commands.snooze, (input) => ({
664 type: "snooze" as const,
665 snoozedUntil: input.snoozedUntil,
666 })),
667 (thread, input, now, accepted) => applySnooze(thread, input.snoozedUntil, now, accepted),
668 ),
669 unsnooze: triage.cancelQueued(
670 optimistic.wrap(commands.unsnooze, (thread) => ({
671 ...thread,
672 snoozedUntil: null,
673 snoozedAt: null,
674 })),
675 "snooze",
676 ),
677 setAutoSettle: optimistic.wrap(commands.setAutoSettle, (thread, input, now) => ({
678 ...thread,
679 autoSettleDisabledAt: input.enabled ? null : (thread.autoSettleDisabledAt ?? now),
680 })),
681 pin: optimistic.wrap(commands.pin, (thread, input, now) => ({
682 ...thread,
683 pinnedAt: thread.pinnedAt ?? now,
684 pinOrderKey: thread.pinnedAt == null ? (input.orderKey ?? null) : thread.pinOrderKey,
685 ...(thread.settledOverride === "settled"
686 ? {
687 settledOverride: "active" as const,
688 settledAt: null,
689 unsettledAt: now,
690 }
691 : {}),
692 snoozedUntil: null,
693 snoozedAt: null,
694 })),
695 unpin: optimistic.wrap(commands.unpin, (thread) => ({
696 ...thread,
697 pinnedAt: null,
698 pinOrderKey: null,
699 })),
700 reorderPin: optimistic.wrap(commands.reorderPin, (thread, input) => ({
701 ...thread,
702 pinOrderKey: input.orderKey,
703 })),
704 reorderActive: optimistic.wrap(commands.reorderActive, (thread, input) => ({
705 ...thread,
706 activeOrderKey: input.orderKey,
707 })),
708 // Shown at once, so a composer that releases its accepted pick keeps showing it.
709 setModelSelection: optimistic.wrap(commands.setModelSelection, (thread, input) => ({
710 ...thread,
711 modelSelection: input.modelSelection,
712 })),
713 };
714}