Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

fix(threads): a merged PR settles its thread only once (#7454)

Theo Brownef21b47e52d98
diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx
index 60cb1b475..642f7afe1 100644
--- a/apps/mobile/src/features/home/HomeScreen.tsx
+++ b/apps/mobile/src/features/home/HomeScreen.tsx
@@ -12,6 +12,7 @@ import {
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
+import type { ChangeRequestSettleSource } from "@t3tools/client-runtime/state/thread-settled";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -488,18 +489,24 @@ export function HomeScreen(props: HomeScreenProps) {
// optimistic holds.
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule, matching web.
- const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
- ReadonlyMap<string, "open" | "closed" | "merged">
+ const [changeRequestByKey, setChangeRequestByKey] = useState<
+ ReadonlyMap<string, ChangeRequestSettleSource>
>(() => new Map());
const handleChangeRequestState = useCallback(
- (threadKey: string, state: "open" | "closed" | "merged" | null) => {
- setChangeRequestStateByKey((current) => {
- if ((current.get(threadKey) ?? null) === state) return current;
+ (threadKey: string, changeRequest: ChangeRequestSettleSource | null) => {
+ setChangeRequestByKey((current) => {
+ const existing = current.get(threadKey) ?? null;
+ if (
+ (existing?.state ?? null) === (changeRequest?.state ?? null) &&
+ (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null)
+ ) {
+ return current;
+ }
const next = new Map(current);
- if (state === null) {
+ if (changeRequest === null) {
next.delete(threadKey);
} else {
- next.set(threadKey, state);
+ next.set(threadKey, changeRequest);
}
return next;
});
@@ -667,7 +674,7 @@ export function HomeScreen(props: HomeScreenProps) {
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
- changeRequestStateByKey,
+ changeRequestByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -679,7 +686,7 @@ export function HomeScreen(props: HomeScreenProps) {
selectedThreadKey: null,
});
}, [
- changeRequestStateByKey,
+ changeRequestByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 007778c0a..2e8186fa8 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -13,6 +13,7 @@ import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
+import type { ChangeRequestSettleSource } from "@t3tools/client-runtime/state/thread-settled";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import { Platform, Pressable, StyleSheet, TextInput, View } from "react-native";
@@ -420,18 +421,24 @@ function ThreadNavigationSidebarPane(
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule.
- const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
- ReadonlyMap<string, "open" | "closed" | "merged">
+ const [changeRequestByKey, setChangeRequestByKey] = useState<
+ ReadonlyMap<string, ChangeRequestSettleSource>
>(() => new Map());
const handleChangeRequestState = useCallback(
- (threadKey: string, state: "open" | "closed" | "merged" | null) => {
- setChangeRequestStateByKey((current) => {
- if ((current.get(threadKey) ?? null) === state) return current;
+ (threadKey: string, changeRequest: ChangeRequestSettleSource | null) => {
+ setChangeRequestByKey((current) => {
+ const existing = current.get(threadKey) ?? null;
+ if (
+ (existing?.state ?? null) === (changeRequest?.state ?? null) &&
+ (existing?.updatedAt ?? null) === (changeRequest?.updatedAt ?? null)
+ ) {
+ return current;
+ }
const next = new Map(current);
- if (state === null) {
+ if (changeRequest === null) {
next.delete(threadKey);
} else {
- next.set(threadKey, state);
+ next.set(threadKey, changeRequest);
}
return next;
});
@@ -552,7 +559,7 @@ function ThreadNavigationSidebarPane(
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
- changeRequestStateByKey,
+ changeRequestByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
@@ -564,7 +571,7 @@ function ThreadNavigationSidebarPane(
selectedThreadKey: props.selectedThreadKey ?? null,
});
}, [
- changeRequestStateByKey,
+ changeRequestByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index 0906bab4d..fa1e752d6 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -3,7 +3,11 @@ import type {
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
-import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
+import {
+ canSnooze,
+ resolveSnoozePresets,
+ type ChangeRequestSettleSource,
+} from "@t3tools/client-runtime/state/thread-settled";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
import { Alert, Platform, Pressable, useWindowDimensions, View } from "react-native";
@@ -365,11 +369,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
- /** Reports this row's live PR state for the partition's merge and close
- rules. Mirrors web's onChangeRequestState. */
+ /** Reports this row's live PR (state + last activity) for the partition's
+ merge and close rules. Mirrors web's onChangeRequestState. */
readonly onChangeRequestState?: (
threadKey: string,
- state: "open" | "closed" | "merged" | null,
+ changeRequest: ChangeRequestSettleSource | null,
) => void;
readonly projectCwd?: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
@@ -400,10 +404,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
+ const prUpdatedAt = pr?.updatedAt ?? null;
const threadKey = `${thread.environmentId}:${thread.id}`;
useEffect(() => {
- onChangeRequestState?.(threadKey, prState);
- }, [onChangeRequestState, prState, threadKey]);
+ onChangeRequestState?.(
+ threadKey,
+ prState === null ? null : { state: prState, updatedAt: prUpdatedAt },
+ );
+ }, [onChangeRequestState, prState, prUpdatedAt, threadKey]);
const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer");
diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts
index c4a1a844c..c58dbb675 100644
--- a/apps/mobile/src/features/threads/threadListV2.test.ts
+++ b/apps/mobile/src/features/threads/threadListV2.test.ts
@@ -269,7 +269,9 @@ describe("buildThreadListV2Items", () => {
threads: [merged],
environmentId: null,
searchQuery: "",
- changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
+ changeRequestByKey: new Map([
+ [`${environmentId}:${merged.id}`, { state: "merged" as const }],
+ ]),
autoSettleOnMerge: false,
now: NOW,
});
diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts
index 53b80e52c..45079bac6 100644
--- a/apps/mobile/src/features/threads/threadListV2.ts
+++ b/apps/mobile/src/features/threads/threadListV2.ts
@@ -6,7 +6,10 @@ import {
resolveSnoozePresets,
snoozeWakeLabel,
} from "@t3tools/client-runtime/state/thread-settled";
-import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
+import type {
+ ChangeRequestSettleSource,
+ SnoozePreset,
+} from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
@@ -318,8 +321,8 @@ export function buildThreadListV2Items(input: {
}> | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
- /** Per-row PR state reported up by visible rows ("env:threadId" keys). */
- readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
+ /** Per-row PR reported up by visible rows ("env:threadId" keys). */
+ readonly changeRequestByKey?: ReadonlyMap<string, ChangeRequestSettleSource>;
/** Environments whose server supports thread.settle/unsettle. Threads on
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
@@ -381,8 +384,8 @@ export function buildThreadListV2Items(input: {
}
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
- const changeRequestState =
- input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
+ const changeRequest =
+ input.changeRequestByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
@@ -410,7 +413,7 @@ export function buildThreadListV2Items(input: {
now,
autoSettleAfterDays,
autoSettleOnMerge,
- changeRequestState,
+ changeRequest,
})
) {
settled.push(thread);
diff --git a/apps/mobile/src/state/thread-pr-presentation.ts b/apps/mobile/src/state/thread-pr-presentation.ts
index 601e29fa4..76d57d557 100644
--- a/apps/mobile/src/state/thread-pr-presentation.ts
+++ b/apps/mobile/src/state/thread-pr-presentation.ts
@@ -6,6 +6,8 @@ export type ThreadPr = NonNullable<VcsStatusResult["pr"]>;
export interface ThreadPrPresentation {
readonly number: number;
readonly state: ThreadPr["state"];
+ /** Provider-side last activity, bounding when a terminal state landed. */
+ readonly updatedAt: string | null;
readonly url: string;
/** Compact pull request number label, e.g. "3774". */
readonly label: string;
@@ -28,6 +30,7 @@ export function presentThreadPr(
return {
number: pr.number,
state: pr.state,
+ updatedAt: pr.updatedAt ?? null,
url: pr.url,
label: String(pr.number),
accessibilityLabel: `#${pr.number} ${presentation.longName} ${pr.state}`,
diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts
index 2db58bbec..6291b3f33 100644
--- a/apps/server/src/git/GitManager.test.ts
+++ b/apps/server/src/git/GitManager.test.ts
@@ -717,6 +717,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-open-pr",
state: "open",
+ updatedAt: null,
});
}),
);
@@ -756,6 +757,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-trimmed-pr",
state: "open",
+ updatedAt: null,
});
}),
);
@@ -808,6 +810,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-valid-pr-entry",
state: "open",
+ updatedAt: null,
});
}),
);
@@ -858,6 +861,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-lowercase-state",
state: "merged",
+ updatedAt: "2026-01-02T00:00:00.000Z",
});
}),
);
@@ -1121,6 +1125,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "statemachine",
state: "open",
+ updatedAt: "2026-03-10T07:00:00.000Z",
});
expect(ghCalls).toContain(
"pr list --head jasonLaster:statemachine --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
@@ -1186,6 +1191,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "main",
state: "open",
+ updatedAt: "2026-03-10T07:00:00.000Z",
});
expect(ghCalls).toContain(
"pr list --head contributor:main --state all --limit 20 --json number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt,isCrossRepository,headRepository,headRepositoryOwner",
@@ -1294,6 +1300,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "effect-atom",
state: "open",
+ updatedAt: "2026-03-01T10:00:00.000Z",
});
expect(ghCalls.some((call) => call.includes("pr list --head upstream/effect-atom "))).toBe(
false,
@@ -1345,6 +1352,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-merged-pr",
state: "merged",
+ updatedAt: "2026-01-30T10:00:00.000Z",
});
}),
);
@@ -1461,6 +1469,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
baseRef: "main",
headRef: "feature/status-open-over-merged",
state: "open",
+ updatedAt: "2026-01-30T10:00:00.000Z",
});
}),
);
diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts
index 1020df217..c13505126 100644
--- a/apps/server/src/git/GitManager.ts
+++ b/apps/server/src/git/GitManager.ts
@@ -538,6 +538,7 @@ function toStatusPr(pr: PullRequestInfo): {
baseRef: string;
headRef: string;
state: "open" | "closed" | "merged";
+ updatedAt: string | null;
} {
return {
number: pr.number,
@@ -546,6 +547,10 @@ function toStatusPr(pr: PullRequestInfo): {
baseRef: pr.baseRefName,
headRef: pr.headRefName,
state: pr.state,
+ updatedAt: Option.match(pr.updatedAt, {
+ onNone: () => null,
+ onSome: (updatedAt) => DateTime.formatIso(updatedAt),
+ }),
};
}
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 64dd5ebfd..3ed1aa76b 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -4151,6 +4151,18 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
+ // Primitive slice of the displayed PR for the settle-rule memos below:
+ // resolveDisplayedThreadPr returns a fresh object every render, so memoize
+ // on the fields the rules read instead of the object identity.
+ const activeThreadPrState = activeThreadPr?.state ?? null;
+ const activeThreadPrUpdatedAt = activeThreadPr?.updatedAt ?? null;
+ const activeThreadChangeRequest = useMemo(
+ () =>
+ activeThreadPrState === null
+ ? null
+ : { state: activeThreadPrState, updatedAt: activeThreadPrUpdatedAt },
+ [activeThreadPrState, activeThreadPrUpdatedAt],
+ );
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
@@ -4186,7 +4198,14 @@ function ChatViewContent(props: ChatViewProps) {
);
const activeThreadWokeVisible = useMemo(() => {
if (activeThreadWokeAt === null) return false;
- if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false;
+ if (
+ changeRequestAutoSettles(activeThreadChangeRequest, {
+ autoSettleOnMerge,
+ thread: activeThreadShell,
+ })
+ ) {
+ return false;
+ }
const wokeAtMs = Date.parse(activeThreadWokeAt);
if (Number.isNaN(wokeAtMs)) return false;
// Having the thread open counts as a visit at completedAt (the effect
@@ -4206,7 +4225,8 @@ function ChatViewContent(props: ChatViewProps) {
}, [
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
- activeThreadPr?.state,
+ activeThreadChangeRequest,
+ activeThreadShell,
activeThreadWokeAt,
autoSettleOnMerge,
]);
@@ -4216,10 +4236,10 @@ function ChatViewContent(props: ChatViewProps) {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
- changeRequestState: activeThreadPr?.state ?? null,
+ changeRequest: activeThreadChangeRequest,
});
}, [
- activeThreadPr?.state,
+ activeThreadChangeRequest,
activeThreadShell,
autoSettleAfterDays,
autoSettleOnMerge,
@@ -6245,7 +6265,7 @@ function ChatViewContent(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
isServerThread={isServerThread}
- changeRequestState={activeThreadPr?.state ?? null}
+ changeRequest={activeThreadChangeRequest}
activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index d7285d749..31a73d133 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -801,7 +801,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
snapshot: changeRequestSnapshot,
retainTerminalOnBranchMismatch,
});
- const prState = pr?.state ?? null;
// Same semantics as the legacy sidebar (never-visited counts as read):
// switching sidebars must not light up every historical thread as unread.
@@ -819,7 +818,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
const isWoke =
wokeAtDate !== null &&
(lastVisitedDate === null || lastVisitedDate < wokeAtDate) &&
- !changeRequestAutoSettles(prState, props.autoSettleOnMerge);
+ !changeRequestAutoSettles(pr, {
+ autoSettleOnMerge: props.autoSettleOnMerge,
+ thread,
+ });
// In-flight rows (working, or waiting on approval/input) fade as a whole:
// there is nothing for the user to do yet, so prominence is reserved for
// rows that need a human — done (unread), read-but-unsettled, failed, and
@@ -2024,9 +2026,9 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const snapshot = changeRequestSnapshotByKey.get(threadKey);
- const changeRequestState =
+ const changeRequest =
snapshot != null && (thread.worktreePath === null || snapshot.branch === thread.branch)
- ? snapshot.pr.state
+ ? snapshot.pr
: null;
// Snooze outranks everything, including a pin: "hide until Tuesday"
// temporarily suspends "keep on top". The pin survives underneath —
@@ -2048,7 +2050,7 @@ export default function Sidebar() {
now,
autoSettleAfterDays,
autoSettleOnMerge,
- changeRequestState,
+ changeRequest,
})
) {
settled.push(thread);
diff --git a/apps/web/src/components/ThreadStatusIndicators.test.ts b/apps/web/src/components/ThreadStatusIndicators.test.ts
index f77959d9f..91a5829b9 100644
--- a/apps/web/src/components/ThreadStatusIndicators.test.ts
+++ b/apps/web/src/components/ThreadStatusIndicators.test.ts
@@ -426,7 +426,7 @@ describe("resolveDisplayedThreadPr + nextThreadChangeRequestSnapshot", () => {
effectiveSettled(shell, {
now: "2026-04-10T00:00:00.000Z",
autoSettleAfterDays: null,
- changeRequestState: displayed?.state ?? null,
+ changeRequest: displayed,
}),
).toBe(true);
});
diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx
index a6ea2e7fd..cfb726271 100644
--- a/apps/web/src/components/ThreadStatusIndicators.tsx
+++ b/apps/web/src/components/ThreadStatusIndicators.tsx
@@ -169,6 +169,7 @@ export function threadChangeRequestSnapshotsEqual(
left.pr.baseRef === right.pr.baseRef &&
left.pr.headRef === right.pr.headRef &&
left.pr.state === right.pr.state &&
+ (left.pr.updatedAt ?? null) === (right.pr.updatedAt ?? null) &&
sourceControlProvidersEqual(left.sourceControlProvider, right.sourceControlProvider)
);
}
diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx
index 08e0422dd..d032b16a1 100644
--- a/apps/web/src/components/chat/ChatHeader.tsx
+++ b/apps/web/src/components/chat/ChatHeader.tsx
@@ -10,7 +10,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
+import type { ChangeRequestSettleSource } from "@t3tools/client-runtime/state/thread-settled";
import { ChevronDownIcon } from "lucide-react";
import {
memo,
@@ -51,8 +51,8 @@ interface ChatHeaderProps {
activeThreadTitle: string;
/** Drafts have no server thread yet, so the title carries no action menu. */
isServerThread: boolean;
- /** PR state feeding the settled classification, resolved by ChatView. */
- changeRequestState: ChangeRequestStateLike | null;
+ /** PR feeding the settled classification, resolved by ChatView. */
+ changeRequest: ChangeRequestSettleSource | null;
activeProjectName: string | undefined;
activeProjectCwd: string | null;
activeProjectFaviconPath: string | null;
@@ -113,7 +113,7 @@ export const ChatHeader = memo(function ChatHeader({
draftId,
activeThreadTitle,
isServerThread,
- changeRequestState,
+ changeRequest,
activeProjectName,
activeProjectCwd,
activeProjectFaviconPath,
@@ -191,7 +191,7 @@ export const ChatHeader = memo(function ChatHeader({
const { openMenu } = useThreadActionMenu({
threadRef: isServerThread ? activeThreadRef : null,
projectCwd: activeProjectCwd,
- changeRequestState,
+ changeRequest,
onStartRename: startRename,
});
const titleButtonRef = useRef<HTMLButtonElement | null>(null);
diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts
index 4a25df47b..91f31e4df 100644
--- a/apps/web/src/hooks/useThreadActionMenu.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.ts
@@ -9,7 +9,7 @@ import {
canSnooze,
effectiveSettled,
effectiveSnoozed,
- type ChangeRequestStateLike,
+ type ChangeRequestSettleSource,
} from "@t3tools/client-runtime/state/thread-settled";
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { useCallback } from "react";
@@ -60,11 +60,11 @@ export function useThreadActionMenu(input: {
readonly threadRef: ScopedThreadRef | null;
/** Fallback for "Copy path" when the thread has no worktree. */
readonly projectCwd: string | null;
- /** PR state feeding auto-settle classification, as resolved by the caller. */
- readonly changeRequestState: ChangeRequestStateLike | null;
+ /** PR feeding auto-settle classification, as resolved by the caller. */
+ readonly changeRequest: ChangeRequestSettleSource | null;
readonly onStartRename: () => void;
}) {
- const { threadRef, projectCwd, changeRequestState, onStartRename } = input;
+ const { threadRef, projectCwd, changeRequest, onStartRename } = input;
const {
settleThread,
unsettleThread,
@@ -136,7 +136,7 @@ export function useThreadActionMenu(input: {
now: `${now.toISOString().slice(0, 16)}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
- changeRequestState,
+ changeRequest,
}),
isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
@@ -312,7 +312,7 @@ export function useThreadActionMenu(input: {
archiveThread,
autoSettleAfterDays,
autoSettleOnMerge,
- changeRequestState,
+ changeRequest,
confirmThreadArchive,
confirmThreadDelete,
copyBranchToClipboard,
diff --git a/packages/client-runtime/src/state/threadSettled.test.ts b/packages/client-runtime/src/state/threadSettled.test.ts
index 97f397da3..06a8bb32c 100644
--- a/packages/client-runtime/src/state/threadSettled.test.ts
+++ b/packages/client-runtime/src/state/threadSettled.test.ts
@@ -28,7 +28,97 @@ describe("changeRequestAutoSettles", () => {
["closed", false, true],
[null, false, false],
] as const)("state=%s autoSettleOnMerge=%s returns %s", (state, autoSettleOnMerge, expected) => {
- expect(changeRequestAutoSettles(state, autoSettleOnMerge)).toBe(expected);
+ expect(changeRequestAutoSettles(state === null ? null : { state }, { autoSettleOnMerge })).toBe(
+ expected,
+ );
+ });
+
+ const THREAD_CREATED_AT = "2026-04-01T00:00:00.000Z";
+ const idleThread = {
+ createdAt: THREAD_CREATED_AT,
+ latestUserMessageAt: null,
+ latestTurn: null,
+ };
+
+ it("ignores a terminal change request last touched before the thread existed", () => {
+ for (const state of ["merged", "closed"] as const) {
+ expect(
+ changeRequestAutoSettles(
+ { state, updatedAt: "2026-03-31T23:59:59.999Z" },
+ { thread: idleThread },
+ ),
+ ).toBe(false);
+ }
+ });
+
+ it("settles on a terminal change request touched at or after the thread's latest event", () => {
+ for (const updatedAt of [THREAD_CREATED_AT, "2026-04-02T00:00:00.000Z"]) {
+ expect(changeRequestAutoSettles({ state: "merged", updatedAt }, { thread: idleThread })).toBe(
+ true,
+ );
+ }
+ });
+
+ it("never re-settles a thread revived after the merge", () => {
+ // Settling on a merge happens once: a user message newer than the PR's
+ // last activity means the conversation outlived the PR.
+ const revived = {
+ createdAt: THREAD_CREATED_AT,
+ latestUserMessageAt: "2026-04-05T00:00:00.000Z",
+ latestTurn: null,
+ };
+ expect(
+ changeRequestAutoSettles(
+ { state: "merged", updatedAt: "2026-04-03T00:00:00.000Z" },
+ { thread: revived },
+ ),
+ ).toBe(false);
+ // A merge landing after the revival still settles.
+ expect(
+ changeRequestAutoSettles(
+ { state: "merged", updatedAt: "2026-04-06T00:00:00.000Z" },
+ { thread: revived },
+ ),
+ ).toBe(true);
+ });
+
+ it("still settles when the merge lands during an in-flight turn", () => {
+ // Anchor is user-initiated activity only: the agent finishing a turn
+ // after the merge must not block the settle the merge earned.
+ const midTurnMerge = {
+ createdAt: THREAD_CREATED_AT,
+ latestUserMessageAt: "2026-04-02T00:00:00.000Z",
+ latestTurn: {
+ turnId: TurnId.make("turn-mid"),
+ state: "completed" as const,
+ requestedAt: "2026-04-02T00:00:00.000Z",
+ startedAt: "2026-04-02T00:00:05.000Z",
+ completedAt: "2026-04-02T00:20:00.000Z",
+ assistantMessageId: null,
+ },
+ };
+ expect(
+ changeRequestAutoSettles(
+ { state: "merged", updatedAt: "2026-04-02T00:10:00.000Z" },
+ { thread: midTurnMerge },
+ ),
+ ).toBe(true);
+ });
+
+ it("falls back to settling when either timestamp is missing or malformed", () => {
+ expect(changeRequestAutoSettles({ state: "merged" }, { thread: idleThread })).toBe(true);
+ expect(
+ changeRequestAutoSettles({ state: "merged", updatedAt: null }, { thread: idleThread }),
+ ).toBe(true);
+ expect(
+ changeRequestAutoSettles({ state: "merged", updatedAt: "2026-03-01T00:00:00.000Z" }, {}),
+ ).toBe(true);
+ expect(
+ changeRequestAutoSettles(
+ { state: "merged", updatedAt: "not-a-date" },
+ { thread: idleThread },
+ ),
+ ).toBe(true);
});
});
@@ -155,7 +245,7 @@ describe("effectiveSettled", () => {
const changeRequestOptions =
changeRequestState === undefined
? {}
- : { changeRequestState: changeRequestState as ChangeRequestStateLike };
+ : { changeRequest: { state: changeRequestState as ChangeRequestStateLike } };
expect(
effectiveSettled(shell, {
@@ -173,7 +263,7 @@ describe("effectiveSettled", () => {
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: null,
- changeRequestState: "closed",
+ changeRequest: { state: "closed" },
}),
).toBe(true);
});
@@ -185,12 +275,36 @@ describe("effectiveSettled", () => {
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
- changeRequestState,
+ changeRequest: { state: changeRequestState },
}),
).toBe(true);
}
});
+ it("ignores a change request that merged before the thread's latest event", () => {
+ // A new thread started at a worktree root inherits the branch's old
+ // merged PR, and a revived thread outlives its merge; neither settles
+ // the live conversation.
+ const fresh = makeShell({ activityAt: FRESH });
+ for (const state of ["merged", "closed"] as const) {
+ expect(
+ effectiveSettled(fresh, {
+ now: NOW,
+ autoSettleAfterDays: null,
+ changeRequest: { state, updatedAt: "2026-03-20T00:00:00.000Z" },
+ }),
+ ).toBe(false);
+ }
+ // A merge during the thread's life still settles it.
+ expect(
+ effectiveSettled(fresh, {
+ now: NOW,
+ autoSettleAfterDays: null,
+ changeRequest: { state: "merged", updatedAt: "2026-04-09T00:00:00.000Z" },
+ }),
+ ).toBe(true);
+ });
+
it("can keep a merged change request active", () => {
const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
expect(
@@ -198,7 +312,7 @@ describe("effectiveSettled", () => {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
- changeRequestState: "merged",
+ changeRequest: { state: "merged" },
}),
).toBe(false);
@@ -207,7 +321,7 @@ describe("effectiveSettled", () => {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
- changeRequestState: "closed",
+ changeRequest: { state: "closed" },
}),
).toBe(true);
});
@@ -218,7 +332,7 @@ describe("effectiveSettled", () => {
effectiveSettled(stale, {
now: NOW,
autoSettleAfterDays: 3,
- changeRequestState: "open",
+ changeRequest: { state: "open" },
}),
).toBe(false);
// An explicit user settle still wins: open PR only blocks the auto path.
@@ -227,7 +341,7 @@ describe("effectiveSettled", () => {
effectiveSettled(settled, {
now: NOW,
autoSettleAfterDays: 3,
- changeRequestState: "open",
+ changeRequest: { state: "open" },
}),
).toBe(true);
});
@@ -241,7 +355,7 @@ describe("effectiveSettled", () => {
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: null,
- changeRequestState: "merged",
+ changeRequest: { state: "merged" },
}),
).toBe(false);
});
@@ -256,7 +370,7 @@ describe("effectiveSettled", () => {
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: 3,
- changeRequestState: "merged",
+ changeRequest: { state: "merged" },
}),
).toBe(false);
});
@@ -300,7 +414,7 @@ describe("effectiveSettled", () => {
effectiveSettled(shell, {
now: transitionNow,
autoSettleAfterDays: 3,
- changeRequestState: "merged",
+ changeRequest: { state: "merged" },
}),
).toBe(false);
}
@@ -418,7 +532,7 @@ describe("canSettle", () => {
effectiveSettled(queued, {
now: justAfter,
autoSettleAfterDays: 3,
- changeRequestState: "merged",
+ changeRequest: { state: "merged" },
}),
).toBe(false);
// Past the window the message is a failed/stale start: settleable again.
diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts
index e2e93f288..8ccf0d230 100644
--- a/packages/client-runtime/src/state/threadSettled.ts
+++ b/packages/client-runtime/src/state/threadSettled.ts
@@ -3,17 +3,77 @@ import type { OrchestrationThreadShell } from "@t3tools/contracts";
export type ChangeRequestStateLike = "open" | "closed" | "merged";
-/** Returns whether the change request state settles the thread immediately. */
+/**
+ * The slice of a change request the settle rules need. `updatedAt` is the
+ * provider's last-activity timestamp; for a merged/closed request it bounds
+ * when the terminal state landed.
+ */
+export interface ChangeRequestSettleSource {
+ readonly state: ChangeRequestStateLike;
+ readonly updatedAt?: string | null | undefined;
+}
+
+/** What the settle rules need to know about the thread's own timeline. */
+export type ThreadActivitySource = Pick<
+ OrchestrationThreadShell,
+ "createdAt" | "latestUserMessageAt" | "latestTurn"
+>;
+
+/**
+ * Latest USER-initiated activity: messages and the turn requests they start,
+ * deliberately not the agent-side started/completed stamps. The settle-on-
+ * merge anchor uses this so a merge landing mid-turn still settles the
+ * thread when that turn finishes, while a user re-engaging after the merge
+ * blocks it for good. Falls back to creation time for untouched threads.
+ */
+function threadUserActivityAnchorAt(thread: ThreadActivitySource): string {
+ const messageAt = thread.latestUserMessageAt;
+ const requestedAt = thread.latestTurn?.requestedAt;
+ let anchor = thread.createdAt;
+ for (const candidate of [messageAt, requestedAt]) {
+ if (candidate != null && Date.parse(candidate) > Date.parse(anchor)) {
+ anchor = candidate;
+ }
+ }
+ return anchor;
+}
+
+/**
+ * Returns whether the change request settles the thread immediately. A
+ * terminal request settles the thread only while it postdates every user-
+ * initiated event in it: settling on a merge happens ONCE. A request last
+ * touched before the thread was created is inherited branch history (a new
+ * thread started at a worktree root whose PR already merged), and one older
+ * than the user's latest engagement was already adjudicated — re-engaging a
+ * thread whose PR merged is the user saying the conversation outlived the
+ * PR. Unknown timestamps keep the old always-settle behavior.
+ */
export function changeRequestAutoSettles(
- state: ChangeRequestStateLike | null | undefined,
- autoSettleOnMerge = true,
+ changeRequest: ChangeRequestSettleSource | null | undefined,
+ options: {
+ readonly autoSettleOnMerge?: boolean | undefined;
+ readonly thread?: ThreadActivitySource | null | undefined;
+ } = {},
): boolean {
- return state === "closed" || (state === "merged" && autoSettleOnMerge);
+ if (changeRequest == null) return false;
+ const terminal =
+ changeRequest.state === "closed" ||
+ (changeRequest.state === "merged" && options.autoSettleOnMerge !== false);
+ if (!terminal) return false;
+ if (changeRequest.updatedAt == null || options.thread == null) return true;
+ const updatedAtMs = Date.parse(changeRequest.updatedAt);
+ const anchorAtMs = Date.parse(threadUserActivityAnchorAt(options.thread));
+ // Malformed timestamps fall back to settling, matching servers that never
+ // report updatedAt.
+ if (Number.isNaN(updatedAtMs) || Number.isNaN(anchorAtMs)) return true;
+ return updatedAtMs >= anchorAtMs;
}
const DAY_MS = 24 * 60 * 60 * 1_000;
-export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
+export function threadLastActivityAt(
+ shell: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn">,
+): string | null {
const candidates = [
shell.latestUserMessageAt,
shell.latestTurn?.requestedAt,
@@ -230,8 +290,10 @@ export function threadWokeAt(
* override. Past the blockers, the explicit user override (thread.settle /
* thread.unsettle commands, projected into settledOverride + settledAt)
* wins in both directions; without one, a thread can auto-settle on a
- * merged PR, always settles on a closed PR, or settles on inactivity past
- * the window. An open PR blocks the inactivity path entirely. The server
+ * merged PR or always on a closed PR (both only while the terminal state is
+ * the thread's latest event, see changeRequestAutoSettles), or settles on
+ * inactivity past the window.
+ * An open PR blocks the inactivity path entirely. The server
* un-settles on real activity (user message, session start, approval/
* user-input request), so an override never goes stale silently.
*/
@@ -241,7 +303,7 @@ export function effectiveSettled(
readonly now: string;
readonly autoSettleAfterDays: number | null;
readonly autoSettleOnMerge?: boolean;
- readonly changeRequestState?: ChangeRequestStateLike | null;
+ readonly changeRequest?: ChangeRequestSettleSource | null;
},
): boolean {
// Blocked work must remain visible even when a user explicitly settled it.
@@ -267,14 +329,19 @@ export function effectiveSettled(
// "active" is the explicit keep-active pin: it suppresses auto-settle
// until real activity clears it server-side.
if (shell.settledOverride === "active") return false;
- if (changeRequestAutoSettles(options.changeRequestState, options.autoSettleOnMerge !== false)) {
+ if (
+ changeRequestAutoSettles(options.changeRequest, {
+ autoSettleOnMerge: options.autoSettleOnMerge,
+ thread: shell,
+ })
+ ) {
return true;
}
// An open PR is unfinished business regardless of how long the thread has
// been quiet: review can take days, and hiding the thread would bury the
// work waiting on it. A configured merge, a close, or an explicit user
// settle resolves it.
- if (options.changeRequestState === "open") return false;
+ if (options.changeRequest?.state === "open") return false;
if (options.autoSettleAfterDays === null) return false;
const lastActivityAt = threadLastActivityAt(shell);
diff --git a/packages/contracts/src/git.ts b/packages/contracts/src/git.ts
index bdbf8f88d..915c3627c 100644
--- a/packages/contracts/src/git.ts
+++ b/packages/contracts/src/git.ts
@@ -197,6 +197,14 @@ const VcsStatusChangeRequest = Schema.Struct({
baseRef: TrimmedNonEmptyStringSchema,
headRef: TrimmedNonEmptyStringSchema,
state: VcsStatusChangeRequestState,
+ /**
+ * Last provider-side activity (ISO). For a merged/closed change request
+ * this bounds when it reached that state, so clients can tell a PR that
+ * terminated during a thread's life from one that was already history
+ * when the thread was created. Optional for old servers and providers
+ * whose lookups do not report it.
+ */
+ updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
});
const VcsStatusLocalShape = {