π¬ 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: DOM context extraction and text-based AI descriptions
Luis Ortizb7a98c4c4110
diff --git a/src/core/capture/ai-description.ts b/src/core/capture/ai-description.tsdeleted file mode 100644index a7d1c67..0000000--- a/src/core/capture/ai-description.ts+++ /dev/null@@ -1,70 +0,0 @@-import { generateText } from 'ai';-import { createOpenAI } from '@ai-sdk/openai';-import { createAnthropic } from '@ai-sdk/anthropic';-import { logger } from '@/lib/logger';-import type { ElementMeta } from '@/core/guides/types';--function createModel(provider: string, model: string, apiKey: string) {- if (provider === 'anthropic') {- return createAnthropic({ apiKey })(model);- }- return createOpenAI({ apiKey })(model);-}--export async function generateGuideTitle(- stepDescriptions: string[],- provider: string,- model: string,- apiKey: string,-): Promise<string | null> {- if (stepDescriptions.length === 0) return null;-- const steps = stepDescriptions.map((d, i) => `${i + 1}. ${d}`).join('\n');- const prompt = `These are the steps of a browser workflow:\n\n${steps}\n\nWrite a short title (max 8 words) that describes what this workflow does. Examples: "Create a new GitHub repository", "Update profile settings in Slack". Just the title, no quotes, no preamble.`;-- try {- const { text } = await generateText({- model: createModel(provider, model, apiKey),- prompt,- maxOutputTokens: 30,- });- return text.trim() || null;- } catch (err) {- logger.error('Guide title generation failed', err);- return null;- }-}--export async function getAIDescription(- blob: Blob,- action: string,- meta: ElementMeta,- provider: string,- model: string,- apiKey: string,-): Promise<string | null> {- const arrayBuffer = await blob.arrayBuffer();- const base64 = btoa(String.fromCharCode(...new Uint8Array(arrayBuffer)));- const dataUrl = `data:image/jpeg;base64,${base64}`;-- const targetText = meta.textContent || meta.ariaLabel || meta.placeholder || meta.tag;- const prompt = `This is a browser screenshot. The highlighted element (blue border) is a ${meta.tag} with text "${targetText}". The user performed a "${action}" action on it. Write a single concise sentence describing this step (e.g., "Click the Submit button"). No preamble.`;-- try {- const { text } = await generateText({- model: createModel(provider, model, apiKey),- messages: [{- role: 'user',- content: [- { type: 'image', image: dataUrl },- { type: 'text', text: prompt },- ],- }],- maxOutputTokens: 100,- });- return text.trim() || null;- } catch (err) {- logger.error('AI description failed, using fallback', err);- return null;- }-}diff --git a/src/core/capture/ai/description.ts b/src/core/capture/ai/description.tsnew file mode 100644index 0000000..2e730b1--- /dev/null+++ b/src/core/capture/ai/description.ts@@ -0,0 +1,25 @@+import { generateText } from 'ai';+import { logger } from '@/lib/logger';+import type { DOMContext } from '../dom/context';+import { serializeDOMContext } from '../dom/context';+import { createModel } from './provider';+import { STEP_DESCRIPTION_PROMPT } from './prompts';++export async function getAIDescription(+ domContext: DOMContext,+ provider: string,+ model: string,+ apiKey: string,+): Promise<string | null> {+ try {+ const { text } = await generateText({+ model: createModel(provider, model, apiKey),+ prompt: STEP_DESCRIPTION_PROMPT.replace('{{context}}', serializeDOMContext(domContext)),+ maxOutputTokens: 50,+ });+ return text.trim() || null;+ } catch (err) {+ logger.error('AI description failed, using fallback', err);+ return null;+ }+}diff --git a/src/core/capture/ai/prompts.ts b/src/core/capture/ai/prompts.tsnew file mode 100644index 0000000..86bb8c8--- /dev/null+++ b/src/core/capture/ai/prompts.ts@@ -0,0 +1,25 @@+export const STEP_DESCRIPTION_PROMPT = `You are describing steps in a browser workflow guide. Given the following context about a user action on a web page, write a single concise sentence describing this step.++{{context}}++Examples of good descriptions:+- "Click the Submit button"+- "Enter email address in the Email field"+- "Select 'Admin' from the Role dropdown"+- "Navigate to the Settings page"++Write only the description, no preamble.`;++export const GUIDE_TITLE_PROMPT = `These are the steps of a browser workflow, with the page URL and description for each step:++{{steps}}++Write a specific, descriptive title for this workflow. The title should mention the application or website name and the specific task being performed. Be precise β reference specific pages, features, or items that were interacted with.++Examples:+- "Review Most-Commented claude-code Pull Requests"+- "Configure Slack Notification Preferences for #engineering"+- "Submit Expense Report in Workday"+- "Create New Repository in GitHub Organization"++Just the title, no quotes, no preamble.`;diff --git a/src/core/capture/ai/provider.ts b/src/core/capture/ai/provider.tsnew file mode 100644index 0000000..4c79f9c--- /dev/null+++ b/src/core/capture/ai/provider.ts@@ -0,0 +1,7 @@+import { createOpenAI } from '@ai-sdk/openai';+import { createAnthropic } from '@ai-sdk/anthropic';++export function createModel(provider: string, model: string, apiKey: string) {+ if (provider === 'anthropic') return createAnthropic({ apiKey })(model);+ return createOpenAI({ apiKey })(model);+}diff --git a/src/core/capture/ai/title.ts b/src/core/capture/ai/title.tsnew file mode 100644index 0000000..6b0f43a--- /dev/null+++ b/src/core/capture/ai/title.ts@@ -0,0 +1,27 @@+import { generateText } from 'ai';+import { logger } from '@/lib/logger';+import { createModel } from './provider';+import { GUIDE_TITLE_PROMPT } from './prompts';++export async function generateGuideTitle(+ steps: { description: string; url: string }[],+ provider: string,+ model: string,+ apiKey: string,+): Promise<string | null> {+ if (steps.length === 0) return null;++ const formatted = steps.map((s, i) => `${i + 1}. [${s.url}] ${s.description}`).join('\n');++ try {+ const { text } = await generateText({+ model: createModel(provider, model, apiKey),+ prompt: GUIDE_TITLE_PROMPT.replace('{{steps}}', formatted),+ maxOutputTokens: 30,+ });+ return text.trim() || null;+ } catch (err) {+ logger.error('Guide title generation failed', err);+ return null;+ }+}diff --git a/src/core/capture/dom/context.ts b/src/core/capture/dom/context.tsnew file mode 100644index 0000000..e06a577--- /dev/null+++ b/src/core/capture/dom/context.ts@@ -0,0 +1,159 @@+export interface SiblingElement {+ tag: string;+ role: string | null;+ name: string | null;+ value: string | null;+}++export interface DOMContext {+ page: { title: string; path: string };+ container: { tag: string; role: string | null; label: string | null } | null;+ heading: string | null;+ siblings: SiblingElement[];+ target: { tag: string; role: string | null; name: string | null; value: string | null; action: string };+}++const SEMANTIC_CONTAINERS = new Set([+ 'form', 'nav', 'dialog', 'section', 'main', 'aside', 'header', 'footer', 'article',+]);++const INTERACTIVE_SELECTOR = 'a[href], button, input:not([type="hidden"]), select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [tabindex]:not([tabindex="-1"])';++const MAX_WALK_UP = 3;+const MAX_SIBLINGS = 10;++function textOf(el: Element | null): string | null {+ return el?.textContent?.trim() || null;+}++function attr(el: Element, name: string): string | null {+ return el.getAttribute(name) || null;+}++function resolveAriaLabelledBy(el: Element): string | null {+ const ids = attr(el, 'aria-labelledby');+ if (!ids) return null;+ return ids.split(/\s+/).map(id => textOf(document.getElementById(id))).filter(Boolean).join(' ') || null;+}++function getLabelForInput(el: Element): string | null {+ const id = el.id;+ if (id) {+ const label = textOf(document.querySelector(`label[for="${CSS.escape(id)}"]`));+ if (label) return label;+ }+ const parentLabel = el.closest('label');+ if (!parentLabel) return null;+ const clone = parentLabel.cloneNode(true) as HTMLElement;+ clone.querySelectorAll('input, select, textarea').forEach(c => c.remove());+ return textOf(clone);+}++function getAccessibleName(el: Element): string | null {+ return attr(el, 'aria-label')+ ?? resolveAriaLabelledBy(el)+ ?? (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement ? getLabelForInput(el) : null)+ ?? (el.textContent?.trim()?.length! <= 80 ? el.textContent?.trim() || null : null)+ ?? attr(el, 'title')+ ?? attr(el, 'placeholder');+}++function getElementValue(el: Element): string | null {+ if (el instanceof HTMLInputElement && (el.type === 'checkbox' || el.type === 'radio')) return el.checked ? 'checked' : 'unchecked';+ if (el instanceof HTMLInputElement && el.type === 'password') return '***';+ if (el instanceof HTMLInputElement && el.value) return `value=${el.value.slice(0, 50)}`;+ if (el instanceof HTMLTextAreaElement && el.value) return `value=${el.value.slice(0, 50)}`;+ if (el instanceof HTMLSelectElement && el.selectedOptions.length) return `selected=${el.selectedOptions[0].text.slice(0, 50)}`;+ if (attr(el, 'aria-checked')) return attr(el, 'aria-checked') === 'true' ? 'checked' : 'unchecked';+ if (attr(el, 'aria-selected') === 'true') return 'selected';+ if (attr(el, 'aria-current')) return 'current';+ return null;+}++function getContainerLabel(el: Element): string | null {+ return attr(el, 'aria-label')+ ?? textOf(el.querySelector(':scope > legend, :scope > caption'))+ ?? resolveAriaLabelledBy(el);+}++function findContainer(el: Element): { tag: string; role: string | null; label: string | null } | null {+ let current = el.parentElement;+ for (let depth = 0; current && current !== document.body && depth < MAX_WALK_UP; depth++, current = current.parentElement) {+ const tag = current.tagName.toLowerCase();+ const role = attr(current, 'role');+ if (SEMANTIC_CONTAINERS.has(tag) || role) {+ return { tag, role, label: getContainerLabel(current) };+ }+ }+ return null;+}++function findNearestHeading(el: Element): string | null {+ let current = el.parentElement;+ for (let depth = 0; current && current !== document.body && depth < 5; depth++, current = current.parentElement) {+ const text = textOf(current.querySelector('h1, h2, h3, h4, h5, h6, [role="heading"]'));+ if (text) return text.slice(0, 100);+ }++ let closest: Element | null = null;+ for (const h of document.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')) {+ if (el.compareDocumentPosition(h) & Node.DOCUMENT_POSITION_PRECEDING) closest = h;+ else break;+ }+ return closest ? textOf(closest)?.slice(0, 100) ?? null : null;+}++function collectSiblings(el: Element, container: Element | null): SiblingElement[] {+ const parent = container ?? el.parentElement;+ if (!parent) return [];++ const result: SiblingElement[] = [];+ for (const sib of parent.querySelectorAll(INTERACTIVE_SELECTOR)) {+ if (result.length >= MAX_SIBLINGS) break;+ if (sib.closest('[data-mimik-ignore]')) continue;+ result.push({ tag: sib.tagName.toLowerCase(), role: attr(sib, 'role'), name: getAccessibleName(sib), value: getElementValue(sib) });+ }+ return result;+}++export function extractDOMContext(el: HTMLElement, action: string): DOMContext {+ const container = findContainer(el);+ const containerEl = container+ ? el.closest(`${container.tag}${container.role ? `[role="${container.role}"]` : ''}`)+ : null;++ return {+ page: { title: document.title, path: location.pathname },+ container,+ heading: findNearestHeading(el),+ siblings: collectSiblings(el, containerEl),+ target: { tag: el.tagName.toLowerCase(), role: attr(el, 'role'), name: getAccessibleName(el), value: getElementValue(el), action },+ };+}++export function serializeDOMContext(ctx: DOMContext): string {+ const lines: string[] = [];++ lines.push(`Page: "${ctx.page.title}" ${ctx.page.path}`);++ if (ctx.container) {+ const role = ctx.container.role ? ` [role=${ctx.container.role}]` : '';+ const label = ctx.container.label ? ` "${ctx.container.label}"` : '';+ lines.push(`Container: ${ctx.container.tag}${role}${label}`);+ }++ lines.push(`Heading: ${ctx.heading ? `"${ctx.heading}"` : 'none'}`);++ if (ctx.siblings.length > 0) {+ lines.push(`Siblings: ${ctx.siblings.map(s => {+ const name = s.name ? ` "${s.name}"` : '';+ const val = s.value ? ` [${s.value}]` : '';+ return `${s.tag}${name}${val}`;+ }).join(', ')}`);+ }++ const { tag, name, value, action } = ctx.target;+ lines.push(`β Target: ${tag}${name ? ` "${name}"` : ''}${value ? ` [${value}]` : ''} (${action})`);++ return lines.join('\n');+}diff --git a/src/core/capture/dom/element-utils.ts b/src/core/capture/dom/element-utils.tsnew file mode 100644index 0000000..e80083c--- /dev/null+++ b/src/core/capture/dom/element-utils.ts@@ -0,0 +1,45 @@+export const FOCUSABLE_SELECTOR = 'a[href], button, input, select, textarea, [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="checkbox"], [role="radio"], [tabindex], [contenteditable="true"]';++const MAX_ELEMENT_RATIO = 0.8;++export function findFocusableAncestor(el: Element): HTMLElement {+ const focusable = el.closest(FOCUSABLE_SELECTOR);+ if (focusable instanceof HTMLElement) return focusable;+ if (el instanceof HTMLElement) return el;+ if (el.parentElement instanceof HTMLElement) return el.parentElement;+ return document.body;+}++export function isTextField(el: Element): boolean {+ if (el instanceof HTMLInputElement) {+ return ['text', 'email', 'password', 'search', 'tel', 'url', 'number'].includes(el.type);+ }+ return el instanceof HTMLTextAreaElement || (el instanceof HTMLElement && el.isContentEditable);+}++export function isNavigatingClick(el: HTMLElement): boolean {+ const anchor = el.closest('a[href]');+ if (!anchor) return false;+ const href = anchor.getAttribute('href');+ return !(!href || href === '#' || href.startsWith('javascript:'));+}++export function isTooLarge(el: Element): boolean {+ const rect = el.getBoundingClientRect();+ return (rect.width / window.innerWidth > MAX_ELEMENT_RATIO)+ && (rect.height / window.innerHeight > MAX_ELEMENT_RATIO);+}++export function isMimikElement(el: Element): boolean {+ return !!el.closest('[data-mimik-ignore]');+}++export function getFieldValue(el: HTMLElement): string {+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) return el.value;+ if (el.isContentEditable) return el.textContent?.trim() ?? '';+ return '';+}++export function getFieldLabel(el: HTMLElement): string {+ return el.getAttribute('aria-label') || el.getAttribute('placeholder') || el.getAttribute('name') || 'text field';+}