diff options
| author | tanaka takashi <isazaka@gmail.com> | 2026-09-01 20:10:20 +0900 |
|---|---|---|
| committer | tanaka takashi <isazaka@gmail.com> | 2026-09-01 20:10:20 +0900 |
| commit | 55e581bab9b600e7c070ec596d3109fc897d2d86 (patch) | |
| tree | 15ca196a1858696c216946dc9608fae613ad6e5f /src/popup/popup.js | |
feat: Firefox selection translation extension with local Ollama (initial version)
Implement the complete initial version of a Firefox WebExtension (Manifest V3)
that translates selected text on web pages using a local Ollama LLM and shows
the result in a small popover near the selection.
Specification alignment (Phase 0)
- Unified Specifications.md / Design.md / Security.md on the same approach:
Ollama REST API + Fetch API + NDJSON streaming (no ollama-js SDK dependency)
- Fixed host_permissions to http://localhost/* and http://127.0.0.1/* because
Firefox match patterns do not support port numbers (bug 1362809/1468162);
the actual connection target is restricted to localhost/127.0.0.1 + any port
by application-side validation (defense in depth, OLL-09)
- Clipboard: use navigator.clipboard.writeText() only inside the copy button
click (user activation); no deprecated execCommand fallback
Implementation (zero dependencies, vanilla JS, no npm/Node required)
- manifest.json: MV3, background.scripts + type:module (event page, no
service_worker), action popup, options_ui, content_scripts for http/https,
permissions: storage + localhost host permissions only
- src/shared: constants (ports, limits, presets, error codes), message
validation, settings schema (defaults / merge / sanitize / buildOptions /
toApiThinking), system prompt builder (fixed prompt first + user prompt)
- src/background: message-router (runtime.Port streaming + runtime.onMessage
for model list), translation-session (single active request, abort previous
on new request, stale chunk suppression), ollama-client (fetch against
/api/tags and /api/chat with buffering NDJSON line parser tolerant to chunk
boundaries inside JSON objects, AbortController, host re-validation before
every request, HTTP status to error-code mapping), settings-service
(storage.local load/save with validation and fallback to defaults)
- src/content/content.js: single classic script (Firefox does not support ES
modules in content scripts) with selection detection (selectionchange +
mouseup + keyup, debounced), Shadow DOM action button, Shadow DOM popover
with HIDDEN/LOADING/STREAMING/COMPLETED/ERROR state machine, port client
with requestId-based stale chunk filtering, enabled-state sync via
storage.onChanged; all dynamic text rendered via textContent only
- src/popup + src/options: full settings UI (enable toggle, Ollama host,
model list from Ollama with saved-model warning, target language, thinking
mode, temperature slider 0.0-2.0 step 0.1, context length presets
4k/8k/16k/32k/128k/256k, seed random/fixed with integer value, user system
prompt, advanced numeric options with steppers, stop sequences textarea)
- icons generated by tools/make-icons.ps1 (System.Drawing, no external tools)
- build.ps1 packages manifest.json + icons/ + src/ into dist zip, excluding
tests/, doc/, ollama-js/ and tools/
Tests (71 passed, 0 failed)
- In-browser test runner (tests/test.html) with custom describe/it/assert
framework; no npm, no Node.js
- Unit: constants sync between content mirror and shared module, Ollama host
validation (localhost/127.0.0.1 + any port only; rejects external hosts,
LAN IPs, https, credentials, paths), settings schema defaults and fallback,
temperature 0.1-step validation, context length presets, seed modes,
advanced option types, buildOptions omission of unset values and absence of
tfs_z/mirostat fields, system prompt composition order, message validation
with selection length boundary values
- Integration: NDJSON streaming across awkward byte boundaries, thinking
chunk forwarding, malformed line tolerance, error payload mapping, think/
options inclusion rules, model list, TranslationSession abort semantics,
settings round-trip with storage.onChanged cache refresh, full port flow
(started/chunk/completed), newer request aborts older with stale chunk
discard, malformed message rejection, OLLAMA_UNAVAILABLE and
INVALID_SETTINGS error paths, untrusted sender rejection
Security audit (Design.md section 24 checklist: all pass)
- No innerHTML/outerHTML/document.write/eval/new Function/localStorage
- No remote JS/CSS/fonts/CDN resources; no inline scripts in extension pages
- Ollama access limited to background; content scripts never fetch Ollama
- Background validates message type/length/requestId; single concurrent
translation enforced
- Clipboard API only (no execCommand fallback)
- Minimal permissions: storage + localhost host permissions
Docs
- README.md with build/load/usage instructions, API list, permission rationale
- doc/Testing-Results.md with automated test results, security audit results,
and a 14-item manual Firefox verification checklist (to be executed on a
real Firefox + Ollama environment)
Diffstat (limited to 'src/popup/popup.js')
| -rw-r--r-- | src/popup/popup.js | 134 |
1 files changed, 134 insertions, 0 deletions
diff --git a/src/popup/popup.js b/src/popup/popup.js new file mode 100644 index 0000000..c07851e --- /dev/null +++ b/src/popup/popup.js @@ -0,0 +1,134 @@ +'use strict'; + +import { LANGUAGES, ERROR_CODES, RUNTIME_MESSAGES } from '../shared/constants.js'; +import { defaultSettings } from '../shared/settings-schema.js'; + +const $enabled = /** @type {HTMLInputElement} */ (document.getElementById('enabled-toggle')); +const $model = /** @type {HTMLSelectElement} */ (document.getElementById('model-select')); +const $reload = /** @type {HTMLButtonElement} */ (document.getElementById('reload-models')); +const $modelStatus = /** @type {HTMLParagraphElement} */ (document.getElementById('model-status')); +const $language = /** @type {HTMLSelectElement} */ (document.getElementById('language-select')); +const $openOptions = /** @type {HTMLButtonElement} */ (document.getElementById('open-options')); + +/** @type {string[]} current model list for change detection */ +let knownModels = []; + +function fillLanguages(selected) { + $language.textContent = ''; + for (const lang of LANGUAGES) { + const option = document.createElement('option'); + option.value = lang.code; + option.textContent = lang.label; + if (lang.code === selected) option.selected = true; + $language.append(option); + } +} + +function fillModels(models, selected) { + $model.textContent = ''; + if (models.length === 0) { + const option = document.createElement('option'); + option.value = ''; + option.textContent = '(モデルなし / Ollama未起動)'; + $model.append(option); + } + for (const name of models) { + const option = document.createElement('option'); + option.value = name; + option.textContent = name; + if (name === selected) option.selected = true; + $model.append(option); + } + if (selected && !models.includes(selected)) { + const option = document.createElement('option'); + option.value = selected; + option.textContent = `${selected}(一覧にありません)`; + option.selected = true; + $model.append(option); + } +} + +function showStatus(message, isError) { + $modelStatus.hidden = false; + $modelStatus.textContent = message; + $modelStatus.classList.toggle('error', Boolean(isError)); +} + +async function loadModels() { + showStatus('モデル一覧を取得中…', false); + try { + const response = await browser.runtime.sendMessage({ type: RUNTIME_MESSAGES.LIST_MODELS }); + if (response && response.ok && Array.isArray(response.models)) { + knownModels = response.models; + const current = $model.value; + fillModels(response.models, current); + if (response.models.length === 0) { + $modelStatus.hidden = true; + } else { + $modelStatus.hidden = true; + } + } else { + const code = response && response.error; + if (code === ERROR_CODES.OLLAMA_UNAVAILABLE) { + showStatus('Ollamaに接続できません。', true); + } else { + showStatus('モデル一覧の取得に失敗しました。', true); + } + fillModels([], $model.value); + } + } catch { + showStatus('モデル一覧の取得に失敗しました。', true); + } +} + +async function loadSettings() { + const result = await browser.storage.local.get({ settings: null }); + const settings = result.settings || defaultSettings(); + $enabled.checked = Boolean(settings.enabled); + $language.value = settings.targetLanguage || 'ja'; + fillModels(knownModels, settings.model || ''); + if (settings.model) { + // Preserve the stored model even before the first list load. + fillModels(knownModels.length ? knownModels : [settings.model], settings.model); + } +} + +async function persist(patch) { + const result = await browser.storage.local.get({ settings: null }); + const settings = result.settings || defaultSettings(); + const merged = { ...settings, ...patch }; + await browser.storage.local.set({ settings: merged }); +} + +$enabled.addEventListener('change', () => { + void persist({ enabled: $enabled.checked }); +}); + +$model.addEventListener('change', () => { + const value = $model.value; + if (value) void persist({ model: value }); +}); + +$language.addEventListener('change', () => { + void persist({ targetLanguage: $language.value }); +}); + +$reload.addEventListener('click', () => { + void loadModels(); +}); + +$openOptions.addEventListener('click', () => { + browser.runtime.openOptionsPage(); +}); + +// Init +for (const language of LANGUAGES) { + const option = document.createElement('option'); + option.value = language.code; + option.textContent = language.label; + $language.append(option); +} +void (async () => { + await loadSettings(); + await loadModels(); +})();
\ No newline at end of file |
