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