diff options
| author | tanaka takashi <isazaka@gmail.com> | 2026-09-02 03:14:05 +0900 |
|---|---|---|
| committer | tanaka takashi <isazaka@gmail.com> | 2026-09-02 03:14:05 +0900 |
| commit | 82bb55f66071b452e3bc7adeb09eafb5003de11f (patch) | |
| tree | 01d48a68273594fc2ed480d837724562dd6fb05d /doc/Design.md | |
| parent | f5439335e1d18ee577e2b7c1e67f7844f9f235ac (diff) | |
feat: PDF Viewer translation via context menu and two-mode Action Popupv0.1.0
Add Firefox built-in PDF Viewer support using only public WebExtensions
APIs: a selection context menu ("選択したテキストを翻訳") starts a
translation and the toolbar Action Popup shows the streaming result.
No content-script injection into the privileged PDF Viewer, no PDF.js
internals, no separate windows, no custom viewer (Specifications.md §4.6).
Specification alignment (Phase 1)
- Specifications.md: new requirements PDF-01..04 (PDF selection
translation), CTX-01..03 (context menu translation), POP-01..06
(popup two modes); SEL-06 updated to route PDF through the menus API;
section 13.4 adds a 14-item manual PDF verification checklist; section
15 removes "Firefox内蔵PDF Viewerへの対応" from out-of-scope
- Design.md: architecture diagram with the menus path, menu-translation
component, menus permission, popup translation-result state machine
(idle/starting/streaming/completed/error/cancelled), shared translation
state (§9.2), context-menu integration phase, test plan and API audit
checklist items (menus permission scope, no PDF Viewer internals)
- Security.md: menus permission restricted to selection-context
translation; PDF Viewer treated as privileged browser UI (no injection,
no wrappedJSObject/cloneInto/exportFunction, no internal DOM access);
menus.OnClickData.selectionText treated as untrusted input passing the
same validation pipeline; popup result rendering stays textContent-only
Background (Phase 2)
- translation-service.js (new): the single translation pipeline shared by
every entry point - selection validation (type/trim/empty/control
chars/max length), prompt building, Ollama request, session/abort, and
the shared translation state (requestId, sourceText, translatedText,
status, model, error, startedAt, source). "source" is metadata only; a
PDF-specific translation engine does not exist
- menu-translation.js (new): validates menus.OnClickData.selectionText
and starts a sink-less translation observed via GET_POPUP_STATE
- message-router.js: routes port translations through the shared service;
new runtime messages GET_POPUP_STATE and REGENERATE_LAST; popup-state
port handler broadcasts live state (initial push + every chunk/status
change) so an open popup shows streaming progress in real time
- index.js: registers the selection context menu (contexts: ["selection"]
only, no menus.onShown) and calls browser.action.openPopup()
synchronously inside the click user gesture, catching failures so a
popup-open problem never breaks the translation itself
- manifest.json: permissions now ["storage", "menus"]
- settings-service.js: __resetCacheForTests hook for test isolation
Popup two-mode UI (Phase 3)
- popup.html/js/css: mode nav (設定 / 翻訳). Translation mode shows
status, model, streaming text (textContent only), user-safe error, and
copy (Clipboard API only, no execCommand fallback), regenerate (new
requestId reusing the stored source text) and a settings shortcut.
Closing the popup never cancels the request; reopening shows the
latest text and continues receiving chunks live. Initial mode: active
(starting/streaming) translation wins, otherwise the last tab the user
picked is restored (storage.local.popupMode, default settings)
Fresh-install model auto-selection
- translation-service.js ensureModelConfigured(): when storage.model is
empty, pick the first model from the running Ollama and persist it
before translating, mirroring the popup/options auto-select. A user who
never opened any settings UI can translate immediately; when Ollama is
unreachable a clear OLLAMA_UNAVAILABLE message is shown
User-safe error details
- detailForUser(): strips URLs (no internal host names echoed to the UI),
caps length at 120 chars, drops full JSON response bodies, and hides
meaningless low-level network errors so the popover/popup shows the
base message plus at most a short, safe detail
Tests: 85 passed, 0 failed
- selectionText validation (untrusted input pipeline)
- menu selection -> translation -> popup state streaming/completed
- empty selection rejected without starting a request
- streaming status transitions observed through GET_POPUP_STATE
- Ollama unreachable surfaces a user-safe error into popup state
- newer request replaces older state (abort semantics)
- regenerateLast reuses source text with a fresh requestId
- popup-state port receives live broadcasts; wrong port names ignored
- fresh-install auto-select persists the first Ollama model
- error detail sanitization (URL stripping, length cap, JSON drop)
- popup/options smoke tests updated for the two-mode markup
- setupRouter resets the shared settings cache for test isolation
Docs: README documents the two-mode popup and PDF flow; Testing-Results
records automated results and the manual PDF checklist (to be executed).
No git-side surprises: this commit was created explicitly on request
(requirement 18 of the PDF task had deferred commits until now).
Diffstat (limited to 'doc/Design.md')
| -rw-r--r-- | doc/Design.md | 142 |
1 files changed, 116 insertions, 26 deletions
diff --git a/doc/Design.md b/doc/Design.md index 20de3e5..bc7f1ff 100644 --- a/doc/Design.md +++ b/doc/Design.md @@ -2,29 +2,32 @@ ## 1. 設計概要 -本拡張は、Webページとの接点をContent Scriptに限定し、権限を伴うOllama通信と設定管理をBackgroundへ分離する。 +本拡張は、内容の翻訳接点をContent Script、権限の Ollama comunicación y administración de configuración を Background 内に分離する。Firefox内蔵PDF Viewerなどの content script 非対応ページおよび通常Webページの両方で、selectionベースの翻訳を context menuから実行できるようにする。 ```text -Web Page - │ - │ selection - ▼ -Content Script - │ runtime.Port - ▼ -Background - │ fetch / HTTP - ▼ -Ollama - │ streaming - ▼ -Background - │ runtime.Port - ▼ -Content Script - │ - ▼ -Shadow DOM Popover +Web Page / PDF Viewer + │ + │ selection + ▼ + selection経由 + │ + ├─ Content Script (通常ページのみ: 翻訳アイコン → Shadow DOM Popover) + ▼ │ + ├─ menus API (任意ページ: PDF Viewer含むselection → context menu → Action Popup) + │ │ + ▼ ▼ + Background + │ fetch / HTTP + ▼ + Ollama + │ streaming + ▼ + Background + TranslationSession + │ runtime.Port / popup state + ▼ + UI + ├─ Content Script: Shadow DOM Popover + └─ Action Popup: 翻訳結果モード ``` 設計原則: @@ -33,7 +36,7 @@ Shadow DOM Popover - Ollama通信はBackgroundのみ(Ollama REST API + Fetch API + NDJSON streaming)。 - UI文字列はHTMLとして評価しない。 - 翻訳要求は常に1-shot。 -- 同時翻訳は1件に制限。 +- 同時翻訳は1件に制限(新規要求で旧要求abort)。 - 設定値はUIだけでなくBackgroundでも検証する。 - Ollama接続先は初期版ではlocalhost / 127.0.0.1 + 任意ポートのみ許可する。 @@ -47,11 +50,12 @@ Shadow DOM Popover | `content/action-button` | 翻訳アイコン表示/非表示 | | `content/translation-popover` | 翻訳結果UI、stream描画、copy/regenerate/close | | `content/port-client` | Backgroundとの長期接続 | -| `background/message-router` | Content Scriptからのrequest受信・validation | +| `background/message-router` | Content Scriptからのrequest受信・validation(popup state 共有) | +| `background/menu-controller` | context menu登録・selectionText取得・popup開き・selection経由翻訳 | | `background/translation-session` | requestId、AbortController、active stream管理 | | `background/ollama-client` | Ollama REST API呼び出し(fetch + NDJSON streaming) | | `background/settings-service` | storage読書き、default、validation | -| `popup` | 有効/無効、簡易設定、Options起動 | +| `popup` | 設定UI + 翻訳結果モード(streaming表示、copy/regenerate、error表示) | | `options` | 全設定UI | | `shared/settings-schema` | 設定型、既定値、範囲 | | `shared/messages` | runtime message型定義 | @@ -113,7 +117,7 @@ Shadow DOM Popover "manifest_version": 3, "name": "Selected Text Translator", "version": "0.1.0", - "permissions": ["storage"], + "permissions": ["storage", "menus"], "host_permissions": ["http://localhost/*", "http://127.0.0.1/*"], "background": { "scripts": ["background.js"], @@ -143,7 +147,7 @@ Shadow DOM Popover - `scripting` 権限は初期版では付与しない。 - `tabs` 権限は付与しない。 - localhost以外のhost permissionは初期版では付与しない。 -- Firefoxのmatch patternはポート番号指定に対応していない(Firefox bug 1362809 / 1468162)。`http://localhost/*` および `http://127.0.0.1/*` は任意ポートに一致するため、実際に通信してよい接続先はアプリ側Host validatorで `http://localhost:<port>` / `http://127.0.0.1:<port>` のみに限定する。 +- `menus` permission は selection context の翻訳のためのみに使用する。 --- @@ -250,6 +254,41 @@ ERROR - Abortされた旧requestのchunkはrequestId不一致なら無視。 - Error時は再生成可能な状態に戻す。 +### 7.4 Action Popup 翻訳結果モード + +Pdf viewerやcontext menu経由翻訳では Action Popup が翻訳結果を表示する。状態機械と表示内容はPopoverと同様。 + +状態: + +```text +IDLE +STARTING +STREAMING +COMPLETED +ERROR +CANCELLED +``` + +* `starting`: 翻訳 request を backgroundへ送信し、まだ started/chunk を受け取っていない状態 +* `streaming`: chunk受信中 +* `completed`: chunk完了(最後のchunkはdone:trueと推定) +* `error`: ollamaエラーまたは request中止 +* `cancelled`: ユーザー cancel(request abort または新規 request abort) + +表示内容: + +| 要素 | 内容 | +|---|---| +| Header | 翻訳結果 | +| TranslatedText | streaming翻訳本文 | +| Meta | Model名 / Ollama | +| Footer | コピー / 再生成 / 状態表示 / 「設定へ戻る」 | + +* popupが streaming中に開かれた場合でも、その時点での translation textを表示し、以降のchunkを継続受信する。 +* popupが閉じても requestを自動cancelしない。 +* 新しい翻訳request開始時に古いrequestは abortされる(既存方針)。 +* request sourceは backgroundで metadataとして識別してよい(例: `"content"` / `"context-menu"`)。ただし Ollama request生成処理は共通(prompt、settings、options生成)。 + --- ## 8. Runtime通信設計 @@ -365,6 +404,29 @@ Ollama streaming開始 ### 9.1 古いchunk対策 受信chunkごとにactive requestIdを確認し、不一致なら破棄する。 +### 9.2 Translation state 共有(popup連携) + +Backgroundは context menu / content script いずれの経由でも translation stateを保持し、popupが開いた時に最新状態を取得できるようにする。 + +```js +// module internal state (background) +translationState = { + requestId, // string + sourceText, // string (validated) + translatedText, // accumulated chunk text + status, // idle | starting | streaming | completed | error | cancelled + model, // settings.model when started + error, // error message (or null) + startedAt, // epoch ms + source // 'content' | 'context-menu' +} +``` + +* popupからの `GET_POPUP_STATE` runtime messageでこのstateを返す。 +* `onChunk` ごとに state を更新(translatedText累積、status=streaming)。 +* completed/error/cancelledでもstateを更新する。popupが開き直されたときに最終状態を表示できる。 +* 新しい翻訳request開始時には state を初期化(古いrequestはabort)。 + --- ## 10. OllamaClient設計 @@ -742,6 +804,13 @@ BackgroundのOllamaClientからモデル一覧取得APIを呼び、Settings UIã� - chat stream - Abort +### Phase 4.5: Context Menu 翻訳(PDF Viewer対応) +- menus permission 追加 +- menu-controller.js(selection context menu 登録、selectionText取得、popup open) +- message-routerへ request 生成共通化(port / menu / popup 経由の request が同じ設定・prompt・options生成を利用) +- backgroundに translation state 共有(requestId/sourceText/translatedText/status/model/error) +- Action Popup 翻訳結果モード表示 + ### Phase 5: Settings - storage.local - Basic settings @@ -784,6 +853,8 @@ BackgroundのOllamaClientからモデル一覧取得APIを呼び、Settings UIã� | prompt builder | fixed + user prompt結合 | | message validation | malformed message拒否 | | length limit | 境界値 | +| selectionText validation | context menu selectionText の型/trim/空/最大長 | +| popup state | status遷移、requestId/sourceText/translatedText/model/error更新 | ### 23.2 Integration @@ -797,6 +868,17 @@ Content request → complete ``` +Context menu flow: + +```text +menus selection (selectionText) +→ validation +→ translation request +→ mock Ollama stream +→ TranslationSession +→ popup result state更新 +``` + Abortテスト: ```text @@ -814,6 +896,7 @@ B chunks only displayed - 選択文字列にHTMLタグ表現を含むページ - CSSが強く指定されたページ - スクロール位置が深いページ +- Firefox内蔵PDF Viewer(context menu翻訳) 確認: - 選択位置近傍UI @@ -825,6 +908,11 @@ B chunks only displayed - close - settings persistence - Ollama down/up +- context menu表示(通常ページ / PDF Viewer) +- context menu翻訳→popup streaming表示 +- popup copy / regenerate +- 新規翻訳時の旧request cancel +- PDF上のHTML/script風文字列が実行されないこと --- @@ -848,6 +936,8 @@ B chunks only displayed - [ ] LLM出力への`innerHTML`なし - [ ] 不要permissionsなし - [ ] iframe初期対応なし +- [ ] `menus` permission は selection context translationのみに使用 +- [ ] PDF Viewer内部DOM / PDF.js内部オブジェクトへのアクセスなし --- |
