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

@@ -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 && (