Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(policy): Harden desktop policy enforcement lifecycle
Chadpiha0ac3aba552aa
diff --git a/src/components/ui/PromptStudio.tsx b/src/components/ui/PromptStudio.tsxindex acab347bd..db4d477ef 100644--- a/src/components/ui/PromptStudio.tsx+++ b/src/components/ui/PromptStudio.tsx@@ -204,6 +204,7 @@ export default function PromptStudio({ className = "", kind = "cleanup" }: Promptry {const result = await ReasoningService.processText(testText, agent.model, agentName, {...agent.config,+ requiresAgent: true,systemPrompt: resolvePrompt("dictationAgent", {agentName,language: settings.preferredLanguage,diff --git a/src/helpers/audioManager.js b/src/helpers/audioManager.jsindex 3a42b9e92..35a4e24d1 100644--- a/src/helpers/audioManager.js+++ b/src/helpers/audioManager.js@@ -2161,12 +2161,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);const result =route.kind === "agent"- ? await this.processAgentCommand(- normalizedText,- targetModel,- agentName,- { ...reasoningConfig, requiresAgent: true }- )+ ? await this.processAgentCommand(normalizedText, targetModel, agentName, {+ ...reasoningConfig,+ requiresAgent: true,+ }): await this.processWithReasoningModel(normalizedText,targetModel,@@ -2422,12 +2420,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);try {if (route.kind === "agent") {this.assertAgentAllowedByPolicy();- const reasoned = await this.processAgentCommand(- processedText,- route.model,- agentName,- { ...route.config, requiresAgent: true }- );+ const reasoned = await this.processAgentCommand(processedText, route.model, agentName, {+ ...route.config,+ requiresAgent: true,+ });if (reasoned) processedText = reasoned;} else if (route.kind === "cleanup" && cleanupCloudMode === "openwhispr") {const reasonResult = await withSessionRefresh(async () => {@@ -4043,12 +4039,10 @@ registerProcessor("pcm-streaming-processor", PCMStreamingProcessor);try {if (route.kind === "agent") {this.assertAgentAllowedByPolicy();- const reasoned = await this.processAgentCommand(- finalText,- route.model,- agentName,- { ...route.config, requiresAgent: true }- );+ const reasoned = await this.processAgentCommand(finalText, route.model, agentName, {+ ...route.config,+ requiresAgent: true,+ });if (reasoned) finalText = reasoned;logger.info("Streaming dictation-agent complete",diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 8e18f051b..932402a62 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -7274,6 +7274,7 @@ class IPCHandlers {customDictionary: opts.customDictionary,customPrompt: opts.customPrompt,systemPrompt: opts.systemPrompt,+ requestPurpose: opts.requestPurpose,promptMode: opts.promptMode,language: opts.language,locale: opts.locale,diff --git a/src/helpers/workspacePolicyManager.js b/src/helpers/workspacePolicyManager.jsindex 3c7a294f8..65addd26b 100644--- a/src/helpers/workspacePolicyManager.js+++ b/src/helpers/workspacePolicyManager.js@@ -8,6 +8,10 @@ function authError(message, code = "AUTH_CONTEXT_CHANGED") {return Object.assign(new Error(message), { code });}+function unresolvablePolicyError(message) {+ return Object.assign(new Error(message), { code: "POLICY_UNRESOLVABLE" });+}+function normalizeAccountId(value) {return typeof value === "string" && value.trim() ? value.trim() : null;}@@ -59,6 +63,7 @@ function createWorkspacePolicyManager({const successfulRefreshes = new Map();const lastAttempts = new Map();const lastRecoveryAttempts = new Map();+ const managedPolicyRequired = new Set();let revision = 0;function captureIdentity(request = {}) {@@ -116,11 +121,58 @@ function createWorkspacePolicyManager({};}- function cachedData(identity) {+ function rawCachedData(identity) {const cached = readWorkspacePolicyCache(cachePath, cacheIdentity(identity));return validatePolicyData(cached) ? cached : null;}+ function cachedData(identity) {+ const cached = rawCachedData(identity);+ return cached?.managed === false && cached.requiresManagedPolicy === true ? null : cached;+ }++ function requiresManagedPolicy(identity) {+ if (managedPolicyRequired.has(identityKey(identity))) return true;+ const cached = rawCachedData(identity);+ return cached?.managed === false && cached.requiresManagedPolicy === true;+ }++ function errorSnapshot(identity, code, error) {+ const current = snapshots.get(identityKey(identity));+ return {+ success: false,+ status: "error",+ revision: current?.revision ?? revision,+ accountId: identity.accountId,+ authGeneration: identity.authGeneration,+ code,+ error,+ };+ }++ function markManagedPolicyRequired(identity, message) {+ const key = identityKey(identity);+ const current = snapshots.get(key);+ const cached = rawCachedData(identity);+ if (current?.data.managed || cached?.managed) return;++ const wasRequired = requiresManagedPolicy(identity);+ managedPolicyRequired.add(key);+ if (cached && !wasRequired) {+ try {+ writeWorkspacePolicyCache(cachePath, cacheIdentity(identity), {+ ...cached,+ requiresManagedPolicy: true,+ });+ } catch (error) {+ logger?.error?.("Policy fail-closed marker write failed", error);+ }+ }+ if (!wasRequired) {+ broadcast?.(errorSnapshot(identity, "POLICY_UNRESOLVABLE", message));+ }+ }+function publicSnapshot(identity, data, status, snapshotRevision) {return {success: true,@@ -169,6 +221,7 @@ function createWorkspacePolicyManager({}function acceptSuccessfulResponse(identity, data, status) {+ managedPolicyRequired.delete(identityKey(identity));const result = accept(identity, data, status);if (result.status !== "current") successfulRefreshes.set(identityKey(identity), now());return result;@@ -191,6 +244,9 @@ function createWorkspacePolicyManager({if (current?.data.managed) {return publicSnapshot(identity, current.data, "cached", current.revision);}+ if (requiresManagedPolicy(identity)) {+ throw unresolvablePolicyError("Organization policy was previously unresolved");+ }const cached = cachedData(identity);if (cached?.managed) return accept(identity, cached, "cached");return acceptSuccessfulResponse(@@ -200,6 +256,13 @@ function createWorkspacePolicyManager({);}if (!response.ok) {+ let errorBody = null;+ try {+ errorBody = await response.json();+ } catch {}+ if (errorBody?.code === "POLICY_UNRESOLVABLE") {+ throw unresolvablePolicyError(errorBody.error || "Organization policy is unresolvable");+ }const error = new Error(`API error: ${response.status}`);error.status = response.status;throw error;@@ -211,7 +274,12 @@ function createWorkspacePolicyManager({...json?.data,endpointSupported: true,};- if (!validatePolicyData(data)) throw new Error("Malformed policy response");+ if (!validatePolicyData(data)) {+ if (data.managed === true) {+ throw unresolvablePolicyError("Managed policy response is malformed");+ }+ throw new Error("Malformed policy response");+ }return acceptSuccessfulResponse(identity, data, "network");} finally {clearTimeout(timeout);@@ -228,20 +296,20 @@ function createWorkspacePolicyManager({};}+ const requiresManagedFallback = error?.code === "POLICY_UNRESOLVABLE";+ if (requiresManagedFallback) markManagedPolicyRequired(identity, error.message);const cached = cachedData(identity);- if (cached) {+ if (cached && (!requiresManagedFallback || cached.managed)) {const key = identityKey(identity);const current = snapshots.get(key);if (current) return publicSnapshot(identity, current.data, "cached", current.revision);return accept(identity, cached, "cached");}logger?.warn?.("Workspace policy unavailable", { error: error?.message });- return {- success: false,- status: "error",- code: "POLICY_UNAVAILABLE",- error: error?.message || String(error),- };+ const code = requiresManagedPolicy(identity)+ ? "POLICY_UNRESOLVABLE"+ : error?.code || "POLICY_UNAVAILABLE";+ return errorSnapshot(identity, code, error?.message || String(error));}}@@ -264,6 +332,7 @@ function createWorkspacePolicyManager({lastSuccessfulRefresh === undefined ? null : now() - lastSuccessfulRefresh;if (current &&+ !(current.data.managed === false && requiresManagedPolicy(identity)) &&successfulRefreshAge !== null &&successfulRefreshAge >= 0 &&successfulRefreshAge < successfulRefreshMs@@ -293,6 +362,13 @@ function createWorkspacePolicyManager({recoveryAttemptAge < minimumAttemptIntervalMs: attemptAge !== null && attemptAge >= 0 && attemptAge < minimumAttemptIntervalMs;if (attemptIsThrottled) {+ if (requiresManagedPolicy(identity)) {+ return errorSnapshot(+ identity,+ "POLICY_UNRESOLVABLE",+ "Organization policy is awaiting a successful refresh"+ );+ }if (current) return publicSnapshot(identity, current.data, "cached", current.revision);const cached = cachedData(identity);if (cached) return accept(identity, cached, "cached");diff --git a/src/services/ai/inferenceProviders/openwhispr.ts b/src/services/ai/inferenceProviders/openwhispr.tsindex d3ee0f241..5734b4a6f 100644--- a/src/services/ai/inferenceProviders/openwhispr.ts+++ b/src/services/ai/inferenceProviders/openwhispr.ts@@ -18,6 +18,7 @@ export const openwhisprProvider: InferenceProvider = {customDictionary: ctx.getCustomDictionary(),customPrompt,systemPrompt: config.systemPrompt,+ requestPurpose: config.requiresAgent ? "agent" : undefined,// Routing already decided this is cleanup — stop the server from// flipping to the action prompt on an agent-name mention.promptMode: config.systemPrompt ? undefined : "cleanup",diff --git a/src/stores/policyLifecycle.ts b/src/stores/policyLifecycle.tsindex a7cc9a3ae..7fa15ee72 100644--- a/src/stores/policyLifecycle.ts+++ b/src/stores/policyLifecycle.ts@@ -12,6 +12,16 @@ interface ResolvedPolicyRefreshState {authGeneration: number | null;}+type PolicyLifecycleStatus = ResolvedPolicyRefreshState["status"];++export function shouldPreserveResolvedPolicyOnFailure(+ status: PolicyLifecycleStatus,+ failureCode?: string+): boolean {+ if (status === "managed") return true;+ return status === "unmanaged" && failureCode !== "POLICY_UNRESOLVABLE";+}+export function resolvedPolicyRefreshIdentity(state: ResolvedPolicyRefreshState): Omit<PolicySnapshotIdentity, "revision"> | null {diff --git a/src/stores/policyStore.ts b/src/stores/policyStore.tsindex 5be99dcf9..f34a75dd2 100644--- a/src/stores/policyStore.ts+++ b/src/stores/policyStore.ts@@ -7,6 +7,7 @@ import {POLICY_SUCCESS_REFRESH_MS,resolvedPolicyRefreshIdentity,shouldAcceptPolicySnapshot,+ shouldPreserveResolvedPolicyOnFailure,} from "./policyLifecycle";import {effectiveAudioRetentionDays as effectiveAudioRetentionDaysRule,@@ -151,10 +152,35 @@ function applyPolicySnapshot(result: PolicyIpcSnapshot, appVersion: string | nulreturn true;}+function applyPolicyFailure(result: PolicyIpcSnapshot): boolean {+ const current = usePolicyStore.getState();+ if (+ result.code !== "POLICY_UNRESOLVABLE" ||+ !current.accountId ||+ current.authGeneration == null ||+ result.accountId !== current.accountId ||+ result.authGeneration !== current.authGeneration+ ) {+ return false;+ }+ if (current.status === "managed") return true;+ usePolicyStore.setState({+ status: "error",+ managed: false,+ policy: null,+ loaded: true,+ });+ return true;+}+function ensurePolicyLifecycleListeners(): void {if (lifecycleListenersReady) return;lifecycleListenersReady = true;window.electronAPI.onWorkspacePolicyChanged?.((snapshot) => {+ if (!snapshot.success) {+ applyPolicyFailure(snapshot);+ return;+ }void readAppVersion().then((appVersion) => applyPolicySnapshot(snapshot, appVersion));});const refreshResolvedPolicy = (): void => {@@ -224,14 +250,20 @@ export const usePolicyStore = create<PolicyState>()((set, get) => ({if (applyPolicySnapshot(result, appVersion)) return;throw new Error("Workspace policy response did not match the active credential");}- throw new Error(result?.error || "Workspace policy is unavailable");+ throw Object.assign(new Error(result?.error || "Workspace policy is unavailable"), {+ code: result?.code,+ });} catch (error) {if (sequence !== fetchSequence) return;logger.error("Failed to fetch workspace policy:", error);const current = get();+ const failureCode =+ error && typeof error === "object" && "code" in error && typeof error.code === "string"+ ? error.code+ : undefined;if (current.accountId === accountId &&- (current.status === "managed" || current.status === "unmanaged")+ shouldPreserveResolvedPolicyOnFailure(current.status, failureCode)) {set({ loaded: true });} else {diff --git a/src/types/electron.ts b/src/types/electron.tsindex c9bf77540..7cea63dbf 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -801,17 +801,29 @@ declare global {error?: string;}>;onWorkspacePolicyChanged?: (- callback: (snapshot: {- success: true;- status: "network" | "cached" | "current" | "unsupported";- revision: number;- accountId: string | null;- authGeneration: number;- managed: boolean;- policy: OrgPolicy | null;- policyUpdatedAt: string | null;- endpointSupported: boolean;- }) => void+ callback: (+ snapshot:+ | {+ success: true;+ status: "network" | "cached" | "current" | "unsupported";+ revision: number;+ accountId: string | null;+ authGeneration: number;+ managed: boolean;+ policy: OrgPolicy | null;+ policyUpdatedAt: string | null;+ endpointSupported: boolean;+ }+ | {+ success: false;+ status: "error";+ revision: number;+ accountId: string | null;+ authGeneration: number;+ code: "POLICY_UNRESOLVABLE";+ error: string;+ }+ ) => void) => () => void;getNoteRecordingConfig?: () => Promise<{@@ -1637,6 +1649,7 @@ declare global {customDictionary?: string[];customPrompt?: string;systemPrompt?: string;+ requestPurpose?: "agent";promptMode?: "cleanup";language?: string;locale?: string;diff --git a/src/utils/version.ts b/src/utils/version.tsindex 5d2d2d04a..d6ebdcae4 100644--- a/src/utils/version.ts+++ b/src/utils/version.ts@@ -8,11 +8,7 @@ function parseCanonicalAppVersion(value: unknown): AppVersionParts | null {const match = CANONICAL_APP_VERSION.exec(value);if (!match) return null;- const parts: AppVersionParts = [- Number(match[1]),- Number(match[2]),- Number(match[3]),- ];+ const parts: AppVersionParts = [Number(match[1]), Number(match[2]), Number(match[3])];return parts.every(Number.isSafeInteger) ? parts : null;}diff --git a/test/helpers/appVersion.test.js b/test/helpers/appVersion.test.jsindex 3cd65531b..ff6061cff 100644--- a/test/helpers/appVersion.test.js+++ b/test/helpers/appVersion.test.js@@ -1,19 +1,8 @@const test = require("node:test");const assert = require("node:assert/strict");-const fs = require("node:fs");-const path = require("node:path");const load = () => import("../../src/utils/version.ts");-test("keeps the renderer version utility browser-compatible", () => {- const source = fs.readFileSync(- path.join(__dirname, "../../src/utils/version.ts"),- "utf8",- );-- assert.doesNotMatch(source, /helpers\/appVersion\.js/);-});-test("recognizes only canonical three-part app versions", async () => {const { isCanonicalAppVersion } = await load();@@ -56,7 +45,7 @@ test("keeps renderer and main-process validation behavior aligned", async () =>assert.equal(isCanonicalAppVersion(version),mainVersion.isCanonicalAppVersion(version),- String(version),+ String(version));}});diff --git a/test/helpers/policyFailClosedTransition.test.js b/test/helpers/policyFailClosedTransition.test.jsnew file mode 100644index 000000000..0b8511fcf--- /dev/null+++ b/test/helpers/policyFailClosedTransition.test.js@@ -0,0 +1,109 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++test("renderer fails closed when a managed-unresolvable refresh supersedes unmanaged", async (t) => {+ const originalWindow = globalThis.window;+ let policyRequestCount = 0;+ let policyChanged;+ globalThis.window = {+ addEventListener() {},+ setInterval() {+ return 1;+ },+ electronAPI: {+ getAppVersion: async () => ({ version: "1.8.1" }),+ getWorkspacePolicy: async () => {+ policyRequestCount += 1;+ if (policyRequestCount === 1) {+ return {+ success: true,+ status: "network",+ revision: 1,+ accountId: "account-a",+ authGeneration: 1,+ managed: false,+ policy: null,+ policyUpdatedAt: null,+ endpointSupported: true,+ };+ }+ return {+ success: false,+ status: "error",+ code: "POLICY_UNRESOLVABLE",+ error: "Organization policy could not be resolved.",+ };+ },+ onWorkspacePolicyChanged(callback) {+ policyChanged = callback;+ },+ },+ };++ const { createServer } = await import("vite");+ const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-policy-transition-test-"));+ const vite = await createServer({+ root: path.resolve(__dirname, "../../src"),+ cacheDir,+ configFile: false,+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ plugins: [+ {+ name: "policy-transition-test-app-version",+ enforce: "pre",+ resolveId(source) {+ if (source.endsWith("/helpers/appVersion.js")) return "\0policy-transition-app-version";+ if (source.endsWith("/utils/logger")) return "\0policy-transition-logger";+ return null;+ },+ load(id) {+ if (id === "\0policy-transition-logger") {+ return "export default { error() {} };";+ }+ if (id !== "\0policy-transition-app-version") return null;+ return `+ export function parseCanonicalAppVersion(value) {+ const match = typeof value === "string" ? /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/.exec(value) : null;+ return match ? match.slice(1).map(Number) : null;+ }+ export function isCanonicalAppVersion(value) {+ return parseCanonicalAppVersion(value) !== null;+ }+ `;+ },+ },+ ],+ server: { middlewareMode: true },+ });+ t.after(async () => {+ await vite.close();+ fs.rmSync(cacheDir, { recursive: true, force: true });+ if (originalWindow === undefined) delete globalThis.window;+ else globalThis.window = originalWindow;+ });++ const { usePolicyStore } = await vite.ssrLoadModule("/stores/policyStore.ts");+ await usePolicyStore.getState().fetchPolicy("account-a", 1);+ assert.equal(usePolicyStore.getState().status, "unmanaged");++ policyChanged({+ success: false,+ status: "error",+ revision: 1,+ accountId: "account-a",+ authGeneration: 1,+ code: "POLICY_UNRESOLVABLE",+ error: "Organization policy could not be resolved.",+ });+ await Promise.resolve();+ assert.equal(usePolicyStore.getState().status, "error");++ await usePolicyStore.getState().fetchPolicy("account-a", 1);+ assert.equal(usePolicyStore.getState().status, "error");+ assert.equal(usePolicyStore.getState().loaded, true);+});diff --git a/test/helpers/policyLifecycle.test.js b/test/helpers/policyLifecycle.test.jsindex d0e1c1354..f386d814e 100644--- a/test/helpers/policyLifecycle.test.js+++ b/test/helpers/policyLifecycle.test.js@@ -38,3 +38,12 @@ test("selects only resolved policy identities for cadence and focus refresh", asnull);});++test("an unmanaged verdict is preserved for transient failures but not a managed-unresolvable signal", async () => {+ const { shouldPreserveResolvedPolicyOnFailure } = await load();++ assert.equal(shouldPreserveResolvedPolicyOnFailure("unmanaged", "POLICY_UNAVAILABLE"), true);+ assert.equal(shouldPreserveResolvedPolicyOnFailure("unmanaged", "POLICY_UNRESOLVABLE"), false);+ assert.equal(shouldPreserveResolvedPolicyOnFailure("managed", "POLICY_UNRESOLVABLE"), true);+ assert.equal(shouldPreserveResolvedPolicyOnFailure("error", "POLICY_UNRESOLVABLE"), false);+});diff --git a/test/helpers/workspacePolicyManager.test.js b/test/helpers/workspacePolicyManager.test.jsindex d374abec4..e6c421d33 100644--- a/test/helpers/workspacePolicyManager.test.js+++ b/test/helpers/workspacePolicyManager.test.js@@ -509,7 +509,7 @@ test("rejects an older policy response instead of downgrading main or cache statassert.equal(context.broadcasts.length, 1);});-test("invalid managed policy fails closed and is never broadcast", async (t) => {+test("invalid managed policy fails closed and broadcasts only the error state", async (t) => {const malformed = validPolicy();malformed.data.policy.version = 2;const context = setup(async () => response(200, malformed));@@ -520,8 +520,10 @@ test("invalid managed policy fails closed and is never broadcast", async (t) =>expectedAuthGeneration: 1,});assert.equal(result.success, false);- assert.equal(result.code, "POLICY_UNAVAILABLE");- assert.equal(context.broadcasts.length, 0);+ assert.equal(result.code, "POLICY_UNRESOLVABLE");+ assert.equal(context.broadcasts.length, 1);+ assert.equal(context.broadcasts[0].success, false);+ assert.equal(context.broadcasts[0].code, "POLICY_UNRESOLVABLE");});test("a first policy-enabled offline launch remains unavailable without a policy verdict", async (t) => {@@ -557,6 +559,106 @@ test("HTTP policy denials and malformed success payloads remain unavailable", as}});+test("a positive managed-unresolvable signal cannot reuse an unmanaged cache", async (t) => {+ for (const failedResponse of [+ response(503, {+ error: "Organization policy could not be resolved.",+ code: "POLICY_UNRESOLVABLE",+ }),+ response(200, { data: { managed: true, policy: null, policyUpdatedAt: null } }),+ ]) {+ const responses = [+ response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } }),+ failedResponse,+ ];+ const context = setup(async () => responses.shift());+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ const unmanaged = await context.manager.getPolicy(request);+ const transitioned = await context.manager.getPolicy(request);++ assert.equal(unmanaged.success, true);+ assert.equal(unmanaged.managed, false);+ assert.equal(transitioned.success, false);+ assert.equal(transitioned.status, "error");+ assert.equal(transitioned.code, "POLICY_UNRESOLVABLE");+ }+});++test("a managed cache remains fail-closed during an unresolvable refresh", async (t) => {+ const responses = [+ response(200, validPolicy()),+ response(503, {+ error: "Organization policy could not be resolved.",+ code: "POLICY_UNRESOLVABLE",+ }),+ ];+ const context = setup(async () => responses.shift());+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ const managed = await context.manager.getPolicy(request);+ const fallback = await context.manager.getPolicy(request);++ assert.equal(fallback.success, true);+ assert.equal(fallback.status, "cached");+ assert.equal(fallback.managed, true);+ assert.deepEqual(fallback.policy, managed.policy);+});++test("a managed-unresolvable signal survives throttling, other windows, and restart", async (t) => {+ let currentTime = 0;+ let requestCount = 0;+ const context = setup(+ async () => {+ requestCount += 1;+ if (requestCount === 1) {+ return response(200, { data: { managed: false, policy: null, policyUpdatedAt: null } });+ }+ return response(503, {+ error: "Organization policy could not be resolved.",+ code: "POLICY_UNRESOLVABLE",+ });+ },+ {+ now: () => currentTime,+ successfulRefreshMs: 0,+ minimumAttemptIntervalMs: 5_000,+ }+ );+ t.after(context.cleanup);+ const request = { accountId: "account-a", expectedAuthGeneration: 1 };++ assert.equal((await context.manager.getPolicy(request)).managed, false);+ currentTime = 5_000;+ const unresolvable = await context.manager.getPolicy(request);+ const throttledOtherWindow = await context.manager.getPolicy(request);++ assert.equal(unresolvable.success, false);+ assert.equal(unresolvable.code, "POLICY_UNRESOLVABLE");+ assert.equal(throttledOtherWindow.success, false);+ assert.equal(throttledOtherWindow.code, "POLICY_UNRESOLVABLE");+ assert.equal(requestCount, 2);+ assert.equal(context.broadcasts.at(-1).success, false);+ assert.equal(context.broadcasts.at(-1).code, "POLICY_UNRESOLVABLE");++ const restarted = createWorkspacePolicyManager({+ cachePath: context.cachePath,+ getApiUrl: () => "https://api.openwhispr.test",+ getAppVersion: () => "1.8.1",+ proxyFetch: async () => {+ throw new Error("offline");+ },+ tokenStore: { getState: () => ({ ...context.tokenState }) },+ logger: { error() {}, warn() {} },+ });+ const offlineRestart = await restarted.getPolicy(request);++ assert.equal(offlineRestart.success, false);+ assert.equal(offlineRestart.code, "POLICY_UNRESOLVABLE");+});+test("a corrupt policy cache cannot authorize an offline identity", async (t) => {const context = setup(async () => {throw new Error("offline");diff --git a/test/services/openwhisprReasonPurpose.test.js b/test/services/openwhisprReasonPurpose.test.jsnew file mode 100644index 000000000..4decb6364--- /dev/null+++ b/test/services/openwhisprReasonPurpose.test.js@@ -0,0 +1,88 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++test("OpenWhispr reasoning labels only dictation-agent requests for server enforcement", async (t) => {+ const originalWindow = globalThis.window;+ const requests = [];+ globalThis.window = {+ electronAPI: {+ cloudReason: async (_text, options) => {+ requests.push(options);+ return { success: true, text: "result", model: "model", provider: "openwhispr" };+ },+ },+ };++ const { createServer } = await import("vite");+ const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-reason-purpose-test-"));+ const vite = await createServer({+ root: path.resolve(__dirname, "../../src"),+ cacheDir,+ configFile: false,+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ plugins: [+ {+ name: "openwhispr-reason-purpose-dependencies",+ enforce: "pre",+ resolveId(source) {+ if (source.endsWith("/lib/auth")) return "\0reason-purpose-auth";+ if (source.endsWith("/stores/settingsStore")) return "\0reason-purpose-settings";+ if (source.endsWith("/utils/logger")) return "\0reason-purpose-logger";+ return null;+ },+ load(id) {+ if (id === "\0reason-purpose-auth") {+ return "export async function withSessionRefresh(callback) { return callback(); }";+ }+ if (id === "\0reason-purpose-settings") {+ return "export function getSettings() { return { customPrompts: { cleanup: '' } }; }";+ }+ if (id === "\0reason-purpose-logger") {+ return "export default { logReasoning() {} };";+ }+ return null;+ },+ },+ ],+ server: { middlewareMode: true },+ });+ t.after(async () => {+ await vite.close();+ fs.rmSync(cacheDir, { recursive: true, force: true });+ if (originalWindow === undefined) delete globalThis.window;+ else globalThis.window = originalWindow;+ });++ const { openwhisprProvider } = await vite.ssrLoadModule(+ "/services/ai/inferenceProviders/openwhispr.ts"+ );+ const context = {+ getCustomDictionary: () => [],+ getPreferredLanguage: () => "en",+ getUiLanguage: () => "en",+ };++ await openwhisprProvider.call({+ text: "do this",+ model: "",+ agentName: "Whisper",+ config: { systemPrompt: "Act on the request.", requiresAgent: true },+ ctx: context,+ });+ await openwhisprProvider.call({+ text: "clean this",+ model: "",+ agentName: "Whisper",+ config: {},+ ctx: context,+ });++ assert.equal(requests[0].requestPurpose, "agent");+ assert.equal(requests[1].requestPurpose, undefined);+ assert.equal(requests[1].promptMode, "cleanup");+});diff --git a/test/services/promptStudioAgentPurpose.test.js b/test/services/promptStudioAgentPurpose.test.jsnew file mode 100644index 000000000..7dd3bf45a--- /dev/null+++ b/test/services/promptStudioAgentPurpose.test.js@@ -0,0 +1,203 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++function findRunButton(node) {+ if (!node) return null;+ if (Array.isArray(node)) {+ for (const child of node) {+ const match = findRunButton(child);+ if (match) return match;+ }+ return null;+ }+ if (node.props?.className === "w-full" && typeof node.props.onClick === "function") return node;+ return findRunButton(node.props?.children);+}++test("Prompt Studio labels dictation-agent runs for policy enforcement", async (t) => {+ const calls = [];+ globalThis.__promptStudioReasoningCalls = calls;++ const { createServer } = await import("vite");+ const cacheDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-prompt-studio-test-"));+ const vite = await createServer({+ root: path.resolve(__dirname, "../../src"),+ cacheDir,+ configFile: false,+ appType: "custom",+ logLevel: "silent",+ optimizeDeps: { noDiscovery: true },+ ssr: { noExternal: true },+ plugins: [+ {+ name: "prompt-studio-agent-policy-dependencies",+ enforce: "pre",+ resolveId(source) {+ const modules = {+ react: "react",+ "react/jsx-dev-runtime": "jsx-runtime",+ "react/jsx-runtime": "jsx-runtime",+ "react-i18next": "i18n",+ "./button": "button",+ "./textarea": "textarea",+ "lucide-react": "icons",+ "./dialog": "dialog",+ };+ if (modules[source]) return `\0prompt-studio-${modules[source]}`;+ if (source.endsWith("/hooks/useDialogs")) return "\0prompt-studio-dialogs";+ if (source.endsWith("/utils/agentName")) return "\0prompt-studio-agent-name";+ if (source.endsWith("/services/ReasoningService")) return "\0prompt-studio-reasoning";+ if (source.endsWith("/models/ModelRegistry")) return "\0prompt-studio-models";+ if (source.endsWith("/utils/logger")) return "\0prompt-studio-logger";+ if (source.endsWith("/config/prompts")) return "\0prompt-studio-prompts";+ if (source.endsWith("/stores/settingsStore")) return "\0prompt-studio-settings";+ if (source.endsWith("/utils/languageSupport")) return "\0prompt-studio-language";+ if (source.endsWith("/utils/snippets")) return "\0prompt-studio-snippets";+ if (source.endsWith("/helpers/dictationAgentInference")) {+ return "\0prompt-studio-agent-inference";+ }+ return null;+ },+ load(id) {+ if (id === "\0prompt-studio-react") {+ return `+ let call = 0;+ export function useState(initial) {+ call += 1;+ const value = call === 1 ? "test" : typeof initial === "function" ? initial() : initial;+ return [value, () => {}];+ }+ `;+ }+ if (id === "\0prompt-studio-jsx-runtime") {+ return `+ export const Fragment = Symbol.for("prompt-studio-fragment");+ export function jsxDEV(type, props, key) { return { type, props, key }; }+ export const jsx = jsxDEV;+ export const jsxs = jsxDEV;+ `;+ }+ if (id === "\0prompt-studio-i18n") {+ return `export function useTranslation() { return { t: (key) => key }; }`;+ }+ if (id === "\0prompt-studio-button") return "export function Button() {}";+ if (id === "\0prompt-studio-textarea") return "export function Textarea() {}";+ if (id === "\0prompt-studio-icons") {+ return `+ export const Eye = () => null;+ export const Edit3 = () => null;+ export const Play = () => null;+ export const Save = () => null;+ export const RotateCcw = () => null;+ export const Copy = () => null;+ export const TestTube = () => null;+ export const AlertTriangle = () => null;+ export const Check = () => null;+ `;+ }+ if (id === "\0prompt-studio-dialog") return "export function AlertDialog() {}";+ if (id === "\0prompt-studio-dialogs") {+ return `+ export function useDialogs() {+ return {+ alertDialog: { open: false, title: "", description: "" },+ showAlertDialog() {},+ hideAlertDialog() {},+ };+ }+ `;+ }+ if (id === "\0prompt-studio-agent-name") {+ return `export function useAgentName() { return { agentName: "Whisper" }; }`;+ }+ if (id === "\0prompt-studio-reasoning") {+ return `+ export default {+ async processText(...args) {+ globalThis.__promptStudioReasoningCalls.push(args);+ return "result";+ },+ };+ `;+ }+ if (id === "\0prompt-studio-models") {+ return `export function getModelProvider() { return "openai"; }`;+ }+ if (id === "\0prompt-studio-logger") {+ return `export default { debug() {}, error() {} };`;+ }+ if (id === "\0prompt-studio-prompts") {+ return `+ export function getDefaultPromptText() { return "default prompt"; }+ export function resolvePrompt() { return "resolved agent prompt"; }+ `;+ }+ if (id === "\0prompt-studio-settings") {+ return `+ const state = {+ uiLanguage: "en",+ useCleanupModel: true,+ cleanupModel: "",+ useDictationAgent: true,+ dictationAgentProvider: "openwhispr",+ dictationAgentModel: "auto",+ useDictationTranslation: true,+ translationMode: "openwhispr",+ translationProvider: "openwhispr",+ translationModel: "auto",+ translationRemoteUrl: "",+ translationCloudBaseUrl: "",+ translationCustomApiKey: "",+ translationDisableThinking: false,+ translationTargetLanguage: "es",+ customPrompts: { cleanup: "", dictationAgent: "", translate: "" },+ preferredLanguage: "en",+ cleanupDisableThinking: false,+ setCustomPrompt() {},+ };+ export function useSettingsStore(selector) { return selector(state); }+ useSettingsStore.getState = () => state;+ export const selectIsCloudCleanupMode = () => true;+ export const selectIsCloudDictationAgentMode = () => true;+ export const selectIsCloudTranslationMode = () => true;+ `;+ }+ if (id === "\0prompt-studio-language") {+ return `export function getLanguageLabel(value) { return value; }`;+ }+ if (id === "\0prompt-studio-snippets") {+ return `export function getDictionaryHintWords() { return []; }`;+ }+ if (id === "\0prompt-studio-agent-inference") {+ return `+ export function resolveDictationAgentInference() {+ return { reachable: true, model: "auto", config: { provider: "openwhispr" } };+ }+ `;+ }+ return null;+ },+ },+ ],+ server: { middlewareMode: true },+ });++ t.after(async () => {+ await vite.close();+ fs.rmSync(cacheDir, { recursive: true, force: true });+ delete globalThis.__promptStudioReasoningCalls;+ });++ const { default: PromptStudio } = await vite.ssrLoadModule("/components/ui/PromptStudio.tsx");+ const rendered = PromptStudio({ kind: "dictationAgent" });+ const runButton = findRunButton(rendered);+ assert.ok(runButton, "expected the Prompt Studio test action to render");++ await runButton.props.onClick();++ assert.equal(calls.length, 1);+ assert.equal(calls[0][3].requiresAgent, true);+});