- {field?.label || humanizeKey(key)}: {clearing ? "will be cleared" : "saved"}
+ {field?.label || humanizeConfigKey(key)}: {clearing ? "will be cleared" : "saved"}
{required ? " (required)" : ""}
{!required ? (
diff --git a/web/src/components/admin/plugins/SchemaForm.test.tsx b/web/src/components/admin/plugins/SchemaForm.test.tsx
index 3c13a9a5689..f2383248cf1 100644
--- a/web/src/components/admin/plugins/SchemaForm.test.tsx
+++ b/web/src/components/admin/plugins/SchemaForm.test.tsx
@@ -98,6 +98,32 @@ describe("SchemaForm", () => {
"true",
);
});
+ it("uses a controlling field default when rendering a conditional field", () => {
+ const d: PluginAdminForm = {
+ fields: [
+ {
+ key: "advanced_enabled",
+ label: "Advanced",
+ control: "SWITCH",
+ required: false,
+ secret: false,
+ multiline: false,
+ default_value: true,
+ },
+ {
+ key: "endpoint",
+ label: "Endpoint",
+ control: "TEXT",
+ required: false,
+ secret: false,
+ multiline: false,
+ show_when: [{ field: "advanced_enabled", equals: ["true"] }],
+ },
+ ],
+ };
+ render(
);
+ expect(screen.getByText("Endpoint")).toBeTruthy();
+ });
it("reports validity through onValidityChange (#14)", () => {
const onValidityChange = vi.fn();
const d: PluginAdminForm = {
@@ -193,6 +219,43 @@ describe("SchemaForm collapsible sections", () => {
fireEvent.click(screen.getByText("Show"));
expect(screen.getByText("Verbose")).toBeTruthy();
});
+
+ it("uses a controlling field default when rendering a conditional section", () => {
+ const d: PluginAdminForm = {
+ fields: [
+ {
+ key: "advanced_enabled",
+ label: "Advanced",
+ control: "SWITCH",
+ required: false,
+ secret: false,
+ multiline: false,
+ default_value: true,
+ },
+ {
+ key: "endpoint",
+ label: "Endpoint",
+ control: "TEXT",
+ required: false,
+ secret: false,
+ multiline: false,
+ },
+ ],
+ sections: [
+ {
+ key: "advanced",
+ title: "Advanced options",
+ collapsible: false,
+ collapsed_default: false,
+ field_keys: ["endpoint"],
+ show_when: [{ field: "advanced_enabled", equals: ["true"] }],
+ },
+ ],
+ };
+ render(
);
+ expect(screen.getByText("Advanced options")).toBeTruthy();
+ expect(screen.getByText("Endpoint")).toBeTruthy();
+ });
});
it("marks a show_when-gated field as nested when it is revealed", () => {
diff --git a/web/src/components/admin/plugins/SchemaForm.tsx b/web/src/components/admin/plugins/SchemaForm.tsx
index b84bd55abd3..590209c3e97 100644
--- a/web/src/components/admin/plugins/SchemaForm.tsx
+++ b/web/src/components/admin/plugins/SchemaForm.tsx
@@ -97,11 +97,13 @@ function ChipsSkeleton() {
function SchemaFormSection({
section,
values,
+ fields,
forceOpen,
renderFields,
}: {
section: PluginAdminFormSection;
values: Record
;
+ fields: PluginAdminFormField[];
forceOpen: boolean;
renderFields: (keys: string[]) => React.ReactNode;
}) {
@@ -109,7 +111,7 @@ function SchemaFormSection({
// (the section has unresolved errors) always wins so setup can't be hidden.
const [userOpen, setUserOpen] = useState(null);
- if (!evaluateShowWhen(section.show_when, values)) {
+ if (!evaluateShowWhen(section.show_when, values, fields)) {
return null;
}
@@ -331,7 +333,9 @@ export function SchemaForm({
// bordered, divided container so toggles read as a cohesive group instead of
// a column of separate boxes. Honors show_when on each field.
function renderFieldList(fields: PluginAdminFormField[]): React.ReactNode {
- const visible = fields.filter((field) => evaluateShowWhen(field.show_when, values));
+ const visible = fields.filter((field) =>
+ evaluateShowWhen(field.show_when, values, descriptor.fields),
+ );
const nodes: React.ReactNode[] = [];
let run: PluginAdminFormField[] = [];
// Key switch groups by their position in the list, not by their first
@@ -389,6 +393,7 @@ export function SchemaForm({
key={section.key}
section={section}
values={values}
+ fields={descriptor.fields}
forceOpen={section.field_keys.some((key) => mergedErrors[key] != null)}
renderFields={(keys) => renderFieldList(resolveKeys(keys))}
/>
diff --git a/web/src/components/admin/plugins/configSchemaAdminForm.test.ts b/web/src/components/admin/plugins/configSchemaAdminForm.test.ts
new file mode 100644
index 00000000000..636d96c2a38
--- /dev/null
+++ b/web/src/components/admin/plugins/configSchemaAdminForm.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it } from "vitest";
+
+import type { PluginConfigSchema } from "@/api/types";
+
+import { adminFormForConfigSchema } from "./configSchemaAdminForm";
+
+function schema(overrides: Partial = {}): PluginConfigSchema {
+ return {
+ key: "connection",
+ title: "Connection",
+ json_schema: JSON.stringify({
+ type: "object",
+ properties: {},
+ additionalProperties: false,
+ }),
+ required: true,
+ ...overrides,
+ };
+}
+
+describe("adminFormForConfigSchema", () => {
+ it("preserves primitive JSON Schema defaults on inferred fields", () => {
+ const form = adminFormForConfigSchema(
+ schema({
+ json_schema: JSON.stringify({
+ type: "object",
+ properties: {
+ base_url: { type: "string", default: "https://floppy.example.com" },
+ port: { type: "integer", default: 8080 },
+ verify_tls: { type: "boolean", default: true },
+ },
+ }),
+ }),
+ );
+
+ expect(form?.fields.map(({ key, default_value }) => ({ key, default_value }))).toEqual([
+ { key: "base_url", default_value: "https://floppy.example.com" },
+ { key: "port", default_value: 8080 },
+ { key: "verify_tls", default_value: true },
+ ]);
+ });
+
+ it("adds scalar schema properties omitted by a partial admin form", () => {
+ const form = adminFormForConfigSchema(
+ schema({
+ json_schema: JSON.stringify({
+ type: "object",
+ properties: {
+ base_url: { type: "string" },
+ username: { type: "string" },
+ },
+ required: ["base_url", "username"],
+ }),
+ admin_form: {
+ fields: [
+ {
+ key: "base_url",
+ label: "Custom URL",
+ control: "TEXT",
+ required: true,
+ secret: false,
+ multiline: false,
+ },
+ ],
+ },
+ }),
+ );
+
+ expect(form?.fields.map(({ key, label, required }) => ({ key, label, required }))).toEqual([
+ { key: "base_url", label: "Custom URL", required: true },
+ { key: "username", label: "Username", required: true },
+ ]);
+ });
+
+ it("preserves an explicit form when its schema cannot be inferred", () => {
+ const explicit = {
+ fields: [
+ {
+ key: "api_key",
+ label: "API Key",
+ control: "PASSWORD" as const,
+ required: true,
+ secret: true,
+ multiline: false,
+ },
+ ],
+ };
+ expect(adminFormForConfigSchema(schema({ json_schema: "", admin_form: explicit }))).toBe(
+ explicit,
+ );
+ });
+
+ it("applies JSON Schema sensitivity to matching explicit fields", () => {
+ const form = adminFormForConfigSchema(
+ schema({
+ json_schema: JSON.stringify({
+ type: "object",
+ properties: {
+ api_key: { type: "string", writeOnly: true },
+ password: { type: "string", format: "password" },
+ advanced: { type: "object", writeOnly: true },
+ },
+ }),
+ admin_form: {
+ fields: [
+ {
+ key: "api_key",
+ label: "API Key",
+ control: "TEXT",
+ required: false,
+ secret: false,
+ multiline: false,
+ },
+ {
+ key: "password",
+ label: "Password",
+ control: "TEXT",
+ required: false,
+ secret: false,
+ multiline: false,
+ },
+ {
+ key: "advanced",
+ label: "Advanced",
+ control: "TEXTAREA",
+ required: false,
+ secret: false,
+ multiline: true,
+ },
+ ],
+ },
+ }),
+ );
+
+ expect(form?.fields.map(({ key, secret }) => ({ key, secret }))).toEqual([
+ { key: "api_key", secret: true },
+ { key: "password", secret: true },
+ { key: "advanced", secret: true },
+ ]);
+ });
+});
diff --git a/web/src/components/admin/plugins/configSchemaAdminForm.ts b/web/src/components/admin/plugins/configSchemaAdminForm.ts
new file mode 100644
index 00000000000..34e09237b2e
--- /dev/null
+++ b/web/src/components/admin/plugins/configSchemaAdminForm.ts
@@ -0,0 +1,98 @@
+import type { PluginAdminForm, PluginAdminFormField, PluginConfigSchema } from "@/api/types";
+
+export function humanizeConfigKey(value: string) {
+ return value
+ .split("_")
+ .filter(Boolean)
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
+ .join(" ");
+}
+
+export function adminFormForConfigSchema(schema: PluginConfigSchema): PluginAdminForm | null {
+ const explicitFields = schema.admin_form?.fields ?? [];
+ try {
+ const parsed = JSON.parse(schema.json_schema) as {
+ type?: string;
+ required?: string[];
+ properties?: Record<
+ string,
+ {
+ type?: string;
+ title?: string;
+ description?: string;
+ writeOnly?: boolean;
+ format?: string;
+ default?: unknown;
+ }
+ >;
+ };
+ if (parsed.type !== "object" || !parsed.properties) {
+ return explicitFields.length > 0 ? schema.admin_form! : null;
+ }
+
+ const inferredFields = Object.entries(parsed.properties).map(
+ ([key, property]): PluginAdminFormField | null => {
+ const propertyType = property.type;
+ if (!propertyType || !["string", "number", "integer", "boolean"].includes(propertyType)) {
+ return null;
+ }
+ const secret = property.writeOnly === true || property.format === "password";
+ const control =
+ propertyType === "boolean"
+ ? "SWITCH"
+ : propertyType === "number" || propertyType === "integer"
+ ? "NUMBER"
+ : secret
+ ? "PASSWORD"
+ : "TEXT";
+ return {
+ key,
+ label: property.title || humanizeConfigKey(key),
+ description: property.description,
+ control,
+ placeholder: "",
+ required: parsed.required?.includes(key) ?? false,
+ secret,
+ multiline: false,
+ default_value:
+ typeof property.default === "string" ||
+ typeof property.default === "number" ||
+ typeof property.default === "boolean"
+ ? property.default
+ : undefined,
+ options: [],
+ rows: 0,
+ };
+ },
+ );
+
+ if (explicitFields.length > 0) {
+ const explicitKeys = new Set(explicitFields.map((field) => field.key));
+ const sensitiveKeys = new Set(
+ Object.entries(parsed.properties)
+ .filter(([, property]) => property.writeOnly === true || property.format === "password")
+ .map(([key]) => key),
+ );
+ return {
+ ...schema.admin_form,
+ fields: [
+ ...explicitFields.map((field) =>
+ sensitiveKeys.has(field.key) ? { ...field, secret: true } : field,
+ ),
+ ...inferredFields.filter(
+ (field): field is PluginAdminFormField => field != null && !explicitKeys.has(field.key),
+ ),
+ ],
+ };
+ }
+
+ if (inferredFields.some((field) => field == null)) return null;
+
+ return {
+ ...schema.admin_form,
+ fields: inferredFields.filter((field): field is PluginAdminFormField => field != null),
+ };
+ } catch {
+ return explicitFields.length > 0 ? schema.admin_form! : null;
+ }
+}
diff --git a/web/src/components/admin/plugins/schemaFormUtils.test.ts b/web/src/components/admin/plugins/schemaFormUtils.test.ts
index 875a8dd51e8..34f7c9057ac 100644
--- a/web/src/components/admin/plugins/schemaFormUtils.test.ts
+++ b/web/src/components/admin/plugins/schemaFormUtils.test.ts
@@ -172,6 +172,7 @@ describe("parseFieldTypes (#15)", () => {
root_folder: { type: "string" },
tags: { type: "array", items: { type: "integer" } },
labels: { type: "array", items: { type: "string" } },
+ flags: { type: "array", items: { type: "boolean" } },
enabled: { type: "boolean" },
},
});
@@ -180,6 +181,7 @@ describe("parseFieldTypes (#15)", () => {
root_folder: "string",
tags: "array:int",
labels: "array",
+ flags: "array:bool",
enabled: "boolean",
});
});
@@ -443,3 +445,63 @@ describe("coerceFieldValue array:num coercion (CodeRabbit #5)", () => {
expect(coerceFieldValue(numArrayField, ["abc"], "array:num")).toEqual(["abc"]);
});
});
+
+describe("coerceFieldValue array:bool coercion", () => {
+ it("coerces boolean multi-select values using their declared item type", () => {
+ expect(coerceFieldValue(numArrayField, ["true", "false", true], "array:bool")).toEqual([
+ true,
+ false,
+ true,
+ ]);
+ });
+});
+
+describe("section visibility", () => {
+ const sectionDescriptor: PluginAdminForm = {
+ fields: [
+ {
+ key: "advanced_enabled",
+ label: "Advanced",
+ control: "SWITCH",
+ required: false,
+ secret: false,
+ multiline: false,
+ default_value: false,
+ },
+ {
+ key: "endpoint",
+ label: "Endpoint",
+ control: "TEXT",
+ required: true,
+ secret: false,
+ multiline: false,
+ },
+ ],
+ sections: [
+ {
+ key: "advanced",
+ title: "Advanced",
+ collapsible: false,
+ collapsed_default: false,
+ field_keys: ["endpoint"],
+ show_when: [{ field: "advanced_enabled", equals: ["true"] }],
+ },
+ ],
+ };
+
+ it("does not validate required fields in a hidden section", () => {
+ expect(validateSchemaValues(sectionDescriptor, { endpoint: "stale" })).toEqual({});
+ expect(validateSchemaValues(sectionDescriptor, { advanced_enabled: true }).endpoint).toMatch(
+ /required/i,
+ );
+ });
+
+ it("does not persist stale values from a hidden section", () => {
+ expect(buildSchemaValues(sectionDescriptor, { endpoint: "stale" })).toEqual({
+ advanced_enabled: false,
+ });
+ expect(
+ buildSchemaValues(sectionDescriptor, { advanced_enabled: true, endpoint: "active" }),
+ ).toEqual({ advanced_enabled: true, endpoint: "active" });
+ });
+});
diff --git a/web/src/components/admin/plugins/schemaFormUtils.ts b/web/src/components/admin/plugins/schemaFormUtils.ts
index b46287ee8c3..e0eae44d11c 100644
--- a/web/src/components/admin/plugins/schemaFormUtils.ts
+++ b/web/src/components/admin/plugins/schemaFormUtils.ts
@@ -45,7 +45,7 @@ export function validateSchemaValues(
): Record {
const errors: Record = {};
for (const field of descriptor.fields) {
- if (!evaluateShowWhen(field.show_when, values, descriptor.fields)) continue;
+ if (!fieldIsVisible(descriptor, field, values)) continue;
const raw = effectiveValue(field, values);
if (field.required && isEmpty(raw)) {
errors[field.key] = `${field.label || field.key} is required`;
@@ -120,6 +120,7 @@ export type FieldType =
| "number"
| "boolean"
| "array"
+ | "array:bool"
| "array:int"
| "array:num";
@@ -150,6 +151,7 @@ export function parseFieldTypes(jsonSchema: string | undefined | null): Record coerceBoolean(v));
if (fieldType === "array:int") return arr.map((v) => coerceNumericString(v));
return arr.map((v) => coerceNumberString(v));
}
@@ -237,6 +241,23 @@ export function effectiveValue(
return values[field.key] !== undefined ? values[field.key] : field.default_value;
}
+export function fieldIsVisible(
+ descriptor: PluginAdminForm,
+ field: PluginAdminFormField,
+ values: Record,
+): boolean {
+ if (!evaluateShowWhen(field.show_when, values, descriptor.fields)) return false;
+ const containingSections = (descriptor.sections ?? []).filter((section) =>
+ section.field_keys.includes(field.key),
+ );
+ return (
+ containingSections.length === 0 ||
+ containingSections.some((section) =>
+ evaluateShowWhen(section.show_when, values, descriptor.fields),
+ )
+ );
+}
+
export function buildSchemaValues(
descriptor: PluginAdminForm,
draft: Record,
@@ -244,7 +265,7 @@ export function buildSchemaValues(
): Record {
const out: Record = {};
for (const field of descriptor.fields) {
- if (!evaluateShowWhen(field.show_when, draft, descriptor.fields)) continue; // don't persist hidden fields' stale values
+ if (!fieldIsVisible(descriptor, field, draft)) continue; // don't persist hidden fields' stale values
// Fall back to the declared default for untouched fields so an unmodified
// default persists exactly as it is displayed.
const rawSource = draft[field.key] !== undefined ? draft[field.key] : field.default_value;
diff --git a/web/src/hooks/queries/watchProviders.test.ts b/web/src/hooks/queries/watchProviders.test.ts
index 5d8fd89d6ba..aba503c4c87 100644
--- a/web/src/hooks/queries/watchProviders.test.ts
+++ b/web/src/hooks/queries/watchProviders.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
import {
+ connectWatchProviderAPIKey,
fetchWatchProviders,
pollWatchProviderDeviceAuth,
startWatchProviderDeviceAuth,
@@ -42,6 +43,7 @@ vi.mock("@/api/client", () => ({
return {
path,
method: init?.method ?? "GET",
+ body: init?.body,
};
}),
}));
@@ -61,6 +63,18 @@ describe("watch provider queries", () => {
path: "/watch-providers/trakt/auth/poll",
method: "POST",
});
+ await expect(
+ connectWatchProviderAPIKey("plugin:4:floppy", "token", {
+ floppy: { base_url: "https://floppy.example.com" },
+ }),
+ ).resolves.toMatchObject({
+ path: "/watch-providers/plugin:4:floppy/auth/api-key",
+ method: "POST",
+ body: JSON.stringify({
+ api_key: "token",
+ connection_config: { floppy: { base_url: "https://floppy.example.com" } },
+ }),
+ });
await expect(
updateWatchProviderConnection("trakt", { scrobble_enabled: true }),
).resolves.toMatchObject({
diff --git a/web/src/hooks/queries/watchProviders.ts b/web/src/hooks/queries/watchProviders.ts
index 673a66615f5..d282a4178ad 100644
--- a/web/src/hooks/queries/watchProviders.ts
+++ b/web/src/hooks/queries/watchProviders.ts
@@ -3,11 +3,15 @@ import { api, ApiClientError } from "@/api/client";
import { favoriteKeys, watchlistKeys, watchProviderKeys } from "./keys";
import { toast } from "sonner";
import { storage } from "@/utils/storage";
+import type { PluginConfigSchema } from "@/api/types";
+
+export type WatchProviderConnectionConfig = Record>;
export interface WatchProviderSummary {
key: string;
display_name: string;
capabilities: WatchProviderCapabilities;
+ connection_config_schema?: PluginConfigSchema[];
}
export const WatchProviderAuthMethod = {
@@ -52,6 +56,7 @@ export interface WatchProviderConnection {
sync_watchlist_order_enabled: boolean;
scrobble_enabled: boolean;
credentials_configured: boolean;
+ connection_config_schema?: PluginConfigSchema[];
last_inbound_sync_at?: string;
last_progress_sync_at?: string;
last_outbound_sync_at?: string;
@@ -159,10 +164,14 @@ export function pollWatchProviderDeviceAuth(provider: string, authSessionId: str
});
}
-export function connectWatchProviderAPIKey(provider: string, apiKey: string) {
+export function connectWatchProviderAPIKey(
+ provider: string,
+ apiKey: string,
+ connectionConfig: WatchProviderConnectionConfig = {},
+) {
return api(`/watch-providers/${provider}/auth/api-key`, {
method: "POST",
- body: JSON.stringify({ api_key: apiKey }),
+ body: JSON.stringify({ api_key: apiKey, connection_config: connectionConfig }),
});
}
@@ -248,7 +257,13 @@ export function usePollWatchProviderDeviceAuth(provider: string) {
export function useConnectWatchProviderAPIKey(provider: string) {
const queryClient = useQueryClient();
return useMutation({
- mutationFn: (apiKey: string) => connectWatchProviderAPIKey(provider, apiKey),
+ mutationFn: ({
+ apiKey,
+ connectionConfig,
+ }: {
+ apiKey: string;
+ connectionConfig?: WatchProviderConnectionConfig;
+ }) => connectWatchProviderAPIKey(provider, apiKey, connectionConfig),
onSuccess: (connection) => {
const profileId = getActiveProfileId();
queryClient.setQueryData(watchProviderKeys.connection(profileId, provider), connection);
diff --git a/web/src/pages/settings/WatchProvidersSettings.tsx b/web/src/pages/settings/WatchProvidersSettings.tsx
index f2df7e40045..fc966a161fa 100644
--- a/web/src/pages/settings/WatchProvidersSettings.tsx
+++ b/web/src/pages/settings/WatchProvidersSettings.tsx
@@ -33,6 +33,14 @@ import {
} from "@/hooks/queries/watchProviders";
import { Input } from "@/components/ui/input";
import { formatRelativeTime as formatRelativeTimeBase } from "@/lib/date";
+import { SchemaForm } from "@/components/admin/plugins/SchemaForm";
+import type { PluginConfigSchema } from "@/api/types";
+import type { WatchProviderConnectionConfig } from "@/hooks/queries/watchProviders";
+import {
+ buildConnectionConfig,
+ connectionSchemasAreValid,
+ renderableConnectionSchemas,
+} from "./watchProviderConnectionConfig";
function formatRelativeTime(value?: string) {
return formatRelativeTimeBase(value, { rounding: "floor", justNowLabel: "Just now" }) ?? "Never";
@@ -206,17 +214,29 @@ function AuthCodeBlock({
function APIKeyBlock({
displayName,
+ providerKey,
+ configSchemas,
pending,
onSubmit,
onCancel,
}: {
displayName: string;
+ providerKey: string;
+ configSchemas: PluginConfigSchema[];
pending: boolean;
- onSubmit: (apiKey: string) => void;
+ onSubmit: (apiKey: string, connectionConfig: WatchProviderConnectionConfig) => void;
onCancel: () => void;
}) {
const [value, setValue] = useState("");
+ const [connectionConfig, setConnectionConfig] = useState({});
+ const [configValidity, setConfigValidity] = useState>({});
const trimmed = value.trim();
+ const renderableSchemas = renderableConnectionSchemas(configSchemas);
+ const configValid = connectionSchemasAreValid(
+ renderableSchemas,
+ connectionConfig,
+ configValidity,
+ );
return (
@@ -237,6 +257,29 @@ function APIKeyBlock({
+ {renderableSchemas.map((schema) => (
+
+
+
{schema.title || schema.key}
+ {schema.description ? (
+
+ {schema.description}
+
+ ) : null}
+
+
+ setConnectionConfig((current) => ({ ...current, [schema.key]: next }))
+ }
+ idPrefix={`watch-provider-${providerKey}-${schema.key}`}
+ onValidityChange={(valid) =>
+ setConfigValidity((current) => ({ ...current, [schema.key]: valid }))
+ }
+ />
+
+ ))}
onSubmit(trimmed)}
+ disabled={pending || trimmed.length === 0 || !configValid}
+ onClick={() =>
+ onSubmit(trimmed, buildConnectionConfig(renderableSchemas, connectionConfig))
+ }
className="sm:flex-none"
>
{pending ?
:
}
@@ -446,12 +491,15 @@ function WatchProviderCard({ providerKey }: { providerKey: string }) {
});
};
- const handleSubmitAPIKey = (apiKey: string) => {
- connectAPIKey.mutate(apiKey, {
- onSuccess: () => {
- setApiKeyPrompt(false);
+ const handleSubmitAPIKey = (apiKey: string, connectionConfig: WatchProviderConnectionConfig) => {
+ connectAPIKey.mutate(
+ { apiKey, connectionConfig },
+ {
+ onSuccess: () => {
+ setApiKeyPrompt(false);
+ },
},
- });
+ );
};
const handleCancelAPIKey = () => {
@@ -541,6 +589,8 @@ function WatchProviderCard({ providerKey }: { providerKey: string }) {
updateConnection.mutate({ export_watched_enabled: checked })}
/>
- updateConnection.mutate({ export_unwatched_enabled: checked })}
- />
+ {connection.capabilities.export_unwatched ? (
+
+ updateConnection.mutate({ export_unwatched_enabled: checked })
+ }
+ />
+ ) : null}
{connection.capabilities.import_favorites ||
connection.capabilities.export_favorites ? (
{
+ it("omits an untouched optional schema without blocking Connect", () => {
+ expect(activeConnectionSchemas([optionalSchema], {})).toEqual([]);
+ expect(connectionSchemasAreValid([optionalSchema], {}, { optional: false })).toBe(true);
+ expect(buildConnectionConfig([optionalSchema], {})).toEqual({});
+ });
+
+ it("validates and submits an optional schema after the user enters a value", () => {
+ const drafts = { optional: { base_url: "https://floppy.example.com" } };
+ expect(connectionSchemasAreValid([optionalSchema], drafts, { optional: false })).toBe(false);
+ expect(connectionSchemasAreValid([optionalSchema], drafts, { optional: true })).toBe(true);
+ expect(buildConnectionConfig([optionalSchema], drafts)).toEqual({
+ optional: { base_url: "https://floppy.example.com" },
+ });
+ });
+
+ it("keeps required schemas active before any values are entered", () => {
+ const requiredSchema = { ...optionalSchema, key: "required", required: true };
+ expect(activeConnectionSchemas([requiredSchema], {})).toEqual([requiredSchema]);
+ expect(connectionSchemasAreValid([requiredSchema], {}, {})).toBe(false);
+ });
+
+ it("derives a usable form for a required JSON-schema-only block", () => {
+ const headless = { ...optionalSchema, required: true, admin_form: undefined };
+ const schemas = renderableConnectionSchemas([headless]);
+ expect(schemas).toHaveLength(1);
+ const renderable = schemas[0]!;
+ expect(renderable.admin_form.fields).toEqual([
+ expect.objectContaining({
+ key: "base_url",
+ label: "Base Url",
+ control: "TEXT",
+ required: true,
+ }),
+ ]);
+ expect(connectionSchemasAreValid([renderable], {}, {})).toBe(false);
+ });
+});
diff --git a/web/src/pages/settings/watchProviderConnectionConfig.ts b/web/src/pages/settings/watchProviderConnectionConfig.ts
new file mode 100644
index 00000000000..b269ea5cccf
--- /dev/null
+++ b/web/src/pages/settings/watchProviderConnectionConfig.ts
@@ -0,0 +1,59 @@
+import type { PluginConfigSchema } from "@/api/types";
+import { adminFormForConfigSchema } from "@/components/admin/plugins/configSchemaAdminForm";
+import { buildSchemaValues, parseFieldTypes } from "@/components/admin/plugins/schemaFormUtils";
+import type { WatchProviderConnectionConfig } from "@/hooks/queries/watchProviders";
+
+export type RenderableConnectionSchema = PluginConfigSchema & {
+ admin_form: NonNullable;
+};
+
+export function renderableConnectionSchemas(
+ schemas: PluginConfigSchema[],
+): RenderableConnectionSchema[] {
+ return schemas.flatMap((schema) => {
+ const adminForm = adminFormForConfigSchema(schema);
+ return adminForm == null ? [] : [{ ...schema, admin_form: adminForm }];
+ });
+}
+
+function hasEnteredValue(value: unknown): boolean {
+ if (value == null) return false;
+ if (typeof value === "string") return value.trim().length > 0;
+ if (Array.isArray(value)) return value.some(hasEnteredValue);
+ if (typeof value === "object") return Object.values(value).some(hasEnteredValue);
+ return true;
+}
+
+export function activeConnectionSchemas(
+ schemas: PluginConfigSchema[],
+ drafts: WatchProviderConnectionConfig,
+): RenderableConnectionSchema[] {
+ return schemas.filter(
+ (schema): schema is RenderableConnectionSchema =>
+ schema.admin_form != null && (schema.required || hasEnteredValue(drafts[schema.key])),
+ );
+}
+
+export function connectionSchemasAreValid(
+ schemas: PluginConfigSchema[],
+ drafts: WatchProviderConnectionConfig,
+ validity: Record,
+): boolean {
+ return activeConnectionSchemas(schemas, drafts).every((schema) => validity[schema.key] ?? false);
+}
+
+export function buildConnectionConfig(
+ schemas: PluginConfigSchema[],
+ drafts: WatchProviderConnectionConfig,
+): WatchProviderConnectionConfig {
+ return Object.fromEntries(
+ activeConnectionSchemas(schemas, drafts).map((schema) => [
+ schema.key,
+ buildSchemaValues(
+ schema.admin_form,
+ drafts[schema.key] ?? {},
+ parseFieldTypes(schema.json_schema),
+ ),
+ ]),
+ );
+}