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

test(enterprise): harden managed pipe e2e

Louis Beaumont252464784b80
diff --git a/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
index 5494a4e9e..4b38d8b2d 100644
--- a/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
+++ b/apps/screenpipe-app-tauri/e2e/specs/zz-enterprise-license-prompt.spec.ts
@@ -7,6 +7,10 @@
// - a full-seat license must show a human-readable error instead of spinning,
// - retrying after seats are added must activate without a reload.
+import { readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { E2E_DATA_DIR } from '../helpers/app-launcher.js';
+import { saveScreenshot } from '../helpers/screenshot-utils.js';
import { openHomeWindow, waitForAppReady, t } from '../helpers/test-utils.js';
import {
closeWindow,
@@ -23,6 +27,94 @@ const POLICY_CACHE_KEY = 'enterprise-policy-cache';
const VALID_LICENSE = 'ENT-GWXX-RNUB-LW9F-3YA6';
const WRONG_LICENSE = 'ENT-WRNG-WRNG-WRNG-WRNG';
+const MANAGED_PIPE_NAME = 'e2e-managed-review';
+const MANAGED_PRESET_ID = 'e2e-org-private-ai';
+const LOCAL_API_PORT = Number(process.env.SCREENPIPE_PORT ?? '3030');
+const LOCAL_API_BASE = `http://127.0.0.1:${LOCAL_API_PORT}`;
+const LOCAL_API_AUTH_HEADERS: Record<string, string> = process.env.SCREENPIPE_API_KEY
+ ? { Authorization: `Bearer ${process.env.SCREENPIPE_API_KEY}` }
+ : {};
+const MANAGED_PIPE_SCHEDULE = 'at 2099-01-01T00:00:00Z';
+const MANAGED_PIPE_DIR = join(E2E_DATA_DIR, 'pipes', MANAGED_PIPE_NAME);
+const MANAGED_PIPE_PATH = join(MANAGED_PIPE_DIR, 'pipe.md');
+const EXPECTED_MANAGED_PIPE = `---
+schedule: "${MANAGED_PIPE_SCHEDULE}"
+enabled: true
+preset: ["${MANAGED_PRESET_ID}"]
+enterprise_managed: true
+timeout: 60
+---
+
+# enterprise-managed:v7
+
+Review repetitive work and report one traceable automation opportunity.`;
+
+const ACTIVATION_POLICY_MOCK = JSON.stringify({
+ acceptedLicenseKey: VALID_LICENSE,
+ policy: {
+ hiddenSections: [],
+ lockedSettings: {},
+ managedAiPreset: null,
+ managedPipes: [],
+ orgName: 'Bungalow',
+ syncStreams: {
+ frames: true,
+ audio: true,
+ ui_events: true,
+ memories: true,
+ snapshots: true,
+ frame_images: 'off',
+ },
+ },
+});
+
+const MANAGED_POLICY_MOCK = JSON.stringify({
+ acceptedLicenseKey: VALID_LICENSE,
+ policy: {
+ hiddenSections: [],
+ lockedSettings: {},
+ managedAiPreset: null,
+ aiPresetPolicy: {
+ version: 2,
+ allow_screenpipe_cloud: false,
+ allow_employee_custom_presets: false,
+ lock_default_preset: true,
+ default_preset_id: MANAGED_PRESET_ID,
+ managed_presets: [
+ {
+ id: MANAGED_PRESET_ID,
+ provider: 'native-ollama',
+ url: 'http://127.0.0.1:11434',
+ model: 'e2e-org-model',
+ api_key: '',
+ },
+ ],
+ },
+ managedPipes: [
+ {
+ name: MANAGED_PIPE_NAME,
+ display_name: 'E2E managed review',
+ prompt_body: 'Review repetitive work and report one traceable automation opportunity.',
+ schedule: MANAGED_PIPE_SCHEDULE,
+ model: null,
+ provider: null,
+ preset: MANAGED_PRESET_ID,
+ timeout: 60,
+ enabled: true,
+ version: 7,
+ },
+ ],
+ orgName: 'Bungalow',
+ syncStreams: {
+ frames: true,
+ audio: true,
+ ui_events: true,
+ memories: true,
+ snapshots: true,
+ frame_images: 'off',
+ },
+ },
+});
async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void> {
await browser.execute(
@@ -32,34 +124,14 @@ async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void>
heartbeatStatusKey: string,
skipSavedLicenseKey: string,
policyCacheKey: string,
- validLicense: string,
+ policyMock: string,
status: number,
) => {
window.localStorage.setItem(forceEnterpriseBuildKey, '1');
window.localStorage.setItem(skipSavedLicenseKey, '1');
window.localStorage.removeItem(policyCacheKey);
window.localStorage.setItem(heartbeatStatusKey, String(status));
- window.localStorage.setItem(
- policyKey,
- JSON.stringify({
- acceptedLicenseKey: validLicense,
- policy: {
- hiddenSections: [],
- lockedSettings: {},
- managedAiPreset: null,
- managedPipes: [],
- orgName: 'Bungalow',
- syncStreams: {
- frames: true,
- audio: true,
- ui_events: true,
- memories: true,
- snapshots: true,
- frame_images: 'off',
- },
- },
- }),
- );
+ window.localStorage.setItem(policyKey, policyMock);
window.location.reload();
},
FORCE_ENTERPRISE_BUILD_KEY,
@@ -67,7 +139,7 @@ async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void>
HEARTBEAT_STATUS_KEY,
SKIP_SAVED_LICENSE_KEY,
POLICY_CACHE_KEY,
- VALID_LICENSE,
+ ACTIVATION_POLICY_MOCK,
heartbeatStatus,
);
@@ -79,6 +151,72 @@ async function configureEnterpriseMocks(heartbeatStatus: number): Promise<void>
await browser.switchToWindow('onboarding');
}
+async function configureManagedHomeMocks(): Promise<void> {
+ await browser.switchToWindow('home').catch(() => {});
+ await invokeOrThrow('save_enterprise_license_key', { licenseKey: VALID_LICENSE });
+ await browser.execute(
+ (
+ forceEnterpriseBuildKey: string,
+ policyKey: string,
+ heartbeatStatusKey: string,
+ skipSavedLicenseKey: string,
+ policyCacheKey: string,
+ policyMock: string,
+ ) => {
+ window.localStorage.setItem(forceEnterpriseBuildKey, '1');
+ window.localStorage.removeItem(skipSavedLicenseKey);
+ window.localStorage.removeItem(policyCacheKey);
+ window.localStorage.setItem(heartbeatStatusKey, '200');
+ window.localStorage.setItem(policyKey, policyMock);
+ window.location.reload();
+ },
+ FORCE_ENTERPRISE_BUILD_KEY,
+ POLICY_KEY,
+ HEARTBEAT_STATUS_KEY,
+ SKIP_SAVED_LICENSE_KEY,
+ POLICY_CACHE_KEY,
+ MANAGED_POLICY_MOCK,
+ );
+ await browser.pause(t(2500));
+ await browser.switchToWindow('home');
+}
+
+async function openHomeReliably(): Promise<void> {
+ let lastError: unknown;
+ for (let attempt = 0; attempt < 3; attempt += 1) {
+ try {
+ await openHomeWindow();
+ return;
+ } catch (error) {
+ lastError = error;
+ await browser.pause(t(3000));
+ }
+ }
+ throw lastError;
+}
+
+async function ensureLocalApi(): Promise<void> {
+ const healthy = async () => {
+ try {
+ const response = await fetch(`${LOCAL_API_BASE}/health`, {
+ headers: LOCAL_API_AUTH_HEADERS,
+ });
+ return response.ok;
+ } catch {
+ return false;
+ }
+ };
+
+ if (await healthy()) return;
+ await browser.switchToWindow('home').catch(() => {});
+ await invokeOrThrow('spawn_screenpipe', { overrideArgs: null });
+ await browser.waitUntil(healthy, {
+ timeout: t(45_000),
+ interval: 500,
+ timeoutMsg: `local API did not recover on port ${LOCAL_API_PORT}`,
+ });
+}
+
async function setHeartbeatStatus(status: number): Promise<void> {
await browser.execute(
(key: string, value: number) => window.localStorage.setItem(key, String(value)),
@@ -108,6 +246,61 @@ async function clearEnterpriseMocks(): Promise<void> {
await browser.pause(t(2000));
await closeWindow('Onboarding').catch(() => {});
+
+ rmSync(MANAGED_PIPE_DIR, { recursive: true, force: true });
+ await fetch(`${LOCAL_API_BASE}/pipes`, { headers: LOCAL_API_AUTH_HEADERS }).catch(() => {});
+}
+
+async function getManagedPipe(): Promise<any> {
+ const response = await fetch(
+ `${LOCAL_API_BASE}/pipes/${encodeURIComponent(MANAGED_PIPE_NAME)}`,
+ { headers: LOCAL_API_AUTH_HEADERS },
+ );
+ return (await response.json()).data;
+}
+
+async function waitForManagedPipe(): Promise<any> {
+ await ensureLocalApi();
+ await browser.waitUntil(
+ async () => {
+ try {
+ const pipe = await getManagedPipe();
+ return (
+ pipe?.config?.enterprise_managed === true &&
+ pipe?.config?.enabled === true &&
+ pipe?.config?.schedule === MANAGED_PIPE_SCHEDULE &&
+ pipe?.config?.preset?.[0] === MANAGED_PRESET_ID
+ );
+ } catch {
+ return false;
+ }
+ },
+ {
+ timeout: t(20_000),
+ interval: 250,
+ timeoutMsg: 'enterprise managed pipe did not reach the local engine',
+ },
+ );
+ return await getManagedPipe();
+}
+
+async function openManagedPipesPage(): Promise<void> {
+ await browser.switchToWindow('home').catch(() => {});
+ await openHomeWindow();
+
+ const navPipes = await $('[data-testid="nav-pipes"]');
+ await navPipes.waitForExist({ timeout: t(10_000) });
+ await navPipes.click();
+
+ const section = await $('[data-testid="section-pipes"]');
+ try {
+ await section.waitForExist({ timeout: t(15_000) });
+ } catch {
+ await browser.execute(() => {
+ window.location.href = '/home?section=pipes&tab=my-pipes';
+ });
+ await section.waitForExist({ timeout: t(15_000) });
+ }
}
async function waitForBodyText(text: string): Promise<void> {
@@ -151,6 +344,74 @@ async function submitLicense(value: string): Promise<void> {
await button.click();
}
+describe('Enterprise managed pipe enforcement', () => {
+ before(async () => {
+ await waitForAppReady();
+ await openHomeReliably();
+ await configureManagedHomeMocks();
+ });
+
+ after(async () => {
+ await clearEnterpriseMocks();
+ });
+
+ it('installs the managed pipe, locks its UI, and rejects local API mutations', async () => {
+ const installed = await waitForManagedPipe();
+ expect(installed.config.enterprise_managed).toBe(true);
+ expect(installed.config.preset).toEqual([MANAGED_PRESET_ID]);
+ expect(readFileSync(MANAGED_PIPE_PATH, 'utf8')).toBe(EXPECTED_MANAGED_PIPE);
+
+ await openManagedPipesPage();
+
+ const row = await $(`[data-pipe-row="${MANAGED_PIPE_NAME}"]`);
+ await row.waitForExist({ timeout: t(15_000) });
+ expect((await row.getText()).toLowerCase()).toContain('managed');
+
+ const enabledSwitch = await row.$('[role="switch"]');
+ await enabledSwitch.waitForExist({ timeout: t(5_000) });
+ expect(await enabledSwitch.isEnabled()).toBe(false);
+
+ await row.$('[role="button"]').click();
+ await browser.waitUntil(
+ async () => (await row.getText()).toLowerCase().includes('managed by your organization'),
+ {
+ timeout: t(10_000),
+ interval: 250,
+ timeoutMsg: 'managed pipe read-only explanation did not render',
+ },
+ );
+ await saveScreenshot('enterprise-managed-pipe-locked');
+
+ const pipeUrl = `${LOCAL_API_BASE}/pipes/${encodeURIComponent(MANAGED_PIPE_NAME)}`;
+ const disable = await fetch(`${pipeUrl}/enable`, {
+ method: 'POST',
+ headers: { ...LOCAL_API_AUTH_HEADERS, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enabled: false }),
+ }).then((response) => response.json());
+ expect(disable.error).toContain('managed by your organization');
+
+ const editResponse = await fetch(`${pipeUrl}/config`, {
+ method: 'POST',
+ headers: { ...LOCAL_API_AUTH_HEADERS, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ config: { schedule: 'daily' } }),
+ });
+ expect(editResponse.status).toBe(400);
+ expect((await editResponse.json()).error).toContain('managed by your organization');
+
+ const remove = await fetch(pipeUrl, {
+ method: 'DELETE',
+ headers: LOCAL_API_AUTH_HEADERS,
+ }).then((response) => response.json());
+ expect(remove.error).toContain('managed by your organization');
+
+ const afterMutations = await getManagedPipe();
+ expect(afterMutations.config.enabled).toBe(true);
+ expect(afterMutations.config.schedule).toBe(MANAGED_PIPE_SCHEDULE);
+ expect(afterMutations.config.preset).toEqual([MANAGED_PRESET_ID]);
+ expect(readFileSync(MANAGED_PIPE_PATH, 'utf8')).toBe(EXPECTED_MANAGED_PIPE);
+ });
+});
+
describe('Enterprise onboarding activation', () => {
before(async () => {
await waitForAppReady();
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-pipes.ts b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-pipes.ts
index 2087c2432..eec87a846 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-pipes.ts
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-enterprise-pipes.ts
@@ -19,6 +19,7 @@ import {
} from "@tauri-apps/plugin-fs";
import { homeDir, join } from "@tauri-apps/api/path";
import { localFetch } from "@/lib/api";
+import { commands } from "@/lib/utils/tauri";
export interface ManagedPipe {
name: string;
@@ -47,6 +48,26 @@ export interface PipeStatus {
const MARKER_PREFIX = "# enterprise-managed:v";
+async function enterprisePipesDir(): Promise<string> {
+ try {
+ const result = await commands.getActiveDataDir();
+ if (result.status === "ok") {
+ return await join(result.data, "pipes");
+ }
+ console.warn(
+ "[enterprise-pipes] failed to resolve active data dir, using ~/.screenpipe:",
+ result.error,
+ );
+ } catch (error) {
+ console.warn(
+ "[enterprise-pipes] active data dir command unavailable, using ~/.screenpipe:",
+ error,
+ );
+ }
+
+ return await join(await homeDir(), ".screenpipe", "pipes");
+}
+
export function buildEnterpriseManagedPipeMd(pipe: ManagedPipe): string {
const frontmatter = [
"---",
@@ -89,8 +110,7 @@ export async function syncManagedPipes(
const pipesToSync = managedPipes || [];
try {
- const home = await homeDir();
- const pipesDir = await join(home, ".screenpipe", "pipes");
+ const pipesDir = await enterprisePipesDir();
for (const pipe of pipesToSync) {
try {
@@ -184,8 +204,7 @@ export async function gatherPipeStatuses(): Promise<PipeStatus[]> {
const statuses: PipeStatus[] = [];
try {
- const home = await homeDir();
- const pipesDir = await join(home, ".screenpipe", "pipes");
+ const pipesDir = await enterprisePipesDir();
// Fetch all pipe statuses from local API
const res = await localFetch("/pipes", {
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index 28b3c421e..a446d0a1e 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -540,6 +540,19 @@ async forceRegenerateSuggestions() : Promise<Result<CachedSuggestions, string>>
else return { status: "error", error: e as any };
}
},
+/**
+ * Absolute path of the data directory used by the running engine. This is
+ * distinct from the app base directory when the user selected a custom
+ * `dataDir`, and it also honors `SCREENPIPE_DATA_DIR` in isolated E2E runs.
+ */
+async getActiveDataDir() : Promise<Result<string, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("get_active_data_dir") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
/**
* Return the macOS bundle identifier of the running app
* (e.g. `screenpi.pe`, `screenpi.pe.beta`, `screenpi.pe.dev`,
@@ -1492,7 +1505,7 @@ async piRequestState(sessionId: string) : Promise<Result<null, string>> {
},
/**
* Hot-swap Pi's active model without killing the subprocess. Preserves the
- * full conversation state in-place — the user can switch Luna ↔ Sonnet ↔ Opus
+ * full conversation state in-place — the user can switch haiku ↔ sonnet ↔ opus
* mid-session and the new model sees the real threaded history, not a
* glued-transcript workaround.
*
@@ -2071,7 +2084,7 @@ async setCloudMediaAnalysisSkill(enabled: boolean) : Promise<Result<null, string
* `Server.cloud_token` and `PiExecutor.user_token` captured at engine
* boot would be permanent for the lifetime of the sidecar process —
* users who signed in AFTER the engine started would stay on the
- * gateway's anonymous tier (allowed_models = Auto/Luna only) on
+ * gateway's anonymous tier (allowed_models = haiku/gemini only) on
* every pipe run, surfacing as `403 "model_not_allowed"` for any
* Sonnet/Opus preset even with an active Pro subscription. Logout +
* log-in from the webview alone does NOT restart the sidecar, which
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
index 27b5b6840..4db4fe89c 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/log_files.rs
@@ -29,6 +29,17 @@ pub async fn get_log_files(app: AppHandle) -> Result<Vec<LogFile>, String> {
Ok(collect_log_files(&[data_dir, screenpipe_data_dir]).await)
}
+/// Absolute path of the data directory used by the running engine. This is
+/// distinct from the app base directory when the user selected a custom
+/// `dataDir`, and it also honors `SCREENPIPE_DATA_DIR` in isolated E2E runs.
+#[tauri::command]
+#[specta::specta]
+pub async fn get_active_data_dir(app: AppHandle) -> Result<String, String> {
+ get_data_dir(&app)
+ .map(|path| path.to_string_lossy().into_owned())
+ .map_err(|error| error.to_string())
+}
+
/// Gather `.log` files from the given directories, newest first.
///
/// Resilience is the whole point of this helper: a directory that can't be read
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index cdfccc8ab..adc7fdb30 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -71,6 +71,12 @@ fn build_config(app: &tauri::AppHandle) -> Result<RecordingConfig, String> {
Ok(store.to_recording_config(data_dir))
}
+fn configured_local_api_port(app: &tauri::AppHandle) -> u16 {
+ build_config(app)
+ .map(|config| config.port)
+ .unwrap_or(DEFAULT_LOCAL_API_PORT)
+}
+
fn recording_access_policy(
is_enterprise_build: bool,
dev_bypass: bool,
@@ -770,11 +776,7 @@ async fn spawn_screenpipe_inner(
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(remaining + 1)).await;
info!("Cooldown expired, checking if server needs restart");
- let port = SettingsStore::get(&app_handle)
- .ok()
- .flatten()
- .map(|s| s.recording.port)
- .unwrap_or(3030);
+ let port = configured_local_api_port(&app_handle);
if let Ok(resp) = reqwest::Client::new()
.get(format!("http://localhost:{}/health", port))
.timeout(std::time::Duration::from_secs(2))
@@ -809,7 +811,10 @@ async fn spawn_screenpipe_inner(
state.is_starting_capture.store(false, Ordering::SeqCst);
return Err(err);
}
- let port = store.recording.port;
+ // `to_recording_config` applies SCREENPIPE_PORT for isolated dev/E2E
+ // instances. Lifecycle health checks and orphan cleanup must use that
+ // same effective port or a restart can kill an unrelated app on :3030.
+ let port = configured_local_api_port(&app);
let health_url = format!("http://localhost:{}/health", port);
// --- Race prevention ---