Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 38 additions & 5 deletions apps/web/components/connections/connection-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down Expand Up @@ -174,7 +175,13 @@ export function ConnectionForm({
const startConfig = connection ? ((connection.config ?? {}) as Record<string, unknown>) : 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<string[]>(connection?.scopes ?? []);
Expand All @@ -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<ResourceAccessHandle>(null);

const connector = connectors.find((item) => item.slug === connectorSlug);
Expand Down Expand Up @@ -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<string, unknown>) {
if (!parsedConfig) return;
setConfigText(JSON.stringify({ ...parsedConfig, ...patch }, null, 2));
Expand Down Expand Up @@ -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<string, unknown> | 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);
Expand Down Expand Up @@ -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."
}
Expand All @@ -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)}
/>
</Field>
Expand All @@ -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)}
/>
</Field>
Expand Down
6 changes: 4 additions & 2 deletions apps/web/components/resource-access-fields.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 };

Expand Down Expand Up @@ -108,8 +109,9 @@ export const ResourceAccessFields = forwardRef<ResourceAccessHandle, ResourceAcc
toast.success("Access updated");
setDraftDirty(false);
onDirtyChange?.(false);
void queryClient.invalidateQueries({ queryKey: ["sharing", resource, id] });
void queryClient.invalidateQueries({ queryKey: [resource] });
for (const queryKey of sharingInvalidationKeys(resource, id)) {
void queryClient.invalidateQueries({ queryKey });
}
return true;
} catch (error) {
toast.error(`Access could not be updated: ${errorMessage(error)}`);
Expand Down
11 changes: 9 additions & 2 deletions apps/web/components/workers/model-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export { providerOptionValue, resolveProvider };
export function ModelFields({ form, providers }: { form: WorkerFormApi; providers: ProviderRow[] }) {
const { values, set } = form;
const { provider, model } = values;
const { selectedProvider, providerModels } = resolveProvider(providers, provider);
const { selectedProvider, providerModels } = resolveProvider(providers, provider, values.harness);
const mismatch = harnessMismatch(values.harness, provider, providers);

return (
Expand All @@ -45,7 +45,7 @@ export function ModelFields({ form, providers }: { form: WorkerFormApi; provider
set({ provider: "", model: "" });
return;
}
const next = providers.find((candidate) => providerOptionValue(candidate) === event.target.value);
const next = resolveProvider(providers, event.target.value, values.harness).selectedProvider;
const config = (next?.config ?? {}) as Record<string, unknown>;
const settings = config.settings as Record<string, unknown> | undefined;
const catalog = Array.isArray(settings?.models)
Expand All @@ -61,6 +61,13 @@ export function ModelFields({ form, providers }: { form: WorkerFormApi; provider
<optgroup label="Harness-authenticated (worker handles auth)">
{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<string, unknown>;
const optionName = providerOptionValue(candidate);
Expand Down
2 changes: 1 addition & 1 deletion apps/web/components/workers/runtime-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<>
<Field label="Name" htmlFor="wp-name">
Expand Down
17 changes: 16 additions & 1 deletion apps/web/components/workers/worker-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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<string[] | null>(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,
Expand All @@ -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;
Expand Down Expand Up @@ -436,3 +447,7 @@ export function WorkerEditor({
</div>
);
}

function sameIds(a: string[], b: string[]): boolean {
return a.length === b.length && a.every((id) => b.includes(id));
}
24 changes: 24 additions & 0 deletions apps/web/lib/kubernetes-credential.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
32 changes: 32 additions & 0 deletions apps/web/lib/kubernetes-credential.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown> | 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.";
}
29 changes: 2 additions & 27 deletions apps/web/lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -60,33 +61,7 @@ export function unwrap<T>(result: {
return result.data;
}

export const queryKeys = {
meta: ["meta"] as const,
me: ["me"] as const,
dashboard: ["dashboard"] as const,
agents: (params?: Record<string, unknown>) => ["agents", params ?? {}] as const,
agent: (id: string) => ["agent", id] as const,
agentVersions: (id: string) => ["agent", id, "versions"] as const,
executions: (params?: Record<string, unknown>) => ["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<MetaResponse>({
Expand Down
28 changes: 28 additions & 0 deletions apps/web/lib/query-keys.test.ts
Original file line number Diff line number Diff line change
@@ -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`);
}
});
Loading