From 152221f3dd79bf0b3bc7d22b0b0da64216dbeda2 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 17:59:48 +0100 Subject: [PATCH] feat(usage): shared quota observation ledger and conditional recovery insights for 1.2.1 --- ai/chatgpt/CHANGELOG.md | 14 ++ ai/chatgpt/README.md | 37 ++-- ai/chatgpt/docs/quota-insights.md | 48 +++++ ai/chatgpt/package.json | 2 +- ai/chatgpt/src/main.ts | 138 +++++++------- ai/chatgpt/src/session.ts | 10 +- ai/chatgpt/src/tours.ts | 4 +- ai/perplexity/CHANGELOG.md | 14 ++ ai/perplexity/README.md | 1 + ai/perplexity/docs/quota-insights.md | 48 +++++ ai/perplexity/package.json | 2 +- ai/perplexity/src/main.ts | 102 +++++------ .../src/modules/usage-status/service.ts | 12 +- ai/perplexity/src/tours.ts | 4 +- bun.lock | 4 +- core/ai/src/features/index.ts | 2 + core/ai/src/features/quota-insights/index.ts | 101 +++++++++++ core/ai/src/features/quota-insights/tour.ts | 15 ++ core/ai/src/index.ts | 2 + core/ai/src/quota.ts | 170 ++++++++++++++++++ 20 files changed, 580 insertions(+), 150 deletions(-) create mode 100644 ai/chatgpt/docs/quota-insights.md create mode 100644 ai/perplexity/docs/quota-insights.md create mode 100644 core/ai/src/features/quota-insights/index.ts create mode 100644 core/ai/src/features/quota-insights/tour.ts create mode 100644 core/ai/src/quota.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index 3ef73fc..6c401b4 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [1.2.1] - 2026-11-10 + +### Added + +- Quota Insights: persistent counter observations, observed capacity lower bounds, last net increase and conditional recovery scenarios. +- Adjustable recovery horizon, +1 and +5 scenarios, and full-recovery scenarios when the API supplies capacity. +- Shared tutorial and platform documentation. + +### Fixed + +- Usage totals no longer fall back to configured allowances. +- Forecasts distinguish observed recovery from guaranteed refill mechanics. + ## [1.2.0] - 2026-11-10 ### Changed @@ -94,3 +107,4 @@ [1.1.1]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.1.1 [1.1.2]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.1.2 [1.2.0]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.2.0 +[1.2.1]: https://github.com/thenolle/userscripts/releases/tag/better-chatgpt-v1.2.1 diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md index e65229a..cce8f06 100644 --- a/ai/chatgpt/README.md +++ b/ai/chatgpt/README.md @@ -14,24 +14,25 @@ Updates arrive automatically. The script also checks on its own and offers to up ## Features -| Feature | What you get | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -| Usage Status | Remaining counts reported by ChatGPT, your plan, and low/empty alerts; totals and reset schedules are not inferred | -| Code Blocks V2 | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe copy | -| Message Splitter | Paste any amount of text; split into parts or attach as a file only when needed | -| Prompt Library | Your prompts plus community prompts, with a form for placeholders | -| Batch Runner | Run one template over a list, with pause, resume and reload recovery | -| Selection Toolbar | Ask, explain, summarize, fact-check or quote highlighted text | -| Exporter | Markdown, text, Word, PDF and JSON | -| Draft Guard | Drafts survive reloads; size meter; warning before closing with unsent text | -| Command Palette | Search every action | -| Enter as Newline | Enter adds a line, a shortcut sends | -| Message Queue | Queue follow-ups while an answer generates; they send one by one | -| Recall | Search everything you sent and reuse it | -| Tutorial | Guided tours of every feature, started from the “?” button in the header | -| Max Width | Full-width conversations, optional sidebar removal | -| Update Checker | Checks on load and every few minutes, tells you once per version | -| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | +| Feature | What you get | +| ----------------- | ---------------------------------------------------------------------------------------------------------------------- | +| Usage Status | Remaining counts reported by ChatGPT, your plan, and low/empty alerts; totals and reset schedules are not inferred | +| Quota Insights | Persistent counter observations, observed capacity lower bounds, last net increase, and conditional recovery scenarios | +| Code Blocks V2 | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe copy | +| Message Splitter | Paste any amount of text; split into parts or attach as a file only when needed | +| Prompt Library | Your prompts plus community prompts, with a form for placeholders | +| Batch Runner | Run one template over a list, with pause, resume and reload recovery | +| Selection Toolbar | Ask, explain, summarize, fact-check or quote highlighted text | +| Exporter | Markdown, text, Word, PDF and JSON | +| Draft Guard | Drafts survive reloads; size meter; warning before closing with unsent text | +| Command Palette | Search every action | +| Enter as Newline | Enter adds a line, a shortcut sends | +| Message Queue | Queue follow-ups while an answer generates; they send one by one | +| Recall | Search everything you sent and reuse it | +| Tutorial | Guided tours of every feature, started from the “?” button in the header | +| Max Width | Full-width conversations, optional sidebar removal | +| Update Checker | Checks on load and every few minutes, tells you once per version | +| Context Packs | Save sourced excerpts from conversations and assemble a previewable briefing for your next task | ## Shortcuts diff --git a/ai/chatgpt/docs/quota-insights.md b/ai/chatgpt/docs/quota-insights.md new file mode 100644 index 0000000..078b910 --- /dev/null +++ b/ai/chatgpt/docs/quota-insights.md @@ -0,0 +1,48 @@ +--- +title: Quota insights +description: Capacity evidence, observed recovery and conditional forecasts. +section: Guides +order: 25 +--- + +# Quota insights + +Open Settings → Quota Insights → Open Quota Insights, or find it in the command palette. + +## What is recorded + +The feature stores remaining counts, observation times, explicit API caps and reported reset timestamps. It does not store conversation text. + +History is limited to 30 days and 2,000 observations per counter. + +## Maximum allowance + +An observed peak means capacity is at least that large. A plateau does not prove the maximum. + +Full-recovery scenarios require an explicit API cap. A reported reset timestamp alone does not establish the refill amount. + +## Recovery calculations + +Positive changes are observed net recovery. Additional spending between observations can hide refill. + +The engine calculates an observed net recovery rate across comparable intervals. It excludes gaps longer than five minutes and intervals known to be cap-bound. + +Rate scenarios require 30 minutes of comparable observations, at least three positive intervals and a recent observation. + +## Forecasts + +The panel can show conditional +1, +5, full recovery and recovery within a selected number of minutes. + +These scenarios assume the observed net recovery rate continues and no additional units are spent. They are not guaranteed refill schedules or calibrated confidence intervals. + +Rolling-window recovery and batch resets can behave differently. The existing Perplexity rolling estimator remains separate. + +## Privacy and account changes + +Saved observations are local to each userscript. + +Perplexity uses its existing account/tier namespace. ChatGPT currently partitions by reported plan, not a verified account id. Do not mix accounts in the same userscript storage when evaluating its history. + +## Tutorial + +The Help menu includes a Quota insights walkthrough explaining observations, lower bounds and projections. diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index 706931a..881c49f 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-chatgpt", - "version": "1.2.0", + "version": "1.2.1", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 28169e7..bf17480 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,21 +1,22 @@ import { - BatchRunnerFeature, - CodeBlocksFeature, - CommandPaletteFeature, - ContextPacksFeature, - DraftGuardFeature, - EnterAsNewlineFeature, - ExporterFeature, - MaxWidthFeature, - MessageSplitterFeature, - PromptLibraryFeature, - PromptQueueFeature, - RecallFeature, - SelectionToolbarFeature, - TutorialFeature, - UpdatesFeature, - configurePlatform, - configureUi + BatchRunnerFeature, + CodeBlocksFeature, + CommandPaletteFeature, + ContextPacksFeature, + DraftGuardFeature, + EnterAsNewlineFeature, + ExporterFeature, + MaxWidthFeature, + MessageSplitterFeature, + PromptLibraryFeature, + PromptQueueFeature, + RecallFeature, + SelectionToolbarFeature, + TutorialFeature, + UpdatesFeature, + configurePlatform, + configureUi, + QuotaInsightsFeature } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' @@ -38,60 +39,61 @@ import { installTheme } from './theme' import { tutorialSource } from './tutorial-source' const onSend = (listener: () => void): (() => void) => - session.subscribe((event) => { - if (event === 'generation-start') listener() - }) + session.subscribe((event) => { + if (event === 'generation-start') listener() + }) whenReady(() => { - configureUi({ - id: 'better-chatgpt', - title: 'Better ChatGPT', - version: __VERSION__, - marker: uiMarker, - composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) - }) + configureUi({ + id: 'better-chatgpt', + title: 'Better ChatGPT', + version: __VERSION__, + marker: uiMarker, + composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) + }) - configurePlatform({ - id: 'better-chatgpt', - storage, - logger, - composer: composerKit, - generation: generationKit, - sendPrompt, - onSend, - threadOf, - promptsUrl: URLS.prompts, - exporter: exportSource, - release: { name: 'Better ChatGPT', slug: SLUG, version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, - tutorial: tutorialSource, - codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]'), - rejectEditable, - send: (editable) => void composerKit.sendComposer(editable), - splitterDefaults: SPLITTER_DEFAULTS, - attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null), - scroller: findScroller - }) + configurePlatform({ + id: 'better-chatgpt', + storage, + logger, + composer: composerKit, + generation: generationKit, + sendPrompt, + onSend, + threadOf, + promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better ChatGPT', slug: SLUG, version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, + tutorial: tutorialSource, + codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]'), + rejectEditable, + send: (editable) => void composerKit.sendComposer(editable), + splitterDefaults: SPLITTER_DEFAULTS, + attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null), + scroller: findScroller + }) - installTheme() + installTheme() - new App() - .register((context) => new HeaderButtonFeature(context)) - .register((context) => new PromptLibraryFeature(context)) - .register((context) => new SelectionToolbarFeature(context)) - .register((context) => new MaxWidthFeature(context, { storage, sidebar: { rule: { id: 'left-sidebar', selector: 'aside' }, label: 'Left Sidebar', defaultRemoved: false } })) - .register((context) => new CodeBlocksFeature(context)) - .register((context) => new EnterAsNewlineFeature(context)) - .register((context) => new MessageSplitterFeature(context)) - .register((context) => new BatchRunnerFeature(context)) - .register((context) => new DraftGuardFeature(context)) - .register((context) => new CommandPaletteFeature(context)) - .register((context) => new PromptQueueFeature(context)) - .register((context) => new RecallFeature(context)) - .register((context) => new ContextPacksFeature(context)) - .register((context) => new ExporterFeature(context)) - .register((context) => new UpdatesFeature(context)) - .register((context) => new UsageFeature(context)) - .register((context) => new TutorialFeature(context)) - .register((context) => new DiagnosticsFeature(context)) - .start() + new App() + .register((context) => new HeaderButtonFeature(context)) + .register((context) => new PromptLibraryFeature(context)) + .register((context) => new SelectionToolbarFeature(context)) + .register((context) => new MaxWidthFeature(context, { storage, sidebar: { rule: { id: 'left-sidebar', selector: 'aside' }, label: 'Left Sidebar', defaultRemoved: false } })) + .register((context) => new CodeBlocksFeature(context)) + .register((context) => new EnterAsNewlineFeature(context)) + .register((context) => new MessageSplitterFeature(context)) + .register((context) => new BatchRunnerFeature(context)) + .register((context) => new DraftGuardFeature(context)) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) + .register((context) => new ContextPacksFeature(context)) + .register((context) => new ExporterFeature(context)) + .register((context) => new UpdatesFeature(context)) + .register((context) => new UsageFeature(context)) + .register((context) => new QuotaInsightsFeature(context)) + .register((context) => new TutorialFeature(context)) + .register((context) => new DiagnosticsFeature(context)) + .start() }) diff --git a/ai/chatgpt/src/session.ts b/ai/chatgpt/src/session.ts index bc51ea2..c663a0a 100644 --- a/ai/chatgpt/src/session.ts +++ b/ai/chatgpt/src/session.ts @@ -5,6 +5,8 @@ import { parseFileLimitMb, parseJson, parseLimits, parseUsage } from './payloads import type { LimitProgress, UsageSnapshot } from './payloads' import { interpret } from './stream' import type { ChatEvent } from './stream' +import { QuotaLedger } from '@nolly/ai' +import { storage } from './storage' export type SessionEvent = 'generation-start' | 'generation-end' | 'conversation' | 'model' | 'limits' | 'usage' | 'plan' | 'user-message' @@ -20,6 +22,7 @@ export class ChatSession { private readonly limitMap = new Map() private readonly listeners = new Set<(event: SessionEvent) => void>() + private readonly quotaLedger = new QuotaLedger(storage) private parser = new SseParser() constructor(spy: ResponseSpy) { @@ -61,7 +64,12 @@ export class ChatSession { } private mergeLimits(limits: readonly LimitProgress[]): void { - for (const limit of limits) this.limitMap.set(limit.feature, limit) + const now = Date.now() + for (const limit of limits) { + this.limitMap.set(limit.feature, limit) + const resetAt = limit.resetAfter ? Date.parse(limit.resetAfter) : Number.NaN + this.quotaLedger.observe(`chatgpt:${this.plan ?? 'unidentified'}`, limit.feature, limit.feature.replace(/_/g, ' '), limit.remaining, null, Number.isFinite(resetAt) ? resetAt : null, now) + } this.emit('limits') } diff --git a/ai/chatgpt/src/tours.ts b/ai/chatgpt/src/tours.ts index 6187a7b..fd5b3be 100644 --- a/ai/chatgpt/src/tours.ts +++ b/ai/chatgpt/src/tours.ts @@ -1,4 +1,4 @@ -import { createPdfTour } from '@nolly/ai' +import { createPdfTour, createQuotaTour } from '@nolly/ai' import { contextPacksTour, loadPromptShortcut, loadShortcut, tour } from '@nolly/ai' import type { Tour } from '@nolly/ai' import { composerKit } from './kit' @@ -146,4 +146,4 @@ const contextPacks: Tour = { } } -export const TOURS: readonly Tour[] = [gettingStarted, usage, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour()] +export const TOURS: readonly Tour[] = [gettingStarted, usage, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour()] diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index c3bf8db..44e682f 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -2,6 +2,19 @@ All notable changes to Better Perplexity are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). +## [1.2.1] - 2026-11-10 + +### Added + +- Quota Insights: persistent counter observations, observed capacity lower bounds, last net increase and conditional recovery scenarios. +- Adjustable recovery horizon, +1 and +5 scenarios, and full-recovery scenarios when the API supplies capacity. +- Shared tutorial and platform documentation. + +### Fixed + +- Usage totals no longer fall back to configured allowances. +- Forecasts distinguish observed recovery from guaranteed refill mechanics. + ## [1.2.0] - 2026-11-10 ### Changed @@ -186,3 +199,4 @@ First public release. [1.1.1]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.1.1 [1.1.2]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.1.2 [1.2.0]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.2.0 +[1.2.1]: https://github.com/thenolle/userscripts/releases/tag/better-perplexity-v1.2.1 diff --git a/ai/perplexity/README.md b/ai/perplexity/README.md index dfd9a19..a6af04b 100644 --- a/ai/perplexity/README.md +++ b/ai/perplexity/README.md @@ -17,6 +17,7 @@ Updates arrive automatically. The script also checks on its own and offers to up | Feature | What you get | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | | Usage status | Reported remaining counts per mode in the header, hover summary and details dialog; totals and reset schedules are not invented | +| Quota Insights | Persistent counter observations, observed capacity lower bounds, last net increase and conditional recovery scenarios | | Code Blocks V2 | Language badges, syntax colours, line numbers, wrap, fold, download, indentation-safe selection copy | | Big messages | Paste any amount of text; split into parts or attach as a file only when needed | | Prompt library | Your prompts plus community prompts, with a form for placeholders | diff --git a/ai/perplexity/docs/quota-insights.md b/ai/perplexity/docs/quota-insights.md new file mode 100644 index 0000000..078b910 --- /dev/null +++ b/ai/perplexity/docs/quota-insights.md @@ -0,0 +1,48 @@ +--- +title: Quota insights +description: Capacity evidence, observed recovery and conditional forecasts. +section: Guides +order: 25 +--- + +# Quota insights + +Open Settings → Quota Insights → Open Quota Insights, or find it in the command palette. + +## What is recorded + +The feature stores remaining counts, observation times, explicit API caps and reported reset timestamps. It does not store conversation text. + +History is limited to 30 days and 2,000 observations per counter. + +## Maximum allowance + +An observed peak means capacity is at least that large. A plateau does not prove the maximum. + +Full-recovery scenarios require an explicit API cap. A reported reset timestamp alone does not establish the refill amount. + +## Recovery calculations + +Positive changes are observed net recovery. Additional spending between observations can hide refill. + +The engine calculates an observed net recovery rate across comparable intervals. It excludes gaps longer than five minutes and intervals known to be cap-bound. + +Rate scenarios require 30 minutes of comparable observations, at least three positive intervals and a recent observation. + +## Forecasts + +The panel can show conditional +1, +5, full recovery and recovery within a selected number of minutes. + +These scenarios assume the observed net recovery rate continues and no additional units are spent. They are not guaranteed refill schedules or calibrated confidence intervals. + +Rolling-window recovery and batch resets can behave differently. The existing Perplexity rolling estimator remains separate. + +## Privacy and account changes + +Saved observations are local to each userscript. + +Perplexity uses its existing account/tier namespace. ChatGPT currently partitions by reported plan, not a verified account id. Do not mix accounts in the same userscript storage when evaluating its history. + +## Tutorial + +The Help menu includes a Quota insights walkthrough explaining observations, lower bounds and projections. diff --git a/ai/perplexity/package.json b/ai/perplexity/package.json index 694cfd5..2873773 100644 --- a/ai/perplexity/package.json +++ b/ai/perplexity/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-perplexity", - "version": "1.2.0", + "version": "1.2.1", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index 5e15e57..83288c7 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,21 +1,22 @@ import { - BatchRunnerFeature, - CodeBlocksFeature, - CommandPaletteFeature, - ContextPacksFeature, - DraftGuardFeature, - EnterAsNewlineFeature, - ExporterFeature, - MaxWidthFeature, - MessageSplitterFeature, - PromptLibraryFeature, - PromptQueueFeature, - RecallFeature, - SelectionToolbarFeature, - TutorialFeature, - UpdatesFeature, - configurePlatform, - configureUi + BatchRunnerFeature, + CodeBlocksFeature, + CommandPaletteFeature, + ContextPacksFeature, + DraftGuardFeature, + EnterAsNewlineFeature, + ExporterFeature, + MaxWidthFeature, + MessageSplitterFeature, + PromptLibraryFeature, + PromptQueueFeature, + RecallFeature, + SelectionToolbarFeature, + TutorialFeature, + UpdatesFeature, + configurePlatform, + configureUi, + QuotaInsightsFeature } from '@nolly/ai' import { App } from './core/app' import { composerKit } from './core/composer' @@ -36,43 +37,44 @@ import { URLS } from './repo' import { tutorialSource } from './tutorial-source' const onSend = (listener: () => void): (() => void) => - fetchSpy.subscribe(({ method, url }) => { - if (isAskRequest(method, url)) listener() - }) + fetchSpy.subscribe(({ method, url }) => { + if (isAskRequest(method, url)) listener() + }) configureUi({ id: 'better-perplexity', title: 'Better Perplexity', version: __VERSION__, marker: uiMarker, composerActions: findComposerActions }) configurePlatform({ - id: 'better-perplexity', - storage, - logger, - composer: composerKit, - generation: generationKit, - sendPrompt, - onSend, - threadOf, - promptsUrl: URLS.prompts, - exporter: exportSource, - release: { name: 'Better Perplexity', slug: 'better-perplexity', version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, - tutorial: tutorialSource + id: 'better-perplexity', + storage, + logger, + composer: composerKit, + generation: generationKit, + sendPrompt, + onSend, + threadOf, + promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better Perplexity', slug: 'better-perplexity', version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, + tutorial: tutorialSource }) fetchSpy.install() new App() - .register((context) => new PromptLibraryFeature(context)) - .register((context) => new SelectionToolbarFeature(context)) - .register((context) => new MaxWidthFeature(context, { storage, hidden: ALWAYS_HIDDEN, layout: LAYOUT_RULES, sidebar: { rule: RIGHT_SIDEBAR, label: 'Right Sidebar', defaultRemoved: true } })) - .register((context) => new EnterAsNewlineFeature(context)) - .register((context) => new CodeBlocksFeature(context)) - .register((context) => new MessageSplitterFeature(context)) - .register((context) => new BatchRunnerFeature(context)) - .register((context) => new DraftGuardFeature(context)) - .register((context) => new CommandPaletteFeature(context)) - .register((context) => new ExporterFeature(context)) - .register((context) => new UsageStatusModule(context)) - .register((context) => new GlobalSettingsModule(context)) - .register((context) => new TutorialFeature(context)) - .register((context) => new UpdatesFeature(context)) - .register((context) => new PromptQueueFeature(context)) - .register((context) => new RecallFeature(context)) - .register((context) => new ContextPacksFeature(context)) - .start() + .register((context) => new PromptLibraryFeature(context)) + .register((context) => new SelectionToolbarFeature(context)) + .register((context) => new MaxWidthFeature(context, { storage, hidden: ALWAYS_HIDDEN, layout: LAYOUT_RULES, sidebar: { rule: RIGHT_SIDEBAR, label: 'Right Sidebar', defaultRemoved: true } })) + .register((context) => new EnterAsNewlineFeature(context)) + .register((context) => new CodeBlocksFeature(context)) + .register((context) => new MessageSplitterFeature(context)) + .register((context) => new BatchRunnerFeature(context)) + .register((context) => new DraftGuardFeature(context)) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new ExporterFeature(context)) + .register((context) => new UsageStatusModule(context)) + .register((context) => new GlobalSettingsModule(context)) + .register((context) => new QuotaInsightsFeature(context)) + .register((context) => new TutorialFeature(context)) + .register((context) => new UpdatesFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) + .register((context) => new ContextPacksFeature(context)) + .start() diff --git a/ai/perplexity/src/modules/usage-status/service.ts b/ai/perplexity/src/modules/usage-status/service.ts index 8d54625..9a9621e 100644 --- a/ai/perplexity/src/modules/usage-status/service.ts +++ b/ai/perplexity/src/modules/usage-status/service.ts @@ -11,6 +11,7 @@ import type { Send } from './model' import { resolvePlan } from './plan' import { findResetTimestamp } from './server-reset' import { ResetTracker } from './tracker' +import { QuotaLedger } from '@nolly/ai' import type { ActiveUsage, ApiDiagnostics, Forecast, FreeQueriesInfo, LimitKey, Plan, RateLimitResponse, SettingsResponse, Pace } from './types' type Listener = () => void @@ -43,6 +44,7 @@ export class UsageService { private sends: Send[] = loadSends() private lastUsedKey: LimitKey | null = storage.get(LAST_KEY, null) private readonly listeners = new Set() + private readonly quotaLedger = new QuotaLedger(storage) constructor( private readonly api = new UsageApi(), @@ -148,17 +150,16 @@ export class UsageService { if (!key) return null const cap = findCap(this.rate, key) const remaining = this.getRemaining(key) - if (cap === null || (remaining !== null && remaining > cap)) return null - return cap + return cap !== null && (remaining === null || cap >= remaining) ? cap : null } totalSource(key: LimitKey | null): 'api' | 'configured' | 'learned' | null { - return this.resolveTotal(key) !== null ? 'api' : null + return this.resolveTotal(key) === null ? null : 'api' } formatTotal(key: LimitKey | null): string | null { - const total = this.resolveTotal(key) - return total === null ? null : String(total) + const cap = this.resolveTotal(key) + return cap === null ? null : String(cap) } getForecast(key: LimitKey | null): Forecast | null { @@ -283,6 +284,7 @@ export class UsageService { for (const key of LIMIT_KEYS) { const value = rate[key] if (typeof value !== 'number' || !Number.isFinite(value)) continue + this.quotaLedger.observe(this.namespace(), key, LIMITS[key].label, value, findCap(rate, key), findResetTimestamp(rate, key), now) const { drop } = this.tracker.observe(key, value, now, this.sends) if (drop > 0 && now - this.lastSentAt < LEARN_WINDOW) { this.lastUsedKey = key diff --git a/ai/perplexity/src/tours.ts b/ai/perplexity/src/tours.ts index e1880d2..2a5e55b 100644 --- a/ai/perplexity/src/tours.ts +++ b/ai/perplexity/src/tours.ts @@ -1,4 +1,4 @@ -import { createPdfTour } from '@nolly/ai' +import { createPdfTour, createQuotaTour } from '@nolly/ai' import { findComposer } from './core/composer' import { contextPacksTour, loadPromptShortcut, loadShortcut, tour, type Tour } from '@nolly/ai' @@ -140,4 +140,4 @@ const contextPacks: Tour = { } } -export const TOURS: readonly Tour[] = [gettingStarted, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour()] +export const TOURS: readonly Tour[] = [gettingStarted, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour()] diff --git a/bun.lock b/bun.lock index 8871d23..0000c64 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ }, "ai/chatgpt": { "name": "@nolly/ai-chatgpt", - "version": "1.2.0", + "version": "1.2.1", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", @@ -19,7 +19,7 @@ }, "ai/perplexity": { "name": "@nolly/ai-perplexity", - "version": "1.2.0", + "version": "1.2.1", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 163438c..37aed10 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -24,3 +24,5 @@ export { ContextPacksFeature } from './context-packs' export { contextPacksTour } from './context-packs/tour' export * as tour from './tutorial/steps' export { createPdfTour } from './exporter/tour' +export { QuotaInsightsFeature } from './quota-insights' +export { createQuotaTour } from './quota-insights/tour' diff --git a/core/ai/src/features/quota-insights/index.ts b/core/ai/src/features/quota-insights/index.ts new file mode 100644 index 0000000..b4ddf4d --- /dev/null +++ b/core/ai/src/features/quota-insights/index.ts @@ -0,0 +1,101 @@ +import { Feature, createElement } from '@nolly/core' +import type { MenuEntry } from '@nolly/core' +import { QuotaLedger } from '../../quota' +import { storage } from '../../platform' +import { uiConfig } from '../../ui/config' +import { createButton, createDataRow, createNumberField, createSection } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' + +const duration = (ms: number): string => { + const minutes = Math.max(0, Math.ceil(ms / 60_000)) + if (minutes < 60) return `${minutes}m` + const hours = Math.floor(minutes / 60) + if (hours < 48) return `${hours}h ${minutes % 60}m` + return `${Math.floor(hours / 24)}d ${hours % 24}h` +} + +export class QuotaInsightsFeature extends Feature { + readonly id = 'quota-insights' + readonly name = 'Quota Insights' + readonly description = 'Inspect observed recovery, capacity evidence and conditional +1, +5 and full-recovery scenarios.' + + private readonly ledger = new QuotaLedger(storage) + + run(): void { } + + override menuEntries(): MenuEntry[] { + return [{ id: 'open', label: 'Open Quota Insights', action: () => this.open() }] + } + + private open(): void { + const id = `${uiConfig().id}-quota-insights` + const existing = document.getElementById(id) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + const ui = createDialog({ id, title: 'Quota insights', description: 'Observed counter changes and conditional recovery scenarios—not guaranteed refill schedules.', width: 720 }) + let horizon = 60 + const content = createElement('div', 'bp-stack') + const render = (): void => { + const reports = this.ledger.reports() + content.replaceChildren() + if (!reports.length) { + content.appendChild(createElement('div', 'bp-empty', 'No observations yet. Use the platform normally; observations arrive with its usage responses.')) + return + } + for (const report of reports) { + const section = createSection(report.label) + const rows = createElement('div', 'bp-data-list') + rows.append( + createDataRow('Remaining · last reported', String(report.remaining)), + createDataRow('Observed', new Date(report.observedAt).toLocaleString()), + createDataRow('Capacity', report.cap === null ? `Unknown · observed maximum ≥ ${report.peak}` : `${report.cap} · API-reported`), + createDataRow('Stored observations', String(report.observations)) + ) + if (report.lastIncrease) rows.append(createDataRow('Last net increase', `+${report.lastIncrease.units}`), createDataRow('Increase observed', `${duration(Date.now() - report.lastIncrease.to)} ago · occurred within a ${duration(report.lastIncrease.to - report.lastIncrease.from)} observation interval`)) + rows.append( + createDataRow('Comparable observation time', duration(report.sampledMs)), + createDataRow('Observed net recovery', String(report.netRecovered)), + createDataRow('Observed net spending', String(report.netSpent)) + ) + if (report.recoveryPerHour !== null) { + rows.appendChild(createDataRow('Observed net recovery rate', `~${report.recoveryPerHour.toFixed(2)} units/hour`)) + for (const scenario of report.scenarios) rows.appendChild(createDataRow(`+${scenario.units} · rate scenario`, `~${duration(scenario.estimatedMs)}`)) + const projected = report.recoveryPerHour * horizon / 60 + const missing = report.cap === null ? null : report.cap - report.remaining + const bounded = missing === null ? projected : Math.min(missing, projected) + rows.appendChild(createDataRow(`Recovery in ${horizon}m · rate scenario`, `~${Math.max(0, bounded).toFixed(1)} units`)) + } + rows.appendChild(createDataRow('Full recovery', report.fullMs === 0 ? 'At the API-reported cap' : report.fullMs === null ? 'Unknown · capacity or recovery evidence is insufficient' : `~${duration(report.fullMs)} · rate scenario`)) + if (report.resetAt !== null) rows.appendChild(createDataRow('API-reported reset', `${new Date(report.resetAt).toLocaleString()} · refill amount not assumed`)) + section.append( + rows, + createElement( + 'p', + 'bp-hint', + report.recoveryPerHour === null ? 'Rate scenarios require at least 30 minutes of comparable sampling, three positive intervals and a recent observation. Long gaps and known cap-bound intervals are excluded.' : 'Scenarios assume the observed net recovery rate continues, with no additional spending. Hidden spending, batching, cap changes and activity in other clients can invalidate them.' + ) + ) + content.appendChild(section) + } + } + const minutes = createNumberField({ + label: 'Forecast horizon · minutes', + value: horizon, + min: 1, + max: 10_080, + onChange: (value) => { + horizon = value + render() + } + }) + ui.body.append(minutes.wrapper, content) + ui.footer.append( + createButton('Update view', { onClick: render }), + createButton('Close', { primary: true, onClick: ui.close }) + ) + render() + ui.show() + } +} diff --git a/core/ai/src/features/quota-insights/tour.ts b/core/ai/src/features/quota-insights/tour.ts new file mode 100644 index 0000000..dc605f8 --- /dev/null +++ b/core/ai/src/features/quota-insights/tour.ts @@ -0,0 +1,15 @@ +import type { Tour } from '../tutorial/source' +import { info } from '../tutorial/steps' + +export const createQuotaTour = (): Tour => ({ + id: 'quota-insights', + title: 'Quota insights', + summary: 'Understand capacity evidence, observed recovery and conditional forecasts.', + steps: [ + info('Open Quota Insights', 'Use Settings or the command palette to open Quota Insights. It reads observations gathered from platform usage responses.'), + info('Maximum versus observed peak', 'An observed maximum is only a lower bound. Full-recovery scenarios require an explicit API capacity.'), + info('Recovery evidence', 'Counter increases are net recovery. Spending between observations may hide additional refill, and long sampling gaps are excluded from rate calculations.'), + info('Choose a horizon', 'Change the forecast horizon to inspect a conditional recovery scenario. +1, +5 and full recovery assume no new spending and a continuing observed rate.'), + info('Unknown is useful', 'If evidence is insufficient, forecasts remain unavailable rather than displaying a confident but invented countdown.') + ] +}) diff --git a/core/ai/src/index.ts b/core/ai/src/index.ts index c90f7ba..cee915e 100644 --- a/core/ai/src/index.ts +++ b/core/ai/src/index.ts @@ -15,3 +15,5 @@ export * from './selection' export * from './sse' export * from './tokens' export * from './ui' +export { QuotaLedger } from './quota' +export type { QuotaObservation, QuotaReport, RecoveryScenario } from './quota' diff --git a/core/ai/src/quota.ts b/core/ai/src/quota.ts new file mode 100644 index 0000000..ba67632 --- /dev/null +++ b/core/ai/src/quota.ts @@ -0,0 +1,170 @@ +import type { ScriptStorage } from '@nolly/core' + +export interface QuotaObservation { + readonly at: number + readonly remaining: number + readonly cap: number | null + readonly resetAt: number | null +} + +interface Counter { + readonly key: string + readonly label: string + readonly scope: string + points: QuotaObservation[] +} + +interface Database { + activeScope: string + counters: Record +} + +export interface RecoveryScenario { + readonly units: number + readonly estimatedMs: number +} + +export interface QuotaReport { + readonly label: string + readonly remaining: number + readonly observedAt: number + readonly cap: number | null + readonly peak: number + readonly observations: number + readonly lastIncrease: { + readonly from: number + readonly to: number + readonly units: number + } | null + readonly sampledMs: number + readonly netRecovered: number + readonly netSpent: number + readonly recoveryPerHour: number | null + readonly rateSpread: number | null + readonly positiveIntervals: number + readonly scenarios: readonly RecoveryScenario[] + readonly fullMs: number | null + readonly resetAt: number | null +} + +const KEY = 'quota-insights:v1' +const DAY = 86_400_000 +const MAX_POINTS = 2_000 +const MAX_COUNTERS = 64 +const MAX_GAP = 5 * 60_000 +const MIN_SPAN = 30 * 60_000 +const MAX_AGE = 30 * DAY + +const finite = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value) + +const validPoint = (value: unknown): value is QuotaObservation => { + if (!value || typeof value !== 'object') return false + const point = value as Partial + return finite(point.at) && finite(point.remaining) && point.remaining >= 0 && (point.cap === null || finite(point.cap)) && (point.resetAt === null || finite(point.resetAt)) +} + +const median = (values: readonly number[]): number => { + const sorted = [...values].sort((a, b) => a - b) + const middle = Math.floor(sorted.length / 2) + if (!sorted.length) return 0 + return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2 +} + +export class QuotaLedger { + constructor(private readonly storage: ScriptStorage) { } + + observe(scope: string, key: string, label: string, remaining: number, cap: number | null = null, resetAt: number | null = null, at = Date.now()): void { + if (!scope || !finite(remaining) || remaining < 0 || !finite(at)) return + const database = this.read() + const id = JSON.stringify([scope, key]) + const previous = database.counters[id] + const points = previous?.points ?? [] + const last = points.at(-1) + if (last && at <= last.at) return + if (last && at - last.at < 1_000 && last.remaining === remaining && last.cap === cap && last.resetAt === resetAt) return + points.push({ at, remaining, cap: finite(cap) && cap >= remaining && cap > 0 ? cap : null, resetAt: finite(resetAt) ? resetAt : null }) + database.activeScope = scope + database.counters[id] = { scope, key, label, points: points.filter((point) => at - point.at <= MAX_AGE).slice(-MAX_POINTS) } + const entries = Object.entries(database.counters).sort((a, b) => (b[1].points.at(-1)?.at ?? 0) - (a[1].points.at(-1)?.at ?? 0)).slice(0, MAX_COUNTERS) + database.counters = Object.fromEntries(entries) + this.storage.set(KEY, database) + } + + reports(now = Date.now()): QuotaReport[] { + const database = this.read() + return Object.values(database.counters).filter((counter) => counter.scope === database.activeScope).flatMap((counter): QuotaReport[] => { + const points = counter.points.filter((point) => point.at <= now && now - point.at <= MAX_AGE).sort((a, b) => a.at - b.at) + const latest = points.at(-1) + if (!latest) return [] + let lastIncrease: QuotaReport['lastIncrease'] = null + let sampledMs = 0 + let netRecovered = 0 + let netSpent = 0 + let positiveIntervals = 0 + const rates: number[] = [] + for (let index = 1; index < points.length; index++) { + const previous = points[index - 1]! + const current = points[index]! + const gap = current.at - previous.at + const delta = current.remaining - previous.remaining + if (delta > 0) lastIncrease = { from: previous.at, to: current.at, units: delta } + if (now - current.at > 7 * DAY || gap <= 0 || gap > MAX_GAP) continue + const capped = previous.cap !== null && previous.remaining >= previous.cap + const reachedCap = current.cap !== null && current.remaining >= current.cap + if (capped || reachedCap) continue + sampledMs += gap + netRecovered += Math.max(0, delta) + netSpent += Math.max(0, -delta) + if (delta > 0) positiveIntervals++ + rates.push(Math.max(0, delta) * 3_600_000 / gap) + } + const enough = sampledMs >= MIN_SPAN && positiveIntervals >= 3 && now - latest.at <= MAX_GAP && netRecovered > 0 + const rate = enough ? netRecovered * 3_600_000 / sampledMs : null + const center = median(rates) + const spread = rates.length ? 1.4826 * median(rates.map((value) => Math.abs(value - center))) : null + const missing = latest.cap === null ? null : Math.max(0, latest.cap - latest.remaining) + const scenarios = rate !== null ? [1, 5].filter((units) => missing === null || units <= missing).map((units) => ({ units, estimatedMs: units / rate * 3_600_000 })) : [] + return [{ + label: counter.label, + remaining: latest.remaining, + observedAt: latest.at, + cap: latest.cap, + peak: points.reduce((peak, point) => Math.max(peak, point.remaining), 0), + observations: points.length, + lastIncrease, + sampledMs, + netRecovered, + netSpent, + recoveryPerHour: rate, + rateSpread: enough ? spread : null, + positiveIntervals, + scenarios, + fullMs: missing === 0 ? 0 : missing !== null && rate !== null ? missing / rate * 3_600_000 : null, + resetAt: latest.resetAt + }] + }) + } + + private read(): Database { + const raw = this.storage.get(KEY, null) + if (!raw || typeof raw !== 'object') return { activeScope: '', counters: {} } + const database = raw as Partial + const counters: Record = {} + if (database.counters && typeof database.counters === 'object') { + for (const [id, candidate] of Object.entries(database.counters)) { + if (!candidate || typeof candidate !== 'object') continue + if (typeof candidate.scope !== 'string' || typeof candidate.key !== 'string' || typeof candidate.label !== 'string' || !Array.isArray(candidate.points)) continue + counters[id] = { + scope: candidate.scope, + key: candidate.key, + label: candidate.label, + points: candidate.points.filter(validPoint).slice(-MAX_POINTS) + } + } + } + return { + activeScope: typeof database.activeScope === 'string' ? database.activeScope : '', + counters + } + } +}