Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 8b8bec71c5 refactor(orchestration): derive thread settled state on the server
Settled classification used to be re-derived per client (inactivity window,
PR state, clock hacks), with real drift between web and mobile. The server
is now the single author of settled state: a ThreadAutoSettleReactor sweep
dispatches thread.settle for quiet threads and merged/closed PRs, the
auto-settle window moved to ServerSettings, and clients just read
settledOverride.

Includes the review-hardening rounds: settledAt derived in the decider from
read-model activity (unforgeable, restart-safe via a projected
latestUserMessageAt stamp, revert-consistent, clock-skew clamped), only
live-confirmed PR states act as settle authority (cached open/closed/no-PR
re-verify with cooldown), fail-safe settings reads, and capability-gated
settings UI with blur-committed input.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-14 18:06:26 -07:00
46 changed files with 1611 additions and 824 deletions

No files matched your search

@@ -31,8 +31,6 @@ const clientSettings: ClientSettings = {
glassOpacity: 80, glassOpacity: 80,
planModeEnabled: false, planModeEnabled: false,
providerModelPreferences: {}, providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path", sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: { sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate", "environment-1:/tmp/project-a": "separate",
+9 -40
View File
@@ -207,9 +207,6 @@ export function HomeScreen(props: HomeScreenProps) {
>(() => new Map()); >(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom); const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled(); const threadListV2Enabled = useThreadListV2Enabled();
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const savePreferences = useAtomSet(updateMobilePreferencesAtom); const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null); const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null); const listRef = useRef<LegendListRef | null>(null);
@@ -486,26 +483,6 @@ export function HomeScreen(props: HomeScreenProps) {
// Settled threads stay in the live shell stream (settled ≠ archived), so // Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or // the partition works directly off live shells — no snapshot merging or
// optimistic holds. // 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">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
const handleSettleThread = useCallback( const handleSettleThread = useCallback(
(thread: EnvironmentThreadShell) => { (thread: EnvironmentThreadShell) => {
void props.onSettleThread(thread); void props.onSettleThread(thread);
@@ -569,9 +546,8 @@ export function HomeScreen(props: HomeScreenProps) {
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []); const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true); const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []); const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now is quantized to the minute and ticks so the inactivity auto-settle // Minute clock for snooze preset/wake labels only — settled state is
// boundary is actually crossed while the app stays open (mirrors web); // server-authored, so the partition itself no longer needs a ticking "now".
// without a clock dependency the partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the // Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken // next wake boundary re-runs the partition with a fresh clock so a woken
@@ -580,14 +556,13 @@ export function HomeScreen(props: HomeScreenProps) {
useEffect(() => { useEffect(() => {
if (!threadListV2Enabled) return; if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old // Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the // by the time the beta is switched on.
// inactivity auto-settle boundary until the first tick.
setNowMinute(new Date().toISOString().slice(0, 16)); setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000); const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id); return () => clearInterval(id);
}, [threadListV2Enabled]); }, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as // Servers without the settlement capability reject the settle/unsettle
// settled (the user could neither un-settle nor pin them). // commands, so their rows hide the actions.
const serverConfigs = useAtomValue(environmentServerConfigsAtom); const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => { const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>(); const supported = new Set<EnvironmentId>();
@@ -667,21 +642,14 @@ export function HomeScreen(props: HomeScreenProps) {
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs, projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery, searchQuery: props.searchQuery,
matchedThreadKeys, matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds, snoozeEnvironmentIds,
settledLimit: settledVisibleCount, settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(), snoozeNow: new Date().toISOString(),
snoozedShelfExpanded, snoozedShelfExpanded,
settledShelfExpanded, settledShelfExpanded,
selectedThreadKey: null, selectedThreadKey: null,
}); });
}, [ }, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick, snoozeWakeTick,
snoozedShelfExpanded, snoozedShelfExpanded,
settledShelfExpanded, settledShelfExpanded,
@@ -742,7 +710,10 @@ export function HomeScreen(props: HomeScreenProps) {
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex, settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
snoozeLabelNow: `${nowMinute}:00.000Z`, snoozeLabelNow: `${nowMinute}:00.000Z`,
}), }),
[settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks], // nowMinute keeps the snoozed rows' wake countdown ticking: the settled
// partition no longer depends on a clock, so nothing else re-runs this
// memo each minute.
[nowMinute, settledShelfExpanded, snoozedShelfExpanded, threadListV2Layout, v2PendingTasks],
); );
const renderV2Item = useCallback( const renderV2Item = useCallback(
@@ -850,7 +821,6 @@ export function HomeScreen(props: HomeScreenProps) {
onPinThread={handlePinThread} onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread} onUnpinThread={handleUnpinThread}
onMovePinnedThread={handleMovePinnedThread} onMovePinnedThread={handleMovePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={ projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
} }
@@ -860,7 +830,6 @@ export function HomeScreen(props: HomeScreenProps) {
); );
}, },
[ [
handleChangeRequestState,
handleDeleteThread, handleDeleteThread,
arrangedPinnedKeys, arrangedPinnedKeys,
handleMovePinnedThread, handleMovePinnedThread,
@@ -522,21 +522,12 @@ function ConfiguredSettingsRouteScreen() {
} }
function GeneralSettingsSection() { function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom); // Settle policy (inactivity window, settle-on-merge) is server-authored;
const savePreferences = useAtomSet(updateMobilePreferencesAtom); // mobile reads settledOverride and offers no local knobs. Configure it
const autoSettleOnMerge = // from the web/desktop settings until mobile grows server-settings UI.
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
return ( return (
<SettingsSection title="General"> <SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" /> <SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
<SettingsSwitchRow
icon="arrow.triangle.branch"
label="Auto-settle merged threads"
value={autoSettleOnMerge}
onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}
/>
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" /> <SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
</SettingsSection> </SettingsSection>
); );
@@ -217,9 +217,6 @@ function ThreadNavigationSidebarPane(
} = useThreadListActions(); } = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled(); const threadListV2Enabled = useThreadListV2Enabled();
const preferencesResult = useAtomValue(mobilePreferencesAtom); const preferencesResult = useAtomValue(mobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const pendingTasks = usePendingNewTasks(); const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions(); const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo( const environments = useMemo(
@@ -417,26 +414,6 @@ function ThreadNavigationSidebarPane(
// Thread List v2 (beta) support — same model as the compact Home list // Thread List v2 (beta) support — same model as the compact Home list
// (HomeScreen.tsx): flat creation-order card block + settled recency tail. // (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">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
// The settled tail renders in pages; expansion resets when the filter // The settled tail renders in pages; expansion resets when the filter
// context changes so environment/search flips never inherit a deep page. // context changes so environment/search flips never inherit a deep page.
const [settledVisibleCount, setSettledVisibleCount] = useState( const [settledVisibleCount, setSettledVisibleCount] = useState(
@@ -456,9 +433,8 @@ function ThreadNavigationSidebarPane(
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []); const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true); const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []); const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now ticks per minute so the inactivity auto-settle boundary is actually // Minute clock for snooze preset/wake labels only — settled state is
// crossed while the pane stays open; without a clock dependency the // server-authored, so the partition itself no longer needs a ticking "now".
// partition memoizes a frozen "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16)); const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// Snooze wake times are second-precise; a counter bumped exactly at the // Snooze wake times are second-precise; a counter bumped exactly at the
// next wake boundary re-runs the partition with a fresh clock so a woken // next wake boundary re-runs the partition with a fresh clock so a woken
@@ -467,14 +443,13 @@ function ThreadNavigationSidebarPane(
useEffect(() => { useEffect(() => {
if (!threadListV2Enabled) return; if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old // Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the // by the time the beta is switched on.
// inactivity auto-settle boundary until the first tick.
setNowMinute(new Date().toISOString().slice(0, 16)); setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000); const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id); return () => clearInterval(id);
}, [threadListV2Enabled]); }, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as // Servers without the settlement capability reject the settle/unsettle
// settled (the user could neither un-settle nor pin them). // commands, so their rows hide the actions.
const serverConfigs = useAtomValue(environmentServerConfigsAtom); const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => { const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>(); const supported = new Set<EnvironmentId>();
@@ -551,21 +526,14 @@ function ThreadNavigationSidebarPane(
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs, projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery, searchQuery: props.searchQuery,
matchedThreadKeys, matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds, snoozeEnvironmentIds,
settledLimit: settledVisibleCount, settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(), snoozeNow: new Date().toISOString(),
snoozedShelfExpanded, snoozedShelfExpanded,
settledShelfExpanded, settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null, selectedThreadKey: props.selectedThreadKey ?? null,
}); });
}, [ }, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick, snoozeWakeTick,
snoozedShelfExpanded, snoozedShelfExpanded,
settledShelfExpanded, settledShelfExpanded,
@@ -988,7 +956,6 @@ function ThreadNavigationSidebarPane(
onPinThread={pinThread} onPinThread={pinThread}
onUnpinThread={unpinThread} onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread} onMovePinnedThread={movePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null} projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose} onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen} onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1113,7 +1080,6 @@ function ThreadNavigationSidebarPane(
arrangedPinnedKeys, arrangedPinnedKeys,
confirmDeletePendingTask, confirmDeletePendingTask,
confirmDeleteThread, confirmDeleteThread,
handleChangeRequestState,
handleSelectThread, handleSelectThread,
handleSwipeableClose, handleSwipeableClose,
handleSwipeableWillOpen, handleSwipeableWillOpen,
@@ -369,12 +369,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly canMovePinnedDown?: boolean; readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void; readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (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. */
readonly onChangeRequestState?: (
threadKey: string,
state: "open" | "closed" | "merged" | null,
) => void;
readonly projectCwd?: string | null; readonly projectCwd?: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch; readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string; readonly searchQuery?: string;
@@ -397,17 +391,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPinThread, onPinThread,
onUnpinThread, onUnpinThread,
onMovePinnedThread, onMovePinnedThread,
onChangeRequestState,
} = props; } = props;
const snoozedRow = props.snoozed === true; const snoozedRow = props.snoozed === true;
const pinnedRow = props.pinned === true; const pinnedRow = props.pinned === true;
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null); const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
const prState = pr?.state ?? null;
const threadKey = `${thread.environmentId}:${thread.id}`;
useEffect(() => {
onChangeRequestState?.(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
const screenColor = useThemeColor("--color-screen"); const screenColor = useThemeColor("--color-screen");
const drawerColor = useThemeColor("--color-drawer"); const drawerColor = useThemeColor("--color-drawer");
@@ -8,7 +8,6 @@ import {
ProjectId, ProjectId,
ProviderInstanceId, ProviderInstanceId,
ThreadId, ThreadId,
TurnId,
} from "@t3tools/contracts"; } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test"; import { describe, expect, it } from "vite-plus/test";
@@ -263,21 +262,8 @@ describe("sortThreadsForListV2", () => {
}); });
describe("buildThreadListV2Items", () => { describe("buildThreadListV2Items", () => {
it("keeps a merged thread active when auto-settle on merge is off", () => { // The merge rule (threadAutoSettleOnMerge) is applied by the SERVER sweep,
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" }); // not the client partition — see apps/server autoSettle.test.ts.
const layout = buildThreadListV2Items({
threads: [merged],
environmentId: null,
searchQuery: "",
changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
autoSettleOnMerge: false,
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["merged"]);
expect(layout.settledCount).toBe(0);
});
it("hides snoozed threads and counts them — visibility parity with web", () => { it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({ const layout = buildThreadListV2Items({
threads: [ threads: [
@@ -298,7 +284,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
// Same createdAt → static sort tiebreaks by id; the point is the woken // Same createdAt → static sort tiebreaks by id; the point is the woken
@@ -322,7 +308,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]); expect(layout.items.map((item) => item.thread.id)).toEqual(["pinned-settled", "active"]);
@@ -347,18 +333,21 @@ describe("buildThreadListV2Items", () => {
}; };
// Before the wake time: the snooze wins; the pin holds underneath. // Before the wake time: the snooze wins; the pin holds underneath.
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW }); const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, snoozeNow: NOW });
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]); expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(whileSnoozed.snoozedCount).toBe(1); expect(whileSnoozed.snoozedCount).toBe(1);
// After the wake time: the thread returns pinned, back on top. // After the wake time: the thread returns pinned, back on top.
const afterWake = buildThreadListV2Items({ ...snoozedInput, now: "2026-06-03T10:00:00.000Z" }); const afterWake = buildThreadListV2Items({
...snoozedInput,
snoozeNow: "2026-06-03T10:00:00.000Z",
});
expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]); expect(afterWake.items.map((item) => item.thread.id)).toEqual(["pinned-snoozed", "active"]);
expect(afterWake.items[0]?.pinned).toBe(true); expect(afterWake.items[0]?.pinned).toBe(true);
expect(afterWake.snoozedCount).toBe(0); expect(afterWake.snoozedCount).toBe(0);
}); });
it("classifies snooze with the second-precise clock and reports the next wake", () => { it("classifies snooze with a second-precise clock and reports the next wake", () => {
const layout = buildThreadListV2Items({ const layout = buildThreadListV2Items({
threads: [ threads: [
makeThread({ makeThread({
@@ -378,8 +367,6 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
// Minute-floored partition clock vs precise snooze clock.
now: "2026-06-02T00:01:00.000Z",
snoozeNow: "2026-06-02T00:01:07.500Z", snoozeNow: "2026-06-02T00:01:07.500Z",
}); });
@@ -413,7 +400,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
snoozedShelfExpanded: true, snoozedShelfExpanded: true,
}); });
@@ -440,7 +427,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(layout.items).toEqual([]); expect(layout.items).toEqual([]);
@@ -466,7 +453,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
selectedThreadKey: `${environmentId}:open`, selectedThreadKey: `${environmentId}:open`,
}); });
@@ -488,7 +475,7 @@ describe("buildThreadListV2Items", () => {
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
snoozeEnvironmentIds: new Set(), snoozeEnvironmentIds: new Set(),
now: NOW, snoozeNow: NOW,
}); });
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]); expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
@@ -514,7 +501,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([ expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
@@ -540,7 +527,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
settledShelfExpanded: false, settledShelfExpanded: false,
}); });
@@ -567,7 +554,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
settledShelfExpanded: false, settledShelfExpanded: false,
selectedThreadKey: `${environmentId}:selected`, selectedThreadKey: `${environmentId}:selected`,
}); });
@@ -594,7 +581,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]); expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
@@ -614,7 +601,7 @@ describe("buildThreadListV2Items", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "login", searchQuery: "login",
now: NOW, snoozeNow: NOW,
}); });
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([ expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
@@ -638,7 +625,7 @@ describe("buildThreadListV2Items", () => {
threadId: thread.id, threadId: thread.id,
}), }),
]), ]),
now: NOW, snoozeNow: NOW,
}); });
expect(items.map((item) => item.thread.id)).toEqual(["content-match"]); expect(items.map((item) => item.thread.id)).toEqual(["content-match"]);
@@ -658,7 +645,7 @@ describe("buildThreadListV2Items", () => {
environmentId: null, environmentId: null,
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }], projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(items.map((item) => item.thread.id)).toEqual(["included"]); expect(items.map((item) => item.thread.id)).toEqual(["included"]);
@@ -681,7 +668,7 @@ describe("buildThreadListV2Items", () => {
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") }, { environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
], ],
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]); expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
@@ -697,18 +684,9 @@ describe("buildThreadListV2Items settled paging", () => {
id: ThreadId.make(`settled-${index}`), id: ThreadId.make(`settled-${index}`),
title: `Settled ${index}`, title: `Settled ${index}`,
settledOverride: "settled", settledOverride: "settled",
settledAt: NOW, // Auto-settles backdate settledAt to the last activity, so the
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`, // shelf orders by when the work ended.
// A turn adopted the message (same requestedAt): without it the settledAt: `2026-06-01T0${index}:10:00.000Z`,
// thread reads as a queued turn start, which never settles.
latestTurn: {
turnId: TurnId.make(`turn-${index}`),
state: "completed",
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
startedAt: `2026-06-01T0${index}:00:00.000Z`,
completedAt: `2026-06-01T0${index}:10:00.000Z`,
assistantMessageId: null,
},
}), }),
), ),
]; ];
@@ -718,7 +696,7 @@ describe("buildThreadListV2Items settled paging", () => {
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
settledLimit: 2, settledLimit: 2,
now: NOW, snoozeNow: NOW,
}); });
expect(layout.hiddenSettledCount).toBe(2); expect(layout.hiddenSettledCount).toBe(2);
@@ -772,7 +750,7 @@ describe("buildThreadListV2ListItems", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
it("splices queued tasks between the active block and the settled tail", () => { it("splices queued tasks between the active block and the settled tail", () => {
@@ -805,7 +783,7 @@ describe("buildThreadListV2ListItems", () => {
threads: [makeThread({ id: ThreadId.make("active"), title: "active" })], threads: [makeThread({ id: ThreadId.make("active"), title: "active" })],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
const items = buildThreadListV2ListItems({ const items = buildThreadListV2ListItems({
items: activeOnly.items, items: activeOnly.items,
@@ -849,7 +827,7 @@ describe("buildThreadListV2ListItems", () => {
], ],
environmentId: null, environmentId: null,
searchQuery: "", searchQuery: "",
now: NOW, snoozeNow: NOW,
}); });
const items = buildThreadListV2ListItems({ const items = buildThreadListV2ListItems({
items: snoozedLayout.items, items: snoozedLayout.items,
@@ -306,8 +306,9 @@ export function buildThreadListV2ListItems(input: {
/** /**
* Partitions visible threads into the active card block (creation order) and * Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. Mobile stores these * the settled recency tail, matching the web v2 list. Settled is
* auto-settle preferences per device. * server-authored (settledOverride), so the partition needs no clock, no
* auto-settle window, and no PR state.
*/ */
export function buildThreadListV2Items(input: { export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>; readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -318,25 +319,13 @@ export function buildThreadListV2Items(input: {
}> | null; }> | null;
readonly searchQuery: string; readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>; readonly matchedThreadKeys?: ReadonlySet<string>;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */ /** Environments whose server supports thread.snooze/unsnooze. Threads on
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">; other environments never classify as snoozed. Absent = no gating
/** Environments whose server supports thread.settle/unsettle. Threads on (tests). */
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
/** Environments whose server supports thread.snooze/unsnooze. Same
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>; readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
readonly autoSettleOnMerge?: boolean;
/** Max settled rows to render; the rest are counted, not built. */ /** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number; readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */ /** Second-precise clock for snooze classification; injectable for tests. */
readonly now?: string;
/** Second-precise clock for snooze classification. Callers pass a
minute-quantized `now` for memoization; snooze wake times are
second-precise, so classifying with the floored minute would hold a
woken thread hidden for up to a minute. Defaults to `now`. */
readonly snoozeNow?: string; readonly snoozeNow?: string;
/** Expands the snoozed shelf into rows. Collapsed is the default. */ /** Expands the snoozed shelf into rows. Collapsed is the default. */
readonly snoozedShelfExpanded?: boolean; readonly snoozedShelfExpanded?: boolean;
@@ -346,10 +335,7 @@ export function buildThreadListV2Items(input: {
a split-view detail can never lose its navigation row. */ a split-view detail can never lose its navigation row. */
readonly selectedThreadKey?: string | null; readonly selectedThreadKey?: string | null;
}): ThreadListV2Layout { }): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString(); const snoozeNow = input.snoozeNow ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
const query = input.searchQuery.trim().toLocaleLowerCase(); const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`)) ? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
@@ -379,10 +365,7 @@ export function buildThreadListV2Items(input: {
) { ) {
continue; continue;
} }
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true; const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a // Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its // pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin (and its pinOrderKey) survives underneath, so a woken // hand). The pin (and its pinOrderKey) survives underneath, so a woken
@@ -399,20 +382,14 @@ export function buildThreadListV2Items(input: {
continue; continue;
} }
// A pin otherwise overrides the lifecycle: pinned threads render above // A pin otherwise overrides the lifecycle: pinned threads render above
// the inbox and never auto-settle out of sight. // the inbox and never settle out of sight.
if (thread.pinnedAt != null) { if (thread.pinnedAt != null) {
pinned.push(thread); pinned.push(thread);
continue; continue;
} }
if ( // Settled is server-authored (settledOverride); servers that predate
supportsSettlement && // settlement never emit it, so their threads simply stay active.
effectiveSettled(thread, { if (effectiveSettled(thread)) {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread); settled.push(thread);
} else { } else {
active.push(thread); active.push(thread);
@@ -431,10 +408,13 @@ export function buildThreadListV2Items(input: {
: orderedSnoozed.filter( : orderedSnoozed.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey, (thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
); );
// Settled rows order by when the work ended: the server stamps settledAt
// on every settle (auto-settles backdate it to the last activity). Same
// key as the web sidebar so both platforms render the same shelf order.
const orderedSettled = [...settled].sort( const orderedSettled = [...settled].sort(
(left, right) => (left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) - firstValidTimestampMs(right.settledAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt), firstValidTimestampMs(left.settledAt, left.updatedAt),
); );
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY; const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const pagedSettled = const pagedSettled =
@@ -26,7 +26,6 @@ export interface Preferences {
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */ /** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean; readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode; readonly projectGroupingMode?: SidebarProjectGroupingMode;
readonly autoSettleOnMerge?: boolean;
/** /**
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has * Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into * no client-settings sync, so the legacy grouped thread list is opted into
@@ -88,7 +87,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[]; collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean; projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode; projectGroupingMode?: SidebarProjectGroupingMode;
autoSettleOnMerge?: boolean;
legacyThreadListEnabled?: boolean; legacyThreadListEnabled?: boolean;
planModeEnabled?: boolean; planModeEnabled?: boolean;
} = {}; } = {};
@@ -127,9 +125,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) { ) {
preferences.projectGroupingMode = parsed.projectGroupingMode; preferences.projectGroupingMode = parsed.projectGroupingMode;
} }
if (typeof parsed.autoSettleOnMerge === "boolean") {
preferences.autoSettleOnMerge = parsed.autoSettleOnMerge;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") { if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled; preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
} }
@@ -62,6 +62,7 @@ import {
OrchestrationEngineService, OrchestrationEngineService,
type OrchestrationEngineShape, type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts"; } from "../src/orchestration/Services/OrchestrationEngine.ts";
import { ThreadAutoSettleReactor } from "../src/orchestration/ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts"; import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts"; import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts"; import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -342,6 +343,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge( Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, { Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"), getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: () => refreshLocalStatus: () =>
Effect.succeed({ Effect.succeed({
isRepo: true, isRepo: true,
@@ -369,6 +371,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeIngestionLayer), Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer), Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer), Layer.provideMerge(checkpointReactorLayer),
Layer.provideMerge(
Layer.succeed(ThreadAutoSettleReactor, {
start: () => Effect.void,
sweepOnce: Effect.void,
}),
),
Layer.provideMerge( Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, { Layer.succeed(ThreadDeletionReactor, {
start: () => Effect.void, start: () => Effect.void,
@@ -148,6 +148,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true, connectionProbe: true,
pullRequests: true, pullRequests: true,
threadSettlement: true, threadSettlement: true,
threadAutoSettle: true,
threadSnooze: true, threadSnooze: true,
threadPinning: true, threadPinning: true,
threadPinReorder: true, threadPinReorder: true,
@@ -316,6 +316,7 @@ describe("CheckpointReactor", () => {
}); });
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, { const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"), getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: (cwd: string) => refreshLocalStatus: (cwd: string) =>
Effect.sync(() => { Effect.sync(() => {
options?.gitStatusRefreshCalls?.push(cwd); options?.gitStatusRefreshCalls?.push(cwd);
@@ -8,6 +8,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadAutoSettleReactor } from "../ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts"; import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts"; import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -55,6 +56,15 @@ describe("OrchestrationReactor", () => {
drain: Effect.void, drain: Effect.void,
}), }),
), ),
Layer.provideMerge(
Layer.succeed(ThreadAutoSettleReactor, {
start: () => {
started.push("thread-auto-settle-reactor");
return Effect.void;
},
sweepOnce: Effect.void,
}),
),
Layer.provideMerge( Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, { Layer.succeed(ThreadDeletionReactor, {
start: () => { start: () => {
@@ -84,6 +94,7 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion", "provider-runtime-ingestion",
"provider-command-reactor", "provider-command-reactor",
"checkpoint-reactor", "checkpoint-reactor",
"thread-auto-settle-reactor",
"thread-deletion-reactor", "thread-deletion-reactor",
"agent-awareness-relay", "agent-awareness-relay",
]); ]);
@@ -8,6 +8,7 @@ import {
import { CheckpointReactor } from "../Services/CheckpointReactor.ts"; import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts"; import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts"; import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadAutoSettleReactor } from "../ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts"; import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts"; import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
@@ -15,6 +16,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService; const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor; const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor; const checkpointReactor = yield* CheckpointReactor;
const threadAutoSettleReactor = yield* ThreadAutoSettleReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor; const threadDeletionReactor = yield* ThreadDeletionReactor;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay; const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
@@ -22,6 +24,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* providerRuntimeIngestion.start(); yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start(); yield* providerCommandReactor.start();
yield* checkpointReactor.start(); yield* checkpointReactor.start();
yield* threadAutoSettleReactor.start();
yield* threadDeletionReactor.start(); yield* threadDeletionReactor.start();
yield* agentAwarenessRelay.start(); yield* agentAwarenessRelay.start();
}); });
@@ -326,6 +326,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
pinnedAt: "2026-02-24T00:00:01.000Z", pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm", pinOrderKey: "gm",
titleRegeneration: null, titleRegeneration: null,
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
deletedAt: null, deletedAt: null,
messages: [ messages: [
{ {
@@ -1578,6 +1578,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: row.pinnedAt, pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null, pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row), titleRegeneration: mapTitleRegeneration(row),
latestUserMessageAt: row.latestUserMessageAt,
deletedAt: row.deletedAt, deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [], messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1785,6 +1786,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: row.pinnedAt, pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null, pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row), titleRegeneration: mapTitleRegeneration(row),
// The command read model never hydrates message bodies, so
// the decider reads this stamp instead of thread.messages.
latestUserMessageAt: row.latestUserMessageAt,
deletedAt: row.deletedAt, deletedAt: row.deletedAt,
messages: [], messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [], proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -2466,6 +2470,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: threadRow.value.pinnedAt, pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null, pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value), titleRegeneration: mapTitleRegeneration(threadRow.value),
latestUserMessageAt: threadRow.value.latestUserMessageAt,
deletedAt: null, deletedAt: null,
messages: messageRows.map((row) => { messages: messageRows.map((row) => {
const message = { const message = {
@@ -400,6 +400,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge( Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, { Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"), getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: () => refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"), Effect.die("refreshLocalStatus should not be called in this test"),
refreshStatus, refreshStatus,
@@ -0,0 +1,321 @@
// @effect-diagnostics globalDate:off -- fixtures are offsets from the real clock the sweep reads.
import {
ProjectId,
ProviderInstanceId,
ServerSettingsError,
ThreadId,
type OrchestrationCommand,
type OrchestrationProjectShell,
type OrchestrationShellSnapshot,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
import { make, ThreadAutoSettleReactor } from "./ThreadAutoSettleReactor.ts";
const NOW_MS = Date.now();
const STALE = new Date(NOW_MS - 4 * 24 * 60 * 60 * 1_000).toISOString();
const FRESH = new Date(NOW_MS - 60 * 60 * 1_000).toISOString();
function makeProject(): OrchestrationProjectShell {
return {
id: ProjectId.make("project-1"),
title: "Project",
workspaceRoot: "/workspace/project-1",
defaultModelSelection: null,
scripts: [],
createdAt: STALE,
updatedAt: STALE,
};
}
function makeThread(input: {
readonly id: string;
readonly activityAt: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly branch?: string | null;
}): OrchestrationThreadShell {
return {
id: ThreadId.make(input.id),
projectId: ProjectId.make("project-1"),
title: input.id,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: input.branch ?? null,
worktreePath: null,
latestTurn: null,
createdAt: STALE,
updatedAt: STALE,
archivedAt: null,
settledOverride: input.settledOverride ?? null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
session: null,
latestUserMessageAt: input.activityAt,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
}
function makeHarness(input: {
readonly threads: ReadonlyArray<OrchestrationThreadShell>;
readonly settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0];
/** Cached VCS status handed to peekStatus; null = nothing cached. */
readonly peekStatus?: VcsStatusBroadcaster["Service"]["peekStatus"];
/** Live refreshStatus result; unset = the sweep must not go live. */
readonly refreshStatus?: VcsStatusBroadcaster["Service"]["refreshStatus"];
/** Whether the background policy allows live PR lookups. Default false. */
readonly opportunisticWork?: boolean;
/** Make getSettings fail, exercising the disabled-sweep fallback. */
readonly failSettings?: boolean;
}) {
const dispatched: OrchestrationCommand[] = [];
const snapshot: OrchestrationShellSnapshot = {
snapshotSequence: 1,
projects: [makeProject()],
threads: input.threads,
updatedAt: STALE,
};
const layer = Layer.effect(ThreadAutoSettleReactor, make()).pipe(
Layer.provide(
Layer.mock(OrchestrationEngineService)({
dispatch: (command) =>
Effect.sync(() => {
dispatched.push(command);
return { sequence: dispatched.length };
}),
}),
),
Layer.provide(
Layer.mock(ProjectionSnapshotQuery)({
getShellSnapshot: () => Effect.succeed(snapshot),
}),
),
Layer.provide(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called"),
peekStatus: input.peekStatus ?? (() => Effect.succeed(null)),
refreshLocalStatus: () => Effect.die("refreshLocalStatus should not be called"),
refreshStatus:
input.refreshStatus ?? (() => Effect.die("refreshStatus should not be called")),
streamStatus: () => Stream.empty,
}),
),
Layer.provide(
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
shouldRunOpportunisticWork: Effect.succeed(input.opportunisticWork ?? false),
}),
),
Layer.provide(
input.failSettings === true
? Layer.mock(ServerSettingsService)({
getSettings: Effect.fail(
new ServerSettingsError({
operation: "read-file",
settingsPath: "/tmp/settings.json",
cause: "unreadable",
}),
),
})
: ServerSettingsService.layerTest(input.settingsOverrides ?? {}),
),
Layer.provide(NodeServices.layer),
);
return { dispatched, layer };
}
const runSweep = (layer: Layer.Layer<ThreadAutoSettleReactor, ServerSettingsError>) =>
Effect.service(ThreadAutoSettleReactor).pipe(
Effect.flatMap((reactor) => reactor.sweepOnce),
Effect.provide(layer),
Effect.orDie,
);
describe("ThreadAutoSettleReactor", () => {
// it.live: fixtures are offsets from the real clock the sweep reads; the
// TestClock's epoch-zero "now" would put every fixture in the future.
it.live("settles quiet threads past the window", () =>
Effect.gen(function* () {
const { dispatched, layer } = makeHarness({
threads: [
makeThread({ id: "stale", activityAt: STALE }),
makeThread({ id: "fresh", activityAt: FRESH }),
makeThread({ id: "pinned-active", activityAt: STALE, settledOverride: "active" }),
makeThread({ id: "already-settled", activityAt: STALE, settledOverride: "settled" }),
],
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(1);
const command = dispatched[0];
expect(command?.type).toBe("thread.settle");
if (command?.type === "thread.settle") {
expect(command.threadId).toBe("stale");
expect(command.commandId.startsWith("server:auto-settle:")).toBe(true);
}
}),
);
it.live("does nothing with auto-settle disabled", () =>
Effect.gen(function* () {
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "stale", activityAt: STALE })],
settingsOverrides: { threadAutoSettleAfterDays: null },
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(0);
}),
);
it.live("defers a quiet branch-carrying thread with no cached PR state", () =>
Effect.gen(function* () {
// peekStatus returns null (nothing cached) and opportunistic work is
// off, so the sweep can neither confirm nor rule out an open PR — it
// must leave the thread alone rather than hide work waiting on review.
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "stale-branch", activityAt: STALE, branch: "feature/x" })],
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(0);
}),
);
it.live("re-verifies a stale cached open PR and settles once it turns out merged", () =>
Effect.gen(function* () {
// The cache still says "open" (polling stopped before the merge). The
// sweep must not trust it: cached open triggers a live verification,
// which reports merged, and the thread settles.
const vcsStatus = (state: "open" | "merged") => ({
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/x",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: {
number: 42,
title: "Feature X",
url: "https://github.com/example/repo/pull/42",
baseRef: "main",
headRef: "feature/x",
state,
},
});
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "stale-open", activityAt: STALE, branch: "feature/x" })],
peekStatus: () => Effect.succeed(vcsStatus("open")),
refreshStatus: () => Effect.succeed(vcsStatus("merged")),
opportunisticWork: true,
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(1);
expect(dispatched[0]?.type).toBe("thread.settle");
}),
);
it.live("keeps a quiet thread active when live verification confirms the PR is open", () =>
Effect.gen(function* () {
const vcsStatus = {
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/x",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr: {
number: 42,
title: "Feature X",
url: "https://github.com/example/repo/pull/42",
baseRef: "main",
headRef: "feature/x",
state: "open" as const,
},
};
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "stale-open", activityAt: STALE, branch: "feature/x" })],
peekStatus: () => Effect.succeed(vcsStatus),
refreshStatus: () => Effect.succeed(vcsStatus),
opportunisticWork: true,
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(0);
}),
);
it.live("does not trust a cached no-PR result: live verification finds the open PR", () =>
Effect.gen(function* () {
// The cached status predates the PR being opened (pr: null). The sweep
// must live-verify rather than settle on the stale cache; the live
// lookup finds an open PR and the thread stays active.
const vcsStatus = (pr: null | "open") => ({
isRepo: true,
hasPrimaryRemote: true,
isDefaultRef: false,
refName: "feature/x",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
hasUpstream: true,
aheadCount: 0,
behindCount: 0,
pr:
pr === null
? null
: {
number: 42,
title: "Feature X",
url: "https://github.com/example/repo/pull/42",
baseRef: "main",
headRef: "feature/x",
state: pr,
},
});
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "cached-no-pr", activityAt: STALE, branch: "feature/x" })],
peekStatus: () => Effect.succeed(vcsStatus(null)),
refreshStatus: () => Effect.succeed(vcsStatus("open")),
opportunisticWork: true,
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(0);
}),
);
it.live("disables the inactivity sweep when the settings read fails", () =>
Effect.gen(function* () {
// A failed settings read must not fall back to the default window: the
// user may have auto-settle disabled, and hiding threads on a read
// error is not undone by the next successful sweep.
const { dispatched, layer } = makeHarness({
threads: [makeThread({ id: "stale", activityAt: STALE })],
failSettings: true,
});
yield* runSweep(layer);
expect(dispatched).toHaveLength(0);
}),
);
});
@@ -0,0 +1,271 @@
/**
* ThreadAutoSettleReactor - Server-side auto-settle sweep.
*
* The server is the single author of settled state: this reactor periodically
* evaluates unsettled threads against the auto-settle policy (inactivity
* window from the threadAutoSettleAfterDays server setting, merged/closed PR)
* and dispatches thread.settle for the ones that qualify. Clients only read
* settledOverride.
*
* @module ThreadAutoSettleReactor
*/
import { CommandId, type ThreadId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import { forkParked } from "../serverActivation.ts";
import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
import { type AutoSettleChangeRequestState, resolveAutoSettleVerdict } from "./autoSettle.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
export class ThreadAutoSettleReactor extends Context.Service<
ThreadAutoSettleReactor,
{
/** Start the periodic auto-settle sweep within the provided scope. */
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
/** Run one sweep immediately. Intended for tests, which must never wait
on the timer schedule. */
readonly sweepOnce: Effect.Effect<void>;
}
>()("t3/orchestration/ThreadAutoSettleReactor") {}
// A sweep is one shell-snapshot read plus cache-only PR peeks, so it can run
// often; a merged PR settles its thread within a tick while a client's VCS
// watcher keeps the status cache warm.
const DEFAULT_SWEEP_INTERVAL_MS = 60 * 1_000;
// Live PR verification hits git and the forge, so cold cwds are re-checked at
// most this often — an unwatched repo's open PR still unblocks settle within
// the cooldown of merging.
const DEFAULT_PR_VERIFY_COOLDOWN_MS = 30 * 60 * 1_000;
// At most this many live verifications per sweep: right after an upgrade a
// server can hold dozens of quiet branch-carrying threads, and verifying all
// of them at once would stampede git and the forge. The backlog drains a few
// threads per sweep instead.
const PR_VERIFY_MAX_PER_SWEEP = 5;
export interface ThreadAutoSettleReactorOptions {
readonly sweepIntervalMs?: number;
readonly prVerifyCooldownMs?: number;
}
export const make = (options?: ThreadAutoSettleReactorOptions) =>
Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const serverSettings = yield* ServerSettingsService;
const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
const crypto = yield* Crypto.Crypto;
const sweepIntervalMs = Math.max(1, options?.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS);
const prVerifyCooldownMs = Math.max(
1,
options?.prVerifyCooldownMs ?? DEFAULT_PR_VERIFY_COOLDOWN_MS,
);
const lastPrVerifyAtByCwd = yield* Ref.make(new Map<string, number>());
const serverCommandId = crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`server:auto-settle:${uuid}`)),
);
// A failed settings read disables the sweep (window null, merge-settle
// off) rather than falling back to defaults: the user may have
// auto-settle turned OFF, and hiding threads on a read error is not
// recoverable by retry the way skipping a sweep is.
const autoSettlePolicy = serverSettings.getSettings.pipe(
Effect.map((settings) => ({
autoSettleAfterDays: settings.threadAutoSettleAfterDays,
autoSettleOnMerge: settings.threadAutoSettleOnMerge,
})),
Effect.orElseSucceed(() => ({
autoSettleAfterDays: null,
autoSettleOnMerge: false,
})),
);
// The cached PR state for a thread's checkout, mapped exactly like the
// clients' old resolveThreadPr: a status only counts when its refName is
// the thread's branch (a workspace checked out elsewhere can never
// determine this thread's PR state, so it gates nothing). A cached
// Cached "open"/"closed" map to their "-cached" variants: an open PR may
// have merged and a closed PR may have been REOPENED since polling
// stopped, so neither is acted on without a cooldown-limited live
// verification. Only "merged" is terminal enough to trust from cache.
const peekChangeRequestState = Effect.fn("ThreadAutoSettleReactor.peekChangeRequestState")(
function* (thread: {
readonly branch: string | null;
readonly cwd: string;
}): Effect.fn.Return<AutoSettleChangeRequestState> {
if (thread.branch === null) return "none";
const status = yield* vcsStatusBroadcaster.peekStatus({ cwd: thread.cwd });
if (status === null) return "unknown";
// A live lookup cannot change the checkout, so a refName mismatch is
// final; but a cached no-PR result may simply predate the PR being
// opened — only a live lookup may conclude "none" for the branch.
if (status.refName !== thread.branch) return "none";
const pr = status.pr ?? null;
if (pr === null) return "unknown";
// The cache's local and remote halves update independently: after a
// branch switch the local half carries the new refName while the
// remote half may still hold the PREVIOUS branch's PR. A PR whose
// headRef is not this thread's branch is that stale pairing — never
// settle on another branch's merge; verify live instead.
if (pr.headRef !== thread.branch) return "unknown";
if (pr.state === "open") return "open-cached";
if (pr.state === "closed") return "closed-cached";
return pr.state;
},
);
// Live PR lookup for an inactivity-settle candidate whose cached state is
// missing or stale-open. Cooldown-limited per cwd and gated on the
// background policy so an idle laptop is not woken for forge polls.
// `verified` is false when the cooldown suppressed the lookup — such
// calls are free and must not consume the sweep's verification budget.
const verifyChangeRequestState = Effect.fn("ThreadAutoSettleReactor.verifyChangeRequestState")(
function* (thread: {
readonly branch: string | null;
readonly cwd: string;
}): Effect.fn.Return<{
readonly state: AutoSettleChangeRequestState;
readonly verified: boolean;
}> {
if (thread.branch === null) return { state: "none", verified: false };
const now = yield* Clock.currentTimeMillis;
const mayVerify = yield* Ref.modify(lastPrVerifyAtByCwd, (byCwd) => {
const lastAt = byCwd.get(thread.cwd);
if (lastAt !== undefined && now - lastAt < prVerifyCooldownMs) {
return [false, byCwd] as const;
}
const next = new Map(byCwd);
next.set(thread.cwd, now);
return [true, next] as const;
});
if (!mayVerify) return { state: "unknown", verified: false };
const status = yield* vcsStatusBroadcaster.refreshStatus(thread.cwd).pipe(
Effect.catch((error) =>
Effect.logDebug("thread.auto-settle.pr-verify-failed", {
cwd: thread.cwd,
error,
}).pipe(Effect.as(null)),
),
);
if (status === null) return { state: "unknown", verified: true };
if (status.refName !== thread.branch) return { state: "none", verified: true };
const pr = status.pr ?? null;
if (pr === null) return { state: "none", verified: true };
// Same coherence guard as the cached path: the refresh loads the
// local and remote halves concurrently, so a checkout switch racing
// the refresh can still pair this branch's refName with another
// branch's PR. Never settle (or block) on a PR that is not for this
// thread's branch — report undetermined and let a later sweep retry.
if (pr.headRef !== thread.branch) return { state: "unknown", verified: true };
return { state: pr.state, verified: true };
},
);
const settleThread = Effect.fn("ThreadAutoSettleReactor.settleThread")(function* (input: {
readonly threadId: ThreadId;
}) {
const commandId = yield* serverCommandId;
yield* orchestrationEngine
.dispatch({
type: "thread.settle",
commandId,
threadId: input.threadId,
})
.pipe(
Effect.tap(() =>
Effect.logInfo("thread.auto-settled", {
threadId: input.threadId,
}),
),
// Invariant rejections are routine races (a turn started between
// snapshot and dispatch); anything else is logged and retried by
// the next sweep.
Effect.catch((error) =>
Effect.logDebug("thread.auto-settle.dispatch-rejected", {
threadId: input.threadId,
error,
}),
),
);
});
const sweepOnce: ThreadAutoSettleReactor["Service"]["sweepOnce"] = Effect.gen(function* () {
const [snapshot, policy, now] = yield* Effect.all([
projectionSnapshotQuery.getShellSnapshot(),
autoSettlePolicy,
Effect.map(DateTime.now, DateTime.formatIso),
]);
const workspaceRootByProjectId = new Map(
snapshot.projects.map((project) => [project.id, project.workspaceRoot]),
);
const mayVerifyPr = yield* backgroundPolicy.shouldRunOpportunisticWork;
let verifyBudget = PR_VERIFY_MAX_PER_SWEEP;
for (const thread of snapshot.threads) {
const cwd = thread.worktreePath ?? workspaceRootByProjectId.get(thread.projectId);
if (cwd === undefined) continue;
const target = { branch: thread.branch, cwd };
const verdict = resolveAutoSettleVerdict(thread, {
now,
...policy,
changeRequestState: yield* peekChangeRequestState(target),
});
if (verdict.kind === "skip") continue;
if (verdict.kind === "settle") {
yield* settleThread({ threadId: thread.id });
continue;
}
// verify-pr: quiet past the window but PR state undetermined (nothing
// cached, or a possibly-stale cached "open").
if (!mayVerifyPr || verifyBudget <= 0) continue;
const verification = yield* verifyChangeRequestState(target);
// Cooldown-suppressed lookups are free; only real refreshes (which
// hit git and possibly the forge) consume the per-sweep budget.
if (verification.verified) verifyBudget -= 1;
const reVerdict = resolveAutoSettleVerdict(thread, {
now,
...policy,
changeRequestState: verification.state,
});
if (reVerdict.kind === "settle") {
yield* settleThread({ threadId: thread.id });
}
}
}).pipe(
Effect.catch((error: unknown) =>
Effect.logWarning("thread.auto-settle.sweep-failed", { error }),
),
Effect.catchDefect((defect: unknown) =>
Effect.logWarning("thread.auto-settle.sweep-defect", { defect }),
),
);
const start: ThreadAutoSettleReactor["Service"]["start"] = () =>
Effect.gen(function* () {
yield* forkParked(
sweepOnce.pipe(Effect.repeat(Schedule.spaced(Duration.millis(sweepIntervalMs)))),
);
yield* Effect.logInfo("thread.auto-settle.started", { sweepIntervalMs });
});
return ThreadAutoSettleReactor.of({
start,
sweepOnce,
});
});
export const layer = Layer.effect(ThreadAutoSettleReactor, make());
@@ -0,0 +1,286 @@
import {
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { resolveAutoSettleVerdict, threadLastActivityAt } from "./autoSettle.ts";
const NOW = "2026-04-10T00:00:00.000Z";
const FRESH = "2026-04-09T00:00:00.000Z";
const STALE = "2026-04-06T23:59:59.999Z";
function makeShell(input: {
readonly settledOverride?: "settled" | "active" | null;
readonly activityAt: string | null;
readonly sessionStatus?: "starting" | "running" | "error";
readonly pending?: "approval" | "user-input";
readonly pinnedAt?: string | null;
readonly snoozedUntil?: string | null;
readonly latestUserMessageAt?: string | null;
}): OrchestrationThreadShell {
const threadId = ThreadId.make("thread-1");
return {
id: threadId,
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn:
input.activityAt === null
? null
: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: input.activityAt,
startedAt: null,
completedAt: null,
assistantMessageId: null,
},
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: NOW,
archivedAt: null,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledOverride === "settled" ? NOW : null,
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: null,
pinnedAt: input.pinnedAt ?? null,
session:
input.sessionStatus === undefined
? null
: {
threadId,
status: input.sessionStatus,
providerName: "Codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
},
latestUserMessageAt: input.latestUserMessageAt ?? null,
hasPendingApprovals: input.pending === "approval",
hasPendingUserInput: input.pending === "user-input",
hasActionableProposedPlan: false,
};
}
describe("threadLastActivityAt", () => {
it("returns the newest user or turn timestamp", () => {
const shell = {
latestUserMessageAt: "2026-04-04T00:00:00.000Z",
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed" as const,
requestedAt: "2026-04-03T00:00:00.000Z",
startedAt: "2026-04-05T00:00:00.000Z",
completedAt: "2026-04-06T00:00:00.000Z",
assistantMessageId: null,
},
snoozedUntil: null,
};
expect(threadLastActivityAt(shell, Date.parse(NOW))).toBe("2026-04-06T00:00:00.000Z");
expect(
threadLastActivityAt({ latestUserMessageAt: null, latestTurn: null, snoozedUntil: null }, 0),
).toBeNull();
});
it("counts an elapsed snooze wake as activity, so a woken thread gets a fresh window", () => {
const wokeAt = "2026-04-09T09:00:00.000Z";
const shell = {
latestUserMessageAt: STALE,
latestTurn: null,
snoozedUntil: wokeAt,
};
expect(threadLastActivityAt(shell, Date.parse(NOW))).toBe(wokeAt);
// A wake still in the future is not activity (the thread is snoozed, and
// the verdict skips it anyway).
expect(threadLastActivityAt(shell, Date.parse("2026-04-09T08:00:00.000Z"))).toBe(STALE);
});
});
describe("resolveAutoSettleVerdict", () => {
const base = {
now: NOW,
autoSettleAfterDays: 3,
autoSettleOnMerge: true,
changeRequestState: "none" as const,
};
it("settles a quiet thread past the window", () => {
expect(resolveAutoSettleVerdict(makeShell({ activityAt: STALE }), base)).toEqual({
kind: "settle",
});
});
it("leaves fresh threads and threads with no recorded activity alone", () => {
expect(resolveAutoSettleVerdict(makeShell({ activityAt: FRESH }), base).kind).toBe("skip");
expect(resolveAutoSettleVerdict(makeShell({ activityAt: null }), base).kind).toBe("skip");
});
it("skips any explicit override, pinned, and still-snoozed threads", () => {
const stale = { activityAt: STALE } as const;
expect(
resolveAutoSettleVerdict(makeShell({ ...stale, settledOverride: "settled" }), base).kind,
).toBe("skip");
expect(
resolveAutoSettleVerdict(makeShell({ ...stale, settledOverride: "active" }), base).kind,
).toBe("skip");
expect(resolveAutoSettleVerdict(makeShell({ ...stale, pinnedAt: FRESH }), base).kind).toBe(
"skip",
);
expect(
resolveAutoSettleVerdict(
makeShell({ ...stale, snoozedUntil: "2026-04-11T00:00:00.000Z" }),
base,
).kind,
).toBe("skip");
});
it("skips blocked-on-you and live-session threads", () => {
const stale = { activityAt: STALE } as const;
for (const shell of [
makeShell({ ...stale, pending: "approval" }),
makeShell({ ...stale, pending: "user-input" }),
makeShell({ ...stale, sessionStatus: "starting" }),
makeShell({ ...stale, sessionStatus: "running" }),
]) {
expect(resolveAutoSettleVerdict(shell, base).kind).toBe("skip");
}
});
it("skips a queued turn start within the grace window", () => {
const messageAt = "2026-04-09T12:00:00.000Z";
const queued = makeShell({ activityAt: STALE, latestUserMessageAt: messageAt });
expect(
resolveAutoSettleVerdict(queued, {
...base,
now: "2026-04-09T12:00:30.000Z",
changeRequestState: "merged",
}).kind,
).toBe("skip");
});
it("settles immediately on a merged or closed PR, however fresh the thread", () => {
const fresh = makeShell({ activityAt: FRESH });
for (const changeRequestState of ["merged", "closed"] as const) {
expect(resolveAutoSettleVerdict(fresh, { ...base, changeRequestState })).toEqual({
kind: "settle",
});
}
});
it("never settles behind an open PR, however quiet the thread", () => {
const stale = makeShell({ activityAt: STALE });
expect(resolveAutoSettleVerdict(stale, { ...base, changeRequestState: "open" }).kind).toBe(
"skip",
);
});
it("asks for PR verification before an inactivity settle with unknown PR state", () => {
const stale = makeShell({ activityAt: STALE });
expect(resolveAutoSettleVerdict(stale, { ...base, changeRequestState: "unknown" }).kind).toBe(
"verify-pr",
);
// Merged/closed need no verification: unknown only gates the quiet path.
const fresh = makeShell({ activityAt: FRESH });
expect(resolveAutoSettleVerdict(fresh, { ...base, changeRequestState: "unknown" }).kind).toBe(
"skip",
);
});
it("honors a disabled inactivity window", () => {
const stale = makeShell({ activityAt: STALE });
expect(resolveAutoSettleVerdict(stale, { ...base, autoSettleAfterDays: null }).kind).toBe(
"skip",
);
// Merged PRs still settle with the window off.
expect(
resolveAutoSettleVerdict(stale, {
...base,
autoSettleAfterDays: null,
changeRequestState: "merged",
}).kind,
).toBe("settle");
});
it("uses a strict window boundary", () => {
const boundary = makeShell({ activityAt: "2026-04-07T00:00:00.000Z" });
expect(resolveAutoSettleVerdict(boundary, base).kind).toBe("skip");
});
it("does not settle a woken thread until a fresh window elapses after the wake", () => {
const wokeRecently = makeShell({
activityAt: STALE,
snoozedUntil: "2026-04-09T09:00:00.000Z",
});
expect(resolveAutoSettleVerdict(wokeRecently, base).kind).toBe("skip");
const wokeLongAgo = makeShell({
activityAt: "2026-04-01T00:00:00.000Z",
snoozedUntil: "2026-04-02T00:00:00.000Z",
});
expect(resolveAutoSettleVerdict(wokeLongAgo, base)).toEqual({ kind: "settle" });
});
it("re-verifies a cached open PR instead of trusting it to block settle", () => {
// A cached "open" may be stale (the PR could have merged since polling
// stopped), so a quiet thread asks for live verification rather than
// staying active forever on stale data.
const stale = makeShell({ activityAt: STALE });
expect(
resolveAutoSettleVerdict(stale, { ...base, changeRequestState: "open-cached" }).kind,
).toBe("verify-pr");
// A fresh thread with a cached open PR needs nothing: the inactivity
// path is not in play yet.
const fresh = makeShell({ activityAt: FRESH });
expect(
resolveAutoSettleVerdict(fresh, { ...base, changeRequestState: "open-cached" }).kind,
).toBe("skip");
});
it("honors threadAutoSettleOnMerge: merged neither settles nor blocks when off", () => {
// Closed still settles with the flag off; merged falls through to the
// inactivity window — a quiet merged thread settles by inactivity, a
// fresh one stays active.
const offBase = { ...base, autoSettleOnMerge: false };
const fresh = makeShell({ activityAt: FRESH });
expect(resolveAutoSettleVerdict(fresh, { ...offBase, changeRequestState: "merged" }).kind).toBe(
"skip",
);
expect(resolveAutoSettleVerdict(fresh, { ...offBase, changeRequestState: "closed" }).kind).toBe(
"settle",
);
const stale = makeShell({ activityAt: STALE });
expect(resolveAutoSettleVerdict(stale, { ...offBase, changeRequestState: "merged" }).kind).toBe(
"settle",
);
});
it("re-verifies a cached closed PR instead of settling on it", () => {
// A closed PR can be REOPENED; only a live-confirmed close settles. The
// check applies regardless of recency, like the live merged/closed path.
for (const shell of [makeShell({ activityAt: FRESH }), makeShell({ activityAt: STALE })]) {
expect(
resolveAutoSettleVerdict(shell, { ...base, changeRequestState: "closed-cached" }).kind,
).toBe("verify-pr");
}
});
it("clamps future-stamped activity to now instead of blocking settle forever", () => {
// A client clock far ahead must not hold the thread permanently fresh.
// The future stamp counts as activity NOW: still active within the
// window measured from the sweep's own clock...
const futureStamped = makeShell({ activityAt: "2026-04-20T00:00:00.000Z" });
expect(resolveAutoSettleVerdict(futureStamped, base).kind).toBe("skip");
// ...but once the sweep's clock alone moves a full window past the
// stamp, the thread settles — the skew cannot extend the window.
expect(
resolveAutoSettleVerdict(futureStamped, { ...base, now: "2026-04-24T00:00:00.001Z" }).kind,
).toBe("settle");
});
});
+195
View File
@@ -0,0 +1,195 @@
/**
* Pure auto-settle policy: decides whether a thread should settle, given the
* thread shell, the wall clock, the configured inactivity window, and the
* thread's change-request (PR) state. The server is the single author of
* settled state — clients only read settledOverride — so everything that used
* to be client-side effectiveSettled derivation lives here and runs in the
* ThreadAutoSettleReactor sweep.
*/
import type { OrchestrationThreadShell } from "@t3tools/contracts";
const DAY_MS = 24 * 60 * 60 * 1_000;
/**
* A queued turn start lives for at most this long: session adoption takes
* seconds, so a user message still unadopted after the grace window is a
* failed start (or stale data), not pending work. Shared by the decider's
* settle invariant and the auto-settle sweep; mirrors the client's constant
* in client-runtime threadSettled.ts.
*/
export const QUEUED_TURN_START_GRACE_MS = 2 * 60 * 1_000;
/**
* Change-request state resolved for a thread's checkout:
* - "open" / "closed" / "merged": the cwd's VCS status matched the thread's
* branch and carried this LIVE-confirmed PR state. Only "merged" is
* terminal enough to trust from cache; a cached "open" may have merged and
* a cached "closed" may have been reopened since polling stopped, so both
* get "-cached" variants that the verdict treats like "unknown" — asking
* for a live lookup instead of acting on stale data. ("closed-cached"
* still settles, but only after the live lookup confirms it.)
* - "none": PR state is decided and there is no gating PR: no branch, a
* LIVE lookup found no PR, or the cwd is checked out on a different
* branch (a live lookup cannot change the checkout, so re-verifying a
* refName mismatch would learn nothing — same as the clients' old
* branch-match guard). A cached no-PR result is NOT "none": the cache may
* predate the PR being opened, so it maps to "unknown" and re-verifies
* before an inactivity settle.
* - "unknown": the thread has a branch but no live-confirmed PR state; the
* sweep must verify with a live lookup before an inactivity settle.
*/
export type AutoSettleChangeRequestState =
| "open"
| "open-cached"
| "closed"
| "closed-cached"
| "merged"
| "none"
| "unknown";
export type AutoSettleVerdict =
| { readonly kind: "skip" }
| { readonly kind: "settle" }
| { readonly kind: "verify-pr" };
type AutoSettleShell = Pick<
OrchestrationThreadShell,
| "settledOverride"
| "pinnedAt"
| "snoozedUntil"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "session"
| "latestUserMessageAt"
| "latestTurn"
>;
/**
* When the thread last saw real activity: the newest of the latest user
* message, any latest-turn timestamp, and — for previously snoozed threads —
* the wake time. Counting the wake as activity gives a woken thread a fresh
* inactivity window; without it, a thread snoozed past the window would
* settle the instant it woke, defeating the snooze.
*
* Candidates ahead of `nowMs` are clamped TO `nowMs` rather than ignored:
* message timestamps are client-supplied, so a skewed clock must neither
* hold the thread "fresh" forever (unclamped future values always beat the
* window) nor erase the activity outright (which could settle a thread that
* genuinely just spoke). Mirrors the decider's settledAt clamp.
*/
export function threadLastActivityAt(
thread: Pick<OrchestrationThreadShell, "latestUserMessageAt" | "latestTurn" | "snoozedUntil">,
nowMs: number,
): string | null {
const snoozeWakePassed =
thread.snoozedUntil != null && Date.parse(thread.snoozedUntil) <= nowMs
? thread.snoozedUntil
: null;
const candidates = [
thread.latestUserMessageAt,
thread.latestTurn?.requestedAt,
thread.latestTurn?.startedAt,
thread.latestTurn?.completedAt,
snoozeWakePassed,
];
let latest: string | null = null;
let latestTimestamp = Number.NEGATIVE_INFINITY;
for (const candidate of candidates) {
if (candidate == null) continue;
const timestamp = Math.min(Date.parse(candidate), nowMs);
if (timestamp > latestTimestamp) {
latest = candidate;
latestTimestamp = timestamp;
}
}
return latest;
}
/**
* A user message no turn has picked up yet (turn.start dispatched, session
* not yet adopted). Bounded on both sides of the grace window because
* message timestamps originate on whichever device sent them — a clock
* ahead of this one must not hold the queued state for the whole skew.
*/
function hasQueuedTurnStart(thread: AutoSettleShell, nowMs: number): boolean {
if (thread.latestUserMessageAt == null) return false;
if (thread.session?.status === "error") return false;
const messageAt = Date.parse(thread.latestUserMessageAt);
if (Number.isNaN(messageAt)) return false;
if (Math.abs(nowMs - messageAt) > QUEUED_TURN_START_GRACE_MS) return false;
const turn = thread.latestTurn;
if (turn === null) return true;
return [turn.requestedAt, turn.startedAt, turn.completedAt].every(
(candidate) => candidate == null || Date.parse(candidate) < messageAt,
);
}
/**
* Auto-settle policy for one eligible-looking thread. Skips anything with an
* explicit override ("settled" is done, "active" is the user's keep-active
* pin), anything pinned or still snoozed, and anything blocked on the user
* or mid-work. Past the blockers: a closed PR settles immediately, a merged
* PR settles immediately when threadAutoSettleOnMerge allows it (and
* otherwise neither settles nor blocks), a live-verified open PR blocks the
* inactivity path, and otherwise the thread settles once its last activity
* falls outside the configured window — with "unknown" and cached "open"
* states asking for a live PR verification first, since either could be
* hiding a merge. (The decider stamps settledAt from the read model.)
*/
export function resolveAutoSettleVerdict(
thread: AutoSettleShell,
options: {
readonly now: string;
readonly autoSettleAfterDays: number | null;
readonly autoSettleOnMerge: boolean;
readonly changeRequestState: AutoSettleChangeRequestState;
},
): AutoSettleVerdict {
const { autoSettleAfterDays, autoSettleOnMerge, changeRequestState } = options;
const nowMs = Date.parse(options.now);
// A malformed clock must never surprise-settle anything.
if (Number.isNaN(nowMs)) return { kind: "skip" };
if (thread.settledOverride !== null) return { kind: "skip" };
// Settling a pinned thread would clear the pin (the decider bundles
// thread.unpinned with thread.settled); a pin means "never out of sight".
if (thread.pinnedAt != null) return { kind: "skip" };
if (thread.snoozedUntil != null && Date.parse(thread.snoozedUntil) > nowMs) {
return { kind: "skip" };
}
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return { kind: "skip" };
if (thread.session?.status === "starting" || thread.session?.status === "running") {
return { kind: "skip" };
}
if (hasQueuedTurnStart(thread, nowMs)) return { kind: "skip" };
// A closed PR always settles; a merged PR settles only when the server
// setting allows it — otherwise the merge neither settles nor blocks, and
// the thread falls through to the inactivity window like any other.
if (changeRequestState === "closed" || (changeRequestState === "merged" && autoSettleOnMerge)) {
return { kind: "settle" };
}
// A cached "closed" would settle immediately if trusted, but the PR may
// have been REOPENED since polling stopped — confirm live first. (This
// sits before the inactivity gate because a confirmed close settles
// regardless of recency, exactly like the live path above.)
if (changeRequestState === "closed-cached") return { kind: "verify-pr" };
// A LIVE open PR is unfinished business no matter how long the thread has
// been quiet: review can take days, and hiding the thread would bury the
// work waiting on it.
if (changeRequestState === "open") return { kind: "skip" };
if (autoSettleAfterDays === null) return { kind: "skip" };
const lastActivityAt = threadLastActivityAt(thread, nowMs);
if (lastActivityAt === null) return { kind: "skip" };
// Same clamp as threadLastActivityAt: a future-stamped candidate counts as
// activity NOW, not activity forever.
if (Math.min(Date.parse(lastActivityAt), nowMs) >= nowMs - autoSettleAfterDays * DAY_MS) {
return { kind: "skip" };
}
// Quiet past the window, but PR state undetermined — either nothing cached
// or a cached "open" that may have merged since polling stopped. Verify
// live before hiding (or keeping) the thread on stale data.
if (changeRequestState === "unknown" || changeRequestState === "open-cached") {
return { kind: "verify-pr" };
}
return { kind: "settle" };
}
@@ -12,6 +12,7 @@ import {
import * as NodeServices from "@effect/platform-node/NodeServices"; import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest"; import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect"; import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
import { decideOrchestrationCommand } from "./decider.ts"; import { decideOrchestrationCommand } from "./decider.ts";
@@ -108,6 +109,50 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
}), }),
); );
it.effect("derives settledAt from the thread's last recorded activity", () =>
Effect.gen(function* () {
// The derivation clamps candidates to the command time; advance the
// TestClock past the fixtures or its epoch-zero "now" would put every
// candidate in the future and clamp them all away.
yield* TestClock.setTime(Date.parse(NOW));
// Shelf ordering keys on when work ENDED. The decider derives the stamp
// from the read model — never from the command — so callers cannot
// forge it.
const lastMessageAt = "2025-12-28T00:00:00.000Z";
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.settle",
commandId: CommandId.make("cmd-settle-backdate"),
threadId: ThreadId.make("thread-1"),
},
readModel: makeReadModel(
null,
null,
null,
[],
[
{
id: MessageId.make("message-1"),
role: "user",
text: "hello",
attachments: [],
turnId: null,
streaming: false,
createdAt: lastMessageAt,
updatedAt: lastMessageAt,
},
],
),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.settled");
if (events[0]?.type === "thread.settled") {
expect(events[0].payload.settledAt).toBe(lastMessageAt);
expect(events[0].payload.updatedAt).not.toBe(lastMessageAt);
}
}),
);
it.effect("rejects settling a thread with a live session", () => it.effect("rejects settling a thread with a live session", () =>
Effect.gen(function* () { Effect.gen(function* () {
for (const status of ["starting", "running"] as const) { for (const status of ["starting", "running"] as const) {
@@ -261,8 +306,9 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
updatedAt: createdAt, updatedAt: createdAt,
}); });
// The decider's clock is the Effect test clock, pinned to the epoch: // Pin the shared test clock explicitly (other tests in this layer move
// timestamps here are relative to 1970-01-01T00:00:00.000Z. // it): timestamps here are relative to 1970-01-01T00:00:00.000Z.
yield* TestClock.setTime(0);
// Within the grace window: genuinely queued, settle rejected. // Within the grace window: genuinely queued, settle rejected.
const queuedError = yield* decideOrchestrationCommand({ const queuedError = yield* decideOrchestrationCommand({
+75 -6
View File
@@ -104,8 +104,35 @@ function hasOpenBlockingRequest(thread: {
* as long as the skew lasts, extending the block far past the intended two * as long as the skew lasts, extending the block far past the intended two
* minutes. * minutes.
*/ */
// The newest user-message time visible to the decider. Reads the projected
// latestUserMessageAt stamp first — the engine's command read model boots
// threads with an EMPTY messages array (bodies are never rehydrated), so a
// messages-only scan silently loses all pre-restart activity — and still
// scans the in-memory messages as a floor for mid-session freshness.
function threadLatestUserMessageAtMs(thread: {
readonly latestUserMessageAt?: string | null | undefined;
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
}): number {
const stampedMs =
thread.latestUserMessageAt == null
? Number.NEGATIVE_INFINITY
: Date.parse(thread.latestUserMessageAt);
// Skip unparseable candidates: Math.max(x, NaN) is NaN, so one malformed
// client-supplied createdAt would otherwise poison the whole reduction and
// disable the queued-turn guard.
return thread.messages.reduce(
(latest, message) => {
if (message.role !== "user") return latest;
const parsed = Date.parse(message.createdAt);
return Number.isNaN(parsed) ? latest : Math.max(latest, parsed);
},
Number.isNaN(stampedMs) ? Number.NEGATIVE_INFINITY : stampedMs,
);
}
function threadHasQueuedTurnStart( function threadHasQueuedTurnStart(
thread: { thread: {
readonly latestUserMessageAt?: string | null | undefined;
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>; readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
readonly latestTurn: { readonly latestTurn: {
readonly requestedAt: string; readonly requestedAt: string;
@@ -116,11 +143,7 @@ function threadHasQueuedTurnStart(
}, },
occurredAt: string, occurredAt: string,
): boolean { ): boolean {
const latestUserMessageAtMs = thread.messages.reduce( const latestUserMessageAtMs = threadLatestUserMessageAtMs(thread);
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestTurnAtMs = const latestTurnAtMs =
thread.latestTurn === null thread.latestTurn === null
? Number.NEGATIVE_INFINITY ? Number.NEGATIVE_INFINITY
@@ -142,6 +165,49 @@ function threadHasQueuedTurnStart(
); );
} }
// The settled shelf orders by when work ended, so thread.settled stamps the
// thread's last recorded activity (newest user message, latestTurn
// timestamp, or an elapsed snooze wake) rather than the settle time — an
// auto-settle three quiet days later must not float the thread to the top
// of the shelf. Candidates ahead of the command time are ignored: message
// timestamps are client-supplied and a still-pending snooze wake is not
// activity, so a skewed clock cannot forge a future shelf position.
// Threads with no recorded activity fall back to the command time.
function threadLastActivityAt(
thread: {
readonly latestUserMessageAt?: string | null | undefined;
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
readonly latestTurn: {
readonly requestedAt: string;
readonly startedAt: string | null;
readonly completedAt: string | null;
} | null;
readonly snoozedUntil?: string | null | undefined;
},
occurredAt: string,
): string {
const occurredAtMs = Date.parse(occurredAt);
let latest: string | null = null;
let latestMs = Number.NEGATIVE_INFINITY;
const candidates = [
thread.latestUserMessageAt,
...thread.messages.filter((message) => message.role === "user").map((m) => m.createdAt),
thread.latestTurn?.requestedAt,
thread.latestTurn?.startedAt,
thread.latestTurn?.completedAt,
thread.snoozedUntil,
];
for (const candidate of candidates) {
if (candidate == null) continue;
const parsed = Date.parse(candidate);
if (!Number.isNaN(parsed) && parsed > latestMs && parsed <= occurredAtMs) {
latest = candidate;
latestMs = parsed;
}
}
return latest ?? occurredAt;
}
function withEventBase( function withEventBase(
input: Pick<OrchestrationCommand, "commandId"> & { input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"]; readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -502,7 +568,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.settled" as const, type: "thread.settled" as const,
payload: { payload: {
threadId: command.threadId, threadId: command.threadId,
settledAt: alreadySettled ? thread.settledAt : occurredAt, // Derived server-side from the read model (never from the command)
// so callers cannot forge shelf ordering: user settles and the
// auto-settle sweep both stamp when the work actually ended.
settledAt: alreadySettled ? thread.settledAt : threadLastActivityAt(thread, occurredAt),
// A re-emission is a projected no-op: keep the existing updatedAt // A re-emission is a projected no-op: keep the existing updatedAt
// so duplicate settles neither rewind nor churn ordering. A fresh // so duplicate settles neither rewind nor churn ordering. A fresh
// settle stamps the command time. // settle stamps the command time.
@@ -93,6 +93,7 @@ describe("orchestration projector", () => {
settledAt: null, settledAt: null,
snoozedUntil: null, snoozedUntil: null,
snoozedAt: null, snoozedAt: null,
latestUserMessageAt: null,
deletedAt: null, deletedAt: null,
messages: [], messages: [],
proposedPlans: [], proposedPlans: [],
@@ -701,6 +702,10 @@ describe("orchestration projector", () => {
).toEqual([{ id: "activity-1", turnId: "turn-1" }]); ).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]); expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([1]);
expect(thread?.latestTurn?.turnId).toBe("turn-1"); expect(thread?.latestTurn?.turnId).toBe("turn-1");
// The stamp rewinds with the messages: leaving the reverted-away second
// user message's time here would block settle/snooze on a message that
// no longer exists (and backdate settledAt to removed work).
expect(thread?.latestUserMessageAt).toBe("2026-02-23T10:00:01.000Z");
}); });
it("does not fallback-retain messages tied to removed turn IDs", async () => { it("does not fallback-retain messages tied to removed turn IDs", async () => {
@@ -305,6 +305,7 @@ export function projectEvent(
settledAt: null, settledAt: null,
snoozedUntil: null, snoozedUntil: null,
snoozedAt: null, snoozedAt: null,
latestUserMessageAt: null,
deletedAt: null, deletedAt: null,
messages: [], messages: [],
activities: [], activities: [],
@@ -540,10 +541,22 @@ export function projectEvent(
: [...thread.messages, message]; : [...thread.messages, message];
const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES); const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES);
// Maintained separately from the capped messages array so the stamp
// survives message eviction AND the unhydrated command read model
// (which boots with messages: []) — the decider's settle logic keys
// on it.
const latestUserMessageAt =
message.role === "user" &&
(thread.latestUserMessageAt == null ||
Date.parse(message.createdAt) > Date.parse(thread.latestUserMessageAt))
? message.createdAt
: thread.latestUserMessageAt;
return { return {
...nextBase, ...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, { threads: updateThread(nextBase.threads, payload.threadId, {
messages: cappedMessages, messages: cappedMessages,
latestUserMessageAt,
updatedAt: event.occurredAt, updatedAt: event.occurredAt,
}), }),
}; };
@@ -756,6 +769,18 @@ export function projectEvent(
assistantMessageId: latestCheckpoint.assistantMessageId, assistantMessageId: latestCheckpoint.assistantMessageId,
}; };
// Recompute the stamp from the retained messages: a revert that
// removes the newest user message must not leave the decider
// seeing it as still queued (blocking settle/snooze) or backdate
// settledAt to reverted-away work.
let latestUserMessageAt: string | null = null;
for (const message of messages) {
if (message.role !== "user") continue;
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
latestUserMessageAt = message.createdAt;
}
}
return { return {
...nextBase, ...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, { threads: updateThread(nextBase.threads, payload.threadId, {
@@ -764,6 +789,7 @@ export function projectEvent(
proposedPlans, proposedPlans,
activities, activities,
latestTurn, latestTurn,
latestUserMessageAt,
updatedAt: event.occurredAt, updatedAt: event.occurredAt,
}), }),
}; };
@@ -655,8 +655,8 @@ function matchesFilters(
viewer: string, viewer: string,
): boolean { ): boolean {
if (filters === undefined) return true; if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase()); const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.includes(label.trim().toLowerCase()); const holds = (label: string) => labels.has(label.trim().toLowerCase());
return ( return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) && (filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined || (filters.review === undefined ||
@@ -649,8 +649,8 @@ export const make = Effect.gen(function* () {
viewer: string, viewer: string,
): boolean => { ): boolean => {
if (filters === undefined) return true; if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase()); const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.includes(label.trim().toLowerCase()); const holds = (label: string) => labels.has(label.trim().toLowerCase());
return ( return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) && (filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// Judged on the provider row rather than the entry, because the two absences mean // Judged on the provider row rather than the entry, because the two absences mean
+2
View File
@@ -57,6 +57,7 @@ import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts"; import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts"; import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts"; import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
import * as ThreadAutoSettleReactor from "./orchestration/ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts"; import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts"; import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
@@ -242,6 +243,7 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(ProviderRuntimeIngestionLive), Layer.provideMerge(ProviderRuntimeIngestionLive),
Layer.provideMerge(ProviderCommandReactorLive), Layer.provideMerge(ProviderCommandReactorLive),
Layer.provideMerge(CheckpointReactorLive), Layer.provideMerge(CheckpointReactorLive),
Layer.provideMerge(ThreadAutoSettleReactor.layer),
Layer.provideMerge(ThreadDeletionReactorLive), Layer.provideMerge(ThreadDeletionReactorLive),
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))), Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
Layer.provideMerge(RuntimeReceiptBusLive), Layer.provideMerge(RuntimeReceiptBusLive),
@@ -159,6 +159,10 @@ export class VcsStatusBroadcaster extends Context.Service<
readonly getStatus: ( readonly getStatus: (
input: VcsStatusInput, input: VcsStatusInput,
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>; ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
/** Cache-only read: the merged status when both halves are cached, else
null. Never touches git or a forge — safe to call for many cwds in a
sweep (the auto-settle reactor's PR check). */
readonly peekStatus: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult | null>;
readonly refreshLocalStatus: ( readonly refreshLocalStatus: (
cwd: string, cwd: string,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>; ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
@@ -339,6 +343,17 @@ export const make = Effect.gen(function* () {
return yield* updateCachedStatus(cwd, local, remote); return yield* updateCachedStatus(cwd, local, remote);
}); });
const peekStatus: VcsStatusBroadcaster["Service"]["peekStatus"] = Effect.fn(
"VcsStatusBroadcaster.peekStatus",
)(function* (input) {
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
const cached = yield* getCachedStatus(cwd);
if (cached?.local && cached.remote) {
return mergeGitStatusParts(cached.local.value, cached.remote.value);
}
return null;
});
const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")( const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
function* (cwd: string) { function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd); yield* workflow.invalidateLocalStatus(cwd);
@@ -587,6 +602,7 @@ export const make = Effect.gen(function* () {
return VcsStatusBroadcaster.of({ return VcsStatusBroadcaster.of({
getStatus, getStatus,
peekStatus,
refreshLocalStatus, refreshLocalStatus,
refreshStatus, refreshStatus,
streamStatus, streamStatus,
+9 -25
View File
@@ -187,7 +187,6 @@ import {
useClientSettingsHydrated, useClientSettingsHydrated,
useEnvironmentSettings, useEnvironmentSettings,
} from "../hooks/useSettings"; } from "../hooks/useSettings";
import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection"; import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus"; import { getTerminalFocusOwner } from "../lib/terminalFocus";
@@ -274,9 +273,9 @@ import {
shouldShowThreadErrorBanner, shouldShowThreadErrorBanner,
ThreadErrorBanner, ThreadErrorBanner,
} from "./chat/ThreadErrorBanner"; } from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill"; import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { import {
DRAFT_HERO_TRANSITION_ANIMATION_ID, DRAFT_HERO_TRANSITION_ANIMATION_ID,
DRAFT_HERO_TRANSITION_DURATION_MS, DRAFT_HERO_TRANSITION_DURATION_MS,
@@ -4105,11 +4104,14 @@ function ChatViewContent(props: ChatViewProps) {
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread], [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
); );
// Settled state of the open thread, resolved exactly like the sidebar // Settled state of the open thread, resolved exactly like the sidebar
// partition (same shell, same capability gate, same PR auto-settle input) // partition (same shell, same override read) so the banner and the sidebar
// so the banner and the sidebar row never disagree. // row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null); const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays); // PR state feeds the Woke suppression only (finished work needs no wake-up
const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge); // call) — settled classification is server-authored and needs no PR input.
// The merge rule reads the thread environment's server setting, matching
// the sweep's own policy.
const autoSettleOnMerge = serverConfig?.settings.threadAutoSettleOnMerge ?? true;
const activeThreadPr = resolveThreadPr({ const activeThreadPr = resolveThreadPr({
threadBranch: activeThread?.branch ?? null, threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null, gitStatus: gitStatusQuery.data ?? null,
@@ -4122,9 +4124,7 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadPr, openThreadPullRequest]); }, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable = const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null; supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
const snoozeNow = new Date().toISOString(); const snoozeNow = new Date().toISOString();
const activeThreadSnoozed = const activeThreadSnoozed =
activeThreadShell !== null && activeThreadShell !== null &&
@@ -4181,22 +4181,7 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadWokeAt, activeThreadWokeAt,
autoSettleOnMerge, autoSettleOnMerge,
]); ]);
const activeThreadSettled = useMemo(() => { const activeThreadSettled = activeThreadShell !== null && effectiveSettled(activeThreadShell);
if (activeThreadShell === null || !supportsSettlement) return false;
return effectiveSettled(activeThreadShell, {
now: `${nowMinute}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState: activeThreadPr?.state ?? null,
});
}, [
activeThreadPr?.state,
activeThreadShell,
autoSettleAfterDays,
autoSettleOnMerge,
nowMinute,
supportsSettlement,
]);
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, { const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
reportFailure: false, reportFailure: false,
}); });
@@ -6185,7 +6170,6 @@ function ChatViewContent(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})} {...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title} activeThreadTitle={activeThread.title}
isServerThread={isServerThread} isServerThread={isServerThread}
changeRequestState={activeThreadPr?.state ?? null}
activeProjectName={activeProject?.title} activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null} activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null} activeProjectFaviconPath={activeProject?.faviconPath ?? null}
@@ -166,7 +166,7 @@ export type BuildThreadActionItemsThread = Pick<
| "worktreePath" | "worktreePath"
> & { > & {
updatedAt: string; updatedAt: string;
latestUserMessageAt?: string | null; latestUserMessageAt?: string | null | undefined;
}; };
export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: { export function buildThreadActionItems<TThread extends BuildThreadActionItemsThread>(input: {
+7 -19
View File
@@ -944,29 +944,17 @@ describe("sortSettledThreadsForSidebar", () => {
expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]); expect(sorted.map((thread) => thread.id)).toEqual(["settled-last", "settled-first"]);
}); });
it("falls back to last activity for auto-settled threads without a settledAt stamp", () => { it("falls back to updatedAt when settledAt is missing (malformed/legacy rows)", () => {
// The server stamps settledAt on every settle, so a missing stamp only
// arises from legacy or malformed data; updatedAt keeps such rows in a
// sane spot rather than sinking them to the bottom.
const sorted = sortSettledThreadsForSidebar([ const sorted = sortSettledThreadsForSidebar([
settled({ id: "auto-old", latestUserMessageAt: "2026-03-09T08:00:00.000Z" }), settled({ id: "legacy-old", updatedAt: "2026-03-09T08:00:00.000Z" }),
settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }), settled({ id: "explicit", settledAt: "2026-03-09T10:00:00.000Z" }),
settled({ id: "auto-recent", latestUserMessageAt: "2026-03-09T11:00:00.000Z" }), settled({ id: "legacy-recent", updatedAt: "2026-03-09T11:00:00.000Z" }),
]); ]);
expect(sorted.map((thread) => thread.id)).toEqual(["auto-recent", "explicit", "auto-old"]); expect(sorted.map((thread) => thread.id)).toEqual(["legacy-recent", "explicit", "legacy-old"]);
});
it("counts a turn completion as activity for auto-settled threads", () => {
// The message came in before the other thread's, but its turn finished
// after: completion time is the real "work ended" moment.
const sorted = sortSettledThreadsForSidebar([
settled({ id: "message-only", latestUserMessageAt: "2026-03-09T10:04:00.000Z" }),
settled({
id: "completed-later",
latestUserMessageAt: "2026-03-09T10:00:00.000Z",
latestTurn: makeLatestTurn({ completedAt: "2026-03-09T10:30:00.000Z" }),
}),
]);
expect(sorted.map((thread) => thread.id)).toEqual(["completed-later", "message-only"]);
}); });
it("breaks timestamp ties by id so the order is stable", () => { it("breaks timestamp ties by id so the order is stable", () => {
+6 -27
View File
@@ -568,35 +568,14 @@ export function searchSidebarThreadsByTitle<T extends { readonly title: string }
return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery)); return threads.filter((thread) => thread.title.toLowerCase().includes(normalizedQuery));
} }
type SettledTimestampInput = Pick< type SettledTimestampInput = Pick<SidebarThreadSummary, "settledAt" | "updatedAt">;
SidebarThreadSummary,
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
>;
/** The timestamp a settled row sorts and labels by: settledAt when stamped /** The timestamp a settled row sorts and labels by. The server stamps
(explicit settles), otherwise last activity — the same candidates settledAt on every settle, derived from the thread's last recorded
threadLastActivityAt feeds the auto-settle window (user message plus all activity, so it directly reads "when the work ended". updatedAt is the
latestTurn stamps), so a thread whose last activity was a turn completion net for malformed data. */
doesn't sort by an older message time. updatedAt is the final net. */
export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null { export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
const settledAt = firstValidTimestamp(thread.settledAt); return firstValidTimestamp(thread.settledAt) ?? firstValidTimestamp(thread.updatedAt);
if (settledAt !== null) return settledAt;
let latest: string | null = null;
let latestMs = Number.NEGATIVE_INFINITY;
for (const candidate of [
thread.latestUserMessageAt,
thread.latestTurn?.requestedAt,
thread.latestTurn?.startedAt,
thread.latestTurn?.completedAt,
]) {
if (candidate == null) continue;
const parsed = Date.parse(candidate);
if (!Number.isNaN(parsed) && parsed > latestMs) {
latest = candidate;
latestMs = parsed;
}
}
return latest ?? firstValidTimestamp(thread.updatedAt);
} }
// Settled rows are history, so they order by when the work ENDED, not when // Settled rows are history, so they order by when the work ENDED, not when
+19 -73
View File
@@ -103,7 +103,6 @@ import { startNewThreadFromContext } from "../lib/chatThreadActions";
import { useClientSettings } from "../hooks/useSettings"; import { useClientSettings } from "../hooks/useSettings";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { useLocalStorage } from "../hooks/useLocalStorage"; import { useLocalStorage } from "../hooks/useLocalStorage";
import { useNowMinute } from "../hooks/useNowMinute";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities"; import { useProjects, useThreadShells } from "../state/entities";
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server"; import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
@@ -711,11 +710,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onUnsnooze: (threadRef: ScopedThreadRef) => void; onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void; onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void; onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
}) { }) {
const { const {
isRenaming, isRenaming,
onChangeRequestState,
onCancelRename, onCancelRename,
onCommitRename, onCommitRename,
onContextMenu, onContextMenu,
@@ -858,11 +855,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
}); });
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider); const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined; const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state so the parent can apply the configured merge rule
// and the always-on close rule during partitioning.
useEffect(() => {
onChangeRequestState(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
@@ -1619,8 +1611,6 @@ export default function Sidebar() {
const router = useRouter(); const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar(); const { isMobile, setOpenMobile } = useSidebar();
const keybindings = useAtomValue(primaryServerKeybindingsAtom); const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat); const timestampFormat = useClientSettings((s) => s.timestampFormat);
@@ -1813,37 +1803,13 @@ export default function Sidebar() {
[projectGroups], [projectGroups],
); );
// now is quantized to the minute so effectiveSettled memoization doesn't // Snooze wake times are second-precise. The tick is a plain counter
// churn on every render; auto-settle thresholds are day-granular anyway. // bumped exactly at the next wake boundary (armed below, after the
const nowMinute = useNowMinute(); // partition knows the boundary); the partition reads a fresh clock
// Snooze wake times are second-precise, so classifying with the quantized // whenever it recomputes. (Settled needs no clock at all: it is
// minute would hold a woken thread on the shelf for up to a minute. The // server-authored via settledOverride.)
// tick is a plain counter bumped exactly at the next wake boundary (armed
// below, after the partition knows the boundary); the partition reads a
// fresh clock whenever it recomputes.
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
// 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">
>(() => new Map());
const handleChangeRequestState = useCallback(
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
setChangeRequestStateByKey((current) => {
if ((current.get(threadKey) ?? null) === state) return current;
const next = new Map(current);
if (state === null) {
next.delete(threadKey);
} else {
next.set(threadKey, state);
}
return next;
});
},
[],
);
// Project scope: one menu above the list. Scoping filters the list without // Project scope: one menu above the list. Scoping filters the list without
// making the header width depend on the number or length of project names. // making the header width depend on the number or length of project names.
const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null); const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null);
@@ -1931,11 +1897,9 @@ export default function Sidebar() {
settledThreads, settledThreads,
snoozeNow, snoozeNow,
} = useMemo(() => { } = useMemo(() => {
const now = `${nowMinute}:00.000Z`; // Snooze classification uses a REAL clock: wake times are second-precise
// Snooze classification uses a REAL clock, not the quantized minute: // and a woken thread must not linger on the shelf. snoozeWakeTick re-runs
// wake times are second-precise and a woken thread must not linger on // this memo exactly at the next wake boundary.
// the shelf for the rest of the minute. snoozeWakeTick re-runs this
// memo exactly at the next wake boundary.
void snoozeWakeTick; void snoozeWakeTick;
const preciseNow = new Date().toISOString(); const preciseNow = new Date().toISOString();
const visible = threads.filter( const visible = threads.filter(
@@ -1949,16 +1913,8 @@ export default function Sidebar() {
const snoozed: EnvironmentThreadShell[] = []; const snoozed: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = []; const settled: EnvironmentThreadShell[] = [];
for (const thread of visible) { for (const thread of visible) {
// Threads on servers without the settlement capability (old server,
// or descriptor not loaded yet) never classify as settled: the user
// could neither un-settle nor pin them, so auto-settling them would
// strand rows in a tail with no working affordances.
const supportsSettlement =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
const supportsSnooze = const supportsSnooze =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
// Snooze outranks everything, including a pin: "hide until Tuesday" // Snooze outranks everything, including a pin: "hide until Tuesday"
// temporarily suspends "keep on top". The pin survives underneath — // temporarily suspends "keep on top". The pin survives underneath —
// and so does its pinOrderKey, so on wake the thread reappears at // and so does its pinOrderKey, so on wake the thread reappears at
@@ -1973,15 +1929,12 @@ export default function Sidebar() {
// arise from stale or raced writes.) // arise from stale or raced writes.)
} else if (thread.pinnedAt != null) { } else if (thread.pinnedAt != null) {
pinned.push(thread); pinned.push(thread);
} else if ( // Settled is server-authored (settledOverride): the server sweeps
supportsSettlement && // quiet threads and merged/closed PRs, so the partition needs no
effectiveSettled(thread, { // clock, no auto-settle window, and no PR state. Servers that
now, // predate settlement never emit the override, so their threads
autoSettleAfterDays, // simply stay active.
autoSettleOnMerge, } else if (effectiveSettled(thread)) {
changeRequestState,
})
) {
settled.push(thread); settled.push(thread);
} else { } else {
active.push(thread); active.push(thread);
@@ -2013,16 +1966,7 @@ export default function Sidebar() {
settledThreads: sortSettledThreadsForSidebar(settled), settledThreads: sortSettledThreadsForSidebar(settled),
snoozeNow: preciseNow, snoozeNow: preciseNow,
}; };
}, [ }, [scopedProjectKeys, serverConfigs, snoozeWakeTick, threads]);
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestStateByKey,
nowMinute,
scopedProjectKeys,
serverConfigs,
snoozeWakeTick,
threads,
]);
const threadSearchInputRef = useRef<HTMLInputElement>(null); const threadSearchInputRef = useRef<HTMLInputElement>(null);
const [threadSearchQuery, setThreadSearchQuery] = useState(""); const [threadSearchQuery, setThreadSearchQuery] = useState("");
@@ -3561,7 +3505,10 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSettlement === true .threadSettlement === true
} }
autoSettleOnMerge={autoSettleOnMerge} autoSettleOnMerge={
serverConfigs.get(thread.environmentId)?.settings
.threadAutoSettleOnMerge !== false
}
snoozeSupported={ snoozeSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSnooze === true .threadSnooze === true
@@ -3619,7 +3566,6 @@ export default function Sidebar() {
onUnsnooze={attemptUnsnooze} onUnsnooze={attemptUnsnooze}
onUnpin={attemptUnpin} onUnpin={attemptUnpin}
onAcknowledgeWoke={acknowledgeWoke} onAcknowledgeWoke={acknowledgeWoke}
onChangeRequestState={handleChangeRequestState}
/> />
); );
}; };
@@ -10,7 +10,6 @@ import {
isAtomCommandInterrupted, isAtomCommandInterrupted,
squashAtomCommandFailure, squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime"; } from "@t3tools/client-runtime/state/runtime";
import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
import { ChevronDownIcon } from "lucide-react"; import { ChevronDownIcon } from "lucide-react";
import { import {
memo, memo,
@@ -51,8 +50,6 @@ interface ChatHeaderProps {
activeThreadTitle: string; activeThreadTitle: string;
/** Drafts have no server thread yet, so the title carries no action menu. */ /** Drafts have no server thread yet, so the title carries no action menu. */
isServerThread: boolean; isServerThread: boolean;
/** PR state feeding the settled classification, resolved by ChatView. */
changeRequestState: ChangeRequestStateLike | null;
activeProjectName: string | undefined; activeProjectName: string | undefined;
activeProjectCwd: string | null; activeProjectCwd: string | null;
activeProjectFaviconPath: string | null; activeProjectFaviconPath: string | null;
@@ -113,7 +110,6 @@ export const ChatHeader = memo(function ChatHeader({
draftId, draftId,
activeThreadTitle, activeThreadTitle,
isServerThread, isServerThread,
changeRequestState,
activeProjectName, activeProjectName,
activeProjectCwd, activeProjectCwd,
activeProjectFaviconPath, activeProjectFaviconPath,
@@ -191,7 +187,6 @@ export const ChatHeader = memo(function ChatHeader({
const { openMenu } = useThreadActionMenu({ const { openMenu } = useThreadActionMenu({
threadRef: isServerThread ? activeThreadRef : null, threadRef: isServerThread ? activeThreadRef : null,
projectCwd: activeProjectCwd, projectCwd: activeProjectCwd,
changeRequestState,
onStartRename: startRename, onStartRename: startRename,
}); });
const titleButtonRef = useRef<HTMLButtonElement | null>(null); const titleButtonRef = useRef<HTMLButtonElement | null>(null);
@@ -311,8 +311,8 @@ export function matchesPullRequestFilters(
filters: PullRequestListFilters, filters: PullRequestListFilters,
viewer?: string | null, viewer?: string | null,
): boolean { ): boolean {
const labels = entry.labels.map((label) => label.name.trim().toLowerCase()); const labels = new Set(entry.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.includes(label.trim().toLowerCase()); const holds = (label: string) => labels.has(label.trim().toLowerCase());
return ( return (
(filters.draft === undefined || entry.isDraft === (filters.draft === "only")) && (filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
(filters.review === undefined || (filters.review === undefined ||
@@ -185,10 +185,10 @@ export function pullRequestChecksState(
checks: ReadonlyArray<PullRequestCheck>, checks: ReadonlyArray<PullRequestCheck>,
): PullRequestChecksState | null { ): PullRequestChecksState | null {
if (checks.length === 0) return null; if (checks.length === 0) return null;
const statuses = checks.map((check) => check.status); const statuses = new Set(checks.map((check) => check.status));
if (statuses.includes("failure") || statuses.includes("cancelled")) return "failing"; if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
if (statuses.includes("pending")) return "pending"; if (statuses.has("pending")) return "pending";
return statuses.includes("success") ? "passing" : null; return statuses.has("success") ? "passing" : null;
} }
export function PullRequestActorAvatar({ export function PullRequestActorAvatar({
@@ -24,13 +24,13 @@ import {
MAX_GLASS_OPACITY, MAX_GLASS_OPACITY,
MAX_INTERFACE_FONT_SIZE, MAX_INTERFACE_FONT_SIZE,
MAX_PROMPT_FONT_SIZE, MAX_PROMPT_FONT_SIZE,
MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, MAX_THREAD_AUTO_SETTLE_AFTER_DAYS,
MAX_TERMINAL_FONT_SIZE, MAX_TERMINAL_FONT_SIZE,
MIN_CODE_FONT_SIZE, MIN_CODE_FONT_SIZE,
MIN_GLASS_OPACITY, MIN_GLASS_OPACITY,
MIN_INTERFACE_FONT_SIZE, MIN_INTERFACE_FONT_SIZE,
MIN_PROMPT_FONT_SIZE, MIN_PROMPT_FONT_SIZE,
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, MIN_THREAD_AUTO_SETTLE_AFTER_DAYS,
MIN_TERMINAL_FONT_SIZE, MIN_TERMINAL_FONT_SIZE,
} from "@t3tools/contracts/settings"; } from "@t3tools/contracts/settings";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
@@ -76,7 +76,11 @@ import {
} from "../../providerInstances"; } from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi"; import { ensureLocalApi, readLocalApi } from "../../localApi";
import { isMacPlatform } from "../../lib/utils"; import { isMacPlatform } from "../../lib/utils";
import { primaryServerObservabilityAtom, primaryServerProvidersAtom } from "../../state/server"; import {
primaryServerConfigAtom,
primaryServerObservabilityAtom,
primaryServerProvidersAtom,
} from "../../state/server";
import { useProjects } from "../../state/entities"; import { useProjects } from "../../state/entities";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState"; import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTimeLabel } from "../../timestampFormat"; import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -489,11 +493,10 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode
? ["Project Grouping"] ? ["Project Grouping"]
: []), : []),
...(settings.sidebarAutoSettleAfterDays !== ...(settings.threadAutoSettleAfterDays !== DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays
? ["Auto-settle inactive threads"] ? ["Auto-settle inactive threads"]
: []), : []),
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ...(settings.threadAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge
? ["Auto-settle merged threads"] ? ["Auto-settle merged threads"]
: []), : []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
@@ -549,8 +552,8 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.glassOpacity, settings.glassOpacity,
settings.enableLegacyTokenStreaming, settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks, settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays, settings.threadAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge, settings.threadAutoSettleOnMerge,
settings.sidebarProjectGroupingMode, settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount, settings.sidebarThreadPreviewCount,
settings.timestampFormat, settings.timestampFormat,
@@ -631,8 +634,8 @@ export function useSettingsRestore(onRestored?: () => void) {
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount, sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, threadAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays,
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, threadAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming, enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity, backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
@@ -1594,7 +1597,7 @@ function FontFamilySettingsRow({
); );
} }
const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3; const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays ?? 3;
function AutoSettleDaysInput({ function AutoSettleDaysInput({
value, value,
@@ -1603,35 +1606,42 @@ function AutoSettleDaysInput({
value: number; value: number;
onCommit: (days: number) => void; onCommit: (days: number) => void;
}) { }) {
// Local draft so the field can be emptied mid-edit; the setting only moves // Local draft; commits only when editing FINISHES (blur or Enter), never
// on valid input and snaps back to the persisted value on blur. // per keystroke. The setting drives a live server-side sweep, so a
// transient "1" while typing "14" would settle threads a day old before
// the real value lands — and un-settling later does not bring them back.
const [draft, setDraft] = useState(String(value)); const [draft, setDraft] = useState(String(value));
useEffect(() => { useEffect(() => {
setDraft(String(value)); setDraft(String(value));
}, [value]); }, [value]);
const commitDraft = () => {
// Number(), not parseInt: "3.5" must be rejected, not truncated to 3.
const parsed = Number(draft);
if (
Number.isInteger(parsed) &&
parsed >= MIN_THREAD_AUTO_SETTLE_AFTER_DAYS &&
parsed <= MAX_THREAD_AUTO_SETTLE_AFTER_DAYS
) {
if (parsed !== value) onCommit(parsed);
setDraft(String(parsed));
} else {
setDraft(String(value));
}
};
return ( return (
<Input <Input
type="number" type="number"
min={MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS} min={MIN_THREAD_AUTO_SETTLE_AFTER_DAYS}
max={MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS} max={MAX_THREAD_AUTO_SETTLE_AFTER_DAYS}
className="w-full sm:w-24" className="w-full sm:w-24"
value={draft} value={draft}
onChange={(event) => { onChange={(event) => setDraft(event.target.value)}
setDraft(event.target.value); onBlur={commitDraft}
// Number(), not parseInt: "3.5" must be rejected (not truncated to a onKeyDown={(event) => {
// committed 3 while the field shows 3.5) — commit only when the if (event.key === "Enter") commitDraft();
// persisted value matches the displayed one.
const parsed = Number(event.target.value);
if (
Number.isInteger(parsed) &&
parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS &&
parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS
) {
onCommit(parsed);
}
}} }}
onBlur={() => setDraft(String(value))}
aria-label="Days of inactivity before auto-settle" aria-label="Days of inactivity before auto-settle"
/> />
); );
@@ -1750,6 +1760,10 @@ export function GeneralSettingsPanel() {
); );
const observability = useAtomValue(primaryServerObservabilityAtom); const observability = useAtomValue(primaryServerObservabilityAtom);
const serverProviders = useAtomValue(primaryServerProvidersAtom); const serverProviders = useAtomValue(primaryServerProvidersAtom);
// Only servers running the auto-settle sweep understand the setting;
// showing the knob against an older server would persist a silent no-op.
const supportsAutoSettle =
useAtomValue(primaryServerConfigAtom)?.environment.capabilities.threadAutoSettle === true;
const diagnosticsDescription = formatDiagnosticsDescription({ const diagnosticsDescription = formatDiagnosticsDescription({
localTracingEnabled: observability?.localTracingEnabled ?? false, localTracingEnabled: observability?.localTracingEnabled ?? false,
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false, otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
@@ -1833,69 +1847,72 @@ export function GeneralSettingsPanel() {
} }
/> />
<SettingsRow {supportsAutoSettle ? (
{...searchableSetting("auto-settle-merged-threads")} <SettingsRow
description="Settle a thread when its pull request merges. Closed pull requests still settle automatically." {...searchableSetting("auto-settle-merged-threads")}
resetAction={ description="Settle a thread when its pull request merges. Closed pull requests still settle automatically. Applies on the server, so every device sees the same list."
settings.sidebarAutoSettleOnMerge !== resetAction={
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? ( settings.threadAutoSettleOnMerge !==
<SettingResetButton DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge ? (
label="auto-settle on merge" <SettingResetButton
onClick={() => label="auto-settle on merge"
onClick={() =>
updateSettings({
threadAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge,
})
}
/>
) : null
}
control={
<Switch
checked={settings.threadAutoSettleOnMerge}
onCheckedChange={(checked) =>
updateSettings({ threadAutoSettleOnMerge: Boolean(checked) })
}
aria-label="Auto-settle merged threads"
/>
}
/>
) : null}
{supportsAutoSettle ? (
<SettingsRow
{...searchableSetting("auto-settle-inactive-threads")}
description="Threads with no activity for this long settle automatically. Applies on the server, so every device sees the same list."
resetAction={
settings.threadAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays ? (
<SettingResetButton
label="auto-settle"
onClick={() =>
updateSettings({
threadAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays,
})
}
/>
) : null
}
control={
<Switch
checked={settings.threadAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({ updateSettings({
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, threadAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
}) })
} }
aria-label="Auto-settle inactive threads"
/> />
) : null }
} />
control={ ) : null}
<Switch {supportsAutoSettle && settings.threadAutoSettleAfterDays !== null ? (
checked={settings.sidebarAutoSettleOnMerge}
onCheckedChange={(checked) =>
updateSettings({ sidebarAutoSettleOnMerge: Boolean(checked) })
}
aria-label="Auto-settle merged threads"
/>
}
/>
<SettingsRow
{...searchableSetting("auto-settle-inactive-threads")}
description="Sidebar threads with no activity for this long settle automatically."
resetAction={
settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? (
<SettingResetButton
label="auto-settle"
onClick={() =>
updateSettings({
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
})
}
/>
) : null
}
control={
<Switch
checked={settings.sidebarAutoSettleAfterDays !== null}
onCheckedChange={(checked) =>
updateSettings({
sidebarAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
})
}
aria-label="Auto-settle inactive threads"
/>
}
/>
{settings.sidebarAutoSettleAfterDays !== null ? (
<SettingsRow <SettingsRow
title="Days of inactivity before auto-settle" title="Days of inactivity before auto-settle"
description="Any new activity un-settles a thread automatically." description="Any new activity un-settles a thread automatically."
control={ control={
<AutoSettleDaysInput <AutoSettleDaysInput
value={settings.sidebarAutoSettleAfterDays} value={settings.threadAutoSettleAfterDays}
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })} onCommit={(days) => updateSettings({ threadAutoSettleAfterDays: days })}
/> />
} }
/> />
+5 -20
View File
@@ -9,7 +9,6 @@ import {
canSnooze, canSnooze,
effectiveSettled, effectiveSettled,
effectiveSnoozed, effectiveSnoozed,
type ChangeRequestStateLike,
} from "@t3tools/client-runtime/state/thread-settled"; } from "@t3tools/client-runtime/state/thread-settled";
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts"; import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { useCallback } from "react"; import { useCallback } from "react";
@@ -60,11 +59,9 @@ export function useThreadActionMenu(input: {
readonly threadRef: ScopedThreadRef | null; readonly threadRef: ScopedThreadRef | null;
/** Fallback for "Copy path" when the thread has no worktree. */ /** Fallback for "Copy path" when the thread has no worktree. */
readonly projectCwd: string | null; readonly projectCwd: string | null;
/** PR state feeding auto-settle classification, as resolved by the caller. */
readonly changeRequestState: ChangeRequestStateLike | null;
readonly onStartRename: () => void; readonly onStartRename: () => void;
}) { }) {
const { threadRef, projectCwd, changeRequestState, onStartRename } = input; const { threadRef, projectCwd, onStartRename } = input;
const { const {
settleThread, settleThread,
unsettleThread, unsettleThread,
@@ -79,8 +76,6 @@ export function useThreadActionMenu(input: {
}); });
const handleNewThread = useNewThreadHandler(); const handleNewThread = useNewThreadHandler();
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread); const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const timestampFormat = useClientSettings((s) => s.timestampFormat); const timestampFormat = useClientSettings((s) => s.timestampFormat);
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({ const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
@@ -125,17 +120,10 @@ export function useThreadActionMenu(input: {
const items = buildThreadActionMenuItems({ const items = buildThreadActionMenuItems({
branch: thread.branch ?? null, branch: thread.branch ?? null,
isPinned: thread.pinnedAt != null, isPinned: thread.pinnedAt != null,
isSettled: // Settled is server-authored (settledOverride); the same override
supports.settlement && // read as the sidebar partition and ChatView's parked banner, so
effectiveSettled(thread, { // the three surfaces can never disagree.
// Minute-quantized like useNowMinute, so this classification isSettled: effectiveSettled(thread),
// can never disagree with the sidebar partition or ChatView's
// parked-thread banner within the same minute.
now: `${now.toISOString().slice(0, 16)}:00.000Z`,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
}),
isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }), isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
isRegeneratingTitle, isRegeneratingTitle,
@@ -285,9 +273,6 @@ export function useThreadActionMenu(input: {
})(); })();
}, },
[ [
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
confirmThreadDelete, confirmThreadDelete,
copyBranchToClipboard, copyBranchToClipboard,
copyPathToClipboard, copyPathToClipboard,
@@ -12,8 +12,6 @@ import {
changeRequestAutoSettles, changeRequestAutoSettles,
effectiveSettled, effectiveSettled,
hasQueuedTurnStart, hasQueuedTurnStart,
threadLastActivityAt,
type ChangeRequestStateLike,
} from "./threadSettled.ts"; } from "./threadSettled.ts";
const NOW = "2026-04-10T00:00:00.000Z"; const NOW = "2026-04-10T00:00:00.000Z";
@@ -83,237 +81,65 @@ function makeShell(input: {
}; };
} }
describe("threadLastActivityAt", () => {
it("returns the latest real user or turn activity and ignores thread/session updates", () => {
const shell = makeShell({ activityAt: null, sessionStatus: "running" });
const withActivity: OrchestrationThreadShell = {
...shell,
latestUserMessageAt: "2026-04-04T00:00:00.000Z",
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: "2026-04-03T00:00:00.000Z",
startedAt: "2026-04-05T00:00:00.000Z",
completedAt: "2026-04-06T00:00:00.000Z",
assistantMessageId: null,
},
};
expect(threadLastActivityAt(withActivity)).toBe("2026-04-06T00:00:00.000Z");
expect(threadLastActivityAt(shell)).toBeNull();
});
});
describe("effectiveSettled", () => { describe("effectiveSettled", () => {
// The server authors settled state; the client reads the override and only
// holds back blocked-on-you / live-session shells whose auto-unsettle event
// has not arrived yet.
const overrideCases = [null, "settled", "active"] as const; const overrideCases = [null, "settled", "active"] as const;
const changeRequestStates = [undefined, "open", "merged"] as const;
const inactivityCases = [
["fresh", FRESH],
["stale", STALE],
["no-activity", null],
] as const;
const runningCases = [false, true] as const; const runningCases = [false, true] as const;
const pendingCases = [undefined, "approval", "user-input"] as const; const pendingCases = [undefined, "approval", "user-input"] as const;
const truthTable = overrideCases.flatMap((settledOverride) => const truthTable = overrideCases.flatMap((settledOverride) =>
changeRequestStates.flatMap((changeRequestState) => runningCases.flatMap((running) =>
inactivityCases.flatMap(([inactivity, activityAt]) => pendingCases.map((pending) => ({
runningCases.flatMap((running) => settledOverride,
pendingCases.map((pending) => ({ running,
settledOverride, pending,
changeRequestState, expected: pending === undefined && !running && settledOverride === "settled",
inactivity, })),
activityAt,
running,
pending,
// Settled iff nothing blocks (pending work / live session) AND
// the override says settled, or (with no override) a merged PR
// or staleness auto-settles. The "active" pin suppresses both
// auto signals, and an open PR suppresses the inactivity path:
// a thread with a PR out for review is never done, however quiet.
expected:
pending === undefined &&
!running &&
(settledOverride === "settled" ||
(settledOverride === null &&
(changeRequestState === "merged" ||
(changeRequestState !== "open" && inactivity === "stale")))),
})),
),
),
), ),
); );
it.each(truthTable)( it.each(truthTable)(
"override=$settledOverride pr=$changeRequestState inactivity=$inactivity running=$running pending=$pending", "override=$settledOverride running=$running pending=$pending",
({ settledOverride, changeRequestState, activityAt, running, pending, expected }) => { ({ settledOverride, running, pending, expected }) => {
const shell = makeShell({ const shell = makeShell({
settledOverride, settledOverride,
activityAt, activityAt: FRESH,
...(running ? { sessionStatus: "running" as const } : {}), ...(running ? { sessionStatus: "running" as const } : {}),
...(pending === undefined ? {} : { pending }), ...(pending === undefined ? {} : { pending }),
}); });
const changeRequestOptions = expect(effectiveSettled(shell)).toBe(expected);
changeRequestState === undefined
? {}
: { changeRequestState: changeRequestState as ChangeRequestStateLike };
expect(
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: 3,
...changeRequestOptions,
}),
).toBe(expected);
}, },
); );
it("treats closed change requests like merged ones", () => {
const shell = makeShell({ activityAt: null });
expect(
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: null,
changeRequestState: "closed",
}),
).toBe(true);
});
it("settles immediately when a change request merges or closes", () => {
const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
for (const changeRequestState of ["merged", "closed"] as const) {
expect(
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
changeRequestState,
}),
).toBe(true);
}
});
it("can keep a merged change request active", () => {
const recentlyActive = makeShell({ activityAt: "2026-04-09T23:59:59.999Z" });
expect(
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
changeRequestState: "merged",
}),
).toBe(false);
expect(
effectiveSettled(recentlyActive, {
now: NOW,
autoSettleAfterDays: null,
autoSettleOnMerge: false,
changeRequestState: "closed",
}),
).toBe(true);
});
it("never auto-settles a stale thread with an open change request", () => {
const stale = makeShell({ activityAt: STALE });
expect(
effectiveSettled(stale, {
now: NOW,
autoSettleAfterDays: 3,
changeRequestState: "open",
}),
).toBe(false);
// An explicit user settle still wins: open PR only blocks the auto path.
const settled = makeShell({ settledOverride: "settled", activityAt: STALE });
expect(
effectiveSettled(settled, {
now: NOW,
autoSettleAfterDays: 3,
changeRequestState: "open",
}),
).toBe(true);
});
it("keeps an explicitly un-settled merged-PR thread active", () => {
const shell = makeShell({
settledOverride: "active",
activityAt: "2026-04-09T23:59:59.999Z",
});
expect(
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: null,
changeRequestState: "merged",
}),
).toBe(false);
});
it("never settles a starting session, even with a settled override", () => { it("never settles a starting session, even with a settled override", () => {
const shell = makeShell({ const shell = makeShell({
settledOverride: "settled", settledOverride: "settled",
activityAt: STALE, activityAt: STALE,
sessionStatus: "starting", sessionStatus: "starting",
}); });
expect( expect(effectiveSettled(shell)).toBe(false);
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: 3,
changeRequestState: "merged",
}),
).toBe(false);
}); });
it("keeps a new turn active from queued through starting and running", () => { it("keeps a settled thread active while a newer user message awaits the server's unsettle", () => {
const requestedAt = "2026-04-09T12:00:00.000Z"; // Between a new user message landing and the server's auto-unsettle
const transitionNow = "2026-04-09T12:00:30.000Z"; // projection arriving, the shell still carries the stale override. A
const base = makeShell({ // message newer than settledAt marks that window; one older than
settledOverride: null, // settledAt was already adjudicated by the settle itself.
activityAt: STALE, const base = makeShell({ settledOverride: "settled", activityAt: null });
}); const reactivated = {
const queued: OrchestrationThreadShell = {
...base, ...base,
latestUserMessageAt: requestedAt, settledAt: "2026-04-09T12:00:00.000Z",
latestTurn: null, latestUserMessageAt: "2026-04-09T12:00:30.000Z",
session: null,
}; };
const starting: OrchestrationThreadShell = { expect(effectiveSettled(reactivated)).toBe(false);
...queued,
session: { const adjudicated = {
threadId: queued.id, ...base,
status: "starting", settledAt: "2026-04-09T12:00:30.000Z",
providerName: "Codex", latestUserMessageAt: "2026-04-09T12:00:00.000Z",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: requestedAt,
},
}; };
const running: OrchestrationThreadShell = { expect(effectiveSettled(adjudicated)).toBe(true);
...starting,
session: {
...starting.session!,
status: "running",
activeTurnId: TurnId.make("turn-new"),
},
};
for (const shell of [queued, starting, running]) {
expect(
effectiveSettled(shell, {
now: transitionNow,
autoSettleAfterDays: 3,
changeRequestState: "merged",
}),
).toBe(false);
}
});
it("uses a strict inactivity boundary and honors a null threshold", () => {
const boundary = makeShell({
activityAt: "2026-04-07T00:00:00.000Z",
});
const stale = makeShell({ activityAt: STALE });
expect(effectiveSettled(boundary, { now: NOW, autoSettleAfterDays: 3 })).toBe(false);
expect(effectiveSettled(stale, { now: NOW, autoSettleAfterDays: null })).toBe(false);
}); });
}); });
@@ -412,53 +238,10 @@ describe("canSettle", () => {
}; };
const justAfter = "2026-04-09T12:00:30.000Z"; const justAfter = "2026-04-09T12:00:30.000Z";
expect(canSettle(queued, { now: justAfter })).toBe(false); expect(canSettle(queued, { now: justAfter })).toBe(false);
// effectiveSettled must agree: queued work never auto-settles either,
// even with a merged PR.
expect(
effectiveSettled(queued, {
now: justAfter,
autoSettleAfterDays: 3,
changeRequestState: "merged",
}),
).toBe(false);
// Past the window the message is a failed/stale start: settleable again. // Past the window the message is a failed/stale start: settleable again.
expect(canSettle(queued, { now: NOW })).toBe(true); expect(canSettle(queued, { now: NOW })).toBe(true);
}); });
it("lets a server-accepted settle overrule the clock-derived queued blocker", () => {
// The settle action ran with wall-clock `now` (past the grace window);
// the list partition re-evaluates with a minute-floored `now` that is
// still INSIDE the window. settledAt >= message time proves the server
// already adjudicated this exact message, so the row must not snap back
// to active until the coarser clock catches up.
const messageAt = "2026-04-09T12:00:00.000Z";
const flooredNow = "2026-04-09T12:01:00.000Z";
const base = makeShell({ settledOverride: "settled", activityAt: null });
const settledAfterMessage = {
...base,
latestUserMessageAt: messageAt,
settledAt: "2026-04-09T12:02:10.000Z",
};
expect(hasQueuedTurnStart(settledAfterMessage, { now: flooredNow })).toBe(true);
expect(effectiveSettled(settledAfterMessage, { now: flooredNow, autoSettleAfterDays: 3 })).toBe(
true,
);
// A message NEWER than settledAt is genuinely new work: still blocked
// until the server's auto-unsettle lands.
const messageAfterSettle = {
...base,
latestUserMessageAt: "2026-04-09T12:03:00.000Z",
settledAt: "2026-04-09T12:02:10.000Z",
};
expect(
effectiveSettled(messageAfterSettle, {
now: "2026-04-09T12:03:30.000Z",
autoSettleAfterDays: 3,
}),
).toBe(false);
});
it("agrees with effectiveSettled's blockers for explicitly settled shells", () => { it("agrees with effectiveSettled's blockers for explicitly settled shells", () => {
// Anything canSettle rejects must render as active even when the user // Anything canSettle rejects must render as active even when the user
// settled it earlier. // settled it earlier.
@@ -468,6 +251,6 @@ describe("canSettle", () => {
pending: "user-input", pending: "user-input",
}); });
expect(canSettle(blocked, { now: NOW })).toBe(false); expect(canSettle(blocked, { now: NOW })).toBe(false);
expect(effectiveSettled(blocked, { now: NOW, autoSettleAfterDays: 3 })).toBe(false); expect(effectiveSettled(blocked)).toBe(false);
}); });
}); });
@@ -3,7 +3,13 @@ import type { OrchestrationThreadShell } from "@t3tools/contracts";
export type ChangeRequestStateLike = "open" | "closed" | "merged"; export type ChangeRequestStateLike = "open" | "closed" | "merged";
/** Returns whether the change request state settles the thread immediately. */ /**
* Whether a PR state settles its thread under the configured merge rule
* (thread environment's threadAutoSettleOnMerge; closed always settles).
* Display-only on clients — the server sweep applies the same rule when it
* actually settles; the UI uses this to suppress signals (like the Woke
* pill) on work that is about to be adjudicated done.
*/
export function changeRequestAutoSettles( export function changeRequestAutoSettles(
state: ChangeRequestStateLike | null | undefined, state: ChangeRequestStateLike | null | undefined,
autoSettleOnMerge = true, autoSettleOnMerge = true,
@@ -13,28 +19,6 @@ export function changeRequestAutoSettles(
const DAY_MS = 24 * 60 * 60 * 1_000; const DAY_MS = 24 * 60 * 60 * 1_000;
export function threadLastActivityAt(shell: OrchestrationThreadShell): string | null {
const candidates = [
shell.latestUserMessageAt,
shell.latestTurn?.requestedAt,
shell.latestTurn?.startedAt,
shell.latestTurn?.completedAt,
];
let latest: string | null = null;
let latestTimestamp = Number.NEGATIVE_INFINITY;
for (const candidate of candidates) {
if (candidate === null || candidate === undefined) continue;
const timestamp = Date.parse(candidate);
if (timestamp > latestTimestamp) {
latest = candidate;
latestTimestamp = timestamp;
}
}
return latest;
}
/** /**
* A queued turn start lives for at most this long: session adoption takes * A queued turn start lives for at most this long: session adoption takes
* seconds, so a user message still unadopted after the grace window is a * seconds, so a user message still unadopted after the grace window is a
@@ -224,69 +208,39 @@ export function threadWokeAt(
} }
/** /**
* Settled resolution over the server-backed settled lifecycle. Activity * Settled resolution: the server is the single author of settled state.
* blockers (pending approval/user-input, a live session, an unadjudicated * The override IS the classification — the server settles (user command or
* queued turn) are checked first and hold a thread active regardless of any * the auto-settle sweep: inactivity window, merged/closed PR) and un-settles
* override. Past the blockers, the explicit user override (thread.settle / * on real activity (user message, session start, approval/user-input
* thread.unsettle commands, projected into settledOverride + settledAt) * request), so clients never re-derive it. The client-side guards only
* wins in both directions; without one, a thread can auto-settle on a * cover the beat between activity landing and the server's auto-unsettle
* merged PR, always settles on a closed PR, or settles on inactivity past * event arriving: blocked-on-you work and live sessions stay visible under
* the window. An open PR blocks the inactivity path entirely. The server * a stale override, and a user message newer than settledAt (a queued turn
* un-settles on real activity (user message, session start, approval/ * start the server has not adjudicated yet) keeps the thread active. All
* user-input request), so an override never goes stale silently. * guards compare shell data to shell data — no wall clock.
*/ */
export function effectiveSettled( export function effectiveSettled(
shell: OrchestrationThreadShell, shell: Pick<
options: { OrchestrationThreadShell,
readonly now: string; | "settledOverride"
readonly autoSettleAfterDays: number | null; | "settledAt"
readonly autoSettleOnMerge?: boolean; | "latestUserMessageAt"
readonly changeRequestState?: ChangeRequestStateLike | null; | "hasPendingApprovals"
}, | "hasPendingUserInput"
| "session"
>,
): boolean { ): boolean {
// Blocked work must remain visible even when a user explicitly settled it.
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false; if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
if (shell.session?.status === "starting" || shell.session?.status === "running") return false; if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
if (hasQueuedTurnStart(shell, { now: options.now })) { if (shell.settledOverride !== "settled") return false;
// The queued-turn blocker alone is forgivable: it is clock-derived, and if (
// list callers pass a coarser `now` than the settle action used. When shell.settledAt !== null &&
// the server already adjudicated the queued message by accepting a shell.latestUserMessageAt !== null &&
// settle after it (settledAt stamps server accept time), trust that Date.parse(shell.latestUserMessageAt) > Date.parse(shell.settledAt)
// ruling — otherwise a settle near the grace boundary leaves the row ) {
// pinned active until the caller's clock ticks over. A message NEWER return false;
// than settledAt is genuinely new work and keeps the block until the
// server's auto-unsettle lands.
const serverAdjudicated =
shell.settledOverride === "settled" &&
shell.settledAt !== null &&
shell.latestUserMessageAt !== null &&
Date.parse(shell.settledAt) >= Date.parse(shell.latestUserMessageAt);
if (!serverAdjudicated) return false;
} }
if (shell.settledOverride === "settled") return true; return true;
// "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)) {
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.autoSettleAfterDays === null) return false;
const lastActivityAt = threadLastActivityAt(shell);
if (lastActivityAt === null) return false;
// threadLastActivityAt only returns candidates whose Date.parse beat
// -Infinity, so this parse is a real number; a malformed `now` yields NaN,
// the comparison is false, and the thread stays active (never a surprise
// auto-settle on bad input).
return (
Date.parse(lastActivityAt) < Date.parse(options.now) - options.autoSettleAfterDays * DAY_MS
);
} }
const HOUR_MS = 60 * 60 * 1_000; const HOUR_MS = 60 * 60 * 1_000;
@@ -6,7 +6,7 @@ import * as Order from "effect/Order";
export interface ThreadSortInput { export interface ThreadSortInput {
readonly createdAt: string; readonly createdAt: string;
readonly updatedAt: string; readonly updatedAt: string;
readonly latestUserMessageAt?: string | null; readonly latestUserMessageAt?: string | null | undefined;
readonly messages?: ReadonlyArray<{ readonly messages?: ReadonlyArray<{
readonly createdAt: string; readonly createdAt: string;
readonly role: string; readonly role: string;
+5
View File
@@ -55,6 +55,11 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
pre-settlement servers, so clients treat missing as unsupported and pre-settlement servers, so clients treat missing as unsupported and
never send the commands under version skew. */ never send the commands under version skew. */
threadSettlement: Schema.optionalKey(Schema.Boolean), threadSettlement: Schema.optionalKey(Schema.Boolean),
/** Server derives settled state itself (auto-settle sweep + the
threadAutoSettleAfterDays server setting). Clients gate the auto-settle
settings UI on this; settled classification itself is just
settledOverride and needs no gate. */
threadAutoSettle: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.snooze / thread.unsnooze commands. Same /** Server understands thread.snooze / thread.unsnooze commands. Same
version-skew contract as threadSettlement. */ version-skew contract as threadSettlement. */
threadSnooze: Schema.optionalKey(Schema.Boolean), threadSnooze: Schema.optionalKey(Schema.Boolean),
+7
View File
@@ -397,6 +397,11 @@ export const OrchestrationThread = Schema.Struct({
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)), pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
// Pending-only state. Optional so older servers remain compatible. // Pending-only state. Optional so older servers remain compatible.
titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)), titleRegeneration: Schema.optional(Schema.NullOr(ThreadTitleRegeneration)),
// Newest user-message time, survives the capped/unhydrated `messages`
// array: the engine's command read model boots threads with no message
// bodies, and the decider needs this stamp for settle invariants and the
// settledAt derivation. Optional for pre-existing payloads.
latestUserMessageAt: Schema.optional(Schema.NullOr(IsoDateTime)),
deletedAt: Schema.NullOr(IsoDateTime), deletedAt: Schema.NullOr(IsoDateTime),
messages: Schema.Array(OrchestrationMessage), messages: Schema.Array(OrchestrationMessage),
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe( proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
@@ -688,6 +693,8 @@ const ThreadSettleCommand = Schema.Struct({
type: Schema.Literal("thread.settle"), type: Schema.Literal("thread.settle"),
commandId: CommandId, commandId: CommandId,
threadId: ThreadId, threadId: ThreadId,
// No settledAt here: the decider derives it from the thread's last
// activity (see decider.ts), so callers cannot forge shelf ordering.
}); });
const ThreadUnsettleCommand = Schema.Struct({ const ThreadUnsettleCommand = Schema.Struct({
+14 -9
View File
@@ -68,11 +68,9 @@ describe("ClientSettings environment identification", () => {
}); });
describe("ClientSettings sidebar", () => { describe("ClientSettings sidebar", () => {
it("defaults to the current sidebar with automatic merge and inactivity settling", () => { it("defaults to the current sidebar", () => {
const settings = decodeClientSettings({}); const settings = decodeClientSettings({});
expect(settings.legacySidebarEnabled).toBe(false); expect(settings.legacySidebarEnabled).toBe(false);
expect(settings.sidebarAutoSettleAfterDays).toBe(3);
expect(settings.sidebarAutoSettleOnMerge).toBe(true);
}); });
it("drops the retired sidebar v2 beta keys, resetting everyone to the default", () => { it("drops the retired sidebar v2 beta keys, resetting everyone to the default", () => {
@@ -91,25 +89,32 @@ describe("ClientSettings sidebar", () => {
true, true,
); );
}); });
});
describe("ServerSettings thread auto-settle", () => {
it("defaults to a three-day auto-settle threshold", () => {
expect(decodeServerSettings({}).threadAutoSettleAfterDays).toBe(3);
});
it("allows auto-settle by inactivity to be disabled", () => { it("allows auto-settle by inactivity to be disabled", () => {
expect( expect(
decodeClientSettings({ sidebarAutoSettleAfterDays: null }).sidebarAutoSettleAfterDays, decodeServerSettings({ threadAutoSettleAfterDays: null }).threadAutoSettleAfterDays,
).toBeNull(); ).toBeNull();
}); });
it("allows auto-settle on merge to be disabled", () => { it("defaults auto-settle on merge to enabled and allows disabling it", () => {
expect(decodeClientSettings({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge).toBe( expect(decodeServerSettings({}).threadAutoSettleOnMerge).toBe(true);
expect(decodeServerSettings({ threadAutoSettleOnMerge: false }).threadAutoSettleOnMerge).toBe(
false, false,
); );
expect( expect(
decodeClientSettingsPatch({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge, decodeServerSettingsPatch({ threadAutoSettleOnMerge: false }).threadAutoSettleOnMerge,
).toBe(false); ).toBe(false);
}); });
it.each([-1, 0, 91])("rejects an auto-settle threshold outside 1..90: %s", (value) => { it.each([-1, 0, 91])("rejects an auto-settle threshold outside 1..90: %s", (value) => {
expect(() => decodeClientSettings({ sidebarAutoSettleAfterDays: value })).toThrow(); expect(() => decodeServerSettings({ threadAutoSettleAfterDays: value })).toThrow();
expect(() => decodeClientSettingsPatch({ sidebarAutoSettleAfterDays: value })).toThrow(); expect(() => decodeServerSettingsPatch({ threadAutoSettleAfterDays: value })).toThrow();
}); });
}); });
+19 -13
View File
@@ -43,16 +43,16 @@ export const SidebarThreadPreviewCount = Schema.Int.check(
); );
export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type; export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6; export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1; export const MIN_THREAD_AUTO_SETTLE_AFTER_DAYS = 1;
export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90; export const MAX_THREAD_AUTO_SETTLE_AFTER_DAYS = 90;
export const SidebarAutoSettleAfterDays = Schema.Number.check( export const ThreadAutoSettleAfterDays = Schema.Number.check(
Schema.isBetween({ Schema.isBetween({
minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, minimum: MIN_THREAD_AUTO_SETTLE_AFTER_DAYS,
maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, maximum: MAX_THREAD_AUTO_SETTLE_AFTER_DAYS,
}), }),
); );
export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type; export type ThreadAutoSettleAfterDays = typeof ThreadAutoSettleAfterDays.Type;
export const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3; export const DEFAULT_THREAD_AUTO_SETTLE_AFTER_DAYS: ThreadAutoSettleAfterDays = 3;
export const MIN_GLASS_OPACITY = 40; export const MIN_GLASS_OPACITY = 40;
export const MAX_GLASS_OPACITY = 100; export const MAX_GLASS_OPACITY = 100;
export const GlassOpacity = Schema.Int.check( export const GlassOpacity = Schema.Int.check(
@@ -177,10 +177,6 @@ export const ClientSettingsSchema = Schema.Struct({
// old keys, so everyone, including prior beta opt-outs, resets to the new // old keys, so everyone, including prior beta opt-outs, resets to the new
// default sidebar. // default sidebar.
legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
),
sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
), ),
@@ -545,6 +541,16 @@ export const ServerSettings = Schema.Struct({
enableLegacyTokenStreaming: Schema.Boolean.pipe( enableLegacyTokenStreaming: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)), Schema.withDecodingDefault(Effect.succeed(false)),
), ),
// Days of inactivity before the server auto-settles a thread; null disables
// auto-settle. Server-side (not a client setting) so every client sees the
// same settled shelf — the server derives settled state, clients only read it.
threadAutoSettleAfterDays: Schema.NullOr(ThreadAutoSettleAfterDays).pipe(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_THREAD_AUTO_SETTLE_AFTER_DAYS)),
),
// Whether a merged PR settles its thread immediately. Closed PRs always
// settle. Server-side for the same reason as the window above (was the
// client-side sidebarAutoSettleOnMerge).
threadAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
backgroundActivity: BackgroundActivitySettings, backgroundActivity: BackgroundActivitySettings,
// Legacy flat fields retained for old settings files and old clients. New // Legacy flat fields retained for old settings files and old clients. New
@@ -708,6 +714,8 @@ const OpenCodeSettingsPatch = Schema.Struct({
export const ServerSettingsPatch = Schema.Struct({ export const ServerSettingsPatch = Schema.Struct({
// Server settings // Server settings
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean), enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
threadAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(ThreadAutoSettleAfterDays)),
threadAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean), enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey( backgroundActivity: Schema.optionalKey(
Schema.Struct({ Schema.Struct({
@@ -793,8 +801,6 @@ export const ClientSettingsPatch = Schema.Struct({
), ),
planModeEnabled: Schema.optionalKey(Schema.Boolean), planModeEnabled: Schema.optionalKey(Schema.Boolean),
legacySidebarEnabled: Schema.optionalKey(Schema.Boolean), legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
sidebarProjectGroupingOverrides: Schema.optionalKey( sidebarProjectGroupingOverrides: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode), Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
+3 -3
View File
@@ -189,9 +189,9 @@ it.layer(NodeServices.layer)("external package dependency closure", (it) => {
if (!manifest) continue; if (!manifest) continue;
const declared = { const declared = {
...(manifest.dependencies ?? {}), ...manifest.dependencies,
...(manifest.optionalDependencies ?? {}), ...manifest.optionalDependencies,
...(manifest.peerDependencies ?? {}), ...manifest.peerDependencies,
}; };
for (const dependency of Object.keys(declared)) { for (const dependency of Object.keys(declared)) {
if (!isRuntimeExternal(dependency)) { if (!isRuntimeExternal(dependency)) {