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

useThreadLifecycle.tsx

664 lines26.8 KB

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