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