Skip to content

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

Go

feat(labels): add scoped label management (#5279)

Jiayuan Zhangc377d7fb4f4a
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index a1bdf2d126..21f39b91e3 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -5,6 +5,45 @@ afterEach(() => {
vi.unstubAllGlobals();
});
+describe("ApiClient label response schemas", () => {
+ it("falls back safely for malformed label catalog, label, and resource responses", async () => {
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ labels: "not-an-array", total: "not-a-number" }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(client.listLabels("agent")).resolves.toEqual({ labels: [], total: 0 });
+ await expect(client.getLabel("label-1")).resolves.toMatchObject({ id: "" });
+ await expect(
+ client.createLabel({ resource_type: "agent", name: "Ops", color: "#3b82f6" }),
+ ).resolves.toMatchObject({ id: "" });
+ await expect(
+ client.updateLabel("label-1", { name: "Operations" }),
+ ).resolves.toMatchObject({ id: "" });
+
+ await expect(client.listLabelsForIssue("issue-1")).resolves.toEqual({ labels: [] });
+ await expect(client.attachLabel("issue-1", "label-1")).resolves.toEqual({ labels: [] });
+ await expect(client.detachLabel("issue-1", "label-1")).resolves.toEqual({ labels: [] });
+
+ await expect(client.listLabelsForResource("agent", "agent-1")).resolves.toEqual({ labels: [] });
+ await expect(
+ client.attachLabelToResource("agent", "agent-1", "label-1"),
+ ).resolves.toEqual({ labels: [] });
+ await expect(
+ client.detachLabelFromResource("agent", "agent-1", "label-1"),
+ ).resolves.toEqual({ labels: [] });
+
+ expect(fetchMock).toHaveBeenCalledTimes(10);
+ });
+});
+
describe("ApiClient", () => {
it("preserves HTTP status on failed requests", async () => {
vi.stubGlobal(
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 8bbd867fe5..7feb40d899 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -88,6 +88,8 @@ import type {
UpdateLabelRequest,
ListLabelsResponse,
IssueLabelsResponse,
+ LabelResourceType,
+ ResourceLabelsResponse,
PinnedItem,
CreatePinRequest,
PinnedItemType,
@@ -222,6 +224,12 @@ import {
EMPTY_CREATE_FEEDBACK_RESPONSE,
InboxUnreadSummarySchema,
EMPTY_INBOX_UNREAD_SUMMARY,
+ LabelSchema,
+ ListLabelsResponseSchema,
+ ResourceLabelsResponseSchema,
+ EMPTY_LABEL,
+ EMPTY_LIST_LABELS_RESPONSE,
+ EMPTY_RESOURCE_LABELS_RESPONSE,
} from "./schemas";
/** Identifies the calling client to the server.
@@ -2025,26 +2033,38 @@ export class ApiClient {
}
// Labels
- async listLabels(): Promise<ListLabelsResponse> {
- return this.fetch(`/api/labels`);
+ async listLabels(resourceType: LabelResourceType = "issue"): Promise<ListLabelsResponse> {
+ const raw = await this.fetch<unknown>(`/api/labels?resource_type=${resourceType}`);
+ return parseWithFallback(raw, ListLabelsResponseSchema, EMPTY_LIST_LABELS_RESPONSE, {
+ endpoint: "GET /api/labels",
+ });
}
async getLabel(id: string): Promise<Label> {
- return this.fetch(`/api/labels/${id}`);
+ const raw = await this.fetch<unknown>(`/api/labels/${id}`);
+ return parseWithFallback(raw, LabelSchema, EMPTY_LABEL, {
+ endpoint: "GET /api/labels/{id}",
+ });
}
async createLabel(data: CreateLabelRequest): Promise<Label> {
- return this.fetch(`/api/labels`, {
+ const raw = await this.fetch<unknown>(`/api/labels`, {
method: "POST",
body: JSON.stringify(data),
});
+ return parseWithFallback(raw, LabelSchema, EMPTY_LABEL, {
+ endpoint: "POST /api/labels",
+ });
}
async updateLabel(id: string, data: UpdateLabelRequest): Promise<Label> {
- return this.fetch(`/api/labels/${id}`, {
+ const raw = await this.fetch<unknown>(`/api/labels/${id}`, {
method: "PUT",
body: JSON.stringify(data),
});
+ return parseWithFallback(raw, LabelSchema, EMPTY_LABEL, {
+ endpoint: "PUT /api/labels/{id}",
+ });
}
async deleteLabel(id: string): Promise<void> {
@@ -2052,20 +2072,66 @@ export class ApiClient {
}
async listLabelsForIssue(issueId: string): Promise<IssueLabelsResponse> {
- return this.fetch(`/api/issues/${issueId}/labels`);
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/labels`);
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: "GET /api/issues/{id}/labels",
+ });
}
async attachLabel(issueId: string, labelId: string): Promise<IssueLabelsResponse> {
- return this.fetch(`/api/issues/${issueId}/labels`, {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/labels`, {
method: "POST",
body: JSON.stringify({ label_id: labelId }),
});
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: "POST /api/issues/{id}/labels",
+ });
}
async detachLabel(issueId: string, labelId: string): Promise<IssueLabelsResponse> {
- return this.fetch(`/api/issues/${issueId}/labels/${labelId}`, {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/labels/${labelId}`, {
+ method: "DELETE",
+ });
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: "DELETE /api/issues/{id}/labels/{labelId}",
+ });
+ }
+
+ async listLabelsForResource(
+ resourceType: "agent" | "skill",
+ resourceId: string,
+ ): Promise<ResourceLabelsResponse> {
+ const raw = await this.fetch<unknown>(`/api/${resourceType === "agent" ? "agents" : "skills"}/${resourceId}/labels`);
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: `GET /api/${resourceType === "agent" ? "agents" : "skills"}/{id}/labels`,
+ });
+ }
+
+ async attachLabelToResource(
+ resourceType: "agent" | "skill",
+ resourceId: string,
+ labelId: string,
+ ): Promise<ResourceLabelsResponse> {
+ const raw = await this.fetch<unknown>(`/api/${resourceType === "agent" ? "agents" : "skills"}/${resourceId}/labels`, {
+ method: "POST",
+ body: JSON.stringify({ label_id: labelId }),
+ });
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: `POST /api/${resourceType === "agent" ? "agents" : "skills"}/{id}/labels`,
+ });
+ }
+
+ async detachLabelFromResource(
+ resourceType: "agent" | "skill",
+ resourceId: string,
+ labelId: string,
+ ): Promise<ResourceLabelsResponse> {
+ const raw = await this.fetch<unknown>(`/api/${resourceType === "agent" ? "agents" : "skills"}/${resourceId}/labels/${labelId}`, {
method: "DELETE",
});
+ return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
+ endpoint: `DELETE /api/${resourceType === "agent" ? "agents" : "skills"}/{id}/labels/{labelId}`,
+ });
}
// Pins
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index bf9608d649..ce2dde32cd 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -16,8 +16,11 @@ import type {
CreateBillingPortalSessionResponse,
GroupedIssuesResponse,
InboxWorkspaceUnread,
+ Label,
ListIssuesResponse,
+ ListLabelsResponse,
ListWebhookDeliveriesResponse,
+ ResourceLabelsResponse,
SearchIssuesResponse,
SearchProjectsResponse,
Squad,
@@ -28,6 +31,51 @@ import type {
import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";
import type { CreateFeedbackResponse } from "../feedback/types";
+// Label responses are consumed by settings tables and resource pickers. Keep
+// the resource type lenient so newer server scopes do not break older clients,
+// while defaulting fields that predate scoped label catalogs.
+export const LabelSchema = z.object({
+ id: z.string(),
+ workspace_id: z.string(),
+ resource_type: z.string().optional().default("issue"),
+ name: z.string(),
+ description: z.string().optional().default(""),
+ color: z.string(),
+ usage_count: z.number().optional().default(0),
+ created_at: z.string(),
+ updated_at: z.string(),
+}).loose();
+
+export const EMPTY_LABEL: Label = {
+ id: "",
+ workspace_id: "",
+ resource_type: "issue",
+ name: "",
+ description: "",
+ color: "#6b7280",
+ usage_count: 0,
+ created_at: "",
+ updated_at: "",
+};
+
+export const ListLabelsResponseSchema = z.object({
+ labels: z.array(LabelSchema).default([]),
+ total: z.number().default(0),
+}).loose();
+
+export const EMPTY_LIST_LABELS_RESPONSE: ListLabelsResponse = {
+ labels: [],
+ total: 0,
+};
+
+export const ResourceLabelsResponseSchema = z.object({
+ labels: z.array(LabelSchema).default([]),
+}).loose();
+
+export const EMPTY_RESOURCE_LABELS_RESPONSE: ResourceLabelsResponse = {
+ labels: [],
+};
+
export interface AppConfigResponse {
cdn_domain: string;
// True when the CDN domain serves private content via time-bounded signed
diff --git a/packages/core/labels/index.ts b/packages/core/labels/index.ts
index 19a53dd23a..11713169ca 100644
--- a/packages/core/labels/index.ts
+++ b/packages/core/labels/index.ts
@@ -1,4 +1,4 @@
-export { labelKeys, labelListOptions, issueLabelsOptions } from "./queries";
+export { labelKeys, labelListOptions, issueLabelsOptions, resourceLabelsOptions } from "./queries";
export {
useCreateLabel,
useUpdateLabel,
@@ -6,4 +6,6 @@ export {
useAttachLabel,
useAttachLabelToIssue,
useDetachLabel,
+ useAttachResourceLabel,
+ useDetachResourceLabel,
} from "./mutations";
diff --git a/packages/core/labels/mutations.ts b/packages/core/labels/mutations.ts
index f27520b415..30acf2ec54 100644
--- a/packages/core/labels/mutations.ts
+++ b/packages/core/labels/mutations.ts
@@ -10,6 +10,8 @@ import type {
UpdateLabelRequest,
ListLabelsResponse,
IssueLabelsResponse,
+ LabelResourceType,
+ ResourceLabelsResponse,
} from "../types";
export function useCreateLabel() {
@@ -18,14 +20,14 @@ export function useCreateLabel() {
return useMutation({
mutationFn: (data: CreateLabelRequest) => api.createLabel(data),
onSuccess: (label) => {
- qc.setQueryData<ListLabelsResponse>(labelKeys.list(wsId), (old) =>
+ qc.setQueryData<ListLabelsResponse>(labelKeys.list(wsId, label.resource_type ?? "issue"), (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) });
+ qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
},
});
}
@@ -39,12 +41,13 @@ export function useUpdateLabel() {
const qc = useQueryClient();
const wsId = useWorkspaceId();
return useMutation({
- mutationFn: ({ id, ...data }: { id: string } & UpdateLabelRequest) =>
+ mutationFn: ({ id, resource_type: _resourceType, ...data }: { id: string; resource_type?: LabelResourceType } & 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) =>
+ onMutate: async ({ id, resource_type = "issue", ...data }) => {
+ const listKey = labelKeys.list(wsId, resource_type);
+ await qc.cancelQueries({ queryKey: listKey });
+ const prevList = qc.getQueryData<ListLabelsResponse>(listKey);
+ qc.setQueryData<ListLabelsResponse>(listKey, (old) =>
old
? {
...old,
@@ -52,10 +55,10 @@ export function useUpdateLabel() {
}
: old,
);
- return { prevList, id };
+ return { prevList, listKey };
},
onError: (_err, _vars, ctx) => {
- if (ctx?.prevList) qc.setQueryData(labelKeys.list(wsId), ctx.prevList);
+ if (ctx?.prevList && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.prevList);
},
onSettled: () => {
// Invalidate the entire labels scope so any byIssue cache holding a
@@ -73,19 +76,23 @@ 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) =>
+ mutationFn: (input: string | { id: string; resource_type: LabelResourceType }) =>
+ api.deleteLabel(typeof input === "string" ? input : input.id),
+ onMutate: async (input) => {
+ const id = typeof input === "string" ? input : input.id;
+ const resourceType = typeof input === "string" ? "issue" : input.resource_type;
+ const listKey = labelKeys.list(wsId, resourceType);
+ await qc.cancelQueries({ queryKey: listKey });
+ const prev = qc.getQueryData<ListLabelsResponse>(listKey);
+ qc.setQueryData<ListLabelsResponse>(listKey, (old) =>
old
? { ...old, labels: old.labels.filter((l) => l.id !== id), total: old.total - 1 }
: old,
);
- return { prev };
+ return { prev, listKey };
},
onError: (_err, _id, ctx) => {
- if (ctx?.prev) qc.setQueryData(labelKeys.list(wsId), ctx.prev);
+ if (ctx?.prev && ctx.listKey) qc.setQueryData(ctx.listKey, ctx.prev);
},
onSettled: () => {
qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
@@ -96,6 +103,54 @@ export function useDeleteLabel() {
});
}
+export function useAttachResourceLabel(
+ resourceType: "agent" | "skill",
+ resourceId: string,
+) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (labelId: string) =>
+ api.attachLabelToResource(resourceType, resourceId, labelId),
+ onSuccess: (data: ResourceLabelsResponse) => {
+ qc.setQueryData(
+ labelKeys.byResource(wsId, resourceType, resourceId),
+ data,
+ );
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeysForLabels(resourceType, wsId) });
+ },
+ });
+}
+
+export function useDetachResourceLabel(
+ resourceType: "agent" | "skill",
+ resourceId: string,
+) {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (labelId: string) =>
+ api.detachLabelFromResource(resourceType, resourceId, labelId),
+ onSuccess: (data: ResourceLabelsResponse) => {
+ qc.setQueryData(
+ labelKeys.byResource(wsId, resourceType, resourceId),
+ data,
+ );
+ },
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeysForLabels(resourceType, wsId) });
+ },
+ });
+}
+
+function workspaceKeysForLabels(resourceType: "agent" | "skill", wsId: string) {
+ return ["workspaces", wsId, resourceType === "agent" ? "agents" : "skills"] as const;
+}
+
export function useAttachLabel(issueId: string) {
const qc = useQueryClient();
const wsId = useWorkspaceId();
diff --git a/packages/core/labels/queries.ts b/packages/core/labels/queries.ts
index f2a61b1378..f374e207ed 100644
--- a/packages/core/labels/queries.ts
+++ b/packages/core/labels/queries.ts
@@ -1,23 +1,40 @@
import { queryOptions } from "@tanstack/react-query";
import { api } from "../api";
+import type { LabelResourceType } from "../types";
export const labelKeys = {
all: (wsId: string) => ["labels", wsId] as const,
- list: (wsId: string) => [...labelKeys.all(wsId), "list"] as const,
+ list: (wsId: string, resourceType: LabelResourceType = "issue") =>
+ [...labelKeys.all(wsId), "list", resourceType] 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,
+ byResource: (wsId: string, resourceType: "agent" | "skill", resourceId: string) =>
+ [...labelKeys.all(wsId), resourceType, resourceId] as const,
};
-export function labelListOptions(wsId: string) {
+export function labelListOptions(wsId: string, resourceType: LabelResourceType = "issue") {
return queryOptions({
- queryKey: labelKeys.list(wsId),
- queryFn: () => api.listLabels(),
+ queryKey: labelKeys.list(wsId, resourceType),
+ queryFn: () => api.listLabels(resourceType),
select: (data) => data.labels,
});
}
+export function resourceLabelsOptions(
+ wsId: string,
+ resourceType: "agent" | "skill",
+ resourceId: string,
+) {
+ return queryOptions({
+ queryKey: labelKeys.byResource(wsId, resourceType, resourceId),
+ queryFn: () => api.listLabelsForResource(resourceType, resourceId),
+ select: (data) => data.labels,
+ enabled: Boolean(resourceId),
+ });
+}
+
export function issueLabelsOptions(wsId: string, issueId: string) {
return queryOptions({
queryKey: labelKeys.byIssue(wsId, issueId),
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 54e3df87b2..dc4b6943da 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -483,14 +483,17 @@ export function useRealtimeSync(
}
},
label: () => {
- // label:created/updated/deleted — also refresh issues, since each
- // issue carries a denormalized snapshot of its labels (rename/recolor
- // /delete on a label needs to flush the chips on every issue showing
- // it).
+ // Label catalogs are independently scoped to issues, agents, and
+ // skills. The generic event prefix does not carry the scope into this
+ // dispatcher, so refresh all three resource projections. Issue rows
+ // embed label snapshots; agent/skill label pickers use their resource
+ // cache plus the shared label query tree.
const wsId = getCurrentWsId();
if (wsId) {
qc.invalidateQueries({ queryKey: ["labels", wsId] });
qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
+ qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
}
},
pin: () => {
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index c0c800cff0..00dfe09660 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -68,7 +68,7 @@ export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, Reaction } from "./comment";
-export type { Label, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse } from "./label";
+export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
export type {
TimelineEntry,
AssigneeFrequencyEntry,
diff --git a/packages/core/types/label.ts b/packages/core/types/label.ts
index c3bd5ed0e7..daa9fa1d8e 100644
--- a/packages/core/types/label.ts
+++ b/packages/core/types/label.ts
@@ -5,23 +5,31 @@
* projects group related work, labels are cross-cutting tags (bug, feature,
* performance, …). Colors are normalized to lowercase `#RRGGBB`.
*/
+export type LabelResourceType = "issue" | "agent" | "skill";
+
export interface Label {
id: string;
workspace_id: string;
+ resource_type?: LabelResourceType;
name: string;
+ description?: string;
/** Normalized lowercase hex color, e.g. `#3b82f6`. */
color: string;
+ usage_count?: number;
created_at: string;
updated_at: string;
}
export interface CreateLabelRequest {
+ resource_type?: LabelResourceType;
name: string;
+ description?: string;
color: string;
}
export interface UpdateLabelRequest {
name?: string;
+ description?: string;
color?: string;
}
@@ -33,3 +41,5 @@ export interface ListLabelsResponse {
export interface IssueLabelsResponse {
labels: Label[];
}
+
+export type ResourceLabelsResponse = IssueLabelsResponse;
diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsx
index 584c561113..16f9ec21c5 100644
--- a/packages/views/agents/components/agent-detail-inspector.tsx
+++ b/packages/views/agents/components/agent-detail-inspector.tsx
@@ -20,6 +20,7 @@ import {
import { useAutoSave } from "../../settings/components/use-auto-save";
import { useT } from "../../i18n";
import { CharCounter } from "./char-counter";
+import { ResourceLabelPicker } from "../../labels/resource-label-picker";
import { ModelPicker } from "./inspector/model-picker";
import { RuntimePicker } from "./inspector/runtime-picker";
import { ThinkingSettingField } from "./inspector/thinking-prop-row";
@@ -187,6 +188,18 @@ export function AgentDetailInspector({
/>
</div>
</SettingsRow>
+ <SettingsRow
+ label={t(($) => $.inspector.labels_label)}
+ description={t(($) => $.inspector.labels_hint)}
+ controlClassName="sm:w-96"
+ align="start"
+ >
+ <ResourceLabelPicker
+ resourceType="agent"
+ resourceId={agent.id}
+ canEdit={canEdit}
+ />
+ </SettingsRow>
</SettingsCard>
</SettingsSection>
diff --git a/packages/views/issues/components/labels-panel.tsx b/packages/views/issues/components/labels-panel.tsx
deleted file mode 100644
index dd3e982792..0000000000
--- a/packages/views/issues/components/labels-panel.tsx
+++ /dev/null
@@ -1,298 +0,0 @@
-"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 { isImeComposing } from "@multica/core/utils";
-import { LabelChip } from "../../labels/label-chip";
-import { useT } from "../../i18n";
-
-/** 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 { t } = useT("issues");
- 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 : t(($) => $.labels_panel.create_failed));
- },
- },
- );
- };
-
- 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(t(($) => $.labels_panel.name_required));
- return;
- }
- setEditError("");
- update.mutate(
- { id, name, color: editColor },
- {
- onSuccess: cancelEdit,
- onError: (err: unknown) => {
- toast.error(err instanceof Error ? err.message : t(($) => $.labels_panel.update_failed));
- },
- },
- );
- };
-
- return (
- <div className="space-y-6">
- <p className="text-sm text-muted-foreground">
- {t(($) => $.labels_panel.intro)}
- </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={t(($) => $.labels_panel.new_placeholder)}
- value={newName}
- onChange={(e) => setNewName(e.target.value)}
- onKeyDown={(e) => {
- if (isImeComposing(e)) return;
- if (e.key === "Enter") handleCreate();
- }}
- className="flex-1"
- maxLength={32}
- aria-label={t(($) => $.labels_panel.new_aria)}
- />
- <Button onClick={handleCreate} disabled={!newName.trim() || create.isPending}>
- <Plus className="h-4 w-4 mr-1" />
- {t(($) => $.labels_panel.add_action)}
- </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">{t(($) => $.labels_panel.loading)}</p>}
- {!isLoading && labels.length === 0 && (
- <p className="text-sm text-muted-foreground">{t(($) => $.labels_panel.empty)}</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 === "Escape") {
- cancelEdit();
- return;
- }
- if (isImeComposing(e)) return;
- if (e.key === "Enter") saveEdit(label.id);
- }}
- 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={t(($) => $.labels_panel.save_aria)}
- >
- <Check className="h-4 w-4" />
- </Button>
- <Button size="sm" variant="ghost" onClick={cancelEdit} aria-label={t(($) => $.labels_panel.cancel_aria)}>
- <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={t(($) => $.labels_panel.edit_aria, { name: label.name })}
- >
- <Pencil className="h-4 w-4" />
- </Button>
- <Button
- size="sm"
- variant="ghost"
- onClick={() => setPendingDeletion(label)}
- aria-label={t(($) => $.labels_panel.delete_aria, { name: 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>{t(($) => $.labels_panel.delete_dialog_title)}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(($) => $.labels_panel.delete_dialog_desc_prefix)}<strong>{pendingDeletion?.name}</strong>{t(($) => $.labels_panel.delete_dialog_desc_suffix)}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>{t(($) => $.labels_panel.delete_dialog_cancel)}</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- if (!pendingDeletion) return;
- del.mutate(pendingDeletion.id, {
- onSuccess: () => setPendingDeletion(null),
- onError: (err: unknown) => {
- toast.error(err instanceof Error ? err.message : t(($) => $.labels_panel.delete_failed));
- },
- });
- }}
- >
- {t(($) => $.labels_panel.delete_dialog_confirm)}
- </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 { t } = useT("issues");
- 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">{t(($) => $.labels_panel.color_label)}</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={t(($) => $.labels_panel.pick_color_aria)}
- 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/label-picker.tsx b/packages/views/issues/components/pickers/label-picker.tsx
index fe5ce587cf..ce1713ef12 100644
--- a/packages/views/issues/components/pickers/label-picker.tsx
+++ b/packages/views/issues/components/pickers/label-picker.tsx
@@ -5,8 +5,8 @@ import { useQuery } from "@tanstack/react-query";
import { Tag, Plus, Settings2 } from "lucide-react";
import { toast } from "sonner";
import type { Label } from "@multica/core/types";
-import { Dialog, DialogContent, DialogTitle } from "@multica/ui/components/ui/dialog";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import {
labelListOptions,
issueLabelsOptions,
@@ -15,7 +15,7 @@ import {
useCreateLabel,
} from "@multica/core/labels";
import { LabelChip } from "../../../labels/label-chip";
-import { LabelsPanel } from "../labels-panel";
+import { useNavigation } from "../../../navigation";
import {
PropertyPicker,
PickerItem,
@@ -83,9 +83,9 @@ function pickInlineColor(name: string): string {
* label with a hash-derived color and selects it in one motion. The created
* label is a real workspace label in both modes; only the attach step differs.
*
- * 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.
+ * A "Manage labels" item at the bottom opens the workspace Labels settings
+ * page, which is the single management surface for issue, agent, and skill
+ * label catalogs.
*/
export function LabelPicker({
issueId,
@@ -102,7 +102,8 @@ export function LabelPicker({
const open = controlledOpen ?? internalOpen;
const setOpen = onOpenChange ?? setInternalOpen;
const [filter, setFilter] = useState("");
- const [manageOpen, setManageOpen] = useState(false);
+ const navigation = useNavigation();
+ const paths = useWorkspacePaths();
// Synchronous lock to prevent double-submit on rapid Enter / click. React
// state (create.isPending, filter) isn't visible until the next render, so
@@ -197,7 +198,7 @@ export function LabelPicker({
const openManage = () => {
setOpen(false);
- setManageOpen(true);
+ navigation.push(`${paths.settings()}?tab=labels`);
};
const hasLabels = selectedLabels.length > 0;
@@ -288,13 +289,6 @@ export function LabelPicker({
</PickerItem>
)}
</PropertyPicker>
-
- <Dialog open={manageOpen} onOpenChange={setManageOpen}>
- <DialogContent className="max-w-2xl">
- <DialogTitle className="text-lg font-semibold">{t(($) => $.pickers.label.manage_dialog_title)}</DialogTitle>
- <LabelsPanel />
- </DialogContent>
- </Dialog>
</div>
);
}
diff --git a/packages/views/labels/resource-label-picker.tsx b/packages/views/labels/resource-label-picker.tsx
new file mode 100644
index 0000000000..535cc79f76
--- /dev/null
+++ b/packages/views/labels/resource-label-picker.tsx
@@ -0,0 +1,126 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Check, Search, Tag } from "lucide-react";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ labelListOptions,
+ resourceLabelsOptions,
+ useAttachResourceLabel,
+ useDetachResourceLabel,
+} from "@multica/core/labels";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@multica/ui/components/ui/popover";
+import { useT } from "../i18n";
+import { LabelChip } from "./label-chip";
+
+export function ResourceLabelPicker({
+ resourceType,
+ resourceId,
+ canEdit,
+}: {
+ resourceType: "agent" | "skill";
+ resourceId: string;
+ canEdit: boolean;
+}) {
+ const { t } = useT("labels");
+ const wsId = useWorkspaceId();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const { data: catalog = [] } = useQuery(labelListOptions(wsId, resourceType));
+ const { data: selected = [] } = useQuery(
+ resourceLabelsOptions(wsId, resourceType, resourceId),
+ );
+ const attach = useAttachResourceLabel(resourceType, resourceId);
+ const detach = useDetachResourceLabel(resourceType, resourceId);
+ const selectedIds = useMemo(() => new Set(selected.map((label) => label.id)), [selected]);
+ const filtered = catalog.filter((label) =>
+ label.name.toLowerCase().includes(query.trim().toLowerCase()),
+ );
+
+ const content = selected.length > 0 ? (
+ <div className="flex flex-wrap justify-start gap-1 sm:justify-end">
+ {selected.map((label) => (
+ <LabelChip key={label.id} label={label} />
+ ))}
+ </div>
+ ) : (
+ <span className="text-sm text-muted-foreground">{t(($) => $.resource_picker.empty)}</span>
+ );
+
+ if (!canEdit) return content;
+
+ return (
+ <Popover
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setQuery("");
+ }}
+ >
+ <PopoverTrigger
+ render={
+ <Button
+ type="button"
+ variant="outline"
+ className="h-auto min-h-9 w-full justify-start px-2.5 py-1.5 sm:justify-end"
+ >
+ {selected.length > 0 ? content : (
+ <>
+ <Tag className="size-3.5 text-muted-foreground" />
+ {t(($) => $.resource_picker.add)}
+ </>
+ )}
+ </Button>
+ }
+ />
+ <PopoverContent align="end" className="w-72 p-2">
+ <div className="relative mb-2">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ autoFocus
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t(($) => $.resource_picker.search)}
+ className="h-8 pl-8 text-sm"
+ />
+ </div>
+ <div className="max-h-64 space-y-0.5 overflow-y-auto">
+ {filtered.map((label) => {
+ const isSelected = selectedIds.has(label.id);
+ return (
+ <button
+ key={label.id}
+ type="button"
+ onClick={() =>
+ isSelected ? detach.mutate(label.id) : attach.mutate(label.id)
+ }
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-accent"
+ >
+ <span
+ className="size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: label.color }}
+ />
+ <span className="min-w-0 flex-1 truncate">{label.name}</span>
+ {isSelected ? <Check className="size-3.5 text-primary" /> : null}
+ </button>
+ );
+ })}
+ {filtered.length === 0 ? (
+ <p className="px-2 py-6 text-center text-xs text-muted-foreground">
+ {catalog.length === 0
+ ? t(($) => $.resource_picker.no_labels)
+ : t(($) => $.resource_picker.no_results)}
+ </p>
+ ) : null}
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.json
index e44f472414..b692db5791 100644
--- a/packages/views/locales/en/agents.json
+++ b/packages/views/locales/en/agents.json
@@ -173,6 +173,8 @@
"avatar_hint": "Shown in assignments, activity, and chat.",
"name_label": "Name",
"description_label": "Description",
+ "labels_label": "Labels",
+ "labels_hint": "Workspace labels used to classify this agent.",
"change_avatar_aria": "Change avatar",
"avatar_updated_toast": "Avatar updated",
"avatar_upload_failed_toast": "Failed to upload avatar",
diff --git a/packages/views/locales/en/labels.json b/packages/views/locales/en/labels.json
index 76a91848e0..720d0ba2b9 100644
--- a/packages/views/locales/en/labels.json
+++ b/packages/views/locales/en/labels.json
@@ -1,3 +1,10 @@
{
- "remove_label": "Remove label {{name}}"
+ "remove_label": "Remove label {{name}}",
+ "resource_picker": {
+ "empty": "No labels",
+ "add": "Add labels",
+ "search": "Search labels...",
+ "no_labels": "Create labels in Settings first",
+ "no_results": "No matching labels"
+ }
}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 7a50ffc98a..95ada91ca4 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -48,7 +48,56 @@
"github": "GitHub",
"integrations": "Integrations",
"labs": "Labs",
- "members": "Members"
+ "members": "Members",
+ "labels": "Labels"
+ }
+ },
+ "labels": {
+ "title": "Labels",
+ "description": "Manage the separate label catalogs used to organize issues, agents, and skills in this workspace.",
+ "scopes": {
+ "issue": "Issues",
+ "agent": "Agents",
+ "skill": "Skills"
+ },
+ "search_placeholder": "Filter by name or description...",
+ "new_label": "New label",
+ "columns": {
+ "name": "Name",
+ "description": "Description",
+ "usage": "Used by",
+ "updated": "Updated"
+ },
+ "usage_count": "{{count}} used",
+ "loading": "Loading labels...",
+ "empty": "No {{scope}} labels yet",
+ "no_results": "No matching labels",
+ "save_failed": "Couldn't save label",
+ "actions": {
+ "open": "Actions for {{name}}",
+ "edit": "Edit",
+ "delete": "Delete"
+ },
+ "editor": {
+ "create_title": "New label",
+ "edit_title": "Edit label",
+ "scope_hint": "This label belongs only to the {{scope}} catalog.",
+ "name": "Name",
+ "name_placeholder": "e.g. Bug",
+ "description": "Description",
+ "description_placeholder": "Describe when this label should be used",
+ "color": "Color",
+ "custom_color": "Choose a custom color",
+ "cancel": "Cancel",
+ "save": "Save label",
+ "saving": "Saving..."
+ },
+ "delete_dialog": {
+ "title": "Delete label?",
+ "description": "Delete \"{{name}}\"? It will be removed from {{count}} resources. This can't be undone.",
+ "cancel": "Cancel",
+ "confirm": "Delete label",
+ "failed": "Couldn't delete label"
}
},
"account": {
diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.json
index 9106a719bd..fe2a301932 100644
--- a/packages/views/locales/ja/agents.json
+++ b/packages/views/locales/ja/agents.json
@@ -157,6 +157,8 @@
"avatar_hint": "割り当て、アクティビティ、チャットに表示されます。",
"name_label": "名前",
"description_label": "説明",
+ "labels_label": "ラベル",
+ "labels_hint": "このエージェントを分類するワークスペースラベルです。",
"change_avatar_aria": "アバターを変更",
"avatar_updated_toast": "アバターを更新しました",
"avatar_upload_failed_toast": "アバターをアップロードできませんでした",
diff --git a/packages/views/locales/ja/labels.json b/packages/views/locales/ja/labels.json
index 41af1a54f2..5b70124ce3 100644
--- a/packages/views/locales/ja/labels.json
+++ b/packages/views/locales/ja/labels.json
@@ -1,3 +1,10 @@
{
- "remove_label": "ラベル{{name}}を削除"
+ "remove_label": "ラベル{{name}}を削除",
+ "resource_picker": {
+ "empty": "ラベルなし",
+ "add": "ラベルを追加",
+ "search": "ラベルを検索...",
+ "no_labels": "先に設定でラベルを作成してください",
+ "no_results": "一致するラベルがありません"
+ }
}
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 5f2adb0f10..9447f525b3 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -48,7 +48,52 @@
"github": "GitHub",
"integrations": "連携",
"labs": "ラボ",
- "members": "メンバー"
+ "members": "メンバー",
+ "labels": "ラベル"
+ }
+ },
+ "labels": {
+ "title": "ラベル",
+ "description": "このワークスペースの Issue、エージェント、Skill 用ラベルを個別に管理します。",
+ "scopes": {
+ "issue": "Issue",
+ "agent": "エージェント",
+ "skill": "Skill"
+ },
+ "search_placeholder": "名前または説明で絞り込み...",
+ "new_label": "新しいラベル",
+ "columns": {
+ "name": "名前",
+ "description": "説明",
+ "usage": "使用数",
+ "updated": "更新日"
+ },
+ "usage_count": "{{count}} 件で使用",
+ "loading": "ラベルを読み込み中...",
+ "empty": "{{scope}} ラベルはまだありません",
+ "no_results": "一致するラベルがありません",
+ "save_failed": "ラベルを保存できませんでした",
+ "actions": { "open": "{{name}} の操作", "edit": "編集", "delete": "削除" },
+ "editor": {
+ "create_title": "新しいラベル",
+ "edit_title": "ラベルを編集",
+ "scope_hint": "このラベルは {{scope}} カタログ専用です。",
+ "name": "名前",
+ "name_placeholder": "例: Bug",
+ "description": "説明",
+ "description_placeholder": "このラベルを使用する条件を説明",
+ "color": "色",
+ "custom_color": "カスタム色を選択",
+ "cancel": "キャンセル",
+ "save": "ラベルを保存",
+ "saving": "保存中..."
+ },
+ "delete_dialog": {
+ "title": "ラベルを削除しますか?",
+ "description": "「{{name}}」を削除しますか?{{count}} 件のリソースから削除されます。この操作は元に戻せません。",
+ "cancel": "キャンセル",
+ "confirm": "ラベルを削除",
+ "failed": "ラベルを削除できませんでした"
}
},
"account": {
diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.json
index 7537b0e045..cb432eb81c 100644
--- a/packages/views/locales/ko/agents.json
+++ b/packages/views/locales/ko/agents.json
@@ -165,6 +165,8 @@
"avatar_hint": "할당, 활동 및 채팅에 표시됩니다.",
"name_label": "이름",
"description_label": "설명",
+ "labels_label": "레이블",
+ "labels_hint": "이 에이전트를 분류하는 워크스페이스 레이블입니다.",
"change_avatar_aria": "아바타 변경",
"avatar_updated_toast": "아바타를 업데이트했습니다",
"avatar_upload_failed_toast": "아바타를 업로드하지 못했습니다",
diff --git a/packages/views/locales/ko/labels.json b/packages/views/locales/ko/labels.json
index 517b8ddfc5..f70592d40f 100644
--- a/packages/views/locales/ko/labels.json
+++ b/packages/views/locales/ko/labels.json
@@ -1,3 +1,10 @@
{
- "remove_label": "{{name}} 라벨 제거"
+ "remove_label": "{{name}} 라벨 제거",
+ "resource_picker": {
+ "empty": "레이블 없음",
+ "add": "레이블 추가",
+ "search": "레이블 검색...",
+ "no_labels": "먼저 설정에서 레이블을 만드세요",
+ "no_results": "일치하는 레이블이 없습니다"
+ }
}
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 498ac5f9b5..46761d465e 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -48,7 +48,52 @@
"github": "GitHub",
"integrations": "연동",
"labs": "실험실",
- "members": "멤버"
+ "members": "멤버",
+ "labels": "레이블"
+ }
+ },
+ "labels": {
+ "title": "레이블",
+ "description": "이 워크스페이스의 이슈, 에이전트, 스킬 레이블을 각각 관리합니다.",
+ "scopes": {
+ "issue": "이슈",
+ "agent": "에이전트",
+ "skill": "스킬"
+ },
+ "search_placeholder": "이름 또는 설명으로 필터링...",
+ "new_label": "새 레이블",
+ "columns": {
+ "name": "이름",
+ "description": "설명",
+ "usage": "사용 수",
+ "updated": "업데이트"
+ },
+ "usage_count": "{{count}}개에서 사용",
+ "loading": "레이블 불러오는 중...",
+ "empty": "{{scope}} 레이블이 없습니다",
+ "no_results": "일치하는 레이블이 없습니다",
+ "save_failed": "레이블을 저장하지 못했습니다",
+ "actions": { "open": "{{name}} 작업", "edit": "편집", "delete": "삭제" },
+ "editor": {
+ "create_title": "새 레이블",
+ "edit_title": "레이블 편집",
+ "scope_hint": "이 레이블은 {{scope}} 카탈로그에만 속합니다.",
+ "name": "이름",
+ "name_placeholder": "예: Bug",
+ "description": "설명",
+ "description_placeholder": "이 레이블을 사용할 때를 설명하세요",
+ "color": "색상",
+ "custom_color": "사용자 지정 색상 선택",
+ "cancel": "취소",
+ "save": "레이블 저장",
+ "saving": "저장 중..."
+ },
+ "delete_dialog": {
+ "title": "레이블을 삭제할까요?",
+ "description": "\"{{name}}\" 레이블을 삭제할까요? {{count}}개 리소스에서 제거되며 되돌릴 수 없습니다.",
+ "cancel": "취소",
+ "confirm": "레이블 삭제",
+ "failed": "레이블을 삭제하지 못했습니다"
}
},
"account": {
diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.json
index 1524e2545c..46ba33186f 100644
--- a/packages/views/locales/zh-Hans/agents.json
+++ b/packages/views/locales/zh-Hans/agents.json
@@ -165,6 +165,8 @@
"avatar_hint": "显示在任务分配、动态和聊天中。",
"name_label": "名称",
"description_label": "描述",
+ "labels_label": "标签",
+ "labels_hint": "用于分类这个智能体的工作区标签。",
"change_avatar_aria": "更换头像",
"avatar_updated_toast": "已更新头像",
"avatar_upload_failed_toast": "头像上传失败",
diff --git a/packages/views/locales/zh-Hans/labels.json b/packages/views/locales/zh-Hans/labels.json
index b4ef7c8c85..635afba002 100644
--- a/packages/views/locales/zh-Hans/labels.json
+++ b/packages/views/locales/zh-Hans/labels.json
@@ -1,3 +1,10 @@
{
- "remove_label": "移除标签 {{name}}"
+ "remove_label": "移除标签 {{name}}",
+ "resource_picker": {
+ "empty": "暂无标签",
+ "add": "添加标签",
+ "search": "搜索标签...",
+ "no_labels": "请先在设置中创建标签",
+ "no_results": "没有匹配的标签"
+ }
}
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index db04217518..42e7cf9207 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -48,7 +48,56 @@
"github": "GitHub",
"integrations": "集成",
"labs": "实验室",
- "members": "成员"
+ "members": "成员",
+ "labels": "标签"
+ }
+ },
+ "labels": {
+ "title": "标签",
+ "description": "分别管理工作区中用于整理 issue、智能体和 skill 的标签。三类标签相互独立。",
+ "scopes": {
+ "issue": "Issue",
+ "agent": "智能体",
+ "skill": "Skill"
+ },
+ "search_placeholder": "按名称或描述筛选...",
+ "new_label": "新建标签",
+ "columns": {
+ "name": "名称",
+ "description": "描述",
+ "usage": "使用数量",
+ "updated": "更新时间"
+ },
+ "usage_count": "已使用 {{count}} 次",
+ "loading": "正在加载标签...",
+ "empty": "暂无 {{scope}} 标签",
+ "no_results": "没有匹配的标签",
+ "save_failed": "无法保存标签",
+ "actions": {
+ "open": "{{name}} 的操作",
+ "edit": "编辑",
+ "delete": "删除"
+ },
+ "editor": {
+ "create_title": "新建标签",
+ "edit_title": "编辑标签",
+ "scope_hint": "这个标签只属于 {{scope}} 分类。",
+ "name": "名称",
+ "name_placeholder": "例如:Bug",
+ "description": "描述",
+ "description_placeholder": "说明什么时候应使用这个标签",
+ "color": "颜色",
+ "custom_color": "选择自定义颜色",
+ "cancel": "取消",
+ "save": "保存标签",
+ "saving": "保存中..."
+ },
+ "delete_dialog": {
+ "title": "删除标签?",
+ "description": "确认删除 \"{{name}}\"?它将从 {{count}} 个资源中移除。此操作无法撤销。",
+ "cancel": "取消",
+ "confirm": "删除标签",
+ "failed": "无法删除标签"
}
},
"account": {
diff --git a/packages/views/settings/components/index.ts b/packages/views/settings/components/index.ts
index 1116afeddc..ba802aabe8 100644
--- a/packages/views/settings/components/index.ts
+++ b/packages/views/settings/components/index.ts
@@ -1,2 +1,3 @@
export { SettingsPage } from "./settings-page";
export type { ExtraSettingsTab } from "./settings-page";
+export { LabelsTab } from "./labels-tab";
diff --git a/packages/views/settings/components/labels-tab.tsx b/packages/views/settings/components/labels-tab.tsx
new file mode 100644
index 0000000000..5eb97586a4
--- /dev/null
+++ b/packages/views/settings/components/labels-tab.tsx
@@ -0,0 +1,447 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { MoreHorizontal, Pencil, Plus, Search, Tag, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+import { useWorkspaceId } from "@multica/core/hooks";
+import {
+ labelListOptions,
+ useCreateLabel,
+ useDeleteLabel,
+ useUpdateLabel,
+} from "@multica/core/labels";
+import type { Label, LabelResourceType } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { Textarea } from "@multica/ui/components/ui/textarea";
+import { Label as FieldLabel } from "@multica/ui/components/ui/label";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@multica/ui/components/ui/dialog";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@multica/ui/components/ui/alert-dialog";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { cn } from "@multica/ui/lib/utils";
+import { useT } from "../../i18n";
+import { SettingsTab } from "./settings-layout";
+
+const RESOURCE_TYPES: LabelResourceType[] = ["issue", "agent", "skill"];
+const LABEL_COLORS = [
+ "#6b7280",
+ "#ef4444",
+ "#f97316",
+ "#eab308",
+ "#22c55e",
+ "#14b8a6",
+ "#3b82f6",
+ "#6366f1",
+ "#a855f7",
+ "#ec4899",
+] as const;
+
+interface LabelDraft {
+ name: string;
+ description: string;
+ color: string;
+}
+
+const EMPTY_DRAFT: LabelDraft = {
+ name: "",
+ description: "",
+ color: LABEL_COLORS[6],
+};
+
+export function LabelsTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+
+ const [resourceType, setResourceType] = useState<LabelResourceType>("issue");
+ const [query, setQuery] = useState("");
+ const [editing, setEditing] = useState<Label | null>(null);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [pendingDelete, setPendingDelete] = useState<Label | null>(null);
+
+ const { data: labels = [], isLoading } = useQuery(
+ labelListOptions(wsId, resourceType),
+ );
+ const filteredLabels = useMemo(() => {
+ const normalized = query.trim().toLowerCase();
+ if (!normalized) return labels;
+ return labels.filter(
+ (label) =>
+ label.name.toLowerCase().includes(normalized) ||
+ (label.description ?? "").toLowerCase().includes(normalized),
+ );
+ }, [labels, query]);
+
+ const scopeLabel = t(($) => $.labels.scopes[resourceType]);
+
+ return (
+ <SettingsTab
+ title={t(($) => $.labels.title)}
+ description={t(($) => $.labels.description)}
+ >
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-center gap-2 border-b border-surface-border pb-3">
+ {RESOURCE_TYPES.map((type) => (
+ <Button
+ key={type}
+ type="button"
+ size="sm"
+ variant={resourceType === type ? "secondary" : "ghost"}
+ className={cn(
+ "gap-2",
+ resourceType === type && "bg-surface-selected text-surface-selected-foreground",
+ )}
+ onClick={() => {
+ setResourceType(type);
+ setQuery("");
+ }}
+ >
+ <Tag className="size-3.5" />
+ {t(($) => $.labels.scopes[type])}
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {type === resourceType ? labels.length : ""}
+ </span>
+ </Button>
+ ))}
+ </div>
+
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="relative w-full sm:max-w-sm">
+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
+ <Input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder={t(($) => $.labels.search_placeholder)}
+ className="pl-9"
+ />
+ </div>
+ <Button className="gap-2" onClick={() => setCreateOpen(true)}>
+ <Plus className="size-4" />
+ {t(($) => $.labels.new_label)}
+ </Button>
+ </div>
+
+ <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
+ <div className="hidden grid-cols-[minmax(11rem,1fr)_minmax(12rem,1.4fr)_6rem_7rem_2rem] gap-4 border-b border-surface-border bg-muted/20 px-4 py-2.5 text-xs font-medium text-muted-foreground md:grid">
+ <span>{t(($) => $.labels.columns.name)}</span>
+ <span>{t(($) => $.labels.columns.description)}</span>
+ <span>{t(($) => $.labels.columns.usage)}</span>
+ <span>{t(($) => $.labels.columns.updated)}</span>
+ <span />
+ </div>
+
+ {isLoading ? (
+ <div className="px-4 py-12 text-center text-sm text-muted-foreground">
+ {t(($) => $.labels.loading)}
+ </div>
+ ) : filteredLabels.length === 0 ? (
+ <div className="px-4 py-12 text-center">
+ <Tag className="mx-auto size-6 text-muted-foreground/60" />
+ <p className="mt-3 text-sm font-medium">
+ {query
+ ? t(($) => $.labels.no_results)
+ : t(($) => $.labels.empty, { scope: scopeLabel })}
+ </p>
+ </div>
+ ) : (
+ <div className="divide-y divide-surface-border">
+ {filteredLabels.map((label) => (
+ <div
+ key={label.id}
+ className="grid gap-2 px-4 py-3 md:grid-cols-[minmax(11rem,1fr)_minmax(12rem,1.4fr)_6rem_7rem_2rem] md:items-center md:gap-4"
+ >
+ <div className="flex min-w-0 items-center gap-3">
+ <span
+ className="size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: label.color }}
+ />
+ <span className="truncate text-sm font-medium">{label.name}</span>
+ </div>
+ <p className="min-w-0 truncate text-xs text-muted-foreground md:text-sm">
+ {label.description || "—"}
+ </p>
+ <span className="text-xs tabular-nums text-muted-foreground md:text-sm">
+ {t(($) => $.labels.usage_count, { count: label.usage_count ?? 0 })}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {new Date(label.updated_at).toLocaleDateString()}
+ </span>
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.labels.actions.open, { name: label.name })}
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(label)}>
+ <Pencil className="size-4" />
+ {t(($) => $.labels.actions.edit)}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setPendingDelete(label)}
+ >
+ <Trash2 className="size-4" />
+ {t(($) => $.labels.actions.delete)}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <LabelEditorDialog
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ resourceType={resourceType}
+ />
+ <LabelEditorDialog
+ open={Boolean(editing)}
+ onOpenChange={(open) => !open && setEditing(null)}
+ resourceType={resourceType}
+ label={editing}
+ />
+ <DeleteLabelDialog
+ label={pendingDelete}
+ onClose={() => setPendingDelete(null)}
+ />
+ </SettingsTab>
+ );
+}
+
+function LabelEditorDialog({
+ open,
+ onOpenChange,
+ resourceType,
+ label,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ resourceType: LabelResourceType;
+ label?: Label | null;
+}) {
+ const { t } = useT("settings");
+ const create = useCreateLabel();
+ const update = useUpdateLabel();
+ const [draft, setDraft] = useState<LabelDraft>(EMPTY_DRAFT);
+
+ useEffect(() => {
+ if (!open) return;
+ setDraft(
+ label
+ ? {
+ name: label.name,
+ description: label.description ?? "",
+ color: label.color,
+ }
+ : EMPTY_DRAFT,
+ );
+ }, [label, open]);
+
+ const submit = () => {
+ const name = draft.name.trim();
+ if (!name) return;
+ if (label) {
+ update.mutate(
+ {
+ id: label.id,
+ resource_type: label.resource_type ?? resourceType,
+ name,
+ description: draft.description.trim(),
+ color: draft.color,
+ },
+ {
+ onSuccess: () => onOpenChange(false),
+ onError: (error) =>
+ toast.error(error instanceof Error ? error.message : t(($) => $.labels.save_failed)),
+ },
+ );
+ return;
+ }
+ create.mutate(
+ {
+ resource_type: resourceType,
+ name,
+ description: draft.description.trim(),
+ color: draft.color,
+ },
+ {
+ onSuccess: () => onOpenChange(false),
+ onError: (error) =>
+ toast.error(error instanceof Error ? error.message : t(($) => $.labels.save_failed)),
+ },
+ );
+ };
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={onOpenChange}
+ >
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {label ? t(($) => $.labels.editor.edit_title) : t(($) => $.labels.editor.create_title)}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $.labels.editor.scope_hint, {
+ scope: t(($) => $.labels.scopes[resourceType]),
+ })}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5 py-2">
+ <div className="space-y-2">
+ <FieldLabel htmlFor="label-name">{t(($) => $.labels.editor.name)}</FieldLabel>
+ <Input
+ id="label-name"
+ autoFocus
+ maxLength={32}
+ value={draft.name}
+ onChange={(event) => setDraft((current) => ({ ...current, name: event.target.value }))}
+ placeholder={t(($) => $.labels.editor.name_placeholder)}
+ />
+ </div>
+ <div className="space-y-2">
+ <FieldLabel htmlFor="label-description">
+ {t(($) => $.labels.editor.description)}
+ </FieldLabel>
+ <Textarea
+ id="label-description"
+ rows={3}
+ value={draft.description}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, description: event.target.value }))
+ }
+ placeholder={t(($) => $.labels.editor.description_placeholder)}
+ />
+ </div>
+ <div className="space-y-2">
+ <FieldLabel>{t(($) => $.labels.editor.color)}</FieldLabel>
+ <div className="flex flex-wrap items-center gap-2">
+ {LABEL_COLORS.map((color) => (
+ <button
+ key={color}
+ type="button"
+ aria-label={color}
+ aria-pressed={draft.color === color}
+ onClick={() => setDraft((current) => ({ ...current, color }))}
+ className={cn(
+ "size-7 rounded-full border-2 border-background ring-offset-2 transition-transform hover:scale-110",
+ draft.color === color && "ring-2 ring-ring",
+ )}
+ style={{ backgroundColor: color }}
+ />
+ ))}
+ <label
+ className="relative size-7 cursor-pointer overflow-hidden rounded-full border border-surface-border"
+ title={t(($) => $.labels.editor.custom_color)}
+ style={{ backgroundColor: draft.color }}
+ >
+ <input
+ type="color"
+ value={draft.color}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, color: event.target.value }))
+ }
+ className="absolute inset-0 cursor-pointer opacity-0"
+ aria-label={t(($) => $.labels.editor.custom_color)}
+ />
+ </label>
+ </div>
+ </div>
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ {t(($) => $.labels.editor.cancel)}
+ </Button>
+ <Button
+ onClick={submit}
+ disabled={!draft.name.trim() || create.isPending || update.isPending}
+ >
+ {create.isPending || update.isPending
+ ? t(($) => $.labels.editor.saving)
+ : t(($) => $.labels.editor.save)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function DeleteLabelDialog({
+ label,
+ onClose,
+}: {
+ label: Label | null;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const remove = useDeleteLabel();
+ return (
+ <AlertDialog open={Boolean(label)} onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.labels.delete_dialog.title)}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.labels.delete_dialog.description, {
+ name: label?.name ?? "",
+ count: label?.usage_count ?? 0,
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.labels.delete_dialog.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (!label) return;
+ remove.mutate(
+ { id: label.id, resource_type: label.resource_type ?? "issue" },
+ {
+ onSuccess: onClose,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.labels.delete_dialog.failed),
+ ),
+ },
+ );
+ }}
+ >
+ {t(($) => $.labels.delete_dialog.confirm)}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index efcca0dffe..888eb64866 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -12,6 +12,7 @@ import {
Bell,
Plug,
MessageCircle,
+ Tags,
} from "lucide-react";
import { GitHubMark } from "./github-mark";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
@@ -29,6 +30,7 @@ import { GitHubTab } from "./github-tab";
import { IntegrationsTab } from "./integrations-tab";
import { LabsTab } from "./labs-tab";
import { NotificationsTab } from "./notifications-tab";
+import { LabelsTab } from "./labels-tab";
import { useT } from "../../i18n";
const ACCOUNT_TAB_KEYS = ["profile", "preferences", "chat", "notifications", "tokens"] as const;
@@ -47,6 +49,7 @@ const WORKSPACE_TAB_KEYS = [
"integrations",
"labs",
"members",
+ "labels",
] as const;
const WORKSPACE_TAB_VALUES = {
general: "workspace",
@@ -55,6 +58,7 @@ const WORKSPACE_TAB_VALUES = {
integrations: "integrations",
labs: "labs",
members: "members",
+ labels: "labels",
} as const;
const WORKSPACE_TAB_ICONS = {
general: Settings,
@@ -63,6 +67,7 @@ const WORKSPACE_TAB_ICONS = {
integrations: Plug,
labs: FlaskConical,
members: Users,
+ labels: Tags,
} as const;
const DEFAULT_TAB = "profile";
@@ -189,7 +194,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
{/* Right content */}
<div className="min-w-0 flex-1 md:overflow-y-auto">
- <div className="mx-auto w-full max-w-3xl p-4 sm:p-6 md:p-8">
+ <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" ? "max-w-5xl" : "max-w-3xl"}`}>
<TabsContent value="profile"><AccountTab /></TabsContent>
<TabsContent value="preferences"><PreferencesTab /></TabsContent>
<TabsContent value="chat"><ChatTab /></TabsContent>
@@ -201,6 +206,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<TabsContent value="integrations"><IntegrationsTab /></TabsContent>
<TabsContent value="labs"><LabsTab /></TabsContent>
<TabsContent value="members"><MembersTab /></TabsContent>
+ <TabsContent value="labels"><LabelsTab /></TabsContent>
{extraAccountTabs?.map((tab) => (
<TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>
))}
diff --git a/packages/views/skills/components/skill-detail-page.tsx b/packages/views/skills/components/skill-detail-page.tsx
index dadaa7afa5..08ee8947dd 100644
--- a/packages/views/skills/components/skill-detail-page.tsx
+++ b/packages/views/skills/components/skill-detail-page.tsx
@@ -71,6 +71,7 @@ import {
type SkillActionsContext,
} from "./skill-list-actions";
import { useT } from "../../i18n";
+import { ResourceLabelPicker } from "../../labels/resource-label-picker";
const SKILL_MD = "SKILL.md";
@@ -719,6 +720,11 @@ export function SkillDetailPage({ skillId }: { skillId: string }) {
className="resize-none text-sm read-only:cursor-default"
/>
</div>
+ <ResourceLabelPicker
+ resourceType="skill"
+ resourceId={skill.id}
+ canEdit={canEdit}
+ />
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
{originLabel && (
<span className="inline-flex items-center gap-1">
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 255158e1c5..f01bf5aaa4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1143,6 +1143,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/skills", h.ListAgentSkills)
r.Put("/skills", h.SetAgentSkills)
r.Post("/skills/add", h.AddAgentSkills)
+ r.Get("/labels", h.ListLabelsForAgent)
+ r.Post("/labels", h.AttachLabelToAgent)
+ r.Delete("/labels/{labelId}", h.DetachLabelFromAgent)
r.Put("/skills/{skillId}/enabled", h.SetAgentSkillEnabled)
r.Delete("/skills/{skillId}", h.RemoveAgentSkill)
// Dedicated env-management endpoint. Owner/admin only;
@@ -1172,6 +1175,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/", h.GetSkill)
r.Put("/", h.UpdateSkill)
r.Delete("/", h.DeleteSkill)
+ r.Get("/labels", h.ListLabelsForSkill)
+ r.Post("/labels", h.AttachLabelToSkill)
+ r.Delete("/labels/{labelId}", h.DetachLabelFromSkill)
r.Get("/files", h.ListSkillFiles)
r.Put("/files", h.UpsertSkillFile)
r.Delete("/files/{fileId}", h.DeleteSkillFile)
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index ad983b6723..23f1e865d0 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -160,12 +160,14 @@ func (h *Handler) labelsByIssue(ctx context.Context, wsUUID pgtype.UUID, issueID
for _, r := range rows {
issueID := uuidToString(r.IssueID)
out[issueID] = append(out[issueID], LabelResponse{
- ID: uuidToString(r.ID),
- WorkspaceID: uuidToString(r.WorkspaceID),
- Name: r.Name,
- Color: r.Color,
- CreatedAt: timestampToString(r.CreatedAt),
- UpdatedAt: timestampToString(r.UpdatedAt),
+ ID: uuidToString(r.ID),
+ WorkspaceID: uuidToString(r.WorkspaceID),
+ ResourceType: r.ResourceType,
+ Name: r.Name,
+ Description: r.Description,
+ Color: r.Color,
+ CreatedAt: timestampToString(r.CreatedAt),
+ UpdatedAt: timestampToString(r.UpdatedAt),
})
}
return out
diff --git a/server/internal/handler/label.go b/server/internal/handler/label.go
index 6fc577eaa0..0b3eb56d11 100644
--- a/server/internal/handler/label.go
+++ b/server/internal/handler/label.go
@@ -23,22 +23,41 @@ import (
// ---------------------------------------------------------------------------
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"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ ResourceType string `json:"resource_type"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Color string `json:"color"`
+ UsageCount int64 `json:"usage_count"`
+ 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),
+ ID: uuidToString(l.ID),
+ WorkspaceID: uuidToString(l.WorkspaceID),
+ ResourceType: l.ResourceType,
+ Name: l.Name,
+ Description: l.Description,
+ Color: l.Color,
+ CreatedAt: timestampToString(l.CreatedAt),
+ UpdatedAt: timestampToString(l.UpdatedAt),
+ }
+}
+
+func labelListRowToResponse(l db.ListLabelsRow) LabelResponse {
+ return LabelResponse{
+ ID: uuidToString(l.ID),
+ WorkspaceID: uuidToString(l.WorkspaceID),
+ ResourceType: l.ResourceType,
+ Name: l.Name,
+ Description: l.Description,
+ Color: l.Color,
+ UsageCount: l.UsageCount,
+ CreatedAt: timestampToString(l.CreatedAt),
+ UpdatedAt: timestampToString(l.UpdatedAt),
}
}
@@ -51,13 +70,31 @@ func labelsToResponse(list []db.IssueLabel) []LabelResponse {
}
type CreateLabelRequest struct {
- Name string `json:"name"`
- Color string `json:"color"`
+ ResourceType string `json:"resource_type"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Color string `json:"color"`
}
type UpdateLabelRequest struct {
- Name *string `json:"name"`
- Color *string `json:"color"`
+ Name *string `json:"name"`
+ Description *string `json:"description"`
+ Color *string `json:"color"`
+}
+
+const defaultLabelResourceType = "issue"
+
+func parseLabelResourceType(raw string) (string, error) {
+ value := strings.TrimSpace(raw)
+ if value == "" {
+ return defaultLabelResourceType, nil
+ }
+ switch value {
+ case "issue", "agent", "skill":
+ return value, nil
+ default:
+ return "", errors.New("resource_type must be issue, agent, or skill")
+ }
}
// 6-digit hex, with or without leading '#'.
@@ -106,13 +143,23 @@ func validateLabelName(raw string) (string, error) {
func (h *Handler) ListLabels(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
- labels, err := h.Queries.ListLabels(r.Context(), parseUUID(workspaceID))
+ resourceType, err := parseLabelResourceType(r.URL.Query().Get("resource_type"))
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ labels, err := h.Queries.ListLabels(r.Context(), db.ListLabelsParams{
+ WorkspaceID: parseUUID(workspaceID), ResourceType: resourceType,
+ })
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)
+ resp := make([]LabelResponse, len(labels))
+ for i, label := range labels {
+ resp[i] = labelListRowToResponse(label)
+ }
writeJSON(w, http.StatusOK, map[string]any{"labels": resp, "total": len(resp)})
}
@@ -158,6 +205,11 @@ func (h *Handler) CreateLabel(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, err.Error())
return
}
+ resourceType, err := parseLabelResourceType(req.ResourceType)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
workspaceID := h.resolveWorkspaceID(r)
userID, ok := requireUserID(w, r)
if !ok {
@@ -165,9 +217,11 @@ func (h *Handler) CreateLabel(w http.ResponseWriter, r *http.Request) {
}
label, err := h.Queries.CreateLabel(r.Context(), db.CreateLabelParams{
- WorkspaceID: parseUUID(workspaceID),
- Name: name,
- Color: color,
+ WorkspaceID: parseUUID(workspaceID),
+ ResourceType: resourceType,
+ Name: name,
+ Description: sanitizeNullBytes(strings.TrimSpace(req.Description)),
+ Color: color,
})
if err != nil {
if isUniqueViolation(err) {
@@ -217,6 +271,9 @@ func (h *Handler) UpdateLabel(w http.ResponseWriter, r *http.Request) {
}
params.Name = pgtype.Text{String: name, Valid: true}
}
+ if req.Description != nil {
+ params.Description = pgtype.Text{String: sanitizeNullBytes(strings.TrimSpace(*req.Description)), Valid: true}
+ }
if req.Color != nil {
color, err := normalizeColor(*req.Color)
if err != nil {
@@ -355,9 +412,10 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if _, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
ID: labelID, WorkspaceID: issue.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusNotFound, "label not found")
return
@@ -366,6 +424,10 @@ func (h *Handler) AttachLabel(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to attach label")
return
}
+ if label.ResourceType != "issue" {
+ writeError(w, http.StatusNotFound, "issue label not found")
+ return
+ }
if err := h.Queries.AttachLabelToIssue(r.Context(), db.AttachLabelToIssueParams{
IssueID: issue.ID,
@@ -415,9 +477,10 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
- if _, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{
ID: labelUUID, WorkspaceID: issue.WorkspaceID,
- }); err != nil {
+ })
+ if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusNotFound, "label not found")
return
@@ -426,6 +489,10 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to detach label")
return
}
+ if label.ResourceType != "issue" {
+ writeError(w, http.StatusNotFound, "issue label not found")
+ return
+ }
if err := h.Queries.DetachLabelFromIssue(r.Context(), db.DetachLabelFromIssueParams{
IssueID: issue.ID,
@@ -449,3 +516,133 @@ func (h *Handler) DetachLabel(w http.ResponseWriter, r *http.Request) {
})
writeJSON(w, http.StatusOK, map[string]any{"labels": resp})
}
+
+// ---------------------------------------------------------------------------
+// Handlers — agent/skill↔label attach/detach
+// ---------------------------------------------------------------------------
+
+func (h *Handler) ListLabelsForAgent(w http.ResponseWriter, r *http.Request) {
+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ labels, err := h.Queries.ListLabelsByAgent(r.Context(), db.ListLabelsByAgentParams{
+ AgentID: agent.ID, WorkspaceID: agent.WorkspaceID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list agent labels")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"labels": labelsToResponse(labels)})
+}
+
+func (h *Handler) AttachLabelToAgent(w http.ResponseWriter, r *http.Request) {
+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
+ if !ok || !h.canManageAgent(w, r, agent) {
+ return
+ }
+ var req AttachLabelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.LabelID == "" {
+ writeError(w, http.StatusBadRequest, "label_id is required")
+ return
+ }
+ labelID, ok := parseUUIDOrBadRequest(w, req.LabelID, "label_id")
+ if !ok {
+ return
+ }
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{ID: labelID, WorkspaceID: agent.WorkspaceID})
+ if err != nil || label.ResourceType != "agent" {
+ writeError(w, http.StatusNotFound, "agent label not found")
+ return
+ }
+ if err := h.Queries.AttachLabelToAgent(r.Context(), db.AttachLabelToAgentParams{
+ AgentID: agent.ID, LabelID: labelID, WorkspaceID: agent.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to attach agent label")
+ return
+ }
+ h.publish(protocol.EventLabelUpdated, uuidToString(agent.WorkspaceID), "member", requestUserID(r), map[string]any{"label": labelToResponse(label)})
+ h.ListLabelsForAgent(w, r)
+}
+
+func (h *Handler) DetachLabelFromAgent(w http.ResponseWriter, r *http.Request) {
+ agent, ok := h.loadAgentForUser(w, r, chi.URLParam(r, "id"))
+ if !ok || !h.canManageAgent(w, r, agent) {
+ return
+ }
+ labelID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "labelId"), "label id")
+ if !ok {
+ return
+ }
+ if err := h.Queries.DetachLabelFromAgent(r.Context(), db.DetachLabelFromAgentParams{
+ AgentID: agent.ID, LabelID: labelID, WorkspaceID: agent.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to detach agent label")
+ return
+ }
+ h.publish(protocol.EventLabelUpdated, uuidToString(agent.WorkspaceID), "member", requestUserID(r), map[string]any{"label_id": uuidToString(labelID), "resource_type": "agent"})
+ h.ListLabelsForAgent(w, r)
+}
+
+func (h *Handler) ListLabelsForSkill(w http.ResponseWriter, r *http.Request) {
+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))
+ if !ok {
+ return
+ }
+ labels, err := h.Queries.ListLabelsBySkill(r.Context(), db.ListLabelsBySkillParams{
+ SkillID: skill.ID, WorkspaceID: skill.WorkspaceID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list skill labels")
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"labels": labelsToResponse(labels)})
+}
+
+func (h *Handler) AttachLabelToSkill(w http.ResponseWriter, r *http.Request) {
+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))
+ if !ok || !h.canManageSkill(w, r, skill) {
+ return
+ }
+ var req AttachLabelRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.LabelID == "" {
+ writeError(w, http.StatusBadRequest, "label_id is required")
+ return
+ }
+ labelID, ok := parseUUIDOrBadRequest(w, req.LabelID, "label_id")
+ if !ok {
+ return
+ }
+ label, err := h.Queries.GetLabel(r.Context(), db.GetLabelParams{ID: labelID, WorkspaceID: skill.WorkspaceID})
+ if err != nil || label.ResourceType != "skill" {
+ writeError(w, http.StatusNotFound, "skill label not found")
+ return
+ }
+ if err := h.Queries.AttachLabelToSkill(r.Context(), db.AttachLabelToSkillParams{
+ SkillID: skill.ID, LabelID: labelID, WorkspaceID: skill.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to attach skill label")
+ return
+ }
+ h.publish(protocol.EventLabelUpdated, uuidToString(skill.WorkspaceID), "member", requestUserID(r), map[string]any{"label": labelToResponse(label)})
+ h.ListLabelsForSkill(w, r)
+}
+
+func (h *Handler) DetachLabelFromSkill(w http.ResponseWriter, r *http.Request) {
+ skill, ok := h.loadSkillForUser(w, r, chi.URLParam(r, "id"))
+ if !ok || !h.canManageSkill(w, r, skill) {
+ return
+ }
+ labelID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "labelId"), "label id")
+ if !ok {
+ return
+ }
+ if err := h.Queries.DetachLabelFromSkill(r.Context(), db.DetachLabelFromSkillParams{
+ SkillID: skill.ID, LabelID: labelID, WorkspaceID: skill.WorkspaceID,
+ }); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to detach skill label")
+ return
+ }
+ h.publish(protocol.EventLabelUpdated, uuidToString(skill.WorkspaceID), "member", requestUserID(r), map[string]any{"label_id": uuidToString(labelID), "resource_type": "skill"})
+ h.ListLabelsForSkill(w, r)
+}
diff --git a/server/internal/handler/label_test.go b/server/internal/handler/label_test.go
index 8dbcb6a2bc..e385ba8bae 100644
--- a/server/internal/handler/label_test.go
+++ b/server/internal/handler/label_test.go
@@ -7,6 +7,8 @@ import (
"net/http/httptest"
"strings"
"testing"
+
+ "github.com/google/uuid"
)
// TestLabelCRUD exercises label create/list/get/update/delete.
@@ -196,6 +198,62 @@ func TestIssueLabelAttachDetach(t *testing.T) {
}
}
+func TestIssueLabelRejectsNonIssueScope(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Issue rejects agent label",
+ "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
+ if err := json.NewDecoder(w.Body).Decode(&issue); err != nil {
+ t.Fatalf("decode issue: %v", err)
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/labels", map[string]any{
+ "resource_type": "agent",
+ "name": "agent-only-" + uuid.NewString()[:8],
+ "color": "#3b82f6",
+ })
+ 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
+ if err := json.NewDecoder(w.Body).Decode(&label); err != nil {
+ t.Fatalf("decode label: %v", err)
+ }
+ t.Cleanup(func() {
+ w := httptest.NewRecorder()
+ req := newRequest("DELETE", "/api/labels/"+label.ID, nil)
+ req = withURLParam(req, "id", label.ID)
+ testHandler.DeleteLabel(w, req)
+ })
+
+ w = httptest.NewRecorder()
+ req = newRequest("POST", "/api/issues/"+issue.ID+"/labels", map[string]any{
+ "label_id": label.ID,
+ })
+ req = withURLParam(req, "id", issue.ID)
+ testHandler.AttachLabel(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("AttachLabel with agent label: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+
+ w = httptest.NewRecorder()
+ req = newRequest("DELETE", "/api/issues/"+issue.ID+"/labels/"+label.ID, nil)
+ req = withURLParams(req, "id", issue.ID, "labelId", label.ID)
+ testHandler.DetachLabel(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("DetachLabel with agent label: expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
// 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) {
@@ -439,6 +497,49 @@ func TestLabelNameAllowsEmoji(t *testing.T) {
})
}
+func TestLabelResourceTypesHaveIndependentNamespaces(t *testing.T) {
+ name := "shared-scope-label-" + uuid.NewString()[:8]
+ for _, resourceType := range []string{"issue", "agent", "skill"} {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "resource_type": resourceType,
+ "name": name,
+ "description": resourceType + " description",
+ "color": "#3b82f6",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateLabel resource_type=%s: expected 201, got %d: %s", resourceType, w.Code, w.Body.String())
+ }
+ var created LabelResponse
+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {
+ t.Fatalf("decode created label: %v", err)
+ }
+ if created.ResourceType != resourceType || created.Description != resourceType+" description" {
+ t.Fatalf("unexpected scoped label: %+v", 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)
+ })
+ }
+}
+
+func TestLabelRejectsUnknownResourceType(t *testing.T) {
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/labels", map[string]any{
+ "resource_type": "project",
+ "name": "invalid-scope",
+ "color": "#3b82f6",
+ })
+ testHandler.CreateLabel(w, req)
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
// 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 #).
diff --git a/server/migrations/162_resource_labels.down.sql b/server/migrations/162_resource_labels.down.sql
new file mode 100644
index 0000000000..d0d93b0526
--- /dev/null
+++ b/server/migrations/162_resource_labels.down.sql
@@ -0,0 +1,16 @@
+DROP TABLE IF EXISTS skill_to_label;
+DROP TABLE IF EXISTS agent_to_label;
+
+DROP INDEX IF EXISTS issue_label_workspace_type_idx;
+DROP INDEX IF EXISTS issue_label_workspace_type_name_lower_idx;
+
+-- The pre-162 schema can only represent issue labels. Resource-scoped rows
+-- must be removed before restoring its workspace-wide unique name index.
+DELETE FROM issue_label WHERE resource_type <> 'issue';
+
+ALTER TABLE issue_label
+ DROP COLUMN IF EXISTS description,
+ DROP COLUMN IF EXISTS resource_type;
+
+CREATE UNIQUE INDEX issue_label_workspace_name_lower_idx
+ ON issue_label (workspace_id, LOWER(name));
diff --git a/server/migrations/162_resource_labels.up.sql b/server/migrations/162_resource_labels.up.sql
new file mode 100644
index 0000000000..f3bb17e24f
--- /dev/null
+++ b/server/migrations/162_resource_labels.up.sql
@@ -0,0 +1,33 @@
+-- Generalise the existing issue-label catalog into three independent
+-- workspace namespaces. Existing rows remain issue labels; agent and skill
+-- labels use the same management primitives without sharing vocabulary.
+
+ALTER TABLE issue_label
+ ADD COLUMN resource_type TEXT NOT NULL DEFAULT 'issue'
+ CHECK (resource_type IN ('issue', 'agent', 'skill')),
+ ADD COLUMN description TEXT NOT NULL DEFAULT '';
+
+DROP INDEX IF EXISTS issue_label_workspace_name_lower_idx;
+
+CREATE UNIQUE INDEX issue_label_workspace_type_name_lower_idx
+ ON issue_label (workspace_id, resource_type, LOWER(name));
+
+CREATE INDEX issue_label_workspace_type_idx
+ ON issue_label (workspace_id, resource_type);
+
+CREATE TABLE agent_to_label (
+ agent_id UUID NOT NULL REFERENCES agent(id) ON DELETE CASCADE,
+ label_id UUID NOT NULL REFERENCES issue_label(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (agent_id, label_id)
+);
+
+CREATE TABLE skill_to_label (
+ skill_id UUID NOT NULL REFERENCES skill(id) ON DELETE CASCADE,
+ label_id UUID NOT NULL REFERENCES issue_label(id) ON DELETE CASCADE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (skill_id, label_id)
+);
+
+CREATE INDEX agent_to_label_label_idx ON agent_to_label(label_id);
+CREATE INDEX skill_to_label_label_idx ON skill_to_label(label_id);
diff --git a/server/pkg/db/generated/issue_label.sql.go b/server/pkg/db/generated/issue_label.sql.go
index ae2eb270c6..21a213a830 100644
--- a/server/pkg/db/generated/issue_label.sql.go
+++ b/server/pkg/db/generated/issue_label.sql.go
@@ -11,6 +11,34 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)
+const attachLabelToAgent = `-- name: AttachLabelToAgent :exec
+INSERT INTO agent_to_label (agent_id, label_id)
+SELECT $1::uuid, $2::uuid
+WHERE EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = $1::uuid
+ AND a.workspace_id = $3::uuid
+)
+AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = $2::uuid
+ AND l.workspace_id = $3::uuid
+ AND l.resource_type = 'agent'
+)
+ON CONFLICT DO NOTHING
+`
+
+type AttachLabelToAgentParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) AttachLabelToAgent(ctx context.Context, arg AttachLabelToAgentParams) error {
+ _, err := q.db.Exec(ctx, attachLabelToAgent, arg.AgentID, arg.LabelID, arg.WorkspaceID)
+ return err
+}
+
const attachLabelToIssue = `-- name: AttachLabelToIssue :exec
INSERT INTO issue_to_label (issue_id, label_id)
SELECT $1::uuid, $2::uuid
@@ -23,6 +51,7 @@ AND EXISTS (
SELECT 1 FROM issue_label l
WHERE l.id = $2::uuid
AND l.workspace_id = $3::uuid
+ AND l.resource_type = 'issue'
)
ON CONFLICT DO NOTHING
`
@@ -41,20 +70,56 @@ func (q *Queries) AttachLabelToIssue(ctx context.Context, arg AttachLabelToIssue
return err
}
+const attachLabelToSkill = `-- name: AttachLabelToSkill :exec
+INSERT INTO skill_to_label (skill_id, label_id)
+SELECT $1::uuid, $2::uuid
+WHERE EXISTS (
+ SELECT 1 FROM skill s
+ WHERE s.id = $1::uuid
+ AND s.workspace_id = $3::uuid
+)
+AND EXISTS (
+ SELECT 1 FROM issue_label l
+ WHERE l.id = $2::uuid
+ AND l.workspace_id = $3::uuid
+ AND l.resource_type = 'skill'
+)
+ON CONFLICT DO NOTHING
+`
+
+type AttachLabelToSkillParams struct {
+ SkillID pgtype.UUID `json:"skill_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) AttachLabelToSkill(ctx context.Context, arg AttachLabelToSkillParams) error {
+ _, err := q.db.Exec(ctx, attachLabelToSkill, arg.SkillID, 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
+INSERT INTO issue_label (workspace_id, resource_type, name, description, color)
+VALUES ($1, $2, $3, $4, $5)
+RETURNING id, workspace_id, name, color, created_at, updated_at, resource_type, description
`
type CreateLabelParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Name string `json:"name"`
- Color string `json:"color"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResourceType string `json:"resource_type"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ 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)
+ row := q.db.QueryRow(ctx, createLabel,
+ arg.WorkspaceID,
+ arg.ResourceType,
+ arg.Name,
+ arg.Description,
+ arg.Color,
+ )
var i IssueLabel
err := row.Scan(
&i.ID,
@@ -63,6 +128,8 @@ func (q *Queries) CreateLabel(ctx context.Context, arg CreateLabelParams) (Issue
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
)
return i, err
}
@@ -87,6 +154,28 @@ func (q *Queries) DeleteLabel(ctx context.Context, arg DeleteLabelParams) (pgtyp
return id, err
}
+const detachLabelFromAgent = `-- name: DetachLabelFromAgent :exec
+DELETE FROM agent_to_label
+WHERE agent_id = $1::uuid
+ AND label_id = $2::uuid
+ AND EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = $1::uuid
+ AND a.workspace_id = $3::uuid
+ )
+`
+
+type DetachLabelFromAgentParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) DetachLabelFromAgent(ctx context.Context, arg DetachLabelFromAgentParams) error {
+ _, err := q.db.Exec(ctx, detachLabelFromAgent, arg.AgentID, arg.LabelID, arg.WorkspaceID)
+ return err
+}
+
const detachLabelFromIssue = `-- name: DetachLabelFromIssue :exec
DELETE FROM issue_to_label
WHERE issue_id = $1::uuid
@@ -111,8 +200,30 @@ func (q *Queries) DetachLabelFromIssue(ctx context.Context, arg DetachLabelFromI
return err
}
+const detachLabelFromSkill = `-- name: DetachLabelFromSkill :exec
+DELETE FROM skill_to_label
+WHERE skill_id = $1::uuid
+ AND label_id = $2::uuid
+ AND EXISTS (
+ SELECT 1 FROM skill s
+ WHERE s.id = $1::uuid
+ AND s.workspace_id = $3::uuid
+ )
+`
+
+type DetachLabelFromSkillParams struct {
+ SkillID pgtype.UUID `json:"skill_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) DetachLabelFromSkill(ctx context.Context, arg DetachLabelFromSkillParams) error {
+ _, err := q.db.Exec(ctx, detachLabelFromSkill, arg.SkillID, arg.LabelID, arg.WorkspaceID)
+ return err
+}
+
const getLabel = `-- name: GetLabel :one
-SELECT id, workspace_id, name, color, created_at, updated_at FROM issue_label
+SELECT id, workspace_id, name, color, created_at, updated_at, resource_type, description FROM issue_label
WHERE id = $1 AND workspace_id = $2
`
@@ -131,18 +242,90 @@ func (q *Queries) GetLabel(ctx context.Context, arg GetLabelParams) (IssueLabel,
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
)
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
+SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description,
+ CASE l.resource_type
+ WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id)
+ WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
+ WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
+ ELSE 0
+ END::bigint AS usage_count
+FROM issue_label l
+WHERE l.workspace_id = $1::uuid
+ AND l.resource_type = $2::text
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)
+type ListLabelsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResourceType string `json:"resource_type"`
+}
+
+type ListLabelsRow struct {
+ 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"`
+ ResourceType string `json:"resource_type"`
+ Description string `json:"description"`
+ UsageCount int64 `json:"usage_count"`
+}
+
+func (q *Queries) ListLabels(ctx context.Context, arg ListLabelsParams) ([]ListLabelsRow, error) {
+ rows, err := q.db.Query(ctx, listLabels, arg.WorkspaceID, arg.ResourceType)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListLabelsRow{}
+ for rows.Next() {
+ var i ListLabelsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
+ &i.UsageCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLabelsByAgent = `-- name: ListLabelsByAgent :many
+SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
+FROM issue_label l
+JOIN agent_to_label atl ON atl.label_id = l.id
+WHERE atl.agent_id = $1::uuid
+ AND l.workspace_id = $2::uuid
+ AND l.resource_type = 'agent'
+ORDER BY LOWER(l.name) ASC
+`
+
+type ListLabelsByAgentParams struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListLabelsByAgent(ctx context.Context, arg ListLabelsByAgentParams) ([]IssueLabel, error) {
+ rows, err := q.db.Query(ctx, listLabelsByAgent, arg.AgentID, arg.WorkspaceID)
if err != nil {
return nil, err
}
@@ -157,6 +340,8 @@ func (q *Queries) ListLabels(ctx context.Context, workspaceID pgtype.UUID) ([]Is
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
); err != nil {
return nil, err
}
@@ -169,11 +354,12 @@ func (q *Queries) ListLabels(ctx context.Context, workspaceID pgtype.UUID) ([]Is
}
const listLabelsByIssue = `-- name: ListLabelsByIssue :many
-SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at
+SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
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
+ AND l.resource_type = 'issue'
ORDER BY LOWER(l.name) ASC
`
@@ -200,6 +386,109 @@ func (q *Queries) ListLabelsByIssue(ctx context.Context, arg ListLabelsByIssuePa
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLabelsBySkill = `-- name: ListLabelsBySkill :many
+SELECT l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
+FROM issue_label l
+JOIN skill_to_label stl ON stl.label_id = l.id
+WHERE stl.skill_id = $1::uuid
+ AND l.workspace_id = $2::uuid
+ AND l.resource_type = 'skill'
+ORDER BY LOWER(l.name) ASC
+`
+
+type ListLabelsBySkillParams struct {
+ SkillID pgtype.UUID `json:"skill_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) ListLabelsBySkill(ctx context.Context, arg ListLabelsBySkillParams) ([]IssueLabel, error) {
+ rows, err := q.db.Query(ctx, listLabelsBySkill, arg.SkillID, 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,
+ &i.ResourceType,
+ &i.Description,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLabelsForAgents = `-- name: ListLabelsForAgents :many
+SELECT atl.agent_id, l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
+FROM issue_label l
+JOIN agent_to_label atl ON atl.label_id = l.id
+WHERE atl.agent_id = ANY($1::uuid[])
+ AND l.workspace_id = $2::uuid
+ AND l.resource_type = 'agent'
+ORDER BY atl.agent_id, LOWER(l.name) ASC
+`
+
+type ListLabelsForAgentsParams struct {
+ AgentIds []pgtype.UUID `json:"agent_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+type ListLabelsForAgentsRow struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ 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"`
+ ResourceType string `json:"resource_type"`
+ Description string `json:"description"`
+}
+
+func (q *Queries) ListLabelsForAgents(ctx context.Context, arg ListLabelsForAgentsParams) ([]ListLabelsForAgentsRow, error) {
+ rows, err := q.db.Query(ctx, listLabelsForAgents, arg.AgentIds, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListLabelsForAgentsRow{}
+ for rows.Next() {
+ var i ListLabelsForAgentsRow
+ if err := rows.Scan(
+ &i.AgentID,
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
); err != nil {
return nil, err
}
@@ -212,11 +501,12 @@ func (q *Queries) ListLabelsByIssue(ctx context.Context, arg ListLabelsByIssuePa
}
const listLabelsForIssues = `-- name: ListLabelsForIssues :many
-SELECT il.issue_id, l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at
+SELECT il.issue_id, l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
FROM issue_label l
JOIN issue_to_label il ON il.label_id = l.id
WHERE il.issue_id = ANY($1::uuid[])
AND l.workspace_id = $2::uuid
+ AND l.resource_type = 'issue'
ORDER BY il.issue_id, LOWER(l.name) ASC
`
@@ -226,13 +516,15 @@ type ListLabelsForIssuesParams struct {
}
type ListLabelsForIssuesRow struct {
- IssueID pgtype.UUID `json:"issue_id"`
- 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"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ 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"`
+ ResourceType string `json:"resource_type"`
+ Description string `json:"description"`
}
// Bulk variant: fetch labels for many issues in one round-trip so the issue
@@ -255,6 +547,65 @@ func (q *Queries) ListLabelsForIssues(ctx context.Context, arg ListLabelsForIssu
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listLabelsForSkills = `-- name: ListLabelsForSkills :many
+SELECT stl.skill_id, l.id, l.workspace_id, l.name, l.color, l.created_at, l.updated_at, l.resource_type, l.description
+FROM issue_label l
+JOIN skill_to_label stl ON stl.label_id = l.id
+WHERE stl.skill_id = ANY($1::uuid[])
+ AND l.workspace_id = $2::uuid
+ AND l.resource_type = 'skill'
+ORDER BY stl.skill_id, LOWER(l.name) ASC
+`
+
+type ListLabelsForSkillsParams struct {
+ SkillIds []pgtype.UUID `json:"skill_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+type ListLabelsForSkillsRow struct {
+ SkillID pgtype.UUID `json:"skill_id"`
+ 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"`
+ ResourceType string `json:"resource_type"`
+ Description string `json:"description"`
+}
+
+func (q *Queries) ListLabelsForSkills(ctx context.Context, arg ListLabelsForSkillsParams) ([]ListLabelsForSkillsRow, error) {
+ rows, err := q.db.Query(ctx, listLabelsForSkills, arg.SkillIds, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListLabelsForSkillsRow{}
+ for rows.Next() {
+ var i ListLabelsForSkillsRow
+ if err := rows.Scan(
+ &i.SkillID,
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Color,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
); err != nil {
return nil, err
}
@@ -269,16 +620,18 @@ func (q *Queries) ListLabelsForIssues(ctx context.Context, arg ListLabelsForIssu
const updateLabel = `-- name: UpdateLabel :one
UPDATE issue_label SET
name = COALESCE($3, name),
- color = COALESCE($4, color),
+ description = COALESCE($4, description),
+ color = COALESCE($5, color),
updated_at = now()
WHERE id = $1 AND workspace_id = $2
-RETURNING id, workspace_id, name, color, created_at, updated_at
+RETURNING id, workspace_id, name, color, created_at, updated_at, resource_type, description
`
type UpdateLabelParams struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
Name pgtype.Text `json:"name"`
+ Description pgtype.Text `json:"description"`
Color pgtype.Text `json:"color"`
}
@@ -287,6 +640,7 @@ func (q *Queries) UpdateLabel(ctx context.Context, arg UpdateLabelParams) (Issue
arg.ID,
arg.WorkspaceID,
arg.Name,
+ arg.Description,
arg.Color,
)
var i IssueLabel
@@ -297,6 +651,8 @@ func (q *Queries) UpdateLabel(ctx context.Context, arg UpdateLabelParams) (Issue
&i.Color,
&i.CreatedAt,
&i.UpdatedAt,
+ &i.ResourceType,
+ &i.Description,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 37f4199978..15d84f447b 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -131,6 +131,12 @@ type AgentTaskQueue struct {
ChatInputTaskID pgtype.UUID `json:"chat_input_task_id"`
}
+type AgentToLabel struct {
+ AgentID pgtype.UUID `json:"agent_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type Attachment struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
@@ -536,12 +542,14 @@ 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"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ 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"`
+ ResourceType string `json:"resource_type"`
+ Description string `json:"description"`
}
type IssuePullRequest struct {
@@ -757,6 +765,12 @@ type SkillFile struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type SkillToLabel struct {
+ SkillID pgtype.UUID `json:"skill_id"`
+ LabelID pgtype.UUID `json:"label_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type Squad struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
diff --git a/server/pkg/db/queries/issue_label.sql b/server/pkg/db/queries/issue_label.sql
index 0469c02476..b975112082 100644
--- a/server/pkg/db/queries/issue_label.sql
+++ b/server/pkg/db/queries/issue_label.sql
@@ -1,6 +1,14 @@
-- name: ListLabels :many
-SELECT * FROM issue_label
-WHERE workspace_id = $1
+SELECT l.*,
+ CASE l.resource_type
+ WHEN 'issue' THEN (SELECT COUNT(*) FROM issue_to_label x WHERE x.label_id = l.id)
+ WHEN 'agent' THEN (SELECT COUNT(*) FROM agent_to_label x WHERE x.label_id = l.id)
+ WHEN 'skill' THEN (SELECT COUNT(*) FROM skill_to_label x WHERE x.label_id = l.id)
+ ELSE 0
+ END::bigint AS usage_count
+FROM issue_label l
+WHERE l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = sqlc.arg('resource_type')::text
ORDER BY LOWER(name) ASC;
-- name: GetLabel :one
@@ -8,13 +16,14 @@ 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)
+INSERT INTO issue_label (workspace_id, resource_type, name, description, color)
+VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: UpdateLabel :one
UPDATE issue_label SET
name = COALESCE(sqlc.narg('name'), name),
+ description = COALESCE(sqlc.narg('description'), description),
color = COALESCE(sqlc.narg('color'), color),
updated_at = now()
WHERE id = $1 AND workspace_id = $2
@@ -42,6 +51,7 @@ 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
+ AND l.resource_type = 'issue'
)
ON CONFLICT DO NOTHING;
@@ -65,6 +75,7 @@ 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
+ AND l.resource_type = 'issue'
ORDER BY LOWER(l.name) ASC;
-- name: ListLabelsForIssues :many
@@ -76,4 +87,93 @@ FROM issue_label l
JOIN issue_to_label il ON il.label_id = l.id
WHERE il.issue_id = ANY(sqlc.arg('issue_ids')::uuid[])
AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'issue'
ORDER BY il.issue_id, LOWER(l.name) ASC;
+
+-- name: ListLabelsByAgent :many
+SELECT l.*
+FROM issue_label l
+JOIN agent_to_label atl ON atl.label_id = l.id
+WHERE atl.agent_id = sqlc.arg('agent_id')::uuid
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'agent'
+ORDER BY LOWER(l.name) ASC;
+
+-- name: ListLabelsForAgents :many
+SELECT atl.agent_id, l.*
+FROM issue_label l
+JOIN agent_to_label atl ON atl.label_id = l.id
+WHERE atl.agent_id = ANY(sqlc.arg('agent_ids')::uuid[])
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'agent'
+ORDER BY atl.agent_id, LOWER(l.name) ASC;
+
+-- name: AttachLabelToAgent :exec
+INSERT INTO agent_to_label (agent_id, label_id)
+SELECT sqlc.arg('agent_id')::uuid, sqlc.arg('label_id')::uuid
+WHERE EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = sqlc.arg('agent_id')::uuid
+ AND a.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
+ AND l.resource_type = 'agent'
+)
+ON CONFLICT DO NOTHING;
+
+-- name: DetachLabelFromAgent :exec
+DELETE FROM agent_to_label
+WHERE agent_id = sqlc.arg('agent_id')::uuid
+ AND label_id = sqlc.arg('label_id')::uuid
+ AND EXISTS (
+ SELECT 1 FROM agent a
+ WHERE a.id = sqlc.arg('agent_id')::uuid
+ AND a.workspace_id = sqlc.arg('workspace_id')::uuid
+ );
+
+-- name: ListLabelsBySkill :many
+SELECT l.*
+FROM issue_label l
+JOIN skill_to_label stl ON stl.label_id = l.id
+WHERE stl.skill_id = sqlc.arg('skill_id')::uuid
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'skill'
+ORDER BY LOWER(l.name) ASC;
+
+-- name: ListLabelsForSkills :many
+SELECT stl.skill_id, l.*
+FROM issue_label l
+JOIN skill_to_label stl ON stl.label_id = l.id
+WHERE stl.skill_id = ANY(sqlc.arg('skill_ids')::uuid[])
+ AND l.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND l.resource_type = 'skill'
+ORDER BY stl.skill_id, LOWER(l.name) ASC;
+
+-- name: AttachLabelToSkill :exec
+INSERT INTO skill_to_label (skill_id, label_id)
+SELECT sqlc.arg('skill_id')::uuid, sqlc.arg('label_id')::uuid
+WHERE EXISTS (
+ SELECT 1 FROM skill s
+ WHERE s.id = sqlc.arg('skill_id')::uuid
+ AND s.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
+ AND l.resource_type = 'skill'
+)
+ON CONFLICT DO NOTHING;
+
+-- name: DetachLabelFromSkill :exec
+DELETE FROM skill_to_label
+WHERE skill_id = sqlc.arg('skill_id')::uuid
+ AND label_id = sqlc.arg('label_id')::uuid
+ AND EXISTS (
+ SELECT 1 FROM skill s
+ WHERE s.id = sqlc.arg('skill_id')::uuid
+ AND s.workspace_id = sqlc.arg('workspace_id')::uuid
+ );