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

useThreadLifecycle.tsx

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