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

Support saved AI presets in local Workflows (#7515)

Louis Beaumonta979c5cfea7a
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.test.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.test.tsx
index 4e50378be..d9abdb4b3 100644
--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.test.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.test.tsx
@@ -678,3 +678,50 @@ describe("AIPresetsSelector preset copy", () => {
expect(within(dialog).getByRole("button", { name: "save changes" })).toBeInTheDocument();
});
});
+
+describe("Workflows model selection", () => {
+ beforeEach(() => {
+ mocks.settings.current = { aiPresets: [originalPreset], user: {} };
+ mocks.settings.listeners.clear();
+ mocks.updateSettings.mockClear();
+ mocks.acpEnabled.current = false;
+ });
+
+ it("persists the workflow choice without changing the chat default", async () => {
+ const { WorkflowModelSelector } = await import("../workflows/workflow-model-selector");
+ const preference = { load: vi.fn(async () => "intelligent" as const), save: vi.fn(async () => {}) };
+ render(<WorkflowModelSelector preference={preference} />);
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Workflows AI" })).toHaveTextContent("Intelligent"));
+ fireEvent.click(screen.getByRole("combobox", { name: "Workflows AI" }));
+ fireEvent.click(screen.getByRole("option", { name: new RegExp(originalPreset.id) }));
+ await waitFor(() => expect(preference.save).toHaveBeenCalledWith(`preset:${originalPreset.id}`));
+ expect(mocks.updateSettings).not.toHaveBeenCalled();
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Workflows AI" })).not.toBeDisabled());
+ fireEvent.click(screen.getByRole("combobox", { name: "Workflows AI" }));
+ fireEvent.click(screen.getByRole("option", { name: "Private (Beta)" }));
+ await waitFor(() => expect(preference.save).toHaveBeenLastCalledWith("private"));
+ });
+
+ it("offers model presets without unsupported agents in the workflow create dialog", async () => {
+ mocks.acpEnabled.current = true;
+ const { WorkflowModelSelector } = await import("../workflows/workflow-model-selector");
+ const preference = { load: vi.fn(async () => "intelligent" as const), save: vi.fn(async () => {}) };
+ render(<WorkflowModelSelector preference={preference} />);
+ fireEvent.click(screen.getByRole("combobox", { name: "Workflows AI" }));
+ fireEvent.click(await screen.findByText("Create new preset"));
+ expect(screen.queryByRole("button", { name: /Claude Code/ })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: /Codex/ })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /Advanced/ })).toBeInTheDocument();
+ });
+
+ it("keeps the previous choice and reports a failed save", async () => {
+ const { WorkflowModelSelector } = await import("../workflows/workflow-model-selector");
+ const preference = { load: vi.fn(async () => "intelligent" as const), save: vi.fn(async () => { throw new Error("disk unavailable"); }) };
+ render(<WorkflowModelSelector preference={preference} />);
+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Workflows AI" })).toHaveTextContent("Intelligent"));
+ fireEvent.click(screen.getByRole("combobox", { name: "Workflows AI" }));
+ fireEvent.click(screen.getByRole("option", { name: "Private (Beta)" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not save");
+ expect(screen.getByRole("combobox", { name: "Workflows AI" })).toHaveTextContent("Intelligent");
+ });
+});
diff --git a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
index 52f734772..e7a114208 100644
--- a/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
+++ b/apps/screenpipe-app-tauri/components/rewind/ai-presets-selector.tsx
@@ -160,6 +160,7 @@ type RecommendedPreset = BaseRecommendedPreset &
type PresetDialogMode = "create" | "edit" | "copy";
interface AIProviderConfigProps {
+ allowAgentPresets?: boolean;
onSubmit: (data: AIPreset) => void;
defaultPreset?: AIPreset;
showLoginCta?: boolean;
@@ -240,6 +241,7 @@ function ChatGptSignInButton({
}
export function AIProviderConfig({
+ allowAgentPresets = true,
onSubmit,
defaultPreset,
showLoginCta = true,
@@ -335,7 +337,8 @@ export function AIProviderConfig({
// Second ACP entry point (the first is Settings → AI presets). Same
// fail-closed rollout gate, otherwise this selector would hand every user a
// coding-agent provider the settings page deliberately hides.
- const acpEnabled = useAcpRolloutEnabled();
+ const acpRolloutEnabled = useAcpRolloutEnabled();
+ const acpEnabled = allowAgentPresets && acpRolloutEnabled;
const acpAdapters = useSelectableAcpAdapters(formData.acpAgent?.id);
const primaryAcpAdapters = primaryAcpAdapterChoices(acpAdapters);
const customAcpAdapter = acpAdapters.find(
@@ -1329,6 +1332,7 @@ export function AIProviderConfig({
}
interface AIPresetDialogProps {
+ allowAgentPresets?: boolean;
open: boolean;
onOpenChange: (open: boolean) => void;
onSave: (preset: Partial<AIPreset>) => void;
@@ -1338,6 +1342,20 @@ interface AIPresetDialogProps {
}
interface AIPresetsSelectorProps {
+ allowAgentPresets?: boolean;
+ /** Host-owned choices rendered alongside saved presets without changing chat defaults. */
+ builtinOptions?: {
+ id: string;
+ label: string;
+ icon?: ReactNode;
+ badge?: string;
+ description?: string;
+ selected: boolean;
+ onSelect: () => void;
+ }[];
+ selectionLabel?: ReactNode;
+ presetFilter?: (preset: AIPreset) => boolean;
+ disabled?: boolean;
recommendedPresets?: RecommendedPreset[];
shortcutKey?: string;
onPresetChange?: (preset: AIPreset) => void;
@@ -1372,6 +1390,7 @@ interface AIPresetsSelectorProps {
}
export const AIPresetDialog = ({
+ allowAgentPresets = true,
open,
onOpenChange,
onSave,
@@ -1449,6 +1468,7 @@ export const AIPresetDialog = ({
</DialogDescription>
</DialogHeader>
<AIProviderConfig
+ allowAgentPresets={allowAgentPresets}
onSubmit={handleProviderSubmit}
defaultPreset={defaultPreset}
showLoginCta={showLoginCta}
@@ -1460,6 +1480,8 @@ export const AIPresetDialog = ({
};
export const AIPresetsSelector = ({
+ allowAgentPresets = true,
+ builtinOptions, selectionLabel, presetFilter, disabled = false,
recommendedPresets,
shortcutKey = "/",
onPresetChange,
@@ -1504,11 +1526,11 @@ export const AIPresetsSelector = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
const aiPresets = useMemo(() => {
- const presets = (settings?.aiPresets || []) as AIPreset[];
+ const presets = ((settings?.aiPresets || []) as AIPreset[]).filter(preset => !presetFilter || presetFilter(preset));
return isManagedDeployment
? filterPresetsForEnterprisePolicy(presets, aiPresetPolicy)
: presets;
- }, [settings?.aiPresets, isManagedDeployment, aiPresetPolicy]);
+ }, [settings?.aiPresets, isManagedDeployment, aiPresetPolicy, presetFilter]);
const selectedPreset = useMemo(() => {
if (isControlled) {
@@ -1556,6 +1578,7 @@ export const AIPresetsSelector = ({
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
+ if (!shortcutKey || disabled) return;
// Check for Cmd/Ctrl + /
if ((e.metaKey || e.ctrlKey) && e.key === shortcutKey) {
e.preventDefault();
@@ -1589,7 +1612,7 @@ export const AIPresetsSelector = ({
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
- }, [aiPresets, selectedPreset, updateSettings, shortcutKey, onPresetSaved, isControlled, onControlledSelect]);
+ }, [aiPresets, selectedPreset, updateSettings, shortcutKey, disabled, onPresetSaved, isControlled, onControlledSelect]);
const handleSavePreset = (preset: Partial<AIPreset>) => {
if (!canManageEmployeePresets) {
@@ -1906,6 +1929,7 @@ export const AIPresetsSelector = ({
type="button"
variant="outline"
role="combobox"
+ disabled={disabled}
aria-label={
triggerAriaLabel ??
(providerIconOnly
@@ -1920,7 +1944,7 @@ export const AIPresetsSelector = ({
triggerClassName
)}
>
- {selectedPreset ? (
+ {selectionLabel ? <span>{selectionLabel}</span> : selectedPreset ? (
showModelOnly ? (
<div className={cn(
"flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden",
@@ -2147,6 +2171,25 @@ export const AIPresetsSelector = ({
</CommandGroup>
)}
<CommandGroup>
+ {builtinOptions?.map(option => (
+ <CommandItem
+ key={option.id}
+ value={option.id}
+ aria-label={option.badge ? `${option.label} (${option.badge})` : option.label}
+ onSelect={() => { option.onSelect(); handleOpenChange(false); }}
+ className="flex min-h-10 py-2"
+ >
+ <div className="flex w-full items-center justify-between gap-2 overflow-hidden">
+ <div className="flex min-w-0 items-center gap-2">
+ <Check className={cn("h-4 w-4 shrink-0", option.selected ? "opacity-100" : "opacity-0")} />
+ {option.icon && <span className="h-4 w-4 shrink-0 opacity-80">{option.icon}</span>}
+ <span className="truncate font-medium">{option.label}</span>
+ {option.badge && <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-xs font-medium">{option.badge}</span>}
+ </div>
+ {option.description && <span className="truncate text-xs text-muted-foreground">{option.description}</span>}
+ </div>
+ </CommandItem>
+ ))}
{aiPresets.map((preset) => {
const isCloud = preset.provider === "screenpipe-cloud";
@@ -2333,6 +2376,7 @@ export const AIPresetsSelector = ({
</div>
</div>
<AIPresetDialog
+ allowAgentPresets={allowAgentPresets}
open={dialogOpen}
onOpenChange={setDialogOpen}
onSave={handleSavePreset}
diff --git a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.test.tsx b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.test.tsx
index 7cbaeb13d..039e2692b 100644
--- a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.test.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.test.tsx
@@ -8,6 +8,20 @@ import { RecordingStatus } from "@/components/recording-status";
import { SidebarFooter } from "@/components/sidebar-footer";
import { DeviceWorkflows as IntegratedWorkflows, workflowAgentTask } from "./integrated-workflows";
+// DeviceWorkflows is normally mounted beneath the app shell's settings and policy providers.
+vi.mock("@/lib/hooks/use-settings", () => ({
+ useSettings: () => ({ settings: { aiPresets: [], user: {} }, updateSettings: vi.fn() }),
+}));
+vi.mock("@/lib/hooks/use-model-upsell-gating", () => ({
+ useModelUpsellGating: () => false,
+}));
+vi.mock("@/lib/hooks/use-managed-policy", () => ({
+ useManagedPolicy: () => ({ isManagedDeployment: false, policy: {} }),
+}));
+vi.mock("@/lib/hooks/use-pi-models", () => ({
+ usePiModels: () => ({ piModels: [], isLoading: false, upgradeEligible: false }),
+}));
+
vi.mock("@/lib/workflows/desktop-platform", async () => {
const { createFixtureWorkflowsPlatform, fixtureWorkflowAnalysis } = await import("@screenpipe/workflows-ui/fixture");
return { desktopWorkflowsPlatform: {
diff --git a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
index 61d9508e6..b4f213340 100644
--- a/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/integrated-workflows.tsx
@@ -23,6 +23,7 @@ import { CloudWorkflows } from "./cloud-workflows";
import { fixtureCloudWorkflows } from "@/lib/dev/cloud-workflows-fixture";
import { useSettings } from "@/lib/hooks/use-settings";
import { useEnterpriseBuildStatus } from "@/lib/hooks/use-is-enterprise-build";
+import { WorkflowModelSelector } from "./workflow-model-selector";
import { WorkflowAccess } from "./workflow-access";
function WorkflowDictation(props: WorkflowComposerAccessoryProps) {
@@ -94,7 +95,7 @@ export function DeviceWorkflows({ active, fullscreen = false, onModeChange, reco
onConnectionClose={closeConnections}
/>}
- <WorkflowsApp readyWorkflowIds={readyWorkflowIds} reviewRequest={reviewRequest} onReviewRequestHandled={handleReview} onAnalysisUnavailable={() => setAccessRequested(true)} analysisUnavailableReason={analysisUnavailableReason} composerAccessory={composerAccessory} fullscreen={fullscreen} onShareWorkflow={openShare} workflowAgentActions={workflowAgentActions} platform={platform} active={active} storageKey={null}
+ <WorkflowsApp modelControl={<WorkflowModelSelector preference={platform.modelPreference} />} readyWorkflowIds={readyWorkflowIds} reviewRequest={reviewRequest} onReviewRequestHandled={handleReview} onAnalysisUnavailable={() => setAccessRequested(true)} analysisUnavailableReason={analysisUnavailableReason} composerAccessory={composerAccessory} fullscreen={fullscreen} onShareWorkflow={openShare} workflowAgentActions={workflowAgentActions} platform={platform} active={active} storageKey={null}
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}
sourceControl={sourceControl} navigationBrand={<ProductSwitcher mode="workflows" onChange={onModeChange} />} />
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
index 33c2d35a5..d98a62801 100644
--- a/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-access.tsx
@@ -1,7 +1,9 @@
// screenpipe — AI that knows everything you've seen, said, or heard
// https://screenpipe.com
"use client";
+import type { WorkflowModelMode } from "@screenpipe/workflows-ui";
import { workflowModelPreference } from "@/lib/workflows/model-choice";
+import { useSettings } from "@/lib/hooks/use-settings";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { useUsageStatusQuery } from "@/lib/hooks/use-usage-status";
@@ -20,14 +22,17 @@ export function WorkflowAccess({ active, requested = false, onRequestChange, onA
const { health, isServerDown } = useHealthCheck();
const backendReady = !!health && !isServerDown;
const router = useRouter();
- const [mode, setMode] = useState<"intelligent" | "private">("intelligent");
+ const [mode, setMode] = useState<WorkflowModelMode>("intelligent");
useEffect(() => {
const refresh = () => { void workflowModelPreference.load().then(setMode).catch(() => setMode("intelligent")); };
refresh(); window.addEventListener("workflows:model-changed", refresh);
window.addEventListener("focus", refresh);
return () => { window.removeEventListener("workflows:model-changed", refresh); window.removeEventListener("focus", refresh); };
}, []);
- const access = workflowAccess(query.usage, mode);
+ const { settings } = useSettings();
+ const preset = mode.startsWith("preset:") ? settings.aiPresets.find(p => p.id === mode.slice(7)) : undefined;
+ const customProvider = !!preset && ["openai", "openai-chatgpt", "anthropic", "custom", "native-ollama"].includes(preset.provider);
+ const access = workflowAccess(query.usage, mode, customProvider);
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]);
diff --git a/apps/screenpipe-app-tauri/components/workflows/workflow-model-selector.tsx b/apps/screenpipe-app-tauri/components/workflows/workflow-model-selector.tsx
new file mode 100644
index 000000000..979a933e7
--- /dev/null
+++ b/apps/screenpipe-app-tauri/components/workflows/workflow-model-selector.tsx
@@ -0,0 +1,154 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+"use client";
+import { useEffect, useState } from "react";
+import { Shield, Sparkles } from "lucide-react";
+import { AIPresetsSelector } from "@/components/rewind/ai-presets-selector";
+import { workflowModelPreference } from "@/lib/workflows/model-choice";
+import { supportsWorkflowPreset } from "@/lib/workflows/model-provider";
+import { useManagedPolicy } from "@/lib/hooks/use-managed-policy";
+import {
+ ConfidentialVerificationDetails,
+ useConfidentialVerification,
+} from "@screenpipe/workflows-ui";
+import type {
+ WorkflowModelMode,
+ WorkflowModelPreference,
+} from "@screenpipe/workflows-ui";
+
+export function WorkflowModelSelector({
+ preference = workflowModelPreference,
+}: {
+ preference?: WorkflowModelPreference;
+}) {
+ const [mode, setMode] = useState<WorkflowModelMode | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const { isManagedDeployment, policy } = useManagedPolicy();
+ const cloudAllowed =
+ !isManagedDeployment ||
+ policy.aiPresetPolicy?.allow_screenpipe_cloud !== false;
+ const verification = useConfidentialVerification(preference.verification);
+ useEffect(() => {
+ let active = true;
+ const refresh = () => {
+ void preference
+ .load()
+ .then((value) => {
+ if (active) {
+ setMode(value);
+ setError("");
+ }
+ })
+ .catch(() => {
+ if (active) {
+ setMode(null);
+ setError("Could not read your AI choice. Choose it again.");
+ }
+ });
+ };
+ refresh();
+ window.addEventListener("focus", refresh);
+ window.addEventListener("workflows:model-changed", refresh);
+ return () => {
+ active = false;
+ window.removeEventListener("focus", refresh);
+ window.removeEventListener("workflows:model-changed", refresh);
+ };
+ }, [preference]);
+ async function choose(value: WorkflowModelMode) {
+ setBusy(true);
+ setError("");
+ try {
+ await preference.save(value);
+ setMode(value);
+ } catch {
+ setError("Could not save your AI choice. Try again.");
+ } finally {
+ setBusy(false);
+ }
+ }
+ return (
+ <div className="flex flex-col gap-1">
+ <AIPresetsSelector
+ compact
+ containerClassName="w-auto"
+ triggerClassName="max-w-[240px]"
+ triggerAriaLabel="Workflows AI"
+ allowAgentPresets={false}
+ shortcutKey=""
+ disabled={busy}
+ presetFilter={supportsWorkflowPreset}
+ controlledPresetId={mode?.startsWith("preset:") ? mode.slice(7) : null}
+ selectionLabel={
+ busy ? (
+ "Saving…"
+ ) : mode === "intelligent" ? (
+ <span className="flex min-w-0 items-center gap-2">
+ <Sparkles className="h-4 w-4 shrink-0 opacity-80" />
+ <span>Intelligent</span>
+ </span>
+ ) : mode === "private" ? (
+ <span className="flex min-w-0 items-center gap-2">
+ <Shield className="h-4 w-4 shrink-0 opacity-80" />
+ <span>Private</span>
+ <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium">
+ Beta
+ </span>
+ </span>
+ ) : undefined
+ }
+ onControlledSelect={(preset) => {
+ if (preset && supportsWorkflowPreset(preset))
+ void choose(`preset:${preset.id}`);
+ else
+ setError(
+ "This agent is not supported by Workflows. Choose a model preset.",
+ );
+ }}
+ builtinOptions={
+ cloudAllowed
+ ? [
+ {
+ id: "workflow-intelligent",
+ label: "Intelligent",
+ icon: <Sparkles className="h-4 w-4" />,
+ description: "Automatic model selection",
+ selected: mode === "intelligent",
+ onSelect: () => void choose("intelligent"),
+ },
+ {
+ id: "workflow-private",
+ label: "Private",
+ icon: <Shield className="h-4 w-4" />,
+ badge: "Beta",
+ description: "Confidential AI",
+ selected: mode === "private",
+ onSelect: () => void choose("private"),
+ },
+ ]
+ : []
+ }
+ popoverFooter={
+ <div className="space-y-2 text-xs text-muted-foreground">
+ <p>
+ Applies to new chats and workflow updates. Custom presets use your
+ configured provider.
+ </p>
+ {mode === "private" && (
+ <ConfidentialVerificationDetails
+ current={verification}
+ showLabel
+ />
+ )}
+ </div>
+ }
+ />
+ {error && (
+ <span role="alert" className="text-xs text-destructive">
+ {error}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/apps/screenpipe-app-tauri/lib/workflows/access.test.ts b/apps/screenpipe-app-tauri/lib/workflows/access.test.ts
index e69312f89..d4fbe4d0d 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/access.test.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/access.test.ts
@@ -37,3 +37,11 @@ it("keeps Private usable after Intelligent is exhausted while retaining verified
expect(workflowAccess(null, "private").state).toBe("unavailable");
expect(workflowAccess(usage({ hosted_ai: { plan: "free" } }), "private").state).toBe("upgrade");
});
+
+it("custom provider bypasses hosted allowance without bypassing Business entitlement", () => {
+ const exhausted = usage({ remaining: 0, cost_limit_reached: true });
+ expect(workflowAccess(exhausted, "preset:Own API", true).state).toBe("ready");
+ expect(workflowAccess(exhausted, "preset:Hosted preset", false).state).toBe("paused");
+ expect(workflowAccess(usage({ hosted_ai: { plan: "free" } }), "preset:Own API", true).state).toBe("upgrade");
+ expect(workflowAccess(null, "preset:Own API", true).state).toBe("unavailable");
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/access.ts b/apps/screenpipe-app-tauri/lib/workflows/access.ts
index 825c4b2ac..fbdcf05b8 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/access.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/access.ts
@@ -1,13 +1,14 @@
// screenpipe — AI that knows everything you've seen, said, or heard
// https://screenpipe.com
+import type { WorkflowModelMode } from "@screenpipe/workflows-ui";
import type { UsageStatus } from "@/lib/hooks/use-usage-status";
-export function workflowAccess(usage: UsageStatus | null, mode: "intelligent" | "private" = "intelligent") {
+export function workflowAccess(usage: UsageStatus | null, mode: WorkflowModelMode = "intelligent", customProvider = false) {
// The gateway reports its privileged allowance as super_admin, not a billing tier.
// Trust only the authenticated usage response; never infer this from local user settings.
const plan = usage?.hosted_ai?.plan;
if (!plan || plan === "unknown") return { state: "unavailable", message: "Reconnect to check workflow access and AI allowance." } as const;
if (!["business", "business_max", "business_ultra", "pro", "pro_max", "pro_ultra", "team", "enterprise", "super_admin"].includes(plan)) return { state: "upgrade", message: "Automatic workflow discovery is included with Business. Your saved workflows remain available." } as const;
- if (mode === "private") return { state: "ready", message: "" } as const;
+ if (mode === "private" || customProvider) return { state: "ready", message: "" } as const;
const advisory = usage?.background_pipe_advisory;
if (usage?.cost_limit_reached || (usage && usage.remaining <= 0) || advisory?.reason === "background_pipe_allowance_low") return { state: "paused", message: usage?.cost_limit_reached || usage?.remaining === 0 ? "Workflow updates are paused because your AI allowance is used up." : "Workflow updates are paused to preserve AI allowance for chat.", resetAt: advisory?.reset_at ?? (usage?.cost_limit_reached ? usage.hosted_ai?.allowances?.find(a => a.remaining_percent === 0)?.resets_at : usage?.resets_at) } as const;
if (usage?.cost_limit_reached == null) return { state: "unavailable", message: "AI allowance is unavailable. Your saved workflows are still accessible." } as const;
diff --git a/apps/screenpipe-app-tauri/lib/workflows/agent-runner.ts b/apps/screenpipe-app-tauri/lib/workflows/agent-runner.ts
index 3fac0925e..f13edb728 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/agent-runner.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/agent-runner.ts
@@ -2,7 +2,7 @@
// https://screenpipe.com
import { workflowModelPreference } from "./model-choice";
-import { WORKFLOW_MODELS } from "@screenpipe/workflows-ui";
+import { resolveWorkflowProvider } from "./model-provider";
import { commands, type PiProviderConfig } from "@/lib/utils/tauri";
import { mountAgentEventBus, registerForeground, onTerminated, onEvicted } from "@/lib/events/bus";
import type { AgentInnerEvent } from "@/lib/events/types";
@@ -46,6 +46,8 @@ export async function runWorkflowAgent({ name, prompt, config, signal, onProgres
if (base.status === "error") throw new Error("Couldn’t open your local workspace.");
// Use the same encrypted account token that hydrates normal chat's
// settings.user.token. Read it for each run so login/logout is current.
+ const choice = await workflowModelPreference.load(); assertActive();
+ config = await resolveWorkflowProvider(choice, config); assertActive();
const userToken = await commands.getCloudToken(); assertActive();
if (config.provider === "screenpipe-cloud" && !userToken) {
throw new Error("Sign in to Screenpipe in Settings to continue.");
@@ -76,8 +78,6 @@ export async function runWorkflowAgent({ name, prompt, config, signal, onProgres
}));
unregister.push(onTerminated((event) => { if (event.sessionId === sessionId) fail(new Error("The conversation was interrupted. Try again.")); }));
unregister.push(onEvicted((event) => { if (event.sessionId === sessionId) fail(new Error("The conversation was interrupted. Try again.")); }));
- const choice = await workflowModelPreference.load(); assertActive();
- config = { ...config, provider: "screenpipe-cloud", model: WORKFLOW_MODELS[choice].model, url: "", apiKey: null, acpAgent: null, backend: null, maxContextChars: null };
const started = await commands.piStart(sessionId, projectPath ?? `${base.data}/pi-workflows-${name}`, userToken, config);
assertActive();
if (started.status === "error" || !started.data.running) throw new Error(started.status === "error" ? started.error : "Couldn’t start the assistant.");
diff --git a/apps/screenpipe-app-tauri/lib/workflows/assistant.test.ts b/apps/screenpipe-app-tauri/lib/workflows/assistant.test.ts
index a77b0a94d..941ec2380 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/assistant.test.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/assistant.test.ts
@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({
handlers: new Map<string, (e: AgentEventEnvelope) => void>(),
start: vi.fn(), prompt: vi.fn(), stop: vi.fn(), save: vi.fn(), token: vi.fn(),
}));
+const presetStore = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@/lib/hooks/use-settings", () => ({ getStore: async () => presetStore }));
vi.mock("./model-choice", () => ({ workflowModelPreference: { load: vi.fn(async () => "intelligent") } }));
vi.mock("./disk-storage", () => ({ loadAssistantFromDisk: vi.fn(), saveAssistantToDisk: mocks.save }));
vi.mock("@/lib/events/bus", () => ({
@@ -162,3 +164,17 @@ describe("workflow assistant agent transport", () => {
expect(prompt).toContain("actually search memory");
});
});
+
+it("starts a custom workflow provider without a Screenpipe cloud token", async () => {
+ vi.mocked(workflowModelPreference.load).mockResolvedValue("preset:Own API");
+ presetStore.get.mockResolvedValue({ aiPresets: [{ id: "Own API", provider: "custom", model: "private-model", url: "http://localhost:1234/v1", apiKey: "fixture-key", maxContextChars: 64000, maxTokens: 1000, prompt: "", defaultPreset: false }] });
+ mocks.token.mockResolvedValue(null);
+ mocks.start.mockResolvedValue({ status: "ok", data: { running: true } });
+ mocks.prompt.mockImplementation(async (id: string) => {
+ mocks.handlers.get(id)?.({ sessionId: id, source: "pi", event: { type: "message_update", assistantMessageEvent: { type: "text_delta", delta: "Custom answer" } } });
+ mocks.handlers.get(id)?.({ sessionId: id, source: "pi", event: { type: "agent_end" } });
+ return { status: "ok" };
+ });
+ await expect(desktopAssistant.ask({ question: "Find a task", context: null, history: [], signal: new AbortController().signal, onProgress: vi.fn() })).resolves.toBe("Custom answer");
+ expect(mocks.start).toHaveBeenLastCalledWith(expect.any(String), expect.any(String), null, expect.objectContaining({ provider: "custom", model: "private-model", url: "http://localhost:1234/v1", apiKey: "fixture-key" }));
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/model-choice.ts b/apps/screenpipe-app-tauri/lib/workflows/model-choice.ts
index 11e37771d..42dad58e7 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/model-choice.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/model-choice.ts
@@ -26,7 +26,7 @@ export const workflowModelPreference: WorkflowModelPreference = {
return parseWorkflowModel(await exists(file) ? await readTextFile(file) : null);
},
async save(mode) {
- if (mode !== "private" && mode !== "intelligent") throw new Error("Unsupported AI choice");
+ parseWorkflowModel(JSON.stringify({ mode }));
const file = await path();
const temporary = `${file}.${crypto.randomUUID()}.tmp`;
try {
diff --git a/apps/screenpipe-app-tauri/lib/workflows/model-preference.test.ts b/apps/screenpipe-app-tauri/lib/workflows/model-preference.test.ts
index e306629ce..c73c8edc9 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/model-preference.test.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/model-preference.test.ts
@@ -33,3 +33,9 @@ it("never treats damaged preferences as permission to use Intelligent", async ()
await expect(workflowModelPreference.load()).rejects.toThrow();
expect(fs.writeTextFile).not.toHaveBeenCalled();
});
+
+it("persists only the custom preset reference, not its credentials", async () => {
+ await workflowModelPreference.save("preset:Clinic model");
+ expect(await workflowModelPreference.load()).toBe("preset:Clinic model");
+ expect(files.get("/test/base/workflows-model.json")).toBe('{"mode":"preset:Clinic model"}');
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/model-provider.test.ts b/apps/screenpipe-app-tauri/lib/workflows/model-provider.test.ts
new file mode 100644
index 000000000..3e8b2f56f
--- /dev/null
+++ b/apps/screenpipe-app-tauri/lib/workflows/model-provider.test.ts
@@ -0,0 +1,75 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+import { beforeEach, expect, it, vi } from "vitest";
+import type { AIPreset, PiProviderConfig } from "@/lib/utils/tauri";
+const store = vi.hoisted(() => ({ get: vi.fn() }));
+vi.mock("@/lib/hooks/use-settings", () => ({ getStore: async () => store }));
+import { resolveWorkflowProvider } from "./model-provider";
+const base = {
+ provider: "screenpipe-cloud",
+ model: "auto",
+ systemPrompt: "Workflow rules",
+ allowedTools: ["read"],
+ maxTokens: 1000,
+} as PiProviderConfig;
+const custom = {
+ id: "Clinic model",
+ provider: "custom",
+ model: "my-model",
+ url: "http://localhost:1234/v1",
+ apiKey: "fixture-key",
+ prompt: "Prefer concise answers",
+ maxContextChars: 64000,
+ maxTokens: 2000,
+ defaultPreset: false,
+} as AIPreset;
+beforeEach(() => {
+ store.get.mockResolvedValue({ aiPresets: [custom] });
+});
+it("uses the exact saved endpoint and credentials while retaining workflow permissions", async () => {
+ expect(
+ await resolveWorkflowProvider("preset:Clinic model", base),
+ ).toMatchObject({
+ provider: "custom",
+ model: "my-model",
+ url: custom.url,
+ apiKey: "fixture-key",
+ allowedTools: ["read"],
+ maxContextChars: 64000,
+ maxTokens: 2000,
+ systemPrompt: "Workflow rules\n\nPrefer concise answers",
+ backend: null,
+ });
+});
+it("reads edited presets again for the next run", async () => {
+ await resolveWorkflowProvider("preset:Clinic model", base);
+ store.get.mockResolvedValue({
+ aiPresets: [{ ...custom, model: "new-model", apiKey: "new-fixture-key" }],
+ });
+ expect(
+ await resolveWorkflowProvider("preset:Clinic model", base),
+ ).toMatchObject({ model: "new-model", apiKey: "new-fixture-key" });
+});
+it("does not use the chat default or cloud when the saved preset is deleted", async () => {
+ store.get.mockResolvedValue({
+ aiPresets: [{ ...custom, id: "Other", defaultPreset: true }],
+ });
+ await expect(
+ resolveWorkflowProvider("preset:Clinic model", base),
+ ).rejects.toThrow("missing or unsupported");
+});
+it("rejects external agents instead of treating their name as a hosted model", async () => {
+ store.get.mockResolvedValue({ aiPresets: [{ ...custom, provider: "acp" }] });
+ await expect(
+ resolveWorkflowProvider("preset:Clinic model", base),
+ ).rejects.toThrow("missing or unsupported");
+});
+it("clears custom credentials when switching back to a built-in choice", async () => {
+ expect(
+ await resolveWorkflowProvider("private", {
+ ...base,
+ apiKey: "old-fixture-key",
+ url: custom.url,
+ }),
+ ).toMatchObject({ provider: "screenpipe-cloud", apiKey: null, url: "" });
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/model-provider.ts b/apps/screenpipe-app-tauri/lib/workflows/model-provider.ts
new file mode 100644
index 000000000..06524242b
--- /dev/null
+++ b/apps/screenpipe-app-tauri/lib/workflows/model-provider.ts
@@ -0,0 +1,70 @@
+// screenpipe — AI that knows everything you've seen, said, or heard
+// https://screenpipe.com
+
+import {
+ WORKFLOW_MODELS,
+ type WorkflowModelMode,
+} from "@screenpipe/workflows-ui";
+import { getStore } from "@/lib/hooks/use-settings";
+import { applyResolvedModelLimits } from "@/lib/model-metadata";
+import type { AIPreset, PiProviderConfig } from "@/lib/utils/tauri";
+
+// Workflows uses the Pi tool/event contract. External ACP agents are not model presets.
+export const supportsWorkflowPreset = (preset: AIPreset) =>
+ [
+ "screenpipe-cloud",
+ "openai",
+ "openai-chatgpt",
+ "anthropic",
+ "custom",
+ "native-ollama",
+ "pi",
+ ].includes(preset.provider);
+
+export async function resolveWorkflowProvider(
+ mode: WorkflowModelMode,
+ config: PiProviderConfig,
+): Promise<PiProviderConfig> {
+ if (mode === "intelligent" || mode === "private") {
+ return {
+ ...config,
+ provider: "screenpipe-cloud",
+ model: WORKFLOW_MODELS[mode].model,
+ url: "",
+ apiKey: null,
+ acpAgent: null,
+ backend: null,
+ maxContextChars: null,
+ };
+ }
+ const settings = await (
+ await getStore()
+ ).get<{ aiPresets?: AIPreset[] }>("settings");
+ const selected = settings?.aiPresets?.find(
+ (preset) => preset.id === mode.slice(7),
+ );
+ if (
+ !selected ||
+ !supportsWorkflowPreset(selected) ||
+ !selected.model?.trim()
+ ) {
+ throw new Error(
+ "Your Workflows AI preset is missing or unsupported. Choose an AI preset again.",
+ );
+ }
+ const preset = applyResolvedModelLimits(selected);
+ return {
+ ...config,
+ provider: preset.provider === "pi" ? "screenpipe-cloud" : preset.provider,
+ model: preset.model!,
+ url: preset.url || "",
+ apiKey: preset.apiKey || null,
+ maxContextChars: preset.maxContextChars,
+ maxTokens: preset.maxTokens ?? config.maxTokens,
+ systemPrompt: [config.systemPrompt, preset.prompt]
+ .filter(Boolean)
+ .join("\n\n"),
+ acpAgent: null,
+ backend: null,
+ };
+}
diff --git a/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.test.ts b/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.test.ts
index a9598479e..8857ceeff 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.test.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.test.ts
@@ -32,3 +32,9 @@ it('uses the existing agent with no tools and only accepts known unlocked ground
expect(stubs.run).toHaveBeenCalledWith(expect.objectContaining({ config: expect.objectContaining({ allowedTools: [] }) }));
expect(() => parseVoiceAnswers('{}', [], '', [])).toThrow();
});
+
+it('does not send custom-preset voice input to the hosted provider', async () => {
+ stubs.mode.mockResolvedValueOnce('preset:Own API');
+ await expect(desktopQuestionnaireVoice.connect({ sdp: 'v=0', title: 'Fixture', questions: [] }, new AbortController().signal)).rejects.toThrow('Switch to Intelligent');
+ expect(stubs.fetch).not.toHaveBeenCalled();
+});
diff --git a/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.ts b/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.ts
index 14a5dc4c2..5c446ab79 100644
--- a/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.ts
+++ b/apps/screenpipe-app-tauri/lib/workflows/questionnaire-voice.ts
@@ -11,7 +11,7 @@ import { parseVoiceAnswers, type QuestionnaireVoice } from "@screenpipe/workflow
export const desktopQuestionnaireVoice: QuestionnaireVoice = {
async connect(input, signal) {
// Private mode must never silently send microphone audio to OpenAI.
- if (await workflowModelPreference.load() === "private") throw new Error("Live voice uses cloud AI. Switch to Intelligent to use it, or answer by hand.");
+ if (await workflowModelPreference.load() !== "intelligent") throw new Error("Live voice uses cloud AI. Switch to Intelligent to use it, or answer by hand.");
const token = await commands.getCloudToken();
if (!token) throw new Error("Sign in to Screenpipe in Settings to use voice.");
const response = await fetchAiGateway("/workflow-voice", { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, body: JSON.stringify(input), signal });
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/workflows_runtime.rs b/apps/screenpipe-app-tauri/src-tauri/src/workflows_runtime.rs
index 186b5169b..ffcca6199 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/workflows_runtime.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/workflows_runtime.rs
@@ -644,13 +644,18 @@ fn scope_workflow_agent(mut config: PiProviderConfig, skill: bool) -> PiProvider
} else {
WORKFLOW_TOOLS.iter().map(|name| name.to_string()).collect()
});
+ let workflow_prompt = if skill {
+ SKILL_SYSTEM_PROMPT
+ } else {
+ WORKFLOW_SYSTEM_PROMPT
+ };
config.system_prompt = Some(
- if skill {
- SKILL_SYSTEM_PROMPT
- } else {
- WORKFLOW_SYSTEM_PROMPT
- }
- .to_string(),
+ [Some(workflow_prompt), config.system_prompt.as_deref()]
+ .into_iter()
+ .flatten()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n\n"),
);
config.max_tokens = if skill {
6_000
@@ -663,20 +668,43 @@ fn scope_workflow_agent(mut config: PiProviderConfig, skill: bool) -> PiProvider
config
}
+fn workflow_provider_config(preset: screenpipe_core::pipes::ResolvedPreset) -> PiProviderConfig {
+ let provider = match preset.provider.as_deref() {
+ Some("screenpipe") => "screenpipe-cloud",
+ Some("ollama") => "native-ollama",
+ Some(provider) => provider,
+ None => "screenpipe-cloud",
+ }
+ .to_string();
+ PiProviderConfig {
+ provider,
+ model: preset.model,
+ url: preset.url.unwrap_or_default(),
+ api_key: preset.api_key,
+ backend: None,
+ acp_agent: None,
+ max_tokens: 4096,
+ max_context_chars: None,
+ system_prompt: preset.prompt,
+ allowed_tools: None,
+ resume_session_id: None,
+ unattended: true,
+ }
+}
+
async fn configured_workflow_agent(
app: &AppHandle,
skill: bool,
) -> Result<(PiProviderConfig, Option<String>), String> {
let settings = crate::store::SettingsStore::get(app)?.ok_or("Settings are not available")?;
- let config = PiProviderConfig {
- provider: "screenpipe-cloud".into(),
- model: screenpipe_core::workflows::model_choice::selected_model()
- .map_err(|error| error.to_string())?.into(),
- url: String::new(), api_key: None, backend: None, acp_agent: None,
- max_tokens: 4096, max_context_chars: None, system_prompt: None,
- allowed_tools: None, resume_session_id: None, unattended: true,
- };
- let token = settings.user.token.clone().filter(|token| !token.is_empty());
+ let preset = screenpipe_core::workflows::model_choice::selected_provider()
+ .map_err(|error| error.to_string())?;
+ let config = workflow_provider_config(preset);
+ let token = settings
+ .user
+ .token
+ .clone()
+ .filter(|token| !token.is_empty());
let token = match token {
Some(token) => Some(token),
None => cloud_token().await,
@@ -1527,6 +1555,38 @@ mod tests {
assert!(reference.contains("Retrieval is not permission to execute"));
}
+ #[test]
+ fn workflow_selection_keeps_custom_credentials_and_workflow_permissions() {
+ let preset = screenpipe_core::pipes::ResolvedPreset {
+ provider: Some("custom".into()),
+ model: "local-model".into(),
+ url: Some("http://localhost:1234/v1".into()),
+ api_key: Some("fixture-key".into()),
+ prompt: Some("Prefer concise answers".into()),
+ executor: None,
+ executor_config: None,
+ };
+ let config = scope_workflow_agent(workflow_provider_config(preset), false);
+ assert_eq!(config.provider, "custom");
+ assert_eq!(config.model, "local-model");
+ assert_eq!(config.url, "http://localhost:1234/v1");
+ assert_eq!(config.api_key.as_deref(), Some("fixture-key"));
+ assert_eq!(
+ config.allowed_tools,
+ Some(WORKFLOW_TOOLS.iter().map(|s| s.to_string()).collect())
+ );
+ assert!(config
+ .system_prompt
+ .as_deref()
+ .unwrap()
+ .starts_with(WORKFLOW_SYSTEM_PROMPT));
+ assert!(config
+ .system_prompt
+ .as_deref()
+ .unwrap()
+ .ends_with("Prefer concise answers"));
+ }
+
#[test]
fn processing_preserves_the_configured_provider_and_scopes_tools() {
let mut settings = crate::store::SettingsStore::default();
diff --git a/crates/screenpipe-core/src/agents/pi.rs b/crates/screenpipe-core/src/agents/pi.rs
index e771cd25f..c06f1873a 100644
--- a/crates/screenpipe-core/src/agents/pi.rs
+++ b/crates/screenpipe-core/src/agents/pi.rs
@@ -2233,22 +2233,23 @@ impl AgentExecutor for PiExecutor {
// 1. Explicit provider from pipe frontmatter → use it
// 2. No provider specified → screenpipe cloud (default)
let workflow_task = crate::workflows::pipeline::task_at(working_dir).is_some();
- let model = if workflow_task {
- crate::workflows::model_choice::selected_model()?
+ let workflow_provider = if workflow_task {
+ Some(crate::workflows::model_choice::selected_provider()?)
} else {
- model
- };
- let provider = if workflow_task {
- Some("screenpipe")
- } else {
- provider
- };
- let provider_url = if workflow_task { None } else { provider_url };
- let provider_api_key = if workflow_task {
None
- } else {
- provider_api_key
};
+ let model = workflow_provider
+ .as_ref()
+ .map_or(model, |p| p.model.as_str());
+ let provider = workflow_provider
+ .as_ref()
+ .map_or(provider, |p| p.provider.as_deref());
+ let provider_url = workflow_provider
+ .as_ref()
+ .map_or(provider_url, |p| p.url.as_deref());
+ let provider_api_key = workflow_provider
+ .as_ref()
+ .map_or(provider_api_key, |p| p.api_key.as_deref());
if workflow_task {
if !crate::workflows::pipeline::has_pending_input(working_dir).await? {
return Ok(AgentOutput {
@@ -2258,10 +2259,11 @@ impl AgentExecutor for PiExecutor {
pid: None,
});
}
- crate::workflows::pipeline::check_admission(
+ crate::workflows::pipeline::check_admission_for_provider(
&self.api_url,
self.current_user_token().as_deref(),
model,
+ provider.unwrap_or("screenpipe"),
)
.await?;
}
@@ -2324,7 +2326,7 @@ impl AgentExecutor for PiExecutor {
provider_api_key,
shared_pid.clone(),
continue_session,
- None, // no pipe system prompt for trait-based calls
+ workflow_provider.as_ref().and_then(|p| p.prompt.as_deref()),
)
.await?;
@@ -2360,7 +2362,7 @@ impl AgentExecutor for PiExecutor {
provider_api_key,
None,
continue_session,
- None,
+ workflow_provider.as_ref().and_then(|p| p.prompt.as_deref()),
)
.await?;
}
@@ -2399,22 +2401,33 @@ impl AgentExecutor for PiExecutor {
_executor_config: Option<&serde_json::Value>,
) -> Result<AgentOutput> {
let workflow_task = crate::workflows::pipeline::task_at(working_dir).is_some();
- let model = if workflow_task {
- crate::workflows::model_choice::selected_model()?
+ let workflow_provider = if workflow_task {
+ Some(crate::workflows::model_choice::selected_provider()?)
} else {
- model
- };
- let provider = if workflow_task {
- Some("screenpipe")
- } else {
- provider
- };
- let provider_url = if workflow_task { None } else { provider_url };
- let provider_api_key = if workflow_task {
None
- } else {
- provider_api_key
};
+ let workflow_system_prompt = workflow_provider.as_ref().and_then(|preset| {
+ preset.prompt.as_deref().map(|preset_prompt| {
+ [pipe_system_prompt.unwrap_or(""), preset_prompt]
+ .into_iter()
+ .filter(|part| !part.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n\n")
+ })
+ });
+ let pipe_system_prompt = workflow_system_prompt.as_deref().or(pipe_system_prompt);
+ let model = workflow_provider
+ .as_ref()
+ .map_or(model, |p| p.model.as_str());
+ let provider = workflow_provider
+ .as_ref()
+ .map_or(provider, |p| p.provider.as_deref());
+ let provider_url = workflow_provider
+ .as_ref()
+ .map_or(provider_url, |p| p.url.as_deref());
+ let provider_api_key = workflow_provider
+ .as_ref()
+ .map_or(provider_api_key, |p| p.api_key.as_deref());
if workflow_task {
if !crate::workflows::pipeline::has_pending_input(working_dir).await? {
return Ok(AgentOutput {
@@ -2424,10 +2437,11 @@ impl AgentExecutor for PiExecutor {
pid: None,
});
}
- crate::workflows::pipeline::check_admission(
+ crate::workflows::pipeline::check_admission_for_provider(
&self.api_url,
self.current_user_token().as_deref(),
model,
+ provider.unwrap_or("screenpipe"),
)
.await?;
}
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 82f332a95..1ae4a274a 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -1999,10 +1999,21 @@ fn read_store_bin(path: &Path) -> Option<serde_json::Value> {
/// Falls back to the default preset if `preset_id` is `"default"`.
/// Creates store.bin with a default preset if it doesn't exist (CLI mode).
fn resolve_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {
+ resolve_preset_inner(pipes_dir, preset_id, false)
+}
+
+pub(crate) fn resolve_exact_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {
+ resolve_preset_inner(pipes_dir, preset_id, true)
+}
+
+fn resolve_preset_inner(pipes_dir: &Path, preset_id: &str, exact: bool) -> Option<ResolvedPreset> {
// store.bin lives at ~/.screenpipe/store.bin (sibling of pipes/)
let store_path = pipes_dir.parent()?.join("store.bin");
if !store_path.exists() {
+ if exact {
+ return None;
+ }
// Bootstrap for CLI users who don't have the app.
// Default to screenpipe cloud — user needs SCREENPIPE_API_KEY env var.
// Mirrors the app's first-install seed (use-settings.tsx makeDefaultPresets):
@@ -2045,6 +2056,7 @@ fn resolve_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {
// Normalize legacy preset IDs to current names
let normalized_id = match preset_id {
+ id if exact => id,
"pi-agent" => "screenpipe-cloud",
"auto" => "default",
other => other,
@@ -2054,7 +2066,7 @@ fn resolve_preset(pipes_dir: &Path, preset_id: &str) -> Option<ResolvedPreset> {
preset.get("provider").and_then(|value| value.as_str()) != Some("acp")
};
- let preset = if normalized_id == "default" {
+ let preset = if !exact && normalized_id == "default" {
// Preserve existing scheduled behavior when the user's chat default is
// ACP: only an explicit pipe selection opts into the ACP executor.
// Otherwise prefer the dedicated `pipes` preset, then another raw one.
diff --git a/crates/screenpipe-core/src/workflows/model_choice.rs b/crates/screenpipe-core/src/workflows/model_choice.rs
index 5dcaf8ffe..20b9380bd 100644
--- a/crates/screenpipe-core/src/workflows/model_choice.rs
+++ b/crates/screenpipe-core/src/workflows/model_choice.rs
@@ -2,26 +2,57 @@
// https://screenpipe.com
//! One persisted choice for interactive and scheduled Workflows AI.
-use anyhow::{bail, Result};
+use crate::pipes::{resolve_exact_preset, ResolvedPreset};
+use anyhow::{bail, Context, Result};
use std::path::Path;
pub const PRIVATE_MODEL: &str = "glm-5.3-flash-reap50-iq3m";
-pub fn selected_model() -> Result<&'static str> {
- read_model(&crate::paths::default_screenpipe_data_dir().join("workflows-model.json"))
+pub fn selected_provider() -> Result<ResolvedPreset> {
+ read_provider(&crate::paths::default_screenpipe_data_dir())
}
-fn read_model(path: &Path) -> Result<&'static str> {
- let text = match std::fs::read_to_string(path) {
+fn read_provider(base: &Path) -> Result<ResolvedPreset> {
+ let text = match std::fs::read_to_string(base.join("workflows-model.json")) {
Ok(text) => text,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok("auto"),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ "{\"mode\":\"intelligent\"}".into()
+ }
Err(error) => return Err(error.into()),
};
- match serde_json::from_str::<serde_json::Value>(&text)?["mode"].as_str() {
- Some("intelligent") => Ok("auto"),
- Some("private") => Ok(PRIVATE_MODEL),
- _ => {
- bail!("The saved Workflows AI choice is invalid. Select Intelligent or Private again.")
+ let value: serde_json::Value = serde_json::from_str(&text)?;
+ let model = match value["mode"].as_str() {
+ Some("intelligent") => "auto",
+ Some("private") => PRIVATE_MODEL,
+ Some(mode) if mode.starts_with("preset:") && !mode[7..].trim().is_empty() => {
+ let preset = resolve_exact_preset(&base.join("pipes"), &mode[7..])
+ .context("Your Workflows AI preset is unavailable. Choose an AI preset again.")?;
+ if preset.model.trim().is_empty()
+ || !matches!(
+ preset.provider.as_deref(),
+ Some(
+ "screenpipe"
+ | "openai"
+ | "openai-chatgpt"
+ | "anthropic"
+ | "custom"
+ | "ollama"
+ )
+ )
+ {
+ bail!("Your Workflows AI preset is unsupported. Choose an AI preset again.");
+ }
+ return Ok(preset);
}
- }
+ _ => bail!("The saved Workflows AI choice is invalid. Choose an AI preset again."),
+ };
+ Ok(ResolvedPreset {
+ model: model.into(),
+ provider: Some("screenpipe".into()),
+ url: None,
+ api_key: None,
+ prompt: None,
+ executor: None,
+ executor_config: None,
+ })
}
#[cfg(test)]
@@ -30,13 +61,45 @@ mod tests {
#[test]
fn preserves_private_selection_and_rejects_corrupt_preferences() {
let dir = tempfile::tempdir().unwrap();
- let path = dir.path().join("model.json");
- assert_eq!(read_model(&path).unwrap(), "auto");
+ let path = dir.path().join("workflows-model.json");
+ assert_eq!(read_provider(dir.path()).unwrap().model, "auto");
std::fs::write(&path, r#"{"mode":"private"}"#).unwrap();
- assert_eq!(read_model(&path).unwrap(), PRIVATE_MODEL);
- for invalid in ["{", r#"{"mode":"custom"}"#, "null"] {
+ assert_eq!(read_provider(dir.path()).unwrap().model, PRIVATE_MODEL);
+ for invalid in ["{", r#"{"mode":"custom"}"#, r#"{"mode":"preset:"}"#, "null"] {
std::fs::write(&path, invalid).unwrap();
- assert!(read_model(&path).is_err());
+ assert!(read_provider(dir.path()).is_err());
}
}
+ #[test]
+ fn resolves_exact_current_preset_and_never_falls_back_to_cloud() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(
+ dir.path().join("workflows-model.json"),
+ r#"{"mode":"preset:default"}"#,
+ )
+ .unwrap();
+ let store = dir.path().join("store.bin");
+ std::fs::write(&store, r#"{"settings":{"aiPresets":[
+ {"id":"chat","provider":"screenpipe-cloud","model":"auto","defaultPreset":true},
+ {"id":"default","provider":"custom","model":"my-model","url":"http://localhost:1234/v1","apiKey":"fixture-key"}
+ ]}}"#).unwrap();
+ let preset = read_provider(dir.path()).unwrap();
+ assert_eq!(preset.model, "my-model");
+ assert_eq!(preset.provider.as_deref(), Some("custom"));
+ assert_eq!(preset.url.as_deref(), Some("http://localhost:1234/v1"));
+ assert_eq!(preset.api_key.as_deref(), Some("fixture-key"));
+ std::fs::write(&store, r#"{"settings":{"aiPresets":[]}}"#).unwrap();
+ assert!(read_provider(dir.path()).is_err());
+ std::fs::remove_file(&store).unwrap();
+ std::fs::write(
+ dir.path().join("workflows-model.json"),
+ r#"{"mode":"preset:chat"}"#,
+ )
+ .unwrap();
+ assert!(read_provider(dir.path()).is_err());
+ assert!(
+ !store.exists(),
+ "exact selection must not recreate cloud presets"
+ );
+ }
}
diff --git a/crates/screenpipe-core/src/workflows/pipeline.rs b/crates/screenpipe-core/src/workflows/pipeline.rs
index a65a31b17..31ff4c30a 100644
--- a/crates/screenpipe-core/src/workflows/pipeline.rs
+++ b/crates/screenpipe-core/src/workflows/pipeline.rs
@@ -45,6 +45,13 @@ pub fn admission(usage: &Value) -> Result<(), (&'static str, &'static str)> {
admission_for_model(usage, "auto")
}
fn admission_for_model(usage: &Value, model: &str) -> Result<(), (&'static str, &'static str)> {
+ admission_for_provider(usage, model, "screenpipe")
+}
+fn admission_for_provider(
+ usage: &Value,
+ model: &str,
+ provider: &str,
+) -> Result<(), (&'static str, &'static str)> {
let plan = usage
.pointer("/hosted_ai/plan")
.and_then(Value::as_str)
@@ -76,7 +83,7 @@ fn admission_for_model(usage: &Value, model: &str) -> Result<(), (&'static str,
}
// Owned-GPU inference has no paid-provider allowance debit. Authentication,
// Business entitlement and gateway capacity limits still apply.
- if model == super::model_choice::PRIVATE_MODEL {
+ if provider != "screenpipe" || model == super::model_choice::PRIVATE_MODEL {
return Ok(());
}
if usage["cost_limit_reached"] == true || usage["remaining"].as_f64().is_some_and(|n| n <= 0.0)
@@ -190,6 +197,15 @@ pub async fn check_admission(
api_url: &str,
token: Option<&str>,
model: &str,
+) -> anyhow::Result<()> {
+ check_admission_for_provider(api_url, token, model, "screenpipe").await
+}
+
+pub async fn check_admission_for_provider(
+ api_url: &str,
+ token: Option<&str>,
+ model: &str,
+ provider: &str,
) -> anyhow::Result<()> {
require_rollout(rollout_enabled())?;
let token = token.filter(|s| !s.is_empty()).ok_or_else(|| {
@@ -214,7 +230,7 @@ pub async fn check_admission(
.json()
.await
.map_err(|_| anyhow::anyhow!("workflow_usage_unavailable: Invalid allowance response."))?;
- admission_for_model(&value, model).map_err(|(code, message)| {
+ admission_for_provider(&value, model, provider).map_err(|(code, message)| {
anyhow::anyhow!("{}", json!({"error":{"code":code,"message":message}}))
})
}
@@ -345,6 +361,17 @@ mod tests {
assert!(has_pending_input(&task).await.unwrap());
assert_eq!(server.received_requests().await.unwrap().len(), 1);
}
+ #[test]
+ fn custom_provider_ignores_hosted_allowance_but_requires_business() {
+ let mut usage =
+ json!({"hosted_ai":{"plan":"business"},"remaining":0,"cost_limit_reached":true});
+ assert!(admission_for_provider(&usage, "my-model", "custom").is_ok());
+ assert!(admission_for_provider(&usage, "my-model", "screenpipe").is_err());
+ usage["hosted_ai"]["plan"] = json!("free");
+ assert!(admission_for_provider(&usage, "my-model", "custom").is_err());
+ assert!(admission_for_provider(&Value::Null, "my-model", "ollama").is_err());
+ }
+
#[test]
fn private_model_ignores_paid_allowance_but_requires_business() {
let mut usage =
diff --git a/docs/COVERAGE.md b/docs/COVERAGE.md
index 1556d6d16..9d664b3f5 100644
--- a/docs/COVERAGE.md
+++ b/docs/COVERAGE.md
@@ -37,16 +37,16 @@ results and `cargo llvm-cov` data on top when judging release confidence.
### Core Engine
- Mapped suites: 36
-- Mapped Rust files: 383
-- Active test blocks: 3774
+- Mapped Rust files: 384
+- Active test blocks: 3791
- Ignored/manual test blocks: 170
-- Weighted coverage points: 3113.0
+- Weighted coverage points: 3126.7
| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| windows | 32 | 3628 | 156 | 3046.8 | 21 | 11 | 100% |
-| macos | 31 | 3654 | 131 | 3035.3 | 22 | 11 | 100% |
-| linux | 28 | 3211 | 131 | 2670.1 | 20 | 11 | 100% |
+| windows | 32 | 3645 | 156 | 3060.4 | 21 | 11 | 100% |
+| macos | 31 | 3671 | 131 | 3048.9 | 22 | 11 | 100% |
+| linux | 28 | 3228 | 131 | 2683.8 | 20 | 11 | 100% |
## Refresh
diff --git a/docs/coverage/CORE.md b/docs/coverage/CORE.md
index b6856ca5d..6ad9d3d4b 100644
--- a/docs/coverage/CORE.md
+++ b/docs/coverage/CORE.md
@@ -8,11 +8,11 @@ confidence, and criticality.
- Manifest: `docs/coverage/core-engine-map.json`
- Tracked crates: screenpipe-engine, screenpipe-db, screenpipe-sqlite-coordinator, screenpipe-audio, screenpipe-screen, screenpipe-a11y, screenpipe-fs
- Mapped suites: 36
-- Mapped Rust files: 383
-- Active test blocks: 3774
+- Mapped Rust files: 384
+- Active test blocks: 3791
- Ignored/manual test blocks: 170
-- Declared test blocks: 3944
-- Weighted coverage points: 3113.0
+- Declared test blocks: 3961
+- Weighted coverage points: 3126.7
Confidence weights: strong=1.0, partial=0.7, conditional=0.4, smoke=0.3.
Criticality weights: high=1.0, medium=0.7, low=0.4.
@@ -23,16 +23,16 @@ are explicitly enabled in a runtime lane.
| Platform | Suites | Active tests | Ignored tests | Weighted points | Layers | Flows | Critical score |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| windows | 32 | 3628 | 156 | 3046.8 | 21 | 11 | 100% |
-| macos | 31 | 3654 | 131 | 3035.3 | 22 | 11 | 100% |
-| linux | 28 | 3211 | 131 | 2670.1 | 20 | 11 | 100% |
+| windows | 32 | 3645 | 156 | 3060.4 | 21 | 11 | 100% |
+| macos | 31 | 3671 | 131 | 3048.9 | 22 | 11 | 100% |
+| linux | 28 | 3228 | 131 | 2683.8 | 20 | 11 | 100% |
## Crate Summary
| Crate | Suites | Integration files | Source unit files | Active tests | Ignored tests | Weighted points | Flows |
| --- | --- | --- | --- | --- | --- | --- | --- |
-| screenpipe-engine | 12 | 21 | 127 | 1818 | 52 | 1399.1 | 10 |
-| screenpipe-db | 5 | 65 | 26 | 595 | 26 | 566.6 | 9 |
+| screenpipe-engine | 12 | 21 | 127 | 1830 | 52 | 1408.7 | 10 |
+| screenpipe-db | 5 | 66 | 26 | 596 | 26 | 567.6 | 9 |
| screenpipe-sqlite-coordinator | 1 | 0 | 3 | 27 | 0 | 27.0 | 2 |
| screenpipe-audio | 7 | 26 | 53 | 675 | 49 | 590.3 | 5 |
| screenpipe-screen | 6 | 9 | 19 | 276 | 9 | 245.4 | 4 |
@@ -65,25 +65,25 @@ bun run coverage:core -- --llvm-cov-summary ../../docs/coverage/core-llvm-cov-su
| accessibility | 4 suites / 383 active / 35 ignored / 348.0 pts | 4 suites / 422 active / 10 ignored / 342.9 pts | 4 suites / 341 active / 7 ignored / 313.0 pts |
| audio | 9 suites / 798 active / 50 ignored / 713.3 pts | 8 suites / 792 active / 50 ignored / 709.0 pts | 7 suites / 713 active / 49 ignored / 653.8 pts |
| audio-device | 2 suites / 234 active / 7 ignored / 210.3 pts | 2 suites / 234 active / 7 ignored / 210.3 pts | 1 suites / 155 active / 6 ignored / 155.0 pts |
-| configuration | 2 suites / 151 active / 3 ignored / 136.7 pts | 2 suites / 151 active / 3 ignored / 136.7 pts | 2 suites / 151 active / 3 ignored / 136.7 pts |
-| database | 7 suites / 548 active / 22 ignored / 519.6 pts | 7 suites / 548 active / 22 ignored / 519.6 pts | 7 suites / 548 active / 22 ignored / 519.6 pts |
-| db-search | 2 suites / 116 active / 9 ignored / 116.0 pts | 2 suites / 116 active / 9 ignored / 116.0 pts | 2 suites / 116 active / 9 ignored / 116.0 pts |
-| engine-lifecycle | 6 suites / 254 active / 1 ignored / 229.0 pts | 6 suites / 254 active / 1 ignored / 229.0 pts | 6 suites / 250 active / 9 ignored / 228.1 pts |
-| local-api | 3 suites / 474 active / 11 ignored / 334.8 pts | 3 suites / 474 active / 11 ignored / 334.8 pts | 3 suites / 474 active / 11 ignored / 334.8 pts |
-| meeting | 6 suites / 1706 active / 24 ignored / 1391.9 pts | 6 suites / 1706 active / 24 ignored / 1391.9 pts | 4 suites / 1357 active / 20 ignored / 1066.6 pts |
-| ocr | 4 suites / 137 active / 7 ignored / 127.7 pts | 4 suites / 130 active / 7 ignored / 125.5 pts | 3 suites / 121 active / 6 ignored / 116.5 pts |
+| configuration | 2 suites / 153 active / 3 ignored / 138.7 pts | 2 suites / 153 active / 3 ignored / 138.7 pts | 2 suites / 153 active / 3 ignored / 138.7 pts |
+| database | 7 suites / 549 active / 22 ignored / 520.6 pts | 7 suites / 549 active / 22 ignored / 520.6 pts | 7 suites / 549 active / 22 ignored / 520.6 pts |
+| db-search | 2 suites / 118 active / 9 ignored / 118.0 pts | 2 suites / 118 active / 9 ignored / 118.0 pts | 2 suites / 118 active / 9 ignored / 118.0 pts |
+| engine-lifecycle | 6 suites / 261 active / 1 ignored / 234.5 pts | 6 suites / 261 active / 1 ignored / 234.5 pts | 6 suites / 257 active / 9 ignored / 233.6 pts |
+| local-api | 3 suites / 478 active / 11 ignored / 338.2 pts | 3 suites / 478 active / 11 ignored / 338.2 pts | 3 suites / 478 active / 11 ignored / 338.2 pts |
+| meeting | 6 suites / 1708 active / 24 ignored / 1393.3 pts | 6 suites / 1708 active / 24 ignored / 1393.3 pts | 4 suites / 1359 active / 20 ignored / 1068.0 pts |
+| ocr | 4 suites / 140 active / 7 ignored / 129.8 pts | 4 suites / 133 active / 7 ignored / 127.6 pts | 3 suites / 124 active / 6 ignored / 118.6 pts |
| os-integration | 1 suites / 6 active / 0 ignored / 1.7 pts | 1 suites / 6 active / 0 ignored / 1.7 pts | - |
| performance | 13 suites / 1655 active / 80 ignored / 1463.6 pts | 14 suites / 1763 active / 84 ignored / 1506.8 pts | 13 suites / 1655 active / 80 ignored / 1463.6 pts |
| pipes | 1 suites / 540 active / 3 ignored / 378.0 pts | 1 suites / 540 active / 3 ignored / 378.0 pts | 1 suites / 540 active / 3 ignored / 378.0 pts |
| privacy | 5 suites / 1002 active / 42 ignored / 809.1 pts | 5 suites / 1041 active / 17 ignored / 804.0 pts | 5 suites / 960 active / 14 ignored / 774.0 pts |
| real-app | - | 1 suites / 108 active / 4 ignored / 43.2 pts | - |
| speaker | 2 suites / 389 active / 11 ignored / 389.0 pts | 2 suites / 389 active / 11 ignored / 389.0 pts | 2 suites / 389 active / 11 ignored / 389.0 pts |
-| storage | 4 suites / 674 active / 39 ignored / 560.0 pts | 4 suites / 674 active / 39 ignored / 560.0 pts | 4 suites / 674 active / 39 ignored / 560.0 pts |
-| sync | 1 suites / 539 active / 3 ignored / 377.3 pts | 1 suites / 539 active / 3 ignored / 377.3 pts | 1 suites / 539 active / 3 ignored / 377.3 pts |
-| timeline | 4 suites / 1221 active / 45 ignored / 1000.5 pts | 4 suites / 1221 active / 45 ignored / 1000.5 pts | 4 suites / 1221 active / 45 ignored / 1000.5 pts |
-| transcription | 6 suites / 870 active / 48 ignored / 680.2 pts | 5 suites / 864 active / 48 ignored / 676.0 pts | 5 suites / 864 active / 48 ignored / 676.0 pts |
-| ui-events | 4 suites / 816 active / 34 ignored / 619.3 pts | 3 suites / 747 active / 5 ignored / 571.0 pts | 3 suites / 747 active / 5 ignored / 571.0 pts |
-| vision-capture | 6 suites / 572 active / 32 ignored / 450.5 pts | 6 suites / 565 active / 32 ignored / 448.3 pts | 5 suites / 556 active / 31 ignored / 439.3 pts |
+| storage | 4 suites / 676 active / 39 ignored / 561.7 pts | 4 suites / 676 active / 39 ignored / 561.7 pts | 4 suites / 676 active / 39 ignored / 561.7 pts |
+| sync | 1 suites / 540 active / 3 ignored / 378.0 pts | 1 suites / 540 active / 3 ignored / 378.0 pts | 1 suites / 540 active / 3 ignored / 378.0 pts |
+| timeline | 4 suites / 1224 active / 45 ignored / 1003.2 pts | 4 suites / 1224 active / 45 ignored / 1003.2 pts | 4 suites / 1224 active / 45 ignored / 1003.2 pts |
+| transcription | 6 suites / 871 active / 48 ignored / 680.9 pts | 5 suites / 865 active / 48 ignored / 676.8 pts | 5 suites / 865 active / 48 ignored / 676.8 pts |
+| ui-events | 4 suites / 817 active / 34 ignored / 620.0 pts | 3 suites / 748 active / 5 ignored / 571.7 pts | 3 suites / 748 active / 5 ignored / 571.7 pts |
+| vision-capture | 6 suites / 576 active / 32 ignored / 453.6 pts | 6 suites / 569 active / 32 ignored / 451.4 pts | 5 suites / 560 active / 31 ignored / 442.4 pts |
## Critical Flow Matrix
diff --git a/packages/workflows-ui/src/model-choice.tsx b/packages/workflows-ui/src/model-choice.tsx
index b48e263f1..e9fab1304 100644
--- a/packages/workflows-ui/src/model-choice.tsx
+++ b/packages/workflows-ui/src/model-choice.tsx
@@ -10,7 +10,10 @@ import styles from "./model-choice.module.css";
import { useGT, msg, useMessages } from "gt-react";
-export type WorkflowModelMode = "intelligent" | "private";
+export type WorkflowModelMode = "intelligent" | "private" | `preset:${string}`;
+export function isWorkflowPreset(mode: string): mode is `preset:${string}` {
+ return mode.startsWith("preset:") && mode.slice(7).trim().length > 0;
+}
export type WorkflowModelPreference = {
verification?: ConfidentialVerificationSource;
load(): Promise<WorkflowModelMode>;
@@ -23,7 +26,7 @@ export const WORKFLOW_MODELS = {
export function parseWorkflowModel(text: string | null): WorkflowModelMode {
if (text === null) return "intelligent";
const mode = JSON.parse(text)?.mode;
- if (mode !== "intelligent" && mode !== "private") throw new Error("Could not read your saved AI choice.");
+ if (mode !== "intelligent" && mode !== "private" && !(typeof mode === "string" && isWorkflowPreset(mode))) throw new Error("Could not read your saved AI choice.");
return mode;
}
export function WorkflowModelControl({ preference }: { preference: WorkflowModelPreference }) {
@@ -78,7 +81,7 @@ export function WorkflowModelControl({ preference }: { preference: WorkflowModel
if (["ArrowDown", "ArrowUp"].includes(event.key)) { event.preventDefault(); setOpen(true); }
}}>
{mode === "private" ? <Shield size={15} aria-hidden="true" /> : <Sparkles size={15} aria-hidden="true" />}
- <span>{busy ? ui("Saving…") : mode ? uiMessages(WORKFLOW_MODELS[mode].label) : ui("Choose AI")}</span><ChevronDown size={13} aria-hidden="true" />
+ <span>{busy ? ui("Saving…") : mode ? isWorkflowPreset(mode) ? mode.slice(7) : uiMessages(WORKFLOW_MODELS[mode].label) : ui("Choose AI")}</span><ChevronDown size={13} aria-hidden="true" />
</button>
{open && <div ref={menu} id={menuId} className={styles.menu} role="menu" aria-label={ui("Workflows AI")} onKeyDown={event => {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key) || (event.target as HTMLElement).closest("dialog")) return;
diff --git a/packages/workflows-ui/src/platform.ts b/packages/workflows-ui/src/platform.ts
index 6e316de41..317304168 100644
--- a/packages/workflows-ui/src/platform.ts
+++ b/packages/workflows-ui/src/platform.ts
@@ -149,6 +149,7 @@ export type WorkflowRecording = {
};
export type WorkflowsAppProps = {
+ modelControl?: import("react").ReactNode;
/** Quiet in-app alternative to interrupting a focused workflow reader. */
readyWorkflowIds?: string[];
/** Host-owned request survives cold startup until the saved catalog loads. */
diff --git a/packages/workflows-ui/src/workflows-app.tsx b/packages/workflows-ui/src/workflows-app.tsx
index e02494d64..18be635ed 100644
--- a/packages/workflows-ui/src/workflows-app.tsx
+++ b/packages/workflows-ui/src/workflows-app.tsx
@@ -928,7 +928,7 @@ function ProfileView({
</div>;
}
-export function WorkflowsApp({ readyWorkflowIds, reviewRequest, onReviewRequestHandled, platform, initialAnalysis = null, storageKey = "screenpipe-workflows:last-analysis-v2", initialScopeId, embedded = false, active = true, fullscreen = false, navigationBrand, sourceControl, composerAccessory, recordingStatus, statusNotice, toolbarAccessory, analysisUnavailableReason, onAnalysisUnavailable, navigationFooter, onShareWorkflow, workflowAgentActions }: WorkflowsAppProps) {
+export function WorkflowsApp({ modelControl, readyWorkflowIds, reviewRequest, onReviewRequestHandled, platform, initialAnalysis = null, storageKey = "screenpipe-workflows:last-analysis-v2", initialScopeId, embedded = false, active = true, fullscreen = false, navigationBrand, sourceControl, composerAccessory, recordingStatus, statusNotice, toolbarAccessory, analysisUnavailableReason, onAnalysisUnavailable, navigationFooter, onShareWorkflow, workflowAgentActions }: WorkflowsAppProps) {
const uiLanguage = useLocale();
const ui = useGT();
const shortcuts = useSidebarShortcuts();
@@ -1337,7 +1337,7 @@ export function WorkflowsApp({ readyWorkflowIds, reviewRequest, onReviewRequestH
}
return <>
- <AppShell sourceControl={sourceControl} hasLibrary={Boolean(platform.guides?.list || platform.library)} 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={query} setQuery={setQuery} 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 sourceControl={sourceControl} hasLibrary={Boolean(platform.guides?.list || platform.library)} toolbarAccessory={toolbarAccessory} modelControl={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={query} setQuery={setQuery} 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"}>