Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadLifecycle.tsx

704 lines28.1 KB

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