From 8d0e0986ea069bbb0ff751425529ca1f702d9112 Mon Sep 17 00:00:00 2001 From: Benjamin Coriou Date: Tue, 27 Oct 2026 19:05:18 +0100 Subject: [PATCH 1/3] feat(fork): stagger snoozes that would wake together Snoozing several threads to the same preset made every one of them return at once. A preset that collides with a wake time another thread still holds now lands five minutes later, up to an hour, and a multiple selection staggers in order. One client-side allocator serves web and mobile, so menu labels show the slot that is actually dispatched. Custom times, snoozes until a usage limit resets, and undo keep the exact time. `snoozeSpacingMinutes` is an environment setting (default 5, 0 turns it off) synced across environments, with rows in General on web and Thread behavior on mobile. --- apps/mobile/src/features/home/HomeScreen.tsx | 8 + .../settings/SettingsThreadsRouteScreen.tsx | 56 +++- .../src/features/settings/settings-search.ts | 2 + .../threads/ThreadNavigationSidebar.tsx | 8 + .../features/threads/thread-list-v2-items.tsx | 27 +- .../src/features/threads/threadListV2.test.ts | 24 ++ .../src/features/threads/threadListV2.ts | 20 +- .../src/features/threads/useThreadListV2.ts | 17 +- .../src/state/thread-list-environments.ts | 7 +- .../web/src/components/Sidebar.snooze.test.ts | 42 +++ apps/web/src/components/Sidebar.snooze.ts | 42 ++- apps/web/src/components/Sidebar.tsx | 102 +++++- .../components/settings/SettingsPanels.tsx | 61 +++- .../src/components/settings/settingsSearch.ts | 6 + .../components/sidebar/SidebarThreadRow.tsx | 16 +- .../web/src/hooks/useThreadActionMenu.test.ts | 2 + apps/web/src/hooks/useThreadActionMenu.ts | 17 +- docs/user/thread-sidebar.md | 8 + packages/client-runtime/package.json | 4 + .../src/state/sharedSettings.ts | 2 + .../src/state/snoozeSpacing.test.ts | 301 ++++++++++++++++++ .../client-runtime/src/state/snoozeSpacing.ts | 134 ++++++++ .../client-runtime/src/state/threadSettled.ts | 18 +- packages/contracts/src/settings.ts | 15 + 24 files changed, 874 insertions(+), 65 deletions(-) create mode 100644 apps/web/src/components/Sidebar.snooze.test.ts create mode 100644 packages/client-runtime/src/state/snoozeSpacing.test.ts create mode 100644 packages/client-runtime/src/state/snoozeSpacing.ts diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index e9a71f2c253fc..fe6b96b206267 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -11,6 +11,7 @@ import { } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; +import { DEFAULT_SNOOZE_SPACING_MINUTES } from "@t3tools/contracts/settings"; import { useAtomValue } from "@effect/atom-react"; import { useFocusEffect } from "@react-navigation/native"; import { use, useEffect, useRef, useState, type ComponentProps } from "react"; @@ -443,6 +444,7 @@ export function HomeScreen(props: HomeScreenProps) { pinReorderEnvironmentIds, activeReorderEnvironmentIds, titleRegenerationEnvironmentIds, + snoozeSpacingMinutesByEnvironment, } = listEnvironments; const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId); const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick); @@ -451,6 +453,7 @@ export function HomeScreen(props: HomeScreenProps) { items: threadListV2Items, contentOnlyThreadKeys, olderSettledShelf, + snoozeOccupancy, } = useThreadListV2({ threads: props.threads, pendingTasks: props.pendingTasks, @@ -587,6 +590,11 @@ export function HomeScreen(props: HomeScreenProps) { pinned={item.item.pinned} wokeAt={item.item.wokeAt} snoozePresetMinute={item.snoozePresetMinute ?? ""} + snoozeOccupancy={snoozeOccupancy} + snoozeSpacingMinutes={ + snoozeSpacingMinutesByEnvironment.get(thread.environmentId) ?? + DEFAULT_SNOOZE_SPACING_MINUTES + } snoozeWakeLabelText={item.snoozeWakeLabelText} timeLabel={item.timeLabel} showTrailingDivider={item.showTrailingDivider} diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx index c8f3c4c7d170b..fa4fcf6f6026a 100644 --- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx @@ -10,6 +10,11 @@ import { View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; +import { + MAX_SNOOZE_SPACING_MINUTES, + MIN_SNOOZE_SPACING_MINUTES, +} from "@t3tools/contracts/settings"; +import { NumberField } from "../../components/ui/NumberField"; import { supportsSharedSettingsSync } from "@t3tools/client-runtime/state/shared-settings"; import { AppText as Text } from "../../components/ui/AppText"; import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; @@ -90,6 +95,7 @@ function AutoSettleSettingsRows() { patch: Partial & { autoResumeLimitedThreads?: boolean; snoozeLimitedThreads?: boolean; + snoozeSpacingMinutes?: number; }, ) => { if ( @@ -176,22 +182,40 @@ function AutoSettleSettingsRows() { /> ) : null} {!projectSelected ? ( - - writeToAll({ autoResumeLimitedThreads: value })} - /> - writeToAll({ snoozeLimitedThreads: value })} - /> - + <> + + writeToAll({ autoResumeLimitedThreads: value })} + /> + writeToAll({ snoozeLimitedThreads: value })} + /> + + + + + Space snoozes by + + writeToAll({ snoozeSpacingMinutes: value })} + min={MIN_SNOOZE_SPACING_MINUTES} + max={MAX_SNOOZE_SPACING_MINUTES} + label="Minutes between snoozes" + formatValue={(value) => (value === 0 ? "Off" : `${value} min`)} + /> + + + ) : null} | undefined; readonly providerInstance: ThreadRowProviderInstance | null; @@ -735,12 +742,20 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { snoozable: canSnooze(thread, { now: snoozeGateNow }), snoozed: snoozedRow, }); - const snoozePresets = useMemo( + const snoozeSpacing = useMemo( + () => ({ + occupied: withoutSnoozeOccupant(props.snoozeOccupancy, thread.snoozedUntil), + spacingMinutes: props.snoozeSpacingMinutes, + }), + [props.snoozeOccupancy, props.snoozeSpacingMinutes, thread.snoozedUntil], + ); + const snoozePresets = useMemo(() => { + if (swipeActions.secondary !== "snooze") return [] as const; // oxlint-disable-next-line react/purity -- The memo recomputes on the snoozePresetMinute tick, so preset times refresh every minute. - () => (swipeActions.secondary === "snooze" ? resolveSnoozePresets(new Date()) : ([] as const)), + const now = new Date(); + return resolveThreadListV2SnoozePresets(now, snoozeSpacing); // oxlint-disable-next-line react/memo-dependencies -- The minute tick refreshes relative snooze times while the row remains mounted. - [props.snoozePresetMinute, swipeActions.secondary], - ); + }, [props.snoozePresetMinute, snoozeSpacing, swipeActions.secondary]); const snoozePresetActions = useMemo( () => [ ...snoozePresets.map((preset) => ({ @@ -910,6 +925,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { event: nativeEvent.event, displayedPresets: snoozePresets, now: new Date(), + spacing: snoozeSpacing, }); if (snoozeSelection._tag === "selected") { handleSnooze(snoozeSelection.preset.snoozedUntil); @@ -938,6 +954,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { handleUnsnooze, setCustomSnoozeOpen, snoozePresets, + snoozeSpacing, ], ); const primaryAction = useMemo(() => { diff --git a/apps/mobile/src/features/threads/threadListV2.test.ts b/apps/mobile/src/features/threads/threadListV2.test.ts index de7400ba741ee..9156a340c96b0 100644 --- a/apps/mobile/src/features/threads/threadListV2.test.ts +++ b/apps/mobile/src/features/threads/threadListV2.test.ts @@ -35,6 +35,7 @@ import { buildThreadListV2ListItems, getThreadListV2OrderedSection, resolveThreadListV2SnoozeMenuSelection, + resolveThreadListV2SnoozePresets, resolveThreadListV2Status, resolveThreadListV2WokeAt, sortThreadsForListV2, @@ -74,6 +75,29 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => { ); } }); + + it("dispatches the staggered slot the menu showed", () => { + const selectedAt = new Date(2026, 4, 8, 10, 30); + const spacing = { + occupied: new Map([[selectedAt.getTime() + 60 * 60 * 1_000, 1]]), + spacingMinutes: 5, + }; + const displayedPresets = resolveThreadListV2SnoozePresets(selectedAt, spacing); + const selection = resolveThreadListV2SnoozeMenuSelection({ + event: "snooze:hour", + displayedPresets, + now: selectedAt, + spacing, + }); + + expect(selection._tag).toBe("selected"); + if (selection._tag === "selected") { + expect(selection.preset).toEqual(displayedPresets.find((preset) => preset.id === "hour")); + expect(selection.preset.snoozedUntil).toBe( + new Date(selectedAt.getTime() + 65 * 60 * 1_000).toISOString(), + ); + } + }); }); describe("resolveThreadListV2Status", () => { diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index d72ab913dec35..a595eca15a0a5 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -8,6 +8,10 @@ import { threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +import { + spaceSnoozePresets, + type SnoozeSpacing, +} from "@t3tools/client-runtime/state/snooze-spacing"; import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; import { resolveThreadProviderStack } from "@t3tools/client-runtime/state/models"; import { @@ -72,17 +76,31 @@ export type ThreadListV2Status = | "ready"; export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze"; +export function resolveThreadListV2SnoozePresets( + now: Date, + spacing?: SnoozeSpacing, +): ReadonlyArray { + const presets = resolveSnoozePresets(now); + return spacing === undefined + ? presets + : spaceSnoozePresets(presets, { + occupied: spacing.occupied, + spacingMinutes: spacing.spacingMinutes, + }); +} + export function resolveThreadListV2SnoozeMenuSelection(input: { readonly event: string; readonly displayedPresets: ReadonlyArray; readonly now: Date; + readonly spacing?: SnoozeSpacing; }): | { readonly _tag: "selected"; readonly preset: SnoozePreset } | { readonly _tag: "expired" } | { readonly _tag: "not-snooze" } { if (!input.event.startsWith("snooze:")) return { _tag: "not-snooze" }; - const currentPreset = resolveSnoozePresets(input.now).find( + const currentPreset = resolveThreadListV2SnoozePresets(input.now, input.spacing).find( (candidate) => input.event === `snooze:${candidate.id}`, ); if (currentPreset) return { _tag: "selected", preset: currentPreset }; diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts index 2a6f3504e2f5d..469aaf9411727 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -1,4 +1,6 @@ import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; +import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; +import { selectSnoozeOccupancy } from "@t3tools/client-runtime/state/snooze-spacing"; import type { EnvironmentId } from "@t3tools/contracts"; import { useMemo, useSyncExternalStore } from "react"; @@ -146,6 +148,19 @@ export function useThreadListV2(input: { )) && (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)), ); + // Rows read one occupancy value; keying it on reservations keeps unrelated + // shell updates from re-rendering every row that offers a snooze menu. + const reservationKey = threads + .flatMap((thread) => + effectiveSnoozed(thread, { now: input.now }) ? [thread.snoozedUntil ?? ""] : [], + ) + .sort() + .join("\n"); + const snoozeOccupancy = useMemo( + // oxlint-disable-next-line react/memo-dependencies -- reservations are the only input that changes the result + () => selectSnoozeOccupancy(threads, { now: input.now }), + [reservationKey], + ); const items = buildThreadListV2ListItems({ items: layout.items, pendingTasks, @@ -164,7 +179,7 @@ export function useThreadListV2(input: { moveAvailability, shelfPreferencesLoading: !input.shelfPreferencesLoaded, }); - return { layout, items, contentOnlyThreadKeys, olderSettledShelf }; + return { layout, items, contentOnlyThreadKeys, olderSettledShelf, snoozeOccupancy }; } /** The list's scope per environment: its projects there, or every project. */ diff --git a/apps/mobile/src/state/thread-list-environments.ts b/apps/mobile/src/state/thread-list-environments.ts index 04389802f1a85..3d21b1b7f014b 100644 --- a/apps/mobile/src/state/thread-list-environments.ts +++ b/apps/mobile/src/state/thread-list-environments.ts @@ -36,6 +36,7 @@ function selectEnvironment(config: ServerConfig) { ), machineKind: resolveEnvironmentMachineKind(config), capabilities: config.environment.capabilities, + snoozeSpacingMinutes: config.settings.snoozeSpacingMinutes, }; } @@ -71,9 +72,11 @@ function collectEnvironments(environments: ReadonlyMap(); const activeReorderEnvironmentIds = new Set(); const titleRegenerationEnvironmentIds = new Set(); - for (const [id, { providers, machineKind, capabilities }] of environments) { + const snoozeSpacingMinutesByEnvironment = new Map(); + for (const [id, { providers, machineKind, capabilities, snoozeSpacingMinutes }] of environments) { providersByEnvironmentId.set(id, providers); machineByEnvironmentId.set(id, machineKind); + snoozeSpacingMinutesByEnvironment.set(id, snoozeSpacingMinutes); if (capabilities.threadSettlement === true) settlementEnvironmentIds.add(id); if (capabilities.threadSnooze === true) snoozeEnvironmentIds.add(id); if (capabilities.threadAutoSettleOptOut === true) autoSettleOptOutEnvironmentIds.add(id); @@ -92,6 +95,7 @@ function collectEnvironments(environments: ReadonlyMap (prior.capabilities[key] === true) === (selected.capabilities[key] === true), ); diff --git a/apps/web/src/components/Sidebar.snooze.test.ts b/apps/web/src/components/Sidebar.snooze.test.ts new file mode 100644 index 0000000000000..e97e0e810d97d --- /dev/null +++ b/apps/web/src/components/Sidebar.snooze.test.ts @@ -0,0 +1,42 @@ +// @effect-diagnostics globalDate:off -- Presets are local calendar times. +import { describe, expect, it } from "vite-plus/test"; + +import { formatShortTimestamp } from "../timestampFormat"; +import { resolveSnoozePresets } from "./Sidebar.snooze"; + +const now = new Date(2026, 4, 8, 10, 0); +const tomorrow = resolveSnoozePresets(now, "24-hour").find((preset) => preset.id === "tomorrow")!; +const MINUTE_MS = 60_000; + +describe("resolveSnoozePresets", () => { + it("formats every preset with the user's timestamp format", () => { + for (const preset of resolveSnoozePresets(now, "24-hour")) { + expect(preset.whenLabel.endsWith(formatShortTimestamp(preset.snoozedUntil, "24-hour"))).toBe( + true, + ); + } + }); + + it("labels the staggered slot instead of the base time", () => { + const spaced = resolveSnoozePresets(now, "24-hour", { + occupied: new Map([[Date.parse(tomorrow.snoozedUntil), 1]]), + spacingMinutes: 5, + }); + const shifted = spaced.find((preset) => preset.id === "tomorrow")!; + + expect(Date.parse(shifted.snoozedUntil)).toBe( + Date.parse(tomorrow.snoozedUntil) + 5 * MINUTE_MS, + ); + expect(shifted.whenLabel).toBe(formatShortTimestamp(shifted.snoozedUntil, "24-hour")); + }); + + it("keeps the base time when spacing is off", () => { + const spaced = resolveSnoozePresets(now, "24-hour", { + occupied: new Map([[Date.parse(tomorrow.snoozedUntil), 1]]), + spacingMinutes: 0, + }); + expect(spaced.find((preset) => preset.id === "tomorrow")?.snoozedUntil).toBe( + tomorrow.snoozedUntil, + ); + }); +}); diff --git a/apps/web/src/components/Sidebar.snooze.ts b/apps/web/src/components/Sidebar.snooze.ts index 38595f3a1654d..cfbd749fd91b7 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -1,4 +1,8 @@ import type { TimestampFormat } from "@t3tools/contracts/settings"; +import { + spaceSnoozePresets, + type SnoozeSpacing, +} from "@t3tools/client-runtime/state/snooze-spacing"; import { resolveSnoozePresets as resolveSharedSnoozePresets, snoozeWakeLabel, @@ -13,20 +17,36 @@ function timeOfDayLabel(date: Date, timestampFormat: TimestampFormat): string { return formatShortTimestamp(date.toISOString(), timestampFormat); } +function whenLabel( + preset: SnoozePreset, + snoozedUntil: string, + timestampFormat: TimestampFormat, +): string { + const wake = parseTimestampDate(snoozedUntil); + if (wake === null) return preset.whenLabel; + const time = timeOfDayLabel(wake, timestampFormat); + return preset.id === "next-week" + ? `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}` + : time; +} + export function resolveSnoozePresets( now: Date, timestampFormat: TimestampFormat, + spacing?: SnoozeSpacing, ): ReadonlyArray { - return resolveSharedSnoozePresets(now).map((preset) => { - const wake = parseTimestampDate(preset.snoozedUntil); - if (wake === null) return preset; - const time = timeOfDayLabel(wake, timestampFormat); - return { - ...preset, - whenLabel: - preset.id === "next-week" - ? `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}` - : time, - }; + const presets = resolveSharedSnoozePresets(now); + const spaced = + spacing === undefined + ? presets + : spaceSnoozePresets(presets, { + occupied: spacing.occupied, + spacingMinutes: spacing.spacingMinutes, + formatWhenLabel: (preset, snoozedUntil) => + whenLabel(preset, snoozedUntil, timestampFormat), + }); + return spaced.map((preset) => { + const label = whenLabel(preset, preset.snoozedUntil, timestampFormat); + return label === preset.whenLabel ? preset : { ...preset, whenLabel: label }; }); } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 72f90e27a8e3a..8cea3a69f43a8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -28,6 +28,11 @@ import { effectiveSnoozed, threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; +import { + allocateSnoozeSlots, + selectSnoozeOccupancy, + type SnoozeSpacing, +} from "@t3tools/client-runtime/state/snooze-spacing"; import { createInboxReturnTracker, isThreadWorking, @@ -53,10 +58,12 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + DEFAULT_SERVER_SETTINGS, ProjectId, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; +import { formatShortTimestamp } from "../timestampFormat"; import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; import { ChevronDownIcon, FolderIcon, ListFilterIcon, PlusIcon, SettingsIcon } from "lucide-react"; @@ -1218,6 +1225,43 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const threadByKeyRef = useRef(threadByKey); const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); + // Every environment's shells, unlike the scoped `threads`; snooze slots compare across them. + const quietThreadsRef = useRef(threads); + + // Fork-local: reserve wake times other threads still hold so a batch wakes in sequence. + const snoozeSpacingFor = ( + now: Date, + environmentId: EnvironmentId | null, + exclude?: (thread: EnvironmentThreadShell) => boolean, + ): SnoozeSpacing => { + const at = now.toISOString(); + return { + occupied: selectSnoozeOccupancy( + quietThreadsRef.current, + exclude === undefined ? { now: at } : { now: at, exclude }, + ), + spacingMinutes: + (environmentId === null + ? undefined + : serverConfigs.get(environmentId)?.settings.snoozeSpacingMinutes) ?? + DEFAULT_SERVER_SETTINGS.snoozeSpacingMinutes, + }; + }; + + // Stable so memoized rows do not re-render; the occupancy scan runs when a row opens its menu. + const resolveRowSnoozePresets = useStableCallback((thread: EnvironmentThreadShell) => { + const now = new Date(); + return resolveSnoozePresets( + now, + timestampFormat, + snoozeSpacingFor( + now, + thread.environmentId, + (candidate) => + candidate.id === thread.id && candidate.environmentId === thread.environmentId, + ), + ); + }); const jumpLabelByKey = (() => { const mapping = new Map(); @@ -1562,6 +1606,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threadByKeyRef.current = threadByKey; settledThreadKeysRef.current = settledThreadKeys; snoozedThreadKeysRef.current = snoozedThreadKeys; + quietThreadsRef.current = threads; sectionByThreadKeyRef.current = sectionByThreadKey; }); const startActionSweep = useStableCallback( @@ -2073,7 +2118,16 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const unpinMenuItem = buildBulkUnpinContextMenuItem({ pinnedCount: pinnedSelectedThreads.length, }); - const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); + const selectedThreadKeySet = new Set(selectedThreadKeys); + const snoozeSpacing = snoozeSpacingFor( + selectionNow, + selectedThreads[0]?.environmentId ?? primaryEnvironmentId, + (candidate) => + selectedThreadKeySet.has( + scopedThreadKey(scopeThreadRef(candidate.environmentId, candidate.id)), + ), + ); + const snoozePresets = resolveSnoozePresets(selectionNow, timestampFormat, snoozeSpacing); const clicked = await settlePromise(() => api.contextMenu.show( [ @@ -2145,17 +2199,30 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (clicked.value === "settle" && actionTargets.length === 0) return; if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return; if (clicked.value?.startsWith("snooze:")) { - const preset = - clicked.value === "snooze:custom" - ? await requestCustomSnooze() - : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value); + const custom = clicked.value === "snooze:custom"; + const preset = custom + ? await requestCustomSnooze() + : snoozePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value); if (preset) { + // A custom time is one explicit choice for the whole selection; presets stagger. + const snoozeSlots = custom + ? selectedThreads.map(() => preset.snoozedUntil) + : allocateSnoozeSlots({ + snoozedUntil: preset.snoozedUntil, + count: selectedThreads.length, + occupied: snoozeSpacing.occupied, + spacingMinutes: snoozeSpacing.spacingMinutes, + }); const coSnoozingKeys = new Set(threadKeys); clearSelection(); const outcomes = await Promise.all( - selectedThreads.map(async (thread) => { + selectedThreads.map(async (thread, index) => { const threadRef = scopeThreadRef(thread.environmentId, thread.id); - const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys }); + const outcome = await performSnooze( + threadRef, + { snoozedUntil: snoozeSlots[index] ?? preset.snoozedUntil }, + { coSnoozingKeys }, + ); return { outcome, threadRef }; }), ); @@ -2180,6 +2247,24 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }), ); } + + const firstSlot = snoozeSlots[0]; + const lastSlot = snoozeSlots.at(-1); + if ( + failures.length === 0 && + snoozedThreadRefs.length > 1 && + firstSlot !== undefined && + lastSlot !== undefined && + firstSlot !== lastSlot + ) { + toastManager.add( + stackedThreadToast({ + type: "success", + title: `${snoozedThreadRefs.length} threads snoozed`, + description: `${formatShortTimestamp(firstSlot, timestampFormat)}–${formatShortTimestamp(lastSlot, timestampFormat)}`, + }), + ); + } } return; } @@ -2365,7 +2450,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const isSettled = settledThreadKeysRef.current.has(threadKey); const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); const isPinned = thread.pinnedAt != null; - const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); + const snoozePresets = resolveRowSnoozePresets(thread); const threadProjectGroup = projectGroupsRef.current.find((project) => project.memberProjectRefs.some( @@ -3038,6 +3123,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve EMPTY_PROVIDER_ENTRIES } timestampFormat={timestampFormat} + resolveSnoozePresets={resolveRowSnoozePresets} onThreadClick={handleThreadClick} onThreadActivate={navigateToThread} onStartRename={startThreadRename} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 134e61ef13c3a..431819050034c 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -16,7 +16,9 @@ import { DEFAULT_UNIFIED_SETTINGS, type DiffLayout, MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, + MAX_SNOOZE_SPACING_MINUTES, MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, + MIN_SNOOZE_SPACING_MINUTES, type ResponseStreamingMode, type QuitConfirmationMode, SidebarProjectSortOrder, @@ -471,6 +473,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.snoozeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads ? ["Snooze until limits reset"] : []), + ...(settings.snoozeSpacingMinutes !== DEFAULT_UNIFIED_SETTINGS.snoozeSpacingMinutes + ? ["Space snoozes by"] + : []), ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), ...(settings.persistComposerContextStrip !== DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip @@ -634,6 +639,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, + snoozeSpacingMinutes: DEFAULT_UNIFIED_SETTINGS.snoozeSpacingMinutes, responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, @@ -682,12 +688,18 @@ export function useSettingsRestore(onRestored?: () => void) { const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3; -function AutoSettleDaysInput({ +function NumberSettingInput({ value, + min, + max, + ariaLabel, onCommit, }: { value: number; - onCommit: (days: number) => void; + min: number; + max: number; + ariaLabel: string; + onCommit: (value: number) => void; }) { const [draft, setDraft] = useState(String(value)); const [draftSource, setDraftSource] = useState(value); @@ -700,23 +712,19 @@ function AutoSettleDaysInput({ { setDraft(event.target.value); const parsed = Number(event.target.value); - if ( - Number.isInteger(parsed) && - parsed >= MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS && - parsed <= MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS - ) { + if (Number.isInteger(parsed) && parsed >= min && parsed <= max) { onCommit(parsed); } }} onBlur={() => setDraft(String(value))} - aria-label="Days of inactivity before auto-settle" + aria-label={ariaLabel} /> ); } @@ -990,6 +998,34 @@ export function GeneralSettingsPanel() { } /> + + updateSettings({ + snoozeSpacingMinutes: DEFAULT_UNIFIED_SETTINGS.snoozeSpacingMinutes, + }) + } + /> + ) : null + } + control={ + updateSettings({ snoozeSpacingMinutes: minutes })} + /> + } + /> + updateSettings({ sidebarAutoSettleAfterDays: days })} /> } diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index f5b73dc7fb6c9..50209a8398d19 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -344,6 +344,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["usage quota rate limit reset wake recover continue"], }, + { + id: "snooze-spacing", + title: "Space snoozes by", + to: "/settings/general", + searchTerms: ["stagger spread batch tomorrow minutes wake snooze"], + }, { id: "auto-resume-limited-threads", title: "Resume after usage limits", diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 26f4dd38c601e..44daa029c210d 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -369,11 +369,10 @@ function SnoozeMenuButton(props: { open: boolean; onOpenChange: (open: boolean) => void; onSnooze: (preset: Pick) => void; - timestampFormat: TimestampFormat; + resolvePresets: () => ReadonlyArray; }) { - const { open, onOpenChange, onSnooze, timestampFormat } = props; - // oxlint-disable-next-line react/purity -- Presets are resolved only while the menu is open, so each opening reads a fresh time. - const presets = open ? resolveSnoozePresets(new Date(), timestampFormat) : []; + const { open, onOpenChange, onSnooze, resolvePresets } = props; + const presets = open ? resolvePresets() : []; return ( @@ -541,6 +540,10 @@ type SidebarThreadRowProps = { projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; timestampFormat: TimestampFormat; + /** Fork-local: spreads consecutive snoozes across slots; resolved when the menu opens. */ + resolveSnoozePresets?: + | ((thread: SidebarThreadSummary) => ReadonlyArray) + | undefined; onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; onThreadActivate: (threadRef: ScopedThreadRef) => void; onStartRename: (threadRef: ScopedThreadRef, title: string) => void; @@ -1436,7 +1439,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP open={snoozeMenuOpen} onOpenChange={setSnoozeMenuOpen} onSnooze={handleSnoozePreset} - timestampFormat={props.timestampFormat} + resolvePresets={() => + props.resolveSnoozePresets?.(thread) ?? + resolveSnoozePresets(new Date(), props.timestampFormat) + } /> ) : null} {props.settlementSupported ? ( diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 899cf38ee51bb..30cd9b18419ac 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -63,6 +63,8 @@ vi.mock("../state/entities", () => ({ latestRun: null, }), useProjects: () => [{ id: "project", environmentId: "secondary" }], + useQuietThreadShells: () => [], + useServerConfigs: () => new Map(), })); vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" })); vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } })); diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index 0804fc007e1a6..a1e4f98776eb3 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -8,8 +8,10 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; +import { selectSnoozeOccupancy } from "@t3tools/client-runtime/state/snooze-spacing"; import { AuthOrchestrationOperateScope, + DEFAULT_SERVER_SETTINGS, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -33,6 +35,8 @@ import { readEnvironmentSupportsTitleRegeneration, readThreadShell, useProjects, + useQuietThreadShells, + useServerConfigs, } from "../state/entities"; import { usePrimaryEnvironmentId } from "../state/environments"; import { readLocalApi } from "../localApi"; @@ -67,6 +71,8 @@ export function useThreadActionMenu(input: { const { threadRef, projectCwd, onStartRename, canShareWithGuest } = input; const router = useRouter(); const projects = useProjects(); + const quietThreads = useQuietThreadShells(); + const serverConfigs = useServerConfigs(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({ @@ -129,7 +135,16 @@ export function useThreadActionMenu(input: { titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId), }; const isRegeneratingTitle = thread.titleRegeneration != null; - const snoozePresets = resolveSnoozePresets(now, timestampFormat); + const snoozePresets = resolveSnoozePresets(now, timestampFormat, { + occupied: selectSnoozeOccupancy(quietThreads, { + now: now.toISOString(), + exclude: (candidate) => + candidate.id === thread.id && candidate.environmentId === thread.environmentId, + }), + spacingMinutes: + serverConfigs.get(thread.environmentId)?.settings.snoozeSpacingMinutes ?? + DEFAULT_SERVER_SETTINGS.snoozeSpacingMinutes, + }); const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), branch: thread.branch ?? null, diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 45e568efd3fb8..7c87acfabec8a 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -262,6 +262,14 @@ Choose **Snooze → Custom…** from a thread's menu to pick a date and time in local time zone, or a duration in minutes, hours, or days. Durations start when you confirm; one day means 24 hours. On web and desktop, you can also snooze several selected threads together. Choose **Wake thread** to bring a thread back early. + +Presets spread out instead of waking a batch at once: if another snoozed thread +already holds the wake time a preset would pick, the next snooze lands 5 minutes +later, and so on up to an hour. The menu shows the time each preset will actually +use, and a multiple selection staggers in order. Custom times, snoozes until a +usage limit resets, and undo keep the exact time you chose. Change the spacing or +turn it off with **Space snoozes by** in **Settings → General** on web and +desktop, or **Settings → Thread behavior** on mobile. A snoozed thread keeps working and stays hidden until its wake time, even while its agent wakes itself for background work. It comes back early only when it needs an approval or answer from you, when a run fails, or when you send it a message. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index ac2b5e5b2bd1b..2fc7a7218a57a 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -343,6 +343,10 @@ "types": "./src/state/threadSettled.ts", "default": "./src/state/threadSettled.ts" }, + "./state/snooze-spacing": { + "types": "./src/state/snoozeSpacing.ts", + "default": "./src/state/snoozeSpacing.ts" + }, "./state/thread-search": { "types": "./src/state/threadSearch.ts", "default": "./src/state/threadSearch.ts" diff --git a/packages/client-runtime/src/state/sharedSettings.ts b/packages/client-runtime/src/state/sharedSettings.ts index 032a0bf7e720c..63ea6584b2e8f 100644 --- a/packages/client-runtime/src/state/sharedSettings.ts +++ b/packages/client-runtime/src/state/sharedSettings.ts @@ -14,6 +14,8 @@ const SHARED_SERVER_SETTING_KEYS = [ "sidebarAutoSettleOnMerge", "autoResumeLimitedThreads", "snoozeLimitedThreads", + // Fork-local: keep the spacing rule identical on every environment a snooze can land in. + "snoozeSpacingMinutes", "newWorktreesStartFromOrigin", "sourceControlWritingStyle", "textGenerationModelSelection", diff --git a/packages/client-runtime/src/state/snoozeSpacing.test.ts b/packages/client-runtime/src/state/snoozeSpacing.test.ts new file mode 100644 index 0000000000000..5873ddfca12b2 --- /dev/null +++ b/packages/client-runtime/src/state/snoozeSpacing.test.ts @@ -0,0 +1,301 @@ +// @effect-diagnostics globalDate:off -- Slot allocation and DST cases use local calendar boundaries. +import { afterEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + allocateSnoozeSlot, + allocateSnoozeSlots, + selectSnoozeOccupancy, + spaceSnoozePresets, + withoutSnoozeOccupant, + type SnoozeOccupancy, + type SnoozeOccupantShell, +} from "./snoozeSpacing.ts"; +import { resolveSnoozePresets } from "./threadSettled.ts"; + +const NOW = "2026-04-10T12:00:00.000Z"; +const TOMORROW = "2026-04-11T09:00:00.000Z"; +const MINUTE_MS = 60_000; + +afterEach(() => vi.unstubAllEnvs()); + +function plusMinutes(iso: string, minutes: number): string { + return new Date(Date.parse(iso) + minutes * MINUTE_MS).toISOString(); +} + +function occupancy(...wakeTimes: readonly string[]): SnoozeOccupancy { + const counts = new Map(); + for (const wakeTime of wakeTimes) { + const wakeAtMs = Date.parse(wakeTime); + counts.set(wakeAtMs, (counts.get(wakeAtMs) ?? 0) + 1); + } + return counts; +} + +function makeShell( + input: { + readonly snoozedUntil?: string | null; + readonly archivedAt?: string | null; + readonly pending?: "approval" | "user-input"; + readonly environmentId?: string; + } = {}, +): SnoozeOccupantShell & { readonly environmentId: string } { + return { + environmentId: input.environmentId ?? "environment-1", + snoozedUntil: input.snoozedUntil ?? null, + snoozedAt: input.snoozedUntil == null ? null : "2026-04-10T08:00:00.000Z", + archivedAt: input.archivedAt ?? null, + hasPendingApprovals: input.pending === "approval", + hasPendingUserInput: input.pending === "user-input", + latestUserMessageAt: null, + latestTurn: null, + session: null, + }; +} + +describe("allocateSnoozeSlot", () => { + it("keeps the base time when nothing occupies it", () => { + expect( + allocateSnoozeSlot({ snoozedUntil: TOMORROW, occupied: occupancy(), spacingMinutes: 5 }), + ).toBe(TOMORROW); + }); + + it("walks past every occupied slot in five-minute steps", () => { + expect( + allocateSnoozeSlot({ + snoozedUntil: TOMORROW, + occupied: occupancy(TOMORROW, plusMinutes(TOMORROW, 5)), + spacingMinutes: 5, + }), + ).toBe(plusMinutes(TOMORROW, 10)); + }); + + it("skips occupied slots that are not on the step grid", () => { + expect( + allocateSnoozeSlot({ + snoozedUntil: TOMORROW, + occupied: occupancy(plusMinutes(TOMORROW, 2)), + spacingMinutes: 5, + }), + ).toBe(TOMORROW); + }); + + it("shares the last slot past the one-hour cap", () => { + const wakeTimes = Array.from({ length: 13 }, (_, index) => plusMinutes(TOMORROW, index * 5)); + expect( + allocateSnoozeSlot({ + snoozedUntil: TOMORROW, + occupied: occupancy(...wakeTimes), + spacingMinutes: 5, + }), + ).toBe(plusMinutes(TOMORROW, 60)); + }); + + it("caps an uneven step on the hour instead of overshooting", () => { + const wakeTimes = Array.from({ length: 9 }, (_, index) => plusMinutes(TOMORROW, index * 7)); + expect( + allocateSnoozeSlot({ + snoozedUntil: TOMORROW, + occupied: occupancy(...wakeTimes), + spacingMinutes: 7, + }), + ).toBe(plusMinutes(TOMORROW, 60)); + }); + + it("is an identity allocator when spacing is disabled", () => { + expect( + allocateSnoozeSlot({ + snoozedUntil: TOMORROW, + occupied: occupancy(TOMORROW), + spacingMinutes: 0, + }), + ).toBe(TOMORROW); + }); + + it("returns malformed timestamps untouched", () => { + expect( + allocateSnoozeSlot({ + snoozedUntil: "not-a-date", + occupied: occupancy(TOMORROW), + spacingMinutes: 5, + }), + ).toBe("not-a-date"); + }); +}); + +describe("allocateSnoozeSlots", () => { + it("claims consecutive slots in selection order", () => { + expect( + allocateSnoozeSlots({ + snoozedUntil: TOMORROW, + count: 3, + occupied: occupancy(), + spacingMinutes: 5, + }), + ).toEqual([TOMORROW, plusMinutes(TOMORROW, 5), plusMinutes(TOMORROW, 10)]); + }); + + it("starts after slots that were already taken", () => { + expect( + allocateSnoozeSlots({ + snoozedUntil: TOMORROW, + count: 2, + occupied: occupancy(TOMORROW), + spacingMinutes: 5, + }), + ).toEqual([plusMinutes(TOMORROW, 5), plusMinutes(TOMORROW, 10)]); + }); + + it("does not mutate the occupancy it is given", () => { + const occupied = occupancy(TOMORROW); + allocateSnoozeSlots({ snoozedUntil: TOMORROW, count: 2, occupied, spacingMinutes: 5 }); + expect([...occupied.keys()]).toEqual([Date.parse(TOMORROW)]); + }); + + it("keeps the base time for every thread when spacing is disabled", () => { + expect( + allocateSnoozeSlots({ + snoozedUntil: TOMORROW, + count: 2, + occupied: occupancy(TOMORROW), + spacingMinutes: 0, + }), + ).toEqual([TOMORROW, TOMORROW]); + }); +}); + +describe("selectSnoozeOccupancy", () => { + it("counts future snoozes across environments", () => { + expect([ + ...selectSnoozeOccupancy( + [ + makeShell({ snoozedUntil: TOMORROW, environmentId: "environment-1" }), + makeShell({ snoozedUntil: TOMORROW, environmentId: "environment-2" }), + makeShell({ snoozedUntil: plusMinutes(TOMORROW, 5), environmentId: "environment-2" }), + ], + { now: NOW }, + ), + ]).toEqual([ + [Date.parse(TOMORROW), 2], + [Date.parse(plusMinutes(TOMORROW, 5)), 1], + ]); + }); + + it("ignores expired snoozes", () => { + const counts = selectSnoozeOccupancy( + [makeShell({ snoozedUntil: "2026-04-10T10:00:00.000Z" })], + { + now: NOW, + }, + ); + expect(counts.size).toBe(0); + }); + + it("frees the slot when the thread is already back", () => { + const counts = selectSnoozeOccupancy( + [makeShell({ snoozedUntil: TOMORROW, pending: "approval" })], + { now: NOW }, + ); + expect(counts.size).toBe(0); + }); + + it("ignores archived threads", () => { + const counts = selectSnoozeOccupancy( + [makeShell({ snoozedUntil: TOMORROW, archivedAt: "2026-04-10T09:00:00.000Z" })], + { now: NOW }, + ); + expect(counts.size).toBe(0); + }); + + it("excludes the threads being snoozed", () => { + const self = makeShell({ snoozedUntil: TOMORROW }); + const counts = selectSnoozeOccupancy([self], { + now: NOW, + exclude: (shell) => shell === self, + }); + expect(counts.size).toBe(0); + }); + + it("ignores malformed wake data", () => { + const counts = selectSnoozeOccupancy([makeShell({ snoozedUntil: "not-a-date" })], { + now: NOW, + }); + expect(counts.size).toBe(0); + }); +}); + +describe("withoutSnoozeOccupant", () => { + it("drops one reservation and keeps the others at the same time", () => { + const counts = occupancy(TOMORROW, TOMORROW); + expect([...withoutSnoozeOccupant(counts, TOMORROW)]).toEqual([[Date.parse(TOMORROW), 1]]); + }); + + it("removes the entry when it was the last reservation", () => { + expect(withoutSnoozeOccupant(occupancy(TOMORROW), TOMORROW).size).toBe(0); + }); + + it("returns the same occupancy for a thread with no snooze", () => { + const counts = occupancy(TOMORROW); + expect(withoutSnoozeOccupant(counts, null)).toBe(counts); + }); +}); + +describe("spaceSnoozePresets", () => { + const presets = resolveSnoozePresets(new Date(NOW)); + const tomorrowUntil = presets.find((preset) => preset.id === "tomorrow")!.snoozedUntil; + + it("returns the resolver's presets untouched when spacing is disabled", () => { + expect(spaceSnoozePresets(presets, { spacingMinutes: 0 })).toBe(presets); + }); + + it("shifts only the preset whose base time is occupied", () => { + const shifted = spaceSnoozePresets(presets, { + spacingMinutes: 5, + occupied: occupancy(tomorrowUntil), + }); + expect(shifted.find((preset) => preset.id === "tomorrow")?.snoozedUntil).toBe( + plusMinutes(tomorrowUntil, 5), + ); + expect(shifted.find((preset) => preset.id === "hour")).toEqual( + presets.find((preset) => preset.id === "hour"), + ); + }); + + it("labels the shifted time through the callback", () => { + const shifted = spaceSnoozePresets(presets, { + spacingMinutes: 5, + occupied: occupancy(tomorrowUntil), + formatWhenLabel: (_preset, snoozedUntil) => `shifted ${snoozedUntil}`, + }); + expect(shifted.find((preset) => preset.id === "tomorrow")?.whenLabel).toBe( + `shifted ${plusMinutes(tomorrowUntil, 5)}`, + ); + }); + + it("keeps the resolver's wording by default", () => { + const shifted = spaceSnoozePresets(presets, { + spacingMinutes: 5, + occupied: occupancy(tomorrowUntil), + }); + expect(shifted.find((preset) => preset.id === "tomorrow")?.whenLabel).toBe( + new Date(plusMinutes(tomorrowUntil, 5)).toLocaleTimeString(undefined, { + hour: "numeric", + minute: "2-digit", + }), + ); + }); + + it("staggers a next-day preset across a daylight-saving boundary", () => { + vi.stubEnv("TZ", "Europe/Berlin"); + const now = new Date(2026, 2, 28, 12, 0); + const dstPresets = resolveSnoozePresets(now); + const tomorrow = dstPresets.find((preset) => preset.id === "tomorrow")!; + const shifted = spaceSnoozePresets(dstPresets, { + spacingMinutes: 5, + occupied: occupancy(tomorrow.snoozedUntil), + }).find((preset) => preset.id === "tomorrow")!; + const shiftedDate = new Date(shifted.snoozedUntil); + expect(shiftedDate.getDate()).toBe(29); + expect(shiftedDate.getHours()).toBe(9); + expect(shiftedDate.getMinutes()).toBe(5); + }); +}); diff --git a/packages/client-runtime/src/state/snoozeSpacing.ts b/packages/client-runtime/src/state/snoozeSpacing.ts new file mode 100644 index 0000000000000..4c6937fa40365 --- /dev/null +++ b/packages/client-runtime/src/state/snoozeSpacing.ts @@ -0,0 +1,134 @@ +// @effect-diagnostics globalDate:off -- Slot allocation works in epoch milliseconds. +// Fork-local: spread snoozes that would otherwise wake together; upstream has no equivalent. +import { + effectiveSnoozed, + snoozePresetWhenLabel, + type SnoozePreset, + type ThreadSnoozeShell, +} from "./threadSettled.ts"; + +/** A crowded preset still wakes within the hour; past that, colliding snoozes share the last slot. */ +const MAX_SNOOZE_SPACING_OFFSET_MS = 60 * 60 * 1_000; + +const MINUTE_MS = 60 * 1_000; + +/** Wake time (epoch ms) to the number of threads still holding it. */ +export type SnoozeOccupancy = ReadonlyMap; + +export interface SnoozeSpacing { + readonly occupied: SnoozeOccupancy; + readonly spacingMinutes: number; +} + +export interface SnoozeOccupantShell extends ThreadSnoozeShell { + readonly archivedAt?: string | null; +} + +const NO_OCCUPANTS: SnoozeOccupancy = new Map(); + +function formatSnoozeWhenLabel(preset: SnoozePreset, snoozedUntil: string): string { + return snoozePresetWhenLabel(preset.id, new Date(snoozedUntil)); +} + +/** + * Only a snooze that will still wake on its own reserves a slot: an expired timer or a + * thread already woken by approval, input or failure is back and must not push others later. + */ +export function selectSnoozeOccupancy( + shells: ReadonlyArray, + options: { readonly now: string; readonly exclude?: (shell: T) => boolean }, +): SnoozeOccupancy { + const occupancy = new Map(); + for (const shell of shells) { + if (shell.archivedAt != null) continue; + if (options.exclude?.(shell) === true) continue; + if (!effectiveSnoozed(shell, options)) continue; + if (shell.snoozedUntil == null) continue; + const wakeAtMs = Date.parse(shell.snoozedUntil); + if (Number.isNaN(wakeAtMs)) continue; + occupancy.set(wakeAtMs, (occupancy.get(wakeAtMs) ?? 0) + 1); + } + return occupancy; +} + +/** Frees one reservation, so a thread being re-snoozed keeps its slot and keeps others' counts. */ +export function withoutSnoozeOccupant( + occupancy: SnoozeOccupancy, + snoozedUntil: string | null | undefined, +): SnoozeOccupancy { + if (snoozedUntil == null) return occupancy; + const wakeAtMs = Date.parse(snoozedUntil); + const count = Number.isNaN(wakeAtMs) ? 0 : (occupancy.get(wakeAtMs) ?? 0); + if (count === 0) return occupancy; + const next = new Map(occupancy); + if (count === 1) next.delete(wakeAtMs); + else next.set(wakeAtMs, count - 1); + return next; +} + +/** `occupied` is not mutated; callers keep reporting the same reservations. */ +export function allocateSnoozeSlot(input: { + readonly snoozedUntil: string; + readonly occupied: SnoozeOccupancy; + readonly spacingMinutes: number; +}): string { + const baseMs = Date.parse(input.snoozedUntil); + const stepMs = input.spacingMinutes * MINUTE_MS; + if (Number.isNaN(baseMs) || stepMs <= 0) return input.snoozedUntil; + let offsetMs = 0; + while ( + offsetMs < MAX_SNOOZE_SPACING_OFFSET_MS && + (input.occupied.get(baseMs + offsetMs) ?? 0) > 0 + ) { + offsetMs = Math.min(offsetMs + stepMs, MAX_SNOOZE_SPACING_OFFSET_MS); + } + if (offsetMs === 0) return input.snoozedUntil; + return new Date(baseMs + offsetMs).toISOString(); +} + +/** + * One batch snoozes in selection order, so threads selected together claim consecutive + * slots even though every command is dispatched before any of them lands. + */ +export function allocateSnoozeSlots(input: { + readonly snoozedUntil: string; + readonly count: number; + readonly occupied: SnoozeOccupancy; + readonly spacingMinutes: number; +}): ReadonlyArray { + const claimed = new Map(input.occupied); + const slots: string[] = []; + for (let index = 0; index < input.count; index += 1) { + const slot = allocateSnoozeSlot({ + snoozedUntil: input.snoozedUntil, + occupied: claimed, + spacingMinutes: input.spacingMinutes, + }); + const slotMs = Date.parse(slot); + claimed.set(slotMs, (claimed.get(slotMs) ?? 0) + 1); + slots.push(slot); + } + return slots; +} + +export function spaceSnoozePresets( + presets: ReadonlyArray, + options: { + readonly occupied?: SnoozeOccupancy; + readonly spacingMinutes: number; + readonly formatWhenLabel?: (preset: SnoozePreset, snoozedUntil: string) => string; + }, +): ReadonlyArray { + if (options.spacingMinutes <= 0) return presets; + const occupied = options.occupied ?? NO_OCCUPANTS; + const formatWhenLabel = options.formatWhenLabel ?? formatSnoozeWhenLabel; + return presets.map((preset) => { + const snoozedUntil = allocateSnoozeSlot({ + snoozedUntil: preset.snoozedUntil, + occupied, + spacingMinutes: options.spacingMinutes, + }); + if (snoozedUntil === preset.snoozedUntil) return preset; + return { ...preset, snoozedUntil, whenLabel: formatWhenLabel(preset, snoozedUntil) }; + }); +} diff --git a/packages/client-runtime/src/state/threadSettled.ts b/packages/client-runtime/src/state/threadSettled.ts index 30621750a3fcd..31959d90dbe3a 100644 --- a/packages/client-runtime/src/state/threadSettled.ts +++ b/packages/client-runtime/src/state/threadSettled.ts @@ -187,6 +187,14 @@ function snoozeTimeOfDayLabel(date: Date): string { return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" }); } +// Fork-local: staggered presets need the same wording the resolver gives its own presets. +export function snoozePresetWhenLabel(id: SnoozePresetId, wake: Date): string { + const time = snoozeTimeOfDayLabel(wake); + return id === "next-week" + ? `${wake.toLocaleDateString(undefined, { weekday: "short" })} ${time}` + : time; +} + function snoozeAtHour(base: Date, hour: number): Date { const next = DateTime.toDate(DateTime.makeUnsafe(base)); next.setHours(hour, 0, 0, 0); @@ -209,13 +217,13 @@ export function resolveSnoozePresets(now: Date): ReadonlyArray { { id: "hour", label: "In 1 hour", - whenLabel: snoozeTimeOfDayLabel(inAnHour), + whenLabel: snoozePresetWhenLabel("hour", inAnHour), snoozedUntil: inAnHour.toISOString(), }, { id: "three-hours", label: "In 3 hours", - whenLabel: snoozeTimeOfDayLabel(inThreeHours), + whenLabel: snoozePresetWhenLabel("three-hours", inThreeHours), snoozedUntil: inThreeHours.toISOString(), }, ]; @@ -225,7 +233,7 @@ export function resolveSnoozePresets(now: Date): ReadonlyArray { presets.push({ id: "evening", label: "This evening", - whenLabel: snoozeTimeOfDayLabel(evening), + whenLabel: snoozePresetWhenLabel("evening", evening), snoozedUntil: evening.toISOString(), }); } @@ -234,7 +242,7 @@ export function resolveSnoozePresets(now: Date): ReadonlyArray { presets.push({ id: "tomorrow", label: "Tomorrow", - whenLabel: snoozeTimeOfDayLabel(tomorrow), + whenLabel: snoozePresetWhenLabel("tomorrow", tomorrow), snoozedUntil: tomorrow.toISOString(), }); @@ -244,7 +252,7 @@ export function resolveSnoozePresets(now: Date): ReadonlyArray { presets.push({ id: "next-week", label: "Next week", - whenLabel: `${nextWeek.toLocaleDateString(undefined, { weekday: "short" })} ${snoozeTimeOfDayLabel(nextWeek)}`, + whenLabel: snoozePresetWhenLabel("next-week", nextWeek), snoozedUntil: nextWeek.toISOString(), }); } diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index d8edcb0f017db..8c2b13980eaf7 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -92,6 +92,17 @@ export const SidebarAutoSettleAfterDays = Schema.Number.check( ); export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type; const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3; +// Fork-local: minutes added between snoozes that would otherwise wake together; 0 disables it. +export const MIN_SNOOZE_SPACING_MINUTES = 0; +export const MAX_SNOOZE_SPACING_MINUTES = 60; +export const SnoozeSpacingMinutes = Schema.Int.check( + Schema.isBetween({ + minimum: MIN_SNOOZE_SPACING_MINUTES, + maximum: MAX_SNOOZE_SPACING_MINUTES, + }), +); +export type SnoozeSpacingMinutes = typeof SnoozeSpacingMinutes.Type; +export const DEFAULT_SNOOZE_SPACING_MINUTES: SnoozeSpacingMinutes = 5; export const MIN_GLASS_OPACITY = 40; export const MAX_GLASS_OPACITY = 100; export const GlassOpacity = Schema.Int.check( @@ -1285,6 +1296,9 @@ export const ServerSettings = Schema.Struct({ ), idleCompaction: Schema.optionalKey(IdleCompactionMode), snoozeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), + snoozeSpacingMinutes: SnoozeSpacingMinutes.pipe( + Schema.withDecodingDefault(Effect.succeed(DEFAULT_SNOOZE_SPACING_MINUTES)), + ), autoResumeLimitedThreads: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), /** Beta: guest links for this machine's threads. Off refuses new links and pauses existing ones. */ guestSharingEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), @@ -1634,6 +1648,7 @@ export const ServerSettingsPatch = Schema.Struct({ sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean), autoResumeLimitedThreads: Schema.optionalKey(Schema.Boolean), snoozeLimitedThreads: Schema.optionalKey(Schema.Boolean), + snoozeSpacingMinutes: Schema.optionalKey(SnoozeSpacingMinutes), guestSharingEnabled: Schema.optionalKey(Schema.Boolean), backgroundActivity: Schema.optionalKey( Schema.Struct({ From 332ccf99654d412c0275672e845ecaaa6883158f Mon Sep 17 00:00:00 2001 From: Benjamin Coriou Date: Tue, 27 Oct 2026 19:54:39 +0100 Subject: [PATCH 2/3] fix(fork): tighten snooze spacing after review Review round 1 found the bulk batch counted the hour cap from the menu's already-shifted slot, so a long selection could wake 80 minutes past the base preset. The batch now allocates from the unshifted preset. The chat header's action menu no longer subscribes to every thread shell and server config; it reads both through the atom registry when a menu opens. The mobile row stops freeing another thread's reservation when it re-snoozes a thread that already woke, and the user docs append the fork paragraph instead of splitting an upstream one. Fork markers now cover every added hunk, and a test pins a long batch to the hour cap. --- apps/mobile/src/features/home/HomeScreen.tsx | 3 +++ .../settings/SettingsThreadsRouteScreen.tsx | 3 +++ .../src/features/settings/settings-search.ts | 1 + .../features/threads/ThreadNavigationSidebar.tsx | 3 +++ .../src/features/threads/thread-list-v2-items.tsx | 13 ++++++++++--- apps/mobile/src/features/threads/threadListV2.ts | 2 ++ .../mobile/src/features/threads/useThreadListV2.ts | 5 +++-- apps/mobile/src/state/thread-list-environments.ts | 4 ++++ apps/web/src/components/Sidebar.snooze.ts | 3 +++ apps/web/src/components/Sidebar.tsx | 14 ++++++++++++-- .../web/src/components/settings/SettingsPanels.tsx | 5 +++++ apps/web/src/components/settings/settingsSearch.ts | 1 + .../src/components/sidebar/SidebarThreadRow.tsx | 1 + apps/web/src/hooks/useThreadActionMenu.test.ts | 4 ++-- apps/web/src/hooks/useThreadActionMenu.ts | 13 +++++++------ apps/web/src/state/entities.ts | 12 ++++++++++++ docs/user/thread-sidebar.md | 6 +++--- .../client-runtime/src/state/snoozeSpacing.test.ts | 12 ++++++++++++ 18 files changed, 87 insertions(+), 18 deletions(-) diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index fe6b96b206267..0f0349577476d 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -11,6 +11,7 @@ import { } from "@t3tools/client-runtime/state/shell"; import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search"; import { type EnvironmentId, type SidebarProjectGroupingMode } from "@t3tools/contracts"; +// Fork-local: row menus stagger snooze presets by each environment's minutes. import { DEFAULT_SNOOZE_SPACING_MINUTES } from "@t3tools/contracts/settings"; import { useAtomValue } from "@effect/atom-react"; import { useFocusEffect } from "@react-navigation/native"; @@ -444,6 +445,7 @@ export function HomeScreen(props: HomeScreenProps) { pinReorderEnvironmentIds, activeReorderEnvironmentIds, titleRegenerationEnvironmentIds, + // Fork-local: spacing is set per environment, so rows read their own. snoozeSpacingMinutesByEnvironment, } = listEnvironments; const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId); @@ -453,6 +455,7 @@ export function HomeScreen(props: HomeScreenProps) { items: threadListV2Items, contentOnlyThreadKeys, olderSettledShelf, + // Fork-local: rows space their presets against other threads' wake times. snoozeOccupancy, } = useThreadListV2({ threads: props.threads, diff --git a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx index fa4fcf6f6026a..ab07ed2380cea 100644 --- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx @@ -10,6 +10,7 @@ import { View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts"; +// Fork-local: the spacing row below needs these bounds and a numeric field. import { MAX_SNOOZE_SPACING_MINUTES, MIN_SNOOZE_SPACING_MINUTES, @@ -95,6 +96,7 @@ function AutoSettleSettingsRows() { patch: Partial & { autoResumeLimitedThreads?: boolean; snoozeLimitedThreads?: boolean; + // Fork-local: spacing writes ride along with the other snooze settings. snoozeSpacingMinutes?: number; }, ) => { @@ -199,6 +201,7 @@ function AutoSettleSettingsRows() { onValueChange={(value) => writeToAll({ snoozeLimitedThreads: value })} /> + {/* Fork-local: spacing applies wherever a snooze can land, not per project. */} diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 13969d5fe213c..4a7bd77c1c683 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -37,6 +37,7 @@ const SETTINGS_SEARCH_TERMS = { "auto-settle", "settle", "snooze", + // Fork-local: settings search finds the spacing row with these terms. "snooze spacing", "stagger snoozes", "usage limits", diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx index 685b66a9d5b26..ab2f7f24f7078 100644 --- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx +++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx @@ -2,6 +2,7 @@ import { useActiveNewTask } from "../../state/active-new-task"; import { ThreadUndoNotice } from "../home/ThreadUndoNotice"; import { useAndroidControlSizing } from "../../components/ui/useAndroidControlSizing"; import { resolveScratchProjectScopeKey } from "@t3tools/client-runtime/state/project-grouping"; +// Fork-local: row menus stagger snooze presets by each environment's minutes. import { DEFAULT_SNOOZE_SPACING_MINUTES } from "@t3tools/contracts/settings"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import type { @@ -291,6 +292,7 @@ function ThreadNavigationSidebarPane( pinReorderEnvironmentIds, activeReorderEnvironmentIds, titleRegenerationEnvironmentIds, + // Fork-local: spacing is set per environment, so rows read their own. snoozeSpacingMinutesByEnvironment, } = listEnvironments; const resolveProviderInstance = useThreadRowProviderInstanceResolver(providersByEnvironmentId); @@ -300,6 +302,7 @@ function ThreadNavigationSidebarPane( items: threadListV2Items, contentOnlyThreadKeys, olderSettledShelf, + // Fork-local: rows space their presets against other threads' wake times. snoozeOccupancy, } = useThreadListV2({ threads, diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 95bbee21eb8b7..50f1a07ff188a 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -26,7 +26,7 @@ import { resolveThreadWorkingStartedAt, } from "@t3tools/client-runtime/state/models"; import { AuthOrchestrationOperateScope, type EnvironmentMachineKind } from "@t3tools/contracts"; -import { canSnooze } from "@t3tools/client-runtime/state/thread-settled"; +import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import type { MenuAction } from "@react-native-menu/menu"; import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react"; import { Pressable, useWindowDimensions, View } from "react-native"; @@ -52,6 +52,7 @@ import { useThreadPr } from "../../state/use-thread-pr"; import { useSwipeRowDormant } from "../home/swipe-row-activation"; import { ThreadSwipeable } from "../home/thread-swipe-actions"; import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu"; +// Fork-local: the menu and the click-time resolver share one spaced preset set. import { withoutSnoozeOccupant, type SnoozeOccupancy, @@ -562,6 +563,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { readonly snoozeWakeLabelText?: string; readonly timeLabel: string; readonly snoozePresetMinute: string; + /** Fork-local: wake times other threads hold, and the configured spacing. */ readonly snoozeOccupancy: SnoozeOccupancy; readonly snoozeSpacingMinutes: number; readonly project: EnvironmentProject | null; @@ -742,13 +744,18 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { snoozable: canSnooze(thread, { now: snoozeGateNow }), snoozed: snoozedRow, }); + // Fork-local: a thread that woke early holds no slot, so freeing one here would steal another's. + const stillSnoozed = effectiveSnoozed(thread, { now: snoozeGateNow }); const snoozeSpacing = useMemo( () => ({ - occupied: withoutSnoozeOccupant(props.snoozeOccupancy, thread.snoozedUntil), + occupied: stillSnoozed + ? withoutSnoozeOccupant(props.snoozeOccupancy, thread.snoozedUntil) + : props.snoozeOccupancy, spacingMinutes: props.snoozeSpacingMinutes, }), - [props.snoozeOccupancy, props.snoozeSpacingMinutes, thread.snoozedUntil], + [props.snoozeOccupancy, props.snoozeSpacingMinutes, stillSnoozed, thread.snoozedUntil], ); + // Fork-local: presets are spaced against the other threads' reservations. const snoozePresets = useMemo(() => { if (swipeActions.secondary !== "snooze") return [] as const; // oxlint-disable-next-line react/purity -- The memo recomputes on the snoozePresetMinute tick, so preset times refresh every minute. diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index a595eca15a0a5..3f5f7c778e67f 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -8,6 +8,7 @@ import { threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +// Fork-local: mobile menus space presets the same way the web sidebar does. import { spaceSnoozePresets, type SnoozeSpacing, @@ -76,6 +77,7 @@ export type ThreadListV2Status = | "ready"; export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze"; +// Fork-local: spread presets across free wake slots when spacing is configured. export function resolveThreadListV2SnoozePresets( now: Date, spacing?: SnoozeSpacing, diff --git a/apps/mobile/src/features/threads/useThreadListV2.ts b/apps/mobile/src/features/threads/useThreadListV2.ts index 469aaf9411727..15d43ede68cef 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -1,4 +1,5 @@ import type { OlderSettledScope } from "@t3tools/client-runtime/state/threads"; +// Fork-local: occupancy for the mobile row snooze menus, from live reservations. import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; import { selectSnoozeOccupancy } from "@t3tools/client-runtime/state/snooze-spacing"; import type { EnvironmentId } from "@t3tools/contracts"; @@ -148,8 +149,7 @@ export function useThreadListV2(input: { )) && (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)), ); - // Rows read one occupancy value; keying it on reservations keeps unrelated - // shell updates from re-rendering every row that offers a snooze menu. + // Fork-local: keyed on reservations so unrelated shell updates skip row re-renders. const reservationKey = threads .flatMap((thread) => effectiveSnoozed(thread, { now: input.now }) ? [thread.snoozedUntil ?? ""] : [], @@ -179,6 +179,7 @@ export function useThreadListV2(input: { moveAvailability, shelfPreferencesLoading: !input.shelfPreferencesLoaded, }); + // Fork-local: rows read occupancy to space their own menu presets. return { layout, items, contentOnlyThreadKeys, olderSettledShelf, snoozeOccupancy }; } diff --git a/apps/mobile/src/state/thread-list-environments.ts b/apps/mobile/src/state/thread-list-environments.ts index 3d21b1b7f014b..e00ddda74a847 100644 --- a/apps/mobile/src/state/thread-list-environments.ts +++ b/apps/mobile/src/state/thread-list-environments.ts @@ -36,6 +36,7 @@ function selectEnvironment(config: ServerConfig) { ), machineKind: resolveEnvironmentMachineKind(config), capabilities: config.environment.capabilities, + // Fork-local: rows space snoozes with the minutes this environment reports. snoozeSpacingMinutes: config.settings.snoozeSpacingMinutes, }; } @@ -72,6 +73,7 @@ function collectEnvironments(environments: ReadonlyMap(); const activeReorderEnvironmentIds = new Set(); const titleRegenerationEnvironmentIds = new Set(); + // Fork-local: one spacing value per environment, for the rows that offer a menu. const snoozeSpacingMinutesByEnvironment = new Map(); for (const [id, { providers, machineKind, capabilities, snoozeSpacingMinutes }] of environments) { providersByEnvironmentId.set(id, providers); @@ -95,6 +97,7 @@ function collectEnvironments(environments: ReadonlyMap (prior.capabilities[key] === true) === (selected.capabilities[key] === true), diff --git a/apps/web/src/components/Sidebar.snooze.ts b/apps/web/src/components/Sidebar.snooze.ts index cfbd749fd91b7..dc1e1369ac111 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -1,4 +1,5 @@ import type { TimestampFormat } from "@t3tools/contracts/settings"; +// Fork-local: presets come back spaced, each carrying its own wake time. import { spaceSnoozePresets, type SnoozeSpacing, @@ -17,6 +18,7 @@ function timeOfDayLabel(date: Date, timestampFormat: TimestampFormat): string { return formatShortTimestamp(date.toISOString(), timestampFormat); } +// Fork-local: a spaced preset's label follows the slot it landed in. function whenLabel( preset: SnoozePreset, snoozedUntil: string, @@ -30,6 +32,7 @@ function whenLabel( : time; } +// Fork-local: optional spacing spreads presets and relabels them from their slots. export function resolveSnoozePresets( now: Date, timestampFormat: TimestampFormat, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8cea3a69f43a8..bb2c1041b4be8 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -28,6 +28,7 @@ import { effectiveSnoozed, threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; +// Fork-local: batch snoozes reserve wake times other threads still hold. import { allocateSnoozeSlots, selectSnoozeOccupancy, @@ -58,6 +59,7 @@ import { } from "@t3tools/client-runtime/environment"; import { AuthOrchestrationOperateScope, + // Fork-local: menu copy states the default spacing and the spread's time range. DEFAULT_SERVER_SETTINGS, ProjectId, type ScopedThreadRef, @@ -1248,7 +1250,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; }; - // Stable so memoized rows do not re-render; the occupancy scan runs when a row opens its menu. + // Fork-local: stable so memoized rows do not re-render; the scan runs when a menu opens. const resolveRowSnoozePresets = useStableCallback((thread: EnvironmentThreadShell) => { const now = new Date(); return resolveSnoozePresets( @@ -1606,6 +1608,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threadByKeyRef.current = threadByKey; settledThreadKeysRef.current = settledThreadKeys; snoozedThreadKeysRef.current = snoozedThreadKeys; + // Fork-local: slots compare wake times across every environment a row can see. quietThreadsRef.current = threads; sectionByThreadKeyRef.current = sectionByThreadKey; }); @@ -2118,6 +2121,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const unpinMenuItem = buildBulkUnpinContextMenuItem({ pinnedCount: pinnedSelectedThreads.length, }); + // Fork-local: a multi-select snooze ignores the selection's own reservations. const selectedThreadKeySet = new Set(selectedThreadKeys); const snoozeSpacing = snoozeSpacingFor( selectionNow, @@ -2128,6 +2132,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ), ); const snoozePresets = resolveSnoozePresets(selectionNow, timestampFormat, snoozeSpacing); + // The hour cap counts from the unshifted base, not the first free slot the menu shows. + const snoozeBasePresets = resolveSnoozePresets(selectionNow, timestampFormat); const clicked = await settlePromise(() => api.contextMenu.show( [ @@ -2199,6 +2205,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (clicked.value === "settle" && actionTargets.length === 0) return; if (clicked.value !== "mark-unread" && !checkThreadOperations(actionTargets)) return; if (clicked.value?.startsWith("snooze:")) { + // Fork-local: presets fan out across free slots; a custom time stays exact. const custom = clicked.value === "snooze:custom"; const preset = custom ? await requestCustomSnooze() @@ -2208,7 +2215,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const snoozeSlots = custom ? selectedThreads.map(() => preset.snoozedUntil) : allocateSnoozeSlots({ - snoozedUntil: preset.snoozedUntil, + snoozedUntil: + snoozeBasePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value) + ?.snoozedUntil ?? preset.snoozedUntil, count: selectedThreads.length, occupied: snoozeSpacing.occupied, spacingMinutes: snoozeSpacing.spacingMinutes, @@ -2450,6 +2459,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const isSettled = settledThreadKeysRef.current.has(threadKey); const isSnoozed = snoozedThreadKeysRef.current.has(threadKey); const isPinned = thread.pinnedAt != null; + // Fork-local: rows spread theirs against the other threads' wake times. const snoozePresets = resolveRowSnoozePresets(thread); const threadProjectGroup = projectGroupsRef.current.find((project) => diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 431819050034c..e111d12546778 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -16,6 +16,7 @@ import { DEFAULT_UNIFIED_SETTINGS, type DiffLayout, MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, + // Fork-local: the spacing row below needs these bounds. MAX_SNOOZE_SPACING_MINUTES, MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS, MIN_SNOOZE_SPACING_MINUTES, @@ -473,6 +474,7 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.snoozeLimitedThreads !== DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads ? ["Snooze until limits reset"] : []), + // Fork-local: resetting settings also clears the spacing value. ...(settings.snoozeSpacingMinutes !== DEFAULT_UNIFIED_SETTINGS.snoozeSpacingMinutes ? ["Space snoozes by"] : []), @@ -639,6 +641,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, autoResumeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.autoResumeLimitedThreads, snoozeLimitedThreads: DEFAULT_UNIFIED_SETTINGS.snoozeLimitedThreads, + // Fork-local: restored defaults include the fork's spacing setting. snoozeSpacingMinutes: DEFAULT_UNIFIED_SETTINGS.snoozeSpacingMinutes, responseStreamingMode: DEFAULT_UNIFIED_SETTINGS.responseStreamingMode, enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks, @@ -688,6 +691,7 @@ export function useSettingsRestore(onRestored?: () => void) { const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3; +// Fork-local: widened from auto-settle days so spacing can reuse the same field. function NumberSettingInput({ value, min, @@ -998,6 +1002,7 @@ export function GeneralSettingsPanel() { } /> + {/* Fork-local: spacing between snoozes that would otherwise wake together. */} void; diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts index 30cd9b18419ac..a92e3bf4b13c3 100644 --- a/apps/web/src/hooks/useThreadActionMenu.test.ts +++ b/apps/web/src/hooks/useThreadActionMenu.test.ts @@ -63,8 +63,8 @@ vi.mock("../state/entities", () => ({ latestRun: null, }), useProjects: () => [{ id: "project", environmentId: "secondary" }], - useQuietThreadShells: () => [], - useServerConfigs: () => new Map(), + readQuietThreadShells: () => [], + readEnvironmentSnoozeSpacingMinutes: () => undefined, })); vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" })); vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } })); diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index a1e4f98776eb3..66a6646afdfff 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -8,6 +8,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { canSnooze, effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled"; +// Fork-local: menus space presets against the wake times other threads hold. import { selectSnoozeOccupancy } from "@t3tools/client-runtime/state/snooze-spacing"; import { AuthOrchestrationOperateScope, @@ -33,10 +34,11 @@ import { readEnvironmentSupportsSettlement, readEnvironmentSupportsSnooze, readEnvironmentSupportsTitleRegeneration, + // Fork-local: spacing comes from the thread's environment and every shell. + readEnvironmentSnoozeSpacingMinutes, + readQuietThreadShells, readThreadShell, useProjects, - useQuietThreadShells, - useServerConfigs, } from "../state/entities"; import { usePrimaryEnvironmentId } from "../state/environments"; import { readLocalApi } from "../localApi"; @@ -71,8 +73,6 @@ export function useThreadActionMenu(input: { const { threadRef, projectCwd, onStartRename, canShareWithGuest } = input; const router = useRouter(); const projects = useProjects(); - const quietThreads = useQuietThreadShells(); - const serverConfigs = useServerConfigs(); const primaryEnvironmentId = usePrimaryEnvironmentId(); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); const logicalProjectKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({ @@ -135,14 +135,15 @@ export function useThreadActionMenu(input: { titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId), }; const isRegeneratingTitle = thread.titleRegeneration != null; + // Fork-local: skip this thread's own wake time so it can move into a free slot. const snoozePresets = resolveSnoozePresets(now, timestampFormat, { - occupied: selectSnoozeOccupancy(quietThreads, { + occupied: selectSnoozeOccupancy(readQuietThreadShells(), { now: now.toISOString(), exclude: (candidate) => candidate.id === thread.id && candidate.environmentId === thread.environmentId, }), spacingMinutes: - serverConfigs.get(thread.environmentId)?.settings.snoozeSpacingMinutes ?? + readEnvironmentSnoozeSpacingMinutes(thread.environmentId) ?? DEFAULT_SERVER_SETTINGS.snoozeSpacingMinutes, }); const items = buildThreadActionMenuItems({ diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index f7c5fc1d75629..8b2591eee565c 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -274,6 +274,18 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell | return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref)); } +// Fork-local: snooze spacing reads every environment's reservations once, when a menu opens. +export function readQuietThreadShells(): ReadonlyArray { + return appAtomRegistry.get(environmentThreadShells.quietThreadShellsAtom); +} + +export function readEnvironmentSnoozeSpacingMinutes( + environmentId: EnvironmentId, +): number | undefined { + return appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.settings + .snoozeSpacingMinutes; +} + export function waitForThreadShell(ref: ScopedThreadRef, timeoutMs = 5_000): Promise { return waitForAtomValue({ registry: appAtomRegistry, diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 7c87acfabec8a..5e1dffa6b0ae6 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -262,6 +262,9 @@ Choose **Snooze → Custom…** from a thread's menu to pick a date and time in local time zone, or a duration in minutes, hours, or days. Durations start when you confirm; one day means 24 hours. On web and desktop, you can also snooze several selected threads together. Choose **Wake thread** to bring a thread back early. +A snoozed thread keeps working and stays hidden until its wake time, even while +its agent wakes itself for background work. It comes back early only when it needs +an approval or answer from you, when a run fails, or when you send it a message. Presets spread out instead of waking a batch at once: if another snoozed thread already holds the wake time a preset would pick, the next snooze lands 5 minutes @@ -270,6 +273,3 @@ use, and a multiple selection staggers in order. Custom times, snoozes until a usage limit resets, and undo keep the exact time you chose. Change the spacing or turn it off with **Space snoozes by** in **Settings → General** on web and desktop, or **Settings → Thread behavior** on mobile. -A snoozed thread keeps working and stays hidden until its wake time, even while -its agent wakes itself for background work. It comes back early only when it needs -an approval or answer from you, when a run fails, or when you send it a message. diff --git a/packages/client-runtime/src/state/snoozeSpacing.test.ts b/packages/client-runtime/src/state/snoozeSpacing.test.ts index 5873ddfca12b2..9abb086f570a8 100644 --- a/packages/client-runtime/src/state/snoozeSpacing.test.ts +++ b/packages/client-runtime/src/state/snoozeSpacing.test.ts @@ -151,6 +151,18 @@ describe("allocateSnoozeSlots", () => { expect([...occupied.keys()]).toEqual([Date.parse(TOMORROW)]); }); + it("holds a long batch to the hour cap counted from its base", () => { + const slots = allocateSnoozeSlots({ + snoozedUntil: TOMORROW, + count: 20, + occupied: occupancy(), + spacingMinutes: 5, + }); + expect(slots[0]).toBe(TOMORROW); + expect(slots[12]).toBe(plusMinutes(TOMORROW, 60)); + expect(slots[19]).toBe(plusMinutes(TOMORROW, 60)); + }); + it("keeps the base time for every thread when spacing is disabled", () => { expect( allocateSnoozeSlots({ From 60717fbe6f29de58055713b49ad52ac57f040a1a Mon Sep 17 00:00:00 2001 From: Benjamin Coriou Date: Tue, 27 Oct 2026 21:23:13 +0100 Subject: [PATCH 3/3] fix(fork): correct the snooze occupancy ref comment --- apps/web/src/components/Sidebar.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index bb2c1041b4be8..bb4247fe3c8a4 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1227,7 +1227,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const threadByKeyRef = useRef(threadByKey); const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - // Every environment's shells, unlike the scoped `threads`; snooze slots compare across them. + // Fork-local: every environment's quiet shells; snooze slots compare across them. const quietThreadsRef = useRef(threads); // Fork-local: reserve wake times other threads still hold so a batch wakes in sequence.