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

useThreadLifecycle.tsx

619 lines25.2 KB

1import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3import type { Dispatch } from "react";
4import type { ComposerThreadTarget } from "../../composerDraftStore";
5import type { ComposerHandleRef } from "../../composerHandleContext";
6import {
7 isThreadWokeUnseen,
8 branchMismatchKey,
9 isBranchMismatchDismissedForSession,
10 shouldShowBranchMismatchBanner,
11 chatActionErrorMessage,
12 makeThreadErrorSetter,
13} from "../ChatView.logic";
14import { useStableCallback } from "../../hooks/useStableCallback";
15import type { usePendingThreadRequests } from "./usePendingThreadRequests";
16import {
17 AuthOrchestrationOperateScope,
18 AuthSourceControlWriteScope,
19 type EnvironmentId,
20 type ScopedThreadRef,
21 type ThreadId,
22 ProviderInteractionMode,
23 RuntimeMode,
24} from "@t3tools/contracts";
25import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
26import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions";
27import { settleAndAdvance } from "../../settleAndAdvance";
28import type { ChatShortcutCommands } from "./useChatShortcuts";
29import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
30import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
31import { type SetStateAction, useEffect, useRef, useState } from "react";
32import { useNavigate, useRouter } from "@tanstack/react-router";
33import {
34 isAtomCommandInterrupted,
35 squashAtomCommandFailure,
36 type AtomCommandResult,
37} from "@t3tools/client-runtime/state/runtime";
38import { useUiStateStore } from "../../uiStateStore";
39import { type ChatMessage } from "../../types";
40import { AlarmClockIcon, CheckCircle2Icon } from "lucide-react";
41import { stackedThreadToast, toastManager } from "../ui/toast";
42import { newMessageId } from "~/lib/utils";
43import { buildThreadRouteParams } from "../../threadRoutes";
44import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore";
45import { useEnvironmentScope } from "~/state/session";
46import { threadEnvironment } from "../../state/threads";
47import { vcsEnvironment } from "../../state/vcs";
48import { useChildThreadInputs, readThreadShell, waitForThreadShell } from "../../state/entities";
49import { environmentShell } from "../../state/shell";
50import { ThreadStatusLine } from "./ThreadStatusLine";
51import { formatRelativeTimeLabel, formatRelativeTimeUntilLabel } from "../../timestampFormat";
52import { appAtomRegistry } from "../../rpc/atomRegistry";
53import { readEnvironmentScope } from "../../state/session";
54import { useAtomCommand } from "../../state/use-atom-command";
55import { useOrchestrationCommand } from "../../state/use-orchestration-command";
56import {
57 backgroundWorkBannerItem,
58 childInputBannerItem,
59 goalBannerItem,
60} from "./ThreadActivityBanners";
61import type { useLocalDispatchState } from "./useLocalDispatchState";
62const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
63​
64type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
65type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
66​
67interface ThreadLifecycleInput {
68 readonly environmentId: EnvironmentId;
69 readonly routeThreadKey: string;
70 readonly currentRouteThreadKeyRef: { readonly current: string | null };
71 readonly canOperateThread: boolean;
72 readonly clientSettingsHydrated: boolean;
73 readonly activeThread: EnvironmentThreadShell | undefined;
74 readonly activeThreadId: ThreadId | null;
75 readonly activeThreadRef: ScopedThreadRef | null;
76 readonly activeThreadKey: string | null;
77 readonly activeThreadShell: EnvironmentThreadShell | null;
78 readonly activeLatestRun: EnvironmentThreadShell["latestRun"];
79 readonly activeProjectCwd: string | null;
80 readonly serverConfig: EnvironmentServerConfig | null;
81 readonly runtimeMode: RuntimeMode;
82 readonly isWorking: boolean;
83 readonly pendingBackgroundTasks: Parameters<typeof backgroundWorkBannerItem>[0]["tasks"];
84 readonly activePendingApproval: PendingThreadRequests["activePendingApproval"];
85 readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"];
86 readonly localCheckoutBranchMismatch: {
87 readonly threadBranch: string;
88 readonly currentBranch: string;
89 } | null;
90 readonly gitStatusQuery: { readonly refresh: () => void };
91 readonly nowMinute: string;
92 readonly composerRef: ComposerHandleRef;
93 readonly composerDraftTarget: ComposerThreadTarget;
94 readonly sendInFlightRef: { current: boolean };
95 readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
96 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
97 readonly clearUsageLimitsFor: (threadKey: string) => void;
98 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
99 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
100 readonly scheduleComposerFocus: () => void;
101 readonly scrollToEnd: (animated?: boolean) => void;
102 readonly persistThreadSettingsForNextTurn: (input: {
103 threadId: ThreadId;
104 createdAt: string;
105 branch?: string;
106 runtimeMode: RuntimeMode;
107 interactionMode: ProviderInteractionMode;
108 }) => Promise<AtomCommandResult<void, unknown>>;
110​
111/**
112 * Thread state the chat shows and changes outside a normal send: snooze and settle with
113 * their status line, the local checkout's branch, background work, child-thread and goal
114 * banners, opening related threads, and standalone slash commands.
115 */
116export function useThreadLifecycle(input: ThreadLifecycleInput) {
117 const {
118 environmentId,
119 routeThreadKey,
120 currentRouteThreadKeyRef,
121 canOperateThread,
122 clientSettingsHydrated,
123 activeThread,
124 activeThreadId,
125 activeThreadRef,
126 activeThreadKey,
127 activeThreadShell,
128 activeLatestRun,
129 activeProjectCwd,
130 serverConfig,
131 runtimeMode,
132 isWorking,
133 pendingBackgroundTasks,
134 activePendingApproval,
135 activePendingUserInput,
136 localCheckoutBranchMismatch,
137 gitStatusQuery,
138 nowMinute,
139 composerRef,
140 composerDraftTarget,
141 sendInFlightRef,
142 setOptimisticUserMessages,
143 setThreadError,
144 clearUsageLimitsFor,
145 beginLocalDispatch,
146 resetLocalDispatch,
147 scheduleComposerFocus,
148 scrollToEnd,
149 persistThreadSettingsForNextTurn,
150 } = input;
151 const navigate = useNavigate();
152 const router = useRouter();
153 const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
154 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
155 const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
156 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
157 reportFailure: false,
158 });
159 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
160 reportFailure: false,
161 });
162 const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
163 reportFailure: false,
164 });
165​
166 const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
167 const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
168 const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
169 const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null;
170 // The compiler caches render results on their inputs, so a clock read in render
171 // stays frozen until the shell changes. The clock is state: reset with the shell,
172 // and moved by the wake timer.
173 const [snoozeClockState, setSnoozeClockState] = useState(() => ({
174 shell: activeThreadShell,
175 now: new Date().toISOString(),
176 }));
177 if (snoozeClockState.shell !== activeThreadShell) {
178 setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
179 }
180 const snoozeClock = snoozeClockState.now;
181 const activeThreadSnoozed =
182 activeThreadShell !== null &&
183 supportsSnooze &&
184 effectiveSnoozed(activeThreadShell, { now: snoozeClock });
185 useEffect(() => {
186 if (!activeThreadSnoozed) return;
187 const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
188 if (!Number.isFinite(wakeAtMs)) return;
189 const id = window.setTimeout(
190 () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
191 Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
192 );
193 return () => window.clearTimeout(id);
194 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
195 }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
196 const activeThreadWokeAt =
197 activeThreadShell !== null && supportsSnooze
198 ? threadWokeAt(activeThreadShell, { now: snoozeClock })
199 : null;
200 const acknowledgeThreadWoke = useAcknowledgeThreadWoke();
201 const acknowledgeActiveThreadWoke = () => {
202 if (activeThreadRef === null || activeThreadWokeAt === null) return;
203 acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt);
204 };
205 const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke);
206 const activeThreadLocalVisitedAt = useUiStateStore((store) =>
207 activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
208 );
209 const activeThreadLastVisitedAt = resolveThreadLastVisitedAt(
210 activeThreadShell?.lastVisitedAt,
211 activeThreadLocalVisitedAt,
212 );
213 const activeThreadWokeVisible = isThreadWokeUnseen({
214 wokeAt: activeThreadWokeAt,
215 settled: activeThreadShell?.settledOverride === "settled",
216 lastVisitedAt: activeThreadLastVisitedAt,
217 latestRunCompletedAt: activeLatestRun?.completedAt ?? null,
218 });
219 const activeThreadSettled =
220 supportsSettlement && activeThreadShell?.settledOverride === "settled";
221 const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
222 reportFailure: false,
223 });
224 const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
225 const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
226 const handleUnsettleActiveThread = async () => {
227 if (
228 !activeThreadRef ||
229 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
230 )
231 return;
232 const threadKey = scopedThreadKey(activeThreadRef);
233 setUnsettlingThreadKey(threadKey);
234 // Commands settle into a result, so this always runs.
235 const result = await unsettleThreadMutation({
236 environmentId: activeThreadRef.environmentId,
237 input: { threadId: activeThreadRef.threadId, reason: "user" },
238 });
239 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
240 const error = squashAtomCommandFailure(result);
241 toastManager.add(
242 stackedThreadToast({
243 type: "error",
244 title: "Failed to un-settle thread",
245 description: error instanceof Error ? error.message : "An error occurred.",
246 }),
247 );
248 }
249 setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
250 };
251 const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
252 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
253 reportFailure: false,
254 });
255 const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
256 const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
257 const handleUnsnoozeActiveThread = async () => {
258 if (
259 !activeThreadRef ||
260 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
261 )
262 return;
263 const threadKey = scopedThreadKey(activeThreadRef);
264 setUnsnoozingThreadKey(threadKey);
265 // Commands settle into a result, so this always runs.
266 const recovery = activeThreadShell?.limitRecovery;
267 const recoveryOwnsSnooze =
268 recovery?.snooze === true &&
269 recovery.runId === activeThreadShell?.latestRun?.runId &&
270 activeThreadShell?.snoozedUntil != null &&
271 Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
272 const result = recoveryOwnsSnooze
273 ? await updateThreadMetadata({
274 environmentId: activeThreadRef.environmentId,
275 input: {
276 threadId: activeThreadRef.threadId,
277 limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
278 },
279 })
280 : await unsnoozeThreadMutation({
281 environmentId: activeThreadRef.environmentId,
282 input: { threadId: activeThreadRef.threadId, reason: "user" },
283 });
284 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
285 const error = squashAtomCommandFailure(result);
286 toastManager.add(
287 stackedThreadToast({
288 type: "error",
289 title: "Failed to wake thread",
290 description: error instanceof Error ? error.message : "An error occurred.",
291 }),
292 );
293 }
294 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
295 };
296 const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
297 const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
298 const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
299 const [, setBranchMismatchDismissTick] = useState(0);
300 const composerHasDraftContent = useComposerDraftStore((store) =>
301 composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
302 );
303 const activeBranchMismatchKey = branchMismatchKey(
304 activeThread?.id ?? null,
305 localCheckoutBranchMismatch,
306 );
307 const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
308 hasMismatch: localCheckoutBranchMismatch !== null,
309 isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
310 composerHasContent: composerHasDraftContent,
311 wasShownForCurrentMismatch:
312 revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
313 });
314 const nextRevealedBranchMismatchKey = showBranchMismatchBanner
315 ? activeBranchMismatchKey
316 : revealedBranchMismatchKey !== activeBranchMismatchKey
317 ? null
318 : revealedBranchMismatchKey;
319 if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
320 setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
321 }
322 const handleSwitchCheckoutToThread = async () => {
323 if (!canWriteSourceControl) return;
324 if (
325 !activeProjectCwd ||
326 !activeThread ||
327 !localCheckoutBranchMismatch ||
328 isRestoringThreadBranch
329 ) {
330 return;
331 }
332 setIsRestoringThreadBranch(true);
333 const checkoutResult = await switchGitRef({
334 environmentId,
335 input: {
336 cwd: activeProjectCwd,
337 refName: localCheckoutBranchMismatch.threadBranch,
338 },
339 });
340 if (checkoutResult._tag === "Failure") {
341 setIsRestoringThreadBranch(false);
342 if (!isAtomCommandInterrupted(checkoutResult)) {
343 toastManager.add(
344 stackedThreadToast({
345 type: "error",
346 title: "Failed to switch checkout",
347 description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
348 }),
349 );
350 }
351 return;
352 }
353​
354 if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
355 setIsRestoringThreadBranch(false);
356 return;
357 }
358 const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
359 if (nextBranch !== activeThread.branch) {
360 const updateResult = await updateThreadMetadata({
361 environmentId,
362 input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
363 });
364 if (updateResult._tag === "Failure") {
365 setIsRestoringThreadBranch(false);
366 if (!isAtomCommandInterrupted(updateResult)) {
367 toastManager.add(
368 stackedThreadToast({
369 type: "error",
370 title: "Checkout switched, but the thread could not be updated",
371 description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
372 }),
373 );
374 }
375 gitStatusQuery.refresh();
376 return;
377 }
378 }
379 gitStatusQuery.refresh();
380 setIsRestoringThreadBranch(false);
381 scheduleComposerFocus();
382 };
383 const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
384 void handleSwitchCheckoutToThread();
385 });
386 // The interrupt path also accepts a completed run while its provider still
387 // has background work.
388 const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
389 const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
390 const isStoppingBackgroundWork =
391 stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
392 const handleStopBackgroundWork = async () => {
393 if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
394 return;
395 const requestKey = `${environmentId}:${activeThread.id}`;
396 setStoppingBackgroundWorkKey(requestKey);
397 const result = await interruptThreadTurn({
398 environmentId,
399 input: { threadId: activeThread.id },
400 });
401 // Acceptance does not confirm termination. Allow retry while the provider
402 // finishes stopping the tasks or reports a failure.
403 setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
404 if (result._tag === "Failure") {
405 if (!isAtomCommandInterrupted(result)) {
406 const error = squashAtomCommandFailure(result);
407 setThreadError(
408 activeThread.id,
409 error instanceof Error ? error.message : "Failed to stop background work.",
410 );
411 }
412 }
413 };
414 const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
415 const openRelatedThreadGenerationRef = useRef(0);
416 const onOpenRelatedThread = async (threadId: ThreadId) => {
417 const generation = ++openRelatedThreadGenerationRef.current;
418 const threadRef = scopeThreadRef(environmentId, threadId);
419 const isEnvironmentLive = () =>
420 appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live";
421 // The shell can leave idle subagent children out, so absence is not deletion there: the
422 // route decides from the thread's own detail.
423 const shellOmitsChildren = serverConfig?.shellThreadFamilies === true;
424 // A just-launched child can reach this timeline before its shell syncs.
425 if (!shellOmitsChildren && isEnvironmentLive() && readThreadShell(threadRef) === null) {
426 const location = router.latestLocation;
427 await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
428 if (
429 generation !== openRelatedThreadGenerationRef.current ||
430 currentRouteThreadKeyRef.current !== routeThreadKey ||
431 router.latestLocation !== location
432 ) {
433 return;
434 }
435 }
436 const shell = readThreadShell(threadRef);
437 if (shell === null ? !shellOmitsChildren && isEnvironmentLive() : shell.deletedAt != null) {
438 toastManager.add({ type: "info", title: "This thread is no longer available" });
439 return;
440 }
441 void navigate({
442 to: "/$environmentId/$threadId",
443 params: buildThreadRouteParams(threadRef),
444 });
445 };
446 const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
447 const childThreadInputs = useChildThreadInputs(activeThreadRef);
448 const childInputBanner = childInputBannerItem({
449 childThreadInputs,
450 parentAwaitingUser: Boolean(
451 activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
452 ),
453 onOpenThread: onOpenRelatedThreadStable,
454 });
455​
456 const sendStandaloneCommand = async (text: string, failureMessage: string) => {
457 if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
458 const context = composerRef.current?.getSendContext();
459 if (!context?.providerAvailable) return;
460​
461 const threadId = activeThread.id;
462 const messageId = newMessageId();
463 const createdAt = new Date().toISOString();
464 sendInFlightRef.current = true;
465 beginLocalDispatch();
466 setThreadError(threadId, null);
467 setOptimisticUserMessages((messages) => [
468 ...messages,
469 {
470 id: messageId,
471 role: "user",
472 text,
473 runId: null,
474 createdAt,
475 updatedAt: createdAt,
476 streaming: false,
477 },
478 ]);
479 scrollToEnd();
480 // Commands settle into a result, so this always runs.
481 const settingsResult = await persistThreadSettingsForNextTurn({
482 threadId,
483 createdAt,
484 ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
485 runtimeMode,
486 interactionMode: context.interactionMode,
487 });
488 const result =
489 settingsResult._tag === "Failure"
490 ? settingsResult
491 : await startThreadTurn({
492 environmentId,
493 input: {
494 threadId,
495 message: { messageId, role: "user", text, attachments: [] },
496 modelSelection: context.selectedModelSelection,
497 runtimeMode,
498 interactionMode: context.interactionMode,
499 createdAt,
500 },
501 });
502 if (result._tag === "Failure") {
503 setOptimisticUserMessages((messages) =>
504 messages.filter((message) => message.id !== messageId),
505 );
506 resetLocalDispatch();
507 if (!isAtomCommandInterrupted(result)) {
508 const error = squashAtomCommandFailure(result);
509 setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
510 }
511 } else {
512 clearUsageLimitsFor(routeThreadKey);
513 }
514 sendInFlightRef.current = false;
515 };
516 const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
517 const activeGoal = activeThreadShell?.goal ?? null;
518 const goalBanner =
519 activeThread && activeGoal !== null
520 ? goalBannerItem({
521 threadId: activeThread.id,
522 goal: activeGoal,
523 isWorking,
524 onSendCommand: sendStandaloneCommandStable,
525 })
526 : null;
527​
528 const backgroundWorkBanner = activeThread
529 ? backgroundWorkBannerItem({
530 threadId: activeThread.id,
531 tasks: activeBackgroundTasks,
532 stopDisabled: !canOperateThread || isStoppingBackgroundWork,
533 stopping: isStoppingBackgroundWork,
534 onStop: handleStopBackgroundWorkStable,
535 onOpenThread: onOpenRelatedThreadStable,
536 })
537 : null;
538 // The relative times read the clock; nowMinute re-renders them on the minute.
539 const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
540 const settledAt = activeThreadShell?.settledAt ?? null;
541 const threadStatusLine = activeThreadSnoozed ? (
542 <ThreadStatusLine
543 icon={<AlarmClockIcon />}
544 label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"}
545 clockMinute={nowMinute}
546 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
547 actionDisabled={!canOperateThread || isUnsnoozing}
548 onAction={() => void handleUnsnoozeActiveThreadStable()}
549 />
550 ) : activeThreadSettled ? (
551 <ThreadStatusLine
552 icon={<CheckCircle2Icon />}
553 label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
554 clockMinute={nowMinute}
555 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
556 actionDisabled={!canOperateThread || isUnsettling}
557 onAction={() => void handleUnsettleActiveThreadStable()}
558 />
559 ) : activeThreadWokeVisible ? (
560 <ThreadStatusLine
561 icon={<AlarmClockIcon />}
562 label="Woke from snooze"
563 actionLabel="Dismiss"
564 onAction={acknowledgeActiveThreadWokeStable}
565 />
566 ) : null;
567 const toastThreadActionFailure =
568 (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
569 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
570 const error = squashAtomCommandFailure(result);
571 toastManager.add(
572 stackedThreadToast({
573 type: "error",
574 title,
575 description: error instanceof Error ? error.message : "An error occurred.",
576 }),
577 );
578 };
579 const shortcuts = {
580 "thread.settle": () => {
581 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
582 if (!activeThreadShell || !activeThreadRef || !supportsSettlement) return;
583 if (activeThreadSettled) {
584 void handleUnsettleActiveThread();
585 return;
586 }
587 if (settleAndAdvance(activeThreadRef)) return;
588 void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
589 },
590 "thread.pin": () => {
591 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
592 if (!activeThreadShell || !activeThreadRef || !supportsPinning) return;
593 void (
594 activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
595 ).then(
596 toastThreadActionFailure(
597 activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread",
598 ),
599 );
600 },
601 } satisfies ChatShortcutCommands;
602 return {
603 shortcuts,
604 acknowledgeActiveThreadWoke,
605 activeBranchMismatchKey,
606 backgroundWorkBanner,
607 childInputBanner,
608 goalBanner,
609 handleSwitchCheckoutToThread,
610 handleSwitchCheckoutToThreadStable,
611 isRestoringThreadBranch,
612 onOpenRelatedThread,
613 onOpenRelatedThreadStable,
614 sendStandaloneCommand,
615 setBranchMismatchDismissTick,
616 showBranchMismatchBanner,
617 threadStatusLine,
618 };