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

useThreadLifecycle.tsx

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