Skip to content

Automate browser based workflows with AI

fix(SKY-12453): reserved system tags read-only + Labels page search and creation (#7446)

Aaron Perez75b4a5486082
diff --git a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
index 964f5b699..f4d8140b7 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
@@ -110,7 +110,12 @@ vi.mock("@/api/AxiosClient", () => ({
vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
useRunTagsBatchQuery: () => ({
- data: { wr_1: [{ key: "skyvern.platform", value: "platform_a" }] },
+ data: {
+ wr_1: [
+ { key: "skyvern.platform", value: "platform_a" },
+ { key: null, value: "adhoc" },
+ ],
+ },
isPending: false,
}),
}));
@@ -136,11 +141,16 @@ vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({
vi.mock("@/routes/workflows/components/tagging/TagChipList", () => ({
TagChipList: ({
tags,
+ hideSystemTags,
}: {
tags: Array<{ key: string | null; value: string }>;
+ hideSystemTags?: boolean;
}) => (
<span data-testid="tag-chip-list">
- {tags.map((tag) => `${tag.key ?? "label"}:${tag.value}`).join(",")}
+ {tags
+ .filter((tag) => !hideSystemTags || !tag.key?.startsWith("skyvern."))
+ .map((tag) => `${tag.key ?? "label"}:${tag.value}`)
+ .join(",")}
</span>
),
}));
@@ -171,12 +181,63 @@ afterEach(() => {
});
describe("RunHistory run tags", () => {
- it("renders a run-tag chip on the all-runs list", () => {
+ it("shows user labels and hides reserved system tags on the all-runs list", () => {
const { container } = render(<RunHistory />, { wrapper });
+ const chipList = within(container).getByTestId("tag-chip-list");
+ expect(chipList.textContent).toContain("adhoc");
+ expect(chipList.textContent).not.toContain("platform_a");
+ });
+
+ it("selects only workflow runs and supports shift-range bulk actions", () => {
+ render(<RunHistory />, { wrapper });
+
+ const first = screen.getByRole("checkbox", { name: "Select My Run" });
+ const second = screen.getByRole("checkbox", { name: "Select Second Run" });
+ expect(
+ screen.queryByRole("checkbox", { name: "Select Task Run" }),
+ ).toBeNull();
+
+ fireEvent.click(first.parentElement!);
+ fireEvent.click(second.parentElement!, { shiftKey: true });
+
expect(
- within(container).getByTestId("tag-chip-list").textContent,
- ).toContain("platform_a");
+ screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
+ ).toContain("2 selected");
+
+ fireEvent.contextMenu(screen.getByRole("row", { name: /tsk_1 Task Run/ }));
+ expect(screen.queryByRole("menu")).toBeNull();
+ });
+
+ it("hides selection when workflow tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+ render(<RunHistory />, { wrapper });
+
+ expect(screen.queryByLabelText(/^Select /)).toBeNull();
+ });
+
+ it("does not restore selection after the tagging flag is toggled", () => {
+ const view = render(<RunHistory />, { wrapper });
+ fireEvent.click(
+ screen.getByRole("checkbox", { name: "Select My Run" }).parentElement!,
+ );
+
+ flagState.taggingEnabled = false;
+ view.rerender(<RunHistory />);
+ flagState.taggingEnabled = true;
+ view.rerender(<RunHistory />);
+
+ expect(screen.queryByRole("toolbar", { name: "Bulk actions" })).toBeNull();
+ });
+
+ it("opens the tag context menu from a workflow-run row", async () => {
+ render(<RunHistory />, { wrapper });
+
+ const row = screen.getByRole("row", { name: /wr_1 My Run/ });
+ fireEvent.contextMenu(row);
+
+ expect(await screen.findByRole("menu")).not.toBeNull();
+ expect(row.hasAttribute("data-row-active")).toBe(true);
});
it("selects only workflow runs and supports shift-range bulk actions", () => {
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index 8c45d9e9a..dd5f34fda 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -476,14 +476,17 @@ function RunHistory() {
className="max-w-0 truncate"
title={run.title ?? undefined}
>
- <div className="flex min-w-0 flex-col gap-1">
- {titleContent}
+ <div className="flex min-w-0 items-center gap-2">
+ <div className="min-w-0 truncate">{titleContent}</div>
{taggingEnabled && runTags && runTags.length > 0 ? (
<TagChipList
tags={runTags}
descriptions={tagDescriptions}
colors={tagColors}
maxVisible={2}
+ hideSystemTags
+ compact
+ className="shrink-0"
/>
) : null}
</div>
@@ -641,35 +644,22 @@ function RunHistory() {
</div>
) : null}
<div className="flex items-center justify-between gap-4">
- <TableSearchInput
- value={search}
- onChange={(value) => {
- setSearch(value);
- const params = new URLSearchParams(searchParams);
- params.set("page", "1");
- setSearchParams(params, { replace: true });
- }}
- placeholder={
- workflowPermanentIdFilter
- ? "Clear the agent filter above to search"
- : "Search by run ID or input..."
- }
- disabled={!!workflowPermanentIdFilter}
- className="w-48 lg:w-72"
- />
<div className="flex items-center gap-2">
- <RunTypeFilterDropdown
- values={runTypeGroups}
- onChange={(groups) => {
+ <TableSearchInput
+ value={search}
+ onChange={(value) => {
+ setSearch(value);
const params = new URLSearchParams(searchParams);
- if (groups.length === 0) {
- params.delete("run_type");
- } else {
- params.set("run_type", groups.join(","));
- }
params.set("page", "1");
setSearchParams(params, { replace: true });
}}
+ placeholder={
+ workflowPermanentIdFilter
+ ? "Clear the agent filter above to search"
+ : "Search by run ID or input..."
+ }
+ disabled={!!workflowPermanentIdFilter}
+ className="w-48 lg:w-72"
/>
{taggingEnabled ? (
<TagFilterControl
@@ -681,6 +671,21 @@ function RunHistory() {
colors={tagColors}
/>
) : null}
+ </div>
+ <div className="flex items-center gap-2">
+ <RunTypeFilterDropdown
+ values={runTypeGroups}
+ onChange={(groups) => {
+ const params = new URLSearchParams(searchParams);
+ if (groups.length === 0) {
+ params.delete("run_type");
+ } else {
+ params.set("run_type", groups.join(","));
+ }
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ }}
+ />
<StatusFilterDropdown
values={statusFilters}
onChange={(filters) => {
diff --git a/skyvern-frontend/src/routes/settings/LabelManagement.test.tsx b/skyvern-frontend/src/routes/settings/LabelManagement.test.tsx
index f50b2eb4f..ce010775d 100644
--- a/skyvern-frontend/src/routes/settings/LabelManagement.test.tsx
+++ b/skyvern-frontend/src/routes/settings/LabelManagement.test.tsx
@@ -25,12 +25,18 @@ Element.prototype.hasPointerCapture = () => false;
Element.prototype.releasePointerCapture = () => {};
const getMock = vi.fn();
+const postMock = vi.fn();
const patchMock = vi.fn();
const deleteMock = vi.fn();
vi.mock("@/api/AxiosClient", () => ({
getClient: () =>
- Promise.resolve({ get: getMock, patch: patchMock, delete: deleteMock }),
+ Promise.resolve({
+ get: getMock,
+ post: postMock,
+ patch: patchMock,
+ delete: deleteMock,
+ }),
}));
vi.mock("@/hooks/useCredentialGetter", () => ({
useCredentialGetter: () => null,
@@ -44,6 +50,7 @@ const tagValues: Array<TagValue> = [
beforeEach(() => {
getMock.mockResolvedValue({ data: tagValues });
+ postMock.mockResolvedValue({ data: {} });
patchMock.mockResolvedValue({ data: {} });
deleteMock.mockResolvedValue({ data: {} });
});
@@ -75,9 +82,9 @@ describe("LabelManagement", () => {
expect(await screen.findByRole("heading", { name: "env" })).toBeTruthy();
expect(screen.getByRole("heading", { name: "team" })).toBeTruthy();
- expect(screen.getByText("3 workflows")).toBeTruthy();
- expect(screen.getByText("1 workflow")).toBeTruthy();
- expect(screen.getByText("0 workflows")).toBeTruthy();
+ expect(screen.getByText("3 agents")).toBeTruthy();
+ expect(screen.getByText("1 agent")).toBeTruthy();
+ expect(screen.getByText("0 agents")).toBeTruthy();
});
it("shows an empty state when no labels are registered", async () => {
@@ -94,7 +101,7 @@ describe("LabelManagement", () => {
expect(screen.getByText(/Delete label/)).toBeTruthy();
expect(
- screen.getByText(/removes it from 3 workflows and from the/),
+ screen.getByText(/removes it from 3 agents and from the/),
).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Delete" }));
@@ -154,4 +161,138 @@ describe("LabelManagement", () => {
});
});
});
+
+ it("hides reserved skyvern.* rows from the label list entirely", async () => {
+ getMock.mockResolvedValue({
+ data: [
+ ...tagValues,
+ {
+ key: "skyvern.platform",
+ value: "web",
+ color: "blue",
+ workflow_count: 2,
+ },
+ ],
+ });
+ renderSurface();
+
+ expect(await screen.findByRole("heading", { name: "env" })).toBeTruthy();
+ expect(
+ screen.queryByRole("heading", { name: "skyvern.platform" }),
+ ).toBeNull();
+ expect(screen.queryByText(/skyvern\.platform/)).toBeNull();
+ // Non-reserved rows are unaffected.
+ expect(screen.getByLabelText("Rename prod")).toBeTruthy();
+ });
+
+ it("shows the empty state when only reserved labels exist", async () => {
+ getMock.mockResolvedValue({
+ data: [
+ {
+ key: "skyvern.platform",
+ value: "web",
+ color: "blue",
+ workflow_count: 2,
+ },
+ ],
+ });
+ renderSurface();
+
+ expect(await screen.findByText(/No labels yet/)).toBeTruthy();
+ });
+
+ it("renders rows with value-only chips, without the group prefix", async () => {
+ renderSurface();
+
+ await screen.findByRole("heading", { name: "env" });
+ // The group name lives only in the section heading (h3), never in the chips.
+ expect(screen.queryByText("env", { selector: "span" })).toBeNull();
+ expect(screen.getByText("prod")).toBeTruthy();
+ });
+
+ it("filters rows by label value as you type", async () => {
+ renderSurface();
+
+ await screen.findByRole("heading", { name: "env" });
+ fireEvent.change(screen.getByLabelText("Search labels"), {
+ target: { value: "grow" },
+ });
+
+ expect(screen.queryByRole("heading", { name: "env" })).toBeNull();
+ expect(screen.getByRole("heading", { name: "team" })).toBeTruthy();
+ expect(screen.getByText("growth")).toBeTruthy();
+ });
+
+ it("keeps a whole group visible when the query matches its name", async () => {
+ renderSurface();
+
+ await screen.findByRole("heading", { name: "env" });
+ fireEvent.change(screen.getByLabelText("Search labels"), {
+ target: { value: "env" },
+ });
+
+ expect(screen.getByText("prod")).toBeTruthy();
+ expect(screen.getByText("staging")).toBeTruthy();
+ expect(screen.queryByRole("heading", { name: "team" })).toBeNull();
+ });
+
+ it("shows a no-match state for an unmatched query", async () => {
+ renderSurface();
+
+ await screen.findByRole("heading", { name: "env" });
+ fireEvent.change(screen.getByLabelText("Search labels"), {
+ target: { value: "zzz" },
+ });
+
+ expect(screen.getByText(/No labels match/)).toBeTruthy();
+ });
+
+ it("creates a label from the New label dialog", async () => {
+ postMock.mockResolvedValue({
+ data: { key: "region", value: "emea", color: "teal", workflow_count: 0 },
+ });
+ renderSurface();
+
+ fireEvent.click(await screen.findByRole("button", { name: "New label" }));
+ fireEvent.change(screen.getByLabelText("Group"), {
+ target: { value: "region" },
+ });
+ fireEvent.change(screen.getByLabelText("Label"), {
+ target: { value: "emea" },
+ });
+ fireEvent.click(screen.getByLabelText("teal"));
+ fireEvent.click(screen.getByRole("button", { name: "Create label" }));
+
+ await waitFor(() => {
+ expect(postMock).toHaveBeenCalledWith("/tag-values", {
+ key: "region",
+ value: "emea",
+ color: "teal",
+ });
+ });
+ });
+
+ it("rejects a reserved group inline in the create dialog", async () => {
+ renderSurface();
+
+ fireEvent.click(await screen.findByRole("button", { name: "New label" }));
+ fireEvent.change(screen.getByLabelText("Group"), {
+ target: { value: "skyvern.platform" },
+ });
+ fireEvent.change(screen.getByLabelText("Label"), {
+ target: { value: "web" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Create label" }));
+
+ expect(await screen.findByText(/reserved/)).toBeTruthy();
+ expect(postMock).not.toHaveBeenCalled();
+ });
+
+ it("offers a New label CTA in the empty state", async () => {
+ getMock.mockResolvedValue({ data: [] });
+ renderSurface();
+
+ expect(await screen.findByText(/No labels yet/)).toBeTruthy();
+ expect(screen.getByRole("button", { name: "New label" })).toBeTruthy();
+ });
});
diff --git a/skyvern-frontend/src/routes/settings/LabelManagement.tsx b/skyvern-frontend/src/routes/settings/LabelManagement.tsx
index eafe34bda..0a2ce5d32 100644
--- a/skyvern-frontend/src/routes/settings/LabelManagement.tsx
+++ b/skyvern-frontend/src/routes/settings/LabelManagement.tsx
@@ -3,6 +3,7 @@ import { isAxiosError } from "axios";
import {
CheckIcon,
Pencil1Icon,
+ PlusIcon,
ReloadIcon,
TrashIcon,
} from "@radix-ui/react-icons";
@@ -23,11 +24,13 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
+import { Search } from "@/components/ui/search";
import { Skeleton } from "@/components/ui/skeleton";
import { toast } from "@/components/ui/use-toast";
import { cn } from "@/util/utils";
@@ -38,6 +41,7 @@ import { TagColorSwatchPicker } from "@/routes/workflows/components/tagging/TagC
import { useTagValuesListQuery } from "@/routes/workflows/hooks/useTagValuesQuery";
import {
tagErrorMessage,
+ useCreateTagValueMutation,
useDeleteTagValueMutation,
useRecolorTagValueMutation,
useRenameTagValueMutation,
@@ -45,9 +49,12 @@ import {
import {
isPaletteColorName,
paletteDotClass,
+ randomPaletteColor,
type PaletteColorName,
} from "@/routes/workflows/types/tagColors";
import {
+ isSystemTagKey,
+ validateTagKey,
validateTagValue,
type TagValue,
} from "@/routes/workflows/types/tagTypes";
@@ -56,7 +63,9 @@ type LabelGroup = { key: string; values: Array<TagValue> };
function groupLabels(tagValues: Array<TagValue>): Array<LabelGroup> {
const byKey = new Map<string, Array<TagValue>>();
- for (const row of tagValues) {
+ // Reserved skyvern.* labels are system-managed (not user-editable), so they
+ // don't belong on a management surface; they stay visible on runs/filters.
+ for (const row of tagValues.filter((row) => !isSystemTagKey(row.key))) {
const list = byKey.get(row.key) ?? [];
list.push(row);
byKey.set(row.key, list);
@@ -69,8 +78,32 @@ function groupLabels(tagValues: Array<TagValue>): Array<LabelGroup> {
.sort((a, b) => a.key.localeCompare(b.key));
}
+// Case-insensitive filter: a query matching a group name keeps the whole group;
+// otherwise groups are narrowed to their matching values, and emptied groups drop.
+function filterGroups(
+ groups: Array<LabelGroup>,
+ query: string,
+): Array<LabelGroup> {
+ const q = query.trim().toLowerCase();
+ if (!q) {
+ return groups;
+ }
+ return groups
+ .map((group) =>
+ group.key.toLowerCase().includes(q)
+ ? group
+ : {
+ key: group.key,
+ values: group.values.filter((row) =>
+ row.value.toLowerCase().includes(q),
+ ),
+ },
+ )
+ .filter((group) => group.values.length > 0);
+}
+
function usageLabel(count: number): string {
- return `${count} workflow${count === 1 ? "" : "s"}`;
+ return `${count} agent${count === 1 ? "" : "s"}`;
}
type LabelRowProps = {
@@ -195,22 +228,39 @@ function LabelRow({ label, onRequestDelete }: LabelRowProps) {
);
}
+ const iconButtonClass =
+ "flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted " +
+ "focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring";
+
return (
- <div className="flex items-center justify-between gap-2 py-1.5">
+ <div className="group -mx-2 flex items-center justify-between gap-2 rounded-sm px-2 py-1.5 hover:bg-muted/40">
<div className="flex min-w-0 items-center gap-2">
- <TagChip tagKey={label.key} value={label.value} color={label.color} />
+ <TagChip
+ tagKey={label.key}
+ value={label.value}
+ color={label.color}
+ hideKey
+ />
<span className="shrink-0 text-xs text-muted-foreground">
{usageLabel(count)}
</span>
</div>
- <div className="flex shrink-0 items-center gap-1">
+ {/* Revealed on hover AND focus-within (opacity only, so buttons stay
+ tabbable and the row height never shifts). */}
+ <div
+ className={cn(
+ "flex shrink-0 items-center gap-1 opacity-0 transition-opacity",
+ "group-focus-within:opacity-100 group-hover:opacity-100",
+ colorOpen && "opacity-100",
+ )}
+ >
<Popover open={colorOpen} onOpenChange={setColorOpen}>
<PopoverTrigger asChild>
<button
type="button"
aria-label={`Change color for ${label.value}`}
disabled={recolorMutation.isPending}
- className="flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted disabled:opacity-50"
+ className={cn(iconButtonClass, "disabled:opacity-50")}
>
<span
aria-hidden="true"
@@ -232,7 +282,7 @@ function LabelRow({ label, onRequestDelete }: LabelRowProps) {
type="button"
aria-label={`Rename ${label.value}`}
onClick={startEditing}
- className="flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted"
+ className={iconButtonClass}
>
<Pencil1Icon className="h-3.5 w-3.5" />
</button>
@@ -240,7 +290,7 @@ function LabelRow({ label, onRequestDelete }: LabelRowProps) {
type="button"
aria-label={`Delete ${label.value}`}
onClick={() => onRequestDelete(label)}
- className="flex h-7 w-7 items-center justify-center rounded-sm text-muted-foreground hover:bg-muted hover:text-destructive"
+ className={cn(iconButtonClass, "hover:text-destructive")}
>
<TrashIcon className="h-3.5 w-3.5" />
</button>
@@ -249,17 +299,183 @@ function LabelRow({ label, onRequestDelete }: LabelRowProps) {
);
}
+type CreateLabelDialogProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ existingGroups: Array<string>;
+};
+
+function CreateLabelDialog({
+ open,
+ onOpenChange,
+ existingGroups,
+}: CreateLabelDialogProps) {
+ const [group, setGroup] = React.useState("");
+ const [value, setValue] = React.useState("");
+ const [color, setColor] = React.useState<PaletteColorName>("gray");
+ const [error, setError] = React.useState<string | null>(null);
+ const createMutation = useCreateTagValueMutation();
+
+ React.useEffect(() => {
+ if (open) {
+ setGroup("");
+ setValue("");
+ setColor(randomPaletteColor());
+ setError(null);
+ }
+ }, [open]);
+
+ const trimmedGroup = group.trim().toLowerCase();
+ const suggestions = existingGroups
+ .filter(
+ (key) => key.toLowerCase().includes(trimmedGroup) && key !== group.trim(),
+ )
+ .slice(0, 6);
+
+ function submit() {
+ const groupError = validateTagKey(group);
+ if (groupError) {
+ setError(groupError);
+ return;
+ }
+ const valueError = validateTagValue(value, { hasKey: true });
+ if (valueError) {
+ setError(valueError);
+ return;
+ }
+ createMutation.mutate(
+ { key: group.trim(), value: value.trim(), color },
+ {
+ onSuccess: () => onOpenChange(false),
+ onError: (mutationError) => {
+ if (
+ isAxiosError(mutationError) &&
+ mutationError.response?.status === 409
+ ) {
+ setError("That label already exists in this group.");
+ return;
+ }
+ setError(tagErrorMessage(mutationError));
+ },
+ },
+ );
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ if (!createMutation.isPending) {
+ onOpenChange(next);
+ }
+ }}
+ >
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>New label</DialogTitle>
+ <DialogDescription>
+ Labels are grouped as group:label. A new label counts 0 agents until
+ you tag one with it.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="new-label-group">Group</Label>
+ <Input
+ id="new-label-group"
+ value={group}
+ placeholder="e.g. env"
+ disabled={createMutation.isPending}
+ onChange={(event) => {
+ setGroup(event.target.value);
+ setError(null);
+ }}
+ />
+ {suggestions.length > 0 ? (
+ <div className="flex flex-wrap items-center gap-1.5 pt-0.5">
+ <span className="text-xs text-muted-foreground">Existing:</span>
+ {suggestions.map((key) => (
+ <button
+ key={key}
+ type="button"
+ className="rounded-sm bg-muted px-1.5 py-0.5 text-xs hover:bg-muted/70 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ onClick={() => {
+ setGroup(key);
+ setError(null);
+ }}
+ >
+ {key}
+ </button>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="new-label-value">Label</Label>
+ <Input
+ id="new-label-value"
+ value={value}
+ placeholder="e.g. production"
+ disabled={createMutation.isPending}
+ onChange={(event) => {
+ setValue(event.target.value);
+ setError(null);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ submit();
+ }
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-1.5">
+ <Label>Color</Label>
+ <TagColorSwatchPicker value={color} onChange={setColor} />
+ </div>
+ {error ? <p className="text-xs text-destructive">{error}</p> : null}
+ </div>
+ <DialogFooter>
+ <Button
+ variant="outline"
+ onClick={() => onOpenChange(false)}
+ disabled={createMutation.isPending}
+ >
+ Cancel
+ </Button>
+ <Button
+ className="gap-2"
+ onClick={submit}
+ disabled={createMutation.isPending}
+ >
+ {createMutation.isPending ? (
+ <ReloadIcon className="h-4 w-4 animate-spin" />
+ ) : null}
+ Create label
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
function LabelManagement() {
const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
const { data: tagValues = [], isPending } = useTagValuesListQuery({
enabled: taggingEnabled,
});
+ const [query, setQuery] = React.useState("");
+ const [createOpen, setCreateOpen] = React.useState(false);
const [labelToDelete, setLabelToDelete] = React.useState<TagValue | null>(
null,
);
const deleteMutation = useDeleteTagValueMutation();
const groups = React.useMemo(() => groupLabels(tagValues), [tagValues]);
+ const visibleGroups = React.useMemo(
+ () => filterGroups(groups, query),
+ [groups, query],
+ );
const deleteCount = labelToDelete?.workflow_count ?? 0;
function confirmDelete() {
@@ -278,8 +494,9 @@ function LabelManagement() {
<CardHeader className="border-b-2">
<CardTitle className="text-lg">Labels</CardTitle>
<CardDescription>
- Manage the grouped labels used to organize your workflows. Rename,
- recolor, or remove a label — changes apply everywhere it's used.
+ Manage the grouped labels used to organize your agents. Create,
+ rename, recolor, or remove a label — changes apply everywhere it's
+ used.
</CardDescription>
</CardHeader>
<CardContent className="p-8">
@@ -290,37 +507,68 @@ function LabelManagement() {
<Skeleton className="h-6 w-full" />
</div>
) : groups.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- No labels yet. Grouped labels you add to workflows (group:label)
- appear here for management.
- </p>
+ <div className="flex flex-col items-start gap-3">
+ <p className="text-sm text-muted-foreground">
+ No labels yet. Create one here, or add grouped labels
+ (group:label) to agents and they appear here for management.
+ </p>
+ <Button className="gap-1" onClick={() => setCreateOpen(true)}>
+ <PlusIcon className="h-4 w-4" />
+ New label
+ </Button>
+ </div>
) : (
<div className="flex flex-col gap-6">
- {groups.map((group) => (
- <div key={group.key} className="flex flex-col gap-1">
- <div className="flex items-baseline gap-2">
- <h3 className="text-sm font-medium">{group.key}</h3>
- <span className="text-xs text-muted-foreground">
- {group.values.length} label
- {group.values.length === 1 ? "" : "s"}
- </span>
- </div>
- <div className="divide-y divide-border">
- {group.values.map((label) => (
- <LabelRow
- key={`${label.key}:${label.value}`}
- label={label}
- onRequestDelete={setLabelToDelete}
- />
- ))}
+ <div className="flex items-center justify-between gap-3">
+ <Search
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder="Search labels…"
+ label="Search labels"
+ className="h-10 w-72"
+ />
+ <Button className="gap-1" onClick={() => setCreateOpen(true)}>
+ <PlusIcon className="h-4 w-4" />
+ New label
+ </Button>
+ </div>
+ {visibleGroups.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ No labels match “{query.trim()}”.
+ </p>
+ ) : (
+ visibleGroups.map((group) => (
+ <div key={group.key} className="flex flex-col gap-1.5">
+ <div className="flex items-baseline gap-2">
+ <h3 className="text-sm font-medium">{group.key}</h3>
+ <span className="text-xs text-muted-foreground">
+ {group.values.length} label
+ {group.values.length === 1 ? "" : "s"}
+ </span>
+ </div>
+ <div className="divide-y divide-border">
+ {group.values.map((label) => (
+ <LabelRow
+ key={`${label.key}:${label.value}`}
+ label={label}
+ onRequestDelete={setLabelToDelete}
+ />
+ ))}
+ </div>
</div>
- </div>
- ))}
+ ))
+ )}
</div>
)}
</CardContent>
</Card>
+ <CreateLabelDialog
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ existingGroups={groups.map((group) => group.key)}
+ />
+
<Dialog
open={labelToDelete !== null}
onOpenChange={(next) => {
diff --git a/skyvern-frontend/src/routes/tasks/list/TaskHistory.tsx b/skyvern-frontend/src/routes/tasks/list/TaskHistory.tsx
index 64d6fed1a..0b838fb9a 100644
--- a/skyvern-frontend/src/routes/tasks/list/TaskHistory.tsx
+++ b/skyvern-frontend/src/routes/tasks/list/TaskHistory.tsx
@@ -183,14 +183,17 @@ function TaskHistory() {
className="w-1/4 cursor-pointer"
onClick={(event) => handleNavigate(event, task.task_id)}
>
- <div className="flex min-w-0 flex-col gap-1">
- <span>{task.task_id}</span>
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="min-w-0 truncate">{task.task_id}</span>
{taggingEnabled && runTags && runTags.length > 0 ? (
<TagChipList
tags={runTags}
descriptions={tagDescriptions}
colors={tagColors}
maxVisible={2}
+ hideSystemTags
+ compact
+ className="shrink-0"
/>
) : null}
</div>
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
index 0766d8141..dcd6c9a3c 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
@@ -127,7 +127,12 @@ vi.mock("./hooks/useTagValuesQuery", () => ({
vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
useRunTagsBatchQuery: () => ({
- data: { wr_1: [{ key: "skyvern.status", value: "completed" }] },
+ data: {
+ wr_1: [
+ { key: "skyvern.status", value: "completed" },
+ { key: null, value: "adhoc" },
+ ],
+ },
isPending: false,
}),
}));
@@ -145,11 +150,16 @@ vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({
vi.mock("./components/tagging/TagChipList", () => ({
TagChipList: ({
tags,
+ hideSystemTags,
}: {
tags: Array<{ key: string | null; value: string }>;
+ hideSystemTags?: boolean;
}) => (
<span data-testid="tag-chip-list">
- {tags.map((tag) => `${tag.key ?? "label"}:${tag.value}`).join(",")}
+ {tags
+ .filter((tag) => !hideSystemTags || !tag.key?.startsWith("skyvern."))
+ .map((tag) => `${tag.key ?? "label"}:${tag.value}`)
+ .join(",")}
</span>
),
}));
@@ -222,12 +232,35 @@ function renderWorkflowPage(initialEntry = "/workflows/wpid_abc123") {
}
describe("WorkflowPage run tags", () => {
- it("renders a run-tag chip on the agent runs list row", () => {
+ it("shows user labels and hides system tags on the agent runs list row", () => {
const { container } = renderWorkflowPage();
expect(
within(container).getByTestId("tag-chip-list").textContent,
- ).toContain("completed");
+ ).toContain("adhoc");
+ expect(
+ within(container).getByTestId("tag-chip-list").textContent,
+ ).not.toContain("completed");
+ });
+
+ it("shift-selects runs and exposes bulk tag actions", () => {
+ renderWorkflowPage();
+
+ const first = screen.getByRole("checkbox", { name: "Select wr_1" });
+ const second = screen.getByRole("checkbox", { name: "Select wr_2" });
+ fireEvent.click(first.parentElement!);
+ fireEvent.click(second.parentElement!, { shiftKey: true });
+
+ expect(
+ screen.getByRole("toolbar", { name: "Bulk actions" }).textContent,
+ ).toContain("2 selected");
+ });
+
+ it("hides selection when workflow tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+ renderWorkflowPage();
+
+ expect(screen.queryByLabelText(/^Select /)).toBeNull();
});
it("shift-selects runs and exposes bulk tag actions", () => {
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index e136cf0e0..a252938a4 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -347,21 +347,18 @@ function WorkflowPage() {
) : (
<>
<div className="flex items-center justify-between gap-4">
- <TableSearchInput
- value={search}
- onChange={(value) => {
- setSearch(value);
- const params = new URLSearchParams(searchParams);
- params.set("page", "1");
- setSearchParams(params, { replace: true });
- }}
- placeholder="Search runs by input..."
- className="w-48 lg:w-72"
- />
<div className="flex items-center gap-2">
- {WorkflowRunsFilterControls ? (
- <WorkflowRunsFilterControls />
- ) : null}
+ <TableSearchInput
+ value={search}
+ onChange={(value) => {
+ setSearch(value);
+ const params = new URLSearchParams(searchParams);
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ }}
+ placeholder="Search runs by input..."
+ className="w-48 lg:w-72"
+ />
{taggingEnabled ? (
<TagFilterControl
tagKeys={tagFilterKeys}
@@ -372,6 +369,11 @@ function WorkflowPage() {
colors={tagColors}
/>
) : null}
+ </div>
+ <div className="flex items-center gap-2">
+ {WorkflowRunsFilterControls ? (
+ <WorkflowRunsFilterControls />
+ ) : null}
<StatusFilterDropdown
values={statusFilters}
onChange={setStatusFilters}
@@ -468,14 +470,19 @@ function WorkflowPage() {
/>
)}
<TableCell className="font-mono text-xs text-muted-foreground">
- <div className="flex flex-col gap-1">
- {workflowRunId}
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="min-w-0 truncate">
+ {workflowRunId}
+ </span>
{taggingEnabled && runTags?.length ? (
<TagChipList
tags={runTags}
descriptions={tagDescriptions}
colors={tagColors}
maxVisible={2}
+ hideSystemTags
+ compact
+ className="shrink-0 font-sans"
/>
) : null}
</div>
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx
index 0ef7c3aff..592ec89e7 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChip.tsx
@@ -17,6 +17,9 @@ type Props = {
// Palette color name for grouped tags. Ignored for standalone labels (which
// stay neutral) and for names outside the curated palette.
color?: string | null;
+ // Hide the `key: ` prefix while keeping grouped-tag color semantics — for
+ // surfaces that already display the group (e.g. rows under a group heading).
+ hideKey?: boolean;
onRemove?: () => void;
className?: string;
};
@@ -28,6 +31,7 @@ function TagChip({
value,
description,
color,
+ hideKey = false,
onRemove,
className,
}: Props) {
@@ -59,7 +63,7 @@ function TagChip({
/>
) : null}
<span className="truncate">
- {tagKey !== null ? (
+ {tagKey !== null && !hideKey ? (
<>
<span className="font-medium">{tagKey}</span>
<span className="text-muted-foreground">: </span>
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
index bab576678..e596aa133 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.shape.test.tsx
@@ -97,6 +97,73 @@ describe("TagChipList colors", () => {
expect(screen.getByText("standalone")).toBeTruthy();
});
+ it("hides system tags when hideSystemTags is set, and renders nothing when only system tags remain", () => {
+ const { container } = render(
+ <TagChipList
+ tags={[
+ { key: "skyvern.platform", value: "browser" },
+ { key: "env", value: "prod" },
+ ]}
+ hideSystemTags
+ />,
+ );
+ expect(screen.getByText("prod")).toBeTruthy();
+ expect(container.textContent).not.toContain("skyvern.platform");
+
+ const { container: systemOnly } = render(
+ <TagChipList
+ tags={[{ key: "skyvern.platform", value: "browser" }]}
+ hideSystemTags
+ />,
+ );
+ expect(systemOnly.textContent).toBe("");
+ });
+
+ it("sorts system tags after user tags and renders them muted", () => {
+ const { container } = render(
+ <TagChipList
+ tags={[
+ { key: "skyvern.platform", value: "browser" },
+ { key: "team", value: "growth" },
+ ]}
+ maxVisible={1}
+ />,
+ );
+ // The single visible slot goes to the user tag; the system tag overflows
+ // into the +1 badge.
+ expect(screen.getByText("growth")).toBeTruthy();
+ expect(screen.getByText("+1")).toBeTruthy();
+
+ const { container: bothVisible } = render(
+ <TagChipList
+ tags={[{ key: "skyvern.platform", value: "browser" }]}
+ maxVisible={2}
+ />,
+ );
+ const systemChip = bothVisible.querySelector("span");
+ expect(systemChip?.className).toContain("text-muted-foreground");
+ expect(systemChip?.className).toContain("bg-transparent");
+ expect(container.textContent).not.toContain("browser");
+ });
+
+ it("compact renders single-line small chips including the overflow badge", () => {
+ const { container } = render(
+ <TagChipList
+ tags={[
+ { key: null, value: "a" },
+ { key: null, value: "b" },
+ ]}
+ maxVisible={1}
+ compact
+ />,
+ );
+ expect(container.firstElementChild?.className).toContain("flex-nowrap");
+ const chip = screen.getByText("a").parentElement;
+ expect(chip?.className).toContain("h-5");
+ const overflow = screen.getByText("+1");
+ expect(overflow.className).toContain("h-5");
+ });
+
it("only offers removal for user-editable tags", () => {
const onRemove = vi.fn();
render(
diff --git a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
index 04218afc5..96521c480 100644
--- a/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
+++ b/skyvern-frontend/src/routes/workflows/components/tagging/TagChipList.tsx
@@ -8,6 +8,7 @@ import { badgeVariants } from "@/components/ui/badge-variants";
import { cn } from "@/util/utils";
import {
normalizeWorkflowTags,
+ isSystemTagKey,
isUserWritableTagKey,
sortTags,
tagElementKey,
@@ -24,10 +25,18 @@ type Props = {
// (key, value) -> palette color for grouped tags. Standalone labels stay neutral.
colors?: TagColorMap;
maxVisible?: number;
+ // Drop reserved skyvern.* tags entirely — for table rows, where system
+ // metadata duplicates real columns (e.g. skyvern.status vs the STATUS cell).
+ hideSystemTags?: boolean;
+ // Row-density styling: single line, smaller quieter chips.
+ compact?: boolean;
className?: string;
onRemove?: (tag: Tag) => void;
};
+const COMPACT_CHIP_CLASS = "h-5 max-w-40 px-1.5 py-0";
+const SYSTEM_CHIP_CLASS = "border-border bg-transparent text-muted-foreground";
+
// 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({
@@ -35,21 +44,35 @@ function TagChipList({
descriptions,
colors,
maxVisible = 3,
+ hideSystemTags = false,
+ compact = false,
className,
onRemove,
}: Props) {
// Re-validate at render time: callers feed this straight from API payloads,
// and a shape skew here previously killed the whole route via React #31.
- const safeTags = normalizeWorkflowTags(tags);
+ const safeTags = normalizeWorkflowTags(tags).filter(
+ (tag) => !hideSystemTags || isUserWritableTagKey(tag.key),
+ );
if (safeTags.length === 0) {
return null;
}
- const sorted = sortTags(safeTags);
+ // System tags sort after user tags (stable within each group) so user
+ // labels keep the visible slots.
+ const sorted = sortTags(safeTags).sort(
+ (a, b) => Number(isSystemTagKey(a.key)) - Number(isSystemTagKey(b.key)),
+ );
const visible = sorted.slice(0, maxVisible);
const hidden = sorted.slice(maxVisible);
return (
- <div className={cn("flex flex-wrap items-center gap-1", className)}>
+ <div
+ className={cn(
+ "flex items-center gap-1",
+ compact ? "flex-nowrap" : "flex-wrap",
+ className,
+ )}
+ >
{visible.map((tag) => (
<TagChip
key={tagElementKey(tag)}
@@ -59,6 +82,10 @@ function TagChipList({
tag.key !== null ? descriptions?.get(tag.key) : undefined
}
color={tagColorFor(colors, tag.key, tag.value)}
+ className={cn(
+ compact && COMPACT_CHIP_CLASS,
+ isSystemTagKey(tag.key) && SYSTEM_CHIP_CLASS,
+ )}
onRemove={
onRemove && isUserWritableTagKey(tag.key)
? () => onRemove(tag)
@@ -74,6 +101,7 @@ function TagChipList({
className={cn(
badgeVariants({ variant: "outline" }),
"cursor-default font-normal text-muted-foreground",
+ compact && COMPACT_CHIP_CLASS,
)}
>
+{hidden.length}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts
index f5c3756fb..89f9a4820 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowTagMutations.ts
@@ -128,6 +128,34 @@ function useDeleteTagKeyMutation() {
// carries the value in the BODY (so a value containing "/" can't break the path),
// and delete is a DELETE-with-body — axios sends it via the `data` option.
+function useCreateTagValueMutation() {
+ const credentialGetter = useCredentialGetter();
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async ({
+ key,
+ value,
+ color,
+ }: {
+ key: string;
+ value: string;
+ color: PaletteColorName;
+ }) => {
+ const client = await getClient(credentialGetter);
+ return client
+ .post<TagValue>("/tag-values", { key, value, color })
+ .then((response) => response.data);
+ },
+ onSuccess: () => {
+ // Registering a label also registers its key row for pickers.
+ queryClient.invalidateQueries({ queryKey: ["tag-values"] });
+ queryClient.invalidateQueries({ queryKey: ["tag-keys"] });
+ },
+ // No global onError toast: the caller surfaces 409 (already exists) inline.
+ });
+}
+
function useRenameTagValueMutation() {
const credentialGetter = useCredentialGetter();
const queryClient = useQueryClient();
@@ -229,6 +257,7 @@ export {
useApplyWorkflowTagsMutation,
useUpdateTagKeyMutation,
useDeleteTagKeyMutation,
+ useCreateTagValueMutation,
useRenameTagValueMutation,
useRecolorTagValueMutation,
useDeleteTagValueMutation,
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
index 1fd87a358..7bbdcd1ef 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimeline.test.tsx
@@ -1,6 +1,12 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type ReactNode } from "react";
@@ -365,9 +371,13 @@ describe("WorkflowRunTimeline", () => {
buildBlockItem(conditional, [buildBlockItem(takenChild)]),
];
- renderTimeline(null);
+ const { container } = renderTimeline(null);
- expect(screen.getByText("B • Else If")).toBeDefined();
+ const branchType = within(container).getByText("B • Else If");
+ expect(branchType.className).toContain("text-muted-foreground");
+ expect(branchType.className).not.toMatch(
+ /\b(?:rounded|border(?:-\S+)?|bg-\S+|p[xy]-\S+)\b/,
+ );
expect(screen.getByText("· Use alternate path")).toBeDefined();
expect(screen.getByText("condition false")).toBeDefined();
expect(screen.getByText("1 block")).toBeDefined();
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
index 1d8fa7f97..eb3a57d13 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.test.tsx
@@ -5,7 +5,13 @@ vi.mock("@/hooks/useCredentialGetter", () => ({
useCredentialGetter: () => null,
}));
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ActionTypes, Status } from "@/api/types";
@@ -69,6 +75,12 @@ function buildBlockItem(
const noop = () => {};
+function expectNoPillChrome(element: HTMLElement) {
+ expect(element.className).not.toMatch(
+ /\b(?:rounded|border(?:-\S+)?|bg-\S+|p[xy]-\S+)\b/,
+ );
+}
+
afterEach(() => {
cleanup();
});
@@ -94,7 +106,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
expect(rowButton.getAttribute("aria-pressed")).toBe("true");
});
- it("renders a fixed row anatomy with order, type, descriptor, and action count", () => {
+ it("renders a fixed row anatomy without a redundant block type label", () => {
const block = buildBlock({
workflow_run_block_id: "wrb_active",
block_type: "conditional",
@@ -106,7 +118,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -118,7 +130,10 @@ describe("WorkflowRunTimelineBlockItem", () => {
);
expect(screen.getByText("#5")).toBeDefined();
- expect(screen.getByText("Condition")).toBeDefined();
+ expect(within(container).queryByText("Condition")).toBeNull();
+ expect(
+ within(container).getByRole("button", { name: /Conditional/ }),
+ ).toBeDefined();
expect(screen.getByText("block_5")).toBeDefined();
expect(
screen.getByText(
@@ -175,7 +190,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -189,7 +204,8 @@ describe("WorkflowRunTimelineBlockItem", () => {
/Extract the calendar event date from the page/,
);
const secondAction = screen.getByText(/Click the account menu/);
- expect(screen.getByText("Extract Data")).toBeDefined();
+ const actionType = within(container).getByText("Extract Data");
+ expect(actionType.className).toContain("sr-only");
expect(screen.queryByText("100%")).toBeNull();
expect(
firstAction.compareDocumentPosition(secondAction) &
@@ -385,7 +401,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -405,6 +421,15 @@ describe("WorkflowRunTimelineBlockItem", () => {
gotoRow.compareDocumentPosition(clickRow) &
Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
+ expect(within(container).getByText("Goto URL").className).toContain(
+ "sr-only",
+ );
+ expect(within(container).getByText("Click").className).toContain("sr-only");
+ expect(
+ within(container).getByRole("button", {
+ name: /Goto URL.*page\.goto https:\/\/example\.com/,
+ }),
+ ).toBeDefined();
});
it("labels a recorded page.evaluate action as Execute JS instead of a blank badge", () => {
@@ -492,7 +517,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
] as unknown as WorkflowRunBlock["actions"],
});
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -502,7 +527,9 @@ describe("WorkflowRunTimelineBlockItem", () => {
/>,
);
- expect(screen.getByText("Error")).toBeDefined();
+ const errorType = within(container).getByText("Error");
+ expect(errorType.className).toContain("text-rose-700");
+ expectNoPillChrome(errorType);
expect(screen.queryByText("Screenshot")).toBeNull();
expect(screen.getByText(/ValueError: boom · line 7/)).toBeDefined();
});
@@ -656,7 +683,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
},
];
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -670,7 +697,9 @@ describe("WorkflowRunTimelineBlockItem", () => {
expect(screen.getByText(/Open the homepage/)).toBeDefined();
expect(screen.getByText(/Click the top post/)).toBeDefined();
expect(screen.getByText("Goto")).toBeDefined();
- expect(screen.getByText("Click")).toBeDefined();
+ const clickType = within(container).getByText("Click");
+ expect(clickType.className).toContain("text-muted-foreground");
+ expectNoPillChrome(clickType);
expect(screen.getByText("L1")).toBeDefined();
expect(screen.getByText("L3-5")).toBeDefined();
});
@@ -790,7 +819,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
actions: [],
});
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -800,8 +829,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
/>,
);
- // Both the type badge and the row name read "Code" when nothing else exists.
- expect(screen.getAllByText("Code").length).toBe(2);
+ expect(within(container).getAllByText("Code").length).toBe(1);
});
it("selects the block when a code step row is clicked", () => {
@@ -876,7 +904,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
},
];
- render(
+ const { container } = render(
<WorkflowRunTimelineBlockItem
activeItem={block}
block={block}
@@ -892,6 +920,9 @@ describe("WorkflowRunTimelineBlockItem", () => {
expect(didntRun.length).toBe(2);
expect(screen.getByText(/Read the result/)).toBeDefined();
expect(screen.getByText(/Summarize the page/)).toBeDefined();
+ const skippedType = within(container).getByText("Extract Data");
+ expect(skippedType.className).toContain("text-muted-foreground");
+ expectNoPillChrome(skippedType);
// The executed goto step (line 1) reads its plain-English step copy in its
// fired action row, not as a didn't-run row.
expect(screen.getByText(/Open the homepage · line 1/)).toBeDefined();
@@ -1145,7 +1176,7 @@ describe("WorkflowRunTimelineBlockItem", () => {
screen.getByText(/Extract the product details · line 12/),
).toBeDefined();
expect(screen.queryByText(/page\.extract/)).toBeNull();
- // The readable action type stays as the chip.
+ // The readable action type stays as plain text.
expect(screen.getByText("Extract Data")).toBeDefined();
});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
index 861a2be26..2ff8b4731 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunTimelineBlockItem.tsx
@@ -198,7 +198,7 @@ type ActionRowPresentation = {
// (failed null_action) is labeled Error instead of Screenshot. The leading
// text reuses the matched definition step's plain-English copy so a fired
// action reads the same as the editor, falling back to the action's own
-// reasoning and finally to the readable action type chip.
+// reasoning and finally to the readable action type label.
function getCodeActionRowPresentation(
action: ActionsApiResponse,
matchedStep: CodeBlockStep | null,
@@ -289,24 +289,6 @@ function getTimelineDescriptor(block: WorkflowRunBlock): string {
return `${workflowBlockTitle[block.block_type]} block`;
}
-function getTimelineTypeLabel(block: WorkflowRunBlock): string {
- switch (block.block_type) {
- case "conditional":
- return "Condition";
- case "for_loop":
- case "while_loop":
- return "Loop";
- case "navigation":
- case "task":
- case "task_v2":
- return "Task";
- case "http_request":
- return "HTTP";
- default:
- return workflowBlockTitle[block.block_type];
- }
-}
-
// getCodeBlockTitle ends at the bare "Code" label for prompt-less runs, which
// dropped the reasoning subtitle the timeline used to show. Fall back to the
// block reasoning (description) before bare "Code", normalized like a prompt.
@@ -590,16 +572,13 @@ function TimelineActionRows({
<span className="w-7 shrink-0 text-[10px] tabular-nums text-muted-foreground dark:text-slate-500">
#{displayIndex}
</span>
- <span
- className={cn(
- "shrink-0 rounded border px-1.5 py-0.5 text-[10px] font-medium",
- tone === "error"
- ? "border-rose-500/30 bg-rose-500/10 text-rose-700 dark:text-rose-300"
- : "border-border text-muted-foreground",
- )}
- >
- {label}
- </span>
+ {tone === "error" ? (
+ <span className="shrink-0 text-[10px] text-rose-700 dark:text-rose-300">
+ {label}
+ </span>
+ ) : (
+ <span className="sr-only">{label}</span>
+ )}
{summary && (
<span className="min-w-0 flex-1 truncate text-muted-foreground dark:text-slate-500">
· {summary}
@@ -705,7 +684,7 @@ function TimelineCodeStepRows({
<span className="w-7 shrink-0 text-[10px] tabular-nums text-muted-foreground dark:text-slate-500">
#{index + 1}
</span>
- <span className="shrink-0 rounded border border-border px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
+ <span className="shrink-0 text-[10px] text-muted-foreground">
{getReadableActionType(step.action_type)}
</span>
{summary && (
@@ -780,7 +759,7 @@ function TimelineSkippedStepRows({
className="size-2 shrink-0 rounded-full border border-dashed border-border dark:border-slate-500"
aria-hidden="true"
/>
- <span className="shrink-0 rounded border border-border px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground">
+ <span className="shrink-0 text-[10px] text-muted-foreground">
{getReadableActionType(step.action_type)}
</span>
{summary && (
@@ -946,7 +925,7 @@ function TimelineSkippedBranchGroup({
className="size-2 shrink-0 rounded-full border border-dashed border-border dark:border-slate-500"
aria-hidden="true"
/>
- <span className="shrink-0 rounded border border-border bg-muted/50 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
+ <span className="shrink-0 text-[10px] uppercase tracking-wide text-muted-foreground">
{branchMarker}
</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground dark:text-slate-500">
@@ -1000,7 +979,6 @@ function WorkflowRunTimelineBlockItem({
const duration =
block.duration !== null ? formatDuration(toDuration(block.duration)) : null;
const blockTypeTitle = workflowBlockTitle[block.block_type];
- const blockTypeLabel = getTimelineTypeLabel(block);
const blockIndex = blockOrder?.get(block.workflow_run_block_id);
const actions = block.actions ?? [];
const actionCount = actions.length;
@@ -1187,7 +1165,12 @@ function WorkflowRunTimelineBlockItem({
status={block.status}
isFinalized={!!workflowRunIsFinalized}
/>
- <span title={blockTypeTitle} className="shrink-0">
+ <span
+ title={blockTypeTitle}
+ role="img"
+ aria-label={blockTypeTitle}
+ className="shrink-0"
+ >
<WorkflowBlockIcon
workflowBlockType={block.block_type}
className="size-3.5 text-tertiary-foreground"
@@ -1198,9 +1181,6 @@ function WorkflowRunTimelineBlockItem({
#{blockIndex}
</span>
)}
- <span className="inline-flex min-w-[6rem] max-w-[8rem] shrink-0 justify-center truncate rounded bg-muted/70 px-1.5 py-0.5 text-[10px] font-medium text-tertiary-foreground dark:bg-slate-700/70">
- {blockTypeLabel}
- </span>
<span className="min-w-0 max-w-[12rem] truncate text-foreground dark:text-slate-200">
{blockName}
</span>
diff --git a/skyvern/forge/sdk/db/repositories/tags.py b/skyvern/forge/sdk/db/repositories/tags.py
index 05df43b3e..8a5651772 100644
--- a/skyvern/forge/sdk/db/repositories/tags.py
+++ b/skyvern/forge/sdk/db/repositories/tags.py
@@ -54,6 +54,10 @@ class TagValueRenameCollision(ValueError):
already exists active org-wide. v1 rejects rather than merging."""
+class TagValueAlreadyExists(ValueError):
+ """Raised when registering a ``(key, value)`` that is already registered active."""
+
+
class RunTagWorkflowRunMismatch(ValueError):
"""Raised when a run-tag write targets a workflow run outside the supplied org."""
@@ -62,6 +66,7 @@ class RunTagWorkflowRunMismatch(ValueError):
# BusinessLogicError (WARN), not UnexpectedError (ERROR).
register_passthrough_exception(TagCountLimitExceeded)
register_passthrough_exception(TagValueRenameCollision)
+register_passthrough_exception(TagValueAlreadyExists)
register_passthrough_exception(RunTagWorkflowRunMismatch)
@@ -846,7 +851,10 @@ class TagsRepository(BaseRepository):
color: str,
) -> TagValueModel | None:
"""Recolor an existing (key, value) registry row. Returns None when the pair
- is not registered for the org (caller should 404)."""
+ is not registered for the org (caller should 404). Reserved ``skyvern.*``
+ keys are system-managed and always rejected (no system recolor path exists)."""
+ if is_reserved_tag_key(key):
+ raise ValueError("reserved skyvern.* tag values are system-managed and cannot be recolored")
async with self.Session() as session:
stmt = (
select(TagValueModel)
@@ -863,6 +871,73 @@ class TagsRepository(BaseRepository):
await session.refresh(row)
return row
+ @db_operation("register_tag_value")
+ async def register_tag_value(
+ self,
+ organization_id: str,
+ key: str,
+ value: str,
+ color: str | None = None,
+ ) -> TagValueModel:
+ """Register a grouped label ``(key, value)`` before any workflow uses it
+ (the settings-surface create path; applying tags registers implicitly).
+ Also registers the key row so the group shows up in pickers. Writes no
+ tag events — the label attaches to nothing yet. Raises
+ ``TagValueAlreadyExists`` when the pair is already registered active;
+ reserved ``skyvern.*`` keys are always rejected (system-managed)."""
+ if is_reserved_tag_key(key):
+ raise ValueError("reserved skyvern.* tag values are system-managed and cannot be created manually")
+ async with self.Session() as session:
+ existing = (
+ await session.execute(
+ select(TagValueModel).where(
+ and_(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.value == value,
+ TagValueModel.deleted_at.is_(None),
+ )
+ )
+ )
+ ).scalar_one_or_none()
+ if existing is not None:
+ raise TagValueAlreadyExists(f"tag value '{key}:{value}' already exists")
+
+ dialect_name = session.bind.dialect.name if session.bind is not None else "postgresql"
+ insert = sqlite.insert if dialect_name == "sqlite" else postgresql.insert
+ # ON CONFLICT DO NOTHING keeps a concurrent create/apply race benign;
+ # the read-back below returns whichever row won.
+ await session.execute(
+ insert(TagValueModel.__table__)
+ .values(organization_id=organization_id, key=key, value=value, color=color or random_tag_color())
+ .on_conflict_do_nothing(
+ index_elements=["organization_id", "key", "value"],
+ index_where=text("deleted_at IS NULL"),
+ )
+ )
+ await session.execute(
+ insert(TagKeyModel.__table__)
+ .values(organization_id=organization_id, key=key)
+ .on_conflict_do_nothing(
+ index_elements=["organization_id", "key"],
+ index_where=text("deleted_at IS NULL"),
+ )
+ )
+ await session.commit()
+
+ return (
+ await session.execute(
+ select(TagValueModel).where(
+ and_(
+ TagValueModel.organization_id == organization_id,
+ TagValueModel.key == key,
+ TagValueModel.value == value,
+ TagValueModel.deleted_at.is_(None),
+ )
+ )
+ )
+ ).scalar_one()
+
@db_operation("get_tag_key")
async def get_tag_key(self, organization_id: str, key: str) -> TagKeyModel | None:
async with self.Session() as session:
@@ -1173,7 +1248,12 @@ class TagsRepository(BaseRepository):
iterates in Python. Fine for realistic key fan-out (a key on at most a
few hundred workflows) and a one-off admin action; if a key ever spans
thousands of workflows, switch to a bulk UPDATE (supersede) + batched
- INSERT for the DELETE events to avoid the ORM round-trip."""
+ INSERT for the DELETE events to avoid the ORM round-trip.
+
+ Reserved ``skyvern.*`` keys are rejected unless the write carries system
+ provenance, so no user-provenance DELETE can land in the system-tag event log."""
+ if is_reserved_tag_key(key) and context.source != TagSource.SYSTEM:
+ raise ValueError("reserved skyvern.* tag keys can only be modified with system provenance")
now = datetime.now(timezone.utc)
async with self.Session() as session:
key_row = (
@@ -1255,7 +1335,12 @@ class TagsRepository(BaseRepository):
DELETE events don't match the SET-only partial UNIQUE, so superseding the SET
and inserting the DELETE in one transaction needs no flush ordering (same as
- ``delete_tag_key``). The same accepted delete-vs-SET race applies."""
+ ``delete_tag_key``). The same accepted delete-vs-SET race applies.
+
+ Reserved ``skyvern.*`` keys are rejected unless the write carries system
+ provenance, so no user-provenance DELETE can land in the system-tag event log."""
+ if is_reserved_tag_key(key) and context.source != TagSource.SYSTEM:
+ raise ValueError("reserved skyvern.* tag values can only be modified with system provenance")
now = datetime.now(timezone.utc)
async with self.Session() as session:
value_row = (
@@ -1355,7 +1440,12 @@ class TagsRepository(BaseRepository):
coexist with the rename — surfacing as a transient IntegrityError on the partial
UNIQUE (the caller's one retry covers it) or two active SETs that the next apply
reconciles. Serializing would need dialect-specific row/advisory locking,
- disproportionate for a rare manual admin action."""
+ disproportionate for a rare manual admin action.
+
+ Reserved ``skyvern.*`` keys are rejected unless the write carries system
+ provenance, so no user-provenance SET can land in the system-tag event log."""
+ if is_reserved_tag_key(key) and context.source != TagSource.SYSTEM:
+ raise ValueError("reserved skyvern.* tag values can only be modified with system provenance")
now = datetime.now(timezone.utc)
async with self.Session() as session:
old_row = (
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 47863384d..c8ee4d057 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -59,6 +59,7 @@ from skyvern.forge.sdk.core.security import generate_skyvern_signature
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.db.repositories.tags import (
RunTagWorkflowRunMismatch,
+ TagValueAlreadyExists,
TagValueRenameCollision,
TagValueRenameResult,
)
@@ -170,6 +171,7 @@ from skyvern.schemas.tags import (
TagResponse,
TagsResponse,
TagValue,
+ TagValueCreate,
TagValueDelete,
TagValueDeleteResponse,
TagValueRename,
@@ -2241,6 +2243,41 @@ async def list_tag_values(
]
+@legacy_base_router.post("/tag-values", response_model=TagValue, tags=["agent"], include_in_schema=False)
+@legacy_base_router.post("/tag-values/", response_model=TagValue, include_in_schema=False)
+@base_router.post(
+ "/tag-values",
+ response_model=TagValue,
+ tags=["Tags"],
+ openapi_extra={"x-fern-sdk-method-name": "create_tag_value"},
+ description="Register a grouped tag (key, value) with a palette color before any workflow uses it. "
+ "The label shows a zero workflow count until applied to a workflow.",
+ summary="Create tag value",
+ responses={
+ 200: {"description": "Successfully registered tag value"},
+ 409: {"description": "Tag value already exists"},
+ 422: {"description": "Invalid key, value, or color"},
+ },
+)
+@base_router.post("/tag-values/", response_model=TagValue, include_in_schema=False)
+async def create_tag_value(
+ data: TagValueCreate = Body(...),
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+ _tagging_gate: None = Depends(require_workflow_tagging),
+) -> TagValue:
+ analytics.capture("skyvern-oss-tag-value-create")
+ try:
+ row = await app.DATABASE.tags.register_tag_value(
+ organization_id=current_org.organization_id,
+ key=data.key,
+ value=data.value,
+ color=data.color,
+ )
+ except TagValueAlreadyExists as e:
+ raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(e)) from e
+ return TagValue(key=row.key, value=row.value, color=row.color, workflow_count=0)
+
+
@legacy_base_router.patch("/tag-values/{key}", response_model=TagValue, tags=["agent"], include_in_schema=False)
@legacy_base_router.patch("/tag-values/{key}/", response_model=TagValue, include_in_schema=False)
@base_router.patch(
diff --git a/skyvern/schemas/tags.py b/skyvern/schemas/tags.py
index ef42c8f95..3606648da 100644
--- a/skyvern/schemas/tags.py
+++ b/skyvern/schemas/tags.py
@@ -250,6 +250,41 @@ class TagValue(BaseModel):
)
+class TagValueCreate(BaseModel):
+ """Body for ``POST /v1/tag-values``: register a grouped label before any
+ workflow uses it. The label shows a zero workflow count until applied."""
+
+ key: str = Field(description="Tag key (group) for the new label.")
+ value: str = Field(description="Tag value (label) to register under the key.")
+ color: str | None = Field(
+ None, description="Palette color name for the label; a random palette color when omitted."
+ )
+
+ @field_validator("key", mode="before")
+ @classmethod
+ def _normalize_key(cls, v: object) -> str:
+ key = normalize_optional_tag_key(v)
+ if key is None:
+ raise ValueError("tag key is required")
+ return key
+
+ @field_validator("value", mode="before")
+ @classmethod
+ def _normalize_value(cls, v: object) -> str:
+ value = normalize_tag_value(v)
+ # Grouped values reserve '*' as the group filter wildcard (mirrors TagInput).
+ if value == "*":
+ raise ValueError("grouped tag values must not be exactly '*' (reserved as the group filter wildcard)")
+ return value
+
+ @field_validator("color", mode="before")
+ @classmethod
+ def _normalize_color(cls, v: object) -> str | None:
+ if v is None:
+ return None
+ return normalize_tag_color(v)
+
+
class TagValueUpdate(BaseModel):
"""Body for ``PATCH /v1/tag-values/{key}``. The value rides in the body, not the
path, so values containing ``/`` stay addressable."""
diff --git a/tests/unit/forge/sdk/db/test_self_heal_schema.py b/tests/unit/forge/sdk/db/test_self_heal_schema.py
index 8d17a4510..0dd92699a 100644
--- a/tests/unit/forge/sdk/db/test_self_heal_schema.py
+++ b/tests/unit/forge/sdk/db/test_self_heal_schema.py
@@ -54,10 +54,13 @@ def test_heal_migration_chains_from_current_head() -> None:
heads = script.get_heads()
assert len(heads) == 1
- revision = script.get_revision("2b8e37d98d97")
- assert revision is not None
- # down_revision is re-pointed to main's head on every rebase (migration-rebase policy);
- # assert the parent resolves to a real revision instead of pinning a specific hash.
+ # Revision hashes differ between this repo and the OSS mirror (migrations are
+ # regenerated on sync), so locate the migration by its docstring title instead.
+ heal_revisions = [
+ rev for rev in script.walk_revisions() if rev.doc == "add heal episode workflow block label index"
+ ]
+ assert len(heal_revisions) == 1
+ revision = heal_revisions[0]
assert revision.down_revision is not None
assert script.get_revision(revision.down_revision) is not None
# The heal migration must be part of the single linear history, not pinned as the tip:
diff --git a/tests/unit/test_tag_endpoints.py b/tests/unit/test_tag_endpoints.py
index 9d1b629f9..2ce7ef1e1 100644
--- a/tests/unit/test_tag_endpoints.py
+++ b/tests/unit/test_tag_endpoints.py
@@ -29,6 +29,7 @@ from skyvern.forge.sdk.db.repositories.tags import TagsRepository
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.services import org_auth_service
from skyvern.forge.sdk.workflow.models.tags import CallerType
+from skyvern.forge.sdk.workflow.models.validators import TAG_COLOR_PALETTE
ORG_ID = "o_test"
OTHER_ORG_ID = "o_other"
@@ -1038,6 +1039,47 @@ def test_patch_tag_value_reserved_prefix_returns_400(client: TestClient) -> None
assert resp.status_code == 400
+# ----------------------------- POST /tag-values ------------------------------------
+
+
+def test_create_tag_value_registers_label(client: TestClient) -> None:
+ resp = client.post("/v1/tag-values", json={"key": "env", "value": "prod", "color": "blue"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json() == {"key": "env", "value": "prod", "color": "blue", "workflow_count": 0}
+ values = client.get("/v1/tag-values").json()
+ assert [(v["key"], v["value"], v["color"], v["workflow_count"]) for v in values] == [("env", "prod", "blue", 0)]
+ # The group is registered for pickers even before any workflow uses it.
+ keys = client.get("/v1/tag-keys").json()
+ assert [k["key"] for k in keys] == ["env"]
+
+
+def test_create_tag_value_409_when_already_registered(client: TestClient) -> None:
+ client.post("/v1/tag-values", json={"key": "env", "value": "prod", "color": "blue"})
+ resp = client.post("/v1/tag-values", json={"key": "env", "value": "prod", "color": "red"})
+ assert resp.status_code == 409
+
+
+def test_create_tag_value_reserved_key_returns_422(client: TestClient) -> None:
+ resp = client.post("/v1/tag-values", json={"key": "skyvern.platform", "value": "web", "color": "blue"})
+ assert resp.status_code == 422
+
+
+def test_create_tag_value_invalid_color_returns_422(client: TestClient) -> None:
+ resp = client.post("/v1/tag-values", json={"key": "env", "value": "prod", "color": "chartreuse"})
+ assert resp.status_code == 422
+
+
+def test_create_tag_value_defaults_color_when_omitted(client: TestClient) -> None:
+ resp = client.post("/v1/tag-values", json={"key": "env", "value": "prod"})
+ assert resp.status_code == 200, resp.text
+ assert resp.json()["color"] in TAG_COLOR_PALETTE
+
+
+def test_create_tag_value_legacy_route_works(client: TestClient) -> None:
+ resp = client.post("/api/v1/tag-values", json={"key": "env", "value": "prod", "color": "blue"})
+ assert resp.status_code == 200, resp.text
+
+
# ----------------------------- GET /tag-values workflow_count ----------------------
diff --git a/tests/unit/test_tags_repository.py b/tests/unit/test_tags_repository.py
index 4448a169a..b8bc4b21f 100644
--- a/tests/unit/test_tags_repository.py
+++ b/tests/unit/test_tags_repository.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.db.repositories.tags import (
RunTagWorkflowRunMismatch,
TagCountLimitExceeded,
TagsRepository,
+ TagValueAlreadyExists,
TagValueRenameCollision,
)
from skyvern.forge.sdk.workflow.models.tags import (
@@ -1373,3 +1374,146 @@ async def test_delete_tag_value_then_reapply_reregisters(repo: TagsRepository) -
)
assert await repo.get_active_grouped_tags_for_workflow("wpid_a", ORG_ID) == {"env": "prod"}
assert [(v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("prod", "green")]
+
+
+def _system_ctx() -> TagWriteContext:
+ return TagWriteContext(
+ caller_id="system:test",
+ source=TagSource.SYSTEM,
+ caller_type=CallerType.SYSTEM,
+ )
+
+
+async def _seed_system_run_tag(repo: TagsRepository) -> None:
+ await _seed_workflow_run(repo, WRID)
+ await repo.apply_system_run_tag_changes(
+ workflow_run_id=WRID,
+ organization_id=ORG_ID,
+ sets={"skyvern.platform": "web"},
+ )
+
+
+async def test_recolor_tag_value_rejects_reserved_key(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ with pytest.raises(ValueError, match="reserved"):
+ await repo.recolor_tag_value(ORG_ID, "skyvern.platform", "web", "pink")
+
+
+async def test_delete_tag_value_rejects_reserved_key_with_user_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ with pytest.raises(ValueError, match="reserved"):
+ await repo.delete_tag_value(ORG_ID, "skyvern.platform", "web", _ctx())
+
+ # The system tag is untouched and no user-provenance event leaked into the log.
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {"skyvern.platform": "web"}
+ assert all(row.source == TagSource.SYSTEM.value for row in await _all_run_events(repo))
+
+
+async def test_rename_tag_value_rejects_reserved_key_with_user_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ with pytest.raises(ValueError, match="reserved"):
+ await repo.rename_tag_value(ORG_ID, "skyvern.platform", "web", "browser", _ctx())
+
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {"skyvern.platform": "web"}
+ assert all(row.source == TagSource.SYSTEM.value for row in await _all_run_events(repo))
+
+
+async def test_delete_tag_value_allows_reserved_key_with_system_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ removed = await repo.delete_tag_value(ORG_ID, "skyvern.platform", "web", _system_ctx())
+
+ assert removed is not None
+ assert removed.removed_from_run_count == 1
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {}
+
+
+async def test_rename_tag_value_allows_reserved_key_with_system_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ result = await repo.rename_tag_value(ORG_ID, "skyvern.platform", "web", "browser", _system_ctx())
+
+ assert result is not None
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {"skyvern.platform": "browser"}
+
+
+async def test_delete_tag_key_rejects_reserved_key_with_user_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ with pytest.raises(ValueError, match="reserved"):
+ await repo.delete_tag_key(ORG_ID, "skyvern.platform", _ctx())
+
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {"skyvern.platform": "web"}
+ assert all(row.source == TagSource.SYSTEM.value for row in await _all_run_events(repo))
+
+
+async def test_delete_tag_key_allows_reserved_key_with_system_provenance(repo: TagsRepository) -> None:
+ await _seed_system_run_tag(repo)
+
+ removed = await repo.delete_tag_key(ORG_ID, "skyvern.platform", _system_ctx())
+
+ assert removed is not None
+ assert removed.removed_from_run_count == 1
+ assert await repo.get_active_grouped_tags_for_run(WRID, ORG_ID) == {}
+
+
+async def test_register_tag_value_registers_color_row_and_key(repo: TagsRepository) -> None:
+ row = await repo.register_tag_value(ORG_ID, "env", "prod", "blue")
+
+ assert row is not None
+ assert (row.key, row.value, row.color) == ("env", "prod", "blue")
+ assert [(v.key, v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("env", "prod", "blue")]
+ # The group participates in the key registry (pickers/descriptions) too.
+ assert await _registered_keys(repo) == ["env"]
+
+
+async def test_register_tag_value_assigns_random_color_when_none(repo: TagsRepository) -> None:
+ row = await repo.register_tag_value(ORG_ID, "env", "prod", None)
+
+ assert row is not None
+ assert row.color in TAG_COLOR_PALETTE
+
+
+async def test_register_tag_value_writes_no_tag_events(repo: TagsRepository) -> None:
+ await repo.register_tag_value(ORG_ID, "env", "prod", "blue")
+
+ assert await _all_events(repo) == []
+ assert await _all_run_events(repo) == []
+
+
+async def test_register_tag_value_conflicts_when_already_registered(repo: TagsRepository) -> None:
+ await repo.register_tag_value(ORG_ID, "env", "prod", "blue")
+
+ with pytest.raises(TagValueAlreadyExists):
+ await repo.register_tag_value(ORG_ID, "env", "prod", "red")
+
+
+async def test_register_tag_value_rejects_reserved_key(repo: TagsRepository) -> None:
+ with pytest.raises(ValueError, match="reserved"):
+ await repo.register_tag_value(ORG_ID, "skyvern.platform", "web", "blue")
+
+
+async def test_register_tag_value_reuses_soft_deleted_pair(repo: TagsRepository) -> None:
+ await repo.register_tag_value(ORG_ID, "env", "prod", "blue")
+ await repo.delete_tag_value(ORG_ID, "env", "prod", _ctx())
+
+ row = await repo.register_tag_value(ORG_ID, "env", "prod", "green")
+
+ assert row is not None
+ assert [(v.value, v.color) for v in await repo.list_tag_values(ORG_ID)] == [("prod", "green")]