diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e604d3..beff1d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,31 @@ All notable changes to ThunderClaw are documented here. Current releases ship only the Thunderbird extension. Earlier component releases remain recorded below. +## Thunderbird extension [0.3.0] - 2026-10-25 + +### Added + +- Review compose edits with local Changes, Original, and Proposed views. Inline + comparisons preserve supported text, list, and rich formatting; large changes + fall back to complete removed and inserted blocks without truncating content. +- Expand the same preview into a separate review window with a scrolling + comparison and visible Apply/Undo controls, without another model request. +- Show elapsed generation time and Cancel controls for compose edits and + received-message summaries and translations. Running and cancelled state + survives reopening the popup; late cancelled results are not used. Providers + may continue processing after cancellation. +- Choose Fireworks AI directly in connection settings, using an exact full model, + router, or deployment ID. Default to JSON Schema, support provider-specific + thinking choices, and reject context overflow instead of reducing the output + allowance. Model discovery is unavailable for this preset. + +### Fixed + +- Shorten displayed Fireworks model names while preserving full IDs in requests. +- Keep Apply/Undo and cancellation bound to the exact draft, preview, and run + across popup reopening and expanded review. Preserve Thunderbird's separate + Send decision. + ## Thunderbird extension [0.2.4] - 2026-10-24 ### Changed diff --git a/README.md b/README.md index 0fea8f6..a2e8e94 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ eligibility rules. ## Your inference connection ThunderClaw connects directly to OpenAI, OpenRouter, -DeepSeek, Ollama, LM Studio, or a custom OpenAI-compatible endpoint. Choose the +DeepSeek, Fireworks AI, Ollama, LM Studio, or a custom OpenAI-compatible endpoint. Choose the endpoint and model in settings, provide a key if needed, grant host access, save, and run the synthetic connection test. Keys are remembered locally across restarts. They are not synchronized or an encrypted vault. @@ -92,7 +92,7 @@ See [architecture](docs/architecture.md) and [security and privacy](docs/securit ## Installation Install from [Thunderbird Add-ons](https://addons.thunderbird.net/en-US/thunderbird/addon/thunderclaw/), then open ThunderClaw settings. Choose a provider, -load or enter a model, save your key and connection, grant host access, and click +load a model where available or enter its exact ID, save your key and connection, grant host access, and click **Test connection**. Your key stays saved across restarts. For local development, build the XPI from this checkout and install it through diff --git a/docs/architecture.md b/docs/architecture.md index 833c329..12bf2be 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -19,10 +19,17 @@ The existing local compose lifecycle and product types retain some legacy protoc ## Inference boundary -One configured provider and model are active. Presets cover OpenAI, OpenRouter, DeepSeek, Ollama, LM Studio, and custom compatible servers. Configuration contains a canonical API base, model, structured-output mode, response-token limit, thinking level, and optional writing style. Provider differences are explicit; there is no automatic endpoint/model fallback. +One configured provider and model are active. Presets cover OpenAI, OpenRouter, DeepSeek, Fireworks AI, Ollama, LM Studio, and custom compatible servers. Configuration contains a canonical API base, model, structured-output mode, response-token limit, thinking level, and optional writing style. Provider differences are explicit; there is no automatic endpoint/model fallback. Calls use nonstreaming Chat Completions with bounded JSON output. JSON Schema is preferred where supported; JSON-object mode accommodates DeepSeek and compatible servers. Both modes use the same local product validation. Model names and API errors are untrusted data. Reject tool calls, refusals, truncation, invalid shapes, oversize output, and stale completions. +Compose review compares the captured original with the locally validated +replacement in a text-only renderer. The expanded review is a fixed extension +page bound by the background to its opening compose tab and exact job. Its +sender, job, and suggestion identities are checked before Apply or Undo; it +cannot select another source tab. Both review surfaces share one background job +and one mutation gate. + Remote endpoints require HTTPS. HTTP is restricted to explicit loopback addresses. Build only fixed models/chat-completions routes under the configured base, reject redirects, and omit cookies. Host permissions do not replace exact application-level origin/path checks. ## Credentials and context diff --git a/docs/compatibility.md b/docs/compatibility.md index cd81b10..3923b55 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -20,17 +20,21 @@ See the [product contract](product-contract.md) for eligibility rules. ## Inference API ThunderClaw supports OpenAI-compatible, nonstreaming Chat Completions. Presets -provide API bases and request defaults for OpenAI, OpenRouter, DeepSeek, Ollama, -and LM Studio; Custom accepts another compatible base. The extension appends -`/models` for discovery and `/chat/completions` for generation. A model ID can be -entered manually when discovery is unavailable. It never silently chooses a -model, changes endpoints, or retries with a fallback model. +provide API bases and request defaults for OpenAI, OpenRouter, DeepSeek, +Fireworks AI, Ollama, and LM Studio; Custom accepts another compatible base. +The extension appends `/models` for discovery where supported and +`/chat/completions` for generation. Fireworks model discovery is unavailable; +enter an exact full model, router, or deployment ID manually. ThunderClaw never +silently chooses a model, changes endpoints, or retries with a fallback model. The endpoint/model must accept the configured structured-output mode and return a complete, bounded JSON result. JSON Schema is the default for most presets; -DeepSeek defaults to JSON object compatibility. Local validation is equally -strict in both modes. Chat-only models without suitable structured output may -fail despite accepting ordinary chat requests. +DeepSeek defaults to JSON object compatibility; Fireworks defaults to JSON Schema. +Local validation is equally strict in both modes. Chat-only models without suitable +structured output may fail despite accepting ordinary chat requests. +Fireworks requests reject cases where the prompt plus requested output budget +exceeds the context window, instead of silently reducing the output allowance. +An over-limit request fails without applying partial output. Response limits and reasoning controls differ by provider and model. Presets select a request vocabulary, not a discovered capability guarantee. See diff --git a/docs/inference-prompts.md b/docs/inference-prompts.md index a6c357d..2acaae0 100644 --- a/docs/inference-prompts.md +++ b/docs/inference-prompts.md @@ -37,6 +37,7 @@ levels are opt-in, and saved changes require a fresh connection test. | OpenAI | `max_completion_tokens`, optional `reasoning_effort` | [Effort values vary by model](https://developers.openai.com/api/docs/guides/reasoning?api-mode=chat); some cannot turn reasoning off. | | OpenRouter | `max_tokens`, optional `reasoning` | [Unified efforts](https://openrouter.ai/docs/guides/best-practices/reasoning-tokens) depend on the routed model; some require reasoning. Explicit provider fallback remains disabled. | | DeepSeek | `max_tokens`, `thinking`, optional `reasoning_effort` | [Thinking controls](https://api-docs.deepseek.com/guides/thinking_mode/) support Off and low/high/max effort. Model default omits both controls. | +| Fireworks AI | `max_tokens`, `context_length_exceeded_behavior: error`, optional `reasoning_effort` | [Chat Completions](https://docs.fireworks.ai/api-reference/post-chatcompletions) uses the exact model/router/deployment ID entered in settings. Model default omits effort; explicit Off/Low/Medium/High/Very high/Maximum may be rejected or reinterpreted by the selected model. Requests fail when the prompt plus requested output budget exceeds the context window, instead of reducing the output allowance. | | Ollama | `max_tokens`, optional `reasoning_effort` | [Compatibility controls](https://docs.ollama.com/api/openai-compatibility) depend on local model metadata; unsupported named levels may resolve to the model default. | | LM Studio | `max_tokens`, optional `reasoning_effort` | Requires a server version with chat reasoning controls and a compatible model; see the [API changelog](https://lmstudio.ai/changelog/lmstudio). | | Custom | `max_tokens`, optional `reasoning_effort` | Explicit efforts require support for OpenAI-style reasoning controls. Model default omits the effort parameter. | @@ -45,7 +46,7 @@ These selectors describe request formats, not discovered model capabilities. The extension does not query extra capability routes or silently substitute a different effort/model. A connection test checks whether the request and result are accepted; it cannot prove that a server honored an effort setting internally. -Use Model default when uncertain about a local or custom model's support. +Use Model default when uncertain about a model's support. Reasoning can consume the generation budget before the final JSON response, leaving too little room for a newsletter translation. Responses reaching their diff --git a/docs/installation.md b/docs/installation.md index 0e40c40..606d289 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -23,8 +23,9 @@ release XPI rather than a local rebuild. 1. Open ThunderClaw settings from its add-on entry. 2. Choose a provider. Check the API base URL, including any required base path. 3. Enter an API key if the endpoint requires one. Keys are remembered locally. -4. Click **Load models** and choose a model, or enter its exact **Model ID**. - Loading the list does not select a model automatically. +4. Click **Load models** where available and choose a model, or enter its exact + **Model ID**. Fireworks AI requires manual entry of its full model, router, + or deployment ID. Loading a list does not select a model automatically. 5. Review **Structured output**, **Response token limit**, and **Thinking level**. Start with the preset defaults. Writing style is optional. 6. Confirm the data-sharing notice, click **Save connection**, and approve @@ -37,6 +38,7 @@ release XPI rather than a local rebuild. | OpenAI | `https://api.openai.com/v1` | Supply your API key and a compatible model. | | OpenRouter | `https://openrouter.ai/api/v1` | Supply your key; compatibility depends on the selected model and route. | | DeepSeek | `https://api.deepseek.com` | Supply your key; JSON object compatibility and thinking Off are preset defaults. | +| Fireworks AI | `https://api.fireworks.ai/inference/v1` | Supply your key and copy the exact full model, router, or deployment ID from Fireworks; model discovery is unavailable. JSON Schema and Model default thinking are preset defaults. | | Ollama | `http://127.0.0.1:11434/v1` | Start your local server and make a compatible model available. | | LM Studio | `http://127.0.0.1:1234/v1` | Start the local API server and load a compatible model. | | Custom | Enter your API base | Requires compatible models and Chat Completions routes with structured JSON output. | @@ -64,24 +66,32 @@ not increase the model's input context or remove other safety limits. Thinking defaults to **Off** for DeepSeek and **Model default** for other presets. Available levels depend on the provider, and individual models may reject or -ignore a level. The connection test checks acceptance, not the server's internal +reinterpret a level. Fireworks offers Off, Low, Medium, High, Very high, and +Maximum in addition to Model default; start with Model default when support is +unknown. The connection test checks acceptance, not the server's internal reasoning behavior. For long translations, reducing thinking can leave more room for the answer. See [response controls](inference-prompts.md#response-limit-and-thinking). ## Use and troubleshoot In a draft, select eligible text and open ThunderClaw. Generate a proposal, -review the Preview, then Apply it. Undo restores the accepted previous state +review Changes, Original, or Proposed in the popup or choose **Expand review** +for a larger window, then Apply the whole suggestion. Undo restores the accepted previous state when no intervening change makes that unsafe. Sending remains Thunderbird's normal separate action. For a received message, choose Summarize or Translate. Translation defaults to automatic source-language detection; choose the target language. Translations can be restored to the original, and summaries appear in a separate card. - -If model discovery fails, verify the server is running, endpoint, key, and host -permission. You can enter a known model ID manually. If structured output is -unsupported, choose **JSON object compatibility** and save/retest. Both modes +While a model is running, ThunderClaw shows elapsed time and Cancel. A cancelled +result is not used, though the provider may continue processing or charging. + +If model discovery is available but fails, verify the server is running, +endpoint, key, and host permission. You can enter a known model ID manually. +Fireworks requires an exact full ID, such as +`accounts/fireworks/models/deepseek-v4p1-flash-1017`; this is an example, not a +preselected model. If structured output is unsupported, choose **JSON object +compatibility** and save/retest. Both modes receive the same local validation. A response-limit error means the result was incomplete: increase the limit within the model's supported range, reduce thinking, or use a shorter input. Partial output is never applied. For connection diff --git a/docs/privacy-policy.md b/docs/privacy-policy.md index f726da8..8c522cd 100644 --- a/docs/privacy-policy.md +++ b/docs/privacy-policy.md @@ -24,4 +24,6 @@ Change or remove a saved connection/key in settings. Local removal does not revo A loopback server can forward requests to cloud services. OpenRouter may route to an upstream provider. Choose the model/server configuration appropriate for your data. ThunderClaw does not silently switch your connection. +For Fireworks AI, its [data-handling documentation](https://docs.fireworks.ai/guides/security_compliance/data_handling) says open-model prompts and outputs are not persistently retained unless you opt in, while request metadata is logged and transient caches may hold content. Provider and account settings govern actual handling; ThunderClaw cannot control those policies. + Models cannot send email or change recipients, attachments, or headers. Compose edits require Preview and Apply, with stale-state checks and Undo. Reading translations are reversible and summaries are displayed separately. diff --git a/docs/product-contract.md b/docs/product-contract.md index 75f8841..8d1043b 100644 --- a/docs/product-contract.md +++ b/docs/product-contract.md @@ -8,12 +8,22 @@ record of how the behavior was developed. ThunderClaw can improve, proofread, shorten, retone, translate, summarize, or follow a custom instruction for an eligible selection. -Generate does not mutate the draft. Preview shows only a validated result. +Generate does not mutate the draft. Preview shows a local Changes comparison by +default, with Original and Proposed views and an optional expanded review window. +The comparison is built from the captured source and validated replacement, +never from model-supplied markup. A long comparison scrolls without hiding the +whole-suggestion Apply and Undo controls. Closing the review window keeps the +current suggestion available in the compose popup. Apply is allowed only while the compose generation, connection binding, selected provider/model, target identity, target hash, context hash, headers, recipients, and attachments still match the authoritative state captured for the result. Undo is rejected after a newer user edit or another state change makes exact restoration unsafe. +An elapsed timer and Cancel are available while a compose or message model run +is active. Cancel invalidates the local run; a late response cannot become a +preview or displayed message result. A result already being committed to the +message display cannot be cancelled. Cancelling cannot guarantee the remote +provider stops processing or charging. ## Plain selected text diff --git a/docs/security-and-privacy.md b/docs/security-and-privacy.md index 9378a54..d47d441 100644 --- a/docs/security-and-privacy.md +++ b/docs/security-and-privacy.md @@ -11,7 +11,7 @@ have their own retention, privacy, and billing policies. The project operates no inference or analytics service. A local API address can still route to hosted models. OpenRouter can route to upstream providers. Choose a connection appropriate for your mail. See the [privacy policy](privacy-policy.md) -for what is transmitted and stored. +for what is transmitted and stored, including Fireworks data handling. ## Model authority and prompt injection diff --git a/docs/testing.md b/docs/testing.md index 796850d..adf8ef4 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -23,8 +23,8 @@ sequentially when they share the default `build/` directory. | Layer | Coverage | Limits | | --- | --- | --- | -| Deterministic tests | Prompt assembly, strict contracts, provider mappings, credentials, permissions, races, lifecycle, stale results, DOM/Undo rules, workflow guards | Mocked responses do not establish real-model quality or provider availability | -| Real Thunderbird with a synthetic API fixture | Built XPI installation, settings, model picker, key persistence/restart, capture, Preview, Apply, Undo/Redo, and eligible rich formatting | Bounded pinned versions and disposable profile configuration | +| Deterministic tests | Prompt assembly, strict contracts, provider mappings, credentials, permissions, review-window bindings, cancellation races, local comparison rendering, lifecycle, stale results, DOM/Undo rules, workflow guards | Mocked responses do not establish real-model quality or provider availability | +| Real Thunderbird with a synthetic API fixture | Built XPI installation, settings, model picker, key persistence/restart, capture, expanded review, Apply, Undo/Redo, compose and received elapsed timers and Cancel, and eligible rich formatting | Bounded pinned versions and disposable profile configuration | | Live model trials | Request acceptance, faithful transformations, translations, formatting, injection evaluations | Model/server/version-specific evidence; never universal compatibility | | Release qualification | Checksummed build-once XPI, Linux/Windows Thunderbird gates, reviewer-source reproduction, protected promotion and public signed-XPI verification | Successful upload alone does not mean marketplace review is complete | diff --git a/e2e/thunderbird/received.py b/e2e/thunderbird/received.py index a25d433..69932b7 100644 --- a/e2e/thunderbird/received.py +++ b/e2e/thunderbird/received.py @@ -84,7 +84,7 @@ def state(client) -> dict[str, Any]: """, [STATE]) -def open_action(client) -> None: +def open_action(client, allow_cancelled: bool = False) -> None: for handle in client.chrome_window_handles: client.switch_to_window(handle) if harness.chrome(client, 'return document.documentElement.getAttribute("windowtype");') == "mail:3pane": @@ -106,10 +106,12 @@ def open_action(client) -> None: return true; """) harness.wait_until("received action popup", lambda: harness.chrome(client, harness.FIND_EXTENSION_DOCUMENT, ["message-popup.html"])) - harness.wait_until("received newsletter captured", lambda: "message characters" in (harness.extension_document(client, "message-popup.html", "text", "#status") or "")) + harness.wait_until("received newsletter captured", lambda: ( + "message characters" in (harness.extension_document(client, "message-popup.html", "text", "#status") or "") + or (allow_cancelled and "Cancelled" in (harness.extension_document(client, "message-popup.html", "text", "#status") or "")))) -def exercise(client) -> dict[str, Any]: +def exercise(client, stub_state) -> dict[str, Any]: # Close the compose popup and compose window before opening the received UI. harness.extension_document(client, "popup.html", "close", None) harness.chrome(client, 'Services.wm.getMostRecentWindow("msgcompose")?.close(); return true;') @@ -146,6 +148,26 @@ def exercise(client) -> dict[str, Any]: harness.wait_until("received translation shown again", lambda: state(client)["html"] == translated["html"]) harness.extension_document(client, "message-popup.html", "click", "#dismiss") harness.wait_until("received dismiss restores original", lambda: state(client)["html"] == original["html"]) + open_action(client) + stub_state.arm_delay("summarize") + try: + if harness.extension_document(client, "message-popup.html", "click", "#run") is not True: + raise RuntimeError("Delayed received Summary was unavailable") + if not stub_state.delay_entered.wait(timeout=10): + raise RuntimeError("Delayed received request did not reach the synthetic provider") + harness.wait_until("received elapsed timer", lambda: (harness.extension_document(client, "message-popup.html", "text", "#elapsed") or "") not in ("", "Elapsed: 0s"), 5) + if harness.extension_document(client, "message-popup.html", "click", "#cancel") is not True: + raise RuntimeError("Received Cancel was unavailable") + harness.wait_until("received Cancelled state", lambda: "Cancelled" in (harness.extension_document(client, "message-popup.html", "text", "#status") or ""), 5) + finally: + stub_state.release_delay() + if state(client)["html"] != original["html"] or state(client)["summaryCards"] != 0: + raise AssertionError("Cancelled received result changed the message") + harness.extension_document(client, "message-popup.html", "close", None) + harness.wait_until("received Cancel popup closed", lambda: not harness.chrome(client, harness.FIND_EXTENSION_DOCUMENT, ["message-popup.html"])) + open_action(client, allow_cancelled=True) + harness.wait_until("received Cancel survives reopen", lambda: "Cancelled" in (harness.extension_document(client, "message-popup.html", "text", "#status") or ""), 5) return {"status": "passed", "sourceCharacters": len(original["text"]), "summaryPreservesOriginal": True, "automaticSourceLanguage": True, "translationPreservesFormattingNodes": True, - "showOriginal": True, "showTranslation": True, "dismissRestoresOriginal": True} + "showOriginal": True, "showTranslation": True, "dismissRestoresOriginal": True, + "elapsedTimer": True, "cancelledResultUnused": True, "cancelSurvivesReopen": True} diff --git a/e2e/thunderbird/run_compose.py b/e2e/thunderbird/run_compose.py index d96727c..99afe7c 100644 --- a/e2e/thunderbird/run_compose.py +++ b/e2e/thunderbird/run_compose.py @@ -20,7 +20,7 @@ from marionette_driver.by import By from marionette_driver.marionette import Marionette -from stub_inference import RICH_FORMATTING_INSTRUCTION, RICH_SOURCE_BLOCKS, RICH_SOURCE_TEXT, start_stub +from stub_inference import RICH_FORMATTING_INSTRUCTION, RICH_SOURCE_BLOCKS, RICH_SOURCE_TEXT, State, start_stub EXTENSION_ID = "thunderclaw@addons.thunderbird.net" @@ -664,12 +664,32 @@ def exercise_popup(client: Marionette) -> dict[str, Any]: lambda: extension_document(client, "popup.html", "text", "#status") == "Preview ready", 30.0, ) + if extension_document(client, "popup.html", "click", '[data-view="proposed"]') is not True: + raise RuntimeError("Proposed review tab was unavailable") preview = extension_document(client, "popup.html", "text", "#replacement") after_preview = compose_body(client) if after_preview != before_preview: raise AssertionError("Generate/Preview mutated the compose body") if preview != EXPECTED: raise AssertionError(f"Unexpected preview: {preview!r}") + if extension_document(client, "popup.html", "click", "#expand") is not True: + raise RuntimeError("Expanded review was unavailable") + wait_until("expanded review", lambda: chrome(client, FIND_EXTENSION_DOCUMENT, ["review.html"])) + try: + wait_until("expanded review ready", lambda: extension_document(client, "review.html", "text", "#status") == "Preview ready", 5.0) + except TimeoutError as error: + status = extension_document(client, "review.html", "text", "#status") + detail = extension_document(client, "review.html", "text", "#error") + raise RuntimeError(f"Expanded review did not become ready: {status!r}; {detail!r}") from error + if extension_document(client, "review.html", "click", '[data-view="proposed"]') is not True: + raise RuntimeError("Expanded Proposed tab was unavailable") + if extension_document(client, "review.html", "text", "#replacement") != EXPECTED: + raise AssertionError("Expanded review changed the proposed text") + if extension_document(client, "review.html", "click", "#close") is not True: + raise RuntimeError("Expanded review could not be closed") + wait_until("expanded review closed", lambda: not chrome(client, FIND_EXTENSION_DOCUMENT, ["review.html"])) + open_compose_action(client) + wait_until("reopened compose preview", lambda: extension_document(client, "popup.html", "text", "#status") == "Preview ready") if extension_document(client, "popup.html", "click", "#apply") is not True: raise RuntimeError("Apply button was not available") wait_until( @@ -699,6 +719,35 @@ def exercise_popup(client: Marionette) -> dict[str, Any]: } +def exercise_compose_cancel(client: Marionette, stub_state: State) -> dict[str, Any]: + source = "Synthetic delayed draft." + extension_document(client, "popup.html", "close", None) + wait_until("compose popup closed before Cancel fixture", lambda: not chrome(client, FIND_EXTENSION_DOCUMENT, ["popup.html"])) + if set_and_select_body(client, source) != source: + raise AssertionError("Delayed compose fixture was not selected") + open_compose_action(client) + wait_until("delayed compose selection", lambda: extension_document(client, "popup.html", "text", "#status") == f"{len(source)} characters selected") + stub_state.arm_delay("improve", source) + try: + if extension_document(client, "popup.html", "click", "#run") is not True: + raise RuntimeError("Delayed compose Generate was unavailable") + if not stub_state.delay_entered.wait(timeout=10): + raise RuntimeError("Delayed compose request did not reach the synthetic provider") + wait_until("compose elapsed timer", lambda: (extension_document(client, "popup.html", "text", "#elapsed") or "") not in ("", "Elapsed: 0s"), 5) + if extension_document(client, "popup.html", "click", "#cancel") is not True: + raise RuntimeError("Compose Cancel was unavailable") + wait_until("compose Cancelled state", lambda: "Cancelled" in (extension_document(client, "popup.html", "text", "#status") or ""), 5) + finally: + stub_state.release_delay() + if compose_body(client) != source: + raise AssertionError("Cancelled compose result changed the draft") + extension_document(client, "popup.html", "close", None) + wait_until("compose Cancel popup closed", lambda: not chrome(client, FIND_EXTENSION_DOCUMENT, ["popup.html"])) + open_compose_action(client) + wait_until("compose Cancel survives reopen", lambda: "Cancelled" in (extension_document(client, "popup.html", "text", "#status") or ""), 5) + return {"elapsedTimer": True, "cancelledResultUnused": True, "cancelSurvivesReopen": True} + + def exercise_body_text_list_popup(client: Marionette) -> dict[str, Any]: action = open_compose_action(client) wait_until("Body Text compose action popup", lambda: chrome(client, FIND_EXTENSION_DOCUMENT, ["popup.html"])) @@ -716,6 +765,8 @@ def exercise_body_text_list_popup(client: Marionette) -> dict[str, Any]: if extension_document(client, "popup.html", "click", "#run") is not True: raise RuntimeError("Generate preview button was unavailable for Body Text") wait_until("Body Text list preview", lambda: extension_document(client, "popup.html", "text", "#status") == "Preview ready", 30.0) + if extension_document(client, "popup.html", "click", '[data-view="proposed"]') is not True: + raise RuntimeError("Proposed review tab was unavailable") preview_html = extension_document(client, "popup.html", "html", "#replacement") after_preview = body_text_state(client) if preview_html != BODY_TEXT_PREVIEW: @@ -766,6 +817,8 @@ def exercise_paragraph_expansion_popup(client: Marionette) -> dict[str, Any]: if extension_document(client, "popup.html", "click", "#run") is not True: raise RuntimeError("Generate preview button was unavailable for paragraph expansion") wait_until("paragraph expansion preview", lambda: extension_document(client, "popup.html", "text", "#status") == "Preview ready", 30.0) + if extension_document(client, "popup.html", "click", '[data-view="proposed"]') is not True: + raise RuntimeError("Proposed review tab was unavailable") preview_html = extension_document(client, "popup.html", "html", "#replacement") after_preview = paragraph_state(client) if preview_html != PARAGRAPH_PREVIEW or after_preview != original: @@ -817,6 +870,8 @@ def exercise_rich_formatting_popup(client: Marionette) -> dict[str, Any]: # selected original paragraph's exact text, blocks, and all three marks. wait_until("source-verified rich formatting preview", lambda: extension_document(client, "popup.html", "text", "#status") == "Preview ready", 30.0) + if extension_document(client, "popup.html", "click", '[data-view="proposed"]') is not True: + raise RuntimeError("Proposed review tab was unavailable") preview_html = extension_document(client, "popup.html", "html", "#replacement") after_preview = paragraph_state(client) if preview_html != RICH_FORMATTING_PREVIEW or after_preview != original: @@ -861,6 +916,7 @@ def run_trial( xpi: Path, artifacts: Path, stub_port: int, + stub_state: State, expected_version: str, expected_build_id: str, thunderbird: Path, @@ -951,6 +1007,7 @@ def run_trial( if initial != ORIGINAL: raise AssertionError(f"Unexpected initial compose body: {initial!r}") compose = exercise_popup(client) + compose_cancel = exercise_compose_cancel(client, stub_state) body_text_list = None paragraph_expansion = None rich_formatting = None @@ -975,7 +1032,7 @@ def run_trial( raise AssertionError(f"Unexpected rich formatting fixture: {fixture!r}") rich_formatting = exercise_rich_formatting_popup(client) import received - received_result = received.exercise(client) + received_result = received.exercise(client, stub_state) result = { "receivedMessage": received_result, "trial": number, @@ -985,6 +1042,7 @@ def run_trial( "installedExtensionId": installed_id, "connection": connection, "compose": compose, + "composeCancel": compose_cancel, "bodyTextListConversion": body_text_list, "paragraphExpansion": paragraph_expansion, "richSourceFormatting": rich_formatting, @@ -1084,6 +1142,7 @@ def main() -> int: args.xpi, args.artifacts, server.server_address[1], + state, actual_version, actual_build_id, args.thunderbird, diff --git a/e2e/thunderbird/stub_inference.py b/e2e/thunderbird/stub_inference.py index a60069a..ae67253 100644 --- a/e2e/thunderbird/stub_inference.py +++ b/e2e/thunderbird/stub_inference.py @@ -36,11 +36,33 @@ class State: def __init__(self) -> None: self.lock = threading.Lock() self.requests: list[dict[str, Any]] = [] + self.delay_action: str | None = None + self.delay_text: str | None = None + self.delay_release = threading.Event() + self.delay_entered = threading.Event() def record(self, method: str, path: str, metadata: dict[str, Any] | None) -> None: with self.lock: self.requests.append({"method": method, "path": path, **(metadata or {})}) + def arm_delay(self, action: str, text: str | None = None) -> None: + with self.lock: + self.delay_action = action + self.delay_text = text + self.delay_release.clear() + self.delay_entered.clear() + + def maybe_delay(self, prompt: dict[str, Any]) -> None: + with self.lock: + if prompt.get("action") != self.delay_action or (self.delay_text is not None and prompt.get("text") != self.delay_text): + return + self.delay_action = None + self.delay_entered.set() + self.delay_release.wait(timeout=20) + + def release_delay(self) -> None: + self.delay_release.set() + class Handler(BaseHTTPRequestHandler): server: "StubServer" @@ -55,7 +77,11 @@ def _json(self, status: int, value: dict[str, Any]) -> None: self.send_header("Content-Length", str(len(encoded))) self.send_header("Cache-Control", "no-store") self.end_headers() - self.wfile.write(encoded) + try: + self.wfile.write(encoded) + except (BrokenPipeError, ConnectionResetError): + # A synthetic Cancel can close the client while its held response is released. + pass def _authorized(self) -> bool: if self.headers.get("Authorization") == f"Bearer {INFERENCE_KEY}": @@ -101,6 +127,7 @@ def do_POST(self) -> None: "segments": len(prompt.get("segments", [])), "sourceCharacters": sum(len(text) for text in prompt.get("segments", [])), }) + self.server.state.maybe_delay(prompt) if "segments" in prompt: # Only the adapter's exact bounded connection probe may be short. # Every received UI operation must forward the long fixture, diff --git a/package-lock.json b/package-lock.json index 19bce8a..d336954 100644 --- a/package-lock.json +++ b/package-lock.json @@ -595,7 +595,7 @@ }, "packages/thunderbird-extension": { "name": "@thunderclaw/thunderbird-extension", - "version": "0.2.4", + "version": "0.3.0", "license": "Apache-2.0" } } diff --git a/packages/thunderbird-extension/package.json b/packages/thunderbird-extension/package.json index 2e6a6bd..8ec4831 100644 --- a/packages/thunderbird-extension/package.json +++ b/packages/thunderbird-extension/package.json @@ -1,6 +1,6 @@ { "name": "@thunderclaw/thunderbird-extension", - "version": "0.2.4", + "version": "0.3.0", "private": true, "type": "module", "description": "ThunderClaw extension for Mozilla Thunderbird", diff --git a/packages/thunderbird-extension/src/background-coordinator.ts b/packages/thunderbird-extension/src/background-coordinator.ts index 9494280..cdd0d1a 100644 --- a/packages/thunderbird-extension/src/background-coordinator.ts +++ b/packages/thunderbird-extension/src/background-coordinator.ts @@ -25,12 +25,15 @@ type ComposeSession = { type ComposeJob = { jobId: string; - state: "running" | "ready" | "applied" | "error"; + state: "running" | "ready" | "applied" | "cancelled" | "error"; + startedAt: number; + mutation?: "apply" | "undo"; + settled?: Promise; binding: ConnectionBinding; abort: AbortController; result?: { suggestionId: string; original: string; replacement: string; summary: string; applied?: true; selectionShape?: "text-range" | "flat-list-items" | "rich-blocks"; listKind?: "ul" | "ol"; - replacementItems?: string[]; replacementBlocks?: RichBlock[] }; + originalItems?: string[]; replacementItems?: string[]; originalBlocks?: RichBlock[]; replacementBlocks?: RichBlock[] }; error?: string; }; @@ -46,7 +49,8 @@ type MessageCapture = { type MessageJob = { jobId: string; - state: "running" | "ready" | "error"; + state: "running" | "finishing" | "ready" | "cancelled" | "error"; + startedAt: number; action: "translate" | "summarize"; requestId: string; runId: string; @@ -108,6 +112,7 @@ const featureErrorMessages = new Set([ "The preview is no longer available.", "The preview is stale.", "The preview was discarded.", + "The review window could not be opened.", "The rich-block suggestion is invalid or stale. Run ThunderClaw again.", "The selected list changed. Run ThunderClaw again on the current draft.", "The selected text changed. Run ThunderClaw again on the current draft.", @@ -161,10 +166,10 @@ function validPopupMessage(message: Record): boolean { "popup.initialize": [], "popup.job": [], "popup.transform": ["agentId", "action", "instruction"], "popup.apply": ["suggestionId", "jobId"], "popup.undo": ["suggestionId", "jobId"], - "popup.discard": ["jobId"], "popup.cancel": ["jobId"], + "popup.discard": ["jobId"], "popup.cancel": ["jobId"], "popup.expand": ["jobId"], "messagePopup.initialize": [], "messagePopup.job": [], "messagePopup.transform": ["agentId", "action", "sourceLanguage", "targetLanguage"], - "messagePopup.original": ["jobId"], "messagePopup.translation": ["jobId"], "messagePopup.dismiss": ["jobId"], + "messagePopup.original": ["jobId"], "messagePopup.translation": ["jobId"], "messagePopup.dismiss": ["jobId"], "messagePopup.cancel": ["jobId"], }; const required = fields[message.type as string]; if (!required || Object.keys(message).length !== required.length + 2 @@ -183,6 +188,15 @@ function validPopupMessage(message: Record): boolean { return true; } +function validReviewMessage(message: Record): boolean { + const fields: Record = { "review.initialize": [], "review.job": ["jobId"], + "review.apply": ["jobId", "suggestionId"], "review.undo": ["jobId", "suggestionId"], "review.discard": ["jobId"] }; + const required = fields[message.type as string]; + return Boolean(required) && Object.keys(message).length === required.length + 1 + && Object.keys(message).every((key) => key === "type" || required.includes(key)) + && required.every((key) => typeof message[key] === "string" && (message[key] as string).length > 0 && (message[key] as string).length <= 128); +} + export function installFeatureBackground(controller: FeatureConnectionController): void { const minimumSameKindListThunderbirdMajor = 153; const runtimeCapabilityInstance = randomId(); @@ -209,6 +223,11 @@ export function installFeatureBackground(controller: FeatureConnectionController const jobs = new Map(); const messageJobs = new Map(); const messageCaptures = new Map(); + const pendingComposeCancelCleanups = new Map>(); + const pendingComposeStarts = new Map>(); + const pendingMessageStarts = new Map>(); + const reviewBindings = new Map(); + const reviewOpening = new Map>(); const lifecycles = new WeakMap(); function lifecycleFor(lease: BackgroundFeatureLease): DirectComposeLifecycleRegistry { @@ -333,24 +352,40 @@ export function installFeatureBackground(controller: FeatureConnectionController } async function initialize(tabId: number): Promise { - const existingJob = jobs.get(tabId); - if (existingJob?.state === "ready" && existingJob.result) { - const suggestion = suggestions.get(existingJob.result.suggestionId); + let existingJob = jobs.get(tabId); + const terminalOnEntry = existingJob && ["cancelled", "error"].includes(existingJob.state); + if (existingJob?.state === "ready" && existingJob.result && !existingJob.mutation) { + const expectedResult = existingJob.result; + const suggestion = suggestions.get(expectedResult.suggestionId); try { if (!suggestion) throw new Error("The preview is no longer available."); await validateSuggestionSnapshot(tabId, suggestion); } catch { - discardSuggestionState(tabId); - captures.delete(tabId); - existingJob.state = "error"; - existingJob.error = "The draft changed after this preview was created. Run ThunderClaw again."; - delete existingJob.result; + if (jobs.get(tabId) === existingJob && existingJob.state === "ready" + && existingJob.result === expectedResult && !existingJob.mutation) { + discardSuggestionState(tabId); + captures.delete(tabId); + existingJob.state = "error"; + existingJob.error = "The draft changed after this preview was created. Run ThunderClaw again."; + delete existingJob.result; + } } } const selection = existingJob && ["running", "ready", "applied"].includes(existingJob.state) ? captures.get(tabId) || { text: existingJob.result?.original || "" } : await composeMessage(tabId, { type: "thunderclaw.capture" }); if (!existingJob) captures.set(tabId, selection); + else if (terminalOnEntry && jobs.get(tabId) === existingJob) { + const previous = captures.get(tabId); + captures.set(tabId, selection); + if (!previous || previous.text !== selection.text || previous.selectionShape !== selection.selectionShape + || JSON.stringify(previous.items ?? null) !== JSON.stringify(selection.items ?? null) + || JSON.stringify(previous.blocks ?? null) !== JSON.stringify(selection.blocks ?? null)) { + jobs.delete(tabId); + existingJob = undefined; + } + } + else if (existingJob.state === "error") captures.set(tabId, selection); const lease = await controller.acquireFeatureLease(); const requestId = randomId(); const [hello, listed] = await Promise.all([lease.client.hello(), lease.client.listAgents(requestId)]); @@ -362,7 +397,7 @@ export function installFeatureBackground(controller: FeatureConnectionController async function transform(tabId: number, agentId: string, action: any, instruction: string, job: ComposeJob, snapshot: any): Promise { const lease = await controller.acquireFeatureLease(); - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) throw new Error("The ThunderClaw connection changed."); + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) throw new Error("The ThunderClaw connection changed."); if (snapshot.selectionShape === "flat-list-items" || snapshot.selectionShape === "rich-blocks") { const hello = await lease.client.hello(); if (!sameConnectionBinding(hello.binding, lease.binding) || !bindingCurrent(lease.binding)) throw new Error("The ThunderClaw connection changed."); @@ -374,9 +409,9 @@ export function installFeatureBackground(controller: FeatureConnectionController } } await requireUsableAgent(lease, agentId, job.abort.signal); - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) throw new Error("The preview was discarded."); + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) throw new Error("The preview was discarded."); const session = await ensureSession(tabId, agentId, lease); - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding)) { + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding)) { if (sessions.get(tabId) === session) sessions.delete(tabId); await session.lifecycle.close(session.composeId).catch(() => undefined); throw new Error("The preview was discarded."); @@ -392,7 +427,7 @@ export function installFeatureBackground(controller: FeatureConnectionController await session.lifecycle.close(session.composeId).catch(() => undefined); throw error; } - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) { + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding) || !sameConnectionBinding(job.binding, lease.binding)) { if (sessions.get(tabId) === session) sessions.delete(tabId); await session.lifecycle.close(session.composeId).catch(() => undefined); throw new Error("The preview was discarded."); @@ -409,7 +444,7 @@ export function installFeatureBackground(controller: FeatureConnectionController ...(snapshot.selectionShape === "rich-blocks" ? { blocks: structuredClone(snapshot.blocks) } : {}) }, limits: { maxOperations: 1, maxOutputCharacters: 12_000 }, }, { signal: job.abort.signal }); - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding) || !sameConnectionBinding(completion.binding, job.binding)) throw new Error("The preview is stale."); + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding) || !sameConnectionBinding(completion.binding, job.binding)) throw new Error("The preview is stale."); const operation = completion.value.operations[0]!; if ((snapshot.selectionShape === "flat-list-items" && operation.type !== "replace_flat_list_items") || (snapshot.selectionShape === "rich-blocks" && operation.type !== "replace_rich_blocks") @@ -420,7 +455,7 @@ export function installFeatureBackground(controller: FeatureConnectionController const [{ contextHash: postContextHash }, postTargetHash, postGenerationState] = await Promise.all([ composeContext(tabId, postSnapshot), targetFingerprint(postSnapshot), composeStateFingerprint(tabId), ]); - if (postContextHash !== contextHash || postTargetHash !== targetHash || postGenerationState.hash !== composeState.hash + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || postContextHash !== contextHash || postTargetHash !== targetHash || postGenerationState.hash !== composeState.hash || postGenerationState.identity !== composeState.identity) { throw new Error("The draft changed while ThunderClaw was generating the preview. Run ThunderClaw again."); } @@ -438,9 +473,9 @@ export function installFeatureBackground(controller: FeatureConnectionController selectionShape: snapshot.selectionShape === "flat-list-items" ? "flat-list-items" : snapshot.selectionShape === "rich-blocks" ? "rich-blocks" : "text-range", ...(snapshot.selectionShape === "flat-list-items" && operation.type === "replace_flat_list_items" ? { - listKind: snapshot.listKind, replacementItems: [...operation.items], + listKind: snapshot.listKind, originalItems: [...snapshot.items], replacementItems: [...operation.items], } : {}), ...(snapshot.selectionShape === "rich-blocks" && operation.type === "replace_rich_blocks" ? { - replacementBlocks: structuredClone(operation.blocks), + originalBlocks: structuredClone(snapshot.blocks), replacementBlocks: structuredClone(operation.blocks), } : {}) }; } finally { if (session.activeRunId === runId) delete session.activeRunId; @@ -449,7 +484,7 @@ export function installFeatureBackground(controller: FeatureConnectionController function composeJobView(job?: ComposeJob): any { if (!job) return null; - return { jobId: job.jobId, state: job.state, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }; + return { jobId: job.jobId, state: job.state, startedAt: job.startedAt, ...(job.mutation ? { mutation: job.mutation } : {}), ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }; } function discardSuggestionState(tabId: number): void { @@ -469,6 +504,18 @@ export function installFeatureBackground(controller: FeatureConnectionController return cleanups; } + function cancelRunningCompose(tabId: number, jobId: string): any { + const job = jobs.get(tabId); + if (!validJobId(jobId) || !job || job.jobId !== jobId) throw new Error("This preview is no longer current."); + if (job.state !== "running") return composeJobView(job); + job.state = "cancelled"; + const cleanups = cancelComposeJob(tabId, false); + const cleanup = Promise.allSettled([...cleanups, ...(job.settled ? [job.settled] : [])]).then(() => undefined); + pendingComposeCancelCleanups.set(tabId, cleanup); + void cleanup.finally(() => { if (pendingComposeCancelCleanups.get(tabId) === cleanup) pendingComposeCancelCleanups.delete(tabId); }); + return composeJobView(job); + } + async function startTransform(tabId: number, agentId: string, action: any, instruction: string): Promise { if (!instruction.trim()) { if (action === "tone") throw new Error("Describe the tone you want before generating a preview."); @@ -477,6 +524,8 @@ export function installFeatureBackground(controller: FeatureConnectionController } const existing = jobs.get(tabId); if (existing?.state === "running") return composeJobView(existing); + if (existing?.mutation) throw new Error("The preview is no longer current."); + if (pendingComposeCancelCleanups.has(tabId)) await pendingComposeCancelCleanups.get(tabId); discardSuggestionState(tabId); jobs.delete(tabId); const captured = captures.get(tabId) || await composeMessage(tabId, { type: "thunderclaw.capture" }); @@ -491,13 +540,13 @@ export function installFeatureBackground(controller: FeatureConnectionController } captures.set(tabId, snapshot); const lease = await controller.acquireFeatureLease(); - const job: ComposeJob = { jobId: randomId(), state: "running", binding: lease.binding, abort: new AbortController() }; + const job: ComposeJob = { jobId: randomId(), state: "running", startedAt: Date.now(), binding: lease.binding, abort: new AbortController() }; jobs.set(tabId, job); - void transform(tabId, agentId, action, instruction, job, snapshot).then((result) => { - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding)) return; + job.settled = transform(tabId, agentId, action, instruction, job, snapshot).then((result) => { + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding)) return; job.state = "ready"; job.result = result; }).catch((error) => { - if (jobs.get(tabId) !== job || !bindingCurrent(job.binding)) return; + if (jobs.get(tabId) !== job || job.state !== "running" || job.abort.signal.aborted || !bindingCurrent(job.binding)) return; job.state = "error"; job.error = featureErrorMessage(error); }); return composeJobView(job); @@ -506,13 +555,16 @@ export function installFeatureBackground(controller: FeatureConnectionController async function applySuggestion(tabId: number, suggestionId: string, jobId: string): Promise { const suggestion = suggestions.get(suggestionId); const job = jobs.get(tabId); - if (!validJobId(jobId) || !suggestion || !job || suggestion.tabId !== tabId || suggestion.jobId !== job.jobId || jobId !== job.jobId + if (!validJobId(jobId) || !suggestion || !job || job.state !== "ready" || job.mutation || suggestion.tabId !== tabId || suggestion.jobId !== job.jobId || jobId !== job.jobId || !bindingCurrent(suggestion.binding)) throw new Error("This suggestion is no longer available."); + job.mutation = "apply"; + try { let current; try { current = await validateSuggestionSnapshot(tabId, suggestion); } catch { suggestions.delete(suggestionId); + job.state = "error"; job.error = "The draft changed after this suggestion was created. Run ThunderClaw again."; delete job.result; throw new Error("The draft changed after this suggestion was created. Run ThunderClaw again."); } if (jobs.get(tabId) !== job) throw new Error("The draft changed after this suggestion was created. Run ThunderClaw again."); @@ -522,20 +574,65 @@ export function installFeatureBackground(controller: FeatureConnectionController ...(suggestion.operationType === "replace_flat_list_items" ? { replacement: suggestion.replacement, replacementItems: suggestion.replacementItems } : {}), ...(suggestion.operationType === "replace_rich_blocks" ? { replacementBlocks: suggestion.replacementBlocks } : {}) }); + if (jobs.get(tabId) !== job || !bindingCurrent(job.binding)) throw new Error("This suggestion is no longer available."); suggestions.delete(suggestionId); undos.set(suggestionId, { tabId, jobId: job.jobId, undoId: result.undoId }); captures.delete(tabId); job.state = "applied"; job.result = { ...job.result!, applied: true }; return composeJobView(job); + } finally { delete job.mutation; } } async function undoSuggestion(tabId: number, suggestionId: string, jobId: string): Promise { const undo = undos.get(suggestionId); const job = jobs.get(tabId); - if (!validJobId(jobId) || !undo || !job || undo.tabId !== tabId || undo.jobId !== job.jobId || jobId !== job.jobId) throw new Error("This applied change can no longer be undone."); + if (!validJobId(jobId) || !undo || !job || job.state !== "applied" || job.mutation || undo.tabId !== tabId || undo.jobId !== job.jobId || jobId !== job.jobId) throw new Error("This applied change can no longer be undone."); + job.mutation = "undo"; + try { const result = await composeMessage(tabId, { type: "thunderclaw.undo", undoId: undo.undoId }); + if (jobs.get(tabId) !== job || !bindingCurrent(job.binding)) throw new Error("This applied change can no longer be undone."); undos.delete(suggestionId); captures.delete(tabId); jobs.delete(tabId); return result; + } finally { delete job.mutation; } + } + + async function checkedReviewJob(sourceTabId: number, jobId: string, validateReady = false): Promise { + const job = jobs.get(sourceTabId); + if (!validJobId(jobId) || !job || job.jobId !== jobId || !["ready", "applied"].includes(job.state) + || !job.result || !bindingCurrent(job.binding)) throw new Error("This preview is no longer current."); + if (validateReady && job.state === "ready" && !job.mutation) { + const suggestion = suggestions.get(job.result.suggestionId); + if (!suggestion) throw new Error("The preview is no longer available."); + await validateSuggestionSnapshot(sourceTabId, suggestion); + if (jobs.get(sourceTabId) !== job || job.state !== "ready" || !bindingCurrent(job.binding)) throw new Error("This preview is no longer current."); + } + return job; + } + + async function expandReview(sourceTabId: number, jobId: string): Promise<{ opened: true }> { + await checkedReviewJob(sourceTabId, jobId, true); + const existing = [...reviewBindings.values()].find((item) => item.sourceTabId === sourceTabId && item.jobId === jobId); + if (existing) { + try { await browser.windows.update(existing.windowId, { focused: true }); return { opened: true }; } + catch { for (const [id, value] of reviewBindings) if (value === existing) reviewBindings.delete(id); } + } + const pending = reviewOpening.get(jobId); + if (pending) { await pending; return { opened: true }; } + const opening = (async () => { + // Thunderbird can load an extension page before windows.create resolves. + // Bind the real tab first, then navigate it to the review page. + const created = await browser.windows.create({ type: "popup", url: "about:blank", width: 900, height: 700, allowScriptsToClose: true }); + const reviewTabId = created?.tabs?.[0]?.id ?? (created?.id ? (await browser.tabs.query({ windowId: created.id }))[0]?.id : undefined); + if (!Number.isSafeInteger(reviewTabId) || reviewTabId <= 0 || !Number.isSafeInteger(created?.id)) throw new Error("The review window could not be opened."); + try { await checkedReviewJob(sourceTabId, jobId, true); } + catch (error) { await browser.windows.remove(created.id).catch(() => undefined); throw error; } + reviewBindings.set(reviewTabId, { sourceTabId, jobId, windowId: created.id }); + try { await browser.tabs.update(reviewTabId, { url: browser.runtime.getURL("review.html") }); } + catch (error) { reviewBindings.delete(reviewTabId); await browser.windows.remove(created.id).catch(() => undefined); throw error; } + })(); + reviewOpening.set(jobId, opening); + try { await opening; } finally { if (reviewOpening.get(jobId) === opening) reviewOpening.delete(jobId); } + return { opened: true }; } async function ensureMessageDisplayScript(tabId: number): Promise { @@ -563,7 +660,7 @@ export function installFeatureBackground(controller: FeatureConnectionController function messageJobView(job?: MessageJob): any { if (!job) return null; - return { jobId: job.jobId, state: job.state, action: job.action, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }; + return { jobId: job.jobId, state: job.state, startedAt: job.startedAt, action: job.action, ...(job.result ? { result: job.result } : {}), ...(job.error ? { error: job.error } : {}) }; } async function initializeMessage(tabId: number): Promise { @@ -592,32 +689,45 @@ export function installFeatureBackground(controller: FeatureConnectionController return [cleanup]; } + function cancelRunningMessage(tabId: number, jobId: string): any { + const job = messageJobs.get(tabId); + if (!validJobId(jobId) || !job || job.jobId !== jobId) throw new Error("This message result is no longer current."); + if (job.state !== "running") return messageJobView(job); + job.state = "cancelled"; + job.abort.abort(); + void job.lease.client.cancelMessageTransform({ protocolVersion: 1, requestId: randomId(), transformRequestId: job.requestId, runId: job.runId, messageHash: job.messageHash }).catch(() => undefined); + return messageJobView(job); + } + async function startMessageTransform(tabId: number, agentId: string, action: "translate" | "summarize", sourceLanguage: string | null, targetLanguage: string | null): Promise { const existing = messageJobs.get(tabId); - if (existing?.state === "running") return messageJobView(existing); + if (existing?.state === "running" || existing?.state === "finishing") return messageJobView(existing); const captured = messageCaptures.get(tabId); if (!captured) throw new Error("The displayed message is no longer available. Reopen ThunderClaw."); const requestId = randomId(); const runId = randomId(); const abort = new AbortController(); const lease = await controller.acquireFeatureLease(); if (messageCaptures.get(tabId) !== captured || !bindingCurrent(lease.binding)) throw new Error("The displayed message changed."); - const job: MessageJob = { jobId: randomId(), state: "running", action, requestId, runId, messageId: captured.messageId, messageHash: captured.messageHash, displayInstanceId: captured.displayInstanceId, lease, abort }; + const job: MessageJob = { jobId: randomId(), state: "running", startedAt: Date.now(), action, requestId, runId, messageId: captured.messageId, messageHash: captured.messageHash, displayInstanceId: captured.displayInstanceId, lease, abort }; messageJobs.set(tabId, job); try { await requireUsableAgent(lease, agentId, abort.signal); - if (messageJobs.get(tabId) !== job || messageCaptures.get(tabId) !== captured || !bindingCurrent(lease.binding)) { + if (messageJobs.get(tabId) !== job || job.state !== "running" || abort.signal.aborted || messageCaptures.get(tabId) !== captured || !bindingCurrent(lease.binding)) { throw new Error("The displayed message changed."); } } catch (error) { - if (messageJobs.get(tabId) === job) messageJobs.delete(tabId); + if (messageJobs.get(tabId) === job && job.state !== "cancelled") messageJobs.delete(tabId); abort.abort(); + if (job.state === "cancelled") return messageJobView(job); throw error; } void (async () => { try { const completion = await lease.client.transformMessage({ protocolVersion: 1, requestId, runId, agentId, action, sourceLanguage, targetLanguage, messageHash: captured.messageHash, document: { subject: captured.subject, author: captured.author, segments: captured.segments }, limits: { maxSegments: 400, maxOutputCharacters: 200_000 } }, { signal: abort.signal }); - if (messageJobs.get(tabId) !== job || !bindingCurrent(lease.binding) || !sameConnectionBinding(completion.binding, lease.binding)) return; + if (messageJobs.get(tabId) !== job || job.state !== "running" || abort.signal.aborted || !bindingCurrent(lease.binding) || !sameConnectionBinding(completion.binding, lease.binding)) return; const fresh = await captureDisplayedMessage(tabId); - if (messageJobs.get(tabId) !== job || fresh.messageId !== job.messageId || fresh.messageHash !== job.messageHash || fresh.displayInstanceId !== job.displayInstanceId || !bindingCurrent(lease.binding)) throw new Error("The displayed message changed while ThunderClaw was working."); + if (messageJobs.get(tabId) !== job || job.state !== "running" || abort.signal.aborted) return; + if (fresh.messageId !== job.messageId || fresh.messageHash !== job.messageHash || fresh.displayInstanceId !== job.displayInstanceId || !bindingCurrent(lease.binding)) throw new Error("The displayed message changed while ThunderClaw was working."); + job.state = "finishing"; if (action === "translate") { await messageDisplayCall(tabId, { type: "thunderclaw.message.translate", displayInstanceId: job.displayInstanceId, segments: completion.value.result.segments }); if (messageJobs.get(tabId) !== job || !bindingCurrent(lease.binding)) return; @@ -628,7 +738,7 @@ export function installFeatureBackground(controller: FeatureConnectionController if (messageJobs.get(tabId) !== job || !bindingCurrent(lease.binding)) return; job.state = "ready"; job.result = completion.value.result; } catch (error) { - if (messageJobs.get(tabId) !== job || !bindingCurrent(job.lease.binding)) return; + if (messageJobs.get(tabId) !== job || job.state === "cancelled" || !bindingCurrent(job.lease.binding)) return; job.state = "error"; job.error = featureErrorMessage(error); } })(); @@ -644,6 +754,8 @@ export function installFeatureBackground(controller: FeatureConnectionController } function closeTab(tabId: number): Promise[] { + reviewBindings.delete(tabId); + for (const [id, binding] of reviewBindings) if (binding.sourceTabId === tabId) reviewBindings.delete(id); const cleanups = [...cancelComposeJob(tabId), ...invalidateMessage(tabId)]; const session = sessions.get(tabId) ?? pendingSessions.get(tabId); sessions.delete(tabId); pendingSessions.delete(tabId); captures.delete(tabId); jobs.delete(tabId); messageJobs.delete(tabId); messageCaptures.delete(tabId); @@ -672,7 +784,14 @@ export function installFeatureBackground(controller: FeatureConnectionController async function dispatchPopupMessage(message: any): Promise { if (message.type === "messagePopup.initialize") return initializeMessage(message.tabId); - if (message.type === "messagePopup.transform") return startMessageTransform(message.tabId, message.agentId, message.action, message.sourceLanguage, message.targetLanguage); + if (message.type === "messagePopup.transform") { + const pending = pendingMessageStarts.get(message.tabId); + if (pending) return pending; + const starting = startMessageTransform(message.tabId, message.agentId, message.action, message.sourceLanguage, message.targetLanguage); + pendingMessageStarts.set(message.tabId, starting); + void starting.finally(() => { if (pendingMessageStarts.get(message.tabId) === starting) pendingMessageStarts.delete(message.tabId); }).catch(() => undefined); + return starting; + } if (message.type === "messagePopup.job") return Promise.resolve(messageJobView(messageJobs.get(message.tabId))); if (message.type === "messagePopup.original" || message.type === "messagePopup.translation") { const job = messageJobs.get(message.tabId); @@ -680,30 +799,55 @@ export function installFeatureBackground(controller: FeatureConnectionController return messageDisplayCall(message.tabId, { type: message.type === "messagePopup.original" ? "thunderclaw.message.original" : "thunderclaw.message.showTranslation", displayInstanceId: job.displayInstanceId }); } if (message.type === "messagePopup.dismiss") return dismissMessageResult(message.tabId, message.jobId); + if (message.type === "messagePopup.cancel") return cancelRunningMessage(message.tabId, message.jobId); if (message.type === "popup.initialize") return initialize(message.tabId); - if (message.type === "popup.transform") return startTransform(message.tabId, message.agentId, message.action, message.instruction); + if (message.type === "popup.transform") { + const pending = pendingComposeStarts.get(message.tabId); + if (pending) return pending; + const starting = startTransform(message.tabId, message.agentId, message.action, message.instruction); + pendingComposeStarts.set(message.tabId, starting); + void starting.finally(() => { if (pendingComposeStarts.get(message.tabId) === starting) pendingComposeStarts.delete(message.tabId); }).catch(() => undefined); + return starting; + } if (message.type === "popup.job") return Promise.resolve(composeJobView(jobs.get(message.tabId))); if (message.type === "popup.discard") { const job = jobs.get(message.tabId); - if (!validJobId(message.jobId) || job?.jobId !== message.jobId) return Promise.reject(new Error("This preview is no longer current.")); + if (!validJobId(message.jobId) || !job || job.jobId !== message.jobId || job.mutation) return Promise.reject(new Error("This preview is no longer current.")); void Promise.allSettled(cancelComposeJob(message.tabId)); captures.delete(message.tabId); return Promise.resolve({ discarded: true }); } if (message.type === "popup.apply") return applySuggestion(message.tabId, message.suggestionId, message.jobId); if (message.type === "popup.undo") return undoSuggestion(message.tabId, message.suggestionId, message.jobId); - if (message.type === "popup.cancel") { - const job = jobs.get(message.tabId); - if (!validJobId(message.jobId) || job?.jobId !== message.jobId) return Promise.reject(new Error("This preview is no longer current.")); - const active = sessions.get(message.tabId)?.activeRunId; - void Promise.allSettled(cancelComposeJob(message.tabId, false)); - return Promise.resolve({ cancelled: Boolean(active) }); - } + if (message.type === "popup.expand") return expandReview(message.tabId, message.jobId); + if (message.type === "popup.cancel") return cancelRunningCompose(message.tabId, message.jobId); return undefined; } browser.runtime.onMessage.addListener((message: any, sender: any) => { if (!message || typeof message !== "object" || typeof message.type !== "string" - || (!message.type.startsWith("popup.") && !message.type.startsWith("messagePopup."))) return undefined; + || (!message.type.startsWith("popup.") && !message.type.startsWith("messagePopup.") && !message.type.startsWith("review."))) return undefined; + if (message.type.startsWith("review.")) { + if (sender?.id !== browser.runtime.id || sender?.url !== browser.runtime.getURL("review.html") + || !Number.isSafeInteger(sender?.tab?.id) || !validReviewMessage(message)) { + return Promise.reject(new Error("This ThunderClaw action is only available from its popup.")); + } + return (async () => { + const binding = reviewBindings.get(sender.tab.id); + if (!binding) throw new Error("This preview is no longer current."); + const source = await browser.tabs.get(binding.sourceTabId); + if (source?.type !== "messageCompose") throw new Error("This preview is no longer current."); + const job = await checkedReviewJob(binding.sourceTabId, binding.jobId, message.type === "review.initialize"); + if (message.jobId !== undefined && message.jobId !== binding.jobId) throw new Error("This preview is no longer current."); + if (message.type === "review.initialize" || message.type === "review.job") return { job: composeJobView(job) }; + if (message.type === "review.apply") return { job: await applySuggestion(binding.sourceTabId, message.suggestionId, binding.jobId) }; + if (message.type === "review.undo") return { job: await undoSuggestion(binding.sourceTabId, message.suggestionId, binding.jobId) }; + if (message.type === "review.discard") { + if (job.state !== "ready" || job.mutation) throw new Error("This preview is no longer current."); + void Promise.allSettled(cancelComposeJob(binding.sourceTabId)); captures.delete(binding.sourceTabId); return { discarded: true }; + } + return undefined; + })().catch((error) => { throw new Error(featureErrorMessage(error)); }); + } const reading = message.type.startsWith("messagePopup."); const expectedUrl = browser.runtime.getURL(reading ? "message-popup.html" : "popup.html"); // Thunderbird may include tab metadata for an extension action popup. diff --git a/packages/thunderbird-extension/src/inference-client.ts b/packages/thunderbird-extension/src/inference-client.ts index 1ed8387..5ec47e7 100644 --- a/packages/thunderbird-extension/src/inference-client.ts +++ b/packages/thunderbird-extension/src/inference-client.ts @@ -1,6 +1,6 @@ import * as C from "./direct-client-contract.js"; import * as V from "./direct-client-validators.js"; -import { canonicalizeInferenceBase, DEFAULT_MAX_RESPONSE_TOKENS, PROVIDER_PRESETS, validateInferenceConfiguration, type InferenceConfiguration } from "./inference-provider.js"; +import { canonicalizeInferenceBase, DEFAULT_MAX_RESPONSE_TOKENS, PROVIDER_PRESETS, supportsModelDiscovery, validateInferenceConfiguration, type InferenceConfiguration } from "./inference-provider.js"; import { bindComposeOutput, bindMessageOutput, composeOutputSchema, inferenceMessages, messageOutputSchema } from "./inference-output.js"; export const CONFIGURED_MODEL_ID = "configured-model"; @@ -273,6 +273,7 @@ export class InferenceClient implements C.ThunderClawDirectClient { model: this.configuration.model, stream: false, n: 1, messages: inferenceMessages(request, schema, this.configuration.writingStyle), response_format: responseFormat, ...(this.configuration.provider === "openai" ? { store: false, max_completion_tokens: this.configuration.maxResponseTokens ?? DEFAULT_MAX_RESPONSE_TOKENS } : { max_tokens: this.configuration.maxResponseTokens ?? DEFAULT_MAX_RESPONSE_TOKENS }), + ...(this.configuration.provider === "fireworks" ? { context_length_exceeded_behavior: "error" } : {}), ...reasoningParameters(this.configuration), ...(this.configuration.provider === "openrouter" ? { provider: { require_parameters: true, allow_fallbacks: false } } : {}), }, signal)); @@ -292,6 +293,7 @@ export class InferenceClient implements C.ThunderClawDirectClient { catch { failure("contract", "INVALID_INFERENCE_JSON", "The model returned invalid JSON content."); } } async listModels(options?: C.DirectCallOptions): Promise { + if (!supportsModelDiscovery(this.configuration.provider)) failure("capability", "MODEL_DISCOVERY_UNAVAILABLE", "Enter the exact full Fireworks model ID manually."); return this.scope(async (signal) => { const envelope = record(await this.request("/models", undefined, signal)); if (!Array.isArray(envelope.data) || envelope.data.length > 5_000) failure("contract", "INVALID_MODEL_LIST", "The inference server returned an invalid model list."); diff --git a/packages/thunderbird-extension/src/inference-connection-controller.ts b/packages/thunderbird-extension/src/inference-connection-controller.ts index b691862..244ab70 100644 --- a/packages/thunderbird-extension/src/inference-connection-controller.ts +++ b/packages/thunderbird-extension/src/inference-connection-controller.ts @@ -1,6 +1,6 @@ import { DirectClientError, nextConnectionEpoch, sameConnectionBinding, type ConnectionBinding, type ThunderClawDirectClient } from "./direct-client-contract.js"; import { InferenceClient, inferenceFailureMessage } from "./inference-client.js"; -import { canonicalizeInferenceBase, PROVIDER_PRESETS, validateInferenceConfiguration, type InferenceConfiguration } from "./inference-provider.js"; +import { canonicalizeInferenceBase, PROVIDER_PRESETS, supportsModelDiscovery, validateInferenceConfiguration, type InferenceConfiguration } from "./inference-provider.js"; import { canonicalizeApiBase } from "./endpoint-policy.js"; import { IndexedDbInferenceCredentialStore, type InferenceCredentialStore } from "./credential-store.js"; import { randomId } from "./random-id.js"; @@ -26,8 +26,8 @@ export type InferencePublicState = Readonly<{ }>; function record(value: unknown): Record | null { return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : null; } -function fail(kind: "configuration" | "permission" | "cancellation" | "contract", code: string): never { - throw new DirectClientError(kind, code, kind === "permission" ? "Grant access to the selected inference endpoint in settings." : kind === "cancellation" ? "The connection changed. Try the action again." : "Save and test a valid inference connection in settings."); +function fail(kind: "configuration" | "permission" | "cancellation" | "contract" | "capability", code: string): never { + throw new DirectClientError(kind, code, kind === "permission" ? "Grant access to the selected inference endpoint in settings." : kind === "cancellation" ? "The connection changed. Try the action again." : kind === "capability" ? "Enter the exact full Fireworks model ID manually." : "Save and test a valid inference connection in settings."); } function readSettings(value: unknown): SavedSettings | null { const item = record(value); @@ -235,6 +235,7 @@ export class InferenceConnectionController { if (!input || typeof input.model !== "string") fail("configuration", "INVALID_DISCOVERY_CONFIGURATION"); // GET /models requires an endpoint, not a selected inference model. This ID is never inferred or saved. const configuration = validateInferenceConfiguration({ ...input, model: "thunderclaw-model-discovery" }); + if (!supportsModelDiscovery(configuration.provider)) fail("capability", "MODEL_DISCOVERY_UNAVAILABLE"); if (apiKey !== undefined && (typeof apiKey !== "string" || apiKey.length > 4096 || /[\s\u0000-\u001F\u007F]/u.test(apiKey))) fail("configuration", "INVALID_DISCOVERY_KEY"); await this.initialized; await this.tail; if (this.pendingMutations) fail("cancellation", "CONNECTION_CHANGING"); diff --git a/packages/thunderbird-extension/src/inference-provider.ts b/packages/thunderbird-extension/src/inference-provider.ts index d31afb9..b16387e 100644 --- a/packages/thunderbird-extension/src/inference-provider.ts +++ b/packages/thunderbird-extension/src/inference-provider.ts @@ -1,17 +1,20 @@ import { DirectClientError } from "./direct-client-contract.js"; -export type ProviderId = "openai" | "openrouter" | "deepseek" | "ollama" | "lmstudio" | "custom"; +export type ProviderId = "openai" | "openrouter" | "deepseek" | "fireworks" | "ollama" | "lmstudio" | "custom"; export type ReasoningEffort = "default" | "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max"; export const DEFAULT_MAX_RESPONSE_TOKENS = 16_384; // Application guardrail, not a claim about any model's supported token limit. export const MAX_RESPONSE_TOKENS = 131_072; const ALL_REASONING_EFFORTS: readonly ReasoningEffort[] = Object.freeze(["default", "none", "minimal", "low", "medium", "high", "xhigh", "max"]); const DEEPSEEK_REASONING_EFFORTS: readonly ReasoningEffort[] = Object.freeze(["default", "none", "low", "high", "max"]); +const FIREWORKS_REASONING_EFFORTS: readonly ReasoningEffort[] = Object.freeze(["default", "none", "low", "medium", "high", "xhigh", "max"]); const LOCAL_REASONING_EFFORTS: readonly ReasoningEffort[] = Object.freeze(["default", "none", "low", "medium", "high"]); /** Request formats supported by the provider adapter; individual models may support fewer levels. */ export function reasoningEffortsForProvider(provider: ProviderId): readonly ReasoningEffort[] { - return provider === "deepseek" ? DEEPSEEK_REASONING_EFFORTS : provider === "ollama" || provider === "lmstudio" ? LOCAL_REASONING_EFFORTS : ALL_REASONING_EFFORTS; + return provider === "deepseek" ? DEEPSEEK_REASONING_EFFORTS : provider === "fireworks" ? FIREWORKS_REASONING_EFFORTS : provider === "ollama" || provider === "lmstudio" ? LOCAL_REASONING_EFFORTS : ALL_REASONING_EFFORTS; } +/** Fireworks model, router, and deployment IDs are entered manually for this preset. */ +export function supportsModelDiscovery(provider: ProviderId): boolean { return provider !== "fireworks"; } export type InferenceConfiguration = Readonly<{ provider: ProviderId; apiBase: string; @@ -26,6 +29,7 @@ export const PROVIDER_PRESETS = Object.freeze([ { id: "openai", label: "OpenAI", apiBase: "https://api.openai.com/v1", outputMode: "json_schema", requiresKey: true }, { id: "openrouter", label: "OpenRouter", apiBase: "https://openrouter.ai/api/v1", outputMode: "json_schema", requiresKey: true }, { id: "deepseek", label: "DeepSeek", apiBase: "https://api.deepseek.com", outputMode: "json_object", requiresKey: true }, + { id: "fireworks", label: "Fireworks AI", apiBase: "https://api.fireworks.ai/inference/v1", outputMode: "json_schema", requiresKey: true }, { id: "ollama", label: "Ollama", apiBase: "http://127.0.0.1:11434/v1", outputMode: "json_schema", requiresKey: false }, { id: "lmstudio", label: "LM Studio", apiBase: "http://127.0.0.1:1234/v1", outputMode: "json_schema", requiresKey: false }, { id: "custom", label: "Custom", apiBase: "", outputMode: "json_schema", requiresKey: false }, diff --git a/packages/thunderbird-extension/src/manifest.json b/packages/thunderbird-extension/src/manifest.json index 35af4bf..5008012 100644 --- a/packages/thunderbird-extension/src/manifest.json +++ b/packages/thunderbird-extension/src/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 2, "name": "ThunderClaw", "description": "Reviewable AI writing and reading assistance using your chosen provider or local model.", - "version": "0.2.4", + "version": "0.3.0", "browser_specific_settings": { "gecko": { "id": "thunderclaw@addons.thunderbird.net", diff --git a/packages/thunderbird-extension/src/message-popup.html b/packages/thunderbird-extension/src/message-popup.html index 43be0c2..b4d7019 100644 --- a/packages/thunderbird-extension/src/message-popup.html +++ b/packages/thunderbird-extension/src/message-popup.html @@ -32,6 +32,7 @@