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): keep the request deadline running while the body is read (#2839)

Chad Piha4c648dd5d831
diff --git a/src/helpers/enterpriseIdentityManager.js b/src/helpers/enterpriseIdentityManager.js
index 33a7e685c..46b8cfcb8 100644
--- a/src/helpers/enterpriseIdentityManager.js
+++ b/src/helpers/enterpriseIdentityManager.js
@@ -222,11 +222,22 @@ function createEnterpriseIdentityManager({
};
}
- async function fetchWithTimeout(url, init) {
+ // The deadline covers the body as well as the headers: a server that sends
+ // headers and then stalls would otherwise hang the shared config and
+ // credential requests that every later caller joins.
+ async function fetchWithTimeout(url, init, read) {
const controller = new AbortController();
+ const aborted = new Promise((_, reject) => {
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), {
+ once: true,
+ });
+ });
const timeout = setTimeout(() => controller.abort(), requestTimeoutMs);
try {
- return await proxyFetch(url, { ...init, signal: controller.signal });
+ return await Promise.race([
+ proxyFetch(url, { ...init, signal: controller.signal }).then(read),
+ aborted,
+ ]);
} finally {
clearTimeout(timeout);
}
@@ -245,28 +256,40 @@ function createEnterpriseIdentityManager({
const url = `${identity.apiUrl}/api/workspaces/${encodeURIComponent(
identity.workspaceId
)}/enterprise-providers`;
- const response = await fetchWithTimeout(url, {
- method: "GET",
- headers: requestHeaders(identity),
+ let responseError;
+ const body = await fetchWithTimeout(
+ url,
+ { method: "GET", headers: requestHeaders(identity) },
+ async (response) => {
+ assertIdentityCurrent(identity);
+ if (!response.ok) {
+ responseError = Object.assign(
+ new Error(`Managed enterprise API error: ${response.status}`),
+ {
+ code: response.status === 401 ? "AUTH_EXPIRED" : "MANAGED_CONFIG_FAILED",
+ status: response.status,
+ }
+ );
+ const detail = await readError(response, responseError.message);
+ responseError.message = detail.message;
+ responseError.code = detail.code || responseError.code;
+ throw responseError;
+ }
+ try {
+ return await response.json();
+ } catch (cause) {
+ const error = new Error("Managed enterprise configuration response is malformed", {
+ cause,
+ });
+ error.code = "MANAGED_CONFIG_INVALID";
+ throw error;
+ }
+ }
+ ).catch((error) => {
+ // A stalled error body must not turn a known authorization failure into a timeout.
+ throw responseError || error;
});
assertIdentityCurrent(identity);
- if (!response.ok) {
- const detail = await readError(response, `Managed enterprise API error: ${response.status}`);
- const error = new Error(detail.message);
- error.code =
- detail.code || (response.status === 401 ? "AUTH_EXPIRED" : "MANAGED_CONFIG_FAILED");
- error.status = response.status;
- throw error;
- }
- let body;
- try {
- body = await response.json();
- } catch (cause) {
- const error = new Error("Managed enterprise configuration response is malformed", { cause });
- error.code = "MANAGED_CONFIG_INVALID";
- throw error;
- }
- assertIdentityCurrent(identity);
const config = validateManagedEnterpriseEnvelope(body?.data, identity.workspaceId);
if (!config) {
const error = new Error("Managed enterprise configuration is malformed");
@@ -365,18 +388,33 @@ function createEnterpriseIdentityManager({
const url = `${identity.apiUrl}/api/workspaces/${encodeURIComponent(
identity.workspaceId
)}/enterprise-providers/${provider}/assertion`;
- const response = await fetchWithTimeout(url, {
- method: "POST",
- headers: requestHeaders(identity, true),
- body: JSON.stringify(inferenceScope ? { inferenceScope } : {}),
- });
- assertIdentityCurrent(identity);
- if (!response.ok) {
- const detail = await readError(response, `Managed identity API error: ${response.status}`);
- const error = new Error(detail.message);
- error.code =
- detail.code || (response.status === 401 ? "AUTH_EXPIRED" : "IDENTITY_EXCHANGE_FAILED");
- error.status = response.status;
+ let responseError;
+ const body = await fetchWithTimeout(
+ url,
+ {
+ method: "POST",
+ headers: requestHeaders(identity, true),
+ body: JSON.stringify(inferenceScope ? { inferenceScope } : {}),
+ },
+ async (response) => {
+ assertIdentityCurrent(identity);
+ if (!response.ok) {
+ responseError = Object.assign(
+ new Error(`Managed identity API error: ${response.status}`),
+ {
+ code: response.status === 401 ? "AUTH_EXPIRED" : "IDENTITY_EXCHANGE_FAILED",
+ status: response.status,
+ }
+ );
+ const detail = await readError(response, responseError.message);
+ responseError.message = detail.message;
+ responseError.code = detail.code || responseError.code;
+ throw responseError;
+ }
+ return response.json();
+ }
+ ).catch((cause) => {
+ const error = responseError || cause;
if (isAuthorizationError(error)) {
const prior = configs.get(identity.cacheKey)?.config || cachedConfig(cachePath, identity);
error.enforcementRequired =
@@ -386,8 +424,7 @@ function createEnterpriseIdentityManager({
evictIdentity(identity, error.code, error.enforcementRequired, error.enforcedScopes);
}
throw error;
- }
- const body = await response.json();
+ });
if (typeof body?.data?.assertion !== "string") {
throw Object.assign(new Error("Managed identity assertion is malformed"), {
code: "IDENTITY_EXCHANGE_FAILED",
@@ -480,19 +517,26 @@ function createEnterpriseIdentityManager({
client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
client_assertion: assertion,
});
- const response = await fetchWithTimeout(tokenUrl, {
- method: "POST",
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
- body: body.toString(),
- });
- if (!response.ok) {
- const detail = await readError(
- response,
- `Microsoft identity error: ${response.status}`
- );
- throw Object.assign(new Error(detail.message), { code: "IDENTITY_EXCHANGE_FAILED" });
- }
- const token = await response.json();
+ const token = await fetchWithTimeout(
+ tokenUrl,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
+ body: body.toString(),
+ },
+ async (response) => {
+ if (!response.ok) {
+ const detail = await readError(
+ response,
+ `Microsoft identity error: ${response.status}`
+ );
+ throw Object.assign(new Error(detail.message), {
+ code: "IDENTITY_EXCHANGE_FAILED",
+ });
+ }
+ return response.json();
+ }
+ );
assertIdentityCurrent(identity);
if (typeof token?.access_token !== "string" || !Number.isFinite(token?.expires_in)) {
throw Object.assign(new Error("Microsoft identity response is malformed"), {
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index b4fdd133c..edcbe9d62 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -698,6 +698,10 @@ class ReasoningService extends BaseReasoningService {
model,
surface: "llm",
};
+ const timeoutError = () =>
+ route.kind === "self-hosted"
+ ? providerError(PROVIDER_ERROR_CODES.TIMEOUT, selfHostedErrorContext)
+ : new Error("Streaming request timed out");
let response: Response;
try {
response = await fetchWithParamFallback(
@@ -716,17 +720,24 @@ class ReasoningService extends BaseReasoningService {
clearTimeout(timeoutId);
if ((error as Error).name === "AbortError" && abortController.signal.aborted) {
if (!timeoutTriggered) return;
- throw route.kind === "self-hosted"
- ? providerError(PROVIDER_ERROR_CODES.TIMEOUT, selfHostedErrorContext)
- : new Error("Streaming request timed out");
+ throw timeoutError();
}
// A stopped LAN server rejects the fetch before any response.
throw route.kind === "self-hosted" ? asProviderError(error, selfHostedErrorContext) : error;
}
if (!response.ok) {
- clearTimeout(timeoutId);
- const errorText = await response.text();
+ // Keep the deadline running while the error body arrives, or a stalled body hangs.
+ let errorText: string;
+ try {
+ errorText = await response.text();
+ } catch (error) {
+ if (!abortController.signal.aborted) throw error;
+ if (!timeoutTriggered) return;
+ throw timeoutError();
+ } finally {
+ clearTimeout(timeoutId);
+ }
logger.logReasoning("AGENT_STREAM_ERROR", {
status: response.status,
body: redactProviderBody(errorText),
@@ -808,9 +819,7 @@ class ReasoningService extends BaseReasoningService {
} catch (error) {
if ((error as Error).name === "AbortError" && abortController.signal.aborted) {
if (!timeoutTriggered) return;
- throw route.kind === "self-hosted"
- ? providerError(PROVIDER_ERROR_CODES.TIMEOUT, selfHostedErrorContext)
- : new Error("Streaming request timed out");
+ throw timeoutError();
}
throw error;
} finally {
diff --git a/test/helpers/enterpriseIdentityManager.test.js b/test/helpers/enterpriseIdentityManager.test.js
index fe02dfb20..2554a6a3a 100644
--- a/test/helpers/enterpriseIdentityManager.test.js
+++ b/test/helpers/enterpriseIdentityManager.test.js
@@ -366,3 +366,223 @@ test("assertion requests carry the inference scope being exercised", async (t) =
await resolved.tokenProvider();
assert.deepEqual(bodies, [{ inferenceScope: "transcription" }]);
});
+
+function stalledBodyResponse(status = 200) {
+ return new Response(new ReadableStream({ start() {} }), {
+ status,
+ headers: { "Content-Type": "application/json" },
+ });
+}
+
+function settles(promise) {
+ const state = { settled: false };
+ promise.then(
+ () => (state.settled = true),
+ () => (state.settled = true)
+ );
+ return state;
+}
+
+const flush = () => new Promise((resolve) => setImmediate(resolve));
+
+test("a config body that stalls after headers times out and frees the shared request", async (t) => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-enterprise-stall-"));
+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let configCalls = 0;
+ const manager = createEnterpriseIdentityManager({
+ cachePath: path.join(tempDir, "cache.json"),
+ getApiUrl: () => "https://api.example.com",
+ getAppVersion: () => "1.10.0",
+ proxyFetch: async () => {
+ configCalls += 1;
+ return configCalls === 1 ? stalledBodyResponse() : jsonResponse({ data: managedConfig() });
+ },
+ tokenStore: { getState: () => ({ generation: 4, token: "openwhispr-session" }) },
+ });
+
+ const stalled = manager.getConfig(request());
+ const joined = manager.getConfig(request());
+ const state = settles(Promise.all([stalled, joined]));
+ await flush();
+ t.mock.timers.tick(9_999);
+ await flush();
+ assert.equal(state.settled, false);
+ t.mock.timers.tick(1);
+ await flush();
+ assert.equal(state.settled, true);
+ const [left, right] = await Promise.all([stalled, joined]);
+ assert.equal(left.success, false);
+ // A timeout is transient: it must not read as a malformed config or evict the identity.
+ assert.notEqual(left.code, "MANAGED_CONFIG_INVALID");
+ assert.equal(left.enforcementRequired, undefined);
+ assert.equal(right.success, false);
+
+ const retried = await manager.getConfig(request());
+ assert.equal(retried.success, true);
+ assert.equal(configCalls, 2);
+});
+
+for (const status of [401, 403]) {
+ test(`a cached config is evicted when a ${status} response body stalls`, async (t) => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-enterprise-stall-"));
+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const cachePath = path.join(tempDir, "cache.json");
+ const enforcedConfig = managedConfig();
+ enforcedConfig.providers[0].mode = "managed_required";
+ enforcedConfig.providers[0].allowManualSetup = false;
+ const snapshots = [];
+ let response = jsonResponse({ data: enforcedConfig });
+ let configCalls = 0;
+ const manager = createEnterpriseIdentityManager({
+ cachePath,
+ getApiUrl: () => "https://api.example.com",
+ getAppVersion: () => "1.10.0",
+ proxyFetch: async () => {
+ configCalls += 1;
+ return response;
+ },
+ tokenStore: { getState: () => ({ generation: 4, token: "openwhispr-session" }) },
+ broadcast: (snapshot) => snapshots.push(snapshot),
+ });
+ assert.equal((await manager.getConfig(request())).status, "network");
+
+ response = stalledBodyResponse(status);
+ const stalled = manager.getConfig(request({ forceRefresh: true }));
+ const joined = manager.getConfig(request({ forceRefresh: true }));
+ const state = settles(Promise.all([stalled, joined]));
+ await flush();
+ t.mock.timers.tick(9_999);
+ await flush();
+ assert.equal(state.settled, false);
+ t.mock.timers.tick(1);
+ await flush();
+ assert.equal(state.settled, true);
+ const [left, right] = await Promise.all([stalled, joined]);
+ const code = status === 401 ? "AUTH_EXPIRED" : "MANAGED_CONFIG_FAILED";
+ assert.equal(left.success, false);
+ assert.equal(left.code, code);
+ assert.equal(left.enforcementRequired, true);
+ assert.deepEqual(right, left);
+ assert.deepEqual(JSON.parse(fs.readFileSync(cachePath, "utf8")).entries, []);
+ assert.equal(snapshots.length, 2);
+ assert.equal(snapshots[1].config, null);
+ assert.equal(snapshots[1].code, code);
+ assert.equal(snapshots[1].enforcementRequired, true);
+ assert.equal(configCalls, 2);
+
+ response = jsonResponse({ data: enforcedConfig });
+ const retried = await manager.getConfig(request());
+ assert.equal(retried.success, true);
+ assert.equal(retried.status, "network");
+ assert.equal(configCalls, 3);
+ });
+}
+
+test("a stalled 401 assertion body preserves authorization errors and evicts the cached config", async (t) => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-enterprise-stall-"));
+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const cachePath = path.join(tempDir, "cache.json");
+ const enforcedConfig = managedConfig();
+ enforcedConfig.providers[0].mode = "managed_required";
+ enforcedConfig.providers[0].allowManualSetup = false;
+ const snapshots = [];
+ let configCalls = 0;
+ let assertionCalls = 0;
+ const manager = createEnterpriseIdentityManager({
+ cachePath,
+ getApiUrl: () => "https://api.example.com",
+ getAppVersion: () => "1.10.0",
+ proxyFetch: async (url) => {
+ if (url.includes("/enterprise-providers/azure/assertion")) {
+ assertionCalls += 1;
+ return assertionCalls === 1
+ ? stalledBodyResponse(401)
+ : jsonResponse({ data: { assertion: "signed" } });
+ }
+ if (url.startsWith("https://login.microsoftonline.com/")) {
+ return jsonResponse({ access_token: "entra", expires_in: 3600 });
+ }
+ configCalls += 1;
+ return jsonResponse({ data: enforcedConfig });
+ },
+ tokenStore: { getState: () => ({ generation: 4, token: "openwhispr-session" }) },
+ broadcast: (snapshot) => snapshots.push(snapshot),
+ });
+ const resolved = await manager.resolveProvider(request());
+
+ const stalled = resolved.tokenProvider();
+ const joined = resolved.tokenProvider();
+ const state = settles(Promise.allSettled([stalled, joined]));
+ await flush();
+ t.mock.timers.tick(9_999);
+ await flush();
+ assert.equal(state.settled, false);
+ t.mock.timers.tick(1);
+ await flush();
+ assert.equal(state.settled, true);
+ for (const pending of [stalled, joined]) {
+ await assert.rejects(pending, {
+ code: "AUTH_EXPIRED",
+ status: 401,
+ enforcementRequired: true,
+ enforcedScopes: Object.keys(enforcedConfig.providers[0].config.scopeDefaults),
+ });
+ }
+ assert.deepEqual(JSON.parse(fs.readFileSync(cachePath, "utf8")).entries, []);
+ assert.equal(snapshots.length, 2);
+ assert.equal(snapshots[1].config, null);
+ assert.equal(snapshots[1].code, "AUTH_EXPIRED");
+ assert.equal(snapshots[1].enforcementRequired, true);
+ assert.deepEqual(
+ snapshots[1].enforcedScopes,
+ Object.keys(enforcedConfig.providers[0].config.scopeDefaults)
+ );
+ assert.equal(assertionCalls, 1);
+
+ const retried = await manager.resolveProvider(request());
+ assert.equal(await retried.tokenProvider(), "entra");
+ assert.equal(configCalls, 2);
+ assert.equal(assertionCalls, 2);
+});
+
+test("an Azure token body that stalls after headers times out and frees the shared credential", async (t) => {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-enterprise-stall-"));
+ t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ let azureCalls = 0;
+ const manager = createEnterpriseIdentityManager({
+ cachePath: path.join(tempDir, "cache.json"),
+ getApiUrl: () => "https://api.example.com",
+ getAppVersion: () => "1.10.0",
+ proxyFetch: async (url) => {
+ if (url.includes("/enterprise-providers/azure/assertion")) {
+ return jsonResponse({ data: { assertion: "signed" } });
+ }
+ if (url.startsWith("https://login.microsoftonline.com/")) {
+ azureCalls += 1;
+ return azureCalls === 1
+ ? stalledBodyResponse()
+ : jsonResponse({ access_token: "entra", expires_in: 3600 });
+ }
+ return jsonResponse({ data: managedConfig() });
+ },
+ tokenStore: { getState: () => ({ generation: 4, token: "openwhispr-session" }) },
+ });
+ const resolved = await manager.resolveProvider(request());
+
+ const stalled = resolved.tokenProvider();
+ const joined = resolved.tokenProvider();
+ const state = settles(Promise.allSettled([stalled, joined]));
+ await flush();
+ t.mock.timers.tick(10_000);
+ await flush();
+ assert.equal(state.settled, true);
+ await assert.rejects(stalled, { name: "AbortError" });
+ await assert.rejects(joined, { name: "AbortError" });
+
+ assert.equal(await resolved.tokenProvider(), "entra");
+ assert.equal(azureCalls, 2);
+});
diff --git a/test/services/reasoningServiceStreamingTimeout.test.js b/test/services/reasoningServiceStreamingTimeout.test.js
index 5b1dcd855..a6493fdd0 100644
--- a/test/services/reasoningServiceStreamingTimeout.test.js
+++ b/test/services/reasoningServiceStreamingTimeout.test.js
@@ -6,7 +6,7 @@ const flush = () => new Promise((resolve) => setImmediate(resolve));
const contentEvent = (content) =>
`data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`;
-async function startStream(t, provider, { holdHeaders = false } = {}) {
+async function startStream(t, provider, { holdHeaders = false, status = 200 } = {}) {
// Restore real timers before Vite's server-close hook runs.
t.after(() => t.mock.timers.reset());
installBrowserGlobals(t, {
@@ -31,7 +31,10 @@ async function startStream(t, provider, { holdHeaders = false } = {}) {
controller = streamController;
},
});
- const response = new Response(body, { headers: { "content-type": "text/event-stream" } });
+ const response = new Response(body, {
+ status,
+ headers: { "content-type": "text/event-stream" },
+ });
t.mock.method(globalThis, "fetch", async (_url, init) => {
signal = init.signal;
const pendingHeaders = new Promise((resolve, reject) => {
@@ -181,3 +184,11 @@ test("cancelling a raw stream ends normally", async (t) => {
assert.equal((await stream.outcome).error, undefined);
assert.equal(stream.body.locked, false);
});
+
+test("an error response whose body stalls still times out", async (t) => {
+ const stream = await startStream(t, "local", { status: 500 });
+ t.mock.timers.tick(599_999);
+ assert.equal(stream.signal.aborted, false);
+ t.mock.timers.tick(1);
+ assert.equal((await stream.outcome).error.message, "Streaming request timed out");
+});