Files
kandev/apps/web/components/settings/plugins/plugin-detail.tsx
T
João Salavisa fae2303db3 feat(plugins): per-plugin settings pages driven by manifest config_schema (#1761)
* feat(plugins): per-plugin settings pages driven by manifest config_schema

Settings > Plugins rows now open /settings/plugins/:id — a detail page
showing the manifest plus a settings form generated from the plugin
author's config_schema. Secret fields (secret: true / format: password)
are masked on the operator API and kept on masked re-submits; a running
plugin restarts on save and reads its config (cleartext secrets included)
through the new Host GetConfig gRPC RPC.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): write plugin config file owner-only (0600)

Operator config can now carry cleartext secret values (config_schema
fields marked secret), so <id>.config.yml must not be world-readable —
match the 0600 mode the record file already uses.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(plugins): vault-backed plugin secrets — Get/Set/DeleteSecret RPCs and encrypted config secrets

Plugins get vault-backed secret primitives on the Host API
(GetSecret/SetSecret/DeleteSecret, capability-gated, namespaced to
plugin:<id>㊙️<key> so a plugin can only touch its own entries;
purged on uninstall). Secret config_schema fields now live in kandev's
AES-256-GCM vault too — <id>.config.yml persists only a vault reference,
and the Host GetConfig RPC resolves it back to cleartext for the plugin.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore(plugins): serve PR screenshots from the media/pr-1761-screenshots ref instead of the repo

The PR body now points at raw URLs pinned to an unmerged media ref, so
the binaries never land in main (PRs are squash-merged; only the branch
tip tree merges).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): address review feedback on settings validation and save flow

- integer form fields reject non-integral input instead of parseInt-truncating
- enum selections keep their schema-declared types (numeric enums round-trip)
- backend enum validation normalizes int-vs-float64 before comparison
- maskSecrets masks any non-zero secret value regardless of runtime type
- save flow splits PATCH from refetch: a refetch failure no longer reports a
  successful save as an error, and typed secrets are masked on screen
- optional enum fields gain a 'Not set' option so they can be cleared
- resolveConfigSecrets copies before mutating; restart-failure SetStatus
  errors are logged; SDK test fake returns a non-nil empty config map
- add missing tests: usePluginConfigForm hook, getPluginConfig client,
  integer/enum regression cases

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): harden secret config invariants from review

- reject non-string values on declared secret fields at validation time,
  closing the path where a numeric/boolean secret bypassed the vault and
  persisted cleartext in the config file
- delete removed secret fields' vault entries only AFTER the config commit
  succeeds, so a failed SetConfig never leaves the still-current config
  referencing a deleted vault entry
- uninstall fails closed: the plugin's vault namespace is purged before any
  destructive step, and a cleanup failure aborts the uninstall (retryable)
  instead of letting a reinstall inherit stale secrets

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): failure-atomic config secrets, quiesced uninstall purge, ctx propagation

- UpdateConfig is now failure-atomic for secret overwrites: storeConfigSecrets
  snapshots each vault entry before writing and returns a rollback that
  restores prior values (or deletes newly-created ones). A vault.Set failure
  mid-loop or a failed SetConfig commit rolls back, so a request reported as
  failed never changes the value a still-current config ref resolves to.
- Uninstall stops the plugin process BEFORE purging its vault namespace, so
  the plugin can no longer race the cleanup with a SetSecret between ListIDs
  and the deletes; the purge stays fail-closed and retryable.
- Thread the request context through Uninstall -> deletePluginSecrets instead
  of context.Background(), per the pass-context-through-chains convention.
- Consolidate the 'secret not found:' prefix check into isSecretNotFound
  (host.go + service rollback share one definition).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): detach rollback context, fail closed without a vault, reconcile uninstall status

- vault rollback closures now run on context.WithoutCancel(ctx): a request
  cancelled mid-save (browser closed) can no longer abort the rollback and
  leave the vault holding new values while the unchanged config still points
  at them (Greptile P1).
- storeConfigSecrets fails closed (errSecretVaultRequired) when a plugin
  declares secret config fields but no vault is wired, instead of silently
  persisting the secret in cleartext.
- vaultRestoreFunc distinguishes not-found from a genuine Reveal error: a
  backend read failure aborts the update before writing rather than risk a
  rollback that deletes a real secret; rollback now returns errors, joined
  into UpdateConfig's failure so an inconsistent vault is surfaced, not just
  logged.
- Uninstall reconciles lifecycle status when a secret-purge failure aborts
  after the process was stopped: a previously-running plugin transitions to
  error and notifies observers instead of being reported active with no
  process running.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): detach removed-secret cleanup ctx and clear stale save dirty flag

- cleanupRemovedConfigSecrets now runs on context.WithoutCancel(ctx), matching
  the rollback path, so a client disconnect right after the config commit can
  no longer cancel the delete and orphan now-unreferenced vault entries.
- tests: assert GetConfig succeeds before treating an empty map as proof that
  nothing persisted (a swallowed read error would be a false pass).
- web: on a post-save refetch failure, rebase initialValues onto the masked
  snapshot so the saved form no longer reads as dirty.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): fail tests on discarded GetConfig errors, drop setState-in-updater

- config_test: capture and fatal on GetConfig errors at the four remaining
  positive-assertion sites (a nil from a failed read would panic on the next
  map access instead of giving a clear failure), matching the earlier fix.
- web hook: compute the masked post-save snapshot from the current values and
  apply it to setValues + setInitialValues directly, instead of calling
  setInitialValues inside a setValues functional updater (a React anti-pattern
  that runs twice under StrictMode).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(plugins): skip validation of a secret field's own vault ref

- validateConfigSchema takes the plugin id and skips a secret field whose
  value is that field's config vault ref (an internal storage marker,
  already validated when first set). Without this, a field declaring both
  secret: true and enum: [...] 400s on every save that keeps the mask,
  because the enum check saw the vault ref instead of a user value. Freshly
  entered secret values are still validated; a foreign plugin's ref is not
  skipped. Covered by unit + service-level regression tests.
- surface mid-loop vault rollback failures in storeConfigSecrets via a
  warning instead of discarding them (double-fault observability).
- web: integer inputs get step=1 so browsers flag non-integral input in
  place (serializeConfigValues remains the backstop).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(plugins): split config secret tests into config_secrets_test.go

config_test.go had grown past the 800-line backend file-length limit
(revive), failing CI lint. Move the vault-backed config and plugin-scoped
secret tests (plus their fake-vault/store helpers) into a sibling file;
no test logic changes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 22:13:58 +01:00

242 lines
7.5 KiB
TypeScript

"use client";
import { IconArrowLeft } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card";
import { Separator } from "@kandev/ui/separator";
import Link from "@/components/routing/app-link";
import { useRouter } from "@/lib/routing/client-router";
import { usePlugins } from "@/hooks/domains/plugins/use-plugins";
import { UnsavedChangesBadge, UnsavedSaveButton } from "@/components/settings/unsaved-indicator";
import { PluginConfigForm } from "./plugin-config-form";
import { PluginManifestCard } from "./plugin-manifest-card";
import { PluginStatusBadge } from "./plugin-status-badge";
import { UninstallPluginDialog } from "./uninstall-plugin-dialog";
import { usePluginActions } from "./use-plugin-actions";
import { usePluginConfigForm } from "./use-plugin-config-form";
import type { PluginRecord } from "@/lib/types/plugins";
const PLUGINS_SETTINGS_HREF = "/settings/plugins";
/**
* Per-plugin settings page (Settings > Plugins > <plugin>): manifest
* overview plus the schema-driven settings form declared by the plugin
* author via the manifest's config_schema (e.g. a GitHub plugin's PAT).
* Saving restarts a running plugin so it re-reads config via the Host
* GetConfig RPC.
*/
export function PluginDetail({ pluginId }: { pluginId: string }) {
const { items, loaded } = usePlugins();
const router = useRouter();
const actions = usePluginActions();
const plugin = items.find((p) => p.id === pluginId) ?? null;
const form = usePluginConfigForm(plugin);
if (!plugin) {
return loaded ? <PluginNotFound pluginId={pluginId} /> : null;
}
return (
<div className="space-y-6" data-testid={`plugin-detail-${plugin.id}`}>
<PluginDetailHeader
plugin={plugin}
showSave={form.fields.length > 0}
isDirty={form.isDirty}
saveStatus={form.saveStatus}
onSave={form.handleSave}
/>
<Separator />
<PluginSettingsCard plugin={plugin} form={form} busy={actions.busyId === plugin.id} />
<PluginManifestCard plugin={plugin} />
<PluginDangerZone plugin={plugin} actions={actions} />
<UninstallPluginDialog
target={actions.uninstallTarget}
busy={actions.uninstallBusy}
onClose={actions.closeUninstall}
onConfirm={async () => {
await actions.confirmUninstall();
router.push(PLUGINS_SETTINGS_HREF);
}}
/>
</div>
);
}
type PluginDetailHeaderProps = {
plugin: PluginRecord;
showSave: boolean;
isDirty: boolean;
saveStatus: "idle" | "loading" | "success" | "error";
onSave: () => void;
};
function PluginDetailHeader({
plugin,
showSave,
isDirty,
saveStatus,
onSave,
}: PluginDetailHeaderProps) {
return (
<div className="space-y-3">
<Link
href={PLUGINS_SETTINGS_HREF}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground cursor-pointer"
>
<IconArrowLeft className="h-4 w-4" />
Plugins
</Link>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<h2 className="text-2xl font-bold truncate">{plugin.display_name}</h2>
<PluginStatusBadge status={plugin.status} />
{plugin.signed === false && (
<Badge
variant="outline"
className="border-amber-500/40 bg-amber-500/10 text-amber-600 dark:text-amber-400 text-[11px]"
>
unsigned
</Badge>
)}
</div>
<div className="text-xs text-muted-foreground font-mono">
{plugin.id} · v{plugin.version}
</div>
{plugin.description && (
<p className="text-sm text-muted-foreground">{plugin.description}</p>
)}
</div>
{showSave && (
<div className="flex items-center gap-3 shrink-0">
{isDirty && <UnsavedChangesBadge />}
<UnsavedSaveButton
isDirty={isDirty}
isLoading={saveStatus === "loading"}
status={saveStatus}
onClick={onSave}
/>
</div>
)}
</div>
</div>
);
}
type PluginSettingsCardProps = {
plugin: PluginRecord;
form: ReturnType<typeof usePluginConfigForm>;
busy: boolean;
};
function PluginSettingsCard({ plugin, form, busy }: PluginSettingsCardProps) {
return (
<Card data-testid="plugin-settings-card">
<CardHeader>
<CardTitle className="text-base">Settings</CardTitle>
</CardHeader>
<CardContent>
<PluginSettingsBody plugin={plugin} form={form} busy={busy} />
</CardContent>
</Card>
);
}
function PluginSettingsBody({ plugin, form, busy }: PluginSettingsCardProps) {
if (form.fields.length === 0) {
return (
<p className="text-sm text-muted-foreground">
This plugin does not declare any settings (no <code>config_schema</code> in its manifest).
</p>
);
}
if (form.configError) {
return <p className="text-sm text-destructive">{form.configError}</p>;
}
if (form.configLoading) {
return <p className="text-sm text-muted-foreground">Loading settings...</p>;
}
return (
<div className="space-y-4">
<PluginConfigForm
fields={form.fields}
values={form.values}
disabled={busy || form.saveStatus === "loading"}
onChange={form.handleChange}
/>
{plugin.status === "active" && (
<p className="text-xs text-muted-foreground">
Saving restarts the plugin so the new settings take effect.
</p>
)}
</div>
);
}
type PluginDangerZoneProps = {
plugin: PluginRecord;
actions: ReturnType<typeof usePluginActions>;
};
function PluginDangerZone({ plugin, actions }: PluginDangerZoneProps) {
const busy = actions.busyId === plugin.id;
const canEnable = plugin.status === "disabled" || plugin.status === "registered";
const canDisable = plugin.status === "active" || plugin.status === "error";
return (
<div className="flex flex-wrap items-center gap-2">
{canEnable && (
<Button
variant="outline"
size="sm"
className="cursor-pointer"
disabled={busy}
onClick={() => actions.handleEnable(plugin)}
>
Enable
</Button>
)}
{canDisable && (
<Button
variant="outline"
size="sm"
className="cursor-pointer"
disabled={busy}
onClick={() => actions.handleDisable(plugin)}
>
Disable
</Button>
)}
<Button
variant="ghost"
size="sm"
className="cursor-pointer text-destructive hover:text-destructive"
disabled={busy}
onClick={() => actions.openUninstall(plugin)}
>
Uninstall
</Button>
</div>
);
}
function PluginNotFound({ pluginId }: { pluginId: string }) {
return (
<div className="space-y-4">
<Link
href={PLUGINS_SETTINGS_HREF}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground cursor-pointer"
>
<IconArrowLeft className="h-4 w-4" />
Plugins
</Link>
<div className="rounded-md border border-dashed p-6 text-sm text-muted-foreground">
No installed plugin with id <span className="font-mono">{pluginId}</span>.
</div>
</div>
);
}