From 3f71d91157c7c5196ed6f897405c914adb0e5ae5 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 19:58:46 +0100 Subject: [PATCH] release: 1.2.4 wrapped code gutters, automatic folding, quota cards and Answer Diff --- ai/chatgpt/CHANGELOG.md | 19 ++ ai/chatgpt/README.md | 4 + ai/chatgpt/docs/answer-diff.md | 49 +++++ ai/chatgpt/docs/code-blocks-v2.md | 10 +- ai/chatgpt/docs/usage-quota-v2.md | 6 + ai/chatgpt/package.json | 2 +- ai/chatgpt/src/main.ts | 14 +- ai/chatgpt/src/tours.ts | 8 +- ai/perplexity/CHANGELOG.md | 19 ++ ai/perplexity/README.md | 4 + ai/perplexity/docs/answer-diff.md | 49 +++++ ai/perplexity/docs/code-blocks-v2.md | 10 +- ai/perplexity/docs/usage-quota-v2.md | 6 + ai/perplexity/package.json | 2 +- ai/perplexity/src/main.ts | 2 + ai/perplexity/src/tours.ts | 8 +- bun.lock | 6 +- core/ai/CHANGELOG.md | 8 + core/ai/package.json | 2 +- core/ai/src/features/answer-diff/compare.ts | 63 +++++++ core/ai/src/features/answer-diff/index.ts | 192 ++++++++++++++++++++ core/ai/src/features/answer-diff/tour.ts | 20 ++ core/ai/src/features/code-blocks/block.ts | 125 +++++++++---- core/ai/src/features/code-blocks/styles.ts | 21 ++- core/ai/src/features/index.ts | 2 + core/ai/src/ui/composer-toolbar.ts | 2 +- core/ai/src/ui/quota-panel.ts | 163 +++++++++++++---- 27 files changed, 716 insertions(+), 100 deletions(-) create mode 100644 ai/chatgpt/docs/answer-diff.md create mode 100644 ai/perplexity/docs/answer-diff.md create mode 100644 core/ai/src/features/answer-diff/compare.ts create mode 100644 core/ai/src/features/answer-diff/index.ts create mode 100644 core/ai/src/features/answer-diff/tour.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index 5512b13..0c2ee92 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -1,5 +1,24 @@ # Changelog +## [1.2.4] - 2026-11-10 + +### Added + +- Answer Diff: local line-by-line comparisons, an explicitly saved baseline, copy/download and a guided tutorial. +- Quota recovery cards with +1, +5, full recovery, adjustable horizon and local scenario times when evidence is sufficient. + +### Fixed + +- Wrapped code retains enabled line numbers and measures each logical line's rendered height. +- Long code blocks automatically fold according to the configured threshold. +- Code-block resize observers are released when enhanced blocks are removed. +- Original inline display styles are restored when code enhancement is disabled. + +### Documentation + +- Added Answer Diff privacy, persistence, comparison limits and tutorial documentation. +- Updated code wrapping, folding and quota-card instructions. + ## [1.2.2] - 2026-11-10 ### Changed diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md index 6363129..b554754 100644 --- a/ai/chatgpt/README.md +++ b/ai/chatgpt/README.md @@ -83,3 +83,7 @@ PDF export opens a print-ready preview with a contents list, readable sections, ## Usage Quota V2 The header usage dialog combines reported allowances, capacity evidence and observation-based recovery scenarios. See [Usage Quota V2](docs/usage-quota-v2.md). + +## Answer Diff + +Compare two answers or code revisions locally, inspect exact text changes, and explicitly save a reusable baseline. Nothing is sent automatically. See [Answer diff](docs/answer-diff.md). diff --git a/ai/chatgpt/docs/answer-diff.md b/ai/chatgpt/docs/answer-diff.md new file mode 100644 index 0000000..c7e5ada --- /dev/null +++ b/ai/chatgpt/docs/answer-diff.md @@ -0,0 +1,49 @@ +--- +title: Answer diff +description: Compare exact changes between answers or code revisions. +section: Guides +order: 46 +--- + +# Answer diff + +Answer Diff compares two pieces of text locally. It does not send messages, call an AI service or judge which answer is correct. + +## Compare revisions + +1. Select an answer before opening Answer diff, or copy the answer yourself. +2. Open the Answer diff composer tool. +3. Put the original text in Baseline and the revision in Revision. +4. Click Compare. +5. Inspect added, removed and unchanged lines. +6. Copy or download the comparison if useful. + +Blank lines and indentation participate in the comparison. Line endings are normalized. + +## Reuse a baseline + +Save baseline explicitly stores the left editor's text, source URL and save time. + +Return from another conversation, paste the revised answer and compare it against that baseline. You can also paste text from the other platform manually. + +Each installed userscript has its own storage; there is no automatic synchronization. + +Replacing or deleting the saved baseline asks for confirmation. Deleting the saved baseline does not erase text already in the open editors. + +## Privacy + +Editor text is not saved automatically. Only Save baseline persists content. + +Explicitly saved temporary-chat content persists locally. Do not save secrets or sensitive information. Stored source URLs omit query parameters and fragments, but may contain conversation identifiers. + +## Limits + +Each editor accepts up to 100,000 characters. + +The exact line comparison uses a bounded longest-common-subsequence matrix. If the changed region is too large, it is shown as a coarse removal/addition block, clearly labelled. + +The downloaded comparison is a readable report, not a patch intended for automatic application. + +## Tutorial + +Open Help and choose Answer diff. diff --git a/ai/chatgpt/docs/code-blocks-v2.md b/ai/chatgpt/docs/code-blocks-v2.md index 653deaf..e10923d 100644 --- a/ai/chatgpt/docs/code-blocks-v2.md +++ b/ai/chatgpt/docs/code-blocks-v2.md @@ -20,8 +20,8 @@ The feature does not alter ChatGPT's editable Run-code editors. ## Reading - Wrap toggles visual wrapping without changing the source. -- Line numbers appear when wrapping is off. -- Fold is available for sufficiently long blocks, but code starts expanded. +- Line numbers remain available with wrapping and align with logical source lines. +- Long blocks automatically fold at the configured threshold. Expand code reveals the full block; a threshold of zero disables automatic folding. - Download saves the original source text. Syntax highlighting is retained only when its reconstructed text matches the source. Otherwise the block falls back to plain text rather than corrupting code. @@ -39,3 +39,9 @@ Copy a selection containing blank lines, tabs and nested indentation into a plai Code panels follow the site's explicit light/dark theme, with a GitHub-like syntax palette. Language badges retain their language-associated colors. Badges are typographic representations, not official logo artwork. Additional filename labels and conservative content signatures improve detection. New language labels may use an approximate syntax palette or plain text; the original source remains authoritative. + +## Wrapping and folding in 1.2.4 + +Wrapping and line numbers are independent toggles. A wrapped logical line keeps one source line number. The gutter is remeasured when the code viewport resizes. + +Long blocks automatically fold according to the configured threshold. A threshold of zero disables this behavior. Copy and download still use the complete source. diff --git a/ai/chatgpt/docs/usage-quota-v2.md b/ai/chatgpt/docs/usage-quota-v2.md index 81d6d35..f740e9c 100644 --- a/ai/chatgpt/docs/usage-quota-v2.md +++ b/ai/chatgpt/docs/usage-quota-v2.md @@ -38,3 +38,9 @@ Perplexity reports are requested using its current account/tier namespace. ChatG ## Tutorial Open Help and choose Usage Quota V2. There is no separate Quota Insights module to enable. + +## Recovery cards + +The dialog displays +1, +5 and full-recovery cards. When evidence supports a scenario, each card shows a relative duration and an estimated local clock time. These are conditional rate scenarios, not guaranteed server refill deadlines. + +Change the recovery horizon to inspect projected recovery within a selected number of minutes. Expand the evidence section for observations, sampled duration and net counter changes. diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index 36e4211..4abdd0d 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-chatgpt", - "version": "1.2.2", + "version": "1.2.4", "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 4d184e1..5f710ff 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -16,6 +16,7 @@ import { UpdatesFeature, configurePlatform, configureUi, + AnswerDiffFeature, } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' @@ -79,19 +80,20 @@ whenReady(() => { .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 UsageFeature(context)) + .register((context) => new DiagnosticsFeature(context)) .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 TutorialFeature(context)) + .register((context) => new UpdatesFeature(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)) + .register((context) => new AnswerDiffFeature(context)) .start() }) diff --git a/ai/chatgpt/src/tours.ts b/ai/chatgpt/src/tours.ts index ec4a139..4a83de4 100644 --- a/ai/chatgpt/src/tours.ts +++ b/ai/chatgpt/src/tours.ts @@ -1,4 +1,4 @@ -import { createPdfTour, createQuotaTour } from '@nolly/ai' +import { createAnswerDiffTour, createPdfTour, createQuotaTour } from '@nolly/ai' import { contextPacksTour, loadPromptShortcut, loadShortcut, tour } from '@nolly/ai' import type { Tour } from '@nolly/ai' import { composerKit } from './kit' @@ -99,8 +99,8 @@ const codeBlocks: Tour = { find('.bp-code-v2 .bp-code-actions') ), info( - 'Themes and language detection', - 'Code panels follow the site light/dark theme. Language-colored badges remain colored. Filename labels and conservative signatures identify more languages; highlighting remains approximate and never changes the source text.' + 'Wrapping and folding', + 'Line numbers remain visible while wrapping and align with logical source lines. Long blocks automatically fold at the configured threshold. Expand code or use the fold button to reveal them. Setting the threshold to zero disables automatic folding.' ) ] } @@ -146,4 +146,4 @@ const contextPacks: Tour = { } } -export const TOURS: readonly Tour[] = [gettingStarted, usage, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour()] +export const TOURS: readonly Tour[] = [gettingStarted, usage, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour(), createAnswerDiffTour()] diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 78563bf..921f488 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -2,6 +2,25 @@ 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.4] - 2026-11-10 + +### Added + +- Answer Diff: local line-by-line comparisons, an explicitly saved baseline, copy/download and a guided tutorial. +- Quota recovery cards with +1, +5, full recovery, adjustable horizon and local scenario times when evidence is sufficient. + +### Fixed + +- Wrapped code retains enabled line numbers and measures each logical line's rendered height. +- Long code blocks automatically fold according to the configured threshold. +- Code-block resize observers are released when enhanced blocks are removed. +- Original inline display styles are restored when code enhancement is disabled. + +### Documentation + +- Added Answer Diff privacy, persistence, comparison limits and tutorial documentation. +- Updated code wrapping, folding and quota-card instructions. + ## [1.2.2] - 2026-11-10 ### Changed diff --git a/ai/perplexity/README.md b/ai/perplexity/README.md index eae1ae6..49fb3a7 100644 --- a/ai/perplexity/README.md +++ b/ai/perplexity/README.md @@ -91,3 +91,7 @@ PDF export opens a print-ready preview with a contents list, readable sections, ## Usage Quota V2 The header usage dialog combines reported allowances, capacity evidence and observation-based recovery scenarios. See [Usage Quota V2](docs/usage-quota-v2.md). + +## Answer Diff + +Compare two answers or code revisions locally, inspect exact text changes, and explicitly save a reusable baseline. Nothing is sent automatically. See [Answer diff](docs/answer-diff.md). diff --git a/ai/perplexity/docs/answer-diff.md b/ai/perplexity/docs/answer-diff.md new file mode 100644 index 0000000..c7e5ada --- /dev/null +++ b/ai/perplexity/docs/answer-diff.md @@ -0,0 +1,49 @@ +--- +title: Answer diff +description: Compare exact changes between answers or code revisions. +section: Guides +order: 46 +--- + +# Answer diff + +Answer Diff compares two pieces of text locally. It does not send messages, call an AI service or judge which answer is correct. + +## Compare revisions + +1. Select an answer before opening Answer diff, or copy the answer yourself. +2. Open the Answer diff composer tool. +3. Put the original text in Baseline and the revision in Revision. +4. Click Compare. +5. Inspect added, removed and unchanged lines. +6. Copy or download the comparison if useful. + +Blank lines and indentation participate in the comparison. Line endings are normalized. + +## Reuse a baseline + +Save baseline explicitly stores the left editor's text, source URL and save time. + +Return from another conversation, paste the revised answer and compare it against that baseline. You can also paste text from the other platform manually. + +Each installed userscript has its own storage; there is no automatic synchronization. + +Replacing or deleting the saved baseline asks for confirmation. Deleting the saved baseline does not erase text already in the open editors. + +## Privacy + +Editor text is not saved automatically. Only Save baseline persists content. + +Explicitly saved temporary-chat content persists locally. Do not save secrets or sensitive information. Stored source URLs omit query parameters and fragments, but may contain conversation identifiers. + +## Limits + +Each editor accepts up to 100,000 characters. + +The exact line comparison uses a bounded longest-common-subsequence matrix. If the changed region is too large, it is shown as a coarse removal/addition block, clearly labelled. + +The downloaded comparison is a readable report, not a patch intended for automatic application. + +## Tutorial + +Open Help and choose Answer diff. diff --git a/ai/perplexity/docs/code-blocks-v2.md b/ai/perplexity/docs/code-blocks-v2.md index 653deaf..e10923d 100644 --- a/ai/perplexity/docs/code-blocks-v2.md +++ b/ai/perplexity/docs/code-blocks-v2.md @@ -20,8 +20,8 @@ The feature does not alter ChatGPT's editable Run-code editors. ## Reading - Wrap toggles visual wrapping without changing the source. -- Line numbers appear when wrapping is off. -- Fold is available for sufficiently long blocks, but code starts expanded. +- Line numbers remain available with wrapping and align with logical source lines. +- Long blocks automatically fold at the configured threshold. Expand code reveals the full block; a threshold of zero disables automatic folding. - Download saves the original source text. Syntax highlighting is retained only when its reconstructed text matches the source. Otherwise the block falls back to plain text rather than corrupting code. @@ -39,3 +39,9 @@ Copy a selection containing blank lines, tabs and nested indentation into a plai Code panels follow the site's explicit light/dark theme, with a GitHub-like syntax palette. Language badges retain their language-associated colors. Badges are typographic representations, not official logo artwork. Additional filename labels and conservative content signatures improve detection. New language labels may use an approximate syntax palette or plain text; the original source remains authoritative. + +## Wrapping and folding in 1.2.4 + +Wrapping and line numbers are independent toggles. A wrapped logical line keeps one source line number. The gutter is remeasured when the code viewport resizes. + +Long blocks automatically fold according to the configured threshold. A threshold of zero disables this behavior. Copy and download still use the complete source. diff --git a/ai/perplexity/docs/usage-quota-v2.md b/ai/perplexity/docs/usage-quota-v2.md index 81d6d35..f740e9c 100644 --- a/ai/perplexity/docs/usage-quota-v2.md +++ b/ai/perplexity/docs/usage-quota-v2.md @@ -38,3 +38,9 @@ Perplexity reports are requested using its current account/tier namespace. ChatG ## Tutorial Open Help and choose Usage Quota V2. There is no separate Quota Insights module to enable. + +## Recovery cards + +The dialog displays +1, +5 and full-recovery cards. When evidence supports a scenario, each card shows a relative duration and an estimated local clock time. These are conditional rate scenarios, not guaranteed server refill deadlines. + +Change the recovery horizon to inspect projected recovery within a selected number of minutes. Expand the evidence section for observations, sampled duration and net counter changes. diff --git a/ai/perplexity/package.json b/ai/perplexity/package.json index 69777b2..0f7a460 100644 --- a/ai/perplexity/package.json +++ b/ai/perplexity/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-perplexity", - "version": "1.2.2", + "version": "1.2.4", "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 6da0e23..523e5b1 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -16,6 +16,7 @@ import { UpdatesFeature, configurePlatform, configureUi, + AnswerDiffFeature, } from '@nolly/ai' import { App } from './core/app' import { composerKit } from './core/composer' @@ -75,4 +76,5 @@ new App() .register((context) => new PromptQueueFeature(context)) .register((context) => new RecallFeature(context)) .register((context) => new ContextPacksFeature(context)) + .register((context) => new AnswerDiffFeature(context)) .start() diff --git a/ai/perplexity/src/tours.ts b/ai/perplexity/src/tours.ts index 43487b1..0bb3c78 100644 --- a/ai/perplexity/src/tours.ts +++ b/ai/perplexity/src/tours.ts @@ -1,4 +1,4 @@ -import { createPdfTour, createQuotaTour } from '@nolly/ai' +import { createAnswerDiffTour, createPdfTour, createQuotaTour } from '@nolly/ai' import { findComposer } from './core/composer' import { contextPacksTour, loadPromptShortcut, loadShortcut, tour, type Tour } from '@nolly/ai' @@ -92,8 +92,8 @@ const codeBlocks: Tour = { find('.bp-code-v2 .bp-code-actions') ), info( - 'Themes and language detection', - 'Code panels follow the site light/dark theme. Language-colored badges remain colored. Filename labels and conservative signatures identify more languages; highlighting remains approximate and never changes the source text.' + 'Wrapping and folding', + 'Line numbers remain visible while wrapping and align with logical source lines. Long blocks automatically fold at the configured threshold. Expand code or use the fold button to reveal them. Setting the threshold to zero disables automatic folding.' ) ] } @@ -140,4 +140,4 @@ const contextPacks: Tour = { } } -export const TOURS: readonly Tour[] = [gettingStarted, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour()] +export const TOURS: readonly Tour[] = [gettingStarted, longMessages, prompts, batch, codeBlocks, exporting, selection, palette, contextPacks, createPdfTour(), createQuotaTour(), createAnswerDiffTour()] diff --git a/bun.lock b/bun.lock index 9f90ba6..deb29ea 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ }, "ai/chatgpt": { "name": "@nolly/ai-chatgpt", - "version": "1.2.2", + "version": "1.2.4", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", @@ -19,7 +19,7 @@ }, "ai/perplexity": { "name": "@nolly/ai-perplexity", - "version": "1.2.2", + "version": "1.2.4", "dependencies": { "@nolly/ai": "workspace:*", "@nolly/core": "workspace:*", @@ -39,7 +39,7 @@ }, "core/ai": { "name": "@nolly/ai", - "version": "0.2.2", + "version": "0.2.3", "dependencies": { "@nolly/core": "workspace:*", }, diff --git a/core/ai/CHANGELOG.md b/core/ai/CHANGELOG.md index 6c62a5a..b57bfec 100644 --- a/core/ai/CHANGELOG.md +++ b/core/ai/CHANGELOG.md @@ -1,6 +1,14 @@ # Changelog # Changelog +## [0.2.3] - 2026-11-10 + +### Code wrapping and Answer Diff update + +- Added measured wrapped-line gutters and restored threshold-based automatic folding. +- Rebuilt quota reporting as recovery cards with evidence details. +- Added the bounded local Answer Diff engine, feature and tutorial. + ## [0.2.2] - 2026-11-10 - Integrated the quota-ledger panel and summaries into platform usage features. diff --git a/core/ai/package.json b/core/ai/package.json index c6d2db2..cb70d23 100644 --- a/core/ai/package.json +++ b/core/ai/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai", - "version": "0.2.2", + "version": "0.2.3", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/core/ai/src/features/answer-diff/compare.ts b/core/ai/src/features/answer-diff/compare.ts new file mode 100644 index 0000000..713bfcf --- /dev/null +++ b/core/ai/src/features/answer-diff/compare.ts @@ -0,0 +1,63 @@ +export type DiffKind = 'same' | 'added' | 'removed' + +export interface DiffLine { + readonly kind: DiffKind + readonly text: string +} + +export interface DiffResult { + readonly lines: readonly DiffLine[] + readonly added: number + readonly removed: number + readonly same: number + readonly coarse: boolean +} + +const MAX_CELLS = 250_000 + +export const compareAnswers = (before: string, after: string): DiffResult => { + const split = (text: string): string[] => text === '' ? [] : text.replace(/\r\n?/g, '\n').split('\n') + const a = split(before) + const b = split(after) + let prefix = 0 + let suffix = 0 + while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++ + while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++ + const left = a.slice(prefix, a.length - suffix) + const right = b.slice(prefix, b.length - suffix) + const output: DiffLine[] = a.slice(0, prefix).map((text) => ({ kind: 'same', text })) + const coarse = (left.length + 1) * (right.length + 1) > MAX_CELLS + if (coarse) { + output.push(...left.map((text): DiffLine => ({ kind: 'removed', text })), ...right.map((text): DiffLine => ({ kind: 'added', text }))) + } else { + const width = right.length + 1 + const matrix = new Uint32Array((left.length + 1) * width) + for (let i = left.length - 1; i >= 0; i--) { + for (let j = right.length - 1; j >= 0; j--) { + matrix[i * width + j] = left[i] === right[j] ? matrix[(i + 1) * width + j + 1]! + 1 : Math.max(matrix[(i + 1) * width + j]!, matrix[i * width + j + 1]!) + } + } + let i = 0 + let j = 0 + while (i < left.length || j < right.length) { + if (i < left.length && j < right.length && left[i] === right[j]) { + output.push({ kind: 'same', text: left[i++]! }) + j++ + } else if (i < left.length && (j === right.length || matrix[(i + 1) * width + j]! >= matrix[i * width + j + 1]!)) { + output.push({ kind: 'removed', text: left[i++]! }) + } else { + output.push({ kind: 'added', text: right[j++]! }) + } + } + } + if (suffix) output.push(...a.slice(a.length - suffix).map((text): DiffLine => ({ kind: 'same', text }))) + return { + lines: output, + added: output.filter((line) => line.kind === 'added').length, + removed: output.filter((line) => line.kind === 'removed').length, + same: output.filter((line) => line.kind === 'same').length, + coarse + } +} + +export const diffText = (result: DiffResult): string => ['--- baseline', '+++ revision', ...result.lines.map((line) => `${line.kind === 'added' ? '+' : line.kind === 'removed' ? '-' : ' '}${line.text}`)].join('\n') diff --git a/core/ai/src/features/answer-diff/index.ts b/core/ai/src/features/answer-diff/index.ts new file mode 100644 index 0000000..20a85c6 --- /dev/null +++ b/core/ai/src/features/answer-diff/index.ts @@ -0,0 +1,192 @@ +import { Feature, createElement, injectStyle } from '@nolly/core' +import type { MenuEntry } from '@nolly/core' +import { copyText } from '../../clipboard' +import { saveFile } from '../../download' +import { storage } from '../../platform' +import { ComposerButton } from '../../ui/composer-button' +import { uiConfig } from '../../ui/config' +import { createButton } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' +import { compareAnswers, diffText } from './compare' +import type { DiffResult } from './compare' + +interface Baseline { + readonly text: string + readonly url: string + readonly at: number +} + +const KEY = 'answer-diff:baseline' +const MAX_CHARS = 100_000 + +const CSS = ` +.bp-answer-editors { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.bp-answer-editors label { display: flex; flex-direction: column; gap: 7px; font-size: 12px; font-weight: 600; } +.bp-answer-editors textarea { min-height: 220px; font-weight: 400; } +.bp-answer-diff { + margin: 0; + padding: 12px; + max-height: 420px; + overflow: auto; + border: 1px solid var(--bp-border); + border-radius: 8px; + background: var(--bp-bg); + color: var(--bp-fg); + font: 12px/1.65 ui-monospace, monospace; + white-space: pre-wrap; + overflow-wrap: anywhere; + tab-size: 4; +} +.bp-answer-diff .added { background: rgb(34 197 94 / 13%); } +.bp-answer-diff .removed { background: rgb(239 68 68 / 13%); } +.bp-answer-summary { display: flex; flex-wrap: wrap; gap: 8px; } +@media (max-width: 600px) { .bp-answer-editors { grid-template-columns: 1fr; } } +` + +const loadBaseline = (): Baseline | null => { + const value = storage.get(KEY, null) + if (!value || typeof value !== 'object') return null + const item = value as Partial + return typeof item.text === 'string' && item.text.length <= MAX_CHARS && typeof item.url === 'string' && typeof item.at === 'number' && Number.isFinite(item.at) ? item as Baseline : null +} + +export class AnswerDiffFeature extends Feature { + readonly id = 'answer-diff' + readonly name = 'Answer Diff' + readonly description = 'Compare two answers or code revisions locally, with an explicitly saved baseline.' + + private selection = '' + private readonly button = new ComposerButton('Answer diff', 'layers', 'See exactly what changed between two answers', () => this.open(), { id: 'diff' }) + + override onEnable(): void { + this.scope.listen(document, 'selectionchange', () => { + const selection = window.getSelection() + const anchor = selection?.anchorNode + const host = anchor instanceof Element ? anchor : anchor?.parentElement + if (!host || uiConfig().marker.isOwn(host)) return + if (host.closest('input, textarea, [contenteditable], dialog')) return + const text = selection?.toString() ?? '' + if (text.trim()) this.selection = text + }) + } + + run(): void { + if (this.enabled) this.button.mount() + else this.button.unmount() + } + + override onDisable(): void { + this.button.unmount() + this.selection = '' + const dialog = document.getElementById(`${uiConfig().id}-answer-diff`) + if (dialog instanceof HTMLDialogElement) dialog.close() + } + + override menuEntries(): MenuEntry[] { + return [{ id: 'open', label: 'Compare Answers', action: () => this.open() }] + } + + private open(): void { + const id = `${uiConfig().id}-answer-diff` + const existing = document.getElementById(id) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + injectStyle(`${uiConfig().id}-answer-diff`, CSS) + const ui = createDialog({ id, title: 'Answer diff', description: 'Compare exact text changes. Nothing is sent; only an explicitly saved baseline persists.', width: 900 }) + const baseline = loadBaseline() + const before = createElement('textarea', 'bp-input') + const after = createElement('textarea', 'bp-input') + before.value = baseline?.text ?? '' + after.value = this.selection.length <= MAX_CHARS ? this.selection : '' + before.maxLength = MAX_CHARS + after.maxLength = MAX_CHARS + before.spellcheck = false + after.spellcheck = false + const left = createElement('label') + left.append(createElement('span', undefined, 'Baseline'), before) + const right = createElement('label') + right.append(createElement('span', undefined, 'Revision'), after) + const editors = createElement('div', 'bp-answer-editors') + editors.dataset['diffEditors'] = '' + editors.append(left, right) + const metadata = createElement('p', 'bp-hint', baseline ? `Saved baseline: ${baseline.url} · ${new Date(baseline.at).toLocaleString()}` : 'Select an answer before opening, or paste text into either side.') + const summary = createElement('div', 'bp-answer-summary') + const output = createElement('pre', 'bp-answer-diff') + output.dataset['diffOutput'] = '' + const status = createElement('div', 'bp-hint') + status.setAttribute('role', 'status') + let result: DiffResult | null = null + const copy = createButton('Copy comparison') + const download = createButton('Download comparison') + copy.disabled = true + download.disabled = true + const invalidate = (): void => { + result = null + copy.disabled = true + download.disabled = true + output.textContent = 'Text changed. Compare again to update the result.' + summary.replaceChildren() + } + before.addEventListener('input', invalidate) + after.addEventListener('input', invalidate) + const compare = (): void => { + if (before.value.length > MAX_CHARS || after.value.length > MAX_CHARS) { + status.textContent = `Each side is limited to ${MAX_CHARS.toLocaleString()} characters.` + return + } + result = compareAnswers(before.value, after.value) + summary.replaceChildren( + createElement('span', 'bp-badge healthy', `+${result.added} added`), + createElement('span', 'bp-badge empty', `−${result.removed} removed`), + createElement('span', 'bp-badge', `${result.same} unchanged`) + ) + const fragment = document.createDocumentFragment() + result.lines.forEach((line, index) => { + if (index) fragment.appendChild(document.createTextNode('\n')) + const span = createElement('span', line.kind, `${line.kind === 'added' ? '+' : line.kind === 'removed' ? '-' : ' '}${line.text}`) + fragment.appendChild(span) + }) + output.replaceChildren(fragment) + status.textContent = result.coarse ? 'Large changed region: coarse replacement comparison. Common prefix and suffix remain exact.' : 'Exact line comparison. Line endings are normalized; differences do not indicate factual correctness.' + copy.disabled = false + download.disabled = false + } + const save = createButton('Save baseline', { + onClick: () => { + if (before.value.length > MAX_CHARS) return + if (loadBaseline() && !window.confirm('Replace the saved Answer Diff baseline?')) return + const url = new URL(location.href) + url.search = '' + url.hash = '' + const saved: Baseline = { text: before.value, url: url.href, at: Date.now() } + storage.set(KEY, saved) + metadata.textContent = `Saved baseline: ${saved.url} · ${new Date(saved.at).toLocaleString()}` + status.textContent = 'Baseline saved locally. Temporary-chat content also persists if explicitly saved.' + } + }) + const clear = createButton('Delete saved baseline', { + onClick: () => { + if (!window.confirm('Delete the locally saved Answer Diff baseline?')) return + storage.set(KEY, null) + metadata.textContent = 'No saved baseline. Editor text has not been deleted.' + } + }) + copy.addEventListener('click', () => { + if (!result) return + void copyText(diffText(result)).then((ok) => { + status.textContent = ok ? 'Comparison copied.' : 'Could not copy.' + }) + }) + download.addEventListener('click', () => { + if (result) saveFile('answer-comparison.diff', diffText(result)) + }) + const actions = createElement('div', 'bp-actions') + actions.append(createButton('Compare', { primary: true, onClick: compare }), save, clear) + ui.body.append(editors, metadata, actions, summary, output, status) + ui.footer.append(createButton('Close', { onClick: ui.close }), copy, download) + ui.show() + compare() + } +} diff --git a/core/ai/src/features/answer-diff/tour.ts b/core/ai/src/features/answer-diff/tour.ts new file mode 100644 index 0000000..2e386b9 --- /dev/null +++ b/core/ai/src/features/answer-diff/tour.ts @@ -0,0 +1,20 @@ +import type { Tour } from '../tutorial/source' +import { click, closed, find, info, point, wait } from '../tutorial/steps' +import { uiConfig } from '../../ui/config' + +export const createAnswerDiffTour = (): Tour => ({ + id: 'answer-diff', + title: 'Answer diff', + summary: 'See exact changes between two responses or code revisions.', + get steps() { + const id = `${uiConfig().id}-answer-diff` + return [ + info('Compare revisions, not confidence', 'Answer Diff highlights text changes. It does not score truth, quality or safety. Select an answer before opening, or paste both versions.'), + click('Open Answer Diff', 'Click the composer tool labelled Answer diff.', find('.bp-cb-diff')), + point('Choose both versions', 'Paste the original into Baseline and the new answer into Revision. A previously saved baseline loads automatically.', find(`#${id} [data-diff-editors]`)), + point('Review exact changes', 'Compare shows added, removed and unchanged lines. Large changed regions use a clearly labelled coarse fallback.', find(`#${id} [data-diff-output]`)), + info('Persistence is explicit', 'Only Save baseline persists text. It remains local to this userscript, including text saved from temporary chats. Copy or paste manually to compare across platforms.'), + wait('Close without sending', 'Close the dialog. No comparison action sends a message.', closed(id)) + ] + } +}) diff --git a/core/ai/src/features/code-blocks/block.ts b/core/ai/src/features/code-blocks/block.ts index 826070b..b8e5a76 100644 --- a/core/ai/src/features/code-blocks/block.ts +++ b/core/ai/src/features/code-blocks/block.ts @@ -18,10 +18,16 @@ export class EnhancedBlock { private readonly code = createElement('code', 'bp-code-source') private readonly gutter = createElement('div', 'bp-code-gutter') + private readonly pre = createElement('pre', 'bp-code-native-pre') + private readonly sourceLines: HTMLElement[] = [] + private readonly gutterLines: HTMLElement[] = [] private readonly toggles = new Map() private readonly lineCount: number private readonly originalDisplay: string private readonly originalPriority: string + private readonly resizeObserver: ResizeObserver + private frame = 0 + private destroyed = false constructor( readonly source: HTMLElement, @@ -33,6 +39,7 @@ export class EnhancedBlock { this.lineCount = info.text.split('\n').length this.originalDisplay = root.style.getPropertyValue('display') this.originalPriority = root.style.getPropertyPriority('display') + this.resizeObserver = new ResizeObserver(() => this.scheduleGutter()) this.build() } @@ -41,21 +48,33 @@ export class EnhancedBlock { } get fenced(): string { - const longest = Math.max(0, ...(this.text.match(/`+/g) ?? []).map((run) => run.length)) + let longest = 0 + let run = 0 + for (const character of this.text) { + run = character === '`' ? run + 1 : 0 + longest = Math.max(longest, run) + } const marker = '`'.repeat(Math.max(3, longest + 1)) - return `${marker}${this.info.language === 'text' ? '' : this.info.language}\n${this.text}\n${marker}` + const language = this.info.language === 'text' ? '' : this.info.language + return `${marker}${language}\n${this.text}\n${marker}` } mount(): void { this.root.insertAdjacentElement('beforebegin', this.element) this.ensureHidden() + this.resizeObserver.observe(this.pre) + this.scheduleGutter() + void document.fonts.ready.then(() => this.scheduleGutter()) } ensureHidden(): void { - if (this.root.style.getPropertyValue('display') !== 'none') this.root.style.setProperty('display', 'none', 'important') + if (this.root.style.getPropertyValue('display') !== 'none' || this.root.style.getPropertyPriority('display') !== 'important') this.root.style.setProperty('display', 'none', 'important') } destroy(): void { + this.destroyed = true + cancelAnimationFrame(this.frame) + this.resizeObserver.disconnect() this.element.remove() if (this.originalDisplay) this.root.style.setProperty('display', this.originalDisplay, this.originalPriority) else this.root.style.removeProperty('display') @@ -64,6 +83,7 @@ export class EnhancedBlock { private setFlag(flag: Flag, value: boolean): void { this.element.dataset[flag] = String(value) this.toggles.get(flag)?.setAttribute('aria-pressed', String(value)) + if (flag === 'wrap' || flag === 'lines') this.scheduleGutter() } private button(icon: IconName, title: string, action: () => void): HTMLButtonElement { @@ -76,73 +96,79 @@ export class EnhancedBlock { return button } - private toggle(flag: Flag, icon: IconName, title: string, value: boolean): HTMLButtonElement { + private toggle(flag: Flag, icon: IconName, title: string, initial: boolean): HTMLButtonElement { const button = this.button(icon, title, () => { this.setFlag(flag, this.element.dataset[flag] !== 'true') }) this.toggles.set(flag, button) - this.setFlag(flag, value) + this.setFlag(flag, initial) return button } private renderSource(): void { - let lines: HTMLElement[] - if (this.settings.highlight === 'builtin') { - lines = highlightLines(this.text, this.info.language) - ?? renderPlainLines(this.text, this.info.language === 'diff') - } else if (this.settings.highlight === 'site') { - lines = splitHighlighted(this.source.querySelector('code') ?? this.source, this.lineCount) - } else { - lines = renderPlainLines(this.text, this.info.language === 'diff') - } - const fragment = document.createDocumentFragment() - lines.forEach((line, index) => { - if (index > 0) fragment.appendChild(document.createTextNode('\n')) - const cell = line.querySelector('.bp-text') - for (const child of cell?.childNodes ?? []) fragment.appendChild(child.cloneNode(true)) + const rawLines = this.text.split('\n') + let highlighted: HTMLElement[] | null = null + if (this.settings.highlight === 'builtin') highlighted = highlightLines(this.text, this.info.language) + else if (this.settings.highlight === 'site') highlighted = splitHighlighted(this.source.querySelector('code') ?? this.source, this.lineCount) + highlighted ??= renderPlainLines(this.text, this.info.language === 'diff') + rawLines.forEach((text, index) => { + if (index > 0) this.code.appendChild(document.createTextNode('\n')) + const line = createElement('span', 'bp-code-logical-line') + const cell = highlighted[index]?.querySelector('.bp-text') + if (cell && cell.textContent === text) { + for (const child of cell.childNodes) line.appendChild(child.cloneNode(true)) + } else { + line.textContent = text + } + this.sourceLines.push(line) + this.code.appendChild(line) + const number = createElement('div', 'bp-code-gutter-line', String(index + 1)) + this.gutterLines.push(number) + this.gutter.appendChild(number) }) - if (fragment.textContent === this.text) this.code.appendChild(fragment) - else this.code.textContent = this.text } private build(): void { const meta = createElement('div', 'bp-code-meta') meta.append(createLanguageIcon(this.info.language), createElement('span', 'bp-code-lang', languageInfo(this.info.language).name)) if (this.info.filename) meta.appendChild(createElement('span', 'bp-code-file', this.info.filename)) - meta.appendChild(createElement('span', 'bp-code-count', `${this.lineCount} lines`)) + meta.appendChild(createElement('span', 'bp-code-count', `${this.lineCount} ${this.lineCount === 1 ? 'line' : 'lines'}`)) const actions = createElement('div', 'bp-code-actions') actions.append(this.toggle('wrap', 'wrap', 'Wrap lines', this.settings.wrap), this.toggle('lines', 'lines', 'Line numbers', this.settings.lineNumbers)) const collapsible = this.settings.collapseAfter > 0 && this.lineCount > this.settings.collapseAfter - if (collapsible) actions.appendChild(this.toggle('collapsed', 'fold', 'Fold code', false)) + if (collapsible) actions.appendChild(this.toggle('collapsed', 'fold', 'Fold code', true)) const copy = this.button('copy', 'Copy code', () => { void copyText(this.text).then((ok) => { - if (!ok) return + if (!ok || this.destroyed) return copy.replaceChildren(createIcon('check', 16)) - window.setTimeout(() => copy.replaceChildren(createIcon('copy', 16)), 1_200) + window.setTimeout(() => { + if (!this.destroyed) copy.replaceChildren(createIcon('copy', 16)) + }, 1_200) }) }) - actions.appendChild(copy) - actions.appendChild(this.button('download', 'Download code', () => { - const filename = (this.info.filename ?? `snippet.${languageInfo(this.info.language).ext}`).split(/[\\/]/).pop() || 'snippet.txt' - saveFile(filename, this.text) - })) + actions.append( + copy, + this.button('download', 'Download code', () => { + const filename = (this.info.filename ?? `snippet.${languageInfo(this.info.language).ext}`).split(/[\\/]/).pop() || 'snippet.txt' + saveFile(filename, this.text) + }) + ) const head = createElement('div', 'bp-code-head') head.append(meta, actions) this.gutter.setAttribute('aria-hidden', 'true') - this.gutter.textContent = Array.from({ length: this.lineCount }, (_, index) => index + 1).join('\n') - const pre = createElement('pre', 'bp-code-native-pre') - pre.tabIndex = 0 - pre.setAttribute('aria-label', `${languageInfo(this.info.language).name} source code`) + this.pre.tabIndex = 0 + this.pre.setAttribute('aria-label', `${languageInfo(this.info.language).name} source code`) this.renderSource() - pre.appendChild(this.code) + this.pre.appendChild(this.code) const scroll = createElement('div', 'bp-code-scroll') - scroll.append(this.gutter, pre) + scroll.append(this.gutter, this.pre) const body = createElement('div', 'bp-code-body') body.appendChild(scroll) this.element.style.setProperty('--bp-code-collapse', String(this.settings.collapseAfter)) + this.element.style.setProperty('--bp-code-digits', String(String(this.lineCount).length)) this.element.append(head, body) if (collapsible) { - const expand = createElement('button', 'bp-code-more', 'Expand code') + const expand = createElement('button', 'bp-code-more', `Expand all ${this.lineCount.toLocaleString()} lines`) expand.type = 'button' expand.addEventListener('click', () => this.setFlag('collapsed', false)) this.element.appendChild(expand) @@ -150,6 +176,31 @@ export class EnhancedBlock { this.element.addEventListener('copy', this.handleCopy, true) } + private scheduleGutter(): void { + if (this.destroyed || this.frame) return + this.frame = requestAnimationFrame(() => { + this.frame = 0 + this.syncGutter() + }) + } + + private syncGutter(): void { + if (!this.element.isConnected || this.destroyed) return + if (this.element.dataset['lines'] === 'false') return + const lineHeight = Number.parseFloat(getComputedStyle(this.pre).lineHeight) || 21 + const wrapped = this.element.dataset['wrap'] === 'true' + const heights = this.sourceLines.map((line) => { + if (!wrapped || !line.textContent) return lineHeight + const rect = line.getBoundingClientRect() + return Math.max(lineHeight, Math.ceil(Math.max(0, rect.height - 0.5) / lineHeight) * lineHeight) + }) + heights.forEach((height, index) => { + const row = this.gutterLines[index]! + const value = `${height}px` + if (row.style.height !== value) row.style.height = value + }) + } + private readonly handleCopy = (event: ClipboardEvent): void => { const selection = window.getSelection() if (!selection || selection.isCollapsed || !selection.rangeCount || !event.clipboardData) return diff --git a/core/ai/src/features/code-blocks/styles.ts b/core/ai/src/features/code-blocks/styles.ts index f9c3046..a70697f 100644 --- a/core/ai/src/features/code-blocks/styles.ts +++ b/core/ai/src/features/code-blocks/styles.ts @@ -89,8 +89,7 @@ const CSS = ` font: inherit !important; white-space: inherit !important; } -.bp-code-v2[data-lines='false'] .bp-code-gutter, -.bp-code-v2[data-wrap='true'] .bp-code-gutter { display: none; } +.bp-code-v2[data-lines='false'] .bp-code-gutter { display: none; } .bp-code-v2[data-wrap='true'] .bp-code-scroll { width: 100%; } .bp-code-v2[data-wrap='true'] .bp-code-native-pre { white-space: pre-wrap !important; @@ -132,6 +131,24 @@ const CSS = ` color: var(--bp-fg); font: 600 10px system-ui, sans-serif; } + +.bp-code-v2 .bp-code-gutter { + width: calc(var(--bp-code-digits, 2) * 1ch + 25px); + white-space: normal; + padding: 14px 10px; +} +.bp-code-v2 .bp-code-gutter-line { + height: 21px; + line-height: 21px; + font: inherit; + text-align: right; +} +.bp-code-v2 .bp-code-logical-line { display: inline; } +.bp-code-v2[data-wrap='true'] .bp-code-native-pre { + flex: 1 1 0; + width: 0; + min-width: 0; +} ` export const ensureCodeStyles = (): void => { diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 0af3e17..3250418 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -25,3 +25,5 @@ export { contextPacksTour } from './context-packs/tour' export * as tour from './tutorial/steps' export { createPdfTour } from './exporter/tour' export { createQuotaTour } from './quota-insights/tour' +export { AnswerDiffFeature } from './answer-diff' +export { createAnswerDiffTour } from './answer-diff/tour' diff --git a/core/ai/src/ui/composer-toolbar.ts b/core/ai/src/ui/composer-toolbar.ts index ec21d46..17eeae4 100644 --- a/core/ai/src/ui/composer-toolbar.ts +++ b/core/ai/src/ui/composer-toolbar.ts @@ -2,7 +2,7 @@ import { createElement, injectStyle } from '@nolly/core' import { platform } from '../platform' import { markUi, uiConfig } from './config' -const ORDER = ['config', 'big', 'prompts', 'batch', 'queue', 'recall', 'context'] +const ORDER = ['config', 'big', 'prompts', 'batch', 'queue', 'recall', 'context', 'diff'] const MODE = /^(?:switch to |select |use )?(?:pro search|pro|search|deep research|research|labs?|computer|agentic(?: research)?|think|thinking)(?: mode)?$/i const EXCLUDED = 'header, aside, dialog, [role="dialog"], [data-code-block], .cm-editor' const tools = new Map() diff --git a/core/ai/src/ui/quota-panel.ts b/core/ai/src/ui/quota-panel.ts index 6bbf546..4841ea0 100644 --- a/core/ai/src/ui/quota-panel.ts +++ b/core/ai/src/ui/quota-panel.ts @@ -1,6 +1,7 @@ -import { createElement } from '@nolly/core' +import { createElement, injectStyle } from '@nolly/core' import type { QuotaReport } from '../quota' -import { createDataRow, createNumberField, createSection } from './controls' +import { uiConfig } from './config' +import { createDataRow, createNumberField } from './controls' import { ensureUiStyles } from './styles' export interface QuotaPanel { @@ -10,6 +11,7 @@ export interface QuotaPanel { } export const quotaDuration = (milliseconds: number): string => { + if (!Number.isFinite(milliseconds)) return 'Unknown' const minutes = Math.max(0, Math.ceil(milliseconds / 60_000)) if (minutes < 60) return `${minutes}m` const hours = Math.floor(minutes / 60) @@ -19,66 +21,155 @@ export const quotaDuration = (milliseconds: number): string => { export const quotaSummary = (report: QuotaReport | null): string => { if (!report) return 'Collecting quota observations' - const now = Date.now() - if (now - report.observedAt > 5 * 60_000) return 'Last reported count · waiting for fresh observations' + if (Date.now() - report.observedAt > 5 * 60_000) return 'Last reported count · awaiting fresh observations' if (report.cap !== null && report.remaining >= report.cap) return 'At the API-reported capacity' const one = report.scenarios.find((scenario) => scenario.units === 1) if (one) return `+1 in ~${quotaDuration(one.estimatedMs)} · rate scenario` - if (report.lastIncrease) return `Last net recovery +${report.lastIncrease.units} · ${quotaDuration(now - report.lastIncrease.to)} ago` - return `${report.observations} observations · recovery not measured yet` + return report.lastIncrease ? `Last net recovery +${report.lastIncrease.units} · ${quotaDuration(Date.now() - report.lastIncrease.to)} ago` : `${report.observations} observations · learning recovery` +} + +const CSS = ` +.bp-quota-list { display: grid; gap: 18px; } +.bp-quota-card { + padding: 18px; + border: 1px solid var(--bp-border); + border-radius: 10px; + background: var(--bp-bg); +} +.bp-quota-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.bp-quota-head h3 { margin: 0; font-size: 14px; font-weight: 600; } +.bp-quota-count { margin: 14px 0 4px; font-size: 36px; line-height: 1.1; font-weight: 650; letter-spacing: -.04em; font-variant-numeric: tabular-nums; } +.bp-quota-caption { color: var(--bp-muted); font-size: 12px; line-height: 1.5; } +.bp-quota-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin-top: 16px; } +.bp-quota-metric { min-width: 0; padding: 12px; border: 1px solid var(--bp-border); border-radius: 8px; background: var(--bp-accent); } +.bp-quota-metric-label { color: var(--bp-muted); font-size: 11px; } +.bp-quota-metric-value { margin-top: 6px; font-size: 17px; line-height: 1.3; font-weight: 600; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; } +.bp-quota-metric-note { margin-top: 5px; color: var(--bp-muted); font-size: 11px; line-height: 1.5; } +.bp-quota-horizon { margin-top: 10px; padding: 12px; border: 1px dashed var(--bp-border); border-radius: 8px; } +.bp-quota-evidence { margin-top: 12px; } +.bp-quota-evidence summary { cursor: pointer; color: var(--bp-muted); font-size: 12px; } +.bp-quota-evidence .bp-data-list { margin-top: 10px; } +.bp-quota-progress { height: 6px; margin-top: 12px; background: var(--bp-accent); border-radius: 999px; overflow: hidden; } +.bp-quota-progress > span { display: block; height: 100%; background: var(--bp-green); } +.bp-quota-card[data-state='empty'] .bp-quota-count { color: var(--bp-red); } +.bp-quota-card[data-state='low'] .bp-quota-count { color: var(--bp-yellow); } +@media (max-width: 560px) { + .bp-quota-grid { grid-template-columns: 1fr; } + .bp-quota-card { padding: 14px; } +} +` + +const metric = (label: string, value: string, note: string): HTMLElement => { + const card = createElement('div', 'bp-quota-metric') + card.append( + createElement('div', 'bp-quota-metric-label', label), + createElement('div', 'bp-quota-metric-value', value), + createElement('div', 'bp-quota-metric-note', note) + ) + return card +} + +const eta = (milliseconds: number, now: number): string => { + const date = new Date(now + milliseconds) + return Number.isFinite(date.getTime()) ? `Scenario time: ${date.toLocaleString()}` : 'Time exceeds the supported date range' } export const createQuotaPanel = (getReports: () => readonly QuotaReport[]): QuotaPanel => { ensureUiStyles() + injectStyle(`${uiConfig().id}-quota-cards`, CSS) const element = createElement('div', 'bp-stack') element.dataset['usageQuotaV2'] = '' - const results = createElement('div', 'bp-stack') + const results = createElement('div', 'bp-quota-list') + const expanded = new Set() let horizon = 60 let destroyed = false const render = (): void => { if (destroyed) return + const now = Date.now() const reports = getReports() if (!reports.length) { - results.replaceChildren(createElement('div', 'bp-empty', 'No observations for the current account scope yet. Platform usage responses will populate this view.')) + results.replaceChildren(createElement('div', 'bp-empty', 'Waiting for quota observations. Use the platform normally or refresh its usage data.')) return } results.replaceChildren(...reports.map((report) => { - const section = createSection(report.label) + const identity = `${report.scope}:${report.key}` + const stale = now - report.observedAt > 5 * 60_000 + const rateAvailable = !stale && report.recoveryPerHour !== null + const missing = report.cap === null ? null : Math.max(0, report.cap - report.remaining) + const state = stale ? 'stale' : report.remaining === 0 ? 'empty' : report.cap !== null && report.remaining / report.cap <= 0.1 ? 'low' : 'reported' + const card = createElement('section', 'bp-quota-card') + card.dataset['state'] = state + const head = createElement('div', 'bp-quota-head') + head.append( + createElement('h3', undefined, report.label), + createElement('span', `bp-badge ${state === 'empty' ? 'empty' : state === 'low' ? 'low' : ''}`, stale ? 'Last reported' : state === 'empty' ? 'Empty' : state === 'low' ? 'Low' : 'Reported') + ) + card.append( + head, + createElement('div', 'bp-quota-count', report.remaining.toLocaleString()), + createElement('div', 'bp-quota-caption', report.cap === null ? `remaining · capacity unknown · observed maximum ≥ ${report.peak}` : `remaining of ${report.cap} API-reported capacity`) + ) + if (report.cap !== null && report.cap > 0) { + const bar = createElement('div', 'bp-quota-progress') + const fill = createElement('span') + fill.style.width = `${Math.max(0, Math.min(100, report.remaining / report.cap * 100))}%` + if (state === 'empty') fill.style.background = 'var(--bp-red)' + if (state === 'low') fill.style.background = 'var(--bp-yellow)' + bar.appendChild(fill) + card.appendChild(bar) + } + const grid = createElement('div', 'bp-quota-grid') + for (const units of [1, 5]) { + const scenario = rateAvailable ? report.scenarios.find((entry) => entry.units === units) : null + grid.appendChild(metric( + `Recover +${units}`, + scenario ? `~${quotaDuration(scenario.estimatedMs)}` : missing !== null && missing < units ? 'Not applicable' : stale ? 'Stale data' : 'Learning', + scenario ? eta(scenario.estimatedMs, now) : missing !== null && missing < units ? 'Exceeds the missing allowance.' : 'More usable recovery observations are needed.' + )) + } + grid.appendChild(metric( + 'Full recovery', + report.fullMs === 0 ? 'Full' : report.fullMs !== null && rateAvailable ? `~${quotaDuration(report.fullMs)}` : report.cap === null ? 'Cap unknown' : 'Learning', + report.fullMs === 0 ? 'At the API-reported capacity.' : report.fullMs !== null && rateAvailable ? eta(report.fullMs, now) : 'Requires both capacity and usable recovery evidence.' + )) + card.appendChild(grid) + const horizonCard = createElement('div', 'bp-quota-horizon') + const projected = rateAvailable ? report.recoveryPerHour! * horizon / 60 : null + const bounded = projected === null ? null : missing === null ? projected : Math.min(missing, projected) + horizonCard.append( + createElement('div', 'bp-quota-metric-label', `Recovery within ${horizon} minutes`), + createElement('div', 'bp-quota-metric-value', bounded === null ? 'Learning recovery rate' : `~${Math.max(0, bounded).toFixed(1)} units`), + createElement('div', 'bp-quota-metric-note', report.recoveryPerHour !== null && !stale ? `Observed net recovery: ~${report.recoveryPerHour.toFixed(2)} units/hour.` : 'No unsupported countdown is substituted.') + ) + card.appendChild(horizonCard) + if (report.resetAt !== null) card.appendChild(createElement('p', 'bp-hint', `API-reported reset: ${new Date(report.resetAt).toLocaleString()}. The refill amount is not assumed.`)) + const details = createElement('details', 'bp-quota-evidence') + details.open = expanded.has(identity) + details.appendChild(createElement('summary', undefined, 'Observation evidence and assumptions')) const rows = createElement('div', 'bp-data-list') - const stale = Date.now() - report.observedAt > 5 * 60_000 - const availableClass = report.remaining === 0 ? 'negative' : stale ? '' : 'positive' rows.append( - createDataRow(stale ? 'Remaining · last reported' : 'Remaining · reported', String(report.remaining), availableClass), - createDataRow('Capacity', report.cap === null ? `Unknown · observed maximum ≥ ${report.peak}` : `${report.cap} · API-reported`), createDataRow('Last observation', new Date(report.observedAt).toLocaleString()), createDataRow('Saved observations', String(report.observations)), createDataRow('Comparable sampling', quotaDuration(report.sampledMs)), + createDataRow('Positive intervals', String(report.positiveIntervals)), createDataRow('Net recovered · sampled intervals', String(report.netRecovered)), createDataRow('Net spent · sampled intervals', String(report.netSpent)) ) - if (report.lastIncrease) { - rows.append( - createDataRow('Last observed net increase', `+${report.lastIncrease.units} · ${quotaDuration(Date.now() - report.lastIncrease.to)} ago`), - createDataRow('Increase timing uncertainty', `Within a ${quotaDuration(report.lastIncrease.to - report.lastIncrease.from)} observation interval`) - ) - } - if (report.recoveryPerHour !== null && !stale) { - rows.appendChild(createDataRow('Observed net recovery rate', `~${report.recoveryPerHour.toFixed(2)} units/hour`)) - for (const target of [1, 5]) { - const scenario = report.scenarios.find((entry) => entry.units === target) - rows.appendChild(createDataRow(`Recover +${target} · rate scenario`, scenario ? `~${quotaDuration(scenario.estimatedMs)}` : report.cap !== null && report.cap - report.remaining < target ? 'Exceeds the missing allowance' : 'Not enough evidence')) - } - const missing = report.cap === null ? null : Math.max(0, report.cap - report.remaining) - const projected = report.recoveryPerHour * horizon / 60 - rows.appendChild(createDataRow(`Recovery within ${horizon}m · rate scenario`, `~${(missing === null ? projected : Math.min(missing, projected)).toFixed(1)} units`)) - } - rows.appendChild(createDataRow('Full recovery', report.fullMs === 0 ? 'At the API-reported capacity' : report.fullMs !== null && !stale ? `~${quotaDuration(report.fullMs)} · rate scenario` : 'Unknown · capacity or recovery evidence is insufficient')) - if (report.resetAt !== null) rows.appendChild(createDataRow('API-reported reset', `${new Date(report.resetAt).toLocaleString()} · amount not assumed`)) - section.append(rows, createElement('p', 'bp-hint', report.recoveryPerHour === null ? 'Recovery scenarios require 30 minutes of comparable sampling, three positive intervals and a recent observation. Long gaps and known cap-bound intervals are excluded.' : 'Rate scenarios assume no additional spending and an unchanged observed rate. Hidden spending, batched resets and activity in other clients can invalidate them.')) - return section + if (report.lastIncrease) rows.appendChild(createDataRow('Last net increase', `+${report.lastIncrease.units} · ${quotaDuration(now - report.lastIncrease.to)} ago`)) + details.append( + rows, + createElement('p', 'bp-hint', 'Recovery times are conditional rate scenarios, not guaranteed refill events. They assume no further spending and an unchanged observed rate. Capacity is never inferred from a plateau.') + ) + details.addEventListener('toggle', () => { + if (!details.isConnected) return + if (details.open) expanded.add(identity) + else expanded.delete(identity) + }) + card.appendChild(details) + return card })) } - const control = createNumberField({ + const horizonControl = createNumberField({ label: 'Recovery horizon · minutes', value: horizon, min: 1, @@ -90,8 +181,8 @@ export const createQuotaPanel = (getReports: () => readonly QuotaReport[]): Quot } }) element.append( - control.wrapper, - createElement('p', 'bp-hint', 'A counter increase is net recovery, not proof of the complete refill amount. An observed maximum is a lower bound—not a verified capacity.'), + horizonControl.wrapper, + createElement('p', 'bp-hint', 'Recovery cards use the quota observation ledger. Unknown capacity, stale data and insufficient evidence remain explicit.'), results ) const timer = window.setInterval(() => {