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

useThreadLifecycle.tsx

616 lines24.9 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 // A just-launched child can reach this timeline before its shell syncs.
422 if (isEnvironmentLive() && readThreadShell(threadRef) === null) {
423 const location = router.latestLocation;
424 await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
425 if (
426 generation !== openRelatedThreadGenerationRef.current ||
427 currentRouteThreadKeyRef.current !== routeThreadKey ||
428 router.latestLocation !== location
429 ) {
430 return;
431 }
432 }
433 const shell = readThreadShell(threadRef);
434 if (shell === null ? isEnvironmentLive() : shell.deletedAt != null) {
435 toastManager.add({ type: "info", title: "This thread is no longer available" });
436 return;
437 }
438 void navigate({
439 to: "/$environmentId/$threadId",
440 params: buildThreadRouteParams(threadRef),
441 });
442 };
443 const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
444 const childThreadInputs = useChildThreadInputs(activeThreadRef);
445 const childInputBanner = childInputBannerItem({
446 childThreadInputs,
447 parentAwaitingUser: Boolean(
448 activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
449 ),
450 onOpenThread: onOpenRelatedThreadStable,
451 });
452​
453 const sendStandaloneCommand = async (text: string, failureMessage: string) => {
454 if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
455 const context = composerRef.current?.getSendContext();
456 if (!context?.providerAvailable) return;
457​
458 const threadId = activeThread.id;
459 const messageId = newMessageId();
460 const createdAt = new Date().toISOString();
461 sendInFlightRef.current = true;
462 beginLocalDispatch();
463 setThreadError(threadId, null);
464 setOptimisticUserMessages((messages) => [
465 ...messages,
466 {
467 id: messageId,
468 role: "user",
469 text,
470 runId: null,
471 createdAt,
472 updatedAt: createdAt,
473 streaming: false,
474 },
475 ]);
476 scrollToEnd();
477 // Commands settle into a result, so this always runs.
478 const settingsResult = await persistThreadSettingsForNextTurn({
479 threadId,
480 createdAt,
481 ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
482 runtimeMode,
483 interactionMode: context.interactionMode,
484 });
485 const result =
486 settingsResult._tag === "Failure"
487 ? settingsResult
488 : await startThreadTurn({
489 environmentId,
490 input: {
491 threadId,
492 message: { messageId, role: "user", text, attachments: [] },
493 modelSelection: context.selectedModelSelection,
494 runtimeMode,
495 interactionMode: context.interactionMode,
496 createdAt,
497 },
498 });
499 if (result._tag === "Failure") {
500 setOptimisticUserMessages((messages) =>
501 messages.filter((message) => message.id !== messageId),
502 );
503 resetLocalDispatch();
504 if (!isAtomCommandInterrupted(result)) {
505 const error = squashAtomCommandFailure(result);
506 setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
507 }
508 } else {
509 clearUsageLimitsFor(routeThreadKey);
510 }
511 sendInFlightRef.current = false;
512 };
513 const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
514 const activeGoal = activeThreadShell?.goal ?? null;
515 const goalBanner =
516 activeThread && activeGoal !== null
517 ? goalBannerItem({
518 threadId: activeThread.id,
519 goal: activeGoal,
520 isWorking,
521 onSendCommand: sendStandaloneCommandStable,
522 })
523 : null;
524​
525 const backgroundWorkBanner = activeThread
526 ? backgroundWorkBannerItem({
527 threadId: activeThread.id,
528 tasks: activeBackgroundTasks,
529 stopDisabled: !canOperateThread || isStoppingBackgroundWork,
530 stopping: isStoppingBackgroundWork,
531 onStop: handleStopBackgroundWorkStable,
532 onOpenThread: onOpenRelatedThreadStable,
533 })
534 : null;
535 // The relative times read the clock; nowMinute re-renders them on the minute.
536 const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
537 const settledAt = activeThreadShell?.settledAt ?? null;
538 const threadStatusLine = activeThreadSnoozed ? (
539 <ThreadStatusLine
540 icon={<AlarmClockIcon />}
541 label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"}
542 clockMinute={nowMinute}
543 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
544 actionDisabled={!canOperateThread || isUnsnoozing}
545 onAction={() => void handleUnsnoozeActiveThreadStable()}
546 />
547 ) : activeThreadSettled ? (
548 <ThreadStatusLine
549 icon={<CheckCircle2Icon />}
550 label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
551 clockMinute={nowMinute}
552 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
553 actionDisabled={!canOperateThread || isUnsettling}
554 onAction={() => void handleUnsettleActiveThreadStable()}
555 />
556 ) : activeThreadWokeVisible ? (
557 <ThreadStatusLine
558 icon={<AlarmClockIcon />}
559 label="Woke from snooze"
560 actionLabel="Dismiss"
561 onAction={acknowledgeActiveThreadWokeStable}
562 />
563 ) : null;
564 const toastThreadActionFailure =
565 (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
566 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
567 const error = squashAtomCommandFailure(result);
568 toastManager.add(
569 stackedThreadToast({
570 type: "error",
571 title,
572 description: error instanceof Error ? error.message : "An error occurred.",
573 }),
574 );
575 };
576 const shortcuts = {
577 "thread.settle": () => {
578 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
579 if (!activeThreadShell || !activeThreadRef || !supportsSettlement) return;
580 if (activeThreadSettled) {
581 void handleUnsettleActiveThread();
582 return;
583 }
584 if (settleAndAdvance(activeThreadRef)) return;
585 void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
586 },
587 "thread.pin": () => {
588 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
589 if (!activeThreadShell || !activeThreadRef || !supportsPinning) return;
590 void (
591 activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
592 ).then(
593 toastThreadActionFailure(
594 activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread",
595 ),
596 );
597 },
598 } satisfies ChatShortcutCommands;
599 return {
600 shortcuts,
601 acknowledgeActiveThreadWoke,
602 activeBranchMismatchKey,
603 backgroundWorkBanner,
604 childInputBanner,
605 goalBanner,
606 handleSwitchCheckoutToThread,
607 handleSwitchCheckoutToThreadStable,
608 isRestoringThreadBranch,
609 onOpenRelatedThread,
610 onOpenRelatedThreadStable,
611 sendStandaloneCommand,
612 setBranchMismatchDismissTick,
613 showBranchMismatchBanner,
614 threadStatusLine,
615 };