From cb133ebf091f0c92ee82a4ef10935a596802d074 Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Tue, 17 Nov 2026 09:37:34 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=97=93=EF=B8=8F=20feat:=20Align=20Balance?= =?UTF-8?q?=20Resets=20to=20Fixed=20Calendar=20Boundaries=20(#18144)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🗓️ feat: Align Balance Resets to Fixed Calendar Boundaries Add balance.refillAnchor, an ISO timestamp with a fixed offset that periods align to: a refill or reset is due at the first anchor-plus-whole-intervals boundary after the last one, so every user resets at the same moment (e.g. each Monday at 00:00 UTC, or the 1st of each month). Omitted, periods keep running from each user's last refill. The gauge names the reset date for anchored periods. * 🧭 fix: Clear a Removed Reset Anchor During Admission and Shape Balance Responses in TS A policy built without a record now always carries refillAnchor, null when unset, so removing the setting clears a stored anchor instead of looping admission until its retry bound throws. Balance response shaping moves to toBalanceResponse in packages/api; the CJS controller delegates to it. --- api/server/controllers/Balance.js | 11 +- client/src/components/Balance/Summary.tsx | 13 +- .../Balance/__tests__/Summary.spec.tsx | 20 +++ client/src/locales/en/translation.json | 1 + client/src/utils/balance.ts | 34 ++-- librechat.example.yaml | 3 + packages/api/src/middleware/balance.spec.ts | 47 +++++- packages/api/src/middleware/balance.ts | 28 +++- .../api/src/middleware/checkBalance.spec.ts | 29 ++++ packages/api/src/types/balance.ts | 1 + packages/data-provider/specs/balance.spec.ts | 147 +++++++++++++++++ .../specs/config-schemas.spec.ts | 31 ++++ packages/data-provider/src/balance.ts | 152 ++++++++++++++++++ packages/data-provider/src/config.ts | 33 +++- packages/data-provider/src/types.ts | 2 + .../src/methods/transaction.spec.ts | 36 +++++ .../data-schemas/src/methods/transaction.ts | 5 +- packages/data-schemas/src/methods/user.ts | 2 + packages/data-schemas/src/schema/balance.ts | 4 + packages/data-schemas/src/types/balance.ts | 4 +- packages/data-schemas/src/types/user.ts | 1 + 21 files changed, 566 insertions(+), 38 deletions(-) create mode 100644 packages/data-provider/specs/balance.spec.ts diff --git a/api/server/controllers/Balance.js b/api/server/controllers/Balance.js index ebf963da6c..116520946d 100644 --- a/api/server/controllers/Balance.js +++ b/api/server/controllers/Balance.js @@ -1,3 +1,4 @@ +const { toBalanceResponse } = require('@librechat/api'); const { findBalanceByUser } = require('~/models'); async function balanceController(req, res) { @@ -13,15 +14,7 @@ async function balanceController(req, res) { return res.status(404).json({ error: 'Balance not found' }); } - const { _id: _, ...result } = balanceData; - - if (!result.autoRefillEnabled) { - delete result.refillIntervalValue; - delete result.refillIntervalUnit; - delete result.refillAmount; - } - - res.status(200).json(result); + res.status(200).json(toBalanceResponse(balanceData)); } module.exports = balanceController; diff --git a/client/src/components/Balance/Summary.tsx b/client/src/components/Balance/Summary.tsx index a986dea84a..5b8ef16897 100644 --- a/client/src/components/Balance/Summary.tsx +++ b/client/src/components/Balance/Summary.tsx @@ -4,7 +4,7 @@ import { useTimeTick } from '@librechat/chat/react'; import { Progress, Skeleton } from '@librechat/client'; import type { BalanceSummary, BalanceTone, CurrencyConfig } from '~/utils'; import type { BalanceState } from '~/hooks/useBalanceSummary'; -import { formatBalanceAmount, formatTimeUntil } from '~/utils/balance'; +import { formatBalanceAmount, formatResetDate, formatTimeUntil } from '~/utils/balance'; import useLocalize from '~/hooks/useLocalize'; import cn from '~/utils/cn'; @@ -32,12 +32,17 @@ function useRefillText(summary: BalanceSummary, currency?: CurrencyConfig): stri /** Re-render once a minute so "in 5 minutes" counts down while the view stays open */ useTimeTick(); - const { display, refillAmount, refillMode, nextRefill } = summary; + const { display, refillAmount, refillMode, nextRefill, anchored } = summary; if (refillAmount == null) { return localize('com_ui_balance_no_refill'); } - const when = - nextRefill != null ? formatTimeUntil(nextRefill, Date.now(), i18n.resolvedLanguage) : null; + let when: string | null = null; + if (nextRefill != null && anchored) { + const date = formatResetDate(nextRefill, Date.now(), i18n.resolvedLanguage); + when = date != null ? localize('com_ui_balance_on_date', { 0: date }) : null; + } else if (nextRefill != null) { + when = formatTimeUntil(nextRefill, Date.now(), i18n.resolvedLanguage); + } if (refillMode === 'reset') { if (display === 'percent') { return when != null diff --git a/client/src/components/Balance/__tests__/Summary.spec.tsx b/client/src/components/Balance/__tests__/Summary.spec.tsx index 9e8b6a0e00..97cd288009 100644 --- a/client/src/components/Balance/__tests__/Summary.spec.tsx +++ b/client/src/components/Balance/__tests__/Summary.spec.tsx @@ -84,6 +84,26 @@ describe('balance Summary', () => { ); }); + it('names the reset date instead of a countdown for anchored periods', () => { + render( + , + ); + const expected = new Intl.DateTimeFormat('en', { + weekday: 'short', + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + }).format(new Date('2026-07-06T00:00:00.000Z')); + expect(screen.getByTestId('balance-refill')).toHaveTextContent(`Usage resets on ${expected}`); + }); + it('shows the reset target in currency mode', () => { render(); expect(screen.getByTestId('balance-refill')).toHaveTextContent('Resets to $5.00 in 3 days'); diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json index ece65bff6a..9f5e4dc31b 100644 --- a/client/src/locales/en/translation.json +++ b/client/src/locales/en/translation.json @@ -292,6 +292,7 @@ "com_ui_balance_no_refill": "Doesn't refill automatically", "com_ui_balance_refill_amount_in": "+{{0}} available {{1}}", "com_ui_balance_refill_amount_when_empty": "+{{0}} when you run out", + "com_ui_balance_on_date": "on {{0}}", "com_ui_balance_reset_in": "Usage resets {{0}}", "com_ui_balance_reset_due": "Usage resets on your next request", "com_ui_balance_reset_amount_in": "Resets to {{0}} {{1}}", diff --git a/client/src/utils/balance.ts b/client/src/utils/balance.ts index 0930611c78..7c62933687 100644 --- a/client/src/utils/balance.ts +++ b/client/src/utils/balance.ts @@ -1,7 +1,8 @@ import { CREDITS_PER_USD, + parseRefillAnchor, + getNextRefillDate, getGrantedAllotment, - getRefillEligibilityDate, } from 'librechat-data-provider'; import type { BalanceDisplay, BalanceRefillMode, TBalanceResponse } from 'librechat-data-provider'; import type { CurrencyConfig } from './tokens'; @@ -31,6 +32,8 @@ export interface BalanceSummary { refillMode: BalanceRefillMode; /** When the next auto-refill becomes eligible; null without auto-refill. */ nextRefill: Date | null; + /** Periods fall on fixed calendar boundaries, so the reset reads as a date, not a countdown. */ + anchored: boolean; } interface SummaryOptions { @@ -41,18 +44,6 @@ interface SummaryOptions { const positive = (value: unknown): number | null => typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : null; -function getNextRefill(balance: TBalanceResponse): Date | null { - const { lastRefill, refillIntervalValue, refillIntervalUnit } = balance; - if (lastRefill == null || refillIntervalValue == null || refillIntervalUnit == null) { - return null; - } - const last = new Date(lastRefill); - if (Number.isNaN(last.getTime())) { - return null; - } - return getRefillEligibilityDate(last, refillIntervalValue, refillIntervalUnit); -} - /** * Percent spent is floored while credits remain, so a nearly drained balance never * reads "100% used" before it is actually empty; an empty balance is fully spent @@ -93,7 +84,8 @@ export function summarizeBalance( tone, refillAmount, refillMode: balance.refillMode ?? 'add', - nextRefill: balance.autoRefillEnabled ? getNextRefill(balance) : null, + nextRefill: balance.autoRefillEnabled ? getNextRefillDate(balance) : null, + anchored: balance.autoRefillEnabled === true && parseRefillAnchor(balance.refillAnchor) != null, }; } @@ -115,6 +107,20 @@ const MINUTE_MS = 60_000; const HOUR_MS = 60 * MINUTE_MS; const DAY_MS = 24 * HOUR_MS; +/** "Mon, Nov 17, 12:00 AM" in the viewer's locale and time zone; null once the moment has passed. */ +export function formatResetDate(target: Date, now: number, locale?: string): string | null { + if (!(target.getTime() > now)) { + return null; + } + return new Intl.DateTimeFormat(locale, { + weekday: 'short', + month: 'short', + day: 'numeric', + hour: 'numeric', + minute: '2-digit', + }).format(target); +} + /** "in 5 minutes" / "in 3 hours" / "in 4 days"; null once the moment has passed. */ export function formatTimeUntil(target: Date, now: number, locale?: string): string | null { const remaining = target.getTime() - now; diff --git a/librechat.example.yaml b/librechat.example.yaml index 584b72bf32..b88d95cf76 100644 --- a/librechat.example.yaml +++ b/librechat.example.yaml @@ -506,6 +506,9 @@ registration: # refillAmount: 10000 # # Deploy reset-capable servers to every replica before selecting 'reset'. # refillMode: 'add' # 'reset' replaces the allowance each period without rollover +# # Align every period to this instant plus whole intervals, e.g. weekly resets every Monday +# # at 00:00 UTC. Needs a Z or ±HH:MM offset; omit for periods that run from each user's last refill. +# # refillAnchor: '2026-01-05T00:00:00Z' # reservationTtlMs: 1800000 # How long an in-flight request's reserved credits count if never released # display: 'credits' # credits | currency (uses interface.currency) | percent (share of the allotment used) diff --git a/packages/api/src/middleware/balance.spec.ts b/packages/api/src/middleware/balance.spec.ts index 4b39f9c1b0..123c47ab29 100644 --- a/packages/api/src/middleware/balance.spec.ts +++ b/packages/api/src/middleware/balance.spec.ts @@ -3,7 +3,7 @@ import { MongoMemoryServer } from 'mongodb-memory-server'; import { logger, balanceSchema } from '@librechat/data-schemas'; import type { NextFunction, Request as ServerRequest, Response as ServerResponse } from 'express'; import type { IBalance, IBalanceUpdate } from '@librechat/data-schemas'; -import { buildBalanceUpdateFields, createSetBalanceConfig } from './balance'; +import { toBalanceResponse, buildBalanceUpdateFields, createSetBalanceConfig } from './balance'; jest.mock('@librechat/data-schemas', () => ({ ...jest.requireActual('@librechat/data-schemas'), @@ -830,6 +830,32 @@ describe('createSetBalanceConfig', () => { }); }); +describe('toBalanceResponse', () => { + const record = { + _id: 'balance-1', + tokenCredits: 100, + refillAmount: 500, + refillIntervalValue: 1, + refillIntervalUnit: 'weeks', + refillAnchor: '2026-01-05T00:00:00Z', + lastRefill: new Date('2026-07-01T00:00:00.000Z'), + }; + test('returns the refill schedule, anchor included, under auto-refill', () => { + const { _id: _, ...rest } = record; + expect(toBalanceResponse({ ...record, autoRefillEnabled: true })).toEqual({ + ...rest, + autoRefillEnabled: true, + }); + }); + test('hides the schedule but keeps the period start without auto-refill', () => { + expect(toBalanceResponse({ ...record, autoRefillEnabled: false })).toEqual({ + tokenCredits: 100, + autoRefillEnabled: false, + lastRefill: record.lastRefill, + }); + }); +}); + describe('balance refill mode synchronization', () => { const config = { autoRefillEnabled: true, @@ -846,4 +872,23 @@ describe('balance refill mode synchronization', () => { const record = { ...config, refillMode: 'reset', lastRefill: new Date() } as IBalance; expect(buildBalanceUpdateFields(config, record, 'user-1')).toEqual({ refillMode: 'add' }); }); + test('syncs an added anchor and clears a removed one', () => { + const refillAnchor = '2026-01-05T00:00:00Z'; + const record = { ...config, refillMode: 'add', lastRefill: new Date() } as IBalance; + expect(buildBalanceUpdateFields({ ...config, refillAnchor }, record, 'user-1')).toEqual({ + refillAnchor, + }); + const anchored = { ...record, refillAnchor } as IBalance; + expect(buildBalanceUpdateFields(config, anchored, 'user-1')).toEqual({ refillAnchor: null }); + }); + test('disables auto-refill for an anchor whose interval cannot form boundaries', () => { + const record = { ...config, refillMode: 'add', lastRefill: new Date() } as IBalance; + expect( + buildBalanceUpdateFields( + { ...config, refillIntervalValue: 0.5, refillAnchor: '2026-01-05T00:00:00Z' }, + record, + 'user-1', + ), + ).toEqual({ autoRefillEnabled: false }); + }); }); diff --git a/packages/api/src/middleware/balance.ts b/packages/api/src/middleware/balance.ts index 5fe33824f3..64b31e1212 100644 --- a/packages/api/src/middleware/balance.ts +++ b/packages/api/src/middleware/balance.ts @@ -94,7 +94,7 @@ export function buildBalanceUpdateFields( config.refillIntervalValue != null && config.refillIntervalUnit != null && config.refillAmount != null && - (config.refillMode !== 'reset' || + ((config.refillMode !== 'reset' && config.refillAnchor == null) || (Number.isInteger(config.refillIntervalValue) && config.refillIntervalValue > 0)); if (!isAutoRefillConfigValid) { @@ -125,6 +125,12 @@ export function buildBalanceUpdateFields( updateFields.refillAmount = config.refillAmount; } + // A policy built without a record carries the anchor even when cleared, so it can clear one. + const refillAnchor = config.refillAnchor ?? null; + if (userRecord == null || (userRecord.refillAnchor ?? null) !== refillAnchor) { + updateFields.refillAnchor = refillAnchor; + } + // Initialize lastRefill if it's missing when auto-refill is enabled if (config.autoRefillEnabled && !userRecord?.lastRefill) { updateFields.lastRefill ??= new Date(); @@ -133,6 +139,26 @@ export function buildBalanceUpdateFields( return updateFields; } +const AUTO_REFILL_FIELDS = [ + 'refillIntervalValue', + 'refillIntervalUnit', + 'refillAmount', + 'refillAnchor', +] as const; + +/** A balance record as the client reads it: no document id, and no refill schedule without + * auto-refill. `lastRefill` stays, since it places a stored allotment in its period. */ +export function toBalanceResponse(record: Record): Record { + const { _id: _, ...result } = record; + if (result.autoRefillEnabled === true) { + return result; + } + for (const field of AUTO_REFILL_FIELDS) { + delete result[field]; + } + return result; +} + /** * Factory function to create middleware that synchronizes user balance settings with current balance configuration. * @param options - Options containing getBalanceConfig function and Balance model diff --git a/packages/api/src/middleware/checkBalance.spec.ts b/packages/api/src/middleware/checkBalance.spec.ts index 04bf31dda1..c1dd3d7911 100644 --- a/packages/api/src/middleware/checkBalance.spec.ts +++ b/packages/api/src/middleware/checkBalance.spec.ts @@ -329,6 +329,7 @@ describe('checkBalance', () => { refillIntervalValue: 1, refillIntervalUnit: 'days', refillAmount: 1000, + refillAnchor: null, lastRefill: expect.any(Date), }); }); @@ -629,6 +630,34 @@ describe('checkBalance', () => { expect(await methods.getTransactions({ user, context: 'balanceReset' })).toHaveLength(0); }); + it('clears a removed anchor during admission instead of retrying until it fails', async () => { + const user = new mongoose.Types.ObjectId().toString(); + const lastRefill = new Date(); + const policy = { + autoRefillEnabled: true, + refillMode: 'reset' as const, + refillAmount: 1000, + refillIntervalValue: 1, + refillIntervalUnit: 'weeks' as const, + }; + await Balance.create({ + user, + ...policy, + tokenCredits: 500, + lastRefill, + refillAnchor: '2026-01-05T00:00:00Z', + }); + + const reservation = await checkBalance( + { req, res, txData: { ...baseTxData, user, amount: 100 } }, + realDeps({ startBalance: 1000, ...policy }), + ); + await reservation.release(); + + const record = await Balance.findOne({ user }).lean(); + expect(record).toMatchObject({ tokenCredits: 500, refillAnchor: null, lastRefill }); + }); + it('lazily initializes a missing record and reserves against it', async () => { const user = new mongoose.Types.ObjectId().toString(); const deps = realDeps({ startBalance: 1000 }); diff --git a/packages/api/src/types/balance.ts b/packages/api/src/types/balance.ts index e6794c85af..48ec65b03c 100644 --- a/packages/api/src/types/balance.ts +++ b/packages/api/src/types/balance.ts @@ -8,6 +8,7 @@ export interface BalanceUpdateFields { refillIntervalUnit?: RefillIntervalUnit; refillAmount?: number; refillMode?: BalanceRefillMode; + refillAnchor?: string | null; lastRefill?: Date; /** Written only together with `tokenCredits`: the credits that grant starts the period with */ allotment?: number; diff --git a/packages/data-provider/specs/balance.spec.ts b/packages/data-provider/specs/balance.spec.ts new file mode 100644 index 0000000000..4d1baaa45d --- /dev/null +++ b/packages/data-provider/specs/balance.spec.ts @@ -0,0 +1,147 @@ +import { + parseRefillAnchor, + getNextRefillDate, + isBalanceRefillDue, + getAnchoredBoundaryAfter, +} from '../src/balance'; +import type { RefillIntervalUnit } from '../src/balance'; + +const at = (iso: string) => new Date(iso); +const boundary = (after: string, anchor: string, value: number, unit: RefillIntervalUnit) => { + const parsed = parseRefillAnchor(anchor); + if (parsed == null) { + throw new Error(`invalid anchor ${anchor}`); + } + return getAnchoredBoundaryAfter(at(after), parsed, value, unit)?.toISOString() ?? null; +}; + +describe('parseRefillAnchor', () => { + test.each([ + ['2026-01-05T00:00:00Z', Date.parse('2026-01-05T00:00:00Z'), 0], + ['2026-01-05T00:00Z', Date.parse('2026-01-05T00:00:00Z'), 0], + ['2026-01-05T00:00:00.250Z', Date.parse('2026-01-05T00:00:00.250Z'), 0], + ['2026-01-05T00:00:00-05:00', Date.parse('2026-01-05T05:00:00Z'), -5 * 3_600_000], + ['2026-01-05T09:30:00+05:30', Date.parse('2026-01-05T04:00:00Z'), 5.5 * 3_600_000], + ])('reads %s', (anchor, time, offsetMs) => { + expect(parseRefillAnchor(anchor)).toEqual({ time, offsetMs }); + }); + + test.each([ + '2026-01-05T00:00:00', + '2026-01-05', + '2026-02-30T00:00:00Z', + '2026-01-05T24:00:00Z', + '2026-01-05T00:00:00+15:00', + 'next monday', + '', + ])('rejects %s', (anchor) => { + expect(parseRefillAnchor(anchor)).toBeNull(); + }); +}); + +describe('getAnchoredBoundaryAfter', () => { + const monday = '2026-01-05T00:00:00Z'; + + test('lands on the next anchored weekday', () => { + expect(boundary('2026-11-14T12:00:00Z', monday, 1, 'weeks')).toBe('2026-11-16T00:00:00.000Z'); + }); + + test('starts the following period when called exactly on a boundary', () => { + expect(boundary('2026-11-16T00:00:00Z', monday, 1, 'weeks')).toBe('2026-11-23T00:00:00.000Z'); + }); + + test('steps whole multi-unit intervals from the anchor', () => { + expect(boundary('2026-11-14T12:00:00Z', monday, 2, 'weeks')).toBe('2026-11-23T00:00:00.000Z'); + expect(boundary('2026-11-24T12:00:00Z', monday, 2, 'weeks')).toBe('2026-12-07T00:00:00.000Z'); + }); + + test('works backwards from an anchor in the future', () => { + expect(boundary('2026-11-14T12:00:00Z', '2027-01-04T00:00:00Z', 1, 'weeks')).toBe( + '2026-11-16T00:00:00.000Z', + ); + }); + + test('aligns days and hours to the anchor time of day', () => { + expect(boundary('2026-11-14T12:00:00Z', '2026-01-01T06:00:00Z', 1, 'days')).toBe( + '2026-11-15T06:00:00.000Z', + ); + expect(boundary('2026-11-14T12:20:00Z', '2026-01-01T00:30:00Z', 1, 'hours')).toBe( + '2026-11-14T12:30:00.000Z', + ); + }); + + test('falls back to the last day of shorter months without drifting', () => { + const endOfMonth = '2026-01-31T00:00:00Z'; + expect(boundary('2026-02-10T00:00:00Z', endOfMonth, 1, 'months')).toBe( + '2026-02-28T00:00:00.000Z', + ); + expect(boundary('2026-02-28T00:00:00Z', endOfMonth, 1, 'months')).toBe( + '2026-03-31T00:00:00.000Z', + ); + expect(boundary('2028-02-01T00:00:00Z', endOfMonth, 1, 'months')).toBe( + '2028-02-29T00:00:00.000Z', + ); + }); + + test('reads monthly boundaries on the anchor offset wall clock', () => { + const newYork = '2026-01-01T00:00:00-05:00'; + expect(boundary('2026-03-01T04:00:00Z', newYork, 1, 'months')).toBe('2026-03-01T05:00:00.000Z'); + expect(boundary('2026-03-01T05:00:00Z', newYork, 1, 'months')).toBe('2026-04-01T05:00:00.000Z'); + }); + + test('steps multi-month intervals from an earlier anchor', () => { + expect(boundary('2026-11-14T00:00:00Z', '2026-01-01T00:00:00Z', 3, 'months')).toBe( + '2027-01-01T00:00:00.000Z', + ); + expect(boundary('2026-11-14T00:00:00Z', '2027-06-01T00:00:00Z', 3, 'months')).toBe( + '2026-12-01T00:00:00.000Z', + ); + }); + + test.each([0, -1, 1.5])('has no boundary for interval %s', (value) => { + expect(boundary('2026-11-14T00:00:00Z', monday, value, 'weeks')).toBeNull(); + }); +}); + +describe('anchored refill schedule', () => { + const weekly = { + autoRefillEnabled: true, + refillAmount: 1000, + refillMode: 'reset' as const, + refillIntervalValue: 1, + refillIntervalUnit: 'weeks' as const, + refillAnchor: '2026-01-05T00:00:00Z', + lastRefill: '2026-11-14T12:00:00Z', + }; + + test('is due at the next anchored boundary, not a full interval after the last refill', () => { + expect(isBalanceRefillDue(weekly, at('2026-11-15T23:59:59Z'))).toBe(false); + expect(isBalanceRefillDue(weekly, at('2026-11-16T00:00:00Z'))).toBe(true); + expect(getNextRefillDate(weekly)?.toISOString()).toBe('2026-11-16T00:00:00.000Z'); + }); + + test('grants one period after missed boundaries, then waits for the next one', () => { + const idle = { ...weekly, lastRefill: '2026-09-01T00:00:00Z' }; + expect(isBalanceRefillDue(idle, at('2026-11-17T10:00:00Z'))).toBe(true); + const reset = { ...weekly, lastRefill: '2026-11-17T10:00:00Z' }; + expect(isBalanceRefillDue(reset, at('2026-11-22T23:00:00Z'))).toBe(false); + expect(getNextRefillDate(reset)?.toISOString()).toBe('2026-11-23T00:00:00.000Z'); + }); + + test('keeps rolling periods without an anchor', () => { + const rolling = { ...weekly, refillAnchor: null }; + expect(isBalanceRefillDue(rolling, at('2026-11-16T00:00:00Z'))).toBe(false); + expect(getNextRefillDate(rolling)?.toISOString()).toBe('2026-11-21T12:00:00.000Z'); + }); + + test('applies the anchor to additive refills', () => { + const additive = { ...weekly, refillMode: 'add' as const }; + expect(isBalanceRefillDue(additive, at('2026-11-15T00:00:00Z'))).toBe(false); + expect(isBalanceRefillDue(additive, at('2026-11-16T00:00:00Z'))).toBe(true); + }); + + test('never refills an anchored record whose interval cannot form boundaries', () => { + const fractional = { ...weekly, refillMode: 'add' as const, refillIntervalValue: 0.5 }; + expect(isBalanceRefillDue(fractional, at('2027-01-01T00:00:00Z'))).toBe(false); + }); +}); diff --git a/packages/data-provider/specs/config-schemas.spec.ts b/packages/data-provider/specs/config-schemas.spec.ts index d9aaec254b..b00d462457 100644 --- a/packages/data-provider/specs/config-schemas.spec.ts +++ b/packages/data-provider/specs/config-schemas.spec.ts @@ -2153,6 +2153,37 @@ describe('balance refill mode', () => { }); }); +describe('balance refill anchor', () => { + test('is optional and keeps rolling periods by default', () => { + expect(balanceSchema.parse({ autoRefillEnabled: true }).refillAnchor).toBeUndefined(); + }); + test('accepts an ISO timestamp with an explicit offset', () => { + expect( + balanceSchema.parse({ + refillMode: 'reset', + refillIntervalValue: 1, + refillIntervalUnit: 'weeks', + refillAnchor: '2026-01-05T00:00:00-05:00', + }).refillAnchor, + ).toBe('2026-01-05T00:00:00-05:00'); + }); + test.each(['2026-01-05T00:00:00', 'monday', '2026-02-30T00:00:00Z'])( + 'rejects anchor %s', + (refillAnchor) => { + expect(balanceSchema.safeParse({ refillAnchor }).success).toBe(false); + }, + ); + test.each([0, 1.5])('rejects anchored interval %s even for additive refill', (value) => { + expect( + balanceSchema.safeParse({ + refillMode: 'add', + refillIntervalValue: value, + refillAnchor: '2026-01-05T00:00:00Z', + }).success, + ).toBe(false); + }); +}); + describe('reset interval validation', () => { test.each([0, -1, 0.5, 1.5])( 'rejects reset interval %s while preserving additive settings', diff --git a/packages/data-provider/src/balance.ts b/packages/data-provider/src/balance.ts index e657a5876f..79e70032de 100644 --- a/packages/data-provider/src/balance.ts +++ b/packages/data-provider/src/balance.ts @@ -33,6 +33,121 @@ function ensureExhaustive(value: never): void { void value; } +const UNIT_MS: Record, number> = { + seconds: 1000, + minutes: 60 * 1000, + hours: 60 * 60 * 1000, + days: 24 * 60 * 60 * 1000, + weeks: 7 * 24 * 60 * 60 * 1000, +}; + +const ANCHOR_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3})\d*)?)?(Z|([+-])(\d{2}):(\d{2}))$/; + +/** A reset anchor's instant and the fixed UTC offset its calendar fields are read in. */ +export interface RefillAnchor { + time: number; + offsetMs: number; +} + +/** + * Parses an ISO 8601 timestamp with an explicit `Z` or `±HH:MM` offset. Null for anything else, + * including timestamps without an offset, whose meaning would depend on the server's time zone. + */ +export function parseRefillAnchor(anchor: string | null | undefined): RefillAnchor | null { + const match = anchor == null ? null : ANCHOR_PATTERN.exec(anchor); + if (!match) { + return null; + } + const [, year, month, day, hour, minute, second, millis, , sign, offsetHours, offsetMinutes] = + match; + const offsetMs = + sign == null + ? 0 + : (sign === '-' ? -1 : 1) * (Number(offsetHours) * 60 + Number(offsetMinutes)) * 60 * 1000; + const wall = Date.UTC( + Number(year), + Number(month) - 1, + Number(day), + Number(hour), + Number(minute), + Number(second ?? 0), + Number((millis ?? '0').padEnd(3, '0')), + ); + const check = new Date(wall); + if ( + Number.isNaN(wall) || + check.getUTCMonth() !== Number(month) - 1 || + check.getUTCDate() !== Number(day) || + Number(hour) > 23 || + Number(minute) > 59 || + Number(second ?? 0) > 59 || + Math.abs(offsetMs) > 14 * 60 * 60 * 1000 + ) { + return null; + } + return { time: wall - offsetMs, offsetMs }; +} + +function daysInMonth(year: number, monthIndex: number): number { + return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate(); +} + +/** The `k`th monthly boundary from the anchor, read on the anchor's wall clock; a day the month + * lacks falls back to its last day. */ +function monthlyBoundary(anchor: RefillAnchor, months: number): number { + const wall = new Date(anchor.time + anchor.offsetMs); + const index = wall.getUTCFullYear() * 12 + wall.getUTCMonth() + months; + const year = Math.floor(index / 12); + const monthIndex = index - year * 12; + const day = Math.min(wall.getUTCDate(), daysInMonth(year, monthIndex)); + return ( + Date.UTC( + year, + monthIndex, + day, + wall.getUTCHours(), + wall.getUTCMinutes(), + wall.getUTCSeconds(), + wall.getUTCMilliseconds(), + ) - anchor.offsetMs + ); +} + +/** + * The first period boundary strictly after `after`, where boundaries fall on the anchor plus + * whole intervals in either direction. Null for a non-positive or fractional interval. + */ +export function getAnchoredBoundaryAfter( + after: Date, + anchor: RefillAnchor, + value: number, + unit: RefillIntervalUnit, +): Date | null { + if (!(Number.isInteger(value) && value > 0)) { + return null; + } + const from = after.getTime(); + if (unit !== 'months') { + const step = value * UNIT_MS[unit]; + const k = Math.floor((from - anchor.time) / step) + 1; + return new Date(anchor.time + k * step); + } + const wall = new Date(from + anchor.offsetMs); + const anchorWall = new Date(anchor.time + anchor.offsetMs); + const elapsed = + (wall.getUTCFullYear() - anchorWall.getUTCFullYear()) * 12 + + (wall.getUTCMonth() - anchorWall.getUTCMonth()); + let k = Math.floor(elapsed / value); + while (monthlyBoundary(anchor, k * value) <= from) { + k++; + } + while (monthlyBoundary(anchor, (k - 1) * value) > from) { + k--; + } + return new Date(monthlyBoundary(anchor, k * value)); +} + export function getRefillEligibilityDate( lastRefill: Date, value: number, @@ -85,6 +200,32 @@ export function getGrantedAllotment( return Number.isNaN(refilled) || granted < refilled ? null : allotment; } +type RefillSchedule = Pick< + TBalanceResponse, + 'lastRefill' | 'refillIntervalValue' | 'refillIntervalUnit' | 'refillAnchor' +>; + +/** + * When the period that started at `lastRefill` ends: the next anchored boundary when the record + * has a valid anchor, else `lastRefill` plus one interval. Null without a readable `lastRefill`, + * or for an anchor with an interval no boundary can be built from. + */ +export function getNextRefillDate(record: RefillSchedule): Date | null { + const { lastRefill, refillIntervalValue, refillIntervalUnit } = record; + if (lastRefill == null || refillIntervalValue == null || refillIntervalUnit == null) { + return null; + } + const last = new Date(lastRefill); + if (Number.isNaN(last.getTime())) { + return null; + } + const anchor = parseRefillAnchor(record.refillAnchor); + if (anchor != null) { + return getAnchoredBoundaryAfter(last, anchor, refillIntervalValue, refillIntervalUnit); + } + return getRefillEligibilityDate(last, refillIntervalValue, refillIntervalUnit); +} + /** Whether the configured refill/reset period has elapsed. */ export function isBalanceRefillDue( record: Pick< @@ -95,6 +236,7 @@ export function isBalanceRefillDue( | 'lastRefill' | 'refillIntervalValue' | 'refillIntervalUnit' + | 'refillAnchor' >, now: Date, ): boolean { @@ -115,6 +257,16 @@ export function isBalanceRefillDue( if (isNaN(lastRefill.getTime())) { return true; } + const anchor = parseRefillAnchor(record.refillAnchor); + if (anchor != null) { + const boundary = getAnchoredBoundaryAfter( + lastRefill, + anchor, + record.refillIntervalValue ?? 0, + record.refillIntervalUnit ?? 'days', + ); + return boundary != null && now >= boundary; + } const eligibleAt = getRefillEligibilityDate( lastRefill, record.refillIntervalValue ?? 0, diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts index f03575391c..9e591c599e 100644 --- a/packages/data-provider/src/config.ts +++ b/packages/data-provider/src/config.ts @@ -21,6 +21,14 @@ import { MAX_PII_PATTERNS_PER_SOURCE, MAX_PII_PATTERN_LENGTH, } from './filters'; +import { + REFILL_INTERVAL_UNITS, + BALANCE_DISPLAY_MODES, + BALANCE_REFILL_MODES, + MIN_BALANCE_RESERVATION_TTL_MS, + DEFAULT_BALANCE_RESERVATION_TTL_MS, + parseRefillAnchor, +} from './balance'; import { EModelEndpoint, eModelEndpointSchema, @@ -29,13 +37,6 @@ import { eReasoningParameterFormatSchema, eReasoningResponseKeySchema, } from './schemas'; -import { - REFILL_INTERVAL_UNITS, - BALANCE_DISPLAY_MODES, - BALANCE_REFILL_MODES, - MIN_BALANCE_RESERVATION_TTL_MS, - DEFAULT_BALANCE_RESERVATION_TTL_MS, -} from './balance'; import { scheduledMCPResourceBindingSchema, scheduledMCPReadOnlyPolicySchema, @@ -4339,6 +4340,14 @@ export const balanceSchema = z refillAmount: z.number().optional().default(10000), /** Add credits on exhaustion, or replace the allowance on the next read/request once due. */ refillMode: z.enum(BALANCE_REFILL_MODES).optional().default('add'), + /** Aligns every period to this instant plus whole intervals (e.g. a Monday at 00:00Z for + * weekly resets); omitted, each user's period runs from their own last refill. */ + refillAnchor: z + .string() + .refine((anchor) => parseRefillAnchor(anchor) != null, { + message: 'Use an ISO 8601 timestamp with a Z or ±HH:MM offset', + }) + .optional(), reservationTtlMs: z .number() .int() @@ -4359,6 +4368,16 @@ export const balanceSchema = z message: 'Reset intervals must be positive integers', }); } + if ( + balance.refillAnchor != null && + !(Number.isInteger(balance.refillIntervalValue) && balance.refillIntervalValue > 0) + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['refillIntervalValue'], + message: 'Anchored intervals must be positive integers', + }); + } }); export const transactionsSchema = z.object({ diff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.ts index 03f55b1827..5a93749b77 100644 --- a/packages/data-provider/src/types.ts +++ b/packages/data-provider/src/types.ts @@ -1362,6 +1362,8 @@ export type TBalanceResponse = { lastRefill?: Date | string; refillAmount?: number; refillMode?: BalanceRefillMode; + /** ISO timestamp with offset that periods are aligned to; null or absent for rolling periods. */ + refillAnchor?: string | null; /** Credits granted at the start of the current period; absent on records not yet granted one. */ allotment?: number; /** When `allotment` was granted; a later `lastRefill` means a writer replaced the period without it. */ diff --git a/packages/data-schemas/src/methods/transaction.spec.ts b/packages/data-schemas/src/methods/transaction.spec.ts index a88bc20d28..e2496f9233 100644 --- a/packages/data-schemas/src/methods/transaction.spec.ts +++ b/packages/data-schemas/src/methods/transaction.spec.ts @@ -1667,6 +1667,42 @@ describe('Balance Reservations', () => { expect(resets[0].rawAmount).toBe(-500); }); + test('resets at an anchored boundary before a full interval has passed', async () => { + const user = new mongoose.Types.ObjectId(); + const anchor = new Date(Date.now() - 60 * 60 * 1000).toISOString(); + await Balance.create({ + user, + ...resettable, + refillIntervalValue: 1, + refillIntervalUnit: 'weeks', + lastRefill: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), + tokenCredits: 300, + }); + + expect((await findBalanceByUser(user.toString()))?.tokenCredits).toBe(300); + const synced = await reserveBalance({ + user: user.toString(), + reservationId: newId(), + amount: 100, + expiresAt: inFuture(), + refillPolicy: { + autoRefillEnabled: true, + refillMode: 'reset', + refillAmount: 1000, + refillIntervalValue: 1, + refillIntervalUnit: 'weeks', + refillAnchor: anchor, + }, + }); + + expect(synced).toEqual({ reserved: true, balance: 1000 }); + const state = await readState(user); + expect(state?.refillAnchor).toBe(anchor); + expect(state?.tokenCredits).toBe(1000); + expect(await findBalanceByUser(user.toString())).toMatchObject({ tokenCredits: 1000 }); + expect(await Transaction.countDocuments({ user, context: 'balanceReset' })).toBe(1); + }); + test('synchronizes a changed allowance before applying a due reset', async () => { const user = new mongoose.Types.ObjectId(); await Balance.create({ user, ...resettable, tokenCredits: 500 }); diff --git a/packages/data-schemas/src/methods/transaction.ts b/packages/data-schemas/src/methods/transaction.ts index 5e2ce325ac..4b4111ba39 100644 --- a/packages/data-schemas/src/methods/transaction.ts +++ b/packages/data-schemas/src/methods/transaction.ts @@ -104,6 +104,7 @@ function initialDebitBalance(balance: TxData['balance']): IBalanceUpdate | undef refillMode: balance.refillMode ?? 'add', refillIntervalValue: balance.refillIntervalValue, refillIntervalUnit: balance.refillIntervalUnit, + refillAnchor: balance.refillAnchor ?? null, }; } @@ -429,6 +430,7 @@ export function createTransactionMethods( refillMode: record.refillMode ?? null, refillIntervalValue: record.refillIntervalValue ?? null, refillIntervalUnit: record.refillIntervalUnit ?? null, + refillAnchor: record.refillAnchor ?? null, }, { $set: { @@ -563,7 +565,8 @@ export function createTransactionMethods( ((record.refillMode ?? 'add') !== (refillPolicy.refillMode ?? 'add') || record.refillAmount !== refillPolicy.refillAmount || record.refillIntervalValue !== refillPolicy.refillIntervalValue || - record.refillIntervalUnit !== refillPolicy.refillIntervalUnit))) + record.refillIntervalUnit !== refillPolicy.refillIntervalUnit || + (record.refillAnchor ?? null) !== (refillPolicy.refillAnchor ?? null)))) ) { await upsertBalanceRecord(user, refillPolicy); continue; diff --git a/packages/data-schemas/src/methods/user.ts b/packages/data-schemas/src/methods/user.ts index 52378bc0d5..41b3e10fa2 100644 --- a/packages/data-schemas/src/methods/user.ts +++ b/packages/data-schemas/src/methods/user.ts @@ -324,6 +324,7 @@ export function createUserMethods( refillIntervalUnit?: RefillIntervalUnit; refillAmount?: number; refillMode?: BalanceRefillMode; + refillAnchor?: string | null; allotment: number; allottedAt: Date; lastRefill: Date; @@ -345,6 +346,7 @@ export function createUserMethods( initial.refillIntervalUnit = balanceConfig.refillIntervalUnit; initial.refillAmount = balanceConfig.refillAmount; initial.refillMode = balanceConfig.refillMode ?? 'add'; + initial.refillAnchor = balanceConfig.refillAnchor ?? null; } await Balance.findOneAndUpdate( diff --git a/packages/data-schemas/src/schema/balance.ts b/packages/data-schemas/src/schema/balance.ts index 815809b042..5514e1a717 100644 --- a/packages/data-schemas/src/schema/balance.ts +++ b/packages/data-schemas/src/schema/balance.ts @@ -42,6 +42,10 @@ const balanceSchema: Schema = new Schema({ enum: BALANCE_REFILL_MODES, default: 'add', }, + /** ISO timestamp with offset that periods align to; null or absent for rolling periods */ + refillAnchor: { + type: String, + }, /** Credits granted at the start of the current period; usage percent is measured against it */ allotment: { type: Number, diff --git a/packages/data-schemas/src/types/balance.ts b/packages/data-schemas/src/types/balance.ts index 8bae6f79c7..efe2a06ca1 100644 --- a/packages/data-schemas/src/types/balance.ts +++ b/packages/data-schemas/src/types/balance.ts @@ -25,6 +25,7 @@ export interface IBalance extends Document { lastRefill: Date; refillAmount: number; refillMode?: BalanceRefillMode; + refillAnchor?: string | null; /** Credits granted at the start of the current period, kept when the configured amount changes */ allotment?: number; /** When `allotment` was granted; stale once `lastRefill` is later */ @@ -46,6 +47,7 @@ export interface IBalanceUpdate { refillIntervalUnit?: RefillIntervalUnit; refillAmount?: number; refillMode?: BalanceRefillMode; + refillAnchor?: string | null; lastRefill?: Date; allotment?: number; allottedAt?: Date; @@ -65,7 +67,7 @@ export interface BalanceReservationRequest { /** Current request policy; synchronized before existing-record admission without changing credits. */ refillPolicy?: Pick< IBalanceUpdate, - 'refillAmount' | 'refillIntervalValue' | 'refillIntervalUnit' + 'refillAmount' | 'refillIntervalValue' | 'refillIntervalUnit' | 'refillAnchor' > & { autoRefillEnabled: boolean; refillMode: BalanceRefillMode; diff --git a/packages/data-schemas/src/types/user.ts b/packages/data-schemas/src/types/user.ts index 962b5faaa5..287b9cb202 100644 --- a/packages/data-schemas/src/types/user.ts +++ b/packages/data-schemas/src/types/user.ts @@ -138,6 +138,7 @@ export interface BalanceConfig { refillIntervalUnit?: RefillIntervalUnit; refillAmount?: number; refillMode?: BalanceRefillMode; + refillAnchor?: string; reservationTtlMs?: number; }