feat: Implement Prompt Builder functionality in Popup and Options
Some checks failed
CI — Test & Build / Test & Build (push) Failing after 39s

- Added a new "Prompt Builder" tab in the Popup for generating AI prompts with customizable parameters.
- Introduced new state variables for managing prompt styles, personas, formats, and models.
- Enhanced the Options page to fetch and display models based on the provided API key.
- Updated the actions and types to include the new 'prompt' action and its associated parameters.
- Implemented migration logic for legacy plaintext API keys to encrypted storage.
- Updated the getSystemPrompt function to incorporate prompt parameters for better instruction generation.
- Added tests for the new functionality, including context menu entries and prompt generation logic.
This commit is contained in:
john kevin asprec
2026-07-15 15:27:41 +08:00
parent 0fef9848cb
commit acea99d7ad
40 changed files with 1971 additions and 177 deletions

View File

@@ -1,7 +1,7 @@
import { defineBackground } from 'wxt/utils/define-background';
import type { AnalyzePayload, LexAIConfig, LexAIResponse } from '@lib/types';
import { CONTEXT_MENU_ENTRIES, findContextMenuEntry } from '@lib/actions';
import { decryptApiKey } from '@lib/crypto';
import { CONTEXT_MENU_ENTRIES, findContextMenuEntry, resolvePromptPersona } from '@lib/actions';
import { decryptApiKey, migratePlaintextApiKey } from '@lib/crypto';
import { callProvider, getSystemPrompt, listModels } from '@lib/providers';
// Resolve the usable API key from stored config: prefer the encrypted path,
@@ -22,13 +22,35 @@ async function handleAnalyzeText(payload: AnalyzePayload): Promise<LexAIResponse
const stored = await chrome.storage.local.get(['provider', 'apiKey', 'apiKeyEnc', 'encKey', 'model']);
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([
'promptStyle', 'promptPersona', 'customPersona', 'promptFormat', 'promptModel',
])) as Record<string, string | undefined>;
payload = {
...payload,
promptParams: {
promptStyle: 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 resolvedConfig: LexAIConfig = { ...config, apiKey };
const systemPrompt = getSystemPrompt(payload.action, payload.style);
const resolvedConfig: LexAIConfig = {
...config,
apiKey,
...(payload.model ? { model: payload.model } : {}),
};
const systemPrompt = getSystemPrompt(payload.action, payload.style, payload.promptParams);
return callProvider(resolvedConfig, payload.text, systemPrompt);
}
@@ -37,6 +59,10 @@ async function handleAnalyzeText(payload: AnalyzePayload): Promise<LexAIResponse
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(() => {
@@ -64,7 +90,11 @@ export default defineBackground(() => {
});
// ─── Message handler ─────────────────────────────────────────────────────
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
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
@@ -72,6 +102,8 @@ export default defineBackground(() => {
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)
@@ -99,10 +131,16 @@ export default defineBackground(() => {
}
if (message.type === 'LIST_MODELS') {
const provider = (message.provider as string) || 'openai';
// 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) {
const stored = await chrome.storage.local.get(['apiKey', 'apiKeyEnc', 'encKey']);

View File

@@ -1,6 +1,6 @@
import { defineContentScript } from 'wxt/utils/define-content-script';
import { isExtensionValid, safeSendMessage } from '@lib/messaging';
import { MIN_SELECTION_LENGTH, WRITING_STYLES } from '@lib/actions';
import { MIN_SELECTION_LENGTH, WRITING_STYLES, PROMPT_STYLES, PROMPT_PERSONAS, PROMPT_FORMATS } from '@lib/actions';
export default defineContentScript({
matches: ['<all_urls>'],
@@ -19,6 +19,9 @@ export default defineContentScript({
// ─── State ───────────────────────────────────────────────────────────────
let toolbar: HTMLElement | null = null;
let modal: HTMLElement | null = null;
// Removes the document-level listeners registered for the current toolbar's
// "More" menu — without this every selection leaked two document listeners.
let toolbarListenerCleanup: (() => void) | null = null;
// Stored immediately on mouseup — used during Replace (selection is lost by then)
let selectedText = '';
@@ -217,6 +220,7 @@ export default defineContentScript({
{ label: '↓ Shorten', action: 'shorten', color: '#fab387' },
{ label: '↑ Expand', action: 'expand', color: '#cba6f7' },
{ label: '💡 Explain', action: 'explain', color: '#2dd4bf' },
{ label: '🪄 Prompt', action: 'prompt', color: '#f9e2af' },
];
actions.forEach(({ label, action, color }) => {
@@ -254,7 +258,12 @@ export default defineContentScript({
});
btn.addEventListener('click', (e) => {
e.stopPropagation();
runAction(action);
// Prompt opens the Prompt Builder dialog first — parameters, then run.
if (action === 'prompt') {
showPromptBuilderDialog();
} else {
runAction(action);
}
});
toolbar!.appendChild(btn);
@@ -350,24 +359,50 @@ export default defineContentScript({
toolbar!.appendChild(moreBtn);
// Close dropdown on outside click / scroll
// Close dropdown on outside click / scroll; hideToolbar unregisters these
// (and closes any open menu) so listeners never accumulate across selections.
document.addEventListener('click', closeMoveMenu);
document.addEventListener('scroll', closeMoveMenu, { passive: true });
toolbarListenerCleanup = () => {
closeMoveMenu();
document.removeEventListener('click', closeMoveMenu);
document.removeEventListener('scroll', closeMoveMenu);
};
document.body.appendChild(toolbar);
// Re-clamp with the real width — the pre-append estimate undershoots now
// that the toolbar has six action buttons, which could push the last
// ones (🪄 Prompt, ⋯ More) past the right edge of the viewport.
const actualW = toolbar.offsetWidth;
let clampedLeft = rect.left + window.scrollX + rect.width / 2 - actualW / 2;
clampedLeft = Math.max(
window.scrollX + 8,
Math.min(clampedLeft, window.scrollX + window.innerWidth - actualW - 8),
);
toolbar.style.left = `${clampedLeft}px`;
}
function hideToolbar() {
toolbarListenerCleanup?.();
toolbarListenerCleanup = null;
if (toolbar) {
toolbar.remove();
toolbar = null;
}
}
// Close the Prompt Builder dialog (also used as the loading indicator for
// prompt requests — see showPromptBuilderDialog's Make Prompt handler).
function closePromptBuilder() {
document.getElementById('lexai-promptbuilder-overlay')?.remove();
}
// Extension context guard: isExtensionValid is imported from ~/lib/messaging.
function showErrorToast(msg: string) {
const toast = document.createElement('div');
toast.setAttribute('data-lexai', 'true');
toast.style.cssText = `
position: fixed; bottom: 20px; right: 20px; z-index: 999999;
background: #f38ba8; color: #1e1e2e; padding: 10px 16px;
@@ -556,6 +591,218 @@ export default defineContentScript({
document.body.appendChild(overlay);
}
// ─── Prompt Builder dialog ────────────────────────────────────────────────
// Same parameters as the popup's Prompt Builder tab. Selections are saved
// to chrome.storage.local and the request is sent WITHOUT explicit params —
// the background applies the saved ones, so popup and page stay in sync.
function showPromptBuilderDialog() {
document.getElementById('lexai-promptbuilder-overlay')?.remove();
ensureLexAIStyles();
hideToolbar();
selectionLocked = true; // dialog clicks must not reset the stored selection
const overlay = document.createElement('div');
overlay.id = 'lexai-promptbuilder-overlay';
overlay.setAttribute('data-lexai', 'true');
Object.assign(overlay.style, {
position: 'fixed',
inset: '0',
zIndex: '2147483646',
background: 'rgba(0,0,0,0.25)',
});
const panel = document.createElement('div');
panel.setAttribute('data-lexai', 'true');
Object.assign(panel.style, {
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%,-50%)',
zIndex: '2147483647',
background: 'linear-gradient(135deg, #1e1e2e 0%, #181825 100%)',
borderRadius:'12px',
padding: '16px',
width: '320px',
boxShadow: '0 12px 40px rgba(0,0,0,0.55)',
border: '1px solid rgba(205,214,244,0.15)',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
});
const close = () => {
selectionLocked = false;
overlay.remove();
};
// Header
const header = document.createElement('div');
Object.assign(header.style, {
display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '10px',
});
const title = document.createElement('div');
title.innerHTML = '🪄 <strong style="color:#cdd6f4">Prompt Builder</strong>';
Object.assign(title.style, { fontSize: '13px', color: '#89b4fa' });
const closeX = document.createElement('button');
closeX.textContent = '✕';
closeX.setAttribute('data-lexai', 'true');
Object.assign(closeX.style, {
background: 'none', border: 'none', color: '#6c7086',
cursor: 'pointer', fontSize: '14px', padding: '0 2px', lineHeight: '1',
});
closeX.addEventListener('click', close);
header.appendChild(title);
header.appendChild(closeX);
panel.appendChild(header);
const hint = document.createElement('div');
hint.textContent = '"Auto" lets it decide from your selected text.';
Object.assign(hint.style, { fontSize: '11px', color: '#6c7086', marginBottom: '10px' });
panel.appendChild(hint);
const selectStyle = {
flex: '1', background: 'rgba(49,50,68,0.95)', border: '1px solid rgba(205,214,244,0.2)',
borderRadius: '6px', color: '#cdd6f4', fontSize: '12px', padding: '5px 8px',
cursor: 'pointer', outline: 'none', minWidth: '0',
};
function makeRow(labelText: string, control: HTMLElement) {
const row = document.createElement('div');
Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' });
const label = document.createElement('span');
label.textContent = labelText;
Object.assign(label.style, { fontSize: '12px', color: '#a6adc8', width: '58px', flexShrink: '0' });
row.appendChild(label);
row.appendChild(control);
panel.appendChild(row);
return row;
}
function makeSelect(options: readonly string[]): HTMLSelectElement {
const sel = document.createElement('select');
sel.setAttribute('data-lexai', 'true');
Object.assign(sel.style, selectStyle);
options.forEach((o) => {
const opt = document.createElement('option');
opt.value = o;
opt.textContent = o;
sel.appendChild(opt);
});
return sel;
}
const selPromptStyle = makeSelect(PROMPT_STYLES);
makeRow('Style:', selPromptStyle);
const selPersona = makeSelect(PROMPT_PERSONAS);
makeRow('Persona:', selPersona);
const customInput = document.createElement('input');
customInput.type = 'text';
customInput.placeholder = 'e.g. senior UX researcher';
customInput.setAttribute('data-lexai', 'true');
Object.assign(customInput.style, { ...selectStyle, cursor: 'text' });
const customRow = makeRow('', customInput);
customRow.style.display = 'none';
selPersona.addEventListener('change', () => {
customRow.style.display = selPersona.value === 'Custom…' ? 'flex' : 'none';
});
const selFormat = makeSelect(PROMPT_FORMATS);
makeRow('Format:', selFormat);
// Model — 'Default' = the configured model; live list loads in the background.
const selModel = makeSelect([]);
const defaultOpt = document.createElement('option');
defaultOpt.value = '';
defaultOpt.textContent = 'Default';
selModel.appendChild(defaultOpt);
makeRow('Model:', selModel);
// Prefill from saved settings, then fetch the model list.
chrome.storage.local.get(
['promptStyle', 'promptPersona', 'customPersona', 'promptFormat', 'promptModel'],
(saved) => {
if (saved.promptStyle) selPromptStyle.value = saved.promptStyle as string;
if (saved.promptPersona) {
selPersona.value = saved.promptPersona as string;
customRow.style.display = selPersona.value === 'Custom…' ? 'flex' : 'none';
}
if (saved.customPersona) customInput.value = saved.customPersona as string;
if (saved.promptFormat) selFormat.value = saved.promptFormat as string;
const savedModel = (saved.promptModel as string) || '';
sendToBackground({ type: 'LIST_MODELS' }).then((res) => {
const models = (res as { models?: string[] } | null)?.models;
if (!Array.isArray(models)) return; // keep just 'Default' on failure
models.forEach((m) => {
const opt = document.createElement('option');
opt.value = m;
opt.textContent = m;
selModel.appendChild(opt);
});
if (savedModel && models.includes(savedModel)) selModel.value = savedModel;
});
},
);
// Buttons
const btnRow = document.createElement('div');
Object.assign(btnRow.style, { display: 'flex', gap: '8px', marginTop: '12px' });
const cancelBtn = document.createElement('button');
cancelBtn.textContent = 'Cancel';
cancelBtn.setAttribute('data-lexai', 'true');
Object.assign(cancelBtn.style, {
flex: '1', background: 'rgba(49,50,68,0.8)', color: '#a6adc8',
border: '1px solid rgba(205,214,244,0.15)', borderRadius: '8px',
padding: '8px', fontSize: '12px', fontWeight: '600', cursor: 'pointer',
});
cancelBtn.addEventListener('click', close);
const makeBtn = document.createElement('button');
makeBtn.textContent = '🪄 Make Prompt';
makeBtn.setAttribute('data-lexai', 'true');
Object.assign(makeBtn.style, {
flex: '2', background: 'linear-gradient(135deg, #f9e2af, #fab387)', color: '#1e1e2e',
border: 'none', borderRadius: '8px',
padding: '8px', fontSize: '12px', fontWeight: '700', cursor: 'pointer',
});
makeBtn.addEventListener('click', () => {
// Persist selections (shared with the popup), then run — the background
// reads these same keys for prompt requests without explicit params.
chrome.storage.local.set({
promptStyle: selPromptStyle.value,
promptPersona: selPersona.value,
customPersona: customInput.value,
promptFormat: selFormat.value,
promptModel: selModel.value,
});
// Turn the dialog into the progress indicator — runAction closes it
// (closePromptBuilder) when the result modal takes over.
panel.innerHTML = '';
const loading = document.createElement('div');
loading.setAttribute('data-lexai', 'true');
loading.innerHTML =
'<span style="font-size:18px;animation:lexai-spin 0.8s linear infinite;display:inline-block">⟳</span> Building your prompt…';
Object.assign(loading.style, {
display: 'flex', alignItems: 'center', justifyContent: 'center',
gap: '8px', padding: '14px 0', color: '#a6adc8', fontSize: '13px',
});
panel.appendChild(loading);
runAction('prompt'); // keep selectionLocked — runAction owns it from here
});
btnRow.appendChild(cancelBtn);
btnRow.appendChild(makeBtn);
panel.appendChild(btnRow);
overlay.appendChild(panel);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) close();
});
document.body.appendChild(overlay);
}
// ─── Safe chrome.runtime.sendMessage wrapper ──────────────────────────────
// Shared implementation; on a stale extension context we toast and clean up.
@@ -563,6 +810,7 @@ export default defineContentScript({
return safeSendMessage(payload, () => {
showErrorToast('LexAI was updated — please refresh this page.');
hideToolbar();
closePromptBuilder();
});
}
@@ -619,6 +867,7 @@ export default defineContentScript({
}) as { error?: string; result?: string } | null;
hideToolbar();
closePromptBuilder();
if (response === null) return; // sendToBackground already handled the error
@@ -636,6 +885,7 @@ export default defineContentScript({
}
} catch (err) {
hideToolbar();
closePromptBuilder();
if (String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')) {
showErrorToast('LexAI was updated — please refresh this page.');
@@ -686,7 +936,11 @@ export default defineContentScript({
width: '420px',
maxWidth: 'min(90vw, 420px)',
maxHeight: '70vh',
overflowY: 'auto',
// The result body scrolls, not the modal — header and action buttons
// must stay visible for long results (e.g. engineered prompts).
display: 'flex',
flexDirection: 'column',
overflow: 'hidden',
boxShadow: '0 12px 48px rgba(0,0,0,0.6)',
border: '1px solid rgba(205,214,244,0.15)',
fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
@@ -700,10 +954,15 @@ export default defineContentScript({
justifyContent:'space-between',
alignItems: 'center',
marginBottom: '12px',
flexShrink: '0',
});
const isPromptAction = action === 'prompt';
const title = document.createElement('div');
title.innerHTML = '⚡ <strong>LexAI</strong> Suggestion';
title.innerHTML = isPromptAction
? '🪄 <strong>LexAI</strong> Engineered Prompt'
: '⚡ <strong>LexAI</strong> Suggestion';
Object.assign(title.style, { fontSize: '13px', color: '#89b4fa' });
const closeBtn = document.createElement('button');
@@ -741,6 +1000,10 @@ export default defineContentScript({
marginBottom:'14px',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
// Scroll long results inside the box; flex keeps buttons below visible.
overflowY: 'auto',
flex: '1 1 auto',
minHeight: '60px',
});
modal.appendChild(body);
@@ -753,6 +1016,7 @@ export default defineContentScript({
alignItems: 'center',
gap: '8px',
marginBottom:'12px',
flexShrink: '0',
});
const styleLabel = document.createElement('span');
@@ -808,10 +1072,14 @@ export default defineContentScript({
async function doRegenerate() {
if (!action || !textForRegenerate) return;
const chosenStyle = styleSelect.value;
// Save style
currentStyle = chosenStyle;
await chrome.storage.local.set({ writingStyle: chosenStyle });
let chosenStyle = currentStyle;
// The writing-style selector only exists for non-prompt results; prompt
// regeneration re-reads the saved Prompt Builder params in the background.
if (!isPromptAction) {
chosenStyle = styleSelect.value;
currentStyle = chosenStyle;
await chrome.storage.local.set({ writingStyle: chosenStyle });
}
// Show spinner
body.innerHTML = '<span style="font-size:18px;animation:lexai-spin 0.8s linear infinite;display:inline-block">⟳</span> Regenerating…';
regenBtn.disabled = true;
@@ -835,14 +1103,43 @@ export default defineContentScript({
styleSelect.addEventListener('change', () => doRegenerate());
regenBtn.addEventListener('click', () => doRegenerate());
styleRow.appendChild(styleLabel);
styleRow.appendChild(styleSelect);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
if (isPromptAction) {
// Prompt results: writing styles don't apply — offer the Prompt Builder
// parameters instead, plus regenerate with the current ones.
const editBtn = document.createElement('button');
editBtn.textContent = '✎ Edit Parameters';
editBtn.setAttribute('data-lexai', 'true');
Object.assign(editBtn.style, {
background: 'rgba(249,226,175,0.15)',
color: '#f9e2af',
border: '1px solid rgba(249,226,175,0.3)',
borderRadius: '6px',
padding: '5px 10px',
fontSize: '12px',
fontWeight: '600',
cursor: 'pointer',
flex: '1',
});
editBtn.addEventListener('click', () => {
overlay.remove();
modal?.remove();
modal = null;
showPromptBuilderDialog(); // selection stays locked; dialog re-runs from here
});
styleRow.appendChild(editBtn);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
} else {
styleRow.appendChild(styleLabel);
styleRow.appendChild(styleSelect);
styleRow.appendChild(regenBtn);
modal.appendChild(styleRow);
}
// Buttons
const btnRow = document.createElement('div');
Object.assign(btnRow.style, { display: 'flex', gap: '8px' });
Object.assign(btnRow.style, { display: 'flex', gap: '8px', flexShrink: '0' });
if (originalText !== null) {
const replaceBtn = document.createElement('button');
@@ -995,7 +1292,7 @@ export default defineContentScript({
const captured = captureSelectionNow();
setTimeout(() => {
if (!captured || !selectedText || selectedText.length <= 10) {
if (!captured || !selectedText || selectedText.length < MIN_SELECTION_LENGTH) {
hideToolbar();
return;
}
@@ -1045,7 +1342,9 @@ export default defineContentScript({
});
// ─── Context menu trigger from background ─────────────────────────────────
chrome.runtime.onMessage.addListener((message) => {
chrome.runtime.onMessage.addListener((message, sender) => {
// Only our own background worker may inject selections — ignore others.
if (sender.id !== chrome.runtime.id) return;
if (message.type === 'lexai-context-menu') {
selectedText = message.text as string;
currentStyle = (message.style as string) || 'Default';
@@ -1054,7 +1353,12 @@ export default defineContentScript({
storedEnd = -1;
storedElement = null;
storedRange = null;
runAction(message.action as string);
// Prompt goes through the Prompt Builder dialog like the toolbar button.
if (message.action === 'prompt') {
showPromptBuilderDialog();
} else {
runAction(message.action as string);
}
}
});
},

View File

@@ -318,54 +318,7 @@ function OptionsPage() {
</select>
</div>
{/* Model — fetched live from the selected provider */}
<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>
{modelsStatus === 'error' && modelsError && (
<div style={{ ...styles.hint, color: '#f38ba8' }}> {modelsError}</div>
)}
</div>
{/* API Key */}
{/* API Key — comes before Model: the live model list is fetched with this key */}
<div style={styles.formGroup}>
<label style={styles.label}>
API Key{' '}
@@ -424,6 +377,53 @@ function OptionsPage() {
</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>
{modelsStatus === 'error' && modelsError && (
<div style={{ ...styles.hint, color: '#f38ba8' }}> {modelsError}</div>
)}
</div>
{/* Save */}
<button style={saveBtnStyle} onClick={handleSave} disabled={saveStatus === 'saving'}>
{saveStatus === 'saving'
@@ -442,7 +442,7 @@ function OptionsPage() {
<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, or Explain</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>

View File

@@ -2,11 +2,12 @@ import React, { useEffect, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { safeSendMessage, safeStorageGet, safeStorageSet } from '@lib/messaging';
import { WRITING_STYLES } from '@lib/actions';
import { WRITING_STYLES, PROMPT_STYLES, PROMPT_PERSONAS, PROMPT_FORMATS, resolvePromptPersona } from '@lib/actions';
import type { PromptParams } from '@lib/types';
// ─── Types ───────────────────────────────────────────────────────────────────
type Action = 'fix' | 'rephrase' | 'shorten' | 'expand';
type Action = 'fix' | 'rephrase' | 'shorten' | 'expand' | 'prompt';
// ─── Styles ──────────────────────────────────────────────────────────────────
@@ -46,6 +47,25 @@ const S = {
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)',
},
@@ -181,20 +201,40 @@ function Popup() {
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 [promptStyle, setPromptStyle] = 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'], (result) => {
if (result.apiKey || result.apiKeyEnc) {
setConfigured(true);
setProvider(result.provider || 'openai');
setModel(result.model || '');
}
if (result.writingStyle) {
setWritingStyle(result.writingStyle);
}
});
safeStorageGet(
['provider', 'apiKey', 'apiKeyEnc', 'model', 'writingStyle', '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.promptStyle) setPromptStyle(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;
@@ -230,6 +270,14 @@ function Popup() {
}
};
// Resolve the Prompt Builder selections into message params. 'Custom…'
// uses the free-text persona (falls back to Auto when left empty).
const resolvePromptParams = (): PromptParams => ({
promptStyle,
persona: resolvePromptPersona(promptPersona, customPersona),
format: promptFormat,
});
const runAction = async (action: Action) => {
const text = inputText.trim();
if (!text || processing) return;
@@ -240,7 +288,17 @@ function Popup() {
const response = await safeSendMessage({
type: 'ANALYZE_TEXT',
payload: { text, action, style: writingStyle },
payload: {
text,
action,
style: writingStyle,
...(action === 'prompt'
? {
promptParams: resolvePromptParams(),
...(promptModel ? { model: promptModel } : {}),
}
: {}),
},
});
setProcessing(false);
@@ -276,6 +334,33 @@ function Popup() {
{ 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 */}
@@ -314,11 +399,28 @@ function Popup() {
{/* 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 ? ` / ${model}` : ''}
{/* Model shown only on the Writing tab — the Prompt Builder has its own Model field */}
{tab === 'writing' && model ? ` / ${model}` : ''}
</div>
{/* Textarea */}
@@ -331,34 +433,138 @@ function Popup() {
rows={4}
/>
{/* Style selector */}
<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>
{/* 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>
{/* Action buttons */}
<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>
<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' }}>Style:</span>
<select
style={S.styleSelect}
value={promptStyle}
onChange={(e) => setParam('promptStyle', e.target.value, setPromptStyle)}
disabled={processing}
>
{PROMPT_STYLES.map((s) => (
<option key={s} value={s}>{s}</option>
))}
</select>
</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 && (