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