diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index e9a71f2c253fc..0f0349577476d 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -11,6 +11,8 @@ 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"; import { use, useEffect, useRef, useState, type ComponentProps } from "react"; @@ -443,6 +445,8 @@ 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); const pendingOrder = usePendingThreadOrder(nowMinute, snoozeWakeTick); @@ -451,6 +455,8 @@ 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, pendingTasks: props.pendingTasks, @@ -587,6 +593,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..ab07ed2380cea 100644 --- a/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsThreadsRouteScreen.tsx @@ -10,6 +10,12 @@ 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, +} 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 +96,8 @@ function AutoSettleSettingsRows() { patch: Partial & { autoResumeLimitedThreads?: boolean; snoozeLimitedThreads?: boolean; + // Fork-local: spacing writes ride along with the other snooze settings. + snoozeSpacingMinutes?: number; }, ) => { if ( @@ -176,22 +184,41 @@ function AutoSettleSettingsRows() { /> ) : null} {!projectSelected ? ( - - writeToAll({ autoResumeLimitedThreads: value })} - /> - writeToAll({ snoozeLimitedThreads: value })} - /> - + <> + + writeToAll({ autoResumeLimitedThreads: value })} + /> + writeToAll({ snoozeLimitedThreads: value })} + /> + + {/* Fork-local: spacing applies wherever a snooze can land, not per project. */} + + + + 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 +744,25 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: { snoozable: canSnooze(thread, { now: snoozeGateNow }), snoozed: snoozedRow, }); - const snoozePresets = useMemo( + // 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: stillSnoozed + ? withoutSnoozeOccupant(props.snoozeOccupancy, thread.snoozedUntil) + : props.snoozeOccupancy, + spacingMinutes: props.snoozeSpacingMinutes, + }), + [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. - () => (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 +932,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 +961,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..3f5f7c778e67f 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -8,6 +8,11 @@ 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, +} 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 +77,32 @@ 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, +): 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..15d43ede68cef 100644 --- a/apps/mobile/src/features/threads/useThreadListV2.ts +++ b/apps/mobile/src/features/threads/useThreadListV2.ts @@ -1,4 +1,7 @@ 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"; import { useMemo, useSyncExternalStore } from "react"; @@ -146,6 +149,18 @@ export function useThreadListV2(input: { )) && (searchQuery.length === 0 || pendingTask.title.toLocaleLowerCase().includes(searchQuery)), ); + // 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 ?? ""] : [], + ) + .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,8 @@ export function useThreadListV2(input: { moveAvailability, shelfPreferencesLoading: !input.shelfPreferencesLoaded, }); - return { layout, items, contentOnlyThreadKeys, olderSettledShelf }; + // Fork-local: rows read occupancy to space their own menu presets. + 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..e00ddda74a847 100644 --- a/apps/mobile/src/state/thread-list-environments.ts +++ b/apps/mobile/src/state/thread-list-environments.ts @@ -36,6 +36,8 @@ 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, }; } @@ -71,9 +73,12 @@ function collectEnvironments(environments: ReadonlyMap(); const activeReorderEnvironmentIds = new Set(); const titleRegenerationEnvironmentIds = new Set(); - for (const [id, { providers, machineKind, capabilities }] of environments) { + // 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); 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 +97,8 @@ 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..dc1e1369ac111 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -1,4 +1,9 @@ import type { TimestampFormat } from "@t3tools/contracts/settings"; +// Fork-local: presets come back spaced, each carrying its own wake time. +import { + spaceSnoozePresets, + type SnoozeSpacing, +} from "@t3tools/client-runtime/state/snooze-spacing"; import { resolveSnoozePresets as resolveSharedSnoozePresets, snoozeWakeLabel, @@ -13,20 +18,38 @@ 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, + 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; +} + +// Fork-local: optional spacing spreads presets and relabels them from their slots. 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..bb4247fe3c8a4 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -28,6 +28,12 @@ import { effectiveSnoozed, threadWokeAt, } from "@t3tools/client-runtime/state/thread-settled"; +// Fork-local: batch snoozes reserve wake times other threads still hold. +import { + allocateSnoozeSlots, + selectSnoozeOccupancy, + type SnoozeSpacing, +} from "@t3tools/client-runtime/state/snooze-spacing"; import { createInboxReturnTracker, isThreadWorking, @@ -53,10 +59,13 @@ 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, 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 +1227,43 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const threadByKeyRef = useRef(threadByKey); const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); + // 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. + 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, + }; + }; + + // 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( + now, + timestampFormat, + snoozeSpacingFor( + now, + thread.environmentId, + (candidate) => + candidate.id === thread.id && candidate.environmentId === thread.environmentId, + ), + ); + }); const jumpLabelByKey = (() => { const mapping = new Map(); @@ -1562,6 +1608,8 @@ 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; }); const startActionSweep = useStableCallback( @@ -2073,7 +2121,19 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const unpinMenuItem = buildBulkUnpinContextMenuItem({ pinnedCount: pinnedSelectedThreads.length, }); - const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat); + // Fork-local: a multi-select snooze ignores the selection's own reservations. + 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); + // 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( [ @@ -2145,17 +2205,33 @@ 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); + // Fork-local: presets fan out across free slots; a custom time stays exact. + 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: + snoozeBasePresets.find((candidate) => `snooze:${candidate.id}` === clicked.value) + ?.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 +2256,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 +2459,8 @@ 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); + // Fork-local: rows spread theirs against the other threads' wake times. + const snoozePresets = resolveRowSnoozePresets(thread); const threadProjectGroup = projectGroupsRef.current.find((project) => project.memberProjectRefs.some( @@ -3038,6 +3133,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..e111d12546778 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -16,7 +16,10 @@ 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, type ResponseStreamingMode, type QuitConfirmationMode, SidebarProjectSortOrder, @@ -471,6 +474,10 @@ 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"] + : []), ...(settings.wordWrap !== DEFAULT_UNIFIED_SETTINGS.wordWrap ? ["Word wrap"] : []), ...(settings.persistComposerContextStrip !== DEFAULT_UNIFIED_SETTINGS.persistComposerContextStrip @@ -634,6 +641,8 @@ 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, continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, @@ -682,12 +691,19 @@ export function useSettingsRestore(onRestored?: () => void) { const AUTO_SETTLE_DEFAULT_DAYS = DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ?? 3; -function AutoSettleDaysInput({ +// Fork-local: widened from auto-settle days so spacing can reuse the same field. +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 +716,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 +1002,35 @@ export function GeneralSettingsPanel() { } /> + {/* Fork-local: spacing between snoozes that would otherwise wake together. */} + + 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..de1f4268d0bcb 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -344,6 +344,13 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: ["usage quota rate limit reset wake recover continue"], }, + // Fork-local: makes the spacing row reachable from settings search. + { + 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..5a25016509e90 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -365,15 +365,15 @@ function SidebarThreadTooltip({ ); } +// Fork-local: presets resolve per opening, against the slots other threads hold. 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 +541,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 +1440,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..a92e3bf4b13c3 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" }], + 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 0804fc007e1a6..66a6646afdfff 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -8,8 +8,11 @@ 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, + DEFAULT_SERVER_SETTINGS, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -31,6 +34,9 @@ import { readEnvironmentSupportsSettlement, readEnvironmentSupportsSnooze, readEnvironmentSupportsTitleRegeneration, + // Fork-local: spacing comes from the thread's environment and every shell. + readEnvironmentSnoozeSpacingMinutes, + readQuietThreadShells, readThreadShell, useProjects, } from "../state/entities"; @@ -129,7 +135,17 @@ export function useThreadActionMenu(input: { titleRegeneration: readEnvironmentSupportsTitleRegeneration(threadRef.environmentId), }; const isRegeneratingTitle = thread.titleRegeneration != null; - const snoozePresets = resolveSnoozePresets(now, timestampFormat); + // Fork-local: skip this thread's own wake time so it can move into a free slot. + const snoozePresets = resolveSnoozePresets(now, timestampFormat, { + occupied: selectSnoozeOccupancy(readQuietThreadShells(), { + now: now.toISOString(), + exclude: (candidate) => + candidate.id === thread.id && candidate.environmentId === thread.environmentId, + }), + spacingMinutes: + readEnvironmentSnoozeSpacingMinutes(thread.environmentId) ?? + DEFAULT_SERVER_SETTINGS.snoozeSpacingMinutes, + }); const items = buildThreadActionMenuItems({ canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), branch: thread.branch ?? null, 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 45e568efd3fb8..5e1dffa6b0ae6 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -265,3 +265,11 @@ several selected threads together. Choose **Wake thread** to bring a thread back 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 +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. 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..9abb086f570a8 --- /dev/null +++ b/packages/client-runtime/src/state/snoozeSpacing.test.ts @@ -0,0 +1,313 @@ +// @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("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({ + 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({