Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(labels): ship issue labels (closes #1191) (#1233)

Ayman Alkurdie9d04ecfc1a0
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d68d1ea889..8822d4f917 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -51,6 +51,11 @@ import type {
CreateProjectRequest,
UpdateProjectRequest,
ListProjectsResponse,
+ Label,
+ CreateLabelRequest,
+ UpdateLabelRequest,
+ ListLabelsResponse,
+ IssueLabelsResponse,
PinnedItem,
CreatePinRequest,
PinnedItemType,
@@ -978,6 +983,50 @@ export class ApiClient {
await this.fetch(`/api/projects/${id}`, { method: "DELETE" });
}
+ // Labels
+ async listLabels(): Promise<ListLabelsResponse> {
+ return this.fetch(`/api/labels`);
+ }
+
+ async getLabel(id: string): Promise<Label> {
+ return this.fetch(`/api/labels/${id}`);
+ }
+
+ async createLabel(data: CreateLabelRequest): Promise<Label> {
+ return this.fetch(`/api/labels`, {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ }
+
+ async updateLabel(id: string, data: UpdateLabelRequest): Promise<Label> {
+ return this.fetch(`/api/labels/${id}`, {
+ method: "PUT",
+ body: JSON.stringify(data),
+ });
+ }
+
+ async deleteLabel(id: string): Promise<void> {
+ await this.fetch(`/api/labels/${id}`, { method: "DELETE" });
+ }
+
+ async listLabelsForIssue(issueId: string): Promise<IssueLabelsResponse> {
+ return this.fetch(`/api/issues/${issueId}/labels`);
+ }
+
+ async attachLabel(issueId: string, labelId: string): Promise<IssueLabelsResponse> {
+ return this.fetch(`/api/issues/${issueId}/labels`, {
+ method: "POST",
+ body: JSON.stringify({ label_id: labelId }),
+ });
+ }
+
+ async detachLabel(issueId: string, labelId: string): Promise<IssueLabelsResponse> {
+ return this.fetch(`/api/issues/${issueId}/labels/${labelId}`, {
+ method: "DELETE",
+ });
+ }
+
// Pins
async listPins(): Promise<PinnedItem[]> {
return this.fetch("/api/pins");
diff --git a/packages/core/labels/index.ts b/packages/core/labels/index.ts
new file mode 100644
index 0000000000..6a8890b663
--- /dev/null
+++ b/packages/core/labels/index.ts
@@ -0,0 +1,8 @@
+export { labelKeys, labelListOptions, issueLabelsOptions } from "./queries";
+export {
+ useCreateLabel,
+ useUpdateLabel,
+ useDeleteLabel,
+ useAttachLabel,
+ useDetachLabel,
+} from "./mutations";
diff --git a/packages/core/labels/mutations.ts b/packages/core/labels/mutations.ts
new file mode 100644
index 0000000000..8f6abc7935
--- /dev/null
+++ b/packages/core/labels/mutations.ts
@@ -0,0 +1,131 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { labelKeys } from "./queries";
+import { useWorkspaceId } from "../hooks";
+import type {
+ Label,
+ CreateLabelRequest,
+ UpdateLabelRequest,
+ ListLabelsResponse,
+ IssueLabelsResponse,
+} from "../types";
+
+export function useCreateLabel() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (data: CreateLabelRequest) => api.createLabel(data),
+ onSuccess: (label) => {
+ qc.setQueryData<ListLabelsResponse>(labelKeys.list(wsId), (old) =>
+ old && !old.labels.some((l) => l.id === label.id)
+ ? { ...old, labels: [...old.labels, label], total: old.total + 1 }
+ : old,
+ );
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.list(wsId) });
+ },
+ });
+}
+
+/**
+ * Optimistic rename/recolor. Matches the useUpdateProject pattern: apply the
+ * change locally, snapshot for rollback, invalidate on settle. Without this
+ * the UI freezes for the round-trip on every edit.
+ */
+export function useUpdateLabel() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & UpdateLabelRequest) =>
+ api.updateLabel(id, data),
+ onMutate: async ({ id, ...data }) => {
+ await qc.cancelQueries({ queryKey: labelKeys.list(wsId) });
+ const prevList = qc.getQueryData<ListLabelsResponse>(labelKeys.list(wsId));
+ qc.setQueryData<ListLabelsResponse>(labelKeys.list(wsId), (old) =>
+ old
+ ? {
+ ...old,
+ labels: old.labels.map((l) => (l.id === id ? { ...l, ...data } : l)),
+ }
+ : old,
+ );
+ return { prevList, id };
+ },
+ onError: (_err, _vars, ctx) => {
+ if (ctx?.prevList) qc.setQueryData(labelKeys.list(wsId), ctx.prevList);
+ },
+ onSettled: () => {
+ // Invalidate the entire labels scope so any byIssue cache holding a
+ // stale copy of this label is refetched. The list cache is the source
+ // of truth; byIssue views will re-render with the fresh data.
+ qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
+ },
+ });
+}
+
+export function useDeleteLabel() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (id: string) => api.deleteLabel(id),
+ onMutate: async (id) => {
+ await qc.cancelQueries({ queryKey: labelKeys.list(wsId) });
+ const prev = qc.getQueryData<ListLabelsResponse>(labelKeys.list(wsId));
+ qc.setQueryData<ListLabelsResponse>(labelKeys.list(wsId), (old) =>
+ old
+ ? { ...old, labels: old.labels.filter((l) => l.id !== id), total: old.total - 1 }
+ : old,
+ );
+ return { prev };
+ },
+ onError: (_err, _id, ctx) => {
+ if (ctx?.prev) qc.setQueryData(labelKeys.list(wsId), ctx.prev);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
+ },
+ });
+}
+
+export function useAttachLabel(issueId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (labelId: string) => api.attachLabel(issueId, labelId),
+ onSuccess: (data: IssueLabelsResponse) => {
+ // Backend may return an empty object when the post-mutation read fails
+ // (it logs a warning and skips the broadcast). We only apply the list
+ // when the backend gave us one — otherwise rely on onSettled's
+ // invalidation to refetch.
+ if (data && Array.isArray(data.labels)) {
+ qc.setQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId), data);
+ }
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
+ },
+ });
+}
+
+export function useDetachLabel(issueId: string) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (labelId: string) => api.detachLabel(issueId, labelId),
+ onMutate: async (labelId) => {
+ await qc.cancelQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
+ const prev = qc.getQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId));
+ qc.setQueryData<IssueLabelsResponse>(labelKeys.byIssue(wsId, issueId), (old) =>
+ old ? { ...old, labels: old.labels.filter((l: Label) => l.id !== labelId) } : old,
+ );
+ return { prev };
+ },
+ onError: (_err, _id, ctx) => {
+ if (ctx?.prev) qc.setQueryData(labelKeys.byIssue(wsId, issueId), ctx.prev);
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.byIssue(wsId, issueId) });
+ },
+ });
+}
diff --git a/packages/core/labels/queries.ts b/packages/core/labels/queries.ts
new file mode 100644
index 0000000000..f2a61b1378
--- /dev/null
+++ b/packages/core/labels/queries.ts
@@ -0,0 +1,28 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+export const labelKeys = {
+ all: (wsId: string) => ["labels", wsId] as const,
+ list: (wsId: string) => [...labelKeys.all(wsId), "list"] as const,
+ detail: (wsId: string, id: string) =>
+ [...labelKeys.all(wsId), "detail", id] as const,
+ byIssue: (wsId: string, issueId: string) =>
+ [...labelKeys.all(wsId), "issue", issueId] as const,
+};
+
+export function labelListOptions(wsId: string) {
+ return queryOptions({
+ queryKey: labelKeys.list(wsId),
+ queryFn: () => api.listLabels(),
+ select: (data) => data.labels,
+ });
+}
+
+export function issueLabelsOptions(wsId: string, issueId: string) {
+ return queryOptions({
+ queryKey: labelKeys.byIssue(wsId, issueId),
+ queryFn: () => api.listLabelsForIssue(issueId),
+ select: (data) => data.labels,
+ enabled: Boolean(issueId),
+ });
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 2e9b2cfe2c..2b962c7131 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -46,6 +46,9 @@
"./projects/queries": "./projects/queries.ts",
"./projects/mutations": "./projects/mutations.ts",
"./projects/config": "./projects/config.ts",
+ "./labels": "./labels/index.ts",
+ "./labels/queries": "./labels/queries.ts",
+ "./labels/mutations": "./labels/mutations.ts",
"./autopilots": "./autopilots/index.ts",
"./autopilots/queries": "./autopilots/queries.ts",
"./autopilots/mutations": "./autopilots/mutations.ts",
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index a09954a3b0..deb06bf0ad 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -52,6 +52,10 @@ export type WSEventType =
| "project:created"
| "project:updated"
| "project:deleted"
+ | "label:created"
+ | "label:updated"
+ | "label:deleted"
+ | "issue_labels:changed"
| "pin:created"
| "pin:deleted"
| "pin:reordered"
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index fad655fdee..d7fba25184 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -34,6 +34,7 @@ export type {
export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";
export type { InboxItem, InboxSeverity, InboxItemType } from "./inbox";
export type { Comment, CommentType, CommentAuthorType, Reaction } from "./comment";
+export type { Label, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse } from "./label";
export type { TimelineEntry, AssigneeFrequencyEntry } from "./activity";
export type { IssueSubscriber } from "./subscriber";
export type * from "./events";
diff --git a/packages/core/types/label.ts b/packages/core/types/label.ts
new file mode 100644
index 0000000000..c3bd5ed0e7
--- /dev/null
+++ b/packages/core/types/label.ts
@@ -0,0 +1,35 @@
+/**
+ * Issue labels — workspace-scoped, applied as many-to-many to issues.
+ *
+ * Labels are lightweight metadata (name + color) distinct from projects:
+ * projects group related work, labels are cross-cutting tags (bug, feature,
+ * performance, …). Colors are normalized to lowercase `#RRGGBB`.
+ */
+export interface Label {
+ id: string;
+ workspace_id: string;
+ name: string;
+ /** Normalized lowercase hex color, e.g. `#3b82f6`. */
+ color: string;
+ created_at: string;
+ updated_at: string;
+}
+
+export interface CreateLabelRequest {
+ name: string;
+ color: string;
+}
+
+export interface UpdateLabelRequest {
+ name?: string;
+ color?: string;
+}
+
+export interface ListLabelsResponse {
+ labels: Label[];
+ total: number;
+}
+
+export interface IssueLabelsResponse {
+ labels: Label[];
+}
diff --git a/packages/views/issues/components/index.ts b/packages/views/issues/components/index.ts
index 32ed2a466f..75d932b809 100644
--- a/packages/views/issues/components/index.ts
+++ b/packages/views/issues/components/index.ts
@@ -1,6 +1,6 @@
export { StatusIcon } from "./status-icon";
export { PriorityIcon } from "./priority-icon";
-export { StatusPicker, PriorityPicker, AssigneePicker, canAssignAgent, DueDatePicker } from "./pickers";
+export { StatusPicker, PriorityPicker, AssigneePicker, canAssignAgent, DueDatePicker, LabelPicker } from "./pickers";
export { IssueDetail } from "./issue-detail";
export { IssuesPage } from "./issues-page";
export { CommentCard } from "./comment-card";
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index eaa46eb301..775b3b719e 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -36,7 +36,7 @@ import { AvatarGroup, AvatarGroupCount } from "@multica/ui/components/ui/avatar"
import { ActorAvatar } from "../../common/actor-avatar";
import type { IssueStatus, IssuePriority, TimelineEntry } from "@multica/core/types";
import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";
-import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, DueDatePicker, AssigneePicker } from ".";
+import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, DueDatePicker, AssigneePicker, LabelPicker } from ".";
import { IssueActionsDropdown, useIssueActions } from "../actions";
import { ProjectPicker } from "../../projects/components/project-picker";
import { CommentCard } from "./comment-card";
@@ -408,6 +408,9 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
<PropRow label="Project">
<ProjectPicker projectId={issue.project_id} onUpdate={handleUpdateField} />
</PropRow>
+ <PropRow label="Labels">
+ <LabelPicker issueId={issue.id} align="start" />
+ </PropRow>
</div>}
</div>
diff --git a/packages/views/issues/components/labels-panel.tsx b/packages/views/issues/components/labels-panel.tsx
new file mode 100644
index 0000000000..ed05471d2d
--- /dev/null
+++ b/packages/views/issues/components/labels-panel.tsx
@@ -0,0 +1,290 @@
+"use client";
+
+import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Trash2, Plus, Pencil, Check, X } from "lucide-react";
+import { Input } from "@multica/ui/components/ui/input";
+import { Label as UILabel } from "@multica/ui/components/ui/label";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ AlertDialog,
+ AlertDialogContent,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogCancel,
+ AlertDialogAction,
+} from "@multica/ui/components/ui/alert-dialog";
+import { toast } from "sonner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { labelListOptions, useCreateLabel, useUpdateLabel, useDeleteLabel } from "@multica/core/labels";
+import type { Label } from "@multica/core/types";
+import { LabelChip } from "../../labels/label-chip";
+
+/** Default color for brand-new labels. Everything else goes through the native picker. */
+const DEFAULT_COLOR_DEFAULT = "#3b82f6";
+
+/**
+ * Workspace-wide labels management surface. Opened from the Manage labels…
+ * footer in the label picker.
+ */
+export function LabelsPanel() {
+ const wsId = useWorkspaceId();
+ const { data: labels = [], isLoading } = useQuery(labelListOptions(wsId));
+
+ const create = useCreateLabel();
+ const update = useUpdateLabel();
+ const del = useDeleteLabel();
+
+ const [newName, setNewName] = useState("");
+ const [newColor, setNewColor] = useState(DEFAULT_COLOR_DEFAULT);
+
+ const [editingId, setEditingId] = useState<string | null>(null);
+ const [editName, setEditName] = useState("");
+ const [editColor, setEditColor] = useState("");
+ const [editError, setEditError] = useState("");
+
+ const [pendingDeletion, setPendingDeletion] = useState<Label | null>(null);
+
+ const handleCreate = () => {
+ const name = newName.trim();
+ if (!name) return;
+ create.mutate(
+ { name, color: newColor },
+ {
+ onSuccess: () => {
+ setNewName("");
+ setNewColor(DEFAULT_COLOR_DEFAULT);
+ },
+ onError: (err: unknown) => {
+ toast.error(err instanceof Error ? err.message : "Failed to create label");
+ },
+ },
+ );
+ };
+
+ const startEdit = (label: Label) => {
+ setEditingId(label.id);
+ setEditName(label.name);
+ setEditColor(label.color);
+ setEditError("");
+ };
+
+ const cancelEdit = () => {
+ setEditingId(null);
+ setEditName("");
+ setEditColor("");
+ setEditError("");
+ };
+
+ const saveEdit = (id: string) => {
+ const name = editName.trim();
+ if (!name) {
+ // Surface the reason the save didn't happen — previously this was a
+ // silent no-op. Button is also disabled (below) but a visible message
+ // beats a greyed-out button for telling the user WHY.
+ setEditError("Label name is required.");
+ return;
+ }
+ setEditError("");
+ update.mutate(
+ { id, name, color: editColor },
+ {
+ onSuccess: cancelEdit,
+ onError: (err: unknown) => {
+ toast.error(err instanceof Error ? err.message : "Failed to update label");
+ },
+ },
+ );
+ };
+
+ return (
+ <div className="space-y-6">
+ <p className="text-sm text-muted-foreground">
+ Create and manage labels to categorize issues across your workspace.
+ </p>
+
+ {/* Create form — color swatch, name, Add button all in one row */}
+ <div className="flex items-center gap-2">
+ <ColorPalette value={newColor} onChange={setNewColor} compact />
+ <Input
+ id="label-new-name"
+ placeholder="New label name…"
+ value={newName}
+ onChange={(e) => setNewName(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") handleCreate();
+ }}
+ className="flex-1"
+ maxLength={32}
+ aria-label="New label name"
+ />
+ <Button onClick={handleCreate} disabled={!newName.trim() || create.isPending}>
+ <Plus className="h-4 w-4 mr-1" />
+ Add
+ </Button>
+ </div>
+
+ {/* List — scrolls when labels exceed viewport */}
+ <div className="space-y-2 max-h-[50vh] overflow-y-auto">
+ {isLoading && <p className="text-sm text-muted-foreground">Loading…</p>}
+ {!isLoading && labels.length === 0 && (
+ <p className="text-sm text-muted-foreground">No labels yet.</p>
+ )}
+ {labels.map((label) => {
+ const isEditing = editingId === label.id;
+ const editNameEmpty = isEditing && !editName.trim();
+ return (
+ <div
+ key={label.id}
+ className="rounded-md border bg-card px-3 py-2"
+ >
+ <div className="flex items-center gap-3">
+ {isEditing ? (
+ <>
+ <Input
+ value={editName}
+ onChange={(e) => {
+ setEditName(e.target.value);
+ if (e.target.value.trim()) setEditError("");
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") saveEdit(label.id);
+ if (e.key === "Escape") cancelEdit();
+ }}
+ className="flex-1 h-8"
+ maxLength={32}
+ autoFocus
+ aria-invalid={editNameEmpty}
+ aria-describedby={editError ? `label-edit-error-${label.id}` : undefined}
+ />
+ <ColorPalette
+ value={editColor}
+ onChange={setEditColor}
+ compact
+ />
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => saveEdit(label.id)}
+ disabled={editNameEmpty || update.isPending}
+ aria-label="Save"
+ >
+ <Check className="h-4 w-4" />
+ </Button>
+ <Button size="sm" variant="ghost" onClick={cancelEdit} aria-label="Cancel">
+ <X className="h-4 w-4" />
+ </Button>
+ </>
+ ) : (
+ <>
+ {/* min-w-0 on the label wrapper lets long names wrap without
+ pushing the hex/buttons off the right edge. */}
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
+ <LabelChip label={label} fullName />
+ <span className="text-xs text-muted-foreground">
+ {label.color}
+ </span>
+ </div>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => startEdit(label)}
+ aria-label={`Edit ${label.name}`}
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setPendingDeletion(label)}
+ aria-label={`Delete ${label.name}`}
+ >
+ <Trash2 className="h-4 w-4 text-destructive" />
+ </Button>
+ </>
+ )}
+ </div>
+ {isEditing && editError && (
+ <p
+ id={`label-edit-error-${label.id}`}
+ className="mt-1.5 text-xs text-destructive"
+ role="alert"
+ >
+ {editError}
+ </p>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ <AlertDialog open={!!pendingDeletion} onOpenChange={(o) => !o && setPendingDeletion(null)}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete label?</AlertDialogTitle>
+ <AlertDialogDescription>
+ The label <strong>{pendingDeletion?.name}</strong> will be removed from all
+ issues. This cannot be undone.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (!pendingDeletion) return;
+ del.mutate(pendingDeletion.id, {
+ onSuccess: () => setPendingDeletion(null),
+ onError: (err: unknown) => {
+ toast.error(err instanceof Error ? err.message : "Failed to delete label");
+ },
+ });
+ }}
+ >
+ Delete
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
+
+/**
+ * Color picker — a single swatch that opens the browser's native color
+ * picker. Full gamut, trusted UX, zero visual clutter. `focus-within` ring
+ * makes keyboard focus visible despite the transparent `<input type="color">`.
+ */
+function ColorPalette({
+ value,
+ onChange,
+ compact,
+}: {
+ value: string;
+ onChange: (c: string) => void;
+ compact?: boolean;
+}) {
+ const size = compact ? "h-7 w-7" : "h-9 w-9";
+ return (
+ <div className={compact ? "flex items-center" : "flex items-center gap-3"}>
+ {!compact && <UILabel className="text-xs text-muted-foreground">Color</UILabel>}
+ <label
+ className={`relative inline-flex ${size} cursor-pointer items-center justify-center rounded-full border border-border shadow-sm transition-transform hover:scale-105 focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-1 focus-within:ring-offset-background`}
+ style={{ backgroundColor: value }}
+ aria-label="Pick a color"
+ title={value}
+ >
+ <input
+ type="color"
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ className="absolute inset-0 h-full w-full cursor-pointer opacity-0"
+ />
+ </label>
+ {!compact && (
+ <span className="font-mono text-xs text-muted-foreground">{value}</span>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/pickers/index.ts b/packages/views/issues/components/pickers/index.ts
index 3b5876bc91..28622d75d8 100644
--- a/packages/views/issues/components/pickers/index.ts
+++ b/packages/views/issues/components/pickers/index.ts
@@ -3,3 +3,4 @@ export { StatusPicker } from "./status-picker";
export { PriorityPicker } from "./priority-picker";
export { AssigneePicker, canAssignAgent } from "./assignee-picker";
export { DueDatePicker } from "./due-date-picker";
+export { LabelPicker } from "./label-picker";
diff --git a/packages/views/issues/components/pickers/label-picker.tsx b/packages/views/issues/components/pickers/label-picker.tsx
new file mode 100644
index 0000000000..55fc0e2556
--- /dev/null
+++ b/packages/views/issues/components/pickers/label-picker.tsx
@@ -0,0 +1,228 @@
+"use client";
+
+import { useMemo, useRef, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Tag, Plus, Settings2 } from "lucide-react";
+import { toast } from "sonner";
+import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ labelListOptions,
+ issueLabelsOptions,
+ useAttachLabel,
+ useDetachLabel,
+ useCreateLabel,
+} from "@multica/core/labels";
+import { LabelChip } from "../../../labels/label-chip";
+import { LabelsPanel } from "../labels-panel";
+import {
+ PropertyPicker,
+ PickerItem,
+ PickerEmpty,
+} from "./property-picker";
+
+interface LabelPickerProps {
+ issueId: string;
+ /** Optional controlled open state (for tests / cmd+k integration). */
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ align?: "start" | "center" | "end";
+}
+
+/**
+ * Palette of colors used when creating a label inline from the picker.
+ * We cycle by hash(name) so the same name always gets the same color,
+ * and a color can still be changed afterwards from the Manage dialog.
+ */
+const INLINE_COLORS = [
+ "#ef4444", "#f97316", "#eab308", "#22c55e", "#14b8a6",
+ "#3b82f6", "#6366f1", "#a855f7", "#ec4899", "#64748b",
+] as const;
+
+function pickInlineColor(name: string): string {
+ let hash = 0;
+ for (let i = 0; i < name.length; i++) {
+ hash = (hash * 31 + name.charCodeAt(i)) >>> 0;
+ }
+ return INLINE_COLORS[hash % INLINE_COLORS.length] ?? INLINE_COLORS[0]!;
+}
+
+/**
+ * Multi-select label picker for an issue. Shows currently-attached labels
+ * as inline chips above the trigger and lets the user toggle any label in
+ * the workspace. Attach/detach are optimistic — the UI updates before the
+ * server confirms.
+ *
+ * When the search term has no matches, offers inline creation: typing a
+ * new name and pressing Enter (or clicking the "Create X" row) creates the
+ * label with a hash-derived color and attaches it in one motion.
+ *
+ * A "Manage labels" item at the bottom opens a dialog with the full
+ * workspace label management panel (rename, recolor, delete) — keeping
+ * users in context without forcing them to navigate away.
+ */
+export function LabelPicker({
+ issueId,
+ open: controlledOpen,
+ onOpenChange,
+ align = "start",
+}: LabelPickerProps) {
+ const [internalOpen, setInternalOpen] = useState(false);
+ const open = controlledOpen ?? internalOpen;
+ const setOpen = onOpenChange ?? setInternalOpen;
+ const [filter, setFilter] = useState("");
+ const [manageOpen, setManageOpen] = useState(false);
+
+ // Synchronous lock to prevent double-submit on rapid Enter / click. React
+ // state (create.isPending, filter) isn't visible until the next render, so
+ // two events within the same tick can both pass the canCreate guard and
+ // fire two create.mutate calls — the second hits 409 and shows a red toast
+ // for an error the user didn't cause. A ref closes the window cleanly.
+ const creatingRef = useRef(false);
+
+ const wsId = useWorkspaceId();
+ const { data: allLabels = [] } = useQuery(labelListOptions(wsId));
+ const { data: attachedLabels = [] } = useQuery(issueLabelsOptions(wsId, issueId));
+
+ const attach = useAttachLabel(issueId);
+ const detach = useDetachLabel(issueId);
+ const create = useCreateLabel();
+
+ const attachedIds = useMemo(
+ () => new Set(attachedLabels.map((l) => l.id)),
+ [attachedLabels],
+ );
+
+ const query = filter.trim();
+ const queryLower = query.toLowerCase();
+ const filtered = allLabels.filter((l) => l.name.toLowerCase().includes(queryLower));
+ const exactMatch = allLabels.some((l) => l.name.toLowerCase() === queryLower);
+ const canCreate = query.length > 0 && !exactMatch && !create.isPending;
+
+ const toggle = (labelId: string) => {
+ if (attachedIds.has(labelId)) {
+ detach.mutate(labelId);
+ } else {
+ attach.mutate(labelId);
+ }
+ };
+
+ const createAndAttach = () => {
+ if (!canCreate || creatingRef.current) return;
+ creatingRef.current = true;
+ const name = query;
+ create.mutate(
+ { name, color: pickInlineColor(name) },
+ {
+ onSuccess: (label) => {
+ attach.mutate(label.id);
+ setFilter("");
+ },
+ onError: (err: unknown) => {
+ toast.error(err instanceof Error ? err.message : "Failed to create label");
+ },
+ onSettled: () => {
+ creatingRef.current = false;
+ },
+ },
+ );
+ };
+
+ const openManage = () => {
+ setOpen(false);
+ setManageOpen(true);
+ };
+
+ const hasLabels = attachedLabels.length > 0;
+
+ return (
+ <div className="flex flex-col gap-1.5">
+ <PropertyPicker
+ open={open}
+ onOpenChange={(v: boolean) => {
+ setOpen(v);
+ if (!v) setFilter("");
+ }}
+ width="w-80"
+ align={align}
+ searchable
+ searchPlaceholder="Find or create a label…"
+ onSearchChange={setFilter}
+ triggerRender={
+ hasLabels ? (
+ <div className="flex flex-wrap items-center gap-1 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors" />
+ ) : undefined
+ }
+ trigger={
+ hasLabels ? (
+ <>
+ {attachedLabels.map((l) => (
+ <LabelChip
+ key={l.id}
+ label={l}
+ onRemove={() => detach.mutate(l.id)}
+ />
+ ))}
+ </>
+ ) : (
+ <>
+ <Tag className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="text-muted-foreground">Add label</span>
+ </>
+ )
+ }
+ footer={
+ // Rendered outside the arrow-key listbox so keyboard nav doesn't
+ // treat "Manage labels…" as another label option.
+ <button
+ type="button"
+ onClick={openManage}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-muted-foreground hover:bg-accent transition-colors"
+ >
+ <Settings2 className="h-3.5 w-3.5" />
+ <span>Manage labels…</span>
+ </button>
+ }
+ >
+ {filtered.map((label) => {
+ const selected = attachedIds.has(label.id);
+ return (
+ <PickerItem
+ key={label.id}
+ selected={selected}
+ onClick={() => toggle(label.id)}
+ >
+ <span
+ className="inline-block h-3 w-3 shrink-0 rounded-full"
+ style={{ backgroundColor: label.color }}
+ aria-hidden
+ />
+ <span className="truncate">{label.name}</span>
+ </PickerItem>
+ );
+ })}
+ {filtered.length === 0 && !canCreate && <PickerEmpty />}
+ {canCreate && (
+ <PickerItem selected={false} onClick={createAndAttach}>
+ <Plus className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">
+ Create <span className="font-medium">&ldquo;{query}&rdquo;</span>
+ </span>
+ <span
+ className="ml-auto inline-block h-3 w-3 shrink-0 rounded-full"
+ style={{ backgroundColor: pickInlineColor(query) }}
+ aria-hidden
+ />
+ </PickerItem>
+ )}
+ </PropertyPicker>
+
+ <Dialog open={manageOpen} onOpenChange={setManageOpen}>
+ <DialogContent className="max-w-2xl">
+ <DialogTitle className="text-lg font-semibold">Manage labels</DialogTitle>
+ <LabelsPanel />
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/packages/views/issues/components/pickers/property-picker.tsx b/packages/views/issues/components/pickers/property-picker.tsx
index 5372a45c1e..5481a8b0c0 100644
--- a/packages/views/issues/components/pickers/property-picker.tsx
+++ b/packages/views/issues/components/pickers/property-picker.tsx
@@ -26,6 +26,7 @@ export function PropertyPicker({
searchPlaceholder = "Filter...",
onSearchChange,
children,
+ footer,
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
@@ -37,6 +38,13 @@ export function PropertyPicker({
searchPlaceholder?: string;
onSearchChange?: (query: string) => void;
children: React.ReactNode;
+ /**
+ * Optional footer rendered below the listbox. Unlike items rendered as
+ * children, the footer is *not* included in arrow-key navigation — use it
+ * for actions like "Create new…" or "Manage…" that shouldn't be treated as
+ * selectable listbox options.
+ */
+ footer?: React.ReactNode;
}) {
const [query, setQuery] = useState("");
const [highlightedIndex, setHighlightedIndex] = useState(-1);
@@ -131,6 +139,7 @@ export function PropertyPicker({
</div>
)}
<div ref={listRef} className="p-1 max-h-60 overflow-y-auto">{children}</div>
+ {footer && <div className="border-t p-1">{footer}</div>}
</PopoverContent>
</Popover>
);
@@ -161,8 +170,11 @@ export function PickerItem({
onClick={onClick}
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm ${disabled ? "opacity-50 cursor-not-allowed" : hoverClassName ?? "hover:bg-accent"} transition-colors`}
>
- <span className="flex flex-1 items-center gap-2">{children}</span>
- {selected && <Check className="h-3.5 w-3.5 text-muted-foreground" />}
+ {/* min-w-0 lets long children (like truncated label names) shrink
+ inside the flex row instead of pushing the selected checkmark off
+ the right edge. shrink-0 on the Check keeps it visible. */}
+ <span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>
+ {selected && <Check className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />}
</button>
);
}
diff --git a/packages/views/labels/index.ts b/packages/views/labels/index.ts
new file mode 100644
index 0000000000..e181d794f8
--- /dev/null
+++ b/packages/views/labels/index.ts
@@ -0,0 +1 @@
+export { LabelChip } from "./label-chip";
diff --git a/packages/views/labels/label-chip.tsx b/packages/views/labels/label-chip.tsx
new file mode 100644
index 0000000000..7e4c3c2a21
--- /dev/null
+++ b/packages/views/labels/label-chip.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import type { Label } from "@multica/core/types";
+import { X } from "lucide-react";
+
+/**
+ * Map a label's `#rrggbb` color to a readable text color.
+ *
+ * Uses the ITU-R BT.601 perceived-luminance formula: colors above the
+ * threshold get dark text (#111827), colors below get light text (#f9fafb).
+ * This works for both pastel and saturated palettes without a hard lookup
+ * table.
+ *
+ * The malformed-hex fallback returns dark-on-default which is readable on
+ * the default `backgroundColor` rendering path — better than pure black
+ * which disappears on dark chips.
+ *
+ * SECURITY INVARIANT: `LabelChip` applies `style={{ backgroundColor: color }}`
+ * directly, trusting the backend's color format. The backend's
+ * `normalizeColor` regex pins the value to `^#?[0-9a-fA-F]{6}$`. If that regex
+ * ever loosens (named colors, `url(...)`, etc.), this becomes an injection
+ * vector.
+ */
+function contrastTextColor(hex: string): string {
+ const h = hex.replace("#", "");
+ if (h.length !== 6) return "#111827";
+ const r = parseInt(h.slice(0, 2), 16) / 255;
+ const g = parseInt(h.slice(2, 4), 16) / 255;
+ const b = parseInt(h.slice(4, 6), 16) / 255;
+ const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
+ return luminance > 0.55 ? "#111827" : "#f9fafb";
+}
+
+interface LabelChipProps {
+ label: Label;
+ onRemove?: () => void;
+ className?: string;
+ /**
+ * When true, show the full label name without truncation. Use this in
+ * management/edit surfaces where users need to see or verify the exact
+ * name. The default (false) truncates at 12rem to keep chips compact in
+ * the issue sidebar and future board/list card rows.
+ */
+ fullName?: boolean;
+}
+
+/**
+ * Renders a single label as a colored pill. If `onRemove` is provided, shows
+ * an × button that calls it. Used in the issue-detail sidebar, the picker,
+ * and the management dialog.
+ */
+export function LabelChip({ label, onRemove, className, fullName }: LabelChipProps) {
+ const textColor = contrastTextColor(label.color);
+ const nameClass = fullName ? "break-all" : "truncate max-w-[12rem]";
+ return (
+ <span
+ className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${className ?? ""}`}
+ style={{ backgroundColor: label.color, color: textColor }}
+ // aria-label exposes the full name to screen readers when the span
+ // visually truncates. title stays for sighted hover-tooltip.
+ aria-label={label.name}
+ title={label.name}
+ >
+ <span className={nameClass}>{label.name}</span>
+ {onRemove && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove();
+ }}
+ // bg-current/20 uses the computed text color so the hover state is
+ // visible on both light and dark chip backgrounds. hover:bg-black/10
+ // was invisible on darker chips (anything requiring light text).
+ className="flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded-full hover:bg-current/20 focus:outline-none focus:ring-1 focus:ring-current"
+ aria-label={`Remove label ${label.name}`}
+ >
+ <X className="h-2.5 w-2.5" strokeWidth={2.5} />
+ </button>
+ )}
+ </span>
+ );
+}
diff --git a/server/cmd/multica/cmd_issue_label.go b/server/cmd/multica/cmd_issue_label.go
new file mode 100644
index 0000000000..2700dcf537
--- /dev/null
+++ b/server/cmd/multica/cmd_issue_label.go
@@ -0,0 +1,148 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// multica issue label {list|add|remove} — manages the labels attached to a
+// specific issue. The label itself is managed via `multica label ...`.
+
+var issueLabelCmd = &cobra.Command{
+ Use: "label",
+ Short: "Manage labels on an issue",
+}
+
+var issueLabelListCmd = &cobra.Command{
+ Use: "list <issue-id>",
+ Short: "List labels on an issue",
+ Args: exactArgs(1),
+ RunE: runIssueLabelList,
+}
+
+var issueLabelAddCmd = &cobra.Command{
+ Use: "add <issue-id> <label-id>",
+ Short: "Attach a label to an issue",
+ Args: exactArgs(2),
+ RunE: runIssueLabelAdd,
+}
+
+var issueLabelRemoveCmd = &cobra.Command{
+ Use: "remove <issue-id> <label-id>",
+ Short: "Remove a label from an issue",
+ Args: exactArgs(2),
+ RunE: runIssueLabelRemove,
+}
+
+func init() {
+ issueLabelCmd.AddCommand(issueLabelListCmd)
+ issueLabelCmd.AddCommand(issueLabelAddCmd)
+ issueLabelCmd.AddCommand(issueLabelRemoveCmd)
+
+ issueLabelListCmd.Flags().String("output", "table", "Output format: table or json")
+ issueLabelAddCmd.Flags().String("output", "table", "Output format: table or json")
+ issueLabelRemoveCmd.Flags().String("output", "table", "Output format: table or json")
+
+ // Register under the top-level `issue` command.
+ issueCmd.AddCommand(issueLabelCmd)
+}
+
+func runIssueLabelList(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ var result map[string]any
+ if err := client.GetJSON(ctx, "/api/issues/"+args[0]+"/labels", &result); err != nil {
+ return fmt.Errorf("list issue labels: %w", err)
+ }
+ labelsRaw, _ := result["labels"].([]any)
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, labelsRaw)
+ }
+ printLabelTable(labelsRaw)
+ return nil
+}
+
+func runIssueLabelAdd(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ body := map[string]any{"label_id": args[1]}
+ var result map[string]any
+ if err := client.PostJSON(ctx, "/api/issues/"+args[0]+"/labels", body, &result); err != nil {
+ return fmt.Errorf("attach label: %w", err)
+ }
+ labelsRaw, _ := result["labels"].([]any)
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, labelsRaw)
+ }
+ printLabelTable(labelsRaw)
+ return nil
+}
+
+func runIssueLabelRemove(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ if err := client.DeleteJSON(ctx, "/api/issues/"+args[0]+"/labels/"+args[1]); err != nil {
+ return fmt.Errorf("detach label: %w", err)
+ }
+
+ // Follow up with the current label list so the user sees the result.
+ // If the refresh fails, still print a clear success message — the
+ // detach itself already succeeded.
+ var result map[string]any
+ output, _ := cmd.Flags().GetString("output")
+ if err := client.GetJSON(ctx, "/api/issues/"+args[0]+"/labels", &result); err != nil {
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, map[string]any{"detached": true})
+ }
+ fmt.Fprintln(os.Stdout, "Label detached.")
+ return nil
+ }
+ labelsRaw, _ := result["labels"].([]any)
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, labelsRaw)
+ }
+ printLabelTable(labelsRaw)
+ return nil
+}
+
+func printLabelTable(labels []any) {
+ headers := []string{"ID", "NAME", "COLOR"}
+ rows := make([][]string, 0, len(labels))
+ for _, raw := range labels {
+ l, ok := raw.(map[string]any)
+ if !ok {
+ continue
+ }
+ rows = append(rows, []string{
+ truncateID(strVal(l, "id")),
+ strVal(l, "name"),
+ strVal(l, "color"),
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+}
diff --git a/server/cmd/multica/cmd_label.go b/server/cmd/multica/cmd_label.go
new file mode 100644
index 0000000000..3fa46d31be
--- /dev/null
+++ b/server/cmd/multica/cmd_label.go
@@ -0,0 +1,252 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "net/url"
+ "os"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// ---------------------------------------------------------------------------
+// Label commands — workspace-scoped CRUD for issue labels.
+// ---------------------------------------------------------------------------
+
+var labelCmd = &cobra.Command{
+ Use: "label",
+ Short: "Work with issue labels",
+}
+
+var labelListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List labels in the workspace",
+ RunE: runLabelList,
+}
+
+var labelGetCmd = &cobra.Command{
+ Use: "get <id>",
+ Short: "Get label details",
+ Args: exactArgs(1),
+ RunE: runLabelGet,
+}
+
+var labelCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a new label",
+ RunE: runLabelCreate,
+}
+
+var labelUpdateCmd = &cobra.Command{
+ Use: "update <id>",
+ Short: "Update a label",
+ Args: exactArgs(1),
+ RunE: runLabelUpdate,
+}
+
+var labelDeleteCmd = &cobra.Command{
+ Use: "delete <id>",
+ Short: "Delete a label",
+ Args: exactArgs(1),
+ RunE: runLabelDelete,
+}
+
+func init() {
+ labelCmd.AddCommand(labelListCmd)
+ labelCmd.AddCommand(labelGetCmd)
+ labelCmd.AddCommand(labelCreateCmd)
+ labelCmd.AddCommand(labelUpdateCmd)
+ labelCmd.AddCommand(labelDeleteCmd)
+
+ labelListCmd.Flags().String("output", "table", "Output format: table or json")
+ labelGetCmd.Flags().String("output", "json", "Output format: table or json")
+
+ labelCreateCmd.Flags().String("name", "", "Label name (required)")
+ labelCreateCmd.Flags().String("color", "", "Hex color like #3b82f6 (required)")
+ labelCreateCmd.Flags().String("output", "json", "Output format: table or json")
+
+ labelUpdateCmd.Flags().String("name", "", "New name")
+ labelUpdateCmd.Flags().String("color", "", "New hex color")
+ labelUpdateCmd.Flags().String("output", "json", "Output format: table or json")
+
+ labelDeleteCmd.Flags().String("output", "json", "Output format: table or json")
+}
+
+func runLabelList(cmd *cobra.Command, _ []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ params := url.Values{}
+ if client.WorkspaceID != "" {
+ params.Set("workspace_id", client.WorkspaceID)
+ }
+ path := "/api/labels"
+ if len(params) > 0 {
+ path += "?" + params.Encode()
+ }
+
+ var result map[string]any
+ if err := client.GetJSON(ctx, path, &result); err != nil {
+ return fmt.Errorf("list labels: %w", err)
+ }
+ labelsRaw, _ := result["labels"].([]any)
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, labelsRaw)
+ }
+
+ headers := []string{"ID", "NAME", "COLOR", "CREATED"}
+ rows := make([][]string, 0, len(labelsRaw))
+ for _, raw := range labelsRaw {
+ l, ok := raw.(map[string]any)
+ if !ok {
+ continue
+ }
+ created := strVal(l, "created_at")
+ if len(created) >= 10 {
+ created = created[:10]
+ }
+ rows = append(rows, []string{
+ truncateID(strVal(l, "id")),
+ strVal(l, "name"),
+ strVal(l, "color"),
+ created,
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+}
+
+func runLabelGet(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ var label map[string]any
+ if err := client.GetJSON(ctx, "/api/labels/"+args[0], &label); err != nil {
+ return fmt.Errorf("get label: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "table" {
+ headers := []string{"ID", "NAME", "COLOR", "CREATED"}
+ created := strVal(label, "created_at")
+ if len(created) >= 10 {
+ created = created[:10]
+ }
+ rows := [][]string{{
+ truncateID(strVal(label, "id")),
+ strVal(label, "name"),
+ strVal(label, "color"),
+ created,
+ }}
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+ }
+ return cli.PrintJSON(os.Stdout, label)
+}
+
+func runLabelCreate(cmd *cobra.Command, _ []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ color, _ := cmd.Flags().GetString("color")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if color == "" {
+ return fmt.Errorf("--color is required (e.g. #3b82f6)")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ body := map[string]any{"name": name, "color": color}
+ var result map[string]any
+ if err := client.PostJSON(ctx, "/api/labels", body, &result); err != nil {
+ return fmt.Errorf("create label: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "table" {
+ headers := []string{"ID", "NAME", "COLOR"}
+ rows := [][]string{{
+ truncateID(strVal(result, "id")),
+ strVal(result, "name"),
+ strVal(result, "color"),
+ }}
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+ }
+ return cli.PrintJSON(os.Stdout, result)
+}
+
+func runLabelUpdate(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ body := map[string]any{}
+ if v, _ := cmd.Flags().GetString("name"); v != "" {
+ body["name"] = v
+ }
+ if v, _ := cmd.Flags().GetString("color"); v != "" {
+ body["color"] = v
+ }
+ if len(body) == 0 {
+ return fmt.Errorf("nothing to update — provide --name and/or --color")
+ }
+
+ var result map[string]any
+ if err := client.PutJSON(ctx, "/api/labels/"+args[0], body, &result); err != nil {
+ return fmt.Errorf("update label: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "table" {
+ headers := []string{"ID", "NAME", "COLOR"}
+ rows := [][]string{{
+ truncateID(strVal(result, "id")),
+ strVal(result, "name"),
+ strVal(result, "color"),
+ }}
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+ }
+ return cli.PrintJSON(os.Stdout, result)
+}
+
+func runLabelDelete(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ if err := client.DeleteJSON(ctx, "/api/labels/"+args[0]); err != nil {
+ return fmt.Errorf("delete label: %w", err)
+ }
+ // JSON consumers get machine-readable output; humans get natural language.
+ if output, _ := cmd.Flags().GetString("output"); output == "json" {
+ return cli.PrintJSON(os.Stdout, map[string]any{"id": args[0], "deleted": true})
+ }
+ fmt.Fprintf(os.Stdout, "Label %s deleted.\n", args[0])
+ return nil
+}
diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.go
index afe9d455af..2a89aee320 100644
--- a/server/cmd/multica/main.go
+++ b/server/cmd/multica/main.go
@@ -39,6 +39,7 @@ func init() {
// Core commands
issueCmd.GroupID = groupCore
projectCmd.GroupID = groupCore
+ labelCmd.GroupID = groupCore
agentCmd.GroupID = groupCore
autopilotCmd.GroupID = groupCore
workspaceCmd.GroupID = groupCore
@@ -60,6 +61,7 @@ func init() {
rootCmd.AddCommand(issueCmd)
rootCmd.AddCommand(projectCmd)
+ rootCmd.AddCommand(labelCmd)
rootCmd.AddCommand(agentCmd)
rootCmd.AddCommand(autopilotCmd)
rootCmd.AddCommand(workspaceCmd)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index b45bfc4f51..d91cc67d8b 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -282,12 +282,26 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
r.Delete("/reactions", h.RemoveIssueReaction)
r.Get("/attachments", h.ListAttachments)
r.Get("/children", h.ListChildIssues)
+ r.Get("/labels", h.ListLabelsForIssue)
+ r.Post("/labels", h.AttachLabel)
+ r.Delete("/labels/{labelId}", h.DetachLabel)
})
})
// Task messages (user-facing, not daemon auth)
r.Get("/api/tasks/{taskId}/messages", h.ListTaskMessagesByUser)
+ // Labels
+ r.Route("/api/labels", func(r chi.Router) {
+ r.Get("/", h.ListLabels)
+ r.Post("/", h.CreateLabel)
+ r.Route("/{id}", func(r chi.Router) {
+ r.Get("/", h.GetLabel)
+ r.Put("/", h.UpdateLabel)
+ r.Delete("/", h.DeleteLabel)
+ })
+ })
+
// Projects
r.Route("/api/projects", func(r chi.Router) {
r.Get("/search", h.SearchProjects)
diff --git a/server/internal/handler/label.go b/server/internal/handler/label.go
new file mode 100644
index 0000000000..f7945a93a9
--- /dev/null
+++ b/server/internal/handler/label.go
@@ -0,0 +1,421 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strings"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+type LabelResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ Name string `json:"name"`
+ Color string `json:"color"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func labelToResponse(l db.IssueLabel) LabelResponse {
+ return LabelResponse{
+ ID: uuidToString(l.ID),
+ WorkspaceID: uuidToString(l.WorkspaceID),
+ Name: l.Name,
+ Color: l.Color,
+ CreatedAt: timestampToString(l.CreatedAt),
+ UpdatedAt: timestampToString(l.UpdatedAt),
+ }
+}
+
+func labelsToResponse(list []db.IssueLabel) []LabelResponse {
+ out := make([]LabelResponse, len(list))
+ for i, l := range list {
+ out[i] = labelToResponse(l)
+ }
+ return out
+}
+
+type CreateLabelRequest struct {
+ Name string `json:"name"`
+ Color string `json:"color"`
+}
+
+type UpdateLabelRequest struct {
+ Name *string `json:"name"`
+ Color *string `json:"color"`
+}
+
+// 6-digit hex, with or without leading '#'.
+var hexColorRE = regexp.MustCompile(`^#?[0-9a-fA-F]{6}$`)
+
+// normalizeColor returns a canonical "#rrggbb" form or an error if invalid.
+//
+// LOAD-BEARING INVARIANT: LabelChip renders `style={{ backgroundColor: color }}`
+// directly in the frontend. If this regex is ever relaxed to accept arbitrary
+// CSS (named colors, `url(...)`, etc.), that inline style becomes an injection
+// surface. Keep the regex strict.
+func normalizeColor(c string) (string, error) {
+ c = strings.TrimSpace(c)
+ if !hexColorRE.MatchString(c) {
+ return "", errors.New("color must be a 6-digit hex value like #3b82f6")
+ }
+ if !strings.HasPrefix(c, "#") {
+ c = "#" + c
+ }
+ return strings.ToLower(c), nil
+}
+
+const maxLabelNameLen = 32
+
+// validateLabelName trims and validates a label name. Returns the trimmed
+// name or an error suitable for a 400 response.
+func validateLabelName(raw string) (string, error) {
+ name := strings.TrimSpace(raw)
+ if name == "" {
+ return "", errors.New("name is required")
+ }
+ if len(name) > maxLabelNameLen {
+ return "", errors.New("name must be 32 characters or fewer")
+ }
+ // TODO(labels): consider restricting to a charset that excludes newlines,
+ // tabs, and control characters. Emoji are left allowed — users can pick
+ // `🐛 bug` if they want. Tracked as a follow-up so we don't gate this PR.
+ return name, nil
+}
+
+// ---------------------------------------------------------------------------
+// Handlers — label CRUD
+// ---------------------------------------------------------------------------
+
+func (h *Handler) ListLabels(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ labels, err := h.Queries.ListLabels(r.Context(), parseUUID(workspaceID))
+ if err != nil {
+ slog.Warn("ListLabels failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list labels")
+ return
+ }
+ resp := labelsToResponse(labels)
+ writeJSON(w, http.StatusOK, map[string]any{"labels": resp, "total": len(resp)})
+}
+
+func (h *Handler) GetLabel(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
+ ID: parseUUID(id), WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "label not found")
+ return
+ }
+ slog.Warn("GetLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to get label")
+ return
+ }
+ writeJSON(w, http.StatusOK, labelToResponse(label))
+}
+
+func (h *Handler) CreateLabel(w http.ResponseWriter, r *http.Request) {
+ var req CreateLabelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ name, err := validateLabelName(req.Name)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ color, err := normalizeColor(req.Color)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ label, err := h.Queries.CreateLabel(r.Context(), db.CreateLabelParams{
+ WorkspaceID: parseUUID(workspaceID),
+ Name: name,
+ Color: color,
+ })
+ if err != nil {
+ if isUniqueViolation(err) {
+ writeError(w, http.StatusConflict, "a label with that name already exists")
+ return
+ }
+ slog.Warn("CreateLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create label")
+ return
+ }
+ resp := labelToResponse(label)
+ h.publish(protocol.EventLabelCreated, workspaceID, "member", userID, map[string]any{"label": resp})
+ writeJSON(w, http.StatusCreated, resp)
+}
+
+func (h *Handler) UpdateLabel(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+
+ var req UpdateLabelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ params := db.UpdateLabelParams{
+ ID: parseUUID(id),
+ WorkspaceID: parseUUID(workspaceID),
+ }
+ if req.Name != nil {
+ name, err := validateLabelName(*req.Name)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ params.Name = pgtype.Text{String: name, Valid: true}
+ }
+ if req.Color != nil {
+ color, err := normalizeColor(*req.Color)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ params.Color = pgtype.Text{String: color, Valid: true}
+ }
+
+ // Branch on pgx.ErrNoRows directly from the UPDATE — the WHERE clause
+ // already enforces (id, workspace_id), so a missing row means either the
+ // label doesn't exist or it's not in this workspace. Dropping the prior
+ // GetLabel precheck removes a TOCTOU window and saves a round-trip.
+ label, err := h.Queries.UpdateLabel(r.Context(), params)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "label not found")
+ return
+ }
+ if isUniqueViolation(err) {
+ writeError(w, http.StatusConflict, "a label with that name already exists")
+ return
+ }
+ slog.Warn("UpdateLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update label")
+ return
+ }
+ resp := labelToResponse(label)
+ h.publish(protocol.EventLabelUpdated, workspaceID, "member", userID, map[string]any{"label": resp})
+ writeJSON(w, http.StatusOK, resp)
+}
+
+func (h *Handler) DeleteLabel(w http.ResponseWriter, r *http.Request) {
+ id := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+ // DeleteLabel is :one RETURNING id — ErrNoRows means the label wasn't in
+ // this workspace (404). Any other error is a real 500.
+ if _, err := h.Queries.DeleteLabel(r.Context(), db.DeleteLabelParams{
+ ID: parseUUID(id), WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "label not found")
+ return
+ }
+ slog.Warn("DeleteLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to delete label")
+ return
+ }
+ h.publish(protocol.EventLabelDeleted, workspaceID, "member", userID, map[string]any{"label_id": id})
+ w.WriteHeader(http.StatusNoContent)
+}
+
+// ---------------------------------------------------------------------------
+// Handlers — issue↔label attach/detach
+// ---------------------------------------------------------------------------
+
+type AttachLabelRequest struct {
+ LabelID string `json:"label_id"`
+}
+
+// listLabelsForIssueSafe reads the attached-label list and handles the error
+// by logging + returning nil. Callers use this after a successful attach/detach
+// mutation: if the read fails, the mutation is already committed, so returning
+// nil → clients refetch via query invalidation, and we skip broadcasting an
+// empty list that would incorrectly overwrite every subscriber's optimistic
+// state.
+func (h *Handler) listLabelsForIssueSafe(r *http.Request, issueID, workspaceID string) ([]db.IssueLabel, bool) {
+ labels, err := h.Queries.ListLabelsByIssue(r.Context(), db.ListLabelsByIssueParams{
+ IssueID: parseUUID(issueID),
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ slog.Warn("ListLabelsByIssue failed after mutation", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
+ return nil, false
+ }
+ return labels, true
+}
+
+// ListLabelsForIssue returns the labels currently attached to an issue.
+func (h *Handler) ListLabelsForIssue(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+ // Authorize via the issue — if it's not in this workspace, the caller
+ // shouldn't see its labels.
+ issue, err := h.Queries.GetIssue(r.Context(), parseUUID(issueID))
+ if err != nil || uuidToString(issue.WorkspaceID) != workspaceID {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return
+ }
+ labels, err := h.Queries.ListLabelsByIssue(r.Context(), db.ListLabelsByIssueParams{
+ IssueID: parseUUID(issueID),
+ WorkspaceID: parseUUID(workspaceID),
+ })
+ if err != nil {
+ slog.Warn("ListLabelsForIssue failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list labels")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"labels": labelsToResponse(labels)})
+}
+
+// AttachLabel attaches a label to an issue.
+func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ var req AttachLabelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ if req.LabelID == "" {
+ writeError(w, http.StatusBadRequest, "label_id is required")
+ return
+ }
+
+ // Both the issue and label must belong to this workspace.
+ issue, err := h.Queries.GetIssue(r.Context(), parseUUID(issueID))
+ if err != nil || uuidToString(issue.WorkspaceID) != workspaceID {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return
+ }
+ if _, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
+ ID: parseUUID(req.LabelID), WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "label not found")
+ return
+ }
+ slog.Warn("GetLabel in AttachLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to attach label")
+ return
+ }
+
+ if err := h.Queries.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{
+ IssueID: parseUUID(issueID),
+ LabelID: parseUUID(req.LabelID),
+ WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ slog.Warn("AttachLabelToIssue failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to attach label")
+ return
+ }
+
+ // Read the updated label list; on read failure, the attach is already
+ // committed — return success without a labels body (clients refetch via
+ // query invalidation) and skip the broadcast so we don't overwrite every
+ // subscriber's optimistic state with an incorrect empty list.
+ labels, ok2 := h.listLabelsForIssueSafe(r, issueID, workspaceID)
+ if !ok2 {
+ writeJSON(w, http.StatusOK, map[string]any{})
+ return
+ }
+ resp := labelsToResponse(labels)
+ h.publish(protocol.EventIssueLabelsChanged, workspaceID, "member", userID, map[string]any{
+ "issue_id": issueID,
+ "labels": resp,
+ })
+ writeJSON(w, http.StatusOK, map[string]any{"labels": resp})
+}
+
+// DetachLabel removes a label from an issue.
+func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ labelID := chi.URLParam(r, "labelId")
+ workspaceID := h.resolveWorkspaceID(r)
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ // Verify both issue and label belong to this workspace before detaching
+ // (mirror of AttachLabel). Without this, a crafted request with a foreign
+ // labelID would no-op and return 200 — "silent success" is worse than an
+ // explicit 404.
+ issue, err := h.Queries.GetIssue(r.Context(), parseUUID(issueID))
+ if err != nil || uuidToString(issue.WorkspaceID) != workspaceID {
+ writeError(w, http.StatusNotFound, "issue not found")
+ return
+ }
+ if _, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
+ ID: parseUUID(labelID), WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "label not found")
+ return
+ }
+ slog.Warn("GetLabel in DetachLabel failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to detach label")
+ return
+ }
+
+ if err := h.Queries.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{
+ IssueID: parseUUID(issueID),
+ LabelID: parseUUID(labelID),
+ WorkspaceID: parseUUID(workspaceID),
+ }); err != nil {
+ slog.Warn("DetachLabelFromIssue failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to detach label")
+ return
+ }
+
+ labels, ok2 := h.listLabelsForIssueSafe(r, issueID, workspaceID)
+ if !ok2 {
+ writeJSON(w, http.StatusOK, map[string]any{})
+ return
+ }
+ resp := labelsToResponse(labels)
+ h.publish(protocol.EventIssueLabelsChanged, workspaceID, "member", userID, map[string]any{
+ "issue_id": issueID,
+ "labels": resp,
+ })
+ writeJSON(w, http.StatusOK, map[string]any{"labels": resp})
+}
diff --git a/server/internal/handler/label_test.go b/server/internal/handler/label_test.go
new file mode 100644
index 0000000000..c5942ec2b2
--- /dev/null
+++ b/server/internal/handler/label_test.go
@@ -0,0 +1,438 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+)
+
+// TestLabelCRUD exercises label create/list/get/update/delete.
+func TestLabelCRUD(t *testing.T) {
+ // Create
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "name": "bug",
+ "color": "#ef4444",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created LabelResponse
+ json.NewDecoder(w.Body).Decode(&created)
+ if created.Name != "bug" || created.Color != "#ef4444" {
+ t.Fatalf("CreateLabel: unexpected payload: %+v", created)
+ }
+ labelID := created.ID
+
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.DeleteLabel(w, req)
+ })
+
+ // Duplicate name → 409
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/labels", map[string]any{
+ "name": "BUG", // case-insensitive unique
+ "color": "#000000",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("Duplicate CreateLabel: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Invalid color → 400
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/labels", map[string]any{
+ "name": "enhancement",
+ "color": "nope",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("Invalid color: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // List
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/labels", nil)
+ testHandler.ListLabels(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListLabels: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var listResp struct {
+ Labels []LabelResponse `json:"labels"`
+ Total int `json:"total"`
+ }
+ json.NewDecoder(w.Body).Decode(&listResp)
+ if listResp.Total < 1 {
+ t.Fatalf("ListLabels: expected >= 1 label, got %d", listResp.Total)
+ }
+
+ // Get
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.GetLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetLabel: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Update
+ w = httptest.NewRecorder()
+ req = newRequest("PUT", "/api/labels/"+labelID, map[string]any{
+ "name": "Bug (P0)",
+ "color": "#b91c1c",
+ })
+ req = withURLParam(req, "id", labelID)
+ testHandler.UpdateLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateLabel: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var updated LabelResponse
+ json.NewDecoder(w.Body).Decode(&updated)
+ if updated.Name != "Bug (P0)" || updated.Color != "#b91c1c" {
+ t.Fatalf("UpdateLabel: unexpected payload: %+v", updated)
+ }
+}
+
+// TestIssueLabelAttachDetach exercises attach/detach + the issue-scoped endpoints.
+func TestIssueLabelAttachDetach(t *testing.T) {
+ // Create issue
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Issue for label attach test",
+ "status": "todo",
+ "priority": "medium",
+ })
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var issue IssueResponse
+ json.NewDecoder(w.Body).Decode(&issue)
+ issueID := issue.ID
+
+ // Create label
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/labels", map[string]any{
+ "name": "feature",
+ "color": "#3b82f6",
+ })
+ testHandler.CreateLabel(w, req)
+ var label LabelResponse
+ json.NewDecoder(w.Body).Decode(&label)
+ labelID := label.ID
+
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.DeleteLabel(w, req)
+ })
+
+ // Attach
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/issues/"+issueID+"/labels", map[string]any{
+ "label_id": labelID,
+ })
+ req = withURLParam(req, "id", issueID)
+ testHandler.AttachLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("AttachLabel: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Attach again (idempotent — ON CONFLICT DO NOTHING)
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/issues/"+issueID+"/labels", map[string]any{
+ "label_id": labelID,
+ })
+ req = withURLParam(req, "id", issueID)
+ testHandler.AttachLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("AttachLabel (second): expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // List labels for issue
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/issues/"+issueID+"/labels", nil)
+ req = withURLParam(req, "id", issueID)
+ testHandler.ListLabelsForIssue(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListLabelsForIssue: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var issueLabels struct {
+ Labels []LabelResponse `json:"labels"`
+ }
+ json.NewDecoder(w.Body).Decode(&issueLabels)
+ if len(issueLabels.Labels) != 1 {
+ t.Fatalf("ListLabelsForIssue: expected 1 label, got %d", len(issueLabels.Labels))
+ }
+ if issueLabels.Labels[0].ID != labelID {
+ t.Fatalf("ListLabelsForIssue: wrong label returned: %+v", issueLabels.Labels[0])
+ }
+
+ // Detach
+ w = httptest.NewRecorder()
+ req = newRequest("DELETE", "/api/issues/"+issueID+"/labels/"+labelID, nil)
+ req = withURLParams(req, "id", issueID, "labelId", labelID)
+ testHandler.DetachLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("DetachLabel: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Confirm detached
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/issues/"+issueID+"/labels", nil)
+ req = withURLParam(req, "id", issueID)
+ testHandler.ListLabelsForIssue(w, req)
+ json.NewDecoder(w.Body).Decode(&issueLabels)
+ if len(issueLabels.Labels) != 0 {
+ t.Fatalf("after Detach: expected 0 labels, got %d", len(issueLabels.Labels))
+ }
+}
+
+// TestLabelNotFoundAcrossWorkspaces ensures GET with a foreign workspace
+// header returns 404 — the query's `WHERE workspace_id = $2` does the work.
+func TestLabelNotFoundAcrossWorkspaces(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "name": "cross-ws-test",
+ "color": "#a855f7",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var label LabelResponse
+ json.NewDecoder(w.Body).Decode(&label)
+ labelID := label.ID
+
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.DeleteLabel(w, req)
+ })
+
+ // GET with a different workspace ID → 404
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/labels/"+labelID, nil)
+ req.Header.Set("X-Workspace-ID", "00000000-0000-0000-0000-000000000000")
+ req = withURLParam(req, "id", labelID)
+ testHandler.GetLabel(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("GetLabel cross-workspace: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// TestUpdateLabelCrossWorkspace — PUT with a foreign workspace header must not
+// allow updating a label in another workspace (404 via pgx.ErrNoRows from the
+// UPDATE ... WHERE id = $1 AND workspace_id = $2 clause).
+func TestUpdateLabelCrossWorkspace(t *testing.T) {
+ // Create in real workspace
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "name": "cross-ws-update-test",
+ "color": "#10b981",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel: expected 201, got %d", w.Code)
+ }
+ var label LabelResponse
+ json.NewDecoder(w.Body).Decode(&label)
+ labelID := label.ID
+
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.DeleteLabel(w, req)
+ })
+
+ // PUT with a foreign workspace ID → 404
+ w = httptest.NewRecorder()
+ req = newRequest("PUT", "/api/labels/"+labelID, map[string]any{"name": "hacked"})
+ req.Header.Set("X-Workspace-ID", "00000000-0000-0000-0000-000000000000")
+ req = withURLParam(req, "id", labelID)
+ testHandler.UpdateLabel(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("UpdateLabel cross-workspace: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Sanity: the label wasn't renamed.
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/labels/"+labelID, nil)
+ req = withURLParam(req, "id", labelID)
+ testHandler.GetLabel(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetLabel after failed cross-workspace PUT: expected 200, got %d", w.Code)
+ }
+ var after LabelResponse
+ json.NewDecoder(w.Body).Decode(&after)
+ if after.Name != "cross-ws-update-test" {
+ t.Fatalf("label name changed despite cross-workspace PUT: got %q", after.Name)
+ }
+}
+
+// TestAttachLabelCrossWorkspaceLabel — an attach request whose label_id
+// belongs to a different workspace must return 404, not silently no-op.
+// Directly exercises the GetLabel workspace precheck and the SQL-layer
+// defense-in-depth guard.
+func TestAttachLabelCrossWorkspaceLabel(t *testing.T) {
+ // Issue in the test workspace
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "cross-ws-attach-issue",
+ "status": "todo",
+ "priority": "medium",
+ })
+ testHandler.CreateIssue(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateIssue: expected 201, got %d", w.Code)
+ }
+ var issue IssueResponse
+ json.NewDecoder(w.Body).Decode(&issue)
+
+ // Label in a second workspace — insert directly via the pool to avoid
+ // the public API (which would require creating a full second workspace
+ // fixture). The defense-in-depth is exactly that the handler refuses
+ // even labels that exist *somewhere* but not in the current workspace.
+ otherWorkspaceID := createOtherTestWorkspace(t)
+ var otherLabelID string
+ err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue_label (workspace_id, name, color)
+ VALUES ($1, 'foreign-label', '#000000')
+ RETURNING id
+ `, otherWorkspaceID).Scan(&otherLabelID)
+ if err != nil {
+ t.Fatalf("insert foreign label: %v", err)
+ }
+
+ // Try to attach the foreign label to the test-workspace issue.
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/issues/"+issue.ID+"/labels", map[string]any{
+ "label_id": otherLabelID,
+ })
+ req = withURLParam(req, "id", issue.ID)
+ testHandler.AttachLabel(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("AttachLabel cross-workspace label: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Confirm nothing was attached.
+ w = httptest.NewRecorder()
+ req = newRequest("GET", "/api/issues/"+issue.ID+"/labels", nil)
+ req = withURLParam(req, "id", issue.ID)
+ testHandler.ListLabelsForIssue(w, req)
+ var list struct {
+ Labels []LabelResponse `json:"labels"`
+ }
+ json.NewDecoder(w.Body).Decode(&list)
+ if len(list.Labels) != 0 {
+ t.Fatalf("expected 0 labels on issue, got %d", len(list.Labels))
+ }
+}
+
+// TestLabelNameTooLong — names longer than 64 chars must return 400.
+func TestLabelNameTooLong(t *testing.T) {
+ longName := strings.Repeat("a", 33)
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "name": longName,
+ "color": "#123456",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("CreateLabel too-long name: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Exactly 32 chars is fine.
+ okName := strings.Repeat("b", 32)
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/labels", map[string]any{
+ "name": okName,
+ "color": "#123456",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel 64-char name: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created LabelResponse
+ json.NewDecoder(w.Body).Decode(&created)
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+created.ID, nil)
+ req = withURLParam(req, "id", created.ID)
+ testHandler.DeleteLabel(w, req)
+ })
+}
+
+// TestColorCaseNormalization — input `#ABCDEF` must be stored as `#abcdef`
+// so the case-insensitive uniqueness and downstream CSS rendering are
+// consistent. Also accepts a bare `ABCDEF` (no leading #).
+func TestColorCaseNormalization(t *testing.T) {
+ cases := []struct {
+ nameSuffix string
+ input string
+ want string
+ }{
+ {"upper", "#ABCDEF", "#abcdef"},
+ {"mixed", "#AbCdEf", "#abcdef"},
+ {"bare", "ABCDEF", "#abcdef"},
+ {"lower", "#123abc", "#123abc"},
+ }
+ for _, tc := range cases {
+ w := httptest.NewRecorder()
+ name := "color-norm-" + tc.nameSuffix // unique & case-independent
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "name": name,
+ "color": tc.input,
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel %q: expected 201, got %d: %s", tc.input, w.Code, w.Body.String())
+ }
+ var got LabelResponse
+ json.NewDecoder(w.Body).Decode(&got)
+ if got.Color != tc.want {
+ t.Errorf("color normalization %q: got %q, want %q", tc.input, got.Color, tc.want)
+ }
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+got.ID, nil)
+ req = withURLParam(req, "id", got.ID)
+ testHandler.DeleteLabel(w, req)
+ })
+ }
+}
+
+// createOtherTestWorkspace inserts a second workspace + owner membership for
+// cross-workspace tests. Returns the new workspace id; cleanup registered.
+func createOtherTestWorkspace(t *testing.T) string {
+ t.Helper()
+ ctx := context.Background()
+ var wsID string
+ err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description, issue_prefix)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id
+ `, "Other Handler Tests", handlerTestWorkspaceSlug+"-other", "temp second workspace", "OTH").Scan(&wsID)
+ if err != nil {
+ t.Fatalf("create other workspace: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')
+ `, wsID, testUserID); err != nil {
+ t.Fatalf("add member to other workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+ return wsID
+}
diff --git a/server/migrations/059_label_timestamps.down.sql b/server/migrations/059_label_timestamps.down.sql
new file mode 100644
index 0000000000..2c98ebe5cc
--- /dev/null
+++ b/server/migrations/059_label_timestamps.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS issue_label_workspace_name_lower_idx;
+ALTER TABLE issue_label
+ DROP COLUMN IF EXISTS updated_at,
+ DROP COLUMN IF EXISTS created_at;
diff --git a/server/migrations/059_label_timestamps.up.sql b/server/migrations/059_label_timestamps.up.sql
new file mode 100644
index 0000000000..5631f4cf76
--- /dev/null
+++ b/server/migrations/059_label_timestamps.up.sql
@@ -0,0 +1,29 @@
+-- Add timestamp columns to issue_label so labels track their own lifecycle.
+-- The table was scaffolded in 001_init.up.sql but never wired up to any code
+-- path; timestamps are added here as a precondition for the new CRUD handlers,
+-- CLI, and UI (see #1191).
+
+ALTER TABLE issue_label
+ ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
+
+-- Dedupe case-insensitive collisions before the unique index is created.
+-- Self-hosted deployments may have `Bug` + `bug` pairs from manual poking at
+-- the table, which would otherwise abort this migration when the unique index
+-- is added below. Keep the oldest row intact (smallest id, by lexicographic
+-- UUID order — effectively earliest-inserted since ids are gen_random_uuid()),
+-- rename every later duplicate by appending a short UUID suffix. Visible only
+-- on the rare installs that had duplicates; a no-op otherwise.
+UPDATE issue_label AS il
+SET name = il.name || ' (' || substring(il.id::text, 1, 8) || ')'
+WHERE EXISTS (
+ SELECT 1 FROM issue_label il2
+ WHERE il2.workspace_id = il.workspace_id
+ AND LOWER(il2.name) = LOWER(il.name)
+ AND il2.id < il.id
+);
+
+-- Workspace-scoped uniqueness on label name. Case-insensitive to avoid
+-- "Bug" / "bug" drift that would confuse users in the picker UI.
+CREATE UNIQUE INDEX IF NOT EXISTS issue_label_workspace_name_lower_idx
+ ON issue_label (workspace_id, LOWER(name));
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
new file mode 100644
index 0000000000..d58758edbd
--- /dev/null
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -0,0 +1,247 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.30.0
+// source: issue_label.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const attachLabelToIssue = `-- name: AttachLabelToIssue :exec
+INSERT INTO issue_to_label (issue_id, label_id)
+SELECT $1::uuid, $2::uuid
+WHERE EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = $1::uuid
+ AND i.workspace_id = $3::uuid
+)
+AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = $2::uuid
+ AND l.workspace_id = $3::uuid
+)
+ON CONFLICT DO NOTHING
+`
+
+type AttachLabelToIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
+// and the label belong to the given workspace. A future caller that forgets
+// handler-level prechecks still cannot attach labels across workspaces.
+func (q *Queries) AttachLabelToIssue(ctx context.Context, arg AttachLabelToIssueParams) error {
+ _, err := q.db.Exec(ctx, attachLabelToIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
+ return err
+}
+
+const createLabel = `-- name: CreateLabel :one
+INSERT INTO issue_label (workspace_id, name, color)
+VALUES ($1, $2, $3)
+RETURNING id, workspace_id, name, color, created_at, updated_at
+`
+
+type CreateLabelParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Color string `json:"color"`
+}
+
+func (q *Queries) CreateLabel(ctx context.Context, arg CreateLabelParams) (IssueLabel, error) {
+ row := q.db.QueryRow(ctx, createLabel, arg.WorkspaceID, arg.Name, arg.Color)
+ var i IssueLabel
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deleteLabel = `-- name: DeleteLabel :one
+DELETE FROM issue_label
+WHERE id = $1 AND workspace_id = $2
+RETURNING id
+`
+
+type DeleteLabelParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// :one RETURNING id so the handler distinguishes pgx.ErrNoRows (→ 404) from
+// infrastructure errors (→ 500), and avoids a TOCTOU precheck.
+func (q *Queries) DeleteLabel(ctx context.Context, arg DeleteLabelParams) (pgtype.UUID, error) {
+ row := q.db.QueryRow(ctx, deleteLabel, arg.ID, arg.WorkspaceID)
+ var id pgtype.UUID
+ err := row.Scan(&id)
+ return id, err
+}
+
+const detachLabelFromIssue = `-- name: DetachLabelFromIssue :exec
+DELETE FROM issue_to_label
+WHERE issue_id = $1::uuid
+ AND label_id = $2::uuid
+ AND EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = $1::uuid
+ AND i.workspace_id = $3::uuid
+ )
+`
+
+type DetachLabelFromIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Workspace-guarded DELETE: only deletes if the issue is in the given
+// workspace. Mirror of the attach query.
+func (q *Queries) DetachLabelFromIssue(ctx context.Context, arg DetachLabelFromIssueParams) error {
+ _, err := q.db.Exec(ctx, detachLabelFromIssue, arg.IssueID, arg.LabelID, arg.WorkspaceID)
+ return err
+}
+
+const getLabel = `-- name: GetLabel :one
+SELECT id, workspace_id, name, color, created_at, updated_at FROM issue_label
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetLabelParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetLabel(ctx context.Context, arg GetLabelParams) (IssueLabel, error) {
+ row := q.db.QueryRow(ctx, getLabel, arg.ID, arg.WorkspaceID)
+ var i IssueLabel
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const listLabels = `-- name: ListLabels :many
+SELECT id, workspace_id, name, color, created_at, updated_at FROM issue_label
+WHERE workspace_id = $1
+ORDER BY LOWER(name) ASC
+`
+
+func (q *Queries) ListLabels(ctx context.Context, workspaceID pgtype.UUID) ([]IssueLabel, error) {
+ rows, err := q.db.Query(ctx, listLabels, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueLabel{}
+ for rows.Next() {
+ var i IssueLabel
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLabelsByIssue = `-- name: ListLabelsByIssue :many
+SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at
+FROM issue_label l
+JOIN issue_to_label il ON il.label_id = l.id
+WHERE il.issue_id = $1::uuid
+ AND l.workspace_id = $2::uuid
+ORDER BY LOWER(l.name) ASC
+`
+
+type ListLabelsByIssueParams struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Workspace filter at the SQL layer (mirrors GetProjectInWorkspace). Any caller
+// that passes the wrong workspace gets an empty list rather than leaking labels.
+func (q *Queries) ListLabelsByIssue(ctx context.Context, arg ListLabelsByIssueParams) ([]IssueLabel, error) {
+ rows, err := q.db.Query(ctx, listLabelsByIssue, arg.IssueID, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []IssueLabel{}
+ for rows.Next() {
+ var i IssueLabel
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const updateLabel = `-- name: UpdateLabel :one
+UPDATE issue_label SET
+ name = COALESCE($3, name),
+ color = COALESCE($4, color),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING id, workspace_id, name, color, created_at, updated_at
+`
+
+type UpdateLabelParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name pgtype.Text `json:"name"`
+ Color pgtype.Text `json:"color"`
+}
+
+func (q *Queries) UpdateLabel(ctx context.Context, arg UpdateLabelParams) (IssueLabel, error) {
+ row := q.db.QueryRow(ctx, updateLabel,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Color,
+ )
+ var i IssueLabel
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 3eaebd66a4..45613342af 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -279,10 +279,12 @@ type IssueDependency struct {
}
type IssueLabel struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Name string `json:"name"`
- Color string `json:"color"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Color string `json:"color"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
type IssueReaction struct {
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
new file mode 100644
index 0000000000..13036d32c0
--- /dev/null
+++ b/server/pkg/db/queries/issue_label.sql
@@ -0,0 +1,68 @@
+-- name: ListLabels :many
+SELECT * FROM issue_label
+WHERE workspace_id = $1
+ORDER BY LOWER(name) ASC;
+
+-- name: GetLabel :one
+SELECT * FROM issue_label
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: CreateLabel :one
+INSERT INTO issue_label (workspace_id, name, color)
+VALUES ($1, $2, $3)
+RETURNING *;
+
+-- name: UpdateLabel :one
+UPDATE issue_label SET
+ name = COALESCE(sqlc.narg('name'), name),
+ color = COALESCE(sqlc.narg('color'), color),
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING *;
+
+-- name: DeleteLabel :one
+-- :one RETURNING id so the handler distinguishes pgx.ErrNoRows (→ 404) from
+-- infrastructure errors (→ 500), and avoids a TOCTOU precheck.
+DELETE FROM issue_label
+WHERE id = $1 AND workspace_id = $2
+RETURNING id;
+
+-- name: AttachLabelToIssue :exec
+-- Workspace-guarded INSERT: the WHERE EXISTS clauses ensure both the issue
+-- and the label belong to the given workspace. A future caller that forgets
+-- handler-level prechecks still cannot attach labels across workspaces.
+INSERT INTO issue_to_label (issue_id, label_id)
+SELECT sqlc.arg('issue_id')::uuid, sqlc.arg('label_id')::uuid
+WHERE EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = sqlc.arg('issue_id')::uuid
+ AND i.workspace_id = sqlc.arg('workspace_id')::uuid
+)
+AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = sqlc.arg('label_id')::uuid
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+)
+ON CONFLICT DO NOTHING;
+
+-- name: DetachLabelFromIssue :exec
+-- Workspace-guarded DELETE: only deletes if the issue is in the given
+-- workspace. Mirror of the attach query.
+DELETE FROM issue_to_label
+WHERE issue_id = sqlc.arg('issue_id')::uuid
+ AND label_id = sqlc.arg('label_id')::uuid
+ AND EXISTS (
+ SELECT 1 FROM issue i
+ WHERE i.id = sqlc.arg('issue_id')::uuid
+ AND i.workspace_id = sqlc.arg('workspace_id')::uuid
+ );
+
+-- name: ListLabelsByIssue :many
+-- Workspace filter at the SQL layer (mirrors GetProjectInWorkspace). Any caller
+-- that passes the wrong workspace gets an empty list rather than leaking labels.
+SELECT l.*
+FROM issue_label l
+JOIN issue_to_label il ON il.label_id = l.id
+WHERE il.issue_id = sqlc.arg('issue_id')::uuid
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ORDER BY LOWER(l.name) ASC;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 6dec82eaa1..b5ba64e834 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -68,6 +68,12 @@ const (
EventProjectUpdated = "project:updated"
EventProjectDeleted = "project:deleted"
+ // Label events
+ EventLabelCreated = "label:created"
+ EventLabelUpdated = "label:updated"
+ EventLabelDeleted = "label:deleted"
+ EventIssueLabelsChanged = "issue_labels:changed"
+
// Pin events
EventPinCreated = "pin:created"
EventPinDeleted = "pin:deleted"