Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(tagging): Phase 6.1 frontend — key-optional labels + flexible tag filter (SKY-10683) (#6470)
Trevor Cheung987a6df20e50
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsxindex 912823984..e95a37bee 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx@@ -176,9 +176,7 @@ function WorkflowPage() {</>)}</div>- {!workflowIsLoading &&- workflowTags &&- Object.keys(workflowTags).length > 0 ? (+ {!workflowIsLoading && workflowTags && workflowTags.length > 0 ? (<TagChipListtags={workflowTags}descriptions={tagDescriptions}diff --git a/skyvern-frontend/src/routes/workflows/Workflows.tsx b/skyvern-frontend/src/routes/workflows/Workflows.tsxindex d1d1182c1..db6233b0f 100644--- a/skyvern-frontend/src/routes/workflows/Workflows.tsx+++ b/skyvern-frontend/src/routes/workflows/Workflows.tsx@@ -65,7 +65,7 @@ import { WorkflowTagEditor } from "./components/tagging/WorkflowTagEditor";import {parseTagFilter,serializeTagFilter,- type TagFilterPair,+ type TagFilterTerm,} from "./types/tagTypes";import { ImportWorkflowButton } from "./ImportWorkflowButton";import { convert } from "./editor/workflowEditorUtils";@@ -146,9 +146,9 @@ function Workflows() {const serializedTagFilter = serializeTagFilter(tagFilters);const setTagFilters = useCallback(- (pairs: TagFilterPair[]) => {+ (terms: TagFilterTerm[]) => {const params = new URLSearchParams(searchParams);- const serialized = serializeTagFilter(pairs);+ const serialized = serializeTagFilter(terms);if (serialized) {params.set("tags", serialized);} else {@@ -342,25 +342,33 @@ function Workflows() {);const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(workflowIds);- // Distinct values per key observed on the page, used as filter suggestions.- // Maps avoid prototype-key collisions from user-controlled tag keys.- const tagValueSuggestions = useMemo(() => {+ // Tags observed on the page for editor/filter suggestions: grouped values per+ // key plus standalone labels. Maps avoid prototype-key collisions.+ const { valueSuggestionsByKey, labelSuggestions } = useMemo(() => {const collected = new Map<string, Set<string>>();+ const labels = new Set<string>();for (const tags of Object.values(workflowTagsMap)) {- for (const [key, value] of Object.entries(tags)) {- let values = collected.get(key);+ for (const tag of tags) {+ if (tag.key === null) {+ labels.add(tag.value);+ continue;+ }+ let values = collected.get(tag.key);if (!values) {values = new Set<string>();- collected.set(key, values);+ collected.set(tag.key, values);}- values.add(value);+ values.add(tag.value);}}- const suggestions = new Map<string, string[]>();+ const byKey = new Map<string, string[]>();for (const [key, values] of collected) {- suggestions.set(key, [...values].sort());+ byKey.set(key, [...values].sort());}- return suggestions;+ return {+ valueSuggestionsByKey: byKey,+ labelSuggestions: [...labels].sort(),+ };}, [workflowTagsMap]);const { matchesParameter, isSearchActive } =@@ -587,7 +595,8 @@ function Workflows() {tagKeys={tagKeys}value={tagFilters}onChange={setTagFilters}- valueSuggestions={tagValueSuggestions}+ labelSuggestions={labelSuggestions}+ valueSuggestionsByKey={valueSuggestionsByKey}/></div><div className="flex items-center gap-4">@@ -785,8 +794,7 @@ function Workflows() {</TooltipProvider>)}</div>- {workflowTags &&- Object.keys(workflowTags).length > 0 ? (+ {workflowTags && workflowTags.length > 0 ? (<TagChipListtags={workflowTags}descriptions={tagDescriptions}@@ -860,9 +868,10 @@ function Workflows() {workflowPermanentId={workflow.workflow_permanent_id}- tags={workflowTags ?? {}}+ tags={workflowTags ?? []}tagKeys={tagKeys}- valueSuggestions={tagValueSuggestions}+ labelSuggestions={labelSuggestions}+ valueSuggestionsByKey={valueSuggestionsByKey}/><TooltipProvider><Tooltip>diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsxindex 69f8c1ae4..59fa1fad2 100644--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx@@ -9,18 +9,18 @@ import { badgeVariants } from "@/components/ui/badge-variants";import { cn } from "@/util/utils";type Props = {- tagKey: string;+ // null = a standalone label (no group); rendered as just the value.+ tagKey: string | null;value: string;description?: string | null;onRemove?: () => void;className?: string;};-// Generic single-tag chip. Rendered as a styled span (not the Badge div) so it-// can be a Radix TooltipTrigger `asChild` target without a ref/nesting warning.-// Reusable wherever a `key: value` tag is shown (workflow cards today, run-tag-// UI later).+// Generic single-tag chip: a styled span (not Badge div) so it can be a Radix+// TooltipTrigger `asChild` target. Grouped shows `key: value`, standalone the value.function TagChip({ tagKey, value, description, onRemove, className }: Props) {+ const label = tagKey === null ? value : `${tagKey}: ${value}`;const chip = (<spanclassName={cn(@@ -30,14 +30,18 @@ function TagChip({ tagKey, value, description, onRemove, className }: Props) {)}><span className="truncate">- <span className="font-medium">{tagKey}</span>- <span className="text-muted-foreground">: </span>+ {tagKey !== null ? (+ <>+ <span className="font-medium">{tagKey}</span>+ <span className="text-muted-foreground">: </span>+ </>+ ) : null}{value}</span>{onRemove ? (<buttontype="button"- aria-label={`Remove ${tagKey}: ${value}`}+ aria-label={`Remove ${label}`}className="ml-0.5 shrink-0 rounded-sm opacity-70 hover:opacity-100"onClick={(event) => {event.stopPropagation();diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsxindex 8adaa077c..51279d5c5 100644--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx@@ -6,36 +6,38 @@ import {} from "@/components/ui/tooltip";import { badgeVariants } from "@/components/ui/badge-variants";import { cn } from "@/util/utils";+import { sortTags, tagElementKey, type Tag } from "../../types/tagTypes";import { TagChip } from "./TagChip";type Props = {- tags: Record<string, string>;- // Map (not a plain object) so lookups by user-controlled tag keys can't hit- // inherited Object prototype members (e.g. a key named "constructor").+ tags: Array<Tag>;+ // Group (key) -> description. A Map (not a plain object) so user-controlled keys+ // can't hit Object prototype members (e.g. a key named "constructor").descriptions?: Map<string, string | null>;maxVisible?: number;className?: string;};-// Generic list of tag chips with a "+N" overflow affordance. Sorts by key for-// stable ordering across renders. Reusable for any key->value tag map.+// Generic list of tag chips with a "+N" overflow affordance. Standalone labels+// sort first, then grouped by key, for stable ordering across renders.function TagChipList({ tags, descriptions, maxVisible = 3, className }: Props) {- const entries = Object.entries(tags).sort(([a], [b]) => a.localeCompare(b));- if (entries.length === 0) {+ if (tags.length === 0) {return null;}-- const visible = entries.slice(0, maxVisible);- const hidden = entries.slice(maxVisible);+ const sorted = sortTags(tags);+ const visible = sorted.slice(0, maxVisible);+ const hidden = sorted.slice(maxVisible);return (<div className={cn("flex flex-wrap items-center gap-1", className)}>- {visible.map(([key, value]) => (+ {visible.map((tag) => (<TagChip- key={key}- tagKey={key}- value={value}- description={descriptions?.get(key)}+ key={tagElementKey(tag)}+ tagKey={tag.key}+ value={tag.value}+ description={+ tag.key !== null ? descriptions?.get(tag.key) : undefined+ }/>))}{hidden.length > 0 ? (@@ -53,9 +55,14 @@ function TagChipList({ tags, descriptions, maxVisible = 3, className }: Props) {</TooltipTrigger><TooltipContent className="max-w-xs"><div className="flex flex-col gap-1">- {hidden.map(([key, value]) => (- <span key={key} className="break-words">- <span className="font-medium">{key}</span>: {value}+ {hidden.map((tag) => (+ <span key={tagElementKey(tag)} className="break-words">+ {tag.key !== null ? (+ <>+ <span className="font-medium">{tag.key}</span>:{" "}+ </>+ ) : null}+ {tag.value}</span>))}</div>diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagEditor.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagEditor.tsxindex 1db0aee36..d58972383 100644--- a/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagEditor.tsx+++ b/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagEditor.tsx@@ -1,10 +1,5 @@import * as React from "react";-import {- ArrowLeftIcon,- PlusIcon,- ReloadIcon,- TokensIcon,-} from "@radix-ui/react-icons";+import { PlusIcon, ReloadIcon, TokensIcon } from "@radix-ui/react-icons";import { Button } from "@/components/ui/button";import {Command,@@ -27,108 +22,100 @@ import {} from "@/components/ui/tooltip";import { toast } from "@/components/ui/use-toast";import {+ MAX_AUTOCOMPLETE_SUGGESTIONS,MAX_TAGS_PER_WORKFLOW,- validateTagKey,- validateTagValue,+ parseTagInput,+ parseTypedTagQuery,+ serializeTagFilterTerm,+ sortTags,+ tagElementKey,+ validateTag,+ type Tag,+ type TagDeleteInput,type TagKey,} from "../../types/tagTypes";-import {- useApplyWorkflowTagsMutation,- useDeleteWorkflowTagMutation,-} from "../../hooks/useWorkflowTagMutations";+import { useApplyWorkflowTagsMutation } from "../../hooks/useWorkflowTagMutations";import { TagChip } from "./TagChip";type Props = {workflowPermanentId: string;- tags: Record<string, string>;+ tags: Array<Tag>;+ // Registered groups (keys) for autocomplete; standalone labels aren't here.tagKeys: Array<TagKey>;- // key -> existing values observed on the page, so the value step can suggest- // existing values for the chosen key (the backend has no list-values- // endpoint). Free-text entry still works. A Map keeps lookups safe against- // tag keys like "constructor".- valueSuggestions?: Map<string, Array<string>>;+ // Standalone label values observed on the page, suggested when typing a label.+ labelSuggestions?: Array<string>;+ // Grouped values observed per key, suggested after typing `group:`.+ valueSuggestionsByKey?: Map<string, Array<string>>;};-// Inline tag editor for a workflow row: add / overwrite / remove tags. Uses a-// cmdk Command (key step -> value step) rather than native <datalist>, which is-// unreliable inside a Radix popover; this mirrors WorkflowTagFilter so key and-// value autosuggest behave the same. Adding a key that already exists overwrites-// its value (backend set-wins) = the edit path.+// Inline tag editor: type a bare `label` for a standalone tag or `group:label`+// for a grouped one. Re-adding overwrites that group's label (backend set-wins).function WorkflowTagEditor({workflowPermanentId,tags,tagKeys,- valueSuggestions,+ labelSuggestions = [],+ valueSuggestionsByKey,}: Props) {const [open, setOpen] = React.useState(false);- const [selectedKey, setSelectedKey] = React.useState<string | null>(null);const [query, setQuery] = React.useState("");const [error, setError] = React.useState<string | null>(null);const applyMutation = useApplyWorkflowTagsMutation();- const deleteMutation = useDeleteWorkflowTagMutation();- const isPending = applyMutation.isPending || deleteMutation.isPending;-- const entries = Object.entries(tags).sort(([a], [b]) => a.localeCompare(b));-- function resetForm() {- setSelectedKey(null);- setQuery("");- setError(null);- }+ const isPending = applyMutation.isPending;React.useEffect(() => {- // Inline the resets (rather than calling resetForm) so the effect's only- // dependency is `open`; setState identities are stable.if (!open) {- setSelectedKey(null);setQuery("");setError(null);}}, [open]);- function applyTag(key: string, value: string) {- // A write is in flight; ignore further selects so quick double Enter/click- // can't queue racing POSTs whose arrival order would decide the final tag- // (backend is set-wins).+ const sortedTags = React.useMemo(() => sortTags(tags), [tags]);++ function addTag(tag: Tag) {+ // A write is in flight; ignore further adds so a quick double Enter/click+ // can't queue racing POSTs whose arrival order would decide the final tag.if (isPending) {return;}- const trimmedKey = key.trim();- const trimmedValue = value.trim();-- const keyError = validateTagKey(trimmedKey);- if (keyError) {- setError(keyError);+ const validationError = validateTag(tag);+ if (validationError) {+ setError(validationError);return;}- const valueError = validateTagValue(trimmedValue);- if (valueError) {- setError(valueError);+ const exactExists = tags.some(+ (existing) => existing.key === tag.key && existing.value === tag.value,+ );+ if (exactExists) {+ setQuery("");+ setError(null);return;}- // Own-key check: `key in tags` would treat inherited names like- // "constructor"/"toString" (valid backend tag keys) as already present.- const hasKey = Object.prototype.hasOwnProperty.call(tags, trimmedKey);- const previousValue = hasKey ? tags[trimmedKey] : undefined;- if (!hasKey && Object.keys(tags).length >= MAX_TAGS_PER_WORKFLOW) {+ // A grouped tag with an existing key overwrites that group's label (no new+ // identity); anything else is a new tag and counts against the cap.+ const previousInGroup =+ tag.key !== null+ ? tags.find((existing) => existing.key === tag.key)+ : undefined;+ const isOverwrite = previousInGroup !== undefined;+ if (!isOverwrite && tags.length >= MAX_TAGS_PER_WORKFLOW) {setError(`A workflow can have at most ${MAX_TAGS_PER_WORKFLOW} tags.`);return;}- // Same key, different value: the backend overwrites (set-wins); proceed but- // tell the user it replaced the existing tag.- const isOverwrite =- previousValue !== undefined && previousValue !== trimmedValue;-applyMutation.mutate(- { workflowPermanentId, data: { tags: { [trimmedKey]: trimmedValue } } },+ {+ workflowPermanentId,+ data: { tags: [{ key: tag.key, value: tag.value }] },+ },{onSuccess: () => {- resetForm();- if (isOverwrite) {+ setQuery("");+ setError(null);+ if (isOverwrite && previousInGroup) {toast({title: "Tag overwritten",- description: `“${trimmedKey}” changed from “${previousValue}” to “${trimmedValue}”.`,+ description: `“${tag.key}” changed from “${previousInGroup.value}” to “${tag.value}”.`,});}},@@ -136,37 +123,52 @@ function WorkflowTagEditor({);}- function handleRemove(key: string) {+ function removeTag(tag: Tag) {if (isPending) {return;}- deleteMutation.mutate({ workflowPermanentId, key });+ // Grouped tags delete by key, standalone labels by value.+ const target: TagDeleteInput =+ tag.key !== null ? { key: tag.key } : { value: tag.value };+ applyMutation.mutate({+ workflowPermanentId,+ data: { tags_to_delete: [target] },+ });}- const normalizedQuery = query.trim().toLowerCase();const trimmedQuery = query.trim();+ const normalizedQuery = trimmedQuery.toLowerCase();+ const candidate = parseTagInput(query);+ const candidateExists =+ candidate !== null &&+ tags.some((t) => t.key === candidate.key && t.value === candidate.value);+ const showAdd = candidate !== null && !candidateExists;- // Rank an exact (case-insensitive) match first so cmdk highlights it by- // default — plain Enter then commits the exact typed text, while arrow+Enter- // still selects any other highlighted suggestion (sort is stable otherwise).- const exactFirst = (a: string, b: string) =>- (a.toLowerCase() === normalizedQuery ? 0 : 1) -- (b.toLowerCase() === normalizedQuery ? 0 : 1);-- const filteredKeys = tagKeys- .filter((tagKey) => tagKey.key.toLowerCase().includes(normalizedQuery))- .sort((a, b) => exactFirst(a.key, b.key));- const showUseKey =- trimmedQuery.length > 0 && !tagKeys.some((tk) => tk.key === trimmedQuery);+ // When the user has typed `group:partial`, suggest existing values for that+ // group; otherwise suggest groups (to start a grouped tag) and labels.+ const { typedKey, typedValuePartial } = parseTypedTagQuery(trimmedQuery);- const suggestionsForKey = selectedKey- ? (valueSuggestions?.get(selectedKey) ?? [])- : [];- const filteredValues = suggestionsForKey- .filter((value) => value.toLowerCase().includes(normalizedQuery))- .sort(exactFirst);- const showAddValue =- trimmedQuery.length > 0 && !suggestionsForKey.includes(trimmedQuery);+ const groupSuggestions =+ typedKey === null+ ? tagKeys+ .filter((tk) => tk.key.toLowerCase().includes(normalizedQuery))+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];+ const labelMatches =+ typedKey === null+ ? labelSuggestions+ .filter((value) => value.toLowerCase().includes(normalizedQuery))+ .filter(+ (value) => !tags.some((t) => t.key === null && t.value === value),+ )+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];+ const groupedValueMatches =+ typedKey !== null+ ? (valueSuggestionsByKey?.get(typedKey) ?? [])+ .filter((value) => value.toLowerCase().includes(typedValuePartial))+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];return (<Popover open={open} onOpenChange={setOpen}>@@ -190,14 +192,14 @@ function WorkflowTagEditor({<PopoverContent className="w-80 p-0" align="end"><div className="space-y-2 p-3"><div className="text-sm font-medium">Tags</div>- {entries.length > 0 ? (+ {sortedTags.length > 0 ? (<div className="flex flex-wrap gap-1">- {entries.map(([key, value]) => (+ {sortedTags.map((tag) => (<TagChip- key={key}- tagKey={key}- value={value}- onRemove={() => handleRemove(key)}+ key={tagElementKey(tag)}+ tagKey={tag.key}+ value={tag.value}+ onRemove={() => removeTag(tag)}/>))}</div>@@ -209,119 +211,89 @@ function WorkflowTagEditor({) : null}</div><Command shouldFilter={false}>- {selectedKey === null ? (- <>- <CommandInput- placeholder="Tag key…"- value={query}- onValueChange={(value) => {- setQuery(value);- setError(null);- }}- />- <CommandList>- <CommandEmpty>Type a key to add.</CommandEmpty>- {showUseKey ? (- <CommandGroup>- <CommandItem- value={`__use__,${trimmedQuery}`}- onSelect={() => {- setSelectedKey(trimmedQuery);- setQuery("");- }}- >- <PlusIcon className="mr-2 h-4 w-4" />- Use “{trimmedQuery}”- </CommandItem>- </CommandGroup>- ) : null}- {filteredKeys.length > 0 ? (- <CommandGroup heading="Existing keys">- {filteredKeys.map((tagKey) => (- <CommandItem- key={tagKey.key}- value={tagKey.key}- onSelect={() => {- setSelectedKey(tagKey.key);- setQuery("");- }}- >- <div className="flex min-w-0 flex-col">- <span className="truncate">{tagKey.key}</span>- {tagKey.description ? (- <span className="truncate text-xs text-muted-foreground">- {tagKey.description}- </span>- ) : null}- </div>- </CommandItem>- ))}- </CommandGroup>- ) : null}- </CommandList>- </>- ) : (- <>- <div className="flex items-center gap-1 border-b px-2 py-1.5">- <Button- variant="ghost"- size="icon"- className="h-6 w-6 shrink-0"- onClick={() => {- setSelectedKey(null);- setQuery("");- }}+ <CommandInput+ placeholder="Add a tag — label or group:label…"+ value={query}+ onValueChange={(value) => {+ setQuery(value);+ setError(null);+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter" && candidate && showAdd) {+ event.preventDefault();+ addTag(candidate);+ }+ }}+ />+ <CommandList>+ <CommandEmpty>Type a label or group:label.</CommandEmpty>+ {showAdd && candidate ? (+ <CommandGroup>+ <CommandItem+ value={`__add__,${trimmedQuery}`}+ onSelect={() => addTag(candidate)}>- <ArrowLeftIcon className="h-4 w-4" />- </Button>- <span className="truncate text-sm font-medium">- {selectedKey}- </span>- </div>- <CommandInput- placeholder="Value…"- value={query}- onValueChange={(value) => {- setQuery(value);- setError(null);- }}- />- <CommandList>- <CommandEmpty>Type a value to add.</CommandEmpty>- {showAddValue ? (- <CommandGroup>- {/* cmdk item values must be unique. The comma can't appear- in a valid tag value, so this sentinel can never collide- with a real suggestion's value. */}- <CommandItem- value={`__add__,${trimmedQuery}`}- onSelect={() => applyTag(selectedKey, trimmedQuery)}- >- {applyMutation.isPending ? (- <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />- ) : (- <PlusIcon className="mr-2 h-4 w-4" />- )}- Add “{selectedKey}: {trimmedQuery}”- </CommandItem>- </CommandGroup>- ) : null}- {filteredValues.length > 0 ? (- <CommandGroup heading="Existing values">- {filteredValues.map((value) => (- <CommandItem- key={value}- value={value}- onSelect={() => applyTag(selectedKey, value)}- >- {value}- </CommandItem>- ))}- </CommandGroup>- ) : null}- </CommandList>- </>- )}+ {isPending ? (+ <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />+ ) : (+ <PlusIcon className="mr-2 h-4 w-4" />+ )}+ Add “+ {candidate.key !== null+ ? `${candidate.key}: ${candidate.value}`+ : candidate.value}+ ”+ </CommandItem>+ </CommandGroup>+ ) : null}+ {groupSuggestions.length > 0 ? (+ <CommandGroup heading="Groups">+ {groupSuggestions.map((tk) => (+ <CommandItem+ key={tk.key}+ value={`__group__,${tk.key}`}+ // Selecting a group seeds `group:` so the next keystrokes+ // type the label.+ onSelect={() => setQuery(`${tk.key}:`)}+ >+ <span className="font-medium">{tk.key}</span>+ <span className="text-muted-foreground">:</span>+ {tk.description ? (+ <span className="ml-2 truncate text-xs text-muted-foreground">+ {tk.description}+ </span>+ ) : null}+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ {labelMatches.length > 0 ? (+ <CommandGroup heading="Labels">+ {labelMatches.map((value) => (+ <CommandItem+ key={`label:${value}`}+ value={`__label__,${value}`}+ onSelect={() => addTag({ key: null, value })}+ >+ {value}+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ {groupedValueMatches.length > 0 && typedKey !== null ? (+ <CommandGroup heading={`Existing ${typedKey} values`}>+ {groupedValueMatches.map((value) => (+ <CommandItem+ key={`gv:${value}`}+ value={`__gv__,${value}`}+ onSelect={() => addTag({ key: typedKey, value })}+ >+ {serializeTagFilterTerm({ key: typedKey, value })}+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ </CommandList></Command></PopoverContent></Popover>diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagFilter.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagFilter.tsxindex 9b78c15fb..0c50b82b1 100644--- a/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagFilter.tsx+++ b/skyvern-frontend/src/routes/workflows/components/tagging/WorkflowTagFilter.tsx@@ -1,7 +1,6 @@import * as React from "react";import {- ArrowLeftIcon,- CheckIcon,+ Cross2Icon,PlusIcon,ReloadIcon,TokensIcon,@@ -29,92 +28,97 @@ import {PopoverContent,PopoverTrigger,} from "@/components/ui/popover";+import { badgeVariants } from "@/components/ui/badge-variants";import { cn } from "@/util/utils";import { copyText } from "@/util/copyText";import { toast } from "@/components/ui/use-toast";-import type { TagFilterPair, TagKey } from "../../types/tagTypes";+import {+ MAX_AUTOCOMPLETE_SUGGESTIONS,+ parseTagFilterTerm,+ parseTypedTagQuery,+ termDedupeKey,+ type TagFilterTerm,+ type TagKey,+} from "../../types/tagTypes";import { useDeleteTagKeyMutation } from "../../hooks/useWorkflowTagMutations";-import { TagChip } from "./TagChip";type Props = {tagKeys: Array<TagKey>;- value: Array<TagFilterPair>;- onChange: (pairs: Array<TagFilterPair>) => void;- // key -> distinct values observed on the current page; used to suggest values- // since the backend has no "list values for key" endpoint. Free-text entry- // always works regardless. A Map (not a plain object) so a tag key like- // "constructor" can't resolve to an inherited Object prototype member.- valueSuggestions?: Map<string, Array<string>>;+ value: Array<TagFilterTerm>;+ onChange: (terms: Array<TagFilterTerm>) => void;+ // Standalone label values observed on the page (for value-only suggestions).+ labelSuggestions?: Array<string>;+ // Grouped values observed per key (for exact suggestions after `group:`).+ valueSuggestionsByKey?: Map<string, Array<string>>;};-// Tag filter pill for the workflows-list page. Collects `key:value` pairs; the-// backend (GET /workflows?tags=) ANDs across distinct keys and ORs within a-// key, so adding several values for one key is the OR-within-key path.+// Group identity used for display + dedupe: exact terms sharing a key OR+// together (shown adjacent), everything else is its own AND conjunct.+function termGroupId(term: TagFilterTerm): string {+ if (term.key === null) {+ return `l:${term.value}`; // label+ }+ if (term.value === null) {+ return `k:${term.key}`; // group-only+ }+ return `e:${term.key}`; // exact (OR within key)+}++function sameTerm(a: TagFilterTerm, b: TagFilterTerm): boolean {+ return a.key === b.key && a.value === b.value;+}++// Tag filter pill for the workflows list. Collects terms in three shapes — label+// (value-only), group (`key:*`), and exact (group:label). Backend ANDs, ORs per key.function WorkflowTagFilter({tagKeys,value,onChange,- valueSuggestions,+ labelSuggestions = [],+ valueSuggestionsByKey,}: Props) {const [open, setOpen] = React.useState(false);- const [selectedKey, setSelectedKey] = React.useState<string | null>(null);const [query, setQuery] = React.useState("");const [keyToDelete, setKeyToDelete] = React.useState<TagKey | null>(null);const deleteKeyMutation = useDeleteTagKeyMutation();React.useEffect(() => {if (!open) {- setSelectedKey(null);setQuery("");}}, [open]);- function addPair(key: string, rawValue: string) {- const trimmedKey = key.trim();- const trimmedValue = rawValue.trim();- // Comma is the pair separator in the serialized `tags` param, so a value- // containing one cannot round-trip (it would split into a different- // filter). Backend filter values can't contain commas, so reject here.- if (!trimmedKey || !trimmedValue || trimmedValue.includes(",")) {- return;- }- const exists = value.some(- (pair) => pair.key === trimmedKey && pair.value === trimmedValue,- );- if (exists) {+ function addTerm(term: TagFilterTerm) {+ if (value.some((existing) => sameTerm(existing, term))) {+ setQuery("");return;}- onChange([...value, { key: trimmedKey, value: trimmedValue }]);+ onChange([...value, term]);+ setQuery("");}- function removePair(target: TagFilterPair) {- onChange(- value.filter(- (pair) => !(pair.key === target.key && pair.value === target.value),- ),- );+ function removeTerm(target: TagFilterTerm) {+ onChange(value.filter((term) => !sameTerm(term, target)));}- // Registered keys, to flag active filters whose key isn't in the org's- // registry (e.g. a typo'd / hand-edited URL).const knownKeys = React.useMemo(() => new Set(tagKeys.map((tagKey) => tagKey.key)),[tagKeys],);- // Stable key-then-value order so same-key pairs sit together and the "AND"- // separators land between distinct keys.- const sortedValue = React.useMemo(+ // Sort by group id then value so OR'd exact terms sit together and AND+ // separators land between distinct conjuncts.+ const sortedTerms = React.useMemo(() =>[...value].sort(- (a, b) => a.key.localeCompare(b.key) || a.value.localeCompare(b.value),+ (a, b) =>+ termGroupId(a).localeCompare(termGroupId(b)) ||+ (a.value ?? "").localeCompare(b.value ?? ""),),[value],);function copyFilterUrl() {- // copyText handles the secure-context navigator.clipboard path plus an- // execCommand fallback, and resolves false on failure (no silent no-op).copyText(window.location.href).then((ok) => {toast(ok@@ -124,27 +128,68 @@ function WorkflowTagFilter({});}- const normalizedQuery = query.trim().toLowerCase();+ const trimmedQuery = query.trim();+ const normalizedQuery = trimmedQuery.toLowerCase();+ const candidate = parseTagFilterTerm(query);+ const candidateExists =+ candidate !== null && value.some((term) => sameTerm(term, candidate));+ const showAdd = candidate !== null && !candidateExists;- const filteredKeys = tagKeys.filter((tagKey) =>- tagKey.key.toLowerCase().includes(normalizedQuery),- );+ const { typedKey, typedValuePartial } = parseTypedTagQuery(trimmedQuery);- const suggestionsForKey = selectedKey- ? (valueSuggestions?.get(selectedKey) ?? [])- : [];- // Drop unselectable comma-containing values (they can't be applied as a- // filter) so the suggestion list never dangles a no-op item.- const filteredValues = suggestionsForKey.filter(- (suggestion) =>- !suggestion.includes(",") &&- suggestion.toLowerCase().includes(normalizedQuery),- );- const trimmedQuery = query.trim();- const showAddOption =- trimmedQuery.length > 0 &&- !trimmedQuery.includes(",") &&- !suggestionsForKey.includes(trimmedQuery);+ const groupSuggestions =+ typedKey === null+ ? tagKeys+ .filter((tk) => tk.key.toLowerCase().includes(normalizedQuery))+ .filter(+ (tk) =>+ !value.some((term) => term.key === tk.key && term.value === null),+ )+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];+ const labelMatches =+ typedKey === null+ ? labelSuggestions+ .filter((label) => label.toLowerCase().includes(normalizedQuery))+ .filter(+ (label) =>+ !value.some((term) => term.key === null && term.value === label),+ )+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];+ const groupedValueMatches =+ typedKey !== null+ ? (valueSuggestionsByKey?.get(typedKey) ?? [])+ .filter((v) => v.toLowerCase().includes(typedValuePartial))+ .slice(0, MAX_AUTOCOMPLETE_SUGGESTIONS)+ : [];++ function termLabel(term: TagFilterTerm): React.ReactNode {+ if (term.key === null) {+ return term.value;+ }+ return (+ <>+ <span className="font-medium">{term.key}</span>+ <span className="text-muted-foreground">: </span>+ {term.value === null ? (+ <span className="italic text-muted-foreground">any</span>+ ) : (+ term.value+ )}+ </>+ );+ }++ function candidateLabel(term: TagFilterTerm): string {+ if (term.key === null) {+ return `label “${term.value}”`;+ }+ if (term.value === null) {+ return `group “${term.key}”`;+ }+ return `${term.key}: ${term.value}`;+ }return (<>@@ -185,32 +230,43 @@ function WorkflowTagFilter({</div></div><div className="flex flex-wrap items-center gap-1">- {sortedValue.map((pair, index) => {+ {sortedTerms.map((term, index) => {const previous =- index > 0 ? sortedValue[index - 1] : undefined;- // Different key from the previous chip → AND; same key →- // adjacent (OR within a key).- const startsNewKey =- previous !== undefined && previous.key !== pair.key;- const unknownKey = !knownKeys.has(pair.key);+ index > 0 ? sortedTerms[index - 1] : undefined;+ const startsNewConjunct =+ previous !== undefined &&+ termGroupId(previous) !== termGroupId(term);+ const unknownKey =+ term.key !== null && !knownKeys.has(term.key);return (- <React.Fragment key={`${pair.key}:${pair.value}`}>- {startsNewKey ? (+ <React.Fragment key={termDedupeKey(term)}>+ {startsNewConjunct ? (<span className="px-0.5 text-[10px] font-semibold uppercase text-muted-foreground">and</span>) : null}- <TagChip- tagKey={pair.key}- value={pair.value}- description={+ <span+ className={cn(+ badgeVariants({ variant: "secondary" }),+ "max-w-full gap-1 font-normal",+ unknownKey ? "border-warning" : undefined,+ )}+ title={unknownKey- ? `"${pair.key}" isn't a registered tag key in this org.`+ ? `"${term.key}" isn't a registered group in this org.`: undefined}- className={unknownKey ? "border-warning" : undefined}- onRemove={() => removePair(pair)}- />+ >+ <span className="truncate">{termLabel(term)}</span>+ <button+ type="button"+ aria-label={`Remove ${candidateLabel(term)}`}+ className="ml-0.5 shrink-0 rounded-sm opacity-70 hover:opacity-100"+ onClick={() => removeTerm(term)}+ >+ <Cross2Icon className="h-3 w-3" />+ </button>+ </span></React.Fragment>);})}@@ -218,145 +274,106 @@ function WorkflowTagFilter({</div>) : null}<Command shouldFilter={false}>- {selectedKey === null ? (- <>- <CommandInput- placeholder="Filter by tag key…"- value={query}- onValueChange={setQuery}- />- <CommandList>- <CommandEmpty>No tag keys found.</CommandEmpty>- <CommandGroup>- {filteredKeys.map((tagKey) => (- <CommandItem- key={tagKey.key}- value={tagKey.key}- className="justify-between gap-2"- onSelect={() => {- setSelectedKey(tagKey.key);- setQuery("");- }}- >- <div className="flex min-w-0 flex-col">- <span className="truncate">{tagKey.key}</span>- {tagKey.description ? (- <span className="truncate text-xs text-muted-foreground">- {tagKey.description}- </span>- ) : null}- </div>- <div className="flex shrink-0 items-center gap-1.5">- {tagKey.workflow_count > 0 ? (- <span className="text-xs text-muted-foreground">- {tagKey.workflow_count}- </span>- ) : null}- <button- type="button"- aria-label={`Delete tag key ${tagKey.key}`}- className="rounded-sm p-1 text-muted-foreground hover:text-destructive"- onClick={(event) => {- // Stop cmdk from treating this as selecting the key.- event.preventDefault();- event.stopPropagation();- setKeyToDelete(tagKey);- }}- >- <TrashIcon className="h-3.5 w-3.5" />- </button>- </div>- </CommandItem>- ))}- </CommandGroup>- </CommandList>- </>- ) : (- <>- <div className="flex items-center gap-1 border-b px-2 py-1.5">- <Button- variant="ghost"- size="icon"- className="h-6 w-6 shrink-0"- onClick={() => {- setSelectedKey(null);- setQuery("");- }}+ <CommandInput+ placeholder="Filter by label or group:label…"+ value={query}+ onValueChange={setQuery}+ onKeyDown={(event) => {+ if (event.key === "Enter" && candidate && showAdd) {+ event.preventDefault();+ addTerm(candidate);+ }+ }}+ />+ <CommandList>+ <CommandEmpty>+ Type a label, group:*, or group:label.+ </CommandEmpty>+ {showAdd && candidate ? (+ <CommandGroup>+ <CommandItem+ value={`__add__,${trimmedQuery}`}+ onSelect={() => addTerm(candidate)}>- <ArrowLeftIcon className="h-4 w-4" />- </Button>- <span className="truncate text-sm font-medium">- {selectedKey}- </span>- </div>- <CommandInput- placeholder="Add a value…"- value={query}- onValueChange={setQuery}- onKeyDown={(event) => {- if (event.key === "Enter" && trimmedQuery.length > 0) {- event.preventDefault();- addPair(selectedKey, trimmedQuery);- setQuery("");- }- }}- />- <CommandList>- {filteredValues.length === 0 && !showAddOption ? (- <CommandEmpty>Type a value to filter.</CommandEmpty>- ) : null}- {showAddOption ? (- <CommandGroup>- <CommandItem- value={`__add__:${trimmedQuery}`}- onSelect={() => {- addPair(selectedKey, trimmedQuery);- setQuery("");- }}- >- <PlusIcon className="mr-2 h-4 w-4" />- Add “{trimmedQuery}”- </CommandItem>- </CommandGroup>- ) : null}- {filteredValues.length > 0 ? (- <CommandGroup heading="Suggestions">- {filteredValues.map((suggestion) => {- const checked = value.some(- (pair) =>- pair.key === selectedKey &&- pair.value === suggestion,- );- return (- <CommandItem- key={suggestion}- value={suggestion}- onSelect={() => {- if (checked) {- removePair({- key: selectedKey,- value: suggestion,- });- } else {- addPair(selectedKey, suggestion);- }- }}- >- <CheckIcon- className={cn(- "mr-2 h-4 w-4",- checked ? "opacity-100" : "opacity-0",- )}- />- {suggestion}- </CommandItem>- );- })}- </CommandGroup>- ) : null}- </CommandList>- </>- )}+ <PlusIcon className="mr-2 h-4 w-4" />+ Filter by {candidateLabel(candidate)}+ </CommandItem>+ </CommandGroup>+ ) : null}+ {groupSuggestions.length > 0 ? (+ <CommandGroup heading="Groups">+ {groupSuggestions.map((tagKey) => (+ <CommandItem+ key={tagKey.key}+ value={`__group__,${tagKey.key}`}+ className="justify-between gap-2"+ // Filter by group (any value in it). Type `group:value`+ // for an exact match instead.+ onSelect={() => addTerm({ key: tagKey.key, value: null })}+ >+ <div className="flex min-w-0 flex-col">+ <span className="truncate">+ <span className="font-medium">{tagKey.key}</span>+ <span className="text-muted-foreground">: any</span>+ </span>+ {tagKey.description ? (+ <span className="truncate text-xs text-muted-foreground">+ {tagKey.description}+ </span>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ {tagKey.workflow_count > 0 ? (+ <span className="text-xs text-muted-foreground">+ {tagKey.workflow_count}+ </span>+ ) : null}+ <button+ type="button"+ aria-label={`Delete group ${tagKey.key}`}+ className="rounded-sm p-1 text-muted-foreground hover:text-destructive"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setKeyToDelete(tagKey);+ }}+ >+ <TrashIcon className="h-3.5 w-3.5" />+ </button>+ </div>+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ {labelMatches.length > 0 ? (+ <CommandGroup heading="Labels">+ {labelMatches.map((label) => (+ <CommandItem+ key={`label:${label}`}+ value={`__label__,${label}`}+ onSelect={() => addTerm({ key: null, value: label })}+ >+ {label}+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ {groupedValueMatches.length > 0 && typedKey !== null ? (+ <CommandGroup heading={`${typedKey} values`}>+ {groupedValueMatches.map((v) => (+ <CommandItem+ key={`gv:${v}`}+ value={`__gv__,${v}`}+ onSelect={() => addTerm({ key: typedKey, value: v })}+ >+ <span className="font-medium">{typedKey}</span>+ <span className="text-muted-foreground">: </span>+ {v}+ </CommandItem>+ ))}+ </CommandGroup>+ ) : null}+ </CommandList></Command></PopoverContent></Popover>@@ -370,10 +387,10 @@ function WorkflowTagFilter({><DialogContent className="sm:max-w-md"><DialogHeader>- <DialogTitle>Delete tag “{keyToDelete?.key}”?</DialogTitle>+ <DialogTitle>Delete group “{keyToDelete?.key}”?</DialogTitle><DialogDescription>This removes it from {keyToDelete?.workflow_count ?? 0} workflow- {keyToDelete?.workflow_count === 1 ? "" : "s"} and from the tag+ {keyToDelete?.workflow_count === 1 ? "" : "s"} and from the grouplist. This can’t be undone.</DialogDescription></DialogHeader>@@ -396,9 +413,9 @@ function WorkflowTagFilter({const deletedKey = keyToDelete.key;deleteKeyMutation.mutate(deletedKey, {onSuccess: () => {- // Drop any active filter on the now-deleted key, else the- // list refetches with a stale ?tags= and shows empty.- onChange(value.filter((pair) => pair.key !== deletedKey));+ // Drop any active filter term on the now-deleted group, else+ // the list refetches with a stale ?tags= and shows empty.+ onChange(value.filter((term) => term.key !== deletedKey));setKeyToDelete(null);},});diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.tsindex 437e34a07..509dc81ae 100644--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts@@ -5,9 +5,8 @@ import { getClient } from "@/api/AxiosClient";import { toast } from "@/components/ui/use-toast";import type { TagApplyRequest, TagKey, TagsResponse } from "../types/tagTypes";-// Tag writes surface validation/conflict reasons in the FastAPI `detail`-// string (422 cap/regex, 409 concurrent write), so prefer it over the generic-// axios message.+// Tag writes put validation/conflict reasons in the FastAPI `detail` (422 cap/regex,+// 409 concurrent write), so prefer it over the generic axios message.function tagErrorMessage(error: unknown): string {if (isAxiosError(error)) {const detail = error.response?.data?.detail;@@ -53,46 +52,11 @@ function useApplyWorkflowTagsMutation() {});}-function useDeleteWorkflowTagMutation() {- const credentialGetter = useCredentialGetter();- const queryClient = useQueryClient();-- return useMutation({- mutationFn: async ({- workflowPermanentId,- key,- }: {- workflowPermanentId: string;- key: string;- }) => {- const client = await getClient(credentialGetter);- return client- .delete<TagsResponse>(- `/workflows/${workflowPermanentId}/tags/${encodeURIComponent(key)}`,- )- .then((response) => response.data);- },- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ["workflow-tags"] });- // Removing a tag decrements the key's workflow_count (and a last-remove- // drops it to 0), so refresh the registry that feeds the filter dropdown.- queryClient.invalidateQueries({ queryKey: ["tag-keys"] });- // A removed tag can drop the row out of the active ?tags= filter.- queryClient.invalidateQueries({ queryKey: ["workflows"] });- },- onError: (error: unknown) => {- toast({- variant: "destructive",- title: "Failed to delete tag",- description: tagErrorMessage(error),- });- },- });-}+// Per-tag removal goes through the apply mutation's `tags_to_delete` (grouped by+// {key}, standalone by {value}) so one path handles both.-// Part of the tag-key mutation surface (SKY-10660). Not yet wired to a UI —-// the tag-key description editor is a queued follow-up (SKY-10661 optional) —-// but exported so that surface can consume it without re-deriving the hook.+// Exported for the not-yet-wired tag-key description editor so that surface can+// consume it without re-deriving the hook.function useUpdateTagKeyMutation() {const credentialGetter = useCredentialGetter();const queryClient = useQueryClient();@@ -135,9 +99,8 @@ function useDeleteTagKeyMutation() {.then((response) => response.data);},onSuccess: () => {- // Cascade delete drops the key from the registry AND removes the tag from- // every workflow, so refresh the registry, batch tags, and the (tag-- // filterable) workflows list.+ // Cascade delete drops the key and removes the tag from every workflow; refresh+ // the registry, batch tags, and the (tag-filterable) workflows list.queryClient.invalidateQueries({ queryKey: ["tag-keys"] });queryClient.invalidateQueries({ queryKey: ["workflow-tags"] });queryClient.invalidateQueries({ queryKey: ["workflows"] });@@ -154,7 +117,6 @@ function useDeleteTagKeyMutation() {export {useApplyWorkflowTagsMutation,- useDeleteWorkflowTagMutation,useUpdateTagKeyMutation,useDeleteTagKeyMutation,};diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagsBatchQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagsBatchQuery.tsindex f6d70993b..38a062b6d 100644--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagsBatchQuery.ts+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagsBatchQuery.ts@@ -1,17 +1,14 @@import { getClient } from "@/api/AxiosClient";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";-import type { WorkflowTagsBatchResponse } from "../types/tagTypes";+import type { Tag, WorkflowTagsBatchResponse } from "../types/tagTypes";-// The backend batch endpoint rejects more than this many IDs per request-// (_BATCH_TAGS_MAX_WPIDS). The workflows list page size is unbounded via the-// URL, so chunk rather than slice to avoid silently dropping tags for rows-// beyond the limit. The common case (page size <= 50) is a single request.+// Backend rejects more than this many IDs per request (_BATCH_TAGS_MAX_WPIDS); the+// list page size is unbounded, so chunk rather than slice to avoid dropping tags.const BATCH_TAGS_MAX_WPIDS = 200;-// One batch fetch for all visible workflows, avoiding an N+1 of per-row tag-// fetches on the workflows-list page. Ids are sorted so the query key is-// order-independent and two renders with the same set share a cache entry.+// One batch fetch for all visible workflows (avoids per-row N+1). Ids are sorted so+// the query key is order-independent and identical sets share a cache entry.function useWorkflowTagsBatchQuery(workflowPermanentIds: Array<string>) {const credentialGetter = useCredentialGetter();const sortedIds = [...workflowPermanentIds].sort();@@ -35,7 +32,7 @@ function useWorkflowTagsBatchQuery(workflowPermanentIds: Array<string>) {}),);// Chunks are disjoint slices, so wpid keys never collide on merge.- const merged: Record<string, Record<string, string>> = {};+ const merged: Record<string, Array<Tag>> = {};for (const response of responses) {Object.assign(merged, response);}diff --git a/skyvern-frontend/src/routes/workflows/types/tagTypes.test.ts b/skyvern-frontend/src/routes/workflows/types/tagTypes.test.tsnew file mode 100644index 000000000..6656b942f--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/types/tagTypes.test.ts@@ -0,0 +1,194 @@+import { describe, expect, it } from "vitest";++import {+ parseTagFilter,+ parseTagFilterTerm,+ parseTagInput,+ parseTypedTagQuery,+ serializeTagFilter,+ serializeTagFilterTerm,+ sortTags,+ tagElementKey,+ validateTagKey,+ validateTagValue,+ type Tag,+ type TagFilterTerm,+} from "./tagTypes";++describe("parseTagInput", () => {+ it("parses a bare label as a standalone tag", () => {+ expect(parseTagInput("production")).toEqual({+ key: null,+ value: "production",+ });+ });++ it("splits group:label on the first colon, keeping later colons in the value", () => {+ expect(parseTagInput("env:prod")).toEqual({ key: "env", value: "prod" });+ expect(parseTagInput("url:http://x:8000")).toEqual({+ key: "url",+ value: "http://x:8000",+ });+ });++ it("trims surrounding whitespace", () => {+ expect(parseTagInput(" env : prod ")).toEqual({+ key: "env",+ value: "prod",+ });+ });++ it("returns null for empty or partial input", () => {+ expect(parseTagInput("")).toBeNull();+ expect(parseTagInput(" ")).toBeNull();+ expect(parseTagInput("env:")).toBeNull();+ expect(parseTagInput(":prod")).toBeNull();+ });+});++describe("parseTagFilterTerm", () => {+ it("parses the three term shapes", () => {+ expect(parseTagFilterTerm("prod")).toEqual({ key: null, value: "prod" });+ expect(parseTagFilterTerm("env:*")).toEqual({ key: "env", value: null });+ expect(parseTagFilterTerm("env:prod")).toEqual({+ key: "env",+ value: "prod",+ });+ });++ it("returns null for malformed terms", () => {+ expect(parseTagFilterTerm("")).toBeNull();+ expect(parseTagFilterTerm(":prod")).toBeNull();+ expect(parseTagFilterTerm("env:")).toBeNull();+ });+});++describe("serializeTagFilterTerm", () => {+ it("serializes each shape", () => {+ expect(serializeTagFilterTerm({ key: null, value: "prod" })).toBe("prod");+ expect(serializeTagFilterTerm({ key: "env", value: null })).toBe("env:*");+ expect(serializeTagFilterTerm({ key: "env", value: "prod" })).toBe(+ "env:prod",+ );+ });+});++describe("serializeTagFilter", () => {+ it("sorts standalone first, then by key, then value", () => {+ const terms: Array<TagFilterTerm> = [+ { key: "env", value: "prod" },+ { key: null, value: "beta" },+ { key: "env", value: null },+ { key: null, value: "alpha" },+ ];+ expect(serializeTagFilter(terms)).toBe("alpha,beta,env:*,env:prod");+ });++ it("drops a degenerate empty term instead of emitting stray commas", () => {+ // {key:null, value:null} is never produced by parseTagFilterTerm; this guards+ // the serializer against it if the type is ever widened.+ const terms: Array<TagFilterTerm> = [+ { key: null, value: null },+ { key: null, value: "x" },+ ];+ expect(serializeTagFilter(terms)).toBe("x");+ });++ it("is order-independent", () => {+ const a: Array<TagFilterTerm> = [+ { key: "env", value: "prod" },+ { key: null, value: "x" },+ ];+ const b: Array<TagFilterTerm> = [+ { key: null, value: "x" },+ { key: "env", value: "prod" },+ ];+ expect(serializeTagFilter(a)).toBe(serializeTagFilter(b));+ });+});++describe("parseTagFilter", () => {+ it("round-trips a canonical string", () => {+ const raw = "alpha,beta,env:*,env:prod";+ expect(serializeTagFilter(parseTagFilter(raw))).toBe(raw);+ });++ it("dedupes repeats and drops blank segments", () => {+ expect(parseTagFilter("x,x, ,env:*")).toEqual([+ { key: null, value: "x" },+ { key: "env", value: null },+ ]);+ });++ it("returns [] for empty input", () => {+ expect(parseTagFilter(null)).toEqual([]);+ expect(parseTagFilter("")).toEqual([]);+ });+});++describe("sortTags", () => {+ it("orders standalone labels first, then grouped by key then value", () => {+ const tags: Array<Tag> = [+ { key: "env", value: "prod" },+ { key: null, value: "b" },+ { key: "env", value: "dev" },+ { key: null, value: "a" },+ ];+ expect(sortTags(tags)).toEqual([+ { key: null, value: "a" },+ { key: null, value: "b" },+ { key: "env", value: "dev" },+ { key: "env", value: "prod" },+ ]);+ });+});++describe("tagElementKey", () => {+ it("namespaces standalone vs grouped so a null key can't collide with an empty key", () => {+ expect(tagElementKey({ key: null, value: "foo" })).toBe("label:foo");+ expect(tagElementKey({ key: "", value: "foo" })).toBe("group::foo");+ expect(tagElementKey({ key: null, value: "foo" })).not.toBe(+ tagElementKey({ key: "", value: "foo" }),+ );+ });+});++describe("parseTypedTagQuery", () => {+ it("returns a null key for a bare query", () => {+ expect(parseTypedTagQuery("prod")).toEqual({+ typedKey: null,+ typedValuePartial: "",+ });+ });++ it("splits group:partial and lowercases the value fragment", () => {+ expect(parseTypedTagQuery("env:PR")).toEqual({+ typedKey: "env",+ typedValuePartial: "pr",+ });+ });++ it("treats a leading colon as no group", () => {+ expect(parseTypedTagQuery(":prod")).toEqual({+ typedKey: null,+ typedValuePartial: "",+ });+ });+});++describe("tag validation", () => {+ it("rejects a colon in a standalone label but allows it in a grouped value", () => {+ expect(validateTagValue("a:b", { hasKey: false })).not.toBeNull();+ expect(validateTagValue("a:b", { hasKey: true })).toBeNull();+ });++ it("rejects a grouped value of exactly the wildcard", () => {+ expect(validateTagValue("*", { hasKey: true })).not.toBeNull();+ });++ it("rejects an empty key and the reserved prefix", () => {+ expect(validateTagKey("")).not.toBeNull();+ expect(validateTagKey("skyvern.foo")).not.toBeNull();+ expect(validateTagKey("env")).toBeNull();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/types/tagTypes.ts b/skyvern-frontend/src/routes/workflows/types/tagTypes.tsindex de62d2556..7c197e777 100644--- a/skyvern-frontend/src/routes/workflows/types/tagTypes.ts+++ b/skyvern-frontend/src/routes/workflows/types/tagTypes.ts@@ -1,33 +1,53 @@+// A tag is a `value` (always present) with an optional `key` (the group).+// `key === null` is a standalone label; a non-null key is a grouped label.+export interface Tag {+ key: string | null;+ value: string;+}+export interface TagResponse {+ key: string | null;value: string;source: string;set_at: string;set_by: string;}+// Responses are lists (not key-maps) so standalone labels, which have no key,+// are representable.export interface TagsResponse {workflow_permanent_id: string;- tags: Record<string, TagResponse>;+ tags: Array<TagResponse>;}export interface TagKey {key: string;description: string | null;// Number of workflows currently carrying this key (from GET /tag-keys).+ // Standalone labels are not registered here — the registry is groups only.workflow_count: number;}-// Batch endpoint returns a flat key->value map per workflow (no per-tag+// Batch endpoint returns a list of {key, value} per workflow (no per-tag// metadata). Descriptions come from the tag-key registry (GET /tag-keys).export interface WorkflowTagsBatchResponse {- workflow_tags: Record<string, Record<string, string>>;+ workflow_tags: Record<string, Array<Tag>>;+}++// Body for POST /workflows/{wpid}/tags. `tags` sets/overwrites ({key?, value});+// `tags_to_delete` removes a grouped tag by {key} or a label by {value}.+export interface TagInput {+ key?: string | null;+ value: string;}-// Body for POST /workflows/{wpid}/tags. `tags` is set (overwrite, set-wins);-// `tags_to_delete` soft-deletes keys. Both optional; both empty is a no-op.+export type TagDeleteInput =+ | { key: string; value?: never }+ | { value: string; key?: never };+export interface TagApplyRequest {- tags?: Record<string, string>;- tags_to_delete?: Array<string>;+ tags?: Array<TagInput>;+ tags_to_delete?: Array<TagDeleteInput>;}// Mirror skyvern/forge/sdk/workflow/models/validators.py so the editor rejects@@ -37,17 +57,19 @@ export const RESERVED_TAG_KEY_PREFIX = "skyvern.";export const MAX_TAGS_PER_WORKFLOW = 20;export const TAG_KEY_MAX_LENGTH = 64;export const TAG_VALUE_MAX_LENGTH = 256;+export const MAX_AUTOCOMPLETE_SUGGESTIONS = 6;+// Returns an error string when `key` (a group) is invalid, or null when valid.export function validateTagKey(key: string): string | null {const trimmed = key.trim();if (!trimmed) {- return "Key is required.";+ return "Group is required.";}if (trimmed.length > TAG_KEY_MAX_LENGTH) {- return `Key must be at most ${TAG_KEY_MAX_LENGTH} characters.`;+ return `Group must be at most ${TAG_KEY_MAX_LENGTH} characters.`;}if (trimmed.startsWith(RESERVED_TAG_KEY_PREFIX)) {- return `Keys can't start with the reserved "${RESERVED_TAG_KEY_PREFIX}" prefix.`;+ return `Groups can't start with the reserved "${RESERVED_TAG_KEY_PREFIX}" prefix.`;}if (!TAG_KEY_REGEX.test(trimmed)) {return "Use letters, digits, _ . or - (must start with a letter or digit).";@@ -55,67 +77,182 @@ export function validateTagKey(key: string): string | null {return null;}-export function validateTagValue(value: string): string | null {+// Validates a label value. `hasKey` toggles two backend rules: a standalone label+// can't contain ":", and a grouped value can't be exactly "*" (group wildcard).+export function validateTagValue(+ value: string,+ { hasKey }: { hasKey: boolean } = { hasKey: false },+): string | null {const trimmed = value.trim();if (!trimmed) {- return "Value is required.";+ return "Label is required.";}if (trimmed.length > TAG_VALUE_MAX_LENGTH) {- return `Value must be at most ${TAG_VALUE_MAX_LENGTH} characters.`;+ return `Label must be at most ${TAG_VALUE_MAX_LENGTH} characters.`;}if (trimmed.includes(",")) {- return "Value can't contain a comma.";+ return "Label can't contain a comma.";+ }+ if (!hasKey && trimmed.includes(":")) {+ return "A label without a group can't contain a colon — add a group (group:label).";+ }+ if (hasKey && trimmed === "*") {+ return 'A grouped value can\'t be exactly "*" (reserved as the group filter wildcard).';}return null;}-export interface TagFilterPair {- key: string;- value: string;+// Parse a typed `group:label` or bare `label` into a Tag, splitting on the first+// colon so a grouped value may itself contain colons. Null if nothing usable.+export function parseTagInput(raw: string): Tag | null {+ const trimmed = raw.trim();+ if (!trimmed) {+ return null;+ }+ const colon = trimmed.indexOf(":");+ if (colon === -1) {+ return { key: null, value: trimmed };+ }+ const key = trimmed.slice(0, colon).trim();+ const value = trimmed.slice(colon + 1).trim();+ if (!key || !value) {+ return null;+ }+ return { key, value };+}++// Split an in-progress editor/filter query at the first colon into a group key+// and the lowercased value fragment, for autocomplete matching.+export function parseTypedTagQuery(trimmedQuery: string): {+ typedKey: string | null;+ typedValuePartial: string;+} {+ const colonIndex = trimmedQuery.indexOf(":");+ if (colonIndex <= 0) {+ return { typedKey: null, typedValuePartial: "" };+ }+ return {+ typedKey: trimmedQuery.slice(0, colonIndex).trim(),+ typedValuePartial: trimmedQuery+ .slice(colonIndex + 1)+ .trim()+ .toLowerCase(),+ };+}++// Validate a parsed tag (both key — if present — and value). Returns an error+// string or null.+export function validateTag(tag: Tag): string | null {+ if (tag.key !== null) {+ const keyError = validateTagKey(tag.key);+ if (keyError) {+ return keyError;+ }+ }+ return validateTagValue(tag.value, { hasKey: tag.key !== null });}-// Parse the `?tags=key:value,key:value` URL param into pairs. Forgiving on-// read (drops malformed/blank segments) so a hand-edited URL can't crash the-// page; the backend GET /workflows filter is strict, so we only ever serialize-// valid pairs back. Mirrors the backend's first-colon partition so values may-// themselves contain colons. Duplicate pairs are collapsed.+// A filter term: value-only {key:null, value:"x"}, group-only {key:"env",+// value:null}, or exact {key:"env", value:"prod"}.+export interface TagFilterTerm {+ key: string | null;+ value: string | null;+}++export function termDedupeKey(term: TagFilterTerm): string {+ return `${term.key ?? ""} ${term.value ?? ""}`;+}++// Parse the `?tags=` param into terms. Forgiving on read (drops malformed/blank+// segments); mirrors the backend, splitting on the first colon (`*` = wildcard).export function parseTagFilter(raw: string | null | undefined,-): TagFilterPair[] {+): Array<TagFilterTerm> {if (!raw) {return [];}- const pairs: TagFilterPair[] = [];+ const terms: Array<TagFilterTerm> = [];const seen = new Set<string>();for (const segment of raw.split(",")) {- const separatorIndex = segment.indexOf(":");- if (separatorIndex <= 0) {- continue;- }- const key = segment.slice(0, separatorIndex).trim();- const value = segment.slice(separatorIndex + 1).trim();- if (!key || !value) {+ const term = parseTagFilterTerm(segment);+ if (!term) {continue;}- const dedupeKey = `${key}:${value}`;- if (seen.has(dedupeKey)) {+ const dedupe = termDedupeKey(term);+ if (seen.has(dedupe)) {continue;}- seen.add(dedupeKey);- pairs.push({ key, value });+ seen.add(dedupe);+ terms.push(term);+ }+ return terms;+}++// Parse a single `?tags=` term. Returns null for malformed/blank input.+export function parseTagFilterTerm(segment: string): TagFilterTerm | null {+ const trimmed = segment.trim();+ if (!trimmed) {+ return null;+ }+ const colon = trimmed.indexOf(":");+ if (colon === -1) {+ // Bare token -> label / value-only.+ return { key: null, value: trimmed };}- return pairs;+ const key = trimmed.slice(0, colon).trim();+ const value = trimmed.slice(colon + 1).trim();+ if (!key) {+ return null;+ }+ if (value === "*") {+ return { key, value: null }; // group-only+ }+ if (!value) {+ return null;+ }+ return { key, value };}-// Canonical serialization: pairs are sorted by key then value so that-// semantically identical filters (the backend ANDs keys / ORs values, order-// is irrelevant) produce one stable string. This keeps the URL and the React-// Query key order-independent, so reordering can't cause a needless refetch.-export function serializeTagFilter(pairs: TagFilterPair[]): string {- return [...pairs]+// Canonical serialization: terms sorted (standalone first, then key, then value)+// so identical filters produce one stable, order-independent string.+export function serializeTagFilter(terms: Array<TagFilterTerm>): string {+ return [...terms].sort(- (a, b) => a.key.localeCompare(b.key) || a.value.localeCompare(b.value),+ (a, b) =>+ Number(a.key !== null) - Number(b.key !== null) ||+ (a.key ?? "").localeCompare(b.key ?? "") ||+ (a.value ?? "").localeCompare(b.value ?? ""),)- .map((pair) => `${pair.key}:${pair.value}`)+ .map(serializeTagFilterTerm)+ .filter((term) => term !== "").join(",");}++export function serializeTagFilterTerm(term: TagFilterTerm): string {+ if (term.key === null) {+ return term.value ?? "";+ }+ if (term.value === null) {+ return `${term.key}:*`;+ }+ return `${term.key}:${term.value}`;+}++// Stable React key for a tag. Standalone labels and grouped tags live in+// disjoint namespaces so a null key can't collide with an (invalid) empty key.+export function tagElementKey(tag: Tag): string {+ return tag.key === null+ ? `label:${tag.value}`+ : `group:${tag.key}:${tag.value}`;+}++// Stable order for displaying a list of tags: standalone labels first, then+// grouped by key, then by value. Matches the backend response ordering.+export function sortTags(tags: Array<Tag>): Array<Tag> {+ return [...tags].sort(+ (a, b) =>+ Number(a.key !== null) - Number(b.key !== null) ||+ (a.key ?? "").localeCompare(b.key ?? "") ||+ a.value.localeCompare(b.value),+ );+}