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,
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
+9 -40
View File
@@ -207,9 +207,6 @@ export function HomeScreen(props: HomeScreenProps) {
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | 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
// the partition works directly off live shells — no snapshot merging or
// 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(
(thread: EnvironmentThreadShell) => {
void props.onSettleThread(thread);
@@ -569,9 +546,8 @@ export function HomeScreen(props: HomeScreenProps) {
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now is quantized to the minute and ticks so the inactivity auto-settle
// boundary is actually crossed while the app stays open (mirrors web);
// without a clock dependency the partition memoizes a frozen "now".
// Minute clock for snooze preset/wake labels only — settled state is
// server-authored, so the partition itself no longer needs a ticking "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// 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
@@ -580,14 +556,13 @@ export function HomeScreen(props: HomeScreenProps) {
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
// by the time the beta is switched on.
setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id);
}, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as
// settled (the user could neither un-settle nor pin them).
// Servers without the settlement capability reject the settle/unsettle
// commands, so their rows hide the actions.
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
@@ -667,21 +642,14 @@ export function HomeScreen(props: HomeScreenProps) {
projectRefs: v2ScopedProjectGroup === null ? null : v2ScopedProjectGroup.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: null,
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
@@ -742,7 +710,10 @@ export function HomeScreen(props: HomeScreenProps) {
settledShelfHeaderIndex: threadListV2Layout.settledShelfHeaderIndex,
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(
@@ -850,7 +821,6 @@ export function HomeScreen(props: HomeScreenProps) {
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onMovePinnedThread={handleMovePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
}
@@ -860,7 +830,6 @@ export function HomeScreen(props: HomeScreenProps) {
);
},
[
handleChangeRequestState,
handleDeleteThread,
arrangedPinnedKeys,
handleMovePinnedThread,
@@ -522,21 +522,12 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
// Settle policy (inactivity window, settle-on-merge) is server-authored;
// mobile reads settledOverride and offers no local knobs. Configure it
// from the web/desktop settings until mobile grows server-settings UI.
return (
<SettingsSection title="General">
<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" />
</SettingsSection>
);
@@ -217,9 +217,6 @@ function ThreadNavigationSidebarPane(
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -417,26 +414,6 @@ function ThreadNavigationSidebarPane(
// Thread List v2 (beta) support — same model as the compact Home list
// (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
// context changes so environment/search flips never inherit a deep page.
const [settledVisibleCount, setSettledVisibleCount] = useState(
@@ -456,9 +433,8 @@ function ThreadNavigationSidebarPane(
const toggleSnoozedShelf = useCallback(() => setSnoozedShelfExpanded((value) => !value), []);
const [settledShelfExpanded, setSettledShelfExpanded] = useState(true);
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
// now ticks per minute so the inactivity auto-settle boundary is actually
// crossed while the pane stays open; without a clock dependency the
// partition memoizes a frozen "now".
// Minute clock for snooze preset/wake labels only — settled state is
// server-authored, so the partition itself no longer needs a ticking "now".
const [nowMinute, setNowMinute] = useState(() => new Date().toISOString().slice(0, 16));
// 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
@@ -467,14 +443,13 @@ function ThreadNavigationSidebarPane(
useEffect(() => {
if (!threadListV2Enabled) return;
// Refresh immediately on enable: the mount-time value can be hours old
// by the time the beta is switched on, which would misclassify the
// inactivity auto-settle boundary until the first tick.
// by the time the beta is switched on.
setNowMinute(new Date().toISOString().slice(0, 16));
const id = setInterval(() => setNowMinute(new Date().toISOString().slice(0, 16)), 60_000);
return () => clearInterval(id);
}, [threadListV2Enabled]);
// Threads on servers without the settlement capability never classify as
// settled (the user could neither un-settle nor pin them).
// Servers without the settlement capability reject the settle/unsettle
// commands, so their rows hide the actions.
const serverConfigs = useAtomValue(environmentServerConfigsAtom);
const settlementEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
@@ -551,21 +526,14 @@ function ThreadNavigationSidebarPane(
projectRefs: selectedProjectScope === null ? null : selectedProjectScope.projectRefs,
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
now: `${nowMinute}:00.000Z`,
snoozeNow: new Date().toISOString(),
snoozedShelfExpanded,
settledShelfExpanded,
selectedThreadKey: props.selectedThreadKey ?? null,
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
settledShelfExpanded,
@@ -988,7 +956,6 @@ function ThreadNavigationSidebarPane(
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1113,7 +1080,6 @@ function ThreadNavigationSidebarPane(
arrangedPinnedKeys,
confirmDeletePendingTask,
confirmDeleteThread,
handleChangeRequestState,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
@@ -369,12 +369,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state for the partition's merge and close
rules. Mirrors web's onChangeRequestState. */
readonly onChangeRequestState?: (
threadKey: string,
state: "open" | "closed" | "merged" | null,
) => void;
readonly projectCwd?: string | null;
readonly searchMatch?: EnvironmentThreadSearchMatch;
readonly searchQuery?: string;
@@ -397,17 +391,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onPinThread,
onUnpinThread,
onMovePinnedThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
const pinnedRow = props.pinned === true;
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 drawerColor = useThemeColor("--color-drawer");
@@ -8,7 +8,6 @@ import {
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -263,21 +262,8 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("keeps a merged thread active when auto-settle on merge is off", () => {
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
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);
});
// The merge rule (threadAutoSettleOnMerge) is applied by the SERVER sweep,
// not the client partition — see apps/server autoSettle.test.ts.
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -298,7 +284,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
// Same createdAt → static sort tiebreaks by id; the point is the woken
@@ -322,7 +308,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
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.
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, now: NOW });
const whileSnoozed = buildThreadListV2Items({ ...snoozedInput, snoozeNow: NOW });
expect(whileSnoozed.items.map((item) => item.thread.id)).toEqual(["active"]);
expect(whileSnoozed.snoozedCount).toBe(1);
// 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[0]?.pinned).toBe(true);
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({
threads: [
makeThread({
@@ -378,8 +367,6 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
// Minute-floored partition clock vs precise snooze clock.
now: "2026-06-02T00:01:00.000Z",
snoozeNow: "2026-06-02T00:01:07.500Z",
});
@@ -413,7 +400,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
snoozedShelfExpanded: true,
});
@@ -440,7 +427,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
expect(layout.items).toEqual([]);
@@ -466,7 +453,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
selectedThreadKey: `${environmentId}:open`,
});
@@ -488,7 +475,7 @@ describe("buildThreadListV2Items", () => {
environmentId: null,
searchQuery: "",
snoozeEnvironmentIds: new Set(),
now: NOW,
snoozeNow: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["snoozed"]);
@@ -514,7 +501,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
@@ -540,7 +527,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
settledShelfExpanded: false,
});
@@ -567,7 +554,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
settledShelfExpanded: false,
selectedThreadKey: `${environmentId}:selected`,
});
@@ -594,7 +581,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["newer-created", "older-created"]);
@@ -614,7 +601,7 @@ describe("buildThreadListV2Items", () => {
],
environmentId: null,
searchQuery: "login",
now: NOW,
snoozeNow: NOW,
});
expect(items.map((item) => [item.thread.id, item.variant])).toEqual([
@@ -638,7 +625,7 @@ describe("buildThreadListV2Items", () => {
threadId: thread.id,
}),
]),
now: NOW,
snoozeNow: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["content-match"]);
@@ -658,7 +645,7 @@ describe("buildThreadListV2Items", () => {
environmentId: null,
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["included"]);
@@ -681,7 +668,7 @@ describe("buildThreadListV2Items", () => {
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
],
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
expect(items.map((item) => item.thread.id)).toEqual(["local", "remote"]);
@@ -697,18 +684,9 @@ describe("buildThreadListV2Items settled paging", () => {
id: ThreadId.make(`settled-${index}`),
title: `Settled ${index}`,
settledOverride: "settled",
settledAt: NOW,
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
// A turn adopted the message (same requestedAt): without it the
// 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,
},
// Auto-settles backdate settledAt to the last activity, so the
// shelf orders by when the work ended.
settledAt: `2026-06-01T0${index}:10:00.000Z`,
}),
),
];
@@ -718,7 +696,7 @@ describe("buildThreadListV2Items settled paging", () => {
environmentId: null,
searchQuery: "",
settledLimit: 2,
now: NOW,
snoozeNow: NOW,
});
expect(layout.hiddenSettledCount).toBe(2);
@@ -772,7 +750,7 @@ describe("buildThreadListV2ListItems", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
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" })],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
const items = buildThreadListV2ListItems({
items: activeOnly.items,
@@ -849,7 +827,7 @@ describe("buildThreadListV2ListItems", () => {
],
environmentId: null,
searchQuery: "",
now: NOW,
snoozeNow: NOW,
});
const items = buildThreadListV2ListItems({
items: snoozedLayout.items,
@@ -306,8 +306,9 @@ export function buildThreadListV2ListItems(input: {
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. Mobile stores these
* auto-settle preferences per device.
* the settled recency tail, matching the web v2 list. Settled is
* server-authored (settledOverride), so the partition needs no clock, no
* auto-settle window, and no PR state.
*/
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -318,25 +319,13 @@ export function buildThreadListV2Items(input: {
}> | null;
readonly searchQuery: string;
readonly matchedThreadKeys?: ReadonlySet<string>;
/** Per-row PR state reported up by visible rows ("env:threadId" keys). */
readonly changeRequestStateByKey?: ReadonlyMap<string, "open" | "closed" | "merged">;
/** Environments whose server supports thread.settle/unsettle. Threads on
other environments never classify as settled — the user could neither
un-settle nor pin them. Absent = no gating (tests). */
readonly settlementEnvironmentIds?: ReadonlySet<EnvironmentId>;
/** Environments whose server supports thread.snooze/unsnooze. Same
contract as settlementEnvironmentIds. */
/** Environments whose server supports thread.snooze/unsnooze. Threads on
other environments never classify as snoozed. Absent = no gating
(tests). */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
readonly autoSettleOnMerge?: boolean;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
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`. */
/** Second-precise clock for snooze classification; injectable for tests. */
readonly snoozeNow?: string;
/** Expands the snoozed shelf into rows. Collapsed is the default. */
readonly snoozedShelfExpanded?: boolean;
@@ -346,10 +335,7 @@ export function buildThreadListV2Items(input: {
a split-view detail can never lose its navigation row. */
readonly selectedThreadKey?: string | null;
}): ThreadListV2Layout {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
const snoozeNow = input.snoozeNow ?? new Date().toISOString();
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
@@ -379,10 +365,7 @@ export function buildThreadListV2Items(input: {
) {
continue;
}
const supportsSettlement = input.settlementEnvironmentIds?.has(thread.environmentId) ?? true;
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
@@ -399,20 +382,14 @@ export function buildThreadListV2Items(input: {
continue;
}
// 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) {
pinned.push(thread);
continue;
}
if (
supportsSettlement &&
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
// Settled is server-authored (settledOverride); servers that predate
// settlement never emit it, so their threads simply stay active.
if (effectiveSettled(thread)) {
settled.push(thread);
} else {
active.push(thread);
@@ -431,10 +408,13 @@ export function buildThreadListV2Items(input: {
: orderedSnoozed.filter(
(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(
(left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
firstValidTimestampMs(right.settledAt, right.updatedAt) -
firstValidTimestampMs(left.settledAt, left.updatedAt),
);
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const pagedSettled =
@@ -26,7 +26,6 @@ export interface Preferences {
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
readonly autoSettleOnMerge?: boolean;
/**
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* 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[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
autoSettleOnMerge?: boolean;
legacyThreadListEnabled?: boolean;
planModeEnabled?: boolean;
} = {};
@@ -127,9 +125,6 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.autoSettleOnMerge === "boolean") {
preferences.autoSettleOnMerge = parsed.autoSettleOnMerge;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
}
@@ -62,6 +62,7 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts";
import { ThreadAutoSettleReactor } from "../src/orchestration/ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -342,6 +343,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
@@ -369,6 +371,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
Layer.provideMerge(
Layer.succeed(ThreadAutoSettleReactor, {
start: () => Effect.void,
sweepOnce: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => Effect.void,
@@ -148,6 +148,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
pullRequests: true,
threadSettlement: true,
threadAutoSettle: true,
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
@@ -316,6 +316,7 @@ describe("CheckpointReactor", () => {
});
const vcsStatusBroadcasterLayer = Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: (cwd: string) =>
Effect.sync(() => {
options?.gitStatusRefreshCalls?.push(cwd);
@@ -8,6 +8,7 @@ import { afterEach, describe, expect, it } from "vite-plus/test";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadAutoSettleReactor } from "../ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
@@ -55,6 +56,15 @@ describe("OrchestrationReactor", () => {
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadAutoSettleReactor, {
start: () => {
started.push("thread-auto-settle-reactor");
return Effect.void;
},
sweepOnce: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => {
@@ -84,6 +94,7 @@ describe("OrchestrationReactor", () => {
"provider-runtime-ingestion",
"provider-command-reactor",
"checkpoint-reactor",
"thread-auto-settle-reactor",
"thread-deletion-reactor",
"agent-awareness-relay",
]);
@@ -8,6 +8,7 @@ import {
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ThreadAutoSettleReactor } from "../ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "../../relay/AgentAwarenessRelay.ts";
@@ -15,6 +16,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
const providerCommandReactor = yield* ProviderCommandReactor;
const checkpointReactor = yield* CheckpointReactor;
const threadAutoSettleReactor = yield* ThreadAutoSettleReactor;
const threadDeletionReactor = yield* ThreadDeletionReactor;
const agentAwarenessRelay = yield* AgentAwarenessRelay.AgentAwarenessRelay;
@@ -22,6 +24,7 @@ export const makeOrchestrationReactor = Effect.gen(function* () {
yield* providerRuntimeIngestion.start();
yield* providerCommandReactor.start();
yield* checkpointReactor.start();
yield* threadAutoSettleReactor.start();
yield* threadDeletionReactor.start();
yield* agentAwarenessRelay.start();
});
@@ -326,6 +326,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
latestUserMessageAt: "2026-02-24T00:00:04.000Z",
deletedAt: null,
messages: [
{
@@ -1578,6 +1578,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
latestUserMessageAt: row.latestUserMessageAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -1785,6 +1786,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
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,
messages: [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
@@ -2466,6 +2470,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
latestUserMessageAt: threadRow.value.latestUserMessageAt,
deletedAt: null,
messages: messageRows.map((row) => {
const message = {
@@ -400,6 +400,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
peekStatus: () => Effect.succeed(null),
refreshLocalStatus: () =>
Effect.die("refreshLocalStatus should not be called in this test"),
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 { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as TestClock from "effect/testing/TestClock";
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", () =>
Effect.gen(function* () {
for (const status of ["starting", "running"] as const) {
@@ -261,8 +306,9 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {
updatedAt: createdAt,
});
// The decider's clock is the Effect test clock, pinned to the epoch:
// timestamps here are relative to 1970-01-01T00:00:00.000Z.
// Pin the shared test clock explicitly (other tests in this layer move
// it): timestamps here are relative to 1970-01-01T00:00:00.000Z.
yield* TestClock.setTime(0);
// Within the grace window: genuinely queued, settle rejected.
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
* 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(
thread: {
readonly latestUserMessageAt?: string | null | undefined;
readonly messages: ReadonlyArray<{ readonly role: string; readonly createdAt: string }>;
readonly latestTurn: {
readonly requestedAt: string;
@@ -116,11 +143,7 @@ function threadHasQueuedTurnStart(
},
occurredAt: string,
): boolean {
const latestUserMessageAtMs = thread.messages.reduce(
(latest, message) =>
message.role === "user" ? Math.max(latest, Date.parse(message.createdAt)) : latest,
Number.NEGATIVE_INFINITY,
);
const latestUserMessageAtMs = threadLatestUserMessageAtMs(thread);
const latestTurnAtMs =
thread.latestTurn === null
? 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(
input: Pick<OrchestrationCommand, "commandId"> & {
readonly aggregateKind: OrchestrationEvent["aggregateKind"];
@@ -502,7 +568,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
type: "thread.settled" as const,
payload: {
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
// so duplicate settles neither rewind nor churn ordering. A fresh
// settle stamps the command time.
@@ -93,6 +93,7 @@ describe("orchestration projector", () => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -701,6 +702,10 @@ describe("orchestration projector", () => {
).toEqual([{ id: "activity-1", turnId: "turn-1" }]);
expect(thread?.checkpoints.map((checkpoint) => checkpoint.checkpointTurnCount)).toEqual([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 () => {
@@ -305,6 +305,7 @@ export function projectEvent(
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
latestUserMessageAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -540,10 +541,22 @@ export function projectEvent(
: [...thread.messages, message];
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 {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
messages: cappedMessages,
latestUserMessageAt,
updatedAt: event.occurredAt,
}),
};
@@ -756,6 +769,18 @@ export function projectEvent(
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 {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -764,6 +789,7 @@ export function projectEvent(
proposedPlans,
activities,
latestTurn,
latestUserMessageAt,
updatedAt: event.occurredAt,
}),
};
@@ -655,8 +655,8 @@ function matchesFilters(
viewer: string,
): boolean {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
@@ -649,8 +649,8 @@ export const make = Effect.gen(function* () {
viewer: string,
): boolean => {
if (filters === undefined) return true;
const labels = item.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(item.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || item.isDraft === (filters.draft === "only")) &&
// 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 { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
import * as ThreadAutoSettleReactor from "./orchestration/ThreadAutoSettleReactor.ts";
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
@@ -242,6 +243,7 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(ProviderRuntimeIngestionLive),
Layer.provideMerge(ProviderCommandReactorLive),
Layer.provideMerge(CheckpointReactorLive),
Layer.provideMerge(ThreadAutoSettleReactor.layer),
Layer.provideMerge(ThreadDeletionReactorLive),
Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
Layer.provideMerge(RuntimeReceiptBusLive),
@@ -159,6 +159,10 @@ export class VcsStatusBroadcaster extends Context.Service<
readonly getStatus: (
input: VcsStatusInput,
) => 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: (
cwd: string,
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
@@ -339,6 +343,17 @@ export const make = Effect.gen(function* () {
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")(
function* (cwd: string) {
yield* workflow.invalidateLocalStatus(cwd);
@@ -587,6 +602,7 @@ export const make = Effect.gen(function* () {
return VcsStatusBroadcaster.of({
getStatus,
peekStatus,
refreshLocalStatus,
refreshStatus,
streamStatus,
+9 -25
View File
@@ -187,7 +187,6 @@ import {
useClientSettingsHydrated,
useEnvironmentSettings,
} from "../hooks/useSettings";
import { useNowMinute } from "../hooks/useNowMinute";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { getTerminalFocusOwner } from "../lib/terminalFocus";
@@ -274,9 +273,9 @@ import {
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
DRAFT_HERO_TRANSITION_DURATION_MS,
@@ -4105,11 +4104,14 @@ function ChatViewContent(props: ChatViewProps) {
[activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
);
// Settled state of the open thread, resolved exactly like the sidebar
// partition (same shell, same capability gate, same PR auto-settle input)
// so the banner and the sidebar row never disagree.
// partition (same shell, same override read) so the banner and the sidebar
// row never disagree.
const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);
const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge);
// PR state feeds the Woke suppression only (finished work needs no wake-up
// 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({
threadBranch: activeThread?.branch ?? null,
gitStatus: gitStatusQuery.data ?? null,
@@ -4122,9 +4124,7 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadPr, openThreadPullRequest]);
const pullRequestSurfaceAvailable =
supportsPullRequests && activeThreadPr !== null && threadRepository !== null;
const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;
const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;
const nowMinute = useNowMinute();
const snoozeNow = new Date().toISOString();
const activeThreadSnoozed =
activeThreadShell !== null &&
@@ -4181,22 +4181,7 @@ function ChatViewContent(props: ChatViewProps) {
activeThreadWokeAt,
autoSettleOnMerge,
]);
const activeThreadSettled = useMemo(() => {
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 activeThreadSettled = activeThreadShell !== null && effectiveSettled(activeThreadShell);
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
reportFailure: false,
});
@@ -6185,7 +6170,6 @@ function ChatViewContent(props: ChatViewProps) {
{...(routeKind === "draft" && draftId ? { draftId } : {})}
activeThreadTitle={activeThread.title}
isServerThread={isServerThread}
changeRequestState={activeThreadPr?.state ?? null}
activeProjectName={activeProject?.title}
activeProjectCwd={activeProject?.workspaceRoot ?? null}
activeProjectFaviconPath={activeProject?.faviconPath ?? null}
@@ -166,7 +166,7 @@ export type BuildThreadActionItemsThread = Pick<
| "worktreePath"
> & {
updatedAt: string;
latestUserMessageAt?: string | null;
latestUserMessageAt?: string | null | undefined;
};
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"]);
});
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([
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: "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"]);
});
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"]);
expect(sorted.map((thread) => thread.id)).toEqual(["legacy-recent", "explicit", "legacy-old"]);
});
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));
}
type SettledTimestampInput = Pick<
SidebarThreadSummary,
"settledAt" | "latestUserMessageAt" | "latestTurn" | "updatedAt"
>;
type SettledTimestampInput = Pick<SidebarThreadSummary, "settledAt" | "updatedAt">;
/** The timestamp a settled row sorts and labels by: settledAt when stamped
(explicit settles), otherwise last activity — the same candidates
threadLastActivityAt feeds the auto-settle window (user message plus all
latestTurn stamps), so a thread whose last activity was a turn completion
doesn't sort by an older message time. updatedAt is the final net. */
/** The timestamp a settled row sorts and labels by. The server stamps
settledAt on every settle, derived from the thread's last recorded
activity, so it directly reads "when the work ended". updatedAt is the
net for malformed data. */
export function resolveSettledTimestamp(thread: SettledTimestampInput): string | null {
const settledAt = firstValidTimestamp(thread.settledAt);
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);
return firstValidTimestamp(thread.settledAt) ?? firstValidTimestamp(thread.updatedAt);
}
// 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 { useCopyToClipboard } from "../hooks/useCopyToClipboard";
import { useLocalStorage } from "../hooks/useLocalStorage";
import { useNowMinute } from "../hooks/useNowMinute";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
@@ -711,11 +710,9 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
}) {
const {
isRenaming,
onChangeRequestState,
onCancelRename,
onCommitRename,
onContextMenu,
@@ -858,11 +855,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
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 providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
@@ -1619,8 +1611,6 @@ export default function Sidebar() {
const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
@@ -1813,37 +1803,13 @@ export default function Sidebar() {
[projectGroups],
);
// now is quantized to the minute so effectiveSettled memoization doesn't
// churn on every render; auto-settle thresholds are day-granular anyway.
const nowMinute = useNowMinute();
// Snooze wake times are second-precise, so classifying with the quantized
// minute would hold a woken thread on the shelf for up to a minute. The
// 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.
// Snooze wake times are second-precise. The 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. (Settled needs no clock at all: it is
// server-authored via settledOverride.)
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
// making the header width depend on the number or length of project names.
const [projectScopeKey, setProjectScopeKey] = useState<string | null>(null);
@@ -1931,11 +1897,9 @@ export default function Sidebar() {
settledThreads,
snoozeNow,
} = useMemo(() => {
const now = `${nowMinute}:00.000Z`;
// Snooze classification uses a REAL clock, not the quantized minute:
// wake times are second-precise and a woken thread must not linger on
// the shelf for the rest of the minute. snoozeWakeTick re-runs this
// memo exactly at the next wake boundary.
// Snooze classification uses a REAL clock: wake times are second-precise
// and a woken thread must not linger on the shelf. snoozeWakeTick re-runs
// this memo exactly at the next wake boundary.
void snoozeWakeTick;
const preciseNow = new Date().toISOString();
const visible = threads.filter(
@@ -1949,16 +1913,8 @@ export default function Sidebar() {
const snoozed: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
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 =
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"
// temporarily suspends "keep on top". The pin survives underneath —
// 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.)
} else if (thread.pinnedAt != null) {
pinned.push(thread);
} else if (
supportsSettlement &&
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
// Settled is server-authored (settledOverride): the server sweeps
// quiet threads and merged/closed PRs, so the partition needs no
// clock, no auto-settle window, and no PR state. Servers that
// predate settlement never emit the override, so their threads
// simply stay active.
} else if (effectiveSettled(thread)) {
settled.push(thread);
} else {
active.push(thread);
@@ -2013,16 +1966,7 @@ export default function Sidebar() {
settledThreads: sortSettledThreadsForSidebar(settled),
snoozeNow: preciseNow,
};
}, [
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestStateByKey,
nowMinute,
scopedProjectKeys,
serverConfigs,
snoozeWakeTick,
threads,
]);
}, [scopedProjectKeys, serverConfigs, snoozeWakeTick, threads]);
const threadSearchInputRef = useRef<HTMLInputElement>(null);
const [threadSearchQuery, setThreadSearchQuery] = useState("");
@@ -3561,7 +3505,10 @@ export default function Sidebar() {
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSettlement === true
}
autoSettleOnMerge={autoSettleOnMerge}
autoSettleOnMerge={
serverConfigs.get(thread.environmentId)?.settings
.threadAutoSettleOnMerge !== false
}
snoozeSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSnooze === true
@@ -3619,7 +3566,6 @@ export default function Sidebar() {
onUnsnooze={attemptUnsnooze}
onUnpin={attemptUnpin}
onAcknowledgeWoke={acknowledgeWoke}
onChangeRequestState={handleChangeRequestState}
/>
);
};
@@ -10,7 +10,6 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { ChangeRequestStateLike } from "@t3tools/client-runtime/state/thread-settled";
import { ChevronDownIcon } from "lucide-react";
import {
memo,
@@ -51,8 +50,6 @@ interface ChatHeaderProps {
activeThreadTitle: string;
/** Drafts have no server thread yet, so the title carries no action menu. */
isServerThread: boolean;
/** PR state feeding the settled classification, resolved by ChatView. */
changeRequestState: ChangeRequestStateLike | null;
activeProjectName: string | undefined;
activeProjectCwd: string | null;
activeProjectFaviconPath: string | null;
@@ -113,7 +110,6 @@ export const ChatHeader = memo(function ChatHeader({
draftId,
activeThreadTitle,
isServerThread,
changeRequestState,
activeProjectName,
activeProjectCwd,
activeProjectFaviconPath,
@@ -191,7 +187,6 @@ export const ChatHeader = memo(function ChatHeader({
const { openMenu } = useThreadActionMenu({
threadRef: isServerThread ? activeThreadRef : null,
projectCwd: activeProjectCwd,
changeRequestState,
onStartRename: startRename,
});
const titleButtonRef = useRef<HTMLButtonElement | null>(null);
@@ -311,8 +311,8 @@ export function matchesPullRequestFilters(
filters: PullRequestListFilters,
viewer?: string | null,
): boolean {
const labels = entry.labels.map((label) => label.name.trim().toLowerCase());
const holds = (label: string) => labels.includes(label.trim().toLowerCase());
const labels = new Set(entry.labels.map((label) => label.name.trim().toLowerCase()));
const holds = (label: string) => labels.has(label.trim().toLowerCase());
return (
(filters.draft === undefined || entry.isDraft === (filters.draft === "only")) &&
(filters.review === undefined ||
@@ -185,10 +185,10 @@ export function pullRequestChecksState(
checks: ReadonlyArray<PullRequestCheck>,
): PullRequestChecksState | null {
if (checks.length === 0) return null;
const statuses = checks.map((check) => check.status);
if (statuses.includes("failure") || statuses.includes("cancelled")) return "failing";
if (statuses.includes("pending")) return "pending";
return statuses.includes("success") ? "passing" : null;
const statuses = new Set(checks.map((check) => check.status));
if (statuses.has("failure") || statuses.has("cancelled")) return "failing";
if (statuses.has("pending")) return "pending";
return statuses.has("success") ? "passing" : null;
}
export function PullRequestActorAvatar({
@@ -24,13 +24,13 @@ import {
MAX_GLASS_OPACITY,
MAX_INTERFACE_FONT_SIZE,
MAX_PROMPT_FONT_SIZE,
MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MAX_THREAD_AUTO_SETTLE_AFTER_DAYS,
MAX_TERMINAL_FONT_SIZE,
MIN_CODE_FONT_SIZE,
MIN_GLASS_OPACITY,
MIN_INTERFACE_FONT_SIZE,
MIN_PROMPT_FONT_SIZE,
MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
MIN_THREAD_AUTO_SETTLE_AFTER_DAYS,
MIN_TERMINAL_FONT_SIZE,
} from "@t3tools/contracts/settings";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
@@ -76,7 +76,11 @@ import {
} from "../../providerInstances";
import { ensureLocalApi, readLocalApi } from "../../localApi";
import { isMacPlatform } from "../../lib/utils";
import { primaryServerObservabilityAtom, primaryServerProvidersAtom } from "../../state/server";
import {
primaryServerConfigAtom,
primaryServerObservabilityAtom,
primaryServerProvidersAtom,
} from "../../state/server";
import { useProjects } from "../../state/entities";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { formatRelativeTimeLabel } from "../../timestampFormat";
@@ -489,11 +493,10 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode
? ["Project Grouping"]
: []),
...(settings.sidebarAutoSettleAfterDays !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays
...(settings.threadAutoSettleAfterDays !== DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays
? ["Auto-settle inactive threads"]
: []),
...(settings.sidebarAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge
...(settings.threadAutoSettleOnMerge !== DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge
? ["Auto-settle merged threads"]
: []),
...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []),
@@ -549,8 +552,8 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.glassOpacity,
settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks,
settings.sidebarAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge,
settings.threadAutoSettleAfterDays,
settings.threadAutoSettleOnMerge,
settings.sidebarProjectGroupingMode,
settings.sidebarThreadPreviewCount,
settings.timestampFormat,
@@ -631,8 +634,8 @@ export function useSettingsRestore(onRestored?: () => void) {
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays,
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
threadAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleAfterDays,
threadAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
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({
value,
@@ -1603,35 +1606,42 @@ function AutoSettleDaysInput({
value: number;
onCommit: (days: number) => void;
}) {
// Local draft so the field can be emptied mid-edit; the setting only moves
// on valid input and snaps back to the persisted value on blur.
// Local draft; commits only when editing FINISHES (blur or Enter), never
// 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));
useEffect(() => {
setDraft(String(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 (
<Input
type="number"
min={MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
max={MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS}
min={MIN_THREAD_AUTO_SETTLE_AFTER_DAYS}
max={MAX_THREAD_AUTO_SETTLE_AFTER_DAYS}
className="w-full sm:w-24"
value={draft}
onChange={(event) => {
setDraft(event.target.value);
// Number(), not parseInt: "3.5" must be rejected (not truncated to a
// committed 3 while the field shows 3.5) — commit only when the
// 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);
}
onChange={(event) => setDraft(event.target.value)}
onBlur={commitDraft}
onKeyDown={(event) => {
if (event.key === "Enter") commitDraft();
}}
onBlur={() => setDraft(String(value))}
aria-label="Days of inactivity before auto-settle"
/>
);
@@ -1750,6 +1760,10 @@ export function GeneralSettingsPanel() {
);
const observability = useAtomValue(primaryServerObservabilityAtom);
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({
localTracingEnabled: observability?.localTracingEnabled ?? false,
otlpTracesEnabled: observability?.otlpTracesEnabled ?? false,
@@ -1833,69 +1847,72 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("auto-settle-merged-threads")}
description="Settle a thread when its pull request merges. Closed pull requests still settle automatically."
resetAction={
settings.sidebarAutoSettleOnMerge !==
DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge ? (
<SettingResetButton
label="auto-settle on merge"
onClick={() =>
{supportsAutoSettle ? (
<SettingsRow
{...searchableSetting("auto-settle-merged-threads")}
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."
resetAction={
settings.threadAutoSettleOnMerge !==
DEFAULT_UNIFIED_SETTINGS.threadAutoSettleOnMerge ? (
<SettingResetButton
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({
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
threadAutoSettleAfterDays: checked ? AUTO_SETTLE_DEFAULT_DAYS : null,
})
}
aria-label="Auto-settle inactive threads"
/>
) : null
}
control={
<Switch
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 ? (
}
/>
) : null}
{supportsAutoSettle && settings.threadAutoSettleAfterDays !== null ? (
<SettingsRow
title="Days of inactivity before auto-settle"
description="Any new activity un-settles a thread automatically."
control={
<AutoSettleDaysInput
value={settings.sidebarAutoSettleAfterDays}
onCommit={(days) => updateSettings({ sidebarAutoSettleAfterDays: days })}
value={settings.threadAutoSettleAfterDays}
onCommit={(days) => updateSettings({ threadAutoSettleAfterDays: days })}
/>
}
/>
+5 -20
View File
@@ -9,7 +9,6 @@ import {
canSnooze,
effectiveSettled,
effectiveSnoozed,
type ChangeRequestStateLike,
} from "@t3tools/client-runtime/state/thread-settled";
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import { useCallback } from "react";
@@ -60,11 +59,9 @@ export function useThreadActionMenu(input: {
readonly threadRef: ScopedThreadRef | null;
/** Fallback for "Copy path" when the thread has no worktree. */
readonly projectCwd: string | null;
/** PR state feeding auto-settle classification, as resolved by the caller. */
readonly changeRequestState: ChangeRequestStateLike | null;
readonly onStartRename: () => void;
}) {
const { threadRef, projectCwd, changeRequestState, onStartRename } = input;
const { threadRef, projectCwd, onStartRename } = input;
const {
settleThread,
unsettleThread,
@@ -79,8 +76,6 @@ export function useThreadActionMenu(input: {
});
const handleNewThread = useNewThreadHandler();
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 timestampFormat = useClientSettings((s) => s.timestampFormat);
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
@@ -125,17 +120,10 @@ export function useThreadActionMenu(input: {
const items = buildThreadActionMenuItems({
branch: thread.branch ?? null,
isPinned: thread.pinnedAt != null,
isSettled:
supports.settlement &&
effectiveSettled(thread, {
// Minute-quantized like useNowMinute, so this classification
// 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,
}),
// Settled is server-authored (settledOverride); the same override
// read as the sidebar partition and ChatView's parked banner, so
// the three surfaces can never disagree.
isSettled: effectiveSettled(thread),
isSnoozed: supports.snooze && effectiveSnoozed(thread, { now: now.toISOString() }),
canSnoozeNow: canSnooze(thread, { now: now.toISOString() }),
isRegeneratingTitle,
@@ -285,9 +273,6 @@ export function useThreadActionMenu(input: {
})();
},
[
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
confirmThreadDelete,
copyBranchToClipboard,
copyPathToClipboard,
@@ -12,8 +12,6 @@ import {
changeRequestAutoSettles,
effectiveSettled,
hasQueuedTurnStart,
threadLastActivityAt,
type ChangeRequestStateLike,
} from "./threadSettled.ts";
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", () => {
// 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 changeRequestStates = [undefined, "open", "merged"] as const;
const inactivityCases = [
["fresh", FRESH],
["stale", STALE],
["no-activity", null],
] as const;
const runningCases = [false, true] as const;
const pendingCases = [undefined, "approval", "user-input"] as const;
const truthTable = overrideCases.flatMap((settledOverride) =>
changeRequestStates.flatMap((changeRequestState) =>
inactivityCases.flatMap(([inactivity, activityAt]) =>
runningCases.flatMap((running) =>
pendingCases.map((pending) => ({
settledOverride,
changeRequestState,
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")))),
})),
),
),
runningCases.flatMap((running) =>
pendingCases.map((pending) => ({
settledOverride,
running,
pending,
expected: pending === undefined && !running && settledOverride === "settled",
})),
),
);
it.each(truthTable)(
"override=$settledOverride pr=$changeRequestState inactivity=$inactivity running=$running pending=$pending",
({ settledOverride, changeRequestState, activityAt, running, pending, expected }) => {
"override=$settledOverride running=$running pending=$pending",
({ settledOverride, running, pending, expected }) => {
const shell = makeShell({
settledOverride,
activityAt,
activityAt: FRESH,
...(running ? { sessionStatus: "running" as const } : {}),
...(pending === undefined ? {} : { pending }),
});
const changeRequestOptions =
changeRequestState === undefined
? {}
: { changeRequestState: changeRequestState as ChangeRequestStateLike };
expect(
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: 3,
...changeRequestOptions,
}),
).toBe(expected);
expect(effectiveSettled(shell)).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", () => {
const shell = makeShell({
settledOverride: "settled",
activityAt: STALE,
sessionStatus: "starting",
});
expect(
effectiveSettled(shell, {
now: NOW,
autoSettleAfterDays: 3,
changeRequestState: "merged",
}),
).toBe(false);
expect(effectiveSettled(shell)).toBe(false);
});
it("keeps a new turn active from queued through starting and running", () => {
const requestedAt = "2026-04-09T12:00:00.000Z";
const transitionNow = "2026-04-09T12:00:30.000Z";
const base = makeShell({
settledOverride: null,
activityAt: STALE,
});
const queued: OrchestrationThreadShell = {
it("keeps a settled thread active while a newer user message awaits the server's unsettle", () => {
// Between a new user message landing and the server's auto-unsettle
// projection arriving, the shell still carries the stale override. A
// message newer than settledAt marks that window; one older than
// settledAt was already adjudicated by the settle itself.
const base = makeShell({ settledOverride: "settled", activityAt: null });
const reactivated = {
...base,
latestUserMessageAt: requestedAt,
latestTurn: null,
session: null,
settledAt: "2026-04-09T12:00:00.000Z",
latestUserMessageAt: "2026-04-09T12:00:30.000Z",
};
const starting: OrchestrationThreadShell = {
...queued,
session: {
threadId: queued.id,
status: "starting",
providerName: "Codex",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: requestedAt,
},
expect(effectiveSettled(reactivated)).toBe(false);
const adjudicated = {
...base,
settledAt: "2026-04-09T12:00:30.000Z",
latestUserMessageAt: "2026-04-09T12:00:00.000Z",
};
const running: OrchestrationThreadShell = {
...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);
expect(effectiveSettled(adjudicated)).toBe(true);
});
});
@@ -412,53 +238,10 @@ describe("canSettle", () => {
};
const justAfter = "2026-04-09T12:00:30.000Z";
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.
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", () => {
// Anything canSettle rejects must render as active even when the user
// settled it earlier.
@@ -468,6 +251,6 @@ describe("canSettle", () => {
pending: "user-input",
});
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";
/** 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(
state: ChangeRequestStateLike | null | undefined,
autoSettleOnMerge = true,
@@ -13,28 +19,6 @@ export function changeRequestAutoSettles(
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
* 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
* blockers (pending approval/user-input, a live session, an unadjudicated
* queued turn) are checked first and hold a thread active regardless of any
* override. Past the blockers, the explicit user override (thread.settle /
* thread.unsettle commands, projected into settledOverride + settledAt)
* wins in both directions; without one, a thread can auto-settle on a
* merged PR, always settles on a closed PR, or settles on inactivity past
* the window. An open PR blocks the inactivity path entirely. The server
* un-settles on real activity (user message, session start, approval/
* user-input request), so an override never goes stale silently.
* Settled resolution: the server is the single author of settled state.
* The override IS the classification — the server settles (user command or
* the auto-settle sweep: inactivity window, merged/closed PR) and un-settles
* on real activity (user message, session start, approval/user-input
* request), so clients never re-derive it. The client-side guards only
* cover the beat between activity landing and the server's auto-unsettle
* event arriving: blocked-on-you work and live sessions stay visible under
* a stale override, and a user message newer than settledAt (a queued turn
* start the server has not adjudicated yet) keeps the thread active. All
* guards compare shell data to shell data — no wall clock.
*/
export function effectiveSettled(
shell: OrchestrationThreadShell,
options: {
readonly now: string;
readonly autoSettleAfterDays: number | null;
readonly autoSettleOnMerge?: boolean;
readonly changeRequestState?: ChangeRequestStateLike | null;
},
shell: Pick<
OrchestrationThreadShell,
| "settledOverride"
| "settledAt"
| "latestUserMessageAt"
| "hasPendingApprovals"
| "hasPendingUserInput"
| "session"
>,
): boolean {
// Blocked work must remain visible even when a user explicitly settled it.
if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
if (shell.session?.status === "starting" || shell.session?.status === "running") return false;
if (hasQueuedTurnStart(shell, { now: options.now })) {
// The queued-turn blocker alone is forgivable: it is clock-derived, and
// list callers pass a coarser `now` than the settle action used. When
// the server already adjudicated the queued message by accepting a
// settle after it (settledAt stamps server accept time), trust that
// ruling — otherwise a settle near the grace boundary leaves the row
// pinned active until the caller's clock ticks over. A message NEWER
// 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 false;
if (
shell.settledAt !== null &&
shell.latestUserMessageAt !== null &&
Date.parse(shell.latestUserMessageAt) > Date.parse(shell.settledAt)
) {
return false;
}
if (shell.settledOverride === "settled") 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
);
return true;
}
const HOUR_MS = 60 * 60 * 1_000;
@@ -6,7 +6,7 @@ import * as Order from "effect/Order";
export interface ThreadSortInput {
readonly createdAt: string;
readonly updatedAt: string;
readonly latestUserMessageAt?: string | null;
readonly latestUserMessageAt?: string | null | undefined;
readonly messages?: ReadonlyArray<{
readonly createdAt: 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
never send the commands under version skew. */
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
version-skew contract as threadSettlement. */
threadSnooze: Schema.optionalKey(Schema.Boolean),
+7
View File
@@ -397,6 +397,11 @@ export const OrchestrationThread = Schema.Struct({
pinOrderKey: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
// Pending-only state. Optional so older servers remain compatible.
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),
messages: Schema.Array(OrchestrationMessage),
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(
@@ -688,6 +693,8 @@ const ThreadSettleCommand = Schema.Struct({
type: Schema.Literal("thread.settle"),
commandId: CommandId,
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({
+14 -9
View File
@@ -68,11 +68,9 @@ describe("ClientSettings environment identification", () => {
});
describe("ClientSettings sidebar", () => {
it("defaults to the current sidebar with automatic merge and inactivity settling", () => {
it("defaults to the current sidebar", () => {
const settings = decodeClientSettings({});
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", () => {
@@ -91,25 +89,32 @@ describe("ClientSettings sidebar", () => {
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", () => {
expect(
decodeClientSettings({ sidebarAutoSettleAfterDays: null }).sidebarAutoSettleAfterDays,
decodeServerSettings({ threadAutoSettleAfterDays: null }).threadAutoSettleAfterDays,
).toBeNull();
});
it("allows auto-settle on merge to be disabled", () => {
expect(decodeClientSettings({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge).toBe(
it("defaults auto-settle on merge to enabled and allows disabling it", () => {
expect(decodeServerSettings({}).threadAutoSettleOnMerge).toBe(true);
expect(decodeServerSettings({ threadAutoSettleOnMerge: false }).threadAutoSettleOnMerge).toBe(
false,
);
expect(
decodeClientSettingsPatch({ sidebarAutoSettleOnMerge: false }).sidebarAutoSettleOnMerge,
decodeServerSettingsPatch({ threadAutoSettleOnMerge: false }).threadAutoSettleOnMerge,
).toBe(false);
});
it.each([-1, 0, 91])("rejects an auto-settle threshold outside 1..90: %s", (value) => {
expect(() => decodeClientSettings({ sidebarAutoSettleAfterDays: value })).toThrow();
expect(() => decodeClientSettingsPatch({ sidebarAutoSettleAfterDays: value })).toThrow();
expect(() => decodeServerSettings({ threadAutoSettleAfterDays: 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 const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;
export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;
export const SidebarAutoSettleAfterDays = Schema.Number.check(
export const MIN_THREAD_AUTO_SETTLE_AFTER_DAYS = 1;
export const MAX_THREAD_AUTO_SETTLE_AFTER_DAYS = 90;
export const ThreadAutoSettleAfterDays = Schema.Number.check(
Schema.isBetween({
minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
minimum: MIN_THREAD_AUTO_SETTLE_AFTER_DAYS,
maximum: MAX_THREAD_AUTO_SETTLE_AFTER_DAYS,
}),
);
export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
export const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;
export type ThreadAutoSettleAfterDays = typeof ThreadAutoSettleAfterDays.Type;
export const DEFAULT_THREAD_AUTO_SETTLE_AFTER_DAYS: ThreadAutoSettleAfterDays = 3;
export const MIN_GLASS_OPACITY = 40;
export const MAX_GLASS_OPACITY = 100;
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
// default sidebar.
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(
Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
),
@@ -545,6 +541,16 @@ export const ServerSettings = Schema.Struct({
enableLegacyTokenStreaming: Schema.Boolean.pipe(
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))),
backgroundActivity: BackgroundActivitySettings,
// 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({
// Server settings
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
threadAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(ThreadAutoSettleAfterDays)),
threadAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
backgroundActivity: Schema.optionalKey(
Schema.Struct({
@@ -793,8 +801,6 @@ export const ClientSettingsPatch = Schema.Struct({
),
planModeEnabled: Schema.optionalKey(Schema.Boolean),
legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
sidebarProjectGroupingOverrides: Schema.optionalKey(
Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
+3 -3
View File
@@ -189,9 +189,9 @@ it.layer(NodeServices.layer)("external package dependency closure", (it) => {
if (!manifest) continue;
const declared = {
...(manifest.dependencies ?? {}),
...(manifest.optionalDependencies ?? {}),
...(manifest.peerDependencies ?? {}),
...manifest.dependencies,
...manifest.optionalDependencies,
...manifest.peerDependencies,
};
for (const dependency of Object.keys(declared)) {
if (!isRuntimeExternal(dependency)) {