The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): ChatView's snooze, settle, and checkout actions live in useThreadLifecycle (#23065)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 13:40 UTC
92105d49946474a048f2fccadb3d2c1300d7d27b
2 files changed
+641
-427
apps/web/src/components/ChatView.tsx
+59
-427
@@ -1,10 +1,11 @@
1
+import { useThreadLifecycle } from "./chat/useThreadLifecycle";
2
import { useRightPanelActions } from "./chat/useRightPanelActions";
3
import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions";
4
import { useComposerSend } from "./chat/useComposerSend";
5
import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
6
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
7
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
7
-import { isThreadWokeUnseen, resolveDraftHeroState } from "./ChatView.logic";
8
+import { resolveDraftHeroState } from "./ChatView.logic";
9
import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";
10
import {
11
isPaintOnlyThreadTimeline,
@@ -63,9 +64,8 @@ import {
64
} from "@t3tools/contracts";
65
import { readPastedComposerContext } from "./composerInlineTokenPaste";
66
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
66
-import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
67
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
68
-import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
68
+import { useThreadActions } from "../hooks/useThreadActions";
69
import {
70
deriveProviderSubagentStatus,
71
deriveReportedModelSelection,
@@ -87,7 +87,6 @@ import {
87
shouldShowLoadEarlierControl,
88
type CodexFeedbackSubmission,
89
} from "@t3tools/client-runtime/state/threads";
90
-import { resolveThreadLastVisitedAt } from "./Sidebar.logic";
90
import {
91
parseScopedThreadKey,
92
scopedThreadKey,
@@ -107,7 +106,7 @@ import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReferenc
106
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
107
import { useAtomValue } from "@effect/atom-react";
108
import { type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react";
110
-import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";
109
+import { useLocation, useNavigate } from "@tanstack/react-router";
110
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
111
import { isMacPlatform } from "../lib/utils";
112
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
@@ -137,7 +136,6 @@ import {
136
isLatestRunSettled,
137
} from "../session-logic";
138
import { type LegendListRef } from "@legendapp/list/react";
140
-import { useUiStateStore } from "../uiStateStore";
139
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
140
import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types";
141
import { useTheme } from "../hooks/useTheme";
@@ -178,13 +176,7 @@ import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
176
import { isEditableFocused } from "../lib/editableFocus";
177
import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
178
import { shortcutLabelForCommand } from "../keybindings";
181
-import {
182
- AlarmClockIcon,
183
- CheckCircle2Icon,
184
- PaperclipIcon,
185
- ChevronDownIcon,
186
- DownloadIcon,
187
-} from "lucide-react";
179
+import { PaperclipIcon, ChevronDownIcon, DownloadIcon } from "lucide-react";
180
import { cn } from "~/lib/utils";
181
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
182
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -261,13 +253,11 @@ import {
253
useThreadStatus,
254
useThreadHistory,
255
useQuietThreadShell,
264
- useChildThreadInputs,
256
useThreadVisibleTurnItems,
257
useThreadCheckpointSummaries,
267
- readThreadShell,
258
waitForThreadShell,
259
} from "../state/entities";
270
-import { environmentShell, useEnvironmentShellHasSnapshot } from "../state/shell";
260
+import { useEnvironmentShellHasSnapshot } from "../state/shell";
261
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
262
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
263
import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog";
@@ -326,8 +316,6 @@ import { useIncrementalTimelineEntries } from "../hooks/useIncrementalTimelineEn
316
import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose";
317
import { useAgentOpenedPreviews } from "./preview/useAgentOpenedPreviews";
318
import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack";
329
-import { ThreadStatusLine } from "./chat/ThreadStatusLine";
330
-import { formatRelativeTimeLabel, formatRelativeTimeUntilLabel } from "../timestampFormat";
319
import { ComposerSurface } from "./chat/ComposerSurface";
320
import { resolveThreadSyncPhase } from "../threadSync";
321
import {
@@ -344,13 +332,10 @@ import {
332
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
333
} from "./chat/draftHeroTransition";
334
import {
347
- branchMismatchKey,
335
buildLocalDraftThread,
336
collectUserMessageBlobPreviewUrls,
337
deriveCommittedServerUserMessageIds,
338
dismissBranchMismatchForSession,
352
- isBranchMismatchDismissedForSession,
353
- shouldShowBranchMismatchBanner,
339
shouldShowPlanFollowUpPrompt,
340
shouldRenderPreviewMiniPlayer,
341
getStartedThreadModelChangeBlockReason,
@@ -382,12 +367,7 @@ import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
367
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
368
import { ChatRightPanel } from "./chat/ChatRightPanel";
369
import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting";
385
-import {
386
- backgroundWorkBannerItem,
387
- branchMismatchBannerItem,
388
- childInputBannerItem,
389
- goalBannerItem,
390
-} from "./chat/ThreadActivityBanners";
370
+import { branchMismatchBannerItem } from "./chat/ThreadActivityBanners";
371
import { useTimelineFollow } from "./chat/useTimelineFollow";
372
import {
373
type EnvironmentUnavailableState,
@@ -397,7 +377,6 @@ import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransitio
377
import { useLocalDispatchState } from "./chat/useLocalDispatchState";
378
import { draftFanoutSelectionsAtom, draftSendState, rewindToMessage } from "./chat/chatViewSend";
379
import {
400
- chatActionErrorMessage,
380
isCompactCommandMessage,
381
type LocalThreadErrorEntry,
382
makeModelDisabledReason,
@@ -410,7 +389,6 @@ const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];
389
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
390
391
const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
413
-const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
392
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
393
const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
394
@@ -469,7 +447,6 @@ export default function ChatView(props: ChatViewProps) {
447
reportFailure: false,
448
});
449
const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
472
- const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
450
const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
451
reportFailure: false,
452
});
@@ -630,7 +607,6 @@ export default function ChatView(props: ChatViewProps) {
607
);
608
const timestampFormat = settings.timestampFormat;
609
const navigate = useNavigate();
633
- const router = useRouter();
610
// Selects primitives: an object here is new on every router store update, which
611
// re-renders ChatView on unrelated navigation state changes.
612
const citationHref = useLocation({ select: (location) => location.href });
@@ -3017,405 +2993,61 @@ export default function ChatView(props: ChatViewProps) {
2993
onDiffPanelOpen,
2994
});
2995
const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null;
3020
- const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
3021
- const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
3022
- const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
3023
- const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null;
3024
- // The compiler caches render results on their inputs, so a clock read in render
3025
- // stays frozen until the shell changes. The clock is state: reset with the shell,
3026
- // and moved by the wake timer.
3027
- const [snoozeClockState, setSnoozeClockState] = useState(() => ({
3028
- shell: activeThreadShell,
3029
- now: new Date().toISOString(),
3030
- }));
3031
- if (snoozeClockState.shell !== activeThreadShell) {
3032
- setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
3033
- }
3034
- const snoozeClock = snoozeClockState.now;
3035
- const activeThreadSnoozed =
3036
- activeThreadShell !== null &&
3037
- supportsSnooze &&
3038
- effectiveSnoozed(activeThreadShell, { now: snoozeClock });
3039
- useEffect(() => {
3040
- if (!activeThreadSnoozed) return;
3041
- const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
3042
- if (!Number.isFinite(wakeAtMs)) return;
3043
- const id = window.setTimeout(
3044
- () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
3045
- Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
3046
- );
3047
- return () => window.clearTimeout(id);
3048
- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
3049
- }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
3050
- const activeThreadWokeAt =
3051
- activeThreadShell !== null && supportsSnooze
3052
- ? threadWokeAt(activeThreadShell, { now: snoozeClock })
3053
- : null;
3054
- const acknowledgeThreadWoke = useAcknowledgeThreadWoke();
3055
- const acknowledgeActiveThreadWoke = () => {
3056
- if (activeThreadRef === null || activeThreadWokeAt === null) return;
3057
- acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt);
3058
- };
3059
- const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke);
3060
- const activeThreadLocalVisitedAt = useUiStateStore((store) =>
3061
- activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
3062
- );
3063
- const activeThreadLastVisitedAt = resolveThreadLastVisitedAt(
3064
- activeThreadShell?.lastVisitedAt,
3065
- activeThreadLocalVisitedAt,
3066
- );
3067
- const activeThreadWokeVisible = isThreadWokeUnseen({
3068
- wokeAt: activeThreadWokeAt,
3069
- settled: activeThreadShell?.settledOverride === "settled",
3070
- lastVisitedAt: activeThreadLastVisitedAt,
3071
- latestRunCompletedAt: activeLatestRun?.completedAt ?? null,
3072
- });
3073
- const activeThreadSettled =
3074
- supportsSettlement && activeThreadShell?.settledOverride === "settled";
3075
- const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
3076
- reportFailure: false,
3077
- });
3078
- const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
3079
- const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
3080
- const handleUnsettleActiveThread = async () => {
3081
- if (
3082
- !activeThreadRef ||
3083
- !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
3084
- )
3085
- return;
3086
- const threadKey = scopedThreadKey(activeThreadRef);
3087
- setUnsettlingThreadKey(threadKey);
3088
- // Commands settle into a result, so this always runs.
3089
- const result = await unsettleThreadMutation({
3090
- environmentId: activeThreadRef.environmentId,
3091
- input: { threadId: activeThreadRef.threadId, reason: "user" },
3092
- });
3093
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3094
- const error = squashAtomCommandFailure(result);
3095
- toastManager.add(
3096
- stackedThreadToast({
3097
- type: "error",
3098
- title: "Failed to un-settle thread",
3099
- description: error instanceof Error ? error.message : "An error occurred.",
3100
- }),
3101
- );
3102
- }
3103
- setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
3104
- };
3105
- const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
3106
- const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
3107
- reportFailure: false,
3108
- });
3109
- const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
3110
- const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
3111
- const handleUnsnoozeActiveThread = async () => {
3112
- if (
3113
- !activeThreadRef ||
3114
- !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
3115
- )
3116
- return;
3117
- const threadKey = scopedThreadKey(activeThreadRef);
3118
- setUnsnoozingThreadKey(threadKey);
3119
- // Commands settle into a result, so this always runs.
3120
- const recovery = activeThreadShell?.limitRecovery;
3121
- const recoveryOwnsSnooze =
3122
- recovery?.snooze === true &&
3123
- recovery.runId === activeThreadShell?.latestRun?.runId &&
3124
- activeThreadShell?.snoozedUntil != null &&
3125
- Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
3126
- const result = recoveryOwnsSnooze
3127
- ? await updateThreadMetadata({
3128
- environmentId: activeThreadRef.environmentId,
3129
- input: {
3130
- threadId: activeThreadRef.threadId,
3131
- limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
3132
- },
3133
- })
3134
- : await unsnoozeThreadMutation({
3135
- environmentId: activeThreadRef.environmentId,
3136
- input: { threadId: activeThreadRef.threadId, reason: "user" },
3137
- });
3138
- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3139
- const error = squashAtomCommandFailure(result);
3140
- toastManager.add(
3141
- stackedThreadToast({
3142
- type: "error",
3143
- title: "Failed to wake thread",
3144
- description: error instanceof Error ? error.message : "An error occurred.",
3145
- }),
3146
- );
3147
- }
3148
- setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
3149
- };
3150
- const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
3151
- const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
3152
- const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
3153
- const [, setBranchMismatchDismissTick] = useState(0);
3154
- const composerHasDraftContent = useComposerDraftStore((store) =>
3155
- composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
3156
- );
2996
const nowMinute = useNowMinute();
3158
- const activeBranchMismatchKey = branchMismatchKey(
3159
- activeThread?.id ?? null,
2997
+ const {
2998
+ acknowledgeActiveThreadWoke,
2999
+ activeBranchMismatchKey,
3000
+ activeThreadPinned,
3001
+ activeThreadSettled,
3002
+ backgroundWorkBanner,
3003
+ childInputBanner,
3004
+ goalBanner,
3005
+ handleSwitchCheckoutToThread,
3006
+ handleSwitchCheckoutToThreadStable,
3007
+ handleUnsettleActiveThreadStable,
3008
+ isRestoringThreadBranch,
3009
+ onOpenRelatedThread,
3010
+ onOpenRelatedThreadStable,
3011
+ sendStandaloneCommand,
3012
+ setBranchMismatchDismissTick,
3013
+ showBranchMismatchBanner,
3014
+ supportsPinning,
3015
+ supportsSettlement,
3016
+ threadStatusLine,
3017
+ } = useThreadLifecycle({
3018
+ environmentId,
3019
+ routeThreadKey,
3020
+ currentRouteThreadKeyRef,
3021
+ canOperateThread,
3022
+ clientSettingsHydrated,
3023
+ activeThread,
3024
+ activeThreadId,
3025
+ activeThreadRef,
3026
+ activeThreadKey,
3027
+ activeThreadShell,
3028
+ activeLatestRun,
3029
+ activeProjectCwd,
3030
+ serverConfig,
3031
+ runtimeMode,
3032
+ isWorking,
3033
+ pendingBackgroundTasks,
3034
+ activePendingApproval,
3035
+ activePendingUserInput,
3036
localCheckoutBranchMismatch,
3161
- );
3162
- const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
3163
- hasMismatch: localCheckoutBranchMismatch !== null,
3164
- isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
3165
- composerHasContent: composerHasDraftContent,
3166
- wasShownForCurrentMismatch:
3167
- revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
3168
- });
3169
- const nextRevealedBranchMismatchKey = showBranchMismatchBanner
3170
- ? activeBranchMismatchKey
3171
- : revealedBranchMismatchKey !== activeBranchMismatchKey
3172
- ? null
3173
- : revealedBranchMismatchKey;
3174
- if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
3175
- setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
3176
- }
3177
- const handleSwitchCheckoutToThread = async () => {
3178
- if (!canWriteSourceControl) return;
3179
- if (
3180
- !activeProjectCwd ||
3181
- !activeThread ||
3182
- !localCheckoutBranchMismatch ||
3183
- isRestoringThreadBranch
3184
- ) {
3185
- return;
3186
- }
3187
- setIsRestoringThreadBranch(true);
3188
- const checkoutResult = await switchGitRef({
3189
- environmentId,
3190
- input: {
3191
- cwd: activeProjectCwd,
3192
- refName: localCheckoutBranchMismatch.threadBranch,
3193
- },
3194
- });
3195
- if (checkoutResult._tag === "Failure") {
3196
- setIsRestoringThreadBranch(false);
3197
- if (!isAtomCommandInterrupted(checkoutResult)) {
3198
- toastManager.add(
3199
- stackedThreadToast({
3200
- type: "error",
3201
- title: "Failed to switch checkout",
3202
- description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
3203
- }),
3204
- );
3205
- }
3206
- return;
3207
- }
3208
-
3209
- if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
3210
- setIsRestoringThreadBranch(false);
3211
- return;
3212
- }
3213
- const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
3214
- if (nextBranch !== activeThread.branch) {
3215
- const updateResult = await updateThreadMetadata({
3216
- environmentId,
3217
- input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
3218
- });
3219
- if (updateResult._tag === "Failure") {
3220
- setIsRestoringThreadBranch(false);
3221
- if (!isAtomCommandInterrupted(updateResult)) {
3222
- toastManager.add(
3223
- stackedThreadToast({
3224
- type: "error",
3225
- title: "Checkout switched, but the thread could not be updated",
3226
- description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
3227
- }),
3228
- );
3229
- }
3230
- gitStatusQuery.refresh();
3231
- return;
3232
- }
3233
- }
3234
- gitStatusQuery.refresh();
3235
- setIsRestoringThreadBranch(false);
3236
- scheduleComposerFocus();
3237
- };
3238
- const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
3239
- void handleSwitchCheckoutToThread();
3240
- });
3241
- // The interrupt path also accepts a completed run while its provider still
3242
- // has background work.
3243
- const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
3244
- const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
3245
- const isStoppingBackgroundWork =
3246
- stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
3247
- const handleStopBackgroundWork = async () => {
3248
- if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
3249
- return;
3250
- const requestKey = `${environmentId}:${activeThread.id}`;
3251
- setStoppingBackgroundWorkKey(requestKey);
3252
- const result = await interruptThreadTurn({
3253
- environmentId,
3254
- input: { threadId: activeThread.id },
3255
- });
3256
- // Acceptance does not confirm termination. Allow retry while the provider
3257
- // finishes stopping the tasks or reports a failure.
3258
- setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
3259
- if (result._tag === "Failure") {
3260
- if (!isAtomCommandInterrupted(result)) {
3261
- const error = squashAtomCommandFailure(result);
3262
- setThreadError(
3263
- activeThread.id,
3264
- error instanceof Error ? error.message : "Failed to stop background work.",
3265
- );
3266
- }
3267
- }
3268
- };
3269
- const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
3270
- const openRelatedThreadGenerationRef = useRef(0);
3271
- const onOpenRelatedThread = async (threadId: ThreadId) => {
3272
- const generation = ++openRelatedThreadGenerationRef.current;
3273
- const threadRef = scopeThreadRef(environmentId, threadId);
3274
- const isEnvironmentLive = () =>
3275
- appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live";
3276
- // A just-launched child can reach this timeline before its shell syncs.
3277
- if (isEnvironmentLive() && readThreadShell(threadRef) === null) {
3278
- const location = router.latestLocation;
3279
- await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
3280
- if (
3281
- generation !== openRelatedThreadGenerationRef.current ||
3282
- currentRouteThreadKeyRef.current !== routeThreadKey ||
3283
- router.latestLocation !== location
3284
- ) {
3285
- return;
3286
- }
3287
- }
3288
- const shell = readThreadShell(threadRef);
3289
- if (shell === null ? isEnvironmentLive() : shell.deletedAt != null) {
3290
- toastManager.add({ type: "info", title: "This thread is no longer available" });
3291
- return;
3292
- }
3293
- void navigate({
3294
- to: "/$environmentId/$threadId",
3295
- params: buildThreadRouteParams(threadRef),
3296
- });
3297
- };
3298
- const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
3299
- const childThreadInputs = useChildThreadInputs(activeThreadRef);
3300
- const childInputBanner = childInputBannerItem({
3301
- childThreadInputs,
3302
- parentAwaitingUser: Boolean(
3303
- activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
3304
- ),
3305
- onOpenThread: onOpenRelatedThreadStable,
3037
+ gitStatusQuery,
3038
+ nowMinute,
3039
+ composerRef,
3040
+ composerDraftTarget,
3041
+ sendInFlightRef,
3042
+ setOptimisticUserMessages,
3043
+ setThreadError,
3044
+ clearUsageLimitsFor,
3045
+ beginLocalDispatch,
3046
+ resetLocalDispatch,
3047
+ scheduleComposerFocus,
3048
+ scrollToEnd,
3049
+ persistThreadSettingsForNextTurn,
3050
});
3307
-
3308
- const sendStandaloneCommand = async (text: string, failureMessage: string) => {
3309
- if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
3310
- const context = composerRef.current?.getSendContext();
3311
- if (!context?.providerAvailable) return;
3312
-
3313
- const threadId = activeThread.id;
3314
- const messageId = newMessageId();
3315
- const createdAt = new Date().toISOString();
3316
- sendInFlightRef.current = true;
3317
- beginLocalDispatch();
3318
- setThreadError(threadId, null);
3319
- setOptimisticUserMessages((messages) => [
3320
- ...messages,
3321
- {
3322
- id: messageId,
3323
- role: "user",
3324
- text,
3325
- runId: null,
3326
- createdAt,
3327
- updatedAt: createdAt,
3328
- streaming: false,
3329
- },
3330
- ]);
3331
- scrollToEnd();
3332
- // Commands settle into a result, so this always runs.
3333
- const settingsResult = await persistThreadSettingsForNextTurn({
3334
- threadId,
3335
- createdAt,
3336
- ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
3337
- runtimeMode,
3338
- interactionMode: context.interactionMode,
3339
- });
3340
- const result =
3341
- settingsResult._tag === "Failure"
3342
- ? settingsResult
3343
- : await startThreadTurn({
3344
- environmentId,
3345
- input: {
3346
- threadId,
3347
- message: { messageId, role: "user", text, attachments: [] },
3348
- modelSelection: context.selectedModelSelection,
3349
- runtimeMode,
3350
- interactionMode: context.interactionMode,
3351
- createdAt,
3352
- },
3353
- });
3354
- if (result._tag === "Failure") {
3355
- setOptimisticUserMessages((messages) =>
3356
- messages.filter((message) => message.id !== messageId),
3357
- );
3358
- resetLocalDispatch();
3359
- if (!isAtomCommandInterrupted(result)) {
3360
- const error = squashAtomCommandFailure(result);
3361
- setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
3362
- }
3363
- } else {
3364
- clearUsageLimitsFor(routeThreadKey);
3365
- }
3366
- sendInFlightRef.current = false;
3367
- };
3368
- const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
3369
- const activeGoal = activeThreadShell?.goal ?? null;
3370
- const goalBanner =
3371
- activeThread && activeGoal !== null
3372
- ? goalBannerItem({
3373
- threadId: activeThread.id,
3374
- goal: activeGoal,
3375
- isWorking,
3376
- onSendCommand: sendStandaloneCommandStable,
3377
- })
3378
- : null;
3379
-
3380
- const backgroundWorkBanner = activeThread
3381
- ? backgroundWorkBannerItem({
3382
- threadId: activeThread.id,
3383
- tasks: activeBackgroundTasks,
3384
- stopDisabled: !canOperateThread || isStoppingBackgroundWork,
3385
- stopping: isStoppingBackgroundWork,
3386
- onStop: handleStopBackgroundWorkStable,
3387
- onOpenThread: onOpenRelatedThreadStable,
3388
- })
3389
- : null;
3390
- // The relative times read the clock; nowMinute re-renders them on the minute.
3391
- const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
3392
- const settledAt = activeThreadShell?.settledAt ?? null;
3393
- const threadStatusLine = activeThreadSnoozed ? (
3394
- <ThreadStatusLine
3395
- icon={<AlarmClockIcon />}
3396
- label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"}
3397
- clockMinute={nowMinute}
3398
- actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
3399
- actionDisabled={!canOperateThread || isUnsnoozing}
3400
- onAction={() => void handleUnsnoozeActiveThreadStable()}
3401
- />
3402
- ) : activeThreadSettled ? (
3403
- <ThreadStatusLine
3404
- icon={<CheckCircle2Icon />}
3405
- label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
3406
- clockMinute={nowMinute}
3407
- actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
3408
- actionDisabled={!canOperateThread || isUnsettling}
3409
- onAction={() => void handleUnsettleActiveThreadStable()}
3410
- />
3411
- ) : activeThreadWokeVisible ? (
3412
- <ThreadStatusLine
3413
- icon={<AlarmClockIcon />}
3414
- label="Woke from snooze"
3415
- actionLabel="Dismiss"
3416
- onAction={acknowledgeActiveThreadWokeStable}
3417
- />
3418
- ) : null;
3051
const activeThreadHasCompactableConversation = serverVisibleTurnItems.some(
3052
({ item }) =>
3053
item.type === "user_message" &&
apps/web/src/components/chat/useThreadLifecycle.tsx
new
+582
@@ -0,0 +1,582 @@
1
+import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
2
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
3
+import type { Dispatch } from "react";
4
+import type { ComposerThreadTarget } from "../../composerDraftStore";
5
+import type { ComposerHandleRef } from "../../composerHandleContext";
6
+import {
7
+ isThreadWokeUnseen,
8
+ branchMismatchKey,
9
+ isBranchMismatchDismissedForSession,
10
+ shouldShowBranchMismatchBanner,
11
+ chatActionErrorMessage,
12
+ makeThreadErrorSetter,
13
+} from "../ChatView.logic";
14
+import { useStableCallback } from "../../hooks/useStableCallback";
15
+import type { usePendingThreadRequests } from "./usePendingThreadRequests";
16
+import {
17
+ AuthOrchestrationOperateScope,
18
+ AuthSourceControlWriteScope,
19
+ type EnvironmentId,
20
+ type ScopedThreadRef,
21
+ type ThreadId,
22
+ ProviderInteractionMode,
23
+ RuntimeMode,
24
+} from "@t3tools/contracts";
25
+import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
26
+import { useAcknowledgeThreadWoke } from "../../hooks/useThreadActions";
27
+import { resolveThreadLastVisitedAt } from "../Sidebar.logic";
28
+import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
29
+import { type SetStateAction, useEffect, useRef, useState } from "react";
30
+import { useNavigate, useRouter } from "@tanstack/react-router";
31
+import {
32
+ isAtomCommandInterrupted,
33
+ squashAtomCommandFailure,
34
+ type AtomCommandResult,
35
+} from "@t3tools/client-runtime/state/runtime";
36
+import { useUiStateStore } from "../../uiStateStore";
37
+import { type ChatMessage } from "../../types";
38
+import { AlarmClockIcon, CheckCircle2Icon } from "lucide-react";
39
+import { stackedThreadToast, toastManager } from "../ui/toast";
40
+import { newMessageId } from "~/lib/utils";
41
+import { buildThreadRouteParams } from "../../threadRoutes";
42
+import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore";
43
+import { useEnvironmentScope } from "~/state/session";
44
+import { threadEnvironment } from "../../state/threads";
45
+import { vcsEnvironment } from "../../state/vcs";
46
+import { useChildThreadInputs, readThreadShell, waitForThreadShell } from "../../state/entities";
47
+import { environmentShell } from "../../state/shell";
48
+import { ThreadStatusLine } from "./ThreadStatusLine";
49
+import { formatRelativeTimeLabel, formatRelativeTimeUntilLabel } from "../../timestampFormat";
50
+import { appAtomRegistry } from "../../rpc/atomRegistry";
51
+import { readEnvironmentScope } from "../../state/session";
52
+import { useAtomCommand } from "../../state/use-atom-command";
53
+import { useOrchestrationCommand } from "../../state/use-orchestration-command";
54
+import {
55
+ backgroundWorkBannerItem,
56
+ childInputBannerItem,
57
+ goalBannerItem,
58
+} from "./ThreadActivityBanners";
59
+import type { useLocalDispatchState } from "./useLocalDispatchState";
60
+const RELATED_THREAD_SHELL_WAIT_MS = 1_000;
61
+
62
+type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
63
+type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
64
+
65
+interface ThreadLifecycleInput {
66
+ readonly environmentId: EnvironmentId;
67
+ readonly routeThreadKey: string;
68
+ readonly currentRouteThreadKeyRef: { readonly current: string | null };
69
+ readonly canOperateThread: boolean;
70
+ readonly clientSettingsHydrated: boolean;
71
+ readonly activeThread: EnvironmentThreadShell | undefined;
72
+ readonly activeThreadId: ThreadId | null;
73
+ readonly activeThreadRef: ScopedThreadRef | null;
74
+ readonly activeThreadKey: string | null;
75
+ readonly activeThreadShell: EnvironmentThreadShell | null;
76
+ readonly activeLatestRun: EnvironmentThreadShell["latestRun"];
77
+ readonly activeProjectCwd: string | null;
78
+ readonly serverConfig: EnvironmentServerConfig | null;
79
+ readonly runtimeMode: RuntimeMode;
80
+ readonly isWorking: boolean;
81
+ readonly pendingBackgroundTasks: Parameters<typeof backgroundWorkBannerItem>[0]["tasks"];
82
+ readonly activePendingApproval: PendingThreadRequests["activePendingApproval"];
83
+ readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"];
84
+ readonly localCheckoutBranchMismatch: {
85
+ readonly threadBranch: string;
86
+ readonly currentBranch: string;
87
+ } | null;
88
+ readonly gitStatusQuery: { readonly refresh: () => void };
89
+ readonly nowMinute: string;
90
+ readonly composerRef: ComposerHandleRef;
91
+ readonly composerDraftTarget: ComposerThreadTarget;
92
+ readonly sendInFlightRef: { current: boolean };
93
+ readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
94
+ readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
95
+ readonly clearUsageLimitsFor: (threadKey: string) => void;
96
+ readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
97
+ readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
98
+ readonly scheduleComposerFocus: () => void;
99
+ readonly scrollToEnd: (animated?: boolean) => void;
100
+ readonly persistThreadSettingsForNextTurn: (input: {
101
+ threadId: ThreadId;
102
+ createdAt: string;
103
+ branch?: string;
104
+ runtimeMode: RuntimeMode;
105
+ interactionMode: ProviderInteractionMode;
106
+ }) => Promise<AtomCommandResult<void, unknown>>;
107
+}
108
+
109
+/**
110
+ * Thread state the chat shows and changes outside a normal send: snooze and settle with
111
+ * their status line, the local checkout's branch, background work, child-thread and goal
112
+ * banners, opening related threads, and standalone slash commands.
113
+ */
114
+export function useThreadLifecycle(input: ThreadLifecycleInput) {
115
+ const {
116
+ environmentId,
117
+ routeThreadKey,
118
+ currentRouteThreadKeyRef,
119
+ canOperateThread,
120
+ clientSettingsHydrated,
121
+ activeThread,
122
+ activeThreadId,
123
+ activeThreadRef,
124
+ activeThreadKey,
125
+ activeThreadShell,
126
+ activeLatestRun,
127
+ activeProjectCwd,
128
+ serverConfig,
129
+ runtimeMode,
130
+ isWorking,
131
+ pendingBackgroundTasks,
132
+ activePendingApproval,
133
+ activePendingUserInput,
134
+ localCheckoutBranchMismatch,
135
+ gitStatusQuery,
136
+ nowMinute,
137
+ composerRef,
138
+ composerDraftTarget,
139
+ sendInFlightRef,
140
+ setOptimisticUserMessages,
141
+ setThreadError,
142
+ clearUsageLimitsFor,
143
+ beginLocalDispatch,
144
+ resetLocalDispatch,
145
+ scheduleComposerFocus,
146
+ scrollToEnd,
147
+ persistThreadSettingsForNextTurn,
148
+ } = input;
149
+ const navigate = useNavigate();
150
+ const router = useRouter();
151
+ const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
152
+ const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });
153
+ const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
154
+ reportFailure: false,
155
+ });
156
+ const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
157
+ reportFailure: false,
158
+ });
159
+ const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
160
+ reportFailure: false,
161
+ });
162
+
163
+ const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
164
+ const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
165
+ const supportsPinning = serverConfig?.environment.capabilities.threadPinning === true;
166
+ const activeThreadPinned = supportsPinning && activeThreadShell?.pinnedAt != null;
167
+ // The compiler caches render results on their inputs, so a clock read in render
168
+ // stays frozen until the shell changes. The clock is state: reset with the shell,
169
+ // and moved by the wake timer.
170
+ const [snoozeClockState, setSnoozeClockState] = useState(() => ({
171
+ shell: activeThreadShell,
172
+ now: new Date().toISOString(),
173
+ }));
174
+ if (snoozeClockState.shell !== activeThreadShell) {
175
+ setSnoozeClockState({ shell: activeThreadShell, now: new Date().toISOString() });
176
+ }
177
+ const snoozeClock = snoozeClockState.now;
178
+ const activeThreadSnoozed =
179
+ activeThreadShell !== null &&
180
+ supportsSnooze &&
181
+ effectiveSnoozed(activeThreadShell, { now: snoozeClock });
182
+ useEffect(() => {
183
+ if (!activeThreadSnoozed) return;
184
+ const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
185
+ if (!Number.isFinite(wakeAtMs)) return;
186
+ const id = window.setTimeout(
187
+ () => setSnoozeClockState((clock) => ({ ...clock, now: new Date().toISOString() })),
188
+ Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
189
+ );
190
+ return () => window.clearTimeout(id);
191
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A clock that lands before the wake time (timer clamping, clock skew) re-arms the timer.
192
+ }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeClock]);
193
+ const activeThreadWokeAt =
194
+ activeThreadShell !== null && supportsSnooze
195
+ ? threadWokeAt(activeThreadShell, { now: snoozeClock })
196
+ : null;
197
+ const acknowledgeThreadWoke = useAcknowledgeThreadWoke();
198
+ const acknowledgeActiveThreadWoke = () => {
199
+ if (activeThreadRef === null || activeThreadWokeAt === null) return;
200
+ acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt);
201
+ };
202
+ const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke);
203
+ const activeThreadLocalVisitedAt = useUiStateStore((store) =>
204
+ activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],
205
+ );
206
+ const activeThreadLastVisitedAt = resolveThreadLastVisitedAt(
207
+ activeThreadShell?.lastVisitedAt,
208
+ activeThreadLocalVisitedAt,
209
+ );
210
+ const activeThreadWokeVisible = isThreadWokeUnseen({
211
+ wokeAt: activeThreadWokeAt,
212
+ settled: activeThreadShell?.settledOverride === "settled",
213
+ lastVisitedAt: activeThreadLastVisitedAt,
214
+ latestRunCompletedAt: activeLatestRun?.completedAt ?? null,
215
+ });
216
+ const activeThreadSettled =
217
+ supportsSettlement && activeThreadShell?.settledOverride === "settled";
218
+ const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
219
+ reportFailure: false,
220
+ });
221
+ const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
222
+ const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
223
+ const handleUnsettleActiveThread = async () => {
224
+ if (
225
+ !activeThreadRef ||
226
+ !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
227
+ )
228
+ return;
229
+ const threadKey = scopedThreadKey(activeThreadRef);
230
+ setUnsettlingThreadKey(threadKey);
231
+ // Commands settle into a result, so this always runs.
232
+ const result = await unsettleThreadMutation({
233
+ environmentId: activeThreadRef.environmentId,
234
+ input: { threadId: activeThreadRef.threadId, reason: "user" },
235
+ });
236
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
237
+ const error = squashAtomCommandFailure(result);
238
+ toastManager.add(
239
+ stackedThreadToast({
240
+ type: "error",
241
+ title: "Failed to un-settle thread",
242
+ description: error instanceof Error ? error.message : "An error occurred.",
243
+ }),
244
+ );
245
+ }
246
+ setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
247
+ };
248
+ const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread);
249
+ const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
250
+ reportFailure: false,
251
+ });
252
+ const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);
253
+ const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;
254
+ const handleUnsnoozeActiveThread = async () => {
255
+ if (
256
+ !activeThreadRef ||
257
+ !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope)
258
+ )
259
+ return;
260
+ const threadKey = scopedThreadKey(activeThreadRef);
261
+ setUnsnoozingThreadKey(threadKey);
262
+ // Commands settle into a result, so this always runs.
263
+ const recovery = activeThreadShell?.limitRecovery;
264
+ const recoveryOwnsSnooze =
265
+ recovery?.snooze === true &&
266
+ recovery.runId === activeThreadShell?.latestRun?.runId &&
267
+ activeThreadShell?.snoozedUntil != null &&
268
+ Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt);
269
+ const result = recoveryOwnsSnooze
270
+ ? await updateThreadMetadata({
271
+ environmentId: activeThreadRef.environmentId,
272
+ input: {
273
+ threadId: activeThreadRef.threadId,
274
+ limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false },
275
+ },
276
+ })
277
+ : await unsnoozeThreadMutation({
278
+ environmentId: activeThreadRef.environmentId,
279
+ input: { threadId: activeThreadRef.threadId, reason: "user" },
280
+ });
281
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
282
+ const error = squashAtomCommandFailure(result);
283
+ toastManager.add(
284
+ stackedThreadToast({
285
+ type: "error",
286
+ title: "Failed to wake thread",
287
+ description: error instanceof Error ? error.message : "An error occurred.",
288
+ }),
289
+ );
290
+ }
291
+ setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));
292
+ };
293
+ const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
294
+ const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
295
+ const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
296
+ const [, setBranchMismatchDismissTick] = useState(0);
297
+ const composerHasDraftContent = useComposerDraftStore((store) =>
298
+ composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),
299
+ );
300
+ const activeBranchMismatchKey = branchMismatchKey(
301
+ activeThread?.id ?? null,
302
+ localCheckoutBranchMismatch,
303
+ );
304
+ const showBranchMismatchBanner = shouldShowBranchMismatchBanner({
305
+ hasMismatch: localCheckoutBranchMismatch !== null,
306
+ isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),
307
+ composerHasContent: composerHasDraftContent,
308
+ wasShownForCurrentMismatch:
309
+ revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
310
+ });
311
+ const nextRevealedBranchMismatchKey = showBranchMismatchBanner
312
+ ? activeBranchMismatchKey
313
+ : revealedBranchMismatchKey !== activeBranchMismatchKey
314
+ ? null
315
+ : revealedBranchMismatchKey;
316
+ if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
317
+ setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
318
+ }
319
+ const handleSwitchCheckoutToThread = async () => {
320
+ if (!canWriteSourceControl) return;
321
+ if (
322
+ !activeProjectCwd ||
323
+ !activeThread ||
324
+ !localCheckoutBranchMismatch ||
325
+ isRestoringThreadBranch
326
+ ) {
327
+ return;
328
+ }
329
+ setIsRestoringThreadBranch(true);
330
+ const checkoutResult = await switchGitRef({
331
+ environmentId,
332
+ input: {
333
+ cwd: activeProjectCwd,
334
+ refName: localCheckoutBranchMismatch.threadBranch,
335
+ },
336
+ });
337
+ if (checkoutResult._tag === "Failure") {
338
+ setIsRestoringThreadBranch(false);
339
+ if (!isAtomCommandInterrupted(checkoutResult)) {
340
+ toastManager.add(
341
+ stackedThreadToast({
342
+ type: "error",
343
+ title: "Failed to switch checkout",
344
+ description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),
345
+ }),
346
+ );
347
+ }
348
+ return;
349
+ }
350
+
351
+ if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) {
352
+ setIsRestoringThreadBranch(false);
353
+ return;
354
+ }
355
+ const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;
356
+ if (nextBranch !== activeThread.branch) {
357
+ const updateResult = await updateThreadMetadata({
358
+ environmentId,
359
+ input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },
360
+ });
361
+ if (updateResult._tag === "Failure") {
362
+ setIsRestoringThreadBranch(false);
363
+ if (!isAtomCommandInterrupted(updateResult)) {
364
+ toastManager.add(
365
+ stackedThreadToast({
366
+ type: "error",
367
+ title: "Checkout switched, but the thread could not be updated",
368
+ description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),
369
+ }),
370
+ );
371
+ }
372
+ gitStatusQuery.refresh();
373
+ return;
374
+ }
375
+ }
376
+ gitStatusQuery.refresh();
377
+ setIsRestoringThreadBranch(false);
378
+ scheduleComposerFocus();
379
+ };
380
+ const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
381
+ void handleSwitchCheckoutToThread();
382
+ });
383
+ // The interrupt path also accepts a completed run while its provider still
384
+ // has background work.
385
+ const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
386
+ const [stoppingBackgroundWorkKey, setStoppingBackgroundWorkKey] = useState<string | null>(null);
387
+ const isStoppingBackgroundWork =
388
+ stoppingBackgroundWorkKey === `${environmentId}:${activeThreadId}`;
389
+ const handleStopBackgroundWork = async () => {
390
+ if (!activeThread || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope))
391
+ return;
392
+ const requestKey = `${environmentId}:${activeThread.id}`;
393
+ setStoppingBackgroundWorkKey(requestKey);
394
+ const result = await interruptThreadTurn({
395
+ environmentId,
396
+ input: { threadId: activeThread.id },
397
+ });
398
+ // Acceptance does not confirm termination. Allow retry while the provider
399
+ // finishes stopping the tasks or reports a failure.
400
+ setStoppingBackgroundWorkKey((current) => (current === requestKey ? null : current));
401
+ if (result._tag === "Failure") {
402
+ if (!isAtomCommandInterrupted(result)) {
403
+ const error = squashAtomCommandFailure(result);
404
+ setThreadError(
405
+ activeThread.id,
406
+ error instanceof Error ? error.message : "Failed to stop background work.",
407
+ );
408
+ }
409
+ }
410
+ };
411
+ const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork);
412
+ const openRelatedThreadGenerationRef = useRef(0);
413
+ const onOpenRelatedThread = async (threadId: ThreadId) => {
414
+ const generation = ++openRelatedThreadGenerationRef.current;
415
+ const threadRef = scopeThreadRef(environmentId, threadId);
416
+ const isEnvironmentLive = () =>
417
+ appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live";
418
+ // A just-launched child can reach this timeline before its shell syncs.
419
+ if (isEnvironmentLive() && readThreadShell(threadRef) === null) {
420
+ const location = router.latestLocation;
421
+ await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);
422
+ if (
423
+ generation !== openRelatedThreadGenerationRef.current ||
424
+ currentRouteThreadKeyRef.current !== routeThreadKey ||
425
+ router.latestLocation !== location
426
+ ) {
427
+ return;
428
+ }
429
+ }
430
+ const shell = readThreadShell(threadRef);
431
+ if (shell === null ? isEnvironmentLive() : shell.deletedAt != null) {
432
+ toastManager.add({ type: "info", title: "This thread is no longer available" });
433
+ return;
434
+ }
435
+ void navigate({
436
+ to: "/$environmentId/$threadId",
437
+ params: buildThreadRouteParams(threadRef),
438
+ });
439
+ };
440
+ const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
441
+ const childThreadInputs = useChildThreadInputs(activeThreadRef);
442
+ const childInputBanner = childInputBannerItem({
443
+ childThreadInputs,
444
+ parentAwaitingUser: Boolean(
445
+ activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput,
446
+ ),
447
+ onOpenThread: onOpenRelatedThreadStable,
448
+ });
449
+
450
+ const sendStandaloneCommand = async (text: string, failureMessage: string) => {
451
+ if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
452
+ const context = composerRef.current?.getSendContext();
453
+ if (!context?.providerAvailable) return;
454
+
455
+ const threadId = activeThread.id;
456
+ const messageId = newMessageId();
457
+ const createdAt = new Date().toISOString();
458
+ sendInFlightRef.current = true;
459
+ beginLocalDispatch();
460
+ setThreadError(threadId, null);
461
+ setOptimisticUserMessages((messages) => [
462
+ ...messages,
463
+ {
464
+ id: messageId,
465
+ role: "user",
466
+ text,
467
+ runId: null,
468
+ createdAt,
469
+ updatedAt: createdAt,
470
+ streaming: false,
471
+ },
472
+ ]);
473
+ scrollToEnd();
474
+ // Commands settle into a result, so this always runs.
475
+ const settingsResult = await persistThreadSettingsForNextTurn({
476
+ threadId,
477
+ createdAt,
478
+ ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
479
+ runtimeMode,
480
+ interactionMode: context.interactionMode,
481
+ });
482
+ const result =
483
+ settingsResult._tag === "Failure"
484
+ ? settingsResult
485
+ : await startThreadTurn({
486
+ environmentId,
487
+ input: {
488
+ threadId,
489
+ message: { messageId, role: "user", text, attachments: [] },
490
+ modelSelection: context.selectedModelSelection,
491
+ runtimeMode,
492
+ interactionMode: context.interactionMode,
493
+ createdAt,
494
+ },
495
+ });
496
+ if (result._tag === "Failure") {
497
+ setOptimisticUserMessages((messages) =>
498
+ messages.filter((message) => message.id !== messageId),
499
+ );
500
+ resetLocalDispatch();
501
+ if (!isAtomCommandInterrupted(result)) {
502
+ const error = squashAtomCommandFailure(result);
503
+ setThreadError(threadId, error instanceof Error ? error.message : failureMessage);
504
+ }
505
+ } else {
506
+ clearUsageLimitsFor(routeThreadKey);
507
+ }
508
+ sendInFlightRef.current = false;
509
+ };
510
+ const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
511
+ const activeGoal = activeThreadShell?.goal ?? null;
512
+ const goalBanner =
513
+ activeThread && activeGoal !== null
514
+ ? goalBannerItem({
515
+ threadId: activeThread.id,
516
+ goal: activeGoal,
517
+ isWorking,
518
+ onSendCommand: sendStandaloneCommandStable,
519
+ })
520
+ : null;
521
+
522
+ const backgroundWorkBanner = activeThread
523
+ ? backgroundWorkBannerItem({
524
+ threadId: activeThread.id,
525
+ tasks: activeBackgroundTasks,
526
+ stopDisabled: !canOperateThread || isStoppingBackgroundWork,
527
+ stopping: isStoppingBackgroundWork,
528
+ onStop: handleStopBackgroundWorkStable,
529
+ onOpenThread: onOpenRelatedThreadStable,
530
+ })
531
+ : null;
532
+ // The relative times read the clock; nowMinute re-renders them on the minute.
533
+ const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
534
+ const settledAt = activeThreadShell?.settledAt ?? null;
535
+ const threadStatusLine = activeThreadSnoozed ? (
536
+ <ThreadStatusLine
537
+ icon={<AlarmClockIcon />}
538
+ label={snoozedUntil ? `Snoozed, ${formatRelativeTimeUntilLabel(snoozedUntil)}` : "Snoozed"}
539
+ clockMinute={nowMinute}
540
+ actionLabel={isUnsnoozing ? "Waking..." : "Wake now"}
541
+ actionDisabled={!canOperateThread || isUnsnoozing}
542
+ onAction={() => void handleUnsnoozeActiveThreadStable()}
543
+ />
544
+ ) : activeThreadSettled ? (
545
+ <ThreadStatusLine
546
+ icon={<CheckCircle2Icon />}
547
+ label={settledAt ? `Settled ${formatRelativeTimeLabel(settledAt)}` : "Settled"}
548
+ clockMinute={nowMinute}
549
+ actionLabel={isUnsettling ? "Un-settling..." : "Un-settle"}
550
+ actionDisabled={!canOperateThread || isUnsettling}
551
+ onAction={() => void handleUnsettleActiveThreadStable()}
552
+ />
553
+ ) : activeThreadWokeVisible ? (
554
+ <ThreadStatusLine
555
+ icon={<AlarmClockIcon />}
556
+ label="Woke from snooze"
557
+ actionLabel="Dismiss"
558
+ onAction={acknowledgeActiveThreadWokeStable}
559
+ />
560
+ ) : null;
561
+ return {
562
+ acknowledgeActiveThreadWoke,
563
+ activeBranchMismatchKey,
564
+ activeThreadPinned,
565
+ activeThreadSettled,
566
+ backgroundWorkBanner,
567
+ childInputBanner,
568
+ goalBanner,
569
+ handleSwitchCheckoutToThread,
570
+ handleSwitchCheckoutToThreadStable,
571
+ handleUnsettleActiveThreadStable,
572
+ isRestoringThreadBranch,
573
+ onOpenRelatedThread,
574
+ onOpenRelatedThreadStable,
575
+ sendStandaloneCommand,
576
+ setBranchMismatchDismissTick,
577
+ showBranchMismatchBanner,
578
+ supportsPinning,
579
+ supportsSettlement,
580
+ threadStatusLine,
581
+ };
582
+}