Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

fix(enterprise): harden AWS Bedrock error handling (#1981)

Joshuafdded860bb94
diff --git a/.superpowers/sdd/2026-09-01-bedrock-error-handling-review-fixes/final-fix-report.md b/.superpowers/sdd/2026-09-01-bedrock-error-handling-review-fixes/final-fix-report.md
new file mode 100644
index 000000000..8c5f3ac27
--- /dev/null
+++ b/.superpowers/sdd/2026-09-01-bedrock-error-handling-review-fixes/final-fix-report.md
@@ -0,0 +1,37 @@
+# Bedrock Error-Handling Final Fix Report
+
+**Status:** Complete on `fix/bedrock-error-handling`; local only, not pushed or merged.
+
+## Implementation commits
+
+- `4dfd282a` — `fix(enterprise): normalize Bedrock exception diagnostics`
+- `b65965db` — `fix(dictation): skip AutoLearn after clipboard-only paste`
+
+## Changed files
+
+- `src/helpers/enterpriseProviderErrors.js` — reads AWS exception identity from case-insensitive `x-amzn-errortype`, `data.code`, and `data.__type`; safely removes namespace and suffix; retains status and request-ID discovery.
+- `src/helpers/ipcHandlers.js` — computes the paste outcome once, gates AutoLearn monitoring on a real paste, and applies the two required Prettier wraps.
+- `test/helpers/enterpriseAiProviders.test.js` — exercises the installed Bedrock provider with fake 403, 404, and 503 fetch responses.
+- `test/helpers/bedrockRequestPolicy.test.js` — covers mixed-case headers plus `data.code` and `data.__type` normalization.
+- `test/helpers/ipcPasteOutcome.test.js` — proves clipboard-only fallback does not schedule AutoLearn monitoring.
+
+## TDD evidence
+
+- RED: the production-provider/header tests failed because header-only `InvalidClientTokenId` mapped to permission copy and exception diagnostics were absent; the parsed-data normalization test failed for the same missing extraction.
+- RED after correcting the platform fake: the clipboard-only test observed one `startMonitoring` call instead of zero.
+- GREEN: `node --import tsx --test test/helpers/enterpriseAiProviders.test.js test/helpers/bedrockRequestPolicy.test.js test/helpers/ipcPasteOutcome.test.js` passed 24/24.
+
+## Verification
+
+- Focused Bedrock/provider/IPC/cancellation/preload/paste/fallback/managed-routing matrix: 70/70 passed.
+- `npm run typecheck`: passed.
+- `npm run lint`: passed.
+- `npm run format:check`: passed; all matched files use Prettier style.
+- `npm run build:renderer`: passed; existing large-chunk warning only.
+- Plain Node 25 full suite: 3,414 tests; 3,227 passed; 1 failed; 185 skipped; 1 todo. The sole failure is the recorded pre-existing `globalThis.localStorage` runtime assumption in `enterpriseIdentityStoreImports.test.js`.
+- `NODE_OPTIONS=--no-experimental-webstorage npm test`: 3,414 tests; 3,228 passed; 0 failed; 185 skipped; 1 todo.
+
+## Concerns
+
+- No final-wave behavior concern remains. Exact 503, 429, and timeout primary messages and non-retry classifications were preserved.
+- The plain Node 25 experimental web-storage failure remains an unrelated baseline issue; no change was made for it.
diff --git a/docs/superpowers/plans/2026-09-01-bedrock-error-handling-review-fixes.md b/docs/superpowers/plans/2026-09-01-bedrock-error-handling-review-fixes.md
new file mode 100644
index 000000000..6c7ff891e
--- /dev/null
+++ b/docs/superpowers/plans/2026-09-01-bedrock-error-handling-review-fixes.md
@@ -0,0 +1,314 @@
+# Bedrock Error-Handling Review Fixes Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Close all six review findings on the Bedrock error-handling branch with cancellable requests, production-shaped AWS diagnostics, accurate region guidance, and truthful paste fallback state.
+
+**Architecture:** Reuse the existing sender/request registry for single-shot enterprise cleanup, make Bedrock retry waits abort-aware, and apply a per-attempt application timeout. Resolve credential providers before the AI SDK wraps their errors, pass the resolved runtime region to error mapping, and replace the paste IPC's implicit success contract with an explicit `pasted` outcome.
+
+**Tech Stack:** Electron IPC, TypeScript, JavaScript, Vercel AI SDK 6, `@ai-sdk/amazon-bedrock` 4, AWS SDK v3, Node test runner, React renderer.
+
+**Spec:** `docs/superpowers/specs/2026-09-01-bedrock-error-handling-review-fixes-design.md`
+
+## Global Constraints
+
+- Bedrock retry policy remains six total attempts with exponential backoff and random jitter for 503, 429, timeout, and audited safe-network failures only.
+- Authentication, permission, invalid-model, configuration, and user-cancellation failures are never automatically retried.
+- AWS requests remain in the resolved/requested region; no region failover is permitted.
+- `RetryError.lastError`, HTTP status, AWS exception type, AWS request ID, and underlying error fidelity must remain intact.
+- The exact existing 503, 429, and timeout primary message strings must remain byte-for-byte unchanged.
+- “Original dictation pasted without AI cleanup.” appears only after the original text was actually pasted following cleanup failure.
+- The fallback status remains visually quieter and separate from the primary AWS error, and never appears for connection tests, eventual cleanup success, disabled auto-paste, failed/no-op paste, translation, Agent, or selection-edit failure.
+- Technical details remain expandable/copyable.
+- Preserve Azure, Vertex, Agent streaming, translation, selection-edit, and non-cleanup dictation behavior.
+- Follow strict TDD: add each regression test, observe its expected failure, then make the smallest production change that passes it.
+
+---
+
+### Task 1: Abortable Bedrock request lifecycle
+
+**Files:**
+- Modify: `src/helpers/enterpriseProviderErrors.js`
+- Modify: `src/helpers/ipcHandlers.js`
+- Modify: `src/services/ReasoningService.ts`
+- Modify: `preload.js`
+- Modify: `src/types/electron.ts`
+- Modify: `test/helpers/bedrockRequestPolicy.test.js`
+- Modify: `test/helpers/bedrockEnterpriseIpc.test.js`
+- Modify: `test/helpers/preloadAuthBridge.test.js`
+
+**Interfaces:**
+- Consumes: `AgentStreamRequestRegistry.begin(senderId, requestId)`, `.complete(...)`, and `.cancelSender(senderId)`.
+- Produces: `runBedrockRequest(operation, { signal, ...retryOptions })`, where `signal` aborts before an attempt and during backoff.
+- Produces: `window.electronAPI.cancelEnterpriseReasoning(): void`, forwarded as `enterprise-reasoning-cancel`.
+- Preserves: `processEnterpriseReasoning(...)` result shape and every non-Bedrock request path.
+
+- [ ] **Step 1: Add failing retry-policy cancellation tests**
+
+Add a test that starts `runBedrockRequest` with a retryable 503, waits until its injected sleep begins, aborts the supplied controller, and asserts rejection with the abort reason, one operation attempt, and no later retry. The production mutation this catches is a retry delay that ignores cancellation.
+
+```js
+const controller = new AbortController();
+let attempts = 0;
+let releaseSleep;
+const sleeping = new Promise((resolve) => (releaseSleep = resolve));
+const request = runBedrockRequest(
+ async () => {
+ attempts += 1;
+ throw awsError({ name: "ServiceUnavailableException", status: 503 });
+ },
+ {
+ signal: controller.signal,
+ random: () => 0.5,
+ sleep: async (_delay, signal) => {
+ releaseSleep();
+ await new Promise((resolve, reject) => {
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
+ });
+ },
+ }
+);
+await sleeping;
+controller.abort();
+await assert.rejects(request, (error) => error?.name === "AbortError");
+assert.equal(attempts, 1);
+```
+
+- [ ] **Step 2: Run the focused retry test and observe RED**
+
+Run: `node --import tsx --test test/helpers/bedrockRequestPolicy.test.js`
+
+Expected: the cancellation test fails because `runBedrockRequest` neither accepts nor checks `signal`, and its delay cannot be interrupted.
+
+- [ ] **Step 3: Make the Bedrock retry loop abort-aware**
+
+Extend `runBedrockRequest` with an optional `signal`. Check `signal?.throwIfAborted()` before every operation, check again in the catch before classification, and pass the signal into the delay. The default delay must remove its abort listener on both resolution and rejection and reject with `signal.reason` when cancelled.
+
+```js
+async function runBedrockRequest(operation, options = {}) {
+ const { signal, sleep = sleepWithAbort, ...retryOptions } = options;
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ signal?.throwIfAborted();
+ try {
+ return await operation();
+ } catch (error) {
+ signal?.throwIfAborted();
+ // existing classification and six-attempt ceiling
+ await sleep(delay, signal);
+ }
+ }
+}
+```
+
+- [ ] **Step 4: Add failing IPC timeout and cancellation tests**
+
+Extend the IPC harness so `ipcMain.on` listeners are captured and sender fakes expose an integer `id`, `once`, `removeListener`, and `isDestroyed`. Add:
+
+1. A “Check connection” test with a small `timeoutMs` whose fake `generateText` waits for `options.abortSignal` and rejects with that signal's timeout reason. Assert six attempts and the exact existing timeout message.
+2. A cleanup test that starts a Bedrock request, fires `enterprise-reasoning-cancel` for the same sender while the first attempt is pending or in backoff, and asserts its signal aborts without a second attempt.
+3. A preload bridge test asserting `cancelEnterpriseReasoning()` sends `enterprise-reasoning-cancel`.
+
+The production mutations caught are omission of the application timeout, omission of main-process cancellation, sender-crossing cancellation, and cancellation that still retries.
+
+- [ ] **Step 5: Run the IPC/preload tests and observe RED**
+
+Run: `node --import tsx --test test/helpers/bedrockEnterpriseIpc.test.js test/helpers/preloadAuthBridge.test.js`
+
+Expected: timeout signal/cancellation bridge assertions fail because neither exists.
+
+- [ ] **Step 6: Register and propagate enterprise cancellation**
+
+Instantiate a dedicated `AgentStreamRequestRegistry` for single-shot enterprise reasoning. For Bedrock cleanup, begin a request with the renderer sender ID and a generated UUID, attach sender destruction to `cancelSender`, and combine its controller signal with a fresh per-attempt timeout signal. Pass the request controller signal to `runBedrockRequest`, and complete only that controller in `finally`.
+
+Register `ipcMain.on("enterprise-reasoning-cancel", ...)` to cancel only the sending renderer's enterprise requests. Forward it from preload and declare `cancelEnterpriseReasoning?: () => void` in `src/types/electron.ts`. Call it from `ReasoningService.cancelAllRequests()` beside `cancelCloudReason()`.
+
+For “Check connection,” give every Bedrock attempt a fresh bounded `AbortSignal.timeout(config?.timeoutMs || 30_000)` while preserving `maxRetries: 0` and the outer six-attempt policy. Do not change Azure or Vertex connection behavior.
+
+- [ ] **Step 7: Run focused tests and verify GREEN**
+
+Run: `node --import tsx --test test/helpers/bedrockRequestPolicy.test.js test/helpers/bedrockEnterpriseIpc.test.js test/helpers/preloadAuthBridge.test.js test/helpers/audioManagerCancelLifecycle.test.js test/services/enterpriseInferenceErrors.test.js`
+
+Expected: all pass with no new warnings.
+
+- [ ] **Step 8: Run static checks and commit**
+
+Run: `npm run typecheck && npm run lint`
+
+Commit only the named task files:
+
+```bash
+git add src/helpers/enterpriseProviderErrors.js src/helpers/ipcHandlers.js src/services/ReasoningService.ts preload.js src/types/electron.ts test/helpers/bedrockRequestPolicy.test.js test/helpers/bedrockEnterpriseIpc.test.js test/helpers/preloadAuthBridge.test.js
+git commit -m "fix(enterprise): cancel Bedrock cleanup requests"
+```
+
+---
+
+### Task 2: Preserve real AWS credential errors and resolved region
+
+**Files:**
+- Modify: `src/helpers/enterpriseAiProviders.js`
+- Modify: `src/helpers/enterpriseProviderErrors.js`
+- Modify: `src/helpers/ipcHandlers.js`
+- Modify: `test/helpers/enterpriseAiProviders.test.js`
+- Modify: `test/helpers/bedrockRequestPolicy.test.js`
+- Modify: `test/helpers/bedrockEnterpriseIpc.test.js`
+
+**Interfaces:**
+- Consumes: resolved enterprise runtime `{ provider, model, apiKey, enterprise }`.
+- Produces: asynchronous `getEnterpriseAIModel(provider, model, apiKey, enterprise): Promise<LanguageModel>`.
+- Produces: Bedrock models built from already-resolved access key, secret, and optional session token when a profile or managed credential provider is used.
+- Preserves: manual static-key behavior and Azure/Vertex model construction semantics.
+
+- [ ] **Step 1: Add failing production-shaped credential tests**
+
+In `enterpriseAiProviders.test.js`, create an AWS-shaped error carrying `name`, `$metadata.httpStatusCode`, `$metadata.requestId`, and `cause`. Supply a `managedCredentialProvider` that throws that exact object and assert `await getEnterpriseAIModel(...)` rejects with the same object identity. Add a successful credential-provider case and assert the resulting real Bedrock model can reach its fetch boundary without invoking the credential provider again.
+
+Update existing Azure tests to `await getEnterpriseAIModel(...)`; assert their request URLs and authorization headers remain unchanged.
+
+The production mutation caught is passing the provider into `@ai-sdk/amazon-bedrock`, whose installed implementation replaces the original error with a plain `Error`.
+
+- [ ] **Step 2: Run the provider tests and observe RED**
+
+Run: `node --import tsx --test test/helpers/enterpriseAiProviders.test.js`
+
+Expected: original error identity/metadata are lost at the installed AI SDK credential-provider boundary.
+
+- [ ] **Step 3: Resolve Bedrock credentials before AI SDK construction**
+
+Make `getEnterpriseAIModel` and `createBedrockModel` async. Await managed/profile credential providers before calling `createAmazonBedrock`, then pass the resolved `accessKeyId`, `secretAccessKey`, and optional `sessionToken` as static provider options. Keep manual static keys and environment fallback unchanged. Update all three `ipcHandlers.js` call sites to await model creation.
+
+```js
+async function createBedrockModel(model, enterprise) {
+ const region = enterprise?.bedrockRegion || "us-east-1";
+ const credentials = enterprise?.managedCredentialProvider
+ ? await enterprise.managedCredentialProvider()
+ : enterprise?.bedrockProfile
+ ? await fromNodeProviderChain({ profile: enterprise.bedrockProfile })()
+ : null;
+ return createAmazonBedrock({
+ region,
+ ...(credentials
+ ? {
+ accessKeyId: credentials.accessKeyId,
+ secretAccessKey: credentials.secretAccessKey,
+ sessionToken: credentials.sessionToken,
+ }
+ : existingManualCredentialOptions),
+ })(model);
+}
+```
+
+- [ ] **Step 4: Add failing managed-region and managed-expiry IPC tests**
+
+Have the IPC harness resolve a managed Bedrock runtime in `us-west-2` while the renderer config contains another/no region. Throw permission/model/configuration failures and assert mapped copy names `us-west-2`. Throw an `ExpiredTokenException` from the managed credential provider and assert the response preserves status/type/request ID, gives managed sign-in guidance, and does not return an `aws sso login --profile default` command.
+
+The production mutations caught are mapping against stale renderer configuration and treating managed temporary credentials as a manual AWS profile.
+
+- [ ] **Step 5: Add failing safe-network shape tests**
+
+Add table cases for `ENETDOWN`, `EHOSTDOWN`, `UND_ERR_HEADERS_TIMEOUT`, and `UND_ERR_BODY_TIMEOUT` through an `AI_APICallError` cause chain. Assert each retries; assert the two Undici timeout codes map to the exact timeout message while host/network-down codes map to the network message.
+
+- [ ] **Step 6: Run mapping/IPC tests and observe RED**
+
+Run: `node --import tsx --test test/helpers/bedrockRequestPolicy.test.js test/helpers/bedrockEnterpriseIpc.test.js`
+
+Expected: missing codes fail retry/timeout classification, and managed errors name the renderer/default region or profile.
+
+- [ ] **Step 7: Carry runtime context and complete classifications**
+
+Retain each resolved runtime outside its handler `try` so the catch can merge only the actual `bedrockRegion` into mapping context. In `mapBedrockError`, branch expired-token guidance on `config.managedContext`: managed access tells the user to sign out and sign back in to refresh company access and exposes no CLI command; manual profile access retains the existing `aws sso login --profile <profile>` guidance.
+
+Add `ENETDOWN` and `EHOSTDOWN` to safe network failures. Add `UND_ERR_HEADERS_TIMEOUT` and `UND_ERR_BODY_TIMEOUT` to both the safe audited transport list and timeout classification so they retain the exact timeout message.
+
+- [ ] **Step 8: Run focused regression tests and verify GREEN**
+
+Run: `node --import tsx --test test/helpers/enterpriseAiProviders.test.js test/helpers/bedrockRequestPolicy.test.js test/helpers/bedrockEnterpriseIpc.test.js test/services/enterpriseInferenceErrors.test.js test/services/managedEnterpriseRouting.test.js`
+
+Expected: all pass with the original exact 503/429/timeout strings and unchanged Azure tests.
+
+- [ ] **Step 9: Run static checks and commit**
+
+Run: `npm run typecheck && npm run lint`
+
+Commit only the named task files:
+
+```bash
+git add src/helpers/enterpriseAiProviders.js src/helpers/enterpriseProviderErrors.js src/helpers/ipcHandlers.js test/helpers/enterpriseAiProviders.test.js test/helpers/bedrockRequestPolicy.test.js test/helpers/bedrockEnterpriseIpc.test.js
+git commit -m "fix(enterprise): preserve Bedrock credential diagnostics"
+```
+
+---
+
+### Task 3: Report cleanup fallback only after a real paste
+
+**Files:**
+- Modify: `src/helpers/ipcHandlers.js`
+- Modify: `src/helpers/audioManager.js`
+- Modify: `preload.js`
+- Modify: `src/types/electron.ts`
+- Create: `test/helpers/ipcPasteOutcome.test.js`
+- Modify: `test/helpers/audioManagerCleanupFallback.test.js`
+- Modify: `test/helpers/useAudioRecordingCleanupFallback.test.js`
+
+**Interfaces:**
+- Produces: `paste-text` / `window.electronAPI.pasteText(...) => Promise<{ success: true; pasted: boolean }>`.
+- Produces: `AudioManager.safePaste(...) => Promise<boolean>`, true only when `pasted === true`.
+- Preserves: callers that intentionally ignore the paste result and the selection-edit replacement contract.
+
+- [ ] **Step 1: Add failing main-process paste outcome tests**
+
+Build a focused IPC handler harness that invokes the real `paste-text` handler. Assert an active onboarding demo returns `{ success: true, pasted: false }` without calling `clipboardManager.pasteText`, while a normal successful paste returns `{ success: true, pasted: true }` after exactly one clipboard paste.
+
+The production mutation caught is treating a no-op handler resolution as proof text reached another application.
+
+- [ ] **Step 2: Add failing renderer paste/fallback tests**
+
+In the AudioManager test, return `{ success: true, pasted: false }` from the real preload-shaped `pasteText` mock and assert `safePaste` returns false. Keep the hook-level assertion that a false paste does not record cleanup failure, and add a structured-result success case so `{ success: true, pasted: true }` remains the only path that records the fallback after paste.
+
+- [ ] **Step 3: Run focused tests and observe RED**
+
+Run: `node --import tsx --test test/helpers/ipcPasteOutcome.test.js test/helpers/audioManagerCleanupFallback.test.js test/helpers/useAudioRecordingCleanupFallback.test.js`
+
+Expected: onboarding reports implicit success and `safePaste` returns true for the no-op result.
+
+- [ ] **Step 4: Implement the explicit paste contract**
+
+Return `{ success: true, pasted: false }` from the onboarding branch and `{ success: true, pasted: true }` only after `clipboardManager.pasteText` resolves. Update the TypeScript declaration from `Promise<void>` to the structured result. Keep preload as a transparent forwarder.
+
+Update `safePaste` to require the affirmative result:
+
+```js
+const result = await window.electronAPI.pasteText(text, options);
+return result?.pasted === true;
+```
+
+Do not change selection-edit behavior or toast rendering.
+
+- [ ] **Step 5: Run focused regression tests and verify GREEN**
+
+Run: `node --import tsx --test test/helpers/ipcPasteOutcome.test.js test/helpers/audioManagerCleanupFallback.test.js test/helpers/useAudioRecordingCleanupFallback.test.js test/helpers/cleanupFailureToast.test.js test/helpers/audioManagerCancelLifecycle.test.js`
+
+Expected: all pass; no fallback is recorded for onboarding no-op, disabled auto-paste, or failed paste.
+
+- [ ] **Step 6: Run static checks and commit**
+
+Run: `npm run typecheck && npm run lint`
+
+Commit only the named task files:
+
+```bash
+git add src/helpers/ipcHandlers.js src/helpers/audioManager.js preload.js src/types/electron.ts test/helpers/ipcPasteOutcome.test.js test/helpers/audioManagerCleanupFallback.test.js test/helpers/useAudioRecordingCleanupFallback.test.js
+git commit -m "fix(dictation): report only completed fallback pastes"
+```
+
+---
+
+### Final verification
+
+- [ ] Run all focused Bedrock, enterprise, cancellation, paste, fallback-toast, and managed-routing tests.
+- [ ] Run `npm run typecheck`.
+- [ ] Run `npm run lint`.
+- [ ] Run `npm run format:check`.
+- [ ] Run `npm run build:renderer`.
+- [ ] Run `npm test`; compare any failure to the baseline ledger and rerun the complete affected file separately.
+- [ ] Dispatch one fresh whole-branch code reviewer against `abfaf2ba010a7a122a70eb7ec4541324eebaf33d..HEAD` and the complete requirements.
diff --git a/docs/superpowers/specs/2026-09-01-bedrock-error-handling-review-fixes-design.md b/docs/superpowers/specs/2026-09-01-bedrock-error-handling-review-fixes-design.md
new file mode 100644
index 000000000..ecee591f7
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-01-bedrock-error-handling-review-fixes-design.md
@@ -0,0 +1,44 @@
+# Bedrock Error-Handling Review Fixes Design
+
+**Date:** 2026-09-01
+
+**Status:** Approved for implementation
+
+## Goal
+
+Close the six findings from the fresh read-only review of commit `ddf983fd` without changing the established Bedrock messages, retry count, AWS region, fallback-toast hierarchy, or non-Bedrock behavior.
+
+## Binding requirements
+
+1. Retry retryable 503, 429, timeout, and safe network failures with exponential backoff and random jitter, using six total attempts.
+2. Never automatically retry authentication, permission, invalid-model, configuration, or user-cancellation failures.
+3. Never silently switch AWS regions.
+4. Unwrap `RetryError.lastError` before classification.
+5. Preserve HTTP status, AWS exception type, AWS request ID, and the underlying error.
+6. Preserve the exact existing primary messages for Bedrock 503, 429, and timeout failures.
+7. Keep authentication, permission, model, and configuration failures specific and actionable.
+8. Show “Original dictation pasted without AI cleanup.” only after cleanup fails and the original text is actually pasted.
+9. Keep the fallback status visually quieter and separate from the primary AWS error.
+10. Never show the fallback status during connection tests, after eventual cleanup success, or when no paste occurred.
+11. Keep technical details expandable or copyable.
+12. Cover both “Check connection” and dictation cleanup.
+
+## Review findings to close
+
+- Cancellation must abort in-flight Bedrock cleanup and retry backoff in the main process, rather than merely discarding the eventual renderer result.
+- “Check connection” must use a bounded application timeout.
+- Credential-provider failures must cross the real AI SDK boundary without losing their type, status, request ID, cause, or managed/manual context.
+- Managed Bedrock error copy must use the resolved runtime region.
+- The paste IPC contract must distinguish a real paste from the onboarding no-op.
+- The safe-network allowlist must include `ENETDOWN`, `EHOSTDOWN`, `UND_ERR_HEADERS_TIMEOUT`, and `UND_ERR_BODY_TIMEOUT`; the two Undici timeout codes must retain timeout classification and copy.
+
+## Architecture
+
+Use the existing main-process request registry pattern to own Bedrock cleanup cancellation by renderer sender and request ID. Feed its abort signal into each AI SDK attempt and into the retry delay. Resolve AWS credential providers before constructing the Bedrock AI SDK model so the original AWS/Smithy error remains classifiable, and carry the resolved region into mapping context. Finally, make `paste-text` return an explicit `{ success, pasted }` result so renderer fallback state reflects a completed paste rather than a merely resolved IPC call.
+
+## Scope boundaries
+
+- Do not add region failover.
+- Do not change Azure, Vertex, Agent streaming, translation, selection-edit, or non-cleanup dictation routing.
+- Do not change the established toast hierarchy or the exact 503/429/timeout strings.
+- Do not fix unrelated baseline test pollution in this branch.
diff --git a/preload.js b/preload.js
index 21d20db01..79157a38f 100644
--- a/preload.js
+++ b/preload.js
@@ -623,6 +623,7 @@ contextBridge.exposeInMainWorld("electronAPI", {
// Node-only SDKs (AWS/Azure/Google credential providers) can resolve.
processEnterpriseReasoning: (text, modelId, agentName, config) =>
ipcRenderer.invoke("process-enterprise-reasoning", text, modelId, agentName, config),
+ cancelEnterpriseReasoning: () => ipcRenderer.send("enterprise-reasoning-cancel"),
enterpriseStreamStart: (payload) => ipcRenderer.invoke("enterprise-stream-start", payload),
enterpriseStreamCancel: (streamId) => ipcRenderer.invoke("enterprise-stream-cancel", streamId),
onEnterpriseStreamPart: registerListener(
diff --git a/src/components/CleanupFailureToastListener.tsx b/src/components/CleanupFailureToastListener.tsx
index 2cdd80cb6..ae6e8bfaf 100644
--- a/src/components/CleanupFailureToastListener.tsx
+++ b/src/components/CleanupFailureToastListener.tsx
@@ -13,17 +13,25 @@ export default function CleanupFailureToastListener() {
useEffect(() => {
if (pending === 0) return;
- const cause = useCleanupFailureStore.getState().lastMessage;
+ const state = useCleanupFailureStore.getState();
+ const failure = state.lastFailure ?? { message: state.lastMessage };
// Draining first keeps a re-run of this effect from toasting the same failure twice.
if (consumeCleanupFailures() === 0) return;
// The panel may already be hidden after dictation; surface it so the toast is seen.
if (isDictationPanelWindow()) {
window.electronAPI?.showDictationPanel?.();
}
- const description = t("app.toasts.cleanupFailed.description");
+ const title = failure.messageKey
+ ? t(failure.messageKey, failure.messageParams)
+ : failure.message || t("app.toasts.cleanupFailed.title");
+ const description = failure.actionKey ? t(failure.actionKey) : failure.action;
toast({
- title: t("app.toasts.cleanupFailed.title"),
- description: cause ? `${description} ${cause}` : description,
+ title,
+ ...(description ? { description } : {}),
+ secondaryDescription: t("app.toasts.cleanupFailed.description"),
+ ...(failure.copyCommand ? { copyCommand: failure.copyCommand } : {}),
+ technicalDetails: failure.technicalDetails,
+ variant: "destructive",
duration: 10000,
});
}, [pending, toast, t]);
diff --git a/src/components/TestConnectionButton.tsx b/src/components/TestConnectionButton.tsx
index 777844bfd..0430392be 100644
--- a/src/components/TestConnectionButton.tsx
+++ b/src/components/TestConnectionButton.tsx
@@ -2,6 +2,8 @@ import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "./ui/button";
import { CheckCircle, XCircle, Loader2, Copy } from "lucide-react";
+import { TechnicalErrorDetails } from "./ui/TechnicalErrorDetails";
+import type { TechnicalErrorDetailsData } from "./ui/useToast";
interface TestConnectionButtonProps {
provider: string;
@@ -15,6 +17,7 @@ export default function TestConnectionButton({ provider, getConfig }: TestConnec
message: string;
action?: string;
copyCommand?: string;
+ technicalDetails?: TechnicalErrorDetailsData;
} | null>(null);
const requestIdRef = useRef(0);
const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -31,14 +34,7 @@ export default function TestConnectionButton({ provider, getConfig }: TestConnec
setStatus("testing");
setErrorInfo(null);
try {
- const result:
- | {
- success?: boolean;
- error?: string;
- action?: string;
- copyCommand?: string;
- }
- | undefined = await window.electronAPI?.testEnterpriseConnection?.(provider, getConfig());
+ const result = await window.electronAPI?.testEnterpriseConnection?.(provider, getConfig());
if (requestId !== requestIdRef.current) return;
if (result?.success) {
setStatus("success");
@@ -48,9 +44,12 @@ export default function TestConnectionButton({ provider, getConfig }: TestConnec
} else {
setStatus("error");
setErrorInfo({
- message: result?.error || "Connection failed",
- action: result?.action,
+ message: result?.messageKey
+ ? t(result.messageKey, result.messageParams)
+ : result?.error || t("reasoning.enterprise.testFailed"),
+ action: result?.actionKey ? t(result.actionKey) : result?.action,
copyCommand: result?.copyCommand,
+ technicalDetails: result?.technicalDetails,
});
}
} catch {
@@ -99,11 +98,13 @@ export default function TestConnectionButton({ provider, getConfig }: TestConnec
size="sm"
className="h-6 w-6 p-0 shrink-0"
onClick={() => handleCopy(errorInfo.copyCommand!)}
+ aria-label={t("reasoning.enterprise.technicalDetails.copyCommand")}
>
<Copy className="w-3 h-3" />
</Button>
</div>
)}
+ <TechnicalErrorDetails details={errorInfo.technicalDetails} />
</div>
)}
</div>
diff --git a/src/components/ui/TechnicalErrorDetails.tsx b/src/components/ui/TechnicalErrorDetails.tsx
new file mode 100644
index 000000000..eaf246eb1
--- /dev/null
+++ b/src/components/ui/TechnicalErrorDetails.tsx
@@ -0,0 +1,70 @@
+import { Check, Copy } from "lucide-react";
+import type { TFunction } from "i18next";
+import type { JSX } from "react";
+import { useTranslation } from "react-i18next";
+import { useCopyFeedback } from "../../hooks/useCopyFeedback";
+import { cn } from "../lib/utils";
+import type { TechnicalErrorDetailsData } from "./useToast";
+
+function formatTechnicalErrorDetails(details: TechnicalErrorDetailsData, t: TFunction): string {
+ return [
+ details.status !== undefined
+ ? `${t("reasoning.enterprise.technicalDetails.httpStatus")}: ${details.status}`
+ : "",
+ details.exceptionType
+ ? `${t("reasoning.enterprise.technicalDetails.awsException")}: ${details.exceptionType}`
+ : "",
+ details.requestId
+ ? `${t("reasoning.enterprise.technicalDetails.awsRequestId")}: ${details.requestId}`
+ : "",
+ details.underlyingError
+ ? `${t("reasoning.enterprise.technicalDetails.underlyingError")}: ${details.underlyingError}`
+ : "",
+ ]
+ .filter(Boolean)
+ .join("\n");
+}
+
+export function TechnicalErrorDetails({
+ details,
+ onDark = false,
+}: {
+ details?: TechnicalErrorDetailsData;
+ onDark?: boolean;
+}): JSX.Element | null {
+ const { t } = useTranslation();
+ const text = details ? formatTechnicalErrorDetails(details, t) : "";
+ const { copied, copy } = useCopyFeedback(text, { resetMs: 2000 });
+ if (!text) return null;
+
+ return (
+ <details
+ className={cn(
+ "group/details mt-1.5 rounded-[3px] border px-1.5 py-1 text-xs",
+ onDark ? "border-white/6 bg-white/4 text-white/45" : "border-border bg-muted/50"
+ )}
+ >
+ <summary className="cursor-pointer select-none text-xs text-muted-foreground">
+ {t("reasoning.enterprise.technicalDetails.title")}
+ </summary>
+ <div className="mt-1.5 flex items-start justify-between gap-2">
+ <pre className="min-w-0 flex-1 whitespace-pre-wrap wrap-break-word font-mono text-[11px] leading-snug select-all">
+ {text}
+ </pre>
+ <button
+ type="button"
+ onClick={() => void copy()}
+ className={cn(
+ "shrink-0 rounded-xs p-1 transition-colors",
+ onDark
+ ? "text-white/30 hover:bg-white/6 hover:text-white/70"
+ : "text-muted-foreground hover:bg-muted hover:text-foreground"
+ )}
+ aria-label={t("reasoning.enterprise.technicalDetails.copy")}
+ >
+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ </button>
+ </div>
+ </details>
+ );
+}
diff --git a/src/components/ui/Toast.tsx b/src/components/ui/Toast.tsx
index 9f9a31d0a..f9e2c715d 100644
--- a/src/components/ui/Toast.tsx
+++ b/src/components/ui/Toast.tsx
@@ -1,5 +1,6 @@
import * as React from "react";
import { X, Copy, Check } from "lucide-react";
+import { useTranslation } from "react-i18next";
import { cn } from "../lib/utils";
import {
ToastContext,
@@ -15,6 +16,7 @@ import {
} from "../../helpers/toastPresentation";
import { useCopyFeedback } from "../../hooks/useCopyFeedback";
import { DictationErrorCard } from "../dictation/DictationErrorCard";
+import { TechnicalErrorDetails } from "./TechnicalErrorDetails";
interface ToastState extends ToastProps {
id: string;
@@ -243,6 +245,9 @@ const Toast: React.FC<
> = ({
title,
description,
+ secondaryDescription,
+ copyCommand,
+ technicalDetails,
action,
actions,
presentation = "standard",
@@ -259,6 +264,10 @@ const Toast: React.FC<
const remainingDurationRef = React.useRef(duration);
const timerStartedAtRef = React.useRef(createdAt);
const { copied, copy } = useCopyFeedback(description ?? "", { resetMs: 2000 });
+ const { copied: commandCopied, copy: copyRecoveryCommand } = useCopyFeedback(copyCommand ?? "", {
+ resetMs: 2000,
+ });
+ const { t } = useTranslation();
const [timerPaused, setTimerPaused] = React.useState(false);
const [errorSurfaceReady, setErrorSurfaceReady] = React.useState(false);
const isDestructive = variant === "destructive";
@@ -360,6 +369,9 @@ const Toast: React.FC<
{message && (
<div className="text-xs font-medium leading-tight text-white/90">{message}</div>
)}
+ {secondaryDescription && (
+ <div className="mt-1 text-xs leading-snug text-white/45">{secondaryDescription}</div>
+ )}
{detail &&
(isDestructive ? (
<div
@@ -388,6 +400,22 @@ const Toast: React.FC<
) : (
<div className="text-xs leading-snug mt-0.5 text-white/45">{detail}</div>
))}
+ {copyCommand && (
+ <div className="mt-1.5 flex items-center gap-1.5 rounded-[3px] border border-white/6 bg-white/4 px-1.5 py-1">
+ <code className="min-w-0 flex-1 wrap-break-word font-mono text-[11px] text-white/60 select-all">
+ {copyCommand}
+ </code>
+ <button
+ type="button"
+ onClick={() => void copyRecoveryCommand()}
+ className="shrink-0 rounded-xs p-1 text-white/30 transition-colors hover:bg-white/6 hover:text-white/70"
+ aria-label={t("reasoning.enterprise.technicalDetails.copyCommand")}
+ >
+ {commandCopied ? <Check className="size-3" /> : <Copy className="size-3" />}
+ </button>
+ </div>
+ )}
+ <TechnicalErrorDetails details={technicalDetails} onDark />
</div>
{action && <div className="shrink-0 self-center">{action}</div>}
diff --git a/src/components/ui/useToast.ts b/src/components/ui/useToast.ts
index 6bddd17e6..3d3935fe4 100644
--- a/src/components/ui/useToast.ts
+++ b/src/components/ui/useToast.ts
@@ -2,6 +2,13 @@ import * as React from "react";
export type ToastPresentation = "standard" | "dictation-error";
+export interface TechnicalErrorDetailsData {
+ status?: number;
+ exceptionType?: string;
+ requestId?: string;
+ underlyingError?: string;
+}
+
export interface ToastActionConfig {
label: string;
icon?: "retry" | "transcript";
@@ -13,6 +20,9 @@ export interface ToastProps {
id?: string;
title?: string;
description?: string;
+ secondaryDescription?: string;
+ copyCommand?: string;
+ technicalDetails?: TechnicalErrorDetailsData;
action?: React.ReactNode;
actions?: ToastActionConfig[];
presentation?: ToastPresentation;
diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.js
index 92f964e7b..28e53780f 100644
--- a/src/helpers/audioManager.js
+++ b/src/helpers/audioManager.js
@@ -46,7 +46,6 @@ import {
isTranscriptionSelectionAllowed,
} from "../stores/policyRules";
import { usePolicyStore } from "../stores/policyStore";
-import { recordCleanupFailure } from "../stores/cleanupFailureStore";
import {
getBatchTranscriptionModel,
getCloudModel,
@@ -114,6 +113,16 @@ const neverCancelled = () => false;
const MIN_SPARSE_RECORDING_DURATION_SECONDS = 3;
const MIN_UNIQUE_WORD_GAIN = 2;
+const cleanupFailureFromError = (error) => ({
+ message: error?.message || String(error),
+ ...(error?.messageKey ? { messageKey: error.messageKey } : {}),
+ ...(error?.messageParams ? { messageParams: error.messageParams } : {}),
+ ...(error?.action ? { action: error.action } : {}),
+ ...(error?.actionKey ? { actionKey: error.actionKey } : {}),
+ ...(error?.copyCommand ? { copyCommand: error.copyCommand } : {}),
+ ...(error?.technicalDetails ? { technicalDetails: error.technicalDetails } : {}),
+});
+
const micDeviceKey = (settings) =>
`${settings.microphoneSelectionMode}|${settings.selectedMicDeviceId}`;
@@ -513,6 +522,7 @@ class AudioManager {
this.translationApplied = false;
this.pendingSelectionEdit = null;
this.pendingAssistantConversation = null;
+ this.pendingCleanupFailure = null;
this._processingCancellationGeneration = 0;
this._activeProcessingPipeline = null;
this.assistantSelectionContext = null;
@@ -742,6 +752,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this.voiceAgentRequested = requested;
this.pendingSelectionEdit = null;
this.pendingAssistantConversation = null;
+ this.pendingCleanupFailure = null;
this.assistantSelectionContext = null;
// No recording must ever see a stale capture (e.g. left over from a
// cancelled voice-agent recording, even after the setting was turned
@@ -2488,9 +2499,11 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
? { assistantConversation: this.pendingAssistantConversation }
: {}),
...(this.pendingSelectionEdit ? { selectionEdit: this.pendingSelectionEdit } : {}),
+ ...(this.pendingCleanupFailure ? { cleanupFailure: this.pendingCleanupFailure } : {}),
};
this.pendingAssistantConversation = null;
this.pendingSelectionEdit = null;
+ this.pendingCleanupFailure = null;
return extras;
}
@@ -2932,7 +2945,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
fallbackToCleanup: true,
});
logger.warn("Reasoning failed", { source, error: error.message }, "notes");
- if (route?.kind === "cleanup") recordCleanupFailure(error.message);
+ if (route?.kind === "cleanup") this.pendingCleanupFailure = cleanupFailureFromError(error);
if (route?.kind === "agent") this._notifyAgentReasoningFailed();
}
}
@@ -3260,7 +3273,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ error: reasonError.message },
"transcription"
);
- if (route.kind === "cleanup") recordCleanupFailure(reasonError.message);
+ if (route.kind === "cleanup") {
+ this.pendingCleanupFailure = cleanupFailureFromError(reasonError);
+ }
if (route.kind === "agent") this._notifyAgentReasoningFailed();
}
}
@@ -3721,8 +3736,8 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
async safePaste(text, options = {}) {
try {
- await window.electronAPI.pasteText(text, options);
- return true;
+ const result = await window.electronAPI.pasteText(text, options);
+ return result?.pasted === true;
} catch (error) {
const message =
error?.message ??
@@ -4505,6 +4520,7 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
this._activeTranscriptionAbortController = null;
this.pendingSelectionEdit = null;
this.pendingAssistantConversation = null;
+ this.pendingCleanupFailure = null;
this.assistantSelectionContext = null;
this.screenContextPromise = null;
this.selectionCapturePromise = null;
@@ -4890,7 +4906,9 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);
{ error: reasonError.message },
"streaming"
);
- if (route.kind === "cleanup") recordCleanupFailure(reasonError.message);
+ if (route.kind === "cleanup") {
+ this.pendingCleanupFailure = cleanupFailureFromError(reasonError);
+ }
if (route.kind === "agent") this._notifyAgentReasoningFailed();
}
if (wasCancelled()) return true;
diff --git a/src/helpers/enterpriseAiProviders.js b/src/helpers/enterpriseAiProviders.js
index 0575384de..6a0ab7c12 100644
--- a/src/helpers/enterpriseAiProviders.js
+++ b/src/helpers/enterpriseAiProviders.js
@@ -8,7 +8,7 @@
// app startup doesn't eager-load ~100 MB of AWS/Azure/Google SDKs for users
// who never select an enterprise provider.
-function getEnterpriseAIModel(provider, model, apiKey, enterprise) {
+async function getEnterpriseAIModel(provider, model, apiKey, enterprise) {
switch (provider) {
case "bedrock":
return createBedrockModel(model, enterprise);
@@ -21,35 +21,55 @@ function getEnterpriseAIModel(provider, model, apiKey, enterprise) {
}
}
-function createBedrockModel(model, enterprise) {
+async function createBedrockModel(model, enterprise) {
const { createAmazonBedrock } = require("@ai-sdk/amazon-bedrock");
const region = enterprise?.bedrockRegion || "us-east-1";
+ const explicitCredentialSource = enterprise?.managedCredentialProvider
+ ? "managed credential provider"
+ : enterprise?.bedrockProfile
+ ? "profile credential provider"
+ : enterprise?.bedrockAccessKeyId || enterprise?.bedrockSecretAccessKey
+ ? "static credentials"
+ : null;
+ const credentials = enterprise?.managedCredentialProvider
+ ? await enterprise.managedCredentialProvider()
+ : enterprise?.bedrockProfile
+ ? await require("@aws-sdk/credential-providers").fromNodeProviderChain({
+ profile: enterprise.bedrockProfile,
+ })()
+ : explicitCredentialSource
+ ? {
+ accessKeyId: enterprise.bedrockAccessKeyId,
+ secretAccessKey: enterprise.bedrockSecretAccessKey,
+ sessionToken: enterprise.bedrockSessionToken,
+ }
+ : null;
- if (enterprise?.managedCredentialProvider) {
- return createAmazonBedrock({
- region,
- credentialProvider: enterprise.managedCredentialProvider,
- })(model);
- }
-
- if (enterprise?.bedrockProfile) {
- const { fromNodeProviderChain } = require("@aws-sdk/credential-providers");
- return createAmazonBedrock({
- region,
- credentialProvider: fromNodeProviderChain({ profile: enterprise.bedrockProfile }),
- })(model);
- }
-
- if (enterprise?.bedrockAccessKeyId && enterprise?.bedrockSecretAccessKey) {
- return createAmazonBedrock({
- region,
- accessKeyId: enterprise.bedrockAccessKeyId,
- secretAccessKey: enterprise.bedrockSecretAccessKey,
- sessionToken: enterprise.bedrockSessionToken,
- })(model);
+ if (
+ explicitCredentialSource &&
+ (!credentials ||
+ typeof credentials.accessKeyId !== "string" ||
+ credentials.accessKeyId.length === 0 ||
+ typeof credentials.secretAccessKey !== "string" ||
+ credentials.secretAccessKey.length === 0)
+ ) {
+ const error = new Error(
+ `AWS ${explicitCredentialSource} returned invalid credentials. Expected accessKeyId and secretAccessKey.`
+ );
+ error.name = "CredentialsProviderError";
+ throw error;
}
- return createAmazonBedrock({ region })(model);
+ return createAmazonBedrock({
+ region,
+ ...(credentials
+ ? {
+ accessKeyId: credentials.accessKeyId,
+ secretAccessKey: credentials.secretAccessKey,
+ sessionToken: credentials.sessionToken,
+ }
+ : {}),
+ })(model);
}
function createAzureModel(model, apiKey, enterprise) {
diff --git a/src/helpers/enterpriseProviderErrors.js b/src/helpers/enterpriseProviderErrors.js
index 7be5690cd..504c5cd14 100644
--- a/src/helpers/enterpriseProviderErrors.js
+++ b/src/helpers/enterpriseProviderErrors.js
@@ -6,6 +6,252 @@
const { classifyNetworkError } = require("./networkErrors");
+const BEDROCK_MAX_ATTEMPTS = 6;
+const BEDROCK_INITIAL_DELAY_MS = 500;
+const BEDROCK_MAX_DELAY_MS = 8_000;
+
+const BEDROCK_SAFE_NETWORK_CODES = new Set([
+ "EAI_AGAIN",
+ "ECONNREFUSED",
+ "ECONNRESET",
+ "EHOSTDOWN",
+ "EHOSTUNREACH",
+ "ENETDOWN",
+ "ENETUNREACH",
+ "ENOTFOUND",
+ "EPIPE",
+ "ETIMEDOUT",
+ "UND_ERR_CONNECT_TIMEOUT",
+ "UND_ERR_HEADERS_TIMEOUT",
+ "UND_ERR_BODY_TIMEOUT",
+ "UND_ERR_SOCKET",
+]);
+
+function unwrapRetryError(error) {
+ let current = error;
+ const seen = new Set();
+ while (current?.lastError && !seen.has(current)) {
+ seen.add(current);
+ current = current.lastError;
+ }
+ return current;
+}
+
+function bedrockErrorChain(error) {
+ const chain = [];
+ let current = unwrapRetryError(error);
+ const seen = new Set();
+ while (current && !seen.has(current)) {
+ chain.push(current);
+ seen.add(current);
+ current = current.cause;
+ }
+ return chain;
+}
+
+function getBedrockHttpStatus(error) {
+ for (const item of bedrockErrorChain(error)) {
+ const status =
+ item?.status ?? item?.statusCode ?? item?.$metadata?.httpStatusCode ?? item?.response?.status;
+ if (Number.isInteger(status)) return status;
+ }
+ return undefined;
+}
+
+function getHeaderCaseInsensitive(headers, headerName) {
+ if (!headers) return undefined;
+ if (typeof headers.get === "function") return headers.get(headerName) || undefined;
+ const normalizedName = headerName.toLowerCase();
+ for (const [name, value] of Object.entries(headers)) {
+ if (name.toLowerCase() === normalizedName) return value;
+ }
+ return undefined;
+}
+
+function normalizeBedrockExceptionType(value) {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ const namespaceSeparator = trimmed.lastIndexOf("#");
+ const withoutNamespace =
+ namespaceSeparator === -1 ? trimmed : trimmed.slice(namespaceSeparator + 1);
+ const suffixSeparator = withoutNamespace.indexOf(":");
+ const normalized =
+ suffixSeparator === -1 ? withoutNamespace : withoutNamespace.slice(0, suffixSeparator);
+ return normalized.trim() || undefined;
+}
+
+function getBedrockExceptionType(error) {
+ for (const item of bedrockErrorChain(error)) {
+ const headers = item?.responseHeaders || item?.response?.headers;
+ const candidates = [
+ getHeaderCaseInsensitive(headers, "x-amzn-errortype"),
+ item?.data?.code,
+ item?.data?.__type,
+ item?.data?.type,
+ item?.type,
+ item?.code,
+ item?.name,
+ ];
+ for (const candidate of candidates) {
+ const type = normalizeBedrockExceptionType(candidate);
+ if (type && !["Error", "AI_APICallError", "AI_RetryError"].includes(type)) return type;
+ }
+ }
+ return undefined;
+}
+
+function getBedrockRequestId(error) {
+ for (const item of bedrockErrorChain(error)) {
+ const headers = item?.responseHeaders || item?.response?.headers || {};
+ const requestId =
+ item?.$metadata?.requestId ||
+ item?.requestId ||
+ getHeaderCaseInsensitive(headers, "x-amzn-requestid") ||
+ getHeaderCaseInsensitive(headers, "x-amz-request-id");
+ if (requestId) return requestId;
+ }
+ return undefined;
+}
+
+function getBedrockErrorCode(error) {
+ for (const item of bedrockErrorChain(error)) {
+ if (typeof item?.code === "string") return item.code;
+ if (typeof item?.cause?.code === "string") return item.cause.code;
+ }
+ return undefined;
+}
+
+function isBedrockTimeout(error) {
+ const status = getBedrockHttpStatus(error);
+ const type = (getBedrockExceptionType(error) || "").toLowerCase();
+ const code = (getBedrockErrorCode(error) || "").toUpperCase();
+ return (
+ status === 408 ||
+ type === "timeouterror" ||
+ type.includes("requesttimeout") ||
+ code === "ETIMEDOUT" ||
+ code === "UND_ERR_CONNECT_TIMEOUT" ||
+ code === "UND_ERR_HEADERS_TIMEOUT" ||
+ code === "UND_ERR_BODY_TIMEOUT"
+ );
+}
+
+function isSafeBedrockNetworkError(error) {
+ if (getBedrockHttpStatus(error) !== undefined) return false;
+ const code = (getBedrockErrorCode(error) || "").toUpperCase();
+ if (BEDROCK_SAFE_NETWORK_CODES.has(code)) return true;
+ return bedrockErrorChain(error).some(
+ (item) => item?.name === "TypeError" && /fetch failed|network/i.test(item?.message || "")
+ );
+}
+
+function getBedrockFailureKind(error) {
+ const status = getBedrockHttpStatus(error);
+ const type = (getBedrockExceptionType(error) || "").toLowerCase();
+ const message = bedrockErrorChain(error)
+ .map((item) => item?.message || "")
+ .join(" ")
+ .toLowerCase();
+
+ if (status === 503 || type.includes("serviceunavailable")) return "unavailable";
+ if (
+ status === 429 ||
+ type.includes("throttl") ||
+ type.includes("toomanyrequests") ||
+ message.includes("too many requests")
+ ) {
+ return "throttled";
+ }
+ if (isBedrockTimeout(error)) return "timeout";
+ if (isSafeBedrockNetworkError(error)) return "network";
+ return "other";
+}
+
+function shouldRetryBedrockError(error) {
+ return ["unavailable", "throttled", "timeout", "network"].includes(getBedrockFailureKind(error));
+}
+
+function sleepWithAbort(delay, signal) {
+ return new Promise((resolve, reject) => {
+ if (signal?.aborted) {
+ reject(signal.reason);
+ return;
+ }
+
+ let timer;
+ const onAbort = () => {
+ clearTimeout(timer);
+ signal.removeEventListener("abort", onAbort);
+ reject(signal.reason);
+ };
+ const onTimeout = () => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ };
+
+ timer = setTimeout(onTimeout, delay);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+async function runAbortableOperation(operation, signal) {
+ if (!signal) return operation();
+ signal.throwIfAborted();
+
+ let onAbort;
+ const aborted = new Promise((_, reject) => {
+ onAbort = () => reject(signal.reason);
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+
+ try {
+ signal.throwIfAborted();
+ return await Promise.race([operation(), aborted]);
+ } finally {
+ signal.removeEventListener("abort", onAbort);
+ }
+}
+
+async function runBedrockRequest(operation, options = {}) {
+ const {
+ signal,
+ maxAttempts = BEDROCK_MAX_ATTEMPTS,
+ initialDelayMs = BEDROCK_INITIAL_DELAY_MS,
+ maxDelayMs = BEDROCK_MAX_DELAY_MS,
+ random = Math.random,
+ sleep = sleepWithAbort,
+ } = options;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ signal?.throwIfAborted();
+ try {
+ return await operation();
+ } catch (error) {
+ signal?.throwIfAborted();
+ const underlying = unwrapRetryError(error);
+ if (attempt === maxAttempts || !shouldRetryBedrockError(underlying)) throw underlying;
+ const backoffCeiling = Math.min(maxDelayMs, initialDelayMs * 2 ** Math.max(0, attempt - 1));
+ await sleep(Math.floor(random() * backoffCeiling), signal);
+ }
+ }
+
+ throw new Error("Bedrock retry loop exited unexpectedly");
+}
+
+function getBedrockTechnicalDetails(error) {
+ const underlying = unwrapRetryError(error);
+ return {
+ ...(getBedrockHttpStatus(underlying) !== undefined
+ ? { status: getBedrockHttpStatus(underlying) }
+ : {}),
+ ...(getBedrockExceptionType(underlying)
+ ? { exceptionType: getBedrockExceptionType(underlying) }
+ : {}),
+ ...(getBedrockRequestId(underlying) ? { requestId: getBedrockRequestId(underlying) } : {}),
+ underlyingError: underlying?.message || String(underlying),
+ };
+}
+
function mapManagedIdentityError(error, provider) {
const code = error?.code;
if (!code) return null;
@@ -49,42 +295,117 @@ function mapManagedIdentityError(error, provider) {
}
function mapBedrockError(error, config = {}) {
- const msg = error?.message || error?.code || String(error);
+ const underlying = unwrapRetryError(error);
+ const msg = underlying?.message || underlying?.code || String(underlying);
+ const status = getBedrockHttpStatus(underlying);
+ const exceptionType = getBedrockExceptionType(underlying) || "";
+ const signature = `${exceptionType} ${msg}`.toLowerCase();
const profile = config.bedrockProfile || "default";
const region = config.bedrockRegion || "us-east-1";
+ const technicalDetails = getBedrockTechnicalDetails(underlying);
+ const withDetails = (mapped) => ({ ...mapped, technicalDetails });
- if (msg.includes("ExpiredToken") || msg.includes("expired")) {
- return {
+ if (signature.includes("expiredtoken") || signature.includes("expired")) {
+ if (config.managedContext) {
+ return withDetails({
+ message: "Temporary AWS access expired.",
+ messageKey: "reasoning.enterprise.errors.bedrock.temporaryAccessExpired",
+ action: "Sign out and sign back in to refresh company access, then retry.",
+ actionKey: "reasoning.enterprise.errors.bedrock.actions.refreshManagedAccess",
+ retryable: true,
+ });
+ }
+ return withDetails({
message: "AWS SSO session expired.",
+ messageKey: "reasoning.enterprise.errors.bedrock.ssoExpired",
action: "Run the command below in your terminal to re-authenticate:",
+ actionKey: "reasoning.enterprise.errors.bedrock.actions.reauthenticate",
copyCommand: `aws sso login --profile ${profile}`,
retryable: true,
- };
+ });
}
- if (msg.includes("AccessDenied")) {
- return {
- message: `Model access not enabled. Enable it in the AWS Bedrock console for region ${region}.`,
- action: "Open the AWS Bedrock console and request model access.",
- };
+ if (
+ status === 401 ||
+ signature.includes("unrecognizedclient") ||
+ signature.includes("invalidclienttoken") ||
+ signature.includes("invalidsignature") ||
+ signature.includes("incompletesignature") ||
+ signature.includes("signaturedoesnotmatch")
+ ) {
+ return withDetails({
+ message: "AWS credentials were rejected. Check the access key ID, secret, and session token.",
+ messageKey: "reasoning.enterprise.errors.bedrock.credentialsRejected",
+ });
}
- if (msg.includes("ValidationException") || msg.includes("not found")) {
- return {
- message: `Model not found in region ${region}. Check the model ID format.`,
- action: "Bedrock model IDs look like: anthropic.claude-sonnet-4-20250514-v1:0",
- };
+ if (status === 403 || signature.includes("accessdenied") || signature.includes("permission")) {
+ return withDetails({
+ message: `AWS Bedrock denied this request. Ask your AWS administrator to grant permission to invoke the selected model in region ${region}.`,
+ messageKey: "reasoning.enterprise.errors.bedrock.accessDenied",
+ messageParams: { region },
+ });
}
- if (msg.includes("UnrecognizedClient") || msg.includes("InvalidSignature")) {
- return {
- message: "Invalid AWS credentials. Check your access key ID and secret.",
- };
+ if (signature.includes("resourcenotfound") || signature.includes("modelnotfound")) {
+ return withDetails({
+ message: `AWS Bedrock could not find the selected model in region ${region}. Check the model ID and whether it is available in that region.`,
+ messageKey: "reasoning.enterprise.errors.bedrock.modelNotFound",
+ messageParams: { region },
+ });
}
- if (msg.includes("Throttling") || msg.includes("TooManyRequests")) {
- return {
- message: "Rate limited by AWS Bedrock. Wait a moment and retry.",
+ if (status === 400 || signature.includes("validationexception")) {
+ return withDetails({
+ message: `AWS Bedrock rejected the model configuration for region ${region}. Check the model ID, inference profile, and region.`,
+ messageKey: "reasoning.enterprise.errors.bedrock.configurationRejected",
+ messageParams: { region },
+ });
+ }
+ if (
+ signature.includes("credentialsprovidererror") ||
+ signature.includes("configerror") ||
+ signature.includes("region is missing") ||
+ signature.includes("could not load credentials")
+ ) {
+ return withDetails({
+ message: "AWS Bedrock is not configured correctly. Check the region and AWS credentials.",
+ messageKey: "reasoning.enterprise.errors.bedrock.notConfigured",
+ });
+ }
+ const kind = getBedrockFailureKind(underlying);
+ if (kind === "unavailable") {
+ return withDetails({
+ message:
+ "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes.",
+ messageKey: "reasoning.enterprise.errors.bedrock.serviceUnavailable",
retryable: true,
- };
+ });
+ }
+ if (kind === "throttled") {
+ return withDetails({
+ message:
+ "AWS Bedrock is temporarily limiting requests because it is receiving too many. Please wait a moment and try again. If this continues, ask your AWS administrator to check your Bedrock usage and quotas.",
+ messageKey: "reasoning.enterprise.errors.bedrock.throttled",
+ retryable: true,
+ });
+ }
+ if (kind === "timeout") {
+ return withDetails({
+ message:
+ "AWS Bedrock did not respond in time. Please try again. If this continues, check your internet connection and AWS Bedrock service status.",
+ messageKey: "reasoning.enterprise.errors.bedrock.timeout",
+ retryable: true,
+ });
+ }
+ if (kind === "network") {
+ return withDetails({
+ message: "AWS Bedrock could not be reached. Check your internet connection and try again.",
+ messageKey: "reasoning.enterprise.errors.bedrock.network",
+ retryable: true,
+ });
}
- return { message: `AWS Bedrock error: ${msg}` };
+ return withDetails({
+ message: `AWS Bedrock error: ${msg}`,
+ messageKey: "reasoning.enterprise.errors.bedrock.unknown",
+ messageParams: { error: msg },
+ });
}
function mapAzureError(error) {
@@ -270,5 +591,8 @@ module.exports = {
isEnterpriseProvider,
mapEnterpriseError,
pickEnterpriseConfig,
+ runAbortableOperation,
+ runBedrockRequest,
+ unwrapRetryError,
validateEnterpriseEndpoint,
};
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index eda48a8c8..6233ed6dc 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -597,6 +597,7 @@ class IPCHandlers {
this._agentStreamRequests = new AgentStreamRequestRegistry();
this._cloudReasonRequests = new AgentStreamRequestRegistry();
this._cloudTranscriptionRequests = new AgentStreamRequestRegistry();
+ this._enterpriseReasoningRequests = new AgentStreamRequestRegistry();
// webContents id -> its release listener, for renderers holding the mic open.
this._micHoldSenders = new Map();
this.assemblyAiStreaming = null;
@@ -2746,10 +2747,11 @@ class IPCHandlers {
ipcMain.handle("paste-text", async (event, text, options) => {
// An onboarding demo already puts the transcript in its own textarea from
// the demo event, and that textarea is what has focus — pasting on top of
- // it appends the same sentence a second time. Reported as success because
- // nothing failed and the caller would otherwise toast a paste error.
+ // it appends the same sentence a second time. This is a successful no-op,
+ // not a completed paste, so callers can avoid reporting paste-dependent
+ // fallbacks as if text reached another application.
if (this.windowManager?.isOnboardingDemoActive()) {
- return { success: true };
+ return { success: true, pasted: false };
}
const mainWindow = this.windowManager?.mainWindow;
@@ -2788,17 +2790,19 @@ class IPCHandlers {
? ((await this.selectionManager?.getWinTargetHwnd?.()) ?? null)
: null;
- await this.clipboardManager.pasteText(textToPaste, {
+ const pasteResult = await this.clipboardManager.pasteText(textToPaste, {
...options,
webContents: event.sender,
targetWindow,
});
+ const pasted = pasteResult?.pasted !== false;
debugLogger.debug("[AutoLearn] Paste completed", {
autoLearnEnabled: this._autoLearnEnabled,
hasMonitor: !!this.textEditMonitor,
targetPid,
+ pasted,
});
- if (this.textEditMonitor && this._autoLearnEnabled) {
+ if (pasted && this.textEditMonitor && this._autoLearnEnabled) {
setTimeout(() => {
try {
debugLogger.debug("[AutoLearn] Starting monitoring", {
@@ -2813,8 +2817,10 @@ class IPCHandlers {
// ClipboardManager returns `restoreComplete` so main-process callers can
// serialize subsequent clipboard work behind its delayed restore. A
// Promise cannot cross Electron's IPC boundary, though, and renderer
- // callers only need to know that the paste was accepted.
- return { success: true };
+ // callers need to know whether text was pasted, but not the delayed
+ // clipboard restoration promise. Successful platform paths predate the
+ // explicit `pasted` outcome; only the clipboard-only fallback sets false.
+ return { success: true, pasted };
});
ipcMain.handle("check-accessibility-permission", async (_event, silent = false) => {
@@ -4351,42 +4357,71 @@ class IPCHandlers {
ipcMain.handle("test-enterprise-connection", async (event, provider, config) => {
const {
mapEnterpriseError,
+ runAbortableOperation,
+ runBedrockRequest,
validateEnterpriseEndpoint,
} = require("./enterpriseProviderErrors");
+ let runtime;
try {
- const runtime = await resolveEnterpriseRuntime(
- event,
- provider,
- config?.model || "test",
- config
- );
- validateEnterpriseEndpoint(runtime.enterprise.azureEndpoint);
-
const { generateText } = require("ai");
const { getEnterpriseAIModel } = require("./enterpriseAiProviders");
- const model = getEnterpriseAIModel(
- runtime.provider,
- runtime.model,
- runtime.apiKey,
- runtime.enterprise
- );
+ const resolveModel = (abortSignal) =>
+ runAbortableOperation(async () => {
+ runtime = await resolveEnterpriseRuntime(
+ event,
+ provider,
+ config?.model || "test",
+ config
+ );
+ abortSignal?.throwIfAborted();
+ validateEnterpriseEndpoint(runtime.enterprise.azureEndpoint);
+ return getEnterpriseAIModel(
+ runtime.provider,
+ runtime.model,
+ runtime.apiKey,
+ runtime.enterprise
+ );
+ }, abortSignal);
- await generateText({
- model,
- prompt: "Say hello in one word.",
- maxOutputTokens: 10,
- });
+ if (provider === "bedrock") {
+ await runBedrockRequest(async () => {
+ const abortSignal = AbortSignal.timeout(config?.timeoutMs || 30_000);
+ const model = await resolveModel(abortSignal);
+ return generateText({
+ model,
+ prompt: "Say hello in one word.",
+ maxOutputTokens: 10,
+ abortSignal,
+ maxRetries: 0,
+ });
+ });
+ } else {
+ const model = await resolveModel();
+ await generateText({
+ model,
+ prompt: "Say hello in one word.",
+ maxOutputTokens: 10,
+ });
+ }
return { success: true };
} catch (err) {
- const mapped = mapEnterpriseError(provider, err, config);
+ const mappingConfig =
+ runtime?.provider === "bedrock" && runtime.enterprise?.bedrockRegion
+ ? { ...(config || {}), bedrockRegion: runtime.enterprise.bedrockRegion }
+ : config;
+ const mapped = mapEnterpriseError(provider, err, mappingConfig);
return {
success: false,
error: mapped.message,
+ messageKey: mapped.messageKey,
+ messageParams: mapped.messageParams,
action: mapped.action,
+ actionKey: mapped.actionKey,
copyCommand: mapped.copyCommand,
retryable: mapped.retryable,
+ technicalDetails: mapped.technicalDetails,
};
}
});
@@ -4397,56 +4432,122 @@ class IPCHandlers {
const {
isEnterpriseProvider,
mapEnterpriseError,
+ runAbortableOperation,
+ runBedrockRequest,
validateEnterpriseEndpoint,
} = require("./enterpriseProviderErrors");
const provider = config?.provider;
+ let runtime;
try {
if (!isEnterpriseProvider(provider)) {
throw new Error(`Unsupported enterprise provider: ${provider}`);
}
- const runtime = await resolveEnterpriseRuntime(event, provider, modelId, config || {});
- if (!runtime.model) throw new Error("No model specified for enterprise reasoning");
- validateEnterpriseEndpoint(runtime.enterprise.azureEndpoint);
-
- const { generateText } = require("ai");
- const { getEnterpriseAIModel } = require("./enterpriseAiProviders");
-
- const model = getEnterpriseAIModel(
- runtime.provider,
- runtime.model,
- runtime.apiKey,
- runtime.enterprise
- );
+ const isBedrockCleanup =
+ provider === "bedrock" && config?.inferenceScope === "dictationCleanup";
+ const sender = isBedrockCleanup ? event.sender : null;
+ const senderId = sender?.id;
+ const requestId = isBedrockCleanup ? crypto.randomUUID() : null;
+ const controller = isBedrockCleanup
+ ? this._enterpriseReasoningRequests.begin(senderId, requestId)
+ : null;
+ const cancelSenderRequests = () =>
+ this._enterpriseReasoningRequests.cancelSender(senderId);
+ try {
+ if (controller) {
+ sender.once("destroyed", cancelSenderRequests);
+ if (sender.isDestroyed()) controller.abort();
+ }
+ controller?.signal.throwIfAborted();
+
+ const { generateText } = require("ai");
+ const { getEnterpriseAIModel } = require("./enterpriseAiProviders");
+ const timeoutMs = config?.timeoutMs || 60000;
+ // Opus 4.7 / GPT-5 / o-series dropped `temperature`; renderer
+ // derives support from the model registry and we honor that here.
+ const useTemperature = config?.supportsTemperature !== false;
+ const resolveModel = (abortSignal) =>
+ runAbortableOperation(async () => {
+ runtime = await resolveEnterpriseRuntime(event, provider, modelId, config || {});
+ abortSignal?.throwIfAborted();
+ if (!runtime.model) throw new Error("No model specified for enterprise reasoning");
+ validateEnterpriseEndpoint(runtime.enterprise.azureEndpoint);
+ return getEnterpriseAIModel(
+ runtime.provider,
+ runtime.model,
+ runtime.apiKey,
+ runtime.enterprise
+ );
+ }, abortSignal);
+ const generate = (model, abortSignal, disableNestedRetries = false) => {
+ return generateText({
+ model,
+ system: config?.systemPrompt || "",
+ prompt: text,
+ maxOutputTokens: config?.maxTokens || 4096,
+ ...(useTemperature ? { temperature: config?.temperature ?? 0.3 } : {}),
+ abortSignal,
+ ...(disableNestedRetries ? { maxRetries: 0 } : {}),
+ });
+ };
+ let result;
+ if (isBedrockCleanup) {
+ result = await runBedrockRequest(
+ async () => {
+ const abortSignal = AbortSignal.any([
+ controller.signal,
+ AbortSignal.timeout(timeoutMs),
+ ]);
+ const model = await resolveModel(abortSignal);
+ return generate(model, abortSignal, true);
+ },
+ { signal: controller.signal }
+ );
+ } else {
+ const model = await resolveModel();
+ result = await generate(model, AbortSignal.timeout(timeoutMs));
+ }
+ const { text: generated, finishReason } = result;
- const timeoutMs = config?.timeoutMs || 60000;
- // Opus 4.7 / GPT-5 / o-series dropped `temperature`; renderer
- // derives support from the model registry and we honor that here.
- const useTemperature = config?.supportsTemperature !== false;
- const { text: generated, finishReason } = await generateText({
- model,
- system: config?.systemPrompt || "",
- prompt: text,
- maxOutputTokens: config?.maxTokens || 4096,
- ...(useTemperature ? { temperature: config?.temperature ?? 0.3 } : {}),
- abortSignal: AbortSignal.timeout(timeoutMs),
- });
+ if (
+ config?.requireCompleteOutput &&
+ ["length", "max-tokens", "max_tokens"].includes(finishReason)
+ ) {
+ throw new Error("Model output was truncated before the selection edit completed");
+ }
- if (
- config?.requireCompleteOutput &&
- ["length", "max-tokens", "max_tokens"].includes(finishReason)
- ) {
- throw new Error("Model output was truncated before the selection edit completed");
+ return { success: true, text: (generated || "").trim() };
+ } finally {
+ if (controller) {
+ sender.removeListener("destroyed", cancelSenderRequests);
+ this._enterpriseReasoningRequests.complete(senderId, requestId, controller);
+ }
}
-
- return { success: true, text: (generated || "").trim() };
} catch (err) {
debugLogger.error("Enterprise reasoning error:", err);
- const mapped = mapEnterpriseError(provider, err, config || {});
- return { success: false, error: mapped.message, retryable: mapped.retryable };
+ const mappingConfig =
+ runtime?.provider === "bedrock" && runtime.enterprise?.bedrockRegion
+ ? { ...(config || {}), bedrockRegion: runtime.enterprise.bedrockRegion }
+ : config || {};
+ const mapped = mapEnterpriseError(provider, err, mappingConfig);
+ return {
+ success: false,
+ error: mapped.message,
+ messageKey: mapped.messageKey,
+ messageParams: mapped.messageParams,
+ action: mapped.action,
+ actionKey: mapped.actionKey,
+ copyCommand: mapped.copyCommand,
+ retryable: mapped.retryable,
+ technicalDetails: mapped.technicalDetails,
+ };
}
}
);
+ ipcMain.on("enterprise-reasoning-cancel", (event) => {
+ this._enterpriseReasoningRequests.cancelSender(event.sender.id);
+ });
+
// Runs doStream for the renderer's enterprise chat model shim; parts are
// relayed verbatim over enterprise-stream-part, ending with {done}/{error}.
this.enterpriseStreamAborts = new Map();
@@ -4457,6 +4558,7 @@ class IPCHandlers {
validateEnterpriseEndpoint,
} = require("./enterpriseProviderErrors");
const { streamId, provider, modelId, config, options } = payload || {};
+ let runtime;
const send = (message) => {
if (!event.sender.isDestroyed()) {
event.sender.send("enterprise-stream-part", { streamId, ...message });
@@ -4477,12 +4579,12 @@ class IPCHandlers {
if (!streamId || !isEnterpriseProvider(provider)) {
throw new Error(`Unsupported enterprise provider: ${provider}`);
}
- const runtime = await resolveEnterpriseRuntime(event, provider, modelId, config || {});
+ runtime = await resolveEnterpriseRuntime(event, provider, modelId, config || {});
if (!runtime.model) throw new Error("No model specified for enterprise streaming");
validateEnterpriseEndpoint(runtime.enterprise.azureEndpoint);
const { getEnterpriseAIModel } = require("./enterpriseAiProviders");
- const model = getEnterpriseAIModel(
+ const model = await getEnterpriseAIModel(
runtime.provider,
runtime.model,
runtime.apiKey,
@@ -4511,7 +4613,11 @@ class IPCHandlers {
return { success: true };
} catch (err) {
debugLogger.error("Enterprise stream error:", err);
- const mapped = mapEnterpriseError(provider, err, config || {});
+ const mappingConfig =
+ runtime?.provider === "bedrock" && runtime.enterprise?.bedrockRegion
+ ? { ...(config || {}), bedrockRegion: runtime.enterprise.bedrockRegion }
+ : config || {};
+ const mapped = mapEnterpriseError(provider, err, mappingConfig);
send({ error: mapped.message });
return { success: false, error: mapped.message };
} finally {
diff --git a/src/hooks/useAudioRecording.js b/src/hooks/useAudioRecording.js
index 2fa24c5aa..9a22c99b3 100644
--- a/src/hooks/useAudioRecording.js
+++ b/src/hooks/useAudioRecording.js
@@ -23,6 +23,7 @@ import { canStartDictation } from "../utils/dictationReadiness";
import { waitForVisualFrames } from "../utils/visualFrame";
import { resolveLifecycleInputKind } from "../helpers/dictationRouting";
import { createAssistantResponseDelivery } from "../helpers/assistantResponseDelivery";
+import { recordCleanupFailure } from "../stores/cleanupFailureStore";
// Maps a failed selection-replacement code to its `selectionEditing.*` toast
// detail key; unlisted codes fall back to the generic "unavailable" message.
@@ -584,6 +585,7 @@ export const useAudioRecording = (toast, options = {}) => {
// visible somewhere.
if (pasteSucceeded) {
window.electronAPI?.hideDictationPreview?.();
+ if (result.cleanupFailure) recordCleanupFailure(result.cleanupFailure);
}
} else if (keepTranscriptionInClipboard && !result.assistantConversation) {
await navigator.clipboard.writeText(result.text);
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 5edd69b49..c473a7623 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Verwendet Ihre AWS-CLI-SSO-Konfiguration. Stellen Sie sicher, dass Sie 'aws sso login' ausgeführt haben.",
"keysHelp": "Geben Sie Ihre AWS-IAM-Zugriffsschlüssel ein."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "Der temporäre AWS-Zugriff ist abgelaufen.",
+ "ssoExpired": "Die AWS-SSO-Sitzung ist abgelaufen.",
+ "credentialsRejected": "Die AWS-Anmeldedaten wurden abgelehnt. Prüfe Zugriffsschlüssel-ID, Geheimnis und Sitzungstoken.",
+ "accessDenied": "AWS Bedrock hat diese Anfrage abgelehnt. Bitte deinen AWS-Administrator um die Berechtigung, das ausgewählte Modell in der Region {{region}} aufzurufen.",
+ "modelNotFound": "AWS Bedrock konnte das ausgewählte Modell in der Region {{region}} nicht finden. Prüfe die Modell-ID und ob das Modell dort verfügbar ist.",
+ "configurationRejected": "AWS Bedrock hat die Modellkonfiguration für die Region {{region}} abgelehnt. Prüfe Modell-ID, Inferenzprofil und Region.",
+ "notConfigured": "AWS Bedrock ist nicht richtig konfiguriert. Prüfe Region und AWS-Anmeldedaten.",
+ "serviceUnavailable": "AWS Bedrock ist wegen hoher Nachfrage vorübergehend nicht verfügbar. Dies ist ein Problem des AWS-Dienstes und kein OpenWhispr-Ausfall. Versuche es in einigen Minuten erneut.",
+ "throttled": "AWS Bedrock begrenzt Anfragen vorübergehend, weil zu viele eingehen. Warte kurz und versuche es erneut. Wenn das Problem anhält, bitte deinen AWS-Administrator, Bedrock-Nutzung und Kontingente zu prüfen.",
+ "timeout": "AWS Bedrock hat nicht rechtzeitig geantwortet. Versuche es erneut. Wenn das Problem anhält, prüfe deine Internetverbindung und den Status des AWS-Bedrock-Dienstes.",
+ "network": "AWS Bedrock konnte nicht erreicht werden. Prüfe deine Internetverbindung und versuche es erneut.",
+ "unknown": "AWS-Bedrock-Fehler: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Melde dich ab und wieder an, um den Unternehmenszugriff zu erneuern, und versuche es dann erneut.",
+ "reauthenticate": "Führe den folgenden Befehl im Terminal aus, um dich erneut zu authentifizieren:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Technische Details",
+ "httpStatus": "HTTP-Status",
+ "awsException": "AWS-Ausnahme",
+ "awsRequestId": "AWS-Anfrage-ID",
+ "underlyingError": "Zugrunde liegender Fehler",
+ "copy": "Technische Details kopieren",
+ "copyCommand": "Wiederherstellungsbefehl kopieren"
+ },
"azure": {
"endpointHelp": "Endpoint-URL Ihrer Azure-OpenAI-Ressource (z. B. https://myresource.openai.azure.com).",
"deploymentHelp": "Name Ihres Modell-Deployments in Azure OpenAI."
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index 97ff0730f..01bef4ea2 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Uses your AWS CLI SSO configuration. Ensure you have run 'aws sso login'.",
"keysHelp": "Enter your AWS IAM access keys."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "Temporary AWS access expired.",
+ "ssoExpired": "AWS SSO session expired.",
+ "credentialsRejected": "AWS credentials were rejected. Check the access key ID, secret, and session token.",
+ "accessDenied": "AWS Bedrock denied this request. Ask your AWS administrator to grant permission to invoke the selected model in region {{region}}.",
+ "modelNotFound": "AWS Bedrock could not find the selected model in region {{region}}. Check the model ID and whether it is available in that region.",
+ "configurationRejected": "AWS Bedrock rejected the model configuration for region {{region}}. Check the model ID, inference profile, and region.",
+ "notConfigured": "AWS Bedrock is not configured correctly. Check the region and AWS credentials.",
+ "serviceUnavailable": "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes.",
+ "throttled": "AWS Bedrock is temporarily limiting requests because it is receiving too many. Please wait a moment and try again. If this continues, ask your AWS administrator to check your Bedrock usage and quotas.",
+ "timeout": "AWS Bedrock did not respond in time. Please try again. If this continues, check your internet connection and AWS Bedrock service status.",
+ "network": "AWS Bedrock could not be reached. Check your internet connection and try again.",
+ "unknown": "AWS Bedrock error: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Sign out and sign back in to refresh company access, then retry.",
+ "reauthenticate": "Run the command below in your terminal to re-authenticate:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Technical details",
+ "httpStatus": "HTTP status",
+ "awsException": "AWS exception",
+ "awsRequestId": "AWS request ID",
+ "underlyingError": "Underlying error",
+ "copy": "Copy technical details",
+ "copyCommand": "Copy recovery command"
+ },
"azure": {
"endpointHelp": "Your Azure OpenAI resource endpoint (e.g., https://myresource.openai.azure.com).",
"deploymentHelp": "The name of your model deployment in Azure OpenAI."
@@ -3448,7 +3477,7 @@
},
"cleanupFailed": {
"title": "Cleanup failed",
- "description": "Your dictation was pasted without AI cleanup."
+ "description": "Original dictation pasted without AI cleanup."
}
},
"mic": {
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 191326bfb..12845189f 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Usa tu configuración SSO de AWS CLI. Asegúrate de haber ejecutado 'aws sso login'.",
"keysHelp": "Introduce tus claves de acceso de AWS IAM."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "El acceso temporal a AWS ha caducado.",
+ "ssoExpired": "La sesión SSO de AWS ha caducado.",
+ "credentialsRejected": "AWS rechazó las credenciales. Comprueba el ID de la clave de acceso, el secreto y el token de sesión.",
+ "accessDenied": "AWS Bedrock rechazó esta solicitud. Pide a tu administrador de AWS permiso para invocar el modelo seleccionado en la región {{region}}.",
+ "modelNotFound": "AWS Bedrock no encontró el modelo seleccionado en la región {{region}}. Comprueba el ID del modelo y si está disponible en esa región.",
+ "configurationRejected": "AWS Bedrock rechazó la configuración del modelo para la región {{region}}. Comprueba el ID del modelo, el perfil de inferencia y la región.",
+ "notConfigured": "AWS Bedrock no está configurado correctamente. Comprueba la región y las credenciales de AWS.",
+ "serviceUnavailable": "AWS Bedrock no está disponible temporalmente debido a una alta demanda. Este es un problema del servicio de AWS, no una interrupción de OpenWhispr. Vuelve a intentarlo en unos minutos.",
+ "throttled": "AWS Bedrock está limitando temporalmente las solicitudes porque recibe demasiadas. Espera un momento y vuelve a intentarlo. Si continúa, pide a tu administrador de AWS que revise el uso y las cuotas de Bedrock.",
+ "timeout": "AWS Bedrock no respondió a tiempo. Vuelve a intentarlo. Si continúa, comprueba tu conexión a internet y el estado del servicio AWS Bedrock.",
+ "network": "No se pudo acceder a AWS Bedrock. Comprueba tu conexión a internet y vuelve a intentarlo.",
+ "unknown": "Error de AWS Bedrock: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Cierra sesión y vuelve a iniciarla para renovar el acceso de la empresa; después, inténtalo de nuevo.",
+ "reauthenticate": "Ejecuta el siguiente comando en tu terminal para volver a autenticarte:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Detalles técnicos",
+ "httpStatus": "Estado HTTP",
+ "awsException": "Excepción de AWS",
+ "awsRequestId": "ID de solicitud de AWS",
+ "underlyingError": "Error subyacente",
+ "copy": "Copiar detalles técnicos",
+ "copyCommand": "Copiar comando de recuperación"
+ },
"azure": {
"endpointHelp": "El endpoint de tu recurso Azure OpenAI (por ejemplo, https://myresource.openai.azure.com).",
"deploymentHelp": "Nombre del deployment de tu modelo en Azure OpenAI."
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 280c64364..14359842d 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Utilise votre configuration SSO d'AWS CLI. Assurez-vous d'avoir exécuté 'aws sso login'.",
"keysHelp": "Saisissez vos clés d'accès AWS IAM."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "L’accès AWS temporaire a expiré.",
+ "ssoExpired": "La session SSO AWS a expiré.",
+ "credentialsRejected": "Les identifiants AWS ont été refusés. Vérifiez l’ID de clé d’accès, le secret et le jeton de session.",
+ "accessDenied": "AWS Bedrock a refusé cette requête. Demandez à votre administrateur AWS l’autorisation d’appeler le modèle sélectionné dans la région {{region}}.",
+ "modelNotFound": "AWS Bedrock n’a pas trouvé le modèle sélectionné dans la région {{region}}. Vérifiez l’ID du modèle et sa disponibilité dans cette région.",
+ "configurationRejected": "AWS Bedrock a refusé la configuration du modèle pour la région {{region}}. Vérifiez l’ID du modèle, le profil d’inférence et la région.",
+ "notConfigured": "AWS Bedrock n’est pas configuré correctement. Vérifiez la région et les identifiants AWS.",
+ "serviceUnavailable": "AWS Bedrock est temporairement indisponible en raison d’une forte demande. Il s’agit d’un problème du service AWS, et non d’une panne d’OpenWhispr. Réessayez dans quelques minutes.",
+ "throttled": "AWS Bedrock limite temporairement les requêtes car il en reçoit trop. Patientez un instant et réessayez. Si le problème persiste, demandez à votre administrateur AWS de vérifier l’utilisation et les quotas Bedrock.",
+ "timeout": "AWS Bedrock n’a pas répondu à temps. Réessayez. Si le problème persiste, vérifiez votre connexion Internet et l’état du service AWS Bedrock.",
+ "network": "AWS Bedrock est inaccessible. Vérifiez votre connexion Internet et réessayez.",
+ "unknown": "Erreur AWS Bedrock : {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Déconnectez-vous puis reconnectez-vous pour actualiser l’accès de l’entreprise, puis réessayez.",
+ "reauthenticate": "Exécutez la commande suivante dans votre terminal pour vous réauthentifier :"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Détails techniques",
+ "httpStatus": "État HTTP",
+ "awsException": "Exception AWS",
+ "awsRequestId": "ID de requête AWS",
+ "underlyingError": "Erreur sous-jacente",
+ "copy": "Copier les détails techniques",
+ "copyCommand": "Copier la commande de récupération"
+ },
"azure": {
"endpointHelp": "L'endpoint de votre ressource Azure OpenAI (par ex. https://myresource.openai.azure.com).",
"deploymentHelp": "Nom du déploiement de votre modèle dans Azure OpenAI."
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index d2bea11b8..c0149e555 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Usa la tua configurazione SSO di AWS CLI. Assicurati di aver eseguito 'aws sso login'.",
"keysHelp": "Inserisci le tue chiavi di accesso AWS IAM."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "L’accesso AWS temporaneo è scaduto.",
+ "ssoExpired": "La sessione SSO AWS è scaduta.",
+ "credentialsRejected": "Le credenziali AWS sono state rifiutate. Controlla l’ID della chiave di accesso, il segreto e il token di sessione.",
+ "accessDenied": "AWS Bedrock ha rifiutato questa richiesta. Chiedi all’amministratore AWS l’autorizzazione a richiamare il modello selezionato nella regione {{region}}.",
+ "modelNotFound": "AWS Bedrock non ha trovato il modello selezionato nella regione {{region}}. Controlla l’ID del modello e la sua disponibilità in quella regione.",
+ "configurationRejected": "AWS Bedrock ha rifiutato la configurazione del modello per la regione {{region}}. Controlla l’ID del modello, il profilo di inferenza e la regione.",
+ "notConfigured": "AWS Bedrock non è configurato correttamente. Controlla la regione e le credenziali AWS.",
+ "serviceUnavailable": "AWS Bedrock è temporaneamente non disponibile a causa dell’elevata richiesta. È un problema del servizio AWS, non un’interruzione di OpenWhispr. Riprova tra qualche minuto.",
+ "throttled": "AWS Bedrock sta limitando temporaneamente le richieste perché ne riceve troppe. Attendi un momento e riprova. Se il problema continua, chiedi all’amministratore AWS di controllare l’utilizzo e le quote di Bedrock.",
+ "timeout": "AWS Bedrock non ha risposto in tempo. Riprova. Se il problema continua, controlla la connessione Internet e lo stato del servizio AWS Bedrock.",
+ "network": "Impossibile raggiungere AWS Bedrock. Controlla la connessione Internet e riprova.",
+ "unknown": "Errore AWS Bedrock: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Esci e accedi di nuovo per aggiornare l’accesso aziendale, quindi riprova.",
+ "reauthenticate": "Esegui il comando seguente nel terminale per autenticarti di nuovo:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Dettagli tecnici",
+ "httpStatus": "Stato HTTP",
+ "awsException": "Eccezione AWS",
+ "awsRequestId": "ID richiesta AWS",
+ "underlyingError": "Errore sottostante",
+ "copy": "Copia dettagli tecnici",
+ "copyCommand": "Copia comando di ripristino"
+ },
"azure": {
"endpointHelp": "L'endpoint della tua risorsa Azure OpenAI (ad es. https://myresource.openai.azure.com).",
"deploymentHelp": "Nome del deployment del tuo modello in Azure OpenAI."
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index e41d0b36b..4ea49df14 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "AWS CLI の SSO 設定を使用します。'aws sso login' を実行済みであることを確認してください。",
"keysHelp": "AWS IAM のアクセスキーを入力してください。"
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "AWS の一時アクセスの有効期限が切れました。",
+ "ssoExpired": "AWS SSO セッションの有効期限が切れました。",
+ "credentialsRejected": "AWS によって認証情報が拒否されました。アクセスキー ID、シークレット、セッショントークンを確認してください。",
+ "accessDenied": "AWS Bedrock がこのリクエストを拒否しました。リージョン {{region}} で選択したモデルを呼び出す権限を AWS 管理者に依頼してください。",
+ "modelNotFound": "AWS Bedrock はリージョン {{region}} で選択したモデルを見つけられませんでした。モデル ID とそのリージョンでの提供状況を確認してください。",
+ "configurationRejected": "AWS Bedrock はリージョン {{region}} のモデル設定を拒否しました。モデル ID、推論プロファイル、リージョンを確認してください。",
+ "notConfigured": "AWS Bedrock が正しく設定されていません。リージョンと AWS 認証情報を確認してください。",
+ "serviceUnavailable": "需要が高いため、AWS Bedrock は一時的に利用できません。これは OpenWhispr の障害ではなく AWS サービス側の問題です。数分後にもう一度お試しください。",
+ "throttled": "リクエストが多すぎるため、AWS Bedrock は一時的にリクエストを制限しています。少し待ってから再試行してください。続く場合は、AWS 管理者に Bedrock の使用量とクォータの確認を依頼してください。",
+ "timeout": "AWS Bedrock が時間内に応答しませんでした。もう一度お試しください。続く場合は、インターネット接続と AWS Bedrock サービスの状態を確認してください。",
+ "network": "AWS Bedrock に接続できませんでした。インターネット接続を確認して、もう一度お試しください。",
+ "unknown": "AWS Bedrock エラー: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "サインアウトして再度サインインし、会社のアクセスを更新してから再試行してください。",
+ "reauthenticate": "再認証するには、ターミナルで次のコマンドを実行してください:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "技術情報",
+ "httpStatus": "HTTP ステータス",
+ "awsException": "AWS 例外",
+ "awsRequestId": "AWS リクエスト ID",
+ "underlyingError": "原因となったエラー",
+ "copy": "技術情報をコピー",
+ "copyCommand": "復旧コマンドをコピー"
+ },
"azure": {
"endpointHelp": "Azure OpenAI リソースのエンドポイント(例: https://myresource.openai.azure.com)。",
"deploymentHelp": "Azure OpenAI 内のモデルデプロイメント名。"
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index c0a1d4708..327bd40ef 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -759,6 +759,35 @@
"ssoHelp": "Usa sua configuração SSO do AWS CLI. Certifique-se de ter executado 'aws sso login'.",
"keysHelp": "Informe suas chaves de acesso AWS IAM."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "O acesso temporário à AWS expirou.",
+ "ssoExpired": "A sessão SSO da AWS expirou.",
+ "credentialsRejected": "As credenciais da AWS foram rejeitadas. Verifique o ID da chave de acesso, o segredo e o token de sessão.",
+ "accessDenied": "O AWS Bedrock negou esta solicitação. Peça ao administrador da AWS permissão para invocar o modelo selecionado na região {{region}}.",
+ "modelNotFound": "O AWS Bedrock não encontrou o modelo selecionado na região {{region}}. Verifique o ID do modelo e se ele está disponível nessa região.",
+ "configurationRejected": "O AWS Bedrock rejeitou a configuração do modelo para a região {{region}}. Verifique o ID do modelo, o perfil de inferência e a região.",
+ "notConfigured": "O AWS Bedrock não está configurado corretamente. Verifique a região e as credenciais da AWS.",
+ "serviceUnavailable": "O AWS Bedrock está temporariamente indisponível devido à alta demanda. Este é um problema do serviço da AWS, não uma indisponibilidade do OpenWhispr. Tente novamente em alguns minutos.",
+ "throttled": "O AWS Bedrock está limitando temporariamente as solicitações porque está recebendo muitas. Aguarde um momento e tente novamente. Se continuar, peça ao administrador da AWS para verificar o uso e as cotas do Bedrock.",
+ "timeout": "O AWS Bedrock não respondeu a tempo. Tente novamente. Se continuar, verifique sua conexão com a internet e o status do serviço AWS Bedrock.",
+ "network": "Não foi possível acessar o AWS Bedrock. Verifique sua conexão com a internet e tente novamente.",
+ "unknown": "Erro do AWS Bedrock: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Saia e entre novamente para renovar o acesso da empresa e tente outra vez.",
+ "reauthenticate": "Execute o comando abaixo no terminal para se autenticar novamente:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Detalhes técnicos",
+ "httpStatus": "Status HTTP",
+ "awsException": "Exceção da AWS",
+ "awsRequestId": "ID da solicitação da AWS",
+ "underlyingError": "Erro subjacente",
+ "copy": "Copiar detalhes técnicos",
+ "copyCommand": "Copiar comando de recuperação"
+ },
"azure": {
"endpointHelp": "O endpoint do seu recurso Azure OpenAI (ex.: https://myresource.openai.azure.com).",
"deploymentHelp": "Nome do deployment do seu modelo no Azure OpenAI."
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 8280f4e76..bd4a33f45 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "Использует настройки SSO из AWS CLI. Убедитесь, что выполнили 'aws sso login'.",
"keysHelp": "Введите ключи доступа AWS IAM."
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "Срок действия временного доступа к AWS истёк.",
+ "ssoExpired": "Срок действия сеанса AWS SSO истёк.",
+ "credentialsRejected": "AWS отклонил учётные данные. Проверьте ID ключа доступа, секретный ключ и токен сеанса.",
+ "accessDenied": "AWS Bedrock отклонил запрос. Попросите администратора AWS разрешить вызов выбранной модели в регионе {{region}}.",
+ "modelNotFound": "AWS Bedrock не нашёл выбранную модель в регионе {{region}}. Проверьте ID модели и её доступность в этом регионе.",
+ "configurationRejected": "AWS Bedrock отклонил конфигурацию модели для региона {{region}}. Проверьте ID модели, профиль вывода и регион.",
+ "notConfigured": "AWS Bedrock настроен неправильно. Проверьте регион и учётные данные AWS.",
+ "serviceUnavailable": "AWS Bedrock временно недоступен из-за высокой нагрузки. Это проблема сервиса AWS, а не сбой OpenWhispr. Повторите попытку через несколько минут.",
+ "throttled": "AWS Bedrock временно ограничивает запросы из-за их большого количества. Немного подождите и повторите попытку. Если проблема сохраняется, попросите администратора AWS проверить использование и квоты Bedrock.",
+ "timeout": "AWS Bedrock не ответил вовремя. Повторите попытку. Если проблема сохраняется, проверьте подключение к интернету и состояние сервиса AWS Bedrock.",
+ "network": "Не удалось связаться с AWS Bedrock. Проверьте подключение к интернету и повторите попытку.",
+ "unknown": "Ошибка AWS Bedrock: {{error}}",
+ "actions": {
+ "refreshManagedAccess": "Выйдите и войдите снова, чтобы обновить корпоративный доступ, затем повторите попытку.",
+ "reauthenticate": "Выполните следующую команду в терминале для повторной аутентификации:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "Технические сведения",
+ "httpStatus": "Статус HTTP",
+ "awsException": "Исключение AWS",
+ "awsRequestId": "ID запроса AWS",
+ "underlyingError": "Исходная ошибка",
+ "copy": "Копировать технические сведения",
+ "copyCommand": "Копировать команду восстановления"
+ },
"azure": {
"endpointHelp": "Endpoint вашего ресурса Azure OpenAI (например, https://myresource.openai.azure.com).",
"deploymentHelp": "Имя развёртывания модели в Azure OpenAI."
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 230afe850..b9db87e56 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "使用你的 AWS CLI SSO 配置。请确保已运行 'aws sso login'。",
"keysHelp": "输入你的 AWS IAM 访问密钥。"
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "AWS 临时访问权限已过期。",
+ "ssoExpired": "AWS SSO 会话已过期。",
+ "credentialsRejected": "AWS 拒绝了这些凭证。请检查访问密钥 ID、密钥和会话令牌。",
+ "accessDenied": "AWS Bedrock 拒绝了此请求。请让 AWS 管理员授予在区域 {{region}} 中调用所选模型的权限。",
+ "modelNotFound": "AWS Bedrock 在区域 {{region}} 中找不到所选模型。请检查模型 ID 以及该模型是否在此区域可用。",
+ "configurationRejected": "AWS Bedrock 拒绝了区域 {{region}} 的模型配置。请检查模型 ID、推理配置文件和区域。",
+ "notConfigured": "AWS Bedrock 配置不正确。请检查区域和 AWS 凭证。",
+ "serviceUnavailable": "由于需求过高,AWS Bedrock 暂时不可用。这是 AWS 服务问题,并非 OpenWhispr 中断。请几分钟后重试。",
+ "throttled": "由于收到的请求过多,AWS Bedrock 正在暂时限制请求。请稍候再试。如果问题持续,请让 AWS 管理员检查 Bedrock 使用量和配额。",
+ "timeout": "AWS Bedrock 未及时响应。请重试。如果问题持续,请检查互联网连接和 AWS Bedrock 服务状态。",
+ "network": "无法连接到 AWS Bedrock。请检查互联网连接并重试。",
+ "unknown": "AWS Bedrock 错误:{{error}}",
+ "actions": {
+ "refreshManagedAccess": "请退出并重新登录以刷新公司访问权限,然后重试。",
+ "reauthenticate": "请在终端中运行以下命令以重新进行身份验证:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "技术详情",
+ "httpStatus": "HTTP 状态",
+ "awsException": "AWS 异常",
+ "awsRequestId": "AWS 请求 ID",
+ "underlyingError": "底层错误",
+ "copy": "复制技术详情",
+ "copyCommand": "复制恢复命令"
+ },
"azure": {
"endpointHelp": "你的 Azure OpenAI 资源端点(例如 https://myresource.openai.azure.com)。",
"deploymentHelp": "Azure OpenAI 中的模型部署名称。"
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 333f7b732..30158c461 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -780,6 +780,35 @@
"ssoHelp": "使用你的 AWS CLI SSO 設定。請確保已執行 'aws sso login'。",
"keysHelp": "輸入你的 AWS IAM 存取金鑰。"
},
+ "errors": {
+ "bedrock": {
+ "temporaryAccessExpired": "AWS 暫時存取權限已過期。",
+ "ssoExpired": "AWS SSO 工作階段已過期。",
+ "credentialsRejected": "AWS 拒絕了這些憑證。請檢查存取金鑰 ID、密鑰和工作階段權杖。",
+ "accessDenied": "AWS Bedrock 拒絕了此請求。請讓 AWS 管理員授予在區域 {{region}} 中呼叫所選模型的權限。",
+ "modelNotFound": "AWS Bedrock 在區域 {{region}} 中找不到所選模型。請檢查模型 ID,以及該模型是否在此區域提供。",
+ "configurationRejected": "AWS Bedrock 拒絕了區域 {{region}} 的模型設定。請檢查模型 ID、推論設定檔和區域。",
+ "notConfigured": "AWS Bedrock 設定不正確。請檢查區域和 AWS 憑證。",
+ "serviceUnavailable": "由於需求過高,AWS Bedrock 暫時無法使用。這是 AWS 服務問題,並非 OpenWhispr 中斷。請幾分鐘後再試。",
+ "throttled": "由於收到太多請求,AWS Bedrock 正在暫時限制請求。請稍候再試。如果問題持續,請讓 AWS 管理員檢查 Bedrock 使用量和配額。",
+ "timeout": "AWS Bedrock 未及時回應。請重試。如果問題持續,請檢查網際網路連線和 AWS Bedrock 服務狀態。",
+ "network": "無法連線到 AWS Bedrock。請檢查網際網路連線並重試。",
+ "unknown": "AWS Bedrock 錯誤:{{error}}",
+ "actions": {
+ "refreshManagedAccess": "請登出並重新登入以更新公司存取權限,然後重試。",
+ "reauthenticate": "請在終端機中執行以下命令以重新驗證身分:"
+ }
+ }
+ },
+ "technicalDetails": {
+ "title": "技術詳細資料",
+ "httpStatus": "HTTP 狀態",
+ "awsException": "AWS 例外",
+ "awsRequestId": "AWS 請求 ID",
+ "underlyingError": "底層錯誤",
+ "copy": "複製技術詳細資料",
+ "copyCommand": "複製復原命令"
+ },
"azure": {
"endpointHelp": "你的 Azure OpenAI 資源端點(例如 https://myresource.openai.azure.com)。",
"deploymentHelp": "Azure OpenAI 中的模型部署名稱。"
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 66704b20b..a65fac8e3 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -963,7 +963,10 @@ class ReasoningService extends BaseReasoningService {
this.requestCancellationGeneration += 1;
for (const controller of this.activeRequestControllers) controller.abort();
this.activeRequestControllers.clear();
- if (typeof window !== "undefined") window.electronAPI?.cancelCloudReason?.();
+ if (typeof window !== "undefined") {
+ window.electronAPI?.cancelCloudReason?.();
+ window.electronAPI?.cancelEnterpriseReasoning?.();
+ }
this.cancelActiveStream();
}
diff --git a/src/services/ai/inferenceProviders/enterprise.ts b/src/services/ai/inferenceProviders/enterprise.ts
index 48fd46039..340340aa2 100644
--- a/src/services/ai/inferenceProviders/enterprise.ts
+++ b/src/services/ai/inferenceProviders/enterprise.ts
@@ -52,9 +52,26 @@ export const enterpriseProvider: InferenceProvider = {
error: result.error,
});
const enhanced = new Error(result.error || `${enterpriseId} reasoning failed`) as Error & {
+ messageKey?: string;
+ messageParams?: Record<string, string | number>;
+ action?: string;
+ actionKey?: string;
+ copyCommand?: string;
retryable?: boolean;
+ technicalDetails?: {
+ status?: number;
+ exceptionType?: string;
+ requestId?: string;
+ underlyingError?: string;
+ };
};
+ enhanced.messageKey = result.messageKey;
+ enhanced.messageParams = result.messageParams;
+ enhanced.action = result.action;
+ enhanced.actionKey = result.actionKey;
+ enhanced.copyCommand = result.copyCommand;
enhanced.retryable = result.retryable ?? false;
+ enhanced.technicalDetails = result.technicalDetails;
throw enhanced;
}
diff --git a/src/stores/cleanupFailureStore.ts b/src/stores/cleanupFailureStore.ts
index 66e096e98..97b5d4d10 100644
--- a/src/stores/cleanupFailureStore.ts
+++ b/src/stores/cleanupFailureStore.ts
@@ -1,21 +1,41 @@
import { create } from "zustand";
+export interface CleanupFailure {
+ message: string;
+ messageKey?: string;
+ messageParams?: Record<string, string | number>;
+ action?: string;
+ actionKey?: string;
+ copyCommand?: string;
+ technicalDetails?: {
+ status?: number;
+ exceptionType?: string;
+ requestId?: string;
+ underlyingError?: string;
+ };
+}
+
interface CleanupFailureState {
/** Dictations handed back raw because cleanup failed, not yet surfaced to the user. */
pending: number;
/** Cause of the most recent failure, shown with the toast so it's actionable. */
lastMessage: string;
+ /** Structured cause and AWS diagnostics for the most recent fallback. */
+ lastFailure: CleanupFailure | null;
}
export const useCleanupFailureStore = create<CleanupFailureState>(() => ({
pending: 0,
lastMessage: "",
+ lastFailure: null,
}));
-export function recordCleanupFailure(message = ""): void {
+export function recordCleanupFailure(failure: string | CleanupFailure = ""): void {
+ const normalized = typeof failure === "string" ? { message: failure } : failure;
useCleanupFailureStore.setState((state) => ({
pending: state.pending + 1,
- lastMessage: message,
+ lastMessage: normalized.message,
+ lastFailure: normalized,
}));
}
diff --git a/src/types/electron.ts b/src/types/electron.ts
index ae95eda40..f033aafbe 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -936,7 +936,7 @@ declare global {
restoreClipboard?: boolean;
allowClipboardFallback?: boolean;
}
- ) => Promise<void>;
+ ) => Promise<{ success: true; pasted: boolean }>;
captureSelectedText?: (options?: { probeEditable?: boolean }) => Promise<
| {
status: "selected";
@@ -1625,7 +1625,24 @@ declare global {
modelId: string,
agentName: string | null,
config: any
- ) => Promise<{ success: boolean; text?: string; error?: string; retryable?: boolean }>;
+ ) => Promise<{
+ success: boolean;
+ text?: string;
+ error?: string;
+ messageKey?: string;
+ messageParams?: Record<string, string | number>;
+ action?: string;
+ actionKey?: string;
+ copyCommand?: string;
+ retryable?: boolean;
+ technicalDetails?: {
+ status?: number;
+ exceptionType?: string;
+ requestId?: string;
+ underlyingError?: string;
+ };
+ }>;
+ cancelEnterpriseReasoning?: () => void;
enterpriseStreamStart?: (payload: {
streamId: string;
provider: string;
@@ -1897,7 +1914,21 @@ declare global {
testEnterpriseConnection?: (
provider: string,
config: Record<string, unknown>
- ) => Promise<{ success: boolean; error?: string; action?: string; copyCommand?: string }>;
+ ) => Promise<{
+ success: boolean;
+ error?: string;
+ messageKey?: string;
+ messageParams?: Record<string, string | number>;
+ action?: string;
+ actionKey?: string;
+ copyCommand?: string;
+ technicalDetails?: {
+ status?: number;
+ exceptionType?: string;
+ requestId?: string;
+ underlyingError?: string;
+ };
+ }>;
getManagedEnterpriseConfig?: (
accountId: string,
workspaceId: string,
diff --git a/test/helpers/audioManagerCancelLifecycle.test.js b/test/helpers/audioManagerCancelLifecycle.test.js
index 3d072e067..210bf9abf 100644
--- a/test/helpers/audioManagerCancelLifecycle.test.js
+++ b/test/helpers/audioManagerCancelLifecycle.test.js
@@ -436,13 +436,18 @@ test(
assert.equal(await manager.stopStreamingRecording(), true);
+ assert.equal(completions.length, 1);
+ assert.equal(completions[0].text, "the raw transcript");
+ assert.equal(
+ completions[0].cleanupFailure?.message,
+ "genuine cloud reasoning failure",
+ "a genuine cloud-reasoning failure in the streaming fallback must survive until paste"
+ );
assert.deepEqual(
globalThis.__streamingLeakCleanupFailureCalls,
- ["genuine cloud reasoning failure"],
- "a genuine cloud-reasoning failure in the streaming fallback must still be recorded"
+ [],
+ "cleanup failure must not be surfaced before the raw dictation is pasted"
);
- assert.equal(completions.length, 1);
- assert.equal(completions[0].text, "the raw transcript");
}
);
diff --git a/test/helpers/audioManagerCleanupFallback.test.js b/test/helpers/audioManagerCleanupFallback.test.js
new file mode 100644
index 000000000..a1e7db7d3
--- /dev/null
+++ b/test/helpers/audioManagerCleanupFallback.test.js
@@ -0,0 +1,128 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { loadAudioManager } = require("./harness/audioManager");
+
+test("cleanup failure details ride the raw result instead of notifying before paste", async (t) => {
+ globalThis.__cleanupFallbackImmediateNotifications = [];
+ t.after(() => delete globalThis.__cleanupFallbackImmediateNotifications);
+
+ const { createManager } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-audio-cleanup-fallback-",
+ settingsKey: "__audioCleanupFallbackSettings",
+ settings: {
+ useCleanupModel: true,
+ cleanupProvider: "bedrock",
+ cleanupMode: "enterprise",
+ cleanupDisableThinking: true,
+ useDictationAgent: false,
+ useDictationTranslation: false,
+ preferredLanguage: "en",
+ enterpriseSetupMode: "manual",
+ },
+ mockModules: {
+ "/stores/settingsStore": `
+ export const getSettings = () => globalThis.__audioCleanupFallbackSettings;
+ export const getEffectiveCleanupModel = () => "anthropic.claude-haiku";
+ export const selectResolvedLLMConfig = () => ({
+ mode: "enterprise",
+ provider: "bedrock",
+ model: "anthropic.claude-haiku"
+ });
+ export const isCloudCleanupMode = () => false;
+ export const isCloudDictationAgentMode = () => false;
+ export const isCloudTranslationMode = () => false;
+ export const useSettingsStore = { subscribe: () => () => {} };
+ `,
+ "/dictationAgentInference": `
+ export const resolveDictationAgentInference = () => ({
+ reachable: false, model: "", displayProvider: "none", config: {}
+ });
+ export const resolveDictationAgentVisionInference = () => ({
+ active: false, model: "", config: {}
+ });
+ `,
+ "/dictationTranslationInference": `
+ export const resolveDictationTranslationInference = () => ({
+ reachable: false, model: "", displayProvider: "none", config: {}
+ });
+ `,
+ "/stores/cleanupFailureStore": `
+ export const recordCleanupFailure = (failure) => {
+ globalThis.__cleanupFallbackImmediateNotifications.push(failure);
+ };
+ `,
+ },
+ });
+
+ const technicalDetails = {
+ status: 503,
+ exceptionType: "ServiceUnavailableException",
+ requestId: "request-503",
+ underlyingError: "AWS overloaded",
+ };
+ const failure = Object.assign(
+ new Error(
+ "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes."
+ ),
+ {
+ messageKey: "reasoning.enterprise.errors.bedrock.serviceUnavailable",
+ action: "Run the command below in your terminal to re-authenticate:",
+ actionKey: "reasoning.enterprise.errors.bedrock.actions.reauthenticate",
+ copyCommand: "aws sso login --profile company-sso",
+ technicalDetails,
+ }
+ );
+ const manager = createManager({
+ voiceAgentRequested: false,
+ translationRequested: false,
+ pendingCleanupFailure: null,
+ pendingAssistantConversation: null,
+ pendingSelectionEdit: null,
+ isReasoningAvailable: async () => true,
+ processWithReasoningModel: async () => {
+ throw failure;
+ },
+ });
+
+ const text = await manager.processTranscriptionCore("original dictation", "local");
+
+ assert.equal(text, "original dictation");
+ assert.deepEqual(globalThis.__cleanupFallbackImmediateNotifications, []);
+ assert.deepEqual(manager._takePendingResultExtras(), {
+ cleanupFailure: {
+ message: failure.message,
+ messageKey: failure.messageKey,
+ action: failure.action,
+ actionKey: failure.actionKey,
+ copyCommand: failure.copyCommand,
+ technicalDetails,
+ },
+ });
+ assert.deepEqual(manager._takePendingResultExtras(), {});
+});
+
+test("safePaste returns false when the preload reports that no text was pasted", async (t) => {
+ const { createManager, window } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-audio-cleanup-paste-outcome-",
+ settingsKey: "__audioCleanupPasteOutcomeSettings",
+ });
+ const manager = createManager({
+ onError: () => assert.fail("a resolved no-op is not a paste error"),
+ });
+ window.electronAPI.pasteText = async () => ({ success: true, pasted: false });
+
+ assert.equal(await manager.safePaste("onboarding transcript"), false);
+});
+
+test("safePaste returns true only when the preload reports a completed paste", async (t) => {
+ const { createManager, window } = await loadAudioManager(t, {
+ cachePrefix: "openwhispr-audio-cleanup-paste-success-",
+ settingsKey: "__audioCleanupPasteSuccessSettings",
+ });
+ const manager = createManager({
+ onError: () => assert.fail("a completed paste must not report an error"),
+ });
+ window.electronAPI.pasteText = async () => ({ success: true, pasted: true });
+
+ assert.equal(await manager.safePaste("completed transcript"), true);
+});
diff --git a/test/helpers/bedrockEnterpriseIpc.test.js b/test/helpers/bedrockEnterpriseIpc.test.js
new file mode 100644
index 000000000..dc42f6460
--- /dev/null
+++ b/test/helpers/bedrockEnterpriseIpc.test.js
@@ -0,0 +1,670 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+const handlers = new Map();
+const listeners = new Map();
+const generateCalls = [];
+let generateBehavior = async () => ({ text: "hello", finishReason: "stop" });
+let resolveManagedRuntime = async () => ({ managed: false });
+let handlerContext;
+
+const electronStub = {
+ app: {
+ getPath: () => "/tmp",
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ isPackaged: false,
+ on: () => {},
+ requestSingleInstanceLock: () => true,
+ },
+ ipcMain: {
+ handle: (channel, fn) => handlers.set(channel, fn),
+ on: (channel, fn) => listeners.set(channel, fn),
+ removeHandler: () => {},
+ },
+ net: {
+ fetch: async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({}),
+ text: async () => "{}",
+ }),
+ },
+ BrowserWindow: class BrowserWindow {
+ static getAllWindows() {
+ return [];
+ }
+ static fromWebContents() {
+ return null;
+ }
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+ clipboard: {},
+ nativeImage: {},
+ globalShortcut: {},
+ utilityProcess: {},
+ MessageChannelMain: class {},
+};
+
+Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "electron") return electronStub;
+ if (request === "./tokenStore") return { get: () => "test-token" };
+ if (request === "./enterpriseIdentityManager") {
+ return {
+ createEnterpriseIdentityManager: () => ({
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ }),
+ };
+ }
+ if (parent?.filename === handlersModulePath) {
+ if (request === "./debugLogger") {
+ return new Proxy({}, { get: () => () => {} });
+ }
+ if (request === "ai") {
+ return {
+ generateText: async (options) => {
+ generateCalls.push(options);
+ return generateBehavior(options);
+ },
+ };
+ }
+ if (request === "./enterpriseAiProviders") {
+ return {
+ getEnterpriseAIModel: async (_provider, _model, _apiKey, enterprise) => {
+ await enterprise?.managedCredentialProvider?.();
+ return { provider: "bedrock-test-model" };
+ },
+ };
+ }
+ if (request === "./cortiTranscription") {
+ return { transcribeAudio: async () => ({ text: "corti text" }) };
+ }
+ if (request === "./tinfoilTranscription") {
+ return {
+ transcribeWithTinfoil: async () => ({ text: "tinfoil text", model: "tinfoil-model" }),
+ getTinfoilChatModels: () => [],
+ };
+ }
+ if (request === "./windowBroadcast") {
+ return { broadcastToWindows: () => {} };
+ }
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+
+function buildFakeThis() {
+ const AgentStreamRequestRegistry = require("../../src/helpers/agentStreamRequestRegistry");
+ const target = {
+ sessionId: "test-session",
+ _enterpriseReasoningRequests: new AgentStreamRequestRegistry(),
+ };
+ return new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ });
+}
+
+function sender(id) {
+ const eventListeners = new Map();
+ let destroyed = false;
+ return {
+ id,
+ once: (event, listener) => eventListeners.set(event, listener),
+ removeListener: (event, listener) => {
+ if (eventListeners.get(event) === listener) eventListeners.delete(event);
+ },
+ isDestroyed: () => destroyed,
+ destroy: () => {
+ destroyed = true;
+ eventListeners.get("destroyed")?.();
+ },
+ };
+}
+
+function retryable503() {
+ return Object.assign(new Error("Bedrock overloaded"), {
+ name: "ServiceUnavailableException",
+ statusCode: 503,
+ responseHeaders: { "x-amzn-requestid": "aws-request-503" },
+ });
+}
+
+function managedContext() {
+ return {
+ accountId: "account-1",
+ workspaceId: "workspace-1",
+ authGeneration: 1,
+ inferenceScope: "cleanup",
+ setupMode: "managed",
+ provider: "bedrock",
+ generation: 1,
+ providerVersion: 1,
+ };
+}
+
+function managedBedrockRuntime(overrides = {}) {
+ return {
+ managed: true,
+ provider: "bedrock",
+ model: "anthropic.claude-haiku",
+ generation: 1,
+ version: 1,
+ config: { region: "us-west-2" },
+ credentialProvider: async () => ({
+ accessKeyId: "AKIAEXAMPLE",
+ secretAccessKey: "example-secret",
+ sessionToken: "example-session-token",
+ }),
+ ...overrides,
+ };
+}
+
+test.before(() => {
+ delete require.cache[handlersModulePath];
+ const IPCHandlers = require(handlersModulePath);
+ const Ctor = IPCHandlers.default || IPCHandlers;
+ handlerContext = buildFakeThis();
+ Ctor.prototype.setupHandlers.call(handlerContext);
+ assert.ok(handlers.get("test-enterprise-connection"));
+ assert.ok(handlers.get("process-enterprise-reasoning"));
+ assert.ok(listeners.get("enterprise-reasoning-cancel"));
+});
+
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+test.beforeEach(() => {
+ generateCalls.length = 0;
+ resolveManagedRuntime = async () => ({ managed: false });
+});
+
+test("Check connection uses the Bedrock retry policy and disables nested AI SDK retries", async () => {
+ let attempts = 0;
+ generateBehavior = async () => {
+ attempts += 1;
+ if (attempts === 1) throw retryable503();
+ return { text: "hello", finishReason: "stop" };
+ };
+ const originalRandom = Math.random;
+ Math.random = () => 0;
+ try {
+ const result = await handlers.get("test-enterprise-connection")(
+ { sender: sender(2) },
+ "bedrock",
+ {
+ model: "anthropic.claude-haiku",
+ bedrockRegion: "eu-west-1",
+ }
+ );
+
+ assert.deepEqual(result, { success: true });
+ assert.equal(generateCalls.length, 2);
+ assert.ok(generateCalls.every((call) => call.maxRetries === 0));
+ } finally {
+ Math.random = originalRandom;
+ }
+});
+
+test("Check connection retries timed-out Bedrock attempts with the existing timeout message", async () => {
+ let attempts = 0;
+ generateBehavior = async (options) => {
+ attempts += 1;
+ await new Promise((resolve, reject) => {
+ options.abortSignal.addEventListener("abort", () => reject(options.abortSignal.reason), {
+ once: true,
+ });
+ });
+ };
+ const originalRandom = Math.random;
+ Math.random = () => 0;
+ let watchdog;
+ try {
+ const request = handlers.get("test-enterprise-connection")({ sender: sender(1) }, "bedrock", {
+ model: "anthropic.claude-haiku",
+ bedrockRegion: "eu-west-1",
+ timeoutMs: 5,
+ });
+ const result = await Promise.race([
+ request,
+ new Promise((_, reject) => {
+ watchdog = setTimeout(() => reject(new Error("Bedrock timeout did not settle")), 250);
+ }),
+ ]);
+
+ assert.equal(attempts, 6);
+ assert.equal(
+ result.error,
+ "AWS Bedrock did not respond in time. Please try again. If this continues, check your internet connection and AWS Bedrock service status."
+ );
+ } finally {
+ clearTimeout(watchdog);
+ Math.random = originalRandom;
+ }
+});
+
+test("Check connection timeout includes managed credential resolution", async () => {
+ let releaseCredentials;
+ let credentialAttempts = 0;
+ const resolvingCredentials = new Promise((resolve) => (releaseCredentials = resolve));
+ resolveManagedRuntime = async () =>
+ managedBedrockRuntime({
+ credentialProvider: async () => {
+ credentialAttempts += 1;
+ return resolvingCredentials;
+ },
+ });
+ handlerContext.enterpriseIdentityManager = {
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ };
+ generateBehavior = async () => ({ text: "hello", finishReason: "stop" });
+ const originalRandom = Math.random;
+ Math.random = () => 0;
+ try {
+ const request = handlers.get("test-enterprise-connection")({ sender: sender(22) }, "bedrock", {
+ model: "renderer-model-is-ignored",
+ managedContext: managedContext(),
+ timeoutMs: 5,
+ });
+ const completedInBound = await Promise.race([
+ request.then((result) => ({ completed: true, result })),
+ new Promise((resolve) => setTimeout(() => resolve({ completed: false }), 250)),
+ ]);
+ releaseCredentials({
+ accessKeyId: "AKIAEXAMPLE",
+ secretAccessKey: "example-secret",
+ sessionToken: "example-session-token",
+ });
+ const result = await request;
+
+ assert.equal(completedInBound.completed, true);
+ assert.equal(credentialAttempts, 6);
+ assert.equal(
+ result.error,
+ "AWS Bedrock did not respond in time. Please try again. If this continues, check your internet connection and AWS Bedrock service status."
+ );
+ } finally {
+ Math.random = originalRandom;
+ }
+});
+
+test("dictation cleanup uses the Bedrock retry policy and returns the eventual text", async () => {
+ let attempts = 0;
+ generateBehavior = async () => {
+ attempts += 1;
+ if (attempts === 1) throw retryable503();
+ return { text: "cleaned dictation", finishReason: "stop" };
+ };
+ const originalRandom = Math.random;
+ Math.random = () => 0;
+ try {
+ const result = await handlers.get("process-enterprise-reasoning")(
+ { sender: sender(3) },
+ "raw dictation",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationCleanup",
+ bedrockRegion: "eu-west-1",
+ systemPrompt: "Clean the dictation",
+ }
+ );
+
+ assert.deepEqual(result, { success: true, text: "cleaned dictation" });
+ assert.equal(generateCalls.length, 2);
+ assert.ok(generateCalls.every((call) => call.maxRetries === 0));
+ } finally {
+ Math.random = originalRandom;
+ }
+});
+
+test("non-cleanup Bedrock scopes preserve the AI SDK retry policy", async () => {
+ generateBehavior = async () => {
+ throw retryable503();
+ };
+ const originalRandom = Math.random;
+ Math.random = () => 0;
+ try {
+ const result = await handlers.get("process-enterprise-reasoning")(
+ { sender: sender(6) },
+ "translate this",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationTranslation",
+ bedrockRegion: "eu-west-1",
+ systemPrompt: "Translate it",
+ }
+ );
+
+ assert.equal(result.success, false);
+ assert.equal(generateCalls.length, 1);
+ assert.equal("maxRetries" in generateCalls[0], false);
+ } finally {
+ Math.random = originalRandom;
+ }
+});
+
+test("Bedrock cleanup cancellation aborts only the requesting renderer without retrying", async () => {
+ const requestingSender = sender(10);
+ const otherSender = sender(11);
+ let attempts = 0;
+ let requestSignal;
+ let releaseRequest;
+ const started = new Promise((resolve) => (releaseRequest = resolve));
+ generateBehavior = async (options) => {
+ attempts += 1;
+ requestSignal = options.abortSignal;
+ releaseRequest();
+ await new Promise((resolve, reject) => {
+ options.abortSignal.addEventListener("abort", () => reject(options.abortSignal.reason), {
+ once: true,
+ });
+ });
+ };
+
+ const request = handlers.get("process-enterprise-reasoning")(
+ { sender: requestingSender },
+ "raw dictation",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationCleanup",
+ bedrockRegion: "eu-west-1",
+ systemPrompt: "Clean the dictation",
+ }
+ );
+ await started;
+ listeners.get("enterprise-reasoning-cancel")({ sender: otherSender });
+ assert.equal(requestSignal.aborted, false);
+ listeners.get("enterprise-reasoning-cancel")({ sender: requestingSender });
+ await request;
+
+ assert.equal(requestSignal.aborted, true);
+ assert.equal(attempts, 1);
+});
+
+test("Bedrock cleanup cancellation settles while managed runtime resolution is pending", async () => {
+ const requestingSender = sender(12);
+ let releaseResolution;
+ let resolutionStarted;
+ const resolving = new Promise((resolve) => (releaseResolution = resolve));
+ const started = new Promise((resolve) => (resolutionStarted = resolve));
+ resolveManagedRuntime = async () => {
+ resolutionStarted();
+ return resolving;
+ };
+ handlerContext.enterpriseIdentityManager = {
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ };
+
+ const request = handlers.get("process-enterprise-reasoning")(
+ { sender: requestingSender },
+ "raw dictation",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationCleanup",
+ managedContext: {
+ accountId: "account-1",
+ workspaceId: "workspace-1",
+ authGeneration: 1,
+ inferenceScope: "cleanup",
+ setupMode: "managed",
+ provider: "bedrock",
+ generation: 1,
+ providerVersion: 1,
+ },
+ }
+ );
+ await Promise.race([
+ started,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error("managed resolution did not start")), 100)
+ ),
+ ]);
+ listeners.get("enterprise-reasoning-cancel")({ sender: requestingSender });
+ const settledBeforeRelease = await Promise.race([
+ request.then(() => true),
+ new Promise((resolve) => setTimeout(() => resolve(false), 25)),
+ ]);
+ releaseResolution({
+ managed: true,
+ provider: "bedrock",
+ model: "anthropic.claude-haiku",
+ generation: 1,
+ version: 1,
+ config: { region: "eu-west-1" },
+ credentialProvider: async () => ({}),
+ });
+ await request;
+
+ assert.equal(settledBeforeRelease, true);
+ assert.equal(generateCalls.length, 0);
+});
+
+test("Bedrock cleanup cancellation settles while managed credentials are pending", async () => {
+ const requestingSender = sender(13);
+ let releaseCredentials;
+ let credentialsStarted;
+ const resolvingCredentials = new Promise((resolve) => (releaseCredentials = resolve));
+ const started = new Promise((resolve) => (credentialsStarted = resolve));
+ resolveManagedRuntime = async () =>
+ managedBedrockRuntime({
+ credentialProvider: async () => {
+ credentialsStarted();
+ return resolvingCredentials;
+ },
+ });
+ handlerContext.enterpriseIdentityManager = {
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ };
+
+ const request = handlers.get("process-enterprise-reasoning")(
+ { sender: requestingSender },
+ "raw dictation",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationCleanup",
+ managedContext: managedContext(),
+ }
+ );
+ await Promise.race([
+ started,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error("credentials did not start")), 100)
+ ),
+ ]);
+ listeners.get("enterprise-reasoning-cancel")({ sender: requestingSender });
+ const settledBeforeRelease = await Promise.race([
+ request.then(() => true),
+ new Promise((resolve) => setTimeout(() => resolve(false), 25)),
+ ]);
+ releaseCredentials({
+ accessKeyId: "AKIAEXAMPLE",
+ secretAccessKey: "example-secret",
+ sessionToken: "example-session-token",
+ });
+ await request;
+
+ assert.equal(settledBeforeRelease, true);
+ assert.equal(generateCalls.length, 0);
+});
+
+test("managed Bedrock failures use the resolved region in actionable copy", async () => {
+ resolveManagedRuntime = async () => managedBedrockRuntime();
+ handlerContext.enterpriseIdentityManager = {
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ };
+
+ for (const { label, error, rendererRegion } of [
+ {
+ label: "permission",
+ error: Object.assign(new Error("Not allowed to invoke model"), {
+ name: "AccessDeniedException",
+ $metadata: { httpStatusCode: 403, requestId: "managed-permission-request" },
+ }),
+ rendererRegion: "eu-west-1",
+ },
+ {
+ label: "model",
+ error: Object.assign(new Error("Selected model does not exist"), {
+ name: "ResourceNotFoundException",
+ $metadata: { httpStatusCode: 404, requestId: "managed-model-request" },
+ }),
+ },
+ {
+ label: "configuration",
+ error: Object.assign(new Error("Invalid inference profile"), {
+ name: "ValidationException",
+ $metadata: { httpStatusCode: 400, requestId: "managed-config-request" },
+ }),
+ rendererRegion: "ap-southeast-1",
+ },
+ ]) {
+ generateBehavior = async () => {
+ throw error;
+ };
+ const result = await handlers.get("test-enterprise-connection")(
+ { sender: sender(20) },
+ "bedrock",
+ {
+ model: "renderer-model-is-ignored",
+ managedContext: managedContext(),
+ ...(rendererRegion ? { bedrockRegion: rendererRegion } : {}),
+ }
+ );
+
+ assert.equal(result.success, false, label);
+ assert.match(result.error, /us-west-2/, label);
+ if (rendererRegion) assert.doesNotMatch(result.error, new RegExp(rendererRegion), label);
+ }
+});
+
+test("managed Bedrock credential expiry keeps AWS diagnostics and gives no profile command", async () => {
+ const expired = Object.assign(
+ new Error("The security token included in the request is expired"),
+ {
+ name: "ExpiredTokenException",
+ $metadata: {
+ httpStatusCode: 403,
+ requestId: "managed-expired-request",
+ },
+ }
+ );
+ resolveManagedRuntime = async () =>
+ managedBedrockRuntime({
+ credentialProvider: async () => {
+ throw expired;
+ },
+ });
+ handlerContext.enterpriseIdentityManager = {
+ resolveProvider: (...args) => resolveManagedRuntime(...args),
+ clear: () => {},
+ };
+
+ const result = await handlers.get("test-enterprise-connection")(
+ { sender: sender(21) },
+ "bedrock",
+ { model: "renderer-model-is-ignored", managedContext: managedContext() }
+ );
+
+ assert.equal(result.success, false);
+ assert.match(result.action, /sign out and sign back in/i);
+ assert.equal(result.copyCommand, undefined);
+ assert.deepEqual(result.technicalDetails, {
+ status: 403,
+ exceptionType: "ExpiredTokenException",
+ requestId: "managed-expired-request",
+ underlyingError: "The security token included in the request is expired",
+ });
+});
+
+test("Check connection returns AWS diagnostics without a dictation fallback status", async () => {
+ generateBehavior = async () => {
+ throw Object.assign(new Error("Bad signature"), {
+ name: "UnrecognizedClientException",
+ statusCode: 401,
+ responseHeaders: { "x-amzn-requestid": "connection-request-id" },
+ });
+ };
+
+ const result = await handlers.get("test-enterprise-connection")(
+ { sender: sender(4) },
+ "bedrock",
+ {
+ model: "anthropic.claude-haiku",
+ bedrockRegion: "eu-west-1",
+ }
+ );
+
+ assert.equal(result.success, false);
+ assert.match(result.error, /credentials were rejected/i);
+ assert.deepEqual(result.technicalDetails, {
+ status: 401,
+ exceptionType: "UnrecognizedClientException",
+ requestId: "connection-request-id",
+ underlyingError: "Bad signature",
+ });
+ assert.equal("fallbackStatus" in result, false);
+});
+
+test("dictation cleanup returns preserved AWS diagnostics to the renderer", async () => {
+ generateBehavior = async () => {
+ throw Object.assign(new Error("Not allowed to invoke model"), {
+ name: "AccessDeniedException",
+ statusCode: 403,
+ responseHeaders: { "x-amzn-requestid": "cleanup-request-id" },
+ });
+ };
+
+ const result = await handlers.get("process-enterprise-reasoning")(
+ { sender: sender(5) },
+ "raw dictation",
+ "anthropic.claude-haiku",
+ null,
+ {
+ provider: "bedrock",
+ inferenceScope: "dictationCleanup",
+ bedrockRegion: "eu-west-1",
+ systemPrompt: "Clean it",
+ }
+ );
+
+ assert.equal(result.success, false);
+ assert.match(result.error, /denied this request/i);
+ assert.deepEqual(result.technicalDetails, {
+ status: 403,
+ exceptionType: "AccessDeniedException",
+ requestId: "cleanup-request-id",
+ underlyingError: "Not allowed to invoke model",
+ });
+});
diff --git a/test/helpers/bedrockRequestPolicy.test.js b/test/helpers/bedrockRequestPolicy.test.js
new file mode 100644
index 000000000..8120b15c5
--- /dev/null
+++ b/test/helpers/bedrockRequestPolicy.test.js
@@ -0,0 +1,341 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const {
+ mapEnterpriseError,
+ runBedrockRequest,
+ unwrapRetryError,
+} = require("../../src/helpers/enterpriseProviderErrors");
+
+const SERVICE_UNAVAILABLE_MESSAGE =
+ "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes.";
+const THROTTLED_MESSAGE =
+ "AWS Bedrock is temporarily limiting requests because it is receiving too many. Please wait a moment and try again. If this continues, ask your AWS administrator to check your Bedrock usage and quotas.";
+const TIMEOUT_MESSAGE =
+ "AWS Bedrock did not respond in time. Please try again. If this continues, check your internet connection and AWS Bedrock service status.";
+const NETWORK_MESSAGE =
+ "AWS Bedrock could not be reached. Check your internet connection and try again.";
+
+function awsError({ name, status, message = name, requestId = "request-123", code }) {
+ return Object.assign(new Error(message), {
+ name,
+ ...(code ? { code } : {}),
+ $metadata: {
+ ...(status ? { httpStatusCode: status } : {}),
+ requestId,
+ },
+ });
+}
+
+function deterministicRetryOptions() {
+ const delays = [];
+ return {
+ delays,
+ options: {
+ initialDelayMs: 100,
+ maxDelayMs: 10_000,
+ random: () => 0.5,
+ sleep: async (delay) => delays.push(delay),
+ },
+ };
+}
+
+test("Bedrock cleanup succeeds after a retryable 503", async () => {
+ const { delays, options } = deterministicRetryOptions();
+ let attempts = 0;
+
+ const result = await runBedrockRequest(async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ throw awsError({
+ name: "ServiceUnavailableException",
+ status: 503,
+ message: "Service unavailable",
+ });
+ }
+ return "cleaned text";
+ }, options);
+
+ assert.equal(result, "cleaned text");
+ assert.equal(attempts, 2);
+ assert.deepEqual(delays, [50]);
+});
+
+test("Bedrock cleanup aborts during retry backoff without another attempt", async () => {
+ const controller = new AbortController();
+ let attempts = 0;
+ let releaseSleep;
+ const sleeping = new Promise((resolve) => (releaseSleep = resolve));
+ const request = runBedrockRequest(
+ async () => {
+ attempts += 1;
+ throw awsError({ name: "ServiceUnavailableException", status: 503 });
+ },
+ {
+ signal: controller.signal,
+ random: () => 0.5,
+ sleep: async (_delay, signal) => {
+ releaseSleep();
+ await new Promise((resolve, reject) => {
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
+ });
+ },
+ }
+ );
+
+ await sleeping;
+ controller.abort();
+ await assert.rejects(request, (error) => error?.name === "AbortError");
+ assert.equal(attempts, 1);
+});
+
+test("Bedrock stops after six total attempts when 503 responses continue", async () => {
+ const { delays, options } = deterministicRetryOptions();
+ let attempts = 0;
+
+ await assert.rejects(
+ runBedrockRequest(async () => {
+ attempts += 1;
+ throw awsError({
+ name: "ServiceUnavailableException",
+ status: 503,
+ message: "Still overloaded",
+ requestId: `request-${attempts}`,
+ });
+ }, options),
+ (error) => error.$metadata.requestId === "request-6"
+ );
+
+ assert.equal(attempts, 6);
+ assert.deepEqual(delays, [50, 100, 200, 400, 800]);
+ assert.equal(
+ mapEnterpriseError("bedrock", awsError({ name: "ServiceUnavailableException", status: 503 }))
+ .message,
+ SERVICE_UNAVAILABLE_MESSAGE
+ );
+});
+
+test("Bedrock retries 429 throttling and returns the quota-specific message", async () => {
+ const { options } = deterministicRetryOptions();
+ let attempts = 0;
+ const throttled = awsError({
+ name: "ThrottlingException",
+ status: 429,
+ message: "Too many requests",
+ });
+
+ const result = await runBedrockRequest(async () => {
+ attempts += 1;
+ if (attempts === 1) throw throttled;
+ return "ok";
+ }, options);
+
+ assert.equal(result, "ok");
+ assert.equal(attempts, 2);
+ assert.equal(mapEnterpriseError("bedrock", throttled).message, THROTTLED_MESSAGE);
+});
+
+test("Bedrock retries a request timeout and returns the timeout message", async () => {
+ const { options } = deterministicRetryOptions();
+ let attempts = 0;
+ const timeout = awsError({ name: "TimeoutError", message: "socket timed out" });
+
+ const result = await runBedrockRequest(async () => {
+ attempts += 1;
+ if (attempts === 1) throw timeout;
+ return "ok";
+ }, options);
+
+ assert.equal(result, "ok");
+ assert.equal(attempts, 2);
+ assert.equal(mapEnterpriseError("bedrock", timeout).message, TIMEOUT_MESSAGE);
+});
+
+test("Bedrock retries audited network and Undici timeout cause shapes", async () => {
+ for (const [code, expectedMessage] of [
+ ["ENETDOWN", NETWORK_MESSAGE],
+ ["EHOSTDOWN", NETWORK_MESSAGE],
+ ["UND_ERR_HEADERS_TIMEOUT", TIMEOUT_MESSAGE],
+ ["UND_ERR_BODY_TIMEOUT", TIMEOUT_MESSAGE],
+ ]) {
+ const transportError = Object.assign(new Error(`transport failed: ${code}`), { code });
+ const apiCallError = Object.assign(new Error("Failed to call AWS Bedrock"), {
+ name: "AI_APICallError",
+ cause: transportError,
+ });
+ const { options } = deterministicRetryOptions();
+ let attempts = 0;
+
+ const result = await runBedrockRequest(async () => {
+ attempts += 1;
+ if (attempts === 1) throw apiCallError;
+ return "ok";
+ }, options);
+
+ assert.equal(result, "ok", code);
+ assert.equal(attempts, 2, code);
+ assert.equal(mapEnterpriseError("bedrock", apiCallError).message, expectedMessage, code);
+ }
+});
+
+test("Bedrock does not retry access denied errors", async () => {
+ const { options } = deterministicRetryOptions();
+ let attempts = 0;
+ const denied = awsError({
+ name: "AccessDeniedException",
+ status: 403,
+ message: "User is not authorized to perform bedrock:InvokeModel",
+ });
+
+ await assert.rejects(
+ runBedrockRequest(async () => {
+ attempts += 1;
+ throw denied;
+ }, options),
+ denied
+ );
+
+ assert.equal(attempts, 1);
+ assert.match(
+ mapEnterpriseError("bedrock", denied, { bedrockRegion: "eu-west-1" }).message,
+ /permission/i
+ );
+});
+
+test("Bedrock keeps rejected authentication distinct from permission errors", () => {
+ const invalidToken = awsError({
+ name: "InvalidClientTokenId",
+ status: 403,
+ message: "The security token included in the request is invalid",
+ });
+
+ assert.match(mapEnterpriseError("bedrock", invalidToken).message, /credentials were rejected/i);
+});
+
+test("Bedrock normalizes AI SDK exception identity from headers and parsed data", () => {
+ for (const scenario of [
+ {
+ label: "case-insensitive response header",
+ error: Object.assign(new Error("The security token is invalid"), {
+ name: "AI_APICallError",
+ statusCode: 403,
+ responseHeaders: {
+ "X-AmZn-ErRoRtYpE": "com.amazon.identity#InvalidClientTokenId:client",
+ },
+ }),
+ expectedMessage: /credentials were rejected/i,
+ expectedExceptionType: "InvalidClientTokenId",
+ },
+ {
+ label: "parsed data code",
+ error: Object.assign(new Error("The security token is invalid"), {
+ name: "AI_APICallError",
+ statusCode: 403,
+ data: { code: "InvalidClientTokenId:client" },
+ }),
+ expectedMessage: /credentials were rejected/i,
+ expectedExceptionType: "InvalidClientTokenId",
+ },
+ {
+ label: "parsed data __type",
+ error: Object.assign(new Error("The requested model was not found"), {
+ name: "AI_APICallError",
+ statusCode: 404,
+ data: { __type: "com.amazon.bedrock#ResourceNotFoundException" },
+ }),
+ expectedMessage: /could not find the selected model/i,
+ expectedExceptionType: "ResourceNotFoundException",
+ },
+ ]) {
+ const mapped = mapEnterpriseError("bedrock", scenario.error, {
+ bedrockRegion: "us-west-2",
+ });
+ assert.match(mapped.message, scenario.expectedMessage, scenario.label);
+ assert.equal(
+ mapped.technicalDetails.exceptionType,
+ scenario.expectedExceptionType,
+ scenario.label
+ );
+ }
+});
+
+test("Bedrock does not retry invalid model or configuration errors", async () => {
+ const { options } = deterministicRetryOptions();
+
+ for (const error of [
+ awsError({
+ name: "ValidationException",
+ status: 400,
+ message: "The provided model identifier is invalid",
+ }),
+ Object.assign(new Error("Region is missing"), { name: "CredentialsProviderError" }),
+ ]) {
+ let attempts = 0;
+ await assert.rejects(
+ runBedrockRequest(async () => {
+ attempts += 1;
+ throw error;
+ }, options),
+ error
+ );
+ assert.equal(attempts, 1);
+ }
+
+ assert.match(
+ mapEnterpriseError("bedrock", awsError({ name: "ValidationException", status: 400 }), {
+ bedrockRegion: "eu-west-1",
+ }).message,
+ /model.*configuration.*eu-west-1/i
+ );
+});
+
+test("RetryError.lastError is unwrapped before classification and diagnostics", () => {
+ const underlying = awsError({
+ name: "ServiceUnavailableException",
+ status: 503,
+ message: "Bedrock overloaded in eu-west-1",
+ requestId: "aws-request-underlying",
+ });
+ const wrapped = Object.assign(new Error("Failed after 3 attempts"), {
+ name: "AI_RetryError",
+ lastError: underlying,
+ });
+
+ assert.equal(unwrapRetryError(wrapped), underlying);
+ const mapped = mapEnterpriseError("bedrock", wrapped);
+ assert.equal(mapped.message, SERVICE_UNAVAILABLE_MESSAGE);
+ assert.deepEqual(mapped.technicalDetails, {
+ status: 503,
+ exceptionType: "ServiceUnavailableException",
+ requestId: "aws-request-underlying",
+ underlyingError: "Bedrock overloaded in eu-west-1",
+ });
+});
+
+test("Bedrock mappings include renderer localization metadata", () => {
+ const unavailable = mapEnterpriseError(
+ "bedrock",
+ awsError({ name: "ServiceUnavailableException", status: 503 })
+ );
+ assert.equal(
+ unavailable.messageKey,
+ "reasoning.enterprise.errors.bedrock.serviceUnavailable"
+ );
+
+ const denied = mapEnterpriseError(
+ "bedrock",
+ awsError({ name: "AccessDeniedException", status: 403 }),
+ { bedrockRegion: "eu-west-1" }
+ );
+ assert.equal(denied.messageKey, "reasoning.enterprise.errors.bedrock.accessDenied");
+ assert.deepEqual(denied.messageParams, { region: "eu-west-1" });
+
+ const expired = mapEnterpriseError(
+ "bedrock",
+ awsError({ name: "ExpiredTokenException", status: 403 }),
+ { bedrockProfile: "company-sso" }
+ );
+ assert.equal(expired.messageKey, "reasoning.enterprise.errors.bedrock.ssoExpired");
+ assert.equal(expired.actionKey, "reasoning.enterprise.errors.bedrock.actions.reauthenticate");
+ assert.equal(expired.copyCommand, "aws sso login --profile company-sso");
+});
diff --git a/test/helpers/cleanupFailureToast.test.js b/test/helpers/cleanupFailureToast.test.js
new file mode 100644
index 000000000..687394f76
--- /dev/null
+++ b/test/helpers/cleanupFailureToast.test.js
@@ -0,0 +1,104 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const { renderToStaticMarkup } = require("react-dom/server");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+test("cleanup toast localizes AWS recovery guidance and keeps fallback status quieter", async (t) => {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__cleanupFailureToasts;
+ });
+ globalThis.__cleanupFailureToasts = [];
+ installBrowserGlobals(t);
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-cleanup-failure-toast-",
+ mockModules: {
+ "/ui/useToast": `
+ export const useToast = () => ({
+ toast: (props) => globalThis.__cleanupFailureToasts.push(props)
+ });
+ `,
+ "/utils/windowContext": `
+ export const isDictationPanelWindow = () => false;
+ `,
+ },
+ });
+ const { default: CleanupFailureToastListener } = await vite.ssrLoadModule(
+ "/components/CleanupFailureToastListener.tsx"
+ );
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("es");
+ const { recordCleanupFailure, useCleanupFailureStore } = await vite.ssrLoadModule(
+ "/stores/cleanupFailureStore.ts"
+ );
+ useCleanupFailureStore.setState({ pending: 0, lastMessage: "", lastFailure: null });
+
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(CleanupFailureToastListener)));
+
+ const failure = {
+ message:
+ "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes.",
+ messageKey: "reasoning.enterprise.errors.bedrock.serviceUnavailable",
+ action: "Run the command below in your terminal to re-authenticate:",
+ actionKey: "reasoning.enterprise.errors.bedrock.actions.reauthenticate",
+ copyCommand: "aws sso login --profile company-sso",
+ technicalDetails: {
+ status: 503,
+ exceptionType: "ServiceUnavailableException",
+ requestId: "aws-request-503",
+ underlyingError: "Bedrock overloaded",
+ },
+ };
+ await React.act(async () => recordCleanupFailure(failure));
+
+ assert.equal(globalThis.__cleanupFailureToasts.length, 1);
+ assert.deepEqual(globalThis.__cleanupFailureToasts[0], {
+ title:
+ "AWS Bedrock no está disponible temporalmente debido a una alta demanda. Este es un problema del servicio de AWS, no una interrupción de OpenWhispr. Vuelve a intentarlo en unos minutos.",
+ description: "Ejecuta el siguiente comando en tu terminal para volver a autenticarte:",
+ secondaryDescription: "Tu dictado se pegó sin limpieza con IA.",
+ copyCommand: "aws sso login --profile company-sso",
+ technicalDetails: failure.technicalDetails,
+ variant: "destructive",
+ duration: 10_000,
+ });
+});
+
+test("technical AWS details use the selected UI language", async (t) => {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-technical-error-details-",
+ });
+ const { TechnicalErrorDetails } = await vite.ssrLoadModule(
+ "/components/ui/TechnicalErrorDetails.tsx"
+ );
+ const { default: i18n } = await vite.ssrLoadModule("/i18n.ts");
+ await i18n.changeLanguage("es");
+
+ const markup = renderToStaticMarkup(
+ React.createElement(TechnicalErrorDetails, {
+ details: {
+ status: 503,
+ exceptionType: "ServiceUnavailableException",
+ requestId: "request-123",
+ underlyingError: "Bedrock overloaded",
+ },
+ })
+ );
+
+ assert.match(markup, /Detalles técnicos/);
+ assert.match(markup, /Estado HTTP: 503/);
+ assert.match(markup, /Excepción de AWS: ServiceUnavailableException/);
+ assert.match(markup, /ID de solicitud de AWS: request-123/);
+ assert.match(markup, /Error subyacente: Bedrock overloaded/);
+ assert.match(markup, /aria-label="Copiar detalles técnicos"/);
+});
diff --git a/test/helpers/enterpriseAiProviders.test.js b/test/helpers/enterpriseAiProviders.test.js
index 5f3eb77a3..6675335d2 100644
--- a/test/helpers/enterpriseAiProviders.test.js
+++ b/test/helpers/enterpriseAiProviders.test.js
@@ -4,6 +4,18 @@ const {
getEnterpriseAIModel,
toAzureOpenAIBaseUrl,
} = require("../../src/helpers/enterpriseAiProviders.js");
+const { mapEnterpriseError } = require("../../src/helpers/enterpriseProviderErrors.js");
+
+const bedrockPrompt = [{ role: "user", content: [{ type: "text", text: "Hello" }] }];
+
+async function captureBedrockGenerationError(model) {
+ let error;
+ await assert.rejects(model.doGenerate({ prompt: bedrockPrompt }), (caught) => {
+ error = caught;
+ return true;
+ });
+ return error;
+}
test("builds the Azure SDK base below the public resource origin", () => {
assert.equal(
@@ -27,6 +39,255 @@ test("rejects unsupported managed Azure endpoint forms", () => {
}
});
+test("managed Bedrock credential failures preserve the original AWS error", async () => {
+ const cause = Object.assign(new Error("credential exchange failed"), {
+ code: "ECONNRESET",
+ });
+ const credentialError = Object.assign(new Error("temporary credentials expired"), {
+ name: "ExpiredTokenException",
+ $metadata: {
+ httpStatusCode: 403,
+ requestId: "credential-request-123",
+ },
+ cause,
+ });
+
+ await assert.rejects(
+ getEnterpriseAIModel("bedrock", "anthropic.claude-haiku", "", {
+ bedrockRegion: "us-west-2",
+ managedCredentialProvider: async () => {
+ throw credentialError;
+ },
+ }),
+ (error) => error === credentialError
+ );
+});
+
+test("managed Bedrock credentials are resolved once before the real SDK reaches fetch", async (t) => {
+ const originalFetch = global.fetch;
+ t.after(() => {
+ global.fetch = originalFetch;
+ });
+ let request;
+ global.fetch = async (url, init) => {
+ request = {
+ url: String(url),
+ headers: Object.fromEntries(new Headers(init.headers)),
+ };
+ return new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ let credentialCalls = 0;
+ const model = await getEnterpriseAIModel("bedrock", "anthropic.claude-haiku", "", {
+ bedrockRegion: "us-west-2",
+ managedCredentialProvider: async () => {
+ credentialCalls += 1;
+ return {
+ accessKeyId: "AKIAEXAMPLE",
+ secretAccessKey: "example-secret",
+ sessionToken: "example-session-token",
+ };
+ },
+ });
+
+ assert.equal(credentialCalls, 1);
+ await assert.rejects(
+ model.doGenerate({ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }] })
+ );
+ assert.equal(credentialCalls, 1);
+ assert.match(request.url, /^https:\/\/bedrock-runtime\.us-west-2\.amazonaws\.com\//);
+ assert.match(request.headers.authorization, /^AWS4-HMAC-SHA256 /);
+ assert.equal(request.headers["x-amz-security-token"], "example-session-token");
+});
+
+test("real Bedrock provider maps header-only AWS exception identities", async (t) => {
+ const originalFetch = global.fetch;
+ t.after(() => {
+ global.fetch = originalFetch;
+ });
+
+ for (const scenario of [
+ {
+ label: "authentication",
+ status: 403,
+ exceptionHeader: "InvalidClientTokenId:client",
+ requestId: "auth-request-123",
+ body: { message: "The security token included in the request is invalid" },
+ expectedMessage:
+ "AWS credentials were rejected. Check the access key ID, secret, and session token.",
+ expectedExceptionType: "InvalidClientTokenId",
+ expectedRetryable: undefined,
+ },
+ {
+ label: "model not found",
+ status: 404,
+ exceptionHeader: "com.amazon.bedrock#ResourceNotFoundException",
+ requestId: "model-request-123",
+ body: { message: "The requested model was not found" },
+ expectedMessage:
+ "AWS Bedrock could not find the selected model in region us-west-2. Check the model ID and whether it is available in that region.",
+ expectedExceptionType: "ResourceNotFoundException",
+ expectedRetryable: undefined,
+ },
+ {
+ label: "service unavailable",
+ status: 503,
+ exceptionHeader: "com.amazon.bedrock#ServiceUnavailableException:retry",
+ requestId: "unavailable-request-123",
+ body: { message: "Service unavailable" },
+ expectedMessage:
+ "AWS Bedrock is temporarily unavailable due to high demand. This is an AWS service issue, not an OpenWhispr outage. Please try again in a few minutes.",
+ expectedExceptionType: "ServiceUnavailableException",
+ expectedRetryable: true,
+ },
+ ]) {
+ global.fetch = async () =>
+ new Response(JSON.stringify(scenario.body), {
+ status: scenario.status,
+ headers: {
+ "Content-Type": "application/json",
+ "X-Amzn-ErrorType": scenario.exceptionHeader,
+ "X-Amzn-RequestId": scenario.requestId,
+ },
+ });
+ const model = await getEnterpriseAIModel("bedrock", "anthropic.claude-haiku", "", {
+ bedrockRegion: "us-west-2",
+ bedrockAccessKeyId: "AKIAEXAMPLE",
+ bedrockSecretAccessKey: "example-secret",
+ });
+
+ const error = await captureBedrockGenerationError(model);
+ const mapped = mapEnterpriseError("bedrock", error, { bedrockRegion: "us-west-2" });
+
+ assert.equal(error.name, "AI_APICallError", scenario.label);
+ assert.equal(mapped.message, scenario.expectedMessage, scenario.label);
+ assert.equal(mapped.retryable, scenario.expectedRetryable, scenario.label);
+ assert.deepEqual(
+ mapped.technicalDetails,
+ {
+ status: scenario.status,
+ exceptionType: scenario.expectedExceptionType,
+ requestId: scenario.requestId,
+ underlyingError: scenario.body.message,
+ },
+ scenario.label
+ );
+ }
+});
+
+test("explicit Bedrock credential sources cannot fall through to populated AWS environment", async (t) => {
+ const environmentKeys = [
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ ];
+ const originalEnvironment = new Map(
+ environmentKeys.map((key) => [
+ key,
+ {
+ present: Object.prototype.hasOwnProperty.call(process.env, key),
+ value: process.env[key],
+ },
+ ])
+ );
+ const originalFetch = global.fetch;
+ let fetchCalls = 0;
+ process.env.AWS_ACCESS_KEY_ID = "AKIAENVIRONMENT";
+ process.env.AWS_SECRET_ACCESS_KEY = "environment-secret";
+ process.env.AWS_SESSION_TOKEN = "environment-session-token";
+ global.fetch = async () => {
+ fetchCalls += 1;
+ return new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ t.after(() => {
+ global.fetch = originalFetch;
+ for (const [key, original] of originalEnvironment) {
+ if (original.present) process.env[key] = original.value;
+ else delete process.env[key];
+ }
+ });
+
+ for (const [label, enterprise] of [
+ ["null managed result", { managedCredentialProvider: async () => null }],
+ [
+ "missing managed access key",
+ { managedCredentialProvider: async () => ({ secretAccessKey: "managed-secret" }) },
+ ],
+ [
+ "missing managed secret",
+ { managedCredentialProvider: async () => ({ accessKeyId: "AKIAMANAGED" }) },
+ ],
+ ["partial manual static keys", { bedrockAccessKeyId: "AKIAEXPLICIT" }],
+ ]) {
+ await assert.rejects(
+ getEnterpriseAIModel("bedrock", "anthropic.claude-haiku", "", {
+ bedrockRegion: "us-west-2",
+ ...enterprise,
+ }),
+ (error) =>
+ error?.name === "CredentialsProviderError" &&
+ /accessKeyId and secretAccessKey/.test(error.message),
+ label
+ );
+ }
+ assert.equal(fetchCalls, 0);
+});
+
+test("Bedrock environment fallback remains available without an explicit credential source", async (t) => {
+ const environmentKeys = [
+ "AWS_ACCESS_KEY_ID",
+ "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN",
+ ];
+ const originalEnvironment = new Map(
+ environmentKeys.map((key) => [
+ key,
+ {
+ present: Object.prototype.hasOwnProperty.call(process.env, key),
+ value: process.env[key],
+ },
+ ])
+ );
+ const originalFetch = global.fetch;
+ let request;
+ process.env.AWS_ACCESS_KEY_ID = "AKIAENVIRONMENT";
+ process.env.AWS_SECRET_ACCESS_KEY = "environment-secret";
+ process.env.AWS_SESSION_TOKEN = "environment-session-token";
+ global.fetch = async (url, init) => {
+ request = {
+ url: String(url),
+ headers: Object.fromEntries(new Headers(init.headers)),
+ };
+ return new Response("{}", {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+ t.after(() => {
+ global.fetch = originalFetch;
+ for (const [key, original] of originalEnvironment) {
+ if (original.present) process.env[key] = original.value;
+ else delete process.env[key];
+ }
+ });
+
+ const model = await getEnterpriseAIModel("bedrock", "anthropic.claude-haiku", "", {
+ bedrockRegion: "us-west-2",
+ });
+ await assert.rejects(
+ model.doGenerate({ prompt: [{ role: "user", content: [{ type: "text", text: "Hello" }] }] })
+ );
+
+ assert.match(request.url, /^https:\/\/bedrock-runtime\.us-west-2\.amazonaws\.com\//);
+ assert.match(request.headers.authorization, /^AWS4-HMAC-SHA256 /);
+ assert.equal(request.headers["x-amz-security-token"], "environment-session-token");
+});
+
test("the pinned Azure SDK requests the deployment below /openai/v1 with bearer auth", async (t) => {
const originalFetch = global.fetch;
t.after(() => {
@@ -45,7 +306,7 @@ test("the pinned Azure SDK requests the deployment below /openai/v1 with bearer
});
};
- const model = getEnterpriseAIModel("azure", "deployment-a", "", {
+ const model = await getEnterpriseAIModel("azure", "deployment-a", "", {
azureEndpoint: "https://example.openai.azure.com",
azureApiVersion: "v1",
managedTokenProvider: async () => "temporary-bearer-token",
@@ -78,7 +339,7 @@ test("manual Azure setup preserves legacy endpoints and API-key auth", async (t)
});
};
- const model = getEnterpriseAIModel("azure", "legacy-deployment", "legacy-api-key", {
+ const model = await getEnterpriseAIModel("azure", "legacy-deployment", "legacy-api-key", {
azureEndpoint: "https://legacy.example.com/custom/openai",
azureApiVersion: "2024-10-21",
});
diff --git a/test/helpers/ipcPasteOutcome.test.js b/test/helpers/ipcPasteOutcome.test.js
new file mode 100644
index 000000000..88494bf43
--- /dev/null
+++ b/test/helpers/ipcPasteOutcome.test.js
@@ -0,0 +1,158 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+
+const handlersModulePath = require.resolve("../../src/helpers/ipcHandlers");
+const originalLoad = Module._load;
+const handlers = new Map();
+
+const electronStub = {
+ app: {
+ getPath: () => "/tmp",
+ getName: () => "test",
+ getVersion: () => "0.0.0",
+ isPackaged: false,
+ on: () => {},
+ requestSingleInstanceLock: () => true,
+ },
+ ipcMain: {
+ handle: (channel, fn) => handlers.set(channel, fn),
+ on: () => {},
+ removeHandler: () => {},
+ },
+ net: { fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) },
+ BrowserWindow: class BrowserWindow {
+ static getAllWindows() {
+ return [];
+ }
+ static fromWebContents() {
+ return null;
+ }
+ },
+ shell: {},
+ dialog: {},
+ screen: { getPrimaryDisplay: () => ({ workAreaSize: { width: 0, height: 0 } }) },
+ systemPreferences: { getMediaAccessStatus: () => "granted" },
+ session: { fromPartition: () => ({}) },
+ clipboard: {},
+ nativeImage: {},
+ globalShortcut: {},
+ utilityProcess: {},
+ MessageChannelMain: class {},
+};
+
+Module._load = function loadWithElectronStub(request, parent, isMain) {
+ if (request === "electron") return electronStub;
+ if (parent?.filename === handlersModulePath && request === "./debugLogger") {
+ return new Proxy({}, { get: () => () => {} });
+ }
+ return originalLoad.call(this, request, parent, isMain);
+};
+
+function anything() {
+ return new Proxy(function () {}, {
+ get: (_target, property) => {
+ if (property === Symbol.toPrimitive || property === "toString") return () => "";
+ if (property === "then") return undefined;
+ return anything();
+ },
+ apply: () => anything(),
+ });
+}
+
+let target;
+test.before(() => {
+ delete require.cache[handlersModulePath];
+ const IPCHandlers = require(handlersModulePath);
+ const Ctor = IPCHandlers.default || IPCHandlers;
+ target = {
+ sessionId: "test-session",
+ _autoLearnEnabled: false,
+ textEditMonitor: null,
+ selectionManager: null,
+ };
+ Ctor.prototype.setupHandlers.call(
+ new Proxy(target, {
+ get: (value, property) => (property in value ? value[property] : anything()),
+ })
+ );
+ assert.ok(handlers.get("paste-text"), "paste-text must be registered");
+});
+
+test.after(() => {
+ Module._load = originalLoad;
+});
+
+test("paste-text reports an onboarding demo no-op without invoking the clipboard", async () => {
+ let pasteCalls = 0;
+ target.windowManager = { isOnboardingDemoActive: () => true };
+ target.clipboardManager = {
+ pasteText: async () => {
+ pasteCalls += 1;
+ },
+ };
+
+ const result = await handlers.get("paste-text")({ sender: {} }, "demo transcript");
+
+ assert.deepEqual(result, { success: true, pasted: false });
+ assert.equal(pasteCalls, 0);
+});
+
+test("paste-text reports pasted only after the clipboard paste completes", async () => {
+ const pastes = [];
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ target.clipboardManager = {
+ pasteText: async (text, options) => {
+ pastes.push({ text, options });
+ },
+ };
+
+ const result = await handlers.get("paste-text")({ sender: { id: 1 } }, "normal transcript");
+
+ assert.deepEqual(result, { success: true, pasted: true });
+ assert.equal(pastes.length, 1);
+});
+
+test("paste-text preserves a clipboard-only fallback as not pasted", async () => {
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ target.clipboardManager = {
+ pasteText: async () => ({ pasted: false }),
+ };
+
+ const result = await handlers.get("paste-text")({ sender: { id: 1 } }, "manual transcript", {
+ allowClipboardFallback: true,
+ });
+
+ assert.deepEqual(result, { success: true, pasted: false });
+});
+
+test("paste-text does not schedule AutoLearn monitoring after a clipboard-only fallback", async (t) => {
+ const originalSetTimeout = global.setTimeout;
+ t.after(() => {
+ global.setTimeout = originalSetTimeout;
+ target._autoLearnEnabled = false;
+ target.textEditMonitor = null;
+ });
+ global.setTimeout = (callback) => {
+ callback();
+ return 1;
+ };
+ const monitored = [];
+ target._autoLearnEnabled = true;
+ target.textEditMonitor = {
+ lastTargetPid: 42,
+ activateTargetPid: async () => true,
+ startMonitoring: (...args) => monitored.push(args),
+ };
+ target.windowManager = { isOnboardingDemoActive: () => false };
+ target.clipboardManager = {
+ pasteText: async () => ({ pasted: false }),
+ };
+
+ const result = await handlers.get("paste-text")({ sender: { id: 1 } }, "manual transcript", {
+ allowClipboardFallback: true,
+ });
+
+ assert.deepEqual(result, { success: true, pasted: false });
+ assert.deepEqual(monitored, []);
+});
diff --git a/test/helpers/preloadAuthBridge.test.js b/test/helpers/preloadAuthBridge.test.js
index 905c8c703..48acad92f 100644
--- a/test/helpers/preloadAuthBridge.test.js
+++ b/test/helpers/preloadAuthBridge.test.js
@@ -185,6 +185,14 @@ test("cloud reasoning cancellation is forwarded to the main process", () => {
assert.deepEqual(sends, [["cloud-reason-cancel"]]);
});
+test("enterprise reasoning cancellation is forwarded to the main process", () => {
+ const { api, sends } = loadPreloadApi();
+
+ api.cancelEnterpriseReasoning();
+
+ assert.deepEqual(sends, [["enterprise-reasoning-cancel"]]);
+});
+
test("cloud transcription cancellation is forwarded to the main process", () => {
const { api, sends } = loadPreloadApi();
diff --git a/test/helpers/useAudioRecordingCleanupFallback.test.js b/test/helpers/useAudioRecordingCleanupFallback.test.js
new file mode 100644
index 000000000..e6d59d3e4
--- /dev/null
+++ b/test/helpers/useAudioRecordingCleanupFallback.test.js
@@ -0,0 +1,112 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const React = require("react");
+const { createRoot } = require("react-dom/client");
+const {
+ createRendererServer,
+ installBrowserGlobals,
+ installHookDom,
+} = require("../lib/rendererTestHarness");
+
+const FAKE_AUDIO_MANAGER_SOURCE = `
+export default class FakeAudioManager {
+ constructor() {
+ this.voiceAgentRequested = false;
+ this.translationRequested = false;
+ this.sttConfig = { success: true };
+ this.pasteCalls = 0;
+ globalThis.__cleanupFallbackManager = this;
+ }
+ setCallbacks(callbacks) { this.callbacks = callbacks; }
+ getState() { return {}; }
+ shouldUseStreaming() { return false; }
+ async safePaste() {
+ this.pasteCalls += 1;
+ return globalThis.__cleanupFallbackPasteOutcome?.pasted === true;
+ }
+ saveTranscription() {}
+ cleanup() {}
+}
+`;
+
+test("raw cleanup fallback is reported only after the original dictation is pasted", async (t) => {
+ let root = null;
+ t.after(async () => {
+ if (root) await React.act(async () => root.unmount());
+ delete globalThis.__cleanupFallbackManager;
+ delete globalThis.__cleanupFallbackPasteOutcome;
+ });
+
+ const noopDispose = () => () => {};
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ onToggleDictation: noopDispose,
+ onToggleVoiceAgent: noopDispose,
+ onToggleTranslation: noopDispose,
+ onStartDictation: noopDispose,
+ onPrepareDictation: noopDispose,
+ onCancelDictationPreparation: noopDispose,
+ onStopDictation: noopDispose,
+ completeDictationPreview: async () => {},
+ hideDictationPreview: async () => {},
+ dictationLifecycleStateChanged: () => {},
+ },
+ },
+ });
+ const container = installHookDom(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-cleanup-fallback-hook-",
+ mockModules: {
+ "/helpers/audioManager": FAKE_AUDIO_MANAGER_SOURCE,
+ "/utils/logger": `
+ export default { debug() {}, info() {}, warn() {}, error() {} };
+ `,
+ },
+ });
+ const { useAudioRecording } = await vite.ssrLoadModule("/hooks/useAudioRecording.js");
+ const { useSettingsStore } = await vite.ssrLoadModule("/stores/settingsStore.ts");
+ const { useCleanupFailureStore } = await vite.ssrLoadModule("/stores/cleanupFailureStore.ts");
+ useSettingsStore.setState({
+ autoPasteEnabled: true,
+ keepTranscriptionInClipboard: false,
+ snippets: [],
+ });
+ useCleanupFailureStore.setState({ pending: 0, lastFailure: null });
+
+ function Harness() {
+ useAudioRecording(() => {}, { onDemoEvent: () => {} });
+ return null;
+ }
+
+ root = createRoot(container);
+ await React.act(async () => root.render(React.createElement(Harness)));
+ const manager = globalThis.__cleanupFallbackManager;
+ const cleanupFailure = {
+ message: "AWS Bedrock is temporarily unavailable.",
+ technicalDetails: { status: 503, requestId: "request-503" },
+ };
+ const result = {
+ success: true,
+ text: "original dictation",
+ rawText: "original dictation",
+ source: "local",
+ cleanupFailure,
+ };
+
+ globalThis.__cleanupFallbackPasteOutcome = { success: true, pasted: true };
+ await React.act(async () => manager.callbacks.onTranscriptionComplete({ ...result }));
+ assert.equal(manager.pasteCalls, 1);
+ assert.equal(useCleanupFailureStore.getState().pending, 1);
+ assert.deepEqual(useCleanupFailureStore.getState().lastFailure, cleanupFailure);
+
+ useCleanupFailureStore.setState({ pending: 0, lastFailure: null });
+ globalThis.__cleanupFallbackPasteOutcome = { success: true, pasted: false };
+ await React.act(async () => manager.callbacks.onTranscriptionComplete({ ...result }));
+ assert.equal(useCleanupFailureStore.getState().pending, 0);
+
+ useSettingsStore.setState({ autoPasteEnabled: false, keepTranscriptionInClipboard: false });
+ globalThis.__cleanupFallbackPasteOutcome = { success: true, pasted: true };
+ await React.act(async () => manager.callbacks.onTranscriptionComplete({ ...result }));
+ assert.equal(useCleanupFailureStore.getState().pending, 0);
+});
diff --git a/test/services/enterpriseInferenceErrors.test.js b/test/services/enterpriseInferenceErrors.test.js
new file mode 100644
index 000000000..d2d5bf485
--- /dev/null
+++ b/test/services/enterpriseInferenceErrors.test.js
@@ -0,0 +1,74 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+test("enterprise cleanup preserves AWS technical details on the renderer error", async (t) => {
+ const technicalDetails = {
+ status: 503,
+ exceptionType: "ServiceUnavailableException",
+ requestId: "aws-request-1",
+ underlyingError: "Service unavailable",
+ };
+ installBrowserGlobals(t, {
+ window: {
+ electronAPI: {
+ processEnterpriseReasoning: async () => ({
+ success: false,
+ error: "AWS Bedrock is temporarily unavailable.",
+ messageKey: "reasoning.enterprise.errors.bedrock.serviceUnavailable",
+ messageParams: { region: "eu-west-1" },
+ action: "Retry after signing in.",
+ actionKey: "reasoning.enterprise.errors.bedrock.actions.refreshManagedAccess",
+ copyCommand: "aws sso login --profile company-sso",
+ retryable: true,
+ technicalDetails,
+ }),
+ },
+ },
+ });
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-enterprise-inference-errors-",
+ mockModules: {
+ "/models/ModelRegistry": `
+ export const getOpenAiApiConfig = () => ({ supportsTemperature: true });
+ export const isEnterpriseProvider = (provider) => provider === "bedrock";
+ `,
+ "/stores/settingsStore": `
+ export const getSettings = () => ({ cleanupProvider: "bedrock" });
+ `,
+ "/services/ai/enterpriseSettings": `
+ export const getEnterpriseCallSettings = () => ({});
+ `,
+ "/utils/logger": `
+ export default { logReasoning() {} };
+ `,
+ },
+ });
+ const { enterpriseProvider } = await vite.ssrLoadModule(
+ "/services/ai/inferenceProviders/enterprise.ts"
+ );
+
+ await assert.rejects(
+ enterpriseProvider.call({
+ text: "raw text",
+ model: "anthropic.claude-haiku",
+ agentName: null,
+ config: { provider: "bedrock", systemPrompt: "Clean it" },
+ ctx: { getSystemPrompt: () => "unused" },
+ }),
+ (error) => {
+ assert.equal(error.message, "AWS Bedrock is temporarily unavailable.");
+ assert.equal(error.messageKey, "reasoning.enterprise.errors.bedrock.serviceUnavailable");
+ assert.deepEqual(error.messageParams, { region: "eu-west-1" });
+ assert.equal(error.action, "Retry after signing in.");
+ assert.equal(
+ error.actionKey,
+ "reasoning.enterprise.errors.bedrock.actions.refreshManagedAccess"
+ );
+ assert.equal(error.copyCommand, "aws sso login --profile company-sso");
+ assert.equal(error.retryable, true);
+ assert.deepEqual(error.technicalDetails, technicalDetails);
+ return true;
+ }
+ );
+});