The agent that turns websites into APIs!
improve chrome ext
kalil0321c36195107955
diff --git a/.gitignore b/.gitignoreindex fa75599..3ca9e63 100644--- a/.gitignore+++ b/.gitignore@@ -97,4 +97,5 @@ collector_mode_plan.mdchrome-extension/node_modules/chrome-extension/dist/-chrome-extension-old\ No newline at end of file+chrome-extension-old+migros-demo/\ No newline at end of filediff --git a/chrome-extension/components.json b/chrome-extension/components.jsonnew file mode 100644index 0000000..76d1f60--- /dev/null+++ b/chrome-extension/components.json@@ -0,0 +1,20 @@+{+ "$schema": "https://ui.shadcn.com/schema.json",+ "style": "new-york",+ "rsc": false,+ "tsx": true,+ "tailwind": {+ "config": "tailwind.config.js",+ "css": "src/index.css",+ "baseColor": "neutral",+ "cssVariables": true,+ "prefix": ""+ },+ "aliases": {+ "components": "@/components",+ "utils": "@/lib/utils",+ "ui": "@/components/ui",+ "lib": "@/lib",+ "hooks": "@/hooks"+ }+}\ No newline at end of filediff --git a/chrome-extension/package-lock.json b/chrome-extension/package-lock.jsonindex b2cad03..f60710c 100644--- a/chrome-extension/package-lock.json+++ b/chrome-extension/package-lock.json@@ -10,11 +10,15 @@"dependencies": {"@base-ui/react": "^1.0.0","ansi-to-react": "^6.1.6",+ "clsx": "^2.1.1",+ "lucide-react": "^0.563.0","react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^9.1.0","react-syntax-highlighter": "^15.6.6",- "remark-gfm": "^4.0.1"+ "remark-gfm": "^4.0.1",+ "shiki": "^3.22.0",+ "tailwind-merge": "^3.4.0"},"devDependencies": {"@types/chrome": "^0.0.287",@@ -1312,6 +1316,73 @@"win32"]},+ "node_modules/@shikijs/core": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.22.0.tgz",+ "integrity": "sha512-iAlTtSDDbJiRpvgL5ugKEATDtHdUVkqgHDm/gbD2ZS9c88mx7G1zSYjjOxp5Qa0eaW0MAQosFRmJSk354PRoQA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.22.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4",+ "hast-util-to-html": "^9.0.5"+ }+ },+ "node_modules/@shikijs/engine-javascript": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.22.0.tgz",+ "integrity": "sha512-jdKhfgW9CRtj3Tor0L7+yPwdG3CgP7W+ZEqSsojrMzCjD1e0IxIbwUMDDpYlVBlC08TACg4puwFGkZfLS+56Tw==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.22.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "oniguruma-to-es": "^4.3.4"+ }+ },+ "node_modules/@shikijs/engine-oniguruma": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.22.0.tgz",+ "integrity": "sha512-DyXsOG0vGtNtl7ygvabHd7Mt5EY8gCNqR9Y7Lpbbd/PbJvgWrqaKzH1JW6H6qFkuUa8aCxoiYVv8/YfFljiQxA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.22.0",+ "@shikijs/vscode-textmate": "^10.0.2"+ }+ },+ "node_modules/@shikijs/langs": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.22.0.tgz",+ "integrity": "sha512-x/42TfhWmp6H00T6uwVrdTJGKgNdFbrEdhaDwSR5fd5zhQ1Q46bHq9EO61SCEWJR0HY7z2HNDMaBZp8JRmKiIA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.22.0"+ }+ },+ "node_modules/@shikijs/themes": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.22.0.tgz",+ "integrity": "sha512-o+tlOKqsr6FE4+mYJG08tfCFDS+3CG20HbldXeVoyP+cYSUxDhrFf3GPjE60U55iOkkjbpY2uC3It/eeja35/g==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "3.22.0"+ }+ },+ "node_modules/@shikijs/types": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.22.0.tgz",+ "integrity": "sha512-491iAekgKDBFE67z70Ok5a8KBMsQ2IJwOWw3us/7ffQkIBCyOQfm/aNwVMBUriP02QshIfgHCBSIYAl3u2eWjg==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ }+ },+ "node_modules/@shikijs/vscode-textmate": {+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",+ "license": "MIT"+ },"node_modules/@types/babel__core": {"version": "7.20.5","resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",@@ -1795,6 +1866,15 @@"node": ">= 6"}},+ "node_modules/clsx": {+ "version": "2.1.1",+ "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz",+ "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },"node_modules/comma-separated-tokens": {"version": "2.0.3","resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",@@ -2160,6 +2240,29 @@"url": "https://opencollective.com/unified"}},+ "node_modules/hast-util-to-html": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-whitespace": "^3.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "stringify-entities": "^4.0.0",+ "zwitch": "^2.0.4"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/hast-util-to-jsx-runtime": {"version": "2.3.6","resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",@@ -2290,6 +2393,16 @@"url": "https://opencollective.com/unified"}},+ "node_modules/html-void-elements": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",@@ -2522,6 +2635,15 @@"yallist": "^3.0.2"}},+ "node_modules/lucide-react": {+ "version": "0.563.0",+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.563.0.tgz",+ "integrity": "sha512-8dXPB2GI4dI8jV4MgUDGBeLdGk8ekfqVZ0BdLcrRzocGgG75ltNEmWS+gE7uokKF/0oSUuczNDT+g9hFJ23FkA==",+ "license": "ISC",+ "peerDependencies": {+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"+ }+ },"node_modules/markdown-table": {"version": "3.0.4","resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",@@ -3463,6 +3585,23 @@"node": ">= 6"}},+ "node_modules/oniguruma-parser": {+ "version": "0.12.1",+ "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.1.tgz",+ "integrity": "sha512-8Unqkvk1RYc6yq2WBYRj4hdnsAxVze8i7iPfQr8e4uSP3tRv0rpZcbGUDvxfQQcdwHt/e9PrMvGCsa8OqG9X3w==",+ "license": "MIT"+ },+ "node_modules/oniguruma-to-es": {+ "version": "4.3.4",+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.4.tgz",+ "integrity": "sha512-3VhUGN3w2eYxnTzHn+ikMI+fp/96KoRSVK9/kMTcFqj1NRDh2IhQCKvYxDnWePKRXY/AqH+Fuiyb7VHSzBjHfA==",+ "license": "MIT",+ "dependencies": {+ "oniguruma-parser": "^0.12.1",+ "regex": "^6.0.1",+ "regex-recursion": "^6.0.2"+ }+ },"node_modules/parse-entities": {"version": "4.0.2","resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",@@ -3956,6 +4095,30 @@"node": ">=6"}},+ "node_modules/regex": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-recursion": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-utilities": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",+ "license": "MIT"+ },"node_modules/remark-gfm": {"version": "4.0.1","resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",@@ -4148,6 +4311,22 @@"semver": "bin/semver.js"}},+ "node_modules/shiki": {+ "version": "3.22.0",+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.22.0.tgz",+ "integrity": "sha512-LBnhsoYEe0Eou4e1VgJACes+O6S6QC0w71fCSp5Oya79inkwkm15gQ1UF6VtQ8j/taMDh79hAB49WUk8ALQW3g==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "3.22.0",+ "@shikijs/engine-javascript": "3.22.0",+ "@shikijs/engine-oniguruma": "3.22.0",+ "@shikijs/langs": "3.22.0",+ "@shikijs/themes": "3.22.0",+ "@shikijs/types": "3.22.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ }+ },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",@@ -4242,6 +4421,16 @@"integrity": "sha512-05PUHKSNE8ou2dwIxTngl4EzcnsCDZGJ/iCLtDflR/SHB/ny14rXc+qU5P4mG9JkusiV7EivzY9Mhm55AzAvCg==","license": "MIT"},+ "node_modules/tailwind-merge": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz",+ "integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/dcastil"+ }+ },"node_modules/tailwindcss": {"version": "3.4.19","resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz",diff --git a/chrome-extension/package.json b/chrome-extension/package.jsonindex 2602631..67440b3 100644--- a/chrome-extension/package.json+++ b/chrome-extension/package.json@@ -12,11 +12,15 @@"dependencies": {"@base-ui/react": "^1.0.0","ansi-to-react": "^6.1.6",+ "clsx": "^2.1.1",+ "lucide-react": "^0.563.0","react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^9.1.0","react-syntax-highlighter": "^15.6.6",- "remark-gfm": "^4.0.1"+ "remark-gfm": "^4.0.1",+ "shiki": "^3.22.0",+ "tailwind-merge": "^3.4.0"},"devDependencies": {"@types/chrome": "^0.0.287",diff --git a/chrome-extension/src/background/service-worker.ts b/chrome-extension/src/background/service-worker.tsindex febda25..6fe8904 100644--- a/chrome-extension/src/background/service-worker.ts+++ b/chrome-extension/src/background/service-worker.ts@@ -17,7 +17,9 @@ import {getActiveSessionId,setActiveSessionId,getAppMode,- setAppMode+ setAppMode,+ getSaveLocation,+ updateSessionDualSavePaths} from '../shared/storage'import type { Session, AppMode } from '../shared/types'@@ -72,7 +74,7 @@ function handleCaptureEvent(event: { type: string; request?: unknown }): void {}function broadcastMessage(message: Record<string, unknown>): void {- chrome.runtime.sendMessage(message).catch(() => {})+ chrome.runtime.sendMessage(message).catch(() => { })}chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {@@ -85,7 +87,7 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {return true})-async function handleMessage(message: { type: string; [key: string]: unknown }): Promise<unknown> {+async function handleMessage(message: { type: string;[key: string]: unknown }): Promise<unknown> {switch (message.type) {case 'getState':return getState()@@ -156,13 +158,28 @@ async function getState(): Promise<Record<string, unknown>> {async function createSession(name?: string): Promise<{ success: boolean; session: Session }> {const runId = generateRunId()const sessionId = `session_${Date.now()}`++ // Get current tab info+ const [tab] = await chrome.tabs.query({ active: true, currentWindow: true })+ const url = tab?.url || ''+ let domain = ''+ try {+ if (url) {+ domain = new URL(url).hostname+ }+ } catch (e) {+ console.error('Failed to parse URL:', e)+ }+const sessionName = name || `Session ${new Date().toLocaleString()}`const newSession: Session = {id: sessionId,runId,name: sessionName,- tabId: 0,+ tabId: tab?.id || 0,+ url,+ domain,startTime: new Date().toISOString(),requestCount: 0,isActive: true,@@ -184,10 +201,13 @@ async function createSession(name?: string): Promise<{ success: boolean; session}async function switchSession(sessionId: string): Promise<{ success: boolean; session: Session | null }> {- // Don't allow switching if capturing on current session+ // Don't allow switching if capturing or recording codegen on current sessionif (captureManager.isCapturing()) {throw new Error('Cannot switch sessions while capturing. Stop capture first.')}+ if (codegenActive) {+ throw new Error('Cannot switch sessions while recording codegen. Stop codegen first.')+ }const session = await getSession(sessionId)if (!session) {@@ -278,7 +298,7 @@ def run():return { success: true }}-async function stopCodegen(): Promise<{ success: boolean; script: string }> {+async function stopCodegen(): Promise<{ success: boolean; script: string; savedPath?: string; visiblePath?: string; visibleDirectory?: string }> {if (!codegenActive) {throw new Error('Codegen not active')}@@ -302,40 +322,116 @@ if __name__ == "__main__":codegenActive = falseconst finalScript = codegenScript- // Save to active session if exists+ // Dual save: Hidden (ID-based) + Visible (domain-based)+ let savedPath: string | undefined+ let visiblePath: string | undefined+ let visibleDirectory: string | undefined+if (activeSessionId) {const session = await getSession(activeSessionId)if (session) {session.codegenScript = finalScript++ // Try to save via native host with dual save+ if (nativeHostConnected && session.runId) {+ try {+ // Get user's preferred save location+ const saveLocation = await getSaveLocation()+ const domain = session.domain++ // Call native host with dual save enabled+ const response = await nativeHost.saveCodegenScript(+ session.runId,+ finalScript,+ 'codegen_script.py',+ saveLocation,+ domain+ )++ if (response.success) {+ // Hidden path (for history/sync)+ savedPath = response.hidden_path+ session.codegenSavedPath = savedPath++ // Visible path (easy to find)+ visiblePath = response.visible_path+ visibleDirectory = response.visible_directory+ session.codegenVisiblePath = visiblePath+ session.codegenVisibleDirectory = visibleDirectory++ // Update session with dual save paths+ await updateSessionDualSavePaths(+ activeSessionId,+ response.hidden_path || '',+ response.visible_path || '',+ response.visible_directory || ''+ )++ console.log('Codegen script saved (dual save):')+ console.log(' Hidden:', response.hidden_path)+ console.log(' Visible:', response.visible_path)+ } else if (response.error) {+ console.error('Failed to save codegen script:', response.error)+ }+ } catch (error) {+ console.error('Failed to save codegen script via native host:', error)+ }+ }+await saveSession(session)}}- broadcastMessage({ type: 'codegenStopped', script: finalScript })+ broadcastMessage({+ type: 'codegenStopped',+ script: finalScript,+ savedPath,+ visiblePath,+ visibleDirectory+ })codegenTabId = null- return { success: true, script: finalScript }+ return { success: true, script: finalScript, savedPath, visiblePath, visibleDirectory }+}++// Escape string for Python code generation+function escapePythonString(str: string): string {+ return str+ .replace(/\\/g, '\\\\')+ .replace(/"/g, '\\"')+ .replace(/\n/g, '\\n')+ .replace(/\r/g, '\\r')+ .replace(/\t/g, '\\t')}// Listen for codegen events from content scriptchrome.runtime.onMessage.addListener((message, sender, sendResponse) => {if (message.type === 'codegenAction' && codegenActive && sender.tab?.id === codegenTabId) {- const { action, selector, value, url } = message+ const { action, selector, value, url, scrollX, scrollY, causedByClick } = messagelet code = ''switch (action) {case 'click':- code = ` page.click("${selector}")\n`+ code = ` page.click("${escapePythonString(selector)}")\n`breakcase 'fill':- code = ` page.fill("${selector}", "${value}")\n`+ code = ` page.fill("${escapePythonString(selector)}", "${escapePythonString(value)}")\n`breakcase 'navigate':- code = ` page.goto("${url}")\n`+ if (causedByClick) {+ // Navigation caused by click - add as comment+ code = ` # Navigated to: ${escapePythonString(url)}\n`+ } else {+ // Independent navigation - add as action+ code = ` page.goto("${escapePythonString(url)}")\n`+ }breakcase 'select':- code = ` page.select_option("${selector}", "${value}")\n`+ code = ` page.select_option("${escapePythonString(selector)}", "${escapePythonString(value)}")\n`+ break+ case 'scroll':+ code = ` page.evaluate("window.scrollTo(${scrollX}, ${scrollY})")\n`break}@@ -365,7 +461,6 @@ async function startCapture(tabId?: number): Promise<{ success: boolean; runId:if (!activeSessionId) {const { session } = await createSession()activeSessionId = session.id- currentRunId = session.runId}currentRunId = generateRunId()diff --git a/chrome-extension/src/components/agent-action.tsx b/chrome-extension/src/components/agent-action.tsxindex c4e9670..9a2a186 100644--- a/chrome-extension/src/components/agent-action.tsx+++ b/chrome-extension/src/components/agent-action.tsx@@ -82,7 +82,7 @@ function DoneAction({ cost, durationMs, isError }: { cost?: number; durationMs?:if (durationMs) details.push(`Time: ${(durationMs / 1000).toFixed(1)}s`)return (- <div className={`py-3 border-y-2 border-border/30 my-6 ${isError ? 'text-primary' : 'text-green-500/90'}`}>+ <div className={`py-3 my-6 ${isError ? 'text-primary' : 'text-green-500/90'}`}><div className="text-[12px] font-semibold tracking-wide">{statusText}</div>{details.length > 0 && (<div className="text-[11px] text-text-secondary/80 mt-1.5 tracking-wide">@@ -95,7 +95,7 @@ function DoneAction({ cost, durationMs, isError }: { cost?: number; durationMs?:function ErrorAction({ message }: { message: string }) {return (- <div className="bg-primary/10 border-l-2 border-primary/50 p-4 space-y-2">+ <div className="bg-primary/5 p-4 space-y-2 rounded-lg"><div className="text-[12px] font-semibold text-primary tracking-wide uppercase">Critical Error</div><div className="text-sm text-primary/90">{message}</div></div>diff --git a/chrome-extension/src/components/chat-input.tsx b/chrome-extension/src/components/chat-input.tsxindex 8e64cfc..4f819ca 100644--- a/chrome-extension/src/components/chat-input.tsx+++ b/chrome-extension/src/components/chat-input.tsx@@ -1,5 +1,5 @@-import { Button } from '@base-ui/react/button'-import { useRef, useEffect } from 'react'+import { useRef, useEffect, useState } from 'react'+import type { AppMode } from '../shared/types'interface ChatInputProps {value: string@@ -7,10 +7,14 @@ interface ChatInputProps {onSend: (message: string) => voidisStreaming: booleanplaceholder: string+ mode: AppMode+ onModeChange?: (mode: AppMode) => void+ modeDisabled?: boolean}-export function ChatInput({ value, onChange, onSend, isStreaming, placeholder }: ChatInputProps) {+export function ChatInput({ value, onChange, onSend, isStreaming, placeholder, mode }: ChatInputProps) {const textareaRef = useRef<HTMLTextAreaElement>(null)+ const [isFocused, setIsFocused] = useState(false)useEffect(() => {if (textareaRef.current) {@@ -22,55 +26,118 @@ export function ChatInput({ value, onChange, onSend, isStreaming, placeholder }:const handleKeyPress = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {if (e.key === 'Enter' && !e.shiftKey) {e.preventDefault()- if (value.trim()) {+ if (value.trim() && !isStreaming) {onSend(value.trim())}}}const handleSend = () => {- if (value.trim()) {+ if (value.trim() && !isStreaming) {onSend(value.trim())}}+ const handleContainerClick = () => {+ textareaRef.current?.focus()+ }++ const hasContent = value.trim().length > 0+return (- <div className="p-4">- <div className="flex items-start gap-3 w-full">- <span className="text-primary font-bold mt-1 select-none flex-shrink-0">{'>'}</span>- <textarea- ref={textareaRef}- value={value}- onChange={(e) => onChange(e.target.value)}- onKeyDown={handleKeyPress}- placeholder={placeholder}- rows={1}- className="flex-1 bg-transparent border-none text-sm text-white placeholder:text-text-secondary/50 resize-none focus:outline-none focus:ring-0 p-1 min-h-[28px] max-h-[200px] leading-relaxed w-full"- />- {value.trim() && (- <Button- onClick={handleSend}- className="text-primary hover:text-white transition-colors p-1.5 flex-shrink-0"- title="Send message"- >- <SendIcon />- </Button>- )}+ <div className="p-3">+ <div+ onClick={handleContainerClick}+ className={`+ flex min-h-[120px] flex-col rounded-3xl cursor-text+ bg-card transition-all duration-200+ border ${isFocused ? 'border-capture ring-1 ring-capture/30' : 'border-capture/30'}+ `}+ >+ {/* Textarea Area */}+ <div className="flex-1 relative overflow-y-auto max-h-[258px]">+ <textarea+ ref={textareaRef}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={handleKeyPress}+ onFocus={() => setIsFocused(true)}+ onBlur={() => setIsFocused(false)}+ placeholder={placeholder}+ disabled={isStreaming}+ aria-label="Chat message input"+ className="+ w-full border-0 p-3+ bg-transparent text-[16px] text-foreground+ placeholder:text-muted-foreground+ resize-none shadow-none outline-none+ min-h-[48.4px] leading-relaxed+ whitespace-pre-wrap break-words+ disabled:cursor-not-allowed disabled:opacity-50+ transition-[padding] duration-200 ease-in-out+ "+ />+ </div>++ {/* Bottom Toolbar */}+ <div className="flex min-h-[40px] items-center gap-2 p-2 pb-1 justify-end">+ {/* Right Side Actions */}+ <div className="flex items-center gap-2">+ {/* Send Button */}+ <button+ type="button"+ onClick={handleSend}+ disabled={!hasContent || isStreaming}+ aria-label="Send message"+ className={`+ inline-flex items-center justify-center+ h-8 w-8 rounded-full cursor-pointer+ transition-all duration-150+ outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background+ ${hasContent && !isStreaming+ ? mode === 'capture'+ ? 'bg-capture text-white hover:opacity-90 focus-visible:ring-capture/50'+ : 'bg-codegen text-white hover:opacity-90 focus-visible:ring-codegen/50'+ : 'bg-muted text-muted-foreground cursor-not-allowed opacity-50'+ }+ `}+ >+ <ArrowUpIcon className="h-4 w-4" />+ </button>+ </div>+ </div></div>+{isStreaming && (- <div className="mt-3 ml-6 flex items-center gap-2">- <div className="w-1.5 h-1.5 bg-primary rounded-full animate-pulse" />- <span className="text-[11px] text-text-secondary/80 tracking-wide">Processing...</span>+ <div className="mt-2 flex items-center gap-2 px-1">+ <div+ className={`w-1.5 h-1.5 rounded-full animate-pulse ${mode === 'capture' ? 'bg-capture' : 'bg-codegen'+ }`}+ />+ <span className="text-caption text-muted-foreground">Processing...</span></div>)}</div>)}-function SendIcon() {+function ArrowUpIcon({ className }: { className?: string }) {return (- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14 5l7 7m0 0l-7 7m7-7H3" />+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ >+ <path d="M12 5l0 14"></path>+ <path d="M18 11l-6 -6"></path>+ <path d="M6 11l6 -6"></path></svg>)}diff --git a/chrome-extension/src/components/code-display.tsx b/chrome-extension/src/components/code-display.tsxdeleted file mode 100644index b064bf3..0000000--- a/chrome-extension/src/components/code-display.tsx+++ /dev/null@@ -1,179 +0,0 @@-import { useRef, useEffect, useState } from 'react'-import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'-import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'-import { Button } from '@base-ui/react/button'--interface CodeDisplayProps {- code: string- language?: string- title?: string- isLive?: boolean- onCopy?: () => void-}--export function CodeDisplay({- code,- language = 'python',- title = 'Generated Script',- isLive = false,- onCopy-}: CodeDisplayProps) {- const containerRef = useRef<HTMLDivElement>(null)- const [copied, setCopied] = useState(false)- const [autoScroll, setAutoScroll] = useState(true)-- // Auto-scroll to bottom when new code is added- useEffect(() => {- if (autoScroll && containerRef.current) {- containerRef.current.scrollTop = containerRef.current.scrollHeight- }- }, [code, autoScroll])-- const handleCopy = async () => {- try {- await navigator.clipboard.writeText(code)- setCopied(true)- setTimeout(() => setCopied(false), 2000)- onCopy?.()- } catch (err) {- console.error('Failed to copy:', err)- }- }-- const handleScroll = () => {- if (containerRef.current) {- const { scrollTop, scrollHeight, clientHeight } = containerRef.current- // If user scrolls up, disable auto-scroll- // If they scroll to bottom, re-enable it- const isAtBottom = scrollHeight - scrollTop - clientHeight < 50- setAutoScroll(isAtBottom)- }- }-- const lineCount = code.split('\n').length-- return (- <div className="flex flex-col h-full bg-[#0d0d0d] rounded border border-white/10 overflow-hidden">- {/* Header */}- <div className="flex items-center justify-between px-4 py-2 bg-white/5 border-b border-white/10">- <div className="flex items-center gap-2">- <CodeIcon />- <span className="text-[11px] font-bold text-white/80 uppercase tracking-wider">{title}</span>- {isLive && (- <span className="flex items-center gap-1.5 px-2 py-0.5 bg-green-500/20 text-green-400 text-[9px] font-bold uppercase tracking-wider rounded">- <span className="w-1.5 h-1.5 bg-green-400 rounded-full animate-pulse" />- Live- </span>- )}- </div>- <div className="flex items-center gap-2">- <span className="text-[10px] text-white/40">{lineCount} lines</span>- <Button- onClick={handleCopy}- className="flex items-center gap-1 px-2 py-1 text-[10px] text-white/60 hover:text-white hover:bg-white/10 rounded transition-colors"- >- {copied ? <CheckIcon /> : <CopyIcon />}- {copied ? 'Copied!' : 'Copy'}- </Button>- </div>- </div>-- {/* Code content */}- <div- ref={containerRef}- onScroll={handleScroll}- className="flex-1 overflow-auto custom-scrollbar"- >- {code ? (- <SyntaxHighlighter- style={vscDarkPlus}- language={language}- PreTag="div"- showLineNumbers- lineNumberStyle={{- minWidth: '3em',- paddingRight: '1em',- color: 'rgba(255, 255, 255, 0.2)',- textAlign: 'right',- userSelect: 'none'- }}- customStyle={{- margin: 0,- padding: '1rem',- background: 'transparent',- fontSize: '12px',- lineHeight: '1.6'- }}- >- {code}- </SyntaxHighlighter>- ) : (- <div className="flex flex-col items-center justify-center h-full text-white/30 p-8">- <EmptyCodeIcon />- <p className="mt-4 text-[11px] text-center">- {isLive ? 'Waiting for actions...' : 'No code generated yet'}- </p>- {isLive && (- <p className="mt-1 text-[10px] text-white/20">- Interact with the page to record actions- </p>- )}- </div>- )}- </div>-- {/* Auto-scroll indicator */}- {!autoScroll && code && (- <div className="px-3 py-1.5 bg-primary/10 border-t border-primary/20">- <button- onClick={() => {- setAutoScroll(true)- if (containerRef.current) {- containerRef.current.scrollTop = containerRef.current.scrollHeight- }- }}- className="text-[10px] text-primary hover:text-primary/80 transition-colors"- >- Resume auto-scroll- </button>- </div>- )}- </div>- )-}--function CodeIcon() {- return (- <svg className="w-4 h-4 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />- </svg>- )-}--function CopyIcon() {- return (- <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />- </svg>- )-}--function CheckIcon() {- return (- <svg className="w-3 h-3 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />- </svg>- )-}--function EmptyCodeIcon() {- return (- <svg className="w-12 h-12 opacity-30" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />- <polyline strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} points="14 2 14 8 20 8" />- <line strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} x1="16" y1="13" x2="8" y2="13" />- <line strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} x1="16" y1="17" x2="8" y2="17" />- <polyline strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} points="10 9 9 9 8 9" />- </svg>- )-}diff --git a/chrome-extension/src/components/icons.tsx b/chrome-extension/src/components/icons.tsxnew file mode 100644index 0000000..1bde8c6--- /dev/null+++ b/chrome-extension/src/components/icons.tsx@@ -0,0 +1,8 @@+import { Copy, Download, Check, FileCode, Play, Square } from 'lucide-react'++export const Copy01Icon = Copy+export const Download01Icon = Download+export const Tick02Icon = Check+export const HugeiconsIcon = FileCode+export const PlayIcon = Play+export const StopIcon = Squarediff --git a/chrome-extension/src/components/mode-selector.tsx b/chrome-extension/src/components/mode-selector.tsxindex b70f2d0..9adacba 100644--- a/chrome-extension/src/components/mode-selector.tsx+++ b/chrome-extension/src/components/mode-selector.tsx@@ -8,26 +8,29 @@ interface ModeSelectorProps {export function ModeSelector({ mode, onModeChange, disabled }: ModeSelectorProps) {return (- <div className="flex items-center bg-white/5 rounded border border-white/10 p-0.5">+ <div className="flex items-center justify-center gap-1"><buttononClick={() => onModeChange('capture')}disabled={disabled}- className={`px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded transition-all ${+ className={`px-3 py-1 text-[16px] leading-relaxed font-normal rounded-md transition-all duration-150 cursor-pointer ${mode === 'capture'- ? 'bg-primary/20 text-primary'- : 'text-white/50 hover:text-white/80 hover:bg-white/5'+ ? 'text-capture'+ : 'text-white/50 hover:text-white/80'} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}+ aria-label="Switch to Capture mode">Capture</button>+ <div className="w-px h-3 bg-border" /><buttononClick={() => onModeChange('codegen')}disabled={disabled}- className={`px-3 py-1 text-[10px] font-bold uppercase tracking-wider rounded transition-all ${+ className={`px-3 py-1 text-[16px] leading-relaxed font-normal rounded-md transition-all duration-150 cursor-pointer ${mode === 'codegen'- ? 'bg-primary/20 text-primary'- : 'text-white/50 hover:text-white/80 hover:bg-white/5'+ ? 'text-codegen'+ : 'text-white/50 hover:text-white/80'} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}+ aria-label="Switch to Codegen mode">Codegen</button>diff --git a/chrome-extension/src/components/session-selector.tsx b/chrome-extension/src/components/session-selector.tsxindex e5620f3..bae2e65 100644--- a/chrome-extension/src/components/session-selector.tsx+++ b/chrome-extension/src/components/session-selector.tsx@@ -101,24 +101,24 @@ export function SessionSelector({<div className="relative" ref={dropdownRef}><ButtononClick={() => setIsOpen(!isOpen)}- className="flex items-center gap-2 px-3 py-1.5 text-[11px] font-medium text-white/80 hover:text-white bg-white/5 hover:bg-white/10 border border-white/10 rounded transition-all"+ className="flex items-center gap-2 px-3 py-1.5 text-[16px] leading-relaxed font-normal text-text-primary hover:text-white bg-muted hover:bg-muted/80 rounded-lg transition-all"><FolderIcon />- <span className="truncate max-w-[120px]">+ <span className="truncate max-w-[150px]">{activeSession?.name || 'No Session'}</span><ChevronIcon isOpen={isOpen} /></Button>{isOpen && (- <div className="absolute top-full left-0 mt-1 w-72 bg-[#141414] border border-white/10 rounded shadow-xl z-50 overflow-hidden">+ <div className="absolute top-full left-0 mt-1 w-72 bg-background-secondary rounded-xl shadow-2xl border border-border z-[100] overflow-hidden">{/* Header */}- <div className="px-3 py-2 border-b border-white/10 bg-white/5">+ <div className="px-3 py-2 bg-muted"><div className="flex items-center justify-between">- <span className="text-[10px] font-bold text-white/50 uppercase tracking-wider">Sessions</span>+ <span className="text-[14px] leading-relaxed font-normal text-white/50 uppercase tracking-wider">Sessions</span><ButtononClick={handleCreateSession}- className="text-[10px] text-primary hover:text-primary/80 font-medium transition-colors"+ className="text-[14px] leading-relaxed text-primary hover:text-primary/80 font-normal transition-colors">+ New</Button>@@ -127,7 +127,7 @@ export function SessionSelector({{/* New session input */}{showNewInput && (- <div className="px-3 py-2 border-b border-white/10 bg-primary/5">+ <div className="px-3 py-2 bg-primary/5"><inputref={inputRef}type="text"@@ -135,7 +135,7 @@ export function SessionSelector({onChange={(e) => setNewSessionName(e.target.value)}onKeyDown={handleNewSessionKeyDown}placeholder="Session name..."- className="w-full bg-transparent text-xs text-white placeholder:text-white/30 border-none outline-none"+ className="w-full bg-transparent text-[14px] leading-relaxed font-normal text-white placeholder:text-white/30 border-none outline-none"/></div>)}@@ -143,16 +143,14 @@ export function SessionSelector({{/* Session list */}<div className="max-h-64 overflow-y-auto">{sessions.length === 0 ? (- <div className="px-3 py-4 text-center text-[11px] text-white/30">+ <div className="px-3 py-4 text-center text-[14px] leading-relaxed text-white/30">No sessions yet</div>) : (sessions.map(session => (<divkey={session.id}- className={`group flex items-center gap-2 px-3 py-2 hover:bg-white/5 cursor-pointer transition-colors ${- session.id === activeSessionId ? 'bg-primary/10 border-l-2 border-primary' : ''- }`}+ className="group flex items-center gap-2 px-3 py-2 hover:bg-white/5 cursor-pointer transition-colors"onClick={() => {if (!editingId && session.id !== activeSessionId) {onSwitchSession(session.id)@@ -168,18 +166,18 @@ export function SessionSelector({onChange={(e) => setEditName(e.target.value)}onKeyDown={(e) => handleRenameKeyDown(e, session.id)}onClick={(e) => e.stopPropagation()}- className="flex-1 bg-transparent text-xs text-white border border-primary/50 rounded px-1 py-0.5 outline-none"+ className="flex-1 bg-background text-[14px] leading-relaxed font-normal text-white rounded-lg px-2 py-1 outline-none focus:ring-1 focus:ring-ring/50"/>) : (<><div className="flex-1 min-w-0"><div className="flex items-center gap-2">- <span className="text-xs text-white truncate">{session.name}</span>+ <span className="text-[14px] leading-relaxed font-normal text-white truncate">{session.name}</span>{session.isActive && (<span className="w-1.5 h-1.5 bg-green-500 rounded-full animate-pulse" />)}</div>- <div className="flex items-center gap-2 text-[10px] text-white/40">+ <div className="flex items-center gap-2 text-[12px] leading-relaxed font-normal text-white/40"><span>{formatDate(session.startTime)}</span><span>•</span><span>{session.requestCount} requests</span>@@ -220,8 +218,8 @@ export function SessionSelector({{/* Footer with warning if capturing */}{isCapturing && (- <div className="px-3 py-2 border-t border-white/10 bg-yellow-500/10">- <span className="text-[10px] text-yellow-500/80">+ <div className="px-3 py-2 bg-yellow-500/5">+ <span className="text-[14px] leading-relaxed font-normal text-yellow-500/80">Stop capture to switch sessions</span></div>diff --git a/chrome-extension/src/components/ui/code-block.tsx b/chrome-extension/src/components/ui/code-block.tsxnew file mode 100644index 0000000..1551b24--- /dev/null+++ b/chrome-extension/src/components/ui/code-block.tsx@@ -0,0 +1,292 @@+++import { type FC, useState } from "react";+import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';+import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';+import {+ Copy01Icon,+ Download01Icon,+ Tick02Icon,+} from "@/components/icons";+import { cn } from "@/lib/utils";++// Devicon class mapping for language icons+const deviconMap: Record<string, string> = {+ javascript: "devicon-javascript-plain colored",+ js: "devicon-javascript-plain colored",+ typescript: "devicon-typescript-plain colored",+ ts: "devicon-typescript-plain colored",+ tsx: "devicon-react-original colored",+ jsx: "devicon-react-original colored",+ python: "devicon-python-plain colored",+ py: "devicon-python-plain colored",+ java: "devicon-java-plain colored",+ cpp: "devicon-cplusplus-plain colored",+ c: "devicon-c-plain colored",+ csharp: "devicon-csharp-plain colored",+ cs: "devicon-csharp-plain colored",+ ruby: "devicon-ruby-plain colored",+ rb: "devicon-ruby-plain colored",+ go: "devicon-go-original-wordmark colored",+ rust: "devicon-rust-original colored",+ rs: "devicon-rust-original colored",+ php: "devicon-php-plain colored",+ swift: "devicon-swift-plain colored",+ kotlin: "devicon-kotlin-plain colored",+ kt: "devicon-kotlin-plain colored",+ html: "devicon-html5-plain colored",+ css: "devicon-css3-plain colored",+ json: "devicon-json-plain colored",+ xml: "devicon-xml-plain colored",+ yaml: "devicon-yaml-plain colored",+ yml: "devicon-yaml-plain colored",+ markdown: "devicon-markdown-original",+ md: "devicon-markdown-original",+ bash: "devicon-bash-plain colored",+ shell: "devicon-bash-plain colored",+ sh: "devicon-bash-plain colored",+ sql: "devicon-mysql-plain colored",+ docker: "devicon-docker-plain colored",+ dockerfile: "devicon-docker-plain colored",+ react: "devicon-react-original colored",+ vue: "devicon-vuejs-plain colored",+ angular: "devicon-angularjs-plain colored",+ svelte: "devicon-svelte-plain colored",+ nodejs: "devicon-nodejs-plain colored",+};++// Map common language names to Prism-supported languages+const languageMap: Record<string, string> = {+ javascript: "javascript",+ js: "javascript",+ typescript: "typescript",+ ts: "typescript",+ tsx: "tsx",+ jsx: "jsx",+ python: "python",+ py: "python",+ java: "java",+ cpp: "cpp",+ c: "c",+ csharp: "csharp",+ cs: "csharp",+ ruby: "ruby",+ rb: "ruby",+ go: "go",+ rust: "rust",+ rs: "rust",+ php: "php",+ swift: "swift",+ kotlin: "kotlin",+ kt: "kotlin",+ html: "html",+ css: "css",+ json: "json",+ xml: "xml",+ yaml: "yaml",+ yml: "yaml",+ markdown: "markdown",+ md: "markdown",+ bash: "bash",+ shell: "bash",+ sh: "bash",+ sql: "sql",+};++export interface CodeBlockProps {+ children: string;+ language?: string;+ filename?: string;+ showLineNumbers?: boolean;+ className?: string;+}++export const CodeBlock: FC<CodeBlockProps> = ({+ children,+ language = "plaintext",+ filename,+ showLineNumbers = false,+ className,+}) => {+ const [copied, setCopied] = useState(false);++ const hasCode = children.trim().length > 0;+ const mappedLang = languageMap[language.toLowerCase()] || "text";++ const handleCopy = async () => {+ if (!hasCode) return;+ await navigator.clipboard.writeText(children);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ };++ const handleDownload = () => {+ if (!hasCode) return;++ // Generate descriptive filename+ const extension = getFileExtension(language);+ const timestamp = new Date().toISOString().split('T')[0]; // YYYY-MM-DD+ const defaultFilename = filename || `codegen_${timestamp}.${extension}`;++ const blob = new Blob([children], { type: "text/plain" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = defaultFilename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ };++ const deviconClass =+ deviconMap[language.toLowerCase()] || deviconMap[language];++ return (+ <div+ className={cn(+ "relative mt-0 mx-3 rounded-xl overflow-hidden border border-border",+ "bg-background-elevated flex flex-col h-full",+ className,+ )}+ >+ {/* Header */}+ <div+ className={cn(+ "flex items-center justify-between px-4 py-2",+ "bg-muted border-b border-border",+ )}+ >+ <div className="flex items-center gap-2">+ {deviconClass ? (+ <i className={cn(deviconClass, "text-lg")} aria-hidden="true" />+ ) : (+ <span+ className={cn(+ "rounded px-2 py-0.5 text-[14px] leading-relaxed",+ "bg-background text-text-muted border border-border",+ )}+ >+ {language}+ </span>+ )}+ {filename && (+ <span className="text-[14px] leading-relaxed font-normal text-text-primary">+ {filename}+ </span>+ )}+ </div>+ <div className="flex items-center gap-1">+ <button+ type="button"+ onClick={handleDownload}+ disabled={!hasCode}+ className={cn(+ "rounded-lg p-1.5 transition-all duration-150",+ hasCode+ ? "cursor-pointer text-muted-foreground hover:text-foreground hover:bg-accent"+ : "cursor-not-allowed opacity-30 text-muted-foreground",+ )}+ aria-label="Download code"+ >+ <Download01Icon size={16} />+ </button>+ <button+ type="button"+ onClick={handleCopy}+ disabled={!hasCode}+ className={cn(+ "rounded-lg p-1.5 transition-all duration-150",+ hasCode+ ? "cursor-pointer text-muted-foreground hover:text-foreground hover:bg-accent"+ : "cursor-not-allowed opacity-30 text-muted-foreground",+ )}+ aria-label="Copy code"+ >+ {copied ? (+ <Tick02Icon+ size={16}+ className="text-codegen"+ />+ ) : (+ <Copy01Icon size={16} />+ )}+ </button>+ </div>+ </div>++ {/* Code content */}+ <div className="flex-1 overflow-auto">+ {!hasCode ? (+ <div className="flex flex-col items-center justify-center h-full p-8">+ <div className="w-24 h-24 text-white/10 mb-4">+ <svg viewBox="0 0 400 400" className="w-full h-full" fill="none" stroke="currentColor" strokeWidth="12" strokeLinecap="round" strokeLinejoin="round">+ <path d="M 170 110 Q 150 110 140 120 Q 130 130 130 150 L 130 185 Q 130 195 120 195 L 110 195 L 110 205 L 120 205 Q 130 205 130 215 L 130 250 Q 130 270 140 280 Q 150 290 170 290" />+ <path d="M 230 110 Q 250 110 260 120 Q 270 130 270 150 L 270 185 Q 270 195 280 195 L 290 195 L 290 205 L 280 205 Q 270 205 270 215 L 270 250 Q 270 270 260 280 Q 250 290 230 290" />+ <circle cx="185" cy="200" r="5" fill="currentColor" stroke="none" />+ <circle cx="200" cy="200" r="5" fill="currentColor" stroke="none" />+ <circle cx="215" cy="200" r="5" fill="currentColor" stroke="none" />+ </svg>+ </div>+ <p className="text-sm text-white/30 text-center">+ Click the play button to start recording+ </p>+ <p className="text-xs text-white/20 text-center mt-2">+ Refresh the page if interactions aren't being captured+ </p>+ </div>+ ) : (+ <SyntaxHighlighter+ language={mappedLang}+ style={vscDarkPlus}+ showLineNumbers={showLineNumbers}+ customStyle={{+ margin: 0,+ padding: '1rem',+ background: 'transparent',+ fontSize: '14px',+ lineHeight: '1.5',+ }}+ codeTagProps={{+ style: {+ fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace',+ }+ }}+ >+ {children}+ </SyntaxHighlighter>+ )}+ </div>+ </div>+ );+};++// Helper function to get file extension from language+function getFileExtension(language: string): string {+ const extensionMap: Record<string, string> = {+ javascript: "js",+ typescript: "ts",+ python: "py",+ java: "java",+ cpp: "cpp",+ c: "c",+ csharp: "cs",+ ruby: "rb",+ go: "go",+ rust: "rs",+ php: "php",+ swift: "swift",+ kotlin: "kt",+ html: "html",+ css: "css",+ json: "json",+ xml: "xml",+ yaml: "yaml",+ markdown: "md",+ bash: "sh",+ shell: "sh",+ sql: "sql",+ };++ return extensionMap[language.toLowerCase()] || "txt";+}diff --git a/chrome-extension/src/content/codegen-recorder.ts b/chrome-extension/src/content/codegen-recorder.tsindex 0923a5c..19099c6 100644--- a/chrome-extension/src/content/codegen-recorder.ts+++ b/chrome-extension/src/content/codegen-recorder.ts@@ -2,10 +2,16 @@* Content script for recording user interactions for Playwright codegen*/+console.log('[Codegen Recorder] Content script loaded')+let isRecording = false// Generate a robust CSS selector for an element-function getSelector(element: Element): string {+function getSelector(element: Element, depth: number = 0): string {+ // Prevent infinite recursion+ if (depth > 10) {+ return element.tagName.toLowerCase()+ }// Try data-testid firstif (element.hasAttribute('data-testid')) {return `[data-testid="${element.getAttribute('data-testid')}"]`@@ -44,12 +50,13 @@ function getSelector(element: Element): string {// Try placeholder for inputsif (element.hasAttribute('placeholder')) {const placeholder = element.getAttribute('placeholder')- return `[placeholder="${placeholder}"]`+ return `[placeholder="${CSS.escape(placeholder || '')}"]`}// Try aria-labelif (element.hasAttribute('aria-label')) {- return `[aria-label="${element.getAttribute('aria-label')}"]`+ const ariaLabel = element.getAttribute('aria-label')+ return `[aria-label="${CSS.escape(ariaLabel || '')}"]`}// Try text content for buttons and links@@ -62,14 +69,12 @@ function getSelector(element: Element): string {// Fall back to tag + nth-childconst parent = element.parentElement- if (parent) {+ if (parent && parent.tagName !== 'BODY' && parent.tagName !== 'HTML') {const siblings = Array.from(parent.children)const index = siblings.indexOf(element) + 1const tag = element.tagName.toLowerCase()- const parentSelector = getSelector(parent)- if (parentSelector !== 'body') {- return `${parentSelector} > ${tag}:nth-child(${index})`- }+ const parentSelector = getSelector(parent, depth + 1)+ return `${parentSelector} > ${tag}:nth-child(${index})`}// Last resort: just the tag@@ -101,6 +106,13 @@ function sendAction(action: string, data: Record<string, unknown>) {let lastInputElement: HTMLInputElement | HTMLTextAreaElement | null = nulllet inputTimeout: ReturnType<typeof setTimeout> | null = null+// Track scroll events+let lastScrollTime = 0+let scrollTimeout: ReturnType<typeof setTimeout> | null = null++// Track click events for navigation correlation+let lastClickTime = 0+function handleClick(event: MouseEvent) {if (!isRecording) return@@ -121,6 +133,8 @@ function handleClick(event: MouseEvent) {return}+ console.log('[Codegen] Click on:', selector, target)+ lastClickTime = Date.now()sendAction('click', { selector })}@@ -150,6 +164,7 @@ function commitPendingInput() {const value = escapeString(lastInputElement.value)if (value) {+ console.log('[Codegen] Fill input:', selector, 'with value:', value)sendAction('fill', { selector, value })}@@ -181,13 +196,39 @@ function handleKeyDown(event: KeyboardEvent) {}}+function handleScroll(_event: Event) {+ if (!isRecording) return++ // Debounce scroll events (300ms)+ if (scrollTimeout) {+ clearTimeout(scrollTimeout)+ }++ scrollTimeout = setTimeout(() => {+ const scrollX = window.scrollX+ const scrollY = window.scrollY++ console.log('[Codegen] Scroll detected:', { scrollX, scrollY })+ sendAction('scroll', { scrollX, scrollY })+ lastScrollTime = Date.now()+ }, 300)+}+// Handle navigationlet lastUrl = window.location.href+let navigationInterval: ReturnType<typeof setInterval> | null = nullfunction checkNavigation() {if (window.location.href !== lastUrl) {- lastUrl = window.location.href+ const newUrl = window.location.href+ const timeSinceClick = Date.now() - lastClickTime++ // Mark navigation as click-caused if within 500ms of a click+ const causedByClick = timeSinceClick < 500++ console.log('[Codegen] Navigation detected:', lastUrl, '->', newUrl, causedByClick ? '(caused by click)' : '')+ lastUrl = newUrlif (isRecording) {- sendAction('navigate', { url: lastUrl })+ sendAction('navigate', { url: lastUrl, causedByClick })}}}@@ -199,15 +240,19 @@ function startRecording() {isRecording = truelastUrl = window.location.href+ // Send initial navigation+ sendAction('navigate', { url: lastUrl })+document.addEventListener('click', handleClick, true)document.addEventListener('input', handleInput, true)document.addEventListener('change', handleChange, true)document.addEventListener('keydown', handleKeyDown, true)+ document.addEventListener('scroll', handleScroll, true)// Check for navigation periodically- setInterval(checkNavigation, 100)+ navigationInterval = setInterval(checkNavigation, 100)- console.log('[Codegen] Recording started')+ console.log('[Codegen] Recording started on:', lastUrl)}// Stop recording@@ -221,6 +266,17 @@ function stopRecording() {document.removeEventListener('input', handleInput, true)document.removeEventListener('change', handleChange, true)document.removeEventListener('keydown', handleKeyDown, true)+ document.removeEventListener('scroll', handleScroll, true)++ if (scrollTimeout) {+ clearTimeout(scrollTimeout)+ scrollTimeout = null+ }++ if (navigationInterval) {+ clearInterval(navigationInterval)+ navigationInterval = null+ }console.log('[Codegen] Recording stopped')}@@ -238,10 +294,15 @@ chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {})// Check if we should be recording on load-chrome.runtime.sendMessage({ type: 'getCodegenState' }).then(response => {- if (response?.codegenActive) {- startRecording()- }-}).catch(() => {- // Extension not ready yet-})+function checkInitialState(retries = 3) {+ chrome.runtime.sendMessage({ type: 'getCodegenState' }).then(response => {+ if (response?.codegenActive) {+ startRecording()+ }+ }).catch(() => {+ if (retries > 0) {+ setTimeout(() => checkInitialState(retries - 1), 500)+ }+ })+}+checkInitialState()diff --git a/chrome-extension/src/index.css b/chrome-extension/src/index.cssindex e704118..e1291c1 100644--- a/chrome-extension/src/index.css+++ b/chrome-extension/src/index.css@@ -1,12 +1,36 @@-@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');-@tailwind base;@tailwind components;@tailwind utilities;@layer base {body {- @apply bg-background text-text-primary text-sm;+ @apply bg-background text-text-primary text-base font-sans antialiased;+ }++ h1, h2, h3, h4, h5, h6 {+ @apply font-heading;+ }++ /* System font optimization */+ * {+ -webkit-font-smoothing: antialiased;+ -moz-osx-font-smoothing: grayscale;+ text-rendering: optimizeLegibility;+ }++ /* Enhanced rendering for small text */+ .text-tiny,+ .text-caption,+ .text-small {+ text-rendering: geometricPrecision;+ font-variant-numeric: tabular-nums;+ }++ /* Optimize monospace rendering */+ .font-mono,+ .font-heading {+ text-rendering: optimizeLegibility;+ font-feature-settings: "liga" 0;}}@@ -20,7 +44,7 @@}.btn-secondary {- @apply border border-border text-text-primary hover:bg-background-secondary;+ @apply border-0 text-text-primary hover:bg-background-secondary;}.btn-ghost {@@ -28,9 +52,9 @@}}-/* Custom scrollbar */+/* Custom scrollbar - ultra dark */::-webkit-scrollbar {- width: 8px;+ width: 6px;}::-webkit-scrollbar-track {@@ -38,17 +62,17 @@}::-webkit-scrollbar-thumb {- background: #2a2a2a;- border-radius: 4px;+ background: #1a1a1a;+ border-radius: 3px;}::-webkit-scrollbar-thumb:hover {- background: #3a3a3a;+ background: #222222;}.custom-scrollbar {scrollbar-width: thin;- scrollbar-color: #2a2a2a transparent;+ scrollbar-color: #1a1a1a transparent;}/* Animations */@@ -88,9 +112,27 @@font-size: 0.875rem;}-/* Smooth transitions */-* {- transition-property: color, background-color, border-color, opacity;+/* Smooth transitions - scoped to interactive elements to avoid text rendering issues */+button,+a,+input,+textarea,+select,+[role="button"],+[role="tab"],+.btn {+ transition-property: color, background-color, border-color, opacity, transform;transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);transition-duration: 150ms;}++/* Reduced motion support */+@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ animation-iteration-count: 1 !important;+ transition-duration: 0.01ms !important;+ }+}diff --git a/chrome-extension/src/shared/native-host.ts b/chrome-extension/src/shared/native-host.tsindex f765e85..0951038 100644--- a/chrome-extension/src/shared/native-host.ts+++ b/chrome-extension/src/shared/native-host.ts@@ -154,6 +154,46 @@ class NativeHostClient {})}+ async saveCodegenScript(+ runId: string,+ script: string,+ filename: string = 'codegen_script.py',+ saveLocation: string = 'downloads',+ domain?: string+ ): Promise<{+ success: boolean+ hidden_path?: string+ visible_path?: string+ hidden_directory?: string+ visible_directory?: string+ domain?: string+ error?: string+ }> {+ return new Promise((resolve) => {+ this.sendMessage(+ {+ type: 'saveCodegenScript',+ run_id: runId,+ script,+ filename,+ save_location: saveLocation,+ domain+ },+ (response) => {+ resolve(response as {+ success: boolean+ hidden_path?: string+ visible_path?: string+ hidden_directory?: string+ visible_directory?: string+ domain?: string+ error?: string+ })+ }+ )+ })+ }+isConnected(): boolean {return this.connected && this.port !== null}diff --git a/chrome-extension/src/shared/storage.ts b/chrome-extension/src/shared/storage.tsindex 1f981ca..eaaa1a6 100644--- a/chrome-extension/src/shared/storage.ts+++ b/chrome-extension/src/shared/storage.ts@@ -6,7 +6,8 @@ import type { Settings, Session, ChatMessage, AppMode } from './types'const DEFAULT_SETTINGS: Settings = {captureTypes: ['xhr', 'fetch', 'websocket'],- lastModel: 'claude-sonnet-4-5'+ lastModel: 'claude-sonnet-4-5',+ saveLocation: 'downloads' // Default to downloads folder}export async function getSettings(): Promise<Settings> {@@ -149,3 +150,34 @@ export async function addChatMessage(runId: string, message: ChatMessage): Promihistory.push(message)await chrome.storage.local.set({ [`chat_${runId}`]: history })}++// Save location helpers for dual save system++export async function getSaveLocation(): Promise<string> {+ const settings = await getSettings()+ return settings.saveLocation || 'downloads'+}++export async function setSaveLocation(location: string): Promise<void> {+ await saveSettings({ saveLocation: location })+}++export async function isDownloadsDefault(): Promise<boolean> {+ const location = await getSaveLocation()+ return location === 'downloads'+}++export async function updateSessionDualSavePaths(+ sessionId: string,+ hiddenPath: string,+ visiblePath: string,+ visibleDirectory: string+): Promise<void> {+ const session = await getSession(sessionId)+ if (session) {+ session.codegenHiddenPath = hiddenPath+ session.codegenVisiblePath = visiblePath+ session.codegenVisibleDirectory = visibleDirectory+ await saveSession(session)+ }+}diff --git a/chrome-extension/src/shared/types.ts b/chrome-extension/src/shared/types.tsindex 0d348bc..64056b4 100644--- a/chrome-extension/src/shared/types.ts+++ b/chrome-extension/src/shared/types.ts@@ -3,12 +3,19 @@ export interface Session {runId: stringname: stringtabId: number+ url?: string+ domain?: stringstartTime: stringendTime?: stringrequestCount: numberisActive: booleanmessages: ChatMessage[]codegenScript?: string+ codegenSavedPath?: string+ // Dual save paths+ codegenHiddenPath?: string+ codegenVisiblePath?: string+ codegenVisibleDirectory?: string}export interface ChatMessage {@@ -49,6 +56,17 @@ export interface AgentEvent {export interface Settings {lastModel: stringcaptureTypes: string[]+ saveLocation: 'downloads' | string // 'downloads' or custom path+}++export interface SaveCodegenResult {+ success: boolean+ hidden_path?: string+ visible_path?: string+ hidden_directory?: string+ visible_directory?: string+ domain?: string+ error?: string}export type MessageType =diff --git a/chrome-extension/src/sidepanel/index.html b/chrome-extension/src/sidepanel/index.htmlindex 75b5034..07daef6 100644--- a/chrome-extension/src/sidepanel/index.html+++ b/chrome-extension/src/sidepanel/index.html@@ -4,6 +4,8 @@<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Reverse API Engineer</title>+ <!-- Devicon for language icons in code blocks -->+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devicons/devicon@latest/devicon.min.css"></head><body><div id="root"></div>diff --git a/chrome-extension/src/sidepanel/side-panel.tsx b/chrome-extension/src/sidepanel/side-panel.tsxindex 190acb4..fc1a7a5 100644--- a/chrome-extension/src/sidepanel/side-panel.tsx+++ b/chrome-extension/src/sidepanel/side-panel.tsx@@ -5,7 +5,8 @@ import { AgentAction } from '../components/agent-action'import { ChatInput } from '../components/chat-input'import { SessionSelector } from '../components/session-selector'import { ModeSelector } from '../components/mode-selector'-import { CodeDisplay } from '../components/code-display'+import { CodeBlock } from '../components/ui/code-block'+import { PlayIcon, StopIcon, Tick02Icon } from '../components/icons'import type { AppState, AgentEvent, Settings, Session, AppMode } from '../shared/types'interface ChatMessage {@@ -38,6 +39,7 @@ const DEFAULT_STATE: ExtendedAppState = {const DEFAULT_SETTINGS: Settings = {lastModel: 'claude-sonnet-4-5',captureTypes: ['xhr', 'fetch', 'websocket'],+ saveLocation: 'downloads'}export function SidePanel() {@@ -46,6 +48,10 @@ export function SidePanel() {const [messages, setMessages] = useState<ChatMessage[]>([])const [inputValue, setInputValue] = useState('')const [warningMessage, setWarningMessage] = useState<string | null>(null)+ const [codegenSavedPath, setCodegenSavedPath] = useState<string | null>(null)+ const [codegenVisiblePath, setCodegenVisiblePath] = useState<string | null>(null)+ const [codegenVisibleDirectory, setCodegenVisibleDirectory] = useState<string | null>(null)+ const [showSettings, setShowSettings] = useState(false)const messagesEndRef = useRef<HTMLDivElement>(null)const currentResponseIdRef = useRef<string | null>(null)@@ -63,7 +69,19 @@ export function SidePanel() {chrome.runtime.sendMessage({ type: 'getState' }),chrome.runtime.sendMessage({ type: 'getSettings' }),])- if (stateRes) setState(prev => ({ ...prev, ...stateRes }))+ if (stateRes) {+ setState(prev => ({ ...prev, ...stateRes }))++ // Load active session's data including messages and codegen info+ const sessions = stateRes.sessions as Session[] | undefined+ const activeSession = sessions?.find(s => s.id === stateRes.activeSessionId)+ if (activeSession) {+ setMessages(activeSession.messages || [])+ setCodegenSavedPath(activeSession.codegenSavedPath || null)+ setCodegenVisiblePath(activeSession.codegenVisiblePath || null)+ setCodegenVisibleDirectory(activeSession.codegenVisibleDirectory || null)+ }+ }if (settingsRes) setSettings(prev => ({ ...prev, ...settingsRes }))} catch (err) {console.error('Failed to initialize:', err)@@ -81,7 +99,7 @@ export function SidePanel() {// Listen for messages from backgrounduseEffect(() => {- const handleMessage = (message: { type: string; event?: AgentEvent | { type: string }; script?: string; session?: Session; mode?: AppMode; newCode?: string }) => {+ const handleMessage = (message: { type: string; event?: AgentEvent | { type: string }; script?: string; session?: Session; mode?: AppMode; newCode?: string; savedPath?: string }) => {switch (message.type) {case 'captureEvent':// Refresh state to get updated counts@@ -111,12 +129,23 @@ export function SidePanel() {breakcase 'codegenStarted':setState(prev => ({ ...prev, codegenActive: true, codegenScript: message.script || '' }))+ setCodegenSavedPath(null)breakcase 'codegenUpdate':setState(prev => ({ ...prev, codegenScript: message.script || '' }))breakcase 'codegenStopped':setState(prev => ({ ...prev, codegenActive: false, codegenScript: message.script || '' }))+ if (message.savedPath) {+ setCodegenSavedPath(message.savedPath)+ }+ // Handle dual save paths+ if ((message as { visiblePath?: string }).visiblePath) {+ setCodegenVisiblePath((message as { visiblePath?: string }).visiblePath || null)+ }+ if ((message as { visibleDirectory?: string }).visibleDirectory) {+ setCodegenVisibleDirectory((message as { visibleDirectory?: string }).visibleDirectory || null)+ }break}}@@ -256,8 +285,11 @@ export function SidePanel() {await chrome.runtime.sendMessage({ type: 'createSession', name })const res = await chrome.runtime.sendMessage({ type: 'getState' })if (res) setState(prev => ({ ...prev, ...res }))- // Clear messages for new session+ // Clear messages and codegen data for new sessionsetMessages([])+ setCodegenSavedPath(null)+ setCodegenVisiblePath(null)+ setCodegenVisibleDirectory(null)} catch (err) {console.error('Create session error:', err)showWarning('Failed to create session')@@ -269,8 +301,21 @@ export function SidePanel() {await chrome.runtime.sendMessage({ type: 'switchSession', sessionId })const res = await chrome.runtime.sendMessage({ type: 'getState' })if (res) setState(prev => ({ ...prev, ...res }))- // Load messages for the switched session (TODO: implement message persistence per session)- setMessages([])++ // Load session-specific data including messages and codegen info+ const sessions = res?.sessions as Session[] | undefined+ const currentSession = sessions?.find(s => s.id === sessionId)+ if (currentSession) {+ setMessages(currentSession.messages || [])+ setCodegenSavedPath(currentSession.codegenSavedPath || null)+ setCodegenVisiblePath(currentSession.codegenVisiblePath || null)+ setCodegenVisibleDirectory(currentSession.codegenVisibleDirectory || null)+ } else {+ setMessages([])+ setCodegenSavedPath(null)+ setCodegenVisiblePath(null)+ setCodegenVisibleDirectory(null)+ }} catch (err) {console.error('Switch session error:', err)showWarning((err as Error).message || 'Failed to switch session')@@ -325,95 +370,131 @@ export function SidePanel() {}}+ const isActive = state.mode === 'capture' ? state.capturing : state.codegenActive+return (- <div className="flex flex-col h-screen bg-[#0a0a0a] text-text-primary selection:bg-primary/30">+ <div className="flex flex-col h-screen bg-background text-text-primary selection:bg-primary/30">{/* Header */}- <header className="flex items-center justify-between px-4 py-3 border-b border-border/50 bg-[#0a0a0a]/95 backdrop-blur-md sticky top-0 z-10">- <div className="flex items-center gap-3 overflow-hidden flex-1 min-w-0">- <div className="w-2 h-2 rounded-full bg-primary animate-pulse flex-shrink-0" />- <h1 className="text-xs font-semibold tracking-wide text-white font-sans truncate">reverse-api-engineer</h1>- {state.current_task && (- <div className="flex items-center gap-2 ml-4 px-3 py-1 bg-primary/10 border border-primary/20 text-[10px] text-primary/90 font-medium truncate max-w-md">- <span className="opacity-60">Current:</span>- <span className="truncate">{state.current_task}</span>- </div>- )}- </div>+ <header className="flex items-center justify-between gap-3 px-4 py-3 bg-background backdrop-blur-md sticky top-0 z-10">+ <div className="flex items-center gap-3 flex-1 min-w-0">+ {/* Session Selector */}+ <SessionSelector+ sessions={state.sessions || []}+ activeSessionId={state.activeSessionId}+ isCapturing={state.capturing}+ onCreateSession={handleCreateSession}+ onSwitchSession={handleSwitchSession}+ onDeleteSession={handleDeleteSession}+ onRenameSession={handleRenameSession}+ />- <div className="flex items-center gap-2">- {/* Mode Toggle */}+ {/* Mode Switcher */}<ModeSelectormode={state.mode}onModeChange={handleModeChange}disabled={state.capturing || state.codegenActive}/>++ {/* Current Task Pill */}+ {state.current_task && (+ <div+ className={`flex items-center gap-2 px-3 py-1.5 text-tiny truncate max-w-md rounded-lg border ${state.mode === 'capture'+ ? 'bg-capture/5 text-capture/80 border-capture/10'+ : 'bg-codegen/5 text-codegen/80 border-codegen/10'+ }`}+ >+ <span className="opacity-60">Current:</span>+ <span className="truncate">{state.current_task}</span>+ </div>+ )}</div>- </header>- {/* Sub-header with session selector and action button */}- <div className="flex items-center justify-between px-4 py-2 border-b border-border/30 bg-[#0a0a0a]/90">- <SessionSelector- sessions={state.sessions || []}- activeSessionId={state.activeSessionId}- isCapturing={state.capturing}- onCreateSession={handleCreateSession}- onSwitchSession={handleSwitchSession}- onDeleteSession={handleDeleteSession}- onRenameSession={handleRenameSession}- />-- {/* Action Button based on mode */}- {state.mode === 'capture' ? (+ <div className="flex items-center gap-2 flex-shrink-0">+ {/* Icon-based Trigger Button */}<Tooltip.Root><Tooltip.Triggerrender={<Button- onClick={toggleCapture}- className={`px-3 py-1.5 rounded text-[11px] font-bold uppercase tracking-widest transition-all ${state.capturing- ? 'text-primary bg-primary/10 hover:bg-primary/20'- : 'text-white/60 hover:text-white hover:bg-white/10'- }`}+ onClick={state.mode === 'capture' ? toggleCapture : toggleCodegen}+ className={`p-1.5 rounded-lg cursor-pointer transition-all duration-200 ${isActive+ ? state.mode === 'capture'+ ? 'text-capture bg-capture/10 hover:bg-capture/20'+ : 'text-codegen bg-codegen/10 hover:bg-codegen/20'+ : 'text-white/60 hover:text-white hover:bg-white/10'+ }`}+ aria-label={+ state.mode === 'capture'+ ? state.capturing ? 'Stop capture' : 'Start capture'+ : state.codegenActive ? 'Stop recording' : 'Start recording'+ }>- {state.capturing ? 'Stop Capture' : 'Start Capture'}+ {isActive ? (+ <StopIcon className="w-4 h-4" />+ ) : (+ <PlayIcon className="w-4 h-4" />+ )}</Button>}/><Tooltip.Portal><Tooltip.Positioner sideOffset={4}>- <Tooltip.Popup className="bg-background-secondary text-white text-[10px] px-2 py-1 rounded shadow-lg border border-border z-[100] font-mono">- {state.capturing ? 'Stop recording' : 'Start recording'}- {state.stats.total > 0 && ` (${state.stats.total} requests)`}+ <Tooltip.Popup className="bg-background-elevated text-white text-caption px-2 py-1 rounded-lg z-[100] font-mono">+ {state.mode === 'capture'+ ? state.capturing+ ? `Stop recording (${state.stats.total} requests)`+ : 'Start recording traffic'+ : state.codegenActive+ ? 'Stop code generation'+ : 'Start generating code'}</Tooltip.Popup></Tooltip.Positioner></Tooltip.Portal></Tooltip.Root>- ) : (- <Button- onClick={toggleCodegen}- className={`px-3 py-1.5 rounded text-[11px] font-bold uppercase tracking-widest transition-all ${state.codegenActive- ? 'text-green-400 bg-green-400/10 hover:bg-green-400/20'- : 'text-white/60 hover:text-white hover:bg-white/10'- }`}- >- {state.codegenActive ? 'Stop Recording' : 'Start Recording'}- </Button>- )}- </div>++ {/* Settings Button */}+ <Tooltip.Root>+ <Tooltip.Trigger+ render={+ <Button+ onClick={() => setShowSettings(true)}+ className="p-1.5 rounded-lg cursor-pointer transition-all duration-200 text-white/60 hover:text-white hover:bg-white/10"+ aria-label="Open settings"+ >+ <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2}>+ <path strokeLinecap="round" strokeLinejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />+ <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />+ </svg>+ </Button>+ }+ />+ <Tooltip.Portal>+ <Tooltip.Positioner sideOffset={4}>+ <Tooltip.Popup className="bg-background-elevated text-white text-caption px-2 py-1 rounded-lg z-[100] font-mono">+ Settings+ </Tooltip.Popup>+ </Tooltip.Positioner>+ </Tooltip.Portal>+ </Tooltip.Root>+ </div>+ </header>{/* Native host warning */}{!state.nativeHostConnected && state.mode === 'capture' && (- <div className="mx-4 mt-4 p-3 border border-primary/50 bg-primary/5 rounded">+ <div className="mx-4 mt-4 p-3 bg-capture/5 rounded-xl border border-capture/10"><div className="flex items-start gap-3"><WarningIcon /><div className="flex-1 min-w-0">- <p className="text-xs font-bold text-primary uppercase tracking-tighter">Connection Error</p>- <p className="text-[10px] text-text-secondary mt-1 leading-relaxed">+ <p className="text-small font-bold text-capture uppercase tracking-tight">Connection Error</p>+ <p className="text-caption text-text-secondary mt-1 leading-relaxed">Native host not found. Execute:- <code className="block mt-1 bg-black p-1.5 rounded text-primary border border-primary/20">reverse-api-engineer install-host</code>+ <code className="block mt-1 bg-background-elevated p-1.5 rounded-lg text-capture/80 font-mono">+ reverse-api-engineer install-host+ </code></p><ButtononClick={checkNativeHost}- className="mt-2 text-[10px] text-white hover:text-primary transition-colors font-bold underline font-sans"+ className="mt-2 text-caption text-white hover:text-capture transition-colors font-bold underline cursor-pointer"+ aria-label="Retry connection to native host">{'>'} Retry connection</Button>@@ -425,8 +506,8 @@ export function SidePanel() {{/* Traffic Count indicator (when capturing) */}{state.mode === 'capture' && state.stats.total > 0 && (<div className="px-4 pt-4 pb-0 flex justify-end">- <div className="text-[9px] font-bold text-text-secondary uppercase tracking-widest border border-border/50 px-2 py-0.5 rounded-full bg-white/5">- Traffic captured: <span className="text-white">{state.stats.total}</span>+ <div className="text-tiny text-text-secondary px-2 py-0.5 rounded-full bg-muted border border-border">+ Traffic captured: <span className="text-white font-bold">{state.stats.total}</span></div></div>)}@@ -434,13 +515,69 @@ export function SidePanel() {{/* Main content area - conditional based on mode */}{state.mode === 'codegen' ? (/* Codegen Mode - Show code display */- <div className="flex-1 overflow-hidden p-4">- <CodeDisplay- code={state.codegenScript || ''}- language="python"- title="Playwright Script"- isLive={state.codegenActive}- />+ <div className="flex-1 overflow-hidden flex flex-col">+ {/* Dual save completion notification */}+ {(codegenSavedPath || codegenVisiblePath) && (+ <div className="mx-3 mb-2 px-3 py-3 bg-[#3b82f6]/10 border border-[#3b82f6]/30 rounded-lg">+ <div className="flex items-center gap-2 mb-2">+ <Tick02Icon className="w-4 h-4 text-[#3b82f6] flex-shrink-0" />+ <span className="text-sm text-white font-medium">Script saved (dual location)</span>+ </div>++ {/* Visible location - Primary */}+ {codegenVisiblePath && (+ <div className="mb-2">+ <div className="text-xs text-white/60 mb-1">Visible (easy to find):</div>+ <div className="flex items-center gap-2">+ <button+ onClick={() => {+ navigator.clipboard.writeText(codegenVisiblePath)+ showWarning('Path copied to clipboard')+ }}+ className="text-xs text-[#3b82f6] hover:text-[#3b82f6]/80 font-mono truncate flex-1 text-left"+ title={codegenVisiblePath}+ >+ {codegenVisibleDirectory ? codegenVisibleDirectory.split('/').slice(-2).join('/') : codegenVisiblePath.split('/').slice(-3).join('/')}+ </button>+ <button+ onClick={() => {+ if (codegenVisibleDirectory) {+ // Open folder in file manager (would need native host support)+ navigator.clipboard.writeText(codegenVisibleDirectory)+ showWarning('Folder path copied')+ }+ }}+ className="text-xs bg-[#3b82f6]/20 hover:bg-[#3b82f6]/30 text-[#3b82f6] px-2 py-1 rounded transition-colors"+ >+ Copy+ </button>+ </div>+ </div>+ )}++ {/* Hidden location - Secondary */}+ {codegenSavedPath && (+ <div>+ <div className="text-xs text-white/40 mb-1">Hidden (for sync/history):</div>+ <button+ onClick={() => {+ navigator.clipboard.writeText(codegenSavedPath)+ showWarning('Hidden path copied')+ }}+ className="text-xs text-white/40 hover:text-white/60 font-mono truncate"+ title={codegenSavedPath}+ >+ {codegenSavedPath.split('/').slice(-4).join('/')}+ </button>+ </div>+ )}+ </div>+ )}+ <div className="flex-1 pb-3">+ <CodeBlock language="python" filename="playwright_script.py">+ {state.codegenScript || ''}+ </CodeBlock>+ </div></div>) : (/* Capture Mode - Show chat area */@@ -465,7 +602,7 @@ export function SidePanel() {{msg.role === 'user' ? (<>{msgIdx > 0 && (- <div className="border-t border-primary/30 my-6"></div>+ <div className="h-px bg-primary/10 my-6"></div>)}<div className="flex items-start gap-3 w-full"><span className="text-primary font-bold mt-0.5 select-none flex-shrink-0">{'>'}</span>@@ -490,12 +627,23 @@ export function SidePanel() {</div>{/* Chat input */}- <div className="relative border-t border-border/30 bg-[#0a0a0a]">+ <div className="relative bg-background">{warningMessage && (- <div className="absolute bottom-full left-0 right-0 px-4 py-2 bg-primary/20 backdrop-blur-sm border-t border-primary/30 animate-in slide-in-from-bottom-2 duration-200">+ <div+ className={`absolute bottom-full left-0 right-0 px-4 py-2 backdrop-blur-sm animate-slide-in-from-bottom ${state.mode === 'capture' ? 'bg-capture/10' : 'bg-codegen/10'+ }`}+ ><div className="flex items-center gap-2">- <div className="w-1 h-1 bg-primary rounded-full" />- <span className="text-[10px] font-medium text-primary uppercase tracking-wider">{warningMessage}</span>+ <div+ className={`w-1 h-1 rounded-full ${state.mode === 'capture' ? 'bg-capture' : 'bg-codegen'+ }`}+ />+ <span+ className={`text-tiny ${state.mode === 'capture' ? 'text-capture' : 'text-codegen'+ }`}+ >+ {warningMessage}+ </span></div></div>)}@@ -511,19 +659,95 @@ export function SidePanel() {? 'Capture traffic to begin': 'Build an API client...'}+ mode={state.mode}/></div></>)}++ {/* Settings Modal */}+ {showSettings && (+ <div className="absolute inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center">+ <div className="bg-background border border-border rounded-xl p-6 w-80 max-w-[90vw] shadow-2xl">+ <div className="flex items-center justify-between mb-4">+ <h2 className="text-lg font-semibold text-white">Settings</h2>+ <button+ onClick={() => setShowSettings(false)}+ className="text-white/60 hover:text-white p-1"+ >+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />+ </svg>+ </button>+ </div>++ {/* Save Location Setting */}+ <div className="space-y-3">+ <label className="text-sm text-white/80 block">Save Location</label>++ <div className="space-y-2">+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="saveLocation"+ checked={settings.saveLocation === 'downloads'}+ onChange={() => {+ const newSettings = { ...settings, saveLocation: 'downloads' as const }+ setSettings(newSettings)+ chrome.runtime.sendMessage({ type: 'saveSettings', settings: newSettings })+ }}+ className="w-4 h-4 accent-primary"+ />+ <span className="text-sm text-white/70">Downloads folder (default)</span>+ </label>++ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="radio"+ name="saveLocation"+ checked={settings.saveLocation !== 'downloads'}+ onChange={() => {+ const customPath = prompt('Enter custom folder path:', '/Users/')+ if (customPath) {+ const newSettings = { ...settings, saveLocation: customPath }+ setSettings(newSettings)+ chrome.runtime.sendMessage({ type: 'saveSettings', settings: newSettings })+ }+ }}+ className="w-4 h-4 accent-primary"+ />+ <span className="text-sm text-white/70">Custom folder</span>+ </label>+ </div>++ {settings.saveLocation !== 'downloads' && (+ <div className="mt-2 p-2 bg-background-elevated rounded-lg">+ <div className="text-xs text-white/50 mb-1">Current path:</div>+ <div className="text-xs text-white/80 font-mono break-all">{settings.saveLocation}</div>+ </div>+ )}+ </div>++ <div className="mt-6 pt-4 border-t border-border">+ <button+ onClick={() => setShowSettings(false)}+ className="w-full py-2 bg-primary/20 hover:bg-primary/30 text-primary rounded-lg text-sm font-medium transition-colors"+ >+ Done+ </button>+ </div>+ </div>+ </div>+ )}</div>)}function WarningIcon(): JSX.Element {return (- <div className="text-primary flex-shrink-0">- <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">- <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />+ <div className="text-capture flex-shrink-0">+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">+ <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg></div>)diff --git a/chrome-extension/tailwind.config.js b/chrome-extension/tailwind.config.jsindex 91f1cc9..f5d5207 100644--- a/chrome-extension/tailwind.config.js+++ b/chrome-extension/tailwind.config.js@@ -6,21 +6,121 @@ export default {theme: {extend: {colors: {- primary: '#ef4444',+ // Dual accent system+ capture: {+ DEFAULT: '#ef4444',+ hover: '#dc2626',+ light: '#fef2f2',+ },+ codegen: {+ DEFAULT: '#22c55e',+ hover: '#16a34a',+ light: '#f0fdf4',+ },+ // Core colors+ primary: {+ DEFAULT: '#ef4444', // Default to capture color+ foreground: '#ffffff',+ },background: {- DEFAULT: '#0a0a0a',- secondary: '#1a1a1a',+ DEFAULT: '#000000',+ secondary: '#0a0a0a',+ elevated: '#050505',+ },+ border: {+ DEFAULT: '#111111',+ active: '#1a1a1a',},- border: '#2a2a2a',text: {- primary: '#ffffff',- secondary: '#a0a0a0',+ primary: '#e5e5e5',+ secondary: '#737373',+ muted: '#525252',+ disabled: '#404040',+ },+ card: {+ DEFAULT: '#050505',+ foreground: '#e5e5e5',+ },+ muted: {+ DEFAULT: '#0a0a0a',+ foreground: '#525252',+ },+ accent: {+ DEFAULT: '#0a0a0a',+ foreground: '#e5e5e5',+ },+ ring: '#ef4444',+ input: '#111111',+ foreground: '#e5e5e5',+ // Semantic colors+ destructive: {+ DEFAULT: '#ef4444',+ foreground: '#ffffff',+ },+ success: {+ DEFAULT: '#22c55e',+ foreground: '#ffffff',+ },+ warning: {+ DEFAULT: '#f59e0b',+ foreground: '#ffffff',+ },+ info: {+ DEFAULT: '#3b82f6',+ foreground: '#ffffff',},},fontFamily: {- sans: ['ui-sans-serif', 'system-ui', '-apple-system', 'BlinkMacSystemFont', '"Segoe UI"', 'Roboto', '"Helvetica Neue"', 'Arial', '"Noto Sans"', 'sans-serif'],- poppins: ['Poppins', 'sans-serif'],- mono: ['SF Mono', 'Monaco', 'Cascadia Code', 'monospace'],+ sans: [+ '-apple-system',+ 'BlinkMacSystemFont',+ '"Segoe UI"',+ 'Roboto',+ '"Helvetica Neue"',+ 'Arial',+ 'sans-serif',+ '"Apple Color Emoji"',+ '"Segoe UI Emoji"'+ ],+ heading: [+ 'ui-monospace',+ 'SFMono-Regular',+ '"SF Mono"',+ 'Menlo',+ 'Monaco',+ 'Consolas',+ '"Liberation Mono"',+ '"Courier New"',+ 'monospace'+ ],+ mono: [+ 'ui-monospace',+ 'SFMono-Regular',+ '"SF Mono"',+ 'Menlo',+ 'Monaco',+ 'Consolas',+ '"Liberation Mono"',+ '"Courier New"',+ 'monospace'+ ],+ },+ fontSize: {+ 'tiny': ['11px', { lineHeight: '1.3', letterSpacing: '0.03em', fontWeight: '600' }],+ 'caption': ['11px', { lineHeight: '1.5', letterSpacing: '0.02em', fontWeight: '500' }],+ 'small': ['12px', { lineHeight: '1.5', fontWeight: '500' }],+ 'base': ['14px', { lineHeight: '1.5', fontWeight: '400' }],+ 'code': ['13px', { lineHeight: '1.5', fontWeight: '400' }],+ },+ animation: {+ 'pulse-slow': 'pulse 1.5s ease-in-out infinite',+ 'slide-in-from-bottom': 'slide-in-from-bottom 200ms ease-out',+ },+ keyframes: {+ 'slide-in-from-bottom': {+ 'from': { transform: 'translateY(8px)', opacity: '0' },+ 'to': { transform: 'translateY(0)', opacity: '1' },+ },},},},diff --git a/chrome-extension/tsconfig.json b/chrome-extension/tsconfig.jsonindex a4c834a..24a8d73 100644--- a/chrome-extension/tsconfig.json+++ b/chrome-extension/tsconfig.json@@ -2,7 +2,11 @@"compilerOptions": {"target": "ES2020","useDefineForClassFields": true,- "lib": ["ES2020", "DOM", "DOM.Iterable"],+ "lib": [+ "ES2020",+ "DOM",+ "DOM.Iterable"+ ],"module": "ESNext","skipLibCheck": true,"moduleResolution": "bundler",@@ -14,7 +18,15 @@"strict": true,"noUnusedLocals": true,"noUnusedParameters": true,- "noFallthroughCasesInSwitch": true+ "noFallthroughCasesInSwitch": true,+ "baseUrl": ".",+ "paths": {+ "@/*": [+ "./src/*"+ ]+ }},- "include": ["src"]-}+ "include": [+ "src"+ ]+}\ No newline at end of filediff --git a/pyproject.toml b/pyproject.tomlindex 933b319..e35ac7c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -33,6 +33,7 @@ dependencies = ["aiohttp>=3.12.15","watchdog>=3.0.0","setproctitle>=1.3.0",+ "sprites-py>=0.0.1a1",][project.optional-dependencies]diff --git a/src/reverse_api/auto_engineer.py b/src/reverse_api/auto_engineer.pyindex 179f69f..1697bc4 100644--- a/src/reverse_api/auto_engineer.py+++ b/src/reverse_api/auto_engineer.py@@ -577,3 +577,5 @@ class OpenCodeAutoEngineer(OpenCodeEngineer):debug_log(f"Cleaned up MCP server: {self.mcp_name}")except Exception:pass # Ignore cleanup errors++# https://www.migros.ch/fr/category/home\ No newline at end of filediff --git a/src/reverse_api/base_engineer.py b/src/reverse_api/base_engineer.pyindex 35d4189..4e93cac 100644--- a/src/reverse_api/base_engineer.py+++ b/src/reverse_api/base_engineer.py@@ -240,7 +240,7 @@ After your analysis, generate the files:7. **Handle bot detection**:- If you encounter bot detection, CAPTCHA, or anti-scraping measures with `requests`- - Consider switching to Playwright with CDP (Chrome DevTools Protocol)+ - Consider switching to Playwright with CDP (Chrome DevTools Protocol) or using httpcloak- Use the real user browser context to bypass detection- Maintain the same code quality standards regardless of approachdiff --git a/src/reverse_api/native_host.py b/src/reverse_api/native_host.pyindex bad342c..c140c69 100644--- a/src/reverse_api/native_host.py+++ b/src/reverse_api/native_host.py@@ -11,20 +11,23 @@ Native messaging uses stdin/stdout with length-prefixed JSON messages:import asyncioimport json-import osimport platform+import reimport shutilimport structimport sys+from datetime import datetimefrom pathlib import Pathfrom typing import Anyfrom .config import ConfigManagerfrom .utils import (- generate_run_id,+ extract_domain_from_har,+ get_app_dir,+ get_downloads_dir,get_har_dir,get_scripts_dir,- get_app_dir,+ get_visible_save_path,)HOST_NAME = "com.reverse_api.engineer"@@ -64,7 +67,6 @@ def _find_python_interpreter() -> str:Raises:RuntimeError: If no suitable Python interpreter is found"""- import subprocess# First, try the current interpreter (the one running this code)current_python = sys.executable@@ -359,7 +361,7 @@ class NativeHostHandler:# Save without indentation to improve I/O performance and slightly reduce size.# Note: If HAR data embeds response bodies, the overall file can still be very large;# this function only controls JSON formatting, not how bodies are stored.- har_path.write_text(json.dumps(har_data, separators=(',', ':')))+ har_path.write_text(json.dumps(har_data, separators=(",", ":")))self.current_run_id = run_id@@ -496,6 +498,126 @@ class NativeHostHandler:"_callbackId": message.get("_callbackId"),}+ def handle_save_codegen_script(self, message: dict[str, Any]) -> dict[str, Any]:+ """Save codegen script to both hidden and visible locations (dual save)."""+ try:+ run_id = message.get("run_id")+ script_content = message.get("script")+ filename = message.get("filename", "codegen_script.py")+ save_location = message.get("save_location", "downloads")+ domain = message.get("domain")++ if not run_id or not script_content:+ return {+ "success": False,+ "error": "Missing run_id or script content",+ "_callbackId": message.get("_callbackId"),+ }++ # Validate run_id (alphanumeric, hyphens, underscores only)+ if not re.match(r"^[a-zA-Z0-9_-]{1,64}$", run_id):+ return {+ "success": False,+ "error": "Invalid run_id format",+ "_callbackId": message.get("_callbackId"),+ }++ # === DUAL SAVE: HIDDEN LOCATION ===+ # Save to ~/.reverse-api/runs/scripts/{run_id}/ (ID-based for history/sync)+ scripts_dir = get_scripts_dir(run_id)+ scripts_dir.mkdir(parents=True, exist_ok=True)++ # Save script file to hidden location+ hidden_script_path = scripts_dir / filename+ hidden_script_path.write_text(script_content, encoding="utf-8")++ # Create README with metadata in hidden location+ readme_path = scripts_dir / "README.md"+ readme_content = f"""# Codegen Script++Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}+Run ID: {run_id}++## Usage++```bash+python {filename}+```++This script was generated by the Reverse API Engineer Chrome Extension's codegen feature.+"""+ readme_path.write_text(readme_content, encoding="utf-8")++ # === DUAL SAVE: VISIBLE LOCATION ===+ # Determine base directory for visible save+ if save_location == "downloads":+ visible_base_dir = get_downloads_dir()+ else:+ # Custom path provided+ try:+ visible_base_dir = Path(save_location)+ visible_base_dir.mkdir(parents=True, exist_ok=True)+ except Exception as e:+ # Fallback to downloads if custom path is invalid+ print(f"Warning: Invalid save_location '{save_location}', falling back to downloads: {e}")+ visible_base_dir = get_downloads_dir()++ # Extract domain if not provided (from HAR or use run_id)+ if not domain:+ har_path = get_har_dir(run_id) / "recording.har"+ if har_path.exists():+ domain = extract_domain_from_har(har_path)+ if not domain:+ # Fallback: extract from run_id (e.g., "crx-abc123-domain.com" -> "domain_com")+ domain_match = re.search(r"[a-zA-Z0-9_-]+\.([a-zA-Z]{2,})", run_id)+ domain = domain_match.group(0) if domain_match else "unknown"++ # Generate visible save path with auto-increment suffix+ visible_dir = get_visible_save_path(domain, visible_base_dir)++ # Save script to visible location+ visible_script_path = visible_dir / filename+ visible_script_path.write_text(script_content, encoding="utf-8")++ # Create README in visible location too+ visible_readme_path = visible_dir / "README.md"+ visible_readme_content = f"""# Codegen Script++Generated: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}+Domain: {domain}+Run ID: {run_id}++## Files++- `{filename}` - The generated Playwright script++## Usage++```bash+python {filename}+```++This script was generated by the Reverse API Engineer Chrome Extension.+"""+ visible_readme_path.write_text(visible_readme_content, encoding="utf-8")++ return {+ "success": True,+ "hidden_path": str(hidden_script_path),+ "visible_path": str(visible_script_path),+ "hidden_directory": str(scripts_dir),+ "visible_directory": str(visible_dir),+ "domain": domain,+ "_callbackId": message.get("_callbackId"),+ }++ except Exception as e:+ return {+ "success": False,+ "error": str(e),+ "_callbackId": message.get("_callbackId"),+ }+def handle_chat(self, message: dict) -> dict:"""Handle chat message - streams agent events back to extension."""user_message = message.get("message")@@ -533,10 +655,11 @@ class NativeHostHandler:ClaudeSDKClient,ResultMessage,TextBlock,+ ThinkingBlock,ToolResultBlock,ToolUseBlock,- ThinkingBlock,)+from .utils import get_har_dir, get_scripts_dirhar_dir = get_har_dir(run_id)@@ -545,7 +668,7 @@ class NativeHostHandler:if not har_path.exists():return {"type": "error",- "message": f"No HAR file found. Please capture traffic first.",+ "message": "No HAR file found. Please capture traffic first.","_callbackId": message.get("_callbackId"),}@@ -734,6 +857,7 @@ The HAR content is available at the path above. Use the Read tool to analyze it."saveHar": self.handle_save_har,"generate": self.handle_generate,"chat": self.handle_chat,+ "saveCodegenScript": self.handle_save_codegen_script,}handler = handlers.get(msg_type)diff --git a/src/reverse_api/opencode_engineer.py b/src/reverse_api/opencode_engineer.pyindex 47e7c84..244e9e3 100644--- a/src/reverse_api/opencode_engineer.py+++ b/src/reverse_api/opencode_engineer.py@@ -121,6 +121,8 @@ class OpenCodeEngineer(BaseEngineer):self._last_error: str | None = Noneself._session_id: str | None = Noneself._last_event_time = 0.0+ self._work_started = False # Track if any real work has been done+ self._busy_time: float | None = None # When session became busy# Read OpenCode server authentication from environment variablesself.opencode_password = os.environ.get("OPENCODE_SERVER_PASSWORD")@@ -359,21 +361,33 @@ class OpenCodeEngineer(BaseEngineer):attempt = status.get("attempt", 1)message = status.get("message", "")self.opencode_ui.session_retry(attempt, message)+ elif status_type == "busy":+ import time++ self._busy_time = time.time()+ self.opencode_ui.session_status(status_type)else:self.opencode_ui.session_status(status_type)if status_type == "idle":+ # Check if this is suspiciously fast (< 1 second of work)+ import time++ if self._busy_time and (time.time() - self._busy_time) < 1.0 and not self._work_started:+ debug_log("Suspiciously fast idle - checking for errors")+ # Try to get session details to check for error+ await self._check_session_error(client)debug_log("Our session status is idle, returning!")return # Done!- elif event_type == "permission.updated":+ elif event_type == "permission.updated" or event_type == "permission.asked":# Auto-approve permissions so the agent can proceedpermission_id = properties.get("id")perm_session = properties.get("sessionID")perm_type = properties.get("type", "")perm_title = properties.get("title", "")- debug_log(f"permission.updated: id={permission_id}, type={perm_type}, title={perm_title}")+ debug_log(f"{event_type}: id={permission_id}, type={perm_type}, title={perm_title}")if perm_session == self._session_id and permission_id:# Show permission request in UI@@ -437,6 +451,13 @@ class OpenCodeEngineer(BaseEngineer):provider = error_data.get("providerID", "unknown")msg = error_data.get("message", "Authentication failed")self._last_error = f"Auth error ({provider}): {msg}"+ elif error_name in ("ProviderModelNotFoundError", "ModelNotFoundError"):+ provider = error_data.get("providerID", "unknown")+ model = error_data.get("modelID", "unknown")+ suggestions = error_data.get("suggestions", [])+ self._last_error = f"Model not found: {provider}/{model}"+ if suggestions:+ self._last_error += f"\n Did you mean: {', '.join(suggestions)}?"elif error_name == "APIError":msg = error_data.get("message", "API error")status = error_data.get("statusCode", "")@@ -459,6 +480,62 @@ class OpenCodeEngineer(BaseEngineer):self._last_error = format_error(e)debug_log(f"Exception in _stream_events: {self._last_error}")+ async def _check_session_error(self, client: httpx.AsyncClient):+ """Check session for errors when we get suspiciously fast idle."""+ try:+ # Get the session details to check for errors+ r = await client.get(f"/session/{self._session_id}")+ if r.status_code == 200:+ session_data = r.json()+ debug_log(f"Session data: {session_data}")++ # Check for error in session status+ status = session_data.get("status", {})+ if status.get("type") == "error":+ error = status.get("error", {})+ error_name = error.get("name", "UnknownError")+ error_data = error.get("data", {})++ if error_name in ("ProviderModelNotFoundError", "ModelNotFoundError"):+ provider = error_data.get("providerID", "unknown")+ model = error_data.get("modelID", "unknown")+ suggestions = error_data.get("suggestions", [])+ self._last_error = f"Model not found: {provider}/{model}"+ if suggestions:+ self._last_error += f"\n Did you mean: {', '.join(suggestions)}?"+ else:+ msg = error_data.get("message", "") if isinstance(error_data, dict) else str(error_data)+ self._last_error = f"{error_name}: {msg}" if msg else error_name++ if self._last_error:+ self.opencode_ui.error(self._last_error)++ # Also check messages for errors+ msg_r = await client.get(f"/session/{self._session_id}/message")+ if msg_r.status_code == 200:+ messages = msg_r.json()+ # Look for error messages+ for msg in messages:+ info = msg.get("info", {})+ if info.get("role") == "assistant":+ # Check parts for error info+ for part in msg.get("parts", []):+ if part.get("type") == "error":+ error_data = part.get("error", {})+ error_name = error_data.get("name", "Error")++ if error_name in ("ProviderModelNotFoundError", "ModelNotFoundError"):+ provider = error_data.get("data", {}).get("providerID", "unknown")+ model = error_data.get("data", {}).get("modelID", "unknown")+ suggestions = error_data.get("data", {}).get("suggestions", [])+ self._last_error = f"Model not found: {provider}/{model}"+ if suggestions:+ self._last_error += f"\n Did you mean: {', '.join(suggestions)}?"+ self.opencode_ui.error(self._last_error)+ return+ except Exception as e:+ debug_log(f"Error checking session: {e}")+async def _handle_part_update(self, properties: dict, seen_parts: set):"""Handle message.part.updated events."""part = properties.get("part", {})@@ -468,13 +545,25 @@ class OpenCodeEngineer(BaseEngineer):part_type = part.get("type")part_session = part.get("sessionID")+ debug_log(f"Part update: type={part_type}, session={part_session}, our={self._session_id}")+# Only process parts for our sessionif part_session != self._session_id:+ debug_log(f"Skipping part for other session")returnif part_type == "text":text = part.get("text", "")debug_log(f"Handling text part: id={part_id}, delta={'yes' if delta else 'no'}, len={len(text)}")++ # Filter out known prompt text patterns that get echoed back+ # This prevents the tag context section from appearing in streaming output+ # Check for the specific tag context pattern that appears at the end of prompts+ tag_context_pattern = "By default, treat this as an iterative refinement"+ if tag_context_pattern in text and "Note: Full message history is available" in text:+ debug_log(f"Filtering out echoed tag context from streaming output")+ return+# Use delta for incremental updates if availableself.opencode_ui.update_text(text, delta)@@ -491,6 +580,7 @@ class OpenCodeEngineer(BaseEngineer):debug_log(f"Handling tool part: id={part_id}, tool={tool_name}, status={status}")if status == "running" and part_id not in seen_parts:+ self._work_started = True # Mark that real work has startedseen_parts.add(part_id)tool_input = state.get("input", {})self.opencode_ui.tool_start(tool_name, tool_input)@@ -542,6 +632,10 @@ class OpenCodeEngineer(BaseEngineer):self.usage_metadata["cache_creation_tokens"] = self.usage_metadata.get("cache_creation_tokens", 0) + cache_writeself.usage_metadata["cost"] = self.usage_metadata.get("cost", 0) + cost+ else:+ # Log unhandled part types for debugging+ debug_log(f"Unhandled part type: {part_type}")+def run_opencode_engineering(run_id: str,diff --git a/src/reverse_api/opencode_ui.py b/src/reverse_api/opencode_ui.pyindex 1439314..d5d7f28 100644--- a/src/reverse_api/opencode_ui.py+++ b/src/reverse_api/opencode_ui.py@@ -86,6 +86,18 @@ class OpenCodeUI:"""Build the current display state."""display = Text()+ # Show current text (LLM output/thinking) - last few lines+ if self._current_text:+ # Show last portion of text to keep display manageable+ lines = self._current_text.strip().split("\n")+ # Show last 8 lines+ display_lines = lines[-8:] if len(lines) > 8 else lines+ for line in display_lines:+ # Truncate long lines+ if len(line) > 100:+ line = line[:97] + "..."+ display.append(f" {line}\n", style=THEME_DIM)+# Show current tool if runningif self._current_tool and self._tool_status == "running":display.append(" ⟳ ", style=THEME_PRIMARY)@@ -341,8 +353,9 @@ class OpenCodeUI:self.console.print(f" [dim]⟳ sync: active → {dest_dir}[/dim]")def sync_flash(self, message: str) -> None:- """Display a brief sync notification."""- self.console.print(f" [dim]✓ {message}[/dim]")+ """Display a brief sync notification (silenced to reduce noise)."""+ # Silenced - too noisy when many files sync+ passdef sync_error(self, message: str) -> None:"""Display a sync error."""diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.pyindex aac5f48..03ed50b 100644--- a/src/reverse_api/utils.py+++ b/src/reverse_api/utils.py@@ -1,6 +1,7 @@"""Utility functions for run ID generation and path management."""import asyncio+import platformimport reimport uuidfrom datetime import datetime@@ -433,9 +434,7 @@ def get_har_dir(run_id: str, output_dir: str | None = None) -> Path:# Allow alphanumeric characters, hyphens, and underscores# Chrome extension IDs start with crx- followed by UUID-style formatif not re.match(r"^[a-zA-Z0-9_-]+$", run_id):- raise ValueError(- f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed"- )+ raise ValueError(f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed")# Limit length to prevent extremely long pathsif len(run_id) > 64:@@ -483,9 +482,7 @@ def get_scripts_dir(run_id: str, output_dir: str | None = None) -> Path:# Allow alphanumeric characters, hyphens, and underscores# Chrome extension IDs start with crx- followed by UUID-style formatif not re.match(r"^[a-zA-Z0-9_-]+$", run_id):- raise ValueError(- f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed"- )+ raise ValueError(f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed")# Limit length to prevent extremely long pathsif len(run_id) > 64:@@ -527,9 +524,7 @@ def get_docs_dir(run_id: str, output_dir: str | None = None) -> Path:# Allow alphanumeric characters, hyphens, and underscores# Chrome extension IDs start with crx- followed by UUID-style formatif not re.match(r"^[a-zA-Z0-9_-]+$", run_id):- raise ValueError(- f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed"- )+ raise ValueError(f"Invalid run_id: {run_id}. Only alphanumeric characters, hyphens, and underscores are allowed")# Limit length to prevent extremely long pathsif len(run_id) > 64:@@ -576,3 +571,127 @@ def get_collected_dir(folder_name: str) -> Path:path = Path.cwd() / "collected" / folder_namepath.mkdir(parents=True, exist_ok=True)return path+++def get_downloads_dir() -> Path:+ """Get the user's Downloads folder path (cross-platform).++ Returns:+ Path to the Downloads directory+ """+ system = platform.system()+ home = Path.home()++ if system == "Windows":+ # Windows: Use USERPROFILE environment variable+ import os++ user_profile = os.environ.get("USERPROFILE", str(home))+ downloads = Path(user_profile) / "Downloads"+ elif system == "Darwin": # macOS+ downloads = home / "Downloads"+ else: # Linux and others+ downloads = home / "Downloads"++ # Fallback to home/Downloads if the standard location doesn't exist+ if not downloads.exists():+ downloads = home / "Downloads"++ downloads.mkdir(parents=True, exist_ok=True)+ return downloads+++def sanitize_domain(domain: str) -> str:+ """Clean domain name for use in folder names.++ Args:+ domain: Raw domain (e.g., "api.github.com", "www.example.com")++ Returns:+ Clean domain string (e.g., "api_github_com", "example_com")+ """+ # Remove www. prefix+ domain = re.sub(r"^www\.", "", domain)+ # Remove common TLDs for cleaner names+ domain = re.sub(r"\.(com|org|net|io|co|app|dev)$", "", domain)+ # Replace dots and other invalid chars with underscores+ domain = re.sub(r"[^a-zA-Z0-9]", "_", domain)+ # Collapse multiple underscores+ domain = re.sub(r"_+", "_", domain)+ # Strip leading/trailing underscores+ domain = domain.strip("_")+ return domain.lower()[:50] # Limit length+++def get_visible_save_path(domain: str, base_dir: Path | str, suffix: int = 0) -> Path:+ """Generate a visible save path with unique naming.++ Creates folder names like: rae_github_com_2025-02-02+ If folder exists and has content, appends _1, _2, etc.++ Args:+ domain: Domain name (will be sanitized)+ base_dir: Base directory (e.g., Downloads or custom path)+ suffix: Current suffix number for recursion (start with 0)++ Returns:+ Path object ready for use (directory created)+ """+ if isinstance(base_dir, str):+ base_dir = Path(base_dir)++ # Sanitize domain+ clean_domain = sanitize_domain(domain)+ if not clean_domain:+ clean_domain = "unknown"++ # Get current date+ date_str = datetime.now().strftime("%Y-%m-%d")++ # Build folder name+ suffix_str = f"_{suffix}" if suffix > 0 else ""+ folder_name = f"rae_{clean_domain}_{date_str}{suffix_str}"++ # Build full path+ path = base_dir / folder_name++ # Check if exists and has content (non-empty)+ if path.exists() and any(path.iterdir()):+ # Recursively try next suffix+ return get_visible_save_path(domain, base_dir, suffix + 1)++ # Create directory+ path.mkdir(parents=True, exist_ok=True)+ return path+++def extract_domain_from_har(har_path: Path) -> str | None:+ """Extract the primary domain from a HAR file.++ Args:+ har_path: Path to the HAR file++ Returns:+ Domain string or None if extraction fails+ """+ try:+ import json++ with open(har_path) as f:+ har_data = json.load(f)++ entries = har_data.get("log", {}).get("entries", [])+ if not entries:+ return None++ # Get domain from first entry's URL+ first_url = entries[0].get("request", {}).get("url", "")+ if first_url:+ from urllib.parse import urlparse++ parsed = urlparse(first_url)+ return parsed.netloc++ return None+ except Exception:+ return Nonediff --git a/uv.lock b/uv.lockindex 1c61a0a..f65f2d4 100644--- a/uv.lock+++ b/uv.lock@@ -1995,7 +1995,7 @@ wheels = [[[package]]name = "reverse-api-engineer"-version = "0.3.0"+version = "0.3.2"source = { editable = "." }dependencies = [{ name = "aiohttp" },@@ -2009,6 +2009,7 @@ dependencies = [{ name = "requests" },{ name = "rich" },{ name = "setproctitle" },+ { name = "sprites-py" },{ name = "watchdog" },]@@ -2046,6 +2047,7 @@ requires-dist = [{ name = "requests", specifier = ">=2.32.5" },{ name = "rich", specifier = ">=13.0.0" },{ name = "setproctitle", specifier = ">=1.3.0" },+ { name = "sprites-py", specifier = ">=0.0.1a1" },{ name = "stagehand", marker = "extra == 'agent'" },{ name = "watchdog", specifier = ">=3.0.0" },]@@ -2323,6 +2325,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/48/f3/b67d6ea49ca9154453b6d70b34ea22f3996b9fa55da105a79d8732227adc/soupsieve-2.8.1-py3-none-any.whl", hash = "sha256:a11fe2a6f3d76ab3cf2de04eb339c1be5b506a8a47f2ceb6d139803177f85434", size = 36710, upload-time = "2025-12-18T13:50:33.267Z" },]+[[package]]+name = "sprites-py"+version = "0.0.1a1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "httpx" },+ { name = "websockets" },+]+sdist = { url = "https://files.pythonhosted.org/packages/0b/6c/6bace1ef983c6bb3466416030a88e465d4170522bca5fe9f24709cd99ec1/sprites_py-0.0.1a1.tar.gz", hash = "sha256:b90168a1eaf98d8d550b2d9b674067e388e3b6c2db5bc4ccfa457f4922c04d73", size = 24269, upload-time = "2026-01-10T06:26:38.7Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/67/47/36e48387e976529e2c92663c3912c3d658f973009dc4a1bf19309ffd441a/sprites_py-0.0.1a1-py3-none-any.whl", hash = "sha256:9568ee1001d1b489985413aed1041f0aa4dbf433b8194eb540aa16e6867a96ac", size = 29610, upload-time = "2026-01-10T06:26:37.19Z" },+]+[[package]]name = "sse-starlette"version = "3.0.4"