Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(enterprise): bound local policy waits during authentication (#7435)

Ezra Ellette6b48cdbc6bd4
diff --git a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx
index 13bf814a8..28087fca0 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-enterprise-policy.test.tsx
@@ -107,6 +107,7 @@ vi.mock("@/lib/hooks/use-enterprise-pipes", () => ({
}));
import { useEnterprisePolicyRuntime } from "@/lib/hooks/use-enterprise-policy";
+import { getStore } from "@/lib/hooks/use-settings";
import {
ManagedPolicyProvider,
useManagedPolicy,
@@ -215,6 +216,7 @@ async function renderEnterprisePolicy() {
describe("enterprise policy runtime manual activation", () => {
beforeEach(() => {
vi.clearAllMocks();
+ vi.mocked(getStore).mockResolvedValue(mocks.store as any);
vi.useRealTimers();
localStorage.clear();
mocks.webBaseOverride.value = null;
@@ -1000,6 +1002,66 @@ describe("enterprise policy runtime manual activation", () => {
expect(heartbeatCall?.[1]?.connectTimeout).toBe(10_000);
});
+ it.each(["store open", "settings read", "AI preset write", "AI preset save", "install metadata", "app update save"])(
+ "finishes enterprise verification when %s never returns",
+ async (stage) => {
+ vi.useFakeTimers();
+ const warning = vi.spyOn(console, "warn");
+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);
+ mockEnterpriseApi({});
+ const pending = new Promise<never>(() => {});
+ if (stage === "store open") vi.mocked(getStore).mockReturnValueOnce(pending);
+ if (stage === "settings read") mocks.store.get.mockReturnValueOnce(pending);
+ if (stage === "AI preset write") mocks.store.set.mockReturnValueOnce(pending);
+ if (stage === "AI preset save") mocks.store.save.mockReturnValueOnce(pending);
+ if (stage === "install metadata") {
+ mocks.commands.getEnterpriseInstallMetadata.mockReturnValueOnce(pending);
+ }
+ if (stage === "app update save") {
+ mocks.store.save.mockResolvedValueOnce(undefined).mockReturnValueOnce(pending);
+ }
+
+ const { result, unmount } = await renderEnterprisePolicy();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LOCAL_COMMAND_TIMEOUT_MS + 1);
+ });
+
+ expect(result.current.authenticationState).toBe("authenticated");
+ expect(mocks.commands.setEnterpriseRecordingAuthorized).toHaveBeenCalledWith(
+ true, "license_key", KEY,
+ );
+ expect(warning).toHaveBeenCalledWith(
+ expect.stringContaining("continuing credential verification"),
+ expect.objectContaining({ message: expect.stringContaining("timed out after 8000ms") }),
+ );
+ unmount();
+ warning.mockRestore();
+ },
+ );
+
+ it("does not apply a late metadata result over a newly selected account", async () => {
+ vi.useFakeTimers();
+ mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);
+ mockEnterpriseApi({});
+ let finish!: (metadata: any) => void;
+ mocks.commands.getEnterpriseInstallMetadata.mockReturnValueOnce(
+ new Promise((resolve) => { finish = resolve; }),
+ );
+ const { result, unmount } = await renderEnterprisePolicy();
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(LOCAL_COMMAND_TIMEOUT_MS + 1);
+ });
+ expect(result.current.authenticationState).toBe("authenticated");
+ mocks.settings.user = { token: "new-account-token" };
+ const writes = mocks.store.set.mock.calls.length;
+ await act(async () => {
+ finish({ install_source: "mdm", update_manager: "mdm", managed: true, detected_by: [] });
+ });
+ expect(mocks.store.set).toHaveBeenCalledTimes(writes);
+ expect(mocks.settings.user).toEqual({ token: "new-account-token" });
+ unmount();
+ });
+
it("gives up on a hung policy fetch instead of leaving the gate in checking", async () => {
vi.useFakeTimers();
mocks.commands.getEnterpriseLicenseKey.mockResolvedValue(KEY);
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
index 61e798d0f..8bdb0b23b 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-policy.ts
@@ -87,6 +87,8 @@ const ENTERPRISE_DEFAULT_HIDDEN = ["referral"];
// Re-fetch policy every 5 minutes so admin changes propagate without app restart
const POLL_INTERVAL_MS = 5 * 60 * 1000;
+// The HTTP deadline does not cover local settings or policy application.
+// Bound those waits too so they cannot strand authentication in "checking".
const LOCAL_POLICY_COMMAND_TIMEOUT_MS = 8_000;
// Native authorization verifies both policy and seat-bearing enrollment. Each
// control-plane request has a 9s native timeout, so leave enough room for the
@@ -262,9 +264,36 @@ function toLocalAiPreset(
};
}
+function readPolicySettings() {
+ return withTimeout(
+ "enterprise read policy settings",
+ (async () => {
+ const store = await getStore();
+ const settings = (await store.get<Record<string, unknown>>("settings")) || {};
+ return { store, settings };
+ })(),
+ LOCAL_POLICY_COMMAND_TIMEOUT_MS,
+ );
+}
+
+async function savePolicySettings(
+ store: Awaited<ReturnType<typeof getStore>>,
+ settings: Record<string, unknown>,
+) {
+ await withTimeout(
+ "enterprise write policy settings",
+ store.set("settings", settings),
+ LOCAL_POLICY_COMMAND_TIMEOUT_MS,
+ );
+ await withTimeout(
+ "enterprise save policy settings",
+ store.save(),
+ LOCAL_POLICY_COMMAND_TIMEOUT_MS,
+ );
+}
+
async function applyAiPresetPolicy(policy: EnterpriseAiPresetPolicy): Promise<void> {
- const store = await getStore();
- const settings = (await store.get<Record<string, unknown>>("settings")) || {};
+ const { store, settings } = await readPolicySettings();
const currentPresets = ((settings.aiPresets as any[]) || []).filter(
(preset) => !isEnterpriseManagedPreset(preset)
);
@@ -309,18 +338,22 @@ async function applyAiPresetPolicy(policy: EnterpriseAiPresetPolicy): Promise<vo
}));
}
- await store.set("settings", {
+ await savePolicySettings(store, {
...settings,
aiPresets: nextPresets,
enterpriseSuppressedAiPresets: nextSuppressedPresets,
});
- await store.save();
}
async function getEnterpriseInstallMetadata(): Promise<EnterpriseInstallMetadata> {
try {
- return await commands.getEnterpriseInstallMetadata();
- } catch {
+ return await withTimeout(
+ "enterprise getEnterpriseInstallMetadata",
+ commands.getEnterpriseInstallMetadata(),
+ LOCAL_POLICY_COMMAND_TIMEOUT_MS,
+ );
+ } catch (error) {
+ console.warn("[enterprise] install metadata unavailable; continuing credential verification:", error);
return {
install_source: "unknown",
update_manager: "unknown",
@@ -331,10 +364,9 @@ async function getEnterpriseInstallMetadata(): Promise<EnterpriseInstallMetadata
}
async function applyAppUpdatePolicy(policy: EnterpriseAppUpdatePolicy): Promise<EnterpriseInstallMetadata> {
- const store = await getStore();
- const settings = (await store.get<Record<string, unknown>>("settings")) || {};
+ const { store, settings } = await readPolicySettings();
const metadata = await getEnterpriseInstallMetadata();
- await store.set("settings", {
+ await savePolicySettings(store, {
...settings,
enterpriseAppUpdatePolicy: policy,
enterpriseInstallMetadata: metadata,
@@ -342,7 +374,6 @@ async function applyAppUpdatePolicy(policy: EnterpriseAppUpdatePolicy): Promise<
? settings.autoUpdate ?? policy.default_auto_update
: policy.default_auto_update,
});
- await store.save();
return metadata;
}
@@ -656,8 +687,7 @@ export function useEnterprisePolicyRuntime() {
credential.type === "account" ? credential.value : null;
let deploymentLicenseKey: string | null = null;
try {
- const store = await getStore();
- const settings = (await store.get<Record<string, unknown>>("settings")) || {};
+ const { settings } = await readPolicySettings();
deviceId = (settings.deviceId as string) || "unknown";
const user = settings.user as Record<string, unknown> | undefined;
const token = user?.token;
@@ -668,7 +698,12 @@ export function useEnterprisePolicyRuntime() {
) {
cloudToken = token;
}
- } catch {}
+ } catch (error) {
+ console.warn(
+ "[enterprise] policy settings unavailable; continuing credential verification:",
+ error,
+ );
+ }
// Fallback: read directly from ~/.screenpipe/auth.json when the
// in-memory store hasn't been hydrated yet (dev launches before
@@ -803,7 +838,7 @@ export function useEnterprisePolicyRuntime() {
`[enterprise] applied AI preset policy: cloud=${result.aiPresetPolicy.allow_screenpipe_cloud}, employee=${result.aiPresetPolicy.allow_employee_custom_presets}, managed=${result.aiPresetPolicy.managed_presets.length}`
);
} catch (e) {
- console.warn("[enterprise] failed to apply AI preset policy:", e);
+ console.warn("[enterprise] failed to apply AI preset policy; continuing credential verification:", e);
}
}
@@ -813,7 +848,7 @@ export function useEnterprisePolicyRuntime() {
`[enterprise] applied app update policy: mode=${result.appUpdatePolicy.mode}, manager=${metadata.update_manager}, managed=${metadata.managed}`
);
} catch (e) {
- console.warn("[enterprise] failed to apply app update policy:", e);
+ console.warn("[enterprise] failed to apply app update policy; continuing credential verification:", e);
}
// Recording settings are applied by the native policy watcher and
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
index aa33160c5..3514a598b 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/diagnostic_logs.rs
@@ -221,6 +221,37 @@ async fn build_bundle(files: &[LogFile]) -> String {
mod tests {
use super::*;
+ #[tokio::test]
+ async fn enterprise_access_timeout_survives_support_collection_and_rotation() {
+ let dir = tempfile::tempdir().unwrap();
+ let current = dir.path().join("screenpipe-app.2026-10-02.log");
+ let file = std::fs::File::create(&current).unwrap();
+ let subscriber = tracing_subscriber::fmt()
+ .with_ansi(false)
+ .with_writer(std::sync::Mutex::new(file))
+ .finish();
+ tracing::subscriber::with_default(subscriber, || {
+ crate::commands::write_browser_log(
+ "warn".into(),
+ "[enterprise] failed to apply AI preset policy; continuing credential verification: enterprise save policy settings timed out after 8000ms".into(),
+ );
+ tracing::info!("[email protected]");
+ });
+ tokio::fs::rename(&current, dir.path().join("screenpipe-app.2026-10-02.1.log"))
+ .await
+ .unwrap();
+ tokio::fs::write(&current, "INFO recorder restarted\n")
+ .await
+ .unwrap();
+ let report = collect_redacted_from_dirs(&[dir.path().to_path_buf()])
+ .await
+ .unwrap();
+ assert!(report.contains("enterprise save policy settings timed out after 8000ms"));
+ assert!(report.contains("continuing credential verification"));
+ assert!(report.contains("recorder restarted"));
+ assert!(!report.contains("[email protected]"));
+ }
+
#[cfg(feature = "enterprise-build")]
#[tokio::test]
async fn readable_screenshot_failure_survives_support_collection_and_redaction() {