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