diff --git a/apps/web/components/connections/connection-form.tsx b/apps/web/components/connections/connection-form.tsx index 22ab5a68..b8e3f6b6 100644 --- a/apps/web/components/connections/connection-form.tsx +++ b/apps/web/components/connections/connection-form.tsx @@ -44,6 +44,7 @@ import { import { effectLabel, effectTone, humanizeIdentifier } from "@/lib/presentation"; import type { ConnectionView } from "@/lib/types"; import { useUnsavedChanges } from "@/lib/use-unsaved-changes"; +import { kubernetesAuthMode as authModeOf, kubernetesCredentialIssue } from "@/lib/kubernetes-credential"; import { cn } from "@/lib/utils"; const KUBERNETES_CONFIG_KEYS = new Set([ @@ -174,7 +175,13 @@ export function ConnectionForm({ const startConfig = connection ? ((connection.config ?? {}) as Record) : defaultConfig(firstSlug); const [connectorSlug, setConnectorSlug] = useState(firstSlug); - const [name, setName] = useState(connection?.name ?? ""); + // A new connection starts with a sensible name for its service (set here, not in an + // effect, so the unsaved-changes guard does not count it as an edit). + const [name, setName] = useState(() => { + if (connection) return connection.name; + const first = connectors.find((item) => item.slug === firstSlug); + return first ? `${first.name} connection` : ""; + }); const [credential, setCredential] = useState(""); const [kubeconfigName, setKubeconfigName] = useState(""); const [scopes, setScopes] = useState(connection?.scopes ?? []); @@ -183,7 +190,6 @@ export function ConnectionForm({ const [url, setUrl] = useState(urlFromConfig(firstSlug, startConfig)); // Access is stored separately; keep pending access edits in the unsaved state too. const [accessDirty, setAccessDirty] = useState(false); - useUnsavedChanges({ accessDirty }); const accessRef = useRef(null); const connector = connectors.find((item) => item.slug === connectorSlug); @@ -221,6 +227,21 @@ export function ConnectionForm({ // eslint-disable-next-line react-hooks/exhaustive-deps }, [connectorSlug, connection?.id]); + useUnsavedChanges({ connectorSlug, name, credential, scopes, configText, url, namespaceText, accessDirty }); + + // The credential field holds a token or a kubeconfig depending on the mode. Switching mode + // (in the select or in Advanced config) drops what was entered for the other one. + const previousAuthMode = useRef(kubernetesAuthMode); + useEffect(() => { + // Half-typed Advanced JSON does not parse; that is not a mode change. + if (isKubernetes && !parsedConfig) return; + if (previousAuthMode.current === kubernetesAuthMode) return; + previousAuthMode.current = kubernetesAuthMode; + setCredential(""); + setKubeconfigName(""); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [kubernetesAuthMode, parsedConfig === null]); + function setKubernetesConfig(patch: Record) { if (!parsedConfig) return; setConfigText(JSON.stringify({ ...parsedConfig, ...patch }, null, 2)); @@ -275,6 +296,18 @@ export function ConnectionForm({ } } if (!parsedConfig) issues.push({ section: "advanced", message: "The configuration must be a JSON object." }); + const storedAuthMode = authModeOf(connection?.config as Record | undefined); + const credentialIssue = kubernetesAuthMode + ? kubernetesCredentialIssue({ + editing: editing && Boolean(connection?.hasCredential), + storedMode: storedAuthMode, + mode: authModeOf(parsedConfig), + credential, + }) + : null; + // Whether the stored credential still applies (a Kubernetes one only in its own mode). + const storedCredential = editing && Boolean(connection?.hasCredential) && (!isKubernetes || storedAuthMode === authModeOf(parsedConfig)); + if (credentialIssue) issues.push({ section: "account", message: credentialIssue }); if (configError) issues.push({ section: "account", message: configError }); const [showIssues, setShowIssues] = useState(false); const issueCount = (id: SectionId) => (showIssues ? issues.filter((issue) => issue.section === id).length : 0); @@ -496,7 +529,7 @@ export function ConnectionForm({ label="Or paste kubeconfig" htmlFor="connection-credential" hint={ - editing && connection?.hasCredential && !credential + storedCredential && !credential ? "A kubeconfig is stored. Leave this empty to keep it, or paste a new one to replace it." : "Paste a kubeconfig with a static token or client certificate. exec auth is refused." } @@ -506,7 +539,7 @@ export function ConnectionForm({ className="min-h-28 font-mono text-base md:text-xs" value={credential} spellCheck={false} - placeholder={editing && connection?.hasCredential ? "•••••••• (stored)" : undefined} + placeholder={storedCredential ? "•••••••• (stored)" : undefined} onChange={(event) => setCredential(event.target.value)} /> @@ -532,7 +565,7 @@ export function ConnectionForm({ type="password" value={credential} autoComplete="new-password" - placeholder={editing && connection?.hasCredential ? "•••••••• (stored)" : undefined} + placeholder={storedCredential ? "•••••••• (stored)" : undefined} onChange={(event) => setCredential(event.target.value)} /> diff --git a/apps/web/components/resource-access-fields.tsx b/apps/web/components/resource-access-fields.tsx index 0eed0050..ab1cfd0c 100644 --- a/apps/web/components/resource-access-fields.tsx +++ b/apps/web/components/resource-access-fields.tsx @@ -15,6 +15,7 @@ import { listAccessTeams } from "@/lib/access-teams"; import { request } from "@/lib/http"; import { errorMessage } from "@orbit/api-client"; import { useLicense } from "@/lib/queries"; +import { sharingInvalidationKeys } from "@/lib/query-keys"; type Sharing = { visibility: string; ownerTeamId?: string | null }; @@ -108,8 +109,9 @@ export const ResourceAccessFields = forwardRef providerOptionValue(candidate) === event.target.value); + const next = resolveProvider(providers, event.target.value, values.harness).selectedProvider; const config = (next?.config ?? {}) as Record; const settings = config.settings as Record | undefined; const catalog = Array.isArray(settings?.models) @@ -61,6 +61,13 @@ export function ModelFields({ form, providers }: { form: WorkerFormApi; provider {providers .filter((candidate) => candidate.kind === "harness_managed") + // One option per stored value: providers for different harnesses can + // share a provider name, and the profile stores only that name. + .filter( + (candidate) => + resolveProvider(providers, providerOptionValue(candidate), values.harness).selectedProvider === + candidate, + ) .map((candidate) => { const config = (candidate.config ?? {}) as Record; const optionName = providerOptionValue(candidate); diff --git a/apps/web/components/workers/runtime-section.tsx b/apps/web/components/workers/runtime-section.tsx index 9c65410a..dba236ac 100644 --- a/apps/web/components/workers/runtime-section.tsx +++ b/apps/web/components/workers/runtime-section.tsx @@ -15,7 +15,7 @@ import type { WorkerFormApi } from "./worker-form"; /** Name, harness and target. */ export function BasicsFields({ form, providers }: { form: WorkerFormApi; providers: ProviderRow[] }) { const { values, set } = form; - const { selectedProvider } = resolveProvider(providers, values.provider); + const { selectedProvider } = resolveProvider(providers, values.provider, values.harness); return ( <> diff --git a/apps/web/components/workers/worker-editor.tsx b/apps/web/components/workers/worker-editor.tsx index a91c6bf2..745a90ab 100644 --- a/apps/web/components/workers/worker-editor.tsx +++ b/apps/web/components/workers/worker-editor.tsx @@ -100,7 +100,6 @@ export function WorkerEditor({ ); const { values } = form; const [accessDirty, setAccessDirty] = useState(false); - useUnsavedChanges({ accessDirty }, { enabled: Boolean(editing) }); const [confirmRelaunch, setConfirmRelaunch] = useState(false); const [attempted, setAttempted] = useState(false); @@ -116,11 +115,14 @@ export function WorkerEditor({ // Seed the checkbox state once. Refetches return the same mappings, and re-seeding // would throw away any unsaved ticks the user has made in the meantime. const envMappingsSeeded = useRef(false); + // The attached mappings as stored, once loaded: the baseline for the unsaved-changes guard. + const [storedEnvMappingIds, setStoredEnvMappingIds] = useState(null); useEffect(() => { if (!editing || !profileEnvMappings.data || envMappingsSeeded.current) return; envMappingsSeeded.current = true; const attached = profileEnvMappings.data.map((mapping) => mapping.id); + setStoredEnvMappingIds(attached); form.set({ envMappingIds: attachMappingId && !attached.includes(attachMappingId) ? [...attached, attachMappingId] : attached, @@ -131,6 +133,15 @@ export function WorkerEditor({ // Saving while an attached-mapping read failed would send a form with no ids and // detach every mapping. Wait for a successful read before allowing a save. + // Seeding the attached mappings after they load is not an edit; ticking one afterwards + // (or arriving with one pre-ticked from Environments) is. + const { envMappingIds, ...guardedValues } = values; + useUnsavedChanges({ + values: guardedValues, + envMappingsChanged: !sameIds(envMappingIds, storedEnvMappingIds ?? (editing ? envMappingIds : [])), + accessDirty, + }); + const envMappingsLoading = Boolean(editing) && profileEnvMappings.isLoading; const envMappingsFailed = Boolean(editing) && profileEnvMappings.isError; const envMappingsBlocked = envMappingsLoading || envMappingsFailed; @@ -436,3 +447,7 @@ export function WorkerEditor({ ); } + +function sameIds(a: string[], b: string[]): boolean { + return a.length === b.length && a.every((id) => b.includes(id)); +} diff --git a/apps/web/lib/kubernetes-credential.test.ts b/apps/web/lib/kubernetes-credential.test.ts new file mode 100644 index 00000000..c714c7e1 --- /dev/null +++ b/apps/web/lib/kubernetes-credential.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { kubernetesAuthMode, kubernetesCredentialIssue } from "./kubernetes-credential.ts"; + +test("the auth mode defaults to service account", () => { + assert.equal(kubernetesAuthMode({}), "service_account"); + assert.equal(kubernetesAuthMode(null), "service_account"); + assert.equal(kubernetesAuthMode({ authMode: "kubeconfig" }), "kubeconfig"); + assert.equal(kubernetesAuthMode({ authMode: "other" }), "service_account"); +}); + +test("an edit that changes the auth mode needs a new credential (#400)", () => { + const base = { editing: true, storedMode: "kubeconfig", mode: "service_account", credential: "" } as const; + assert.match(kubernetesCredentialIssue(base) ?? "", /service account: enter its token/); + assert.match( + kubernetesCredentialIssue({ ...base, storedMode: "service_account", mode: "kubeconfig" }) ?? "", + /kubeconfig: load or paste/, + ); + assert.equal(kubernetesCredentialIssue({ ...base, credential: "token" }), null); + assert.equal(kubernetesCredentialIssue({ ...base, credential: " " }) !== null, true, "whitespace is no credential"); + assert.equal(kubernetesCredentialIssue({ ...base, mode: "kubeconfig" }), null, "same mode keeps the stored one"); + assert.equal(kubernetesCredentialIssue({ ...base, editing: false }), null, "a new connection has nothing stored"); +}); diff --git a/apps/web/lib/kubernetes-credential.ts b/apps/web/lib/kubernetes-credential.ts new file mode 100644 index 00000000..bb9e20e8 --- /dev/null +++ b/apps/web/lib/kubernetes-credential.ts @@ -0,0 +1,32 @@ +/** + * A Kubernetes connection stores one credential, and what it means depends on `authMode`: + * a service-account token or a kubeconfig. The form keeps one credential field for both, so + * these rules keep a value typed for one mode from being saved as the other. + */ + +export type KubernetesAuthMode = "service_account" | "kubeconfig"; + +export function kubernetesAuthMode(config: Record | null | undefined): KubernetesAuthMode { + return config?.authMode === "kubeconfig" ? "kubeconfig" : "service_account"; +} + +/** + * The problem with saving this credential, or null. When an existing connection moves to + * another mode, the stored credential belongs to the old mode, so a new one is required. + */ +export function kubernetesCredentialIssue({ + editing, + storedMode, + mode, + credential, +}: { + editing: boolean; + storedMode: KubernetesAuthMode; + mode: KubernetesAuthMode; + credential: string; +}): string | null { + if (!editing || storedMode === mode || credential.trim()) return null; + return mode === "kubeconfig" + ? "The authentication changed to kubeconfig: load or paste a kubeconfig. The stored token is not a kubeconfig." + : "The authentication changed to service account: enter its token. The stored kubeconfig is not a token."; +} diff --git a/apps/web/lib/queries.ts b/apps/web/lib/queries.ts index a227df9e..0f41971f 100644 --- a/apps/web/lib/queries.ts +++ b/apps/web/lib/queries.ts @@ -6,6 +6,7 @@ import { api } from "./api"; import { apiErrorFromBody, handleUnauthorized, isNoAccessError, isSessionError, request } from "./http"; import { listEnvMappings, workerProfileEnvMappings } from "./env-mappings"; import { listOutputs } from "./outputs"; +import { queryKeys } from "./query-keys"; import type { AgentDetail, AgentPage, @@ -60,33 +61,7 @@ export function unwrap(result: { return result.data; } -export const queryKeys = { - meta: ["meta"] as const, - me: ["me"] as const, - dashboard: ["dashboard"] as const, - agents: (params?: Record) => ["agents", params ?? {}] as const, - agent: (id: string) => ["agent", id] as const, - agentVersions: (id: string) => ["agent", id, "versions"] as const, - executions: (params?: Record) => ["executions", params ?? {}] as const, - execution: (id: string) => ["execution", id] as const, - executionEvents: (id: string) => ["execution", id, "events"] as const, - harnesses: ["harnesses"] as const, - providers: ["providers"] as const, - connectors: ["connectors"] as const, - connections: ["connections"] as const, - tokens: ["api-tokens"] as const, - approvals: (status?: string) => ["approvals", status ?? "all"] as const, - workers: ["workers"] as const, - skills: ["skills"] as const, - skill: (id: string) => ["skills", id] as const, - workerProfiles: ["worker-profiles"] as const, - workerLaunches: ["worker-launches"] as const, - agentTeams: ["agent-teams"] as const, - agentTeam: (id: string) => ["agent-teams", id] as const, - teamQueue: (id: string) => ["agent-teams", id, "queue"] as const, - teamRuns: ["team-runs"] as const, - teamRun: (id: string) => ["team-runs", "detail", id] as const, -}; +export { queryKeys } from "./query-keys"; export function useMeta() { return useQuery({ diff --git a/apps/web/lib/query-keys.test.ts b/apps/web/lib/query-keys.test.ts new file mode 100644 index 00000000..ce70ee07 --- /dev/null +++ b/apps/web/lib/query-keys.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { queryKeys, sharingInvalidationKeys } from "./query-keys.ts"; + +/** Whether invalidating `key` refreshes `query` (React Query matches by key prefix). */ +const covers = (keys: (readonly unknown[])[], query: readonly unknown[]) => + keys.some((key) => key.every((part, index) => JSON.stringify(part) === JSON.stringify(query[index]))); + +test("an access change refreshes the resource's real list and detail queries (#400)", () => { + const id = "11111111-1111-1111-1111-111111111111"; + assert.ok(covers(sharingInvalidationKeys("agent_teams", id), queryKeys.agentTeams)); + assert.ok(covers(sharingInvalidationKeys("agent_teams", id), queryKeys.agentTeam(id))); + assert.ok(covers(sharingInvalidationKeys("worker_profiles", id), queryKeys.workerProfiles)); + assert.ok(covers(sharingInvalidationKeys("env_mappings", id), ["env-mappings"])); + assert.ok(covers(sharingInvalidationKeys("env_mappings", id), ["worker-profile-env-mappings", "p1"])); + assert.ok(covers(sharingInvalidationKeys("agents", id), queryKeys.agents({ status: "current" }))); + assert.ok(covers(sharingInvalidationKeys("agents", id), queryKeys.agent(id))); + assert.ok(covers(sharingInvalidationKeys("skills", id), queryKeys.skill(id))); + assert.ok(covers(sharingInvalidationKeys("providers", id), queryKeys.providers)); + assert.ok(covers(sharingInvalidationKeys("connections", id), queryKeys.connections)); + for (const resource of ["agents", "agent_teams", "worker_profiles", "env_mappings", "providers", "connections", "skills"]) { + const keys = sharingInvalidationKeys(resource, id); + assert.ok(covers(keys, ["sharing", resource, id]), `${resource}: its sharing query`); + assert.ok(covers(keys, ["team-resources", "t1"]), `${resource}: access team resource lists`); + assert.ok(!keys.some((key) => key[0] === resource && resource.includes("_")), `${resource}: no snake_case key`); + } +}); diff --git a/apps/web/lib/query-keys.ts b/apps/web/lib/query-keys.ts new file mode 100644 index 00000000..0b1a2cec --- /dev/null +++ b/apps/web/lib/query-keys.ts @@ -0,0 +1,67 @@ +/** + * React Query keys. Kept free of React and the API client so plain `node --test` tests can + * import it. `lib/queries.ts` re-exports `queryKeys`. + */ +export const queryKeys = { + meta: ["meta"] as const, + me: ["me"] as const, + dashboard: ["dashboard"] as const, + agents: (params?: Record) => ["agents", params ?? {}] as const, + agent: (id: string) => ["agent", id] as const, + agentVersions: (id: string) => ["agent", id, "versions"] as const, + executions: (params?: Record) => ["executions", params ?? {}] as const, + execution: (id: string) => ["execution", id] as const, + executionEvents: (id: string) => ["execution", id, "events"] as const, + harnesses: ["harnesses"] as const, + providers: ["providers"] as const, + connectors: ["connectors"] as const, + connections: ["connections"] as const, + tokens: ["api-tokens"] as const, + approvals: (status?: string) => ["approvals", status ?? "all"] as const, + workers: ["workers"] as const, + skills: ["skills"] as const, + skill: (id: string) => ["skills", id] as const, + workerProfiles: ["worker-profiles"] as const, + workerLaunches: ["worker-launches"] as const, + agentTeams: ["agent-teams"] as const, + agentTeam: (id: string) => ["agent-teams", id] as const, + teamQueue: (id: string) => ["agent-teams", id, "queue"] as const, + teamRuns: ["team-runs"] as const, + teamRun: (id: string) => ["team-runs", "detail", id] as const, +}; + +/** + * The list and detail queries to refresh after a resource's access (visibility or owning + * team) changed. `resource` is the sharing API's resource name, e.g. "agent_teams". + */ +export function sharingInvalidationKeys(resource: string, id: string): (readonly unknown[])[] { + // An access team's resource list shows what the team owns. + const keys: (readonly unknown[])[] = [["sharing", resource, id], ["team-resources"]]; + switch (resource) { + case "agents": + // ["agents"] is the prefix of every agent list query. + keys.push(["agents"], queryKeys.agent(id), queryKeys.dashboard); + break; + case "agent_teams": + keys.push(queryKeys.agentTeams); + break; + case "worker_profiles": + keys.push(queryKeys.workerProfiles); + break; + case "env_mappings": + keys.push(["env-mappings"], ["worker-profile-env-mappings"]); + break; + case "providers": + keys.push(queryKeys.providers); + break; + case "connections": + keys.push(queryKeys.connections); + break; + case "skills": + keys.push(queryKeys.skills); + break; + default: + keys.push([resource]); + } + return keys; +} diff --git a/apps/web/lib/worker-harness.test.ts b/apps/web/lib/worker-harness.test.ts index 9809d80f..61abd77a 100644 --- a/apps/web/lib/worker-harness.test.ts +++ b/apps/web/lib/worker-harness.test.ts @@ -55,3 +55,16 @@ test("unknown harnesses get a readable label", () => { assert.equal(harnessLabel("opencode"), "OpenCode"); assert.equal(harnessLabel("my_harness"), "My Harness"); }); + +test("providers for different harnesses that share a provider name resolve by the worker's harness (#400)", () => { + const shared: WorkerProviderLike[] = [ + { name: "Anthropic (OpenCode)", kind: "harness_managed", config: { harness: "opencode", provider: "anthropic", settings: { models: ["a-oc"] } } }, + { name: "Anthropic (Pi)", kind: "harness_managed", config: { harness: "pi", provider: "anthropic", settings: { models: ["a-pi"] } } }, + ]; + assert.equal(resolveProvider(shared, "anthropic", "pi").selectedProvider?.name, "Anthropic (Pi)"); + assert.deepEqual(resolveProvider(shared, "anthropic", "pi").providerModels, ["a-pi"]); + assert.equal(resolveProvider(shared, "anthropic", "opencode").selectedProvider?.name, "Anthropic (OpenCode)"); + assert.equal(resolveProvider(shared, "anthropic").selectedProvider?.name, "Anthropic (OpenCode)", "without a harness the first wins"); + assert.equal(harnessMismatch("pi", "anthropic", shared), null, "a Pi provider of that name exists"); + assert.equal(harnessMismatch("mock", "anthropic", shared)?.providerHarness, "opencode"); +}); diff --git a/apps/web/lib/worker-harness.ts b/apps/web/lib/worker-harness.ts index 31772823..896d9979 100644 --- a/apps/web/lib/worker-harness.ts +++ b/apps/web/lib/worker-harness.ts @@ -40,12 +40,20 @@ export function providerOptionValue(provider: WorkerProviderLike): string { return provider.kind === "harness_managed" ? String(config.provider ?? provider.name) : provider.name; } -/** The provider row matching a profile's provider, and the models it offers. */ +/** + * The provider row matching a profile's provider, and the models it offers. A profile stores + * a harness-managed provider by the harness's provider name, which two providers for + * different harnesses can share (e.g. `anthropic` under OpenCode and under Pi); pass the + * worker's harness so the row for that harness wins. + */ export function resolveProvider( providers: T[], provider: string, + harness?: string, ): { selectedProvider: T | undefined; providerModels: string[] } { - const selectedProvider = providers.find((candidate) => providerOptionValue(candidate) === provider); + const matches = providers.filter((candidate) => providerOptionValue(candidate) === provider); + const selectedProvider = + (harness ? matches.find((candidate) => providerHarness(candidate) === harness) : undefined) ?? matches[0]; const settings = asRecord(asRecord(selectedProvider?.config).settings); const providerModels = Array.isArray(settings.models) ? settings.models.filter((item): item is string => typeof item === "string") @@ -77,7 +85,7 @@ export function harnessMismatch( provider: string, providers: WorkerProviderLike[], ): HarnessMismatch | null { - const selected = resolveProvider(providers, provider).selectedProvider; + const selected = resolveProvider(providers, provider, workerHarness).selectedProvider; const modelHarness = providerHarness(selected); if (!workerHarness || !modelHarness || modelHarness === workerHarness) return null; diff --git a/changelog.d/400.fixed.md b/changelog.d/400.fixed.md new file mode 100644 index 00000000..deb4ecb9 --- /dev/null +++ b/changelog.d/400.fixed.md @@ -0,0 +1,8 @@ +- Web editors keep their state straight (#400). Switching a Kubernetes connection between + service account and kubeconfig clears what was entered for the other mode, and an edit that + changes the mode asks for a new credential instead of keeping the old one under the wrong + mode. The connection and worker-profile editors warn before leaving with any unsaved field, + not only an unsaved access change, and the worker editor does so when creating a profile + too. Changing a resource's access refreshes its lists (teams, worker profiles and + environment mappings were not refreshed), and providers for different harnesses that share + a provider name resolve to the one for the worker's harness.