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