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

feat(workflows): control automatic updates and recover schedule checks (#7269)

Louis Beaumont433df6a7e1de
diff --git a/.github/pr-assets/workflow-schedule-toggle/before.png b/.github/pr-assets/workflow-schedule-toggle/before.png
new file mode 100644
index 000000000..febd2017a
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/before.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/checking.png b/.github/pr-assets/workflow-schedule-toggle/checking.png
new file mode 100644
index 000000000..9af7f34ef
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/checking.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/compact.png b/.github/pr-assets/workflow-schedule-toggle/compact.png
new file mode 100644
index 000000000..61707addd
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/compact.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/enable-confirmation.png b/.github/pr-assets/workflow-schedule-toggle/enable-confirmation.png
new file mode 100644
index 000000000..9d0cfaff9
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/enable-confirmation.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/failure.png b/.github/pr-assets/workflow-schedule-toggle/failure.png
new file mode 100644
index 000000000..fbd564fcd
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/failure.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/keyboard.png b/.github/pr-assets/workflow-schedule-toggle/keyboard.png
new file mode 100644
index 000000000..fe6f04c63
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/keyboard.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/mixed.png b/.github/pr-assets/workflow-schedule-toggle/mixed.png
new file mode 100644
index 000000000..14df5673a
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/mixed.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/narrow.png b/.github/pr-assets/workflow-schedule-toggle/narrow.png
new file mode 100644
index 000000000..bbebc9386
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/narrow.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/off.png b/.github/pr-assets/workflow-schedule-toggle/off.png
new file mode 100644
index 000000000..948e411a2
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/off.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/on.png b/.github/pr-assets/workflow-schedule-toggle/on.png
new file mode 100644
index 000000000..f6ac8e26d
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/on.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/saving.png b/.github/pr-assets/workflow-schedule-toggle/saving.png
new file mode 100644
index 000000000..8b319371b
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/saving.png differ
diff --git a/.github/pr-assets/workflow-schedule-toggle/unavailable.png b/.github/pr-assets/workflow-schedule-toggle/unavailable.png
new file mode 100644
index 000000000..bf83cfcd6
Binary files /dev/null and b/.github/pr-assets/workflow-schedule-toggle/unavailable.png differ
diff --git a/apps/screenpipe-app-tauri/README.md b/apps/screenpipe-app-tauri/README.md
index fec4e397b..0c6ed79eb 100644
--- a/apps/screenpipe-app-tauri/README.md
+++ b/apps/screenpipe-app-tauri/README.md
@@ -50,6 +50,19 @@ SCREENPIPE_WEB_SCENARIO=empty bun run dev:web
SCREENPIPE_WEB_SCENARIO=backend-error bun run dev:web
```
+The Workflows mode includes a persisted, fictional schedule group for checking
+Automatic updates without running agents. Use `workflowScheduleState=saving`,
+`failure`, or `unavailable` in the URL for those states. With this mock server
+running, install the `apps/screenpipe-workflows-web` browser-test dependencies and
+run this from the repository root:
+
+```sh
+WORKFLOW_SCHEDULE_URL=http://127.0.0.1:1420 bun apps/screenpipe-workflows-web/scripts/eval-schedule-toggle.mjs
+```
+
+ The check exercises the real Chat/Workflows switcher, consent, persistence,
+keyboard control, partial-save recovery and narrow layouts with fictional data.
+
The default `ready` state also seeds a stateful Live View and canvas document.
Edits such as changing the time range or layout mode are preserved for the
current browser session, so Live View UI work does not need the Rust backend.
diff --git a/apps/screenpipe-app-tauri/app/dev/workflows-ux/page.tsx b/apps/screenpipe-app-tauri/app/dev/workflows-ux/page.tsx
index 8385b674e..192d5da31 100644
--- a/apps/screenpipe-app-tauri/app/dev/workflows-ux/page.tsx
+++ b/apps/screenpipe-app-tauri/app/dev/workflows-ux/page.tsx
@@ -7,12 +7,12 @@ import { WorkflowsApp, type WorkflowAnalysis, type WorkflowRunActivity, type Wor
import { createFixtureWorkflowsPlatform, fixtureWorkflowAnalysis } from "@screenpipe/workflows-ui/fixture";
import { FirstTaskChoice } from "@/components/workflows/first-task-choice";
import { WorkflowAccessNotice } from "@/components/workflows/workflow-access";
+import { fixtureWorkflowTasks } from "@/lib/dev/workflow-tasks-fixture";
import { WorkflowTasksPrompt } from "@/components/workflows/workflow-tasks-prompt";
import { ProductSwitcher } from "@/components/workflows/product-switcher";
import { useGT } from "gt-react";
-const previewTasks = { load: async () => ({ enabled: false, title: "Keep your workflows current", schedule: "every 24h" }), enable: async () => {} };
const fixture = createFixtureWorkflowsPlatform();
// Older saved workflows have image bytes but no visual-verification metadata.
const legacyAnalysis = structuredClone(fixtureWorkflowAnalysis);
@@ -60,10 +60,9 @@ export default function WorkflowUxPreview() {
<span className="text-muted-foreground">UX preview · fictional data</span>
<div className="flex gap-4"><button onClick={() => setScreen("no-changes")}>No changes</button><button onClick={() => setScreen("legacy")}>SOP screenshots</button><button onClick={() => setScreen("allowance")}>Low allowance</button><button onClick={() => setScreen("business")}>Business access</button><button onClick={() => setScreen("skill")}>Skill install result</button><button onClick={() => setScreen("tasks")}>Enable tasks</button><button onClick={() => setScreen("onboarding")}>First task</button><button onClick={() => setScreen("empty")}>New history</button><button onClick={() => setScreen("catalog")}>Existing history</button><button onClick={() => setScreen("processing")}>Processing preview</button></div>
</nav>
- <WorkflowTasksPrompt active={screen === "tasks"} tasks={previewTasks} />
<div style={{height:"calc(100vh - 40px)", overflow:"auto"}}>
{screen === "onboarding" ? <div className="flex min-h-full items-center"><FirstTaskChoice onComplete={async (mode) => { if(mode === "screenpipe") window.location.assign("/home?mode=screenpipe"); else setScreen("empty"); }} /></div>
- : <WorkflowsApp onAnalysisUnavailable={() => setAccessRequested(true)} analysisUnavailableReason={screen === "allowance" || screen === "business" ? "Workflow updates are paused" : undefined} key={screen} statusNotice={screen === "allowance" || screen === "business" ? <WorkflowAccessNotice open={accessRequested} onOpenChange={setAccessRequested} access={screen === "allowance" ? {state:"paused",resetAt:undefined,message:"Workflow updates are paused to preserve AI allowance for chat."} : {state:"upgrade",message:"Automatic workflow discovery is included with Business. Your saved workflows remain available."}} onRetry={() => {}} onAccount={() => {}} onUsage={() => {}} /> : undefined} platform={screen === "no-changes" ? unchangedFixture : screen === "legacy" ? legacyFixture : screen === "processing" ? processingFixture : screen === "skill" ? installedSkillFixture : fixture} storageKey={null} initialAnalysis={screen === "no-changes" ? unchangedAnalysis : screen === "legacy" ? legacyAnalysis : (screen === "catalog" || screen === "tasks" || screen === "skill" || screen === "processing" || screen === "allowance" || screen === "business") ? fixtureWorkflowAnalysis : null} navigationBrand={<ProductSwitcher mode="workflows" onChange={mode => {if(mode === "screenpipe") window.location.assign("/home?mode=screenpipe");}} />} />}
+ : <WorkflowsApp toolbarAccessory={screen === "tasks" ? <WorkflowTasksPrompt active tasks={fixtureWorkflowTasks} /> : undefined} onAnalysisUnavailable={() => setAccessRequested(true)} analysisUnavailableReason={screen === "allowance" || screen === "business" ? "Workflow updates are paused" : undefined} key={screen} statusNotice={screen === "allowance" || screen === "business" ? <WorkflowAccessNotice open={accessRequested} onOpenChange={setAccessRequested} access={screen === "allowance" ? {state:"paused",resetAt:undefined,message:"Workflow updates are paused to preserve AI allowance for chat."} : {state:"upgrade",message:"Automatic workflow discovery is included with Business. Your saved workflows remain available."}} onRetry={() => {}} onAccount={() => {}} onUsage={() => {}} /> : undefined} platform={screen === "no-changes" ? unchangedFixture : screen === "legacy" ? legacyFixture : screen === "processing" ? processingFixture : screen === "skill" ? installedSkillFixture : fixture} storageKey={null} initialAnalysis={screen === "no-changes" ? unchangedAnalysis : screen === "legacy" ? legacyAnalysis : (screen === "catalog" || screen === "tasks" || screen === "skill" || screen === "processing" || screen === "allowance" || screen === "business") ? fixtureWorkflowAnalysis : null} navigationBrand={<ProductSwitcher mode="workflows" onChange={mode => {if(mode === "screenpipe") window.location.assign("/home?mode=screenpipe");}} />} />}
</div>
</div>;
}
diff --git a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
index 8476da3bc..cfbdb2d3b 100644
--- a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
@@ -15,6 +15,8 @@ import { ProductSwitcher, type ProductMode } from "./product-switcher";
import { ComposerDictationControl } from "@/components/chat/standalone/composer-dictation-control";
import { usePlatform } from "@/lib/hooks/use-platform";
import { useWorkflowsRolloutEnabled } from "@/lib/workflows/rollout";
+import { WorkflowTasksPrompt } from "./workflow-tasks-prompt";
+import { fixtureWorkflowTasks } from "@/lib/dev/workflow-tasks-fixture";
import { WorkflowAccess } from "./workflow-access";
function WorkflowDictation(props: WorkflowComposerAccessoryProps) {
@@ -67,7 +69,7 @@ export function IntegratedWorkflows({ active, fullscreen = false, onModeChange,
/>}
<WorkflowsApp onAnalysisUnavailable={() => setAccessRequested(true)} analysisUnavailableReason={analysisUnavailableReason} composerAccessory={composerAccessory} fullscreen={fullscreen} onShareWorkflow={openShare} workflowAgentActions={workflowAgentActions} platform={platform} active={active} storageKey={null}
- statusNotice={platform.managesAnalysis ? <WorkflowAccess requested={accessRequested} onRequestChange={setAccessRequested} active={active} onAccessChange={setAnalysisUnavailableReason} /> : undefined}
+ toolbarAccessory={platform.managesAnalysis ? <WorkflowAccess requested={accessRequested} onRequestChange={setAccessRequested} active={active} onAccessChange={setAnalysisUnavailableReason} /> : process.env.NEXT_PUBLIC_SCREENPIPE_WEB_DEV === "mock" ? <WorkflowTasksPrompt active={active} tasks={fixtureWorkflowTasks} /> : undefined}
recordingStatus={recordingStatus} navigationFooter={navigationFooter}
navigationBrand={<ProductSwitcher mode="workflows" onChange={onModeChange} />} />
</TooltipProvider>
diff --git a/apps/screenpipe-app-tauri/components/workflows/rollout-sync.tsx b/apps/screenpipe-app-tauri/components/workflows/rollout-sync.tsx
index fb92a8461..3afb2bc6f 100644
--- a/apps/screenpipe-app-tauri/components/workflows/rollout-sync.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/rollout-sync.tsx
@@ -1,6 +1,7 @@
// screenpipe — AI that knows everything you've seen, said, or heard
// https://screenpipe.com
"use client";
+import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { useEffect } from "react";
import { useFeatureFlagEnabled } from "posthog-js/react";
import { syncWorkflowsRollout, WORKFLOWS_FLAG } from "@/lib/workflows/rollout";
@@ -8,6 +9,8 @@ import { syncWorkflowsRollout, WORKFLOWS_FLAG } from "@/lib/workflows/rollout";
// Unresolved flags are not revocations. Any mounted window with a resolved
// flag can restore the engine grant after a restart, including when home is closed.
export function WorkflowsRolloutSync() {
+ const { health, isServerDown } = useHealthCheck();
+ const backendReady = !!health && !isServerDown;
const enabled = useFeatureFlagEnabled(WORKFLOWS_FLAG);
useEffect(() => {
if (typeof enabled !== "boolean" || process.env.NEXT_PUBLIC_SCREENPIPE_WEB_DEV === "mock") return;
@@ -16,6 +19,6 @@ export function WorkflowsRolloutSync() {
sync();
const retry = setInterval(sync, 30_000);
return () => { clearInterval(retry); controller.abort(); };
- }, [enabled]);
+ }, [enabled, backendReady]);
return null;
}
diff --git a/apps/screenpipe-app-tauri/components/workflows/rollout.test.tsx b/apps/screenpipe-app-tauri/components/workflows/rollout.test.tsx
index ca1871a57..5ff74ed50 100644
--- a/apps/screenpipe-app-tauri/components/workflows/rollout.test.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/rollout.test.tsx
@@ -2,7 +2,8 @@
// https://screenpipe.com
import { act, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, expect, it, vi } from "vitest";
-const state = vi.hoisted(() => ({ flag: undefined as boolean | undefined, pathname: "/home", fetch: vi.fn() }));
+const state = vi.hoisted(() => ({ flag: undefined as boolean | undefined, pathname: "/home", fetch: vi.fn(), connected: false }));
+vi.mock("@/lib/hooks/use-health-check", () => ({ useHealthCheck: () => ({health: state.connected ? {status:"healthy"} : null, isServerDown: !state.connected}) }));
vi.mock("next/navigation", () => ({ usePathname: () => state.pathname }));
vi.mock("posthog-js/react", () => ({ useFeatureFlagEnabled: () => state.flag }));
vi.mock("posthog-js", () => ({ default: { isFeatureEnabled: () => state.flag } }));
@@ -11,7 +12,7 @@ import { ProductSwitcher } from "./product-switcher";
import { WorkflowsRolloutSync } from "./rollout-sync";
import { isWorkflowsRolloutEnabled } from "@/lib/workflows/rollout";
import { enableWorkflowTask, startWorkflowJob } from "@/lib/workflows/scheduled-discovery";
-beforeEach(() => { state.flag = undefined; state.pathname = "/home"; state.fetch.mockReset().mockResolvedValue(new Response("{}")); });
+beforeEach(() => { state.flag = undefined; state.connected = false; state.pathname = "/home"; state.fetch.mockReset().mockResolvedValue(new Response("{}")); });
it("fails closed until an explicit boolean true", () => {
for (const flag of [undefined, null, false, "true", "test", 1]) expect(isWorkflowsRolloutEnabled(flag)).toBe(false);
expect(isWorkflowsRolloutEnabled(true)).toBe(true);
@@ -95,3 +96,20 @@ it("reasserts resolved access after the engine restarts and stops on unmount", a
expect(state.fetch).toHaveBeenCalledTimes(2);
} finally { vi.useRealTimers(); }
});
+
+it("resynchronizes immediately when a slow backend becomes reachable", async () => {
+ state.flag = true;
+ state.fetch.mockRejectedValueOnce(new Error("connection refused"));
+ const view = render(<WorkflowsRolloutSync />);
+ await act(async () => {});
+ expect(state.fetch).toHaveBeenCalledTimes(1);
+ state.connected = true;
+ view.rerender(<WorkflowsRolloutSync />);
+ await waitFor(() => expect(state.fetch).toHaveBeenCalledTimes(2));
+ expect(JSON.parse(state.fetch.mock.calls[1][1].body)).toEqual({enabled:true});
+ state.flag = undefined;
+ view.rerender(<WorkflowsRolloutSync />);
+ state.connected = false; view.rerender(<WorkflowsRolloutSync />);
+ state.connected = true; view.rerender(<WorkflowsRolloutSync />);
+ expect(state.fetch).toHaveBeenCalledTimes(2);
+});
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
index bc0b882b9..33c2d35a5 100644
--- a/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
@@ -9,6 +9,7 @@ import { workflowAccess } from "@/lib/workflows/access";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { WorkflowTasksPrompt } from "./workflow-tasks-prompt";
+import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { useGT } from "gt-react";
import { useUiLocale } from "@/lib/i18n/provider";
@@ -16,6 +17,8 @@ import { useUiLocale } from "@/lib/i18n/provider";
export function WorkflowAccess({ active, requested = false, onRequestChange, onAccessChange }: { active: boolean; requested?: boolean; onRequestChange?: (open: boolean) => void; onAccessChange?: (reason: string | undefined) => void }) {
const query = useUsageStatusQuery(active);
+ const { health, isServerDown } = useHealthCheck();
+ const backendReady = !!health && !isServerDown;
const router = useRouter();
const [mode, setMode] = useState<"intelligent" | "private">("intelligent");
useEffect(() => {
@@ -28,9 +31,9 @@ export function WorkflowAccess({ active, requested = false, onRequestChange, onA
const reason = query.isLoading ? "Checking workflow access…" : access.state === "ready" ? undefined : access.message;
useEffect(() => { onAccessChange?.(reason); }, [onAccessChange, reason]);
useEffect(() => { if (requested && access.state === "ready") onRequestChange?.(false); }, [requested, access.state, onRequestChange]);
- if (!active || query.isLoading) return null;
- if (access.state === "ready") return <WorkflowTasksPrompt active={active} />;
- return <WorkflowAccessNotice open={requested} onOpenChange={onRequestChange} access={access} refreshing={query.isRefreshing} onRetry={() => void query.refresh()} onAccount={() => router.push("/settings?section=account")} onUsage={() => router.push("/settings?section=usage")} />;
+ if (!active) return null;
+ return <><WorkflowTasksPrompt active={active} backendReady={backendReady} canEnable={!query.isLoading && access.state === "ready"} onEnableUnavailable={() => onRequestChange?.(true)} />
+ <WorkflowAccessNotice open={requested} onOpenChange={onRequestChange} access={access} refreshing={query.isRefreshing} onRetry={() => void query.refresh()} onAccount={() => router.push("/settings?section=account")} onUsage={() => router.push("/settings?section=usage")} /></>;
}
export function WorkflowAccessNotice({ access, open = false, onOpenChange, refreshing = false, onRetry, onAccount, onUsage }: {
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.module.css b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.module.css
new file mode 100644
index 000000000..6ef6d1ed3
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.module.css
@@ -0,0 +1,10 @@
+/* screenpipe — AI that knows everything you've seen, said, or heard
+ * https://screenpipe.com */
+.control { --foreground: 80 4% 9%; --background: 60 9% 97%; --border: 70 10% 85%; --ring: 80 4% 9%; position: relative; flex: 0 0 auto; color: var(--ink, #171815); font: inherit; }
+.label { display: flex; align-items: center; gap: 10px; font-size: 13px; cursor: pointer; white-space: nowrap; }
+.status { position: absolute; top: calc(100% + 4px); right: 0; font-size: 11px; line-height: 1.3; color: var(--muted, #73766d); white-space: nowrap; }
+.status:empty { display: none; }
+.control:has(.retry) .status { right: 22px; white-space: nowrap; }
+.retry { position: absolute; right: 0; top: calc(100% + 2px); padding: 0; border: 0; background: transparent; color: inherit; cursor: pointer; }
+.retry:focus-visible { outline: 1px solid currentColor; outline-offset: 3px; }
+@media (max-width: 680px) { .label { gap: 6px; font-size: 12px; } }
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.test.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.test.tsx
index 2b176c1e8..eb1791edb 100644
--- a/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.test.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.test.tsx
@@ -2,114 +2,113 @@
// https://screenpipe.com
import React from "react";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WorkflowTasksPrompt } from "./workflow-tasks-prompt";
const f = vi.hoisted(() => ({ settings: {} as any, update: vi.fn() }));
vi.mock("@/lib/hooks/use-settings", () => ({ useSettings: () => ({ settings: f.settings, updateSettings: f.update }) }));
-vi.mock("./workflow-sharing-controls", () => ({ WorkflowSharingControls: ({ onDone }: { onDone: () => void }) => <div data-testid="sharing-controls"><button onClick={onDone}>Not now</button></div> }));
+vi.mock("./workflow-sharing-controls", () => ({ WorkflowSharingControls: ({ onDone }: { onDone: () => void }) => <button onClick={onDone}>Skip sharing</button> }));
beforeEach(() => {
- f.settings = { user: { id: "fixture-user" }, workflowSharing: null };
+ f.settings = { user: { id: "fixture-user" }, workflowSharingPromptSeen: { "fixture-user": "2026-09-23" } };
f.update.mockReset().mockImplementation(async patch => { f.settings = { ...f.settings, ...patch }; });
});
-
-const setup = { enabled: false, title: "Update my workflows", schedule: "every 24h" };
-function service(enabled = false) {
- return { load: vi.fn().mockResolvedValue({ ...setup, enabled }), enable: vi.fn().mockResolvedValue(undefined) };
+afterEach(() => vi.useRealTimers());
+function service(states = [false, false, false, false]) {
+ const value = () => ({ enabled: states.every(Boolean), title: "Keep your workflows current", schedule: "Hourly discovery", tasks: states.map((enabled, i) => ({ name: `task-${i}`, title: `Task ${i}`, enabled })) });
+ return {
+ load: vi.fn().mockImplementation(async () => value()),
+ enable: vi.fn().mockImplementation(async () => { states.fill(true); }),
+ disable: vi.fn().mockImplementation(async () => { states.fill(false); }),
+ };
}
-
-describe("workflow task opt-in", () => {
- it("does not check or enable while Chat is active", () => {
- const tasks = service();
- render(<WorkflowTasksPrompt active={false} tasks={tasks} />);
- expect(tasks.load).not.toHaveBeenCalled();
- expect(tasks.enable).not.toHaveBeenCalled();
+const toggle = () => screen.getByRole("switch", { name: "Automatic updates" });
+async function loaded() { await waitFor(() => expect(toggle()).toBeEnabled()); }
+async function enable() {
+ fireEvent.click(toggle());
+ fireEvent.click(await screen.findByRole("button", { name: "Enable automatic updates" }));
+}
+describe("workflow schedule control", () => {
+ it("does not load or mutate while Chat is active", () => {
+ const tasks = service(); render(<WorkflowTasksPrompt active={false} tasks={tasks} />);
+ expect(tasks.load).not.toHaveBeenCalled(); expect(tasks.enable).not.toHaveBeenCalled();
+ expect(screen.queryByRole("switch")).not.toBeInTheDocument();
});
- it("shows the task on entry, allows dismissal, and checks again on the next switch", async () => {
- const tasks = service();
- const view = render(<WorkflowTasksPrompt active tasks={tasks} />);
- expect(await screen.findByText(/every 24h/)).toBeVisible();
- fireEvent.click(screen.getByText("How daily updates work"));
- expect(screen.getByText(/Chat → Scheduled tasks/)).toBeVisible();
- fireEvent.click(screen.getByRole("button", { name: "Not now" }));
- expect(screen.getByTestId("sharing-controls")).toBeVisible();
- expect(tasks.enable).not.toHaveBeenCalled();
- fireEvent.click(screen.getByRole("button", { name: "Not now" }));
- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
- await waitFor(() => expect(f.settings.workflowSharingPromptSeen).toEqual({ "fixture-user": "2026-09-23" }));
- view.rerender(<WorkflowTasksPrompt active={false} tasks={tasks} />);
- view.rerender(<WorkflowTasksPrompt active tasks={tasks} />);
- expect(await screen.findByRole("dialog")).toBeVisible();
- fireEvent.click(screen.getByRole("button", { name: "Not now" }));
+ it.each([[true,true,true,true], [true,true,false,true], [false,false,false,false]])("reflects the persisted group %j", async (...states) => {
+ const tasks = service(states as boolean[]); render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded();
+ expect(toggle()).toHaveAttribute("aria-checked", String(states.every(Boolean)));
+ expect(tasks.enable).not.toHaveBeenCalled(); expect(tasks.disable).not.toHaveBeenCalled();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
- it("offers the new consent without mutating an already enabled task", async () => {
- const tasks = service(true);
- render(<WorkflowTasksPrompt active tasks={tasks} />);
- await waitFor(() => expect(tasks.load).toHaveBeenCalledOnce());
- expect(await screen.findByTestId("sharing-controls")).toBeVisible();
- expect(tasks.enable).not.toHaveBeenCalled();
+ it("asks before enabling, saves every role, and reads back the result", async () => {
+ const tasks = service([true,false,true,true]); render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded();
+ expect(screen.getByRole("status")).toHaveTextContent("Some tasks are off");
+ await enable(); await waitFor(() => expect(toggle()).toBeChecked());
+ expect(tasks.enable).toHaveBeenCalledOnce(); expect(tasks.load).toHaveBeenCalledTimes(2);
});
- it("enables once then offers sharing only on success", async () => {
- const tasks = service();
- let finish!: () => void;
- tasks.enable.mockImplementation(() => new Promise<void>(resolve => { finish = resolve; }));
- render(<WorkflowTasksPrompt active tasks={tasks} />);
- expect(screen.queryByTestId("sharing-controls")).not.toBeInTheDocument();
- const button = await screen.findByRole("button", { name: "Enable daily updates" });
- fireEvent.click(button);
- fireEvent.click(button);
- expect(tasks.enable).toHaveBeenCalledOnce();
- expect(screen.getByRole("button", { name: "Enabling…" })).toBeDisabled();
- finish();
- await waitFor(() => expect(screen.getByTestId("sharing-controls")).toBeVisible());
+ it("turns all schedules off and does not nag to enable on re-entry", async () => {
+ const tasks = service([true,true,true,true]); const view = render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded();
+ fireEvent.click(toggle()); await waitFor(() => expect(tasks.disable).toHaveBeenCalledOnce());
+ await waitFor(() => expect(toggle()).not.toBeChecked());
+ view.rerender(<WorkflowTasksPrompt active={false} tasks={tasks} />); view.rerender(<WorkflowTasksPrompt active tasks={tasks} />); await loaded();
+ expect(toggle()).not.toBeChecked(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
- it("keeps an enable failure recoverable", async () => {
- const tasks = service();
- tasks.enable.mockRejectedValueOnce(new Error("offline"));
- render(<WorkflowTasksPrompt active tasks={tasks} />);
- fireEvent.click(await screen.findByRole("button", { name: "Enable daily updates" }));
- expect(await screen.findByRole("alert")).toHaveTextContent("Could not enable");
- fireEvent.click(screen.getByRole("button", { name: "Enable daily updates" }));
- await waitFor(() => expect(screen.getByTestId("sharing-controls")).toBeVisible());
- expect(tasks.enable).toHaveBeenCalledTimes(2);
+ it("allows disabling when allowance/access is unavailable, but explains a blocked enable", async () => {
+ const tasks = service([true,true,true,true]); const unavailable = vi.fn();
+ render(<WorkflowTasksPrompt active tasks={tasks} canEnable={false} onEnableUnavailable={unavailable} />); await loaded();
+ fireEvent.click(toggle()); await waitFor(() => expect(toggle()).not.toBeChecked()); await loaded();
+ fireEvent.click(toggle()); expect(unavailable).toHaveBeenCalledOnce(); expect(tasks.enable).not.toHaveBeenCalled();
});
- it("skips sharing for signed-out users", async () => {
- f.settings.user = null;
- render(<WorkflowTasksPrompt active tasks={service()} />);
- fireEvent.click(await screen.findByRole("button", { name: "Not now" }));
- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
- expect(f.update).not.toHaveBeenCalled();
+ it("prevents duplicate writes and keeps the old state while saving", async () => {
+ const tasks = service([true,true,true,true]); let finish!: () => void;
+ tasks.disable.mockImplementationOnce(() => new Promise<void>(r => {finish = r;}));
+ render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded(); fireEvent.click(toggle()); fireEvent.click(toggle());
+ expect(toggle()).toBeDisabled(); expect(toggle()).toBeChecked(); expect(tasks.disable).toHaveBeenCalledOnce();
+ finish(); await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Couldn’t save changes"));
});
- it("does not ask again when sharing is already enabled", async () => {
- f.settings.workflowSharing = { epoch: "existing" };
- f.settings.workflowSharingPromptSeen = { "fixture-user": "2026-09-23" };
- render(<WorkflowTasksPrompt active tasks={service()} />);
- fireEvent.click(await screen.findByRole("button", { name: "Not now" }));
- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ it("keeps partial failures visible and retries the original off intent", async () => {
+ const states = [true,true,true,true]; const tasks = service(states);
+ tasks.disable.mockImplementationOnce(async () => {states[0] = false; throw new Error("offline");});
+ render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded(); fireEvent.click(toggle());
+ expect(await screen.findByRole("button", {name:"Retry automatic updates"})).toBeVisible();
+ expect(toggle()).not.toBeChecked(); expect(screen.getByRole("status")).toHaveTextContent("Couldn’t save changes");
+ await act(async () => {window.dispatchEvent(new Event("focus"));});
+ expect(screen.getByRole("status")).toHaveTextContent("Couldn’t save changes");
+ fireEvent.click(screen.getByRole("button", {name:"Retry automatic updates"}));
+ await waitFor(() => expect(tasks.disable).toHaveBeenCalledTimes(2));
+ await waitFor(() => expect(screen.getByRole("status")).toBeEmptyDOMElement()); expect(tasks.enable).not.toHaveBeenCalled();
});
- it("asks existing sharing users to accept the new notice", async () => {
- f.settings.workflowSharing = { epoch: "existing" };
- f.settings.workflowSharingPromptSeen = { "fixture-user": "2026-09-21" };
- render(<WorkflowTasksPrompt active tasks={service(true)} />);
- expect(await screen.findByTestId("sharing-controls")).toBeVisible();
- expect(screen.getByText("Help improve Screenpipe")).toBeVisible();
- expect(screen.getByText(/train Screenpipe’s own AI models/)).toBeVisible();
- expect(f.update).not.toHaveBeenCalled();
+ it("shows enable failure in the consent dialog and offers sharing only after success", async () => {
+ f.settings.workflowSharingPromptSeen = {};
+ const tasks = service(); tasks.enable.mockRejectedValueOnce(new Error("offline"));
+ render(<WorkflowTasksPrompt active tasks={tasks} />); await loaded(); await enable();
+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not enable");
+ expect(screen.queryByText("Skip sharing")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", {name:"Enable automatic updates"}));
+ expect(await screen.findByText("Skip sharing")).toBeVisible();
});
- it("does not reuse another account's dismissal", async () => {
- f.settings.workflowSharingPromptSeen = { "different-user": "2026-09-23" };
- render(<WorkflowTasksPrompt active tasks={service()} />);
- fireEvent.click(await screen.findByRole("button", { name: "Not now" }));
- expect(screen.getByTestId("sharing-controls")).toBeVisible();
+ it("preserves account-scoped sharing consent separately from the schedules", async () => {
+ f.settings.workflowSharingPromptSeen = {"another-account":"2026-09-23"};
+ const tasks = service([true,true,true,true]); render(<WorkflowTasksPrompt active tasks={tasks} />);
+ fireEvent.click(await screen.findByText("Skip sharing"));
+ await waitFor(() => expect(f.settings.workflowSharingPromptSeen["fixture-user"]).toBe("2026-09-23"));
+ expect(tasks.enable).not.toHaveBeenCalled(); expect(tasks.disable).not.toHaveBeenCalled();
});
- it("retries recorder startup quietly without opening a false consent dialog", async () => {
- vi.useFakeTimers();
- const tasks = service(); tasks.load.mockRejectedValueOnce(new Error("offline"));
- render(<WorkflowTasksPrompt active tasks={tasks} />);
- await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
- expect(tasks.load).toHaveBeenCalledTimes(2);
- expect(screen.getByRole("button", {name:"Enable daily updates"})).toBeVisible();
- vi.useRealTimers();
+ it("waits for backend readiness and recovers on reconnect without clicking retry", async () => {
+ const tasks = service([true,true,true,true]);
+ const view = render(<WorkflowTasksPrompt active backendReady={false} tasks={tasks} />);
+ expect(tasks.load).not.toHaveBeenCalled(); expect(toggle()).toBeDisabled();
+ view.rerender(<WorkflowTasksPrompt active backendReady tasks={tasks} />); await loaded(); expect(toggle()).toBeChecked();
+ });
+ it("recovers after the initial retry window expires and observes external changes", async () => {
+ vi.useFakeTimers(); const states = [true,true,true,true]; const tasks = service(states);
+ for (let i=0;i<4;i++) tasks.load.mockRejectedValueOnce(new Error("offline"));
+ const view = render(<WorkflowTasksPrompt active tasks={tasks} />);
+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
+ expect(toggle()).toBeDisabled(); expect(screen.getByRole("status")).toHaveTextContent("Couldn’t check status");
+ await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
+ expect(toggle()).toBeChecked(); expect(screen.getByRole("status")).toBeEmptyDOMElement();
+ states[2] = false; await act(async () => {window.dispatchEvent(new Event("focus"));});
+ expect(toggle()).not.toBeChecked(); expect(screen.getByRole("status")).toHaveTextContent("Some tasks are off");
+ view.unmount(); expect(vi.getTimerCount()).toBe(0);
});
});
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.tsx
index add70148b..9d9c2af29 100644
--- a/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-tasks-prompt.tsx
@@ -6,18 +6,23 @@ import { WorkflowSharingControls } from "./workflow-sharing-controls";
import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
import { useSettings } from "@/lib/hooks/use-settings";
import { SHARING_NOTICE_VERSION } from "@/lib/trajectories/collector";
-import { Clock3, Loader2 } from "lucide-react";
+import { Clock3, Loader2, RefreshCw } from "lucide-react";
+import { Switch } from "@/components/ui/switch";
+import styles from "./workflow-tasks-prompt.module.css";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
-import { enableWorkflowTask, loadWorkflowTaskSetup, type WorkflowTaskSetup } from "@/lib/workflows/scheduled-discovery";
+import { disableWorkflowTasks, enableWorkflowTask, loadWorkflowTaskSetup, type WorkflowTaskSetup } from "@/lib/workflows/scheduled-discovery";
import { useGT } from "gt-react";
-const desktopTasks = { load: loadWorkflowTaskSetup, enable: enableWorkflowTask };
+const desktopTasks = { load: loadWorkflowTaskSetup, enable: enableWorkflowTask, disable: disableWorkflowTasks };
-export function WorkflowTasksPrompt({ active, tasks = desktopTasks }: {
+export function WorkflowTasksPrompt({ active, tasks = desktopTasks, backendReady = true, canEnable = true, onEnableUnavailable }: {
active: boolean;
- tasks?: { load: () => Promise<WorkflowTaskSetup>; enable: () => Promise<void> };
+ backendReady?: boolean;
+ canEnable?: boolean;
+ onEnableUnavailable?: () => void;
+ tasks?: { load: () => Promise<WorkflowTaskSetup>; enable: () => Promise<void>; disable: () => Promise<void> };
}) {
const ui = useGT();
@@ -32,6 +37,10 @@ export function WorkflowTasksPrompt({ active, tasks = desktopTasks }: {
const [busy, setBusy] = useState(false);
const [retry, setRetry] = useState(0);
const enabling = useRef(false);
+ const revision = useRef(0);
+ const [failedTarget, setFailedTarget] = useState<boolean | null>(null);
+ const failedIntent = useRef<boolean | null>(null);
+ failedIntent.current = failedTarget;
const close = useCallback(() => setOpen(false), []);
const finishSharing = useCallback(() => {
@@ -47,56 +56,112 @@ export function WorkflowTasksPrompt({ active, tasks = desktopTasks }: {
}
useEffect(() => { if (open) title.current?.focus(); }, [step, open]);
+ // Read again on reconnection, returning from Chat, and external task changes.
+ // Slow startup must not leave a permanent error after the recorder recovers.
useEffect(() => {
let cancelled = false;
+ let loading = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let attempts = 0;
+ let offeredSharing = false;
setOpen(false);
setSetup(null);
setStep("tasks");
setError("");
- let timer: ReturnType<typeof setTimeout> | undefined;
- let attempts = 0;
async function load() {
+ if (loading || enabling.current || cancelled) return;
+ if (timer) clearTimeout(timer);
+ loading = true;
+ const startedRevision = revision.current;
try {
const value = await tasks.load();
- if (cancelled) return;
+ if (cancelled || enabling.current || startedRevision !== revision.current) return;
setSetup(value);
- setError("");
+ const target = failedIntent.current;
+ if (target === null || (target ? value.enabled : !value.enabled && !value.tasks?.some(task => task.enabled))) {
+ setError("");
+ setFailedTarget(null);
+ }
+ attempts = 0;
const account = current.current.user?.id;
- const offerSharing = !!account && current.current.workflowSharingPromptSeen?.[account] !== SHARING_NOTICE_VERSION;
- setStep(value.enabled ? "sharing" : "tasks");
- setOpen(!value.enabled || offerSharing);
+ if (!offeredSharing && value.enabled && account && current.current.workflowSharingPromptSeen?.[account] !== SHARING_NOTICE_VERSION) {
+ offeredSharing = true;
+ setStep("sharing");
+ setOpen(true);
+ }
} catch {
- if (cancelled) return;
- // Recorder startup is not a consent failure. Retry quietly first.
- if (++attempts < 4) timer = setTimeout(load, 1500 * attempts);
- else setError(ui("Could not check scheduled tasks. Try again when Screenpipe is connected."));
+ if (cancelled || enabling.current || startedRevision !== revision.current) return;
+ setSetup(null);
+ if (++attempts >= 4) setError(ui("Could not check automatic updates. Try again."));
+ } finally {
+ loading = false;
+ if (!cancelled) timer = setTimeout(load, attempts > 0 && attempts < 4 ? 1500 * attempts : 30_000);
}
}
- if (active) void load();
- return () => { cancelled = true; if (timer) clearTimeout(timer); };
- }, [active, tasks, retry]);
+ if (active && backendReady) {
+ void load();
+ window.addEventListener("focus", load);
+ window.addEventListener("online", load);
+ }
+ return () => {
+ cancelled = true;
+ if (timer) clearTimeout(timer);
+ window.removeEventListener("focus", load);
+ window.removeEventListener("online", load);
+ };
+ }, [active, backendReady, tasks, retry]);
- async function enable() {
- if (enabling.current || !setup) return;
+ async function save(enabled: boolean) {
+ if (enabling.current || (!setup && failedTarget === null)) return;
+ if (enabled && !canEnable) { onEnableUnavailable?.(); return; }
enabling.current = true;
+ revision.current++;
+ setFailedTarget(null);
setBusy(true);
setError("");
try {
- await tasks.enable();
- nextStep();
+ await (enabled ? tasks.enable() : tasks.disable());
+ const confirmed = await tasks.load();
+ setSetup(confirmed);
+ if (enabled ? !confirmed.enabled : confirmed.tasks?.some(task => task.enabled) || confirmed.enabled) {
+ throw new Error("Some task settings did not change.");
+ }
+ if (enabled) nextStep();
} catch {
- setError(ui("Could not enable all tasks. Please try again."));
+ // A partial write is not success. Re-read the actual group, never make an
+ // optimistic all-on/all-off claim or roll a user's off request back on.
+ try { setSetup(await tasks.load()); } catch { setSetup(null); }
+ setFailedTarget(enabled);
+ setError(ui(enabled ? "Could not enable all tasks. Please try again." : "Could not turn off all tasks. Please try again."));
} finally {
enabling.current = false;
setBusy(false);
}
}
- if (active && error && !setup) return <div role="status" className="mx-6 mt-4 flex items-center justify-between gap-3 rounded-lg border p-3 text-sm"><span>{error}</span><Button variant="outline" onClick={() => setRetry(value => value + 1)}>Try again</Button></div>;
- return <Dialog open={active && open} onOpenChange={value => {
- if (enabling.current || busy) return;
- if (!value && step === "sharing") finishSharing(); else setOpen(value);
- }}>
+ const partial = !!setup && !setup.enabled && !!setup.tasks?.some(task => task.enabled);
+ return <>
+ {active && <div className={styles.control}>
+ <label className={styles.label}>
+ <span>Automatic updates</span>
+ <Switch aria-label={ui("Automatic updates")} checked={setup?.enabled ?? false} disabled={busy || !setup || !backendReady}
+ aria-describedby="workflow-schedule-status"
+ onCheckedChange={enabled => {
+ if (!enabled) { void save(false); return; }
+ if (!canEnable) { onEnableUnavailable?.(); return; }
+ setError(""); setStep("tasks"); setOpen(true);
+ }} />
+ </label>
+ <span id="workflow-schedule-status" role="status" title={error || undefined} className={styles.status}>
+ {busy ? ui("Saving…") : error ? (failedTarget !== null ? ui("Couldn’t save changes") : ui("Couldn’t check status")) : !backendReady ? ui("Connecting…") : !setup ? ui("Checking…") : partial ? ui("Some tasks are off") : ""}
+ </span>
+ {error && <button className={styles.retry} type="button" aria-label={ui("Retry automatic updates")} title={ui("Try again")}
+ disabled={busy || !backendReady} onClick={() => { if (failedTarget !== null) void save(failedTarget); else setRetry(value => value + 1); }}><RefreshCw size={14} /></button>}
+ </div>}
+ <Dialog open={active && open} onOpenChange={value => {
+ if (enabling.current || busy) return;
+ if (!value && step === "sharing") finishSharing(); else setOpen(value);
+ }}>
<DialogContent onOpenAutoFocus={event => { event.preventDefault(); title.current?.focus(); }} style={{
"--foreground": "0 0% 9%", "--background": "0 0% 100%", "--muted-foreground": "80 4% 42%",
"--border": "70 10% 85%", "--primary": "0 0% 9%", "--primary-foreground": "0 0% 100%",
@@ -108,7 +173,7 @@ export function WorkflowTasksPrompt({ active, tasks = desktopTasks }: {
{step === "tasks" ? "Keep your workflows up to date?" : "Help improve Screenpipe"}
</DialogTitle>
<DialogDescription className="text-muted-foreground">
- {step === "tasks" ? "Discover workflows and keep them accurate with daily updates." : "Share new Workflows chats to improve workflows and train Screenpipe’s own AI models. Never external providers’ models."}
+ {step === "tasks" ? "Discover workflows and keep them accurate with automatic updates." : "Share new Workflows chats to improve workflows and train Screenpipe’s own AI models. Never external providers’ models."}
</DialogDescription>
</DialogHeader>
{step === "sharing" ? <WorkflowSharingControls compact onDone={finishSharing} onUnavailable={close} onBusyChange={setBusy} /> : <>
@@ -117,16 +182,16 @@ export function WorkflowTasksPrompt({ active, tasks = desktopTasks }: {
<div className="min-w-0"><p className="text-sm font-medium">{setup.title}</p><p className="text-xs text-muted-foreground">{setup.schedule} · While Screenpipe is open</p></div>
</div>}
<p className="text-xs text-muted-foreground">Uses your AI allowance. Selected screen text and screenshots go to Screenpipe’s AI provider. Recording exclusions apply; personal content may be included.</p>
- <details className="text-xs text-muted-foreground"><summary className="cursor-pointer rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground">How daily updates work</summary>
+ <details className="text-xs text-muted-foreground"><summary className="cursor-pointer rounded-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-foreground">How automatic updates work</summary>
<p className="mt-2">Four agents discover workflows, investigate evidence, review drafts, and maintain accuracy. Dependent tasks resume in both Chat and Workflows.</p>
- <p className="mt-2">Turn updates off in <span className="font-medium text-foreground">Chat → Scheduled tasks</span>.</p>
+ <p className="mt-2">Turn updates on or off with <span className="font-medium text-foreground">Automatic updates</span> in Workflows. Turning off pauses future scheduled runs; an update already running can finish.</p>
</details>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" disabled={busy} onClick={nextStep}>Not now</Button>
- <Button disabled={busy || !setup} onClick={enable}>{busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />} {busy ? ui("Enabling…") : ui("Enable daily updates")}</Button>
+ <Button disabled={busy || !setup} onClick={() => void save(true)}>{busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" aria-hidden="true" />} {busy ? ui("Enabling…") : ui("Enable automatic updates")}</Button>
</DialogFooter>
</>}
</DialogContent>
- </Dialog>;
+ </Dialog></>;
}
diff --git a/apps/screenpipe-app-tauri/lib/dev/workflow-tasks-fixture.ts b/apps/screenpipe-app-tauri/lib/dev/workflow-tasks-fixture.ts
new file mode 100644
index 000000000..f3f3fd724
--- /dev/null
+++ b/apps/screenpipe-app-tauri/lib/dev/workflow-tasks-fixture.ts
@@ -0,0 +1,30 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+import type { WorkflowTaskSetup } from "@/lib/workflows/scheduled-discovery";
+
+const key = "screenpipe-web-workflow-schedules";
+function read(): boolean[] {
+ const saved = JSON.parse(localStorage.getItem(key) || "null");
+ return Array.isArray(saved) && saved.length === 4 && saved.every(value => typeof value === "boolean") ? saved : [true, true, true, true];
+}
+// Browser-mock only. These settings never touch the recorder or run agents.
+function scenario() { return new URLSearchParams(window.location.search).get("workflowScheduleState"); }
+let failedOnce = false;
+export const fixtureWorkflowTasks = {
+ async load(): Promise<WorkflowTaskSetup> {
+ if (scenario() === "unavailable") throw new Error("Fixture disconnected");
+ const states = read();
+ return {enabled: states.every(Boolean), title: "Keep your workflows current", schedule: "Hourly discovery, with evidence review and maintenance",
+ tasks: ["Discover", "Deepen", "Review", "Maintain"].map((title, i) => ({name: title, title, enabled: states[i]}))};
+ },
+ async enable() { localStorage.setItem(key, JSON.stringify([true, true, true, true])); },
+ async disable() {
+ if (scenario() === "saving") await new Promise(resolve => setTimeout(resolve, 2500));
+ if (scenario() === "failure" && !failedOnce) {
+ failedOnce = true;
+ localStorage.setItem(key, JSON.stringify([false, true, true, true]));
+ throw new Error("Fixture partial failure");
+ }
+ localStorage.setItem(key, JSON.stringify([false, false, false, false]));
+ },
+};
diff --git a/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.test.ts b/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.test.ts
index 51a663e4d..4b0a1ea4d 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.test.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.test.ts
@@ -2,7 +2,7 @@
// https://screenpipe.com
import { beforeEach, describe, expect, it, vi } from "vitest";
import { localFetch } from "@/lib/api";
-import { WORKFLOW_TASKS, stopWorkflowJob, ensureWorkflowTask, enableWorkflowTask, loadWorkflowTaskSetup, getWorkflowJob, startWorkflowJob, saveWorkflowCorrections, saveWorkflowFeedback, loadScheduledCatalog } from "./scheduled-discovery";
+import { WORKFLOW_TASKS, disableWorkflowTasks, stopWorkflowJob, ensureWorkflowTask, enableWorkflowTask, loadWorkflowTaskSetup, getWorkflowJob, startWorkflowJob, saveWorkflowCorrections, saveWorkflowFeedback, loadScheduledCatalog } from "./scheduled-discovery";
import { fixtureWorkflowAnalysis } from "@screenpipe/workflows-ui/fixture";
vi.mock("@/lib/api", () => ({localFetch:vi.fn()}));
vi.mock("@/lib/workflows/rollout", () => ({requireWorkflowsRollout:vi.fn(),syncWorkflowsRollout:vi.fn().mockResolvedValue(undefined)}));
@@ -196,3 +196,49 @@ it("uses the persisted update cycle across agent handoffs, resume and completion
ws.cycle.id = "cycle-b";
expect(await getWorkflowJob("workflow-review:2")).toMatchObject({ cycleId: "cycle-b" });
});
+
+
+describe("workflow schedule group", () => {
+ it("reads existing settings without installing or requiring a new access grant", async () => {
+ await loadWorkflowTaskSetup();
+ expect(fetchMock.mock.calls.map(([path]) => path)).toEqual(WORKFLOW_TASKS.map(task => `/pipes/${task}`));
+ });
+ it("turns off only the four workflow schedules without stopping a manual run", async () => {
+ await disableWorkflowTasks();
+ expect([...enabled.values()]).toEqual([false,false,false,false]);
+ expect(fetchMock.mock.calls.map(([path]) => path)).toEqual(WORKFLOW_TASKS.map(task => `/pipes/${task}/enable`));
+ });
+ it("tries all four when a disable fails and reports the partial result", async () => {
+ const original = fetchMock.getMockImplementation()!;
+ fetchMock.mockImplementation(async (path, init) => String(path) === "/pipes/workflow-review/enable"
+ ? response({error:"offline"},503) : original(path,init));
+ await expect(disableWorkflowTasks()).rejects.toThrow("Could not turn off");
+ expect([...enabled.values()]).toEqual([false,false,true,false]);
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+ it("does not install missing tasks to turn them off", async () => {
+ fetchMock.mockResolvedValue(response({error:"missing"},404));
+ await disableWorkflowTasks();
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+});
+
+it("treats missing schedules as off without writing on a settings read", async () => {
+ fetchMock.mockResolvedValue(response({error:"missing"},404));
+ const setup = await loadWorkflowTaskSetup();
+ expect(setup.enabled).toBe(false);
+ expect(setup.tasks).toHaveLength(4);
+ expect(fetchMock.mock.calls.every(([, init]) => !init?.method)).toBe(true);
+});
+it("bounds stalled schedule reads so the UI can retry", async () => {
+ vi.useFakeTimers();
+ try {
+ fetchMock.mockImplementation((_path, init) => new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));
+ }));
+ const pending = expect(loadWorkflowTaskSetup()).rejects.toMatchObject({name:"AbortError"});
+ await vi.advanceTimersByTimeAsync(10_000);
+ await pending;
+ expect(vi.getTimerCount()).toBe(0);
+ } finally { vi.useRealTimers(); }
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.ts b/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.ts
index 458381dbe..2d5a51bfd 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/scheduled-discovery.ts
@@ -31,14 +31,27 @@ export interface WorkflowTaskSetup {
}
export async function loadWorkflowTaskSetup(): Promise<WorkflowTaskSetup> {
- await ensureWorkflowTask();
- const tasks = [];
- for (const name of WORKFLOW_TASKS) {
- const { data } = await request(`/pipes/${name}`);
- if (typeof data?.config?.enabled !== "boolean") throw new Error("Could not read the workflow task settings.");
- tasks.push({ name, title: data.config.title || name, enabled: data.config.enabled });
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 10_000);
+ try {
+ const tasks = [];
+ for (const name of WORKFLOW_TASKS) {
+ const response = await localFetch(`/pipes/${name}`, { signal: controller.signal });
+ // Inspection never installs or enables tasks. Missing roles are off;
+ // explicit enable installs the disabled templates before opting in.
+ if (response.status === 404) {
+ tasks.push({ name, title: name, enabled: false });
+ continue;
+ }
+ if (!response.ok) throw new Error("Could not read the workflow task settings.");
+ const { data } = await response.json();
+ if (typeof data?.config?.enabled !== "boolean") throw new Error("Could not read the workflow task settings.");
+ tasks.push({ name, title: data.config.title || name, enabled: data.config.enabled });
+ }
+ return { enabled: tasks.every(task => task.enabled), title: "Keep your workflows current", schedule: "Hourly discovery, with evidence review and maintenance", tasks };
+ } finally {
+ clearTimeout(timeout);
}
- return { enabled: tasks.every(task => task.enabled), title: "Keep your workflows current", schedule: "Hourly discovery, with evidence review and maintenance", tasks };
}
// Only the explicit enable action opts in. Scheduling stays in the Pipe harness.
@@ -61,6 +74,22 @@ export async function enableWorkflowTask() {
if (!setup.enabled) throw new Error("Some workflow tasks could not be enabled.");
}
+/** Disable every role even if one request fails. Never grant access to turn off. */
+export async function disableWorkflowTasks() {
+ const results = await Promise.allSettled(WORKFLOW_TASKS.map(async task => {
+ const response = await localFetch(`/pipes/${task}/enable`, {
+ method: "POST", headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled: false }),
+ });
+ // A missing task cannot be scheduled. Do not install it just to disable it.
+ if (response.status === 404) return;
+ const value = await response.json();
+ if (!response.ok || value.error) throw new Error("Could not turn off all workflow tasks.");
+ }));
+ const failed = results.find(result => result.status === "rejected");
+ if (failed?.status === "rejected") throw failed.reason;
+}
+
export async function loadScheduledCatalog(signal?: AbortSignal): Promise<WorkflowAnalysis | null> {
const controller = new AbortController();
const cancel = () => controller.abort();
@@ -154,7 +183,7 @@ export async function startWorkflowJob(): Promise<WorkflowAnalysisJob> {
requireWorkflowsRollout();
await syncWorkflowsRollout(true);
const setup = await loadWorkflowTaskSetup();
- if (!setup.enabled) throw new Error("Enable workflow tasks before updating. Open Workflows again to review setup.");
+ if (!setup.enabled) throw new Error("Enable workflow tasks with Automatic updates before updating.");
const tasks = await latestTasks();
const running = tasks.find(item => ["running", "queued"].includes(item.execution?.status));
if (running) return getWorkflowJob(`${running.task}:${running.execution.id}`);
diff --git a/apps/screenpipe-workflows-web/scripts/eval-schedule-toggle.mjs b/apps/screenpipe-workflows-web/scripts/eval-schedule-toggle.mjs
new file mode 100644
index 000000000..2ac9f2b39
--- /dev/null
+++ b/apps/screenpipe-workflows-web/scripts/eval-schedule-toggle.mjs
@@ -0,0 +1,59 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+// Run against the main desktop app's browser-mock server, never a live recorder.
+import { chromium } from "playwright";
+import assert from "node:assert/strict";
+import { mkdirSync } from "node:fs";
+const out = process.env.WORKFLOW_SCHEDULE_SCREENSHOTS || "/tmp/screenpipe-workflow-schedules";
+const base = process.env.WORKFLOW_SCHEDULE_URL || "http://127.0.0.1:1420";
+mkdirSync(out, {recursive: true});
+(async()=>{const browser=await chromium.launch({headless:true,channel:'chrome'});try{
+const page=await browser.newPage({viewport:{width:1440,height:960}});
+page.setDefaultTimeout(15000);
+page.on('pageerror',e=>console.log('PAGE ERROR',e.message));
+async function navigate(state='') {
+ await page.goto(base+'/home?mode=workflows'+state,{timeout:60000});
+ const later=page.getByRole('button',{name:'Do later',exact:true});
+ await later.click({timeout:3000}).catch(()=>{});await page.getByRole('dialog',{name:'Upgrade your history storage'}).waitFor({state:'hidden',timeout:3000}).catch(()=>{});
+}
+const toggle=()=>page.getByRole('switch',{name:'Automatic updates',exact:true});
+const key='screenpipe-web-workflow-schedules';
+async function saved(value) {await page.waitForFunction(v=>document.querySelector('[role=switch][aria-label="Automatic updates"]')?.getAttribute('aria-checked')===String(v),value,{timeout:15000});}
+async function dismissMigration() { await page.getByRole('button',{name:'Do later',exact:true}).click({timeout:1500}).catch(()=>{});await page.getByRole('dialog',{name:'Upgrade your history storage'}).waitFor({state:'hidden',timeout:3000}).catch(()=>{}); }
+async function snap(name) {await dismissMigration();await page.mouse.move(1000,850);await page.screenshot({path:out+'/'+name+'.png',animations:'disabled'});console.log('captured',name);}
+await navigate(); await page.getByText('Research synthesis',{exact:true}).waitFor(); await toggle().waitFor(); await saved(true); await snap('on');
+await toggle().focus(); await page.keyboard.press('Tab'); await page.keyboard.press('Shift+Tab'); assert(await toggle().evaluate(e=>e.matches(':focus-visible'))); await snap('keyboard');
+await page.keyboard.press('Space'); await saved(false); await snap('off');
+assert.deepEqual(await page.evaluate(k=>JSON.parse(localStorage.getItem(k)),key),[false,false,false,false]);
+await page.reload(); await dismissMigration(); await saved(false); assert.equal(await page.getByRole('dialog').count(),0);
+await page.evaluate(k=>localStorage.setItem(k,JSON.stringify([true,false,true,true])),key);
+await page.evaluate(()=>window.dispatchEvent(new Event('focus'))); await saved(false);
+await page.getByText('Some tasks are off',{exact:true}).waitFor(); await snap('mixed');
+await dismissMigration(); await toggle().click(); await page.getByRole('dialog').waitFor(); await snap('enable-confirmation');
+await page.getByRole('button',{name:'Enable automatic updates',exact:true}).click(); await saved(true);
+await page.getByRole('dialog',{name:'Keep your workflows up to date?'}).waitFor({state:'hidden'});
+const sharing=page.getByRole('dialog',{name:'Help improve Screenpipe'}); if(await sharing.isVisible()) await sharing.getByRole('button',{name:'Not now',exact:true}).click();
+assert.deepEqual(await page.evaluate(k=>JSON.parse(localStorage.getItem(k)),key),[true,true,true,true]);
+await page.getByRole('button',{name:'Switch workspace',exact:true}).click();
+await page.getByRole('menuitemradio',{name:'Chat',exact:false}).click();
+assert.equal(await toggle().count(),0);
+await page.getByRole('button',{name:'Switch workspace',exact:true}).click();
+await page.getByRole('menuitemradio',{name:'Workflows',exact:false}).click(); await saved(true);
+await navigate('&workflowScheduleState=saving'); await saved(true); await toggle().click();
+await page.getByText('Saving…',{exact:true}).waitFor();assert(await toggle().isDisabled());await snap('saving');await saved(false);
+await page.evaluate(k=>localStorage.setItem(k,JSON.stringify([true,true,true,true])),key);
+await navigate('&workflowScheduleState=failure'); await saved(true); await toggle().click();
+await page.getByRole('button',{name:'Retry automatic updates'}).waitFor();await saved(false);await snap('failure');
+await page.getByRole('button',{name:'Retry automatic updates'}).click();await page.waitForFunction(k=>JSON.parse(localStorage.getItem(k)).every(v=>!v),key);
+await page.getByRole('button',{name:'Retry automatic updates'}).waitFor({state:'hidden'});
+await navigate('&workflowScheduleState=unavailable');await toggle().waitFor();await snap('checking');
+await page.getByText('Couldn’t check status',{exact:true}).waitFor();assert(await toggle().isDisabled());await snap('unavailable');
+await navigate();await saved(false);
+await page.setViewportSize({width:800,height:850});await snap('compact');
+assert(await toggle().isVisible());
+assert(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth));
+await page.setViewportSize({width:390,height:844});await snap('narrow');
+assert(await page.evaluate(()=>document.documentElement.scrollWidth<=window.innerWidth));
+assert((await page.getByRole('textbox',{name:'Search workflows',exact:true}).boundingBox()).width > 100, 'Search stays usable at narrow widths');
+console.log('PASS: on/off/mixed, confirmation, persistence/re-entry, keyboard, partial-failure retry, loading/error, responsive');
+}finally{await browser.close()}})().catch(e=>{console.error(e);process.exit(1)});
diff --git a/packages/workflows-ui/src/platform.ts b/packages/workflows-ui/src/platform.ts
index 988a6ac82..befa504e3 100644
--- a/packages/workflows-ui/src/platform.ts
+++ b/packages/workflows-ui/src/platform.ts
@@ -160,4 +160,6 @@ export type WorkflowsAppProps = {
/** Explain access only after the user requests an update. */
onAnalysisUnavailable?: () => void;
statusNotice?: import("react").ReactNode;
+ /** Host controls beside the model selector, available in every workflow view. */
+ toolbarAccessory?: import("react").ReactNode;
};
diff --git a/packages/workflows-ui/src/workflows-app.module.css b/packages/workflows-ui/src/workflows-app.module.css
index 6ac43d521..6f69933d7 100644
--- a/packages/workflows-ui/src/workflows-app.module.css
+++ b/packages/workflows-ui/src/workflows-app.module.css
@@ -1078,3 +1078,11 @@
.quietRefreshControls .runActivity { left: 0; right: auto; }
@media (max-width: 640px) { .quietCatalogHeader { gap: 10px 12px; } .quietCatalogHeader h1 { font-size: 25px; } }
@media (pointer: coarse) { .quietIconButton { width: 44px; height: 44px; } .quietRefreshControls .runToggle { min-height: 44px; } }
+
+/* Keep host schedule controls alongside the model without crushing search. */
+.toolbarAccessory { flex: 0 0 auto; }
+@media (max-width: 680px) {
+ .topbar:has(.toolbarAccessory) { height: auto; min-height: 96px; flex-wrap: wrap; row-gap: 14px; padding-top: 10px; padding-bottom: 16px; }
+ .topbar:has(.toolbarAccessory) .search { flex: 1 1 calc(100% - 52px); min-width: 0; }
+ .toolbarAccessory { margin-right: auto; }
+}
diff --git a/packages/workflows-ui/src/workflows-app.tsx b/packages/workflows-ui/src/workflows-app.tsx
index bd1c8c5f8..83a94f0e2 100644
--- a/packages/workflows-ui/src/workflows-app.tsx
+++ b/packages/workflows-ui/src/workflows-app.tsx
@@ -381,6 +381,7 @@ function AppShell({
navigationFooter,
recordingStatus,
modelControl,
+ toolbarAccessory,
startWindowDrag,
fullscreen,
openCommandPalette,
@@ -403,6 +404,7 @@ function AppShell({
navigationFooter?: WorkflowsAppProps["navigationFooter"];
recordingStatus?: React.ReactNode;
modelControl?: React.ReactNode;
+ toolbarAccessory?: React.ReactNode;
startWindowDrag?: () => Promise<void> | void;
fullscreen: boolean;
openCommandPalette: () => void;
@@ -509,6 +511,7 @@ function AppShell({
</select>
</label>}
{view === "time" && <div className={styles.profilePeriod}><CalendarRange size={13} /><span>{WORKFLOW_CATALOG_DAYS}-day profile</span></div>}
+ {toolbarAccessory && <div className={styles.toolbarAccessory}>{toolbarAccessory}</div>}
{modelControl}
{recordingStatus ?? <Pill tone={runtime?.recording ? "green" : "plain"}><span className={styles.liveDot} />{statusLabel}</Pill>}
{assistant && !assistantDocked && assistantMode === "sidebar" && <button className={styles.panelToggle} data-workflows-assistant-toggle
@@ -1294,7 +1297,7 @@ function PrivacyView({ runtime }: { runtime: WorkflowRuntime | null }) {
</>;
}
-export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "screenpipe-workflows:last-analysis-v2", initialScopeId, embedded = false, active = true, fullscreen = false, navigationBrand, composerAccessory, recordingStatus, statusNotice, analysisUnavailableReason, onAnalysisUnavailable, navigationFooter, onShareWorkflow, workflowAgentActions }: WorkflowsAppProps) {
+export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "screenpipe-workflows:last-analysis-v2", initialScopeId, embedded = false, active = true, fullscreen = false, navigationBrand, composerAccessory, recordingStatus, statusNotice, toolbarAccessory, analysisUnavailableReason, onAnalysisUnavailable, navigationFooter, onShareWorkflow, workflowAgentActions }: WorkflowsAppProps) {
const uiLanguage = useLocale();
const ui = useGT();
const shortcuts = useSidebarShortcuts();
@@ -1678,7 +1681,7 @@ export function WorkflowsApp({ platform, initialAnalysis = null, storageKey = "s
}
return <>
- <AppShell modelControl={platform.modelPreference ? <WorkflowModelControl preference={platform.modelPreference} /> : undefined} composerAccessory={composerAccessory} active={active} fullscreen={fullscreen} navigationFooter={navigationFooter} navigationBrand={navigationBrand} recordingStatus={recordingStatus} view={view} navigate={navigate} runtime={runtime} workflowCount={knownWorkflows.length} query={filters.query} setQuery={(query) => setFilters((current) => ({ ...current, query }))} activeScope={activeScope} scopes={scopes} setScope={selectScope} embedded={embedded} startWindowDrag={platform.startWindowDrag} openCommandPalette={() => setCommandPaletteOpen(true)} assistant={platform.assistant ? { platform: platform.assistant, context: view === "workflow" && activeWorkflow ? { key: `workflow:${activeWorkflow.title}`, title: activeWorkflow.title, workflow: activeWorkflow } : view === "profile" ? { key: "profile", title: ui("Context"), profile: workProfile } : { key: "workflows", title: ui("Your workflows"), catalog: workflows.map(({ title, description }) => ({ title, description })) } } : undefined}>{statusNotice}
+ <AppShell toolbarAccessory={toolbarAccessory} modelControl={platform.modelPreference ? <WorkflowModelControl preference={platform.modelPreference} /> : undefined} composerAccessory={composerAccessory} active={active} fullscreen={fullscreen} navigationFooter={navigationFooter} navigationBrand={navigationBrand} recordingStatus={recordingStatus} view={view} navigate={navigate} runtime={runtime} workflowCount={knownWorkflows.length} query={filters.query} setQuery={(query) => setFilters((current) => ({ ...current, query }))} activeScope={activeScope} scopes={scopes} setScope={selectScope} embedded={embedded} startWindowDrag={platform.startWindowDrag} openCommandPalette={() => setCommandPaletteOpen(true)} assistant={platform.assistant ? { platform: platform.assistant, context: view === "workflow" && activeWorkflow ? { key: `workflow:${activeWorkflow.title}`, title: activeWorkflow.title, workflow: activeWorkflow } : view === "profile" ? { key: "profile", title: ui("Context"), profile: workProfile } : { key: "workflows", title: ui("Your workflows"), catalog: workflows.map(({ title, description }) => ({ title, description })) } } : undefined}>{statusNotice}
{/* Keep drafts, imports and the active fill alive when navigating away.
A different scope must tear down the old request before accepting fields. */}
<div key={`${activeScope?.kind ?? "personal"}:${activeScope?.id ?? ""}`} hidden={view !== "profile"}>