Skip to content

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

fix(chat): stop a coding-agent preset from billing the cloud as "codex-acp" (#6204)

Louis Beaumont7747c5fe9609
diff --git a/COVERAGE.md b/COVERAGE.md
index b841fa224..33b0cf64f 100644
--- a/COVERAGE.md
+++ b/COVERAGE.md
@@ -19,14 +19,14 @@ results and `cargo llvm-cov` data on top when judging release confidence.
### Tauri E2E
- Mapped specs: 112
-- Declared test blocks: 318
-- Weighted coverage points: 250.0
+- Declared test blocks: 319
+- Weighted coverage points: 250.7
| Platform | Specs | Declared tests | Weighted points | Layers | Features | Critical score |
| --- | --- | --- | --- | --- | --- | --- |
-| windows | 86 | 276 | 226.6 | 15 | 90 | 92% |
-| macos | 108 | 281 | 220.8 | 17 | 93 | 90% |
-| linux | 75 | 233 | 195.2 | 14 | 85 | 88% |
+| windows | 86 | 277 | 227.3 | 15 | 90 | 92% |
+| macos | 108 | 282 | 221.5 | 17 | 93 | 90% |
+| linux | 75 | 234 | 195.9 | 14 | 85 | 88% |
### Core Engine
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
index 90fce46e2..b8cba714e 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts
@@ -19,6 +19,7 @@ import {
buildHostedBusyFinalMessage,
buildHostedBusyMessage,
buildHostedBusyRetryMessage,
+ buildModelNotAllowedMessage,
buildRateLimitMessage,
classifyQuotaError,
parseRateLimitWaitSeconds,
@@ -625,7 +626,7 @@ export function usePiForegroundEvents({
if (piMessageIdRef.current) {
const msgId = piMessageIdRef.current;
setMessages((prev) =>
- prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade to Screenpipe Business. Switch to Auto to keep going." } : m)
+ prev.map((m) => m.id === msgId ? { ...m, content: buildModelNotAllowedMessage(errorStr) } : m)
);
}
} else {
@@ -684,7 +685,7 @@ export function usePiForegroundEvents({
}
} else if (fullError.includes("model_not_allowed")) {
setMessages((prev) =>
- prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade to Screenpipe Business. Switch to Auto to keep going." } : m)
+ prev.map((m) => m.id === msgId ? { ...m, content: buildModelNotAllowedMessage(fullError) } : m)
);
} else {
const providerError = buildProviderErrorPresentation(fullError, presetWithAgentName());
@@ -1007,7 +1008,7 @@ export function usePiForegroundEvents({
} else if (quotaErrorType === "rate") {
content = buildRateLimitMessage(errStr);
} else if (errStr.includes("model_not_allowed")) {
- content = "This model requires an upgrade to Screenpipe Business. Switch to Auto to keep going.";
+ content = buildModelNotAllowedMessage(errStr);
} else {
content = buildProviderErrorPresentation(errStr, getActivePreset())?.message || errStr;
}
@@ -1222,7 +1223,7 @@ export function usePiForegroundEvents({
}
} else if (errorStr.includes("model_not_allowed")) {
setMessages((prev) =>
- prev.map((m) => m.id === msgId ? { ...m, content: "This model requires an upgrade to Screenpipe Business. Switch to Auto to keep going." } : m)
+ prev.map((m) => m.id === msgId ? { ...m, content: buildModelNotAllowedMessage(errorStr) } : m)
);
} else {
const providerError = buildProviderErrorPresentation(errorStr, presetWithAgentName());
diff --git a/apps/screenpipe-app-tauri/e2e/COVERAGE.md b/apps/screenpipe-app-tauri/e2e/COVERAGE.md
index 106b624dd..5eae364e7 100644
--- a/apps/screenpipe-app-tauri/e2e/COVERAGE.md
+++ b/apps/screenpipe-app-tauri/e2e/COVERAGE.md
@@ -7,8 +7,8 @@ and layer declared in the manifest, weighted by confidence and criticality.
- Manifest: `e2e/coverage-map.json`
- Specs directory: `e2e/specs`
- Mapped specs: 112
-- Declared test blocks: 318
-- Weighted coverage points: 250.0
+- Declared test blocks: 319
+- Weighted coverage points: 250.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.
@@ -19,9 +19,9 @@ can execute more runtime cases than this number shows.
| Platform | Specs | Declared tests | Weighted points | Layers | Features | Critical score |
| --- | --- | --- | --- | --- | --- | --- |
-| windows | 86 | 276 | 226.6 | 15 | 90 | 92% |
-| macos | 108 | 281 | 220.8 | 17 | 93 | 90% |
-| linux | 75 | 233 | 195.2 | 14 | 85 | 88% |
+| windows | 86 | 277 | 227.3 | 15 | 90 | 92% |
+| macos | 108 | 282 | 221.5 | 17 | 93 | 90% |
+| linux | 75 | 234 | 195.9 | 14 | 85 | 88% |
## Runtime Results
@@ -37,18 +37,18 @@ pass/fail/skip counts.
| auth | - | 1 specs / 1 tests / 1.0 pts | - |
| billing | 4 specs / 6 tests / 5.7 pts | 4 specs / 6 tests / 5.7 pts | 4 specs / 6 tests / 5.7 pts |
| capture-ocr | 2 specs / 16 tests / 6.4 pts | 8 specs / 12 tests / 4.8 pts | 1 specs / 3 tests / 1.2 pts |
-| chat-ai | 25 specs / 50 tests / 36.9 pts | 36 specs / 71 tests / 50.5 pts | 24 specs / 49 tests / 36.4 pts |
+| chat-ai | 25 specs / 51 tests / 37.6 pts | 36 specs / 72 tests / 51.2 pts | 24 specs / 50 tests / 37.1 pts |
| entitlement | - | 1 specs / 1 tests / 1.0 pts | - |
| local-api | 24 specs / 113 tests / 94.0 pts | 31 specs / 100 tests / 83.5 pts | 19 specs / 81 tests / 72.2 pts |
| notifications | 4 specs / 25 tests / 16.3 pts | 3 specs / 5 tests / 3.4 pts | 2 specs / 4 tests / 3.1 pts |
| onboarding | 8 specs / 33 tests / 30.0 pts | 10 specs / 35 tests / 31.4 pts | 8 specs / 33 tests / 30.0 pts |
-| os-integration | 7 specs / 29 tests / 24.8 pts | 14 specs / 26 tests / 15.3 pts | 2 specs / 12 tests / 8.7 pts |
+| os-integration | 7 specs / 30 tests / 25.5 pts | 14 specs / 27 tests / 16.0 pts | 2 specs / 13 tests / 9.4 pts |
| performance | 2 specs / 44 tests / 44.0 pts | 4 specs / 34 tests / 30.5 pts | 1 specs / 29 tests / 29.0 pts |
| pipes | 6 specs / 19 tests / 19.0 pts | 8 specs / 25 tests / 25.0 pts | 6 specs / 19 tests / 19.0 pts |
| real-ui-e2e | 60 specs / 178 tests / 148.0 pts | 71 specs / 179 tests / 148.6 pts | 55 specs / 153 tests / 133.2 pts |
| settings | 14 specs / 38 tests / 35.0 pts | 16 specs / 33 tests / 28.7 pts | 13 specs / 30 tests / 27.0 pts |
| storage-privacy | 9 specs / 40 tests / 31.3 pts | 9 specs / 26 tests / 25.1 pts | 6 specs / 19 tests / 18.1 pts |
-| tauri-command | 18 specs / 49 tests / 38.4 pts | 25 specs / 57 tests / 43.8 pts | 17 specs / 48 tests / 37.4 pts |
+| tauri-command | 18 specs / 50 tests / 39.1 pts | 25 specs / 58 tests / 44.5 pts | 17 specs / 49 tests / 38.1 pts |
| window-lifecycle | 18 specs / 63 tests / 53.0 pts | 18 specs / 44 tests / 31.4 pts | 13 specs / 39 tests / 29.9 pts |
## Critical Feature Matrix
@@ -100,7 +100,7 @@ pass/fail/skip counts.
| Spec | Platforms | Layers | Features | Criticality | Confidence | UX | Tests | Notes |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
-| acp-backend.spec.ts | windows, macos, linux | chat-ai, tauri-command, os-integration | chat, acp-backend, agent-streaming, agent-permissions, agent-cancellation, agent-terminal, mcp-registration, process-supervision | high | partial | mixed | 11 | Official Rust ACP SDK runtime and inline UI E2E with a deterministic stdio agent: initialization, session close, streaming, background permissions, cancellation, localized auth/cancel, malformed stdout, exact adapter/descendant reaping, terminal lifecycle/output draining, and a real authenticated local API MCP health call. Curated third-party adapters remain manual smoke coverage. |
+| acp-backend.spec.ts | windows, macos, linux | chat-ai, tauri-command, os-integration | chat, acp-backend, agent-streaming, agent-permissions, agent-cancellation, agent-terminal, mcp-registration, process-supervision | high | partial | mixed | 12 | Official Rust ACP SDK runtime and inline UI E2E with a deterministic stdio agent: initialization, session close, streaming, background permissions, cancellation, localized auth/cancel, malformed stdout, exact adapter/descendant reaping, terminal lifecycle/output draining, and a real authenticated local API MCP health call. Curated third-party adapters remain manual smoke coverage. |
| acp-onboarding-ux.spec.ts | windows, macos, linux | chat-ai, real-ui-e2e, tauri-command | chat, acp-backend, acp-onboarding, acp-auth | high | partial | real-user-flow | 2 | Selecting an ACP agent connects it with nothing sent (sign-in surfaces before the first send, not after a cold install), and the settings picker states who owns sign-in/models/API keys next to the agent list. |
| api-key-cold-spawn.spec.ts | windows, macos, linux | local-api, tauri-command | local-api-auth, app-launch | medium | partial | command | 3 | Cold-spawn local API config regression coverage. |
| api-search-stress.spec.ts | windows, macos, linux | local-api, performance | local-api-auth, local-api-search, health, audio-device-health, local-api-load | high | strong | api | 29 | Broad readonly API, auth, search, and load coverage. |
diff --git a/apps/screenpipe-app-tauri/e2e/specs/acp-backend.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/acp-backend.spec.ts
index 583798217..940e852bf 100644
--- a/apps/screenpipe-app-tauri/e2e/specs/acp-backend.spec.ts
+++ b/apps/screenpipe-app-tauri/e2e/specs/acp-backend.spec.ts
@@ -56,6 +56,7 @@ let mcpSession = "";
let terminalSession = "";
let subagentSession = "";
let resumeSession = "";
+let orphanedPresetSession = "";
let treeMarkerPrefix = "";
let treeMarkerToken = "";
@@ -71,6 +72,7 @@ function resetRunIdentifiers(): void {
terminalSession = randomUUID();
subagentSession = randomUUID();
resumeSession = randomUUID();
+ orphanedPresetSession = randomUUID();
treeMarkerPrefix = path.join(os.tmpdir(), `screenpipe-acp-process-${treeSession}`);
treeMarkerToken = randomUUID();
}
@@ -939,6 +941,36 @@ describe("ACP backend", function () {
expect(info.running).toBe(false);
});
+ it("refuses a coding-agent preset that lost its ACP backend instead of charging the cloud", async () => {
+ // The exact shape an ACP-unaware build leaves behind: the preset still
+ // names its agent in `model`, but `backend`/`acpAgent` are gone, so this
+ // lands on the raw-Pi spawn path. That path used to answer an unmapped
+ // provider with "screenpipe", which sent the agent id to the gateway as a
+ // model name; the resulting 403 was rendered as "upgrade to Screenpipe
+ // Business" on accounts that already held the plan.
+ const startupError = await invokeOrThrow<string>("plugin:e2e|capture_pi_start_error", {
+ sessionId: orphanedPresetSession,
+ projectDir: path.join(os.tmpdir(), `screenpipe-acp-e2e-${orphanedPresetSession}`),
+ providerConfig: {
+ provider: "acp",
+ url: "",
+ model: "codex-acp",
+ apiKey: null,
+ maxTokens: 4096,
+ systemPrompt: null,
+ },
+ });
+ expect(startupError).toContain("Re-select the agent in Settings");
+ expect(startupError.toLowerCase()).not.toContain("upgrade");
+
+ // Nothing may be left running: the old behaviour spawned a real Pi child
+ // pointed at the cloud gateway.
+ const info = await invokeOrThrow<{ running: boolean }>("pi_info", {
+ sessionId: orphanedPresetSession,
+ });
+ expect(info.running).toBe(false);
+ });
+
it("routes agent-managed authentication through the existing inline UI response path", async () => {
await foregroundChat(authSession);
await beginAcpStart(authSession, "auth");
diff --git a/apps/screenpipe-app-tauri/lib/chat/__tests__/quota-errors.test.ts b/apps/screenpipe-app-tauri/lib/chat/__tests__/quota-errors.test.ts
index 68c57bc21..c598a5e8b 100644
--- a/apps/screenpipe-app-tauri/lib/chat/__tests__/quota-errors.test.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/__tests__/quota-errors.test.ts
@@ -11,6 +11,7 @@ import {
buildHostedBusyFinalMessage,
buildHostedBusyMessage,
buildHostedBusyRetryMessage,
+ buildModelNotAllowedMessage,
classifyQuotaError,
buildRateLimitMessage,
parseRateLimitWaitSeconds,
@@ -447,3 +448,73 @@ describe("presentQuotaError", () => {
});
});
+
+describe("buildModelNotAllowedMessage", () => {
+ // The real 403 that made a Business account read "upgrade to Business":
+ // required_plan and upgrade_url are both null because no plan unlocks a
+ // model id that does not exist.
+ const GATEWAY_403 = JSON.stringify({
+ error: "model_not_allowed",
+ message:
+ 'Model "codex-acp" is not available through screenpipe cloud. Choose another model or use your own provider key.',
+ plan: "business",
+ required_plan: null,
+ upgrade_url: null,
+ byok_supported: true,
+ });
+
+ it("never sells a plan the gateway did not ask for", () => {
+ const msg = buildModelNotAllowedMessage(GATEWAY_403);
+ expect(msg).not.toMatch(/upgrade/i);
+ expect(msg).not.toMatch(/business/i);
+ });
+
+ it("names the rejected model and the ways out", () => {
+ const msg = buildModelNotAllowedMessage(GATEWAY_403);
+ expect(msg).toContain('"codex-acp" isn\'t available');
+ expect(msg).toContain("Switch to Auto");
+ expect(msg).toContain("Settings → AI presets");
+ });
+
+ it("survives an escaped body and a body with no model name", () => {
+ expect(buildModelNotAllowedMessage(JSON.stringify(`403 ${GATEWAY_403}`))).toContain(
+ '"codex-acp" isn\'t available',
+ );
+ expect(
+ buildModelNotAllowedMessage('{"error":"model_not_allowed"}'),
+ ).toContain("This model isn't available");
+ });
+
+ it("offers the upgrade only when the gateway supplies a validated one", () => {
+ const msg = buildModelNotAllowedMessage(
+ JSON.stringify({
+ error: "model_not_allowed",
+ message: 'Model "claude-opus-5" is not available through screenpipe cloud.',
+ required_plan: "business",
+ upgrade_url: "https://screenpi.pe/account/billing",
+ }),
+ );
+ expect(msg).toBe(
+ "This model needs the Business plan. Switch to Auto to keep going, or upgrade.",
+ );
+ });
+
+ it("ignores an upgrade url that is not screenpipe billing", () => {
+ const msg = buildModelNotAllowedMessage(
+ JSON.stringify({
+ error: "model_not_allowed",
+ required_plan: "business",
+ upgrade_url: "https://evil.example.com/account/billing",
+ }),
+ );
+ expect(msg).not.toMatch(/upgrade/i);
+ });
+
+ it("caps a hostile model name instead of pasting it into the transcript", () => {
+ const msg = buildModelNotAllowedMessage(
+ `{"message":"Model \\"${"x".repeat(500)}\\" is not available"}`,
+ );
+ expect(msg).toContain("This model isn't available");
+ expect(msg.length).toBeLessThan(300);
+ });
+});
diff --git a/apps/screenpipe-app-tauri/lib/chat/quota-errors.ts b/apps/screenpipe-app-tauri/lib/chat/quota-errors.ts
index 7cc5cded7..d0961b6e2 100644
--- a/apps/screenpipe-app-tauri/lib/chat/quota-errors.ts
+++ b/apps/screenpipe-app-tauri/lib/chat/quota-errors.ts
@@ -156,6 +156,42 @@ export function parseQuotaUpgradeAction(
});
}
+/**
+ * The rejected model id, read from the gateway's own prose (`Model "x" is not
+ * available…`) because the body carries no dedicated field for it. Bounded so a
+ * hostile or malformed body can't paste an essay into the chat transcript.
+ */
+function modelNotAllowedName(errorStr: string): string | null {
+ // Pi may hand this body over raw, escaped once, or escaped twice depending on
+ // how many JSON hops it took, so the quotes are matched with any amount of
+ // backslash in front of them rather than unescaping first.
+ return errorStr.match(/model\s+\\*"([^"\\]{1,64})\\*"/i)?.[1] ?? null;
+}
+
+/**
+ * Copy for a `model_not_allowed` rejection.
+ *
+ * This used to be one hardcoded "upgrade to Screenpipe Business" string, which
+ * is wrong for most of the cases that reach it. The gateway sends
+ * `required_plan: null` when no plan unlocks the model — a Business account
+ * asking for a model id that does not exist gets told to buy the plan it is
+ * already on. Only claim an upgrade when the gateway actually offers one.
+ */
+export function buildModelNotAllowedMessage(errorStr: string): string {
+ const upgrade = validateQuotaUpgradeAction({
+ requiredPlan: structuredString(errorStr, "required_plan"),
+ upgradeUrl: structuredString(errorStr, "upgrade_url"),
+ });
+ if (upgrade) {
+ const plan = QUOTA_PLAN_LABELS[upgrade.requiredPlan];
+ return `This model needs the ${plan} plan. Switch to Auto to keep going, or upgrade.`;
+ }
+ const named = modelNotAllowedName(errorStr)
+ ? `"${modelNotAllowedName(errorStr)}" isn't`
+ : "This model isn't";
+ return `${named} available on Screenpipe Cloud. Switch to Auto, or use your own provider key. If you picked a coding agent, re-select it in Settings → AI presets.`;
+}
+
export function buildDailyLimitMessage(errorStr: string): string {
try {
const normalized = errorStr.toLowerCase();
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
index 4cf2252db..27b54e5d4 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/pi.rs
@@ -2333,6 +2333,34 @@ fn kill_orphan_pi_processes(managed_alive: bool) {
/// 200ms is enough to detect immediate-exit crashes without delaying first chat.
const PI_READY_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(200);
+/// What a caller sees when an `acp` preset reaches a raw-Pi spawn path.
+pub(crate) const ACP_PRESET_WITHOUT_BACKEND: &str =
+ "This coding-agent preset is missing its agent configuration. Re-select the agent in Settings → AI presets.";
+
+/// Map a preset provider onto Pi's internal registry name.
+///
+/// An `acp` preset has no Pi provider at all: its model calls belong to the
+/// coding agent, not to a Pi provider. Reaching this mapping with `acp` means
+/// the ACP backend was dropped between the preset and the spawn, and the
+/// catch-all used to answer that with "screenpipe" — which sent the *agent id*
+/// ("codex-acp") to the cloud gateway as a model name. The gateway rejected it
+/// as `model_not_allowed`, and the desktop rendered that as "upgrade to
+/// Screenpipe Business": a billing dead end for what is really a broken preset,
+/// on an account that already had the plan. Fail loudly instead of silently
+/// spending someone's hosted allowance on a model id that cannot exist.
+fn pi_registry_provider(provider: &str, url: &str) -> Result<&'static str, String> {
+ Ok(match provider {
+ "openai" => "openai-byok",
+ "openai-chatgpt" => "openai-chatgpt",
+ "native-ollama" => "ollama",
+ "anthropic" => "anthropic-byok",
+ // "custom" requires a valid URL; fall back to screenpipe cloud if missing
+ "custom" if !url.is_empty() => "custom",
+ "acp" => return Err(ACP_PRESET_WITHOUT_BACKEND.to_string()),
+ "screenpipe-cloud" | "pi" | _ => "screenpipe",
+ })
+}
+
/// Resolve a model name for the screenpipe provider.
///
/// The gateway (api.screenpipe.com) is the source of truth for model validation
@@ -2555,16 +2583,11 @@ pub async fn pi_start_inner(
// Determine which Pi provider and model to use
let (pi_provider, pi_model) = match &provider_config {
+ // An ACP session's model calls belong to the adapter, so there is no Pi
+ // provider to resolve — these values are only used for logging below.
+ Some(config) if use_acp => ("acp".to_string(), config.model.clone()),
Some(config) => {
- let provider_name = match config.provider.as_str() {
- "openai" => "openai-byok",
- "openai-chatgpt" => "openai-chatgpt",
- "native-ollama" => "ollama",
- "anthropic" => "anthropic-byok",
- // "custom" requires a valid URL; fall back to screenpipe cloud if missing
- "custom" if !config.url.is_empty() => "custom",
- "screenpipe-cloud" | "pi" | _ => "screenpipe",
- };
+ let provider_name = pi_registry_provider(&config.provider, &config.url)?;
let model = resolve_pi_model(&config.model, provider_name);
(provider_name.to_string(), model)
}
@@ -4198,17 +4221,10 @@ pub async fn pi_set_model(
) -> Result<(), String> {
let sid = session_id.unwrap_or_else(|| "chat".to_string());
- // Map frontend provider name → Pi's internal registry name. Must stay in
- // sync with the mapping in `pi_start_inner` (line ~1045) — a mismatch
- // means Pi can't find the model and returns "Model not found".
- let pi_provider = match provider_config.provider.as_str() {
- "openai" => "openai-byok",
- "openai-chatgpt" => "openai-chatgpt",
- "native-ollama" => "ollama",
- "anthropic" => "anthropic-byok",
- "custom" if !provider_config.url.is_empty() => "custom",
- "screenpipe-cloud" | "pi" | _ => "screenpipe",
- };
+ // Map frontend provider name → Pi's internal registry name. Shared with
+ // `pi_start_inner` so the two can't drift — a mismatch means Pi can't find
+ // the model and returns "Model not found".
+ let pi_provider = pi_registry_provider(&provider_config.provider, &provider_config.url)?;
let pi_model = resolve_pi_model(&provider_config.model, pi_provider);
let queue = {
@@ -6804,7 +6820,8 @@ error: InstallFailed extracting tarball"#;
// -- build_models_json tests --
use super::{
- build_models_json, build_models_json_with_api_url, resolve_pi_model, PiProviderConfig,
+ build_models_json, build_models_json_with_api_url, pi_registry_provider, resolve_pi_model,
+ PiProviderConfig, ACP_PRESET_WITHOUT_BACKEND,
};
fn make_provider_config(provider: &str, model: &str) -> PiProviderConfig {
@@ -6866,6 +6883,42 @@ error: InstallFailed extracting tarball"#;
);
}
+ /// An `acp` preset that lost its backend must never be answered with the
+ /// cloud provider. That silent fallback sent the *agent id* to the gateway
+ /// as a model name, and the 403 surfaced as "upgrade to Screenpipe
+ /// Business" on accounts that already had the plan.
+ #[test]
+ fn acp_provider_never_falls_back_to_the_cloud() {
+ let error =
+ pi_registry_provider("acp", "").expect_err("acp must not resolve to a provider");
+ assert_eq!(error, ACP_PRESET_WITHOUT_BACKEND);
+ assert!(pi_registry_provider("acp", "https://example.com/v1").is_err());
+ }
+
+ #[test]
+ fn known_providers_still_map_as_before() {
+ assert_eq!(pi_registry_provider("openai", "").unwrap(), "openai-byok");
+ assert_eq!(
+ pi_registry_provider("openai-chatgpt", "").unwrap(),
+ "openai-chatgpt"
+ );
+ assert_eq!(pi_registry_provider("native-ollama", "").unwrap(), "ollama");
+ assert_eq!(
+ pi_registry_provider("anthropic", "").unwrap(),
+ "anthropic-byok"
+ );
+ assert_eq!(
+ pi_registry_provider("custom", "http://localhost:11434/v1").unwrap(),
+ "custom"
+ );
+ // custom without a URL keeps its long-standing cloud fallback
+ assert_eq!(pi_registry_provider("custom", "").unwrap(), "screenpipe");
+ assert_eq!(
+ pi_registry_provider("screenpipe-cloud", "").unwrap(),
+ "screenpipe"
+ );
+ }
+
#[tokio::test]
async fn test_build_models_json_with_user_token() {
let config = build_models_json(Some("tok_abc123"), None).await;
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/store.rs b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
index 4ab7a4d8a..d5030e8b2 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/store.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/store.rs
@@ -1647,6 +1647,7 @@ impl SettingsStore {
if let Some(presets) = obj.get_mut("aiPresets") {
if let Some(arr) = presets.as_array_mut() {
for preset in arr.iter_mut() {
+ Self::repair_orphaned_acp_preset(preset);
if let Some(provider) = preset.get("provider").and_then(|p| p.as_str()) {
if !known_providers.contains(&provider) {
tracing::warn!(
@@ -1668,6 +1669,59 @@ impl SettingsStore {
val
}
+ /// Give a coding-agent preset its `acp` provider back.
+ ///
+ /// The unknown-provider fallback above rewrites `provider` in place and
+ /// leaves everything else alone. Any build predating ACP (`acp` reached
+ /// this allow-list on 2026-08-07) therefore turned a working coding-agent
+ /// preset into `provider: "custom"` with no URL, permanently — the agent id
+ /// survived in `model`, so the desktop then asked the cloud gateway for a
+ /// model literally named "codex-acp" and showed the 403 as "upgrade to
+ /// Screenpipe Business". One downgrade, or one older build opening the
+ /// store, was enough.
+ ///
+ /// The signature is deliberately narrow: an agent config, a model that is
+ /// still exactly that agent's id, and no URL. Switching a preset away from
+ /// a coding agent in the editor always rewrites `model` (cloud → "auto",
+ /// chatgpt → "gpt-5.6-terra") or sets a URL (ollama, custom), so a
+ /// deliberate choice can never match this and get flipped back.
+ fn repair_orphaned_acp_preset(preset: &mut Value) {
+ let Some(obj) = preset.as_object_mut() else {
+ return;
+ };
+ if obj.get("provider").and_then(|p| p.as_str()) == Some("acp") {
+ return;
+ }
+ let agent_id = obj
+ .get("acpAgent")
+ .and_then(|agent| agent.get("id"))
+ .and_then(|id| id.as_str())
+ .map(str::trim)
+ .filter(|id| !id.is_empty())
+ .map(str::to_owned);
+ let Some(agent_id) = agent_id else {
+ return;
+ };
+ if obj.get("model").and_then(|m| m.as_str()).map(str::trim) != Some(agent_id.as_str()) {
+ return;
+ }
+ let url_is_empty = obj
+ .get("url")
+ .map(|url| url.as_str().map(str::trim).unwrap_or("").is_empty())
+ .unwrap_or(true);
+ if !url_is_empty {
+ return;
+ }
+ tracing::warn!(
+ "restoring 'acp' provider for coding-agent preset '{}' (was '{}')",
+ agent_id,
+ obj.get("provider")
+ .and_then(|p| p.as_str())
+ .unwrap_or("none")
+ );
+ obj.insert("provider".to_string(), Value::String("acp".to_string()));
+ }
+
pub fn get(app: &AppHandle) -> Result<Option<Self>, String> {
let store = get_store(app, None).map_err(|e| format!("Failed to get store: {}", e))?;
@@ -3706,6 +3760,66 @@ mod tests {
assert_eq!(preset["acpAgent"]["id"].as_str(), Some("codex-acp"));
}
+ /// The exact shape an ACP-unaware build leaves behind: provider rewritten
+ /// to "custom", no URL, agent id still sitting in `model`. Without the
+ /// repair the desktop asks the cloud gateway for a model named "codex-acp"
+ /// and shows the 403 as "upgrade to Screenpipe Business".
+ #[test]
+ fn orphaned_acp_preset_gets_its_provider_back() {
+ let downgraded = json!({
+ "aiPresets": [{
+ "id": "codex",
+ "provider": "custom",
+ "url": "",
+ "model": "codex-acp",
+ "acpAgent": {"id": "codex-acp"}
+ }]
+ });
+
+ let repaired = SettingsStore::sanitize_legacy_fields(downgraded);
+ let preset = &repaired["aiPresets"][0];
+ assert_eq!(preset["provider"].as_str(), Some("acp"));
+ assert_eq!(preset["acpAgent"]["id"].as_str(), Some("codex-acp"));
+ assert_eq!(preset["model"].as_str(), Some("codex-acp"));
+ }
+
+ /// A preset the user deliberately moved off a coding agent keeps a stale
+ /// `acpAgent` (the editor never clears it) but always gets a new model or a
+ /// URL. Neither may be dragged back onto the ACP backend.
+ #[test]
+ fn deliberate_non_acp_presets_are_left_alone() {
+ let intentional = json!({
+ "aiPresets": [
+ {
+ // switched to cloud: editor rewrote the model
+ "provider": "screenpipe-cloud",
+ "url": "",
+ "model": "auto",
+ "acpAgent": {"id": "codex-acp"}
+ },
+ {
+ // switched to ollama: editor set a URL, model kept
+ "provider": "native-ollama",
+ "url": "http://localhost:11434/v1",
+ "model": "codex-acp",
+ "acpAgent": {"id": "codex-acp"}
+ },
+ {
+ // never an ACP preset at all
+ "provider": "custom",
+ "url": "",
+ "model": "my-model"
+ }
+ ]
+ });
+
+ let sanitized = SettingsStore::sanitize_legacy_fields(intentional);
+ let presets = sanitized["aiPresets"].as_array().unwrap();
+ assert_eq!(presets[0]["provider"].as_str(), Some("screenpipe-cloud"));
+ assert_eq!(presets[1]["provider"].as_str(), Some("native-ollama"));
+ assert_eq!(presets[2]["provider"].as_str(), Some("custom"));
+ }
+
#[test]
fn test_deserialize_settings_with_null_fields() {
let json_data = json!({