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

useThreadLifecycle.tsx

608 lines24.4 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 turnItems: Parameters<typeof backgroundWorkNowItem>[0]["turnItems"];
86 readonly activePendingApproval: PendingThreadRequests["activePendingApproval"];
87 readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"];
88 readonly localCheckoutBranchMismatch: {
89 readonly threadBranch: string;
90 readonly currentBranch: string;
91 } | null;
92 readonly gitStatusQuery: { readonly refresh: () => void };
93 readonly nowMinute: string;
94 readonly composerRef: ComposerHandleRef;
95 readonly composerDraftTarget: ComposerThreadTarget;
96 readonly sendInFlightRef: { current: boolean };
97 readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
98 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
99 readonly clearUsageLimitsFor: (threadKey: string) => void;
100 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
101 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
102 readonly scheduleComposerFocus: () => void;
103 readonly scrollToEnd: (animated?: boolean) => void;
104 readonly persistThreadSettingsForNextTurn: (input: {
105 threadId: ThreadId;
106 createdAt: string;
107 branch?: string;
108 runtimeMode: RuntimeMode;
109 interactionMode: ProviderInteractionMode;
110 }) => Promise<AtomCommandResult<void, unknown>>;
112​
113/**
114 * Thread state the chat shows and changes outside a normal send: snooze and settle with
115 * their status line, the local checkout's branch, background work, child-thread and goal
116 * banners, opening related threads, and standalone slash commands.
117 */
118export function useThreadLifecycle(input: ThreadLifecycleInput) {
119 const {
120 environmentId,
121 routeThreadKey,
122 currentRouteThreadKeyRef,
123 canOperateThread,
124 clientSettingsHydrated,
125 activeThread,
126 activeThreadId,
127 activeThreadRef,
128 activeThreadKey,
129 activeThreadShell,
130 activeLatestRun,
131 activeProjectCwd,
132 serverConfig,
133 runtimeMode,
134 isWorking,
135 pendingBackgroundTasks,
136 turnItems,
137 activePendingApproval,
138 activePendingUserInput,
139 localCheckoutBranchMismatch,
140 gitStatusQuery,
141 nowMinute,
142 composerRef,
143 composerDraftTarget,
144 sendInFlightRef,
145 setOptimisticUserMessages,
146 setThreadError,
147 clearUsageLimitsFor,
148 beginLocalDispatch,
149 resetLocalDispatch,
150 scheduleComposerFocus,
151 scrollToEnd,
152 persistThreadSettingsForNextTurn,
153 } = input;
154 const navigate = useNavigate();
155 const router = useRouter();
156 const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
157 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
158 const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
159 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
160 reportFailure: false,
161 });
162 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
163 reportFailure: false,
164 });
165 const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
166 reportFailure: false,
167 });
168​
169 const serverConfigLoaded = serverConfig !== null;
170 const activeThreadPinned = serverConfigLoaded && 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 serverConfigLoaded &&
179 effectiveSnoozed(activeThreadShell, { now: snoozeClock });
180 const activeThreadWokeAt =
181 activeThreadShell !== null && serverConfigLoaded
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 serverConfigLoaded && 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 turnItems,
517 stopDisabled: !canOperateThread || isStoppingBackgroundWork,
518 stopping: isStoppingBackgroundWork,
519 onStop: handleStopBackgroundWorkStable,
520 onOpenThread: onOpenRelatedThreadStable,
521 })
522 : null;
523 // The relative times read the clock; nowMinute re-renders them on the minute.
524 const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
525 const settledAt = activeThreadShell?.settledAt ?? null;
526 // Same rounding as the sidebar's snoozed shelf, so both read the same hour.
527 const snoozeWake = snoozedUntil
528 ? snoozeWakeLabel(snoozedUntil, { now: `${nowMinute}:00.000Z` })
529 : null;
530 const threadStatusLine = activeThreadSnoozed ? (
531 <ThreadStatusLine
532 icon={<AlarmClockIcon />}
533 label={snoozeWake && snoozeWake !== "now" ? `Snoozed, ${snoozeWake} left` : "Snoozed"}
534 clockMinute={nowMinute}
535 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
536 actionDisabled={!canOperateThread || isUnsnoozing}
537 onAction={() => void handleUnsnoozeActiveThreadStable()}
538 />
539 ) : activeThreadSettled ? (
540 <ThreadStatusLine
541 icon={<CheckCircle2Icon />}
542 label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
543 clockMinute={nowMinute}
544 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
545 actionDisabled={!canOperateThread || isUnsettling}
546 onAction={() => void handleUnsettleActiveThreadStable()}
547 />
548 ) : activeThreadWokeVisible ? (
549 <ThreadStatusLine
550 icon={<AlarmClockIcon />}
551 label="Woke from snooze"
552 actionLabel="Dismiss"
553 onAction={acknowledgeActiveThreadWokeStable}
554 />
555 ) : null;
556 const toastThreadActionFailure =
557 (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
558 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
559 const error = squashAtomCommandFailure(result);
560 toastManager.add(
561 stackedThreadToast({
562 type: "error",
563 title,
564 description: error instanceof Error ? error.message : "An error occurred.",
565 }),
566 );
567 };
568 const shortcuts = {
569 "thread.settle": () => {
570 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
571 if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return;
572 if (activeThreadSettled) {
573 void handleUnsettleActiveThread();
574 return;
575 }
576 if (settleAndAdvance(activeThreadRef)) return;
577 void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
578 },
579 "thread.pin": () => {
580 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
581 if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return;
582 void (
583 activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
584 ).then(
585 toastThreadActionFailure(
586 activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread",
587 ),
588 );
589 },
590 } satisfies ChatShortcutCommands;
591 return {
592 shortcuts,
593 acknowledgeActiveThreadWoke,
594 activeBranchMismatchKey,
595 backgroundWorkNow,
596 childInputNow,
597 goalNow,
598 handleSwitchCheckoutToThread,
599 handleSwitchCheckoutToThreadStable,
600 isRestoringThreadBranch,
601 onOpenRelatedThread,
602 onOpenRelatedThreadStable,
603 sendStandaloneCommand,
604 setBranchMismatchDismissTick,
605 showBranchMismatchBanner,
606 threadStatusLine,
607 };