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

useThreadLifecycle.tsx

754 lines30.0 KB

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