Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(agent-vault): look up variable keys instead of loading every page
Scott Wilsoncad3b6a64c58
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 1a60acfd62..bc5526ea44 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -1341,6 +1341,14 @@ describe("Agent Vault V1 Router", async () => {totalCount: 3});expect((await inject("GET", `${variablesUrl}?limit=101`)).statusCode).toBe(422);++ // Exact keys, so a lookup can tell a key that exists from one that only contains the text.+ expect(await list("keys=GAMMA_KEY,MISSING_KEY,ALPHA_TOKEN")).toEqual({+ keys: ["ALPHA_TOKEN", "GAMMA_KEY"],+ totalCount: 2+ });+ expect(await list("keys=TOKEN")).toEqual({ keys: [], totalCount: 0 });+ expect((await inject("GET", `${variablesUrl}?keys=lower_case`)).statusCode).toBe(422);});test("services in different bundles share a variable, and each resolves it", async () => {diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.tsindex 916f9541a1..548f3f9387 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-variable-router.ts@@ -1,5 +1,6 @@import { z } from "zod";+import { AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH } from "@app/ee/services/agent-vault/agent-vault-variable-fns";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { AGENT_VAULT } from "@app/lib/api-docs";import { ApiDocsTags } from "@app/lib/api-docs/constants";@@ -18,6 +19,8 @@ import {AgentVaultVariableValueSchema} from "./agent-vault-schemas";+const AGENT_VAULT_LIST_MAX_KEYS = 100;+export const registerAgentVaultVariableRouter = async (server: FastifyZodProvider) => {server.route({method: "GET",@@ -31,6 +34,13 @@ export const registerAgentVaultVariableRouter = async (server: FastifyZodProvidequerystring: z.object({orderBy: z.enum(["key", "usedBy"]).default("key").describe(AGENT_VAULT.VARIABLE.orderBy),orderDirection: z.enum(["asc", "desc"]).default("asc").describe(AGENT_VAULT.VARIABLE.orderDirection),+ keys: z+ .string()+ .max(AGENT_VAULT_LIST_MAX_KEYS * (AGENT_VAULT_VARIABLE_KEY_MAX_LENGTH + 1))+ .transform((val) => [...new Set(val.split(",").map((key) => key.trim()))])+ .pipe(AgentVaultVariableKeySchema.array().min(1).max(AGENT_VAULT_LIST_MAX_KEYS))+ .optional()+ .describe(AGENT_VAULT.VARIABLE.keys),...agentVaultListQuery(AGENT_VAULT.VARIABLE)}),response: {diff --git a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.tsindex a96e7ee828..cb778439b8 100644--- a/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts+++ b/backend/src/ee/services/agent-vault-variable/agent-vault-variable-dal.ts@@ -16,6 +16,7 @@ export type TAgentVaultVariableOrderBy = "key" | "usedBy";export type TFindAgentVaultVariablesDTO = {projectId: string;search?: string;+ keys?: string[];orderBy: TAgentVaultVariableOrderBy;orderDirection: "asc" | "desc";limit: number;@@ -43,7 +44,7 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {// Reads the primary even without a tx, so a variable created a moment ago is always listed. usedBy counts the// services that use a variable, each once however many of its fields do.const findForList = async (- { projectId, search, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,+ { projectId, search, keys, orderBy, orderDirection, limit, offset }: TFindAgentVaultVariablesDTO,tx?: Knex): Promise<{ variables: TAgentVaultVariable[]; totalCount: number }> => {try {@@ -54,6 +55,7 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {if (search) {void query.whereILike(`${TableName.AgentVaultVariable}.key`, `%${sanitizeSqlLikeString(search)}%`);}+ if (keys) void query.whereIn(`${TableName.AgentVaultVariable}.key`, keys);return query;};@@ -62,21 +64,25 @@ export const agentVaultVariableDALFactory = (db: TDbClient) => {.first()) as { count: string } | undefined;const totalCount = parseInt(countResult?.count || "0", 10);- const usageCounts = conn(TableName.AgentVaultServiceVariableReference)- .select("variableId")- .countDistinct("serviceId as count")- .groupBy("variableId")- .as("uc");-- const pageQuery = applyFilters(conn(TableName.AgentVaultVariable))- .leftJoin(usageCounts, function joinUsageCount() {- this.on(db.raw(`uc."variableId" = ??.id`, [TableName.AgentVaultVariable]));- })- .limit(limit)- .offset(offset)- .select(columns);+ const pageQuery = applyFilters(conn(TableName.AgentVaultVariable)).limit(limit).offset(offset).select(columns);if (orderBy === "usedBy") {+ // Counted over this project's variables only; the references table holds every org's.+ const usageCounts = conn(TableName.AgentVaultServiceVariableReference)+ .join(+ TableName.AgentVaultVariable,+ `${TableName.AgentVaultServiceVariableReference}.variableId`,+ `${TableName.AgentVaultVariable}.id`+ )+ .where(`${TableName.AgentVaultVariable}.projectId`, projectId)+ .select(`${TableName.AgentVaultServiceVariableReference}.variableId`)+ .countDistinct(`${TableName.AgentVaultServiceVariableReference}.serviceId as count`)+ .groupBy(`${TableName.AgentVaultServiceVariableReference}.variableId`)+ .as("uc");++ void pageQuery.leftJoin(usageCounts, function joinUsageCount() {+ this.on(db.raw(`uc."variableId" = ??.id`, [TableName.AgentVaultVariable]));+ });void pageQuery.orderByRaw(`COALESCE(uc.count, 0) ${orderDirection === "desc" ? "DESC" : "ASC"}`);void pageQuery.orderBy(`${TableName.AgentVaultVariable}.key`, "asc");} else {diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex db8e45a5ee..2514c17603 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -4467,6 +4467,7 @@ export const AGENT_VAULT = {orderBy: "What to sort variables by: key, or usedBy for how many services use each one.",orderDirection: "Which way to sort: asc or desc.",search: "Match variables whose key contains this text.",+ keys: "Return only the variables with these exact keys, comma-separated. A key that doesn't exist is left out, which is how to check whether one does.",limit: "The maximum number of variables to return.",offset: "How many variables to skip.",totalCount: "How many variables match the search, across every page.",diff --git a/frontend/src/components/agent-vault/VariableFormDialog.tsx b/frontend/src/components/agent-vault/VariableFormDialog.tsxindex cc8cc81566..2d6ec51dbc 100644--- a/frontend/src/components/agent-vault/VariableFormDialog.tsx+++ b/frontend/src/components/agent-vault/VariableFormDialog.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import { Controller, useForm, useWatch } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { EyeIcon, EyeOffIcon } from "lucide-react";@@ -32,7 +32,9 @@ import {VARIABLE_KEY_RE,VARIABLE_VALUE_MAX_LENGTH} from "@app/helpers/agentVaultVariables";+import { useDebounce } from "@app/hooks";import {+ useAgentVaultVariableKeyStatus,useCreateAgentVaultVariable,useUpdateAgentVaultVariable} from "@app/hooks/api/agentVault";@@ -41,8 +43,9 @@ import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";// eslint-disable-next-line no-control-regexconst NO_CONTROL_CHARS_RE = /^[^\x00-\x1f\x7f]*$/;-// A stored value never comes back, so on edit its field starts empty and empty keeps it.-const buildSchema = (takenKeys: string[], isValueRequired: boolean) =>+// A stored value never comes back, so on edit its field starts empty and empty keeps it. Taken keys are read+// when the form validates, as the lookup of the typed key answers after it was typed.+const buildSchema = (getTakenKeys: () => ReadonlySet<string>, isValueRequired: boolean) =>z.object({key: z.string()@@ -50,7 +53,7 @@ const buildSchema = (takenKeys: string[], isValueRequired: boolean) =>.max(VARIABLE_KEY_MAX_LENGTH, `A key can be at most ${VARIABLE_KEY_MAX_LENGTH} characters.`).regex(VARIABLE_KEY_RE, VARIABLE_KEY_MESSAGE).refine(- (key) => !takenKeys.includes(key),+ (key) => !getTakenKeys().has(key),(key) => ({ message: `A variable named '${key}' already exists.` })),value: z@@ -73,7 +76,6 @@ type Props = {isOpen: boolean;onOpenChange: (isOpen: boolean) => void;variable?: TAgentVaultVariable | null;- existingKeys: string[];/** A key to start a new variable from, as when it was named in a service before it existed. */initialKey?: string;onCreated?: (variable: TAgentVaultVariable) => void;@@ -84,7 +86,6 @@ export const VariableFormDialog = ({isOpen,onOpenChange,variable,- existingKeys,initialKey,onCreated,onCloseAutoFocus@@ -95,24 +96,36 @@ export const VariableFormDialog = ({const usedByCount = variable?.usedBy.length ?? 0;const [isValueVisible, setIsValueVisible] = useState(false);- const schema = useMemo(- () =>- buildSchema(- existingKeys.filter((key) => key !== variable?.key),- !variable- ),- [existingKeys, variable]- );+ const takenKeysRef = useRef<ReadonlySet<string>>(new Set());+ const schema = useMemo(() => buildSchema(() => takenKeysRef.current, !variable), [variable]);const {control,handleSubmit,reset,setFocus,+ trigger,+ getFieldState,formState: { isDirty, isSubmitting }} = useForm<FormData>({ resolver: zodResolver(schema) });const key = useWatch({ control, name: "key" });++ // Checked against that one key, not a list, so it holds however many variables there are. The API refuses a+ // duplicate that is saved before the answer comes back.+ const [debouncedKey] = useDebounce(key ?? "", 300);+ const lookupKey =+ isOpen && VARIABLE_KEY_RE.test(debouncedKey) && debouncedKey !== variable?.key+ ? debouncedKey+ : null;+ const { existing } = useAgentVaultVariableKeyStatus(lookupKey ? [lookupKey] : [], isOpen);+ takenKeysRef.current = existing;+ // Re-checked when the answer flags the key, and when a key that was flagged is changed, so the message comes+ // and goes with the lookup rather than waiting for a submit.+ useEffect(() => {+ if (!lookupKey) return;+ if (existing.has(lookupKey) || getFieldState("key").error) trigger("key");+ }, [lookupKey, existing, trigger, getFieldState]);const isRenaming = Boolean(variable) && Boolean(key) && key !== variable?.key;useEffect(() => {diff --git a/frontend/src/components/agent-vault/service-sheet/ReferenceHighlights.tsx b/frontend/src/components/agent-vault/service-sheet/ReferenceHighlights.tsxindex f8ef323f3a..6ebae41733 100644--- a/frontend/src/components/agent-vault/service-sheet/ReferenceHighlights.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ReferenceHighlights.tsx@@ -3,7 +3,7 @@ import { RefObject } from "react";import { cn } from "@app/components/v3/utils";import { splitVariableReferences } from "@app/helpers/agentVaultVariables";-import { useKnownVariableKeys } from "./ServiceVariablesContext";+import { useMissingVariableKeys } from "./ServiceVariablesContext";import { chipTone } from "./VariableChips";/**@@ -17,7 +17,7 @@ export const ReferenceHighlights = ({value: string;overlayRef: RefObject<HTMLDivElement>;}) => {- const knownKeys = useKnownVariableKeys();+ const missingKeys = useMissingVariableKeys();return (<div aria-hidden className="pointer-events-none absolute inset-0 flex items-center px-2.5">@@ -35,7 +35,7 @@ export const ReferenceHighlights = ({key={index}className={cn("rounded-[3px]",- chipTone(segment.isValid && (!knownKeys || knownKeys.has(segment.key)))+ chipTone(segment.isValid && !missingKeys.has(segment.key)))}>{segment.text}diff --git a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsxindex 3eb8a66a64..e3a77b0976 100644--- a/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx+++ b/frontend/src/components/agent-vault/service-sheet/SendsPreview.tsx@@ -5,7 +5,7 @@ import { splitVariableReferences } from "@app/helpers/agentVaultVariables";import { AgentVaultCredentialType } from "@app/hooks/api/agentVault";import { TServiceForm, UNCHANGED_SECRET } from "./serviceSchema";-import { useKnownVariableKeys } from "./ServiceVariablesContext";+import { useMissingVariableKeys } from "./ServiceVariablesContext";import { VariableChip } from "./VariableChips";const MASK = "•".repeat(8);@@ -13,7 +13,7 @@ const MASK = "•".repeat(8);// A reference holds no secret, so it is spelled out. Literal text is masked at a fixed length, which// says nothing about the secret's own.const PreviewValue = ({ value, placeholder }: { value?: string; placeholder: string }) => {- const knownKeys = useKnownVariableKeys();+ const missingKeys = useMissingVariableKeys();if (!value) return <span className="text-muted">{placeholder}</span>;if (value === UNCHANGED_SECRET) return <span>{MASK}</span>;@@ -29,7 +29,7 @@ const PreviewValue = ({ value, placeholder }: { value?: string; placeholder: str// eslint-disable-next-line react/no-array-index-keykey={index}reference={segment.text}- isKnown={segment.isValid && (!knownKeys || knownKeys.has(segment.key))}+ isKnown={segment.isValid && !missingKeys.has(segment.key)}/>))}diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsxindex 18d3e75575..b147871a8f 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx+++ b/frontend/src/components/agent-vault/service-sheet/ServiceSheet.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { FormProvider, useForm } from "react-hook-form";+import { FormProvider, useForm, useWatch } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import slugify from "@sindresorhus/slugify";import axios from "axios";@@ -22,12 +22,13 @@ import {import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";import { hostError } from "@app/helpers/agentVaultHostPattern";import { AgentVaultTemplate, findTemplateForHostPattern } from "@app/helpers/agentVaultTemplates";-import { useDiscardChangesGuard, useWizardSteps } from "@app/hooks";+import { findVariableReferences, VARIABLE_KEY_RE } from "@app/helpers/agentVaultVariables";+import { useDebounce, useDiscardChangesGuard, useWizardSteps } from "@app/hooks";import {AgentVaultCredentialType,AgentVaultVariableReferenceField,+ useAgentVaultVariableKeyStatus,useCreateAgentVaultService,- useListAllAgentVaultVariables,useUpdateAgentVaultService} from "@app/hooks/api/agentVault";import {@@ -53,7 +54,11 @@ import {TServiceForm,UNCHANGED_SECRET} from "./serviceSchema";-import { NO_STORED_KEYS, ServiceVariablesContext } from "./ServiceVariablesContext";+import {+ NO_MISSING_KEYS,+ NO_STORED_KEYS,+ ServiceVariablesContext+} from "./ServiceVariablesContext";import { SERVICE_DOCS_URL, SERVICE_STEPS } from "./stepMeta";import { ADVANCED_ITEM, TransformationsFields } from "./TransformationsFields";@@ -156,8 +161,6 @@ export const ServiceSheet = ({const createService = useCreateAgentVaultService();const updateService = useUpdateAgentVaultService();- const { data: variables } = useListAllAgentVaultVariables(isOpen);- const variableKeys = useMemo(() => variables?.map((variable) => variable.key), [variables]);const storedKeys = useMemo(() => storedVariableKeys(service), [service]);// One dialog for every field. The request settles once the dialog has closed, not when the variable is// saved: until then the dialog's focus trap would pull focus back from the field that asked.@@ -176,20 +179,21 @@ export const ServiceSheet = ({[]);- const serviceVariables = useMemo(- () => ({ variables, storedKeys, requestVariable }),- [variables, storedKeys, requestVariable]- );-const [template, setTemplate] = useState<AgentVaultTemplate | null>(null);- const schema = useMemo(() => buildServiceSchema(service, variableKeys), [service, variableKeys]);+ // Read when the form validates, so the schema isn't rebuilt each time a lookup answers.+ const missingKeysRef = useRef<ReadonlySet<string>>(NO_MISSING_KEYS);+ const schema = useMemo(+ () => buildServiceSchema(service, () => missingKeysRef.current),+ [service]+ );const formMethods = useForm<TServiceForm>({defaultValues: BLANK_SERVICE_FORM,resolver: zodResolver(schema)});const {+ control,handleSubmit,reset,setError,@@ -197,6 +201,35 @@ export const ServiceSheet = ({formState: { errors, isDirty, isSubmitting }} = formMethods;+ // Only the keys the form references are looked up, never the whole list.+ const [secret, username, customHeaders, substitutions] = useWatch({+ control,+ name: ["secret", "username", "customHeaders", "substitutions"]+ });+ const referencedKeys = useMemo(() => {+ const texts = [+ secret,+ username,+ ...(customHeaders ?? []).map((header) => header.value),+ ...(substitutions ?? []).map((substitution) => substitution.value)+ ];+ const keys = texts.flatMap((text) =>+ text && text !== UNCHANGED_SECRET ? findVariableReferences(text) : []+ );+ return [...new Set(keys.filter((key) => VARIABLE_KEY_RE.test(key)))].sort().join(",");+ }, [secret, username, customHeaders, substitutions]);+ const [debouncedReferencedKeys] = useDebounce(referencedKeys, 300);+ const { missing: missingKeys } = useAgentVaultVariableKeyStatus(+ debouncedReferencedKeys ? debouncedReferencedKeys.split(",") : [],+ isOpen+ );+ missingKeysRef.current = missingKeys;++ const serviceVariables = useMemo(+ () => ({ missingKeys, storedKeys, requestVariable }),+ [missingKeys, storedKeys, requestVariable]+ );+const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =useDiscardChangesGuard({ isDirty, onDiscard: () => onOpenChange(false) });@@ -652,7 +685,6 @@ export const ServiceSheet = ({if (!open) setNewVariableKey(null);}}initialKey={newVariableKey ?? undefined}- existingKeys={variableKeys ?? []}onCreated={(variable) => {if (newVariableRequest.current) newVariableRequest.current.created = variable;}}diff --git a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.tsindex 24795ee060..75cbde57d7 100644--- a/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts+++ b/frontend/src/components/agent-vault/service-sheet/ServiceVariablesContext.ts@@ -1,10 +1,10 @@-import { createContext, useContext, useMemo } from "react";+import { createContext, useContext } from "react";import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";type TServiceVariables = {- /** Undefined while the list loads, when no key can be called unknown yet. */- variables?: TAgentVaultVariable[];+ /** Keys the form references that Agent Vault has confirmed it does not have. A key still being checked is not in it. */+ missingKeys: ReadonlySet<string>;/** The keys each stored value uses, by field. The values never return, so the fields list these. */storedKeys: {secret: string[];@@ -23,17 +23,13 @@ export const NO_STORED_KEYS: TServiceVariables["storedKeys"] = {substitutions: {}};+export const NO_MISSING_KEYS: ReadonlySet<string> = new Set();+export const ServiceVariablesContext = createContext<TServiceVariables>({+ missingKeys: NO_MISSING_KEYS,storedKeys: NO_STORED_KEYS});export const useServiceVariables = () => useContext(ServiceVariablesContext);-/** Undefined while the list loads, so nothing is marked unknown before it can be known. */-export const useKnownVariableKeys = () => {- const { variables } = useServiceVariables();- return useMemo(- () => (variables ? new Set(variables.map((variable) => variable.key)) : undefined),- [variables]- );-};+export const useMissingVariableKeys = () => useServiceVariables().missingKeys;diff --git a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsxindex ec0b7cddac..d691fbc778 100644--- a/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx+++ b/frontend/src/components/agent-vault/service-sheet/VariableSuggestions.tsx@@ -9,12 +9,19 @@ import {toVariableReference,VARIABLE_KEY_RE} from "@app/helpers/agentVaultVariables";+import { useDebounce } from "@app/hooks";+import {+ useAgentVaultVariableKeyStatus,+ useListAgentVaultVariables+} from "@app/hooks/api/agentVault";import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";import { useServiceVariables } from "./ServiceVariablesContext";type TOpenReference = { start: number; query: string };+const SUGGESTION_LIMIT = 50;+type TSuggestion =| { type: "variable"; variable: TAgentVaultVariable }| { type: "create"; key: string; isKeyValid: boolean };@@ -27,17 +34,33 @@ export const useVariableAutocomplete = ({/** The whole new value, and where in it the caret belongs. */onInsert: (value: string, caret: number) => void;}) => {- const { variables, requestVariable } = useServiceVariables();+ const { requestVariable } = useServiceVariables();const [openReference, setOpenReference] = useState<TOpenReference | null>(null);+ const query = openReference ? normalizeVariableKey(openReference.query) : "";+ const [debouncedQuery] = useDebounce(query, 200);+ const isOpen = Boolean(openReference);++ // Searched on the server, so the list never has to hold every variable. The last page stays up while the next+ // loads, filtered to the new text, which a longer query only narrows.+ const { data } = useListAgentVaultVariables(+ { search: debouncedQuery || undefined, limit: SUGGESTION_LIMIT },+ { enabled: isOpen }+ );+ // A search can show only so many, and the exact key may not be among them, so whether to offer to create it is+ // asked of that key alone.+ const { existing } = useAgentVaultVariableKeyStatus(+ isOpen && VARIABLE_KEY_RE.test(debouncedQuery) ? [debouncedQuery] : [],+ isOpen+ );const [activeIndex, setActiveIndex] = useState(0);// Escape closes the list for the reference being typed, not for the field: it opens again at the next {{.const dismissedAt = useRef<number | null>(null);const listId = useId();const suggestions = useMemo((): TSuggestion[] => {- if (!openReference || !variables) return [];- const key = normalizeVariableKey(openReference.query);- const matches = variables+ if (!openReference || !data) return [];+ const key = query;+ const matches = data.variables.filter((variable) => variable.key.includes(key)).sort((a, b) =>@@ -46,9 +69,10 @@ export const useVariableAutocomplete = ({).map((variable) => ({ type: "variable" as const, variable }));- if (!requestVariable || variables.some((variable) => variable.key === key)) return matches;+ const keyExists = matches.some(({ variable }) => variable.key === key) || existing.has(key);+ if (!requestVariable || keyExists) return matches;return [...matches, { type: "create", key, isKeyValid: VARIABLE_KEY_RE.test(key) }];- }, [openReference, variables, requestVariable]);+ }, [openReference, query, data, existing, requestVariable]);const close = () => setOpenReference(null);@@ -139,7 +163,9 @@ export const useVariableAutocomplete = ({};return {- isOpen: Boolean(openReference),+ isOpen,+ isLoading: isOpen && !data,+ query,suggestions,activeIndex,setActiveIndex,@@ -163,10 +189,19 @@ export const VariableSuggestions = ({autocomplete: TAutocomplete;children: ReactNode;}) => {- const { variables } = useServiceVariables();const anchorRef = useRef<HTMLDivElement>(null);- const { isOpen, suggestions, activeIndex, setActiveIndex, listId, optionId, choose, dismiss } =- autocomplete;+ const {+ isOpen,+ isLoading,+ query,+ suggestions,+ activeIndex,+ setActiveIndex,+ listId,+ optionId,+ choose,+ dismiss+ } = autocomplete;const variableSuggestions = suggestions.filter((suggestion) => suggestion.type === "variable");const createSuggestion = suggestions.find((suggestion) => suggestion.type === "create");@@ -246,9 +281,11 @@ export const VariableSuggestions = ({</div>) : (<p className="px-2 py-1.5 text-xs text-muted">- {variables?.length- ? "No variable matches that name."- : "No variables yet. Add one under Variables."}+ {(() => {+ if (isLoading) return "Loading variables...";+ if (query) return "No variable matches that name.";+ return "No variables yet. Add one under Variables.";+ })()}</p>)}</PopoverContent>diff --git a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts b/frontend/src/components/agent-vault/service-sheet/serviceSchema.tsindex 5304b358e4..ad89f006c6 100644--- a/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts+++ b/frontend/src/components/agent-vault/service-sheet/serviceSchema.ts@@ -104,8 +104,14 @@ export const SERVICE_STEP_FIELDS: Record<ServiceStep, string[]> = {[ServiceStep.Review]: []};-/** `variableKeys` stays undefined while the list loads, so only the shape of a reference is checked. */-export const buildServiceSchema = (service?: TAgentVaultService | null, variableKeys?: string[]) =>+/**+ * Missing keys are read when the form validates rather than when the schema is built, since they arrive as each+ * lookup answers. A key still being checked passes here; the API refuses it on save if it doesn't exist.+ */+export const buildServiceSchema = (+ service?: TAgentVaultService | null,+ getMissingKeys?: () => ReadonlySet<string>+) =>z.object({name: slugSchema({ max: 64, field: "Name" }),@@ -296,10 +302,10 @@ export const buildServiceSchema = (service?: TAgentVaultService | null, variable}});- const variableKeySet = variableKeys ? new Set(variableKeys) : undefined;+ const missingKeys = getMissingKeys?.();const addReferenceIssue = (value: string | undefined, path: (string | number)[]) => {if (!value || value === UNCHANGED_SECRET) return;- const message = variableReferenceError(value, variableKeySet);+ const message = variableReferenceError(value, missingKeys);if (message) ctx.addIssue({ code: z.ZodIssueCode.custom, path, message });};diff --git a/frontend/src/helpers/agentVaultVariables.test.ts b/frontend/src/helpers/agentVaultVariables.test.tsindex c4f47384eb..c76be2bce0 100644--- a/frontend/src/helpers/agentVaultVariables.test.ts+++ b/frontend/src/helpers/agentVaultVariables.test.ts@@ -49,12 +49,13 @@ describe("variableReferenceError", () => {});- it("passes a well-formed reference to a key Agent Vault has", () => {- expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["GITHUB_TOKEN"]))).toBeNull();+ it("passes a well-formed reference to a key not known to be missing", () => {+ expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["OTHER"]))).toBeNull();+ expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}")).toBeNull();});it("names a key Agent Vault does not have, in the API's words", () => {- expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["OTHER"]))).toBe(+ expect(variableReferenceError("Bearer {{GITHUB_TOKEN}}", new Set(["GITHUB_TOKEN"]))).toBe("Agent Vault has no variable named 'GITHUB_TOKEN'. Add it under Variables, or correct the name.");});diff --git a/frontend/src/helpers/agentVaultVariables.ts b/frontend/src/helpers/agentVaultVariables.tsindex a004796c08..6e482fad84 100644--- a/frontend/src/helpers/agentVaultVariables.ts+++ b/frontend/src/helpers/agentVaultVariables.ts@@ -71,10 +71,13 @@ export const findVariableReferenceAtCaret = (text: string, caret: number) => {};/**- * The first problem with the references in a field, or null. Without `keys`, which is the case while- * the list loads, only the shape of each reference is checked.+ * The first problem with the references in a field, or null. A key counts as unknown only once it is in+ * `missingKeys`, so one still being looked up passes.*/-export const variableReferenceError = (text: string, keys?: ReadonlySet<string>): string | null => {+export const variableReferenceError = (+ text: string,+ missingKeys?: ReadonlySet<string>+): string | null => {const refs = findVariableReferences(text);if (refs.length > MAX_REFERENCES_PER_FIELD) {@@ -86,7 +89,7 @@ export const variableReferenceError = (text: string, keys?: ReadonlySet<string>)return `"${toVariableReference(malformed)}" isn't a valid variable reference. ${VARIABLE_KEY_MESSAGE}`;}- const missing = keys ? refs.find((ref) => !keys.has(ref)) : undefined;+ const missing = refs.find((ref) => missingKeys?.has(ref));if (missing) {return `Agent Vault has no variable named '${missing}'. Add it under Variables, or correct the name.`;}diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 2e25e3e554..8c23ba96d1 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -412,11 +412,8 @@ export const useCreateAgentVaultVariable = () => {return data.variable;},onSuccess: (variable) => {- // Listed before the refetch lands, so a reference to it that was just inserted reads as known.- queryClient.setQueryData<TAgentVaultVariable[]>(- agentVaultKeys.allVariables(currentOrg.id),- (prev) => (prev ? [...prev, variable].sort((a, b) => a.key.localeCompare(b.key)) : prev)- );+ // Known before the refetch lands, so a reference to it that was just inserted isn't flagged.+ queryClient.setQueryData(agentVaultKeys.variableKeyStatus(currentOrg.id, variable.key), true);return invalidateVariables(queryClient, currentOrg.id);}});diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex eb1d6a0ba8..96267813d5 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -1,5 +1,11 @@-import { useRef, useState } from "react";-import { InfiniteData, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query";+import { useMemo, useRef, useState } from "react";+import {+ InfiniteData,+ useInfiniteQuery,+ useQueries,+ useQuery,+ useQueryClient+} from "@tanstack/react-query";import axios from "axios";import { apiRequest } from "@app/config/request";@@ -92,7 +98,8 @@ export const agentVaultKeys = {variables: (orgId: string) => [...agentVaultKeys.all(orgId), "variables"] as const,variableList: (orgId: string, params: TListAgentVaultVariablesDTO) =>[...agentVaultKeys.variables(orgId), "list", params] as const,- allVariables: (orgId: string) => [...agentVaultKeys.variables(orgId), "all"] as const,+ variableKeyStatus: (orgId: string, key: string) =>+ [...agentVaultKeys.variables(orgId), "key-status", key] as const,members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>[...agentVaultKeys.members(orgId), params] as const,@@ -533,47 +540,50 @@ export const useGetAgentVaultSessionLogs = (type TAgentVaultVariablePage = { variables: TAgentVaultVariable[]; totalCount: number };-const fetchAgentVaultVariables = async (params: TListAgentVaultVariablesDTO) => {+const fetchAgentVaultVariables = async ({ keys, ...params }: TListAgentVaultVariablesDTO) => {const { data } = await apiRequest.get<TAgentVaultVariablePage>("/api/v1/agent-vault/variables", {- params+ params: { ...params, keys: keys?.join(",") }});return data;};-export const useListAgentVaultVariables = (params: TListAgentVaultVariablesDTO = {}) => {+export const useListAgentVaultVariables = (+ params: TListAgentVaultVariablesDTO = {},+ { enabled = true }: { enabled?: boolean } = {}+) => {const { currentOrg } = useOrganization();return useQuery({queryKey: agentVaultKeys.variableList(currentOrg.id, params),queryFn: () => fetchAgentVaultVariables(params),- placeholderData: (prev) => prev+ placeholderData: (prev) => prev,+ enabled});};-const ALL_VARIABLES_PAGE_SIZE = 100;--// Every variable, sorted by key, for suggesting and checking references, which need the whole set. The product-// caps how many there can be, so this is a handful of pages at most.-export const useListAllAgentVaultVariables = (enabled = true) => {+// Whether each key exists, one cached query per key, so a key checked once is never asked about again until a+// variable changes. Only keys whose answer has arrived are in either set: a pending one is neither.+export const useAgentVaultVariableKeyStatus = (keys: readonly string[], enabled = true) => {const { currentOrg } = useOrganization();- return useQuery({- queryKey: agentVaultKeys.allVariables(currentOrg.id),- queryFn: async () => {- const variables: TAgentVaultVariable[] = [];- let totalCount = Infinity;- while (variables.length < totalCount) {- // eslint-disable-next-line no-await-in-loop- const page = await fetchAgentVaultVariables({- limit: ALL_VARIABLES_PAGE_SIZE,- offset: variables.length- });- variables.push(...page.variables);- totalCount = page.totalCount;- if (page.variables.length < ALL_VARIABLES_PAGE_SIZE) break;- }- return variables;- },- enabled+ const { existing, missing } = useQueries({+ queries: keys.map((key) => ({+ queryKey: agentVaultKeys.variableKeyStatus(currentOrg.id, key),+ queryFn: async () =>+ (await fetchAgentVaultVariables({ keys: [key], limit: 1 })).totalCount > 0,+ enabled+ })),+ combine: (results) => ({+ existing: keys.filter((_, index) => results[index]?.data === true).join(","),+ missing: keys.filter((_, index) => results[index]?.data === false).join(",")+ })});++ return useMemo(+ () => ({+ existing: new Set(existing ? existing.split(",") : []) as ReadonlySet<string>,+ missing: new Set(missing ? missing.split(",") : []) as ReadonlySet<string>+ }),+ [existing, missing]+ );};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex e330bd93f8..5ec7873cd5 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -140,6 +140,8 @@ export type TListAgentVaultAccessBundlesDTO = Omit<TListAgentVaultProxiesDTO, "oexport type TListAgentVaultVariablesDTO = {search?: string;+ /** Exact keys. A key that doesn't exist is left out of the response. */+ keys?: string[];orderBy?: "key" | "usedBy";orderDirection?: "asc" | "desc";limit?: number;diff --git a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsxindex fa8495a8ce..5cdae6d1fb 100644--- a/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultVariablesPage/components/VariablesCard.tsx@@ -56,7 +56,6 @@ import {import { useDebounce, useResetPageHelper } from "@app/hooks";import {useListAgentVaultVariables,- useListAllAgentVaultVariables,useRevealAgentVaultVariableValue} from "@app/hooks/api/agentVault";import { TAgentVaultVariable } from "@app/hooks/api/agentVault/types";@@ -238,9 +237,6 @@ export const VariablesCard = () => {const totalCount = data?.totalCount ?? 0;useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });- // The dialog checks a new key against every key, which no single page holds.- const { data: allVariables } = useListAllAgentVaultVariables(isFormOpen);-const handleSort = (column: SortColumn, direction: "ascending" | "descending" | "none") => {setPage(1);if (direction === "none") {@@ -498,7 +494,6 @@ export const VariablesCard = () => {isOpen={isFormOpen}onOpenChange={setIsFormOpen}variable={variableToEdit}- existingKeys={allVariables?.map((variable) => variable.key) ?? []}/><DeleteVariableDialog