feat(web,mobile): snooze a thread until provider limits reset #9012
Closedvitalyiegorov(GitHub profile, opens in a new tab)wants to merge 8 commits into
main fromrefs/pull/9012/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/orchestration/decider.ts line 1241OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1228,3 +1229,13 @@12281229 return [unsettledEvent, sessionSetEvent];12291230 }123012311232+ case "thread.session.rate-limit-set": {1233+ // A limit report is provider bookkeeping, not thread activity: it must1234+ // never wake a settled thread, never move session.updatedAt (which would1235+ // raise a snoozed thread's hand and reorder sidebars), and never write an1236+ // event when nothing changed. A thread with no session has nowhere to1237+ // record it, which is normal for limits reported between sessions.1238+ const thread = findThreadById(readModel, command.threadId);1239+ const session = thread?.session;1240+ if (!session || (session.rateLimitResetsAt ?? null) === command.resetsAt) {1241+ return [];apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1680OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1659,10 +1664,17 @@16591664 runtimeMode: thread.session?.runtimeMode ?? "full-access",16601665 activeTurnId: nextActiveTurnId,16611666 lastError,1667+ rateLimitResetsAt,16621668 updatedAt: now,16631669 },16641670 createdAt: now,16651671 });16661672 }16671673 }166816741675+ // A limit is account-wide state, but the composer banner lives on the1676+ // thread the user is reading, so it rides that thread's session. An1677+ // absent limitResetsAt means the provider said nothing usable; the1678+ // decider drops the rest as a no-op when the value already matches.1679+ if (1680+ event.type === "account.rate-limits.updated" &&
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts lines 1721 to 1727OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1668,0 +1707,21 @@1707+ ) {1708+ // Best-effort bookkeeping: the session can be replaced or stopped1709+ // between this read and the dispatch, and a limit lost to that race1710+ // self-heals on the provider's next report. It must never fail the1711+ // ingestion stream.1712+ yield* orchestrationEngine1713+ .dispatch({1714+ type: "thread.session.rate-limit-set",1715+ commandId: yield* providerCommandId(event, "session-rate-limit-set"),1716+ threadId: thread.id,1717+ resetsAt: event.payload.limitResetsAt,1718+ createdAt: now,1719+ })1720+ .pipe(1721+ Effect.catchTag("OrchestrationCommandInvariantError", (error) =>1722+ Effect.logDebug("provider runtime ingestion skipped a usage limit update", {1723+ eventId: event.eventId,1724+ threadId: thread.id,1725+ detail: error.detail,1726+ }),1727+ ),
- apps/web/src/components/ChatView.tsx lines 4811 to 4815OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4767,0 +4795,21 @@4795+ const error = squashAtomCommandFailure(result);4796+ toastManager.add(4797+ stackedThreadToast({4798+ type: "error",4799+ title: "Failed to snooze thread",4800+ description: error instanceof Error ? error.message : "An error occurred.",4801+ }),4802+ );4803+ }4804+ return;4805+ }4806+ toastManager.add(4807+ stackedThreadToast({4808+ type: "success",4809+ title: `Snoozed until ${snoozeWakeDescription(usageLimitOffer.snoozedUntil, new Date(), timestampFormat)}`,4810+ timeout: 5_000,4811+ actionProps: {4812+ children: "Undo",4813+ onClick: () => {4814+ void handleUnsnoozeActiveThread();4815+ },
- apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1728OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1668,0 +1708,21 @@1708+ // Best-effort bookkeeping: the session can be replaced or stopped1709+ // between this read and the dispatch, and a limit lost to that race1710+ // self-heals on the provider's next report. It must never fail the1711+ // ingestion stream.1712+ yield* orchestrationEngine1713+ .dispatch({1714+ type: "thread.session.rate-limit-set",1715+ commandId: yield* providerCommandId(event, "session-rate-limit-set"),1716+ threadId: thread.id,1717+ resetsAt: event.payload.limitResetsAt,1718+ createdAt: now,1719+ })1720+ .pipe(1721+ Effect.catchTag("OrchestrationCommandInvariantError", (error) =>1722+ Effect.logDebug("provider runtime ingestion skipped a usage limit update", {1723+ eventId: event.eventId,1724+ threadId: thread.id,1725+ detail: error.detail,1726+ }),1727+ ),1728+ );
- apps/web/src/components/ChatView.tsx line 4779OutdatedResolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -4765,3 +4772,8 @@47654772 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));47664773 }47674774 }, [activeThreadRef, unsnoozeThreadMutation]);4775+ // Minute-quantized like the settle rules, so the offer expires on the same4776+ // shared tick instead of needing a timer of its own.4777+ const usageLimitOffer = useMemo(4778+ () =>4779+ activeThreadShell === null || !supportsSnooze
- apps/server/src/provider/Layers/CodexAdapter.ts line 1443OutdatedResolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -1418,2 +1423,21 @@14181423 return [];14191424 }1425+ // The notification already wraps the snapshot in `rateLimits`; forward the1426+ // snapshot itself rather than nesting it a second time.1427+ const snapshot = payload.rateLimits;1428+ // Every exhausted window has to clear before the account serves again, so1429+ // the account is limited until the LAST of them resets. ISO-8601 UTC1430+ // strings compare chronologically.1431+ const resetsAt = [snapshot.primary, snapshot.secondary]1432+ .map((window) =>1433+ window != null && window.usedPercent >= 100 ? rateLimitResetToIso(window.resetsAt) : null,1434+ )1435+ .reduce<string | null>(1436+ (latest, value) => (value !== null && (latest === null || value > latest) ? value : latest),1437+ null,1438+ );1439+ // Codex sends sparse rolling updates that explicitly "do not clear a1440+ // previously observed value", so this adapter only ever reports a limit,1441+ // never the absence of one. Staleness is bounded by the reset passing and1442+ // by a fresh session starting clean.1443+ const limited = snapshot.rateLimitReachedType != null && resetsAt !== null;apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts line 1643OutdatedResolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -1635,3 +1636,8 @@16351636 : status === "ready"16361637 ? null16371638 : (thread.session?.lastError ?? null);1639+ // Mid-session writes carry the reported limit forward; a provider1640+ // announcing a new session starts clean, so a limit left over from a1641+ // different provider or account cannot outlive the session that hit it.1642+ const rateLimitResetsAt =1643+ event.type === "session.started" ? null : (thread.session?.rateLimitResetsAt ?? null);
- packages/client-runtime/src/state/threadSettled.ts lines 296 to 300OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -261,0 +280,21 @@280+}281+282+/**283+ * The usage-limit offer for a thread, or null when there is nothing to say. A284+ * reset in the past is stale provider state, and a thread the user already285+ * parked has answered the offer.286+ */287+export function usageLimitSnoozeOffer(288+ shell: ThreadSnoozeShell & Pick<OrchestrationThreadShell, "latestUserMessageAt">,289+ options: { readonly now: string },290+): UsageLimitSnoozeOffer | null {291+ const resetsAt = shell.session?.rateLimitResetsAt;292+ if (resetsAt == null) return null;293+ const resetsAtMs = Date.parse(resetsAt);294+ if (Number.isNaN(resetsAtMs) || resetsAtMs <= Date.parse(options.now)) return null;295+ if (effectiveSnoozed(shell, options)) return null;296+ return {297+ resetsAt,298+ snoozedUntil: new Date(resetsAtMs + USAGE_LIMIT_SNOOZE_GRACE_MS).toISOString(),299+ snoozable: canSnooze(shell, options),300+ };
github-actions[bot](GitHub profile, opens in a new tab) removed labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
vitalyiegorov(GitHub profile, opens in a new tab) changed the title
- packages/shared/src/usageLimits.ts line 679Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -210,2 +210,21 @@210210 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;211211 }212+213+/**214+ * The latest reset among exhausted windows still ahead of `now`, or null when215+ * the account is serving. Every exhausted window has to clear before the216+ * account does, so the composer's "reset at" claim has to name the last one.217+ */218+export function exhaustedUntil(219+ limits: ServerProviderUsageLimits | undefined,220+ now: number,221+): string | null {222+ let latest: { readonly at: number; readonly resetsAt: string } | null = null;223+ for (const window of limits?.windows ?? []) {224+ if (window.usedPercent < 100 || window.resetsAt === undefined) continue;225+ const at = resetMillis(window);226+ if (at === null || at <= now) continue;227+ if (latest === null || at > latest.at) latest = { at, resetsAt: window.resetsAt };228+ }229+ return latest?.resetsAt ?? null;230+}
- packages/shared/src/usageLimits.ts line 658Resolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -209,3 +209,15 @@209209 if (resetsAt === null) return null;210210 return resetsAt <= now ? "resets now" : `resets in ${formatDuration(resetsAt - now)}`;211211 }212+213+/**214+ * Windows that gate every turn on the account: Claude's session and weekly215+ * allowances and Codex's two positions. Claude's model-scoped buckets216+ * (`seven_day_<model>`) only limit that one model, so they never count as217+ * the account being exhausted.218+ */219+const ACCOUNT_WIDE_WINDOW_IDS: ReadonlySet<string> = new Set([220+ "five_hour",221+ "seven_day",222+ "primary",223+ "secondary",
vitalyiegorov(GitHub profile, opens in a new tab) changed the title
- apps/web/src/components/Sidebar.snooze.ts line 30Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -18,8 +18,13 @@1818 export function resolveSnoozePresets(1919 now: Date,2020 timestampFormat: TimestampFormat,21+ options?: { readonly limitsResetAt?: string | null },2122 ): ReadonlyArray<SnoozePreset> {22- return resolveSharedSnoozePresets(now).map((preset) => {23+ return resolveSharedSnoozePresets(now, options).map((preset) => {2324 const wake = parseTimestampDate(preset.snoozedUntil);2425 if (wake === null) return preset;2526 const time = timeOfDayLabel(wake, timestampFormat);27+ if (preset.id === "limits-reset") {28+ return {29+ ...preset,30+ whenLabel: snoozeWakeDescription(preset.snoozedUntil, now, timestampFormat),
- apps/web/src/components/ChatView.tsx line 5560OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -5485,0 +5540,21 @@5540+ usageLimitPreset === null ||5541+ usageLimitResetsAt === null ||5542+ usageLimitKey === null ||5543+ activeThreadShell === null ||5544+ dismissedUsageLimitKeys.has(usageLimitKey)5545+ ) {5546+ return null;5547+ }5548+ const snoozable = canSnooze(activeThreadShell, { now: nowMinuteIso });5549+ return {5550+ id: `usage-limit:${usageLimitKey}`,5551+ variant: "warning",5552+ icon: <AlarmClockIcon />,5553+ title: "Usage limit reached",5554+ description: `Limits reset ${snoozeWakeDescription(usageLimitResetsAt, nowMinuteDate, timestampFormat)}`,5555+ actions: (5556+ <Button5557+ size="xs"5558+ variant="outline"5559+ disabled={!snoozable}5560+ title={snoozable ? undefined : "Snoozing is unavailable while work is pending"}
- apps/web/src/components/Sidebar.tsx line 463Resolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -434,10 +436,12 @@434436 onOpenChange: (open: boolean) => void;435437 onSnooze: (preset: SnoozePreset) => void;436438 timestampFormat: TimestampFormat;439+ usageLimits: ServerProviderUsageLimits | undefined;437440 }) {438- const { open, onOpenChange, onSnooze, timestampFormat } = props;441+ const { open, onOpenChange, onSnooze, timestampFormat, usageLimits } = props;439442 // Presets resolve at open time so "In 1 hour" is relative to the click,440443 // not to when the row mounted.441444 const presets = useMemo(442- () => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []),443- [open, timestampFormat],445+ () =>446+ open447+ ? resolveSnoozePresets(new Date(), timestampFormat, {
- apps/web/src/components/ChatView.tsx lines 6150 to 6152Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -5337,3 +5348,16 @@53375348 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));53385349 }53395350 }, [activeThreadRef, unsnoozeThreadMutation]);5351+ // Read off the provider snapshot the Limits tab already draws from: the5352+ // latest reset among the instance's exhausted windows, or null while it serves.5353+ const usageLimitResetsAt = useMemo(5354+ () => exhaustedUntil(conversationProviderStatus?.usageLimits, nowMinuteDate.getTime()),5355+ [conversationProviderStatus?.usageLimits, nowMinuteDate],5356+ );5357+ // The same preset the snooze menus lead with, on the shared minute tick so5358+ // the notice expires with it instead of needing a timer of its own.5359+ const usageLimitPreset = useMemo(5360+ () =>5361+ usageLimitResetsAt === null || !supportsSnooze || activeThreadSnoozed5362+ ? null5363+ : usageLimitSnoozePreset(usageLimitResetsAt, nowMinuteDate),
- apps/web/src/components/ChatView.tsx line 6143Resolvedby vitalyiegorov(GitHub profile, opens in a new tab)@@ -5337,3 +5348,7 @@53375348 setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));53385349 }53395350 }, [activeThreadRef, unsnoozeThreadMutation]);5351+ // Read off the provider snapshot the Limits tab already draws from: the5352+ // latest reset among the instance's exhausted windows, or null while it serves.5353+ const usageLimitResetsAt = useMemo(5354+ () => exhaustedUntil(conversationProviderStatus?.usageLimits, nowMinuteDate.getTime()),
- apps/web/src/components/Sidebar.tsx lines 4104 to 4106Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3916,4 +3928,15 @@39163928 const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);39173929 const isPinned = thread.pinnedAt != null;39183930 // Presets resolve at menu-open time (same as the popover).3919- const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);3931+ const menuProviderInstanceId =3932+ thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;3933+ const menuProviderEntry = providerEntriesByEnvironment3934+ .get(thread.environmentId)3935+ ?.get(menuProviderInstanceId);3936+ const menuLimitsResetAt = exhaustedUntil(3937+ menuProviderEntry?.snapshot.usageLimits,3938+ Date.now(),3939+ );3940+ const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat, {3941+ limitsResetAt: menuLimitsResetAt,3942+ });
- apps/web/src/components/Sidebar.tsx line 4149Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -3944,4 +3966,4 @@39443966 const preset = snoozePresets.find(39453967 (candidate) => `snooze:${candidate.id}` === clicked.value,39463968 );3947- if (preset) attemptSnooze(threadRef, preset);3969+ if (preset && !snoozePresetExpired(preset)) attemptSnooze(threadRef, preset);
juliusmarminge closed this
Sign in to join this conversation.


macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed