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