From 1fb37e214e928389027dc25d6f77bb17b0fcbcba Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 09:58:04 +0100 Subject: [PATCH 01/19] fix(perplexity): import isSynthetic from @nolly/ai and drop re-export shims --- CONTRIBUTING.md | 17 ++- ai/chatgpt/CHANGELOG.md | 6 + ai/chatgpt/README.md | 19 +++ ai/chatgpt/package.json | 1 + ai/chatgpt/src/app.ts | 39 ++--- ai/chatgpt/src/dom.ts | 1 - ai/chatgpt/src/features/diagnostics.ts | 42 +++--- ai/chatgpt/src/features/header-button.ts | 39 +++++ ai/chatgpt/src/kit.ts | 4 + ai/chatgpt/src/main.ts | 21 ++- ai/chatgpt/src/runtime.ts | 6 + ai/chatgpt/src/selectors.ts | 6 +- ai/chatgpt/src/theme.ts | 34 +++++ ai/perplexity/CHANGELOG.md | 5 + ai/perplexity/README.md | 10 +- ai/perplexity/docs/architecture.md | 11 +- ai/perplexity/package.json | 49 ++++--- ai/perplexity/src/core/app.ts | 2 +- ai/perplexity/src/core/composer.ts | 2 - ai/perplexity/src/core/dispatch.ts | 16 +- ai/perplexity/src/core/generation.ts | 2 - ai/perplexity/src/core/synthetic-keys.ts | 1 - ai/perplexity/src/main.ts | 38 ++--- .../src/modules/batch-runner/dialog.ts | 4 +- .../src/modules/batch-runner/index.ts | 6 +- .../src/modules/batch-runner/panel.ts | 4 +- .../src/modules/batch-runner/runner.ts | 5 +- .../src/modules/code-blocks/badges.ts | 2 +- .../src/modules/code-blocks/block.ts | 4 +- .../src/modules/code-blocks/dialog.ts | 4 +- .../src/modules/code-blocks/index.ts | 2 +- .../src/modules/command-palette/dialog.ts | 4 +- .../src/modules/command-palette/index.ts | 2 +- .../src/modules/command-palette/palette.ts | 2 +- .../src/modules/draft-guard/index.ts | 3 +- .../src/modules/draft-guard/overlay.ts | 4 +- .../modules/enter-as-newline/config-button.ts | 4 +- .../src/modules/enter-as-newline/dialog.ts | 4 +- .../src/modules/enter-as-newline/index.ts | 7 +- .../src/modules/enter-as-newline/keyboard.ts | 6 +- ai/perplexity/src/modules/exporter/dialog.ts | 4 +- ai/perplexity/src/modules/exporter/index.ts | 6 +- ai/perplexity/src/modules/exporter/service.ts | 4 +- .../src/modules/global-settings/dialog.ts | 4 +- .../src/modules/global-settings/index.ts | 6 +- .../src/modules/message-splitter/big-text.ts | 6 +- .../src/modules/message-splitter/dialog.ts | 8 +- .../src/modules/message-splitter/index.ts | 9 +- .../src/modules/message-splitter/plan.ts | 2 +- .../src/modules/message-splitter/splitter.ts | 2 +- .../src/modules/prompt-library/index.ts | 2 +- .../src/modules/prompt-library/manager.ts | 6 +- .../src/modules/prompt-library/picker.ts | 2 +- .../src/modules/prompt-library/variables.ts | 6 +- .../src/modules/prompt-queue/index.ts | 7 +- .../src/modules/prompt-queue/panel.ts | 6 +- ai/perplexity/src/modules/recall/dialog.ts | 6 +- ai/perplexity/src/modules/recall/index.ts | 13 +- .../src/modules/selection-toolbar/index.ts | 9 +- ai/perplexity/src/modules/tutorial/engine.ts | 4 +- ai/perplexity/src/modules/tutorial/index.ts | 12 +- ai/perplexity/src/modules/updates/index.ts | 2 +- .../src/modules/usage-status/alerts.ts | 2 +- .../src/modules/usage-status/dialog.ts | 4 +- .../src/modules/usage-status/index.ts | 2 +- .../src/modules/usage-status/indicator.ts | 4 +- ai/perplexity/src/ui/controls.ts | 104 ------------- ai/perplexity/src/ui/css/dialog.ts | 75 ---------- ai/perplexity/src/ui/css/theme.ts | 28 ---- ai/perplexity/src/ui/css/tooltip.ts | 30 ---- ai/perplexity/src/ui/icons.ts | 33 ----- ai/perplexity/src/ui/styles.ts | 9 -- core/CHANGELOG.md | 4 + core/README.md | 3 + core/ai/CHANGELOG.md | 6 + core/ai/README.md | 12 ++ core/ai/package.json | 2 +- core/ai/src/adapter.ts | 1 - .../src/core => core/ai/src}/automation.ts | 2 +- .../src/core => core/ai/src}/clipboard.ts | 2 +- core/ai/src/composer.ts | 9 +- .../src/core => core/ai/src}/download.ts | 2 +- core/ai/src/index.ts | 8 + core/ai/src/keys.ts | 22 +-- .../src/core => core/ai/src}/placeholders.ts | 2 +- core/ai/src/prompt.ts | 17 +++ .../src/core => core/ai/src}/selection.ts | 2 +- .../src/core => core/ai/src}/tokens.ts | 2 +- .../ai}/src/ui/composer-button.ts | 7 +- core/ai/src/ui/config.ts | 29 ++++ core/ai/src/ui/controls.ts | 104 +++++++++++++ .../css/controls.ts => core/ai/src/ui/css.ts | 138 +++++++++++++++++- {ai/perplexity => core/ai}/src/ui/dialog.ts | 4 +- core/ai/src/ui/icons.ts | 33 +++++ core/ai/src/ui/index.ts | 11 ++ .../ai}/src/ui/placeholder-dialog.ts | 12 +- .../ai}/src/ui/settings-dialog.ts | 11 +- core/ai/src/ui/styles.ts | 7 + {ai/perplexity => core/ai}/src/ui/toast.ts | 12 +- {ai/perplexity => core/ai}/src/ui/tooltip.ts | 4 +- core/docs/getting-started.md | 2 + scripts/new-userscript.ts | 87 +++++------ 102 files changed, 820 insertions(+), 592 deletions(-) create mode 100644 ai/chatgpt/CHANGELOG.md create mode 100644 ai/chatgpt/README.md create mode 100644 ai/chatgpt/src/features/header-button.ts create mode 100644 ai/chatgpt/src/kit.ts create mode 100644 ai/chatgpt/src/runtime.ts create mode 100644 ai/chatgpt/src/theme.ts delete mode 100644 ai/perplexity/src/core/synthetic-keys.ts delete mode 100644 ai/perplexity/src/ui/controls.ts delete mode 100644 ai/perplexity/src/ui/css/dialog.ts delete mode 100644 ai/perplexity/src/ui/css/theme.ts delete mode 100644 ai/perplexity/src/ui/css/tooltip.ts delete mode 100644 ai/perplexity/src/ui/icons.ts delete mode 100644 ai/perplexity/src/ui/styles.ts create mode 100644 core/ai/CHANGELOG.md create mode 100644 core/ai/README.md rename {ai/perplexity/src/core => core/ai/src}/automation.ts (99%) rename {ai/perplexity/src/core => core/ai/src}/clipboard.ts (99%) rename {ai/perplexity/src/core => core/ai/src}/download.ts (99%) rename {ai/perplexity/src/core => core/ai/src}/placeholders.ts (94%) create mode 100644 core/ai/src/prompt.ts rename {ai/perplexity/src/core => core/ai/src}/selection.ts (84%) rename {ai/perplexity/src/core => core/ai/src}/tokens.ts (99%) rename {ai/perplexity => core/ai}/src/ui/composer-button.ts (89%) create mode 100644 core/ai/src/ui/config.ts create mode 100644 core/ai/src/ui/controls.ts rename ai/perplexity/src/ui/css/controls.ts => core/ai/src/ui/css.ts (58%) rename {ai/perplexity => core/ai}/src/ui/dialog.ts (97%) create mode 100644 core/ai/src/ui/icons.ts create mode 100644 core/ai/src/ui/index.ts rename {ai/perplexity => core/ai}/src/ui/placeholder-dialog.ts (88%) rename {ai/perplexity => core/ai}/src/ui/settings-dialog.ts (82%) create mode 100644 core/ai/src/ui/styles.ts rename {ai/perplexity => core/ai}/src/ui/toast.ts (86%) rename {ai/perplexity => core/ai}/src/ui/tooltip.ts (99%) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5114dd5..579bafd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,21 +9,30 @@ By submitting a pull request, issue attachment or prompt, you confirm that you w ## Ways to contribute - **Bug reports and ideas:** use the issue forms. -- **Community prompts:** use the "Prompt submission" form, or open a pull request that adds an entry to `better-perplexity/prompts/library.json`. +- **Community prompts:** use the "Prompt submission" form, or open a pull request that adds an entry to `ai/perplexity/prompts/library.json`. - **Code:** open an issue first for anything larger than a small fix. +## Repository layout + +| Folder | Package | Purpose | +| --------------- | ---------------------- | ---------------------------------------------------- | +| `core/` | `@nolly/core` | Runtime, storage, DOM, HTTP, build tooling | +| `core/ai` | `@nolly/ai` | Platform-agnostic code shared by AI-chat userscripts | +| `ai/perplexity` | `@nolly/ai-perplexity` | Better Perplexity | +| `ai/chatgpt` | `@nolly/ai-chatgpt` | Better ChatGPT | + ## Development setup ```bash bun install # at the repository root (Bun workspace) -cd better-perplexity +cd ai/perplexity # or ai/chatgpt bun run dev # unminified, rebuilds on change bun run typecheck bun run validate:prompts bun run build # minified output in dist/ ``` -Install `dist/better-perplexity.user.js` in your userscript manager to test. Shared code lives in `core/` and is published as the workspace package `@nolly/core`; script-specific code stays in the script's own folder. Start a new script with `bun scripts/new-userscript.ts ""`. +Install the file in `dist/` in your userscript manager to test. Code that does not depend on one site belongs in `core/ai`; site-specific selectors and modules stay in the script's folder. Start a new script with `bun scripts/new-userscript.ts "" [parent-folder]`, for example `bun scripts/new-userscript.ts better-claude "Better Claude" ai`. ## Code style @@ -33,7 +42,7 @@ Install `dist/better-perplexity.user.js` in your userscript manager to test. Sha ## Releasing -1. Bump `version` in the script's `package.json`. +1. Bump `version` in the script's `package.json`. Each script also declares its `userscript.slug` there, which names its tag and its folder on the `dist` branch. 2. Add a section to its `CHANGELOG.md` in the form `## [x.y.z] - YYYY-MM-DD`. 3. Merge to `master`. The release workflow does the rest. diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md new file mode 100644 index 0000000..6508835 --- /dev/null +++ b/ai/chatgpt/CHANGELOG.md @@ -0,0 +1,6 @@ +# Changelog + +## [0.1.0] - 2026-11-10 + +- Initial skeleton: composer and header detection, response observer, session state and diagnostics. +- Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md new file mode 100644 index 0000000..1718f85 --- /dev/null +++ b/ai/chatgpt/README.md @@ -0,0 +1,19 @@ +# Better ChatGPT + +A modular userscript for chatgpt.com. It is in early development: version 0.1.0 detects the composer and header and tracks generation, model, plan and limits from the live network stream. + +## Install + +Install [Violentmonkey](https://violentmonkey.github.io/) or [Tampermonkey](https://www.tampermonkey.net/), then open the install link from the project website. + +## Diagnostics + +Open the browser console on chatgpt.com and run `betterChatgptDump()` to print the detected layout and the live session state. + +## Built on the shared core + +Better ChatGPT is built on [`@nolly/core`](../../core/README.md) and [`@nolly/ai`](../../core/ai/README.md), and is bundled into one file at build time. + +## License + +[PolyForm Strict License 1.0.0](../../LICENSE). diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index d55ee97..250ade5 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -4,6 +4,7 @@ "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", + "userscript": { "slug": "better-chatgpt" }, "repository": { "type": "git", "url": "git+https://github.com/thenolle/userscripts.git", diff --git a/ai/chatgpt/src/app.ts b/ai/chatgpt/src/app.ts index 7be1f40..7484787 100644 --- a/ai/chatgpt/src/app.ts +++ b/ai/chatgpt/src/app.ts @@ -1,23 +1,26 @@ -import { Userscript, createLogger } from '@nolly/core' +import { toggleSettingsDialog } from '@nolly/ai' +import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from './config' import { uiMarker } from './dom' -const logger = createLogger('better-chatgpt') - export class App extends Userscript { - constructor() { - super({ - id: 'better-chatgpt', - name: 'Better ChatGPT', - version: __VERSION__, - storage: { gmPrefix: '' }, - ui: uiMarker, - observe: OBSERVER_OPTIONS, - initializationDelay: CONFIG.initializationDelay, - safetyInterval: CONFIG.safetyInterval, - clearConsole: false, - isReady: () => Boolean(document.querySelector('main')), - openSettings: () => logger.info('The settings dialog arrives in step 2.') - }) - } + constructor() { + super({ + id: 'better-chatgpt', + name: 'Better ChatGPT', + version: __VERSION__, + storage: { gmPrefix: '' }, + ui: uiMarker, + observe: OBSERVER_OPTIONS, + initializationDelay: CONFIG.initializationDelay, + safetyInterval: CONFIG.safetyInterval, + clearConsole: false, + isReady: () => Boolean(document.querySelector('main')), + openSettings: (script) => + toggleSettingsDialog(script.getFeatures(), () => { + script.refreshMenu() + script.requestUpdate() + }) + }) + } } diff --git a/ai/chatgpt/src/dom.ts b/ai/chatgpt/src/dom.ts index ab00dee..c80ed52 100644 --- a/ai/chatgpt/src/dom.ts +++ b/ai/chatgpt/src/dom.ts @@ -1,6 +1,5 @@ import { createUiMarker } from '@nolly/core' export const uiMarker = createUiMarker('data-bc-root') -export const UI_ROOT_ATTRIBUTE = uiMarker.attribute export const markUi = uiMarker.mark export const isOwnUi = uiMarker.isOwn diff --git a/ai/chatgpt/src/features/diagnostics.ts b/ai/chatgpt/src/features/diagnostics.ts index cf01918..5f1f3dc 100644 --- a/ai/chatgpt/src/features/diagnostics.ts +++ b/ai/chatgpt/src/features/diagnostics.ts @@ -1,30 +1,30 @@ import { Feature, getPageWindow } from '@nolly/core' -import type { FeatureCommand, ScriptContext } from '@nolly/core' +import type { FeatureCommand } from '@nolly/core' import { chatgptAdapter } from '../adapter' -import type { ChatSession } from '../session' +import { sendPrompt } from '../kit' +import { session } from '../runtime' export class DiagnosticsFeature extends Feature { - readonly id = 'diagnostics' - readonly name = 'Diagnostics' - readonly description = 'Reports the detected ChatGPT layout and live session state in the console.' + readonly id = 'diagnostics' + readonly name = 'Diagnostics' + readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' - constructor(context: ScriptContext, private readonly session: ChatSession) { - super(context) - } + run(): void {} - run(): void { } + override onEnable(): void { + const page = getPageWindow() as unknown as Record | null + if (page) { + page['betterChatgptDump'] = () => this.dump() + page['betterChatgptSend'] = (text: string) => sendPrompt(text) + } + this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') + } - override onEnable(): void { - const page = getPageWindow() as unknown as Record | null - if (page) page['betterChatgptDump'] = () => this.dump() - this.context.logger.info('Diagnostics ready. Run betterChatgptDump() in the console.') - } + override commands(): FeatureCommand[] { + return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] + } - override commands(): FeatureCommand[] { - return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => void this.context.logger.info(this.dump()) }] - } - - private dump(): string { - return JSON.stringify({ page: chatgptAdapter.describePage(), session: this.session.snapshot() }, null, 2) - } + private dump(): string { + return JSON.stringify({ page: chatgptAdapter.describePage(), session: session.snapshot() }, null, 2) + } } diff --git a/ai/chatgpt/src/features/header-button.ts b/ai/chatgpt/src/features/header-button.ts new file mode 100644 index 0000000..3a02cd0 --- /dev/null +++ b/ai/chatgpt/src/features/header-button.ts @@ -0,0 +1,39 @@ +import { Tooltip, createIcon, ensureUiStyles } from '@nolly/ai' +import { Feature, createElement } from '@nolly/core' +import { markUi } from '../dom' +import { findHeaderSlot } from '../locate' + +export class HeaderButtonFeature extends Feature { + readonly id = 'header-button' + readonly name = 'Header button' + readonly description = 'Adds the Better ChatGPT settings button to the header.' + + private readonly wrapper = markUi(createElement('div', 'pointer-events-auto flex items-center no-drag shrink-0')) + private tooltip: Tooltip | null = null + + run(): void { + if (!this.enabled) return + const slot = findHeaderSlot() + if (!slot) return + if (!this.tooltip) this.build() + if (this.wrapper.parentElement !== slot || slot.firstElementChild !== this.wrapper) slot.prepend(this.wrapper) + } + + override onDisable(): void { + this.tooltip?.destroy() + this.tooltip = null + this.wrapper.replaceChildren() + this.wrapper.remove() + } + + private build(): void { + ensureUiStyles() + const button = createElement('button', 'bp-header-btn bp-themed') + button.type = 'button' + button.setAttribute('aria-label', 'Better ChatGPT settings') + button.appendChild(createIcon('sliders')) + button.addEventListener('click', () => this.context.openSettings()) + this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) + this.wrapper.replaceChildren(button) + } +} diff --git a/ai/chatgpt/src/kit.ts b/ai/chatgpt/src/kit.ts new file mode 100644 index 0000000..34d63a4 --- /dev/null +++ b/ai/chatgpt/src/kit.ts @@ -0,0 +1,4 @@ +import { createComposerKit, createPromptSender } from '@nolly/ai' +import { chatgptAdapter } from './adapter' + +export const sendPrompt = createPromptSender(createComposerKit(chatgptAdapter)) diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index cd25cb1..876e555 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,12 +1,23 @@ +import { configureUi } from '@nolly/ai' import { App } from './app' +import { uiMarker } from './dom' import { DiagnosticsFeature } from './features/diagnostics' -import { responseSpy } from './network' -import { ChatSession } from './session' +import { HeaderButtonFeature } from './features/header-button' +import { findAttachButton, findPrimaryAction } from './locate' +import './runtime' +import { installTheme } from './theme' -responseSpy.install() +configureUi({ + id: 'better-chatgpt', + title: 'Better ChatGPT', + version: __VERSION__, + marker: uiMarker, + composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) +}) -const session = new ChatSession(responseSpy) +installTheme() new App() - .register((context) => new DiagnosticsFeature(context, session)) + .register((context) => new HeaderButtonFeature(context)) + .register((context) => new DiagnosticsFeature(context)) .start() diff --git a/ai/chatgpt/src/runtime.ts b/ai/chatgpt/src/runtime.ts new file mode 100644 index 0000000..bff6715 --- /dev/null +++ b/ai/chatgpt/src/runtime.ts @@ -0,0 +1,6 @@ +import { responseSpy } from './network' +import { ChatSession } from './session' + +responseSpy.install() + +export const session = new ChatSession(responseSpy) diff --git a/ai/chatgpt/src/selectors.ts b/ai/chatgpt/src/selectors.ts index 6b54bf0..85e4b36 100644 --- a/ai/chatgpt/src/selectors.ts +++ b/ai/chatgpt/src/selectors.ts @@ -5,11 +5,7 @@ export const SELECTORS = { attach: '[data-composer-navigation-target="add-context"]', modeToggle: 'button[aria-pressed]', headerSlot: '[data-app-shell-header-obstacle="true"]', - sidebar: 'aside', - sidebarNav: 'aside nav', - codeBlock: '[data-code-block="true"]', - codeControls: '[data-code-block-controls]', - codeSource: '[data-chatgpt-copy-code]' + sidebar: 'aside' } as const export const STOP_LABEL = /\b(stop|arr[eê]t\w*|stopp\w*|detener|parar)\b/i diff --git a/ai/chatgpt/src/theme.ts b/ai/chatgpt/src/theme.ts new file mode 100644 index 0000000..624b9db --- /dev/null +++ b/ai/chatgpt/src/theme.ts @@ -0,0 +1,34 @@ +import { injectStyle } from '@nolly/core' + +const CSS = ` +html.dark .bp-themed { + --bp-bg: hsl(0 0% 13%); + --bp-fg: hsl(0 0% 98%); + --bp-muted: hsl(0 0% 64%); + --bp-border: hsl(0 0% 24%); + --bp-accent: hsl(0 0% 18%); + --bp-track: hsl(0 0% 30%); + --bp-ring: hsl(0 0% 60%); + --bp-green: hsl(142 71% 45%); + --bp-yellow: hsl(38 92% 50%); + --bp-red: hsl(0 84% 60%); +} + +html.light .bp-themed { + --bp-bg: hsl(0 0% 100%); + --bp-fg: hsl(0 0% 6%); + --bp-muted: hsl(0 0% 42%); + --bp-border: hsl(0 0% 88%); + --bp-accent: hsl(0 0% 95%); + --bp-track: hsl(0 0% 78%); + --bp-ring: hsl(0 0% 60%); + --bp-green: hsl(142 71% 40%); + --bp-yellow: hsl(38 92% 45%); + --bp-red: hsl(0 84% 55%); +} + +.bp-tip-mode { font-weight: 600; } +.bp-tip-sub { color: var(--bp-muted); } +` + +export const installTheme = (): void => injectStyle('better-chatgpt-theme', CSS) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 1fe6548..0edbca5 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -2,6 +2,11 @@ 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/). +## [Unreleased] + +- Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. +- Fixed: the batch runner was registered twice. + ## [1.0.5-hotfix.1] - 2026-11-09 ### Fixed diff --git a/ai/perplexity/README.md b/ai/perplexity/README.md index 6df4e52..59ca78b 100644 --- a/ai/perplexity/README.md +++ b/ai/perplexity/README.md @@ -59,9 +59,9 @@ No analytics and no server of its own. The script talks to Perplexity from your ## Built on the shared core -Better Perplexity is built on [`@nolly/core`](../core/README.md), the shared runtime used by every userscript in this repository. The core provides the feature lifecycle, storage, logging, DOM helpers, HTTP, menus, style injection and the page request observer. Better Perplexity keeps only what is specific to Perplexity: the modules, the composer and selector logic, and the UI. +Better Perplexity is built on [`@nolly/core`](../../core/README.md), the shared runtime, and on [`@nolly/ai`](../../core/ai/README.md), the code shared with the other AI-chat scripts (composer handling, key synthesis, generation detection). Better Perplexity keeps only what is specific to Perplexity: the modules, the selectors and the UI. -You do not install the core separately. It is bundled into `better-perplexity.user.js` at build time, so the installed script has no extra dependencies. See [Architecture](docs/architecture/) for details. +You do not install either package separately. Both are bundled into `better-perplexity.user.js` at build time, so the installed script has no extra dependencies. See [Architecture](docs/architecture/) for details. ## Development @@ -69,14 +69,14 @@ The repository is a Bun workspace. Install once at the repository root, then wor ```bash bun install # at the repository root -cd better-perplexity +cd ai/perplexity bun run dev # unminified, rebuilds on change bun run typecheck bun run build # minified userscript in dist/ ``` -Building needs the `core/` folder next to `better-perplexity/`. See [CONTRIBUTING.md](../CONTRIBUTING.md). +Building needs the `core/` and `core/ai/` folders at the repository root. See [CONTRIBUTING.md](../../CONTRIBUTING.md). ## License -[PolyForm Strict License 1.0.0](../LICENSE). +[PolyForm Strict License 1.0.0](../../LICENSE). diff --git a/ai/perplexity/docs/architecture.md b/ai/perplexity/docs/architecture.md index d3fe04c..3f21322 100644 --- a/ai/perplexity/docs/architecture.md +++ b/ai/perplexity/docs/architecture.md @@ -16,12 +16,15 @@ Better Perplexity is a thin layer on top of `@nolly/core`, a small library share - **Utilities:** storage, logging, DOM helpers, waiting, HTTP, userscript-manager menus, style injection and the page `fetch` observer. - **Build:** the metadata header and the bundle are produced by `@nolly/core/build`. +## What comes from @nolly/ai + +`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The dialogs, toasts, tooltips, controls, icons and settings dialog also live there; Better Perplexity configures them once in `main.ts`. + ## What stays in Better Perplexity - **Modules:** one folder per feature under `src/modules`. -- **Perplexity logic:** composer handling, selectors, placeholders and the usage tracker. -- **UI kit:** dialogs, toasts, tooltips and controls. -- **Instances:** the logger name, the storage key mapping, the UI marker `data-bp-root`, and the extraction of the account header from page requests. +- **Perplexity logic:** selectors, placeholders and the usage tracker. +- **Instances:** the logger name, the storage key mapping, the UI marker `data-bp-root`, the bindings of the shared kits, and the extraction of the account header from page requests. ## Compatibility @@ -29,4 +32,4 @@ Settings and drafts use the same storage keys as version 1.0.0, so nothing is lo ## Building from source -The repository is a Bun workspace. Run `bun install` at the root, then `bun run build` in `better-perplexity`. The build fails if the `core/` folder is missing. +The repository is a Bun workspace. Run `bun install` at the root, then `bun run build` in `ai/perplexity`. The build fails if the `core/` or `core/ai/` folders are missing. diff --git a/ai/perplexity/package.json b/ai/perplexity/package.json index 8566245..45851ca 100644 --- a/ai/perplexity/package.json +++ b/ai/perplexity/package.json @@ -1,26 +1,27 @@ { - "name": "@nolly/ai-perplexity", - "version": "1.0.5-hotfix.1", - "private": true, - "type": "module", - "license": "PolyForm-Strict-1.0.0", - "repository": { - "type": "git", - "url": "git+https://github.com/thenolle/userscripts.git", - "directory": "ai/perplexity" - }, - "scripts": { - "build": "bun run scripts/build.ts", - "dev": "bun run scripts/build.ts --watch", - "typecheck": "tsc --noEmit", - "validate:prompts": "bun run scripts/validate-prompts.ts" - }, - "dependencies": { - "@nolly/ai": "workspace:*", - "@nolly/core": "workspace:*" - }, - "devDependencies": { - "@types/bun": "^1.4.4", - "typescript": "^7.0.2" - } + "name": "@nolly/ai-perplexity", + "version": "1.0.5-hotfix.1", + "private": true, + "type": "module", + "license": "PolyForm-Strict-1.0.0", + "userscript": { "slug": "better-perplexity" }, + "repository": { + "type": "git", + "url": "git+https://github.com/thenolle/userscripts.git", + "directory": "ai/perplexity" + }, + "scripts": { + "build": "bun run scripts/build.ts", + "dev": "bun run scripts/build.ts --watch", + "typecheck": "tsc --noEmit", + "validate:prompts": "bun run scripts/validate-prompts.ts" + }, + "dependencies": { + "@nolly/ai": "workspace:*", + "@nolly/core": "workspace:*" + }, + "devDependencies": { + "@types/bun": "^1.4.4", + "typescript": "^7.0.2" + } } diff --git a/ai/perplexity/src/core/app.ts b/ai/perplexity/src/core/app.ts index c53c1af..664faca 100644 --- a/ai/perplexity/src/core/app.ts +++ b/ai/perplexity/src/core/app.ts @@ -1,6 +1,6 @@ import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from '../config' -import { toggleSettingsDialog } from '../ui/settings-dialog' +import { toggleSettingsDialog } from '@nolly/ai' import { uiMarker } from './dom' export class App extends Userscript { diff --git a/ai/perplexity/src/core/composer.ts b/ai/perplexity/src/core/composer.ts index e848c96..e006791 100644 --- a/ai/perplexity/src/core/composer.ts +++ b/ai/perplexity/src/core/composer.ts @@ -1,6 +1,4 @@ import { createComposerKit } from '@nolly/ai' import { isOwnUi } from './dom' -export { EDITABLE_SELECTOR, isComposerEmpty, isSendButton, readComposer } from '@nolly/ai' - export const { editableFrom, findComposer, writeComposer, sendComposer, attachFile } = createComposerKit({ isOwnUi }) diff --git a/ai/perplexity/src/core/dispatch.ts b/ai/perplexity/src/core/dispatch.ts index 4cfdf78..e68b97b 100644 --- a/ai/perplexity/src/core/dispatch.ts +++ b/ai/perplexity/src/core/dispatch.ts @@ -1,14 +1,4 @@ -import { sleep, waitFor } from '@nolly/core' -import { automate } from './automation' -import { findComposer, readComposer, sendComposer, writeComposer } from './composer' +import { createPromptSender } from '@nolly/ai' +import { findComposer, sendComposer, writeComposer } from './composer' -export const sendPrompt = (prompt: string, signal?: AbortSignal): Promise => automate(async () => { - for (let attempt = 0; attempt < 2; attempt++) { - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) - if (!composer) return false - if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true - if (readComposer(composer).trim() === '') return true - await sleep(1_500, signal) - } - return false -}) +export const sendPrompt = createPromptSender({ findComposer, writeComposer, sendComposer }) diff --git a/ai/perplexity/src/core/generation.ts b/ai/perplexity/src/core/generation.ts index 8379a17..88ebd07 100644 --- a/ai/perplexity/src/core/generation.ts +++ b/ai/perplexity/src/core/generation.ts @@ -1,6 +1,4 @@ import { createGenerationKit } from '@nolly/ai' import { isOwnUi } from './dom' -export type { ResponseWaitOptions } from '@nolly/ai' - export const { isGenerating, waitForResponse } = createGenerationKit({ adapter: { isOwnUi } }) diff --git a/ai/perplexity/src/core/synthetic-keys.ts b/ai/perplexity/src/core/synthetic-keys.ts deleted file mode 100644 index 038ba9d..0000000 --- a/ai/perplexity/src/core/synthetic-keys.ts +++ /dev/null @@ -1 +0,0 @@ -export { dispatchEnter, findGenericSendButton as findSendButton, isSynthetic } from '@nolly/ai' diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index 24bd66b..72a1686 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,5 +1,8 @@ import { App } from './core/app' import { fetchSpy } from './core/fetch-spy' +import { configureUi } from '@nolly/ai' +import { uiMarker } from './core/dom' +import { findComposerActions } from './locate' import { BatchRunnerModule } from './modules/batch-runner' import { CodeBlocksModule } from './modules/code-blocks' import { CommandPaletteModule } from './modules/command-palette' @@ -17,23 +20,24 @@ import { UsageStatusModule } from './modules/usage-status' import { PromptQueueModule } from './modules/prompt-queue' import { RecallModule } from './modules/recall' +configureUi({ id: 'better-perplexity', title: 'Better Perplexity', version: __VERSION__, marker: uiMarker, composerActions: findComposerActions }) fetchSpy.install() new App() - .register((context) => new PromptLibraryModule(context)) - .register((context) => new SelectionToolbarModule(context)) - .register((context) => new MaxWidthModule(context)) - .register((context) => new EnterAsNewlineModule(context)) - .register((context) => new CodeBlocksModule(context)) - .register((context) => new MessageSplitterModule(context)) - .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardModule(context)) - .register((context) => new CommandPaletteModule(context)) - .register((context) => new ExporterModule(context)) - .register((context) => new UsageStatusModule(context)) - .register((context) => new GlobalSettingsModule(context)) - .register((context) => new TutorialModule(context)) - .register((context) => new UpdatesModule(context)) - .register((context) => new PromptQueueModule(context)) - .register((context) => new RecallModule(context)) - .start() + .register((context) => new PromptLibraryModule(context)) + .register((context) => new SelectionToolbarModule(context)) + .register((context) => new MaxWidthModule(context)) + .register((context) => new EnterAsNewlineModule(context)) + .register((context) => new CodeBlocksModule(context)) + .register((context) => new MessageSplitterModule(context)) + .register((context) => new BatchRunnerModule(context)) + .register((context) => new DraftGuardModule(context)) + .register((context) => new CommandPaletteModule(context)) + .register((context) => new ExporterModule(context)) + .register((context) => new UsageStatusModule(context)) + .register((context) => new GlobalSettingsModule(context)) + .register((context) => new TutorialModule(context)) + .register((context) => new UpdatesModule(context)) + .register((context) => new PromptQueueModule(context)) + .register((context) => new RecallModule(context)) + .start() diff --git a/ai/perplexity/src/modules/batch-runner/dialog.ts b/ai/perplexity/src/modules/batch-runner/dialog.ts index 32858fb..47b5ea3 100644 --- a/ai/perplexity/src/modules/batch-runner/dialog.ts +++ b/ai/perplexity/src/modules/batch-runner/dialog.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSwitch, createTextArea } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createNumberField, createSwitch, createTextArea } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { parseItems, renderTemplate } from './template' const DIALOG_ID = 'better-perplexity-batch-dialog' diff --git a/ai/perplexity/src/modules/batch-runner/index.ts b/ai/perplexity/src/modules/batch-runner/index.ts index 5e562e1..d47d5a5 100644 --- a/ai/perplexity/src/modules/batch-runner/index.ts +++ b/ai/perplexity/src/modules/batch-runner/index.ts @@ -1,7 +1,7 @@ import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { ComposerButton } from '../../ui/composer-button' -import { applyValues, findFields } from '../../core/placeholders' -import { askFields } from '../../ui/placeholder-dialog' +import { ComposerButton } from '@nolly/ai' +import { applyValues, findFields } from '@nolly/ai' +import { askFields } from '@nolly/ai' import { openBatchDialog, type BatchInput } from './dialog' import { renderTemplate } from './template' import { BatchPanel } from './panel' diff --git a/ai/perplexity/src/modules/batch-runner/panel.ts b/ai/perplexity/src/modules/batch-runner/panel.ts index 90f7871..2ce0f3d 100644 --- a/ai/perplexity/src/modules/batch-runner/panel.ts +++ b/ai/perplexity/src/modules/batch-runner/panel.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton } from '../../ui/controls' -import { ensureUiStyles } from '../../ui/styles' +import { createButton } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import type { BatchPhase, BatchResult } from './runner' const CSS_ID = 'better-perplexity-batch-styles' diff --git a/ai/perplexity/src/modules/batch-runner/runner.ts b/ai/perplexity/src/modules/batch-runner/runner.ts index a8ac846..32221fa 100644 --- a/ai/perplexity/src/modules/batch-runner/runner.ts +++ b/ai/perplexity/src/modules/batch-runner/runner.ts @@ -1,5 +1,6 @@ -import { automate } from '../../core/automation' -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' +import { automate } from '@nolly/ai' +import { findComposer, sendComposer, writeComposer } from '../../core/composer' +import { readComposer } from '@nolly/ai' import { waitForResponse } from '../../core/generation' import { logger } from '../../core/logger' import { storage } from '../../core/storage' diff --git a/ai/perplexity/src/modules/code-blocks/badges.ts b/ai/perplexity/src/modules/code-blocks/badges.ts index 373543e..11fd67e 100644 --- a/ai/perplexity/src/modules/code-blocks/badges.ts +++ b/ai/perplexity/src/modules/code-blocks/badges.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { createIcon } from '../../ui/icons' +import { createIcon } from '@nolly/ai' type Badge = readonly [label: string, background: string, color: string] diff --git a/ai/perplexity/src/modules/code-blocks/block.ts b/ai/perplexity/src/modules/code-blocks/block.ts index b6e515a..e30fe50 100644 --- a/ai/perplexity/src/modules/code-blocks/block.ts +++ b/ai/perplexity/src/modules/code-blocks/block.ts @@ -1,7 +1,7 @@ -import { copyText } from '../../core/clipboard' +import { copyText } from '@nolly/ai' import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon, type IconName } from '../../ui/icons' +import { createIcon, type IconName } from '@nolly/ai' import type { BlockInfo } from './detect' import { highlightLines } from './highlight' import { languageInfo } from './languages' diff --git a/ai/perplexity/src/modules/code-blocks/dialog.ts b/ai/perplexity/src/modules/code-blocks/dialog.ts index c128f9a..29e0ce3 100644 --- a/ai/perplexity/src/modules/code-blocks/dialog.ts +++ b/ai/perplexity/src/modules/code-blocks/dialog.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSelectField, createSwitch } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createNumberField, createSelectField, createSwitch } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { DEFAULT_CODE_SETTINGS, type CodeBlockSettings } from './settings' const DIALOG_ID = 'better-perplexity-code-dialog' diff --git a/ai/perplexity/src/modules/code-blocks/index.ts b/ai/perplexity/src/modules/code-blocks/index.ts index 6e3546a..6772f77 100644 --- a/ai/perplexity/src/modules/code-blocks/index.ts +++ b/ai/perplexity/src/modules/code-blocks/index.ts @@ -1,4 +1,4 @@ -import { copyText } from '../../core/clipboard' +import { copyText } from '@nolly/ai' import { Feature, type MenuEntry } from '@nolly/core' import { isOwnUi } from '../../core/dom' import { isGenerating } from '../../core/generation' diff --git a/ai/perplexity/src/modules/command-palette/dialog.ts b/ai/perplexity/src/modules/command-palette/dialog.ts index a3c73f8..05963cc 100644 --- a/ai/perplexity/src/modules/command-palette/dialog.ts +++ b/ai/perplexity/src/modules/command-palette/dialog.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { createButton } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { DEFAULT_SHORTCUT, formatShortcut, shortcutFromEvent, type Shortcut } from './shortcut' import { ensurePaletteStyles } from './styles' diff --git a/ai/perplexity/src/modules/command-palette/index.ts b/ai/perplexity/src/modules/command-palette/index.ts index afa8502..6b04b57 100644 --- a/ai/perplexity/src/modules/command-palette/index.ts +++ b/ai/perplexity/src/modules/command-palette/index.ts @@ -1,5 +1,5 @@ import { findComposer, writeComposer } from '../../core/composer' -import { copyText } from '../../core/clipboard' +import { copyText } from '@nolly/ai' import { Feature, type FeatureCommand, type MenuEntry } from '@nolly/core' import { toggleShortcutDialog } from './dialog' import { togglePalette } from './palette' diff --git a/ai/perplexity/src/modules/command-palette/palette.ts b/ai/perplexity/src/modules/command-palette/palette.ts index 8a81ea4..9e538fe 100644 --- a/ai/perplexity/src/modules/command-palette/palette.ts +++ b/ai/perplexity/src/modules/command-palette/palette.ts @@ -1,6 +1,6 @@ import { type Command, createElement } from '@nolly/core' import { storage } from '../../core/storage' -import { createDialog } from '../../ui/dialog' +import { createDialog } from '@nolly/ai' import { fuzzyScore } from './fuzzy' import { ensurePaletteStyles } from './styles' diff --git a/ai/perplexity/src/modules/draft-guard/index.ts b/ai/perplexity/src/modules/draft-guard/index.ts index 72189eb..aa10190 100644 --- a/ai/perplexity/src/modules/draft-guard/index.ts +++ b/ai/perplexity/src/modules/draft-guard/index.ts @@ -1,4 +1,5 @@ -import { findComposer, isSendButton, readComposer, writeComposer } from '../../core/composer' +import { findComposer, writeComposer } from '../../core/composer' +import { isSendButton, readComposer } from '@nolly/ai' import { Feature, type MenuEntry, type ScriptContext, toElement } from '@nolly/core' import { fetchSpy } from '../../core/fetch-spy' import { storage } from '../../core/storage' diff --git a/ai/perplexity/src/modules/draft-guard/overlay.ts b/ai/perplexity/src/modules/draft-guard/overlay.ts index 75403b7..6bc8327 100644 --- a/ai/perplexity/src/modules/draft-guard/overlay.ts +++ b/ai/perplexity/src/modules/draft-guard/overlay.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' -import { ensureUiStyles } from '../../ui/styles' +import { estimateTokens } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import type { Draft } from './store' import { ensureDraftStyles } from './styles' diff --git a/ai/perplexity/src/modules/enter-as-newline/config-button.ts b/ai/perplexity/src/modules/enter-as-newline/config-button.ts index 0665bfe..b68c0a2 100644 --- a/ai/perplexity/src/modules/enter-as-newline/config-button.ts +++ b/ai/perplexity/src/modules/enter-as-newline/config-button.ts @@ -1,8 +1,8 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' import { findComposerActions } from '../../locate' -import { ensureUiStyles } from '../../ui/styles' -import { Tooltip } from '../../ui/tooltip' +import { ensureUiStyles } from '@nolly/ai' +import { Tooltip } from '@nolly/ai' import { ensureConfigButtonStyles } from './styles' const SVG_NS = 'http://www.w3.org/2000/svg' diff --git a/ai/perplexity/src/modules/enter-as-newline/dialog.ts b/ai/perplexity/src/modules/enter-as-newline/dialog.ts index 0e3a939..e1143e3 100644 --- a/ai/perplexity/src/modules/enter-as-newline/dialog.ts +++ b/ai/perplexity/src/modules/enter-as-newline/dialog.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' import { logger } from '../../core/logger' -import { createButton, createSwitch } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createSwitch } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts, type Modifier, type ShortcutSettings } from './shortcuts' const DIALOG_ID = 'better-perplexity-enter-dialog' diff --git a/ai/perplexity/src/modules/enter-as-newline/index.ts b/ai/perplexity/src/modules/enter-as-newline/index.ts index 656c0d8..ccba4c5 100644 --- a/ai/perplexity/src/modules/enter-as-newline/index.ts +++ b/ai/perplexity/src/modules/enter-as-newline/index.ts @@ -1,8 +1,9 @@ -import { logger } from '../../core/logger' +import { isSynthetic } from '@nolly/ai' import { Feature, type MenuEntry } from '@nolly/core' +import { logger } from '../../core/logger' import { ConfigButton } from './config-button' import { toggleShortcutsDialog } from './dialog' -import { getEditableTarget, insertNewline, isComposing, isSynthetic, sendMessage } from './keyboard' +import { getEditableTarget, insertNewline, isComposing, sendMessage } from './keyboard' import { describeShortcuts, hasModifier, loadShortcuts, matchesShortcut, saveShortcuts, type ShortcutSettings } from './shortcuts' export class EnterAsNewlineModule extends Feature { @@ -59,4 +60,4 @@ export class EnterAsNewlineModule extends Feature { event.stopImmediatePropagation() insertNewline(editable) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts b/ai/perplexity/src/modules/enter-as-newline/keyboard.ts index 44038c6..15018a7 100644 --- a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts +++ b/ai/perplexity/src/modules/enter-as-newline/keyboard.ts @@ -1,7 +1,5 @@ +import { dispatchEnter, findSendButton } from '@nolly/ai' import { toElement } from '@nolly/core' -import { dispatchEnter, findSendButton } from '../../core/synthetic-keys' - -export { isSynthetic } from '../../core/synthetic-keys' const EDITABLE_SELECTOR = 'textarea, [contenteditable="true"], [contenteditable="plaintext-only"]' @@ -43,4 +41,4 @@ export const insertNewline = (editable: HTMLElement): void => { export const sendMessage = (editable: HTMLElement): void => { if (dispatchEnter(editable, false)) findSendButton(editable)?.click() -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/dialog.ts b/ai/perplexity/src/modules/exporter/dialog.ts index 802465c..c8f70ff 100644 --- a/ai/perplexity/src/modules/exporter/dialog.ts +++ b/ai/perplexity/src/modules/exporter/dialog.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { createButton, createSelectField, createSwitch } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createSelectField, createSwitch } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import type { CitationStyle } from './citations' import { runExport } from './service' import type { ExportFormat, ExportSettings } from './settings' diff --git a/ai/perplexity/src/modules/exporter/index.ts b/ai/perplexity/src/modules/exporter/index.ts index 1558c0f..8feac73 100644 --- a/ai/perplexity/src/modules/exporter/index.ts +++ b/ai/perplexity/src/modules/exporter/index.ts @@ -1,8 +1,8 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' -import { Tooltip } from '../../ui/tooltip' +import { createIcon } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' +import { Tooltip } from '@nolly/ai' import { currentThreadSlug } from './api' import { toggleExportDialog } from './dialog' import { loadExportSettings, saveExportSettings, type ExportSettings } from './settings' diff --git a/ai/perplexity/src/modules/exporter/service.ts b/ai/perplexity/src/modules/exporter/service.ts index 418f041..b60202a 100644 --- a/ai/perplexity/src/modules/exporter/service.ts +++ b/ai/perplexity/src/modules/exporter/service.ts @@ -1,5 +1,5 @@ -import { copyText } from '../../core/clipboard' -import { saveFile } from '../../core/download' +import { copyText } from '@nolly/ai' +import { saveFile } from '@nolly/ai' import { currentThreadSlug, exportThread, fetchThreadJson } from './api' import { reformatCitations, stripLogo } from './citations' import { buildDocx } from './docx' diff --git a/ai/perplexity/src/modules/global-settings/dialog.ts b/ai/perplexity/src/modules/global-settings/dialog.ts index fa17fa4..7982c6c 100644 --- a/ai/perplexity/src/modules/global-settings/dialog.ts +++ b/ai/perplexity/src/modules/global-settings/dialog.ts @@ -1,6 +1,6 @@ import { createElement, type ScriptContext } from '@nolly/core' -import { createButton, createSwitch } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createSwitch } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { ensureGearStyles } from './styles' const DIALOG_ID = 'better-perplexity-settings-dialog' diff --git a/ai/perplexity/src/modules/global-settings/index.ts b/ai/perplexity/src/modules/global-settings/index.ts index 2bb100a..7f61b58 100644 --- a/ai/perplexity/src/modules/global-settings/index.ts +++ b/ai/perplexity/src/modules/global-settings/index.ts @@ -1,8 +1,8 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' -import { Tooltip } from '../../ui/tooltip' +import { createIcon } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' +import { Tooltip } from '@nolly/ai' import { toggleGlobalSettings } from './dialog' import { ensureGearStyles } from './styles' diff --git a/ai/perplexity/src/modules/message-splitter/big-text.ts b/ai/perplexity/src/modules/message-splitter/big-text.ts index 1d66a05..618e8fe 100644 --- a/ai/perplexity/src/modules/message-splitter/big-text.ts +++ b/ai/perplexity/src/modules/message-splitter/big-text.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' -import { estimateTokens } from '../../core/tokens' -import { createButton, createNumberField, createSelectField, createTextArea } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { estimateTokens } from '@nolly/ai' +import { createButton, createNumberField, createSelectField, createTextArea } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { createPartRows, formatNumber, type SplitChoice } from './dialog' import { planParts, type SplitPlan } from './plan' import type { SplitterSettings } from './settings' diff --git a/ai/perplexity/src/modules/message-splitter/dialog.ts b/ai/perplexity/src/modules/message-splitter/dialog.ts index b557d94..46e7ff5 100644 --- a/ai/perplexity/src/modules/message-splitter/dialog.ts +++ b/ai/perplexity/src/modules/message-splitter/dialog.ts @@ -1,9 +1,9 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' -import { createButton, createNumberField, createSelectField, createSwitch, createTextArea } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' -import { ensureUiStyles } from '../../ui/styles' +import { estimateTokens } from '@nolly/ai' +import { createButton, createNumberField, createSelectField, createSwitch, createTextArea } from '@nolly/ai' +import { createDialog } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import { planParts, type SplitPlan } from './plan' import type { PartStatus } from './runner' import type { SplitterSettings } from './settings' diff --git a/ai/perplexity/src/modules/message-splitter/index.ts b/ai/perplexity/src/modules/message-splitter/index.ts index 4127a6a..c38934e 100644 --- a/ai/perplexity/src/modules/message-splitter/index.ts +++ b/ai/perplexity/src/modules/message-splitter/index.ts @@ -1,13 +1,14 @@ -import { attachFile, editableFrom, findComposer, isSendButton, readComposer, writeComposer } from '../../core/composer' +import { attachFile, editableFrom, findComposer, writeComposer } from '../../core/composer' +import { isSendButton, readComposer } from '@nolly/ai' import { Feature, type MenuEntry, toElement, waitFor } from '@nolly/core' import { isOwnUi } from '../../core/dom' -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '@nolly/ai' import { ProgressPanel, openSplitDialog, type SplitChoice } from './dialog' import { SendRunner } from './runner' import { loadSplitterSettings, saveSplitterSettings, type SplitterSettings } from './settings' -import { ComposerButton } from '../../ui/composer-button' +import { ComposerButton } from '@nolly/ai' import { openBigTextDialog } from './big-text' -import { isAutomating } from '../../core/automation' +import { isAutomating } from '@nolly/ai' export class MessageSplitterModule extends Feature { readonly id = 'message-splitter' diff --git a/ai/perplexity/src/modules/message-splitter/plan.ts b/ai/perplexity/src/modules/message-splitter/plan.ts index 50eab44..945e469 100644 --- a/ai/perplexity/src/modules/message-splitter/plan.ts +++ b/ai/perplexity/src/modules/message-splitter/plan.ts @@ -1,4 +1,4 @@ -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '@nolly/ai' import { splitText } from './splitter' export interface PartTemplates { diff --git a/ai/perplexity/src/modules/message-splitter/splitter.ts b/ai/perplexity/src/modules/message-splitter/splitter.ts index 123d21e..454bf7e 100644 --- a/ai/perplexity/src/modules/message-splitter/splitter.ts +++ b/ai/perplexity/src/modules/message-splitter/splitter.ts @@ -1,4 +1,4 @@ -import { estimateTokens } from '../../core/tokens' +import { estimateTokens } from '@nolly/ai' interface CodeAtom { kind: 'code' diff --git a/ai/perplexity/src/modules/prompt-library/index.ts b/ai/perplexity/src/modules/prompt-library/index.ts index 3327aaf..ca8fcec 100644 --- a/ai/perplexity/src/modules/prompt-library/index.ts +++ b/ai/perplexity/src/modules/prompt-library/index.ts @@ -1,7 +1,7 @@ import { findComposer, writeComposer } from '../../core/composer' import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { storage } from '../../core/storage' -import { ComposerButton } from '../../ui/composer-button' +import { ComposerButton } from '@nolly/ai' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { toggleManager } from './manager' diff --git a/ai/perplexity/src/modules/prompt-library/manager.ts b/ai/perplexity/src/modules/prompt-library/manager.ts index 11f4bdd..3704449 100644 --- a/ai/perplexity/src/modules/prompt-library/manager.ts +++ b/ai/perplexity/src/modules/prompt-library/manager.ts @@ -1,7 +1,7 @@ -import { copyText } from '../../core/clipboard' +import { copyText } from '@nolly/ai' import { createElement } from '@nolly/core' -import { createButton, createTextArea } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createTextArea } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import type { Prompt, PromptStore } from './store' import { ensureSlashStyles } from './styles' diff --git a/ai/perplexity/src/modules/prompt-library/picker.ts b/ai/perplexity/src/modules/prompt-library/picker.ts index 9ab367c..7fedc49 100644 --- a/ai/perplexity/src/modules/prompt-library/picker.ts +++ b/ai/perplexity/src/modules/prompt-library/picker.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { createDialog } from '../../ui/dialog' +import { createDialog } from '@nolly/ai' import { fuzzyScore } from '../command-palette/fuzzy' import { ensurePaletteStyles } from '../command-palette/styles' import type { Prompt, PromptStore } from './store' diff --git a/ai/perplexity/src/modules/prompt-library/variables.ts b/ai/perplexity/src/modules/prompt-library/variables.ts index ad19c84..f68d21c 100644 --- a/ai/perplexity/src/modules/prompt-library/variables.ts +++ b/ai/perplexity/src/modules/prompt-library/variables.ts @@ -1,6 +1,6 @@ -import { applyValues, findFields, type Field } from '../../core/placeholders' -import { currentSelection } from '../../core/selection' -import { askFields } from '../../ui/placeholder-dialog' +import { applyValues, findFields, type Field } from '@nolly/ai' +import { currentSelection } from '@nolly/ai' +import { askFields } from '@nolly/ai' const BUILTINS = new Set(['clipboard', 'selection', 'date', 'time', 'url', 'title']) diff --git a/ai/perplexity/src/modules/prompt-queue/index.ts b/ai/perplexity/src/modules/prompt-queue/index.ts index 9a6563b..8189dd7 100644 --- a/ai/perplexity/src/modules/prompt-queue/index.ts +++ b/ai/perplexity/src/modules/prompt-queue/index.ts @@ -1,10 +1,11 @@ import { Feature, waitFor, type MenuEntry, type ScriptContext } from '@nolly/core' -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' +import { findComposer, sendComposer, writeComposer } from '../../core/composer' +import { readComposer } from '@nolly/ai' import { sendPrompt } from '../../core/dispatch' import { isGenerating, waitForResponse } from '../../core/generation' import { storage } from '../../core/storage' -import { ComposerButton } from '../../ui/composer-button' -import { showToast } from '../../ui/toast' +import { ComposerButton } from '@nolly/ai' +import { showToast } from '@nolly/ai' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { recordPrompt } from '../recall/history' diff --git a/ai/perplexity/src/modules/prompt-queue/panel.ts b/ai/perplexity/src/modules/prompt-queue/panel.ts index 02adc77..4818593 100644 --- a/ai/perplexity/src/modules/prompt-queue/panel.ts +++ b/ai/perplexity/src/modules/prompt-queue/panel.ts @@ -1,9 +1,9 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' import { storage } from '../../core/storage' -import { createButton } from '../../ui/controls' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' +import { createButton } from '@nolly/ai' +import { createIcon } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import type { PromptQueue, QueueItem } from './queue' import type { Phase, QueueRunner } from './runner' import { ensureQueueStyles } from './styles' diff --git a/ai/perplexity/src/modules/recall/dialog.ts b/ai/perplexity/src/modules/recall/dialog.ts index 01d4a92..949c45b 100644 --- a/ai/perplexity/src/modules/recall/dialog.ts +++ b/ai/perplexity/src/modules/recall/dialog.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' -import { copyText } from '../../core/clipboard' -import { createDialog } from '../../ui/dialog' -import { showToast } from '../../ui/toast' +import { copyText } from '@nolly/ai' +import { createDialog } from '@nolly/ai' +import { showToast } from '@nolly/ai' import { ensurePaletteStyles } from '../command-palette/styles' import { threadLabel, timeAgo } from './format' import type { HistoryEntry, HistoryFilter, HistoryStore } from './store' diff --git a/ai/perplexity/src/modules/recall/index.ts b/ai/perplexity/src/modules/recall/index.ts index d086299..29047b3 100644 --- a/ai/perplexity/src/modules/recall/index.ts +++ b/ai/perplexity/src/modules/recall/index.ts @@ -1,14 +1,15 @@ import { Feature, toElement, type MenuEntry, type ScriptContext } from '@nolly/core' -import { isAutomating } from '../../core/automation' -import { copyText } from '../../core/clipboard' -import { editableFrom, findComposer, isSendButton, readComposer, sendComposer, writeComposer } from '../../core/composer' +import { isAutomating } from '@nolly/ai' +import { copyText } from '@nolly/ai' +import { editableFrom, findComposer, sendComposer, writeComposer } from '../../core/composer' +import { isSendButton, readComposer } from '@nolly/ai' import { isOwnUi } from '../../core/dom' -import { saveFile } from '../../core/download' +import { saveFile } from '@nolly/ai' import { fetchSpy } from '../../core/fetch-spy' import { isAskRequest } from '../../core/requests' import { storage } from '../../core/storage' -import { ComposerButton } from '../../ui/composer-button' -import { showToast } from '../../ui/toast' +import { ComposerButton } from '@nolly/ai' +import { showToast } from '@nolly/ai' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { promptQueue, threadOf } from '../prompt-queue/queue' diff --git a/ai/perplexity/src/modules/selection-toolbar/index.ts b/ai/perplexity/src/modules/selection-toolbar/index.ts index 4371259..a28fd9c 100644 --- a/ai/perplexity/src/modules/selection-toolbar/index.ts +++ b/ai/perplexity/src/modules/selection-toolbar/index.ts @@ -1,9 +1,10 @@ -import { findComposer, readComposer, sendComposer, writeComposer } from '../../core/composer' +import { findComposer, sendComposer, writeComposer } from '../../core/composer' +import { readComposer } from '@nolly/ai' import { createElement, Feature, injectStyle, type MenuEntry } from '@nolly/core' import { isOwnUi, markUi } from '../../core/dom' -import { rememberSelection } from '../../core/selection' -import { ensureUiStyles } from '../../ui/styles' -import { askFields } from '../../ui/placeholder-dialog' +import { rememberSelection } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' +import { askFields } from '@nolly/ai' interface Action { id: string diff --git a/ai/perplexity/src/modules/tutorial/engine.ts b/ai/perplexity/src/modules/tutorial/engine.ts index a9992a9..b343a65 100644 --- a/ai/perplexity/src/modules/tutorial/engine.ts +++ b/ai/perplexity/src/modules/tutorial/engine.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton } from '../../ui/controls' -import { ensureUiStyles } from '../../ui/styles' +import { createButton } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import { formatShortcut, matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { ensureTourStyles } from './styles' diff --git a/ai/perplexity/src/modules/tutorial/index.ts b/ai/perplexity/src/modules/tutorial/index.ts index e7a9b80..529a6c7 100644 --- a/ai/perplexity/src/modules/tutorial/index.ts +++ b/ai/perplexity/src/modules/tutorial/index.ts @@ -1,12 +1,12 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' import { storage } from '../../core/storage' -import { createButton } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' -import { createIcon } from '../../ui/icons' -import { ensureUiStyles } from '../../ui/styles' -import { showToast } from '../../ui/toast' -import { Tooltip } from '../../ui/tooltip' +import { createButton } from '@nolly/ai' +import { createDialog } from '@nolly/ai' +import { createIcon } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' +import { showToast } from '@nolly/ai' +import { Tooltip } from '@nolly/ai' import { TourRunner } from './engine' import { FULL_TOUR, TOURS, type Tour } from './tours' diff --git a/ai/perplexity/src/modules/updates/index.ts b/ai/perplexity/src/modules/updates/index.ts index dfcba75..5dadb00 100644 --- a/ai/perplexity/src/modules/updates/index.ts +++ b/ai/perplexity/src/modules/updates/index.ts @@ -2,7 +2,7 @@ import { Feature, Updater, type MenuEntry } from '@nolly/core' import { logger } from '../../core/logger' import { storage } from '../../core/storage' import { URLS } from '../../repo' -import { showToast } from '../../ui/toast' +import { showToast } from '@nolly/ai' export { isNewerVersion as isNewer } from '@nolly/core' diff --git a/ai/perplexity/src/modules/usage-status/alerts.ts b/ai/perplexity/src/modules/usage-status/alerts.ts index a3c5902..73d418b 100644 --- a/ai/perplexity/src/modules/usage-status/alerts.ts +++ b/ai/perplexity/src/modules/usage-status/alerts.ts @@ -1,6 +1,6 @@ import { notify, notifyPermission } from '@nolly/core' import { storage } from '../../core/storage' -import { showToast } from '../../ui/toast' +import { showToast } from '@nolly/ai' import { LIMITS, LIMIT_KEYS } from './definitions' import type { UsageService } from './service' import type { LimitKey } from './types' diff --git a/ai/perplexity/src/modules/usage-status/dialog.ts b/ai/perplexity/src/modules/usage-status/dialog.ts index bf94a5a..c9034cc 100644 --- a/ai/perplexity/src/modules/usage-status/dialog.ts +++ b/ai/perplexity/src/modules/usage-status/dialog.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { createButton, createDataRow, createSection } from '../../ui/controls' -import { createDialog } from '../../ui/dialog' +import { createButton, createDataRow, createSection } from '@nolly/ai' +import { createDialog } from '@nolly/ai' import { createStatusBar, createTimerBlock } from './components' import { LIMITS, LIMIT_KEYS, SETTINGS_FIELDS, SOURCE_LABELS, STATUS_LABELS } from './definitions' import { getStatus } from './format' diff --git a/ai/perplexity/src/modules/usage-status/index.ts b/ai/perplexity/src/modules/usage-status/index.ts index 5662112..09a4739 100644 --- a/ai/perplexity/src/modules/usage-status/index.ts +++ b/ai/perplexity/src/modules/usage-status/index.ts @@ -4,7 +4,7 @@ import { fetchSpy } from '../../core/fetch-spy' import { logger } from '../../core/logger' import { isAskRequest } from '../../core/requests' import { describePage } from '../../locate' -import { showToast } from '../../ui/toast' +import { showToast } from '@nolly/ai' import { UsageAlerts } from './alerts' import { UsageDialog } from './dialog' import { UsageIndicator } from './indicator' diff --git a/ai/perplexity/src/modules/usage-status/indicator.ts b/ai/perplexity/src/modules/usage-status/indicator.ts index 40f19e4..41d0497 100644 --- a/ai/perplexity/src/modules/usage-status/indicator.ts +++ b/ai/perplexity/src/modules/usage-status/indicator.ts @@ -1,7 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { Tooltip } from '../../ui/tooltip' -import { ensureUiStyles } from '../../ui/styles' +import { Tooltip } from '@nolly/ai' +import { ensureUiStyles } from '@nolly/ai' import { Dock } from './dock' import { isPlaced, type Placement } from './placement' import type { UsageService } from './service' diff --git a/ai/perplexity/src/ui/controls.ts b/ai/perplexity/src/ui/controls.ts deleted file mode 100644 index a64379b..0000000 --- a/ai/perplexity/src/ui/controls.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { createElement } from '@nolly/core' - -export interface ButtonOptions { - primary?: boolean - onClick?: (event: MouseEvent) => void -} - -export interface SwitchOptions { - label: string - hint?: string - checked: boolean - onChange: (checked: boolean) => void -} - -export interface NumberFieldOptions { - label: string - hint?: string - value: number - min?: number - max?: number - step?: number - onChange: (value: number) => void -} - -export const createButton = (label: string, { primary = false, onClick }: ButtonOptions = {}): HTMLButtonElement => { - const button = createElement('button', primary ? 'bp-button bp-button-primary' : 'bp-button', label) - button.type = 'button' - if (onClick) button.addEventListener('click', onClick) - return button -} - -export const createSwitch = ({ label, hint, checked, onChange }: SwitchOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { - const wrapper = createElement('label', 'bp-switch') - const text = createElement('span', 'bp-switch-text') - text.appendChild(createElement('span', undefined, label)) - if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) - const input = createElement('input') - input.type = 'checkbox' - input.checked = checked - input.addEventListener('change', () => onChange(input.checked)) - wrapper.append(text, input, createElement('span', 'bp-switch-track')) - return { wrapper, input } -} - -export const createSection = (title: string, aside?: string): HTMLElement => { - const section = createElement('section', 'bp-section') - const heading = createElement('h3', 'bp-section-heading') - heading.appendChild(createElement('span', undefined, title)) - if (aside !== undefined) heading.appendChild(createElement('span', undefined, aside)) - section.appendChild(heading) - return section -} - -export const createDataRow = (label: string, value: string, className = ''): HTMLElement => { - const row = createElement('div', 'bp-data-row') - row.append(createElement('span', 'bp-data-label', label), createElement('span', `bp-data-value ${className}`.trim(), value)) - return row -} - -export const createNumberField = ({ label, hint, value, min, max, step = 1, onChange }: NumberFieldOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { - const wrapper = createElement('label', 'bp-field') - const text = createElement('span', 'bp-switch-text') - text.appendChild(createElement('span', undefined, label)) - if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) - const input = createElement('input', 'bp-input') - input.type = 'number' - input.value = String(value) - input.step = String(step) - if (min !== undefined) input.min = String(min) - if (max !== undefined) input.max = String(max) - input.addEventListener('change', () => { - const parsed = Number(input.value) - if (!Number.isFinite(parsed)) return - const clamped = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, parsed)) - input.value = String(clamped) - onChange(clamped) - }) - wrapper.append(text, input) - return { wrapper, input } -} - -export const createSelectField = (label: string, options: readonly { value: T; label: string }[], value: T, onChange: (value: T) => void): HTMLLabelElement => { - const wrapper = createElement('label', 'bp-field') - wrapper.appendChild(createElement('span', undefined, label)) - const select = createElement('select', 'bp-input') - for (const option of options) { - const element = createElement('option', undefined, option.label) - element.value = option.value - select.appendChild(element) - } - select.value = value - select.addEventListener('change', () => onChange(select.value as T)) - wrapper.appendChild(select) - return wrapper -} - -export const createTextArea = (placeholder: string, value: string, onInput: (value: string) => void): HTMLTextAreaElement => { - const area = createElement('textarea', 'bp-input') - area.placeholder = placeholder - area.value = value - area.rows = 3 - area.addEventListener('input', () => onInput(area.value)) - return area -} \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/dialog.ts b/ai/perplexity/src/ui/css/dialog.ts deleted file mode 100644 index 983465f..0000000 --- a/ai/perplexity/src/ui/css/dialog.ts +++ /dev/null @@ -1,75 +0,0 @@ -export const DIALOG_CSS = ` -.bp-dialog { - width: min(var(--bp-width, 560px), calc(100vw - 32px)); - max-width: none; - max-height: min(86vh, 820px); - padding: 0; - overflow: hidden; - border: 1px solid var(--bp-border); - border-radius: 14px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 24px 60px -12px rgb(0 0 0 / 35%); - font-family: inherit; - font-size: 13px; - line-height: 1.5; -} - -.bp-dialog[open] { display: flex; flex-direction: column; animation: bp-dialog-in 160ms ease-out; } -.bp-dialog::backdrop { background: rgb(0 0 0 / 55%); backdrop-filter: blur(6px); animation: bp-fade-in 160ms ease-out; } -.bp-dialog *, .bp-dialog *::before, .bp-dialog *::after { box-sizing: border-box; } - -@keyframes bp-dialog-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } } -@keyframes bp-fade-in { from { opacity: 0; } to { opacity: 1; } } - -@media (prefers-reduced-motion: reduce) { - .bp-dialog[open], .bp-dialog::backdrop { animation: none; } -} - -.bp-dialog-header { - display: flex; - align-items: flex-start; - justify-content: space-between; - gap: 16px; - padding: 18px 20px 14px; - border-bottom: 1px solid var(--bp-border); -} - -.bp-dialog-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -.02em; } -.bp-dialog-description { margin: 3px 0 0; color: var(--bp-muted); font-size: 12px; } -.bp-dialog-body { flex: 1; min-height: 0; padding: 16px 20px; overflow-y: auto; overscroll-behavior: contain; } - -.bp-dialog-footer { - display: flex; - align-items: center; - justify-content: flex-end; - gap: 8px; - padding: 12px 20px; - border-top: 1px solid var(--bp-border); -} - -.bp-dialog-footer:empty { display: none; } - -.bp-icon-button { - display: inline-flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - width: 28px; - height: 28px; - border: 0; - border-radius: 7px; - background: transparent; - color: var(--bp-muted); - font: inherit; - font-size: 18px; - line-height: 1; - cursor: pointer; -} - -.bp-icon-button:hover { background: var(--bp-accent); color: var(--bp-fg); } - -@media (max-width: 520px) { - .bp-dialog-header, .bp-dialog-body, .bp-dialog-footer { padding-right: 14px; padding-left: 14px; } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/theme.ts b/ai/perplexity/src/ui/css/theme.ts deleted file mode 100644 index 2700e94..0000000 --- a/ai/perplexity/src/ui/css/theme.ts +++ /dev/null @@ -1,28 +0,0 @@ -export const THEME_CSS = ` -.bp-themed { - --bp-bg: hsl(0 0% 100%); - --bp-fg: hsl(240 10% 3.9%); - --bp-muted: hsl(240 3.8% 46.1%); - --bp-border: hsl(240 5.9% 90%); - --bp-accent: hsl(240 4.8% 95.9%); - --bp-track: hsl(240 5% 78%); - --bp-ring: hsl(240 5% 64.9%); - --bp-green: hsl(142 71% 40%); - --bp-yellow: hsl(38 92% 45%); - --bp-red: hsl(0 84% 55%); -} - -@media (prefers-color-scheme: dark) { - .bp-themed { - --bp-bg: hsl(240 10% 5%); - --bp-fg: hsl(0 0% 98%); - --bp-muted: hsl(240 5% 64.9%); - --bp-border: hsl(240 3.7% 17%); - --bp-accent: hsl(240 3.7% 13%); - --bp-track: hsl(240 3.7% 28%); - --bp-green: hsl(142 71% 45%); - --bp-yellow: hsl(38 92% 50%); - --bp-red: hsl(0 84% 60%); - } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/css/tooltip.ts b/ai/perplexity/src/ui/css/tooltip.ts deleted file mode 100644 index 7e96384..0000000 --- a/ai/perplexity/src/ui/css/tooltip.ts +++ /dev/null @@ -1,30 +0,0 @@ -export const TOOLTIP_CSS = ` -.bp-tooltip { - position: fixed; - inset: auto; - width: max-content; - max-width: min(300px, calc(100vw - 16px)); - margin: 0; - padding: 0; - overflow: visible; - border: 1px solid var(--bp-border); - border-radius: 12px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 12px 32px rgb(0 0 0 / 22%); - font: inherit; - font-size: 12px; - line-height: 1.5; - pointer-events: none; -} - -.bp-tooltip:popover-open { animation: bp-tooltip-in 120ms ease-out; } -.bp-tooltip *, .bp-tooltip *::before, .bp-tooltip *::after { box-sizing: border-box; } -.bp-tooltip-body { padding: 12px 14px; } - -@keyframes bp-tooltip-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } } - -@media (prefers-reduced-motion: reduce) { - .bp-tooltip:popover-open { animation: none; } -} -` \ No newline at end of file diff --git a/ai/perplexity/src/ui/icons.ts b/ai/perplexity/src/ui/icons.ts deleted file mode 100644 index 7fa686a..0000000 --- a/ai/perplexity/src/ui/icons.ts +++ /dev/null @@ -1,33 +0,0 @@ -type Shape = readonly [tag: string, attributes: Readonly>] - -const ICONS = { - copy: [['rect', { x: '9', y: '9', width: '13', height: '13', rx: '2' }], ['path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }]], - check: [['polyline', { points: '20 6 9 17 4 12' }]], - download: [['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }], ['polyline', { points: '7 10 12 15 17 10' }], ['line', { x1: '12', y1: '15', x2: '12', y2: '3' }]], - wrap: [['line', { x1: '3', y1: '6', x2: '21', y2: '6' }], ['path', { d: 'M3 12h15a3 3 0 1 1 0 6h-4' }], ['polyline', { points: '16 16 14 18 16 20' }], ['line', { x1: '3', y1: '18', x2: '10', y2: '18' }]], - lines: [['line', { x1: '10', y1: '6', x2: '21', y2: '6' }], ['line', { x1: '10', y1: '12', x2: '21', y2: '12' }], ['line', { x1: '10', y1: '18', x2: '21', y2: '18' }], ['path', { d: 'M4 6h1v4' }], ['path', { d: 'M4 10h2' }], ['path', { d: 'M6 18H4c0-1 2-2 2-3s-1-1.5-2-1' }]], - fold: [['polyline', { points: '7 20 12 15 17 20' }], ['polyline', { points: '7 4 12 9 17 4' }]], - file: [['path', { d: 'M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z' }], ['polyline', { points: '14 2 14 8 20 8' }], ['line', { x1: '16', y1: '13', x2: '8', y2: '13' }], ['line', { x1: '16', y1: '17', x2: '8', y2: '17' }]], - sliders: [['line', { x1: '21', y1: '4', x2: '14', y2: '4' }], ['line', { x1: '10', y1: '4', x2: '3', y2: '4' }], ['line', { x1: '21', y1: '12', x2: '12', y2: '12' }], ['line', { x1: '8', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '21', y1: '20', x2: '16', y2: '20' }], ['line', { x1: '12', y1: '20', x2: '3', y2: '20' }], ['line', { x1: '14', y1: '2', x2: '14', y2: '6' }], ['line', { x1: '8', y1: '10', x2: '8', y2: '14' }], ['line', { x1: '16', y1: '18', x2: '16', y2: '22' }]], - book: [['path', { d: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20' }]], - layers: [['polygon', { points: '12 2 2 7 12 12 22 7 12 2' }], ['polyline', { points: '2 17 12 22 22 17' }], ['polyline', { points: '2 12 12 17 22 12' }]], - help: [['circle', { cx: '12', cy: '12', r: '10' }], ['path', { d: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3' }], ['line', { x1: '12', y1: '17', x2: '12.01', y2: '17' }]], - clock: [['circle', { cx: '12', cy: '12', r: '10' }], ['polyline', { points: '12 6 12 12 16 14' }]], - queue: [['line', { x1: '11', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '16', y1: '6', x2: '3', y2: '6' }], ['line', { x1: '16', y1: '18', x2: '3', y2: '18' }], ['line', { x1: '18', y1: '9', x2: '18', y2: '15' }], ['line', { x1: '21', y1: '12', x2: '15', y2: '12' }]], -} as const satisfies Record - -export type IconName = keyof typeof ICONS - -const NS = 'http://www.w3.org/2000/svg' - -export const createIcon = (name: IconName, size = 16): SVGSVGElement => { - const svg = document.createElementNS(NS, 'svg') - const attributes = { width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' } - for (const [key, value] of Object.entries(attributes)) svg.setAttribute(key, value) - for (const [tag, props] of ICONS[name] as readonly Shape[]) { - const element = document.createElementNS(NS, tag) - for (const [key, value] of Object.entries(props)) element.setAttribute(key, value) - svg.appendChild(element) - } - return svg -} diff --git a/ai/perplexity/src/ui/styles.ts b/ai/perplexity/src/ui/styles.ts deleted file mode 100644 index eaf1972..0000000 --- a/ai/perplexity/src/ui/styles.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { injectStyle } from '@nolly/core' -import { CONTROLS_CSS } from './css/controls' -import { DIALOG_CSS } from './css/dialog' -import { THEME_CSS } from './css/theme' -import { TOOLTIP_CSS } from './css/tooltip' - -export const ensureUiStyles = (): void => { - injectStyle('better-perplexity-ui-base', [THEME_CSS, DIALOG_CSS, CONTROLS_CSS, TOOLTIP_CSS].join('\n')) -} \ No newline at end of file diff --git a/core/CHANGELOG.md b/core/CHANGELOG.md index ac8eb42..c606160 100644 --- a/core/CHANGELOG.md +++ b/core/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [Unreleased] + +- `repoUrls` accepts an optional `dir` for scripts that live in a nested folder. + ## 1.0.2 ### Added diff --git a/core/README.md b/core/README.md index 28483ea..5db9df4 100644 --- a/core/README.md +++ b/core/README.md @@ -12,8 +12,11 @@ Shared runtime, utilities and build tooling for every userscript in this reposit This is a library. It is bundled into each userscript and is not installed on its own. ## Quick start + ```sh bun scripts/new-userscript.ts my-script "My Script" ``` +Pass a third argument to create it inside a parent folder, for example `ai`. + Then read [Getting started](getting-started/) and the [API reference](api/). diff --git a/core/ai/CHANGELOG.md b/core/ai/CHANGELOG.md new file mode 100644 index 0000000..84f0b8a --- /dev/null +++ b/core/ai/CHANGELOG.md @@ -0,0 +1,6 @@ +# Changelog + +## [0.1.0] - 2026-11-10 + +- Initial release: adapter contract, composer kit, generation kit, response spy and SSE parser. +- Added placeholders, tokens, selection, clipboard, download, prompt sender and the UI kit (moved from Better Perplexity). diff --git a/core/ai/README.md b/core/ai/README.md new file mode 100644 index 0000000..b816c64 --- /dev/null +++ b/core/ai/README.md @@ -0,0 +1,12 @@ +# AI Core + +Platform-agnostic building blocks for AI-chat userscripts such as Better Perplexity and Better ChatGPT. It sits on top of `@nolly/core`. + +## What you get + +- A `PlatformAdapter` contract that a site implements once. +- Composer kits: find the input, write text, send, attach files; a prompt sender built on them. +- Generation detection and a wait-for-answer helper. +- A streaming response observer and an incremental Server-Sent Events parser. +- Placeholders, token estimates, selection memory, clipboard and file download helpers. +- A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. diff --git a/core/ai/package.json b/core/ai/package.json index 529dcb0..95111e9 100644 --- a/core/ai/package.json +++ b/core/ai/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", - "userscript": { "kind": "library" }, + "userscript": { "kind": "library", "slug": "core-ai" }, "repository": { "type": "git", "url": "git+https://github.com/thenolle/userscripts.git", diff --git a/core/ai/src/adapter.ts b/core/ai/src/adapter.ts index 546eb0d..7a6131d 100644 --- a/core/ai/src/adapter.ts +++ b/core/ai/src/adapter.ts @@ -10,7 +10,6 @@ export interface ComposerAdapter { readonly rejectEditable?: (element: HTMLElement) => boolean readonly findSendButton?: (editable: HTMLElement) => HTMLElement | null readonly findStopButton?: () => HTMLElement | null - readonly findFileInput?: () => HTMLInputElement | null readonly sendWith?: 'enter' | 'button' } diff --git a/ai/perplexity/src/core/automation.ts b/core/ai/src/automation.ts similarity index 99% rename from ai/perplexity/src/core/automation.ts rename to core/ai/src/automation.ts index 498e6b7..8f7dfaa 100644 --- a/ai/perplexity/src/core/automation.ts +++ b/core/ai/src/automation.ts @@ -9,4 +9,4 @@ export const automate = async (task: () => Promise): Promise => { } finally { depth-- } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/core/clipboard.ts b/core/ai/src/clipboard.ts similarity index 99% rename from ai/perplexity/src/core/clipboard.ts rename to core/ai/src/clipboard.ts index f6942f6..3af8260 100644 --- a/ai/perplexity/src/core/clipboard.ts +++ b/core/ai/src/clipboard.ts @@ -12,4 +12,4 @@ export const copyText = async (text: string): Promise => { area.remove() return copied } -} \ No newline at end of file +} diff --git a/core/ai/src/composer.ts b/core/ai/src/composer.ts index 7fe2198..9768f94 100644 --- a/core/ai/src/composer.ts +++ b/core/ai/src/composer.ts @@ -1,6 +1,6 @@ import { sleep, toElement } from '@nolly/core' import type { ComposerAdapter } from './adapter' -import { dispatchEnter, findGenericSendButton } from './keys' +import { dispatchEnter, findSendButton } from './keys' export const EDITABLE_SELECTOR = [ 'textarea', @@ -111,7 +111,6 @@ const waitForComposer = async (editable: HTMLElement, text: string, timeout = 30 export interface ComposerKit { editableFrom(target: EventTarget | null): HTMLElement | null findComposer(): HTMLElement | null - findSend(editable: HTMLElement): HTMLElement | null writeComposer(editable: HTMLElement, text: string): Promise sendComposer(editable: HTMLElement): Promise attachFile(editable: HTMLElement, file: File): boolean @@ -138,7 +137,7 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { return candidates.at(-1) ?? null } - const findSend = (editable: HTMLElement): HTMLElement | null => (adapter.findSendButton ? adapter.findSendButton(editable) : findGenericSendButton(editable)) + const findSend = (editable: HTMLElement): HTMLElement | null => (adapter.findSendButton ? adapter.findSendButton(editable) : findSendButton(editable)) const writeComposer = async (editable: HTMLElement, text: string): Promise => { if (!editable.isConnected) return false @@ -182,7 +181,7 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { const attachFile = (editable: HTMLElement, file: File): boolean => { const transfer = new DataTransfer() transfer.items.add(file) - const input = adapter.findFileInput?.() ?? [...document.querySelectorAll('input[type="file"]')].find((candidate) => !isOwnUi(candidate) && !candidate.disabled) + const input = [...document.querySelectorAll('input[type="file"]')].find((candidate) => !isOwnUi(candidate) && !candidate.disabled) if (input) { input.files = transfer.files input.dispatchEvent(new Event('change', { bubbles: true, composed: true })) @@ -193,5 +192,5 @@ export const createComposerKit = (adapter: ComposerAdapter): ComposerKit => { return event.defaultPrevented } - return { editableFrom, findComposer, findSend, writeComposer, sendComposer, attachFile } + return { editableFrom, findComposer, writeComposer, sendComposer, attachFile } } diff --git a/ai/perplexity/src/core/download.ts b/core/ai/src/download.ts similarity index 99% rename from ai/perplexity/src/core/download.ts rename to core/ai/src/download.ts index ef0aa17..e36cd39 100644 --- a/ai/perplexity/src/core/download.ts +++ b/core/ai/src/download.ts @@ -5,4 +5,4 @@ export const saveFile = (name: string, data: BlobPart, type = 'text/plain'): voi link.download = name link.click() URL.revokeObjectURL(url) -} \ No newline at end of file +} diff --git a/core/ai/src/index.ts b/core/ai/src/index.ts index c01cd0b..de403dc 100644 --- a/core/ai/src/index.ts +++ b/core/ai/src/index.ts @@ -1,6 +1,14 @@ export * from './adapter' +export * from './automation' +export * from './clipboard' export * from './composer' +export * from './download' export * from './generation' export * from './keys' +export * from './placeholders' +export * from './prompt' export * from './response-spy' +export * from './selection' export * from './sse' +export * from './tokens' +export * from './ui' diff --git a/core/ai/src/keys.ts b/core/ai/src/keys.ts index f489fb6..2d35330 100644 --- a/core/ai/src/keys.ts +++ b/core/ai/src/keys.ts @@ -6,17 +6,17 @@ const synthetic = new WeakSet() export const isSynthetic = (event: Event): boolean => synthetic.has(event) export const dispatchEnter = (target: HTMLElement, shiftKey: boolean): boolean => { - const event = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, shiftKey, bubbles: true, cancelable: true, composed: true }) - synthetic.add(event) - return target.dispatchEvent(event) + const event = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, shiftKey, bubbles: true, cancelable: true, composed: true }) + synthetic.add(event) + return target.dispatchEvent(event) } -export const findGenericSendButton = (from: HTMLElement): HTMLButtonElement | null => { - let scope: HTMLElement | null = from - for (let depth = 0; scope && depth < MAX_SEARCH_DEPTH; depth++) { - const button = scope.querySelector(SEND_SELECTOR) - if (button && !button.disabled) return button - scope = scope.parentElement - } - return null +export const findSendButton = (from: HTMLElement): HTMLButtonElement | null => { + let scope: HTMLElement | null = from + for (let depth = 0; scope && depth < MAX_SEARCH_DEPTH; depth++) { + const button = scope.querySelector(SEND_SELECTOR) + if (button && !button.disabled) return button + scope = scope.parentElement + } + return null } diff --git a/ai/perplexity/src/core/placeholders.ts b/core/ai/src/placeholders.ts similarity index 94% rename from ai/perplexity/src/core/placeholders.ts rename to core/ai/src/placeholders.ts index 59d5cdd..75f06af 100644 --- a/ai/perplexity/src/core/placeholders.ts +++ b/core/ai/src/placeholders.ts @@ -23,4 +23,4 @@ export const findFields = (text: string, isResolved: (key: string) => boolean): return fields } -export const applyValues = (text: string, values: Readonly>): string => text.replace(TOKEN, (match, key: string) => (key in values ? (values[key] ?? '') : match)) \ No newline at end of file +export const applyValues = (text: string, values: Readonly>): string => text.replace(TOKEN, (match, key: string) => (key in values ? (values[key] ?? '') : match)) diff --git a/core/ai/src/prompt.ts b/core/ai/src/prompt.ts new file mode 100644 index 0000000..17f8247 --- /dev/null +++ b/core/ai/src/prompt.ts @@ -0,0 +1,17 @@ +import { sleep, waitFor } from '@nolly/core' +import { automate } from './automation' +import { readComposer } from './composer' +import type { ComposerKit } from './composer' + +export type PromptSender = (prompt: string, signal?: AbortSignal) => Promise + +export const createPromptSender = ({ findComposer, writeComposer, sendComposer }: Pick): PromptSender => (prompt, signal) => automate(async () => { + for (let attempt = 0; attempt < 2; attempt++) { + const composer = await waitFor(findComposer, { timeout: 15_000, signal }) + if (!composer) return false + if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true + if (readComposer(composer).trim() === '') return true + await sleep(1_500, signal) + } + return false +}) diff --git a/ai/perplexity/src/core/selection.ts b/core/ai/src/selection.ts similarity index 84% rename from ai/perplexity/src/core/selection.ts rename to core/ai/src/selection.ts index 79e2d36..fdaacce 100644 --- a/ai/perplexity/src/core/selection.ts +++ b/core/ai/src/selection.ts @@ -4,4 +4,4 @@ export const rememberSelection = (text: string): void => { if (text.trim()) recent = text } -export const currentSelection = (): string => window.getSelection()?.toString().trim() || recent \ No newline at end of file +export const currentSelection = (): string => window.getSelection()?.toString().trim() || recent diff --git a/ai/perplexity/src/core/tokens.ts b/core/ai/src/tokens.ts similarity index 99% rename from ai/perplexity/src/core/tokens.ts rename to core/ai/src/tokens.ts index bebb013..5c5ba67 100644 --- a/ai/perplexity/src/core/tokens.ts +++ b/core/ai/src/tokens.ts @@ -10,4 +10,4 @@ export const estimateTokens = (text: string, asCode = false): number => { }) const wide = prose.match(WIDE)?.length ?? 0 return Math.ceil((prose.length - wide) / 4 + wide + code / 3.2) -} \ No newline at end of file +} diff --git a/ai/perplexity/src/ui/composer-button.ts b/core/ai/src/ui/composer-button.ts similarity index 89% rename from ai/perplexity/src/ui/composer-button.ts rename to core/ai/src/ui/composer-button.ts index 141e8c3..7417ad1 100644 --- a/ai/perplexity/src/ui/composer-button.ts +++ b/core/ai/src/ui/composer-button.ts @@ -1,6 +1,6 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' -import { findComposerActions } from '../locate' +import { markUi, uiConfig } from './config' +import type { ComposerActions } from './config' import { createIcon, type IconName } from './icons' import { ensureUiStyles } from './styles' import { Tooltip } from './tooltip' @@ -11,6 +11,7 @@ export interface ComposerButtonOptions { } const CONFIG_BUTTON = '.bp-config-button' +const NO_ACTIONS: ComposerActions = { first: null, submit: null } export class ComposerButton { readonly element = markUi(createElement('button')) @@ -32,7 +33,7 @@ export class ComposerButton { } mount(): void { - const { first, submit } = findComposerActions() + const { first, submit } = uiConfig().composerActions?.() ?? NO_ACTIONS const chained = (this.options.after ?? []).map((id) => document.querySelector(`.bp-cb-${id}`)).find(Boolean) const anchor = chained ?? document.querySelector(CONFIG_BUTTON) ?? first if (!anchor && !submit) { diff --git a/core/ai/src/ui/config.ts b/core/ai/src/ui/config.ts new file mode 100644 index 0000000..0e3cb3f --- /dev/null +++ b/core/ai/src/ui/config.ts @@ -0,0 +1,29 @@ +import type { createUiMarker } from '@nolly/core' + +export type UiMarker = ReturnType + +export interface ComposerActions { + readonly first: HTMLElement | null + readonly submit: HTMLElement | null +} + +export interface UiConfig { + readonly id: string + readonly title: string + readonly version: string + readonly marker: UiMarker + readonly composerActions?: () => ComposerActions +} + +let current: UiConfig | null = null + +export const configureUi = (config: UiConfig): void => { + current = config +} + +export const uiConfig = (): UiConfig => { + if (!current) throw new Error('configureUi() must run before any UI is created.') + return current +} + +export const markUi: UiMarker['mark'] = (element) => uiConfig().marker.mark(element) diff --git a/core/ai/src/ui/controls.ts b/core/ai/src/ui/controls.ts new file mode 100644 index 0000000..5a74988 --- /dev/null +++ b/core/ai/src/ui/controls.ts @@ -0,0 +1,104 @@ +import { createElement } from '@nolly/core' + +export interface ButtonOptions { + primary?: boolean + onClick?: (event: MouseEvent) => void +} + +export interface SwitchOptions { + label: string + hint?: string + checked: boolean + onChange: (checked: boolean) => void +} + +export interface NumberFieldOptions { + label: string + hint?: string + value: number + min?: number + max?: number + step?: number + onChange: (value: number) => void +} + +export const createButton = (label: string, { primary = false, onClick }: ButtonOptions = {}): HTMLButtonElement => { + const button = createElement('button', primary ? 'bp-button bp-button-primary' : 'bp-button', label) + button.type = 'button' + if (onClick) button.addEventListener('click', onClick) + return button +} + +export const createSwitch = ({ label, hint, checked, onChange }: SwitchOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { + const wrapper = createElement('label', 'bp-switch') + const text = createElement('span', 'bp-switch-text') + text.appendChild(createElement('span', undefined, label)) + if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) + const input = createElement('input') + input.type = 'checkbox' + input.checked = checked + input.addEventListener('change', () => onChange(input.checked)) + wrapper.append(text, input, createElement('span', 'bp-switch-track')) + return { wrapper, input } +} + +export const createSection = (title: string, aside?: string): HTMLElement => { + const section = createElement('section', 'bp-section') + const heading = createElement('h3', 'bp-section-heading') + heading.appendChild(createElement('span', undefined, title)) + if (aside !== undefined) heading.appendChild(createElement('span', undefined, aside)) + section.appendChild(heading) + return section +} + +export const createDataRow = (label: string, value: string, className = ''): HTMLElement => { + const row = createElement('div', 'bp-data-row') + row.append(createElement('span', 'bp-data-label', label), createElement('span', `bp-data-value ${className}`.trim(), value)) + return row +} + +export const createNumberField = ({ label, hint, value, min, max, step = 1, onChange }: NumberFieldOptions): { wrapper: HTMLLabelElement; input: HTMLInputElement } => { + const wrapper = createElement('label', 'bp-field') + const text = createElement('span', 'bp-switch-text') + text.appendChild(createElement('span', undefined, label)) + if (hint) text.appendChild(createElement('span', 'bp-data-label', hint)) + const input = createElement('input', 'bp-input') + input.type = 'number' + input.value = String(value) + input.step = String(step) + if (min !== undefined) input.min = String(min) + if (max !== undefined) input.max = String(max) + input.addEventListener('change', () => { + const parsed = Number(input.value) + if (!Number.isFinite(parsed)) return + const clamped = Math.min(max ?? Infinity, Math.max(min ?? -Infinity, parsed)) + input.value = String(clamped) + onChange(clamped) + }) + wrapper.append(text, input) + return { wrapper, input } +} + +export const createSelectField = (label: string, options: readonly { value: T; label: string }[], value: T, onChange: (value: T) => void): HTMLLabelElement => { + const wrapper = createElement('label', 'bp-field') + wrapper.appendChild(createElement('span', undefined, label)) + const select = createElement('select', 'bp-input') + for (const option of options) { + const element = createElement('option', undefined, option.label) + element.value = option.value + select.appendChild(element) + } + select.value = value + select.addEventListener('change', () => onChange(select.value as T)) + wrapper.appendChild(select) + return wrapper +} + +export const createTextArea = (placeholder: string, value: string, onInput: (value: string) => void): HTMLTextAreaElement => { + const area = createElement('textarea', 'bp-input') + area.placeholder = placeholder + area.value = value + area.rows = 3 + area.addEventListener('input', () => onInput(area.value)) + return area +} diff --git a/ai/perplexity/src/ui/css/controls.ts b/core/ai/src/ui/css.ts similarity index 58% rename from ai/perplexity/src/ui/css/controls.ts rename to core/ai/src/ui/css.ts index a2a66a0..290c9b7 100644 --- a/ai/perplexity/src/ui/css/controls.ts +++ b/core/ai/src/ui/css.ts @@ -1,3 +1,108 @@ +export const THEME_CSS = ` +.bp-themed { + --bp-bg: hsl(0 0% 100%); + --bp-fg: hsl(240 10% 3.9%); + --bp-muted: hsl(240 3.8% 46.1%); + --bp-border: hsl(240 5.9% 90%); + --bp-accent: hsl(240 4.8% 95.9%); + --bp-track: hsl(240 5% 78%); + --bp-ring: hsl(240 5% 64.9%); + --bp-green: hsl(142 71% 40%); + --bp-yellow: hsl(38 92% 45%); + --bp-red: hsl(0 84% 55%); +} + +@media (prefers-color-scheme: dark) { + .bp-themed { + --bp-bg: hsl(240 10% 5%); + --bp-fg: hsl(0 0% 98%); + --bp-muted: hsl(240 5% 64.9%); + --bp-border: hsl(240 3.7% 17%); + --bp-accent: hsl(240 3.7% 13%); + --bp-track: hsl(240 3.7% 28%); + --bp-green: hsl(142 71% 45%); + --bp-yellow: hsl(38 92% 50%); + --bp-red: hsl(0 84% 60%); + } +} +` + +export const DIALOG_CSS = ` +.bp-dialog { + width: min(var(--bp-width, 560px), calc(100vw - 32px)); + max-width: none; + max-height: min(86vh, 820px); + padding: 0; + overflow: hidden; + border: 1px solid var(--bp-border); + border-radius: 14px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 24px 60px -12px rgb(0 0 0 / 35%); + font-family: inherit; + font-size: 13px; + line-height: 1.5; +} + +.bp-dialog[open] { display: flex; flex-direction: column; animation: bp-dialog-in 160ms ease-out; } +.bp-dialog::backdrop { background: rgb(0 0 0 / 55%); backdrop-filter: blur(6px); animation: bp-fade-in 160ms ease-out; } +.bp-dialog *, .bp-dialog *::before, .bp-dialog *::after { box-sizing: border-box; } + +@keyframes bp-dialog-in { from { opacity: 0; transform: translateY(8px) scale(.98); } to { opacity: 1; transform: none; } } +@keyframes bp-fade-in { from { opacity: 0; } to { opacity: 1; } } + +@media (prefers-reduced-motion: reduce) { + .bp-dialog[open], .bp-dialog::backdrop { animation: none; } +} + +.bp-dialog-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + padding: 18px 20px 14px; + border-bottom: 1px solid var(--bp-border); +} + +.bp-dialog-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: -.02em; } +.bp-dialog-description { margin: 3px 0 0; color: var(--bp-muted); font-size: 12px; } +.bp-dialog-body { flex: 1; min-height: 0; padding: 16px 20px; overflow-y: auto; overscroll-behavior: contain; } + +.bp-dialog-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding: 12px 20px; + border-top: 1px solid var(--bp-border); +} + +.bp-dialog-footer:empty { display: none; } + +.bp-icon-button { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 28px; + height: 28px; + border: 0; + border-radius: 7px; + background: transparent; + color: var(--bp-muted); + font: inherit; + font-size: 18px; + line-height: 1; + cursor: pointer; +} + +.bp-icon-button:hover { background: var(--bp-accent); color: var(--bp-fg); } + +@media (max-width: 520px) { + .bp-dialog-header, .bp-dialog-body, .bp-dialog-footer { padding-right: 14px; padding-left: 14px; } +} +` + export const CONTROLS_CSS = ` .bp-button { display: inline-flex; @@ -179,4 +284,35 @@ textarea.bp-input { width: 100%; min-height: 64px; resize: vertical; font-family .bp-header-btn:hover { background: var(--bp-accent); } .bp-header-btn:focus-visible { outline: 2px solid var(--bp-fg); outline-offset: 2px; } -` \ No newline at end of file +` + +export const TOOLTIP_CSS = ` +.bp-tooltip { + position: fixed; + inset: auto; + width: max-content; + max-width: min(300px, calc(100vw - 16px)); + margin: 0; + padding: 0; + overflow: visible; + border: 1px solid var(--bp-border); + border-radius: 12px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 12px 32px rgb(0 0 0 / 22%); + font: inherit; + font-size: 12px; + line-height: 1.5; + pointer-events: none; +} + +.bp-tooltip:popover-open { animation: bp-tooltip-in 120ms ease-out; } +.bp-tooltip *, .bp-tooltip *::before, .bp-tooltip *::after { box-sizing: border-box; } +.bp-tooltip-body { padding: 12px 14px; } + +@keyframes bp-tooltip-in { from { opacity: 0; transform: translateY(3px); } to { opacity: 1; transform: none; } } + +@media (prefers-reduced-motion: reduce) { + .bp-tooltip:popover-open { animation: none; } +} +` diff --git a/ai/perplexity/src/ui/dialog.ts b/core/ai/src/ui/dialog.ts similarity index 97% rename from ai/perplexity/src/ui/dialog.ts rename to core/ai/src/ui/dialog.ts index 5889478..33f1ee5 100644 --- a/ai/perplexity/src/ui/dialog.ts +++ b/core/ai/src/ui/dialog.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi } from './config' import { ensureUiStyles } from './styles' export interface DialogOptions { @@ -44,4 +44,4 @@ export const createDialog = ({ id, title, description, width = 560 }: DialogOpti dialog.showModal() } return { dialog, body, footer, close, show } -} \ No newline at end of file +} diff --git a/core/ai/src/ui/icons.ts b/core/ai/src/ui/icons.ts new file mode 100644 index 0000000..9c15751 --- /dev/null +++ b/core/ai/src/ui/icons.ts @@ -0,0 +1,33 @@ +type Shape = readonly [tag: string, attributes: Readonly>] + +const ICONS = { + copy: [['rect', { x: '9', y: '9', width: '13', height: '13', rx: '2' }], ['path', { d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1' }]], + check: [['polyline', { points: '20 6 9 17 4 12' }]], + download: [['path', { d: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4' }], ['polyline', { points: '7 10 12 15 17 10' }], ['line', { x1: '12', y1: '15', x2: '12', y2: '3' }]], + wrap: [['line', { x1: '3', y1: '6', x2: '21', y2: '6' }], ['path', { d: 'M3 12h15a3 3 0 1 1 0 6h-4' }], ['polyline', { points: '16 16 14 18 16 20' }], ['line', { x1: '3', y1: '18', x2: '10', y2: '18' }]], + lines: [['line', { x1: '10', y1: '6', x2: '21', y2: '6' }], ['line', { x1: '10', y1: '12', x2: '21', y2: '12' }], ['line', { x1: '10', y1: '18', x2: '21', y2: '18' }], ['path', { d: 'M4 6h1v4' }], ['path', { d: 'M4 10h2' }], ['path', { d: 'M6 18H4c0-1 2-2 2-3s-1-1.5-2-1' }]], + fold: [['polyline', { points: '7 20 12 15 17 20' }], ['polyline', { points: '7 4 12 9 17 4' }]], + file: [['path', { d: 'M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z' }], ['polyline', { points: '14 2 14 8 20 8' }], ['line', { x1: '16', y1: '13', x2: '8', y2: '13' }], ['line', { x1: '16', y1: '17', x2: '8', y2: '17' }]], + sliders: [['line', { x1: '21', y1: '4', x2: '14', y2: '4' }], ['line', { x1: '10', y1: '4', x2: '3', y2: '4' }], ['line', { x1: '21', y1: '12', x2: '12', y2: '12' }], ['line', { x1: '8', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '21', y1: '20', x2: '16', y2: '20' }], ['line', { x1: '12', y1: '20', x2: '3', y2: '20' }], ['line', { x1: '14', y1: '2', x2: '14', y2: '6' }], ['line', { x1: '8', y1: '10', x2: '8', y2: '14' }], ['line', { x1: '16', y1: '18', x2: '16', y2: '22' }]], + book: [['path', { d: 'M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20' }]], + layers: [['polygon', { points: '12 2 2 7 12 12 22 7 12 2' }], ['polyline', { points: '2 17 12 22 22 17' }], ['polyline', { points: '2 12 12 17 22 12' }]], + help: [['circle', { cx: '12', cy: '12', r: '10' }], ['path', { d: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3' }], ['line', { x1: '12', y1: '17', x2: '12.01', y2: '17' }]], + clock: [['circle', { cx: '12', cy: '12', r: '10' }], ['polyline', { points: '12 6 12 12 16 14' }]], + queue: [['line', { x1: '11', y1: '12', x2: '3', y2: '12' }], ['line', { x1: '16', y1: '6', x2: '3', y2: '6' }], ['line', { x1: '16', y1: '18', x2: '3', y2: '18' }], ['line', { x1: '18', y1: '9', x2: '18', y2: '15' }], ['line', { x1: '21', y1: '12', x2: '15', y2: '12' }]] +} as const satisfies Record + +export type IconName = keyof typeof ICONS + +const NS = 'http://www.w3.org/2000/svg' + +export const createIcon = (name: IconName, size = 16): SVGSVGElement => { + const svg = document.createElementNS(NS, 'svg') + const attributes = { width: String(size), height: String(size), viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' } + for (const [key, value] of Object.entries(attributes)) svg.setAttribute(key, value) + for (const [tag, props] of ICONS[name] as readonly Shape[]) { + const element = document.createElementNS(NS, tag) + for (const [key, value] of Object.entries(props)) element.setAttribute(key, value) + svg.appendChild(element) + } + return svg +} diff --git a/core/ai/src/ui/index.ts b/core/ai/src/ui/index.ts new file mode 100644 index 0000000..3031e7d --- /dev/null +++ b/core/ai/src/ui/index.ts @@ -0,0 +1,11 @@ +export * from './composer-button' +export * from './config' +export * from './controls' +export * from './css' +export * from './dialog' +export * from './icons' +export * from './placeholder-dialog' +export * from './settings-dialog' +export * from './styles' +export * from './toast' +export * from './tooltip' diff --git a/ai/perplexity/src/ui/placeholder-dialog.ts b/core/ai/src/ui/placeholder-dialog.ts similarity index 88% rename from ai/perplexity/src/ui/placeholder-dialog.ts rename to core/ai/src/ui/placeholder-dialog.ts index 089ec59..40c3def 100644 --- a/ai/perplexity/src/ui/placeholder-dialog.ts +++ b/core/ai/src/ui/placeholder-dialog.ts @@ -1,10 +1,9 @@ -import type { Field } from '../core/placeholders' import { createElement } from '@nolly/core' +import type { Field } from '../placeholders' +import { uiConfig } from './config' import { createButton } from './controls' import { createDialog } from './dialog' -const DIALOG_ID = 'better-perplexity-fields-dialog' - export interface AskOptions { title: string description: string @@ -12,8 +11,9 @@ export interface AskOptions { } export const askFields = (fields: readonly Field[], { title, description, confirm = 'Continue' }: AskOptions): Promise | null> => new Promise((resolve) => { - document.getElementById(DIALOG_ID)?.remove() - const ui = createDialog({ id: DIALOG_ID, title, description, width: 540 }) + const dialogId = `${uiConfig().id}-fields-dialog` + document.getElementById(dialogId)?.remove() + const ui = createDialog({ id: dialogId, title, description, width: 540 }) const values: Record = Object.fromEntries(fields.map((field) => [field.key, field.value ?? ''])) let settled = false const finish = (result: Record | null): void => { @@ -51,4 +51,4 @@ export const askFields = (fields: readonly Field[], { title, description, confir ui.footer.append(createButton('Cancel', { onClick: ui.close }), createButton(confirm, { primary: true, onClick: submit })) ui.show() first?.focus() -}) \ No newline at end of file +}) diff --git a/ai/perplexity/src/ui/settings-dialog.ts b/core/ai/src/ui/settings-dialog.ts similarity index 82% rename from ai/perplexity/src/ui/settings-dialog.ts rename to core/ai/src/ui/settings-dialog.ts index e0f7e1e..175bba3 100644 --- a/ai/perplexity/src/ui/settings-dialog.ts +++ b/core/ai/src/ui/settings-dialog.ts @@ -1,16 +1,17 @@ import { createElement, type Feature } from '@nolly/core' +import { uiConfig } from './config' import { createButton, createSection, createSwitch } from './controls' import { createDialog } from './dialog' -const DIALOG_ID = 'better-perplexity-settings-dialog' - export const toggleSettingsDialog = (modules: readonly Feature[], onChange: () => void): void => { - const existing = document.getElementById(DIALOG_ID) + const { id, title, version } = uiConfig() + const dialogId = `${id}-settings-dialog` + const existing = document.getElementById(dialogId) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Better Perplexity', description: `Version ${__VERSION__}`, width: 480 }) + const ui = createDialog({ id: dialogId, title, description: `Version ${version}`, width: 480 }) const render = (): void => { const sections = modules.map((module) => { const section = createSection(module.name) @@ -43,4 +44,4 @@ export const toggleSettingsDialog = (modules: readonly Feature[], onChange: () = render() ui.footer.append(createButton('Done', { primary: true, onClick: ui.close })) ui.show() -} \ No newline at end of file +} diff --git a/core/ai/src/ui/styles.ts b/core/ai/src/ui/styles.ts new file mode 100644 index 0000000..fbca7f8 --- /dev/null +++ b/core/ai/src/ui/styles.ts @@ -0,0 +1,7 @@ +import { injectStyle } from '@nolly/core' +import { uiConfig } from './config' +import { CONTROLS_CSS, DIALOG_CSS, THEME_CSS, TOOLTIP_CSS } from './css' + +export const ensureUiStyles = (): void => { + injectStyle(`${uiConfig().id}-ui-base`, [THEME_CSS, DIALOG_CSS, CONTROLS_CSS, TOOLTIP_CSS].join('\n')) +} diff --git a/ai/perplexity/src/ui/toast.ts b/core/ai/src/ui/toast.ts similarity index 86% rename from ai/perplexity/src/ui/toast.ts rename to core/ai/src/ui/toast.ts index 49dcef0..303cd9e 100644 --- a/ai/perplexity/src/ui/toast.ts +++ b/core/ai/src/ui/toast.ts @@ -1,5 +1,5 @@ import { createElement, injectStyle } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi, uiConfig } from './config' import { createButton } from './controls' import { ensureUiStyles } from './styles' @@ -17,7 +17,7 @@ const CSS = ` export const showToast = (message: string, actions: readonly ToastAction[] = [], duration = 8_000): (() => void) => { ensureUiStyles() - injectStyle('better-perplexity-toast-styles', CSS) + injectStyle(`${uiConfig().id}-toast-styles`, CSS) const toast = markUi(createElement('div', 'bp-toast bp-themed')) const dismiss = (): void => toast.remove() toast.appendChild(createElement('div', undefined, message)) @@ -27,10 +27,10 @@ export const showToast = (message: string, actions: readonly ToastAction[] = [], row.appendChild( createButton(action.label, { primary: action.primary, - onClick: () => { - if (!action.keepOpen) dismiss() - action.onClick() - } + onClick: () => { + if (!action.keepOpen) dismiss() + action.onClick() + } }) ) } diff --git a/ai/perplexity/src/ui/tooltip.ts b/core/ai/src/ui/tooltip.ts similarity index 99% rename from ai/perplexity/src/ui/tooltip.ts rename to core/ai/src/ui/tooltip.ts index 8311bfc..f9a2d30 100644 --- a/ai/perplexity/src/ui/tooltip.ts +++ b/core/ai/src/ui/tooltip.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { markUi } from '../core/dom' +import { markUi } from './config' import { ensureUiStyles } from './styles' export type TooltipRenderer = (container: HTMLElement) => void @@ -119,4 +119,4 @@ export class Tooltip { this.element.style.left = `${Math.round(left)}px` this.element.style.top = `${Math.round(top)}px` } -} \ No newline at end of file +} diff --git a/core/docs/getting-started.md b/core/docs/getting-started.md index cc21944..6ccaa08 100644 --- a/core/docs/getting-started.md +++ b/core/docs/getting-started.md @@ -15,6 +15,8 @@ cd my-script bun run dev ``` +Pass a third argument to create it inside a parent folder, for example `ai`. The `cd` command goes to the created folder. + ## A feature ```ts import { Feature } from '@nolly/core' diff --git a/scripts/new-userscript.ts b/scripts/new-userscript.ts index 2e54892..6ce5e6f 100644 --- a/scripts/new-userscript.ts +++ b/scripts/new-userscript.ts @@ -2,57 +2,62 @@ import { existsSync } from 'node:fs' import { mkdir, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' -const [slug, name] = process.argv.slice(2) +const [slug, name, parent = ''] = process.argv.slice(2) if (!slug || !name || !/^[a-z0-9-]+$/.test(slug)) { - console.error('Usage: bun scripts/new-userscript.ts ""') - process.exit(1) + console.error('Usage: bun scripts/new-userscript.ts "" [parent-folder]') + process.exit(1) } -if (existsSync(slug)) { - console.error(`${slug}/ already exists.`) - process.exit(1) + +const dir = parent ? `${parent}/${slug}` : slug +const up = '../'.repeat(dir.split('/').length) + +if (existsSync(dir)) { + console.error(`${dir}/ already exists.`) + process.exit(1) } const files: Record = { - 'package.json': JSON.stringify({ - name: slug, - version: '0.1.0', - private: true, - type: 'module', - license: 'PolyForm-Strict-1.0.0', - repository: { type: 'git', url: 'git+https://github.com/thenolle/userscripts.git', directory: slug }, - scripts: { build: 'bun run scripts/build.ts', dev: 'bun run scripts/build.ts --watch', typecheck: 'tsc --noEmit' }, - dependencies: { '@nolly/core': 'workspace:*' }, - devDependencies: { '@types/bun': '^1.4.4', typescript: '^7.0.2' } - }, null, 2), - 'tsconfig.json': JSON.stringify({ - compilerOptions: { - lib: ['ESNext', 'DOM', 'DOM.Iterable'], types: ['bun'], module: 'preserve', target: 'esnext', moduleResolution: 'bundler', - verbatimModuleSyntax: true, isolatedModules: true, noEmit: true, strict: true, noImplicitOverride: true, skipLibCheck: true, - noUnusedLocals: true, noUnusedParameters: true, noPropertyAccessFromIndexSignature: true - }, - include: ['src', 'scripts', '../core/src/globals.d.ts'] - }, null, 2), - 'README.md': `# ${name}\n\nDescribe what ${name} does in one paragraph.\n\n## Install\n\nInstall from the project website once the first release is published.\n`, - 'CHANGELOG.md': `# Changelog\n\n## 0.1.0\n\n- Initial release.\n`, - 'docs/getting-started.md': `---\ntitle: Getting started\ndescription: Install ${name} and get going.\nsection: Guides\norder: 10\n---\n\n# Getting started\n\nWrite your guide here.\n`, - 'src/types/globals.d.ts': 'declare const __VERSION__: string\n', - 'src/repo.ts': `import { repoUrls } from '@nolly/core'\n\nexport const SLUG = '${slug}'\n\nexport const URLS = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG })\n`, - 'src/main.ts': `import { Userscript } from '@nolly/core'\nimport { Hello } from './features/hello'\n\nnew Userscript({ id: '${slug}', name: '${name}', version: __VERSION__ })\n .register((context) => new Hello(context))\n .start()\n`, - 'src/features/hello.ts': `import { Feature } from '@nolly/core'\n\nexport class Hello extends Feature {\n readonly id = 'hello'\n readonly name = 'Hello'\n readonly description = 'Example feature.'\n\n override onEnable(): void {\n this.context.logger.info('Hello enabled.')\n }\n\n run(): void {}\n}\n`, - 'scripts/header.ts': `import { createHeader as render } from '@nolly/core/build'\nimport { URLS } from '../src/repo'\n\nexport const createHeader = ({ version }: { version: string }): string =>\n render({\n name: '${name}',\n namespace: URLS.namespace,\n version,\n description: 'Describe ${name}.',\n author: 'Nolly',\n license: 'PolyForm-Strict-1.0.0',\n homepageURL: URLS.home,\n supportURL: URLS.issues,\n updateURL: URLS.meta,\n downloadURL: URLS.install,\n icon: 'https://www.google.com/s2/favicons?sz=64&domain=example.com',\n match: ['https://example.com/*'],\n noframes: true,\n grant: ['GM_getValue', 'GM_setValue', 'GM_deleteValue', 'GM_registerMenuCommand', 'GM_unregisterMenuCommand', 'GM_xmlhttpRequest', 'unsafeWindow']\n })\n`, - 'scripts/build.ts': `import { buildUserscript } from '@nolly/core/build'\nimport pkg from '../package.json' with { type: 'json' }\nimport { SLUG } from '../src/repo'\nimport { createHeader } from './header'\n\nawait buildUserscript({ slug: SLUG, version: pkg.version, header: createHeader({ version: pkg.version }) })\n` + 'package.json': JSON.stringify({ + name: slug, + version: '0.1.0', + private: true, + type: 'module', + license: 'PolyForm-Strict-1.0.0', + userscript: { slug }, + repository: { type: 'git', url: 'git+https://github.com/thenolle/userscripts.git', directory: dir }, + scripts: { build: 'bun run scripts/build.ts', dev: 'bun run scripts/build.ts --watch', typecheck: 'tsc --noEmit' }, + dependencies: { '@nolly/core': 'workspace:*' }, + devDependencies: { '@types/bun': '^1.4.4', typescript: '^7.0.2' } + }, null, 2), + 'tsconfig.json': JSON.stringify({ + compilerOptions: { + lib: ['ESNext', 'DOM', 'DOM.Iterable'], types: ['bun'], module: 'preserve', target: 'esnext', moduleResolution: 'bundler', resolveJsonModule: true, + verbatimModuleSyntax: true, isolatedModules: true, noEmit: true, strict: true, noImplicitOverride: true, skipLibCheck: true, + noUnusedLocals: true, noUnusedParameters: true, noPropertyAccessFromIndexSignature: true + }, + include: ['src', 'scripts', `${up}core/src/globals.d.ts`] + }, null, 2), + 'README.md': `# ${name}\n\nDescribe what ${name} does in one paragraph.\n\n## Install\n\nInstall from the project website once the first release is published.\n`, + 'CHANGELOG.md': `# Changelog\n\n## [0.1.0] - ${new Date().toISOString().slice(0, 10)}\n\n- Initial release.\n`, + 'docs/getting-started.md': `---\ntitle: Getting started\ndescription: Install ${name} and get going.\nsection: Guides\norder: 10\n---\n\n# Getting started\n\nWrite your guide here.\n`, + 'src/types/globals.d.ts': 'declare const __VERSION__: string\n', + 'src/repo.ts': `import { repoUrls } from '@nolly/core'\n\nexport const SLUG = '${slug}'\n\nexport const URLS = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG, dir: '${dir}' })\n`, + 'src/main.ts': `import { Userscript } from '@nolly/core'\nimport { Hello } from './features/hello'\n\nnew Userscript({ id: '${slug}', name: '${name}', version: __VERSION__ })\n .register((context) => new Hello(context))\n .start()\n`, + 'src/features/hello.ts': `import { Feature } from '@nolly/core'\n\nexport class Hello extends Feature {\n readonly id = 'hello'\n readonly name = 'Hello'\n readonly description = 'Example feature.'\n\n override onEnable(): void {\n this.context.logger.info('Hello enabled.')\n }\n\n run(): void {}\n}\n`, + 'scripts/header.ts': `import { createHeader as render } from '@nolly/core/build'\nimport { URLS } from '../src/repo'\n\nexport const createHeader = ({ version }: { version: string }): string =>\n render({\n name: '${name}',\n namespace: URLS.namespace,\n version,\n description: 'Describe ${name}.',\n author: 'Nolly',\n license: 'PolyForm-Strict-1.0.0',\n homepageURL: URLS.home,\n supportURL: URLS.issues,\n updateURL: URLS.meta,\n downloadURL: URLS.install,\n icon: 'https://www.google.com/s2/favicons?sz=64&domain=example.com',\n match: ['https://example.com/*'],\n noframes: true,\n grant: ['GM_getValue', 'GM_setValue', 'GM_deleteValue', 'GM_registerMenuCommand', 'GM_unregisterMenuCommand', 'GM_xmlhttpRequest', 'unsafeWindow']\n })\n`, + 'scripts/build.ts': `import { buildUserscript } from '@nolly/core/build'\nimport pkg from '../package.json' with { type: 'json' }\nimport { SLUG } from '../src/repo'\nimport { createHeader } from './header'\n\nawait buildUserscript({ slug: SLUG, version: pkg.version, header: createHeader({ version: pkg.version }) })\n` } for (const [path, content] of Object.entries(files)) { - const target = join(slug, path) - await mkdir(join(target, '..'), { recursive: true }) - await writeFile(target, content.endsWith('\n') ? content : `${content}\n`) + const target = join(dir, path) + await mkdir(join(target, '..'), { recursive: true }) + await writeFile(target, content.endsWith('\n') ? content : `${content}\n`) } const rootFile = JSON.parse(await readFile('package.json', 'utf8')) as { workspaces: string[] } -if (!rootFile.workspaces.includes(slug)) { - rootFile.workspaces.push(slug) - await writeFile('package.json', `${JSON.stringify(rootFile, null, 2)}\n`) +if (!rootFile.workspaces.includes(dir)) { + rootFile.workspaces.push(dir) + await writeFile('package.json', `${JSON.stringify(rootFile, null, 2)}\n`) } -console.log(`Created ${slug}/. Run: bun install && cd ${slug} && bun run dev`) +console.log(`Created ${dir}/. Run: bun install && cd ${dir} && bun run dev`) From b50f153ff922d512b768103430cf5c6b8653fde5 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:03:08 +0100 Subject: [PATCH 02/19] refactor(perplexity): merge duplicate @nolly/ai imports --- ai/perplexity/src/modules/batch-runner/dialog.ts | 3 +-- ai/perplexity/src/modules/batch-runner/index.ts | 4 +--- ai/perplexity/src/modules/batch-runner/panel.ts | 3 +-- ai/perplexity/src/modules/batch-runner/runner.ts | 3 +-- ai/perplexity/src/modules/code-blocks/block.ts | 3 +-- ai/perplexity/src/modules/code-blocks/dialog.ts | 3 +-- ai/perplexity/src/modules/command-palette/dialog.ts | 3 +-- ai/perplexity/src/modules/draft-guard/overlay.ts | 3 +-- .../src/modules/enter-as-newline/config-button.ts | 3 +-- ai/perplexity/src/modules/enter-as-newline/dialog.ts | 3 +-- ai/perplexity/src/modules/exporter/dialog.ts | 3 +-- ai/perplexity/src/modules/exporter/index.ts | 4 +--- ai/perplexity/src/modules/exporter/service.ts | 3 +-- ai/perplexity/src/modules/global-settings/dialog.ts | 3 +-- ai/perplexity/src/modules/global-settings/index.ts | 4 +--- ai/perplexity/src/modules/message-splitter/big-text.ts | 4 +--- ai/perplexity/src/modules/message-splitter/dialog.ts | 5 +---- ai/perplexity/src/modules/message-splitter/index.ts | 5 +---- ai/perplexity/src/modules/prompt-library/manager.ts | 4 +--- ai/perplexity/src/modules/prompt-library/variables.ts | 4 +--- ai/perplexity/src/modules/prompt-queue/index.ts | 4 +--- ai/perplexity/src/modules/prompt-queue/panel.ts | 4 +--- ai/perplexity/src/modules/recall/dialog.ts | 4 +--- ai/perplexity/src/modules/recall/index.ts | 7 +------ ai/perplexity/src/modules/selection-toolbar/index.ts | 5 +---- ai/perplexity/src/modules/tutorial/engine.ts | 3 +-- ai/perplexity/src/modules/tutorial/index.ts | 7 +------ ai/perplexity/src/modules/usage-status/dialog.ts | 3 +-- ai/perplexity/src/modules/usage-status/indicator.ts | 3 +-- 29 files changed, 29 insertions(+), 81 deletions(-) diff --git a/ai/perplexity/src/modules/batch-runner/dialog.ts b/ai/perplexity/src/modules/batch-runner/dialog.ts index 47b5ea3..5d53b75 100644 --- a/ai/perplexity/src/modules/batch-runner/dialog.ts +++ b/ai/perplexity/src/modules/batch-runner/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSwitch, createTextArea } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createNumberField, createSwitch, createTextArea, createDialog } from '@nolly/ai' import { parseItems, renderTemplate } from './template' const DIALOG_ID = 'better-perplexity-batch-dialog' diff --git a/ai/perplexity/src/modules/batch-runner/index.ts b/ai/perplexity/src/modules/batch-runner/index.ts index d47d5a5..1070eee 100644 --- a/ai/perplexity/src/modules/batch-runner/index.ts +++ b/ai/perplexity/src/modules/batch-runner/index.ts @@ -1,7 +1,5 @@ import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { ComposerButton } from '@nolly/ai' -import { applyValues, findFields } from '@nolly/ai' -import { askFields } from '@nolly/ai' +import { ComposerButton, applyValues, findFields, askFields } from '@nolly/ai' import { openBatchDialog, type BatchInput } from './dialog' import { renderTemplate } from './template' import { BatchPanel } from './panel' diff --git a/ai/perplexity/src/modules/batch-runner/panel.ts b/ai/perplexity/src/modules/batch-runner/panel.ts index 2ce0f3d..96daa75 100644 --- a/ai/perplexity/src/modules/batch-runner/panel.ts +++ b/ai/perplexity/src/modules/batch-runner/panel.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { createButton, ensureUiStyles } from '@nolly/ai' import type { BatchPhase, BatchResult } from './runner' const CSS_ID = 'better-perplexity-batch-styles' diff --git a/ai/perplexity/src/modules/batch-runner/runner.ts b/ai/perplexity/src/modules/batch-runner/runner.ts index 32221fa..470c499 100644 --- a/ai/perplexity/src/modules/batch-runner/runner.ts +++ b/ai/perplexity/src/modules/batch-runner/runner.ts @@ -1,6 +1,5 @@ -import { automate } from '@nolly/ai' +import { automate, readComposer } from '@nolly/ai' import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { readComposer } from '@nolly/ai' import { waitForResponse } from '../../core/generation' import { logger } from '../../core/logger' import { storage } from '../../core/storage' diff --git a/ai/perplexity/src/modules/code-blocks/block.ts b/ai/perplexity/src/modules/code-blocks/block.ts index e30fe50..de74449 100644 --- a/ai/perplexity/src/modules/code-blocks/block.ts +++ b/ai/perplexity/src/modules/code-blocks/block.ts @@ -1,7 +1,6 @@ -import { copyText } from '@nolly/ai' +import { copyText, createIcon, type IconName } from '@nolly/ai' import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon, type IconName } from '@nolly/ai' import type { BlockInfo } from './detect' import { highlightLines } from './highlight' import { languageInfo } from './languages' diff --git a/ai/perplexity/src/modules/code-blocks/dialog.ts b/ai/perplexity/src/modules/code-blocks/dialog.ts index 29e0ce3..527e224 100644 --- a/ai/perplexity/src/modules/code-blocks/dialog.ts +++ b/ai/perplexity/src/modules/code-blocks/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSelectField, createSwitch } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createNumberField, createSelectField, createSwitch, createDialog } from '@nolly/ai' import { DEFAULT_CODE_SETTINGS, type CodeBlockSettings } from './settings' const DIALOG_ID = 'better-perplexity-code-dialog' diff --git a/ai/perplexity/src/modules/command-palette/dialog.ts b/ai/perplexity/src/modules/command-palette/dialog.ts index 05963cc..dd6409f 100644 --- a/ai/perplexity/src/modules/command-palette/dialog.ts +++ b/ai/perplexity/src/modules/command-palette/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createDialog } from '@nolly/ai' import { DEFAULT_SHORTCUT, formatShortcut, shortcutFromEvent, type Shortcut } from './shortcut' import { ensurePaletteStyles } from './styles' diff --git a/ai/perplexity/src/modules/draft-guard/overlay.ts b/ai/perplexity/src/modules/draft-guard/overlay.ts index 6bc8327..de8e6b5 100644 --- a/ai/perplexity/src/modules/draft-guard/overlay.ts +++ b/ai/perplexity/src/modules/draft-guard/overlay.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { estimateTokens } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { estimateTokens, ensureUiStyles } from '@nolly/ai' import type { Draft } from './store' import { ensureDraftStyles } from './styles' diff --git a/ai/perplexity/src/modules/enter-as-newline/config-button.ts b/ai/perplexity/src/modules/enter-as-newline/config-button.ts index b68c0a2..a1510a0 100644 --- a/ai/perplexity/src/modules/enter-as-newline/config-button.ts +++ b/ai/perplexity/src/modules/enter-as-newline/config-button.ts @@ -1,8 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' import { findComposerActions } from '../../locate' -import { ensureUiStyles } from '@nolly/ai' -import { Tooltip } from '@nolly/ai' +import { ensureUiStyles, Tooltip } from '@nolly/ai' import { ensureConfigButtonStyles } from './styles' const SVG_NS = 'http://www.w3.org/2000/svg' diff --git a/ai/perplexity/src/modules/enter-as-newline/dialog.ts b/ai/perplexity/src/modules/enter-as-newline/dialog.ts index e1143e3..1da2a8b 100644 --- a/ai/perplexity/src/modules/enter-as-newline/dialog.ts +++ b/ai/perplexity/src/modules/enter-as-newline/dialog.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { logger } from '../../core/logger' -import { createButton, createSwitch } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createSwitch, createDialog } from '@nolly/ai' import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts, type Modifier, type ShortcutSettings } from './shortcuts' const DIALOG_ID = 'better-perplexity-enter-dialog' diff --git a/ai/perplexity/src/modules/exporter/dialog.ts b/ai/perplexity/src/modules/exporter/dialog.ts index c8f70ff..0fe5cd3 100644 --- a/ai/perplexity/src/modules/exporter/dialog.ts +++ b/ai/perplexity/src/modules/exporter/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton, createSelectField, createSwitch } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createSelectField, createSwitch, createDialog } from '@nolly/ai' import type { CitationStyle } from './citations' import { runExport } from './service' import type { ExportFormat, ExportSettings } from './settings' diff --git a/ai/perplexity/src/modules/exporter/index.ts b/ai/perplexity/src/modules/exporter/index.ts index 8feac73..ab791ac 100644 --- a/ai/perplexity/src/modules/exporter/index.ts +++ b/ai/perplexity/src/modules/exporter/index.ts @@ -1,8 +1,6 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' -import { Tooltip } from '@nolly/ai' +import { createIcon, ensureUiStyles, Tooltip } from '@nolly/ai' import { currentThreadSlug } from './api' import { toggleExportDialog } from './dialog' import { loadExportSettings, saveExportSettings, type ExportSettings } from './settings' diff --git a/ai/perplexity/src/modules/exporter/service.ts b/ai/perplexity/src/modules/exporter/service.ts index b60202a..c18ced9 100644 --- a/ai/perplexity/src/modules/exporter/service.ts +++ b/ai/perplexity/src/modules/exporter/service.ts @@ -1,5 +1,4 @@ -import { copyText } from '@nolly/ai' -import { saveFile } from '@nolly/ai' +import { copyText, saveFile } from '@nolly/ai' import { currentThreadSlug, exportThread, fetchThreadJson } from './api' import { reformatCitations, stripLogo } from './citations' import { buildDocx } from './docx' diff --git a/ai/perplexity/src/modules/global-settings/dialog.ts b/ai/perplexity/src/modules/global-settings/dialog.ts index 7982c6c..0dbdc0a 100644 --- a/ai/perplexity/src/modules/global-settings/dialog.ts +++ b/ai/perplexity/src/modules/global-settings/dialog.ts @@ -1,6 +1,5 @@ import { createElement, type ScriptContext } from '@nolly/core' -import { createButton, createSwitch } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createSwitch, createDialog } from '@nolly/ai' import { ensureGearStyles } from './styles' const DIALOG_ID = 'better-perplexity-settings-dialog' diff --git a/ai/perplexity/src/modules/global-settings/index.ts b/ai/perplexity/src/modules/global-settings/index.ts index 7f61b58..aaae2a7 100644 --- a/ai/perplexity/src/modules/global-settings/index.ts +++ b/ai/perplexity/src/modules/global-settings/index.ts @@ -1,8 +1,6 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' -import { Tooltip } from '@nolly/ai' +import { createIcon, ensureUiStyles, Tooltip } from '@nolly/ai' import { toggleGlobalSettings } from './dialog' import { ensureGearStyles } from './styles' diff --git a/ai/perplexity/src/modules/message-splitter/big-text.ts b/ai/perplexity/src/modules/message-splitter/big-text.ts index 618e8fe..4cecd34 100644 --- a/ai/perplexity/src/modules/message-splitter/big-text.ts +++ b/ai/perplexity/src/modules/message-splitter/big-text.ts @@ -1,7 +1,5 @@ import { createElement } from '@nolly/core' -import { estimateTokens } from '@nolly/ai' -import { createButton, createNumberField, createSelectField, createTextArea } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { estimateTokens, createButton, createNumberField, createSelectField, createTextArea, createDialog } from '@nolly/ai' import { createPartRows, formatNumber, type SplitChoice } from './dialog' import { planParts, type SplitPlan } from './plan' import type { SplitterSettings } from './settings' diff --git a/ai/perplexity/src/modules/message-splitter/dialog.ts b/ai/perplexity/src/modules/message-splitter/dialog.ts index 46e7ff5..3e46d5a 100644 --- a/ai/perplexity/src/modules/message-splitter/dialog.ts +++ b/ai/perplexity/src/modules/message-splitter/dialog.ts @@ -1,9 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { estimateTokens } from '@nolly/ai' -import { createButton, createNumberField, createSelectField, createSwitch, createTextArea } from '@nolly/ai' -import { createDialog } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { estimateTokens, createButton, createNumberField, createSelectField, createSwitch, createTextArea, createDialog, ensureUiStyles } from '@nolly/ai' import { planParts, type SplitPlan } from './plan' import type { PartStatus } from './runner' import type { SplitterSettings } from './settings' diff --git a/ai/perplexity/src/modules/message-splitter/index.ts b/ai/perplexity/src/modules/message-splitter/index.ts index c38934e..d55c775 100644 --- a/ai/perplexity/src/modules/message-splitter/index.ts +++ b/ai/perplexity/src/modules/message-splitter/index.ts @@ -1,14 +1,11 @@ import { attachFile, editableFrom, findComposer, writeComposer } from '../../core/composer' -import { isSendButton, readComposer } from '@nolly/ai' +import { isSendButton, readComposer, estimateTokens, ComposerButton, isAutomating } from '@nolly/ai' import { Feature, type MenuEntry, toElement, waitFor } from '@nolly/core' import { isOwnUi } from '../../core/dom' -import { estimateTokens } from '@nolly/ai' import { ProgressPanel, openSplitDialog, type SplitChoice } from './dialog' import { SendRunner } from './runner' import { loadSplitterSettings, saveSplitterSettings, type SplitterSettings } from './settings' -import { ComposerButton } from '@nolly/ai' import { openBigTextDialog } from './big-text' -import { isAutomating } from '@nolly/ai' export class MessageSplitterModule extends Feature { readonly id = 'message-splitter' diff --git a/ai/perplexity/src/modules/prompt-library/manager.ts b/ai/perplexity/src/modules/prompt-library/manager.ts index 3704449..d8002de 100644 --- a/ai/perplexity/src/modules/prompt-library/manager.ts +++ b/ai/perplexity/src/modules/prompt-library/manager.ts @@ -1,7 +1,5 @@ -import { copyText } from '@nolly/ai' +import { copyText, createButton, createTextArea, createDialog } from '@nolly/ai' import { createElement } from '@nolly/core' -import { createButton, createTextArea } from '@nolly/ai' -import { createDialog } from '@nolly/ai' import type { Prompt, PromptStore } from './store' import { ensureSlashStyles } from './styles' diff --git a/ai/perplexity/src/modules/prompt-library/variables.ts b/ai/perplexity/src/modules/prompt-library/variables.ts index f68d21c..3a09ab7 100644 --- a/ai/perplexity/src/modules/prompt-library/variables.ts +++ b/ai/perplexity/src/modules/prompt-library/variables.ts @@ -1,6 +1,4 @@ -import { applyValues, findFields, type Field } from '@nolly/ai' -import { currentSelection } from '@nolly/ai' -import { askFields } from '@nolly/ai' +import { applyValues, findFields, type Field, currentSelection, askFields } from '@nolly/ai' const BUILTINS = new Set(['clipboard', 'selection', 'date', 'time', 'url', 'title']) diff --git a/ai/perplexity/src/modules/prompt-queue/index.ts b/ai/perplexity/src/modules/prompt-queue/index.ts index 8189dd7..f67e071 100644 --- a/ai/perplexity/src/modules/prompt-queue/index.ts +++ b/ai/perplexity/src/modules/prompt-queue/index.ts @@ -1,11 +1,9 @@ import { Feature, waitFor, type MenuEntry, type ScriptContext } from '@nolly/core' import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { readComposer } from '@nolly/ai' +import { readComposer, ComposerButton, showToast } from '@nolly/ai' import { sendPrompt } from '../../core/dispatch' import { isGenerating, waitForResponse } from '../../core/generation' import { storage } from '../../core/storage' -import { ComposerButton } from '@nolly/ai' -import { showToast } from '@nolly/ai' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { recordPrompt } from '../recall/history' diff --git a/ai/perplexity/src/modules/prompt-queue/panel.ts b/ai/perplexity/src/modules/prompt-queue/panel.ts index 4818593..73d57a1 100644 --- a/ai/perplexity/src/modules/prompt-queue/panel.ts +++ b/ai/perplexity/src/modules/prompt-queue/panel.ts @@ -1,9 +1,7 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' import { storage } from '../../core/storage' -import { createButton } from '@nolly/ai' -import { createIcon } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { createButton, createIcon, ensureUiStyles } from '@nolly/ai' import type { PromptQueue, QueueItem } from './queue' import type { Phase, QueueRunner } from './runner' import { ensureQueueStyles } from './styles' diff --git a/ai/perplexity/src/modules/recall/dialog.ts b/ai/perplexity/src/modules/recall/dialog.ts index 949c45b..f470730 100644 --- a/ai/perplexity/src/modules/recall/dialog.ts +++ b/ai/perplexity/src/modules/recall/dialog.ts @@ -1,7 +1,5 @@ import { createElement } from '@nolly/core' -import { copyText } from '@nolly/ai' -import { createDialog } from '@nolly/ai' -import { showToast } from '@nolly/ai' +import { copyText, createDialog, showToast } from '@nolly/ai' import { ensurePaletteStyles } from '../command-palette/styles' import { threadLabel, timeAgo } from './format' import type { HistoryEntry, HistoryFilter, HistoryStore } from './store' diff --git a/ai/perplexity/src/modules/recall/index.ts b/ai/perplexity/src/modules/recall/index.ts index 29047b3..fc04549 100644 --- a/ai/perplexity/src/modules/recall/index.ts +++ b/ai/perplexity/src/modules/recall/index.ts @@ -1,15 +1,10 @@ import { Feature, toElement, type MenuEntry, type ScriptContext } from '@nolly/core' -import { isAutomating } from '@nolly/ai' -import { copyText } from '@nolly/ai' +import { isAutomating, copyText, isSendButton, readComposer, saveFile, ComposerButton, showToast } from '@nolly/ai' import { editableFrom, findComposer, sendComposer, writeComposer } from '../../core/composer' -import { isSendButton, readComposer } from '@nolly/ai' import { isOwnUi } from '../../core/dom' -import { saveFile } from '@nolly/ai' import { fetchSpy } from '../../core/fetch-spy' import { isAskRequest } from '../../core/requests' import { storage } from '../../core/storage' -import { ComposerButton } from '@nolly/ai' -import { showToast } from '@nolly/ai' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { promptQueue, threadOf } from '../prompt-queue/queue' diff --git a/ai/perplexity/src/modules/selection-toolbar/index.ts b/ai/perplexity/src/modules/selection-toolbar/index.ts index a28fd9c..4b2b5ef 100644 --- a/ai/perplexity/src/modules/selection-toolbar/index.ts +++ b/ai/perplexity/src/modules/selection-toolbar/index.ts @@ -1,10 +1,7 @@ import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { readComposer } from '@nolly/ai' +import { readComposer, rememberSelection, ensureUiStyles, askFields } from '@nolly/ai' import { createElement, Feature, injectStyle, type MenuEntry } from '@nolly/core' import { isOwnUi, markUi } from '../../core/dom' -import { rememberSelection } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' -import { askFields } from '@nolly/ai' interface Action { id: string diff --git a/ai/perplexity/src/modules/tutorial/engine.ts b/ai/perplexity/src/modules/tutorial/engine.ts index b343a65..4625e2f 100644 --- a/ai/perplexity/src/modules/tutorial/engine.ts +++ b/ai/perplexity/src/modules/tutorial/engine.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { createButton, ensureUiStyles } from '@nolly/ai' import { formatShortcut, matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { ensureTourStyles } from './styles' diff --git a/ai/perplexity/src/modules/tutorial/index.ts b/ai/perplexity/src/modules/tutorial/index.ts index 529a6c7..d9ad0e8 100644 --- a/ai/perplexity/src/modules/tutorial/index.ts +++ b/ai/perplexity/src/modules/tutorial/index.ts @@ -1,12 +1,7 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' import { storage } from '../../core/storage' -import { createButton } from '@nolly/ai' -import { createDialog } from '@nolly/ai' -import { createIcon } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' -import { showToast } from '@nolly/ai' -import { Tooltip } from '@nolly/ai' +import { createButton, createDialog, createIcon, ensureUiStyles, showToast, Tooltip } from '@nolly/ai' import { TourRunner } from './engine' import { FULL_TOUR, TOURS, type Tour } from './tours' diff --git a/ai/perplexity/src/modules/usage-status/dialog.ts b/ai/perplexity/src/modules/usage-status/dialog.ts index c9034cc..15c4303 100644 --- a/ai/perplexity/src/modules/usage-status/dialog.ts +++ b/ai/perplexity/src/modules/usage-status/dialog.ts @@ -1,6 +1,5 @@ import { createElement } from '@nolly/core' -import { createButton, createDataRow, createSection } from '@nolly/ai' -import { createDialog } from '@nolly/ai' +import { createButton, createDataRow, createSection, createDialog } from '@nolly/ai' import { createStatusBar, createTimerBlock } from './components' import { LIMITS, LIMIT_KEYS, SETTINGS_FIELDS, SOURCE_LABELS, STATUS_LABELS } from './definitions' import { getStatus } from './format' diff --git a/ai/perplexity/src/modules/usage-status/indicator.ts b/ai/perplexity/src/modules/usage-status/indicator.ts index 41d0497..2929037 100644 --- a/ai/perplexity/src/modules/usage-status/indicator.ts +++ b/ai/perplexity/src/modules/usage-status/indicator.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { Tooltip } from '@nolly/ai' -import { ensureUiStyles } from '@nolly/ai' +import { Tooltip, ensureUiStyles } from '@nolly/ai' import { Dock } from './dock' import { isPlaced, type Placement } from './placement' import type { UsageService } from './service' From a693061c94d16f241fd31535068e58af3f367cb5 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:10:51 +0100 Subject: [PATCH 03/19] feat(ai): hoist Enter as Newline into @nolly/ai; add messages, file budget and Enter-as-Newline to better-chatgpt (step 3) --- ai/chatgpt/src/adapter.ts | 4 +- ai/chatgpt/src/budget.ts | 25 ++++++ ai/chatgpt/src/features/diagnostics.ts | 37 +++++---- ai/chatgpt/src/kit.ts | 3 +- ai/chatgpt/src/main.ts | 22 ++--- ai/chatgpt/src/messages.ts | 23 ++++++ ai/chatgpt/src/session.ts | 4 + ai/chatgpt/src/theme.ts | 1 + ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/src/main.ts | 37 +++++---- .../modules/enter-as-newline/config-button.ts | 65 --------------- .../src/modules/enter-as-newline/index.ts | 63 -------------- .../src/modules/enter-as-newline/styles.ts | 15 ---- core/ai/CHANGELOG.md | 1 + core/ai/README.md | 1 + .../enter-as-newline/config-button.ts | 76 +++++++++++++++++ .../src/features}/enter-as-newline/dialog.ts | 20 +++-- .../src/features/enter-as-newline/feature.ts | 82 +++++++++++++++++++ .../ai/src/features/enter-as-newline/index.ts | 2 + .../features}/enter-as-newline/keyboard.ts | 10 ++- .../features}/enter-as-newline/shortcuts.ts | 8 +- core/ai/src/features/index.ts | 2 + core/ai/src/index.ts | 1 + 23 files changed, 296 insertions(+), 207 deletions(-) create mode 100644 ai/chatgpt/src/budget.ts create mode 100644 ai/chatgpt/src/messages.ts delete mode 100644 ai/perplexity/src/modules/enter-as-newline/config-button.ts delete mode 100644 ai/perplexity/src/modules/enter-as-newline/index.ts delete mode 100644 ai/perplexity/src/modules/enter-as-newline/styles.ts create mode 100644 core/ai/src/features/enter-as-newline/config-button.ts rename {ai/perplexity/src/modules => core/ai/src/features}/enter-as-newline/dialog.ts (65%) create mode 100644 core/ai/src/features/enter-as-newline/feature.ts create mode 100644 core/ai/src/features/enter-as-newline/index.ts rename {ai/perplexity/src/modules => core/ai/src/features}/enter-as-newline/keyboard.ts (82%) rename {ai/perplexity/src/modules => core/ai/src/features}/enter-as-newline/shortcuts.ts (86%) create mode 100644 core/ai/src/features/index.ts diff --git a/ai/chatgpt/src/adapter.ts b/ai/chatgpt/src/adapter.ts index c92b70c..bfc462f 100644 --- a/ai/chatgpt/src/adapter.ts +++ b/ai/chatgpt/src/adapter.ts @@ -1,6 +1,7 @@ import type { ConversationRef, PlatformAdapter } from '@nolly/ai' import { isOwnUi } from './dom' import { findAttachButton, findComposerForm, findHeaderSlot, findModeToggles, findPrimaryAction, findSendButton, findSidebar, findStopButton, labelOf, locateEditable, rejectEditable } from './locate' +import { countTurns } from './messages' const CHAT_PATH = /^\/(?:g\/g-p-[0-9a-f]+[^/]*\/)?c\/([^/?#]+)/ const PROJECT_PATH = /^\/g\/(g-p-[0-9a-f]+)/ @@ -43,6 +44,7 @@ export const chatgptAdapter: PlatformAdapter = { attach: brief(findAttachButton()), modeToggles: findModeToggles().map(({ element }) => brief(element)), headerSlot: findHeaderSlot() !== null, - sidebar: findSidebar() !== null + sidebar: findSidebar() !== null, + turns: countTurns(), }) } diff --git a/ai/chatgpt/src/budget.ts b/ai/chatgpt/src/budget.ts new file mode 100644 index 0000000..f137297 --- /dev/null +++ b/ai/chatgpt/src/budget.ts @@ -0,0 +1,25 @@ +import type { ChatSession } from './session' + +export const FILES_PER_MESSAGE = 20 + +export interface FileBudget { + readonly perMessage: number + readonly remainingUploads: number | null + readonly uploadResetsAt: string | null + readonly remainingPasteToFile: number | null + readonly pasteResetsAt: string | null + readonly maxFileMb: number | null +} + +export const fileBudget = (session: ChatSession): FileBudget => { + const upload = session.limit('file_upload') + const paste = session.limit('paste_text_to_file') + return { + perMessage: FILES_PER_MESSAGE, + remainingUploads: upload?.remaining ?? null, + uploadResetsAt: upload?.resetAfter ?? null, + remainingPasteToFile: paste?.remaining ?? null, + pasteResetsAt: paste?.resetAfter ?? null, + maxFileMb: session.maxFileMb + } +} diff --git a/ai/chatgpt/src/features/diagnostics.ts b/ai/chatgpt/src/features/diagnostics.ts index 5f1f3dc..df66abf 100644 --- a/ai/chatgpt/src/features/diagnostics.ts +++ b/ai/chatgpt/src/features/diagnostics.ts @@ -3,28 +3,29 @@ import type { FeatureCommand } from '@nolly/core' import { chatgptAdapter } from '../adapter' import { sendPrompt } from '../kit' import { session } from '../runtime' +import { fileBudget } from '../budget' export class DiagnosticsFeature extends Feature { - readonly id = 'diagnostics' - readonly name = 'Diagnostics' - readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' + readonly id = 'diagnostics' + readonly name = 'Diagnostics' + readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' - run(): void {} + run(): void { } - override onEnable(): void { - const page = getPageWindow() as unknown as Record | null - if (page) { - page['betterChatgptDump'] = () => this.dump() - page['betterChatgptSend'] = (text: string) => sendPrompt(text) - } - this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') - } + override onEnable(): void { + const page = getPageWindow() as unknown as Record | null + if (page) { + page['betterChatgptDump'] = () => this.dump() + page['betterChatgptSend'] = (text: string) => sendPrompt(text) + } + this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') + } - override commands(): FeatureCommand[] { - return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] - } + override commands(): FeatureCommand[] { + return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] + } - private dump(): string { - return JSON.stringify({ page: chatgptAdapter.describePage(), session: session.snapshot() }, null, 2) - } + private dump(): string { + return JSON.stringify({ page: chatgptAdapter.describePage(), session: session.snapshot(), fileBudget: fileBudget(session) }, null, 2) + } } diff --git a/ai/chatgpt/src/kit.ts b/ai/chatgpt/src/kit.ts index 34d63a4..9205a25 100644 --- a/ai/chatgpt/src/kit.ts +++ b/ai/chatgpt/src/kit.ts @@ -1,4 +1,5 @@ import { createComposerKit, createPromptSender } from '@nolly/ai' import { chatgptAdapter } from './adapter' -export const sendPrompt = createPromptSender(createComposerKit(chatgptAdapter)) +export const composerKit = createComposerKit(chatgptAdapter) +export const sendPrompt = createPromptSender(composerKit) diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 876e555..557bfa1 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,23 +1,25 @@ -import { configureUi } from '@nolly/ai' +import { EnterAsNewlineFeature, configureUi } from '@nolly/ai' import { App } from './app' import { uiMarker } from './dom' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' -import { findAttachButton, findPrimaryAction } from './locate' +import { composerKit } from './kit' +import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' import './runtime' import { installTheme } from './theme' configureUi({ - id: 'better-chatgpt', - title: 'Better ChatGPT', - version: __VERSION__, - marker: uiMarker, - composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) + id: 'better-chatgpt', + title: 'Better ChatGPT', + version: __VERSION__, + marker: uiMarker, + composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) }) installTheme() new App() - .register((context) => new HeaderButtonFeature(context)) - .register((context) => new DiagnosticsFeature(context)) - .start() + .register((context) => new HeaderButtonFeature(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage: context.storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) + .register((context) => new DiagnosticsFeature(context)) + .start() diff --git a/ai/chatgpt/src/messages.ts b/ai/chatgpt/src/messages.ts new file mode 100644 index 0000000..0de16ab --- /dev/null +++ b/ai/chatgpt/src/messages.ts @@ -0,0 +1,23 @@ +import { isOwnUi } from './dom' + +export type Role = 'user' | 'assistant' + +export interface Turn { + readonly role: Role + readonly element: HTMLElement + readonly text: () => string +} + +const ROLE_ATTRIBUTE = 'data-message-author-role' + +export const findTurns = (): Turn[] => + [...document.querySelectorAll(`[${ROLE_ATTRIBUTE}]`)].flatMap((element): Turn[] => { + const role = element.getAttribute(ROLE_ATTRIBUTE) + if (isOwnUi(element) || (role !== 'user' && role !== 'assistant')) return [] + return [{ role, element, text: () => (element.innerText ?? '').trim() }] + }) + +export const countTurns = (): Record => { + const turns = findTurns() + return { user: turns.filter((turn) => turn.role === 'user').length, assistant: turns.filter((turn) => turn.role === 'assistant').length } +} diff --git a/ai/chatgpt/src/session.ts b/ai/chatgpt/src/session.ts index 40a33fe..bc51ea2 100644 --- a/ai/chatgpt/src/session.ts +++ b/ai/chatgpt/src/session.ts @@ -30,6 +30,10 @@ export class ChatSession { return [...this.limitMap.values()] } + limit(feature: string): LimitProgress | null { + return this.limitMap.get(feature) ?? null + } + subscribe(listener: (event: SessionEvent) => void): () => void { this.listeners.add(listener) return () => this.listeners.delete(listener) diff --git a/ai/chatgpt/src/theme.ts b/ai/chatgpt/src/theme.ts index 624b9db..196fa87 100644 --- a/ai/chatgpt/src/theme.ts +++ b/ai/chatgpt/src/theme.ts @@ -29,6 +29,7 @@ html.light .bp-themed { .bp-tip-mode { font-weight: 600; } .bp-tip-sub { color: var(--bp-muted); } +.bp-tip-foot { margin-top: 4px; color: var(--bp-muted); font-size: 11px; } ` export const installTheme = (): void => injectStyle('better-chatgpt-theme', CSS) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 0edbca5..c1a10e4 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Better Perplexity are documented here. The format follows ## [Unreleased] - Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. +- Internal: Enter as Newline now comes from the shared package. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index 72a1686..d926813 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,6 +1,8 @@ import { App } from './core/app' import { fetchSpy } from './core/fetch-spy' import { configureUi } from '@nolly/ai' +import { EnterAsNewlineFeature } from '@nolly/ai' +import { storage } from './core/storage' import { uiMarker } from './core/dom' import { findComposerActions } from './locate' import { BatchRunnerModule } from './modules/batch-runner' @@ -24,20 +26,21 @@ configureUi({ id: 'better-perplexity', title: 'Better Perplexity', version: __VE fetchSpy.install() new App() - .register((context) => new PromptLibraryModule(context)) - .register((context) => new SelectionToolbarModule(context)) - .register((context) => new MaxWidthModule(context)) - .register((context) => new EnterAsNewlineModule(context)) - .register((context) => new CodeBlocksModule(context)) - .register((context) => new MessageSplitterModule(context)) - .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardModule(context)) - .register((context) => new CommandPaletteModule(context)) - .register((context) => new ExporterModule(context)) - .register((context) => new UsageStatusModule(context)) - .register((context) => new GlobalSettingsModule(context)) - .register((context) => new TutorialModule(context)) - .register((context) => new UpdatesModule(context)) - .register((context) => new PromptQueueModule(context)) - .register((context) => new RecallModule(context)) - .start() + .register((context) => new PromptLibraryModule(context)) + .register((context) => new SelectionToolbarModule(context)) + .register((context) => new MaxWidthModule(context)) + .register((context) => new EnterAsNewlineModule(context)) + .register((context) => new CodeBlocksModule(context)) + .register((context) => new MessageSplitterModule(context)) + .register((context) => new BatchRunnerModule(context)) + .register((context) => new DraftGuardModule(context)) + .register((context) => new CommandPaletteModule(context)) + .register((context) => new ExporterModule(context)) + .register((context) => new UsageStatusModule(context)) + .register((context) => new GlobalSettingsModule(context)) + .register((context) => new TutorialModule(context)) + .register((context) => new UpdatesModule(context)) + .register((context) => new PromptQueueModule(context)) + .register((context) => new RecallModule(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage })) + .start() diff --git a/ai/perplexity/src/modules/enter-as-newline/config-button.ts b/ai/perplexity/src/modules/enter-as-newline/config-button.ts deleted file mode 100644 index a1510a0..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/config-button.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { findComposerActions } from '../../locate' -import { ensureUiStyles, Tooltip } from '@nolly/ai' -import { ensureConfigButtonStyles } from './styles' - -const SVG_NS = 'http://www.w3.org/2000/svg' - -const createIcon = (): SVGSVGElement => { - const svg = document.createElementNS(SVG_NS, 'svg') - for (const [name, value] of Object.entries({ width: '16', height: '16', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(name, value) - const arrow = document.createElementNS(SVG_NS, 'polyline') - arrow.setAttribute('points', '9 10 4 15 9 20') - const line = document.createElementNS(SVG_NS, 'path') - line.setAttribute('d', 'M20 4v7a4 4 0 0 1-4 4H4') - svg.append(arrow, line) - return svg -} - -export class ConfigButton { - readonly element = markUi(createElement('button', 'bp-config-button')) - private readonly tooltip: Tooltip - private appliedClass = '' - - constructor(onClick: () => void, describe: () => string) { - ensureUiStyles() - ensureConfigButtonStyles() - this.element.type = 'button' - this.element.setAttribute('aria-label', 'Configure Enter as Newline') - this.element.appendChild(createIcon()) - this.element.addEventListener('click', (event) => { - event.preventDefault() - event.stopPropagation() - onClick() - }) - this.tooltip = new Tooltip(this.element, (container) => { - container.append(createElement('div', 'bp-tip-mode', 'Enter as Newline'), createElement('div', 'bp-tip-sub', describe()), createElement('div', 'bp-tip-foot', 'Click to configure')) - }) - } - - mount(): void { - const { first, submit } = findComposerActions() - if (!first && !submit) { - this.unmount() - return - } - if (first) this.syncClass(first) - const placed = first ? first.nextElementSibling === this.element : submit?.previousElementSibling === this.element - if (placed) return - if (first) first.insertAdjacentElement('afterend', this.element) - else submit?.insertAdjacentElement('beforebegin', this.element) - } - - unmount(): void { - this.tooltip.hide() - this.element.remove() - } - - private syncClass(reference: HTMLElement): void { - const next = `${reference.className} bp-config-button` - if (next === this.appliedClass) return - this.element.className = next - this.appliedClass = next - } -} diff --git a/ai/perplexity/src/modules/enter-as-newline/index.ts b/ai/perplexity/src/modules/enter-as-newline/index.ts deleted file mode 100644 index ccba4c5..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/index.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { isSynthetic } from '@nolly/ai' -import { Feature, type MenuEntry } from '@nolly/core' -import { logger } from '../../core/logger' -import { ConfigButton } from './config-button' -import { toggleShortcutsDialog } from './dialog' -import { getEditableTarget, insertNewline, isComposing, sendMessage } from './keyboard' -import { describeShortcuts, hasModifier, loadShortcuts, matchesShortcut, saveShortcuts, type ShortcutSettings } from './shortcuts' - -export class EnterAsNewlineModule extends Feature { - readonly id = 'enter-as-newline' - readonly name = 'Enter as Newline' - readonly description = 'Use Enter for newlines and configurable shortcuts to send messages.' - - private shortcuts: ShortcutSettings = loadShortcuts() - private attached = false - private readonly configButton = new ConfigButton( - () => this.configure(), - () => describeShortcuts(this.shortcuts) - ) - - run(): void { - if (this.enabled) this.configButton.mount() - else this.configButton.unmount() - if (this.enabled && !this.attached) { - window.addEventListener('keydown', this.handleKeydown, true) - this.attached = true - logger.success('Enter as Newline listener registered.') - return - } - if (!this.enabled && this.attached) { - window.removeEventListener('keydown', this.handleKeydown, true) - this.attached = false - logger.info('Enter as Newline listener removed.') - } - } - - override menuEntries(): MenuEntry[] { - return [{ label: 'Configure Enter as Newline', action: () => this.configure() }] - } - - private configure(): void { - toggleShortcutsDialog(this.shortcuts, (settings) => { - this.shortcuts = settings - saveShortcuts(settings) - }) - } - - private readonly handleKeydown = (event: KeyboardEvent): void => { - if (event.key !== 'Enter' || isComposing(event) || isSynthetic(event)) return - const editable = getEditableTarget(event) - if (!editable) return - if (matchesShortcut(event, this.shortcuts)) { - event.preventDefault() - event.stopImmediatePropagation() - sendMessage(editable) - return - } - if (hasModifier(event)) return - event.preventDefault() - event.stopImmediatePropagation() - insertNewline(editable) - } -} diff --git a/ai/perplexity/src/modules/enter-as-newline/styles.ts b/ai/perplexity/src/modules/enter-as-newline/styles.ts deleted file mode 100644 index f1cbee9..0000000 --- a/ai/perplexity/src/modules/enter-as-newline/styles.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { injectStyle } from '@nolly/core' - -const CSS = ` -.bp-config-button { - display: inline-flex; - align-items: center; - justify-content: center; - flex-shrink: 0; - cursor: pointer; -} - -.bp-config-button svg { pointer-events: none; } -` - -export const ensureConfigButtonStyles = (): void => injectStyle('better-perplexity-enter-styles', CSS) \ No newline at end of file diff --git a/core/ai/CHANGELOG.md b/core/ai/CHANGELOG.md index 84f0b8a..d1ed819 100644 --- a/core/ai/CHANGELOG.md +++ b/core/ai/CHANGELOG.md @@ -4,3 +4,4 @@ - Initial release: adapter contract, composer kit, generation kit, response spy and SSE parser. - Added placeholders, tokens, selection, clipboard, download, prompt sender and the UI kit (moved from Better Perplexity). +- Added Enter as Newline with configurable send shortcuts and file budget in diagnostics. diff --git a/core/ai/README.md b/core/ai/README.md index b816c64..af14a43 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,3 +10,4 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. +- Feature modules that need only an adapter: Enter as Newline. diff --git a/core/ai/src/features/enter-as-newline/config-button.ts b/core/ai/src/features/enter-as-newline/config-button.ts new file mode 100644 index 0000000..2c1609e --- /dev/null +++ b/core/ai/src/features/enter-as-newline/config-button.ts @@ -0,0 +1,76 @@ +import { createElement, injectStyle } from '@nolly/core' +import { markUi, uiConfig } from '../../ui/config' +import { ensureUiStyles } from '../../ui/styles' +import { Tooltip } from '../../ui/tooltip' + +const SVG_NS = 'http://www.w3.org/2000/svg' + +const CSS = ` +.bp-config-button { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + cursor: pointer; +} + +.bp-config-button svg { pointer-events: none; } +` + +const createIcon = (): SVGSVGElement => { + const svg = document.createElementNS(SVG_NS, 'svg') + for (const [name, value] of Object.entries({ width: '16', height: '16', viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', 'stroke-width': '2', 'stroke-linecap': 'round', 'stroke-linejoin': 'round', 'aria-hidden': 'true' })) svg.setAttribute(name, value) + const arrow = document.createElementNS(SVG_NS, 'polyline') + arrow.setAttribute('points', '9 10 4 15 9 20') + const line = document.createElementNS(SVG_NS, 'path') + line.setAttribute('d', 'M20 4v7a4 4 0 0 1-4 4H4') + svg.append(arrow, line) + return svg +} + +export class ConfigButton { + readonly element = markUi(createElement('button', 'bp-config-button')) + private readonly tooltip: Tooltip + private appliedClass = '' + + constructor(onClick: () => void, describe: () => string) { + ensureUiStyles() + injectStyle(`${uiConfig().id}-enter-styles`, CSS) + this.element.type = 'button' + this.element.setAttribute('aria-label', 'Configure Enter as Newline') + this.element.appendChild(createIcon()) + this.element.addEventListener('click', (event) => { + event.preventDefault() + event.stopPropagation() + onClick() + }) + this.tooltip = new Tooltip(this.element, (container) => { + container.append(createElement('div', 'bp-tip-mode', 'Enter as Newline'), createElement('div', 'bp-tip-sub', describe()), createElement('div', 'bp-tip-foot', 'Click to configure')) + }) + } + + mount(): void { + const { first, submit } = uiConfig().composerActions?.() ?? { first: null, submit: null } + if (!first && !submit) { + this.unmount() + return + } + if (first) this.syncClass(first) + const placed = first ? first.nextElementSibling === this.element : submit?.previousElementSibling === this.element + if (placed) return + if (first) first.insertAdjacentElement('afterend', this.element) + else submit?.insertAdjacentElement('beforebegin', this.element) + } + + unmount(): void { + this.tooltip.hide() + this.element.remove() + } + + private syncClass(reference: HTMLElement): void { + const next = `${reference.className} bp-config-button` + if (next === this.appliedClass) return + this.element.className = next + this.appliedClass = next + } +} diff --git a/ai/perplexity/src/modules/enter-as-newline/dialog.ts b/core/ai/src/features/enter-as-newline/dialog.ts similarity index 65% rename from ai/perplexity/src/modules/enter-as-newline/dialog.ts rename to core/ai/src/features/enter-as-newline/dialog.ts index 1da2a8b..41aa62b 100644 --- a/ai/perplexity/src/modules/enter-as-newline/dialog.ts +++ b/core/ai/src/features/enter-as-newline/dialog.ts @@ -1,17 +1,19 @@ import { createElement } from '@nolly/core' -import { logger } from '../../core/logger' -import { createButton, createSwitch, createDialog } from '@nolly/ai' -import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts, type Modifier, type ShortcutSettings } from './shortcuts' +import type { Logger } from '@nolly/core' +import { createButton, createSwitch } from '../../ui/controls' +import { uiConfig } from '../../ui/config' +import { createDialog } from '../../ui/dialog' +import { DEFAULT_SHORTCUTS, SHORTCUT_OPTIONS, describeShortcuts } from './shortcuts' +import type { Modifier, ShortcutSettings } from './shortcuts' -const DIALOG_ID = 'better-perplexity-enter-dialog' - -export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settings: ShortcutSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) +export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settings: ShortcutSettings) => void, logger: Logger): void => { + const dialogId = `${uiConfig().id}-enter-dialog` + const existing = document.getElementById(dialogId) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Enter as Newline', description: 'Choose which keyboard shortcuts send your message.', width: 440 }) + const ui = createDialog({ id: dialogId, title: 'Enter as Newline', description: 'Choose which keyboard shortcuts send your message.', width: 440 }) const draft: ShortcutSettings = { ...current } const summary = createElement('p', 'bp-hint', describeShortcuts(draft)) const stack = createElement('div', 'bp-stack') @@ -43,4 +45,4 @@ export const toggleShortcutsDialog = (current: ShortcutSettings, onSave: (settin } ui.footer.append(createButton('Cancel', { onClick: ui.close }), createButton('Reset', { onClick: reset }), createButton('Save', { primary: true, onClick: save })) ui.show() -} \ No newline at end of file +} diff --git a/core/ai/src/features/enter-as-newline/feature.ts b/core/ai/src/features/enter-as-newline/feature.ts new file mode 100644 index 0000000..b07b105 --- /dev/null +++ b/core/ai/src/features/enter-as-newline/feature.ts @@ -0,0 +1,82 @@ +import { Feature } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isSynthetic } from '../../keys' +import { ConfigButton } from './config-button' +import { toggleShortcutsDialog } from './dialog' +import { defaultSend, getEditableTarget, insertNewline, isComposing } from './keyboard' +import type { EditableFilter } from './keyboard' +import { describeShortcuts, hasModifier, loadShortcuts, matchesShortcut, saveShortcuts } from './shortcuts' +import type { ShortcutSettings } from './shortcuts' + +export interface EnterAsNewlineOptions { + readonly storage: ScriptStorage + readonly reject?: EditableFilter + readonly send?: (editable: HTMLElement) => void +} + +export class EnterAsNewlineFeature extends Feature { + readonly id = 'enter-as-newline' + readonly name = 'Enter as Newline' + readonly description = 'Use Enter for newlines and configurable shortcuts to send messages.' + + private shortcuts: ShortcutSettings + private attached = false + private readonly configButton: ConfigButton + + constructor(context: ScriptContext, private readonly options: EnterAsNewlineOptions) { + super(context) + this.shortcuts = loadShortcuts(options.storage) + this.configButton = new ConfigButton( + () => this.configure(), + () => describeShortcuts(this.shortcuts) + ) + } + + run(): void { + if (this.enabled) this.configButton.mount() + else this.configButton.unmount() + if (this.enabled && !this.attached) { + window.addEventListener('keydown', this.handleKeydown, true) + this.attached = true + this.context.logger.success('Enter as Newline listener registered.') + return + } + if (!this.enabled && this.attached) { + window.removeEventListener('keydown', this.handleKeydown, true) + this.attached = false + this.context.logger.info('Enter as Newline listener removed.') + } + } + + override menuEntries(): MenuEntry[] { + return [{ label: 'Configure Enter as Newline', action: () => this.configure() }] + } + + private configure(): void { + toggleShortcutsDialog( + this.shortcuts, + (settings) => { + this.shortcuts = settings + saveShortcuts(this.options.storage, settings) + }, + this.context.logger + ) + } + + private readonly handleKeydown = (event: KeyboardEvent): void => { + if (event.key !== 'Enter' || isComposing(event) || isSynthetic(event)) return + const editable = getEditableTarget(event, this.options.reject) + if (!editable) return + if (matchesShortcut(event, this.shortcuts)) { + event.preventDefault() + event.stopImmediatePropagation() + const sendDefault = this.options.send ?? defaultSend + sendDefault(editable) + return + } + if (hasModifier(event)) return + event.preventDefault() + event.stopImmediatePropagation() + insertNewline(editable) + } +} diff --git a/core/ai/src/features/enter-as-newline/index.ts b/core/ai/src/features/enter-as-newline/index.ts new file mode 100644 index 0000000..19e2a59 --- /dev/null +++ b/core/ai/src/features/enter-as-newline/index.ts @@ -0,0 +1,2 @@ +export { EnterAsNewlineFeature } from './feature' +export type { EnterAsNewlineOptions } from './feature' diff --git a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts b/core/ai/src/features/enter-as-newline/keyboard.ts similarity index 82% rename from ai/perplexity/src/modules/enter-as-newline/keyboard.ts rename to core/ai/src/features/enter-as-newline/keyboard.ts index 15018a7..35f91ae 100644 --- a/ai/perplexity/src/modules/enter-as-newline/keyboard.ts +++ b/core/ai/src/features/enter-as-newline/keyboard.ts @@ -1,12 +1,14 @@ -import { dispatchEnter, findSendButton } from '@nolly/ai' import { toElement } from '@nolly/core' +import { dispatchEnter, findSendButton } from '../../keys' const EDITABLE_SELECTOR = 'textarea, [contenteditable="true"], [contenteditable="plaintext-only"]' -export const getEditableTarget = (event: Event): HTMLElement | null => { +export type EditableFilter = (editable: HTMLElement) => boolean + +export const getEditableTarget = (event: Event, reject: EditableFilter = () => false): HTMLElement | null => { const origin = event.composedPath()[0] ?? event.target const editable = toElement(origin)?.closest(EDITABLE_SELECTOR) - if (!editable?.isConnected) return null + if (!editable?.isConnected || reject(editable)) return null return editable instanceof HTMLTextAreaElement || editable.isContentEditable ? editable : null } @@ -39,6 +41,6 @@ export const insertNewline = (editable: HTMLElement): void => { if (dispatchEnter(editable, true)) insertNewlineManually(editable) } -export const sendMessage = (editable: HTMLElement): void => { +export const defaultSend = (editable: HTMLElement): void => { if (dispatchEnter(editable, false)) findSendButton(editable)?.click() } diff --git a/ai/perplexity/src/modules/enter-as-newline/shortcuts.ts b/core/ai/src/features/enter-as-newline/shortcuts.ts similarity index 86% rename from ai/perplexity/src/modules/enter-as-newline/shortcuts.ts rename to core/ai/src/features/enter-as-newline/shortcuts.ts index b23b921..9054d83 100644 --- a/ai/perplexity/src/modules/enter-as-newline/shortcuts.ts +++ b/core/ai/src/features/enter-as-newline/shortcuts.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import type { ScriptStorage } from '@nolly/core' export type Modifier = 'ctrl' | 'alt' | 'meta' | 'shift' export type ShortcutSettings = Record @@ -20,13 +20,13 @@ export const SHORTCUT_OPTIONS: readonly ShortcutOption[] = [ export const DEFAULT_SHORTCUTS: Readonly = { ctrl: true, alt: false, meta: true, shift: false } -export const loadShortcuts = (): ShortcutSettings => { +export const loadShortcuts = (storage: ScriptStorage): ShortcutSettings => { const saved = storage.get>(STORAGE_KEY, DEFAULT_SHORTCUTS) const entries = SHORTCUT_OPTIONS.map(({ key }) => [key, typeof saved?.[key] === 'boolean' ? saved[key] : DEFAULT_SHORTCUTS[key]]) return Object.fromEntries(entries) as ShortcutSettings } -export const saveShortcuts = (settings: ShortcutSettings): void => storage.set(STORAGE_KEY, settings) +export const saveShortcuts = (storage: ScriptStorage, settings: ShortcutSettings): void => storage.set(STORAGE_KEY, settings) export const matchesShortcut = (event: KeyboardEvent, settings: ShortcutSettings): boolean => { const pressed = SHORTCUT_OPTIONS.filter(({ flag }) => event[flag]) @@ -38,4 +38,4 @@ export const hasModifier = (event: KeyboardEvent): boolean => SHORTCUT_OPTIONS.s export const describeShortcuts = (settings: ShortcutSettings): string => { const labels = SHORTCUT_OPTIONS.filter(({ key }) => settings[key]).map(({ label }) => label) return labels.length ? `Sends with: ${labels.join(', ')}. Plain Enter inserts a newline.` : 'No send shortcut selected: messages can only be sent with the button.' -} \ No newline at end of file +} diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts new file mode 100644 index 0000000..a7cc04a --- /dev/null +++ b/core/ai/src/features/index.ts @@ -0,0 +1,2 @@ +export { EnterAsNewlineFeature } from './enter-as-newline' +export type { EnterAsNewlineOptions } from './enter-as-newline' diff --git a/core/ai/src/index.ts b/core/ai/src/index.ts index de403dc..50b6770 100644 --- a/core/ai/src/index.ts +++ b/core/ai/src/index.ts @@ -12,3 +12,4 @@ export * from './selection' export * from './sse' export * from './tokens' export * from './ui' +export * from './features' From 246d65b258902bae827948d683b05f355a6b3d3f Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:16:56 +0100 Subject: [PATCH 04/19] fix(perplexity): register Enter as Newline from @nolly/ai --- ai/perplexity/src/main.ts | 19 +- .../src/modules/draft-guard/index.ts | 198 ------------------ .../src/modules/draft-guard/overlay.ts | 89 -------- .../src/modules/draft-guard/store.ts | 48 ----- .../src/modules/draft-guard/styles.ts | 42 ---- 5 files changed, 9 insertions(+), 387 deletions(-) delete mode 100644 ai/perplexity/src/modules/draft-guard/index.ts delete mode 100644 ai/perplexity/src/modules/draft-guard/overlay.ts delete mode 100644 ai/perplexity/src/modules/draft-guard/store.ts delete mode 100644 ai/perplexity/src/modules/draft-guard/styles.ts diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index d926813..8a3ab3d 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,26 +1,26 @@ +import { DraftGuardFeature, EnterAsNewlineFeature, configureUi } from '@nolly/ai' import { App } from './core/app' +import { findComposer, writeComposer } from './core/composer' +import { uiMarker } from './core/dom' import { fetchSpy } from './core/fetch-spy' -import { configureUi } from '@nolly/ai' -import { EnterAsNewlineFeature } from '@nolly/ai' +import { isAskRequest } from './core/requests' import { storage } from './core/storage' -import { uiMarker } from './core/dom' import { findComposerActions } from './locate' import { BatchRunnerModule } from './modules/batch-runner' import { CodeBlocksModule } from './modules/code-blocks' import { CommandPaletteModule } from './modules/command-palette' -import { DraftGuardModule } from './modules/draft-guard' -import { EnterAsNewlineModule } from './modules/enter-as-newline' import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' import { MaxWidthModule } from './modules/max-width' import { MessageSplitterModule } from './modules/message-splitter' +import { loadSplitterSettings } from './modules/message-splitter/settings' import { PromptLibraryModule } from './modules/prompt-library' +import { PromptQueueModule } from './modules/prompt-queue' +import { RecallModule } from './modules/recall' import { SelectionToolbarModule } from './modules/selection-toolbar' import { TutorialModule } from './modules/tutorial' import { UpdatesModule } from './modules/updates' import { UsageStatusModule } from './modules/usage-status' -import { PromptQueueModule } from './modules/prompt-queue' -import { RecallModule } from './modules/recall' configureUi({ id: 'better-perplexity', title: 'Better Perplexity', version: __VERSION__, marker: uiMarker, composerActions: findComposerActions }) fetchSpy.install() @@ -29,11 +29,11 @@ new App() .register((context) => new PromptLibraryModule(context)) .register((context) => new SelectionToolbarModule(context)) .register((context) => new MaxWidthModule(context)) - .register((context) => new EnterAsNewlineModule(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage })) .register((context) => new CodeBlocksModule(context)) .register((context) => new MessageSplitterModule(context)) .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardModule(context)) + .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend: (listener) => fetchSpy.subscribe(({ method, url }) => { if (isAskRequest(method, url)) listener() }), tokenLimit: () => loadSplitterSettings().limit })) .register((context) => new CommandPaletteModule(context)) .register((context) => new ExporterModule(context)) .register((context) => new UsageStatusModule(context)) @@ -42,5 +42,4 @@ new App() .register((context) => new UpdatesModule(context)) .register((context) => new PromptQueueModule(context)) .register((context) => new RecallModule(context)) - .register((context) => new EnterAsNewlineFeature(context, { storage })) .start() diff --git a/ai/perplexity/src/modules/draft-guard/index.ts b/ai/perplexity/src/modules/draft-guard/index.ts deleted file mode 100644 index aa10190..0000000 --- a/ai/perplexity/src/modules/draft-guard/index.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { findComposer, writeComposer } from '../../core/composer' -import { isSendButton, readComposer } from '@nolly/ai' -import { Feature, type MenuEntry, type ScriptContext, toElement } from '@nolly/core' -import { fetchSpy } from '../../core/fetch-spy' -import { storage } from '../../core/storage' -import { loadSplitterSettings } from '../message-splitter/settings' -import { DraftOverlay } from './overlay' -import { DraftStore, type Draft } from './store' -import { isAskRequest } from '../../core/requests' - -const SAVE_DELAY = 400 -const SEND_WINDOW = 3_000 -const GUARD_KEY = 'draft-guard:warn-on-close' -const SPLIT_COMMAND = 'message-splitter:split' - -const threadKey = (): string => location.pathname || '/' -const meaningful = (text: string): boolean => text.replace(/[\s\u200b]/g, '') !== '' - -export class DraftGuardModule extends Feature { - readonly id = 'draft-guard' - readonly name = 'Draft Guard' - readonly description = 'Autosaves drafts, shows a size meter and warns about unsent text.' - - private readonly store = new DraftStore() - private readonly overlay = new DraftOverlay() - private readonly wired = new WeakSet() - private readonly dismissed = new Set() - private readonly typed = new Set() - private readonly offered = new Map() - private key = threadKey() - private lastText = '' - private saveTimer = 0 - private sendIntentAt = 0 - private guardAttached = false - private composer: HTMLElement | null = null - - constructor(context: ScriptContext) { - super(context) - this.overlay.onSplit(() => this.context.runCommand(SPLIT_COMMAND)) - fetchSpy.subscribe(({ method, url }) => { - if (this.enabled && isAskRequest(method, url) && meaningful(this.lastText)) this.discard(this.key) - }) - document.addEventListener('click', this.handleClick, true) - document.addEventListener('keydown', this.handleKeydown, true) - window.addEventListener('scroll', this.reposition, true) - window.addEventListener('resize', this.reposition) - } - - get warnOnClose(): boolean { - return storage.get(GUARD_KEY, true) - } - - set warnOnClose(value: boolean) { - storage.set(GUARD_KEY, value) - } - - run(): void { - if (!this.enabled) { - this.teardown() - return - } - this.syncGuard() - const composer = findComposer() - this.composer = composer - if (!composer) { - this.overlay.hideAll() - return - } - this.wire(composer) - this.syncThread() - const text = readComposer(composer) - if (text !== this.lastText) this.handleChange(text) - this.refreshOverlay(composer, text) - } - - override menuEntries(): MenuEntry[] { - return [{ id: 'guard', label: `${this.warnOnClose ? 'Disable' : 'Enable'} Unsent-Text Warning`, action: () => this.toggleGuard() }] - } - - private wire(composer: HTMLElement): void { - if (this.wired.has(composer)) return - this.wired.add(composer) - composer.addEventListener('input', (event) => { - if (event.isTrusted) this.typed.add(this.key) - this.run() - }) - } - - private syncThread(): void { - const key = threadKey() - if (key === this.key) return - window.clearTimeout(this.saveTimer) - this.key = key - this.lastText = '' - } - - private handleChange(text: string): void { - const previous = this.lastText - this.lastText = text - window.clearTimeout(this.saveTimer) - if (!meaningful(text)) { - if (meaningful(previous) && Date.now() - this.sendIntentAt < SEND_WINDOW) this.discard(this.key) - return - } - const key = this.key - this.saveTimer = window.setTimeout(() => this.store.set(key, text), SAVE_DELAY) - } - - private discard(key: string): void { - window.clearTimeout(this.saveTimer) - this.store.remove(key) - this.offered.delete(key) - this.dismissed.add(key) - this.overlay.hideBanner() - } - - private refreshOverlay(composer: HTMLElement, text: string): void { - if (meaningful(text)) this.overlay.showMeter(composer, text, loadSplitterSettings().limit) - else this.overlay.hideMeter() - const key = this.key - if (this.dismissed.has(key) || this.typed.has(key)) { - this.offered.delete(key) - this.overlay.hideBanner() - return - } - const draft = this.offered.get(key) ?? this.store.get(key) - if (!draft) { - this.overlay.hideBanner() - return - } - this.offered.set(key, draft) - this.overlay.showBanner(composer, draft, () => { - this.offered.delete(key) - this.dismissed.add(key) - this.overlay.hideBanner() - void writeComposer(composer, draft.text) - }, () => this.discard(key)) - } - - private isComposerControl(button: HTMLElement): boolean { - const composer = this.composer - if (!composer) return false - const form = composer.closest('form') - if (form) return form.contains(button) - let scope: HTMLElement | null = composer - for (let depth = 0; scope && depth < 4; depth++) { - if (scope.contains(button)) return true - scope = scope.parentElement - } - return false - } - - private readonly handleClick = (event: MouseEvent): void => { - const button = toElement(event.target)?.closest('button') - if (!this.enabled || !button || !isSendButton(button) || !this.isComposerControl(button)) return - this.sendIntentAt = Date.now() - this.dismissed.add(this.key) - this.offered.delete(this.key) - this.overlay.hideBanner() - } - - private readonly handleKeydown = (event: KeyboardEvent): void => { - if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && meaningful(this.lastText)) this.sendIntentAt = Date.now() - } - - private readonly reposition = (): void => { - if (this.composer?.isConnected) this.overlay.position(this.composer) - } - - private readonly handleBeforeUnload = (event: BeforeUnloadEvent): void => { - const composer = this.composer ?? findComposer() - if (!composer || !meaningful(readComposer(composer))) return - event.preventDefault() - event.returnValue = '' - } - - private syncGuard(): void { - if (this.warnOnClose && !this.guardAttached) { - window.addEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = true - } else if (!this.warnOnClose && this.guardAttached) { - window.removeEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = false - } - } - - private toggleGuard(): void { - this.warnOnClose = !this.warnOnClose - this.context.refreshMenu() - this.context.requestUpdate() - } - - private teardown(): void { - this.overlay.hideAll() - if (this.guardAttached) window.removeEventListener('beforeunload', this.handleBeforeUnload) - this.guardAttached = false - } -} diff --git a/ai/perplexity/src/modules/draft-guard/overlay.ts b/ai/perplexity/src/modules/draft-guard/overlay.ts deleted file mode 100644 index de8e6b5..0000000 --- a/ai/perplexity/src/modules/draft-guard/overlay.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { estimateTokens, ensureUiStyles } from '@nolly/ai' -import type { Draft } from './store' -import { ensureDraftStyles } from './styles' - -const WARN_RATIO = 0.7 -const DANGER_RATIO = 0.9 -const GAP = 8 - -const formatAge = (milliseconds: number): string => { - const minutes = Math.floor(milliseconds / 60_000) - if (minutes < 1) return 'just now' - if (minutes < 60) return `${minutes}m ago` - const hours = Math.floor(minutes / 60) - return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago` -} - -export class DraftOverlay { - private readonly meter = markUi(createElement('div', 'bp-draft-meter bp-themed')) - private readonly meterText = createElement('span') - private readonly splitButton = createElement('button', undefined, 'Split') - private readonly banner = markUi(createElement('div', 'bp-draft-banner bp-themed')) - private readonly bannerText = createElement('span') - private readonly restoreButton = createElement('button', undefined, 'Restore') - private readonly discardButton = createElement('button', undefined, 'Discard') - - constructor() { - ensureUiStyles() - ensureDraftStyles() - this.splitButton.type = 'button' - this.splitButton.hidden = true - this.restoreButton.type = 'button' - this.discardButton.type = 'button' - this.meter.append(this.meterText, this.splitButton) - this.banner.append(this.bannerText, this.restoreButton, this.discardButton) - } - - onSplit(handler: () => void): void { - this.splitButton.onclick = handler - } - - showMeter(composer: HTMLElement, text: string, limit: number): void { - const tokens = estimateTokens(text) - const ratio = tokens / limit - const maxChars = Math.round(limit * 4) - this.meterText.textContent = `${text.length.toLocaleString()} / ~${maxChars.toLocaleString()} chars · ~${tokens.toLocaleString()} / ${limit.toLocaleString()} tokens` - this.meter.dataset['level'] = ratio >= DANGER_RATIO ? 'danger' : ratio >= WARN_RATIO ? 'warn' : 'ok' - this.splitButton.hidden = ratio < 1 - this.mount(this.meter) - this.meter.dataset['visible'] = 'true' - this.position(composer) - } - - hideMeter(): void { - this.meter.dataset['visible'] = 'false' - } - - showBanner(composer: HTMLElement, draft: Draft, onRestore: () => void, onDiscard: () => void): void { - this.bannerText.textContent = `Draft from ${formatAge(Date.now() - draft.at)}` - this.restoreButton.onclick = onRestore - this.discardButton.onclick = onDiscard - this.mount(this.banner) - this.banner.dataset['visible'] = 'true' - this.position(composer) - } - - hideBanner(): void { - this.banner.dataset['visible'] = 'false' - } - - position(composer: HTMLElement): void { - const rect = composer.getBoundingClientRect() - const top = Math.max(GAP, rect.top - this.meter.offsetHeight - GAP) - this.meter.style.top = `${top}px` - this.meter.style.left = `${Math.max(GAP, rect.right - this.meter.offsetWidth)}px` - this.banner.style.top = `${top}px` - this.banner.style.left = `${Math.max(GAP, rect.left)}px` - } - - hideAll(): void { - this.hideMeter() - this.hideBanner() - } - - private mount(element: HTMLElement): void { - if (!element.isConnected) document.body.appendChild(element) - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/draft-guard/store.ts b/ai/perplexity/src/modules/draft-guard/store.ts deleted file mode 100644 index 6d3c961..0000000 --- a/ai/perplexity/src/modules/draft-guard/store.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { storage } from '../../core/storage' - -export interface Draft { - text: string - at: number -} - -type Drafts = Record - -const STORAGE_KEY = 'draft-guard:drafts' -const TTL = 30 * 86_400_000 -const MAX_DRAFTS = 50 -const MAX_CHARS = 200_000 - -export class DraftStore { - get(key: string): Draft | null { - const draft = this.read()[key] - return draft && Date.now() - draft.at < TTL ? draft : null - } - - set(key: string, text: string): void { - if (!text.replace(/[\s\u200b]/g, '')) return - const drafts = this.read() - drafts[key] = { text: text.slice(0, MAX_CHARS), at: Date.now() } - this.write(this.prune(drafts)) - } - - remove(key: string): void { - const drafts = this.read() - if (!(key in drafts)) return - delete drafts[key] - this.write(drafts) - } - - private read(): Drafts { - return storage.get(STORAGE_KEY, {}) - } - - private write(drafts: Drafts): void { - storage.set(STORAGE_KEY, drafts) - } - - private prune(drafts: Drafts): Drafts { - const live = Object.entries(drafts).filter(([, draft]) => Date.now() - draft.at < TTL) - live.sort((a, b) => b[1].at - a[1].at) - return Object.fromEntries(live.slice(0, MAX_DRAFTS)) - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/draft-guard/styles.ts b/ai/perplexity/src/modules/draft-guard/styles.ts deleted file mode 100644 index 33e119c..0000000 --- a/ai/perplexity/src/modules/draft-guard/styles.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { injectStyle } from '@nolly/core' - -const CSS = ` -.bp-draft-meter, -.bp-draft-banner { - position: fixed; - z-index: 99990; - display: none; - align-items: center; - gap: 8px; - padding: 4px 10px; - border: 1px solid var(--bp-border); - border-radius: 999px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 4px 14px rgb(0 0 0 / 14%); - font: 11px/1.4 ui-sans-serif, system-ui, sans-serif; - white-space: nowrap; -} - -.bp-draft-meter[data-visible='true'], -.bp-draft-banner[data-visible='true'] { display: inline-flex; } - -.bp-draft-meter[data-level='warn'] { border-color: var(--bp-yellow); color: var(--bp-yellow); } -.bp-draft-meter[data-level='danger'] { border-color: var(--bp-red); color: var(--bp-red); } -.bp-draft-meter button, -.bp-draft-banner button { - padding: 1px 8px; - border: 1px solid var(--bp-border); - border-radius: 999px; - background: transparent; - color: inherit; - font: inherit; - cursor: pointer; -} - -.bp-draft-meter button:hover, -.bp-draft-banner button:hover { background: var(--bp-accent); } -.bp-draft-meter button[hidden] { display: none; } -` - -export const ensureDraftStyles = (): void => injectStyle('better-perplexity-draft-styles', CSS) \ No newline at end of file From 265cd95d4763a14a2089fe5575eb14be2f7c2f9e Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:17:16 +0100 Subject: [PATCH 05/19] feat(ai): hoist Draft Guard into @nolly/ai and enable it in better-chatgpt (step 4) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/config.ts | 2 + ai/chatgpt/src/main.ts | 24 ++- ai/perplexity/CHANGELOG.md | 1 + core/ai/README.md | 2 +- core/ai/src/features/draft-guard/feature.ts | 216 ++++++++++++++++++++ core/ai/src/features/draft-guard/index.ts | 2 + core/ai/src/features/draft-guard/overlay.ts | 90 ++++++++ core/ai/src/features/draft-guard/store.ts | 50 +++++ core/ai/src/features/draft-guard/styles.ts | 43 ++++ 10 files changed, 419 insertions(+), 12 deletions(-) create mode 100644 core/ai/src/features/draft-guard/feature.ts create mode 100644 core/ai/src/features/draft-guard/index.ts create mode 100644 core/ai/src/features/draft-guard/overlay.ts create mode 100644 core/ai/src/features/draft-guard/store.ts create mode 100644 core/ai/src/features/draft-guard/styles.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index 6508835..f6f92fe 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -4,3 +4,4 @@ - Initial skeleton: composer and header detection, response observer, session state and diagnostics. - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. +- Draft Guard: autosaved drafts, size meter and unsent-text warning. diff --git a/ai/chatgpt/src/config.ts b/ai/chatgpt/src/config.ts index 57bd58a..af9156b 100644 --- a/ai/chatgpt/src/config.ts +++ b/ai/chatgpt/src/config.ts @@ -10,3 +10,5 @@ export const OBSERVER_OPTIONS: MutationObserverInit = { attributes: true, attributeFilter: ['class', 'aria-label', 'aria-expanded', 'aria-selected', 'aria-hidden', 'aria-pressed', 'data-state', 'hidden'] } + +export const MESSAGE_TOKEN_LIMIT = 34_000 diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 557bfa1..dfe51fa 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,25 +1,27 @@ -import { EnterAsNewlineFeature, configureUi } from '@nolly/ai' +import { DraftGuardFeature, EnterAsNewlineFeature, configureUi } from '@nolly/ai' import { App } from './app' +import { MESSAGE_TOKEN_LIMIT } from './config' import { uiMarker } from './dom' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' import { composerKit } from './kit' import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' -import './runtime' +import { session } from './runtime' import { installTheme } from './theme' configureUi({ - id: 'better-chatgpt', - title: 'Better ChatGPT', - version: __VERSION__, - marker: uiMarker, - composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) + id: 'better-chatgpt', + title: 'Better ChatGPT', + version: __VERSION__, + marker: uiMarker, + composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) }) installTheme() new App() - .register((context) => new HeaderButtonFeature(context)) - .register((context) => new EnterAsNewlineFeature(context, { storage: context.storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) - .register((context) => new DiagnosticsFeature(context)) - .start() + .register((context) => new HeaderButtonFeature(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage: context.storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) + .register((context) => new DraftGuardFeature(context, { storage: context.storage, composer: composerKit, onSend: (listener) => session.subscribe((event) => { if (event === 'generation-start') listener() }), tokenLimit: () => MESSAGE_TOKEN_LIMIT })) + .register((context) => new DiagnosticsFeature(context)) + .start() diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index c1a10e4..9d1b5bc 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -6,6 +6,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. - Internal: Enter as Newline now comes from the shared package. +- Internal: Draft Guard now comes from the shared package. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/core/ai/README.md b/core/ai/README.md index af14a43..77930ea 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,4 +10,4 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline. +- Feature modules that need only an adapter: Enter as Newline and Draft Guard. diff --git a/core/ai/src/features/draft-guard/feature.ts b/core/ai/src/features/draft-guard/feature.ts new file mode 100644 index 0000000..cbe254e --- /dev/null +++ b/core/ai/src/features/draft-guard/feature.ts @@ -0,0 +1,216 @@ +import { Feature, toElement } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import type { ComposerKit } from '../../composer' +import { isSendButton, readComposer } from '../../composer' +import { DraftOverlay } from './overlay' +import { DraftStore } from './store' +import type { Draft } from './store' + +const SAVE_DELAY = 400 +const SEND_WINDOW = 3_000 +const GUARD_KEY = 'draft-guard:warn-on-close' +const DEFAULT_SPLIT_COMMAND = 'message-splitter:split' + +const defaultThreadKey = (): string => location.pathname || '/' +const meaningful = (text: string): boolean => text.replace(/[\s\u200b]/g, '') !== '' + +export interface DraftGuardOptions { + readonly storage: ScriptStorage + readonly composer: Pick + readonly onSend: (listener: () => void) => () => void + readonly tokenLimit: () => number + readonly threadKey?: () => string + readonly splitCommand?: string +} + +export class DraftGuardFeature extends Feature { + readonly id = 'draft-guard' + readonly name = 'Draft Guard' + readonly description = 'Autosaves drafts, shows a size meter and warns about unsent text.' + + private readonly store: DraftStore + private readonly overlay = new DraftOverlay() + private readonly wired = new WeakSet() + private readonly dismissed = new Set() + private readonly typed = new Set() + private readonly offered = new Map() + private key: string + private lastText = '' + private saveTimer = 0 + private sendIntentAt = 0 + private guardAttached = false + private composer: HTMLElement | null = null + + constructor(context: ScriptContext, private readonly options: DraftGuardOptions) { + super(context) + this.store = new DraftStore(options.storage) + this.key = this.threadKey() + this.overlay.onSplit(() => this.context.runCommand(options.splitCommand ?? DEFAULT_SPLIT_COMMAND)) + options.onSend(() => { + if (this.enabled && meaningful(this.lastText)) this.discard(this.key) + }) + document.addEventListener('click', this.handleClick, true) + document.addEventListener('keydown', this.handleKeydown, true) + window.addEventListener('scroll', this.reposition, true) + window.addEventListener('resize', this.reposition) + } + + get warnOnClose(): boolean { + return this.options.storage.get(GUARD_KEY, true) + } + + set warnOnClose(value: boolean) { + this.options.storage.set(GUARD_KEY, value) + } + + run(): void { + if (!this.enabled) { + this.teardown() + return + } + this.syncGuard() + const composer = this.options.composer.findComposer() + this.composer = composer + if (!composer) { + this.overlay.hideAll() + return + } + this.wire(composer) + this.syncThread() + const text = readComposer(composer) + if (text !== this.lastText) this.handleChange(text) + this.refreshOverlay(composer, text) + } + + override menuEntries(): MenuEntry[] { + return [{ id: 'guard', label: `${this.warnOnClose ? 'Disable' : 'Enable'} Unsent-Text Warning`, action: () => this.toggleGuard() }] + } + + private threadKey(): string { + return (this.options.threadKey ?? defaultThreadKey)() + } + + private wire(composer: HTMLElement): void { + if (this.wired.has(composer)) return + this.wired.add(composer) + composer.addEventListener('input', (event) => { + if (event.isTrusted) this.typed.add(this.key) + this.run() + }) + } + + private syncThread(): void { + const key = this.threadKey() + if (key === this.key) return + window.clearTimeout(this.saveTimer) + this.key = key + this.lastText = '' + } + + private handleChange(text: string): void { + const previous = this.lastText + this.lastText = text + window.clearTimeout(this.saveTimer) + if (!meaningful(text)) { + if (meaningful(previous) && Date.now() - this.sendIntentAt < SEND_WINDOW) this.discard(this.key) + return + } + const key = this.key + this.saveTimer = window.setTimeout(() => this.store.set(key, text), SAVE_DELAY) + } + + private discard(key: string): void { + window.clearTimeout(this.saveTimer) + this.store.remove(key) + this.offered.delete(key) + this.dismissed.add(key) + this.overlay.hideBanner() + } + + private refreshOverlay(composer: HTMLElement, text: string): void { + if (meaningful(text)) this.overlay.showMeter(composer, text, this.options.tokenLimit()) + else this.overlay.hideMeter() + const key = this.key + if (this.dismissed.has(key) || this.typed.has(key)) { + this.offered.delete(key) + this.overlay.hideBanner() + return + } + const draft = this.offered.get(key) ?? this.store.get(key) + if (!draft) { + this.overlay.hideBanner() + return + } + this.offered.set(key, draft) + this.overlay.showBanner( + composer, + draft, + () => { + this.offered.delete(key) + this.dismissed.add(key) + this.overlay.hideBanner() + void this.options.composer.writeComposer(composer, draft.text) + }, + () => this.discard(key) + ) + } + + private isComposerControl(button: HTMLElement): boolean { + const composer = this.composer + if (!composer) return false + const form = composer.closest('form') + if (form) return form.contains(button) + let scope: HTMLElement | null = composer + for (let depth = 0; scope && depth < 4; depth++) { + if (scope.contains(button)) return true + scope = scope.parentElement + } + return false + } + + private readonly handleClick = (event: MouseEvent): void => { + const button = toElement(event.target)?.closest('button') + if (!this.enabled || !button || !isSendButton(button) || !this.isComposerControl(button)) return + this.sendIntentAt = Date.now() + this.dismissed.add(this.key) + this.offered.delete(this.key) + this.overlay.hideBanner() + } + + private readonly handleKeydown = (event: KeyboardEvent): void => { + if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && meaningful(this.lastText)) this.sendIntentAt = Date.now() + } + + private readonly reposition = (): void => { + if (this.composer?.isConnected) this.overlay.position(this.composer) + } + + private readonly handleBeforeUnload = (event: BeforeUnloadEvent): void => { + const composer = this.composer ?? this.options.composer.findComposer() + if (!composer || !meaningful(readComposer(composer))) return + event.preventDefault() + event.returnValue = '' + } + + private syncGuard(): void { + if (this.warnOnClose && !this.guardAttached) { + window.addEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = true + } else if (!this.warnOnClose && this.guardAttached) { + window.removeEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = false + } + } + + private toggleGuard(): void { + this.warnOnClose = !this.warnOnClose + this.context.refreshMenu() + this.context.requestUpdate() + } + + private teardown(): void { + this.overlay.hideAll() + if (this.guardAttached) window.removeEventListener('beforeunload', this.handleBeforeUnload) + this.guardAttached = false + } +} diff --git a/core/ai/src/features/draft-guard/index.ts b/core/ai/src/features/draft-guard/index.ts new file mode 100644 index 0000000..c7b92f5 --- /dev/null +++ b/core/ai/src/features/draft-guard/index.ts @@ -0,0 +1,2 @@ +export { DraftGuardFeature } from './feature' +export type { DraftGuardOptions } from './feature' diff --git a/core/ai/src/features/draft-guard/overlay.ts b/core/ai/src/features/draft-guard/overlay.ts new file mode 100644 index 0000000..a1ffc60 --- /dev/null +++ b/core/ai/src/features/draft-guard/overlay.ts @@ -0,0 +1,90 @@ +import { createElement } from '@nolly/core' +import { estimateTokens } from '../../tokens' +import { markUi } from '../../ui/config' +import { ensureUiStyles } from '../../ui/styles' +import type { Draft } from './store' +import { ensureDraftStyles } from './styles' + +const WARN_RATIO = 0.7 +const DANGER_RATIO = 0.9 +const GAP = 8 + +const formatAge = (milliseconds: number): string => { + const minutes = Math.floor(milliseconds / 60_000) + if (minutes < 1) return 'just now' + if (minutes < 60) return `${minutes}m ago` + const hours = Math.floor(minutes / 60) + return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago` +} + +export class DraftOverlay { + private readonly meter = markUi(createElement('div', 'bp-draft-meter bp-themed')) + private readonly meterText = createElement('span') + private readonly splitButton = createElement('button', undefined, 'Split') + private readonly banner = markUi(createElement('div', 'bp-draft-banner bp-themed')) + private readonly bannerText = createElement('span') + private readonly restoreButton = createElement('button', undefined, 'Restore') + private readonly discardButton = createElement('button', undefined, 'Discard') + + constructor() { + ensureUiStyles() + ensureDraftStyles() + this.splitButton.type = 'button' + this.splitButton.hidden = true + this.restoreButton.type = 'button' + this.discardButton.type = 'button' + this.meter.append(this.meterText, this.splitButton) + this.banner.append(this.bannerText, this.restoreButton, this.discardButton) + } + + onSplit(handler: () => void): void { + this.splitButton.onclick = handler + } + + showMeter(composer: HTMLElement, text: string, limit: number): void { + const tokens = estimateTokens(text) + const ratio = tokens / limit + const maxChars = Math.round(limit * 4) + this.meterText.textContent = `${text.length.toLocaleString()} / ~${maxChars.toLocaleString()} chars · ~${tokens.toLocaleString()} / ${limit.toLocaleString()} tokens` + this.meter.dataset['level'] = ratio >= DANGER_RATIO ? 'danger' : ratio >= WARN_RATIO ? 'warn' : 'ok' + this.splitButton.hidden = ratio < 1 + this.mount(this.meter) + this.meter.dataset['visible'] = 'true' + this.position(composer) + } + + hideMeter(): void { + this.meter.dataset['visible'] = 'false' + } + + showBanner(composer: HTMLElement, draft: Draft, onRestore: () => void, onDiscard: () => void): void { + this.bannerText.textContent = `Draft from ${formatAge(Date.now() - draft.at)}` + this.restoreButton.onclick = onRestore + this.discardButton.onclick = onDiscard + this.mount(this.banner) + this.banner.dataset['visible'] = 'true' + this.position(composer) + } + + hideBanner(): void { + this.banner.dataset['visible'] = 'false' + } + + position(composer: HTMLElement): void { + const rect = composer.getBoundingClientRect() + const top = Math.max(GAP, rect.top - this.meter.offsetHeight - GAP) + this.meter.style.top = `${top}px` + this.meter.style.left = `${Math.max(GAP, rect.right - this.meter.offsetWidth)}px` + this.banner.style.top = `${top}px` + this.banner.style.left = `${Math.max(GAP, rect.left)}px` + } + + hideAll(): void { + this.hideMeter() + this.hideBanner() + } + + private mount(element: HTMLElement): void { + if (!element.isConnected) document.body.appendChild(element) + } +} diff --git a/core/ai/src/features/draft-guard/store.ts b/core/ai/src/features/draft-guard/store.ts new file mode 100644 index 0000000..c2add94 --- /dev/null +++ b/core/ai/src/features/draft-guard/store.ts @@ -0,0 +1,50 @@ +import type { ScriptStorage } from '@nolly/core' + +export interface Draft { + text: string + at: number +} + +type Drafts = Record + +const STORAGE_KEY = 'draft-guard:drafts' +const TTL = 30 * 86_400_000 +const MAX_DRAFTS = 50 +const MAX_CHARS = 200_000 + +export class DraftStore { + constructor(private readonly storage: ScriptStorage) {} + + get(key: string): Draft | null { + const draft = this.read()[key] + return draft && Date.now() - draft.at < TTL ? draft : null + } + + set(key: string, text: string): void { + if (!text.replace(/[\s\u200b]/g, '')) return + const drafts = this.read() + drafts[key] = { text: text.slice(0, MAX_CHARS), at: Date.now() } + this.write(this.prune(drafts)) + } + + remove(key: string): void { + const drafts = this.read() + if (!(key in drafts)) return + delete drafts[key] + this.write(drafts) + } + + private read(): Drafts { + return this.storage.get(STORAGE_KEY, {}) + } + + private write(drafts: Drafts): void { + this.storage.set(STORAGE_KEY, drafts) + } + + private prune(drafts: Drafts): Drafts { + const live = Object.entries(drafts).filter(([, draft]) => Date.now() - draft.at < TTL) + live.sort((a, b) => b[1].at - a[1].at) + return Object.fromEntries(live.slice(0, MAX_DRAFTS)) + } +} diff --git a/core/ai/src/features/draft-guard/styles.ts b/core/ai/src/features/draft-guard/styles.ts new file mode 100644 index 0000000..457e3db --- /dev/null +++ b/core/ai/src/features/draft-guard/styles.ts @@ -0,0 +1,43 @@ +import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' + +const CSS = ` +.bp-draft-meter, +.bp-draft-banner { + position: fixed; + z-index: 99990; + display: none; + align-items: center; + gap: 8px; + padding: 4px 10px; + border: 1px solid var(--bp-border); + border-radius: 999px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 4px 14px rgb(0 0 0 / 14%); + font: 11px/1.4 ui-sans-serif, system-ui, sans-serif; + white-space: nowrap; +} + +.bp-draft-meter[data-visible='true'], +.bp-draft-banner[data-visible='true'] { display: inline-flex; } + +.bp-draft-meter[data-level='warn'] { border-color: var(--bp-yellow); color: var(--bp-yellow); } +.bp-draft-meter[data-level='danger'] { border-color: var(--bp-red); color: var(--bp-red); } +.bp-draft-meter button, +.bp-draft-banner button { + padding: 1px 8px; + border: 1px solid var(--bp-border); + border-radius: 999px; + background: transparent; + color: inherit; + font: inherit; + cursor: pointer; +} + +.bp-draft-meter button:hover, +.bp-draft-banner button:hover { background: var(--bp-accent); } +.bp-draft-meter button[hidden] { display: none; } +` + +export const ensureDraftStyles = (): void => injectStyle(`${uiConfig().id}-draft-styles`, CSS) From 47623b229c540146bf2aa5f1bf49d0a5166c669f Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:25:34 +0100 Subject: [PATCH 06/19] fix(ai): export DraftGuardFeature from the features barrel --- .../src/modules/message-splitter/big-text.ts | 84 ----------- .../src/modules/message-splitter/dialog.ts | 132 ------------------ .../src/modules/message-splitter/index.ts | 129 ----------------- .../src/modules/message-splitter/plan.ts | 34 ----- .../src/modules/message-splitter/runner.ts | 47 ------- .../src/modules/message-splitter/settings.ts | 16 --- .../src/modules/message-splitter/splitter.ts | 120 ---------------- .../src/modules/message-splitter/styles.ts | 28 ---- core/ai/src/features/index.ts | 4 + 9 files changed, 4 insertions(+), 590 deletions(-) delete mode 100644 ai/perplexity/src/modules/message-splitter/big-text.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/dialog.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/index.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/plan.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/runner.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/settings.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/splitter.ts delete mode 100644 ai/perplexity/src/modules/message-splitter/styles.ts diff --git a/ai/perplexity/src/modules/message-splitter/big-text.ts b/ai/perplexity/src/modules/message-splitter/big-text.ts deleted file mode 100644 index 4cecd34..0000000 --- a/ai/perplexity/src/modules/message-splitter/big-text.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { createElement } from '@nolly/core' -import { estimateTokens, createButton, createNumberField, createSelectField, createTextArea, createDialog } from '@nolly/ai' -import { createPartRows, formatNumber, type SplitChoice } from './dialog' -import { planParts, type SplitPlan } from './plan' -import type { SplitterSettings } from './settings' -import { ensureSplitterStyles } from './styles' - -const DIALOG_ID = 'better-perplexity-bigtext-dialog' - -export interface BigTextRequest { - settings: SplitterSettings - onSettings: (settings: SplitterSettings) => void - onInsert: (text: string) => void - onSend: (text: string, choice: SplitChoice) => void -} - -export const openBigTextDialog = ({ settings, onSettings, onInsert, onSend }: BigTextRequest): void => { - if (document.getElementById(DIALOG_ID)) return - ensureSplitterStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Compose a big message', description: 'Paste any amount of text. It is split only if it is too big for one message.', width: 760 }) - const state: SplitterSettings = { ...settings } - let text = '' - let instruction = '' - let plan: SplitPlan = planParts('', '', state.limit, state.balanced) - const area = createTextArea('Paste your message here…', '', (value) => { - text = value - render() - }) - area.rows = 14 - const status = createElement('div', 'bp-split-summary') - const list = createElement('div', 'bp-stack') - const insertButton = createButton('Insert into composer') - const sendButton = createButton('', { primary: true }) - const update = (patch: Partial): void => { - Object.assign(state, patch) - onSettings({ ...state }) - render() - } - const limit = createNumberField({ label: 'Tokens per message', hint: 'Estimate, with a safety margin built in', value: state.limit, min: 500, max: 100_000, step: 100, onChange: (value) => update({ limit: value }) }) - const oversize = createElement('div', 'bp-stack') - oversize.append( - createSelectField('When too big', [ - { value: 'parts', label: 'Send in parts' }, - { value: 'file', label: 'Attach as file (no extra queries)' } - ], state.mode, (value) => update({ mode: value })), - createTextArea('Instruction appended to the last part (optional)', '', (value) => { - instruction = value - render() - }), - list - ) - const render = (): void => { - const tokens = estimateTokens(text) - const oversized = tokens > state.limit - plan = planParts(text, instruction, state.limit, state.balanced) - const count = plan.parts.length - const empty = !text.trim() - oversize.hidden = !oversized - insertButton.hidden = oversized - insertButton.disabled = empty - sendButton.disabled = empty - list.replaceChildren(...(oversized ? createPartRows(plan) : [])) - if (empty) status.textContent = 'Waiting for text…' - else if (!oversized) status.textContent = `~${formatNumber(tokens)} tokens: fits in one message (limit ${formatNumber(state.limit)}).` - else status.textContent = `~${formatNumber(tokens)} tokens: too big for one message. ${state.mode === 'file' ? 'It will be attached as a file.' : `It will be sent as ${count} parts, and each part uses one query.`}` - sendButton.textContent = oversized ? (state.mode === 'file' ? 'Attach as file' : `Send ${count} parts`) : 'Send' - } - insertButton.addEventListener('click', () => { - ui.close() - onInsert(text) - }) - sendButton.addEventListener('click', () => { - const oversized = estimateTokens(text) > state.limit - ui.close() - onSend(text, { mode: oversized ? state.mode : 'parts', plan, instruction }) - }) - const stack = createElement('div', 'bp-stack') - stack.append(area, status, limit.wrapper, oversize) - ui.body.appendChild(stack) - ui.footer.append(createButton('Cancel', { onClick: ui.close }), insertButton, sendButton) - render() - ui.show() - area.focus() -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/dialog.ts b/ai/perplexity/src/modules/message-splitter/dialog.ts deleted file mode 100644 index 3e46d5a..0000000 --- a/ai/perplexity/src/modules/message-splitter/dialog.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { estimateTokens, createButton, createNumberField, createSelectField, createSwitch, createTextArea, createDialog, ensureUiStyles } from '@nolly/ai' -import { planParts, type SplitPlan } from './plan' -import type { PartStatus } from './runner' -import type { SplitterSettings } from './settings' -import { ensureSplitterStyles } from './styles' - -const DIALOG_ID = 'better-perplexity-splitter-dialog' -const PREVIEW_CHARS = 6_000 - -export interface SplitChoice { - mode: SplitterSettings['mode'] - plan: SplitPlan - instruction: string -} - -export interface SplitDialogRequest { - text: string - settings: SplitterSettings - onSettings: (settings: SplitterSettings) => void - onConfirm: (choice: SplitChoice) => void -} - -export const formatNumber = (value: number): string => value.toLocaleString() - -export const createPartRows = (plan: SplitPlan): HTMLElement[] => - plan.parts.map((part, index) => { - const details = createElement('details', 'bp-split-part') - const head = createElement('summary') - head.append(createElement('span', undefined, `Part ${index + 1}`), createElement('span', 'bp-data-label', `${formatNumber(plan.tokens[index] ?? 0)} tokens`)) - details.append(head, createElement('pre', undefined, part.length > PREVIEW_CHARS ? `${part.slice(0, PREVIEW_CHARS)}\n…` : part)) - return details - }) - -export const openSplitDialog = ({ text, settings, onSettings, onConfirm }: SplitDialogRequest): void => { - if (document.getElementById(DIALOG_ID)) return - const ui = createDialog({ id: DIALOG_ID, title: 'Message splitter', description: `This message is about ${formatNumber(estimateTokens(text))} tokens.`, width: 640 }) - const state: SplitterSettings = { ...settings } - let instruction = '' - let plan: SplitPlan = planParts(text, instruction, state.limit, state.balanced) - const summary = createElement('div', 'bp-split-summary') - const list = createElement('div', 'bp-stack') - const confirm = createButton('', { primary: true }) - const render = (): void => { - plan = planParts(text, instruction, state.limit, state.balanced) - const count = plan.parts.length - summary.textContent = `${count} ${count === 1 ? 'part' : 'parts'} · limit ${formatNumber(state.limit)} tokens each. Every part sent uses one query.` - list.replaceChildren(...createPartRows(plan)) - confirm.textContent = state.mode === 'file' ? 'Attach as file' : count > 1 ? `Send ${count} parts` : 'Send' - } - const update = (patch: Partial): void => { - Object.assign(state, patch) - onSettings({ ...state }) - render() - } - const limit = createNumberField({ label: 'Tokens per part', hint: 'Estimate, with a safety margin built in', value: state.limit, min: 500, max: 100_000, step: 100, onChange: (value) => update({ limit: value }) }) - const mode = createSelectField('Mode', [ - { value: 'parts', label: 'Send in parts' }, - { value: 'file', label: 'Attach as file (no extra queries)' } - ], state.mode, (value) => update({ mode: value })) - const auto = createSwitch({ label: 'Offer to split when sending an oversized message', checked: state.autoIntercept, onChange: (value) => update({ autoIntercept: value }) }) - const finalInstruction = createTextArea('Instruction appended to the last part (optional)', '', (value) => { - instruction = value - render() - }) - const options = createElement('div', 'bp-stack') - options.append(limit.wrapper, mode, auto.wrapper, finalInstruction) - ui.body.append(options, createElement('div', 'bp-hint'), summary, list) - confirm.addEventListener('click', () => { - ui.close() - onConfirm({ mode: state.mode, plan, instruction }) - }) - ui.footer.append(createButton('Cancel', { onClick: ui.close }), confirm) - render() - ui.show() -} - -const STATUS_TEXT: Readonly> = { sending: 'sending', waiting: 'waiting for the reply', done: 'done' } - -export class ProgressPanel { - private readonly element = markUi(createElement('div', 'bp-split-panel bp-themed')) - private readonly label = createElement('div') - private readonly fill = createElement('div', 'bp-progress-fill') - private readonly cancel = createButton('Cancel') - private timer = 0 - - constructor() { - ensureUiStyles() - ensureSplitterStyles() - const bar = createElement('div', 'bp-progress') - bar.appendChild(this.fill) - this.element.append(this.label, bar, this.cancel) - } - - show(total: number, onCancel: () => void): void { - this.cancel.hidden = false - this.cancel.onclick = onCancel - this.fill.style.width = '0%' - this.label.textContent = `Preparing ${total} parts…` - this.mount() - } - - update(index: number, total: number, status: PartStatus): void { - this.label.textContent = `Part ${index + 1}/${total}: ${STATUS_TEXT[status]}` - this.fill.style.width = `${(((index + (status === 'done' ? 1 : 0.5)) / total) * 100).toFixed(0)}%` - } - - finish(message: string): void { - this.label.textContent = message - this.cancel.hidden = true - this.autoHide(4_000) - } - - notify(message: string): void { - this.label.textContent = message - this.fill.style.width = '0%' - this.cancel.hidden = true - this.mount() - this.autoHide(3_500) - } - - private mount(): void { - window.clearTimeout(this.timer) - if (!this.element.isConnected) document.body.appendChild(this.element) - } - - private autoHide(ms: number): void { - window.clearTimeout(this.timer) - this.timer = window.setTimeout(() => this.element.remove(), ms) - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/index.ts b/ai/perplexity/src/modules/message-splitter/index.ts deleted file mode 100644 index d55c775..0000000 --- a/ai/perplexity/src/modules/message-splitter/index.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { attachFile, editableFrom, findComposer, writeComposer } from '../../core/composer' -import { isSendButton, readComposer, estimateTokens, ComposerButton, isAutomating } from '@nolly/ai' -import { Feature, type MenuEntry, toElement, waitFor } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { ProgressPanel, openSplitDialog, type SplitChoice } from './dialog' -import { SendRunner } from './runner' -import { loadSplitterSettings, saveSplitterSettings, type SplitterSettings } from './settings' -import { openBigTextDialog } from './big-text' - -export class MessageSplitterModule extends Feature { - readonly id = 'message-splitter' - readonly name = 'Message Splitter' - readonly description = 'Splits oversized prompts into ordered parts, or attaches them as a file.' - - private settings: SplitterSettings = loadSplitterSettings() - private readonly runner = new SendRunner() - private readonly panel = new ProgressPanel() - private attached = false - private readonly bigButton = new ComposerButton('Compose big message', 'file', 'Paste a large message. It is split only if needed.', () => this.openBig(), { id: 'big' }) - - run(): void { - if (this.enabled) this.bigButton.mount() - else this.bigButton.unmount() - if (this.enabled && !this.attached) { - document.addEventListener('keydown', this.handleKeydown, true) - document.addEventListener('click', this.handleClick, true) - this.attached = true - return - } - if (!this.enabled && this.attached) { - document.removeEventListener('keydown', this.handleKeydown, true) - document.removeEventListener('click', this.handleClick, true) - this.attached = false - } - } - - override menuEntries(): MenuEntry[] { - return [ - { id: 'big', label: 'Compose Big Message…', action: () => this.openBig() }, - { id: 'split', label: 'Split Composer Text…', action: () => this.open() }, - { label: `${this.settings.autoIntercept ? 'Disable' : 'Enable'} Auto-Split on Send`, action: () => this.saveSettings({ ...this.settings, autoIntercept: !this.settings.autoIntercept }) } - ] - } - - private saveSettings(settings: SplitterSettings): void { - this.settings = settings - saveSplitterSettings(settings) - this.context.refreshMenu() - } - - private isOversized(editable: HTMLElement): boolean { - return this.settings.autoIntercept && estimateTokens(readComposer(editable)) > this.settings.limit - } - - private readonly handleKeydown = (event: KeyboardEvent): void => { - if (this.runner.active || isAutomating() || event.key !== 'Enter' || event.shiftKey || event.isComposing) return - const editable = editableFrom(event.target) - if (!editable || isOwnUi(editable) || !this.isOversized(editable)) return - event.preventDefault() - event.stopImmediatePropagation() - this.open() - } - - private readonly handleClick = (event: MouseEvent): void => { - if (this.runner.active || isAutomating() || !this.settings.autoIntercept) return - const button = toElement(event.target)?.closest('button') - if (!button || isOwnUi(button) || !isSendButton(button)) return - const composer = findComposer() - if (!composer || !this.isOversized(composer)) return - event.preventDefault() - event.stopImmediatePropagation() - this.open() - } - - private open(): void { - const composer = findComposer() - const text = composer ? readComposer(composer) : '' - if (!text.trim()) { - this.panel.notify('The composer is empty.') - return - } - openSplitDialog({ - text, - settings: this.settings, - onSettings: (settings) => this.saveSettings(settings), - onConfirm: (choice) => void this.execute(text, choice) - }) - } - - private async execute(text: string, { mode, plan, instruction }: SplitChoice): Promise { - if (mode === 'file') { - await this.attachAsFile(text, instruction) - return - } - const total = plan.parts.length - this.panel.show(total, () => this.runner.cancel()) - const result = await this.runner.run(plan.parts, (index, status) => this.panel.update(index, total, status)) - this.panel.finish(result === 'done' ? 'All parts sent.' : result === 'cancelled' ? 'Cancelled.' : 'Stopped: a part could not be written or sent.') - } - - private async attachAsFile(text: string, instruction: string): Promise { - const composer = findComposer() - if (!composer) { - this.panel.notify('No composer found.') - return - } - const attached = attachFile(composer, new File([text], 'message.txt', { type: 'text/plain' })) - await writeComposer(composer, instruction.trim()) - this.panel.notify(attached ? 'File attached. Add your question and send.' : 'Could not attach the file automatically.') - } - - private openBig(): void { - openBigTextDialog({ - settings: this.settings, - onSettings: (settings) => this.saveSettings(settings), - onInsert: (text) => void this.insert(text), - onSend: (text, choice) => void this.execute(text, choice) - }) - } - - private async insert(text: string): Promise { - const composer = await waitFor(findComposer, { timeout: 5_000 }) - if (!composer) { - this.panel.notify('No composer found.') - return - } - this.panel.notify((await writeComposer(composer, text)) ? 'Inserted into the composer.' : 'Could not insert the text.') - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/plan.ts b/ai/perplexity/src/modules/message-splitter/plan.ts deleted file mode 100644 index 945e469..0000000 --- a/ai/perplexity/src/modules/message-splitter/plan.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { estimateTokens } from '@nolly/ai' -import { splitText } from './splitter' - -export interface PartTemplates { - readonly header: string - readonly final: string -} - -export const DEFAULT_TEMPLATES: PartTemplates = { - header: '[Part {{index}}/{{total}}] I am sending one long message in {{total}} parts. Do not answer yet. Reply only with "OK" until the final part.', - final: '[Part {{index}}/{{total}} - final] This is the last part. The full message is now complete; respond to all parts now.' -} - -export interface SplitPlan { - parts: string[] - tokens: number[] - total: number -} - -const fill = (template: string, index: number, total: number): string => template.replace(/\{\{index\}\}/g, String(index)).replace(/\{\{total\}\}/g, String(total)) - -export const planParts = (text: string, instruction: string, limit: number, balanced: boolean, templates: PartTemplates = DEFAULT_TEMPLATES): SplitPlan => { - const total = estimateTokens(text) - const tail = instruction.trim() ? `\n\n${instruction.trim()}` : '' - if (total + estimateTokens(tail) <= limit) { - const only = `${text}${tail}` - return { parts: [only], tokens: [estimateTokens(only)], total } - } - const overhead = estimateTokens(templates.header) + estimateTokens(templates.final) + estimateTokens(tail) + 24 - const raw = splitText(text, { budget: Math.max(200, limit - overhead), balanced }) - const count = raw.length - const parts = raw.map((chunk, index) => index === count - 1 ? `${fill(templates.final, index + 1, count)}\n\n${chunk}${tail}` : `${fill(templates.header, index + 1, count)}\n\n${chunk}`) - return { parts, tokens: parts.map((part) => estimateTokens(part)), total } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/runner.ts b/ai/perplexity/src/modules/message-splitter/runner.ts deleted file mode 100644 index 76e459b..0000000 --- a/ai/perplexity/src/modules/message-splitter/runner.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { waitForResponse } from '../../core/generation' -import { logger } from '../../core/logger' -import { isAbort, waitFor } from '@nolly/core' - -export type PartStatus = 'sending' | 'waiting' | 'done' -export type RunResult = 'done' | 'cancelled' | 'failed' - -export class SendRunner { - private controller: AbortController | null = null - - get active(): boolean { - return this.controller !== null - } - - cancel(): void { - this.controller?.abort() - } - - async run(parts: readonly string[], onStatus: (index: number, status: PartStatus) => void): Promise { - if (this.controller) return 'failed' - const controller = new AbortController() - this.controller = controller - const { signal } = controller - try { - for (let index = 0; index < parts.length; index++) { - onStatus(index, 'sending') - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) - if (!composer) return 'failed' - if (!(await writeComposer(composer, parts[index]!))) return 'failed' - if (!(await sendComposer(composer))) return 'failed' - if (index < parts.length - 1) { - onStatus(index, 'waiting') - await waitForResponse({ signal }) - } - onStatus(index, 'done') - } - return 'done' - } catch (error) { - if (isAbort(error)) return 'cancelled' - logger.error('Message splitter run failed.', error) - return 'failed' - } finally { - this.controller = null - } - } -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/settings.ts b/ai/perplexity/src/modules/message-splitter/settings.ts deleted file mode 100644 index ecd1531..0000000 --- a/ai/perplexity/src/modules/message-splitter/settings.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { storage } from '../../core/storage' - -export interface SplitterSettings { - limit: number - autoIntercept: boolean - balanced: boolean - mode: 'parts' | 'file' -} - -const STORAGE_KEY = 'message-splitter:settings' - -export const DEFAULT_SPLITTER_SETTINGS: Readonly = { limit: 7_500, autoIntercept: true, balanced: true, mode: 'parts' } - -export const loadSplitterSettings = (): SplitterSettings => ({ ...DEFAULT_SPLITTER_SETTINGS, ...storage.get>(STORAGE_KEY, {}) }) - -export const saveSplitterSettings = (settings: SplitterSettings): void => storage.set(STORAGE_KEY, settings) \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/splitter.ts b/ai/perplexity/src/modules/message-splitter/splitter.ts deleted file mode 100644 index 454bf7e..0000000 --- a/ai/perplexity/src/modules/message-splitter/splitter.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { estimateTokens } from '@nolly/ai' - -interface CodeAtom { - kind: 'code' - open: string - close: string - body: string[] -} - -interface TextAtom { - kind: 'text' - lines: string[] -} - -type Atom = CodeAtom | TextAtom - -export interface SplitOptions { - budget: number - balanced: boolean -} - -const FENCE_OPEN = /^\s*(`{3,}|~{3,})/ -const SENTENCE_BREAK = /(?<=[.!?])\s+/ -const CHARS_PER_TOKEN = 3 - -const atomText = (atom: Atom): string => (atom.kind === 'code' ? [atom.open, ...atom.body, atom.close].join('\n') : atom.lines.join('\n')) -const atomTokens = (atom: Atom): number => estimateTokens(atomText(atom)) - -export const parseAtoms = (text: string): Atom[] => { - const atoms: Atom[] = [] - let paragraph: string[] = [] - let fence: { open: string; marker: string; body: string[] } | null = null - const flush = (): void => { - if (paragraph.length) atoms.push({ kind: 'text', lines: paragraph }) - paragraph = [] - } - for (const line of text.replace(/\r\n?/g, '\n').split('\n')) { - if (fence) { - const trimmed = line.trim() - if (trimmed.startsWith(fence.marker) && /^[`~]+$/.test(trimmed)) { - atoms.push({ kind: 'code', open: fence.open, close: trimmed, body: fence.body }) - fence = null - } else { - fence.body.push(line) - } - continue - } - const opening = FENCE_OPEN.exec(line) - if (opening) { - flush() - fence = { open: line.trim(), marker: opening[1]!, body: [] } - continue - } - if (line.trim() === '') flush() - else paragraph.push(line) - } - flush() - if (fence) atoms.push({ kind: 'code', open: fence.open, close: fence.marker, body: fence.body }) - return atoms -} - -const hardSplit = (text: string, budget: number): string[] => { - const size = Math.max(40, Math.floor(budget * CHARS_PER_TOKEN)) - const pieces: string[] = [] - for (let index = 0; index < text.length; index += size) pieces.push(text.slice(index, index + size)) - return pieces -} - -const pack = (units: readonly string[], budget: number, joiner: string, asCode: boolean): string[] => { - const chunks: string[] = [] - let current: string[] = [] - let used = 0 - const flush = (): void => { - if (current.length) chunks.push(current.join(joiner)) - current = [] - used = 0 - } - for (const unit of units.flatMap((entry) => (estimateTokens(entry, asCode) > budget ? hardSplit(entry, budget) : [entry]))) { - const size = estimateTokens(unit, asCode) + 1 - if (current.length && used + size > budget) flush() - current.push(unit) - used += size - } - flush() - return chunks -} - -const splitOversized = (atom: Atom, budget: number): Atom[] => { - if (atom.kind === 'code') { - const room = Math.max(40, budget - estimateTokens(`${atom.open}\n${atom.close}`, true)) - return pack(atom.body, room, '\n', true).map((chunk): Atom => ({ kind: 'code', open: atom.open, close: atom.close, body: chunk.split('\n') })) - } - const single = atom.lines.length === 1 - const units = single ? (atom.lines[0] ?? '').split(SENTENCE_BREAK) : atom.lines - return pack(units, budget, single ? ' ' : '\n', false).map((chunk): Atom => ({ kind: 'text', lines: [chunk] })) -} - -export const splitText = (text: string, { budget, balanced }: SplitOptions): string[] => { - const atoms = parseAtoms(text).flatMap((atom) => (atomTokens(atom) > budget ? splitOversized(atom, budget) : [atom])) - if (!atoms.length) return [] - const sizes = atoms.map((atom) => atomTokens(atom) + 2) - const total = sizes.reduce((sum, size) => sum + size, 0) - const count = Math.max(1, Math.ceil(total / budget)) - const cap = balanced ? Math.min(budget, Math.ceil((total / count) * 1.15)) : budget - const parts: string[][] = [] - let current: string[] = [] - let used = 0 - atoms.forEach((atom, index) => { - const size = sizes[index]! - if (current.length && used + size > cap) { - parts.push(current) - current = [] - used = 0 - } - current.push(atomText(atom)) - used += size - }) - if (current.length) parts.push(current) - return parts.map((part) => part.join('\n\n')) -} \ No newline at end of file diff --git a/ai/perplexity/src/modules/message-splitter/styles.ts b/ai/perplexity/src/modules/message-splitter/styles.ts deleted file mode 100644 index 2b13b51..0000000 --- a/ai/perplexity/src/modules/message-splitter/styles.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { injectStyle } from '@nolly/core' - -const CSS = ` -.bp-split-summary { margin-bottom: 12px; color: var(--bp-muted); font-size: 12px; } -.bp-split-part { border: 1px solid var(--bp-border); border-radius: 10px; } -.bp-split-part summary { display: flex; justify-content: space-between; gap: 12px; padding: 8px 12px; cursor: pointer; } -.bp-split-part pre { max-height: 220px; margin: 0 12px 12px; padding: 10px; overflow: auto; border-radius: 8px; background: var(--bp-accent); font: 11px/1.5 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word; } - -.bp-split-panel { - position: fixed; - right: 20px; - bottom: 20px; - z-index: 100000; - display: flex; - flex-direction: column; - gap: 8px; - width: 280px; - padding: 12px 14px; - border: 1px solid var(--bp-border); - border-radius: 12px; - background: var(--bp-bg); - color: var(--bp-fg); - box-shadow: 0 12px 32px rgb(0 0 0 / 22%); - font-size: 12px; -} -` - -export const ensureSplitterStyles = (): void => injectStyle('better-perplexity-splitter-styles', CSS) \ No newline at end of file diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index a7cc04a..0f8e092 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -1,2 +1,6 @@ +export { DraftGuardFeature } from './draft-guard' +export type { DraftGuardOptions } from './draft-guard' export { EnterAsNewlineFeature } from './enter-as-newline' export type { EnterAsNewlineOptions } from './enter-as-newline' +export { MessageSplitterFeature, loadSplitterSettings } from './message-splitter' +export type { MessageSplitterOptions, SplitterSettings } from './message-splitter' From 99edbdb06f51b2a37f79272ceaf1df98b2c250f0 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:25:34 +0100 Subject: [PATCH 07/19] feat(ai): hoist Message Splitter into @nolly/ai and enable it in better-chatgpt (step 5) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/config.ts | 6 +- ai/chatgpt/src/kit.ts | 4 +- ai/chatgpt/src/main.ts | 10 +- ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/src/core/composer.ts | 3 +- ai/perplexity/src/core/generation.ts | 3 +- ai/perplexity/src/main.ts | 11 +- core/ai/README.md | 2 +- .../src/features/message-splitter/big-text.ts | 88 ++++++++++ .../src/features/message-splitter/dialog.ts | 136 +++++++++++++++ .../src/features/message-splitter/feature.ts | 159 ++++++++++++++++++ .../ai/src/features/message-splitter/index.ts | 4 + core/ai/src/features/message-splitter/plan.ts | 34 ++++ .../src/features/message-splitter/runner.ts | 56 ++++++ .../src/features/message-splitter/settings.ts | 20 +++ .../src/features/message-splitter/splitter.ts | 120 +++++++++++++ .../src/features/message-splitter/styles.ts | 29 ++++ 18 files changed, 671 insertions(+), 16 deletions(-) create mode 100644 core/ai/src/features/message-splitter/big-text.ts create mode 100644 core/ai/src/features/message-splitter/dialog.ts create mode 100644 core/ai/src/features/message-splitter/feature.ts create mode 100644 core/ai/src/features/message-splitter/index.ts create mode 100644 core/ai/src/features/message-splitter/plan.ts create mode 100644 core/ai/src/features/message-splitter/runner.ts create mode 100644 core/ai/src/features/message-splitter/settings.ts create mode 100644 core/ai/src/features/message-splitter/splitter.ts create mode 100644 core/ai/src/features/message-splitter/styles.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index f6f92fe..dabf77c 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -5,3 +5,4 @@ - Initial skeleton: composer and header detection, response observer, session state and diagnostics. - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. - Draft Guard: autosaved drafts, size meter and unsent-text warning. +- Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). diff --git a/ai/chatgpt/src/config.ts b/ai/chatgpt/src/config.ts index af9156b..268bddf 100644 --- a/ai/chatgpt/src/config.ts +++ b/ai/chatgpt/src/config.ts @@ -1,8 +1,12 @@ +import type { SplitterSettings } from '@nolly/ai' + export const CONFIG = { initializationDelay: 500, safetyInterval: 2_000 } as const +export const SPLITTER_DEFAULTS: Partial = { limit: 30_000 } + export const OBSERVER_OPTIONS: MutationObserverInit = { childList: true, subtree: true, @@ -10,5 +14,3 @@ export const OBSERVER_OPTIONS: MutationObserverInit = { attributes: true, attributeFilter: ['class', 'aria-label', 'aria-expanded', 'aria-selected', 'aria-hidden', 'aria-pressed', 'data-state', 'hidden'] } - -export const MESSAGE_TOKEN_LIMIT = 34_000 diff --git a/ai/chatgpt/src/kit.ts b/ai/chatgpt/src/kit.ts index 9205a25..3bee2a5 100644 --- a/ai/chatgpt/src/kit.ts +++ b/ai/chatgpt/src/kit.ts @@ -1,5 +1,7 @@ -import { createComposerKit, createPromptSender } from '@nolly/ai' +import { createComposerKit, createGenerationKit, createPromptSender } from '@nolly/ai' import { chatgptAdapter } from './adapter' +import { session } from './runtime' export const composerKit = createComposerKit(chatgptAdapter) +export const generationKit = createGenerationKit({ adapter: chatgptAdapter, isStreaming: () => session.generating }) export const sendPrompt = createPromptSender(composerKit) diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index dfe51fa..79c64df 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,10 +1,11 @@ -import { DraftGuardFeature, EnterAsNewlineFeature, configureUi } from '@nolly/ai' +import { DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './app' -import { MESSAGE_TOKEN_LIMIT } from './config' +import { fileBudget } from './budget' +import { SPLITTER_DEFAULTS } from './config' import { uiMarker } from './dom' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' -import { composerKit } from './kit' +import { composerKit, generationKit } from './kit' import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' import { session } from './runtime' import { installTheme } from './theme' @@ -22,6 +23,7 @@ installTheme() new App() .register((context) => new HeaderButtonFeature(context)) .register((context) => new EnterAsNewlineFeature(context, { storage: context.storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) - .register((context) => new DraftGuardFeature(context, { storage: context.storage, composer: composerKit, onSend: (listener) => session.subscribe((event) => { if (event === 'generation-start') listener() }), tokenLimit: () => MESSAGE_TOKEN_LIMIT })) + .register((context) => new MessageSplitterFeature(context, { storage: context.storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) + .register((context) => new DraftGuardFeature(context, { storage: context.storage, composer: composerKit, onSend: (listener) => session.subscribe((event) => { if (event === 'generation-start') listener() }), tokenLimit: () => loadSplitterSettings(context.storage, SPLITTER_DEFAULTS).limit })) .register((context) => new DiagnosticsFeature(context)) .start() diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 9d1b5bc..19c2e8a 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -7,6 +7,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. - Internal: Enter as Newline now comes from the shared package. - Internal: Draft Guard now comes from the shared package. +- Internal: Message Splitter now comes from the shared package. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/ai/perplexity/src/core/composer.ts b/ai/perplexity/src/core/composer.ts index e006791..2b0c20b 100644 --- a/ai/perplexity/src/core/composer.ts +++ b/ai/perplexity/src/core/composer.ts @@ -1,4 +1,5 @@ import { createComposerKit } from '@nolly/ai' import { isOwnUi } from './dom' -export const { editableFrom, findComposer, writeComposer, sendComposer, attachFile } = createComposerKit({ isOwnUi }) +export const composerKit = createComposerKit({ isOwnUi }) +export const { editableFrom, findComposer, writeComposer, sendComposer, attachFile } = composerKit diff --git a/ai/perplexity/src/core/generation.ts b/ai/perplexity/src/core/generation.ts index 88ebd07..8652a2a 100644 --- a/ai/perplexity/src/core/generation.ts +++ b/ai/perplexity/src/core/generation.ts @@ -1,4 +1,5 @@ import { createGenerationKit } from '@nolly/ai' import { isOwnUi } from './dom' -export const { isGenerating, waitForResponse } = createGenerationKit({ adapter: { isOwnUi } }) +export const generationKit = createGenerationKit({ adapter: { isOwnUi } }) +export const { isGenerating, waitForResponse } = generationKit diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index 8a3ab3d..e9ed731 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,8 +1,9 @@ -import { DraftGuardFeature, EnterAsNewlineFeature, configureUi } from '@nolly/ai' +import { DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' -import { findComposer, writeComposer } from './core/composer' +import { composerKit, findComposer, writeComposer } from './core/composer' import { uiMarker } from './core/dom' import { fetchSpy } from './core/fetch-spy' +import { generationKit } from './core/generation' import { isAskRequest } from './core/requests' import { storage } from './core/storage' import { findComposerActions } from './locate' @@ -12,8 +13,6 @@ import { CommandPaletteModule } from './modules/command-palette' import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' import { MaxWidthModule } from './modules/max-width' -import { MessageSplitterModule } from './modules/message-splitter' -import { loadSplitterSettings } from './modules/message-splitter/settings' import { PromptLibraryModule } from './modules/prompt-library' import { PromptQueueModule } from './modules/prompt-queue' import { RecallModule } from './modules/recall' @@ -31,9 +30,9 @@ new App() .register((context) => new MaxWidthModule(context)) .register((context) => new EnterAsNewlineFeature(context, { storage })) .register((context) => new CodeBlocksModule(context)) - .register((context) => new MessageSplitterModule(context)) + .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit })) .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend: (listener) => fetchSpy.subscribe(({ method, url }) => { if (isAskRequest(method, url)) listener() }), tokenLimit: () => loadSplitterSettings().limit })) + .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend: (listener) => fetchSpy.subscribe(({ method, url }) => { if (isAskRequest(method, url)) listener() }), tokenLimit: () => loadSplitterSettings(storage).limit })) .register((context) => new CommandPaletteModule(context)) .register((context) => new ExporterModule(context)) .register((context) => new UsageStatusModule(context)) diff --git a/core/ai/README.md b/core/ai/README.md index 77930ea..3e387dd 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,4 +10,4 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline and Draft Guard. +- Feature modules that need only an adapter: Enter as Newline, Draft Guard, and Message Splitter. diff --git a/core/ai/src/features/message-splitter/big-text.ts b/core/ai/src/features/message-splitter/big-text.ts new file mode 100644 index 0000000..dee3225 --- /dev/null +++ b/core/ai/src/features/message-splitter/big-text.ts @@ -0,0 +1,88 @@ +import { createElement } from '@nolly/core' +import { estimateTokens } from '../../tokens' +import { uiConfig } from '../../ui/config' +import { createButton, createNumberField, createSelectField, createTextArea } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' +import { createPartRows, formatNumber } from './dialog' +import type { SplitChoice } from './dialog' +import { planParts } from './plan' +import type { SplitPlan } from './plan' +import type { SplitterSettings } from './settings' +import { ensureSplitterStyles } from './styles' + +export interface BigTextRequest { + settings: SplitterSettings + onSettings: (settings: SplitterSettings) => void + onInsert: (text: string) => void + onSend: (text: string, choice: SplitChoice) => void +} + +export const openBigTextDialog = ({ settings, onSettings, onInsert, onSend }: BigTextRequest): void => { + const dialogId = `${uiConfig().id}-bigtext-dialog` + if (document.getElementById(dialogId)) return + ensureSplitterStyles() + const ui = createDialog({ id: dialogId, title: 'Compose a big message', description: 'Paste any amount of text. It is split only if it is too big for one message.', width: 760 }) + const state: SplitterSettings = { ...settings } + let text = '' + let instruction = '' + let plan: SplitPlan = planParts('', '', state.limit, state.balanced) + const area = createTextArea('Paste your message here…', '', (value) => { + text = value + render() + }) + area.rows = 14 + const status = createElement('div', 'bp-split-summary') + const list = createElement('div', 'bp-stack') + const insertButton = createButton('Insert into composer') + const sendButton = createButton('', { primary: true }) + const update = (patch: Partial): void => { + Object.assign(state, patch) + onSettings({ ...state }) + render() + } + const limit = createNumberField({ label: 'Tokens per message', hint: 'Estimate, with a safety margin built in', value: state.limit, min: 500, max: 100_000, step: 100, onChange: (value) => update({ limit: value }) }) + const oversize = createElement('div', 'bp-stack') + oversize.append( + createSelectField('When too big', [ + { value: 'parts', label: 'Send in parts' }, + { value: 'file', label: 'Attach as file (no extra queries)' } + ], state.mode, (value) => update({ mode: value })), + createTextArea('Instruction appended to the last part (optional)', '', (value) => { + instruction = value + render() + }), + list + ) + const render = (): void => { + const tokens = estimateTokens(text) + const oversized = tokens > state.limit + plan = planParts(text, instruction, state.limit, state.balanced) + const count = plan.parts.length + const empty = !text.trim() + oversize.hidden = !oversized + insertButton.hidden = oversized + insertButton.disabled = empty + sendButton.disabled = empty + list.replaceChildren(...(oversized ? createPartRows(plan) : [])) + if (empty) status.textContent = 'Waiting for text…' + else if (!oversized) status.textContent = `~${formatNumber(tokens)} tokens: fits in one message (limit ${formatNumber(state.limit)}).` + else status.textContent = `~${formatNumber(tokens)} tokens: too big for one message. ${state.mode === 'file' ? 'It will be attached as a file.' : `It will be sent as ${count} parts, and each part uses one query.`}` + sendButton.textContent = oversized ? (state.mode === 'file' ? 'Attach as file' : `Send ${count} parts`) : 'Send' + } + insertButton.addEventListener('click', () => { + ui.close() + onInsert(text) + }) + sendButton.addEventListener('click', () => { + const oversized = estimateTokens(text) > state.limit + ui.close() + onSend(text, { mode: oversized ? state.mode : 'parts', plan, instruction }) + }) + const stack = createElement('div', 'bp-stack') + stack.append(area, status, limit.wrapper, oversize) + ui.body.appendChild(stack) + ui.footer.append(createButton('Cancel', { onClick: ui.close }), insertButton, sendButton) + render() + ui.show() + area.focus() +} diff --git a/core/ai/src/features/message-splitter/dialog.ts b/core/ai/src/features/message-splitter/dialog.ts new file mode 100644 index 0000000..2dc2f9a --- /dev/null +++ b/core/ai/src/features/message-splitter/dialog.ts @@ -0,0 +1,136 @@ +import { createElement } from '@nolly/core' +import { estimateTokens } from '../../tokens' +import { markUi, uiConfig } from '../../ui/config' +import { createButton, createNumberField, createSelectField, createSwitch, createTextArea } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' +import { ensureUiStyles } from '../../ui/styles' +import { planParts } from './plan' +import type { SplitPlan } from './plan' +import type { PartStatus } from './runner' +import type { SplitterSettings } from './settings' +import { ensureSplitterStyles } from './styles' + +const PREVIEW_CHARS = 6_000 + +export interface SplitChoice { + mode: SplitterSettings['mode'] + plan: SplitPlan + instruction: string +} + +export interface SplitDialogRequest { + text: string + settings: SplitterSettings + onSettings: (settings: SplitterSettings) => void + onConfirm: (choice: SplitChoice) => void +} + +export const formatNumber = (value: number): string => value.toLocaleString() + +export const createPartRows = (plan: SplitPlan): HTMLElement[] => + plan.parts.map((part, index) => { + const details = createElement('details', 'bp-split-part') + const head = createElement('summary') + head.append(createElement('span', undefined, `Part ${index + 1}`), createElement('span', 'bp-data-label', `${formatNumber(plan.tokens[index] ?? 0)} tokens`)) + details.append(head, createElement('pre', undefined, part.length > PREVIEW_CHARS ? `${part.slice(0, PREVIEW_CHARS)}\n…` : part)) + return details + }) + +export const openSplitDialog = ({ text, settings, onSettings, onConfirm }: SplitDialogRequest): void => { + const dialogId = `${uiConfig().id}-splitter-dialog` + if (document.getElementById(dialogId)) return + const ui = createDialog({ id: dialogId, title: 'Message splitter', description: `This message is about ${formatNumber(estimateTokens(text))} tokens.`, width: 640 }) + const state: SplitterSettings = { ...settings } + let instruction = '' + let plan: SplitPlan = planParts(text, instruction, state.limit, state.balanced) + const summary = createElement('div', 'bp-split-summary') + const list = createElement('div', 'bp-stack') + const confirm = createButton('', { primary: true }) + const render = (): void => { + plan = planParts(text, instruction, state.limit, state.balanced) + const count = plan.parts.length + summary.textContent = `${count} ${count === 1 ? 'part' : 'parts'} · limit ${formatNumber(state.limit)} tokens each. Every part sent uses one query.` + list.replaceChildren(...createPartRows(plan)) + confirm.textContent = state.mode === 'file' ? 'Attach as file' : count > 1 ? `Send ${count} parts` : 'Send' + } + const update = (patch: Partial): void => { + Object.assign(state, patch) + onSettings({ ...state }) + render() + } + const limit = createNumberField({ label: 'Tokens per part', hint: 'Estimate, with a safety margin built in', value: state.limit, min: 500, max: 100_000, step: 100, onChange: (value) => update({ limit: value }) }) + const mode = createSelectField('Mode', [ + { value: 'parts', label: 'Send in parts' }, + { value: 'file', label: 'Attach as file (no extra queries)' } + ], state.mode, (value) => update({ mode: value })) + const auto = createSwitch({ label: 'Offer to split when sending an oversized message', checked: state.autoIntercept, onChange: (value) => update({ autoIntercept: value }) }) + const finalInstruction = createTextArea('Instruction appended to the last part (optional)', '', (value) => { + instruction = value + render() + }) + const options = createElement('div', 'bp-stack') + options.append(limit.wrapper, mode, auto.wrapper, finalInstruction) + ui.body.append(options, createElement('div', 'bp-hint'), summary, list) + confirm.addEventListener('click', () => { + ui.close() + onConfirm({ mode: state.mode, plan, instruction }) + }) + ui.footer.append(createButton('Cancel', { onClick: ui.close }), confirm) + render() + ui.show() +} + +const STATUS_TEXT: Readonly> = { sending: 'sending', waiting: 'waiting for the reply', done: 'done' } + +export class ProgressPanel { + private readonly element = markUi(createElement('div', 'bp-split-panel bp-themed')) + private readonly label = createElement('div') + private readonly fill = createElement('div', 'bp-progress-fill') + private readonly cancel = createButton('Cancel') + private timer = 0 + + constructor() { + ensureUiStyles() + ensureSplitterStyles() + const bar = createElement('div', 'bp-progress') + bar.appendChild(this.fill) + this.element.append(this.label, bar, this.cancel) + } + + show(total: number, onCancel: () => void): void { + this.cancel.hidden = false + this.cancel.onclick = onCancel + this.fill.style.width = '0%' + this.label.textContent = `Preparing ${total} parts…` + this.mount() + } + + update(index: number, total: number, status: PartStatus): void { + this.label.textContent = `Part ${index + 1}/${total}: ${STATUS_TEXT[status]}` + this.fill.style.width = `${(((index + (status === 'done' ? 1 : 0.5)) / total) * 100).toFixed(0)}%` + } + + finish(message: string): void { + this.label.textContent = message + this.cancel.hidden = true + this.autoHide(4_000) + } + + notify(message: string): void { + this.label.textContent = message + this.fill.style.width = '0%' + this.cancel.hidden = true + this.mount() + this.autoHide(3_500) + } + + private mount(): void { + window.clearTimeout(this.timer) + if (!this.element.isConnected) document.body.appendChild(this.element) + } + + private autoHide(ms: number): void { + window.clearTimeout(this.timer) + this.timer = window.setTimeout(() => this.element.remove(), ms) + } +} diff --git a/core/ai/src/features/message-splitter/feature.ts b/core/ai/src/features/message-splitter/feature.ts new file mode 100644 index 0000000..b44a90f --- /dev/null +++ b/core/ai/src/features/message-splitter/feature.ts @@ -0,0 +1,159 @@ +import { Feature, toElement, waitFor } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isAutomating } from '../../automation' +import { isSendButton, readComposer } from '../../composer' +import type { ComposerKit } from '../../composer' +import type { GenerationKit } from '../../generation' +import { estimateTokens } from '../../tokens' +import { uiConfig } from '../../ui/config' +import { ComposerButton } from '../../ui/composer-button' +import { openBigTextDialog } from './big-text' +import { ProgressPanel, openSplitDialog } from './dialog' +import type { SplitChoice } from './dialog' +import { SendRunner } from './runner' +import { loadSplitterSettings, saveSplitterSettings } from './settings' +import type { SplitterSettings } from './settings' + +export interface MessageSplitterOptions { + readonly storage: ScriptStorage + readonly composer: ComposerKit + readonly generation: Pick + readonly defaults?: Partial + readonly attachBlocked?: () => string | null +} + +export class MessageSplitterFeature extends Feature { + readonly id = 'message-splitter' + readonly name = 'Message Splitter' + readonly description = 'Splits oversized prompts into ordered parts, or attaches them as a file.' + + private settings: SplitterSettings + private readonly runner: SendRunner + private readonly panel = new ProgressPanel() + private attached = false + private readonly bigButton = new ComposerButton('Compose big message', 'file', 'Paste a large message. It is split only if needed.', () => this.openBig(), { id: 'big' }) + + constructor(context: ScriptContext, private readonly options: MessageSplitterOptions) { + super(context) + this.settings = loadSplitterSettings(options.storage, options.defaults) + this.runner = new SendRunner({ composer: options.composer, waitForResponse: options.generation.waitForResponse, logger: context.logger }) + } + + run(): void { + if (this.enabled) this.bigButton.mount() + else this.bigButton.unmount() + if (this.enabled && !this.attached) { + document.addEventListener('keydown', this.handleKeydown, true) + document.addEventListener('click', this.handleClick, true) + this.attached = true + return + } + if (!this.enabled && this.attached) { + document.removeEventListener('keydown', this.handleKeydown, true) + document.removeEventListener('click', this.handleClick, true) + this.attached = false + } + } + + override menuEntries(): MenuEntry[] { + return [ + { id: 'big', label: 'Compose Big Message…', action: () => this.openBig() }, + { id: 'split', label: 'Split Composer Text…', action: () => this.open() }, + { label: `${this.settings.autoIntercept ? 'Disable' : 'Enable'} Auto-Split on Send`, action: () => this.saveSettings({ ...this.settings, autoIntercept: !this.settings.autoIntercept }) } + ] + } + + private saveSettings(settings: SplitterSettings): void { + this.settings = settings + saveSplitterSettings(this.options.storage, settings) + this.context.refreshMenu() + } + + private isOwn(element: Element): boolean { + return uiConfig().marker.isOwn(element) + } + + private isOversized(editable: HTMLElement): boolean { + return this.settings.autoIntercept && estimateTokens(readComposer(editable)) > this.settings.limit + } + + private readonly handleKeydown = (event: KeyboardEvent): void => { + if (this.runner.active || isAutomating() || event.key !== 'Enter' || event.shiftKey || event.isComposing) return + const editable = this.options.composer.editableFrom(event.target) + if (!editable || this.isOwn(editable) || !this.isOversized(editable)) return + event.preventDefault() + event.stopImmediatePropagation() + this.open() + } + + private readonly handleClick = (event: MouseEvent): void => { + if (this.runner.active || isAutomating() || !this.settings.autoIntercept) return + const button = toElement(event.target)?.closest('button') + if (!button || this.isOwn(button) || !isSendButton(button)) return + const composer = this.options.composer.findComposer() + if (!composer || !this.isOversized(composer)) return + event.preventDefault() + event.stopImmediatePropagation() + this.open() + } + + private open(): void { + const composer = this.options.composer.findComposer() + const text = composer ? readComposer(composer) : '' + if (!text.trim()) { + this.panel.notify('The composer is empty.') + return + } + openSplitDialog({ + text, + settings: this.settings, + onSettings: (settings) => this.saveSettings(settings), + onConfirm: (choice) => void this.execute(text, choice) + }) + } + + private async execute(text: string, { mode, plan, instruction }: SplitChoice): Promise { + if (mode === 'file') { + await this.attachAsFile(text, instruction) + return + } + const total = plan.parts.length + this.panel.show(total, () => this.runner.cancel()) + const result = await this.runner.run(plan.parts, (index, status) => this.panel.update(index, total, status)) + this.panel.finish(result === 'done' ? 'All parts sent.' : result === 'cancelled' ? 'Cancelled.' : 'Stopped: a part could not be written or sent.') + } + + private async attachAsFile(text: string, instruction: string): Promise { + const blocked = this.options.attachBlocked?.() + if (blocked) { + this.panel.notify(blocked) + return + } + const composer = this.options.composer.findComposer() + if (!composer) { + this.panel.notify('No composer found.') + return + } + const attached = this.options.composer.attachFile(composer, new File([text], 'message.txt', { type: 'text/plain' })) + await this.options.composer.writeComposer(composer, instruction.trim()) + this.panel.notify(attached ? 'File attached. Add your question and send.' : 'Could not attach the file automatically.') + } + + private openBig(): void { + openBigTextDialog({ + settings: this.settings, + onSettings: (settings) => this.saveSettings(settings), + onInsert: (text) => void this.insert(text), + onSend: (text, choice) => void this.execute(text, choice) + }) + } + + private async insert(text: string): Promise { + const composer = await waitFor(this.options.composer.findComposer, { timeout: 5_000 }) + if (!composer) { + this.panel.notify('No composer found.') + return + } + this.panel.notify((await this.options.composer.writeComposer(composer, text)) ? 'Inserted into the composer.' : 'Could not insert the text.') + } +} diff --git a/core/ai/src/features/message-splitter/index.ts b/core/ai/src/features/message-splitter/index.ts new file mode 100644 index 0000000..d25038a --- /dev/null +++ b/core/ai/src/features/message-splitter/index.ts @@ -0,0 +1,4 @@ +export { MessageSplitterFeature } from './feature' +export type { MessageSplitterOptions } from './feature' +export { loadSplitterSettings } from './settings' +export type { SplitterSettings } from './settings' diff --git a/core/ai/src/features/message-splitter/plan.ts b/core/ai/src/features/message-splitter/plan.ts new file mode 100644 index 0000000..1bf888f --- /dev/null +++ b/core/ai/src/features/message-splitter/plan.ts @@ -0,0 +1,34 @@ +import { estimateTokens } from '../../tokens' +import { splitText } from './splitter' + +export interface PartTemplates { + readonly header: string + readonly final: string +} + +export const DEFAULT_TEMPLATES: PartTemplates = { + header: '[Part {{index}}/{{total}}] I am sending one long message in {{total}} parts. Do not answer yet. Reply only with "OK" until the final part.', + final: '[Part {{index}}/{{total}} - final] This is the last part. The full message is now complete; respond to all parts now.' +} + +export interface SplitPlan { + parts: string[] + tokens: number[] + total: number +} + +const fill = (template: string, index: number, total: number): string => template.replace(/\{\{index\}\}/g, String(index)).replace(/\{\{total\}\}/g, String(total)) + +export const planParts = (text: string, instruction: string, limit: number, balanced: boolean, templates: PartTemplates = DEFAULT_TEMPLATES): SplitPlan => { + const total = estimateTokens(text) + const tail = instruction.trim() ? `\n\n${instruction.trim()}` : '' + if (total + estimateTokens(tail) <= limit) { + const only = `${text}${tail}` + return { parts: [only], tokens: [estimateTokens(only)], total } + } + const overhead = estimateTokens(templates.header) + estimateTokens(templates.final) + estimateTokens(tail) + 24 + const raw = splitText(text, { budget: Math.max(200, limit - overhead), balanced }) + const count = raw.length + const parts = raw.map((chunk, index) => index === count - 1 ? `${fill(templates.final, index + 1, count)}\n\n${chunk}${tail}` : `${fill(templates.header, index + 1, count)}\n\n${chunk}`) + return { parts, tokens: parts.map((part) => estimateTokens(part)), total } +} diff --git a/core/ai/src/features/message-splitter/runner.ts b/core/ai/src/features/message-splitter/runner.ts new file mode 100644 index 0000000..8d72ea5 --- /dev/null +++ b/core/ai/src/features/message-splitter/runner.ts @@ -0,0 +1,56 @@ +import { isAbort, waitFor } from '@nolly/core' +import type { Logger } from '@nolly/core' +import type { ComposerKit } from '../../composer' +import type { GenerationKit } from '../../generation' + +export type PartStatus = 'sending' | 'waiting' | 'done' +export type RunResult = 'done' | 'cancelled' | 'failed' + +export interface RunnerDeps { + readonly composer: Pick + readonly waitForResponse: GenerationKit['waitForResponse'] + readonly logger: Logger +} + +export class SendRunner { + private controller: AbortController | null = null + + constructor(private readonly deps: RunnerDeps) {} + + get active(): boolean { + return this.controller !== null + } + + cancel(): void { + this.controller?.abort() + } + + async run(parts: readonly string[], onStatus: (index: number, status: PartStatus) => void): Promise { + if (this.controller) return 'failed' + const controller = new AbortController() + this.controller = controller + const { signal } = controller + const { composer: kit, waitForResponse, logger } = this.deps + try { + for (let index = 0; index < parts.length; index++) { + onStatus(index, 'sending') + const composer = await waitFor(kit.findComposer, { timeout: 15_000, signal }) + if (!composer) return 'failed' + if (!(await kit.writeComposer(composer, parts[index]!))) return 'failed' + if (!(await kit.sendComposer(composer))) return 'failed' + if (index < parts.length - 1) { + onStatus(index, 'waiting') + await waitForResponse({ signal }) + } + onStatus(index, 'done') + } + return 'done' + } catch (error) { + if (isAbort(error)) return 'cancelled' + logger.error('Message splitter run failed.', error) + return 'failed' + } finally { + this.controller = null + } + } +} diff --git a/core/ai/src/features/message-splitter/settings.ts b/core/ai/src/features/message-splitter/settings.ts new file mode 100644 index 0000000..2b8383a --- /dev/null +++ b/core/ai/src/features/message-splitter/settings.ts @@ -0,0 +1,20 @@ +import type { ScriptStorage } from '@nolly/core' + +export interface SplitterSettings { + limit: number + autoIntercept: boolean + balanced: boolean + mode: 'parts' | 'file' +} + +const STORAGE_KEY = 'message-splitter:settings' + +export const DEFAULT_SPLITTER_SETTINGS: Readonly = { limit: 7_500, autoIntercept: true, balanced: true, mode: 'parts' } + +export const loadSplitterSettings = (storage: ScriptStorage, defaults: Partial = {}): SplitterSettings => ({ + ...DEFAULT_SPLITTER_SETTINGS, + ...defaults, + ...storage.get>(STORAGE_KEY, {}) +}) + +export const saveSplitterSettings = (storage: ScriptStorage, settings: SplitterSettings): void => storage.set(STORAGE_KEY, settings) diff --git a/core/ai/src/features/message-splitter/splitter.ts b/core/ai/src/features/message-splitter/splitter.ts new file mode 100644 index 0000000..be0e902 --- /dev/null +++ b/core/ai/src/features/message-splitter/splitter.ts @@ -0,0 +1,120 @@ +import { estimateTokens } from '../../tokens' + +interface CodeAtom { + kind: 'code' + open: string + close: string + body: string[] +} + +interface TextAtom { + kind: 'text' + lines: string[] +} + +type Atom = CodeAtom | TextAtom + +export interface SplitOptions { + budget: number + balanced: boolean +} + +const FENCE_OPEN = /^\s*(`{3,}|~{3,})/ +const SENTENCE_BREAK = /(?<=[.!?])\s+/ +const CHARS_PER_TOKEN = 3 + +const atomText = (atom: Atom): string => (atom.kind === 'code' ? [atom.open, ...atom.body, atom.close].join('\n') : atom.lines.join('\n')) +const atomTokens = (atom: Atom): number => estimateTokens(atomText(atom)) + +export const parseAtoms = (text: string): Atom[] => { + const atoms: Atom[] = [] + let paragraph: string[] = [] + let fence: { open: string; marker: string; body: string[] } | null = null + const flush = (): void => { + if (paragraph.length) atoms.push({ kind: 'text', lines: paragraph }) + paragraph = [] + } + for (const line of text.replace(/\r\n?/g, '\n').split('\n')) { + if (fence) { + const trimmed = line.trim() + if (trimmed.startsWith(fence.marker) && /^[`~]+$/.test(trimmed)) { + atoms.push({ kind: 'code', open: fence.open, close: trimmed, body: fence.body }) + fence = null + } else { + fence.body.push(line) + } + continue + } + const opening = FENCE_OPEN.exec(line) + if (opening) { + flush() + fence = { open: line.trim(), marker: opening[1]!, body: [] } + continue + } + if (line.trim() === '') flush() + else paragraph.push(line) + } + flush() + if (fence) atoms.push({ kind: 'code', open: fence.open, close: fence.marker, body: fence.body }) + return atoms +} + +const hardSplit = (text: string, budget: number): string[] => { + const size = Math.max(40, Math.floor(budget * CHARS_PER_TOKEN)) + const pieces: string[] = [] + for (let index = 0; index < text.length; index += size) pieces.push(text.slice(index, index + size)) + return pieces +} + +const pack = (units: readonly string[], budget: number, joiner: string, asCode: boolean): string[] => { + const chunks: string[] = [] + let current: string[] = [] + let used = 0 + const flush = (): void => { + if (current.length) chunks.push(current.join(joiner)) + current = [] + used = 0 + } + for (const unit of units.flatMap((entry) => (estimateTokens(entry, asCode) > budget ? hardSplit(entry, budget) : [entry]))) { + const size = estimateTokens(unit, asCode) + 1 + if (current.length && used + size > budget) flush() + current.push(unit) + used += size + } + flush() + return chunks +} + +const splitOversized = (atom: Atom, budget: number): Atom[] => { + if (atom.kind === 'code') { + const room = Math.max(40, budget - estimateTokens(`${atom.open}\n${atom.close}`, true)) + return pack(atom.body, room, '\n', true).map((chunk): Atom => ({ kind: 'code', open: atom.open, close: atom.close, body: chunk.split('\n') })) + } + const single = atom.lines.length === 1 + const units = single ? (atom.lines[0] ?? '').split(SENTENCE_BREAK) : atom.lines + return pack(units, budget, single ? ' ' : '\n', false).map((chunk): Atom => ({ kind: 'text', lines: [chunk] })) +} + +export const splitText = (text: string, { budget, balanced }: SplitOptions): string[] => { + const atoms = parseAtoms(text).flatMap((atom) => (atomTokens(atom) > budget ? splitOversized(atom, budget) : [atom])) + if (!atoms.length) return [] + const sizes = atoms.map((atom) => atomTokens(atom) + 2) + const total = sizes.reduce((sum, size) => sum + size, 0) + const count = Math.max(1, Math.ceil(total / budget)) + const cap = balanced ? Math.min(budget, Math.ceil((total / count) * 1.15)) : budget + const parts: string[][] = [] + let current: string[] = [] + let used = 0 + atoms.forEach((atom, index) => { + const size = sizes[index]! + if (current.length && used + size > cap) { + parts.push(current) + current = [] + used = 0 + } + current.push(atomText(atom)) + used += size + }) + if (current.length) parts.push(current) + return parts.map((part) => part.join('\n\n')) +} diff --git a/core/ai/src/features/message-splitter/styles.ts b/core/ai/src/features/message-splitter/styles.ts new file mode 100644 index 0000000..20011b7 --- /dev/null +++ b/core/ai/src/features/message-splitter/styles.ts @@ -0,0 +1,29 @@ +import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' + +const CSS = ` +.bp-split-summary { margin-bottom: 12px; color: var(--bp-muted); font-size: 12px; } +.bp-split-part { border: 1px solid var(--bp-border); border-radius: 10px; } +.bp-split-part summary { display: flex; justify-content: space-between; gap: 12px; padding: 8px 12px; cursor: pointer; } +.bp-split-part pre { max-height: 220px; margin: 0 12px 12px; padding: 10px; overflow: auto; border-radius: 8px; background: var(--bp-accent); font: 11px/1.5 ui-monospace, monospace; white-space: pre-wrap; word-break: break-word; } + +.bp-split-panel { + position: fixed; + right: 20px; + bottom: 20px; + z-index: 100000; + display: flex; + flex-direction: column; + gap: 8px; + width: 280px; + padding: 12px 14px; + border: 1px solid var(--bp-border); + border-radius: 12px; + background: var(--bp-bg); + color: var(--bp-fg); + box-shadow: 0 12px 32px rgb(0 0 0 / 22%); + font-size: 12px; +} +` + +export const ensureSplitterStyles = (): void => injectStyle(`${uiConfig().id}-splitter-styles`, CSS) From 62d8f9c09e217af959d52cae6d21f8096cf3c401 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:35:59 +0100 Subject: [PATCH 08/19] feat(ai): hoist Command Palette, Prompt Library, Prompt Queue and Recall into @nolly/ai (step 6) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/logger.ts | 3 ++ ai/chatgpt/src/main.ts | 32 +++++++++-- ai/chatgpt/src/repo.ts | 3 +- ai/chatgpt/src/storage.ts | 3 ++ ai/chatgpt/src/threads.ts | 3 ++ ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/docs/architecture.md | 2 +- ai/perplexity/src/core/threads.ts | 3 ++ ai/perplexity/src/main.ts | 33 ++++++++---- core/ai/README.md | 3 ++ .../src/features}/command-palette/dialog.ts | 10 ++-- .../ai/src/features}/command-palette/fuzzy.ts | 0 .../ai/src/features}/command-palette/index.ts | 6 +-- .../src/features}/command-palette/palette.ts | 11 ++-- .../src/features}/command-palette/shortcut.ts | 2 +- .../src/features}/command-palette/styles.ts | 3 +- core/ai/src/features/index.ts | 4 ++ .../ai/src/features}/prompt-library/index.ts | 7 ++- .../src/features}/prompt-library/manager.ts | 11 ++-- .../ai/src/features}/prompt-library/picker.ts | 9 ++-- .../ai/src/features}/prompt-library/remote.ts | 6 +-- .../src/features}/prompt-library/shortcut.ts | 2 +- .../ai/src/features}/prompt-library/store.ts | 2 +- .../ai/src/features}/prompt-library/styles.ts | 3 +- .../src/features}/prompt-library/variables.ts | 4 +- .../ai/src/features}/prompt-queue/index.ts | 11 ++-- .../ai/src/features}/prompt-queue/panel.ts | 8 +-- .../ai/src/features}/prompt-queue/queue.ts | 7 ++- .../ai/src/features}/prompt-queue/runner.ts | 0 .../ai/src/features}/prompt-queue/shortcut.ts | 2 +- .../ai/src/features}/prompt-queue/styles.ts | 3 +- .../ai/src/features}/recall/caret.ts | 0 .../ai/src/features}/recall/cursor.ts | 0 .../ai/src/features}/recall/dialog.ts | 11 ++-- .../ai/src/features}/recall/format.ts | 0 .../ai/src/features}/recall/history.ts | 4 +- .../ai/src/features}/recall/index.ts | 22 ++++---- .../ai/src/features}/recall/recorder.ts | 0 .../ai/src/features}/recall/settings.ts | 2 +- .../ai/src/features}/recall/store.ts | 5 +- .../ai/src/features}/recall/styles.ts | 3 +- core/ai/src/index.ts | 4 +- core/ai/src/platform.ts | 53 +++++++++++++++++++ core/ai/src/ui/config.ts | 2 + 45 files changed, 216 insertions(+), 88 deletions(-) create mode 100644 ai/chatgpt/src/logger.ts create mode 100644 ai/chatgpt/src/storage.ts create mode 100644 ai/chatgpt/src/threads.ts create mode 100644 ai/perplexity/src/core/threads.ts rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/dialog.ts (81%) rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/fuzzy.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/index.ts (93%) rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/palette.ts (91%) rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/shortcut.ts (96%) rename {ai/perplexity/src/modules => core/ai/src/features}/command-palette/styles.ts (88%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/index.ts (92%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/manager.ts (87%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/picker.ts (92%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/remote.ts (79%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/shortcut.ts (89%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/store.ts (97%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/styles.ts (70%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-library/variables.ts (88%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/index.ts (92%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/panel.ts (96%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/queue.ts (90%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/runner.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/shortcut.ts (89%) rename {ai/perplexity/src/modules => core/ai/src/features}/prompt-queue/styles.ts (94%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/caret.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/cursor.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/dialog.ts (93%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/format.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/history.ts (84%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/index.ts (92%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/recorder.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/settings.ts (95%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/store.ts (96%) rename {ai/perplexity/src/modules => core/ai/src/features}/recall/styles.ts (91%) create mode 100644 core/ai/src/platform.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index dabf77c..cf8cb96 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -6,3 +6,4 @@ - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. - Draft Guard: autosaved drafts, size meter and unsent-text warning. - Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). +- Prompt Library (shared community prompts), Command Palette, Message Queue and Recall. diff --git a/ai/chatgpt/src/logger.ts b/ai/chatgpt/src/logger.ts new file mode 100644 index 0000000..70d2688 --- /dev/null +++ b/ai/chatgpt/src/logger.ts @@ -0,0 +1,3 @@ +import { createLogger } from '@nolly/core' + +export const logger = createLogger('Better ChatGPT') diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 79c64df..758ad44 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,15 +1,21 @@ -import { DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, configureUi, loadSplitterSettings } from '@nolly/ai' +import { CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' import { SPLITTER_DEFAULTS } from './config' import { uiMarker } from './dom' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' -import { composerKit, generationKit } from './kit' +import { composerKit, generationKit, sendPrompt } from './kit' +import { logger } from './logger' import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' +import { URLS } from './repo' import { session } from './runtime' +import { storage } from './storage' +import { threadOf } from './threads' import { installTheme } from './theme' +const onSend = (listener: () => void): (() => void) => session.subscribe((event) => { if (event === 'generation-start') listener() }) + configureUi({ id: 'better-chatgpt', title: 'Better ChatGPT', @@ -18,12 +24,28 @@ configureUi({ composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) }) +configurePlatform({ + id: 'better-chatgpt', + storage, + logger, + composer: composerKit, + generation: generationKit, + sendPrompt, + onSend, + threadOf, + promptsUrl: URLS.prompts +}) + installTheme() new App() .register((context) => new HeaderButtonFeature(context)) - .register((context) => new EnterAsNewlineFeature(context, { storage: context.storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) - .register((context) => new MessageSplitterFeature(context, { storage: context.storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) - .register((context) => new DraftGuardFeature(context, { storage: context.storage, composer: composerKit, onSend: (listener) => session.subscribe((event) => { if (event === 'generation-start') listener() }), tokenLimit: () => loadSplitterSettings(context.storage, SPLITTER_DEFAULTS).limit })) + .register((context) => new PromptLibraryFeature(context)) + .register((context) => new EnterAsNewlineFeature(context, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) + .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) + .register((context) => new DraftGuardFeature(context, { storage, composer: composerKit, onSend, tokenLimit: () => loadSplitterSettings(storage, SPLITTER_DEFAULTS).limit })) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) .register((context) => new DiagnosticsFeature(context)) .start() diff --git a/ai/chatgpt/src/repo.ts b/ai/chatgpt/src/repo.ts index aef95f2..2049ef3 100644 --- a/ai/chatgpt/src/repo.ts +++ b/ai/chatgpt/src/repo.ts @@ -3,6 +3,7 @@ import { repoUrls } from '@nolly/core' export const SLUG = 'better-chatgpt' const urls = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: SLUG, dir: 'ai/chatgpt' }) +const sharedPrompts = repoUrls({ owner: 'thenolle', repo: 'userscripts', branch: 'master', slug: 'better-perplexity', dir: 'ai/perplexity' }) export const URLS = { home: urls.home, @@ -11,5 +12,5 @@ export const URLS = { sponsor: urls.sponsor, meta: urls.meta, install: urls.install, - prompts: urls.rawFile('prompts/library.json') + prompts: sharedPrompts.rawFile('prompts/library.json') } as const diff --git a/ai/chatgpt/src/storage.ts b/ai/chatgpt/src/storage.ts new file mode 100644 index 0000000..1f37528 --- /dev/null +++ b/ai/chatgpt/src/storage.ts @@ -0,0 +1,3 @@ +import { createStorage } from '@nolly/core' + +export const storage = createStorage({ namespace: 'better-chatgpt', gmPrefix: '' }) diff --git a/ai/chatgpt/src/threads.ts b/ai/chatgpt/src/threads.ts new file mode 100644 index 0000000..86f102d --- /dev/null +++ b/ai/chatgpt/src/threads.ts @@ -0,0 +1,3 @@ +const THREAD_PATH = /^\/(?:g\/[^/]+\/)?c\/[^/]+/ + +export const threadOf = (pathname: string): string | null => (THREAD_PATH.test(pathname) ? pathname : null) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 19c2e8a..45ae41b 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to Better Perplexity are documented here. The format follows ## [Unreleased] - Internal: composer, synthetic keys and generation detection moved to the shared `@nolly/ai` package. The script moved to `ai/perplexity`; install URLs and storage keys are unchanged. +- Internal: Prompt Library, Command Palette, Message Queue and Recall now come from the shared package. - Internal: Enter as Newline now comes from the shared package. - Internal: Draft Guard now comes from the shared package. - Internal: Message Splitter now comes from the shared package. diff --git a/ai/perplexity/docs/architecture.md b/ai/perplexity/docs/architecture.md index 3f21322..dc811c8 100644 --- a/ai/perplexity/docs/architecture.md +++ b/ai/perplexity/docs/architecture.md @@ -18,7 +18,7 @@ Better Perplexity is a thin layer on top of `@nolly/core`, a small library share ## What comes from @nolly/ai -`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The dialogs, toasts, tooltips, controls, icons and settings dialog also live there; Better Perplexity configures them once in `main.ts`. +`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The dialogs, toasts, tooltips, controls, icons and settings dialog also live there; Better Perplexity configures them once in `main.ts`. Features that need storage, logging or the composer read them from a registry the platform fills once at startup. ## What stays in Better Perplexity diff --git a/ai/perplexity/src/core/threads.ts b/ai/perplexity/src/core/threads.ts new file mode 100644 index 0000000..54e22b3 --- /dev/null +++ b/ai/perplexity/src/core/threads.ts @@ -0,0 +1,3 @@ +const ROOT_PATH = /^\/(?:computer|spaces|library|discover)?\/?$/ + +export const threadOf = (pathname: string): string | null => (ROOT_PATH.test(pathname) ? null : pathname) diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index e9ed731..b2996cb 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,44 +1,57 @@ -import { DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, configureUi, loadSplitterSettings } from '@nolly/ai' +import { CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' import { composerKit, findComposer, writeComposer } from './core/composer' +import { sendPrompt } from './core/dispatch' import { uiMarker } from './core/dom' import { fetchSpy } from './core/fetch-spy' import { generationKit } from './core/generation' +import { logger } from './core/logger' import { isAskRequest } from './core/requests' import { storage } from './core/storage' +import { threadOf } from './core/threads' import { findComposerActions } from './locate' import { BatchRunnerModule } from './modules/batch-runner' import { CodeBlocksModule } from './modules/code-blocks' -import { CommandPaletteModule } from './modules/command-palette' import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' import { MaxWidthModule } from './modules/max-width' -import { PromptLibraryModule } from './modules/prompt-library' -import { PromptQueueModule } from './modules/prompt-queue' -import { RecallModule } from './modules/recall' import { SelectionToolbarModule } from './modules/selection-toolbar' import { TutorialModule } from './modules/tutorial' import { UpdatesModule } from './modules/updates' import { UsageStatusModule } from './modules/usage-status' +import { URLS } from './repo' + +const onSend = (listener: () => void): (() => void) => 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 +}) fetchSpy.install() new App() - .register((context) => new PromptLibraryModule(context)) + .register((context) => new PromptLibraryFeature(context)) .register((context) => new SelectionToolbarModule(context)) .register((context) => new MaxWidthModule(context)) .register((context) => new EnterAsNewlineFeature(context, { storage })) .register((context) => new CodeBlocksModule(context)) .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit })) .register((context) => new BatchRunnerModule(context)) - .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend: (listener) => fetchSpy.subscribe(({ method, url }) => { if (isAskRequest(method, url)) listener() }), tokenLimit: () => loadSplitterSettings(storage).limit })) - .register((context) => new CommandPaletteModule(context)) + .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend, tokenLimit: () => loadSplitterSettings(storage).limit })) + .register((context) => new CommandPaletteFeature(context)) .register((context) => new ExporterModule(context)) .register((context) => new UsageStatusModule(context)) .register((context) => new GlobalSettingsModule(context)) .register((context) => new TutorialModule(context)) .register((context) => new UpdatesModule(context)) - .register((context) => new PromptQueueModule(context)) - .register((context) => new RecallModule(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) .start() diff --git a/core/ai/README.md b/core/ai/README.md index 3e387dd..b9fea5a 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -11,3 +11,6 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. - Feature modules that need only an adapter: Enter as Newline, Draft Guard, and Message Splitter. +- Prompt Library, Command Palette, Prompt Queue and Recall. + +Platforms register once with `configurePlatform` and `configureUi`. diff --git a/ai/perplexity/src/modules/command-palette/dialog.ts b/core/ai/src/features/command-palette/dialog.ts similarity index 81% rename from ai/perplexity/src/modules/command-palette/dialog.ts rename to core/ai/src/features/command-palette/dialog.ts index dd6409f..9461b8e 100644 --- a/ai/perplexity/src/modules/command-palette/dialog.ts +++ b/core/ai/src/features/command-palette/dialog.ts @@ -1,18 +1,20 @@ import { createElement } from '@nolly/core' -import { createButton, createDialog } from '@nolly/ai' +import { createButton } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' import { DEFAULT_SHORTCUT, formatShortcut, shortcutFromEvent, type Shortcut } from './shortcut' import { ensurePaletteStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-shortcut-dialog' +const DIALOG_ID() = `${uiConfig().id}-shortcut-dialog` export const toggleShortcutDialog = (current: Shortcut, onSave: (shortcut: Shortcut) => void, title = 'Palette shortcut', defaults: Shortcut = DEFAULT_SHORTCUT): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title, description: 'Use at least one of Ctrl, Alt or Meta.', width: 420 }) + const ui = createDialog({ id: DIALOG_ID(), title, description: 'Use at least one of Ctrl, Alt or Meta.', width: 420 }) let draft: Shortcut = { ...current } let recording = false const box = createElement('div', 'bp-shortcut-box', formatShortcut(draft)) diff --git a/ai/perplexity/src/modules/command-palette/fuzzy.ts b/core/ai/src/features/command-palette/fuzzy.ts similarity index 100% rename from ai/perplexity/src/modules/command-palette/fuzzy.ts rename to core/ai/src/features/command-palette/fuzzy.ts diff --git a/ai/perplexity/src/modules/command-palette/index.ts b/core/ai/src/features/command-palette/index.ts similarity index 93% rename from ai/perplexity/src/modules/command-palette/index.ts rename to core/ai/src/features/command-palette/index.ts index 6b04b57..2d4ecf3 100644 --- a/ai/perplexity/src/modules/command-palette/index.ts +++ b/core/ai/src/features/command-palette/index.ts @@ -1,11 +1,11 @@ -import { findComposer, writeComposer } from '../../core/composer' -import { copyText } from '@nolly/ai' +import { findComposer, writeComposer } from '../../platform' +import { copyText } from '../../clipboard' import { Feature, type FeatureCommand, type MenuEntry } from '@nolly/core' import { toggleShortcutDialog } from './dialog' import { togglePalette } from './palette' import { loadShortcut, matchesShortcut, saveShortcut, type Shortcut } from './shortcut' -export class CommandPaletteModule extends Feature { +export class CommandPaletteFeature extends Feature { readonly id = 'command-palette' readonly name = 'Command Palette' readonly description = 'Search and run any action with a keyboard shortcut.' diff --git a/ai/perplexity/src/modules/command-palette/palette.ts b/core/ai/src/features/command-palette/palette.ts similarity index 91% rename from ai/perplexity/src/modules/command-palette/palette.ts rename to core/ai/src/features/command-palette/palette.ts index 9e538fe..cfd549d 100644 --- a/ai/perplexity/src/modules/command-palette/palette.ts +++ b/core/ai/src/features/command-palette/palette.ts @@ -1,10 +1,11 @@ import { type Command, createElement } from '@nolly/core' -import { storage } from '../../core/storage' -import { createDialog } from '@nolly/ai' +import { storage } from '../../platform' +import { createDialog } from '../../ui/dialog' import { fuzzyScore } from './fuzzy' import { ensurePaletteStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-palette' +const DIALOG_ID = (): string => `${uiConfig().id}-palette` const RECENT_KEY = 'command-palette:recent' const MAX_RECENT = 6 const MAX_RESULTS = 60 @@ -21,13 +22,13 @@ const rank = (commands: readonly Command[], query: string, recent: readonly stri } export const togglePalette = (getCommands: () => Command[]): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Command palette', width: 560 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Command palette', width: 560 }) ui.dialog.classList.add('bp-palette') const commands = getCommands() const input = createElement('input', 'bp-palette-input') diff --git a/ai/perplexity/src/modules/command-palette/shortcut.ts b/core/ai/src/features/command-palette/shortcut.ts similarity index 96% rename from ai/perplexity/src/modules/command-palette/shortcut.ts rename to core/ai/src/features/command-palette/shortcut.ts index 3a42ee4..fa16e6d 100644 --- a/ai/perplexity/src/modules/command-palette/shortcut.ts +++ b/core/ai/src/features/command-palette/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface Shortcut { ctrl: boolean diff --git a/ai/perplexity/src/modules/command-palette/styles.ts b/core/ai/src/features/command-palette/styles.ts similarity index 88% rename from ai/perplexity/src/modules/command-palette/styles.ts rename to core/ai/src/features/command-palette/styles.ts index ba8c809..b28efe6 100644 --- a/ai/perplexity/src/modules/command-palette/styles.ts +++ b/core/ai/src/features/command-palette/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-palette { max-height: min(70vh, 480px); } @@ -36,4 +37,4 @@ const CSS = ` .bp-shortcut-box { padding: 14px; border: 1px dashed var(--bp-border); border-radius: 10px; font-size: 15px; font-weight: 600; text-align: center; } ` -export const ensurePaletteStyles = (): void => injectStyle('better-perplexity-palette-styles', CSS) \ No newline at end of file +export const ensurePaletteStyles = (): void => injectStyle(`${uiConfig().id}-palette-styles`, CSS) \ No newline at end of file diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 0f8e092..2af8b4d 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -4,3 +4,7 @@ export { EnterAsNewlineFeature } from './enter-as-newline' export type { EnterAsNewlineOptions } from './enter-as-newline' export { MessageSplitterFeature, loadSplitterSettings } from './message-splitter' export type { MessageSplitterOptions, SplitterSettings } from './message-splitter' +export { CommandPaletteFeature } from './command-palette' +export { PromptQueueFeature } from './prompt-queue' +export { PromptLibraryFeature } from './prompt-library' +export { RecallFeature } from './recall' diff --git a/ai/perplexity/src/modules/prompt-library/index.ts b/core/ai/src/features/prompt-library/index.ts similarity index 92% rename from ai/perplexity/src/modules/prompt-library/index.ts rename to core/ai/src/features/prompt-library/index.ts index ca8fcec..91ed2fc 100644 --- a/ai/perplexity/src/modules/prompt-library/index.ts +++ b/core/ai/src/features/prompt-library/index.ts @@ -1,7 +1,6 @@ -import { findComposer, writeComposer } from '../../core/composer' +import { findComposer, writeComposer, storage } from '../../platform' import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { storage } from '../../core/storage' -import { ComposerButton } from '@nolly/ai' +import { ComposerButton } from '../../ui/composer-button' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { toggleManager } from './manager' @@ -11,7 +10,7 @@ import { loadPromptShortcut, PROMPT_SHORTCUT_KEY, DEFAULT_PROMPT_SHORTCUT } from import { PromptStore, type Prompt } from './store' import { expandPrompt } from './variables' -export class PromptLibraryModule extends Feature { +export class PromptLibraryFeature extends Feature { readonly id = 'prompt-library' readonly name = 'Prompt Library' readonly description = 'Insert saved and community prompts from a button or shortcut.' diff --git a/ai/perplexity/src/modules/prompt-library/manager.ts b/core/ai/src/features/prompt-library/manager.ts similarity index 87% rename from ai/perplexity/src/modules/prompt-library/manager.ts rename to core/ai/src/features/prompt-library/manager.ts index d8002de..cd63ca2 100644 --- a/ai/perplexity/src/modules/prompt-library/manager.ts +++ b/core/ai/src/features/prompt-library/manager.ts @@ -1,18 +1,21 @@ -import { copyText, createButton, createTextArea, createDialog } from '@nolly/ai' +import { copyText } from '../../clipboard' +import { createButton, createTextArea } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' import { createElement } from '@nolly/core' import type { Prompt, PromptStore } from './store' import { ensureSlashStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-prompts-dialog' +const DIALOG_ID() = `${uiConfig().id}-prompts-dialog` export const toggleManager = (store: PromptStore, onInsert: (prompt: Prompt) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensureSlashStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Prompt library', description: 'Type / in an empty message box to insert a prompt.', width: 620 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Prompt library', description: 'Type / in an empty message box to insert a prompt.', width: 620 }) const status = createElement('span', 'bp-updated') const editForm = (prompt: Prompt): void => { const draft = { ...prompt } diff --git a/ai/perplexity/src/modules/prompt-library/picker.ts b/core/ai/src/features/prompt-library/picker.ts similarity index 92% rename from ai/perplexity/src/modules/prompt-library/picker.ts rename to core/ai/src/features/prompt-library/picker.ts index 7fedc49..4a81276 100644 --- a/ai/perplexity/src/modules/prompt-library/picker.ts +++ b/core/ai/src/features/prompt-library/picker.ts @@ -1,10 +1,11 @@ import { createElement } from '@nolly/core' -import { createDialog } from '@nolly/ai' +import { createDialog } from '../../ui/dialog' import { fuzzyScore } from '../command-palette/fuzzy' import { ensurePaletteStyles } from '../command-palette/styles' import type { Prompt, PromptStore } from './store' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-prompt-picker' +const DIALOG_ID() = `${uiConfig().id}-prompt-picker` export interface PickerOptions { store: PromptStore @@ -22,13 +23,13 @@ interface Row { } export const togglePromptPicker = ({ store, community, onPick, onSave, onManage }: PickerOptions): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Prompts', width: 600 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Prompts', width: 600 }) ui.dialog.classList.add('bp-palette') const mine = store.list() let shared: Prompt[] = [] diff --git a/ai/perplexity/src/modules/prompt-library/remote.ts b/core/ai/src/features/prompt-library/remote.ts similarity index 79% rename from ai/perplexity/src/modules/prompt-library/remote.ts rename to core/ai/src/features/prompt-library/remote.ts index e872c4b..aa18f7c 100644 --- a/ai/perplexity/src/modules/prompt-library/remote.ts +++ b/core/ai/src/features/prompt-library/remote.ts @@ -1,7 +1,5 @@ import { getText } from '@nolly/core' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { URLS } from '../../repo' +import { logger, platform, storage } from '../../platform' import type { Prompt } from './store' interface Cache { @@ -21,7 +19,7 @@ export const loadCommunity = async (force = false): Promise => { const cached = storage.get(KEY, null) if (cached && !force && Date.now() - cached.at < TTL) return cached.prompts try { - const parsed = JSON.parse(await getText(`${URLS.prompts}?t=${Date.now()}`)) as { prompts?: unknown[] } + const parsed = JSON.parse(await getText(`${platform().promptsUrl}?t=${Date.now()}`)) as { prompts?: unknown[] } const prompts = (parsed.prompts ?? []).filter(isPrompt) storage.set(KEY, { at: Date.now(), prompts }) return prompts diff --git a/ai/perplexity/src/modules/prompt-library/shortcut.ts b/core/ai/src/features/prompt-library/shortcut.ts similarity index 89% rename from ai/perplexity/src/modules/prompt-library/shortcut.ts rename to core/ai/src/features/prompt-library/shortcut.ts index 8b740fe..ba381f2 100644 --- a/ai/perplexity/src/modules/prompt-library/shortcut.ts +++ b/core/ai/src/features/prompt-library/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export const PROMPT_SHORTCUT_KEY = 'prompt-library:shortcut' diff --git a/ai/perplexity/src/modules/prompt-library/store.ts b/core/ai/src/features/prompt-library/store.ts similarity index 97% rename from ai/perplexity/src/modules/prompt-library/store.ts rename to core/ai/src/features/prompt-library/store.ts index c278c40..707a717 100644 --- a/ai/perplexity/src/modules/prompt-library/store.ts +++ b/core/ai/src/features/prompt-library/store.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface Prompt { id: string diff --git a/ai/perplexity/src/modules/prompt-library/styles.ts b/core/ai/src/features/prompt-library/styles.ts similarity index 70% rename from ai/perplexity/src/modules/prompt-library/styles.ts rename to core/ai/src/features/prompt-library/styles.ts index f9bea22..27c7bad 100644 --- a/ai/perplexity/src/modules/prompt-library/styles.ts +++ b/core/ai/src/features/prompt-library/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-prompt-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 12px; border: 1px solid var(--bp-border); border-radius: 10px; } @@ -6,4 +7,4 @@ const CSS = ` .bp-prompt-actions { display: flex; flex-shrink: 0; gap: 6px; } ` -export const ensureSlashStyles = (): void => injectStyle('better-perplexity-slash-styles', CSS) \ No newline at end of file +export const ensureSlashStyles = (): void => injectStyle(`${uiConfig().id}-slash-styles`, CSS) \ No newline at end of file diff --git a/ai/perplexity/src/modules/prompt-library/variables.ts b/core/ai/src/features/prompt-library/variables.ts similarity index 88% rename from ai/perplexity/src/modules/prompt-library/variables.ts rename to core/ai/src/features/prompt-library/variables.ts index 3a09ab7..8e09c57 100644 --- a/ai/perplexity/src/modules/prompt-library/variables.ts +++ b/core/ai/src/features/prompt-library/variables.ts @@ -1,4 +1,6 @@ -import { applyValues, findFields, type Field, currentSelection, askFields } from '@nolly/ai' +import { applyValues, findFields, type Field } from '../../placeholders' +import { currentSelection } from '../../selection' +import { askFields } from '../../ui/placeholder-dialog' const BUILTINS = new Set(['clipboard', 'selection', 'date', 'time', 'url', 'title']) diff --git a/ai/perplexity/src/modules/prompt-queue/index.ts b/core/ai/src/features/prompt-queue/index.ts similarity index 92% rename from ai/perplexity/src/modules/prompt-queue/index.ts rename to core/ai/src/features/prompt-queue/index.ts index f67e071..eb26efc 100644 --- a/ai/perplexity/src/modules/prompt-queue/index.ts +++ b/core/ai/src/features/prompt-queue/index.ts @@ -1,9 +1,8 @@ import { Feature, waitFor, type MenuEntry, type ScriptContext } from '@nolly/core' -import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { readComposer, ComposerButton, showToast } from '@nolly/ai' -import { sendPrompt } from '../../core/dispatch' -import { isGenerating, waitForResponse } from '../../core/generation' -import { storage } from '../../core/storage' +import { findComposer, sendComposer, writeComposer, sendPrompt, isGenerating, waitForResponse, storage } from '../../platform' +import { readComposer } from '../../composer' +import { ComposerButton } from '../../ui/composer-button' +import { showToast } from '../../ui/toast' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { recordPrompt } from '../recall/history' @@ -28,7 +27,7 @@ const deps: RunnerDeps = { onSent: (text) => recordPrompt(text) } -export class PromptQueueModule extends Feature { +export class PromptQueueFeature extends Feature { readonly id = 'prompt-queue' readonly name = 'Message Queue' readonly description = 'Queue follow-up messages while an answer is generating; they send one by one when it finishes.' diff --git a/ai/perplexity/src/modules/prompt-queue/panel.ts b/core/ai/src/features/prompt-queue/panel.ts similarity index 96% rename from ai/perplexity/src/modules/prompt-queue/panel.ts rename to core/ai/src/features/prompt-queue/panel.ts index 73d57a1..014848d 100644 --- a/ai/perplexity/src/modules/prompt-queue/panel.ts +++ b/core/ai/src/features/prompt-queue/panel.ts @@ -1,7 +1,9 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { storage } from '../../core/storage' -import { createButton, createIcon, ensureUiStyles } from '@nolly/ai' +import { markUi } from '../../ui/config' +import { storage } from '../../platform' +import { createButton } from '../../ui/controls' +import { createIcon } from '../../ui/icons' +import { ensureUiStyles } from '../../ui/styles' import type { PromptQueue, QueueItem } from './queue' import type { Phase, QueueRunner } from './runner' import { ensureQueueStyles } from './styles' diff --git a/ai/perplexity/src/modules/prompt-queue/queue.ts b/core/ai/src/features/prompt-queue/queue.ts similarity index 90% rename from ai/perplexity/src/modules/prompt-queue/queue.ts rename to core/ai/src/features/prompt-queue/queue.ts index 4bb9941..1eecdac 100644 --- a/ai/perplexity/src/modules/prompt-queue/queue.ts +++ b/core/ai/src/features/prompt-queue/queue.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage, lazy, platform } from '../../platform' export interface KeyValueStore { get(key: string, fallback: T): T @@ -13,12 +13,11 @@ export interface QueueItem { } const KEY = 'prompt-queue:items' -const ROOT_PATH = /^\/(?:computer|spaces|library|discover)?\/?$/ export const MAX_ITEMS = 50 export const MAX_AGE = 24 * 3_600_000 -export const threadOf = (pathname: string): string | null => (ROOT_PATH.test(pathname) ? null : pathname) +export const threadOf = (pathname: string): string | null => platform().threadOf(pathname) export class PromptQueue { private items: QueueItem[] @@ -104,4 +103,4 @@ export class PromptQueue { } } -export const promptQueue = new PromptQueue() +export const promptQueue = lazy(() => new PromptQueue()) diff --git a/ai/perplexity/src/modules/prompt-queue/runner.ts b/core/ai/src/features/prompt-queue/runner.ts similarity index 100% rename from ai/perplexity/src/modules/prompt-queue/runner.ts rename to core/ai/src/features/prompt-queue/runner.ts diff --git a/ai/perplexity/src/modules/prompt-queue/shortcut.ts b/core/ai/src/features/prompt-queue/shortcut.ts similarity index 89% rename from ai/perplexity/src/modules/prompt-queue/shortcut.ts rename to core/ai/src/features/prompt-queue/shortcut.ts index 91cdfd8..f1b001c 100644 --- a/ai/perplexity/src/modules/prompt-queue/shortcut.ts +++ b/core/ai/src/features/prompt-queue/shortcut.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export const QUEUE_SHORTCUT_KEY = 'prompt-queue:shortcut' diff --git a/ai/perplexity/src/modules/prompt-queue/styles.ts b/core/ai/src/features/prompt-queue/styles.ts similarity index 94% rename from ai/perplexity/src/modules/prompt-queue/styles.ts rename to core/ai/src/features/prompt-queue/styles.ts index df230bb..05de4ac 100644 --- a/ai/perplexity/src/modules/prompt-queue/styles.ts +++ b/core/ai/src/features/prompt-queue/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-queue { position: fixed; right: 20px; bottom: 112px; z-index: 100000; display: flex; flex-direction: column; width: 340px; max-width: calc(100vw - 40px); border: 1px solid var(--bp-border); border-radius: 12px; background: var(--bp-bg); color: var(--bp-fg); box-shadow: 0 12px 32px rgb(0 0 0 / 22%); font: 12px/1.45 ui-sans-serif, system-ui, sans-serif; } @@ -21,4 +22,4 @@ const CSS = ` .bp-queue[data-collapsed='true'] .bp-queue-head { padding-bottom: 8px; } ` -export const ensureQueueStyles = (): void => injectStyle('better-perplexity-queue-styles', CSS) +export const ensureQueueStyles = (): void => injectStyle(`${uiConfig().id}-queue-styles`, CSS) diff --git a/ai/perplexity/src/modules/recall/caret.ts b/core/ai/src/features/recall/caret.ts similarity index 100% rename from ai/perplexity/src/modules/recall/caret.ts rename to core/ai/src/features/recall/caret.ts diff --git a/ai/perplexity/src/modules/recall/cursor.ts b/core/ai/src/features/recall/cursor.ts similarity index 100% rename from ai/perplexity/src/modules/recall/cursor.ts rename to core/ai/src/features/recall/cursor.ts diff --git a/ai/perplexity/src/modules/recall/dialog.ts b/core/ai/src/features/recall/dialog.ts similarity index 93% rename from ai/perplexity/src/modules/recall/dialog.ts rename to core/ai/src/features/recall/dialog.ts index f470730..7c1defa 100644 --- a/ai/perplexity/src/modules/recall/dialog.ts +++ b/core/ai/src/features/recall/dialog.ts @@ -1,11 +1,14 @@ import { createElement } from '@nolly/core' -import { copyText, createDialog, showToast } from '@nolly/ai' +import { copyText } from '../../clipboard' +import { createDialog } from '../../ui/dialog' +import { showToast } from '../../ui/toast' import { ensurePaletteStyles } from '../command-palette/styles' import { threadLabel, timeAgo } from './format' import type { HistoryEntry, HistoryFilter, HistoryStore } from './store' import { ensureRecallStyles } from './styles' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-recall' +const DIALOG_ID = (): string => `${uiConfig().id}-recall` const LIMIT = 100 const FILTERS: readonly { readonly id: HistoryFilter; readonly label: string }[] = [ @@ -31,14 +34,14 @@ const metaLine = (entry: HistoryEntry, now: number): string => { } export const toggleRecall = ({ store, insert, send, queue }: RecallActions): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } ensurePaletteStyles() ensureRecallStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Recall', width: 680 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Recall', width: 680 }) ui.dialog.classList.add('bp-palette', 'bp-recall') const input = createElement('input', 'bp-palette-input') input.placeholder = 'Search the messages you sent…' diff --git a/ai/perplexity/src/modules/recall/format.ts b/core/ai/src/features/recall/format.ts similarity index 100% rename from ai/perplexity/src/modules/recall/format.ts rename to core/ai/src/features/recall/format.ts diff --git a/ai/perplexity/src/modules/recall/history.ts b/core/ai/src/features/recall/history.ts similarity index 84% rename from ai/perplexity/src/modules/recall/history.ts rename to core/ai/src/features/recall/history.ts index f54bdba..39d3632 100644 --- a/ai/perplexity/src/modules/recall/history.ts +++ b/core/ai/src/features/recall/history.ts @@ -1,9 +1,9 @@ -import { storage } from '../../core/storage' +import { storage, lazy } from '../../platform' import { threadOf } from '../prompt-queue/queue' import { loadRecallSettings } from './settings' import { HistoryStore } from './store' -export const history = new HistoryStore() +export const history = lazy(() => new HistoryStore()) export const recordPrompt = (text: string): void => { if (!storage.get('module:recall', true) || loadRecallSettings().paused) return diff --git a/ai/perplexity/src/modules/recall/index.ts b/core/ai/src/features/recall/index.ts similarity index 92% rename from ai/perplexity/src/modules/recall/index.ts rename to core/ai/src/features/recall/index.ts index fc04549..68f2cb0 100644 --- a/ai/perplexity/src/modules/recall/index.ts +++ b/core/ai/src/features/recall/index.ts @@ -1,10 +1,12 @@ import { Feature, toElement, type MenuEntry, type ScriptContext } from '@nolly/core' -import { isAutomating, copyText, isSendButton, readComposer, saveFile, ComposerButton, showToast } from '@nolly/ai' -import { editableFrom, findComposer, sendComposer, writeComposer } from '../../core/composer' -import { isOwnUi } from '../../core/dom' -import { fetchSpy } from '../../core/fetch-spy' -import { isAskRequest } from '../../core/requests' -import { storage } from '../../core/storage' +import { isAutomating } from '../../automation' +import { copyText } from '../../clipboard' +import { isSendButton, readComposer } from '../../composer' +import { saveFile } from '../../download' +import { ComposerButton } from '../../ui/composer-button' +import { showToast } from '../../ui/toast' +import { editableFrom, findComposer, sendComposer, writeComposer, platform, storage } from '../../platform' +import { isOwnUi, uiConfig } from '../../ui/config' import { toggleShortcutDialog } from '../command-palette/dialog' import { matchesShortcut, type Shortcut } from '../command-palette/shortcut' import { promptQueue, threadOf } from '../prompt-queue/queue' @@ -15,7 +17,7 @@ import { history, recordPrompt } from './history' import { SendRecorder } from './recorder' import { DEFAULT_RECALL_SHORTCUT, loadRecallSettings, loadRecallShortcut, RECALL_SHORTCUT_KEY, saveRecallSettings } from './settings' -export class RecallModule extends Feature { +export class RecallFeature extends Feature { readonly id = 'recall' readonly name = 'Recall' readonly description = 'Searchable history of the messages you send, with one-key reuse and arrow-key recall.' @@ -41,9 +43,7 @@ export class RecallModule extends Feature { history.prune(loadRecallSettings().retentionDays) this.scope.listen(window, 'keydown', this.onKeydown as EventListener, { capture: true }) this.scope.listen(document, 'click', this.onClick as EventListener, { capture: true }) - this.scope.add(fetchSpy.subscribe(({ method, url }) => { - if (isAskRequest(method, url)) this.recorder.request() - })) + this.scope.add(platform().onSend(() => this.recorder.request())) this.scope.interval(() => this.recorder.tick(), 250) } @@ -59,7 +59,7 @@ export class RecallModule extends Feature { { id: 'pause', label: settings.paused ? 'Resume Recording' : 'Pause Recording', action: () => this.update({ paused: !settings.paused }) }, { id: 'arrows', label: `Turn Arrow-Key History ${settings.arrowHistory ? 'Off' : 'On'}`, action: () => this.update({ arrowHistory: !settings.arrowHistory }) }, { id: 'retention', label: 'Set History Retention…', action: () => this.setRetention() }, - { id: 'export', label: 'Export History…', action: () => saveFile('better-perplexity-history.json', history.exportJson(), 'application/json') }, + { id: 'export', label: 'Export History…', action: () => saveFile(`${uiConfig().id}-history.json`, history.exportJson(), 'application/json') }, { id: 'import', label: 'Import History…', action: () => this.importFile() }, { id: 'clear', label: 'Clear History…', action: () => this.clear() }, { id: 'shortcut', label: 'Configure Recall Shortcut', action: () => this.configure() } diff --git a/ai/perplexity/src/modules/recall/recorder.ts b/core/ai/src/features/recall/recorder.ts similarity index 100% rename from ai/perplexity/src/modules/recall/recorder.ts rename to core/ai/src/features/recall/recorder.ts diff --git a/ai/perplexity/src/modules/recall/settings.ts b/core/ai/src/features/recall/settings.ts similarity index 95% rename from ai/perplexity/src/modules/recall/settings.ts rename to core/ai/src/features/recall/settings.ts index 4dd4b89..eff5079 100644 --- a/ai/perplexity/src/modules/recall/settings.ts +++ b/core/ai/src/features/recall/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { Shortcut } from '../command-palette/shortcut' export interface RecallSettings { diff --git a/ai/perplexity/src/modules/recall/store.ts b/core/ai/src/features/recall/store.ts similarity index 96% rename from ai/perplexity/src/modules/recall/store.ts rename to core/ai/src/features/recall/store.ts index 9396db7..2078c0a 100644 --- a/ai/perplexity/src/modules/recall/store.ts +++ b/core/ai/src/features/recall/store.ts @@ -1,6 +1,7 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import { fuzzyScore } from '../command-palette/fuzzy' import type { KeyValueStore } from '../prompt-queue/queue' +import { uiConfig } from '../../ui/config' export interface ThreadRef { readonly path: string @@ -171,7 +172,7 @@ export class HistoryStore { } exportJson(): string { - return JSON.stringify({ app: 'better-perplexity', kind: 'recall', version: 1, exportedAt: new Date(this.now()).toISOString(), entries: [...this.entries.values()] }, null, 2) + return JSON.stringify({ app: uiConfig().id, kind: 'recall', version: 1, exportedAt: new Date(this.now()).toISOString(), entries: [...this.entries.values()] }, null, 2) } importJson(json: string): ImportResult { diff --git a/ai/perplexity/src/modules/recall/styles.ts b/core/ai/src/features/recall/styles.ts similarity index 91% rename from ai/perplexity/src/modules/recall/styles.ts rename to core/ai/src/features/recall/styles.ts index 50db0a5..9856775 100644 --- a/ai/perplexity/src/modules/recall/styles.ts +++ b/core/ai/src/features/recall/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-recall .bp-palette-list { max-height: 340px; } @@ -16,4 +17,4 @@ const CSS = ` .bp-recall-hint { padding: 8px 14px; border-top: 1px solid var(--bp-border); color: var(--bp-muted); font-size: 11px; } ` -export const ensureRecallStyles = (): void => injectStyle('better-perplexity-recall-styles', CSS) +export const ensureRecallStyles = (): void => injectStyle(`${uiConfig().id}-recall-styles`, CSS) diff --git a/core/ai/src/index.ts b/core/ai/src/index.ts index 50b6770..c90f7ba 100644 --- a/core/ai/src/index.ts +++ b/core/ai/src/index.ts @@ -3,13 +3,15 @@ export * from './automation' export * from './clipboard' export * from './composer' export * from './download' +export * from './features' export * from './generation' export * from './keys' export * from './placeholders' +export { configurePlatform, lazy } from './platform' +export type { Platform } from './platform' export * from './prompt' export * from './response-spy' export * from './selection' export * from './sse' export * from './tokens' export * from './ui' -export * from './features' diff --git a/core/ai/src/platform.ts b/core/ai/src/platform.ts new file mode 100644 index 0000000..1b27234 --- /dev/null +++ b/core/ai/src/platform.ts @@ -0,0 +1,53 @@ +import type { Logger, ScriptStorage } from '@nolly/core' +import type { ComposerKit } from './composer' +import type { GenerationKit } from './generation' +import type { PromptSender } from './prompt' + +export interface Platform { + readonly id: string + readonly storage: ScriptStorage + readonly logger: Logger + readonly composer: ComposerKit + readonly generation: GenerationKit + readonly sendPrompt: PromptSender + readonly onSend: (listener: () => void) => () => void + readonly threadOf: (pathname: string) => string | null + readonly promptsUrl: string +} + +let current: Platform | null = null + +export const configurePlatform = (platform: Platform): void => { + current = platform +} + +export const platform = (): Platform => { + if (!current) throw new Error('configurePlatform() must run before platform features are used.') + return current +} + +export const lazy = (create: () => T): T => { + let instance: T | null = null + const resolve = (): T => (instance ??= create()) + return new Proxy({} as T, { + get: (_target, key) => { + const target = resolve() + const value: unknown = Reflect.get(target, key, target) + return typeof value === 'function' ? value.bind(target) : value + }, + set: (_target, key, value) => Reflect.set(resolve(), key, value), + has: (_target, key) => Reflect.has(resolve(), key) + }) +} + +export const storage: ScriptStorage = lazy(() => platform().storage) +export const logger: Logger = lazy(() => platform().logger) + +export const findComposer: ComposerKit['findComposer'] = () => platform().composer.findComposer() +export const writeComposer: ComposerKit['writeComposer'] = (editable, text) => platform().composer.writeComposer(editable, text) +export const sendComposer: ComposerKit['sendComposer'] = (editable) => platform().composer.sendComposer(editable) +export const editableFrom: ComposerKit['editableFrom'] = (target) => platform().composer.editableFrom(target) +export const attachFile: ComposerKit['attachFile'] = (editable, file) => platform().composer.attachFile(editable, file) +export const isGenerating: GenerationKit['isGenerating'] = () => platform().generation.isGenerating() +export const waitForResponse: GenerationKit['waitForResponse'] = (options) => platform().generation.waitForResponse(options) +export const sendPrompt: PromptSender = (prompt, signal) => platform().sendPrompt(prompt, signal) diff --git a/core/ai/src/ui/config.ts b/core/ai/src/ui/config.ts index 0e3cb3f..5628da1 100644 --- a/core/ai/src/ui/config.ts +++ b/core/ai/src/ui/config.ts @@ -27,3 +27,5 @@ export const uiConfig = (): UiConfig => { } export const markUi: UiMarker['mark'] = (element) => uiConfig().marker.mark(element) + +export const isOwnUi: UiMarker['isOwn'] = (node) => uiConfig().marker.isOwn(node) From 39e82c291ffbd49e4458491331e382b4591b6761 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:39:35 +0100 Subject: [PATCH 09/19] fix(ai): repair hoisted dialog id constants --- core/ai/src/features/command-palette/dialog.ts | 2 +- core/ai/src/features/prompt-library/manager.ts | 2 +- core/ai/src/features/prompt-library/picker.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/ai/src/features/command-palette/dialog.ts b/core/ai/src/features/command-palette/dialog.ts index 9461b8e..5fba0ea 100644 --- a/core/ai/src/features/command-palette/dialog.ts +++ b/core/ai/src/features/command-palette/dialog.ts @@ -5,7 +5,7 @@ import { DEFAULT_SHORTCUT, formatShortcut, shortcutFromEvent, type Shortcut } fr import { ensurePaletteStyles } from './styles' import { uiConfig } from '../../ui/config' -const DIALOG_ID() = `${uiConfig().id}-shortcut-dialog` +const DIALOG_ID = (): string => `${uiConfig().id}-shortcut-dialog` export const toggleShortcutDialog = (current: Shortcut, onSave: (shortcut: Shortcut) => void, title = 'Palette shortcut', defaults: Shortcut = DEFAULT_SHORTCUT): void => { const existing = document.getElementById(DIALOG_ID()) diff --git a/core/ai/src/features/prompt-library/manager.ts b/core/ai/src/features/prompt-library/manager.ts index cd63ca2..5791e6c 100644 --- a/core/ai/src/features/prompt-library/manager.ts +++ b/core/ai/src/features/prompt-library/manager.ts @@ -6,7 +6,7 @@ import type { Prompt, PromptStore } from './store' import { ensureSlashStyles } from './styles' import { uiConfig } from '../../ui/config' -const DIALOG_ID() = `${uiConfig().id}-prompts-dialog` +const DIALOG_ID = (): string => `${uiConfig().id}-prompts-dialog` export const toggleManager = (store: PromptStore, onInsert: (prompt: Prompt) => void): void => { const existing = document.getElementById(DIALOG_ID()) diff --git a/core/ai/src/features/prompt-library/picker.ts b/core/ai/src/features/prompt-library/picker.ts index 4a81276..4ea355e 100644 --- a/core/ai/src/features/prompt-library/picker.ts +++ b/core/ai/src/features/prompt-library/picker.ts @@ -5,7 +5,7 @@ import { ensurePaletteStyles } from '../command-palette/styles' import type { Prompt, PromptStore } from './store' import { uiConfig } from '../../ui/config' -const DIALOG_ID() = `${uiConfig().id}-prompt-picker` +const DIALOG_ID = (): string => `${uiConfig().id}-prompt-picker` export interface PickerOptions { store: PromptStore From 277c33ce261ce20984dc02663b9533572c65c56b Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:43:07 +0100 Subject: [PATCH 10/19] feat(ai): hoist Batch Runner, Selection Toolbar and Max Width into @nolly/ai (step 7) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/main.ts | 5 +- ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/src/main.ts | 12 +- ai/perplexity/src/modules/max-width/index.ts | 79 ------------ ai/perplexity/src/modules/max-width/rules.ts | 13 +- core/ai/README.md | 2 +- .../ai/src/features}/batch-runner/dialog.ts | 10 +- .../ai/src/features}/batch-runner/index.ts | 6 +- .../ai/src/features}/batch-runner/panel.ts | 11 +- .../ai/src/features}/batch-runner/runner.ts | 8 +- .../ai/src/features}/batch-runner/template.ts | 0 core/ai/src/features/index.ts | 4 + core/ai/src/features/max-width/feature.ts | 116 ++++++++++++++++++ core/ai/src/features/max-width/index.ts | 2 + .../src/features}/max-width/style-manager.ts | 4 +- .../src/features}/selection-toolbar/index.ts | 13 +- 17 files changed, 165 insertions(+), 122 deletions(-) delete mode 100644 ai/perplexity/src/modules/max-width/index.ts rename {ai/perplexity/src/modules => core/ai/src/features}/batch-runner/dialog.ts (92%) rename {ai/perplexity/src/modules => core/ai/src/features}/batch-runner/index.ts (91%) rename {ai/perplexity/src/modules => core/ai/src/features}/batch-runner/panel.ts (91%) rename {ai/perplexity/src/modules => core/ai/src/features}/batch-runner/runner.ts (91%) rename {ai/perplexity/src/modules => core/ai/src/features}/batch-runner/template.ts (100%) create mode 100644 core/ai/src/features/max-width/feature.ts create mode 100644 core/ai/src/features/max-width/index.ts rename {ai/perplexity/src/modules => core/ai/src/features}/max-width/style-manager.ts (97%) rename {ai/perplexity/src/modules => core/ai/src/features}/selection-toolbar/index.ts (92%) diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index cf8cb96..c5530e1 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -2,6 +2,7 @@ ## [0.1.0] - 2026-11-10 +- Batch Runner, Selection Toolbar (Ask, Explain, Summarize, Fact-check, Quote) and Max Width. - Initial skeleton: composer and header detection, response observer, session state and diagnostics. - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. - Draft Guard: autosaved drafts, size meter and unsent-text warning. diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 758ad44..db33cfc 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,4 +1,4 @@ -import { CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' import { SPLITTER_DEFAULTS } from './config' @@ -41,8 +41,11 @@ 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 EnterAsNewlineFeature(context, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) + .register((context) => new BatchRunnerFeature(context)) .register((context) => new DraftGuardFeature(context, { storage, composer: composerKit, onSend, tokenLimit: () => loadSplitterSettings(storage, SPLITTER_DEFAULTS).limit })) .register((context) => new CommandPaletteFeature(context)) .register((context) => new PromptQueueFeature(context)) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 45ae41b..fb5a8bf 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: Enter as Newline now comes from the shared package. - Internal: Draft Guard now comes from the shared package. - Internal: Message Splitter now comes from the shared package. +- Internal: Batch Runner, Selection Toolbar and Max Width now come from the shared package. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index b2996cb..f28d171 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,4 +1,4 @@ -import { CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' import { composerKit, findComposer, writeComposer } from './core/composer' import { sendPrompt } from './core/dispatch' @@ -10,12 +10,10 @@ import { isAskRequest } from './core/requests' import { storage } from './core/storage' import { threadOf } from './core/threads' import { findComposerActions } from './locate' -import { BatchRunnerModule } from './modules/batch-runner' import { CodeBlocksModule } from './modules/code-blocks' import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' -import { MaxWidthModule } from './modules/max-width' -import { SelectionToolbarModule } from './modules/selection-toolbar' +import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR } from './modules/max-width/rules' import { TutorialModule } from './modules/tutorial' import { UpdatesModule } from './modules/updates' import { UsageStatusModule } from './modules/usage-status' @@ -39,12 +37,12 @@ fetchSpy.install() new App() .register((context) => new PromptLibraryFeature(context)) - .register((context) => new SelectionToolbarModule(context)) - .register((context) => new MaxWidthModule(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, { storage })) .register((context) => new CodeBlocksModule(context)) .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit })) - .register((context) => new BatchRunnerModule(context)) + .register((context) => new BatchRunnerFeature(context)) .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend, tokenLimit: () => loadSplitterSettings(storage).limit })) .register((context) => new CommandPaletteFeature(context)) .register((context) => new ExporterModule(context)) diff --git a/ai/perplexity/src/modules/max-width/index.ts b/ai/perplexity/src/modules/max-width/index.ts deleted file mode 100644 index 28dafaa..0000000 --- a/ai/perplexity/src/modules/max-width/index.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { Feature, getElement, type MenuEntry } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR, type HideRule } from './rules' -import { StyleManager } from './style-manager' - -const SIDEBAR_KEY = 'max-width:remove-sidebar' -const CONSTRAINED = 'main [class*="max-w-"], main [style*="max-width"]' -const OVERLAYS = '[role="dialog"], [role="menu"], [role="listbox"], [role="tooltip"], dialog, [data-radix-popper-content-wrapper]' -const MIN_CONSTRAINT = 480 -const SCAN_INTERVAL = 1_200 - -export class MaxWidthModule extends Feature { - readonly id = 'max-width' - readonly name = 'Max Width' - readonly description = 'Remove width restrictions and expand the interface.' - - private readonly styles = new StyleManager() - private readonly touched = new Set() - private scannedAt = 0 - - get removeSidebar(): boolean { - return storage.get(SIDEBAR_KEY, true) - } - - set removeSidebar(value: boolean) { - storage.set(SIDEBAR_KEY, value) - } - - run(): void { - const active = this.enabled - for (const rule of ALWAYS_HIDDEN) this.syncHidden(rule, active) - this.syncHidden(RIGHT_SIDEBAR, active && this.removeSidebar) - for (const { xpath, styles } of LAYOUT_RULES) { - const element = getElement(xpath) - if (!element) continue - if (active) this.styles.apply(element, styles) - else this.styles.restore(element, Object.keys(styles)) - } - this.expand(active) - } - - override menuEntries(): MenuEntry[] { - return [{ label: `${this.removeSidebar ? 'Show' : 'Remove'} Right Sidebar`, action: () => this.toggleSidebar() }] - } - - private expand(active: boolean): void { - if (!active) { - for (const element of this.touched) this.styles.restore(element, ['max-width']) - this.touched.clear() - return - } - const now = Date.now() - if (now - this.scannedAt < SCAN_INTERVAL) return - this.scannedAt = now - for (const element of this.touched) if (!element.isConnected) this.touched.delete(element) - for (const element of document.querySelectorAll(CONSTRAINED)) { - if (this.touched.has(element) || isOwnUi(element) || element.closest(OVERLAYS)) continue - const limit = Number.parseFloat(getComputedStyle(element).maxWidth) - if (!Number.isFinite(limit) || limit < MIN_CONSTRAINT) continue - if (element.getBoundingClientRect().width < limit * 0.9) continue - this.styles.apply(element, { 'max-width': '100%' }) - this.touched.add(element) - } - } - - private syncHidden(rule: HideRule, hidden: boolean): void { - const element = getElement(rule.xpath) - if (element) this.styles.setHidden(element, hidden, rule.xpath) - } - - private toggleSidebar(): void { - this.removeSidebar = !this.removeSidebar - logger.info(`Right sidebar removal ${this.removeSidebar ? 'enabled' : 'disabled'}.`) - this.context.refreshMenu() - this.context.requestUpdate() - } -} diff --git a/ai/perplexity/src/modules/max-width/rules.ts b/ai/perplexity/src/modules/max-width/rules.ts index 1fbc518..94a63c3 100644 --- a/ai/perplexity/src/modules/max-width/rules.ts +++ b/ai/perplexity/src/modules/max-width/rules.ts @@ -1,15 +1,6 @@ +import type { HideRule, LayoutRule } from '@nolly/ai' import { CONTENT, ROOT } from '../../selectors' -export interface HideRule { - readonly id: string - readonly xpath: string -} - -export interface LayoutRule { - readonly xpath: string - readonly styles: Readonly> -} - const FULL = { width: '100%', 'max-width': '100%' } as const export const RIGHT_SIDEBAR: HideRule = { id: 'right-sidebar', xpath: `${CONTENT}[2]` } @@ -31,4 +22,4 @@ export const LAYOUT_RULES: readonly LayoutRule[] = [ { xpath: `${CONTENT}[4]/div`, styles: FULL }, { xpath: `${ROOT}/div[5]/div`, styles: { ...FULL, 'padding-left': '1rem', 'padding-right': '1rem' } }, { xpath: `${ROOT}/div[5]/div/div`, styles: { ...FULL, padding: '0' } } -] \ No newline at end of file +] diff --git a/core/ai/README.md b/core/ai/README.md index b9fea5a..dada51e 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,7 +10,7 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline, Draft Guard, and Message Splitter. +- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, and Max Width. - Prompt Library, Command Palette, Prompt Queue and Recall. Platforms register once with `configurePlatform` and `configureUi`. diff --git a/ai/perplexity/src/modules/batch-runner/dialog.ts b/core/ai/src/features/batch-runner/dialog.ts similarity index 92% rename from ai/perplexity/src/modules/batch-runner/dialog.ts rename to core/ai/src/features/batch-runner/dialog.ts index 5d53b75..b7c0e51 100644 --- a/ai/perplexity/src/modules/batch-runner/dialog.ts +++ b/core/ai/src/features/batch-runner/dialog.ts @@ -1,8 +1,10 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSwitch, createTextArea, createDialog } from '@nolly/ai' +import { createButton, createNumberField, createSwitch, createTextArea } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' import { parseItems, renderTemplate } from './template' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-batch-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-batch-dialog` const MAX_ITEMS = 200 const PREVIEWS = 3 @@ -35,8 +37,8 @@ const section = (step: number, title: string, help: string, tour: string): { roo } export const openBatchDialog = (onStart: (input: BatchInput) => void): void => { - if (document.getElementById(DIALOG_ID)) return - const ui = createDialog({ id: DIALOG_ID, title: 'Batch Runner', description: 'Send the same kind of message many times, one after another, in this conversation.', width: 700 }) + if (document.getElementById(DIALOG_ID())) return + const ui = createDialog({ id: DIALOG_ID(), title: 'Batch Runner', description: 'Send the same kind of message many times, one after another, in this conversation.', width: 700 }) let template = '' let items = '' let delay = 2 diff --git a/ai/perplexity/src/modules/batch-runner/index.ts b/core/ai/src/features/batch-runner/index.ts similarity index 91% rename from ai/perplexity/src/modules/batch-runner/index.ts rename to core/ai/src/features/batch-runner/index.ts index 1070eee..da75c25 100644 --- a/ai/perplexity/src/modules/batch-runner/index.ts +++ b/core/ai/src/features/batch-runner/index.ts @@ -1,11 +1,13 @@ import { Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { ComposerButton, applyValues, findFields, askFields } from '@nolly/ai' +import { ComposerButton } from '../../ui/composer-button' +import { applyValues, findFields } from '../../placeholders' +import { askFields } from '../../ui/placeholder-dialog' import { openBatchDialog, type BatchInput } from './dialog' import { renderTemplate } from './template' import { BatchPanel } from './panel' import { BatchRunner, clearState, loadState, type BatchState } from './runner' -export class BatchRunnerModule extends Feature { +export class BatchRunnerFeature extends Feature { readonly id = 'batch-runner' readonly name = 'Batch Runner' readonly description = 'Send one templated message per item, one after another.' diff --git a/ai/perplexity/src/modules/batch-runner/panel.ts b/core/ai/src/features/batch-runner/panel.ts similarity index 91% rename from ai/perplexity/src/modules/batch-runner/panel.ts rename to core/ai/src/features/batch-runner/panel.ts index 96daa75..863ec1d 100644 --- a/ai/perplexity/src/modules/batch-runner/panel.ts +++ b/core/ai/src/features/batch-runner/panel.ts @@ -1,9 +1,10 @@ import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' -import { createButton, ensureUiStyles } from '@nolly/ai' +import { markUi, uiConfig } from '../../ui/config' +import { createButton } from '../../ui/controls' +import { ensureUiStyles } from '../../ui/styles' import type { BatchPhase, BatchResult } from './runner' -const CSS_ID = 'better-perplexity-batch-styles' +const CSS_ID = (): string => `${uiConfig().id}-batch-styles` const PHASE_TEXT: Readonly> = { sending: 'sending', waiting: 'waiting for the answer', paused: 'paused', resting: 'resting' } @@ -15,9 +16,9 @@ export class BatchPanel { constructor() { ensureUiStyles() - if (!document.getElementById(CSS_ID)) { + if (!document.getElementById(CSS_ID())) { const style = createElement('style') - style.id = CSS_ID + style.id = CSS_ID() style.textContent = ` .bp-batch-panel { position: fixed; right: 20px; bottom: 20px; z-index: 100000; display: flex; flex-direction: column; gap: 8px; width: 300px; padding: 12px 14px; border: 1px solid var(--bp-border); border-radius: 12px; background: var(--bp-bg); color: var(--bp-fg); box-shadow: 0 12px 32px rgb(0 0 0 / 22%); font-size: 12px; } .bp-batch-actions { display: flex; gap: 6px; flex-wrap: wrap; } diff --git a/ai/perplexity/src/modules/batch-runner/runner.ts b/core/ai/src/features/batch-runner/runner.ts similarity index 91% rename from ai/perplexity/src/modules/batch-runner/runner.ts rename to core/ai/src/features/batch-runner/runner.ts index 470c499..e4e54d1 100644 --- a/ai/perplexity/src/modules/batch-runner/runner.ts +++ b/core/ai/src/features/batch-runner/runner.ts @@ -1,8 +1,6 @@ -import { automate, readComposer } from '@nolly/ai' -import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { waitForResponse } from '../../core/generation' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' +import { automate } from '../../automation' +import { readComposer } from '../../composer' +import { findComposer, sendComposer, writeComposer, waitForResponse, logger, storage } from '../../platform' import { isAbort, sleep, waitFor } from '@nolly/core' export interface BatchState { diff --git a/ai/perplexity/src/modules/batch-runner/template.ts b/core/ai/src/features/batch-runner/template.ts similarity index 100% rename from ai/perplexity/src/modules/batch-runner/template.ts rename to core/ai/src/features/batch-runner/template.ts diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 2af8b4d..37d3eb4 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -8,3 +8,7 @@ export { CommandPaletteFeature } from './command-palette' export { PromptQueueFeature } from './prompt-queue' export { PromptLibraryFeature } from './prompt-library' export { RecallFeature } from './recall' +export { BatchRunnerFeature } from './batch-runner' +export { SelectionToolbarFeature } from './selection-toolbar' +export { MaxWidthFeature } from './max-width' +export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './max-width' diff --git a/core/ai/src/features/max-width/feature.ts b/core/ai/src/features/max-width/feature.ts new file mode 100644 index 0000000..c301512 --- /dev/null +++ b/core/ai/src/features/max-width/feature.ts @@ -0,0 +1,116 @@ +import { Feature, getElement } from '@nolly/core' +import type { MenuEntry, ScriptContext, ScriptStorage } from '@nolly/core' +import { isOwnUi } from '../../ui/config' +import { StyleManager } from './style-manager' + +const SIDEBAR_KEY = 'max-width:remove-sidebar' +const DEFAULT_CONSTRAINED = 'main [class*="max-w-"], main [style*="max-width"]' +const OVERLAYS = '[role="dialog"], [role="menu"], [role="listbox"], [role="tooltip"], dialog, [data-radix-popper-content-wrapper]' +const MIN_CONSTRAINT = 480 +const SCAN_INTERVAL = 1_200 + +export interface Target { + readonly xpath?: string + readonly selector?: string +} + +export interface HideRule extends Target { + readonly id: string +} + +export interface LayoutRule extends Target { + readonly styles: Readonly> +} + +export interface SidebarOption { + readonly rule: HideRule + readonly label: string + readonly defaultRemoved: boolean +} + +export interface MaxWidthOptions { + readonly storage: ScriptStorage + readonly hidden?: readonly HideRule[] + readonly layout?: readonly LayoutRule[] + readonly sidebar?: SidebarOption + readonly constrained?: string +} + +const resolveTarget = ({ xpath, selector }: Target): HTMLElement | null => { + if (xpath) return getElement(xpath) + return selector ? document.querySelector(selector) : null +} + +const labelOf = (rule: HideRule): string => rule.xpath ?? rule.selector ?? rule.id + +export class MaxWidthFeature extends Feature { + readonly id = 'max-width' + readonly name = 'Max Width' + readonly description = 'Remove width restrictions and expand the interface.' + + private readonly styles = new StyleManager() + private readonly touched = new Set() + private scannedAt = 0 + + constructor(context: ScriptContext, private readonly options: MaxWidthOptions) { + super(context) + } + + get removeSidebar(): boolean { + return this.options.storage.get(SIDEBAR_KEY, this.options.sidebar?.defaultRemoved ?? false) + } + + set removeSidebar(value: boolean) { + this.options.storage.set(SIDEBAR_KEY, value) + } + + run(): void { + const active = this.enabled + for (const rule of this.options.hidden ?? []) this.syncHidden(rule, active) + if (this.options.sidebar) this.syncHidden(this.options.sidebar.rule, active && this.removeSidebar) + for (const rule of this.options.layout ?? []) { + const element = resolveTarget(rule) + if (!element) continue + if (active) this.styles.apply(element, rule.styles) + else this.styles.restore(element, Object.keys(rule.styles)) + } + this.expand(active) + } + + override menuEntries(): MenuEntry[] { + const { sidebar } = this.options + return sidebar ? [{ label: `${this.removeSidebar ? 'Show' : 'Remove'} ${sidebar.label}`, action: () => this.toggleSidebar(sidebar) }] : [] + } + + private expand(active: boolean): void { + if (!active) { + for (const element of this.touched) this.styles.restore(element, ['max-width']) + this.touched.clear() + return + } + const now = Date.now() + if (now - this.scannedAt < SCAN_INTERVAL) return + this.scannedAt = now + for (const element of this.touched) if (!element.isConnected) this.touched.delete(element) + for (const element of document.querySelectorAll(this.options.constrained ?? DEFAULT_CONSTRAINED)) { + if (this.touched.has(element) || isOwnUi(element) || element.closest(OVERLAYS)) continue + const limit = Number.parseFloat(getComputedStyle(element).maxWidth) + if (!Number.isFinite(limit) || limit < MIN_CONSTRAINT) continue + if (element.getBoundingClientRect().width < limit * 0.9) continue + this.styles.apply(element, { 'max-width': '100%' }) + this.touched.add(element) + } + } + + private syncHidden(rule: HideRule, hidden: boolean): void { + const element = resolveTarget(rule) + if (element) this.styles.setHidden(element, hidden, labelOf(rule)) + } + + private toggleSidebar(sidebar: SidebarOption): void { + this.removeSidebar = !this.removeSidebar + this.context.logger.info(`${sidebar.label} removal ${this.removeSidebar ? 'enabled' : 'disabled'}.`) + this.context.refreshMenu() + this.context.requestUpdate() + } +} diff --git a/core/ai/src/features/max-width/index.ts b/core/ai/src/features/max-width/index.ts new file mode 100644 index 0000000..c184556 --- /dev/null +++ b/core/ai/src/features/max-width/index.ts @@ -0,0 +1,2 @@ +export { MaxWidthFeature } from './feature' +export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './feature' diff --git a/ai/perplexity/src/modules/max-width/style-manager.ts b/core/ai/src/features/max-width/style-manager.ts similarity index 97% rename from ai/perplexity/src/modules/max-width/style-manager.ts rename to core/ai/src/features/max-width/style-manager.ts index 70f3dda..c86237b 100644 --- a/ai/perplexity/src/modules/max-width/style-manager.ts +++ b/core/ai/src/features/max-width/style-manager.ts @@ -1,4 +1,4 @@ -import { logger } from '../../core/logger' +import { logger } from '../../platform' interface OriginalValue { readonly value: string @@ -47,4 +47,4 @@ export class StyleManager { this.hidden.delete(element) logger.debug('Element restored.', label) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/selection-toolbar/index.ts b/core/ai/src/features/selection-toolbar/index.ts similarity index 92% rename from ai/perplexity/src/modules/selection-toolbar/index.ts rename to core/ai/src/features/selection-toolbar/index.ts index 4b2b5ef..ffd3188 100644 --- a/ai/perplexity/src/modules/selection-toolbar/index.ts +++ b/core/ai/src/features/selection-toolbar/index.ts @@ -1,7 +1,10 @@ -import { findComposer, sendComposer, writeComposer } from '../../core/composer' -import { readComposer, rememberSelection, ensureUiStyles, askFields } from '@nolly/ai' +import { findComposer, sendComposer, writeComposer } from '../../platform' +import { readComposer } from '../../composer' +import { rememberSelection } from '../../selection' +import { ensureUiStyles } from '../../ui/styles' +import { askFields } from '../../ui/placeholder-dialog' import { createElement, Feature, injectStyle, type MenuEntry } from '@nolly/core' -import { isOwnUi, markUi } from '../../core/dom' +import { isOwnUi, markUi, uiConfig } from '../../ui/config' interface Action { id: string @@ -36,7 +39,7 @@ const ACTIONS: readonly Action[] = [ { id: 'quote', label: 'Quote', title: 'Quote in the message box', compose: async (selected) => `${quote(selected)}\n\n` } ] -export class SelectionToolbarModule extends Feature { +export class SelectionToolbarFeature extends Feature { readonly id = 'selection-toolbar' readonly name = 'Selection Toolbar' readonly description = 'Ask, explain, summarize or quote any selected text.' @@ -48,7 +51,7 @@ export class SelectionToolbarModule extends Feature { constructor(context: ConstructorParameters[0]) { super(context) ensureUiStyles() - injectStyle('better-perplexity-selection-styles', CSS) + injectStyle(`${uiConfig().id}-selection-styles`, CSS) for (const action of ACTIONS) { const button = createElement('button', undefined, action.label) button.type = 'button' From b9890b3d334678e7b9ba08f681fc9730eb7ce556 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:45:59 +0100 Subject: [PATCH 11/19] fix(perplexity): import tutorial shortcut helpers from @nolly/ai --- ai/perplexity/src/modules/tutorial/engine.ts | 3 +-- ai/perplexity/src/modules/tutorial/tours.ts | 4 +--- core/ai/src/features/index.ts | 3 +++ 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ai/perplexity/src/modules/tutorial/engine.ts b/ai/perplexity/src/modules/tutorial/engine.ts index 4625e2f..d50576a 100644 --- a/ai/perplexity/src/modules/tutorial/engine.ts +++ b/ai/perplexity/src/modules/tutorial/engine.ts @@ -1,7 +1,6 @@ import { createElement } from '@nolly/core' import { markUi } from '../../core/dom' -import { createButton, ensureUiStyles } from '@nolly/ai' -import { formatShortcut, matchesShortcut, type Shortcut } from '../command-palette/shortcut' +import { createButton, ensureUiStyles, formatShortcut, matchesShortcut, type Shortcut } from '@nolly/ai' import { ensureTourStyles } from './styles' export interface Step { diff --git a/ai/perplexity/src/modules/tutorial/tours.ts b/ai/perplexity/src/modules/tutorial/tours.ts index d72187e..a885f5b 100644 --- a/ai/perplexity/src/modules/tutorial/tours.ts +++ b/ai/perplexity/src/modules/tutorial/tours.ts @@ -1,7 +1,5 @@ import { findComposer } from '../../core/composer' -import { loadShortcut } from '../command-palette/shortcut' -import { loadPromptShortcut } from '../prompt-library/shortcut' -import type { Shortcut } from '../command-palette/shortcut' +import { loadPromptShortcut, loadShortcut, type Shortcut } from '@nolly/ai' import type { Step } from './engine' export interface Tour { diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 37d3eb4..b494d8d 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -12,3 +12,6 @@ export { BatchRunnerFeature } from './batch-runner' export { SelectionToolbarFeature } from './selection-toolbar' export { MaxWidthFeature } from './max-width' export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './max-width' +export { formatShortcut, loadShortcut, matchesShortcut } from './command-palette/shortcut' +export type { Shortcut } from './command-palette/shortcut' +export { loadPromptShortcut } from './prompt-library/shortcut' From 67f6a850c4820b49c24182189f7fe40ab874bd54 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 10:50:15 +0100 Subject: [PATCH 12/19] feat(ai): hoist Code Block Pro into @nolly/ai and enable it in better-chatgpt (step 8) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/main.ts | 6 +- ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/src/main.ts | 5 +- core/ai/README.md | 2 +- .../ai/src/features}/code-blocks/badges.ts | 2 +- .../ai/src/features}/code-blocks/block.ts | 5 +- .../ai/src/features}/code-blocks/detect.ts | 5 +- .../ai/src/features}/code-blocks/dialog.ts | 10 +- .../ai/src/features}/code-blocks/guess.ts | 0 .../ai/src/features}/code-blocks/highlight.ts | 0 .../ai/src/features}/code-blocks/index.ts | 9 +- .../ai/src/features}/code-blocks/languages.ts | 0 .../ai/src/features}/code-blocks/lines.ts | 0 .../ai/src/features}/code-blocks/settings.ts | 2 +- .../ai/src/features}/code-blocks/styles.ts | 3 +- core/ai/src/features/index.ts | 1 + core/ai/src/platform.ts | 1 + scripts/hoist-module.mjs | 182 ++++++++++++++++++ 19 files changed, 214 insertions(+), 21 deletions(-) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/badges.ts (98%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/block.ts (98%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/detect.ts (96%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/dialog.ts (81%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/guess.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/highlight.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/index.ts (94%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/languages.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/lines.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/settings.ts (93%) rename {ai/perplexity/src/modules => core/ai/src/features}/code-blocks/styles.ts (97%) create mode 100644 scripts/hoist-module.mjs diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index c5530e1..f63c9de 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -7,4 +7,5 @@ - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. - Draft Guard: autosaved drafts, size meter and unsent-text warning. - Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). +- Code Block Pro: language badges, highlighting, line numbers, wrap, fold, copy and download. - Prompt Library (shared community prompts), Command Palette, Message Queue and Recall. diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index db33cfc..8994c66 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,4 +1,4 @@ -import { BatchRunnerFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' import { SPLITTER_DEFAULTS } from './config' @@ -33,7 +33,8 @@ configurePlatform({ sendPrompt, onSend, threadOf, - promptsUrl: URLS.prompts + promptsUrl: URLS.prompts, + codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]') }) installTheme() @@ -43,6 +44,7 @@ new App() .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, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) .register((context) => new BatchRunnerFeature(context)) diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index fb5a8bf..c7cf1c9 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: Enter as Newline now comes from the shared package. - Internal: Draft Guard now comes from the shared package. - Internal: Message Splitter now comes from the shared package. +- Internal: Code Block Pro now comes from the shared package. - Internal: Batch Runner, Selection Toolbar and Max Width now come from the shared package. - Fixed: the batch runner was registered twice. diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index f28d171..bdf8a6f 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,4 +1,4 @@ -import { BatchRunnerFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' import { composerKit, findComposer, writeComposer } from './core/composer' import { sendPrompt } from './core/dispatch' @@ -10,7 +10,6 @@ import { isAskRequest } from './core/requests' import { storage } from './core/storage' import { threadOf } from './core/threads' import { findComposerActions } from './locate' -import { CodeBlocksModule } from './modules/code-blocks' import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR } from './modules/max-width/rules' @@ -40,7 +39,7 @@ new App() .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, { storage })) - .register((context) => new CodeBlocksModule(context)) + .register((context) => new CodeBlocksFeature(context)) .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit })) .register((context) => new BatchRunnerFeature(context)) .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend, tokenLimit: () => loadSplitterSettings(storage).limit })) diff --git a/core/ai/README.md b/core/ai/README.md index dada51e..3d62a6f 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,7 +10,7 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, and Max Width. +- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, Max Width, and Code Blocks. - Prompt Library, Command Palette, Prompt Queue and Recall. Platforms register once with `configurePlatform` and `configureUi`. diff --git a/ai/perplexity/src/modules/code-blocks/badges.ts b/core/ai/src/features/code-blocks/badges.ts similarity index 98% rename from ai/perplexity/src/modules/code-blocks/badges.ts rename to core/ai/src/features/code-blocks/badges.ts index 11fd67e..373543e 100644 --- a/ai/perplexity/src/modules/code-blocks/badges.ts +++ b/core/ai/src/features/code-blocks/badges.ts @@ -1,5 +1,5 @@ import { createElement } from '@nolly/core' -import { createIcon } from '@nolly/ai' +import { createIcon } from '../../ui/icons' type Badge = readonly [label: string, background: string, color: string] diff --git a/ai/perplexity/src/modules/code-blocks/block.ts b/core/ai/src/features/code-blocks/block.ts similarity index 98% rename from ai/perplexity/src/modules/code-blocks/block.ts rename to core/ai/src/features/code-blocks/block.ts index de74449..1c32602 100644 --- a/ai/perplexity/src/modules/code-blocks/block.ts +++ b/core/ai/src/features/code-blocks/block.ts @@ -1,6 +1,7 @@ -import { copyText, createIcon, type IconName } from '@nolly/ai' +import { copyText } from '../../clipboard' +import { createIcon, type IconName } from '../../ui/icons' import { createElement } from '@nolly/core' -import { markUi } from '../../core/dom' +import { markUi } from '../../ui/config' import type { BlockInfo } from './detect' import { highlightLines } from './highlight' import { languageInfo } from './languages' diff --git a/ai/perplexity/src/modules/code-blocks/detect.ts b/core/ai/src/features/code-blocks/detect.ts similarity index 96% rename from ai/perplexity/src/modules/code-blocks/detect.ts rename to core/ai/src/features/code-blocks/detect.ts index 1fd3946..f56f084 100644 --- a/ai/perplexity/src/modules/code-blocks/detect.ts +++ b/core/ai/src/features/code-blocks/detect.ts @@ -1,3 +1,4 @@ +import { platform } from '../../platform' import { guessLanguage } from './guess' import { isKnownLanguage, languageForFilename, normalizeLanguage } from './languages' @@ -46,6 +47,8 @@ export const detectLanguage = (pre: HTMLElement, root: HTMLElement, text: string export const findBlockRoot = (pre: HTMLElement, includeChrome: boolean): HTMLElement => { if (!includeChrome) return pre + const custom = platform().codeBlockRoot?.(pre) + if (custom) return custom const codeLength = (pre.textContent ?? '').length let root = pre for (let depth = 0; depth < 3; depth++) { @@ -60,4 +63,4 @@ export const findBlockRoot = (pre: HTMLElement, includeChrome: boolean): HTMLEle export const analyze = (pre: HTMLElement, root: HTMLElement, text: string): BlockInfo => { const filename = guessFilename(text, root, pre) return { language: detectLanguage(pre, root, text, filename), filename, text } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/code-blocks/dialog.ts b/core/ai/src/features/code-blocks/dialog.ts similarity index 81% rename from ai/perplexity/src/modules/code-blocks/dialog.ts rename to core/ai/src/features/code-blocks/dialog.ts index 527e224..0821ca3 100644 --- a/ai/perplexity/src/modules/code-blocks/dialog.ts +++ b/core/ai/src/features/code-blocks/dialog.ts @@ -1,16 +1,18 @@ import { createElement } from '@nolly/core' -import { createButton, createNumberField, createSelectField, createSwitch, createDialog } from '@nolly/ai' +import { createButton, createNumberField, createSelectField, createSwitch } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' import { DEFAULT_CODE_SETTINGS, type CodeBlockSettings } from './settings' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-code-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-code-dialog` export const toggleCodeSettingsDialog = (current: CodeBlockSettings, onSave: (settings: CodeBlockSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Code Block Pro', description: 'Applies to code blocks as soon as an answer finishes.', width: 460 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Code Block Pro', description: 'Applies to code blocks as soon as an answer finishes.', width: 460 }) const draft: CodeBlockSettings = { ...current } const stack = createElement('div', 'bp-stack') stack.append( diff --git a/ai/perplexity/src/modules/code-blocks/guess.ts b/core/ai/src/features/code-blocks/guess.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/guess.ts rename to core/ai/src/features/code-blocks/guess.ts diff --git a/ai/perplexity/src/modules/code-blocks/highlight.ts b/core/ai/src/features/code-blocks/highlight.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/highlight.ts rename to core/ai/src/features/code-blocks/highlight.ts diff --git a/ai/perplexity/src/modules/code-blocks/index.ts b/core/ai/src/features/code-blocks/index.ts similarity index 94% rename from ai/perplexity/src/modules/code-blocks/index.ts rename to core/ai/src/features/code-blocks/index.ts index 6772f77..72318d0 100644 --- a/ai/perplexity/src/modules/code-blocks/index.ts +++ b/core/ai/src/features/code-blocks/index.ts @@ -1,8 +1,7 @@ -import { copyText } from '@nolly/ai' +import { copyText } from '../../clipboard' import { Feature, type MenuEntry } from '@nolly/core' -import { isOwnUi } from '../../core/dom' -import { isGenerating } from '../../core/generation' -import { logger } from '../../core/logger' +import { isOwnUi } from '../../ui/config' +import { isGenerating, logger } from '../../platform' import { EnhancedBlock } from './block' import { toggleCodeSettingsDialog } from './dialog' import { analyze, findBlockRoot, readCode } from './detect' @@ -12,7 +11,7 @@ const STABLE_MS = 900 const FORCE_MS = 6_000 const RESCAN_MS = 500 -export class CodeBlocksModule extends Feature { +export class CodeBlocksFeature extends Feature { readonly id = 'code-blocks' readonly name = 'Code Block Pro' readonly description = 'Replaces code blocks with copy, wrap, line numbers, folding and download.' diff --git a/ai/perplexity/src/modules/code-blocks/languages.ts b/core/ai/src/features/code-blocks/languages.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/languages.ts rename to core/ai/src/features/code-blocks/languages.ts diff --git a/ai/perplexity/src/modules/code-blocks/lines.ts b/core/ai/src/features/code-blocks/lines.ts similarity index 100% rename from ai/perplexity/src/modules/code-blocks/lines.ts rename to core/ai/src/features/code-blocks/lines.ts diff --git a/ai/perplexity/src/modules/code-blocks/settings.ts b/core/ai/src/features/code-blocks/settings.ts similarity index 93% rename from ai/perplexity/src/modules/code-blocks/settings.ts rename to core/ai/src/features/code-blocks/settings.ts index 5663b15..57a0d19 100644 --- a/ai/perplexity/src/modules/code-blocks/settings.ts +++ b/core/ai/src/features/code-blocks/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' export interface CodeBlockSettings { collapseAfter: number diff --git a/ai/perplexity/src/modules/code-blocks/styles.ts b/core/ai/src/features/code-blocks/styles.ts similarity index 97% rename from ai/perplexity/src/modules/code-blocks/styles.ts rename to core/ai/src/features/code-blocks/styles.ts index fd2ff4e..9510f61 100644 --- a/ai/perplexity/src/modules/code-blocks/styles.ts +++ b/core/ai/src/features/code-blocks/styles.ts @@ -1,4 +1,5 @@ import { injectStyle } from '@nolly/core' +import { uiConfig } from '../../ui/config' const CSS = ` .bp-code { @@ -142,4 +143,4 @@ const CSS = ` .bp-lang-plain { color: var(--bp-muted); } ` -export const ensureCodeStyles = (): void => injectStyle('better-perplexity-code-styles', CSS) \ No newline at end of file +export const ensureCodeStyles = (): void => injectStyle(`${uiConfig().id}-code-styles`, CSS) \ No newline at end of file diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index b494d8d..86c356b 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -15,3 +15,4 @@ export type { HideRule, LayoutRule, MaxWidthOptions, SidebarOption } from './max export { formatShortcut, loadShortcut, matchesShortcut } from './command-palette/shortcut' export type { Shortcut } from './command-palette/shortcut' export { loadPromptShortcut } from './prompt-library/shortcut' +export { CodeBlocksFeature } from './code-blocks' diff --git a/core/ai/src/platform.ts b/core/ai/src/platform.ts index 1b27234..088e252 100644 --- a/core/ai/src/platform.ts +++ b/core/ai/src/platform.ts @@ -13,6 +13,7 @@ export interface Platform { readonly onSend: (listener: () => void) => () => void readonly threadOf: (pathname: string) => string | null readonly promptsUrl: string + readonly codeBlockRoot?: (pre: HTMLElement) => HTMLElement | null } let current: Platform | null = null diff --git a/scripts/hoist-module.mjs b/scripts/hoist-module.mjs new file mode 100644 index 0000000..432e3de --- /dev/null +++ b/scripts/hoist-module.mjs @@ -0,0 +1,182 @@ +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs' +import { dirname, join, relative, resolve, sep } from 'node:path' + +const ROOT = process.cwd() +const SOURCE = resolve(ROOT, 'ai/perplexity/src/modules') +const SRC = resolve(ROOT, 'core/ai/src') +const FEATURES = join(SRC, 'features') +const PLATFORM_NAMES = new Set(['storage', 'logger', 'composer', 'generation', 'dispatch']) +const IMPORT = /\b(import|export)\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'/g +const EXPORT_DECL = /^export\s+(?:declare\s+)?(?:async\s+)?(?:const|let|function|class|interface|type|enum)\s+(\w+)/gm +const EXPORT_DESTRUCTURE = /^export\s+const\s+\{([^}]*)\}\s*=/gm +const EXPORT_LIST = /^export\s+(?:type\s+)?\{([^}]*)\}/gm + +const modules = process.argv.slice(2) +if (!modules.length) { + console.error('Usage: bun scripts/hoist-module.mjs [...]') + process.exit(1) +} + +const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)])) +const posix = (path) => path.split(sep).join('/') +const names = (list) => list.split(',').map((name) => name.trim()).filter(Boolean) +const bare = (name) => name.replace(/^type\s+/, '') + +const move = (from, to) => { + mkdirSync(dirname(to), { recursive: true }) + try { + execFileSync('git', ['mv', from, to], { stdio: 'pipe' }) + } catch { + renameSync(from, to) + } +} + +const scanExports = () => { + const map = new Map() + for (const file of walk(SRC).filter((entry) => entry.endsWith('.ts') && !entry.endsWith(`${sep}index.ts`))) { + const source = readFileSync(file, 'utf8') + const found = [ + ...[...source.matchAll(EXPORT_DECL)].map((match) => match[1]), + ...[...source.matchAll(EXPORT_DESTRUCTURE)].flatMap((match) => names(match[1]).map((name) => name.split(':').pop().trim())), + ...[...source.matchAll(EXPORT_LIST)].flatMap((match) => names(match[1]).map((name) => bare(name).split(/\s+as\s+/).pop())) + ] + for (const name of found) if (name && !map.has(name)) map.set(name, file) + } + return map +} + +const specifierTo = (fromFile, toFile) => { + const path = posix(relative(dirname(fromFile), toFile)).replace(/\.ts$/, '').replace(/\/index$/, '') + return path.startsWith('.') ? path : `./${path}` +} + +const issues = [] +const exportMap = scanExports() + +const rewriteImports = (source, file) => + source.replace(IMPORT, (match, keyword, typeOnly, list, spec) => { + const core = /^\.\.\/\.\.\/core\/([\w-]+)$/.exec(spec)?.[1] + if (core && PLATFORM_NAMES.has(core)) return `${keyword}${typeOnly ? ' type' : ''} {${list}} from '${specifierTo(file, join(SRC, 'platform.ts'))}'` + if (core === 'dom') return `${keyword}${typeOnly ? ' type' : ''} {${list}} from '${specifierTo(file, join(SRC, 'ui/config.ts'))}'` + if (spec !== '@nolly/ai') return match + const groups = new Map() + for (const entry of names(list)) { + const target = exportMap.get(bare(entry)) + if (!target) { + issues.push(`${relative(ROOT, file)}: '${bare(entry)}' is not exported by @nolly/ai`) + continue + } + groups.set(target, [...(groups.get(target) ?? []), entry]) + } + return [...groups].map(([target, entries]) => `${keyword}${typeOnly ? ' type' : ''} { ${entries.join(', ')} } from '${specifierTo(file, target)}'`).join('\n') + }) + +const rewriteLiterals = (source) => { + let needsConfig = false + const declared = [] + const lines = source.split('\n').map((entry) => { + const match = /^(export\s+)?const\s+(\w+)\s*=\s*'better-perplexity([^']*)'[ \t]*(\r?)$/.exec(entry) + if (!match) return entry + needsConfig = true + declared.push(match[2]) + return `${match[1] ?? ''}const ${match[2]} = (): string => \`\${uiConfig().id}${match[3]}\`${match[4]}` + }) + let text = lines.join('\n') + for (const name of declared) { + const declaration = new RegExp(`^(export\\s+)?const\\s+${name}\\s*=\\s*\\(\\)`) + text = text.split('\n').map((entry) => (declaration.test(entry) ? entry : entry.replace(new RegExp(`\\b${name}\\b`, 'g'), `${name}()`))).join('\n') + } + text = text.replace(/'better-perplexity([^']*)'/g, (_match, suffix) => { + needsConfig = true + return suffix ? `\`\${uiConfig().id}${suffix}\`` : 'uiConfig().id' + }) + return { text, needsConfig } +} + +const mergeImports = (source) => { + const groups = new Map() + const key = (typeOnly, spec) => `${typeOnly ? 'type' : 'value'}|${spec}` + for (const match of source.matchAll(/^import\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'\n?/gm)) { + const id = key(Boolean(match[1]), match[3]) + const group = groups.get(id) ?? { names: [], count: 0 } + for (const name of names(match[2])) if (!group.names.includes(name)) group.names.push(name) + group.count++ + groups.set(id, group) + } + const seen = new Set() + return source.replace(/^import\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'\n?/gm, (match, typeOnly, _list, spec) => { + const id = key(Boolean(typeOnly), spec) + const group = groups.get(id) + if (!group || group.count < 2) return match + if (seen.has(id)) return '' + seen.add(id) + return `import ${typeOnly ? 'type ' : ''}{ ${group.names.join(', ')} } from '${spec}'\n` + }) +} + +const addConfigImport = (source, file) => { + if (/\buiConfig\b[^\n]*from\s+'[^']*ui\/config'/.test(source)) return source + const line = `import { uiConfig } from '${specifierTo(file, join(SRC, 'ui/config.ts'))}'\n` + const imports = [...source.matchAll(/^import[^\n]*\n/gm)] + const last = imports.at(-1) + if (!last) return line + source + const end = last.index + last[0].length + return source.slice(0, end) + line + source.slice(end) +} + +const checkResolution = (source, file) => { + for (const match of source.matchAll(IMPORT)) { + const spec = match[4] + if (!spec.startsWith('.')) continue + const base = resolve(dirname(file), spec) + if (!existsSync(`${base}.ts`) && !existsSync(join(base, 'index.ts'))) issues.push(`${relative(ROOT, file)}: cannot resolve '${spec}'`) + } + source.split('\n').forEach((line, index) => { + if (/perplexity/i.test(line)) issues.push(`${relative(ROOT, file)}:${index + 1}: still mentions Perplexity: ${line.trim().slice(0, 100)}`) + }) +} + +const classRenames = [] +for (const name of modules) { + const from = join(SOURCE, name) + const to = join(FEATURES, name) + if (!existsSync(from)) { + console.error(`Missing ${relative(ROOT, from)}`) + process.exit(1) + } + move(from, to) + for (const file of walk(to).filter((entry) => entry.endsWith('.ts'))) { + let source = readFileSync(file, 'utf8') + source = rewriteImports(source, file) + const literals = rewriteLiterals(source) + source = literals.text + if (literals.needsConfig) source = addConfigImport(source, file) + source = mergeImports(source) + if (file === join(to, 'index.ts')) { + const match = /export class (\w+)Module extends Feature/.exec(source) + if (match) { + source = source.replace(new RegExp(`\\b${match[1]}Module\\b`, 'g'), `${match[1]}Feature`) + classRenames.push({ name, className: `${match[1]}Feature` }) + } + } + writeFileSync(file, source) + } +} + +for (const name of modules) for (const file of walk(join(FEATURES, name)).filter((entry) => entry.endsWith('.ts'))) checkResolution(readFileSync(file, 'utf8'), file) + +const barrel = join(FEATURES, 'index.ts') +let barrelText = existsSync(barrel) ? readFileSync(barrel, 'utf8') : '' +for (const { name, className } of classRenames) { + const line = `export { ${className} } from './${name}'\n` + if (!barrelText.includes(line)) barrelText += line +} +writeFileSync(barrel, barrelText) + +console.log(`Hoisted: ${modules.join(', ')}`) +console.log(classRenames.map(({ className }) => ` ${className}`).join('\n')) +if (issues.length) { + console.log('\nNeeds attention:') + for (const issue of issues) console.log(` ${issue}`) +} From 82f797b4e07affef00e3dd21e1cd4bd240cb2377 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:04:33 +0100 Subject: [PATCH 13/19] feat(ai): hoist Exporter and Update checker; ChatGPT export from the conversation view; hydration-safe start (step 9) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/app.ts | 3 +- ai/chatgpt/src/config.ts | 2 +- ai/chatgpt/src/dom-markdown.ts | 125 ++++++++++++++++++ ai/chatgpt/src/export-source.ts | 42 ++++++ ai/chatgpt/src/features/header-button.ts | 19 ++- ai/chatgpt/src/header-tools.ts | 12 ++ ai/chatgpt/src/main.ts | 9 +- ai/perplexity/CHANGELOG.md | 1 + .../exporter/api.ts => export-source.ts} | 32 ++++- ai/perplexity/src/main.ts | 13 +- core/ai/README.md | 3 +- .../ai/src/features}/exporter/citations.ts | 0 .../ai/src/features}/exporter/dialog.ts | 15 ++- .../ai/src/features}/exporter/docx.ts | 0 .../ai/src/features}/exporter/index.ts | 30 ++--- .../ai/src/features}/exporter/markdown.ts | 4 +- .../ai/src/features}/exporter/pdf.ts | 0 .../ai/src/features}/exporter/service.ts | 29 ++-- .../ai/src/features}/exporter/settings.ts | 2 +- core/ai/src/features/exporter/source.ts | 8 ++ .../ai/src/features}/exporter/text.ts | 0 .../ai/src/features}/exporter/zip.ts | 0 core/ai/src/features/index.ts | 3 + .../ai/src/features}/updates/index.ts | 35 ++--- core/ai/src/platform.ts | 58 ++++---- 26 files changed, 343 insertions(+), 103 deletions(-) create mode 100644 ai/chatgpt/src/dom-markdown.ts create mode 100644 ai/chatgpt/src/export-source.ts create mode 100644 ai/chatgpt/src/header-tools.ts rename ai/perplexity/src/{modules/exporter/api.ts => export-source.ts} (72%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/citations.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/dialog.ts (78%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/docx.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/index.ts (59%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/markdown.ts (97%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/pdf.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/service.ts (58%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/settings.ts (93%) create mode 100644 core/ai/src/features/exporter/source.ts rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/text.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/exporter/zip.ts (100%) rename {ai/perplexity/src/modules => core/ai/src/features}/updates/index.ts (65%) diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index f63c9de..faa1326 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -2,6 +2,7 @@ ## [0.1.0] - 2026-11-10 +- Exporter built from the conversation view (Markdown, text, Word, PDF, JSON) and update checker. - Batch Runner, Selection Toolbar (Ask, Explain, Summarize, Fact-check, Quote) and Max Width. - Initial skeleton: composer and header detection, response observer, session state and diagnostics. - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. diff --git a/ai/chatgpt/src/app.ts b/ai/chatgpt/src/app.ts index 7484787..93fe9c6 100644 --- a/ai/chatgpt/src/app.ts +++ b/ai/chatgpt/src/app.ts @@ -2,6 +2,7 @@ import { toggleSettingsDialog } from '@nolly/ai' import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from './config' import { uiMarker } from './dom' +import { findComposerForm } from './locate' export class App extends Userscript { constructor() { @@ -15,7 +16,7 @@ export class App extends Userscript { initializationDelay: CONFIG.initializationDelay, safetyInterval: CONFIG.safetyInterval, clearConsole: false, - isReady: () => Boolean(document.querySelector('main')), + isReady: () => document.readyState === 'complete' && findComposerForm() !== null, openSettings: (script) => toggleSettingsDialog(script.getFeatures(), () => { script.refreshMenu() diff --git a/ai/chatgpt/src/config.ts b/ai/chatgpt/src/config.ts index 268bddf..eb54e00 100644 --- a/ai/chatgpt/src/config.ts +++ b/ai/chatgpt/src/config.ts @@ -1,7 +1,7 @@ import type { SplitterSettings } from '@nolly/ai' export const CONFIG = { - initializationDelay: 500, + initializationDelay: 1_500, safetyInterval: 2_000 } as const diff --git a/ai/chatgpt/src/dom-markdown.ts b/ai/chatgpt/src/dom-markdown.ts new file mode 100644 index 0000000..6828b7c --- /dev/null +++ b/ai/chatgpt/src/dom-markdown.ts @@ -0,0 +1,125 @@ +import { isOwnUi } from './dom' + +const HEADING = /^H([1-6])$/ +const SKIPPED = 'button, svg, script, style, [data-markdown-copy="exclude"], .katex-html' +const BLOCKS = new Set(['P', 'DIV', 'UL', 'OL', 'PRE', 'TABLE', 'BLOCKQUOTE', 'HR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'SECTION', 'ARTICLE']) + +const skipped = (element: HTMLElement): boolean => isOwnUi(element) || element.matches(SKIPPED) + +const tex = (element: HTMLElement): string => element.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim() ?? element.textContent ?? '' + +const wrap = (mark: string, value: string): string => (value.trim() ? `${mark}${value.trim()}${mark}` : value) + +const inline = (node: Node): string => { + if (node.nodeType === Node.TEXT_NODE) return (node.textContent ?? '').replace(/\s+/g, ' ') + if (!(node instanceof HTMLElement) || skipped(node)) return '' + if (node.classList.contains('katex-display')) return `\n\n$$${tex(node)}$$\n\n` + if (node.classList.contains('katex')) return `$${tex(node)}$` + const inner = (): string => [...node.childNodes].map(inline).join('') + switch (node.tagName) { + case 'BR': + return ' \n' + case 'STRONG': + case 'B': + return wrap('**', inner()) + case 'EM': + case 'I': + return wrap('*', inner()) + case 'DEL': + case 'S': + return wrap('~~', inner()) + case 'CODE': + return `\`${node.textContent ?? ''}\`` + case 'A': { + const href = node.getAttribute('href') + const label = inner().trim() + return href && label ? `[${label}](${href})` : label + } + case 'IMG': { + const source = node.getAttribute('src') + return source ? `![${node.getAttribute('alt') ?? ''}](${source})` : '' + } + default: + return inner() + } +} + +const fence = (pre: HTMLElement): string => { + const raw = pre.closest('[data-chatgpt-copy-code]')?.getAttribute('data-chatgpt-copy-code') ?? (pre.querySelector('code') ?? pre).textContent ?? '' + const label = pre.closest('[data-code-block]')?.querySelector('[data-markdown-copy="exclude"] .truncate')?.textContent ?? '' + const language = label.trim().toLowerCase().replace(/\s+/g, '-') + return `\`\`\`${language}\n${raw.replace(/\n$/, '')}\n\`\`\`` +} + +const table = (element: HTMLElement): string => { + const rows = [...element.querySelectorAll('tr')].map((row) => [...row.children].map((cell) => inline(cell).replace(/\|/g, '\\|').replace(/\s+/g, ' ').trim())) + if (!rows.length) return '' + const width = Math.max(...rows.map((row) => row.length)) + const line = (row: string[]): string => `| ${Array.from({ length: width }, (_, index) => row[index] ?? '').join(' | ')} |` + const [head, ...body] = rows + return [line(head ?? []), `| ${Array.from({ length: width }, () => '---').join(' | ')} |`, ...body.map(line)].join('\n') +} + +const list = (element: HTMLElement, depth: number): string => { + const ordered = element.tagName === 'OL' + let index = Number.parseInt(element.getAttribute('start') ?? '1', 10) || 1 + const indent = ' '.repeat(depth) + const lines: string[] = [] + for (const item of element.children) { + if (!(item instanceof HTMLElement) || item.tagName !== 'LI' || skipped(item)) continue + const own: string[] = [] + const nested: string[] = [] + for (const child of item.childNodes) { + if (child instanceof HTMLElement && (child.tagName === 'UL' || child.tagName === 'OL')) nested.push(list(child, depth + 1)) + else if (child instanceof HTMLElement && child.tagName === 'PRE') nested.push(fence(child).split('\n').map((line) => `${indent} ${line}`).join('\n')) + else own.push(inline(child)) + } + lines.push(`${indent}${ordered ? `${index++}.` : '-'} ${own.join('').trim()}`, ...nested.filter(Boolean)) + } + return lines.join('\n') +} + +const block = (element: HTMLElement): string => { + if (skipped(element)) return '' + const heading = HEADING.exec(element.tagName) + if (heading) return `${'#'.repeat(Number(heading[1]))} ${[...element.childNodes].map(inline).join('').trim()}` + switch (element.tagName) { + case 'P': + return [...element.childNodes].map(inline).join('').trim() + case 'UL': + case 'OL': + return list(element, 0) + case 'PRE': + return fence(element) + case 'HR': + return '---' + case 'TABLE': + return table(element) + case 'BLOCKQUOTE': + return children(element).split('\n').map((line) => `> ${line}`).join('\n') + default: + return children(element) + } +} + +const children = (element: HTMLElement): string => { + const parts: string[] = [] + let run = '' + const flush = (): void => { + if (run.trim()) parts.push(run.trim()) + run = '' + } + for (const child of element.childNodes) { + if (child instanceof HTMLElement && BLOCKS.has(child.tagName)) { + flush() + const value = block(child) + if (value) parts.push(value) + } else { + run += inline(child) + } + } + flush() + return parts.join('\n\n') +} + +export const toMarkdown = (root: HTMLElement): string => children(root).replace(/\n{3,}/g, '\n\n').trim() diff --git a/ai/chatgpt/src/export-source.ts b/ai/chatgpt/src/export-source.ts new file mode 100644 index 0000000..e731697 --- /dev/null +++ b/ai/chatgpt/src/export-source.ts @@ -0,0 +1,42 @@ +import type { ExportSource } from '@nolly/ai' +import { parseConversation } from './adapter' +import { toMarkdown } from './dom-markdown' +import { headerTools } from './header-tools' +import { findTurns } from './messages' +import type { Turn } from './messages' + +const ROLE_LABEL = { user: 'You', assistant: 'ChatGPT' } as const + +const turns = (): Turn[] => { + const found = findTurns() + if (!found.length) throw new Error('No messages found on this page.') + return found +} + +const render = (turn: Turn): string => (turn.role === 'user' ? turn.text() : toMarkdown(turn.element)) + +export const exportSource: ExportSource = { + name: 'ChatGPT', + citations: false, + slug: () => parseConversation(new URL(location.href)).id, + markdown: async () => turns().map((turn) => `**${ROLE_LABEL[turn.role]}**\n\n${render(turn)}`).join('\n\n---\n\n'), + json: async () => + JSON.stringify( + { + app: 'better-chatgpt', + conversationId: parseConversation(new URL(location.href)).id, + title: document.title, + url: location.href, + exportedAt: new Date().toISOString(), + messages: turns().map((turn) => ({ role: turn.role, markdown: render(turn) })) + }, + null, + 2 + ), + place: (button) => { + const tools = headerTools() + if (!tools) return false + if (button.parentElement !== tools) tools.append(button) + return true + } +} diff --git a/ai/chatgpt/src/features/header-button.ts b/ai/chatgpt/src/features/header-button.ts index 3a02cd0..7d68cef 100644 --- a/ai/chatgpt/src/features/header-button.ts +++ b/ai/chatgpt/src/features/header-button.ts @@ -1,29 +1,28 @@ import { Tooltip, createIcon, ensureUiStyles } from '@nolly/ai' import { Feature, createElement } from '@nolly/core' -import { markUi } from '../dom' -import { findHeaderSlot } from '../locate' +import { headerTools } from '../header-tools' export class HeaderButtonFeature extends Feature { readonly id = 'header-button' readonly name = 'Header button' readonly description = 'Adds the Better ChatGPT settings button to the header.' - private readonly wrapper = markUi(createElement('div', 'pointer-events-auto flex items-center no-drag shrink-0')) + private button: HTMLButtonElement | null = null private tooltip: Tooltip | null = null run(): void { if (!this.enabled) return - const slot = findHeaderSlot() - if (!slot) return - if (!this.tooltip) this.build() - if (this.wrapper.parentElement !== slot || slot.firstElementChild !== this.wrapper) slot.prepend(this.wrapper) + const tools = headerTools() + if (!tools) return + if (!this.button) this.build() + if (this.button && this.button.parentElement !== tools) tools.append(this.button) } override onDisable(): void { this.tooltip?.destroy() this.tooltip = null - this.wrapper.replaceChildren() - this.wrapper.remove() + this.button?.remove() + this.button = null } private build(): void { @@ -34,6 +33,6 @@ export class HeaderButtonFeature extends Feature { button.appendChild(createIcon('sliders')) button.addEventListener('click', () => this.context.openSettings()) this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) - this.wrapper.replaceChildren(button) + this.button = button } } diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts new file mode 100644 index 0000000..80dbdc9 --- /dev/null +++ b/ai/chatgpt/src/header-tools.ts @@ -0,0 +1,12 @@ +import { createElement } from '@nolly/core' +import { markUi } from './dom' +import { findHeaderSlot } from './locate' + +const container = markUi(createElement('div', 'pointer-events-auto flex items-center gap-1 no-drag shrink-0')) + +export const headerTools = (): HTMLElement | null => { + const slot = findHeaderSlot() + if (!slot) return null + if (container.parentElement !== slot || slot.firstElementChild !== container) slot.prepend(container) + return container +} diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 8994c66..a320a83 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,14 +1,15 @@ -import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, ExporterFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, UpdatesFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' import { SPLITTER_DEFAULTS } from './config' import { uiMarker } from './dom' +import { exportSource } from './export-source' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' import { composerKit, generationKit, sendPrompt } from './kit' import { logger } from './logger' import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' -import { URLS } from './repo' +import { SLUG, URLS } from './repo' import { session } from './runtime' import { storage } from './storage' import { threadOf } from './threads' @@ -34,6 +35,8 @@ configurePlatform({ onSend, threadOf, promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better ChatGPT', slug: SLUG, version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases }, codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]') }) @@ -52,5 +55,7 @@ new App() .register((context) => new CommandPaletteFeature(context)) .register((context) => new PromptQueueFeature(context)) .register((context) => new RecallFeature(context)) + .register((context) => new ExporterFeature(context)) + .register((context) => new UpdatesFeature(context)) .register((context) => new DiagnosticsFeature(context)) .start() diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index c7cf1c9..1eb18d8 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -11,6 +11,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: Message Splitter now comes from the shared package. - Internal: Code Block Pro now comes from the shared package. - Internal: Batch Runner, Selection Toolbar and Max Width now come from the shared package. +- Internal: Exporter and Update checker now come from the shared package. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/ai/perplexity/src/modules/exporter/api.ts b/ai/perplexity/src/export-source.ts similarity index 72% rename from ai/perplexity/src/modules/exporter/api.ts rename to ai/perplexity/src/export-source.ts index bb50e04..873b856 100644 --- a/ai/perplexity/src/modules/exporter/api.ts +++ b/ai/perplexity/src/export-source.ts @@ -1,7 +1,8 @@ -import { storage } from '../../core/storage' -import { readCookieAccountId } from '../usage-status/account-cookie' +import type { ExportSource } from '@nolly/ai' +import { storage } from './core/storage' +import { readCookieAccountId } from './modules/usage-status/account-cookie' -export interface ExportedFile { +interface ExportedFile { filename: string bytes: Uint8Array } @@ -21,7 +22,7 @@ const request = (path: string, init: RequestInit = {}): Promise => { }) } -export const currentThreadSlug = (): string | null => { +const currentThreadSlug = (): string | null => { const segments = location.pathname.split('/').filter(Boolean) return segments.length >= 2 && !NON_THREAD_ROOTS.has(segments[0]!) ? (segments.at(-1) ?? null) : null } @@ -52,7 +53,7 @@ const fetchThread = async (slug: string): Promise => { return response.json() } -export const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: string): Promise => { +const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: string): Promise => { const slug = currentThreadSlug() if (!slug) throw new Error('Open a thread first.') try { @@ -64,8 +65,25 @@ export const exportThread = async (format: 'md' | 'docx' | 'pdf', filename: stri } } -export const fetchThreadJson = async (): Promise => { +const fetchThreadJson = async (): Promise => { const slug = currentThreadSlug() if (!slug) throw new Error('Open a thread first.') return JSON.stringify(await fetchThread(slug), null, 2) -} \ No newline at end of file +} + +const fileBase = (): string => (currentThreadSlug() ?? 'perplexity-thread').replace(/[^\w-]+/g, '-').slice(0, 60) || 'perplexity-thread' + +export const exportSource: ExportSource = { + name: 'Perplexity', + citations: true, + slug: currentThreadSlug, + markdown: async () => new TextDecoder().decode((await exportThread('md', fileBase())).bytes), + json: fetchThreadJson, + place: (button) => { + const indicator = document.querySelector('.bp-usage-indicator') + if (!indicator) return false + const gear = indicator.querySelector('.bp-gear') + if (button.parentElement !== indicator || (gear && button.nextElementSibling !== gear)) indicator.insertBefore(button, gear) + return true + } +} diff --git a/ai/perplexity/src/main.ts b/ai/perplexity/src/main.ts index bdf8a6f..d0aa46f 100644 --- a/ai/perplexity/src/main.ts +++ b/ai/perplexity/src/main.ts @@ -1,4 +1,4 @@ -import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, ExporterFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, UpdatesFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' import { App } from './core/app' import { composerKit, findComposer, writeComposer } from './core/composer' import { sendPrompt } from './core/dispatch' @@ -9,12 +9,11 @@ import { logger } from './core/logger' import { isAskRequest } from './core/requests' import { storage } from './core/storage' import { threadOf } from './core/threads' +import { exportSource } from './export-source' import { findComposerActions } from './locate' -import { ExporterModule } from './modules/exporter' import { GlobalSettingsModule } from './modules/global-settings' import { ALWAYS_HIDDEN, LAYOUT_RULES, RIGHT_SIDEBAR } from './modules/max-width/rules' import { TutorialModule } from './modules/tutorial' -import { UpdatesModule } from './modules/updates' import { UsageStatusModule } from './modules/usage-status' import { URLS } from './repo' @@ -30,7 +29,9 @@ configurePlatform({ sendPrompt, onSend, threadOf, - promptsUrl: URLS.prompts + promptsUrl: URLS.prompts, + exporter: exportSource, + release: { name: 'Better Perplexity', slug: 'better-perplexity', version: __VERSION__, metaUrl: URLS.meta, installUrl: URLS.install, releasesUrl: URLS.releases } }) fetchSpy.install() @@ -44,11 +45,11 @@ new App() .register((context) => new BatchRunnerFeature(context)) .register((context) => new DraftGuardFeature(context, { storage, composer: { findComposer, writeComposer }, onSend, tokenLimit: () => loadSplitterSettings(storage).limit })) .register((context) => new CommandPaletteFeature(context)) - .register((context) => new ExporterModule(context)) + .register((context) => new ExporterFeature(context)) .register((context) => new UsageStatusModule(context)) .register((context) => new GlobalSettingsModule(context)) .register((context) => new TutorialModule(context)) - .register((context) => new UpdatesModule(context)) + .register((context) => new UpdatesFeature(context)) .register((context) => new PromptQueueFeature(context)) .register((context) => new RecallFeature(context)) .start() diff --git a/core/ai/README.md b/core/ai/README.md index 3d62a6f..e95715c 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -10,7 +10,8 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex - A streaming response observer and an incremental Server-Sent Events parser. - Placeholders, token estimates, selection memory, clipboard and file download helpers. - A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, Max Width, and Code Blocks. +- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, Max Width, Code Blocks, Exporter (Markdown, text, Word, PDF, JSON), and Update checker. +- Exports can be sourced from conversation messages or selected text. - Prompt Library, Command Palette, Prompt Queue and Recall. Platforms register once with `configurePlatform` and `configureUi`. diff --git a/ai/perplexity/src/modules/exporter/citations.ts b/core/ai/src/features/exporter/citations.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/citations.ts rename to core/ai/src/features/exporter/citations.ts diff --git a/ai/perplexity/src/modules/exporter/dialog.ts b/core/ai/src/features/exporter/dialog.ts similarity index 78% rename from ai/perplexity/src/modules/exporter/dialog.ts rename to core/ai/src/features/exporter/dialog.ts index 0fe5cd3..65e89db 100644 --- a/ai/perplexity/src/modules/exporter/dialog.ts +++ b/core/ai/src/features/exporter/dialog.ts @@ -1,10 +1,13 @@ import { createElement } from '@nolly/core' -import { createButton, createSelectField, createSwitch, createDialog } from '@nolly/ai' +import { platform } from '../../platform' +import { createButton, createSelectField, createSwitch } from '../../ui/controls' +import { createDialog } from '../../ui/dialog' import type { CitationStyle } from './citations' import { runExport } from './service' import type { ExportFormat, ExportSettings } from './settings' +import { uiConfig } from '../../ui/config' -const DIALOG_ID = 'better-perplexity-export-dialog' +const DIALOG_ID = (): string => `${uiConfig().id}-export-dialog` const FORMATS: readonly { value: ExportFormat; label: string }[] = [ { value: 'md', label: 'Markdown (.md), formatted' }, @@ -24,20 +27,20 @@ const STYLES: readonly { value: CitationStyle; label: string }[] = [ ] export const toggleExportDialog = (settings: ExportSettings, onSettings: (settings: ExportSettings) => void): void => { - const existing = document.getElementById(DIALOG_ID) + const existing = document.getElementById(DIALOG_ID()) if (existing instanceof HTMLDialogElement) { existing.close() return } - const ui = createDialog({ id: DIALOG_ID, title: 'Export thread', description: 'Exports the thread you are viewing.', width: 480 }) + const ui = createDialog({ id: DIALOG_ID(), title: 'Export thread', description: 'Exports the thread you are viewing.', width: 480 }) const state: ExportSettings = { ...settings } const status = createElement('div', 'bp-hint') const styleField = createSelectField('Citations', STYLES, state.style, (value) => update({ style: value })) - const logoField = createSwitch({ label: 'Remove the Perplexity logo line', checked: state.stripLogo, onChange: (value) => update({ stripLogo: value }) }).wrapper + const logoField = createSwitch({ label: `Remove the ${platform().exporter.name} logo line`, checked: state.stripLogo, onChange: (value) => update({ stripLogo: value }) }).wrapper const copyButton = createButton('Copy') const downloadButton = createButton('Download', { primary: true }) const render = (): void => { - const rendered = state.format !== 'json' + const rendered = state.format !== 'json' && platform().exporter.citations styleField.hidden = !rendered logoField.hidden = !rendered copyButton.hidden = !(state.format === 'md' || state.format === 'txt' || state.format === 'json') diff --git a/ai/perplexity/src/modules/exporter/docx.ts b/core/ai/src/features/exporter/docx.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/docx.ts rename to core/ai/src/features/exporter/docx.ts diff --git a/ai/perplexity/src/modules/exporter/index.ts b/core/ai/src/features/exporter/index.ts similarity index 59% rename from ai/perplexity/src/modules/exporter/index.ts rename to core/ai/src/features/exporter/index.ts index ab791ac..5125287 100644 --- a/ai/perplexity/src/modules/exporter/index.ts +++ b/core/ai/src/features/exporter/index.ts @@ -1,20 +1,21 @@ -import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' -import { markUi } from '../../core/dom' -import { createIcon, ensureUiStyles, Tooltip } from '@nolly/ai' -import { currentThreadSlug } from './api' +import { Feature, createElement } from '@nolly/core' +import type { MenuEntry, ScriptContext } from '@nolly/core' +import { platform } from '../../platform' +import { markUi } from '../../ui/config' +import { createIcon } from '../../ui/icons' +import { ensureUiStyles } from '../../ui/styles' +import { Tooltip } from '../../ui/tooltip' import { toggleExportDialog } from './dialog' -import { loadExportSettings, saveExportSettings, type ExportSettings } from './settings' +import { loadExportSettings, saveExportSettings } from './settings' +import type { ExportSettings } from './settings' -const INDICATOR_SELECTOR = '.bp-usage-indicator' -const GEAR_SELECTOR = '.bp-gear' - -export class ExporterModule extends Feature { +export class ExporterFeature extends Feature { readonly id = 'exporter' readonly name = 'Conversation Exporter' readonly description = 'Exports threads with configurable citation styles.' private settings: ExportSettings = loadExportSettings() - private readonly button = markUi(createElement('button', 'bp-header-btn bp-export')) + private readonly button = markUi(createElement('button', 'bp-header-btn bp-export bp-themed')) private readonly tooltip: Tooltip constructor(context: ScriptContext) { @@ -28,14 +29,11 @@ export class ExporterModule extends Feature { } run(): void { - const indicator = document.querySelector(INDICATOR_SELECTOR) - if (!this.enabled || !indicator || !currentThreadSlug()) { + const source = platform().exporter + if (!this.enabled || !source.slug() || !source.place(this.button)) { this.tooltip.hide() this.button.remove() - return } - const gear = indicator.querySelector(GEAR_SELECTOR) - if (this.button.parentElement !== indicator || (gear && this.button.nextElementSibling !== gear)) indicator.insertBefore(this.button, gear) } override menuEntries(): MenuEntry[] { @@ -48,4 +46,4 @@ export class ExporterModule extends Feature { saveExportSettings(settings) }) } -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/markdown.ts b/core/ai/src/features/exporter/markdown.ts similarity index 97% rename from ai/perplexity/src/modules/exporter/markdown.ts rename to core/ai/src/features/exporter/markdown.ts index 817cac1..38f5899 100644 --- a/ai/perplexity/src/modules/exporter/markdown.ts +++ b/core/ai/src/features/exporter/markdown.ts @@ -116,7 +116,7 @@ export const parseBlocks = (markdown: string): Block[] => { const BLOCK_START = /^(#{1,6}\s|---+\s*$|\s*(?:[-*+]|\d+[.)])\s|\s*\|)/ -export const formatMarkdown = (markdown: string, meta: { title: string; url: string }): string => { +export const formatMarkdown = (markdown: string, meta: { title: string; url: string; source: string }): string => { const cleaned: string[] = [] let fenced = false for (const raw of markdown.replace(/\r\n?/g, '\n').split('\n')) { @@ -143,7 +143,7 @@ export const formatMarkdown = (markdown: string, meta: { title: string; url: str if (fenced || fence || line.trim() !== '' || spaced.at(-1)?.trim() !== '') spaced.push(line) } const body = spaced.join('\n').replace(/\n{3,}/g, '\n\n').trim() - const stamp = `_Exported from Perplexity on ${new Date().toLocaleString()} · ${meta.url}_` + const stamp = `_Exported from ${meta.source} on ${new Date().toLocaleString()} · ${meta.url}_` const firstLine = body.split('\n', 1)[0] ?? '' if (firstLine.startsWith('# ')) return `${firstLine}\n\n${stamp}\n\n${body.slice(firstLine.length).trim()}\n` return `# ${meta.title}\n\n${stamp}\n\n---\n\n${body}\n` diff --git a/ai/perplexity/src/modules/exporter/pdf.ts b/core/ai/src/features/exporter/pdf.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/pdf.ts rename to core/ai/src/features/exporter/pdf.ts diff --git a/ai/perplexity/src/modules/exporter/service.ts b/core/ai/src/features/exporter/service.ts similarity index 58% rename from ai/perplexity/src/modules/exporter/service.ts rename to core/ai/src/features/exporter/service.ts index c18ced9..7c52c37 100644 --- a/ai/perplexity/src/modules/exporter/service.ts +++ b/core/ai/src/features/exporter/service.ts @@ -1,5 +1,6 @@ -import { copyText, saveFile } from '@nolly/ai' -import { currentThreadSlug, exportThread, fetchThreadJson } from './api' +import { copyText } from '../../clipboard' +import { saveFile } from '../../download' +import { platform } from '../../platform' import { reformatCitations, stripLogo } from './citations' import { buildDocx } from './docx' import { formatMarkdown, parseBlocks } from './markdown' @@ -9,25 +10,31 @@ import { blocksToText } from './text' const MIME = { docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', pdf: 'application/pdf' } as const -const filenameBase = (): string => (currentThreadSlug() ?? 'perplexity-thread').replace(/[^\w-]+/g, '-').slice(0, 60) || 'perplexity-thread' +const fallbackName = (): string => `${platform().exporter.name.toLowerCase()}-thread` -const pageTitle = (): string => document.title.replace(/\s*[-–|]\s*Perplexity\s*$/i, '').trim() || 'Perplexity thread' +const filenameBase = (): string => (platform().exporter.slug() ?? fallbackName()).replace(/[^\w-]+/g, '-').slice(0, 60) || fallbackName() -const loadMarkdown = async (settings: ExportSettings, base: string): Promise => { - const file = await exportThread('md', base) - const raw = new TextDecoder().decode(file.bytes) - return formatMarkdown(reformatCitations(settings.stripLogo ? stripLogo(raw) : raw, settings.style), { title: pageTitle(), url: location.href }) +const pageTitle = (): string => { + const { name } = platform().exporter + return document.title.replace(new RegExp(`\\s*[-–|]\\s*${name}\\s*$`, 'i'), '').trim() || `${name} thread` +} + +const loadMarkdown = async (settings: ExportSettings): Promise => { + const source = platform().exporter + const raw = await source.markdown() + const text = source.citations ? reformatCitations(settings.stripLogo ? stripLogo(raw) : raw, settings.style) : raw + return formatMarkdown(text, { title: pageTitle(), url: location.href, source: source.name }) } export const runExport = async (settings: ExportSettings, action: 'download' | 'copy'): Promise => { const base = filenameBase() if (settings.format === 'json') { - const json = await fetchThreadJson() + const json = await platform().exporter.json() if (action === 'copy') return (await copyText(json)) ? 'Copied JSON.' : 'Copy failed.' saveFile(`${base}.json`, json, 'application/json') return 'Downloaded.' } - const markdown = await loadMarkdown(settings, base) + const markdown = await loadMarkdown(settings) const blocks = parseBlocks(markdown) if (settings.format === 'md' || settings.format === 'txt') { const text = settings.format === 'md' ? markdown : blocksToText(blocks) @@ -39,4 +46,4 @@ export const runExport = async (settings: ExportSettings, action: 'download' | ' const bytes = settings.format === 'docx' ? buildDocx(blocks) : buildPdf(blocks, pageTitle()) saveFile(`${base}.${settings.format}`, bytes as BlobPart, MIME[settings.format]) return 'Downloaded.' -} \ No newline at end of file +} diff --git a/ai/perplexity/src/modules/exporter/settings.ts b/core/ai/src/features/exporter/settings.ts similarity index 93% rename from ai/perplexity/src/modules/exporter/settings.ts rename to core/ai/src/features/exporter/settings.ts index 774d7fc..863213b 100644 --- a/ai/perplexity/src/modules/exporter/settings.ts +++ b/core/ai/src/features/exporter/settings.ts @@ -1,4 +1,4 @@ -import { storage } from '../../core/storage' +import { storage } from '../../platform' import type { CitationStyle } from './citations' export type ExportFormat = 'md' | 'txt' | 'docx' | 'pdf' | 'json' diff --git a/core/ai/src/features/exporter/source.ts b/core/ai/src/features/exporter/source.ts new file mode 100644 index 0000000..b72fa84 --- /dev/null +++ b/core/ai/src/features/exporter/source.ts @@ -0,0 +1,8 @@ +export interface ExportSource { + readonly name: string + readonly citations: boolean + readonly slug: () => string | null + readonly markdown: () => Promise + readonly json: () => Promise + readonly place: (button: HTMLElement) => boolean +} diff --git a/ai/perplexity/src/modules/exporter/text.ts b/core/ai/src/features/exporter/text.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/text.ts rename to core/ai/src/features/exporter/text.ts diff --git a/ai/perplexity/src/modules/exporter/zip.ts b/core/ai/src/features/exporter/zip.ts similarity index 100% rename from ai/perplexity/src/modules/exporter/zip.ts rename to core/ai/src/features/exporter/zip.ts diff --git a/core/ai/src/features/index.ts b/core/ai/src/features/index.ts index 86c356b..f4d31d9 100644 --- a/core/ai/src/features/index.ts +++ b/core/ai/src/features/index.ts @@ -16,3 +16,6 @@ export { formatShortcut, loadShortcut, matchesShortcut } from './command-palette export type { Shortcut } from './command-palette/shortcut' export { loadPromptShortcut } from './prompt-library/shortcut' export { CodeBlocksFeature } from './code-blocks' +export { ExporterFeature } from './exporter' +export { UpdatesFeature } from './updates' +export type { ExportSource } from './exporter/source' diff --git a/ai/perplexity/src/modules/updates/index.ts b/core/ai/src/features/updates/index.ts similarity index 65% rename from ai/perplexity/src/modules/updates/index.ts rename to core/ai/src/features/updates/index.ts index 5dadb00..a15e773 100644 --- a/ai/perplexity/src/modules/updates/index.ts +++ b/core/ai/src/features/updates/index.ts @@ -1,14 +1,14 @@ -import { Feature, Updater, type MenuEntry } from '@nolly/core' -import { logger } from '../../core/logger' -import { storage } from '../../core/storage' -import { URLS } from '../../repo' -import { showToast } from '@nolly/ai' +import { Feature, Updater } from '@nolly/core' +import type { MenuEntry } from '@nolly/core' +import { logger, platform, storage } from '../../platform' +import { showToast } from '../../ui/toast' -export { isNewerVersion as isNewer } from '@nolly/core' - -const releaseUrl = (version: string): string => `${URLS.releases}/tag/better-perplexity-v${version}` +const releaseUrl = (version: string): string => { + const { releasesUrl, slug } = platform().release + return `${releasesUrl}/tag/${slug}-v${version}` +} -export class UpdatesModule extends Feature { +export class UpdatesFeature extends Feature { readonly id = 'updates' readonly name = 'Update Checker' readonly description = 'Checks for new versions on load and every few minutes, and tells you once per version.' @@ -16,8 +16,8 @@ export class UpdatesModule extends Feature { private dismissToast: (() => void) | null = null private readonly updater = new Updater({ - metaUrl: URLS.meta, - current: __VERSION__, + metaUrl: platform().release.metaUrl, + current: platform().release.version, storage, logger, namespace: 'updates', @@ -36,10 +36,12 @@ export class UpdatesModule extends Feature { const entries: MenuEntry[] = [] const pending = this.updater.pending const available = this.updater.available - if (pending) entries.push({ id: 'install', label: `Update to v${pending}`, action: () => window.open(URLS.install, '_blank') }) + if (pending) entries.push({ id: 'install', label: `Update to v${pending}`, action: () => window.open(platform().release.installUrl, '_blank') }) if (available && available === this.updater.skipped) { entries.push({ - id: 'unskip', label: `Show Update v${available} Again`, action: () => { + id: 'unskip', + label: `Show Update v${available} Again`, + action: () => { this.updater.unskip() void this.check(true) } @@ -52,14 +54,15 @@ export class UpdatesModule extends Feature { private async check(manual: boolean): Promise { const result = await this.updater.check(manual) if (!manual) return - if (result === 'current') showToast(`You are up to date (v${__VERSION__}).`) + if (result === 'current') showToast(`You are up to date (v${platform().release.version}).`) else if (result === 'failed') showToast('Could not check for updates. Try again later.') } private announce(version: string, current: string): void { this.closeToast() - this.dismissToast = showToast(`Better Perplexity v${version} is available (you have v${current}).`, [ - { label: 'Update', primary: true, onClick: () => window.open(URLS.install, '_blank') }, + const { name, installUrl } = platform().release + this.dismissToast = showToast(`${name} v${version} is available (you have v${current}).`, [ + { label: 'Update', primary: true, onClick: () => window.open(installUrl, '_blank') }, { label: 'What’s new', keepOpen: true, onClick: () => window.open(releaseUrl(version), '_blank') }, { label: 'Skip this version', onClick: () => this.updater.skip(version) } ], 0) diff --git a/core/ai/src/platform.ts b/core/ai/src/platform.ts index 088e252..46db337 100644 --- a/core/ai/src/platform.ts +++ b/core/ai/src/platform.ts @@ -2,43 +2,55 @@ import type { Logger, ScriptStorage } from '@nolly/core' import type { ComposerKit } from './composer' import type { GenerationKit } from './generation' import type { PromptSender } from './prompt' +import type { ExportSource } from './features/exporter/source' + +export interface ReleaseInfo { + readonly name: string + readonly slug: string + readonly version: string + readonly metaUrl: string + readonly installUrl: string + readonly releasesUrl: string +} export interface Platform { - readonly id: string - readonly storage: ScriptStorage - readonly logger: Logger - readonly composer: ComposerKit - readonly generation: GenerationKit - readonly sendPrompt: PromptSender - readonly onSend: (listener: () => void) => () => void - readonly threadOf: (pathname: string) => string | null - readonly promptsUrl: string + readonly id: string + readonly storage: ScriptStorage + readonly logger: Logger + readonly composer: ComposerKit + readonly generation: GenerationKit + readonly sendPrompt: PromptSender + readonly onSend: (listener: () => void) => () => void + readonly threadOf: (pathname: string) => string | null + readonly promptsUrl: string + readonly exporter: ExportSource + readonly release: ReleaseInfo readonly codeBlockRoot?: (pre: HTMLElement) => HTMLElement | null } let current: Platform | null = null export const configurePlatform = (platform: Platform): void => { - current = platform + current = platform } export const platform = (): Platform => { - if (!current) throw new Error('configurePlatform() must run before platform features are used.') - return current + if (!current) throw new Error('configurePlatform() must run before platform features are used.') + return current } export const lazy = (create: () => T): T => { - let instance: T | null = null - const resolve = (): T => (instance ??= create()) - return new Proxy({} as T, { - get: (_target, key) => { - const target = resolve() - const value: unknown = Reflect.get(target, key, target) - return typeof value === 'function' ? value.bind(target) : value - }, - set: (_target, key, value) => Reflect.set(resolve(), key, value), - has: (_target, key) => Reflect.has(resolve(), key) - }) + let instance: T | null = null + const resolve = (): T => (instance ??= create()) + return new Proxy({} as T, { + get: (_target, key) => { + const target = resolve() + const value: unknown = Reflect.get(target, key, target) + return typeof value === 'function' ? value.bind(target) : value + }, + set: (_target, key, value) => Reflect.set(resolve(), key, value), + has: (_target, key) => Reflect.has(resolve(), key) + }) } export const storage: ScriptStorage = lazy(() => platform().storage) From bcff04c3f43896f015031578aaf430947825321e Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:14:29 +0100 Subject: [PATCH 14/19] feat(chatgpt): usage status; header diagnostics (step 10a) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/README.md | 4 + ai/chatgpt/src/features/diagnostics.ts | 52 +++++--- ai/chatgpt/src/features/usage.ts | 168 +++++++++++++++++++++++++ ai/chatgpt/src/main.ts | 2 + 5 files changed, 208 insertions(+), 19 deletions(-) create mode 100644 ai/chatgpt/src/features/usage.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index faa1326..ea68cd1 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -10,3 +10,4 @@ - Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). - Code Block Pro: language badges, highlighting, line numbers, wrap, fold, copy and download. - Prompt Library (shared community prompts), Command Palette, Message Queue and Recall. +- Usage Status: remaining reasoning, upload, image and research limits with reset times, plan and rolling window, and alerts. diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md index 1718f85..e298a25 100644 --- a/ai/chatgpt/README.md +++ b/ai/chatgpt/README.md @@ -10,6 +10,10 @@ Install [Violentmonkey](https://violentmonkey.github.io/) or [Tampermonkey](http Open the browser console on chatgpt.com and run `betterChatgptDump()` to print the detected layout and the live session state. +## Usage + +- Figures come from ChatGPT's own responses and update on page load and after each message. + ## Built on the shared core Better ChatGPT is built on [`@nolly/core`](../../core/README.md) and [`@nolly/ai`](../../core/ai/README.md), and is bundled into one file at build time. diff --git a/ai/chatgpt/src/features/diagnostics.ts b/ai/chatgpt/src/features/diagnostics.ts index df66abf..558c4c6 100644 --- a/ai/chatgpt/src/features/diagnostics.ts +++ b/ai/chatgpt/src/features/diagnostics.ts @@ -1,31 +1,45 @@ import { Feature, getPageWindow } from '@nolly/core' import type { FeatureCommand } from '@nolly/core' import { chatgptAdapter } from '../adapter' +import { fileBudget } from '../budget' +import { exportSource } from '../export-source' import { sendPrompt } from '../kit' import { session } from '../runtime' -import { fileBudget } from '../budget' export class DiagnosticsFeature extends Feature { - readonly id = 'diagnostics' - readonly name = 'Diagnostics' - readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' + readonly id = 'diagnostics' + readonly name = 'Diagnostics' + readonly description = 'Adds betterChatgptDump() and betterChatgptSend(text) to the page console.' - run(): void { } + run(): void {} - override onEnable(): void { - const page = getPageWindow() as unknown as Record | null - if (page) { - page['betterChatgptDump'] = () => this.dump() - page['betterChatgptSend'] = (text: string) => sendPrompt(text) - } - this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') - } + override onEnable(): void { + const page = getPageWindow() as unknown as Record | null + if (page) { + page['betterChatgptDump'] = () => this.dump() + page['betterChatgptSend'] = (text: string) => sendPrompt(text) + } + this.context.logger.info('Diagnostics ready: betterChatgptDump() and betterChatgptSend(text).') + } - override commands(): FeatureCommand[] { - return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] - } + override commands(): FeatureCommand[] { + return [{ id: 'diagnostics.dump', title: 'Dump page diagnostics', keywords: 'debug layout selectors session', run: () => this.context.logger.info(this.dump()) }] + } - private dump(): string { - return JSON.stringify({ page: chatgptAdapter.describePage(), session: session.snapshot(), fileBudget: fileBudget(session) }, null, 2) - } + private dump(): string { + return JSON.stringify( + { + page: chatgptAdapter.describePage(), + header: { + slot: document.querySelector('[data-app-shell-header-obstacle="true"]') !== null, + buttons: [...document.querySelectorAll('.bp-header-btn, .bp-usage-pill')].map((button) => button.getAttribute('aria-label') ?? button.className), + exportSlug: exportSource.slug() + }, + session: session.snapshot(), + fileBudget: fileBudget(session) + }, + null, + 2 + ) + } } diff --git a/ai/chatgpt/src/features/usage.ts b/ai/chatgpt/src/features/usage.ts new file mode 100644 index 0000000..01835e3 --- /dev/null +++ b/ai/chatgpt/src/features/usage.ts @@ -0,0 +1,168 @@ +import { Tooltip, createButton, createDataRow, createDialog, createSection, ensureUiStyles, markUi, showToast, uiConfig } from '@nolly/ai' +import { Feature, createElement, injectStyle } from '@nolly/core' +import type { MenuEntry, ScriptContext } from '@nolly/core' +import { headerTools } from '../header-tools' +import { session } from '../runtime' +import { storage } from '../storage' + +const PRIMARY_KEY = 'usage-status:primary' +const LAST_KEY = 'usage-status:last' +const LOW = 2 + +const LABELS: Readonly> = { + reason: 'Reasoning', + file_upload: 'File uploads', + paste_text_to_file: 'Pasted text as file', + image_gen: 'Image generation', + deep_research: 'Deep research' +} + +const CSS = ` +.bp-usage-pill { width: auto; gap: 6px; padding: 0 12px; font: 600 12px/1 ui-sans-serif, system-ui, sans-serif; white-space: nowrap; } +.bp-usage-pill[data-level='low'] { border-color: var(--bp-yellow); color: var(--bp-yellow); } +.bp-usage-pill[data-level='empty'] { border-color: var(--bp-red); color: var(--bp-red); } +` + +const labelOf = (feature: string): string => LABELS[feature] ?? feature.replace(/_/g, ' ').replace(/^\w/, (letter) => letter.toUpperCase()) + +const formatReset = (iso: string | null): string => { + const ms = iso ? Date.parse(iso) - Date.now() : Number.NaN + if (!Number.isFinite(ms)) return 'no reset time' + if (ms <= 0) return 'resetting now' + const minutes = Math.round(ms / 60_000) + if (minutes < 60) return `resets in ${minutes}m` + const hours = Math.floor(minutes / 60) + if (hours < 24) return `resets in ${hours}h ${minutes % 60}m` + return `resets ${new Date(iso as string).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}` +} + +const level = (remaining: number): 'ok' | 'low' | 'empty' => (remaining === 0 ? 'empty' : remaining <= LOW ? 'low' : 'ok') + +const titleCase = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1) + +export class UsageFeature extends Feature { + readonly id = 'usage-status' + readonly name = 'Usage Status' + readonly description = 'Shows your remaining limits (reasoning, uploads, images, research) and your plan.' + + private readonly pill = markUi(createElement('button', 'bp-header-btn bp-usage-pill bp-themed')) + private readonly label = createElement('span') + private readonly tooltip: Tooltip + + constructor(context: ScriptContext) { + super(context) + ensureUiStyles() + injectStyle(`${uiConfig().id}-usage-styles`, CSS) + this.pill.type = 'button' + this.pill.setAttribute('aria-label', 'Usage status') + this.pill.appendChild(this.label) + this.pill.addEventListener('click', () => this.open()) + this.tooltip = new Tooltip(this.pill, (container) => container.append(this.rows()), { align: 'end' }) + } + + private get primary(): string { + return storage.get(PRIMARY_KEY, 'reason') + } + + override onEnable(): void { + this.scope.add( + session.subscribe((event) => { + if (event !== 'limits' && event !== 'usage' && event !== 'plan') return + if (event === 'limits') this.checkAlerts() + this.update() + this.context.refreshMenu() + }) + ) + } + + run(): void { + const tools = this.enabled ? headerTools() : null + if (!tools) { + this.tooltip.hide() + this.pill.remove() + return + } + if (this.pill.parentElement !== tools) tools.append(this.pill) + this.update() + } + + override menuEntries(): MenuEntry[] { + return [ + { id: 'details', label: 'Show Usage Details', action: () => this.open() }, + { id: 'metric', label: `Badge Shows: ${labelOf(this.primary)} (click to change)`, action: () => this.cycle() } + ] + } + + private update(): void { + const entry = session.limit(this.primary) + this.label.textContent = entry ? `${labelOf(entry.feature)} ${entry.remaining}` : session.plan ? `${titleCase(session.plan)} plan` : 'Usage' + this.pill.dataset['level'] = entry ? level(entry.remaining) : 'ok' + this.tooltip.refresh() + } + + private cycle(): void { + const features = session.limits.map((limit) => limit.feature) + if (!features.length) return + storage.set(PRIMARY_KEY, features[(features.indexOf(this.primary) + 1) % features.length] ?? 'reason') + this.context.refreshMenu() + this.update() + } + + private rows(): HTMLElement { + const list = createElement('div', 'bp-data-list') + const limits = session.limits + if (!limits.length) { + list.appendChild(createElement('div', 'bp-empty', 'No limit data yet. Send a message or reload the page.')) + return list + } + for (const limit of limits) list.appendChild(createDataRow(labelOf(limit.feature), `${limit.remaining} left · ${formatReset(limit.resetAfter)}`, limit.remaining === 0 ? 'negative' : '')) + return list + } + + private open(): void { + const dialogId = `${uiConfig().id}-usage-dialog` + const existing = document.getElementById(dialogId) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + const ui = createDialog({ id: dialogId, title: 'Usage', description: session.plan ? `${titleCase(session.plan)} plan` : 'Plan not detected yet', width: 480 }) + const limits = createSection('Limits') + limits.appendChild(this.rows()) + const body = [limits] + const { usage } = session + if (usage?.usedPercent !== null && usage?.usedPercent !== undefined) { + const window = createSection('Rolling window') + const bar = createElement('div', 'bp-progress') + const fill = createElement('div', `bp-progress-fill ${usage.limitReached ? 'empty' : ''}`.trim()) + fill.style.width = `${Math.min(100, usage.usedPercent)}%` + bar.appendChild(fill) + const reset = usage.resetAt ? new Date(usage.resetAt * 1000).toLocaleString() : 'unknown' + window.append(bar, createDataRow('Used', `${usage.usedPercent}%`), createDataRow('Resets', reset)) + body.push(window) + } + if (session.maxFileMb !== null) { + const files = createSection('Files') + files.appendChild(createDataRow('Largest file', `${session.maxFileMb} MB`)) + body.push(files) + } + ui.body.replaceChildren(...body) + ui.footer.append(createButton('Close', { primary: true, onClick: ui.close })) + ui.show() + } + + private checkAlerts(): void { + const last = storage.get>(LAST_KEY, {}) + const next = { ...last } + for (const { feature, remaining, resetAfter } of session.limits) { + const before = last[feature] + next[feature] = remaining + if (before === undefined) continue + const name = labelOf(feature) + if (before > 0 && remaining === 0) showToast(`${name}: none left, ${formatReset(resetAfter)}.`, [], 10_000) + else if (before === 0 && remaining > 0) showToast(`${name} is available again (${remaining} left).`, [], 8_000) + else if (before > LOW && remaining > 0 && remaining <= LOW) showToast(`${name}: only ${remaining} left, ${formatReset(resetAfter)}.`, [], 8_000) + } + storage.set(LAST_KEY, next) + } +} diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index a320a83..06e03c5 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -14,6 +14,7 @@ import { session } from './runtime' import { storage } from './storage' import { threadOf } from './threads' import { installTheme } from './theme' +import { UsageFeature } from './features/usage' const onSend = (listener: () => void): (() => void) => session.subscribe((event) => { if (event === 'generation-start') listener() }) @@ -57,5 +58,6 @@ new App() .register((context) => new RecallFeature(context)) .register((context) => new ExporterFeature(context)) .register((context) => new UpdatesFeature(context)) + .register((context) => new UsageFeature(context)) .register((context) => new DiagnosticsFeature(context)) .start() From aad81007a85214950e7122626431df5446b970b4 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:23:12 +0100 Subject: [PATCH 15/19] refactor(ai): ready-gated start for ChatGPT, one settings dialog, batch runner uses the shared sender (step 10b) --- ai/chatgpt/CHANGELOG.md | 1 + ai/chatgpt/src/app.ts | 34 +++-- ai/chatgpt/src/main.ts | 126 ++++++++++++------ ai/chatgpt/src/ready.ts | 18 +++ ai/perplexity/CHANGELOG.md | 1 + ai/perplexity/src/core/app.ts | 8 +- .../src/modules/global-settings/dialog.ts | 59 -------- .../src/modules/global-settings/index.ts | 5 +- .../src/modules/global-settings/styles.ts | 3 +- core/ai/src/features/batch-runner/runner.ts | 20 +-- core/ai/src/ui/css.ts | 1 + core/ai/src/ui/settings-dialog.ts | 73 ++++++---- 12 files changed, 172 insertions(+), 177 deletions(-) create mode 100644 ai/chatgpt/src/ready.ts delete mode 100644 ai/perplexity/src/modules/global-settings/dialog.ts diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index ea68cd1..06c219d 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -5,6 +5,7 @@ - Exporter built from the conversation view (Markdown, text, Word, PDF, JSON) and update checker. - Batch Runner, Selection Toolbar (Ask, Explain, Summarize, Fact-check, Quote) and Max Width. - Initial skeleton: composer and header detection, response observer, session state and diagnostics. +- Starts only after the page has loaded and the composer has rendered, so it doesn't interfere with ChatGPT's own startup. - Header settings button and settings dialog from the shared UI kit; `betterChatgptSend(text)` for testing the composer. - Draft Guard: autosaved drafts, size meter and unsent-text warning. - Message Splitter: send oversized prompts in parts or attach them as a file (respects remaining uploads). diff --git a/ai/chatgpt/src/app.ts b/ai/chatgpt/src/app.ts index 93fe9c6..25f6188 100644 --- a/ai/chatgpt/src/app.ts +++ b/ai/chatgpt/src/app.ts @@ -5,23 +5,19 @@ import { uiMarker } from './dom' import { findComposerForm } from './locate' export class App extends Userscript { - constructor() { - super({ - id: 'better-chatgpt', - name: 'Better ChatGPT', - version: __VERSION__, - storage: { gmPrefix: '' }, - ui: uiMarker, - observe: OBSERVER_OPTIONS, - initializationDelay: CONFIG.initializationDelay, - safetyInterval: CONFIG.safetyInterval, - clearConsole: false, - isReady: () => document.readyState === 'complete' && findComposerForm() !== null, - openSettings: (script) => - toggleSettingsDialog(script.getFeatures(), () => { - script.refreshMenu() - script.requestUpdate() - }) - }) - } + constructor() { + super({ + id: 'better-chatgpt', + name: 'Better ChatGPT', + version: __VERSION__, + storage: { gmPrefix: '' }, + ui: uiMarker, + observe: OBSERVER_OPTIONS, + initializationDelay: CONFIG.initializationDelay, + safetyInterval: CONFIG.safetyInterval, + clearConsole: false, + isReady: () => document.readyState === 'complete' && findComposerForm() !== null, + openSettings: (script) => toggleSettingsDialog(script) + }) + } } diff --git a/ai/chatgpt/src/main.ts b/ai/chatgpt/src/main.ts index 06e03c5..db6a199 100644 --- a/ai/chatgpt/src/main.ts +++ b/ai/chatgpt/src/main.ts @@ -1,4 +1,21 @@ -import { BatchRunnerFeature, CodeBlocksFeature, CommandPaletteFeature, DraftGuardFeature, EnterAsNewlineFeature, ExporterFeature, MaxWidthFeature, MessageSplitterFeature, PromptLibraryFeature, PromptQueueFeature, RecallFeature, SelectionToolbarFeature, UpdatesFeature, configurePlatform, configureUi, loadSplitterSettings } from '@nolly/ai' +import { + BatchRunnerFeature, + CodeBlocksFeature, + CommandPaletteFeature, + DraftGuardFeature, + EnterAsNewlineFeature, + ExporterFeature, + MaxWidthFeature, + MessageSplitterFeature, + PromptLibraryFeature, + PromptQueueFeature, + RecallFeature, + SelectionToolbarFeature, + UpdatesFeature, + configurePlatform, + configureUi, + loadSplitterSettings +} from '@nolly/ai' import { App } from './app' import { fileBudget } from './budget' import { SPLITTER_DEFAULTS } from './config' @@ -6,58 +23,81 @@ import { uiMarker } from './dom' import { exportSource } from './export-source' import { DiagnosticsFeature } from './features/diagnostics' import { HeaderButtonFeature } from './features/header-button' +import { UsageFeature } from './features/usage' import { composerKit, generationKit, sendPrompt } from './kit' import { logger } from './logger' import { findAttachButton, findPrimaryAction, rejectEditable } from './locate' +import { whenReady } from './ready' import { SLUG, URLS } from './repo' import { session } from './runtime' import { storage } from './storage' import { threadOf } from './threads' import { installTheme } from './theme' -import { UsageFeature } from './features/usage' -const onSend = (listener: () => void): (() => void) => session.subscribe((event) => { if (event === 'generation-start') listener() }) +const onSend = (listener: () => void): (() => void) => + session.subscribe((event) => { + if (event === 'generation-start') listener() + }) -configureUi({ - id: 'better-chatgpt', - title: 'Better ChatGPT', - version: __VERSION__, - marker: uiMarker, - composerActions: () => ({ first: findAttachButton(), submit: findPrimaryAction()?.element ?? null }) -}) +whenReady(() => { + 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 }, - codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]') -}) + 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 }, + codeBlockRoot: (pre) => pre.closest('[data-chatgpt-copy-code]') ?? pre.closest('[data-code-block]') + }) -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, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) - .register((context) => new MessageSplitterFeature(context, { storage, composer: composerKit, generation: generationKit, defaults: SPLITTER_DEFAULTS, attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) })) - .register((context) => new BatchRunnerFeature(context)) - .register((context) => new DraftGuardFeature(context, { storage, composer: composerKit, onSend, tokenLimit: () => loadSplitterSettings(storage, SPLITTER_DEFAULTS).limit })) - .register((context) => new CommandPaletteFeature(context)) - .register((context) => new PromptQueueFeature(context)) - .register((context) => new RecallFeature(context)) - .register((context) => new ExporterFeature(context)) - .register((context) => new UpdatesFeature(context)) - .register((context) => new UsageFeature(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, { storage, reject: rejectEditable, send: (editable) => void composerKit.sendComposer(editable) })) + .register( + (context) => + new MessageSplitterFeature(context, { + storage, + composer: composerKit, + generation: generationKit, + defaults: SPLITTER_DEFAULTS, + attachBlocked: () => (fileBudget(session).remainingUploads === 0 ? 'No file uploads left until your limit resets.' : null) + }) + ) + .register((context) => new BatchRunnerFeature(context)) + .register( + (context) => + new DraftGuardFeature(context, { + storage, + composer: composerKit, + onSend, + tokenLimit: () => loadSplitterSettings(storage, SPLITTER_DEFAULTS).limit + }) + ) + .register((context) => new CommandPaletteFeature(context)) + .register((context) => new PromptQueueFeature(context)) + .register((context) => new RecallFeature(context)) + .register((context) => new ExporterFeature(context)) + .register((context) => new UpdatesFeature(context)) + .register((context) => new UsageFeature(context)) + .register((context) => new DiagnosticsFeature(context)) + .start() +}) diff --git a/ai/chatgpt/src/ready.ts b/ai/chatgpt/src/ready.ts new file mode 100644 index 0000000..bcd455a --- /dev/null +++ b/ai/chatgpt/src/ready.ts @@ -0,0 +1,18 @@ +import { findComposerForm } from './locate' + +const FALLBACK_MS = 15_000 + +const ready = (): boolean => document.readyState === 'complete' && findComposerForm() !== null + +export const whenReady = (run: () => void): void => { + if (ready()) { + run() + return + } + const started = Date.now() + const timer = window.setInterval(() => { + if (!ready() && Date.now() - started < FALLBACK_MS) return + window.clearInterval(timer) + run() + }, 250) +} diff --git a/ai/perplexity/CHANGELOG.md b/ai/perplexity/CHANGELOG.md index 1eb18d8..f284f18 100644 --- a/ai/perplexity/CHANGELOG.md +++ b/ai/perplexity/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to Better Perplexity are documented here. The format follows - Internal: Code Block Pro now comes from the shared package. - Internal: Batch Runner, Selection Toolbar and Max Width now come from the shared package. - Internal: Exporter and Update checker now come from the shared package. +- Internal: one shared settings dialog; Batch Runner uses the shared prompt sender. - Fixed: the batch runner was registered twice. ## [1.0.5-hotfix.1] - 2026-11-09 diff --git a/ai/perplexity/src/core/app.ts b/ai/perplexity/src/core/app.ts index 664faca..25f26b6 100644 --- a/ai/perplexity/src/core/app.ts +++ b/ai/perplexity/src/core/app.ts @@ -1,6 +1,6 @@ +import { toggleSettingsDialog } from '@nolly/ai' import { Userscript } from '@nolly/core' import { CONFIG, OBSERVER_OPTIONS } from '../config' -import { toggleSettingsDialog } from '@nolly/ai' import { uiMarker } from './dom' export class App extends Userscript { @@ -16,11 +16,7 @@ export class App extends Userscript { safetyInterval: CONFIG.safetyInterval, clearConsole: true, isReady: () => Boolean(document.querySelector('main')?.children.length), - openSettings: (script) => - toggleSettingsDialog(script.getFeatures(), () => { - script.refreshMenu() - script.requestUpdate() - }) + openSettings: (script) => toggleSettingsDialog(script) }) } } diff --git a/ai/perplexity/src/modules/global-settings/dialog.ts b/ai/perplexity/src/modules/global-settings/dialog.ts deleted file mode 100644 index 0dbdc0a..0000000 --- a/ai/perplexity/src/modules/global-settings/dialog.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { createElement, type ScriptContext } from '@nolly/core' -import { createButton, createSwitch, createDialog } from '@nolly/ai' -import { ensureGearStyles } from './styles' - -const DIALOG_ID = 'better-perplexity-settings-dialog' - -export const toggleGlobalSettings = (context: ScriptContext): void => { - const existing = document.getElementById(DIALOG_ID) - if (existing instanceof HTMLDialogElement) { - existing.close() - return - } - ensureGearStyles() - const ui = createDialog({ id: DIALOG_ID, title: 'Better Perplexity', description: `Version ${__VERSION__}`, width: 560 }) - const render = (): void => { - ui.body.replaceChildren( - ...context.getFeatures().map((module) => { - const section = createElement('section', 'bp-section') - section.appendChild( - createSwitch({ - label: module.name, - hint: module.description, - checked: module.enabled, - onChange: () => { - module.toggle() - render() - } - }).wrapper - ) - if (module.enabled) { - const actions = createElement('div', 'bp-actions') - for (const entry of module.menuEntries()) { - actions.appendChild( - createButton(entry.label, { - onClick: () => { - ui.close() - window.setTimeout(entry.action, 0) - } - }) - ) - } - if (actions.childElementCount) section.appendChild(actions) - } - return section - }) - ) - } - render() - ui.footer.append( - createButton('Command palette', { - onClick: () => { - ui.close() - window.setTimeout(() => context.runCommand('command-palette:open'), 0) - } - }), - createButton('Close', { primary: true, onClick: ui.close }) - ) - ui.show() -} diff --git a/ai/perplexity/src/modules/global-settings/index.ts b/ai/perplexity/src/modules/global-settings/index.ts index aaae2a7..98bed3c 100644 --- a/ai/perplexity/src/modules/global-settings/index.ts +++ b/ai/perplexity/src/modules/global-settings/index.ts @@ -1,7 +1,6 @@ import { createElement, Feature, type MenuEntry, type ScriptContext } from '@nolly/core' import { markUi } from '../../core/dom' -import { createIcon, ensureUiStyles, Tooltip } from '@nolly/ai' -import { toggleGlobalSettings } from './dialog' +import { createIcon, ensureUiStyles, toggleSettingsDialog, Tooltip } from '@nolly/ai' import { ensureGearStyles } from './styles' const INDICATOR_SELECTOR = '.bp-usage-indicator' @@ -40,6 +39,6 @@ export class GlobalSettingsModule extends Feature { } private open(): void { - toggleGlobalSettings(this.context) + toggleSettingsDialog(this.context) } } \ No newline at end of file diff --git a/ai/perplexity/src/modules/global-settings/styles.ts b/ai/perplexity/src/modules/global-settings/styles.ts index d346881..8d89da4 100644 --- a/ai/perplexity/src/modules/global-settings/styles.ts +++ b/ai/perplexity/src/modules/global-settings/styles.ts @@ -20,7 +20,6 @@ const CSS = ` .bp-gear:hover { background: var(--bp-accent); } .bp-gear:focus-visible { outline: 2px solid var(--bp-fg); outline-offset: 2px; } -.bp-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 2px; } ` -export const ensureGearStyles = (): void => injectStyle('better-perplexity-gear-styles', CSS) \ No newline at end of file +export const ensureGearStyles = (): void => injectStyle('better-perplexity-gear-styles', CSS) diff --git a/core/ai/src/features/batch-runner/runner.ts b/core/ai/src/features/batch-runner/runner.ts index e4e54d1..0bba29c 100644 --- a/core/ai/src/features/batch-runner/runner.ts +++ b/core/ai/src/features/batch-runner/runner.ts @@ -1,7 +1,6 @@ +import { isAbort, sleep } from '@nolly/core' import { automate } from '../../automation' -import { readComposer } from '../../composer' -import { findComposer, sendComposer, writeComposer, waitForResponse, logger, storage } from '../../platform' -import { isAbort, sleep, waitFor } from '@nolly/core' +import { logger, sendPrompt, storage, waitForResponse } from '../../platform' export interface BatchState { prompts: string[] @@ -68,7 +67,7 @@ export class BatchRunner { } signal.throwIfAborted() onProgress(index, total, 'sending') - if (!(await this.send(state.prompts[index]!, signal))) return 'failed' + if (!(await sendPrompt(state.prompts[index]!, signal))) return 'failed' onProgress(index, total, 'waiting') await waitForResponse({ signal }) storage.set(STORAGE_KEY, { ...state, next: index + 1, at: Date.now() }) @@ -89,15 +88,4 @@ export class BatchRunner { this.paused = false } } - - private async send(prompt: string, signal: AbortSignal): Promise { - for (let attempt = 0; attempt < 2; attempt++) { - const composer = await waitFor(findComposer, { timeout: 15_000, signal }) - if (!composer) return false - if ((await writeComposer(composer, prompt)) && (await sendComposer(composer))) return true - if (readComposer(composer).trim() === '') return true - await sleep(1_500, signal) - } - return false - } -} \ No newline at end of file +} diff --git a/core/ai/src/ui/css.ts b/core/ai/src/ui/css.ts index 290c9b7..bd57c71 100644 --- a/core/ai/src/ui/css.ts +++ b/core/ai/src/ui/css.ts @@ -146,6 +146,7 @@ export const CONTROLS_CSS = ` } .bp-hint { margin: 12px 0 0; color: var(--bp-muted); font-size: 12px; } +.bp-actions { display: flex; flex-wrap: wrap; gap: 6px; margin: 6px 0 2px; } .bp-switch { position: relative; diff --git a/core/ai/src/ui/settings-dialog.ts b/core/ai/src/ui/settings-dialog.ts index 175bba3..28334a7 100644 --- a/core/ai/src/ui/settings-dialog.ts +++ b/core/ai/src/ui/settings-dialog.ts @@ -1,9 +1,12 @@ -import { createElement, type Feature } from '@nolly/core' +import { createElement } from '@nolly/core' +import type { ScriptContext } from '@nolly/core' import { uiConfig } from './config' -import { createButton, createSection, createSwitch } from './controls' +import { createButton, createSwitch } from './controls' import { createDialog } from './dialog' -export const toggleSettingsDialog = (modules: readonly Feature[], onChange: () => void): void => { +type SettingsHost = Pick + +export const toggleSettingsDialog = (host: SettingsHost): void => { const { id, title, version } = uiConfig() const dialogId = `${id}-settings-dialog` const existing = document.getElementById(dialogId) @@ -11,37 +14,49 @@ export const toggleSettingsDialog = (modules: readonly Feature[], onChange: () = existing.close() return } - const ui = createDialog({ id: dialogId, title, description: `Version ${version}`, width: 480 }) + const ui = createDialog({ id: dialogId, title, description: `Version ${version}`, width: 560 }) const render = (): void => { - const sections = modules.map((module) => { - const section = createSection(module.name) - const stack = createElement('div', 'bp-stack') - const toggle = createSwitch({ - label: 'Enabled', - hint: module.description, - checked: module.enabled, - onChange: (checked) => { - module.enabled = checked - onChange() - } - }) - stack.appendChild(toggle.wrapper) - for (const entry of module.menuEntries()) { - stack.appendChild( - createButton(entry.label, { - onClick: () => { - entry.action() + ui.body.replaceChildren( + ...host.getFeatures().map((feature) => { + const section = createElement('section', 'bp-section') + section.appendChild( + createSwitch({ + label: feature.name, + hint: feature.description, + checked: feature.enabled, + onChange: () => { + feature.toggle() render() } - }) + }).wrapper ) - } - section.appendChild(stack) - return section - }) - ui.body.replaceChildren(...sections) + if (feature.enabled) { + const actions = createElement('div', 'bp-actions') + for (const entry of feature.menuEntries()) { + actions.appendChild( + createButton(entry.label, { + onClick: () => { + ui.close() + window.setTimeout(entry.action, 0) + } + }) + ) + } + if (actions.childElementCount) section.appendChild(actions) + } + return section + }) + ) } render() - ui.footer.append(createButton('Done', { primary: true, onClick: ui.close })) + ui.footer.append( + createButton('Command palette', { + onClick: () => { + ui.close() + window.setTimeout(() => host.runCommand('command-palette:open'), 0) + } + }), + createButton('Close', { primary: true, onClick: ui.close }) + ) ui.show() } From 73e3065367979d04a60aa35c406c2eb0e82aad59 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:30:05 +0100 Subject: [PATCH 16/19] fix(chatgpt): style header buttons with ChatGPT's own toolbar classes --- ai/chatgpt/src/export-source.ts | 53 +++++++++++----------- ai/chatgpt/src/features/header-button.ts | 57 ++++++++++++------------ ai/chatgpt/src/features/usage.ts | 8 ++-- ai/chatgpt/src/header-style.ts | 5 +++ ai/chatgpt/src/header-tools.ts | 3 +- ai/chatgpt/src/theme.ts | 2 + 6 files changed, 69 insertions(+), 59 deletions(-) create mode 100644 ai/chatgpt/src/header-style.ts diff --git a/ai/chatgpt/src/export-source.ts b/ai/chatgpt/src/export-source.ts index e731697..cad1daa 100644 --- a/ai/chatgpt/src/export-source.ts +++ b/ai/chatgpt/src/export-source.ts @@ -4,39 +4,40 @@ import { toMarkdown } from './dom-markdown' import { headerTools } from './header-tools' import { findTurns } from './messages' import type { Turn } from './messages' +import { ICON_BUTTON_CLASS } from './header-style' const ROLE_LABEL = { user: 'You', assistant: 'ChatGPT' } as const const turns = (): Turn[] => { - const found = findTurns() - if (!found.length) throw new Error('No messages found on this page.') - return found + const found = findTurns() + if (!found.length) throw new Error('No messages found on this page.') + return found } const render = (turn: Turn): string => (turn.role === 'user' ? turn.text() : toMarkdown(turn.element)) export const exportSource: ExportSource = { - name: 'ChatGPT', - citations: false, - slug: () => parseConversation(new URL(location.href)).id, - markdown: async () => turns().map((turn) => `**${ROLE_LABEL[turn.role]}**\n\n${render(turn)}`).join('\n\n---\n\n'), - json: async () => - JSON.stringify( - { - app: 'better-chatgpt', - conversationId: parseConversation(new URL(location.href)).id, - title: document.title, - url: location.href, - exportedAt: new Date().toISOString(), - messages: turns().map((turn) => ({ role: turn.role, markdown: render(turn) })) - }, - null, - 2 - ), - place: (button) => { - const tools = headerTools() - if (!tools) return false - if (button.parentElement !== tools) tools.append(button) - return true - } + name: 'ChatGPT', + citations: false, + slug: () => parseConversation(new URL(location.href)).id, + markdown: async () => turns().map((turn) => `**${ROLE_LABEL[turn.role]}**\n\n${render(turn)}`).join('\n\n---\n\n'), + json: async () => JSON.stringify( + { + app: 'better-chatgpt', + conversationId: parseConversation(new URL(location.href)).id, + title: document.title, + url: location.href, + exportedAt: new Date().toISOString(), + messages: turns().map((turn) => ({ role: turn.role, markdown: render(turn) })) + }, + null, + 2 + ), + place: (button) => { + const tools = headerTools() + if (!tools) return false + if (button.className !== ICON_BUTTON_CLASS) button.className = ICON_BUTTON_CLASS + if (button.parentElement !== tools) tools.append(button) + return true + } } diff --git a/ai/chatgpt/src/features/header-button.ts b/ai/chatgpt/src/features/header-button.ts index 7d68cef..27183f4 100644 --- a/ai/chatgpt/src/features/header-button.ts +++ b/ai/chatgpt/src/features/header-button.ts @@ -1,38 +1,39 @@ import { Tooltip, createIcon, ensureUiStyles } from '@nolly/ai' import { Feature, createElement } from '@nolly/core' import { headerTools } from '../header-tools' +import { ICON_BUTTON_CLASS } from '../header-style' export class HeaderButtonFeature extends Feature { - readonly id = 'header-button' - readonly name = 'Header button' - readonly description = 'Adds the Better ChatGPT settings button to the header.' + readonly id = 'header-button' + readonly name = 'Header button' + readonly description = 'Adds the Better ChatGPT settings button to the header.' - private button: HTMLButtonElement | null = null - private tooltip: Tooltip | null = null + private button: HTMLButtonElement | null = null + private tooltip: Tooltip | null = null - run(): void { - if (!this.enabled) return - const tools = headerTools() - if (!tools) return - if (!this.button) this.build() - if (this.button && this.button.parentElement !== tools) tools.append(this.button) - } + run(): void { + if (!this.enabled) return + const tools = headerTools() + if (!tools) return + if (!this.button) this.build() + if (this.button && this.button.parentElement !== tools) tools.append(this.button) + } - override onDisable(): void { - this.tooltip?.destroy() - this.tooltip = null - this.button?.remove() - this.button = null - } + override onDisable(): void { + this.tooltip?.destroy() + this.tooltip = null + this.button?.remove() + this.button = null + } - private build(): void { - ensureUiStyles() - const button = createElement('button', 'bp-header-btn bp-themed') - button.type = 'button' - button.setAttribute('aria-label', 'Better ChatGPT settings') - button.appendChild(createIcon('sliders')) - button.addEventListener('click', () => this.context.openSettings()) - this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) - this.button = button - } + private build(): void { + ensureUiStyles() + const button = createElement('button', ICON_BUTTON_CLASS) + button.type = 'button' + button.setAttribute('aria-label', 'Better ChatGPT settings') + button.appendChild(createIcon('sliders', 20)) + button.addEventListener('click', () => this.context.openSettings()) + this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) + this.button = button + } } diff --git a/ai/chatgpt/src/features/usage.ts b/ai/chatgpt/src/features/usage.ts index 01835e3..6f14f37 100644 --- a/ai/chatgpt/src/features/usage.ts +++ b/ai/chatgpt/src/features/usage.ts @@ -4,6 +4,7 @@ import type { MenuEntry, ScriptContext } from '@nolly/core' import { headerTools } from '../header-tools' import { session } from '../runtime' import { storage } from '../storage' +import { PILL_BUTTON_CLASS } from '../header-style' const PRIMARY_KEY = 'usage-status:primary' const LAST_KEY = 'usage-status:last' @@ -18,9 +19,8 @@ const LABELS: Readonly> = { } const CSS = ` -.bp-usage-pill { width: auto; gap: 6px; padding: 0 12px; font: 600 12px/1 ui-sans-serif, system-ui, sans-serif; white-space: nowrap; } -.bp-usage-pill[data-level='low'] { border-color: var(--bp-yellow); color: var(--bp-yellow); } -.bp-usage-pill[data-level='empty'] { border-color: var(--bp-red); color: var(--bp-red); } +.bp-usage-pill[data-level='low'] { color: var(--bp-yellow); } +.bp-usage-pill[data-level='empty'] { color: var(--bp-red); } ` const labelOf = (feature: string): string => LABELS[feature] ?? feature.replace(/_/g, ' ').replace(/^\w/, (letter) => letter.toUpperCase()) @@ -45,7 +45,7 @@ export class UsageFeature extends Feature { readonly name = 'Usage Status' readonly description = 'Shows your remaining limits (reasoning, uploads, images, research) and your plan.' - private readonly pill = markUi(createElement('button', 'bp-header-btn bp-usage-pill bp-themed')) + private readonly pill = markUi(createElement('button', `${PILL_BUTTON_CLASS} bp-usage-pill bp-themed`)) private readonly label = createElement('span') private readonly tooltip: Tooltip diff --git a/ai/chatgpt/src/header-style.ts b/ai/chatgpt/src/header-style.ts new file mode 100644 index 0000000..d624301 --- /dev/null +++ b/ai/chatgpt/src/header-style.ts @@ -0,0 +1,5 @@ +const BASE = 'no-drag cursor-interaction items-center select-none disabled:cursor-default aria-disabled:cursor-default focus:outline-hidden disabled:opacity-40 aria-disabled:opacity-40 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-0 whitespace-nowrap flex border gap-1 rounded-lg text-default not-disabled:not-aria-disabled:hover:bg-secondary-ghost-hover data-[state=open]:bg-secondary-ghost-hover aria-pressed:bg-secondary-ghost-hover border-transparent button-toolbar py-0 text-sm leading-[18px]' + +export const ICON_BUTTON_CLASS = `${BASE} aspect-square shrink-0 items-center justify-center !px-0 bc-header-btn` +export const PILL_BUTTON_CLASS = `${BASE} shrink-0 items-center px-3 font-medium` +export const TOOLS_CLASS = 'pointer-events-auto flex items-center gap-toolbar-action no-drag shrink-0' diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts index 80dbdc9..dbd565b 100644 --- a/ai/chatgpt/src/header-tools.ts +++ b/ai/chatgpt/src/header-tools.ts @@ -1,8 +1,9 @@ import { createElement } from '@nolly/core' import { markUi } from './dom' +import { TOOLS_CLASS } from './header-style' import { findHeaderSlot } from './locate' -const container = markUi(createElement('div', 'pointer-events-auto flex items-center gap-1 no-drag shrink-0')) +const container = markUi(createElement('div', TOOLS_CLASS)) export const headerTools = (): HTMLElement | null => { const slot = findHeaderSlot() diff --git a/ai/chatgpt/src/theme.ts b/ai/chatgpt/src/theme.ts index 196fa87..e1b3d9b 100644 --- a/ai/chatgpt/src/theme.ts +++ b/ai/chatgpt/src/theme.ts @@ -30,6 +30,8 @@ html.light .bp-themed { .bp-tip-mode { font-weight: 600; } .bp-tip-sub { color: var(--bp-muted); } .bp-tip-foot { margin-top: 4px; color: var(--bp-muted); font-size: 11px; } + +.bc-header-btn svg { width: 20px; height: 20px; } ` export const installTheme = (): void => injectStyle('better-chatgpt-theme', CSS) From 41050a616acffead705ca07e22ace535dc2a6310 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:37:35 +0100 Subject: [PATCH 17/19] fix(chatgpt): turn locator for the current DOM, converter for the new renderer, header tools inside the native button row --- ai/chatgpt/src/dom-markdown.ts | 16 +- ai/chatgpt/src/export-source.ts | 7 +- ai/chatgpt/src/features/header-button.ts | 56 +++-- ai/chatgpt/src/features/usage.ts | 274 +++++++++++------------ ai/chatgpt/src/header-tools.ts | 26 ++- ai/chatgpt/src/messages.ts | 35 ++- 6 files changed, 224 insertions(+), 190 deletions(-) diff --git a/ai/chatgpt/src/dom-markdown.ts b/ai/chatgpt/src/dom-markdown.ts index 6828b7c..bbb0a45 100644 --- a/ai/chatgpt/src/dom-markdown.ts +++ b/ai/chatgpt/src/dom-markdown.ts @@ -1,10 +1,10 @@ import { isOwnUi } from './dom' const HEADING = /^H([1-6])$/ -const SKIPPED = 'button, svg, script, style, [data-markdown-copy="exclude"], .katex-html' +const SKIPPED = 'script, style, svg, [data-markdown-copy="exclude"], [data-conversation-role], .katex-html' const BLOCKS = new Set(['P', 'DIV', 'UL', 'OL', 'PRE', 'TABLE', 'BLOCKQUOTE', 'HR', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'SECTION', 'ARTICLE']) -const skipped = (element: HTMLElement): boolean => isOwnUi(element) || element.matches(SKIPPED) +const skipped = (element: HTMLElement): boolean => isOwnUi(element) || element.matches(SKIPPED) || (element.tagName === 'BUTTON' && !element.querySelector('img')) const tex = (element: HTMLElement): string => element.querySelector('annotation[encoding="application/x-tex"]')?.textContent?.trim() ?? element.textContent ?? '' @@ -15,7 +15,13 @@ const inline = (node: Node): string => { if (!(node instanceof HTMLElement) || skipped(node)) return '' if (node.classList.contains('katex-display')) return `\n\n$$${tex(node)}$$\n\n` if (node.classList.contains('katex')) return `$${tex(node)}$` + if (node.hasAttribute('data-pill')) { + const href = node.querySelector('a[href]')?.getAttribute('href') + const label = (node.textContent ?? '').trim() + return href && label ? ` [${label}](${href})` : '' + } const inner = (): string => [...node.childNodes].map(inline).join('') + if (node.hasAttribute('data-d-default-strong')) return wrap('**', inner()) switch (node.tagName) { case 'BR': return ' \n' @@ -60,6 +66,8 @@ const table = (element: HTMLElement): string => { return [line(head ?? []), `| ${Array.from({ length: width }, () => '---').join(' | ')} |`, ...body.map(line)].join('\n') } +const flat = (node: Node): Node[] => (node instanceof HTMLElement && node.tagName === 'DIV' && !skipped(node) ? [...node.childNodes].flatMap(flat) : [node]) + const list = (element: HTMLElement, depth: number): string => { const ordered = element.tagName === 'OL' let index = Number.parseInt(element.getAttribute('start') ?? '1', 10) || 1 @@ -69,10 +77,10 @@ const list = (element: HTMLElement, depth: number): string => { if (!(item instanceof HTMLElement) || item.tagName !== 'LI' || skipped(item)) continue const own: string[] = [] const nested: string[] = [] - for (const child of item.childNodes) { + for (const child of [...item.childNodes].flatMap(flat)) { if (child instanceof HTMLElement && (child.tagName === 'UL' || child.tagName === 'OL')) nested.push(list(child, depth + 1)) else if (child instanceof HTMLElement && child.tagName === 'PRE') nested.push(fence(child).split('\n').map((line) => `${indent} ${line}`).join('\n')) - else own.push(inline(child)) + else own.push(child instanceof HTMLElement && child.tagName === 'P' ? `${inline(child)} ` : inline(child)) } lines.push(`${indent}${ordered ? `${index++}.` : '-'} ${own.join('').trim()}`, ...nested.filter(Boolean)) } diff --git a/ai/chatgpt/src/export-source.ts b/ai/chatgpt/src/export-source.ts index cad1daa..1891065 100644 --- a/ai/chatgpt/src/export-source.ts +++ b/ai/chatgpt/src/export-source.ts @@ -1,7 +1,7 @@ import type { ExportSource } from '@nolly/ai' import { parseConversation } from './adapter' import { toMarkdown } from './dom-markdown' -import { headerTools } from './header-tools' +import { placeTool } from './header-tools' import { findTurns } from './messages' import type { Turn } from './messages' import { ICON_BUTTON_CLASS } from './header-style' @@ -34,10 +34,7 @@ export const exportSource: ExportSource = { 2 ), place: (button) => { - const tools = headerTools() - if (!tools) return false if (button.className !== ICON_BUTTON_CLASS) button.className = ICON_BUTTON_CLASS - if (button.parentElement !== tools) tools.append(button) - return true + return placeTool(button, 'export') } } diff --git a/ai/chatgpt/src/features/header-button.ts b/ai/chatgpt/src/features/header-button.ts index 27183f4..06b7f3e 100644 --- a/ai/chatgpt/src/features/header-button.ts +++ b/ai/chatgpt/src/features/header-button.ts @@ -1,39 +1,37 @@ import { Tooltip, createIcon, ensureUiStyles } from '@nolly/ai' import { Feature, createElement } from '@nolly/core' -import { headerTools } from '../header-tools' import { ICON_BUTTON_CLASS } from '../header-style' +import { placeTool } from '../header-tools' export class HeaderButtonFeature extends Feature { - readonly id = 'header-button' - readonly name = 'Header button' - readonly description = 'Adds the Better ChatGPT settings button to the header.' + readonly id = 'header-button' + readonly name = 'Header button' + readonly description = 'Adds the Better ChatGPT settings button to the header.' - private button: HTMLButtonElement | null = null - private tooltip: Tooltip | null = null + private button: HTMLButtonElement | null = null + private tooltip: Tooltip | null = null - run(): void { - if (!this.enabled) return - const tools = headerTools() - if (!tools) return - if (!this.button) this.build() - if (this.button && this.button.parentElement !== tools) tools.append(this.button) - } + run(): void { + if (!this.enabled) return + if (!this.button) this.build() + if (this.button) placeTool(this.button, 'settings') + } - override onDisable(): void { - this.tooltip?.destroy() - this.tooltip = null - this.button?.remove() - this.button = null - } + override onDisable(): void { + this.tooltip?.destroy() + this.tooltip = null + this.button?.remove() + this.button = null + } - private build(): void { - ensureUiStyles() - const button = createElement('button', ICON_BUTTON_CLASS) - button.type = 'button' - button.setAttribute('aria-label', 'Better ChatGPT settings') - button.appendChild(createIcon('sliders', 20)) - button.addEventListener('click', () => this.context.openSettings()) - this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) - this.button = button - } + private build(): void { + ensureUiStyles() + const button = createElement('button', ICON_BUTTON_CLASS) + button.type = 'button' + button.setAttribute('aria-label', 'Better ChatGPT settings') + button.appendChild(createIcon('sliders', 20)) + button.addEventListener('click', () => this.context.openSettings()) + this.tooltip = new Tooltip(button, (container) => container.append(createElement('div', 'bp-tip-mode', 'Better ChatGPT'), createElement('div', 'bp-tip-sub', 'Settings')), { align: 'end' }) + this.button = button + } } diff --git a/ai/chatgpt/src/features/usage.ts b/ai/chatgpt/src/features/usage.ts index 6f14f37..81fae8d 100644 --- a/ai/chatgpt/src/features/usage.ts +++ b/ai/chatgpt/src/features/usage.ts @@ -1,7 +1,7 @@ import { Tooltip, createButton, createDataRow, createDialog, createSection, ensureUiStyles, markUi, showToast, uiConfig } from '@nolly/ai' import { Feature, createElement, injectStyle } from '@nolly/core' import type { MenuEntry, ScriptContext } from '@nolly/core' -import { headerTools } from '../header-tools' +import { placeTool } from '../header-tools' import { session } from '../runtime' import { storage } from '../storage' import { PILL_BUTTON_CLASS } from '../header-style' @@ -11,11 +11,11 @@ const LAST_KEY = 'usage-status:last' const LOW = 2 const LABELS: Readonly> = { - reason: 'Reasoning', - file_upload: 'File uploads', - paste_text_to_file: 'Pasted text as file', - image_gen: 'Image generation', - deep_research: 'Deep research' + reason: 'Reasoning', + file_upload: 'File uploads', + paste_text_to_file: 'Pasted text as file', + image_gen: 'Image generation', + deep_research: 'Deep research' } const CSS = ` @@ -26,14 +26,14 @@ const CSS = ` const labelOf = (feature: string): string => LABELS[feature] ?? feature.replace(/_/g, ' ').replace(/^\w/, (letter) => letter.toUpperCase()) const formatReset = (iso: string | null): string => { - const ms = iso ? Date.parse(iso) - Date.now() : Number.NaN - if (!Number.isFinite(ms)) return 'no reset time' - if (ms <= 0) return 'resetting now' - const minutes = Math.round(ms / 60_000) - if (minutes < 60) return `resets in ${minutes}m` - const hours = Math.floor(minutes / 60) - if (hours < 24) return `resets in ${hours}h ${minutes % 60}m` - return `resets ${new Date(iso as string).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}` + const ms = iso ? Date.parse(iso) - Date.now() : Number.NaN + if (!Number.isFinite(ms)) return 'no reset time' + if (ms <= 0) return 'resetting now' + const minutes = Math.round(ms / 60_000) + if (minutes < 60) return `resets in ${minutes}m` + const hours = Math.floor(minutes / 60) + if (hours < 24) return `resets in ${hours}h ${minutes % 60}m` + return `resets ${new Date(iso as string).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}` } const level = (remaining: number): 'ok' | 'low' | 'empty' => (remaining === 0 ? 'empty' : remaining <= LOW ? 'low' : 'ok') @@ -41,128 +41,126 @@ const level = (remaining: number): 'ok' | 'low' | 'empty' => (remaining === 0 ? const titleCase = (value: string): string => value.charAt(0).toUpperCase() + value.slice(1) export class UsageFeature extends Feature { - readonly id = 'usage-status' - readonly name = 'Usage Status' - readonly description = 'Shows your remaining limits (reasoning, uploads, images, research) and your plan.' - - private readonly pill = markUi(createElement('button', `${PILL_BUTTON_CLASS} bp-usage-pill bp-themed`)) - private readonly label = createElement('span') - private readonly tooltip: Tooltip - - constructor(context: ScriptContext) { - super(context) - ensureUiStyles() - injectStyle(`${uiConfig().id}-usage-styles`, CSS) - this.pill.type = 'button' - this.pill.setAttribute('aria-label', 'Usage status') - this.pill.appendChild(this.label) - this.pill.addEventListener('click', () => this.open()) - this.tooltip = new Tooltip(this.pill, (container) => container.append(this.rows()), { align: 'end' }) - } - - private get primary(): string { - return storage.get(PRIMARY_KEY, 'reason') - } - - override onEnable(): void { - this.scope.add( - session.subscribe((event) => { - if (event !== 'limits' && event !== 'usage' && event !== 'plan') return - if (event === 'limits') this.checkAlerts() - this.update() - this.context.refreshMenu() - }) - ) - } - - run(): void { - const tools = this.enabled ? headerTools() : null - if (!tools) { - this.tooltip.hide() - this.pill.remove() - return - } - if (this.pill.parentElement !== tools) tools.append(this.pill) - this.update() - } - - override menuEntries(): MenuEntry[] { - return [ - { id: 'details', label: 'Show Usage Details', action: () => this.open() }, - { id: 'metric', label: `Badge Shows: ${labelOf(this.primary)} (click to change)`, action: () => this.cycle() } - ] - } - - private update(): void { - const entry = session.limit(this.primary) - this.label.textContent = entry ? `${labelOf(entry.feature)} ${entry.remaining}` : session.plan ? `${titleCase(session.plan)} plan` : 'Usage' - this.pill.dataset['level'] = entry ? level(entry.remaining) : 'ok' - this.tooltip.refresh() - } - - private cycle(): void { - const features = session.limits.map((limit) => limit.feature) - if (!features.length) return - storage.set(PRIMARY_KEY, features[(features.indexOf(this.primary) + 1) % features.length] ?? 'reason') - this.context.refreshMenu() - this.update() - } - - private rows(): HTMLElement { - const list = createElement('div', 'bp-data-list') - const limits = session.limits - if (!limits.length) { - list.appendChild(createElement('div', 'bp-empty', 'No limit data yet. Send a message or reload the page.')) - return list - } - for (const limit of limits) list.appendChild(createDataRow(labelOf(limit.feature), `${limit.remaining} left · ${formatReset(limit.resetAfter)}`, limit.remaining === 0 ? 'negative' : '')) - return list - } - - private open(): void { - const dialogId = `${uiConfig().id}-usage-dialog` - const existing = document.getElementById(dialogId) - if (existing instanceof HTMLDialogElement) { - existing.close() - return - } - const ui = createDialog({ id: dialogId, title: 'Usage', description: session.plan ? `${titleCase(session.plan)} plan` : 'Plan not detected yet', width: 480 }) - const limits = createSection('Limits') - limits.appendChild(this.rows()) - const body = [limits] - const { usage } = session - if (usage?.usedPercent !== null && usage?.usedPercent !== undefined) { - const window = createSection('Rolling window') - const bar = createElement('div', 'bp-progress') - const fill = createElement('div', `bp-progress-fill ${usage.limitReached ? 'empty' : ''}`.trim()) - fill.style.width = `${Math.min(100, usage.usedPercent)}%` - bar.appendChild(fill) - const reset = usage.resetAt ? new Date(usage.resetAt * 1000).toLocaleString() : 'unknown' - window.append(bar, createDataRow('Used', `${usage.usedPercent}%`), createDataRow('Resets', reset)) - body.push(window) - } - if (session.maxFileMb !== null) { - const files = createSection('Files') - files.appendChild(createDataRow('Largest file', `${session.maxFileMb} MB`)) - body.push(files) - } - ui.body.replaceChildren(...body) - ui.footer.append(createButton('Close', { primary: true, onClick: ui.close })) - ui.show() - } - - private checkAlerts(): void { - const last = storage.get>(LAST_KEY, {}) - const next = { ...last } - for (const { feature, remaining, resetAfter } of session.limits) { - const before = last[feature] - next[feature] = remaining - if (before === undefined) continue - const name = labelOf(feature) - if (before > 0 && remaining === 0) showToast(`${name}: none left, ${formatReset(resetAfter)}.`, [], 10_000) - else if (before === 0 && remaining > 0) showToast(`${name} is available again (${remaining} left).`, [], 8_000) - else if (before > LOW && remaining > 0 && remaining <= LOW) showToast(`${name}: only ${remaining} left, ${formatReset(resetAfter)}.`, [], 8_000) - } - storage.set(LAST_KEY, next) - } + readonly id = 'usage-status' + readonly name = 'Usage Status' + readonly description = 'Shows your remaining limits (reasoning, uploads, images, research) and your plan.' + + private readonly pill = markUi(createElement('button', `${PILL_BUTTON_CLASS} bp-usage-pill bp-themed`)) + private readonly label = createElement('span') + private readonly tooltip: Tooltip + + constructor(context: ScriptContext) { + super(context) + ensureUiStyles() + injectStyle(`${uiConfig().id}-usage-styles`, CSS) + this.pill.type = 'button' + this.pill.setAttribute('aria-label', 'Usage status') + this.pill.appendChild(this.label) + this.pill.addEventListener('click', () => this.open()) + this.tooltip = new Tooltip(this.pill, (container) => container.append(this.rows()), { align: 'end' }) + } + + private get primary(): string { + return storage.get(PRIMARY_KEY, 'reason') + } + + override onEnable(): void { + this.scope.add( + session.subscribe((event) => { + if (event !== 'limits' && event !== 'usage' && event !== 'plan') return + if (event === 'limits') this.checkAlerts() + this.update() + this.context.refreshMenu() + }) + ) + } + + run(): void { + if (!this.enabled || !placeTool(this.pill, 'usage')) { + this.tooltip.hide() + this.pill.remove() + return + } + this.update() + } + + override menuEntries(): MenuEntry[] { + return [ + { id: 'details', label: 'Show Usage Details', action: () => this.open() }, + { id: 'metric', label: `Badge Shows: ${labelOf(this.primary)} (click to change)`, action: () => this.cycle() } + ] + } + + private update(): void { + const entry = session.limit(this.primary) + this.label.textContent = entry ? `${labelOf(entry.feature)} ${entry.remaining}` : session.plan ? `${titleCase(session.plan)} plan` : 'Usage' + this.pill.dataset['level'] = entry ? level(entry.remaining) : 'ok' + this.tooltip.refresh() + } + + private cycle(): void { + const features = session.limits.map((limit) => limit.feature) + if (!features.length) return + storage.set(PRIMARY_KEY, features[(features.indexOf(this.primary) + 1) % features.length] ?? 'reason') + this.context.refreshMenu() + this.update() + } + + private rows(): HTMLElement { + const list = createElement('div', 'bp-data-list') + const limits = session.limits + if (!limits.length) { + list.appendChild(createElement('div', 'bp-empty', 'No limit data yet. Send a message or reload the page.')) + return list + } + for (const limit of limits) list.appendChild(createDataRow(labelOf(limit.feature), `${limit.remaining} left · ${formatReset(limit.resetAfter)}`, limit.remaining === 0 ? 'negative' : '')) + return list + } + + private open(): void { + const dialogId = `${uiConfig().id}-usage-dialog` + const existing = document.getElementById(dialogId) + if (existing instanceof HTMLDialogElement) { + existing.close() + return + } + const ui = createDialog({ id: dialogId, title: 'Usage', description: session.plan ? `${titleCase(session.plan)} plan` : 'Plan not detected yet', width: 480 }) + const limits = createSection('Limits') + limits.appendChild(this.rows()) + const body = [limits] + const { usage } = session + if (usage?.usedPercent !== null && usage?.usedPercent !== undefined) { + const window = createSection('Rolling window') + const bar = createElement('div', 'bp-progress') + const fill = createElement('div', `bp-progress-fill ${usage.limitReached ? 'empty' : ''}`.trim()) + fill.style.width = `${Math.min(100, usage.usedPercent)}%` + bar.appendChild(fill) + const reset = usage.resetAt ? new Date(usage.resetAt * 1000).toLocaleString() : 'unknown' + window.append(bar, createDataRow('Used', `${usage.usedPercent}%`), createDataRow('Resets', reset)) + body.push(window) + } + if (session.maxFileMb !== null) { + const files = createSection('Files') + files.appendChild(createDataRow('Largest file', `${session.maxFileMb} MB`)) + body.push(files) + } + ui.body.replaceChildren(...body) + ui.footer.append(createButton('Close', { primary: true, onClick: ui.close })) + ui.show() + } + + private checkAlerts(): void { + const last = storage.get>(LAST_KEY, {}) + const next = { ...last } + for (const { feature, remaining, resetAfter } of session.limits) { + const before = last[feature] + next[feature] = remaining + if (before === undefined) continue + const name = labelOf(feature) + if (before > 0 && remaining === 0) showToast(`${name}: none left, ${formatReset(resetAfter)}.`, [], 10_000) + else if (before === 0 && remaining > 0) showToast(`${name} is available again (${remaining} left).`, [], 8_000) + else if (before > LOW && remaining > 0 && remaining <= LOW) showToast(`${name}: only ${remaining} left, ${formatReset(resetAfter)}.`, [], 8_000) + } + storage.set(LAST_KEY, next) + } } diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts index dbd565b..65f1272 100644 --- a/ai/chatgpt/src/header-tools.ts +++ b/ai/chatgpt/src/header-tools.ts @@ -1,13 +1,23 @@ -import { createElement } from '@nolly/core' -import { markUi } from './dom' -import { TOOLS_CLASS } from './header-style' import { findHeaderSlot } from './locate' -const container = markUi(createElement('div', TOOLS_CLASS)) +const ORDER = ['settings', 'usage', 'export'] as const -export const headerTools = (): HTMLElement | null => { +export type ToolId = (typeof ORDER)[number] + +const toolRow = (): HTMLElement | null => { const slot = findHeaderSlot() - if (!slot) return null - if (container.parentElement !== slot || slot.firstElementChild !== container) slot.prepend(container) - return container + return slot?.querySelector('.contents > div') ?? slot +} + +export const placeTool = (button: HTMLElement, id: ToolId): boolean => { + const row = toolRow() + if (!row) return false + button.dataset['bcTool'] = id + if (button.parentElement !== row) row.prepend(button) + const ours = ORDER.flatMap((name) => row.querySelector(`:scope > [data-bc-tool="${name}"]`) ?? []) + ours.forEach((element, index) => { + const expected = row.children[index] ?? null + if (expected !== element) row.insertBefore(element, expected) + }) + return true } diff --git a/ai/chatgpt/src/messages.ts b/ai/chatgpt/src/messages.ts index 0de16ab..64b4d8e 100644 --- a/ai/chatgpt/src/messages.ts +++ b/ai/chatgpt/src/messages.ts @@ -5,18 +5,41 @@ export type Role = 'user' | 'assistant' export interface Turn { readonly role: Role readonly element: HTMLElement + readonly id: string | null readonly text: () => string } -const ROLE_ATTRIBUTE = 'data-message-author-role' +const UNIT = '[data-chatgpt-search-unit-key]' +const UNIT_ROLE = /:(user|assistant)$/ +const USER_CONTENT = '[data-user-message-bubble]' +const ASSISTANT_CONTENT = '[data-markdown-copy="contents"], [data-dil-response], [data-markdown-text-style]' +const LEGACY = '[data-message-author-role]' -export const findTurns = (): Turn[] => - [...document.querySelectorAll(`[${ROLE_ATTRIBUTE}]`)].flatMap((element): Turn[] => { - const role = element.getAttribute(ROLE_ATTRIBUTE) - if (isOwnUi(element) || (role !== 'user' && role !== 'assistant')) return [] - return [{ role, element, text: () => (element.innerText ?? '').trim() }] +const make = (role: Role, container: HTMLElement, content: HTMLElement): Turn => ({ + role, + element: content, + id: container.getAttribute('data-chatgpt-search-message-ids')?.split(' ')[0] ?? null, + text: () => (content.innerText ?? '').trim() +}) + +const fromUnits = (): Turn[] => + [...document.querySelectorAll(UNIT)].flatMap((unit): Turn[] => { + const role = UNIT_ROLE.exec(unit.getAttribute('data-chatgpt-search-unit-key') ?? '')?.[1] + if (isOwnUi(unit) || (role !== 'user' && role !== 'assistant')) return [] + return [make(role, unit, unit.querySelector(role === 'user' ? USER_CONTENT : ASSISTANT_CONTENT) ?? unit)] + }) + +const fromLegacy = (): Turn[] => + [...document.querySelectorAll(LEGACY)].flatMap((element): Turn[] => { + const role = element.getAttribute('data-message-author-role') + return !isOwnUi(element) && (role === 'user' || role === 'assistant') ? [make(role, element, element)] : [] }) +export const findTurns = (): Turn[] => { + const units = fromUnits() + return units.length ? units : fromLegacy() +} + export const countTurns = (): Record => { const turns = findTurns() return { user: turns.filter((turn) => turn.role === 'user').length, assistant: turns.filter((turn) => turn.role === 'assistant').length } From 1164c894e9a52f25270e9e853bfc155820782777 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:43:57 +0100 Subject: [PATCH 18/19] chore(chatgpt): header layout diagnostics --- ai/chatgpt/src/features/diagnostics.ts | 23 +++++++++++++++++++++-- ai/chatgpt/src/header-tools.ts | 2 +- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/ai/chatgpt/src/features/diagnostics.ts b/ai/chatgpt/src/features/diagnostics.ts index 558c4c6..e8d5d21 100644 --- a/ai/chatgpt/src/features/diagnostics.ts +++ b/ai/chatgpt/src/features/diagnostics.ts @@ -3,9 +3,24 @@ import type { FeatureCommand } from '@nolly/core' import { chatgptAdapter } from '../adapter' import { fileBudget } from '../budget' import { exportSource } from '../export-source' +import { toolRow } from '../header-tools' import { sendPrompt } from '../kit' +import { findHeaderSlot } from '../locate' import { session } from '../runtime' +const box = (element: Element): { x: number; y: number; w: number; h: number } => { + const { x, y, width, height } = element.getBoundingClientRect() + return { x: Math.round(x), y: Math.round(y), w: Math.round(width), h: Math.round(height) } +} + +const brief = (element: Element): Record => ({ + tag: element.tagName.toLowerCase(), + tool: element.getAttribute('data-bc-tool') ?? undefined, + label: element.getAttribute('aria-label') ?? (element.textContent ?? '').trim().slice(0, 24), + id: element.id || undefined, + ...box(element) +}) + export class DiagnosticsFeature extends Feature { readonly id = 'diagnostics' readonly name = 'Diagnostics' @@ -27,12 +42,16 @@ export class DiagnosticsFeature extends Feature { } private dump(): string { + const slot = findHeaderSlot() + const row = toolRow() return JSON.stringify( { page: chatgptAdapter.describePage(), header: { - slot: document.querySelector('[data-app-shell-header-obstacle="true"]') !== null, - buttons: [...document.querySelectorAll('.bp-header-btn, .bp-usage-pill')].map((button) => button.getAttribute('aria-label') ?? button.className), + slot: slot ? box(slot) : null, + groups: slot ? [...slot.children].map(brief) : [], + row: row ? [...row.children].map(brief) : [], + tools: [...document.querySelectorAll('[data-bc-tool]')].map((tool) => ({ ...brief(tool), connected: tool.isConnected, display: getComputedStyle(tool).display })), exportSlug: exportSource.slug() }, session: session.snapshot(), diff --git a/ai/chatgpt/src/header-tools.ts b/ai/chatgpt/src/header-tools.ts index 65f1272..94f52ef 100644 --- a/ai/chatgpt/src/header-tools.ts +++ b/ai/chatgpt/src/header-tools.ts @@ -4,7 +4,7 @@ const ORDER = ['settings', 'usage', 'export'] as const export type ToolId = (typeof ORDER)[number] -const toolRow = (): HTMLElement | null => { +export const toolRow = (): HTMLElement | null => { const slot = findHeaderSlot() return slot?.querySelector('.contents > div') ?? slot } From 2753eee505a18a67c822645e2a34f0e927a52fb5 Mon Sep 17 00:00:00 2001 From: TheNolle Date: Tue, 10 Nov 2026 11:47:09 +0100 Subject: [PATCH 19/19] release(chatgpt): 1.0.0 --- ai/chatgpt/CHANGELOG.md | 2 +- ai/chatgpt/README.md | 64 ++++++++-- ai/chatgpt/docs/architecture.md | 22 ++++ ai/chatgpt/docs/exporting.md | 17 +++ ai/chatgpt/docs/getting-started.md | 17 +++ ai/chatgpt/docs/troubleshooting.md | 15 +++ ai/chatgpt/docs/usage-tracking.md | 14 +++ ai/chatgpt/package.json | 2 +- ai/perplexity/docs/architecture.md | 2 +- core/ai/README.md | 21 ++-- scripts/hoist-module.mjs | 182 ----------------------------- 11 files changed, 156 insertions(+), 202 deletions(-) create mode 100644 ai/chatgpt/docs/architecture.md create mode 100644 ai/chatgpt/docs/exporting.md create mode 100644 ai/chatgpt/docs/getting-started.md create mode 100644 ai/chatgpt/docs/troubleshooting.md create mode 100644 ai/chatgpt/docs/usage-tracking.md delete mode 100644 scripts/hoist-module.mjs diff --git a/ai/chatgpt/CHANGELOG.md b/ai/chatgpt/CHANGELOG.md index 06c219d..94cb540 100644 --- a/ai/chatgpt/CHANGELOG.md +++ b/ai/chatgpt/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## [0.1.0] - 2026-11-10 +## [1.0.0] - 2026-11-10 - Exporter built from the conversation view (Markdown, text, Word, PDF, JSON) and update checker. - Batch Runner, Selection Toolbar (Ask, Explain, Summarize, Fact-check, Quote) and Max Width. diff --git a/ai/chatgpt/README.md b/ai/chatgpt/README.md index e298a25..def4524 100644 --- a/ai/chatgpt/README.md +++ b/ai/chatgpt/README.md @@ -1,22 +1,70 @@ # Better ChatGPT -A modular userscript for chatgpt.com. It is in early development: version 0.1.0 detects the composer and header and tracks generation, model, plan and limits from the live network stream. +A modular userscript that adds the missing parts of ChatGPT: limits at a glance, better code blocks, long-message handling, a prompt library, batch runs and real exports. + +[Changelog](CHANGELOG.md) · [Report a bug](https://github.com/thenolle/userscripts/issues/new?template=bug_report.yml) ## Install -Install [Violentmonkey](https://violentmonkey.github.io/) or [Tampermonkey](https://www.tampermonkey.net/), then open the install link from the project website. +1. Install [Violentmonkey](https://violentmonkey.github.io/) or [Tampermonkey](https://www.tampermonkey.net/). +2. Open the **Install** link on the project website and confirm. +3. Open chatgpt.com. The settings button sits in the header next to ChatGPT's own buttons. + +Updates arrive automatically. The script also checks on its own and offers to update. + +## Features + +| Feature | What you get | +| ----------------- | ---------------------------------------------------------------------------------------------------- | +| Usage Status | Remaining reasoning, upload, image and research limits with reset times, your plan, low/empty alerts | +| Code Block Pro | 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 | +| Max Width | Full-width conversations, optional sidebar removal | +| Update Checker | Checks on load and every few minutes, tells you once per version | + +## Shortcuts + +| Action | Default | +| --------------- | --------------------------- | +| Command palette | Alt + Shift + P | +| Prompt library | Alt + Shift + L | +| Recall | Alt + Shift + H | +| Send message | Ctrl + Enter or Cmd + Enter | + +All of them can be changed from the settings dialog. + +## Privacy + +No analytics and no server of its own. The script reads ChatGPT's own responses in your session (for limits and the model in use) and talks to `raw.githubusercontent.com` for update checks and community prompts. Drafts, prompts and settings stay in your userscript manager's storage. -## Diagnostics +## Troubleshooting -Open the browser console on chatgpt.com and run `betterChatgptDump()` to print the detected layout and the live session state. +- **A button is missing:** open the settings dialog and check the module is on. In the browser console, `betterChatgptDump()` prints what the script found on the page; attach it to a bug report. +- **Export says no messages found:** ChatGPT changed its layout. Run `betterChatgptDump()` and attach it. +- **Limits look empty:** they come from ChatGPT's own responses and appear after the page loads or a message is sent. -## Usage +## Built on the shared packages -- Figures come from ChatGPT's own responses and update on page load and after each message. +Better ChatGPT is built on [`@nolly/core`](../../core/README.md) and [`@nolly/ai`](../../core/ai/README.md). Both are bundled into `better-chatgpt.user.js` at build time. Only what is specific to ChatGPT lives here: selectors, the network observer, limits, the exporter source and the header placement. -## Built on the shared core +## Development -Better ChatGPT is built on [`@nolly/core`](../../core/README.md) and [`@nolly/ai`](../../core/ai/README.md), and is bundled into one file at build time. +```bash +bun install # at the repository root +cd ai/chatgpt +bun run dev # unminified, rebuilds on change +bun run typecheck +bun run build # minified userscript in dist/ +``` ## License diff --git a/ai/chatgpt/docs/architecture.md b/ai/chatgpt/docs/architecture.md new file mode 100644 index 0000000..ec118a2 --- /dev/null +++ b/ai/chatgpt/docs/architecture.md @@ -0,0 +1,22 @@ +--- +title: Architecture +description: How Better ChatGPT is built on the shared packages. +section: Reference +order: 900 +--- + +# Architecture + +Better ChatGPT is a thin layer on top of two shared packages, both bundled into the final `.user.js`. + +- **`@nolly/core`** is the runtime: features, storage, logging, DOM helpers and the build. +- **`@nolly/ai`** holds everything that is not specific to one site: the composer, prompt and generation handling, the UI kit and the features themselves. A site fills in a small registry once at startup. + +What stays in this folder: + +- selectors and the page locators (message box, header, messages); +- the network observer that reads limits, the model in use and when an answer starts and ends; +- the exporter source, which converts the conversation view to Markdown; +- the usage feature and the header placement. + +The script starts only after the page has loaded and the message box has rendered, so it never touches the page while ChatGPT is still starting up. diff --git a/ai/chatgpt/docs/exporting.md b/ai/chatgpt/docs/exporting.md new file mode 100644 index 0000000..18235ee --- /dev/null +++ b/ai/chatgpt/docs/exporting.md @@ -0,0 +1,17 @@ +--- +title: Exporting a conversation +description: Markdown, text, Word, PDF and JSON. +section: Guides +order: 30 +--- + +# Exporting a conversation + +Open a conversation and click the download icon in the header. Pick a format: + +- **Markdown** keeps headings, lists, tables and code blocks with their language. +- **Plain text** strips the formatting. +- **Word** and **PDF** are generated in your browser from the Markdown. +- **JSON** lists each message with its role and Markdown. + +The export is built from what is on the page, so scroll to load a very long conversation first. diff --git a/ai/chatgpt/docs/getting-started.md b/ai/chatgpt/docs/getting-started.md new file mode 100644 index 0000000..09941c6 --- /dev/null +++ b/ai/chatgpt/docs/getting-started.md @@ -0,0 +1,17 @@ +--- +title: Getting started +description: Install Better ChatGPT and find your way around. +section: Guides +order: 10 +--- + +# Getting started + +Install a userscript manager, then the script, and open chatgpt.com. After the page has loaded you will see: + +- **Settings** (sliders icon) in the header: turn modules on or off and open each module's own settings. +- **Usage** pill: your remaining reasoning messages. Hover for every limit, click for details. +- **Download** icon inside a conversation: exports it. +- Extra buttons next to the message box for big messages, prompts, batches, queue and recall. + +Press Alt + Shift + P at any time to search every action. diff --git a/ai/chatgpt/docs/troubleshooting.md b/ai/chatgpt/docs/troubleshooting.md new file mode 100644 index 0000000..13d5cf0 --- /dev/null +++ b/ai/chatgpt/docs/troubleshooting.md @@ -0,0 +1,15 @@ +--- +title: Troubleshooting +description: Fixes for missing buttons, empty limits and failed exports. +section: Reference +order: 800 +--- + +# Troubleshooting + +Open the browser console on chatgpt.com and run `betterChatgptDump()`. It prints what the script found: the composer, the header, your messages and the current limits. Attach it to any bug report. + +- **No header buttons:** the script waits for the page and the message box to finish loading. Wait a few seconds, or check the module is on in settings. +- **Export finds no messages:** ChatGPT changed how it marks messages. The dump shows `page.turns`; if both counts are 0 while messages are on screen, report it. +- **Limits are empty:** send a message or reload the page. +- **Update check failed (404):** the first release has not been published yet. diff --git a/ai/chatgpt/docs/usage-tracking.md b/ai/chatgpt/docs/usage-tracking.md new file mode 100644 index 0000000..7b5e036 --- /dev/null +++ b/ai/chatgpt/docs/usage-tracking.md @@ -0,0 +1,14 @@ +--- +title: Usage tracking +description: Where the numbers come from and when they refresh. +section: Guides +order: 20 +--- + +# Usage tracking + +ChatGPT reports your remaining limits itself. Better ChatGPT reads those responses in your session: file uploads, pasted text turned into files, image generation, deep research and reasoning messages, each with its reset time. It also shows your plan and the rolling window. + +The numbers refresh when ChatGPT refreshes them: when you load a page and after each message. There are no totals or refill estimates, because ChatGPT only reports what is left. + +Alerts appear when a limit runs out, runs low, or becomes available again. Choose which limit the header pill shows from the settings dialog. diff --git a/ai/chatgpt/package.json b/ai/chatgpt/package.json index 250ade5..8c7de1f 100644 --- a/ai/chatgpt/package.json +++ b/ai/chatgpt/package.json @@ -1,6 +1,6 @@ { "name": "@nolly/ai-chatgpt", - "version": "0.1.0", + "version": "1.0.0", "private": true, "type": "module", "license": "PolyForm-Strict-1.0.0", diff --git a/ai/perplexity/docs/architecture.md b/ai/perplexity/docs/architecture.md index dc811c8..2d09542 100644 --- a/ai/perplexity/docs/architecture.md +++ b/ai/perplexity/docs/architecture.md @@ -18,7 +18,7 @@ Better Perplexity is a thin layer on top of `@nolly/core`, a small library share ## What comes from @nolly/ai -`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The dialogs, toasts, tooltips, controls, icons and settings dialog also live there; Better Perplexity configures them once in `main.ts`. Features that need storage, logging or the composer read them from a registry the platform fills once at startup. +`@nolly/ai` holds the code Better Perplexity shares with the other AI-chat scripts: composer reading and writing, synthetic keys, generation detection and the response observer. Each piece takes a small adapter, so Perplexity supplies only its own selectors. The common UI kit lives here too: the dialogs, toasts, tooltips, controls, icons and settings dialog are all shared across the userscripts, and Better Perplexity configures them once in `main.ts`. Features that need storage, logging or the composer do not reach into global singletons; instead they read them from a runtime registry the platform fills once at startup. That registry is the bridge between the shared AI layer and the script-specific selectors, storage keys and root DOM marker. ## What stays in Better Perplexity diff --git a/core/ai/README.md b/core/ai/README.md index e95715c..e905ebb 100644 --- a/core/ai/README.md +++ b/core/ai/README.md @@ -4,14 +4,17 @@ Platform-agnostic building blocks for AI-chat userscripts such as Better Perplex ## What you get -- A `PlatformAdapter` contract that a site implements once. -- Composer kits: find the input, write text, send, attach files; a prompt sender built on them. -- Generation detection and a wait-for-answer helper. +- A platform registry: `configureUi` and `configurePlatform` are called once at startup with the site's storage, logger, composer, generation detection, thread rule, prompt library URL, export source and release information. +- Composer and generation kits: find the input, write text, send, attach files, wait for an answer. - A streaming response observer and an incremental Server-Sent Events parser. -- Placeholders, token estimates, selection memory, clipboard and file download helpers. -- A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. Call `configureUi` once before using it. -- Feature modules that need only an adapter: Enter as Newline, Draft Guard, Message Splitter, Batch Runner, Selection Toolbar, Max Width, Code Blocks, Exporter (Markdown, text, Word, PDF, JSON), and Update checker. -- Exports can be sourced from conversation messages or selected text. -- Prompt Library, Command Palette, Prompt Queue and Recall. +- A UI kit: dialogs, toasts, tooltips, controls, icons, the settings dialog and the composer button. +- Features that need only the registry: Enter as Newline, Draft Guard, Message Splitter, Prompt Library, Command Palette, Message Queue, Recall, Batch Runner, Selection Toolbar, Max Width, Code Block Pro, Exporter and Update Checker. -Platforms register once with `configurePlatform` and `configureUi`. +This is a library. It is bundled into each userscript and is not installed on its own. + +## Adding a platform + +1. Create `ai/` with `bun scripts/new-userscript.ts "" ai`. +2. Write the site's locators and a composer adapter. +3. Call `configureUi` and `configurePlatform`, then register the features you want. +4. Provide an export source if you want the exporter, and a `codeBlockRoot` hook if you want Code Block Pro. diff --git a/scripts/hoist-module.mjs b/scripts/hoist-module.mjs deleted file mode 100644 index 432e3de..0000000 --- a/scripts/hoist-module.mjs +++ /dev/null @@ -1,182 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs' -import { dirname, join, relative, resolve, sep } from 'node:path' - -const ROOT = process.cwd() -const SOURCE = resolve(ROOT, 'ai/perplexity/src/modules') -const SRC = resolve(ROOT, 'core/ai/src') -const FEATURES = join(SRC, 'features') -const PLATFORM_NAMES = new Set(['storage', 'logger', 'composer', 'generation', 'dispatch']) -const IMPORT = /\b(import|export)\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'/g -const EXPORT_DECL = /^export\s+(?:declare\s+)?(?:async\s+)?(?:const|let|function|class|interface|type|enum)\s+(\w+)/gm -const EXPORT_DESTRUCTURE = /^export\s+const\s+\{([^}]*)\}\s*=/gm -const EXPORT_LIST = /^export\s+(?:type\s+)?\{([^}]*)\}/gm - -const modules = process.argv.slice(2) -if (!modules.length) { - console.error('Usage: bun scripts/hoist-module.mjs [...]') - process.exit(1) -} - -const walk = (dir) => readdirSync(dir, { withFileTypes: true }).flatMap((entry) => (entry.isDirectory() ? walk(join(dir, entry.name)) : [join(dir, entry.name)])) -const posix = (path) => path.split(sep).join('/') -const names = (list) => list.split(',').map((name) => name.trim()).filter(Boolean) -const bare = (name) => name.replace(/^type\s+/, '') - -const move = (from, to) => { - mkdirSync(dirname(to), { recursive: true }) - try { - execFileSync('git', ['mv', from, to], { stdio: 'pipe' }) - } catch { - renameSync(from, to) - } -} - -const scanExports = () => { - const map = new Map() - for (const file of walk(SRC).filter((entry) => entry.endsWith('.ts') && !entry.endsWith(`${sep}index.ts`))) { - const source = readFileSync(file, 'utf8') - const found = [ - ...[...source.matchAll(EXPORT_DECL)].map((match) => match[1]), - ...[...source.matchAll(EXPORT_DESTRUCTURE)].flatMap((match) => names(match[1]).map((name) => name.split(':').pop().trim())), - ...[...source.matchAll(EXPORT_LIST)].flatMap((match) => names(match[1]).map((name) => bare(name).split(/\s+as\s+/).pop())) - ] - for (const name of found) if (name && !map.has(name)) map.set(name, file) - } - return map -} - -const specifierTo = (fromFile, toFile) => { - const path = posix(relative(dirname(fromFile), toFile)).replace(/\.ts$/, '').replace(/\/index$/, '') - return path.startsWith('.') ? path : `./${path}` -} - -const issues = [] -const exportMap = scanExports() - -const rewriteImports = (source, file) => - source.replace(IMPORT, (match, keyword, typeOnly, list, spec) => { - const core = /^\.\.\/\.\.\/core\/([\w-]+)$/.exec(spec)?.[1] - if (core && PLATFORM_NAMES.has(core)) return `${keyword}${typeOnly ? ' type' : ''} {${list}} from '${specifierTo(file, join(SRC, 'platform.ts'))}'` - if (core === 'dom') return `${keyword}${typeOnly ? ' type' : ''} {${list}} from '${specifierTo(file, join(SRC, 'ui/config.ts'))}'` - if (spec !== '@nolly/ai') return match - const groups = new Map() - for (const entry of names(list)) { - const target = exportMap.get(bare(entry)) - if (!target) { - issues.push(`${relative(ROOT, file)}: '${bare(entry)}' is not exported by @nolly/ai`) - continue - } - groups.set(target, [...(groups.get(target) ?? []), entry]) - } - return [...groups].map(([target, entries]) => `${keyword}${typeOnly ? ' type' : ''} { ${entries.join(', ')} } from '${specifierTo(file, target)}'`).join('\n') - }) - -const rewriteLiterals = (source) => { - let needsConfig = false - const declared = [] - const lines = source.split('\n').map((entry) => { - const match = /^(export\s+)?const\s+(\w+)\s*=\s*'better-perplexity([^']*)'[ \t]*(\r?)$/.exec(entry) - if (!match) return entry - needsConfig = true - declared.push(match[2]) - return `${match[1] ?? ''}const ${match[2]} = (): string => \`\${uiConfig().id}${match[3]}\`${match[4]}` - }) - let text = lines.join('\n') - for (const name of declared) { - const declaration = new RegExp(`^(export\\s+)?const\\s+${name}\\s*=\\s*\\(\\)`) - text = text.split('\n').map((entry) => (declaration.test(entry) ? entry : entry.replace(new RegExp(`\\b${name}\\b`, 'g'), `${name}()`))).join('\n') - } - text = text.replace(/'better-perplexity([^']*)'/g, (_match, suffix) => { - needsConfig = true - return suffix ? `\`\${uiConfig().id}${suffix}\`` : 'uiConfig().id' - }) - return { text, needsConfig } -} - -const mergeImports = (source) => { - const groups = new Map() - const key = (typeOnly, spec) => `${typeOnly ? 'type' : 'value'}|${spec}` - for (const match of source.matchAll(/^import\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'\n?/gm)) { - const id = key(Boolean(match[1]), match[3]) - const group = groups.get(id) ?? { names: [], count: 0 } - for (const name of names(match[2])) if (!group.names.includes(name)) group.names.push(name) - group.count++ - groups.set(id, group) - } - const seen = new Set() - return source.replace(/^import\s+(type\s+)?\{([^}]*)\}\s+from\s+'([^']+)'\n?/gm, (match, typeOnly, _list, spec) => { - const id = key(Boolean(typeOnly), spec) - const group = groups.get(id) - if (!group || group.count < 2) return match - if (seen.has(id)) return '' - seen.add(id) - return `import ${typeOnly ? 'type ' : ''}{ ${group.names.join(', ')} } from '${spec}'\n` - }) -} - -const addConfigImport = (source, file) => { - if (/\buiConfig\b[^\n]*from\s+'[^']*ui\/config'/.test(source)) return source - const line = `import { uiConfig } from '${specifierTo(file, join(SRC, 'ui/config.ts'))}'\n` - const imports = [...source.matchAll(/^import[^\n]*\n/gm)] - const last = imports.at(-1) - if (!last) return line + source - const end = last.index + last[0].length - return source.slice(0, end) + line + source.slice(end) -} - -const checkResolution = (source, file) => { - for (const match of source.matchAll(IMPORT)) { - const spec = match[4] - if (!spec.startsWith('.')) continue - const base = resolve(dirname(file), spec) - if (!existsSync(`${base}.ts`) && !existsSync(join(base, 'index.ts'))) issues.push(`${relative(ROOT, file)}: cannot resolve '${spec}'`) - } - source.split('\n').forEach((line, index) => { - if (/perplexity/i.test(line)) issues.push(`${relative(ROOT, file)}:${index + 1}: still mentions Perplexity: ${line.trim().slice(0, 100)}`) - }) -} - -const classRenames = [] -for (const name of modules) { - const from = join(SOURCE, name) - const to = join(FEATURES, name) - if (!existsSync(from)) { - console.error(`Missing ${relative(ROOT, from)}`) - process.exit(1) - } - move(from, to) - for (const file of walk(to).filter((entry) => entry.endsWith('.ts'))) { - let source = readFileSync(file, 'utf8') - source = rewriteImports(source, file) - const literals = rewriteLiterals(source) - source = literals.text - if (literals.needsConfig) source = addConfigImport(source, file) - source = mergeImports(source) - if (file === join(to, 'index.ts')) { - const match = /export class (\w+)Module extends Feature/.exec(source) - if (match) { - source = source.replace(new RegExp(`\\b${match[1]}Module\\b`, 'g'), `${match[1]}Feature`) - classRenames.push({ name, className: `${match[1]}Feature` }) - } - } - writeFileSync(file, source) - } -} - -for (const name of modules) for (const file of walk(join(FEATURES, name)).filter((entry) => entry.endsWith('.ts'))) checkResolution(readFileSync(file, 'utf8'), file) - -const barrel = join(FEATURES, 'index.ts') -let barrelText = existsSync(barrel) ? readFileSync(barrel, 'utf8') : '' -for (const { name, className } of classRenames) { - const line = `export { ${className} } from './${name}'\n` - if (!barrelText.includes(line)) barrelText += line -} -writeFileSync(barrel, barrelText) - -console.log(`Hoisted: ${modules.join(', ')}`) -console.log(classRenames.map(({ className }) => ` ${className}`).join('\n')) -if (issues.length) { - console.log('\nNeeds attention:') - for (const issue of issues) console.log(` ${issue}`) -}