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 { useDeadlinePassed, 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 {
32 BACKGROUND_WORK_STOP_RETRY_AFTER_MS,
33 type BackgroundWorkStopRequest,
34 isBackgroundWorkStopPending,
35} from "@t3tools/client-runtime/state/thread-execution";
36import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions";
37import { settleAndAdvance } from "../../settleAndAdvance";
38import type { ChatShortcutCommands } from "./useChatShortcuts";
39import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
40import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
41import { type SetStateAction, useRef, useState } from "react";
42import { useNavigate, useRouter } from "@tanstack/react-router";
43import {
44 isAtomCommandInterrupted,
45 squashAtomCommandFailure,
46 type AtomCommandResult,
47} from "@t3tools/client-runtime/state/runtime";
48import { useUiStateStore } from "../../uiStateStore";
49import { type ChatMessage } from "../../types";
50import { AlarmClockIcon, CheckCircle2Icon } from "lucide-react";
51import { stackedThreadToast, toastManager } from "../ui/toast";
52import { newMessageId } from "~/lib/utils";
53import { buildThreadRouteParams } from "../../threadRoutes";
54import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore";
55import { useEnvironmentScope } from "~/state/session";
56import { threadEnvironment } from "../../state/threads";
57import { vcsEnvironment } from "../../state/vcs";
58import { useChildThreadInputs, readThreadShell, waitForThreadShell } from "../../state/entities";
59import { serverEnvironment } from "../../state/server";
60import { environmentShell } from "../../state/shell";
61import { ThreadStatusLine } from "./ThreadStatusLine";
62import { formatRelativeTimeLabel } from "../../timestampFormat";
63import { appAtomRegistry } from "../../rpc/atomRegistry";
64import { readEnvironmentScope } from "../../state/session";
65import { useAtomCommand } from "../../state/use-atom-command";
66import { useOrchestrationCommand } from "../../state/use-orchestration-command";
67import {
68 backgroundWorkNowItem,
69 childInputNowItem,
70 goalNowItem,
71 runStopNowItem,
72} from "./ThreadActivityBanners";
73import { useForceStopThread } from "./useForceStopThread";
74import { useAtomValue } from "@effect/atom-react";
75import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution";
76import { Atom } from "effect/reactivity";
77import { environmentThreadDetails } from "../../state/threads";
78import { openSideChatTab } from "../../lib/sideChatPane";
79import type { useLocalDispatchState } from "./useLocalDispatchState";
80const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
81const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe(
82 Atom.withLabel("web-thread-run-stop:empty"),
83);
84
85type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
86type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
87
88interface ThreadLifecycleInput {
89 readonly environmentId: EnvironmentId;
90 readonly routeThreadKey: string;
91 readonly currentRouteThreadKeyRef: { readonly current: string | null };
92 readonly canOperateThread: boolean;
93 readonly clientSettingsHydrated: boolean;
94 readonly activeThread: EnvironmentThreadShell | undefined;
95 readonly activeThreadId: ThreadId | null;
96 readonly activeThreadRef: ScopedThreadRef | null;
97 /** Null until the thread's detail may load; see resolveThreadDetailRef. */
98 readonly threadDetailRef: ScopedThreadRef | null;
99 readonly activeThreadKey: string | null;
100 readonly activeThreadShell: EnvironmentThreadShell | null;
101 readonly activeLatestRun: EnvironmentThreadShell["latestRun"];
102 readonly activeProjectCwd: string | null;
103 readonly serverConfig: EnvironmentServerConfig | null;
104 readonly runtimeMode: RuntimeMode;
105 readonly isWorking: boolean;
106 readonly pendingBackgroundTasks: Parameters<typeof backgroundWorkNowItem>[0]["tasks"];
107 readonly turnItems: Parameters<typeof backgroundWorkNowItem>[0]["turnItems"];
108 readonly activePendingApproval: PendingThreadRequests["activePendingApproval"];
109 readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"];
110 readonly localCheckoutBranchMismatch: {
111 readonly threadBranch: string;
112 readonly currentBranch: string;
113 } | null;
114 readonly gitStatusQuery: { readonly refresh: () => void };
115 readonly nowMinute: string;
116 readonly composerRef: ComposerHandleRef;
117 readonly composerDraftTarget: ComposerThreadTarget;
118 readonly sendInFlightRef: { current: boolean };
119 readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
120 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
121 readonly clearUsageLimitsFor: (threadKey: string) => void;
122 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
123 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
124 readonly scrollToEnd: (animated?: boolean) => void;
125 readonly persistThreadSettingsForNextTurn: (input: {
126 threadId: ThreadId;
127 createdAt: string;
128 branch?: string;
129 runtimeMode: RuntimeMode;
130 interactionMode: ProviderInteractionMode;
131 }) => Promise<AtomCommandResult<void, unknown>>;
132}
133
134/**
135 * Thread state the chat shows and changes outside a normal send: snooze and settle with
136 * their status line, the local checkout's branch, background work, child-thread and goal
137 * banners, opening related threads, and standalone slash commands.
138 */
139export function useThreadLifecycle(input: ThreadLifecycleInput) {
140 const {
141 environmentId,
142 routeThreadKey,
143 currentRouteThreadKeyRef,
144 canOperateThread,
145 clientSettingsHydrated,
146 activeThread,
147 activeThreadId,
148 activeThreadRef,
149 threadDetailRef,
150 activeThreadKey,
151 activeThreadShell,
152 activeLatestRun,
153 activeProjectCwd,
154 serverConfig,
155 runtimeMode,
156 isWorking,
157 pendingBackgroundTasks,
158 turnItems,
159 activePendingApproval,
160 activePendingUserInput,
161 localCheckoutBranchMismatch,
162 gitStatusQuery,
163 nowMinute,
164 composerRef,
165 composerDraftTarget,
166 sendInFlightRef,
167 setOptimisticUserMessages,
168 setThreadError,
169 clearUsageLimitsFor,
170 beginLocalDispatch,
171 resetLocalDispatch,
172 scrollToEnd,
173 persistThreadSettingsForNextTurn,
174 } = input;
175 const navigate = useNavigate();
176 const router = useRouter();
177 const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
178 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
179 const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
180 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
181 reportFailure: false,
182 });
183 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
184 reportFailure: false,
185 });
186 const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
187 reportFailure: false,
188 });
189
190 const serverConfigLoaded = serverConfig !== null;
191 const activeThreadPinned = serverConfigLoaded && activeThreadShell?.pinnedAt != null;
192 // A clock read in render would stay frozen in the compiler's cache, so the
193 // snooze checks read a snapshot that moves when the wake time changes or passes.
194 const snoozeClock = new Date(
195 useNowAfter(Date.parse(activeThreadShell?.snoozedUntil ?? "") || null),
196 ).toISOString();
197 const activeThreadSnoozed =
198 activeThreadShell !== null &&
199 serverConfigLoaded &&
200 effectiveSnoozed(activeThreadShell, { now: snoozeClock });
201 const activeThreadWokeAt =
202 activeThreadShell !== null && serverConfigLoaded
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 serverConfigLoaded && 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 [restoringBranchThreadKeys, setRestoringBranchThreadKeys] = useState<ReadonlySet<string>>(
303 () => new Set(),
304 );
305 const isRestoringThreadBranch =
306 activeThreadKey !== null && restoringBranchThreadKeys.has(activeThreadKey);
307 const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
308 const [, setBranchMismatchDismissTick] = useState(0);
309 const composerHasDraftContent = useComposerDraftStore((store) =>
310 composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
311 );
312 const activeBranchMismatchKey = branchMismatchKey(
313 activeThread?.id ?? null,
314 localCheckoutBranchMismatch,
315 );
316 const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
317 hasMismatch: localCheckoutBranchMismatch !== null,
318 isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
319 composerHasContent: composerHasDraftContent,
320 wasShownForCurrentMismatch:
321 revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
322 });
323 const nextRevealedBranchMismatchKey = showBranchMismatchBanner
324 ? activeBranchMismatchKey
325 : revealedBranchMismatchKey !== activeBranchMismatchKey
326 ? null
327 : revealedBranchMismatchKey;
328 if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
329 setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
330 }
331 const handleSwitchCheckoutToThread = async () => {
332 if (!canWriteSourceControl) return;
333 if (
334 !activeProjectCwd ||
335 !activeThread ||
336 !localCheckoutBranchMismatch ||
337 isRestoringThreadBranch
338 ) {
339 return;
340 }
341 const threadKey = scopedThreadKey(scopeThreadRef(environmentId, activeThread.id));
342 const finishRestore = () =>
343 setRestoringBranchThreadKeys((current) => {
344 const next = new Set(current);
345 next.delete(threadKey);
346 return next;
347 });
348 setRestoringBranchThreadKeys((current) => new Set(current).add(threadKey));
349 const checkoutResult = await switchGitRef({
350 environmentId,
351 input: {
352 cwd: activeProjectCwd,
353 refName: localCheckoutBranchMismatch.threadBranch,
354 },
355 });
356 if (checkoutResult._tag === "Failure") {
357 finishRestore();
358 if (!isAtomCommandInterrupted(checkoutResult)) {
359 toastManager.add(
360 stackedThreadToast({
361 type: "error",
362 title: "Failed to switch checkout",
363 description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
364 }),
365 );
366 }
367 return;
368 }
369
370 if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
371 finishRestore();
372 return;
373 }
374 const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
375 if (nextBranch !== activeThread.branch) {
376 const updateResult = await updateThreadMetadata({
377 environmentId,
378 input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
379 });
380 if (updateResult._tag === "Failure") {
381 finishRestore();
382 if (!isAtomCommandInterrupted(updateResult)) {
383 toastManager.add(
384 stackedThreadToast({
385 type: "error",
386 title: "Checkout switched, but the thread could not be updated",
387 description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
388 }),
389 );
390 }
391 gitStatusQuery.refresh();
392 return;
393 }
394 }
395 gitStatusQuery.refresh();
396 finishRestore();
397 if (currentRouteThreadKeyRef.current === routeThreadKey) {
398 window.requestAnimationFrame(() => {
399 if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd();
400 });
401 }
402 };
403 const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
404 void handleSwitchCheckoutToThread();
405 });
406 // The interrupt path also accepts a completed run while its provider still
407 // has background work.
408 const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
409 const [backgroundWorkStops, setBackgroundWorkStops] = useState<
410 Record<string, BackgroundWorkStopRequest | undefined>
411 >({});
412 const backgroundWorkStop = backgroundWorkStops[`${environmentId}:${activeThreadId}`] ?? null;
413 const isStoppingBackgroundWork = isBackgroundWorkStopPending(
414 backgroundWorkStop,
415 `${environmentId}:${activeThreadId}`,
416 pendingBackgroundTasks,
417 useDeadlinePassed(backgroundWorkStop?.retryAt ?? null),
418 );
419 const handleStopBackgroundWork = async () => {
420 if (
421 isStoppingBackgroundWork ||
422 !activeThread ||
423 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)
424 )
425 return;
426 const request: BackgroundWorkStopRequest = {
427 threadKey: `${environmentId}:${activeThread.id}`,
428 taskIds: pendingBackgroundTasks.map((task) => task.taskId),
429 retryAt: null,
430 };
431 setBackgroundWorkStops((current) => ({ ...current, [request.threadKey]: request }));
432 const result = await interruptThreadTurn({
433 environmentId,
434 input: { threadId: activeThread.id },
435 });
436 setBackgroundWorkStops((current) =>
437 current[request.threadKey] !== request
438 ? current
439 : {
440 ...current,
441 [request.threadKey]:
442 result._tag === "Failure"
443 ? undefined
444 : { ...request, retryAt: Date.now() + BACKGROUND_WORK_STOP_RETRY_AFTER_MS },
445 },
446 );
447 if (result._tag === "Failure") {
448 if (!isAtomCommandInterrupted(result)) {
449 const error = squashAtomCommandFailure(result);
450 setThreadError(
451 activeThread.id,
452 error instanceof Error ? error.message : "Failed to stop background work.",
453 );
454 }
455 }
456 };
457 const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
458 const openRelatedThreadGenerationRef = useRef(0);
459 // A task delegated to a linked environment opens there; the default is this thread's own.
460 const onOpenRelatedThread = async (
461 threadId: ThreadId,
462 threadEnvironmentId: EnvironmentId = environmentId,
463 ) => {
464 const generation = ++openRelatedThreadGenerationRef.current;
465 const threadRef = scopeThreadRef(threadEnvironmentId, threadId);
466 const isEnvironmentLive = () =>
467 appAtomRegistry.get(environmentShell.stateValueAtom(threadEnvironmentId)).status === "live";
468 // The shell can leave idle subagent children out, so absence is not deletion there: the
469 // route decides from the thread's own detail.
470 const shellOmitsChildren =
471 appAtomRegistry.get(serverEnvironment.configValueAtom(threadEnvironmentId))
472 ?.shellThreadFamilies === true;
473 // A just-launched child can reach this timeline before its shell syncs.
474 if (!shellOmitsChildren && isEnvironmentLive() && readThreadShell(threadRef) === null) {
475 const location = router.latestLocation;
476 await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
477 if (
478 generation !== openRelatedThreadGenerationRef.current ||
479 currentRouteThreadKeyRef.current !== routeThreadKey ||
480 router.latestLocation !== location
481 ) {
482 return;
483 }
484 }
485 const shell = readThreadShell(threadRef);
486 if (shell === null ? !shellOmitsChildren && isEnvironmentLive() : shell.deletedAt != null) {
487 toastManager.add({ type: "info", title: "This thread is no longer available" });
488 return;
489 }
490 if (activeThreadRef && openSideChatTab(activeThreadRef, shell)) return;
491 void navigate({
492 to: "/$environmentId/$threadId",
493 params: buildThreadRouteParams(threadRef),
494 });
495 };
496 const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
497 const childThreadInputs = useChildThreadInputs(activeThreadRef);
498 const childInputNow = childInputNowItem({
499 childThreadInputs,
500 parentAwaitingUser: Boolean(
501 activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
502 ),
503 onOpenThread: onOpenRelatedThreadStable,
504 });
505
506 const sendStandaloneCommand = async (text: string, failureMessage: string) => {
507 if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
508 const context = composerRef.current?.getSendContext();
509 if (!context?.providerAvailable) return;
510
511 const threadId = activeThread.id;
512 const messageId = newMessageId();
513 const createdAt = new Date().toISOString();
514 sendInFlightRef.current = true;
515 beginLocalDispatch();
516 setThreadError(threadId, null);
517 setOptimisticUserMessages((messages) => [
518 ...messages,
519 {
520 id: messageId,
521 role: "user",
522 text,
523 runId: null,
524 createdAt,
525 updatedAt: createdAt,
526 streaming: false,
527 },
528 ]);
529 scrollToEnd();
530 // Commands settle into a result, so this always runs.
531 const settingsResult = await persistThreadSettingsForNextTurn({
532 threadId,
533 createdAt,
534 ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
535 runtimeMode,
536 interactionMode: context.interactionMode,
537 });
538 const result =
539 settingsResult._tag === "Failure"
540 ? settingsResult
541 : await startThreadTurn({
542 environmentId,
543 input: {
544 threadId,
545 message: { messageId, role: "user", text, attachments: [] },
546 modelSelection: context.selectedModelSelection,
547 runtimeMode,
548 interactionMode: context.interactionMode,
549 createdAt,
550 },
551 });
552 if (result._tag === "Failure") {
553 setOptimisticUserMessages((messages) =>
554 messages.filter((message) => message.id !== messageId),
555 );
556 resetLocalDispatch();
557 if (!isAtomCommandInterrupted(result)) {
558 const error = squashAtomCommandFailure(result);
559 setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
560 }
561 } else {
562 clearUsageLimitsFor(routeThreadKey);
563 }
564 sendInFlightRef.current = false;
565 };
566 const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
567 const activeGoal = activeThreadShell?.goal ?? null;
568 const goalNow =
569 activeThread && activeGoal !== null
570 ? goalNowItem({
571 threadId: activeThread.id,
572 goal: activeGoal,
573 isWorking,
574 onSendCommand: sendStandaloneCommandStable,
575 })
576 : null;
577
578 const forceStop = useForceStopThread(environmentId);
579 const anyRunStop = useAtomValue(
580 threadDetailRef ? environmentThreadDetails.runStopAtom(threadDetailRef) : NO_RUN_STOP_ATOM,
581 );
582 // A background Stop matters only while that work is still pending.
583 const runStop = anyRunStop?.background && activeBackgroundTasks.length === 0 ? null : anyRunStop;
584 const runStopNow =
585 activeThread && runStop !== null
586 ? runStopNowItem({
587 threadId: activeThread.id,
588 stop: runStop,
589 canForceStop: forceStop.canForceStop,
590 forceStopping: forceStop.stoppingThreadId === activeThread.id,
591 onForceStop: () => void forceStop.forceStopThread(activeThread.id, runStop.runId),
592 })
593 : null;
594 const backgroundWorkNow = activeThread
595 ? backgroundWorkNowItem({
596 threadId: activeThread.id,
597 tasks: activeBackgroundTasks,
598 turnItems,
599 stopDisabled: !canOperateThread || isStoppingBackgroundWork,
600 stopping: isStoppingBackgroundWork,
601 onStop: handleStopBackgroundWorkStable,
602 onOpenThread: onOpenRelatedThreadStable,
603 })
604 : null;
605 // The relative times read the clock; nowMinute re-renders them on the minute.
606 const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
607 const settledAt = activeThreadShell?.settledAt ?? null;
608 // Same rounding as the sidebar's snoozed shelf, so both read the same hour.
609 const snoozeWake = snoozedUntil
610 ? snoozeWakeLabel(snoozedUntil, { now: `${nowMinute}:00.000Z` })
611 : null;
612 const threadStatusLine = activeThreadSnoozed ? (
613 <ThreadStatusLine
614 icon={<AlarmClockIcon />}
615 label={snoozeWake && snoozeWake !== "now" ? `Snoozed, ${snoozeWake} left` : "Snoozed"}
616 clockMinute={nowMinute}
617 actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
618 actionDisabled={!canOperateThread || isUnsnoozing}
619 onAction={() => void handleUnsnoozeActiveThreadStable()}
620 />
621 ) : activeThreadSettled ? (
622 <ThreadStatusLine
623 icon={<CheckCircle2Icon />}
624 label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
625 clockMinute={nowMinute}
626 actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
627 actionDisabled={!canOperateThread || isUnsettling}
628 onAction={() => void handleUnsettleActiveThreadStable()}
629 />
630 ) : activeThreadWokeVisible ? (
631 <ThreadStatusLine
632 icon={<AlarmClockIcon />}
633 label="Woke from snooze"
634 actionLabel="Dismiss"
635 onAction={acknowledgeActiveThreadWokeStable}
636 />
637 ) : null;
638 const toastThreadActionFailure =
639 (title: string) => (result: AtomCommandResult<unknown, unknown>) => {
640 if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
641 const error = squashAtomCommandFailure(result);
642 toastManager.add(
643 stackedThreadToast({
644 type: "error",
645 title,
646 description: error instanceof Error ? error.message : "An error occurred.",
647 }),
648 );
649 };
650 const shortcuts = {
651 "thread.settle": () => {
652 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
653 if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return;
654 if (activeThreadSettled) {
655 void handleUnsettleActiveThread();
656 return;
657 }
658 if (settleAndAdvance(activeThreadRef)) return;
659 void settleThread(activeThreadRef).then(toastThreadActionFailure("Failed to settle thread"));
660 },
661 "thread.pin": ({ event }) => {
662 // An open project list pins its highlighted project with this key instead.
663 if (
664 event.target instanceof Element &&
665 event.target.closest('[role="combobox"][aria-expanded="true"]') !== null
666 ) {
667 return false;
668 }
669 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false;
670 if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return;
671 void (
672 activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef)
673 ).then(
674 toastThreadActionFailure(
675 activeThreadPinned ? "Failed to unpin thread" : "Failed to pin thread",
676 ),
677 );
678 },
679 } satisfies ChatShortcutCommands;
680 return {
681 shortcuts,
682 acknowledgeActiveThreadWoke,
683 activeBranchMismatchKey,
684 // A Stop that went unanswered needs the user; one in progress is the thread's work.
685 attentionNow: runStop?.state === "unresponsive" ? runStopNow : childInputNow,
686 workNow: runStop?.state === "stopping" ? runStopNow : backgroundWorkNow,
687 childInputNow,
688 goalNow,
689 handleSwitchCheckoutToThread,
690 handleSwitchCheckoutToThreadStable,
691 isRestoringThreadBranch,
692 onOpenRelatedThread,
693 onOpenRelatedThreadStable,
694 sendStandaloneCommand,
695 setBranchMismatchDismissTick,
696 showBranchMismatchBanner,
697 threadStatusLine,
698 };
699}