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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(connections): allow connecting when every field is optional (#6351)
Christian Couder4b0d119fd045
diff --git a/apps/screenpipe-app-tauri/components/settings/__tests__/connection-credential-forms.test.tsx b/apps/screenpipe-app-tauri/components/settings/__tests__/connection-credential-forms.test.tsxindex 248833f41..e32f71c5a 100644--- a/apps/screenpipe-app-tauri/components/settings/__tests__/connection-credential-forms.test.tsx+++ b/apps/screenpipe-app-tauri/components/settings/__tests__/connection-credential-forms.test.tsx@@ -4,7 +4,7 @@import React from "react";import { beforeEach, describe, expect, it, vi } from "vitest";-import { render, screen, waitFor } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";import { ApiIntegrationPanel } from "@/components/settings/connections-section";import { ConnectSection } from "@/components/settings/agent-card";@@ -47,6 +47,28 @@ vi.mock("@/components/ui/use-toast", () => ({const jsonResponse = (data: unknown) =>Promise.resolve({ ok: true, json: async () => data } as Response);+/// Shape shared by Claude Code, Codex and OpenCode: exactly one field, marked+/// optional, meant to fall back to a default when left blank.+const optionalOnlyIntegration = {+ id: "opencode",+ name: "OpenCode",+ icon: "opencode",+ category: "productivity",+ description: "test",+ fields: [+ {+ key: "home_path",+ label: "OpenCode config directory (optional)",+ secret: false,+ placeholder: "~/.config/opencode",+ help_url: "",+ },+ ],+ connected: false,+ is_oauth: false,+ supports_oauth_instances: false,+};+beforeEach(() => {mocks.localFetch.mockReset();});@@ -138,4 +160,88 @@ describe("connection credential forms", () => {expect(screen.queryByDisplayValue("secret-sentinel")).toBeNull();expect(screen.queryByDisplayValue("unknown-sentinel")).toBeNull();});++ /// An integration whose only field is optional must still be connectable+ /// with that field left blank. Claude Code, Codex and OpenCode each expose a+ /// single `home_path (optional)` that is meant to fall back to a default, so+ /// gating "connect" on "some field is non-empty" left them permanently+ /// unconnectable unless the user typed a path they did not need to supply.+ it("keeps connect enabled when every field is optional", async () => {+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.endsWith("/instances")) return jsonResponse({ instances: [] });+ return jsonResponse({ connected: false, credentials: {} });+ });++ render(+ <ApiIntegrationPanel+ integration={optionalOnlyIntegration}+ onRefresh={vi.fn()}+ />+ );++ const connect = await screen.findByRole("button", { name: /^connect$/i });+ expect((connect as HTMLButtonElement).disabled).toBe(false);+ });++ /// The blank optional field must still be *sent*. The backend treats an+ /// empty credentials map as not-connected (`enabled && !credentials+ /// .is_empty()` in ConnectionManager::list), so omitting never-typed-into+ /// keys would save `{}` and read back as disconnected — the button would+ /// unlock but connecting still would not stick.+ it("sends blank optional fields so the saved credentials map is non-empty", async () => {+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.endsWith("/instances")) return jsonResponse({ instances: [] });+ return jsonResponse({ connected: false, credentials: {} });+ });++ render(+ <ApiIntegrationPanel+ integration={optionalOnlyIntegration}+ onRefresh={vi.fn()}+ />+ );++ fireEvent.click(await screen.findByRole("button", { name: /^connect$/i }));++ await waitFor(() => {+ const put = mocks.localFetch.mock.calls.find(+ ([, init]) => (init as RequestInit | undefined)?.method === "PUT"+ );+ expect(put).toBeTruthy();+ expect(JSON.parse((put![1] as RequestInit).body as string)).toEqual({+ credentials: { home_path: "" },+ });+ });+ });++ /// The guard must not swing the other way: a field with no "(optional)"+ /// marker is required, and blank required fields still block connect.+ it("keeps connect disabled while a required field is blank", async () => {+ mocks.localFetch.mockImplementation((url: string) => {+ if (url.endsWith("/instances")) return jsonResponse({ instances: [] });+ return jsonResponse({ connected: false, credentials: {} });+ });++ render(+ <ApiIntegrationPanel+ integration={{+ ...optionalOnlyIntegration,+ id: "needs-a-key",+ fields: [+ {+ key: "api_key",+ label: "API Key",+ secret: true,+ placeholder: "sk-...",+ help_url: "",+ },+ ],+ }}+ onRefresh={vi.fn()}+ />+ );++ const connect = await screen.findByRole("button", { name: /^connect$/i });+ expect((connect as HTMLButtonElement).disabled).toBe(true);+ });});diff --git a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx b/apps/screenpipe-app-tauri/components/settings/connections-section.tsxindex bc9d1eeb7..e40720a0a 100644--- a/apps/screenpipe-app-tauri/components/settings/connections-section.tsx+++ b/apps/screenpipe-app-tauri/components/settings/connections-section.tsx@@ -2518,6 +2518,17 @@ export interface IntegrationInfo {// Reusable credential form for a single connection instance// ---------------------------------------------------------------------------+// Fields are conventionally labeled "... (optional)" (see FieldDef instances+// across crates/screenpipe-connect) — there's no machine-readable+// required/optional flag on the wire, so this mirrors that convention. Used+// to (a) let "connect" be clickable with every optional field left blank+// (e.g. OpenCode/Claude Code/Codex's home-directory field, meant to fall+// back to a default) and (b) decide which fields must be non-empty before+// the button unlocks.+function isOptionalField(field: IntegrationField): boolean {+ return /\(optional\b/i.test(field.label);+}+export function ConnectionCredentialForm({integrationId,fields,@@ -2566,18 +2577,26 @@ export function ConnectionCredentialForm({const handleConnect = async () => {setStatus("connecting");setError(null);+ // Always send every field's key, defaulting unset ones to "" — this+ // guarantees a non-empty credentials map even when every field is an+ // untouched optional default (e.g. OpenCode's home directory), matching+ // the backend's `enabled && !credentials.is_empty()` definition of+ // "connected" (ConnectionManager::list). Sending `creds` as-is would omit+ // never-typed-into keys entirely, saving `{}` — which the backend (and+ // this form, post-fix) would then read back as NOT connected.+ const credsToSend = Object.fromEntries(fields.map(f => [f.key, creds[f.key] ?? ""]));try {const testRes = await localFetch(`/connections/${integrationId}/test`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ credentials: creds }),+ body: JSON.stringify({ credentials: credsToSend }),});const testData = await testRes.json();if (!testRes.ok || testData.error) throw new Error(testData.error || "connection test failed");const saveRes = await localFetch(endpoint, {method: "PUT",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ credentials: creds }),+ body: JSON.stringify({ credentials: credsToSend }),});const saveData = await saveRes.json();if (!saveRes.ok || saveData.error) throw new Error(saveData.error || "save failed");@@ -2611,7 +2630,14 @@ export function ConnectionCredentialForm({}};- const hasCredentials = Object.values(creds).some(v => !!v);+ // "connect" unlocks once every non-optional field has a value. A field+ // marked "(optional)" — e.g. OpenCode's config directory — is allowed to+ // stay blank forever; the button must not sit permanently disabled just+ // because the user accepted the default, or the field's own "optional"+ // label would be a lie.+ const missingRequiredField = fields.some(+ (f) => !isOptionalField(f) && !(creds[f.key] || "").trim()+ );return (<div className="space-y-3">@@ -2661,7 +2687,7 @@ export function ConnectionCredentialForm({{error && <p className="text-xs text-destructive">{error}</p>}<div className="flex gap-2">{!isSaved && (- <Button onClick={handleConnect} disabled={!hasCredentials || status === "connecting"} variant={status === "error" ? "outline" : "default"} size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal">+ <Button onClick={handleConnect} disabled={missingRequiredField || status === "connecting"} variant={status === "error" ? "outline" : "default"} size="sm" className="gap-1.5 h-7 text-xs normal-case font-sans tracking-normal">{status === "connecting" ? (<><Loader2 className="h-3 w-3 animate-spin" />connecting...</>): status === "error" ? (<>retry</>): (<><Check className="h-3 w-3" />connect</>)}