From 37e0606122835f68e5eddf67b53384a46cd93403 Mon Sep 17 00:00:00 2001 From: jonvdveen <196496658+jonvdveen@users.noreply.github.com> Date: Thu, 2 Jul 2026 19:43:02 -0600 Subject: [PATCH 1/2] feat: tag condition for workflow IF/SWITCH nodes Adds a "Tag" condition type that filters assets by Immich tags, with the same match modes as the person condition (has any of / has all of / has none of). Selected tags also match their child tags via Immich's tag_closure hierarchy table, mirroring how tag browsing behaves in Immich itself. - conditionBuilder: tag case with EXISTS subqueries on tag_asset, descendant-inclusive via tag_closure (plus a direct id check so a missing self-closure row can't drop matches) - ConditionEditor: Tag entry + TagPicker multi-select (PersonPicker pattern) with tag color chips - conditionSummary: node label ("Tag any of: ...") - new GET /api/tags route + client handler + drizzle schema for Immich's tag table Co-Authored-By: Claude Fable 5 --- .../workflows/config/ConditionEditor.tsx | 111 +++++++++++++++++- .../workflows/nodes/conditionSummary.ts | 8 ++ src/config/routes.ts | 1 + src/handlers/api/tag.handler.ts | 13 ++ src/lib/workflow/conditionBuilder.ts | 30 +++++ src/pages/api/tags/index.ts | 30 +++++ src/schema/index.ts | 3 +- src/schema/tags.schema.ts | 11 ++ src/types/workflow.d.ts | 2 +- 9 files changed, 206 insertions(+), 3 deletions(-) create mode 100644 src/handlers/api/tag.handler.ts create mode 100644 src/pages/api/tags/index.ts create mode 100644 src/schema/tags.schema.ts diff --git a/src/components/workflows/config/ConditionEditor.tsx b/src/components/workflows/config/ConditionEditor.tsx index 084e63b..7b60ba0 100644 --- a/src/components/workflows/config/ConditionEditor.tsx +++ b/src/components/workflows/config/ConditionEditor.tsx @@ -4,8 +4,9 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command"; import { ICondition, ConditionType } from "@/types/workflow"; -import { Plus, X, Check } from "lucide-react"; +import { Plus, X, Check, Tag } from "lucide-react"; import { listPeople } from "@/handlers/api/people.handler"; +import { listTags, ITag } from "@/handlers/api/tag.handler"; import { IPerson } from "@/types/person"; import { PERSON_THUBNAIL_PATH } from "@/config/routes"; import { useEffect, useState } from "react"; @@ -14,6 +15,7 @@ import { cn } from "@/lib/utils"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -124,6 +126,95 @@ function PersonPicker({ selectedIds, onChange }: PersonPickerProps) { ); } +interface TagPickerProps { + selectedIds: string[]; + onChange: (tagIds: string[], tagValues: string[]) => void; +} + +function TagPicker({ selectedIds, onChange }: TagPickerProps) { + const [open, setOpen] = useState(false); + const [tags, setTags] = useState([]); + const [loading, setLoading] = useState(false); + + useEffect(() => { + setLoading(true); + listTags() + .then((res) => setTags(res.tags)) + .finally(() => setLoading(false)); + }, []); + + const selectedSet = new Set(selectedIds || []); + const selectedTags = tags.filter((t) => selectedSet.has(t.id)); + + const toggleTag = (tag: ITag) => { + let nextIds: string[]; + let nextValues: string[]; + if (selectedSet.has(tag.id)) { + nextIds = selectedIds.filter((id) => id !== tag.id); + nextValues = selectedTags.filter((t) => t.id !== tag.id).map((t) => t.value); + } else { + nextIds = [...selectedIds, tag.id]; + nextValues = [...selectedTags.map((t) => t.value), tag.value]; + } + onChange(nextIds, nextValues); + }; + + return ( +
+ {/* Selected tag chips */} + {selectedTags.length > 0 && ( +
+ {selectedTags.map((t) => ( + + ))} +
+ )} + + {/* Picker */} + + + + + + + + + {loading ? "Loading..." : "No tags found."} + + {tags.map((tag) => ( + toggleTag(tag)} + className="flex items-center gap-2" + > + + {tag.value} + + + ))} + + + + + +
+ ); +} + interface ConditionEditorProps { conditions: ICondition[]; onChange: (conditions: ICondition[]) => void; @@ -219,6 +310,24 @@ function ConditionFields({ condition, onChange }: { condition: ICondition; onCha /> ); + case "tag": + return ( +
+ + onChange({ ...condition, tagIds, tagValues })} + /> +

Selected tags also match their child tags.

+
+ ); case "geo_radius": return (
diff --git a/src/components/workflows/nodes/conditionSummary.ts b/src/components/workflows/nodes/conditionSummary.ts index 5cc441c..ce8c3f9 100644 --- a/src/components/workflows/nodes/conditionSummary.ts +++ b/src/components/workflows/nodes/conditionSummary.ts @@ -3,6 +3,7 @@ import { ICondition, ConditionType } from "@/types/workflow"; const conditionTypeLabels: Record = { person: "Person", person_unnamed: "Unnamed People", + tag: "Tag", city: "City", state: "State", country: "Country", @@ -45,6 +46,13 @@ export function formatConditionSummary(c: ICondition): string { } case "person_unnamed": return label; + case "tag": { + const values: string[] = c.tagValues || []; + const match = matchLabels[c.match] || c.match || "any of"; + if (values.length === 0) return `${label}: (none selected)`; + const valueStr = values.length <= 2 ? values.join(", ") : `${values[0]}, ${values[1]} +${values.length - 2}`; + return `${label} ${match}: ${valueStr}`; + } case "city": case "state": case "country": { diff --git a/src/config/routes.ts b/src/config/routes.ts index 5ecd930..2a6478e 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -7,6 +7,7 @@ export const LOGOUT_PATH = BASE_API_ENDPOINT + "/users/logout"; export const LIST_PEOPLE_PATH = BASE_API_ENDPOINT + "/people/list"; +export const LIST_TAGS_PATH = BASE_API_ENDPOINT + "/tags"; export const SEARCH_PEOPLE_PATH = BASE_PROXY_ENDPOINT + "/search/person"; export const SIMILAR_FACES_PATH = (id: string) => BASE_API_ENDPOINT + "/people/" + id + "/similar-faces"; export const PERSON_THUBNAIL_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/thumbnail/" + id; diff --git a/src/handlers/api/tag.handler.ts b/src/handlers/api/tag.handler.ts new file mode 100644 index 0000000..0f62fce --- /dev/null +++ b/src/handlers/api/tag.handler.ts @@ -0,0 +1,13 @@ +import { LIST_TAGS_PATH } from "@/config/routes"; +import API from "@/lib/api"; + +export interface ITag { + id: string; + value: string; + color: string | null; + parentId: string | null; +} + +export const listTags = (): Promise<{ tags: ITag[] }> => { + return API.get(LIST_TAGS_PATH); +}; diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index e695515..3e01a00 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -117,6 +117,36 @@ function buildSingleCondition(c: ICondition): SQL | undefined { return sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IN (${sql.raw(idList)}))`; } + case "tag": { + const ids: string[] = c.tagIds || []; + if (ids.length === 0) return undefined; + + // A selected tag also matches assets tagged with any of its child tags + // (tag_closure holds the hierarchy, including self-references). + const descendants = (tagId: string) => + sql`(SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" = ${tagId})`; + + if (c.match === "not_contains") { + // Asset must not carry ANY of these tags (or their children) + const checks = ids.map((tid: string) => + sql`NOT EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + if (c.match === "contains_all") { + // Asset must carry ALL of these tags (or their children) + const checks = ids.map((tid: string) => + sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" = ${tid} OR ta."tagId" IN ${descendants(tid)}))` + ); + return and(...checks)!; + } + + // contains_any (default) — asset carries at least one of these tags (or their children) + const idList = ids.map((id: string) => `'${id}'`).join(","); + return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${sql.raw(idList)}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${sql.raw(idList)}))))`; + } + case "person_unnamed": if (c.match === "no_unnamed") { return sql`NOT EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`; diff --git a/src/pages/api/tags/index.ts b/src/pages/api/tags/index.ts new file mode 100644 index 0000000..42e37c3 --- /dev/null +++ b/src/pages/api/tags/index.ts @@ -0,0 +1,30 @@ +import { db } from "@/config/db"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { tags } from "@/schema"; +import { asc, eq } from "drizzle-orm"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function handler( + req: NextApiRequest, + res: NextApiResponse +) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const rows = await db + .select({ + id: tags.id, + value: tags.value, + color: tags.color, + parentId: tags.parentId, + }) + .from(tags) + .where(eq(tags.userId, currentUser.id)) + .orderBy(asc(tags.value)); + + return res.status(200).json({ tags: rows }); + } catch (error: any) { + res.status(500).json({ error: error?.message }); + } +} diff --git a/src/schema/index.ts b/src/schema/index.ts index a3d340a..8ea2ff7 100644 --- a/src/schema/index.ts +++ b/src/schema/index.ts @@ -4,4 +4,5 @@ export { person } from './person.schema'; export { assetFaces } from './assetFaces.schema'; export { users } from './users.schema'; export { albumsAssetsAssets } from './albumAssetsAssets.schema'; -export * from './relationships'; \ No newline at end of file +export { tags } from './tags.schema'; +export * from './relationships'; diff --git a/src/schema/tags.schema.ts b/src/schema/tags.schema.ts new file mode 100644 index 0000000..00140bf --- /dev/null +++ b/src/schema/tags.schema.ts @@ -0,0 +1,11 @@ +import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; + +export const tags = pgTable("tag", { + id: uuid("id").notNull().primaryKey(), + userId: uuid("userId").notNull(), + value: varchar("value").notNull(), + color: varchar("color"), + parentId: uuid("parentId"), + createdAt: timestamp("createdAt").notNull(), + updatedAt: timestamp("updatedAt").notNull(), +}); diff --git a/src/types/workflow.d.ts b/src/types/workflow.d.ts index fd1367b..678f9ea 100644 --- a/src/types/workflow.d.ts +++ b/src/types/workflow.d.ts @@ -49,7 +49,7 @@ export interface IWorkflowWithDetails extends IWorkflow { } export type ConditionType = - | "person" | "person_unnamed" + | "person" | "person_unnamed" | "tag" | "city" | "state" | "country" | "geo_radius" | "date_range" | "date_relative" | "day_of_week" | "camera_make" | "camera_model" | "lens" From b66c8218bcfd218c0a6ade1d9238fed50ae6d750 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 13:59:52 +0000 Subject: [PATCH 2/2] fix: parameterize tag contains_any IN-list to close SQL injection vector The id list was built via raw string interpolation into sql.raw(). Switch to sql.join with proper parameter binding, matching the pattern used by the other match branches in this function. --- src/lib/workflow/conditionBuilder.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/workflow/conditionBuilder.ts b/src/lib/workflow/conditionBuilder.ts index 3e01a00..587ab93 100644 --- a/src/lib/workflow/conditionBuilder.ts +++ b/src/lib/workflow/conditionBuilder.ts @@ -143,8 +143,8 @@ function buildSingleCondition(c: ICondition): SQL | undefined { } // contains_any (default) — asset carries at least one of these tags (or their children) - const idList = ids.map((id: string) => `'${id}'`).join(","); - return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${sql.raw(idList)}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${sql.raw(idList)}))))`; + const idParams = sql.join(ids.map((id: string) => sql`${id}`), sql`, `); + return sql`EXISTS (SELECT 1 FROM "tag_asset" ta WHERE ta."assetId" = ${assets.id} AND (ta."tagId" IN (${idParams}) OR ta."tagId" IN (SELECT tc."id_descendant" FROM "tag_closure" tc WHERE tc."id_ancestor" IN (${idParams}))))`; } case "person_unnamed":