🎬 A browser extension and desktop app that turns your clicks into step-by-step guides with annotated screenshots 📖
TypeScript browser-extensionchrome-extensiondocumentationfirefox-extensionguide-generatorlocal-firstmanifest-v3privacy-firstproductivityreactscreenshotstep-by-step-guidetutorialtypescriptworkflowwxt
feat(ai): rewrite a selected span of text from an instruction
Luis Ortizfee922d848d8
diff --git a/src/core/capture/ai/__tests__/rewrite.test.ts b/src/core/capture/ai/__tests__/rewrite.test.tsnew file mode 100644index 0000000..7abd71b--- /dev/null+++ b/src/core/capture/ai/__tests__/rewrite.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';+import { REWRITE_PRESETS } from '../prompts';+import { buildRewritePrompt, cleanRewrite } from '../rewrite';++describe('cleanRewrite', () => {+ it('trims surrounding whitespace', () => {+ expect(cleanRewrite(' Click the Submit button ')).toBe('Click the Submit button');+ });++ it('unwraps a fully quoted response', () => {+ expect(cleanRewrite('"Click the Submit button"')).toBe('Click the Submit button');+ });++ it('unwraps smart quotes', () => {+ expect(cleanRewrite('“Click the Submit button”')).toBe('Click the Submit button');+ });++ it('keeps an unmatched leading quote', () => {+ expect(cleanRewrite('"Submit" is the button label')).toBe('"Submit" is the button label');+ });++ it('keeps quotes that are internal to the text', () => {+ expect(cleanRewrite('Select the "Admin" role')).toBe('Select the "Admin" role');+ });++ it('unwraps across multiple lines', () => {+ expect(cleanRewrite('"line one\nline two"')).toBe('line one\nline two');+ });++ it('returns empty string for a blank response', () => {+ expect(cleanRewrite(' ')).toBe('');+ });+});++describe('buildRewritePrompt', () => {+ it('substitutes the selected text and the instruction', () => {+ const prompt = buildRewritePrompt('Click Save', 'Make it shorter.', 'en');+ expect(prompt).toContain('Click Save');+ expect(prompt).toContain('Make it shorter.');+ expect(prompt).not.toContain('{{text}}');+ expect(prompt).not.toContain('{{instruction}}');+ });++ it('does not interpret dollar patterns in the selected text', () => {+ const prompt = buildRewritePrompt('Enter $& in the Amount field', 'Fix grammar.', 'en');+ expect(prompt).toContain('Enter $& in the Amount field');+ });++ it('does not interpret dollar patterns in the instruction', () => {+ const prompt = buildRewritePrompt('Click Save', 'Replace $1 with $`', 'en');+ expect(prompt).toContain('Replace $1 with $`');+ });++ it('appends a language suffix for non-English locales', () => {+ expect(buildRewritePrompt('Click Save', 'Make it shorter.', 'fr')).toContain('French');+ });++ it('appends nothing for English', () => {+ expect(buildRewritePrompt('Click Save', 'Make it shorter.', 'en')).not.toContain('IMPORTANT');+ });++ it('forbids inventing UI elements', () => {+ expect(buildRewritePrompt('Click Save', 'Expand it.', 'en')).toMatch(/never introduce a UI element/i);+ });++ it('works with every preset instruction', () => {+ for (const instruction of Object.values(REWRITE_PRESETS)) {+ expect(buildRewritePrompt('Click Save', instruction, 'en')).toContain(instruction);+ }+ });+});diff --git a/src/core/capture/ai/prompts.ts b/src/core/capture/ai/prompts.tsindex 763b09a..47e4ebd 100644--- a/src/core/capture/ai/prompts.ts+++ b/src/core/capture/ai/prompts.ts@@ -30,6 +30,33 @@ Examples of good descriptions:- "Reset a locked-out user's password from the Okta admin panel. For IT support staff."- "Configure which Slack channels send desktop notifications, and set a do-not-disturb schedule."`;+export const REWRITE_PROMPT = `You are editing one span of text inside a browser workflow guide. The text describes a step a reader must perform, or summarises what the workflow accomplishes.++Selected text:+"""+{{text}}+"""++Instruction: {{instruction}}++Rules:+- Keep it imperative and describing a single action when the original does.+- Never introduce a UI element, button, page, or value that is absent from the original.+- Preserve specific names, labels, and quoted strings exactly as written.+- Match the length the instruction implies; otherwise stay close to the original length.++Return only the rewritten text. No preamble, no quotes, no explanation.`;++export const REWRITE_PRESETS = {+ shorter: 'Make it shorter and tighter without losing any required detail.',+ detail: 'Add detail that clarifies the action, using only information already present.',+ grammar: 'Fix grammar, spelling, and punctuation. Change nothing else.',+ formal: 'Make the tone more formal and professional.',+ casual: 'Make the tone more casual and conversational.',+} as const;++export type RewritePreset = keyof typeof REWRITE_PRESETS;+export const AI_LANGUAGES = [{ code: 'en', label: 'English' },{ code: 'es', label: 'Español' },diff --git a/src/core/capture/ai/rewrite.ts b/src/core/capture/ai/rewrite.tsnew file mode 100644index 0000000..6251307--- /dev/null+++ b/src/core/capture/ai/rewrite.ts@@ -0,0 +1,48 @@+import { generateText } from 'ai';+import { localStorage } from '@/lib/browser-api';+import { logger } from '@/lib/logger';+import type { RewriteSelectionResponse } from '@/lib/messaging';+import { AI_PROVIDERS } from './models';+import { getLanguageSuffix, REWRITE_PROMPT } from './prompts';+import { createModel } from './provider';++const WRAPPED_IN_QUOTES = /^["“'](.*)["”']$/s;++export function cleanRewrite(raw: string): string {+ const trimmed = raw.trim();+ const unwrapped = trimmed.match(WRAPPED_IN_QUOTES);+ return (unwrapped ? unwrapped[1] : trimmed).trim();+}++export function buildRewritePrompt(text: string, instruction: string, locale: string): string {+ return (+ REWRITE_PROMPT.replace('{{text}}', () => text).replace('{{instruction}}', () => instruction) ++ getLanguageSuffix(locale)+ );+}++export async function rewriteSelection(text: string, instruction: string): Promise<RewriteSelectionResponse> {+ const settings = await localStorage.get(['aiApiKey', 'aiProvider', 'aiModel', 'aiLanguage']);+ if (!settings.aiApiKey) return { error: 'no-api-key' };++ const provider = (settings.aiProvider as string) || 'openai';++ try {+ const { text: raw } = await generateText({+ model: createModel(+ provider,+ (settings.aiModel as string) || AI_PROVIDERS[provider].defaultModel,+ settings.aiApiKey as string,+ ),+ prompt: buildRewritePrompt(text, instruction, (settings.aiLanguage as string) || 'en'),+ maxOutputTokens: 400,+ });++ const cleaned = cleanRewrite(raw);+ if (!cleaned) return { error: 'generation-failed' };+ return { text: cleaned };+ } catch (err) {+ logger.error('Selection rewrite failed', err);+ return { error: 'generation-failed' };+ }+}