diff --git a/migrations/0002_ai_generate.sql b/migrations/0002_ai_generate.sql new file mode 100644 index 0000000..203faba --- /dev/null +++ b/migrations/0002_ai_generate.sql @@ -0,0 +1,31 @@ +-- POST /api/generate (worker/generate.ts, worker/ai-budget.ts): the AI pipeline builder's +-- daily spend, per-IP daily counts and answer cache. Pruned daily (worker/index.ts, scheduled): +-- ip rows after 2 days, spend rows after 92 days, cached answers after 30 days. + +-- One row per UTC day. reserved_micro is in micro-dollars: each call reserves its worst case +-- here before it runs and is corrected to its actual cost afterwards. +CREATE TABLE ai_spend ( + day TEXT PRIMARY KEY, + reserved_micro INTEGER NOT NULL DEFAULT 0, + calls INTEGER NOT NULL DEFAULT 0 +); + +-- Model calls per client per UTC day. ip_hash is an HMAC (secret AI_IP_SALT) of the day and the +-- client's address bucket, so the address is never stored and hashes do not link across days. +CREATE TABLE ai_ip_daily ( + day TEXT NOT NULL, + ip_hash TEXT NOT NULL, + count INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (day, ip_hash) +); + +-- Generated steps by a SHA-256 of the normalised description, model id and catalog version; +-- the description itself is not stored. created_at is Unix milliseconds. +CREATE TABLE ai_answer_cache ( + key TEXT PRIMARY KEY, + steps TEXT NOT NULL, + notes TEXT NOT NULL DEFAULT '', + created_at INTEGER NOT NULL +); + +CREATE INDEX ai_answer_cache_created ON ai_answer_cache (created_at); diff --git a/package-lock.json b/package-lock.json index 2049416..c1863b7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "1.18.2", "license": "MIT", "dependencies": { + "@anthropic-ai/sdk": "^1.14.0", "@codemirror/lang-html": "^6.4.12", "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", @@ -107,6 +108,28 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/@anthropic-ai/sdk": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.14.0.tgz", + "integrity": "sha512-nADYXUd5fn9Zgw2nHi1iKyt/kb1UUt1cN3RbdxEI6XjTDTxbx4LLG4GnMrxWyS9GgXQllFOyAKSiFM3joDNK9A==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.1", + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, "node_modules/@asamuzakjp/css-color": { "version": "4.0.5", "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.0.5.tgz", @@ -2370,6 +2393,15 @@ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", "license": "MIT" }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/@oxc-project/types": { "version": "0.155.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", @@ -2759,6 +2791,12 @@ "dev": true, "license": "CC0-1.0" }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, "node_modules/@tailwindcss/node": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.3.tgz", @@ -5135,6 +5173,12 @@ "dev": true, "license": "MIT" }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, "node_modules/fast-uri": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", @@ -5822,6 +5866,19 @@ "dev": true, "license": "MIT" }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/json-schema-traverse": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", @@ -7427,6 +7484,16 @@ "sql-formatter": "bin/sql-formatter-cli.cjs" } }, + "node_modules/standardwebhooks": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.3.0.tgz", + "integrity": "sha512-5W9skHjqAm2dlA9wWvglTP+oX47JX4lFXVk1aJV7+TG1snvTR4QXaVgPscEzvOw9GRreeavMwbqEeL+MGhZHCg==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -7636,6 +7703,12 @@ "url": "https://github.com/sponsors/wooorm" } }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, "node_modules/ts-api-utils": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", diff --git a/package.json b/package.json index 9f3a8a6..9335070 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "release": "vite-node scripts/release.ts" }, "dependencies": { + "@anthropic-ai/sdk": "^1.14.0", "@codemirror/lang-html": "^6.4.12", "@codemirror/lang-javascript": "^6.2.5", "@codemirror/lang-json": "^6.0.2", diff --git a/src/app/commands/commands.test.ts b/src/app/commands/commands.test.ts index 5500bd8..5c7f9c3 100644 --- a/src/app/commands/commands.test.ts +++ b/src/app/commands/commands.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' import { commands, commandById, listShortcuts, TOOL_COMMAND_EVENT, EVENT_MAGIC, EVENT_OPEN_SHARE, - EVENT_OPEN_LIBRARY, EVENT_OPEN_PRESETS, EVENT_TOGGLE_THEME, EVENT_OPEN_SHORTCUTS, + EVENT_OPEN_LIBRARY, EVENT_OPEN_PRESETS, EVENT_OPEN_GENERATE, EVENT_TOGGLE_THEME, EVENT_OPEN_SHORTCUTS, attachToolBridge, hasToolBridge, queueToolCommand, type ToolCommandDetail, } from './commands' @@ -63,6 +63,7 @@ describe('commands', () => { ['share', EVENT_OPEN_SHARE], ['library', EVENT_OPEN_LIBRARY], ['presets', EVENT_OPEN_PRESETS], + ['generate', EVENT_OPEN_GENERATE], ] it.each(TOOL_DIALOGS)('%s fires the %s window event straight away while an editor is on screen', (id, eventName) => { diff --git a/src/app/commands/commands.ts b/src/app/commands/commands.ts index 86f0d92..e4ea243 100644 --- a/src/app/commands/commands.ts +++ b/src/app/commands/commands.ts @@ -21,6 +21,8 @@ export const EVENT_MAGIC = 'sub:magic' export const EVENT_OPEN_SHARE = 'sub:open-share' export const EVENT_OPEN_LIBRARY = 'sub:open-library' export const EVENT_OPEN_PRESETS = 'sub:open-presets' +/** Opens the describe dialog (the AI pipeline builder, `src/app/generate/`). */ +export const EVENT_OPEN_GENERATE = 'sub:open-generate' export const EVENT_TOGGLE_THEME = 'sub:toggle-theme' export const EVENT_OPEN_SHORTCUTS = 'sub:open-shortcuts' export const EVENT_OPEN_PALETTE = 'sub:open-palette' @@ -142,6 +144,7 @@ export const commands: Command[] = [ { id: 'share', title: 'Share', group: 'Pipeline', keywords: ['share', 'link', 'url'], run: fireInTool(EVENT_OPEN_SHARE) }, { id: 'library', title: 'Library', group: 'Pipeline', keywords: ['library', 'save', 'load', 'pipelines'], run: fireInTool(EVENT_OPEN_LIBRARY) }, { id: 'presets', title: 'Start from a preset', group: 'Pipeline', keywords: ['presets', 'recipes', 'examples', 'templates', 'gallery'], run: fireInTool(EVENT_OPEN_PRESETS) }, + { id: 'generate', title: 'Describe a pipeline (AI)', group: 'Pipeline', keywords: ['ai', 'describe', 'generate', 'build', 'prompt', 'natural language'], run: fireInTool(EVENT_OPEN_GENERATE) }, { id: 'toggle-theme', title: 'Toggle theme', group: 'View', keywords: ['theme', 'dark', 'light', 'mode'], run: fire(EVENT_TOGGLE_THEME) }, { id: 'shortcuts', title: 'Keyboard shortcuts', group: 'Help', keywords: ['shortcuts', 'help', 'keys'], run: fire(EVENT_OPEN_SHORTCUTS) }, { id: 'goto-tool', title: 'Go to Tool', group: 'Navigate', keywords: ['tool', 'home', 'pipeline'], run: goToTool }, diff --git a/src/app/generate/GenerateButton.tsx b/src/app/generate/GenerateButton.tsx new file mode 100644 index 0000000..4ef41fb --- /dev/null +++ b/src/app/generate/GenerateButton.tsx @@ -0,0 +1,51 @@ +import React, { Suspense, lazy, useEffect, useRef, useState } from 'react' +import { Sparkles } from 'lucide-react' +import { EVENT_OPEN_GENERATE } from '@/app/commands/commands' +import { useT } from '@/app/i18n/useT' +import Dialog from '@/app/library/Dialog' +import type { GenerateDialogProps } from './GenerateDialog' + +/** What the dialog shows when its chunk cannot be fetched (offline, or a stale tab after a deploy). */ +function GenerateUnavailable({ onClose, returnFocus }: GenerateDialogProps) { + const { t } = useT() + return ( + +

{t('generate.error.offline')}

+
+ ) +} + +// Lazy, so the dialog stays out of the editor's entry chunk until someone opens it. +const GenerateDialog = lazy(() => + import('./GenerateDialog').catch(() => ({ default: GenerateUnavailable })), +) + +/** + * Opens the describe dialog (REQ-027) from beside the step list. Also opens on the + * `sub:open-generate` window event, which the command palette fires. + */ +export default function GenerateButton({ className = 'btn h-[30px] px-2.5' }: { className?: string }) { + const { t } = useT() + const [open, setOpen] = useState(false) + const buttonRef = useRef(null) + + useEffect(() => { + const onOpen = () => setOpen(true) + window.addEventListener(EVENT_OPEN_GENERATE, onOpen) + return () => window.removeEventListener(EVENT_OPEN_GENERATE, onOpen) + }, []) + + return ( + <> + + {open && ( + + setOpen(false)} returnFocus={buttonRef} /> + + )} + + ) +} diff --git a/src/app/generate/GenerateDialog.test.tsx b/src/app/generate/GenerateDialog.test.tsx new file mode 100644 index 0000000..8e32d81 --- /dev/null +++ b/src/app/generate/GenerateDialog.test.tsx @@ -0,0 +1,159 @@ +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { ToolProvider, useTool } from '@/app/ToolContext' +import type { PipelineStep } from '@/types/utility' +import GenerateDialog from './GenerateDialog' +import GenerateButton from './GenerateButton' +import { EVENT_OPEN_GENERATE } from '@/app/commands/commands' + +const EXISTING: PipelineStep[] = [{ id: 'old', utilityId: 'url_decode', enabled: true, params: {} }] + +const OK = { + steps: [ + { id: 's1', utilityId: 'base64_decode', enabled: true, params: {} }, + { id: 's2', utilityId: 'json_pretty', enabled: true, params: { indent: 4 } }, + ], + why: ['turns the base64 back into text', 'indents the JSON'], + notes: 'Left out sort keys (unknown utility).', + cached: false, +} + +let fetchMock: ReturnType +const answer = (status: number, body: unknown, headers: Record = {}) => { + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(body), { + status, headers: { 'content-type': 'application/json; charset=utf-8', ...headers }, + })) +} + +beforeEach(() => { + fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) +}) +afterEach(() => { vi.unstubAllGlobals() }) + +function Probe() { + const { state, dispatch } = useTool() + return ( + <> +
{state.steps.map(s => ('utilityId' in s ? s.utilityId : s.type)).join(',')}
+ + + ) +} + +function Harness({ steps = EXISTING, onClose = () => {} }: { steps?: PipelineStep[]; onClose?: () => void }) { + return ( + + + + + ) +} + +const ids = () => screen.getByTestId('ids').textContent + +async function describeAndSubmit(text = 'decode base64 then pretty-print') { + const user = userEvent.setup() + await user.type(screen.getByLabelText('What should the pipeline do?'), text) + await user.click(screen.getByRole('button', { name: 'Build steps' })) + return user +} + +describe('GenerateDialog', () => { + it('sends only the description and lists each step with its reason and the notes', async () => { + answer(200, OK) + render() + await describeAndSubmit() + expect(await screen.findByText('base64 decode')).toBeInTheDocument() + expect(screen.getByText(/turns the base64 back into text/)).toBeInTheDocument() + expect(screen.getByText(/indents the JSON/)).toBeInTheDocument() + expect(screen.getByText('Left out sort keys (unknown utility).')).toBeInTheDocument() + expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ description: 'decode base64 then pretty-print' }) + }) + + it('replaces the pipeline in one undoable step and closes', async () => { + answer(200, OK) + const onClose = vi.fn() + render() + const user = await describeAndSubmit() + await user.click(await screen.findByRole('button', { name: 'Replace pipeline' })) + expect(ids()).toBe('base64_decode,json_pretty') + expect(onClose).toHaveBeenCalled() + await user.click(screen.getByRole('button', { name: 'probe undo' })) + expect(ids()).toBe('url_decode') + }) + + it('adds the steps to the end in one undoable step', async () => { + answer(200, OK) + render() + const user = await describeAndSubmit() + await user.click(await screen.findByRole('button', { name: 'Add to the end' })) + expect(ids()).toBe('url_decode,base64_decode,json_pretty') + await user.click(screen.getByRole('button', { name: 'probe undo' })) + expect(ids()).toBe('url_decode') + }) + + it('offers only "Use these steps" when the pipeline is empty', async () => { + answer(200, OK) + render() + const user = await describeAndSubmit() + const use = await screen.findByRole('button', { name: 'Use these steps' }) + expect(screen.queryByRole('button', { name: 'Add to the end' })).toBeNull() + await user.click(use) + expect(ids()).toBe('base64_decode,json_pretty') + }) + + it.each([ + [503, { code: 'ai_off' }, {}, /not switched on/, true], + [503, { code: 'ai_budget' }, {}, /used up today’s budget/, true], + [429, { code: 'ai_rate' }, { 'retry-after': '20' }, /Try again in 20 s/, true], + [429, { code: 'ai_rate' }, { 'retry-after': '43200' }, /all the AI pipelines for today/, true], + [400, { code: 'ai_invalid' }, {}, /at most 500 characters/, false], + [422, { code: 'ai_unusable', notes: 'Left out custom js.' }, {}, /No usable steps/, true], + [502, { code: 'ai_upstream' }, {}, /could not be reached. Try again in a minute/, true], + ])('shows its own message for %s %j', async (status, body, headers, message, fallback) => { + answer(status, { error: 'server text', ...body }, headers) + render() + await describeAndSubmit() + const alert = await screen.findByRole('alert') + expect(alert).toHaveTextContent(message) + if ('notes' in body) expect(alert).toHaveTextContent('Left out custom js.') + const search = screen.queryByRole('link', { name: 'search the utilities' }) + if (fallback) { + expect(search).toHaveAttribute('href', '/utilities/') + expect(screen.getByRole('link', { name: /MCP server/ })).toHaveAttribute('href', '/integrations/#mcp-server-for-ai-agents') + } else { + expect(search).toBeNull() + } + expect(ids()).toBe('url_decode') + }) + + it('says it could not reach the builder when there is no Worker (a dev server page)', async () => { + fetchMock.mockResolvedValueOnce(new Response('', { status: 200, headers: { 'content-type': 'text/html' } })) + render() + await describeAndSubmit() + expect(await screen.findByRole('alert')).toHaveTextContent(/could not be reached. Check your connection/) + }) + + it('keeps the button off for an empty description and caps it at 500 characters', () => { + render() + expect(screen.getByRole('button', { name: 'Build steps' })).toBeDisabled() + expect(screen.getByLabelText('What should the pipeline do?')).toHaveAttribute('maxLength', '500') + expect(screen.getByRole('link', { name: 'What is kept' })).toHaveAttribute('href', '/privacy/#features-that-contact-our-server') + }) +}) + +describe('GenerateButton', () => { + it('opens the dialog on click and on the command palette event', async () => { + const user = userEvent.setup() + render() + await user.click(screen.getByRole('button', { name: /Describe it/ })) + expect(await screen.findByRole('dialog', { name: 'Describe a pipeline' })).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'close dialog' })) + expect(screen.queryByRole('dialog')).toBeNull() + window.dispatchEvent(new CustomEvent(EVENT_OPEN_GENERATE)) + expect(await screen.findByRole('dialog', { name: 'Describe a pipeline' })).toBeInTheDocument() + }) +}) diff --git a/src/app/generate/GenerateDialog.tsx b/src/app/generate/GenerateDialog.tsx new file mode 100644 index 0000000..b1e2f1b --- /dev/null +++ b/src/app/generate/GenerateDialog.tsx @@ -0,0 +1,166 @@ +import React, { useEffect, useId, useRef, useState } from 'react' +import { cloneWithNewIds, isUtilityStep } from '@/core/steps' +import { useTool } from '@/app/ToolContext' +import { registry } from '@/app/registry' +import { useT } from '@/app/i18n/useT' +import Dialog from '@/app/library/Dialog' +import { generatePipeline, MAX_DESCRIPTION_CHARS, type GenerateResult } from './generate' + +export interface GenerateDialogProps { + onClose: () => void + /** Focus target on close when the dialog was not opened from a focused control. */ + returnFocus?: React.RefObject +} + +/** A daily-count refusal waits until midnight UTC; a burst refusal waits seconds. */ +const TODAY_WAIT_S = 15 * 60 + +const LINK = 'underline underline-offset-[3px] hover:text-fg' + +/** + * The describe dialog (REQ-027): the visitor writes what the pipeline should do, the + * Worker's AI builder answers with steps and a reason for each, and the visitor either + * replaces the pipeline or adds them to the end. Either is one reducer action, so one + * undo puts the previous pipeline back. + */ +export default function GenerateDialog({ onClose, returnFocus }: GenerateDialogProps) { + const { state, dispatch } = useTool() + const { t } = useT() + const [description, setDescription] = useState('') + const [busy, setBusy] = useState(false) + const [result, setResult] = useState(null) + const boxRef = useRef(null) + const boxId = useId() + const countId = useId() + // a reply that lands after the dialog closed must not touch anything + const abort = useRef(null) + useEffect(() => () => abort.current?.abort(), []) + + const trimmed = description.trim() + const hasPipeline = state.steps.length > 0 + + const submit = async (e?: React.FormEvent) => { + e?.preventDefault() + if (!trimmed || busy) return + abort.current?.abort() + const ctl = new AbortController() + abort.current = ctl + setBusy(true) + setResult(null) + try { + const r = await generatePipeline(trimmed, { signal: ctl.signal }) + if (!ctl.signal.aborted) setResult(r) + } catch { + // aborted: the dialog closed or a newer request replaced this one + } finally { + if (!ctl.signal.aborted) setBusy(false) + } + } + + const apply = (mode: 'replace' | 'append') => { + if (result?.status !== 'ok') return + const steps = result.steps.map(s => cloneWithNewIds(s.step)) + dispatch(mode === 'replace' ? { type: 'LOAD', steps } : { type: 'INSERT_STEPS', steps }) + onClose() + } + + const errorText = (r: Extract) => { + if (r.code === 'ai_rate') { + return r.retryAfter && r.retryAfter < TODAY_WAIT_S + ? t('generate.error.rateSoon', { seconds: r.retryAfter }) + : t('generate.error.rateToday') + } + if (r.code === 'ai_invalid') return t('generate.error.ai_invalid', { max: MAX_DESCRIPTION_CHARS }) + return t(`generate.error.${r.code}`) + } + // when the builder cannot help today, point at the ways to build it by hand + // REQ-027: whenever generation is unavailable, point to search and the MCP server. + // A description that is too long is the visitor's to fix, so it gets no links. + const offersFallback = (r: GenerateResult) => r.status === 'error' && r.code !== 'ai_invalid' + + return ( + +

+ {t('generate.intro')}{' '} + {t('generate.privacy')} +

+ +
+ +