feat: add popup and options pages for LexAI extension

- Created index.html for options page with basic structure.
- Implemented Popup component in Popup.tsx with state management for user input and actions.
- Added index.html for popup page with necessary scripts.
- Included various icon assets for the extension.
- Designed SVG icon for the extension with gradient background and lightning bolt.
- Added multiple screenshots for Chrome Web Store listing.
- Configured WXT for building the Chrome extension with manifest settings.
This commit is contained in:
john kevin asprec
2026-08-13 19:16:54 +08:00
parent 8bc529ef2d
commit d63d698b57
17 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,187 @@
import { defineBackground } from 'wxt/utils/define-background';
import { CONFIG_STORAGE_KEYS } from '@lib/types';
import type { AnalyzePayload, LexAIConfig, LexAIResponse } from '@lib/types';
import { CONTEXT_MENU_ENTRIES, findContextMenuEntry, resolvePromptPersona, resolvePromptPattern } from '@lib/actions';
import { decryptApiKey, migratePlaintextApiKey } from '@lib/crypto';
import { callProvider, defaultMaxTokens, getSystemPrompt, listModels, providerLabel } from '@lib/providers';
// Resolve the usable API key from stored config: prefer the encrypted path,
// fall back to plaintext for backward compat. Returns null if none is set.
async function resolveApiKey(config: LexAIConfig): Promise<string | null> {
let apiKey = config.apiKey;
if (config.apiKeyEnc && config.encKey) {
const decrypted = decryptApiKey(config.encKey, config.apiKeyEnc);
if (decrypted) apiKey = decrypted;
}
if (!apiKey || apiKey.trim() === '') return null;
return apiKey.trim();
}
// Options can save a provider change without touching the stored key, which
// leaves e.g. an OpenAI key attached to Groq — every call then fails with the
// provider's own "Invalid API Key". Detect it here and say what to do instead.
// `keyProvider` is absent for keys saved by older builds: unknown, so allow it.
function keyProviderMismatch(config: LexAIConfig, provider: string): string | null {
if (!config.keyProvider || config.keyProvider === provider) return null;
return `Your saved API key was entered for ${providerLabel(config.keyProvider)}, but the selected provider is ${providerLabel(provider)}. Open LexAI Settings and enter a ${providerLabel(provider)} API key.`;
}
// ─── Main handler ─────────────────────────────────────────────────────────────
async function handleAnalyzeText(payload: AnalyzePayload): Promise<LexAIResponse> {
const stored = await chrome.storage.local.get([...CONFIG_STORAGE_KEYS]);
const config = stored as LexAIConfig;
// Prompt requests from the toolbar/context menu carry no explicit params —
// apply the Prompt Builder settings saved from the popup so all entry
// points behave the same. The popup still overrides by sending its own.
if (payload.action === 'prompt' && !payload.promptParams) {
const saved = (await chrome.storage.local.get([
'promptPattern', 'promptStyle', 'promptPersona', 'customPersona', 'promptFormat', 'promptModel',
])) as Record<string, string | undefined>;
payload = {
...payload,
promptParams: {
pattern: resolvePromptPattern(saved.promptPattern, saved.promptStyle),
persona: resolvePromptPersona(saved.promptPersona, saved.customPersona),
format: saved.promptFormat,
},
model: payload.model ?? (saved.promptModel || undefined),
};
}
const apiKey = await resolveApiKey(config);
if (!apiKey) {
return { error: 'No API key configured. Please open LexAI settings (click the extension icon).' };
}
const mismatch = keyProviderMismatch(config, config.provider || 'openai');
if (mismatch) return { error: mismatch };
const resolvedConfig: LexAIConfig = {
...config,
apiKey,
...(payload.model ? { model: payload.model } : {}),
};
const systemPrompt = getSystemPrompt(payload.action, payload.style, payload.promptParams);
// The Prompt Builder's engineered prompts (react/pev/gauntlet skeletons
// especially) run well past defaultMaxTokens' input-scaled floor for a
// short input idea — give the 'prompt' action a higher floor.
const callOpts = payload.action === 'prompt'
? { maxTokens: Math.max(2048, defaultMaxTokens(payload.text)) }
: undefined;
return callProvider(resolvedConfig, payload.text, systemPrompt, callOpts);
}
// ─── Background entry ─────────────────────────────────────────────────────────
export default defineBackground(() => {
console.log('LexAI background service worker started');
// Encrypt any legacy plaintext apiKey left by older builds (no-op otherwise).
// The read path keeps its plaintext fallback, so a failed migration is safe.
migratePlaintextApiKey().catch(() => {});
// ─── Context menus ───────────────────────────────────────────────────────
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.removeAll(() => {
CONTEXT_MENU_ENTRIES.forEach((entry) => {
chrome.contextMenus.create({
id: entry.id,
parentId: entry.parentId,
title: entry.title,
contexts: ['selection'],
});
});
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (!info.selectionText || !tab?.id) return;
const entry = findContextMenuEntry(info.menuItemId.toString());
if (!entry) return;
chrome.tabs.sendMessage(tab.id, {
type: 'lexai-context-menu',
action: entry.action,
text: info.selectionText,
style: entry.style,
});
});
// ─── Message handler ─────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Only our own contexts (content scripts, popup, options) may drive the
// key-bearing call path — ignore anything from another extension.
if (sender.id !== chrome.runtime.id) return;
if (message.type === 'ANALYZE_TEXT') {
// Support both { payload: { text, action, style } } (content.ts) and
// { text, action, style } (popup) formats
const payload: AnalyzePayload = message.payload ?? {
text: message.text as string,
action: message.action as string,
style: message.style as string | undefined,
promptParams: message.promptParams,
model: message.model as string | undefined,
};
handleAnalyzeText(payload)
.then(sendResponse)
.catch((err) => sendResponse({ error: String(err) }));
return true; // Keep channel open for async response
}
if (message.type === 'COPY_AS') {
const { text, format } = message as { text: string; format: string };
chrome.storage.local.get([...CONFIG_STORAGE_KEYS])
.then(async (stored) => {
const config = stored as LexAIConfig;
const apiKey = await resolveApiKey(config);
if (!apiKey) {
sendResponse({ error: 'No API key configured. Please open LexAI settings.' });
return;
}
const mismatch = keyProviderMismatch(config, config.provider || 'openai');
if (mismatch) {
sendResponse({ error: mismatch });
return;
}
const resolvedConfig: LexAIConfig = { ...config, apiKey };
const systemPrompt = `Reformat the following text as ${format}. Return only the reformatted result, no explanation.`;
return callProvider(resolvedConfig, text, systemPrompt);
})
.then((res) => { if (res) sendResponse(res); })
.catch((err) => sendResponse({ error: String(err) }));
return true;
}
if (message.type === 'LIST_MODELS') {
// Prefer an inline key (freshly typed, not yet saved); else use the stored key.
const inlineKey = (message.apiKey as string | undefined)?.trim() || undefined;
(async () => {
// Callers that don't know the provider (content script) omit it —
// fall back to the configured one.
let provider = message.provider as string | undefined;
if (!provider) {
const stored = await chrome.storage.local.get('provider');
provider = (stored.provider as string) || 'openai';
}
let apiKey = inlineKey;
if (!apiKey) {
// Stored-key path: refuse to send a key that belongs to a different
// provider — it would come back as that provider's "invalid key".
const stored = await chrome.storage.local.get(['apiKey', 'apiKeyEnc', 'encKey', 'keyProvider']);
const mismatch = keyProviderMismatch(stored as LexAIConfig, provider);
if (mismatch) return { error: mismatch, keyRejected: true };
apiKey = (await resolveApiKey(stored as LexAIConfig)) ?? undefined;
}
if (!apiKey && provider !== 'openrouter') {
return { error: 'No API key found. Enter your API key above, then click Load models.' };
}
return listModels(provider, apiKey);
})()
.then(sendResponse)
.catch((err) => sendResponse({ error: String(err) }));
return true;
}
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,510 @@
import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { safeSendMessage, safeStorageGet, safeStorageSet } from '@lib/messaging';
import { encryptApiKey, getOrCreateEncKey } from '@lib/crypto';
// ─── Provider config ──────────────────────────────────────────────────────────
// Model lists are fetched live per provider (see loadModels) — no static lists here.
const PROVIDERS = [
{
id: 'openai',
name: 'OpenAI',
placeholder: 'sk-...',
docsUrl: 'https://platform.openai.com/api-keys',
},
{
id: 'anthropic',
name: 'Anthropic (Claude)',
placeholder: 'sk-ant-...',
docsUrl: 'https://console.anthropic.com/keys',
},
{
id: 'groq',
name: 'Groq (Free tier)',
placeholder: 'gsk_...',
docsUrl: 'https://console.groq.com/keys',
},
{
id: 'openrouter',
name: 'OpenRouter (100+ models)',
placeholder: 'sk-or-...',
docsUrl: 'https://openrouter.ai/keys',
},
];
// ─── Styles ───────────────────────────────────────────────────────────────────
const styles = {
page: {
minHeight: '100vh',
background: 'linear-gradient(135deg, #1e1e2e 0%, #181825 100%)',
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'center',
padding: '16px 12px',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
} as React.CSSProperties,
card: {
background: 'rgba(30,30,46,0.95)',
border: '1px solid rgba(205,214,244,0.12)',
borderRadius: '12px',
padding: '16px',
width: '100%',
maxWidth: '420px',
boxShadow: '0 8px 48px rgba(0,0,0,0.4)',
color: '#cdd6f4',
} as React.CSSProperties,
logoRow: {
display: 'flex',
alignItems: 'center',
gap: '8px',
marginBottom: '4px',
} as React.CSSProperties,
logo: {
fontSize: '28px',
} as React.CSSProperties,
title: {
fontSize: '22px',
fontWeight: '800',
color: '#89b4fa',
margin: 0,
} as React.CSSProperties,
subtitle: {
fontSize: '13px',
color: '#6c7086',
marginBottom: '14px',
marginTop: '4px',
} as React.CSSProperties,
label: {
display: 'block',
fontSize: '13px',
fontWeight: '600',
color: '#a6adc8',
marginBottom: '6px',
textTransform: 'uppercase' as const,
letterSpacing: '0.04em',
} as React.CSSProperties,
select: {
width: '100%',
padding: '10px 14px',
borderRadius: '9px',
border: '1px solid rgba(205,214,244,0.15)',
background: 'rgba(49,50,68,0.7)',
color: '#cdd6f4',
fontSize: '14px',
outline: 'none',
cursor: 'pointer',
marginBottom: '0',
} as React.CSSProperties,
input: {
width: '100%',
padding: '10px 14px',
borderRadius: '9px',
border: '1px solid rgba(205,214,244,0.15)',
background: 'rgba(49,50,68,0.7)',
color: '#cdd6f4',
fontSize: '14px',
outline: 'none',
boxSizing: 'border-box' as const,
} as React.CSSProperties,
formGroup: {
marginBottom: '12px',
} as React.CSSProperties,
hint: {
fontSize: '12px',
color: '#6c7086',
marginTop: '6px',
display: 'flex',
alignItems: 'center',
gap: '4px',
} as React.CSSProperties,
docsLink: {
color: '#89b4fa',
textDecoration: 'none',
fontSize: '12px',
} as React.CSSProperties,
saveBtn: {
width: '100%',
padding: '10px',
borderRadius: '10px',
border: 'none',
fontSize: '15px',
fontWeight: '700',
cursor: 'pointer',
transition: 'all 0.2s ease',
marginTop: '4px',
} as React.CSSProperties,
divider: {
borderTop: '1px solid rgba(205,214,244,0.08)',
margin: '12px 0',
} as React.CSSProperties,
statusBadge: {
display: 'inline-flex',
alignItems: 'center',
gap: '6px',
fontSize: '12px',
padding: '4px 10px',
borderRadius: '6px',
marginTop: '12px',
} as React.CSSProperties,
};
const providerName = (id: string | null): string =>
PROVIDERS.find((p) => p.id === id)?.name ?? id ?? 'another provider';
// ─── Component ────────────────────────────────────────────────────────────────
function OptionsPage() {
const [provider, setProvider] = useState('openai');
const [apiKey, setApiKey] = useState('');
const [model, setModel] = useState('');
const [models, setModels] = useState<string[]>([]);
const [modelsStatus, setModelsStatus] = useState<'idle' | 'loading' | 'error'>('idle');
const [modelsError, setModelsError] = useState('');
const [saveStatus, setSaveStatus] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle');
const [showKey, setShowKey] = useState(false);
const [isEncrypted, setIsEncrypted] = useState(false);
const apiKeyRef = useRef<HTMLInputElement>(null);
// Which provider the stored key belongs to. A key is only usable for the
// provider it was saved under — see handleProviderChange.
const savedKeyProvider = useRef<string | null>(null);
const hasStoredKey = useRef(false);
// Fetch the live model list from the provider (via the background worker, which
// owns key decryption). Uses a freshly typed key if present, else the stored key.
const loadModels = async (providerOverride?: string, keyOverride?: string) => {
const prov = providerOverride ?? provider;
const inlineKey = keyOverride ?? (apiKey.trim() || undefined);
setModelsStatus('loading');
setModelsError('');
// Never ask the background to fall back to a key saved for another provider —
// it comes back as a bogus "Invalid API Key" from the provider being switched to.
if (!inlineKey && prov !== 'openrouter' && hasStoredKey.current && savedKeyProvider.current !== prov) {
setModels([]);
setModelsStatus('idle');
setModelsError(`Your saved key was entered for ${providerName(savedKeyProvider.current)}. Enter a ${providerName(prov)} API key above, then click ↻ Load.`);
return;
}
const response = await safeSendMessage({ type: 'LIST_MODELS', provider: prov, apiKey: inlineKey });
if (!response) {
setModels([]);
setModelsStatus('error');
setModelsError('No response from the extension. Try reloading the page.');
return;
}
if (response.error) {
setModels([]);
setModelsStatus('error');
// A rejected key means the stored one is unusable — drop the 🔒 badge so
// the field invites a new key instead of implying one is configured.
if (response.keyRejected && !inlineKey) {
hasStoredKey.current = false;
setIsEncrypted(false);
setModelsError(`${response.error} Enter a valid ${providerName(prov)} API key above and save again.`);
return;
}
setModelsError(response.error);
return;
}
const list: string[] = Array.isArray(response.models) ? response.models : [];
setModels(list);
setModelsStatus('idle');
// Keep the current selection if it's still valid; otherwise force a re-pick.
setModel((prev) => (prev && list.includes(prev) ? prev : ''));
};
useEffect(() => {
safeStorageGet(['provider', 'apiKey', 'apiKeyEnc', 'encKey', 'model', 'keyProvider'], (result) => {
const prov = result.provider || 'openai';
if (result.provider) setProvider(result.provider);
if (result.model) setModel(result.model);
// Show placeholder if encrypted key exists
if (result.apiKeyEnc && result.encKey) {
setIsEncrypted(true);
setApiKey(''); // don't show encrypted blob — show empty for re-entry or leave as is
} else if (result.apiKey) {
setApiKey(result.apiKey);
setIsEncrypted(false);
}
if (result.apiKeyEnc || result.apiKey) {
hasStoredKey.current = true;
// Keys saved before `keyProvider` existed: assume the stored provider.
savedKeyProvider.current = (result.keyProvider as string) || prov;
// A key belonging to another provider is not usable here — don't show 🔒.
if (savedKeyProvider.current !== prov) setIsEncrypted(false);
}
// If a key is already configured, pull the live model list on open.
if (result.apiKeyEnc || result.apiKey || prov === 'openrouter') {
loadModels(prov);
}
});
}, []);
const currentProvider = PROVIDERS.find((p) => p.id === provider) ?? PROVIDERS[0];
const handleProviderChange = (newProvider: string) => {
setProvider(newProvider);
setModel('');
setModels([]);
setModelsStatus('idle');
setModelsError('');
// The stored key belongs to whichever provider was saved last. Listing with
// it after a switch makes the *new* provider reject it ("Invalid API Key"),
// which reads as "my key doesn't work". Ask for the new key instead.
const keyIsForThisProvider = hasStoredKey.current && savedKeyProvider.current === newProvider;
// Drives both the 🔒 badge and whether Save may keep the existing key.
setIsEncrypted(keyIsForThisProvider);
if (apiKey.trim() || keyIsForThisProvider || newProvider === 'openrouter') {
loadModels(newProvider);
} else {
setModelsError(`Enter your ${providerName(newProvider)} API key above, then click ↻ Load.`);
}
};
const handleSave = async () => {
// Require an explicit model choice — prevents sending a stale/mismatched model
// id to a provider (the root cause of the OpenRouter failures).
if (!model) {
setModelsError('Please load and select a model before saving.');
return;
}
// If key is blank and we already have an encrypted key, don't overwrite
if (!apiKey.trim() && !isEncrypted) {
setModelsError('Enter your API key before saving.');
apiKeyRef.current?.focus();
return;
}
setModelsError('');
if (!apiKey.trim() && isEncrypted) {
// Only saving provider/model changes — preserve existing encrypted key.
// isEncrypted is only true when that key belongs to `provider`, so
// stamping keyProvider here is safe and upgrades pre-keyProvider saves.
setSaveStatus('saving');
savedKeyProvider.current = provider;
safeStorageSet({ provider, model, keyProvider: provider }, () => {
if (chrome.runtime.lastError) {
setSaveStatus('error');
setTimeout(() => setSaveStatus('idle'), 3000);
} else {
setSaveStatus('saved');
setTimeout(() => setSaveStatus('idle'), 2500);
}
});
return;
}
setSaveStatus('saving');
try {
const key = await getOrCreateEncKey();
const apiKeyEncB64 = encryptApiKey(apiKey.trim(), key);
safeStorageSet({ apiKeyEnc: apiKeyEncB64, provider, model, keyProvider: provider }, () => {
if (chrome.runtime.lastError) {
setSaveStatus('error');
setTimeout(() => setSaveStatus('idle'), 3000);
} else {
// Remove plaintext key if it existed
chrome.storage.local.remove('apiKey');
savedKeyProvider.current = provider;
hasStoredKey.current = true;
setIsEncrypted(true);
setApiKey('');
setSaveStatus('saved');
setTimeout(() => setSaveStatus('idle'), 2500);
}
});
} catch (err) {
console.error('LexAI: Encryption failed', err);
setSaveStatus('error');
setTimeout(() => setSaveStatus('idle'), 3000);
}
};
const saveBtnStyle: React.CSSProperties = {
...styles.saveBtn,
background: saveStatus === 'saved'
? '#a6e3a1'
: saveStatus === 'error'
? '#f38ba8'
: 'linear-gradient(135deg, #89b4fa 0%, #b4befe 100%)',
color: '#1e1e2e',
};
return (
<div style={styles.page}>
<div style={styles.card}>
{/* Header */}
<div style={styles.logoRow}>
<span style={styles.logo}></span>
<h1 style={styles.title}>LexAI Settings</h1>
</div>
<p style={styles.subtitle}>
Configure your LLM provider and API key. Your key is encrypted and stored locally.
</p>
<div style={styles.divider} />
{/* Provider */}
<div style={styles.formGroup}>
<label style={styles.label}>LLM Provider</label>
<select
style={styles.select}
value={provider}
onChange={(e) => handleProviderChange(e.target.value)}
>
{PROVIDERS.map((p) => (
<option key={p.id} value={p.id}>{p.name}</option>
))}
</select>
</div>
{/* API Key — comes before Model: the live model list is fetched with this key */}
<div style={styles.formGroup}>
<label style={styles.label}>
API Key{' '}
{isEncrypted && (
<span
title="API key is encrypted with TweetNaCl secretbox"
style={{ fontSize: '14px', marginLeft: '4px', verticalAlign: 'middle' }}
>
🔒
</span>
)}
</label>
<div style={{ position: 'relative' }}>
<input
ref={apiKeyRef}
type={showKey ? 'text' : 'password'}
value={apiKey}
onChange={(e) => {
setApiKey(e.target.value);
if (isEncrypted && e.target.value) setIsEncrypted(false);
}}
placeholder={isEncrypted ? '••••••• (encrypted — enter new key to change)' : currentProvider.placeholder}
style={{ ...styles.input, paddingRight: '42px' }}
onKeyDown={(e) => e.key === 'Enter' && handleSave()}
/>
<button
onClick={() => setShowKey((s) => !s)}
style={{
position: 'absolute',
right: '10px',
top: '50%',
transform: 'translateY(-50%)',
background: 'none',
border: 'none',
color: '#6c7086',
cursor: 'pointer',
fontSize: '14px',
padding: '4px',
}}
title={showKey ? 'Hide key' : 'Show key'}
>
{showKey ? '🙈' : '👁'}
</button>
</div>
<div style={styles.hint}>
<span>🔒 Encrypted with TweetNaCl on your device.</span>
<span>·</span>
<a
href={currentProvider.docsUrl}
target="_blank"
rel="noopener noreferrer"
style={styles.docsLink}
>
Get API key
</a>
</div>
</div>
{/* Model — fetched live from the selected provider using the key above */}
<div style={styles.formGroup}>
<label style={styles.label}>Model</label>
<div style={{ display: 'flex', gap: '8px' }}>
<select
style={{ ...styles.select, flex: 1, opacity: models.length === 0 ? 0.6 : 1 }}
value={model}
onChange={(e) => setModel(e.target.value)}
disabled={modelsStatus === 'loading' || models.length === 0}
>
{modelsStatus === 'loading' && <option value="">Loading models</option>}
{modelsStatus !== 'loading' && models.length === 0 && (
<option value="">
{modelsStatus === 'error' ? 'Failed to load — see below' : 'Load models to choose'}
</option>
)}
{models.length > 0 && <option value=""> Select a model </option>}
{models.map((m) => (
<option key={m} value={m}>{m}</option>
))}
</select>
<button
type="button"
onClick={() => loadModels()}
disabled={modelsStatus === 'loading'}
title="Fetch the current model list from your provider"
style={{
background: 'rgba(137,180,250,0.15)',
color: '#89b4fa',
border: '1px solid rgba(137,180,250,0.3)',
borderRadius: '9px',
padding: '0 12px',
fontSize: '13px',
fontWeight: 600,
cursor: modelsStatus === 'loading' ? 'not-allowed' : 'pointer',
whiteSpace: 'nowrap',
flexShrink: 0,
}}
>
{modelsStatus === 'loading' ? '⏳' : '↻ Load'}
</button>
</div>
{/* Rendered whenever set — not only on load errors. Gating this on
modelsStatus made the save-time messages invisible, so Save looked
like a no-op. */}
{modelsError && (
<div style={{ ...styles.hint, color: modelsStatus === 'error' ? '#f38ba8' : '#f9e2af' }}>
{modelsError}
</div>
)}
</div>
{/* Save */}
<button style={saveBtnStyle} onClick={handleSave} disabled={saveStatus === 'saving'}>
{saveStatus === 'saving'
? '⏳ Saving…'
: saveStatus === 'saved'
? '✓ Settings Saved!'
: saveStatus === 'error'
? '✕ Save Failed — Try Again'
: '💾 Save Settings'}
</button>
<div style={styles.divider} />
{/* Info */}
<div style={{ fontSize: '12px', color: '#6c7086', lineHeight: '1.6' }}>
<strong style={{ color: '#a6adc8' }}>How to use LexAI:</strong>
<ol style={{ margin: '8px 0 0 16px', padding: 0 }}>
<li>Select any text on a webpage</li>
<li>Click Fix, Rephrase, Shorten, Expand, Explain, or Prompt (turns your text into an engineered AI prompt)</li>
<li>Accept or replace the suggestion</li>
</ol>
</div>
</div>
</div>
);
}
createRoot(document.getElementById('app')!).render(<OptionsPage />);

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LexAI Settings</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="./Options.tsx"></script>
</body>
</html>

View File

@@ -0,0 +1,609 @@
import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { safeSendMessage, safeStorageGet, safeStorageSet } from '@lib/messaging';
import { WRITING_STYLES, PROMPT_PATTERNS, PROMPT_PERSONAS, PROMPT_FORMATS, resolvePromptPersona, resolvePromptPattern } from '@lib/actions';
import type { PromptParams } from '@lib/types';
// ─── Types ───────────────────────────────────────────────────────────────────
type Action = 'fix' | 'rephrase' | 'shorten' | 'expand' | 'prompt';
// ─── Styles ──────────────────────────────────────────────────────────────────
const S = {
root: {
fontFamily: 'system-ui, -apple-system, sans-serif',
background: '#1e1e2e',
color: '#cdd6f4',
padding: '0',
minWidth: '420px',
maxHeight: '600px',
overflowY: 'auto' as const,
},
header: {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '12px 16px',
borderBottom: '1px solid rgba(205,214,244,0.1)',
},
headerLeft: {
display: 'flex',
alignItems: 'center',
gap: '6px',
fontSize: '16px',
fontWeight: 700,
},
settingsBtn: {
background: 'none',
border: '1px solid rgba(205,214,244,0.2)',
borderRadius: '6px',
color: '#a6adc8',
cursor: 'pointer',
fontSize: '12px',
padding: '4px 10px',
},
section: {
padding: '14px 16px',
},
tabBar: {
display: 'flex',
borderBottom: '1px solid rgba(205,214,244,0.1)',
},
tab: {
flex: 1,
background: 'none',
border: 'none',
borderBottom: '2px solid transparent',
color: '#6c7086',
cursor: 'pointer',
fontSize: '13px',
fontWeight: 600,
padding: '10px 0',
},
tabActive: {
color: '#89b4fa',
borderBottom: '2px solid #89b4fa',
},
divider: {
borderTop: '1px solid rgba(205,214,244,0.1)',
},
textarea: {
width: '100%',
minHeight: '100px',
background: 'rgba(49,50,68,0.95)',
border: '1px solid rgba(205,214,244,0.15)',
borderRadius: '8px',
color: '#cdd6f4',
fontSize: '13px',
lineHeight: '1.5',
padding: '10px 12px',
resize: 'vertical' as const,
outline: 'none',
boxSizing: 'border-box' as const,
fontFamily: 'inherit',
},
styleRow: {
display: 'flex',
alignItems: 'center',
gap: '8px',
marginTop: '10px',
marginBottom: '2px',
},
styleLabel: {
fontSize: '12px',
color: '#a6adc8',
flexShrink: 0,
},
styleSelect: {
background: 'rgba(49,50,68,0.95)',
border: '1px solid rgba(205,214,244,0.2)',
borderRadius: '6px',
color: '#cdd6f4',
fontSize: '12px',
padding: '4px 8px',
cursor: 'pointer',
flex: 1,
outline: 'none',
},
actionsRow: {
display: 'flex',
flexWrap: 'wrap' as const,
gap: '8px',
marginTop: '10px',
},
actionBtn: {
background: 'linear-gradient(135deg, #cba6f7, #89b4fa)',
border: 'none',
borderRadius: '6px',
color: '#1e1e2e',
cursor: 'pointer',
fontSize: '12px',
fontWeight: 600,
padding: '6px 12px',
},
actionBtnDisabled: {
background: 'rgba(203,166,247,0.3)',
border: 'none',
borderRadius: '6px',
color: '#a6adc8',
cursor: 'not-allowed',
fontSize: '12px',
fontWeight: 600,
padding: '6px 12px',
},
processingBadge: {
fontSize: '12px',
color: '#a6adc8',
marginTop: '8px',
},
resultSection: {
padding: '0 16px 14px',
},
resultLabel: {
fontSize: '12px',
color: '#a6adc8',
marginBottom: '6px',
fontWeight: 600,
},
resultBox: {
background: 'rgba(49,50,68,0.8)',
border: '1px solid rgba(205,214,244,0.1)',
borderRadius: '8px',
color: '#cdd6f4',
fontSize: '13px',
lineHeight: '1.5',
padding: '10px 12px',
whiteSpace: 'pre-wrap' as const,
wordBreak: 'break-word' as const,
},
copyBtn: {
marginTop: '8px',
background: 'rgba(137,180,250,0.15)',
border: '1px solid rgba(137,180,250,0.3)',
borderRadius: '6px',
color: '#89b4fa',
cursor: 'pointer',
fontSize: '12px',
fontWeight: 600,
padding: '6px 14px',
},
warningBox: {
background: 'rgba(243,139,168,0.1)',
border: '1px solid rgba(243,139,168,0.3)',
borderRadius: '8px',
color: '#f38ba8',
fontSize: '12px',
padding: '10px 12px',
marginBottom: '12px',
},
errorBox: {
background: 'rgba(243,139,168,0.1)',
border: '1px solid rgba(243,139,168,0.3)',
borderRadius: '8px',
color: '#f38ba8',
fontSize: '12px',
padding: '10px 12px',
marginTop: '8px',
},
};
// ─── Component ────────────────────────────────────────────────────────────────
function Popup() {
const [configured, setConfigured] = useState(false);
const [provider, setProvider] = useState('');
const [model, setModel] = useState('');
const [inputText, setInputText] = useState('');
const [result, setResult] = useState('');
const [error, setError] = useState('');
const [processing, setProcessing] = useState(false);
const [copied, setCopied] = useState(false);
const [writingStyle, setWritingStyle] = useState('Default');
// Prompt Builder parameters — persisted so they survive popup close/open.
const [promptPattern, setPromptPattern] = useState('auto');
const [promptPersona, setPromptPersona] = useState('Auto');
const [customPersona, setCustomPersona] = useState('');
const [promptFormat, setPromptFormat] = useState('Auto');
// Model used for building the prompt ('' = the configured default model).
const [promptModel, setPromptModel] = useState('');
const [promptModels, setPromptModels] = useState<string[]>([]);
const [modelsHint, setModelsHint] = useState('');
const modelsRequested = useRef(false);
const [tab, setTab] = useState<'writing' | 'prompt'>('writing');
const sessionRestored = useRef(false);
// Load config + restore session input + load writing style
useEffect(() => {
safeStorageGet(
['provider', 'apiKey', 'apiKeyEnc', 'model', 'writingStyle', 'promptPattern', 'promptStyle', 'promptPersona', 'customPersona', 'promptFormat', 'promptModel', 'popupTab'],
(result) => {
if (result.apiKey || result.apiKeyEnc) {
setConfigured(true);
setProvider(result.provider || 'openai');
setModel(result.model || '');
}
if (result.writingStyle) {
setWritingStyle(result.writingStyle);
}
if (result.promptPattern || result.promptStyle) {
setPromptPattern(resolvePromptPattern(result.promptPattern, result.promptStyle));
}
if (result.promptPersona) setPromptPersona(result.promptPersona);
if (result.customPersona) setCustomPersona(result.customPersona);
if (result.promptFormat) setPromptFormat(result.promptFormat);
if (result.promptModel) setPromptModel(result.promptModel);
if (result.popupTab === 'prompt' || result.popupTab === 'writing') setTab(result.popupTab);
},
);
if (!sessionRestored.current) {
sessionRestored.current = true;
safeStorageGet(['lexai_popup_input'], (res) => {
if (res.lexai_popup_input) {
setInputText(res.lexai_popup_input);
}
}, chrome.storage.session);
}
}, []);
// Persist input to session storage on change
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const val = e.target.value;
setInputText(val);
safeStorageSet({ lexai_popup_input: val }, undefined, chrome.storage.session);
};
// Save writing style on change
const handleStyleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const val = e.target.value;
setWritingStyle(val);
safeStorageSet({ writingStyle: val });
};
const openSettings = () => {
try {
if (typeof chrome !== 'undefined' && chrome.runtime?.id) {
chrome.runtime.openOptionsPage();
}
} catch (err) {
console.warn('LexAI: Extension context invalidated', err);
}
};
// Resolve the Prompt Builder selections into message params. 'Custom…'
// uses the free-text persona (falls back to Auto when left empty).
const resolvePromptParams = (): PromptParams => ({
pattern: promptPattern,
persona: resolvePromptPersona(promptPersona, customPersona),
format: promptFormat,
});
const runAction = async (action: Action) => {
const text = inputText.trim();
if (!text || processing) return;
setProcessing(true);
setResult('');
setError('');
const response = await safeSendMessage({
type: 'ANALYZE_TEXT',
payload: {
text,
action,
style: writingStyle,
...(action === 'prompt'
? {
promptParams: resolvePromptParams(),
...(promptModel ? { model: promptModel } : {}),
}
: {}),
},
});
setProcessing(false);
if (!response) {
setError('No response from extension. Try reloading.');
return;
}
if (response.error) {
setError(response.error);
return;
}
if (response.result) {
setResult(response.result);
}
};
const copyResult = async () => {
if (!result) return;
try {
await navigator.clipboard.writeText(result);
setCopied(true);
setTimeout(() => setCopied(false), 1500);
} catch {
// fallback
}
};
const actions: { label: string; id: Action }[] = [
{ label: 'Fix Grammar', id: 'fix' },
{ label: 'Rephrase', id: 'rephrase' },
{ label: 'Shorten', id: 'shorten' },
{ label: 'Expand', id: 'expand' },
];
// Persist one Prompt Builder param alongside its state update.
const setParam = (key: string, value: string, setter: (v: string) => void) => {
setter(value);
safeStorageSet({ [key]: value });
};
const switchTab = (t: 'writing' | 'prompt') => {
setTab(t);
safeStorageSet({ popupTab: t });
};
// Fetch the provider's model list the first time the Prompt Builder tab is
// shown (background worker resolves the stored key). Failure is non-fatal —
// the picker just stays on the default model.
useEffect(() => {
if (tab !== 'prompt' || !configured || modelsRequested.current) return;
modelsRequested.current = true;
(async () => {
const res = await safeSendMessage({ type: 'LIST_MODELS', provider });
if (res?.models && Array.isArray(res.models)) {
setPromptModels(res.models);
} else {
setModelsHint(res?.error || 'Could not load the model list — using the default model.');
}
})();
}, [tab, configured, provider]);
return (
<div style={S.root}>
{/* Header */}
<div style={S.header}>
<div style={S.headerLeft}>
<span></span>
<span>LexAI</span>
</div>
<button style={S.settingsBtn} onClick={openSettings}>
Settings
</button>
</div>
{/* Not configured warning */}
{!configured && (
<div style={S.section}>
<div style={S.warningBox}>
<strong> Setup Required</strong>
<br />
Add your API key in Settings to use LexAI.
</div>
<button
onClick={openSettings}
style={{
...S.actionBtn,
width: '100%',
fontSize: '13px',
padding: '8px',
}}
>
Open Settings
</button>
</div>
)}
{/* Main input area — only when configured */}
{configured && (
<>
{/* Tabs: quick writing actions vs. the Prompt Builder */}
<div style={S.tabBar}>
<button
style={tab === 'writing' ? { ...S.tab, ...S.tabActive } : S.tab}
onClick={() => switchTab('writing')}
>
Writing
</button>
<button
style={tab === 'prompt' ? { ...S.tab, ...S.tabActive } : S.tab}
onClick={() => switchTab('prompt')}
>
🪄 Prompt Builder
</button>
</div>
<div style={S.section}>
{/* Provider badge */}
<div style={{ fontSize: '11px', color: '#a6adc8', marginBottom: '8px' }}>
{provider}
{/* Model shown only on the Writing tab — the Prompt Builder has its own Model field */}
{tab === 'writing' && model ? ` / ${model}` : ''}
</div>
{/* Textarea */}
<textarea
style={S.textarea}
placeholder="Paste your text here..."
value={inputText}
onChange={handleInputChange}
disabled={processing}
rows={4}
/>
{/* Writing tab: style + quick actions */}
{tab === 'writing' && (
<>
<div style={S.styleRow}>
<span style={S.styleLabel}>Style:</span>
<select
style={S.styleSelect}
value={writingStyle}
onChange={handleStyleChange}
disabled={processing}
>
{WRITING_STYLES.map(s => (
<option key={s} value={s}>{s}</option>
))}
</select>
</div>
<div style={S.actionsRow}>
{actions.map(({ label, id }) => (
<button
key={id}
style={processing ? S.actionBtnDisabled : S.actionBtn}
disabled={processing || !inputText.trim()}
onClick={() => runAction(id)}
>
{label}
</button>
))}
</div>
</>
)}
{/* Prompt Builder tab: dedicated parameters + model + Make Prompt */}
{tab === 'prompt' && (
<>
<div style={{ fontSize: '11px', color: '#6c7086', margin: '8px 0 2px' }}>
Turns the text above into an engineered AI prompt. "Auto" lets it decide from your input.
</div>
<div style={{ ...S.styleRow, marginTop: '6px' }}>
<span style={{ ...S.styleLabel, width: '64px' }}>Pattern:</span>
<select
style={S.styleSelect}
value={promptPattern}
onChange={(e) => setParam('promptPattern', e.target.value, setPromptPattern)}
disabled={processing}
>
{PROMPT_PATTERNS.filter((p) => p.id === 'auto').map((p) => (
<option key={p.id} value={p.id} title={p.hint}>{p.label}</option>
))}
{(['Direct', 'Reasoning', 'Agentic'] as const).map((group) => (
<optgroup key={group} label={group}>
{PROMPT_PATTERNS.filter((p) => p.id !== 'auto' && p.group === group).map((p) => (
<option key={p.id} value={p.id} title={p.hint}>{p.label}</option>
))}
</optgroup>
))}
</select>
</div>
<div style={{ fontSize: '11px', color: '#6c7086', margin: '2px 0 0 72px' }}>
{PROMPT_PATTERNS.find((p) => p.id === promptPattern)?.hint}
</div>
<div style={{ ...S.styleRow, marginTop: '6px' }}>
<span style={{ ...S.styleLabel, width: '64px' }}>Persona:</span>
<select
style={S.styleSelect}
value={promptPersona}
onChange={(e) => setParam('promptPersona', e.target.value, setPromptPersona)}
disabled={processing}
>
{PROMPT_PERSONAS.map((p) => (
<option key={p} value={p}>{p}</option>
))}
</select>
</div>
{promptPersona === 'Custom…' && (
<div style={{ ...S.styleRow, marginTop: '6px' }}>
<span style={{ ...S.styleLabel, width: '64px' }} />
<input
type="text"
style={{ ...S.styleSelect, cursor: 'text' }}
placeholder="e.g. senior UX researcher who writes usability reports"
value={customPersona}
onChange={(e) => setParam('customPersona', e.target.value, setCustomPersona)}
disabled={processing}
/>
</div>
)}
<div style={{ ...S.styleRow, marginTop: '6px' }}>
<span style={{ ...S.styleLabel, width: '64px' }}>Format:</span>
<select
style={S.styleSelect}
value={promptFormat}
onChange={(e) => setParam('promptFormat', e.target.value, setPromptFormat)}
disabled={processing}
>
{PROMPT_FORMATS.map((f) => (
<option key={f} value={f}>{f}</option>
))}
</select>
</div>
<div style={{ ...S.styleRow, marginTop: '6px' }}>
<span style={{ ...S.styleLabel, width: '64px' }}>Model:</span>
<select
style={S.styleSelect}
value={promptModel}
onChange={(e) => setParam('promptModel', e.target.value, setPromptModel)}
disabled={processing}
>
<option value="">Default</option>
{promptModels.map((m) => (
<option key={m} value={m}>{m}</option>
))}
</select>
</div>
{modelsHint && (
<div style={{ fontSize: '11px', color: '#6c7086', marginTop: '4px' }}>
{modelsHint}
</div>
)}
<div style={S.actionsRow}>
<button
style={{
...(processing ? S.actionBtnDisabled : S.actionBtn),
...(processing ? {} : { background: 'linear-gradient(135deg, #f9e2af, #fab387)' }),
width: '100%',
padding: '8px',
fontSize: '13px',
}}
disabled={processing || !inputText.trim()}
onClick={() => runAction('prompt')}
>
🪄 Make Prompt
</button>
</div>
</>
)}
{/* Processing state */}
{processing && (
<div style={S.processingBadge}> Processing...</div>
)}
{/* Error */}
{error && <div style={S.errorBox}> {error}</div>}
</div>
{/* Result area */}
{result && (
<>
<div style={S.divider} />
<div style={S.resultSection}>
<div style={S.resultLabel}>Result:</div>
<div style={S.resultBox}>{result}</div>
<button style={S.copyBtn} onClick={copyResult}>
{copied ? '✓ Copied!' : '⎘ Copy Result'}
</button>
</div>
</>
)}
</>
)}
</div>
);
}
createRoot(document.getElementById('app')!).render(<Popup />);

View File

@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>LexAI</title>
<style>body { margin: 0; min-width: 420px; }</style>
</head>
<body>
<div id="app"></div>
<script type="module" src="./Popup.tsx"></script>
</body>
</html>