Skip to content
This repository was archived by the owner on Oct 10, 2026. It is now read-only.

Commit bb38c33

Browse files
t3dotggclaude
andauthored
fix(web): keep settled threads reachable when opened directly (pingdotgg#4413)
Co-authored-by: Claude Fable 5 <[email protected]>
1 parent 6b9a598 commit bb38c33

3 files changed

Lines changed: 187 additions & 16 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 98 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
connectionStatusTitle,
2626
type EnvironmentConnectionPresentation,
2727
} from "@t3tools/client-runtime/connection";
28+
import { effectiveSettled } from "@t3tools/client-runtime/state/thread-settled";
2829
import {
2930
parseScopedThreadKey,
3031
scopedThreadKey,
@@ -138,7 +139,13 @@ import { BranchToolbar } from "./BranchToolbar";
138139
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
139140
import PlanSidebar from "./PlanSidebar";
140141
import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
141-
import { ChevronDownIcon, GitBranchIcon, TriangleAlertIcon, WifiOffIcon } from "lucide-react";
142+
import {
143+
CheckCircle2Icon,
144+
ChevronDownIcon,
145+
GitBranchIcon,
146+
TriangleAlertIcon,
147+
WifiOffIcon,
148+
} from "lucide-react";
142149
import { cn, randomHex } from "~/lib/utils";
143150
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
144151
import { stackedThreadToast, toastManager } from "./ui/toast";
@@ -153,7 +160,8 @@ import {
153160
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
154161
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
155162
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
156-
import { useEnvironmentSettings } from "../hooks/useSettings";
163+
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
164+
import { useNowMinute } from "../hooks/useNowMinute";
157165
import { resolveAppModelSelectionForInstance } from "../modelSelection";
158166
import { getTerminalFocusOwner } from "../lib/terminalFocus";
159167
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
@@ -202,6 +210,7 @@ import {
202210
useThread,
203211
useThreadProposedPlans,
204212
useThreadRefs,
213+
useThreadShell,
205214
} from "../state/entities";
206215
import { environmentShell } from "../state/shell";
207216
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
@@ -220,6 +229,7 @@ import {
220229
shouldShowProviderStatusBanner,
221230
} from "./chat/ProviderStatusBanner";
222231
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
232+
import { resolveThreadPr } from "./ThreadStatusIndicators";
223233
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
224234
import {
225235
DRAFT_HERO_TRANSITION_ANIMATION_ID,
@@ -3823,6 +3833,63 @@ function ChatViewContent(props: ChatViewProps) {
38233833
: null,
38243834
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
38253835
);
3836+
// Settled state of the open thread, resolved exactly like the sidebar
3837+
// partition (same shell, same capability gate, same PR auto-settle input)
3838+
// so the banner and the sidebar row never disagree.
3839+
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
3840+
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
3841+
const activeThreadPr = resolveThreadPr({
3842+
threadBranch: activeThread?.branch ?? null,
3843+
gitStatus: gitStatusQuery.data ?? null,
3844+
hasDedicatedWorktree: (activeThread?.worktreePath ?? null) !== null,
3845+
});
3846+
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
3847+
const nowMinute = useNowMinute();
3848+
const activeThreadSettled = useMemo(() => {
3849+
if (activeThreadShell === null || !supportsSettlement) return false;
3850+
return effectiveSettled(activeThreadShell, {
3851+
now: `${nowMinute}:00.000Z`,
3852+
autoSettleAfterDays,
3853+
changeRequestState: activeThreadPr?.state ?? null,
3854+
});
3855+
}, [
3856+
activeThreadPr?.state,
3857+
activeThreadShell,
3858+
autoSettleAfterDays,
3859+
nowMinute,
3860+
supportsSettlement,
3861+
]);
3862+
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
3863+
reportFailure: false,
3864+
});
3865+
// Keyed by thread, not a boolean: the pending state must follow the thread
3866+
// it belongs to across navigation, and a request resolving for thread A
3867+
// must never clear (or re-enable) thread B's button.
3868+
const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);
3869+
const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;
3870+
const handleUnsettleActiveThread = useCallback(async () => {
3871+
if (!activeThreadRef) return;
3872+
const threadKey = scopedThreadKey(activeThreadRef);
3873+
setUnsettlingThreadKey(threadKey);
3874+
try {
3875+
const result = await unsettleThreadMutation({
3876+
environmentId: activeThreadRef.environmentId,
3877+
input: { threadId: activeThreadRef.threadId, reason: "user" },
3878+
});
3879+
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
3880+
const error = squashAtomCommandFailure(result);
3881+
toastManager.add(
3882+
stackedThreadToast({
3883+
type: "error",
3884+
title: "Failed to un-settle thread",
3885+
description: error instanceof Error ? error.message : "An error occurred.",
3886+
}),
3887+
);
3888+
}
3889+
} finally {
3890+
setUnsettlingThreadKey((current) => (current === threadKey ? null : current));
3891+
}
3892+
}, [activeThreadRef, unsettleThreadMutation]);
38263893
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
38273894
const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
38283895
// Once revealed for a given mismatch, the banner stays mounted until the
@@ -3930,6 +3997,31 @@ function ChatViewContent(props: ChatViewProps) {
39303997
switchGitRef,
39313998
updateThreadMetadata,
39323999
]);
4000+
// The stack renders items[0] front-most and tucks the rest behind hover, so
4001+
// ordering is priority: system banners, then the branch-mismatch notice,
4002+
// and the informational settled banner last — it must never cover another.
4003+
const settledComposerBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
4004+
if (!activeThreadSettled) {
4005+
return null;
4006+
}
4007+
return {
4008+
id: `thread-settled:${activeThread?.id ?? "unknown"}`,
4009+
variant: "info",
4010+
icon: <CheckCircle2Icon />,
4011+
title: "This thread is settled",
4012+
description: "Sending a message moves it back to Active in the sidebar.",
4013+
actions: (
4014+
<Button
4015+
size="xs"
4016+
variant="outline"
4017+
disabled={isUnsettling}
4018+
onClick={() => void handleUnsettleActiveThread()}
4019+
>
4020+
{isUnsettling ? "Un-settling..." : "Un-settle"}
4021+
</Button>
4022+
),
4023+
};
4024+
}, [activeThread?.id, activeThreadSettled, handleUnsettleActiveThread, isUnsettling]);
39334025
const handleRestoreThreadBranch = useCallback(() => {
39344026
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
39354027
setBranchRestoreConfirmOpen(true);
@@ -3938,8 +4030,9 @@ function ChatViewContent(props: ChatViewProps) {
39384030
void handleSwitchCheckoutToThread();
39394031
}, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);
39404032
const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
4033+
const settledItems = settledComposerBannerItem === null ? [] : [settledComposerBannerItem];
39414034
if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
3942-
return systemComposerBannerItems;
4035+
return [...systemComposerBannerItems, ...settledItems];
39434036
}
39444037
return [
39454038
...systemComposerBannerItems,
@@ -3982,12 +4075,14 @@ function ChatViewContent(props: ChatViewProps) {
39824075
setBranchMismatchDismissTick((tick) => tick + 1);
39834076
},
39844077
},
4078+
...settledItems,
39854079
];
39864080
}, [
39874081
activeBranchMismatchKey,
39884082
handleRestoreThreadBranch,
39894083
isRestoringThreadBranch,
39904084
localCheckoutBranchMismatch,
4085+
settledComposerBannerItem,
39914086
showBranchMismatchBanner,
39924087
systemComposerBannerItems,
39934088
]);

‎apps/web/src/components/SidebarV2.tsx‎

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@ import { openCommandPalette } from "../commandPaletteBus";
7878
import { startNewThreadFromContext } from "../lib/chatThreadActions";
7979
import { useClientSettings, useUpdateClientSettings } from "../hooks/useSettings";
8080
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
81+
import { useNowMinute } from "../hooks/useNowMinute";
8182
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
8283
import { useProjects, useThreadShells } from "../state/entities";
8384
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
@@ -952,14 +953,7 @@ export default function SidebarV2() {
952953

953954
// now is quantized to the minute so effectiveSettled memoization doesn't
954955
// churn on every render; auto-settle thresholds are day-granular anyway.
955-
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
956-
useEffect(() => {
957-
const id = window.setInterval(
958-
() => setNowMinute(new Date().toISOString().slice(0, 16)),
959-
60_000,
960-
);
961-
return () => window.clearInterval(id);
962-
}, []);
956+
const nowMinute = useNowMinute();
963957

964958
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
965959
// closed PR auto-settles its thread on the next partition.
@@ -1223,11 +1217,24 @@ export default function SidebarV2() {
12231217
lastSettledResetKeyRef.current = settledResetKey;
12241218
setSettledVisibleCount(SETTLED_TAIL_INITIAL_COUNT);
12251219
}
1226-
const hiddenSettledCount = Math.max(0, settledThreads.length - settledVisibleCount);
1227-
const visibleSettledThreads = useMemo(
1228-
() => (hiddenSettledCount > 0 ? settledThreads.slice(0, settledVisibleCount) : settledThreads),
1229-
[hiddenSettledCount, settledThreads, settledVisibleCount],
1230-
);
1220+
const visibleSettledThreads = useMemo(() => {
1221+
if (settledThreads.length <= settledVisibleCount) return settledThreads;
1222+
const visible = settledThreads.slice(0, settledVisibleCount);
1223+
// The open thread must never hide under "Show more": navigating into a
1224+
// deep settled thread (search, deep link) pulls its row into the visible
1225+
// tail so the highlight and the un-settle affordance stay reachable.
1226+
if (routeThreadKey !== null) {
1227+
const routeThread = settledThreads
1228+
.slice(settledVisibleCount)
1229+
.find(
1230+
(thread) =>
1231+
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
1232+
);
1233+
if (routeThread !== undefined) visible.push(routeThread);
1234+
}
1235+
return visible;
1236+
}, [routeThreadKey, settledThreads, settledVisibleCount]);
1237+
const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length;
12311238
const showMoreSettled = useCallback(
12321239
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
12331240
[],

‎apps/web/src/hooks/useNowMinute.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { useSyncExternalStore } from "react";
2+
3+
/** Minute-quantized clock ("YYYY-MM-DDTHH:MM") for settled-state resolution.
4+
One module-level timer feeds every consumer through useSyncExternalStore,
5+
so all surfaces resolving effectiveSettled against it (sidebar partition,
6+
composer banner) share a single value by construction and tick on UTC
7+
minute boundaries together. */
8+
9+
function currentMinute(): string {
10+
return new Date().toISOString().slice(0, 16);
11+
}
12+
13+
let nowMinute = currentMinute();
14+
let timerId: number | null = null;
15+
let timerIsInterval = false;
16+
const listeners = new Set<() => void>();
17+
18+
function tick(): void {
19+
const next = currentMinute();
20+
if (next !== nowMinute) {
21+
nowMinute = next;
22+
for (const listener of listeners) listener();
23+
}
24+
}
25+
26+
function startTimer(): void {
27+
// Align to the next UTC minute boundary, then tick every 60s. Ticks re-read
28+
// the clock, so a throttled or late timer self-corrects when it fires.
29+
timerIsInterval = false;
30+
timerId = window.setTimeout(
31+
() => {
32+
tick();
33+
timerIsInterval = true;
34+
timerId = window.setInterval(tick, 60_000);
35+
},
36+
60_000 - (Date.now() % 60_000),
37+
);
38+
}
39+
40+
function subscribe(listener: () => void): () => void {
41+
if (listeners.size === 0) {
42+
startTimer();
43+
}
44+
listeners.add(listener);
45+
return () => {
46+
listeners.delete(listener);
47+
if (listeners.size === 0 && timerId !== null) {
48+
if (timerIsInterval) window.clearInterval(timerId);
49+
else window.clearTimeout(timerId);
50+
timerId = null;
51+
}
52+
};
53+
}
54+
55+
function getSnapshot(): string {
56+
// With no timer running (no subscribers yet — e.g. the first render after
57+
// a full unmount), the stored minute may be stale; re-read it so a fresh
58+
// mount renders the current minute instead of waiting for the first tick.
59+
// While the timer runs the cached value is returned untouched, as
60+
// useSyncExternalStore requires between change notifications.
61+
if (timerId === null) {
62+
nowMinute = currentMinute();
63+
}
64+
return nowMinute;
65+
}
66+
67+
export function useNowMinute(): string {
68+
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
69+
}

0 commit comments

Comments
 (0)