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 // oxlint-disable-next-line react/purity -- Reseeds the snooze clock only in the render-phase adjustment that runs when the shell changes.
183 setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
184 }
185 const snoozeClock = snoozeClockState.now;
186 const activeThreadSnoozed =
187 activeThreadShell !== null &&
188 supportsSnooze &&
189 effectiveSnoozed(activeThreadShell, { now: snoozeClock });
190 useEffect(() => {
191 if (!activeThreadSnoozed) return;
192 const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
193 if (!Number.isFinite(wakeAtMs)) return;
194 const id = window.setTimeout(
195 () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
196 Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
197 );
198 return () => window.clearTimeout(id);
199 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
200 }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
201 const activeThreadWokeAt =
202 activeThreadShell !== null && supportsSnooze
203 ? threadWokeAt(activeThreadShell, { now: snoozeClock })
204 : null;
205 const acknowledgeThreadWoke = useAcknowledgeThreadWoke();
206 const acknowledgeActiveThreadWoke = () => {
207 if (activeThreadRef === null || activeThreadWokeAt === null) return;
208 acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt);
209 };
210 const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke);
211 const activeThreadLocalVisitedAt = useUiStateStore((store) =>
212 activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
213 );
214 const activeThreadLastVisitedAt = resolveThreadLastVisitedAt(
215 activeThreadShell?.lastVisitedAt,
216 activeThreadLocalVisitedAt,
217 );
218 const activeThreadWokeVisible = isThreadWokeUnseen({
219 wokeAt: activeThreadWokeAt,
220 settled: activeThreadShell?.settledOverride === "settled",
221 lastVisitedAt: activeThreadLastVisitedAt,
222 latestRunCompletedAt: activeLatestRun?.completedAt ?? null,
223 });
224 const activeThreadSettled =
225 supportsSettlement && activeThreadShell?.settledOverride === "settled";
226 const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
227 reportFailure: false,
228 });
229 const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
230 const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
231 const handleUnsettleActiveThread = async () => {
232 if (
233 !activeThreadRef ||
234 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
235 )
236 return;
237 const threadKey = scopedThreadKey(activeThreadRef);
238 setUnsettlingThreadKey(threadKey);
239 // Commands settle into a result, so this always runs.
240 const result = await unsettleThreadMutation({
241 environmentId: activeThreadRef.environmentId,
242 input: { threadId: activeThreadRef.threadId, reason: "user" },
243 });
244 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
245 const error = squashAtomCommandFailure(result);
246 toastManager.add(
247 stackedThreadToast({
248 type: "error",
249 title: "Failed to un-settle thread",
250 description: error instanceof Error ? error.message : "An error occurred.",
251 }),
252 );
253 }
254 setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
255 };
256 const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
257 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
258 reportFailure: false,
259 });
260 const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
261 const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
262 const handleUnsnoozeActiveThread = async () => {
263 if (
264 !activeThreadRef ||
265 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
266 )
267 return;
268 const threadKey = scopedThreadKey(activeThreadRef);
269 setUnsnoozingThreadKey(threadKey);
270 // Commands settle into a result, so this always runs.
271 const recovery = activeThreadShell?.limitRecovery;
272 const recoveryOwnsSnooze =
273 recovery?.snooze === true &&
274 recovery.runId === activeThreadShell?.latestRun?.runId &&
275 activeThreadShell?.snoozedUntil != null &&
276 Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
277 const result = recoveryOwnsSnooze
278 ? await updateThreadMetadata({
279 environmentId: activeThreadRef.environmentId,
280 input: {
281 threadId: activeThreadRef.threadId,
282 limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
283 },
284 })
285 : await unsnoozeThreadMutation({
286 environmentId: activeThreadRef.environmentId,
287 input: { threadId: activeThreadRef.threadId, reason: "user" },
288 });
289 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
290 const error = squashAtomCommandFailure(result);
291 toastManager.add(
292 stackedThreadToast({
293 type: "error",
294 title: "Failed to wake thread",
295 description: error instanceof Error ? error.message : "An error occurred.",
296 }),
297 );
298 }
299 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
300 };
301 const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
302 const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
303 const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
304 const [, setBranchMismatchDismissTick] = useState(0);
305 const composerHasDraftContent = useComposerDraftStore((store) =>
306 composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
307 );
308 const activeBranchMismatchKey = branchMismatchKey(
309 activeThread?.id ?? null,
310 localCheckoutBranchMismatch,
311 );
312 const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
313 hasMismatch: localCheckoutBranchMismatch !== null,
314 isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
315 composerHasContent: composerHasDraftContent,
316 wasShownForCurrentMismatch:
317 revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
318 });
319 const nextRevealedBranchMismatchKey = showBranchMismatchBanner
320 ? activeBranchMismatchKey
321 : revealedBranchMismatchKey !== activeBranchMismatchKey
322 ? null
323 : revealedBranchMismatchKey;
324 if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
325 setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
326 }
327 const handleSwitchCheckoutToThread = async () => {
328 if (!canWriteSourceControl) return;
329 if (
330 !activeProjectCwd ||
331 !activeThread ||
332 !localCheckoutBranchMismatch ||
333 isRestoringThreadBranch
334 ) {
335 return;
336 }
337 setIsRestoringThreadBranch(true);
338 const checkoutResult = await switchGitRef({
339 environmentId,
340 input: {
341 cwd: activeProjectCwd,
342 refName: localCheckoutBranchMismatch.threadBranch,
343 },
344 });
345 if (checkoutResult._tag === "Failure") {
346 setIsRestoringThreadBranch(false);
347 if (!isAtomCommandInterrupted(checkoutResult)) {
348 toastManager.add(
349 stackedThreadToast({
350 type: "error",
351 title: "Failed to switch checkout",
352 description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
353 }),
354 );
355 }
356 return;
357 }
358
359 if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
360 setIsRestoringThreadBranch(false);
361 return;
362 }
363 const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
364 if (nextBranch !== activeThread.branch) {
365 const updateResult = await updateThreadMetadata({
366 environmentId,
367 input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
368 });
369 if (updateResult._tag === "Failure") {
370 setIsRestoringThreadBranch(false);
371 if (!isAtomCommandInterrupted(updateResult)) {
372 toastManager.add(
373 stackedThreadToast({
374 type: "error",
375 title: "Checkout switched, but the thread could not be updated",
376 description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
377 }),
378 );
379 }
380 gitStatusQuery.refresh();
381 return;
382 }
383 }
384 gitStatusQuery.refresh();
385 setIsRestoringThreadBranch(false);
386 scheduleComposerFocus();
387 };
388 const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
389 void handleSwitchCheckoutToThread();
390 });
391 // The interrupt path also accepts a completed run while its provider still
392 // has background work.
393 const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
394 const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
395 const isStoppingBackgroundWork =
396 stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
397 const handleStopBackgroundWork = async () => {
398 if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
399 return;
400 const requestKey = `${environmentId}:${activeThread.id}`;
401 setStoppingBackgroundWorkKey(requestKey);
402 const result = await interruptThreadTurn({
403 environmentId,
404 input: { threadId: activeThread.id },
405 });
406 // Acceptance does not confirm termination. Allow retry while the provider
407 // finishes stopping the tasks or reports a failure.
408 setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
409 if (result._tag === "Failure") {
410 if (!isAtomCommandInterrupted(result)) {
411 const error = squashAtomCommandFailure(result);
412 setThreadError(
413 activeThread.id,
414 error instanceof Error ? error.message : "Failed to stop background work.",
415 );
416 }
417 }
418 };
419 const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
420 const openRelatedThreadGenerationRef = useRef(0);
421 const onOpenRelatedThread = async (threadId: ThreadId) => {
422 const generation = ++openRelatedThreadGenerationRef.current;
423 const threadRef = scopeThreadRef(environmentId, threadId);
424 const isEnvironmentLive = () =>
425 appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live";
426 // The shell can leave idle subagent children out, so absence is not deletion there: the
427 // route decides from the thread's own detail.
428 const shellOmitsChildren = serverConfig?.shellThreadFamilies === true;
429 // A just-launched child can reach this timeline before its shell syncs.
430 if (!shellOmitsChildren && isEnvironmentLive() && readThreadShell(threadRef) === null) {
431 const location = router.latestLocation;
432 await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
433 if (
434 generation !== openRelatedThreadGenerationRef.current ||
435 currentRouteThreadKeyRef.current !== routeThreadKey ||
436 router.latestLocation !== location
437 ) {
438 return;
439 }
440 }
441 const shell = readThreadShell(threadRef);
442 if (shell === null ? !shellOmitsChildren && isEnvironmentLive() : shell.deletedAt != null) {
443 toastManager.add({ type: "info", title: "This thread is no longer available" });
444 return;
445 }
446 void navigate({
447 to: "/$environmentId/$threadId",
448 params: buildThreadRouteParams(threadRef),
449 });
450 };
451 const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
452 const childThreadInputs = useChildThreadInputs(activeThreadRef);
453 const childInputBanner = childInputBannerItem({
454 childThreadInputs,
455 parentAwaitingUser: Boolean(
456 activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
457 ),
458 onOpenThread: onOpenRelatedThreadStable,
459 });
460
461 const sendStandaloneCommand = async (text: string, failureMessage: string) => {
462 if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
463 const context = composerRef.current?.getSendContext();
464 if (!context?.providerAvailable) return;
465
466 const threadId = activeThread.id;
467 const messageId = newMessageId();
468 const createdAt = new Date().toISOString();
469 sendInFlightRef.current = true;
470 beginLocalDispatch();
471 setThreadError(threadId, null);
472 setOptimisticUserMessages((messages) => [
473 ...messages,
474 {
475 id: messageId,
476 role: "user",
477 text,
478 runId: null,
479 createdAt,
480 updatedAt: createdAt,
481 streaming: false,
482 },
483 ]);
484 scrollToEnd();
485 // Commands settle into a result, so this always runs.
486 const settingsResult = await persistThreadSettingsForNextTurn({
487 threadId,
488 createdAt,
489 ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
490 runtimeMode,
491 interactionMode: context.interactionMode,
492 });
493 const result =
494 settingsResult._tag === "Failure"
495 ? settingsResult
496 : await startThreadTurn({
497 environmentId,
498 input: {
499 threadId,
500 message: { messageId, role: "user", text, attachments: [] },
501 modelSelection: context.selectedModelSelection,
502 runtimeMode,
503 interactionMode: context.interactionMode,
504 createdAt,
505 },
506 });
507 if (result._tag === "Failure") {
508 setOptimisticUserMessages((messages) =>
509 messages.filter((message) => message.id !== messageId),
510 );
511 resetLocalDispatch();
512 if (!isAtomCommandInterrupted(result)) {
513 const error = squashAtomCommandFailure(result);
514 setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
515 }
516 } else {
517 clearUsageLimitsFor(routeThreadKey);
518 }
519 sendInFlightRef.current = false;
520 };
521 const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
522 const activeGoal = activeThreadShell?.goal ?? null;
523 const goalBanner =
524 activeThread && activeGoal !== null
525 ? goalBannerItem({
526 threadId: activeThread.id,
527 goal: activeGoal,
528 isWorking,
529 onSendCommand: sendStandaloneCommandStable,
530 })
531 : null;
532
533 const backgroundWorkBanner = activeThread
534 ? backgroundWorkBannerItem({
535 threadId: activeThread.id,
536 tasks: activeBackgroundTasks,
537 stopDisabled: !canOperateThread || isStoppingBackgroundWork,
538 stopping: isStoppingBackgroundWork,
539 onStop: handleStopBackgroundWorkStable,
540 onOpenThread: onOpenRelatedThreadStable,
541 })
542 : null;
543 // The relative times read the clock; nowMinute re-renders them on the minute.
544 const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
545 const settledAt = activeThreadShell?.settledAt ?? null;
546 // Same rounding as the sidebar's snoozed shelf, so both read the same hour.
547 const snoozeWake = snoozedUntil
548 ? snoozeWakeLabel(snoozedUntil, { now: `${nowMinute}:00.000Z` })
549 : null;
550 const threadStatusLine = activeThreadSnoozed ? (
551 <ThreadStatusLine
552 icon={<AlarmClockIcon />}
553 label={snoozeWake && snoozeWake !== "now" ? `Snoozed, ${snoozeWake} left` : "Snoozed"}
554 clockMinute={nowMinute}
555 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
556 actionDisabled={!canOperateThread || isUnsnoozing}
557 onAction={() => void handleUnsnoozeActiveThreadStable()}
558 />
559 ) : activeThreadSettled ? (
560 <ThreadStatusLine
561 icon={<CheckCircle2Icon />}
562 label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
563 clockMinute={nowMinute}
564 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
565 actionDisabled={!canOperateThread || isUnsettling}
566 onAction={() => void handleUnsettleActiveThreadStable()}
567 />
568 ) : activeThreadWokeVisible ? (
569 <ThreadStatusLine
570 icon={<AlarmClockIcon />}
571 label="Woke from snooze"
572 actionLabel="Dismiss"
573 onAction={acknowledgeActiveThreadWokeStable}
574 />
575 ) : null;
576 const toastThreadActionFailure =
577 (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
578 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
579 const error = squashAtomCommandFailure(result);
580 toastManager.add(
581 stackedThreadToast({
582 type: "error",
583 title,
584 description: error instanceof Error ? error.message : "An error occurred.",
585 }),
586 );
587 };
588 const shortcuts = {
589 "thread.settle": () => {
590 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
591 if (!activeThreadShell || !activeThreadRef || !supportsSettlement) return;
592 if (activeThreadSettled) {
593 void handleUnsettleActiveThread();
594 return;
595 }
596 if (settleAndAdvance(activeThreadRef)) return;
597 void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
598 },
599 "thread.pin": () => {
600 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
601 if (!activeThreadShell || !activeThreadRef || !supportsPinning) return;
602 void (
603 activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
604 ).then(
605 toastThreadActionFailure(
606 activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread",
607 ),
608 );
609 },
610 } satisfies ChatShortcutCommands;
611 return {
612 shortcuts,
613 acknowledgeActiveThreadWoke,
614 activeBranchMismatchKey,
615 backgroundWorkBanner,
616 childInputBanner,
617 goalBanner,
618 handleSwitchCheckoutToThread,
619 handleSwitchCheckoutToThreadStable,
620 isRestoringThreadBranch,
621 onOpenRelatedThread,
622 onOpenRelatedThreadStable,
623 sendStandaloneCommand,
624 setBranchMismatchDismissTick,
625 showBranchMismatchBanner,
626 threadStatusLine,
627 };
628}