Skip to content

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

Go

feat: custom issue properties — typed workspace-defined fields with list-surface support (MUL-4463) (#5335)

Jiayuan Zhangb85bb71a582e
diff --git a/apps/mobile/data/schemas.ts b/apps/mobile/data/schemas.ts
index 370879d457..6a7c7536ba 100644
--- a/apps/mobile/data/schemas.ts
+++ b/apps/mobile/data/schemas.ts
@@ -693,6 +693,7 @@ export const EMPTY_ISSUE_FALLBACK: import("@multica/core/types").Issue = {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "",
updated_at: "",
};
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 7c962b6fc5..c075626985 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -86,6 +86,12 @@ import type {
UpdateProjectResourceRequest,
ListProjectResourcesResponse,
Label,
+ IssueProperty,
+ IssuePropertyValue,
+ CreatePropertyRequest,
+ UpdatePropertyRequest,
+ ListPropertiesResponse,
+ IssuePropertiesResponse,
CreateLabelRequest,
UpdateLabelRequest,
ListLabelsResponse,
@@ -234,6 +240,12 @@ import {
EMPTY_INBOX_UNREAD_SUMMARY,
LabelSchema,
ListLabelsResponseSchema,
+ IssuePropertySchema,
+ ListPropertiesResponseSchema,
+ IssuePropertiesResponseSchema,
+ EMPTY_ISSUE_PROPERTY,
+ EMPTY_LIST_PROPERTIES_RESPONSE,
+ EMPTY_ISSUE_PROPERTIES_RESPONSE,
ResourceLabelsResponseSchema,
EMPTY_LABEL,
EMPTY_LIST_LABELS_RESPONSE,
@@ -552,6 +564,9 @@ export class ApiClient {
if (params?.metadata && Object.keys(params.metadata).length > 0) {
search.set("metadata", JSON.stringify(params.metadata));
}
+ if (params?.properties && Object.keys(params.properties).length > 0) {
+ search.set("properties", JSON.stringify(params.properties));
+ }
if (params?.open_only) search.set("open_only", "true");
if (params?.scheduled) search.set("scheduled", "true");
if (params?.date_field) search.set("date_field", params.date_field);
@@ -582,6 +597,9 @@ export class ApiClient {
if (params.metadata && Object.keys(params.metadata).length > 0) {
search.set("metadata", JSON.stringify(params.metadata));
}
+ if (params.properties && Object.keys(params.properties).length > 0) {
+ search.set("properties", JSON.stringify(params.properties));
+ }
if (params.assignee_filters?.length) {
search.set("assignee_filters", params.assignee_filters.map((f) => `${f.type}:${f.id}`).join(","));
}
@@ -2150,6 +2168,67 @@ export class ApiClient {
await this.fetch(`/api/labels/${id}`, { method: "DELETE" });
}
+ // Custom issue properties
+ async listProperties(includeArchived = false): Promise<ListPropertiesResponse> {
+ const suffix = includeArchived ? "?include_archived=true" : "";
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>(`/api/properties${suffix}`);
+ } catch (error) {
+ // A backend predating custom properties 404s here (e.g. after a
+ // server-only rollback). Treat it as an empty catalog: the property
+ // UI sections disappear and the active-catalog reconciliation strips
+ // persisted property sorts/filters, so no property params ever reach
+ // the old server. Other errors keep normal query-error semantics.
+ if (error instanceof Error && "status" in error && (error as { status?: number }).status === 404) {
+ return EMPTY_LIST_PROPERTIES_RESPONSE;
+ }
+ throw error;
+ }
+ return parseWithFallback(raw, ListPropertiesResponseSchema, EMPTY_LIST_PROPERTIES_RESPONSE, {
+ endpoint: "GET /api/properties",
+ });
+ }
+
+ async createProperty(data: CreatePropertyRequest): Promise<IssueProperty> {
+ const raw = await this.fetch<unknown>(`/api/properties`, {
+ method: "POST",
+ body: JSON.stringify(data),
+ });
+ return parseWithFallback(raw, IssuePropertySchema, EMPTY_ISSUE_PROPERTY, {
+ endpoint: "POST /api/properties",
+ });
+ }
+
+ async updateProperty(id: string, data: UpdatePropertyRequest): Promise<IssueProperty> {
+ const raw = await this.fetch<unknown>(`/api/properties/${id}`, {
+ method: "PATCH",
+ body: JSON.stringify(data),
+ });
+ return parseWithFallback(raw, IssuePropertySchema, EMPTY_ISSUE_PROPERTY, {
+ endpoint: "PATCH /api/properties/{id}",
+ });
+ }
+
+ async setIssueProperty(issueId: string, propertyId: string, value: IssuePropertyValue): Promise<IssuePropertiesResponse> {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/properties/${propertyId}`, {
+ method: "PUT",
+ body: JSON.stringify({ value }),
+ });
+ return parseWithFallback(raw, IssuePropertiesResponseSchema, EMPTY_ISSUE_PROPERTIES_RESPONSE, {
+ endpoint: "PUT /api/issues/{id}/properties/{propertyId}",
+ });
+ }
+
+ async unsetIssueProperty(issueId: string, propertyId: string): Promise<IssuePropertiesResponse> {
+ const raw = await this.fetch<unknown>(`/api/issues/${issueId}/properties/${propertyId}`, {
+ method: "DELETE",
+ });
+ return parseWithFallback(raw, IssuePropertiesResponseSchema, EMPTY_ISSUE_PROPERTIES_RESPONSE, {
+ endpoint: "DELETE /api/issues/{id}/properties/{propertyId}",
+ });
+ }
+
async listLabelsForIssue(issueId: string): Promise<IssueLabelsResponse> {
const raw = await this.fetch<unknown>(`/api/issues/${issueId}/labels`);
return parseWithFallback(raw, ResourceLabelsResponseSchema, EMPTY_RESOURCE_LABELS_RESPONSE, {
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index d2bb4116b9..046ab176ee 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -19,6 +19,7 @@ import {
InboxUnreadSummarySchema,
IssueTriggerPreviewSchema,
ListIssuesResponseSchema,
+ ListPropertiesResponseSchema,
SearchProjectsResponseSchema,
RuntimeHourlyActivityListSchema,
RuntimeUsageByAgentListSchema,
@@ -101,6 +102,90 @@ describe("IssueSchema (via ListIssuesResponseSchema)", () => {
const parsed = ListIssuesResponseSchema.parse(payload);
expect(parsed.issues[0]?.stage).toBeNull();
});
+
+ it("accepts custom property values including multi_select arrays", () => {
+ const payload = {
+ issues: [
+ {
+ ...baseIssue,
+ properties: { "def-1": "opt-a", "def-2": ["opt-x", "opt-y"], "def-3": 3.5, "def-4": true },
+ },
+ ],
+ total: 1,
+ };
+ const parsed = ListIssuesResponseSchema.parse(payload);
+ expect(parsed.issues[0]?.properties).toEqual({
+ "def-1": "opt-a",
+ "def-2": ["opt-x", "opt-y"],
+ "def-3": 3.5,
+ "def-4": true,
+ });
+ });
+
+ it("defaults properties to {} when the server omits it (older backend)", () => {
+ const parsed = ListIssuesResponseSchema.parse({ issues: [baseIssue], total: 1 });
+ expect(parsed.issues[0]?.properties).toEqual({});
+ });
+
+ it("drops unknown-shaped property values instead of failing the issue parse", () => {
+ // Forward compat: a future server type (actor/relation) may ship object
+ // values. That one entry must disappear; the issue and its other
+ // properties must survive — a full parse failure would blank the whole
+ // list through parseWithFallback on installed desktop builds.
+ const payload = {
+ issues: [
+ {
+ ...baseIssue,
+ properties: { "def-1": { nested: 1 }, "def-2": "opt-a" },
+ },
+ ],
+ total: 1,
+ };
+ const parsed = ListIssuesResponseSchema.parse(payload);
+ expect(parsed.issues[0]?.properties).toEqual({ "def-2": "opt-a" });
+ });
+});
+
+describe("IssuePropertySchema (via ListPropertiesResponseSchema)", () => {
+ const baseProperty = {
+ id: "22222222-2222-2222-2222-222222222222",
+ workspace_id: "ws-1",
+ name: "Severity",
+ type: "select",
+ description: "",
+ config: { options: [{ id: "opt-1", name: "Critical", color: "#ef4444" }] },
+ position: 1,
+ archived: false,
+ archived_at: null,
+ usage_count: 2,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ };
+
+ it("parses a full definition", () => {
+ const parsed = ListPropertiesResponseSchema.parse({ properties: [baseProperty], total: 1 });
+ expect(parsed.properties[0]?.config.options?.[0]?.name).toBe("Critical");
+ });
+
+ it("survives a malformed response by defaulting the list", () => {
+ const parsed = ListPropertiesResponseSchema.parse({});
+ expect(parsed.properties).toEqual([]);
+ expect(parsed.total).toBe(0);
+ });
+
+ it("keeps unknown property types as strings (forward compat)", () => {
+ const parsed = ListPropertiesResponseSchema.parse({
+ properties: [{ ...baseProperty, type: "relation", config: {} }],
+ total: 1,
+ });
+ expect(parsed.properties[0]?.type).toBe("relation");
+ });
+
+ it("defaults config when the server sends none", () => {
+ const { config: _omit, ...withoutConfig } = baseProperty;
+ const parsed = ListPropertiesResponseSchema.parse({ properties: [withoutConfig], total: 1 });
+ expect(parsed.properties[0]?.config).toEqual({});
+ });
});
// POST /api/issues/preview-trigger feeds this schema through parseWithFallback
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f286d2f674..3162b530f7 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -20,6 +20,9 @@ import type {
GroupedIssuesResponse,
InboxWorkspaceUnread,
Label,
+ IssueProperty,
+ ListPropertiesResponse,
+ IssuePropertiesResponse,
ListIssuesResponse,
ListLabelsResponse,
ListWebhookDeliveriesResponse,
@@ -79,6 +82,83 @@ export const EMPTY_RESOURCE_LABELS_RESPONSE: ResourceLabelsResponse = {
labels: [],
};
+// Custom property definitions. `type` stays a lenient string so newer server
+// types don't break installed clients; UI narrows with isKnownPropertyType.
+export const IssuePropertySchema = z.object({
+ id: z.string(),
+ workspace_id: z.string(),
+ name: z.string(),
+ type: z.string(),
+ description: z.string().optional().default(""),
+ config: z.object({
+ options: z.array(z.object({
+ id: z.string(),
+ name: z.string(),
+ color: z.string().optional().default("#6b7280"),
+ }).loose()).optional(),
+ }).loose().default({}),
+ position: z.number().optional().default(0),
+ archived: z.boolean().optional().default(false),
+ archived_at: z.string().nullable().optional(),
+ usage_count: z.number().optional().default(0),
+ created_at: z.string(),
+ updated_at: z.string(),
+}).loose();
+
+export const EMPTY_ISSUE_PROPERTY: IssueProperty = {
+ id: "",
+ workspace_id: "",
+ name: "",
+ type: "text",
+ description: "",
+ config: {},
+ position: 0,
+ archived: false,
+ usage_count: 0,
+ created_at: "",
+ updated_at: "",
+};
+
+export const ListPropertiesResponseSchema = z.object({
+ properties: z.array(IssuePropertySchema).default([]),
+ total: z.number().default(0),
+}).loose();
+
+export const EMPTY_LIST_PROPERTIES_RESPONSE: ListPropertiesResponse = {
+ properties: [],
+ total: 0,
+};
+
+// Value bag: keyed by definition UUID; values are primitives or string
+// arrays (multi_select). The preprocess step drops entries with unknown
+// shapes BEFORE validation — a newer server shipping an object-shaped value
+// (future actor/relation types) must degrade to "that one property missing",
+// never fail the whole IssueSchema and blank the list via parseWithFallback.
+export const IssuePropertyValuesSchema = z.preprocess(
+ (raw) => {
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
+ const out: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(raw)) {
+ const ok =
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ (Array.isArray(value) && value.every((item) => typeof item === "string"));
+ if (ok) out[key] = value;
+ }
+ return out;
+ },
+ z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).default({}),
+);
+
+export const IssuePropertiesResponseSchema = z.object({
+ properties: IssuePropertyValuesSchema,
+}).loose();
+
+export const EMPTY_ISSUE_PROPERTIES_RESPONSE: IssuePropertiesResponse = {
+ properties: {},
+};
+
export interface AppConfigResponse {
cdn_domain: string;
// True when the CDN domain serves private content via time-bounded signed
@@ -360,6 +440,9 @@ export const IssueSchema = z.object({
start_date: z.string().nullable(),
due_date: z.string().nullable(),
metadata: IssueMetadataSchema,
+ // Older backends predate custom properties; default {} so consumers never
+ // nil-guard issue.properties.
+ properties: IssuePropertyValuesSchema,
reactions: z.array(z.unknown()).optional(),
labels: z.array(z.unknown()).optional(),
created_at: z.string(),
diff --git a/packages/core/issues/batch.test.ts b/packages/core/issues/batch.test.ts
index 93326b0349..0df8ee9de8 100644
--- a/packages/core/issues/batch.test.ts
+++ b/packages/core/issues/batch.test.ts
@@ -23,6 +23,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...overrides,
diff --git a/packages/core/issues/cache-coordinator.test.ts b/packages/core/issues/cache-coordinator.test.ts
index 437dced5f3..6e105c6959 100644
--- a/packages/core/issues/cache-coordinator.test.ts
+++ b/packages/core/issues/cache-coordinator.test.ts
@@ -48,6 +48,7 @@ function makeIssue(idx: number, overrides: Partial<Issue> = {}): Issue {
due_date: null,
labels: [],
metadata: {},
+ properties: {},
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
...overrides,
diff --git a/packages/core/issues/cache-helpers.test.ts b/packages/core/issues/cache-helpers.test.ts
index c09f272411..c4f23ebf40 100644
--- a/packages/core/issues/cache-helpers.test.ts
+++ b/packages/core/issues/cache-helpers.test.ts
@@ -25,6 +25,7 @@ function mk(id: string, status: Issue["status"], position: number): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
labels: [],
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index 5b73b95004..4e599f5b2c 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -59,6 +59,7 @@ function makeIssue(idx: number, overrides: Partial<Issue> = {}): Issue {
due_date: null,
labels: [],
metadata: {},
+ properties: {},
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
...overrides,
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 361b4ce657..7068b479ba 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -317,7 +317,13 @@ export function useUpdateIssue() {
// out false unless the server coerced a different value, so this pass
// is the plain surgical patch it always was.
const { suppress_run: _suppressRun, handoff_note: _handoffNote, id: _id, ...intent } = vars;
- const reconcile = applyIssueChange(qc, wsId, serverIssue.id, serverIssue, {
+ // Drop `properties` from the reconcile payload: the bag is owned by the
+ // property mutation pipeline (single-key atomic writes + its own
+ // optimistic state). An UpdateIssue snapshot taken before a concurrent
+ // property write resolves would otherwise overwrite the newer bag
+ // (clean-room review F3 response-ordering race).
+ const { properties: _staleBag, ...reconcilable } = serverIssue;
+ const reconcile = applyIssueChange(qc, wsId, serverIssue.id, reconcilable as typeof serverIssue, {
changed: issueChangedDims(intent, serverIssue),
baseIssue: serverIssue,
});
diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.ts
index 27dd7b6fc6..bd0448375f 100644
--- a/packages/core/issues/queries.test.ts
+++ b/packages/core/issues/queries.test.ts
@@ -44,6 +44,7 @@ function makeIssue(idx: number): Issue {
due_date: null,
labels: [],
metadata: {},
+ properties: {},
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
};
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index ef19cf4b45..52eefa9352 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -16,6 +16,10 @@ export interface IssueSortParam {
date_field?: ListIssuesParams["date_field"];
date_start?: ListIssuesParams["date_start"];
date_end?: ListIssuesParams["date_end"];
+ /** Server-side custom-property filter (definition id → accepted values).
+ * Lives in the sort/window bag so every list surface, query key, and
+ * load-more page carries it automatically. */
+ properties?: ListIssuesParams["properties"];
}
export const issueKeys = {
@@ -186,6 +190,57 @@ async function fetchFirstPages(filter: MyIssuesFilter = {}, sort?: IssueSortPara
* total — pagination on the "All" scope is out of scope; the first
* 50-per-status × 3 widening (deduped) is what the page renders.
*/
+const MERGE_PRIORITY_RANK: Record<string, number> = { urgent: 0, high: 1, medium: 2, low: 3, none: 4 };
+
+/**
+ * Comparator mirroring the server's ORDER BY semantics (including
+ * `property:<id>` sorts and missing-values-last). The merged "All" scope
+ * concatenates three independently-ordered queries, so without a re-sort the
+ * relation order (assigned → created → involves) would override the sort the
+ * user picked — e.g. assigned=9 rendering before created=1 (review round 3).
+ */
+function compareIssuesForSort(a: Issue, b: Issue, sort?: IssueSortParam): number {
+ const by = sort?.sort_by ?? "position";
+ const dir = by !== "position" && sort?.sort_direction === "desc" ? -1 : 1;
+ const tieBreak = () =>
+ new Date(b.created_at).getTime() - new Date(a.created_at).getTime(); // created_at DESC, server parity
+
+ const missingAware = (av: string | null, bv: string | null): number => {
+ if (!av && !bv) return tieBreak();
+ if (!av) return 1;
+ if (!bv) return -1;
+ return dir * av.localeCompare(bv) || tieBreak();
+ };
+
+ if (by.startsWith("property:")) {
+ const propertyId = by.slice("property:".length);
+ const av = a.properties?.[propertyId];
+ const bv = b.properties?.[propertyId];
+ const aMissing = av === undefined || Array.isArray(av) || typeof av === "boolean";
+ const bMissing = bv === undefined || Array.isArray(bv) || typeof bv === "boolean";
+ if (aMissing && bMissing) return tieBreak();
+ if (aMissing) return 1;
+ if (bMissing) return -1;
+ if (typeof av === "number" && typeof bv === "number") return dir * (av - bv) || tieBreak();
+ return dir * String(av).localeCompare(String(bv)) || tieBreak();
+ }
+ switch (by) {
+ case "priority":
+ return dir * ((MERGE_PRIORITY_RANK[a.priority] ?? 9) - (MERGE_PRIORITY_RANK[b.priority] ?? 9)) || tieBreak();
+ case "title":
+ return dir * a.title.localeCompare(b.title) || tieBreak();
+ case "created_at":
+ return dir * (new Date(a.created_at).getTime() - new Date(b.created_at).getTime());
+ case "start_date":
+ return missingAware(a.start_date, b.start_date);
+ case "due_date":
+ return missingAware(a.due_date, b.due_date);
+ case "position":
+ default:
+ return a.position - b.position || tieBreak();
+ }
+}
+
async function fetchAllMyFirstPages(userId: string, sort?: IssueSortParam): Promise<ListIssuesCache> {
const [byAssignee, byCreator, byInvolves] = await Promise.all([
fetchFirstPages({ assignee_id: userId }, sort),
@@ -205,6 +260,7 @@ async function fetchAllMyFirstPages(userId: string, sort?: IssueSortParam): Prom
merged.push(issue);
}
}
+ merged.sort((a, b) => compareIssuesForSort(a, b, sort));
byStatus[status] = { issues: merged, total: merged.length };
}
return { byStatus };
@@ -262,7 +318,11 @@ async function fetchAllMyAssigneeGroups(
existing.total = existing.issues.length;
}
}
- return { groups: [...merged.values()] };
+ const groups = [...merged.values()];
+ for (const group of groups) {
+ group.issues.sort((a, b) => compareIssuesForSort(a, b, sort));
+ }
+ return { groups };
}
/**
diff --git a/packages/core/issues/stores/view-store.ts b/packages/core/issues/stores/view-store.ts
index b4c4f0b561..7a7e2298e6 100644
--- a/packages/core/issues/stores/view-store.ts
+++ b/packages/core/issues/stores/view-store.ts
@@ -11,9 +11,21 @@ import { defaultStorage } from "../../platform/storage";
export type ViewMode = "board" | "list" | "gantt" | "swimlane";
export type GanttZoom = "day" | "week" | "month";
-export type IssueGrouping = "status" | "assignee";
+/**
+ * Board grouping. Besides the two built-ins, a select-type custom property
+ * groups columns by its options via the `property:<definitionId>` form.
+ * Persisted values may reference a since-archived definition — consumers must
+ * fall back to "status" when the definition can't be resolved.
+ */
+export type IssueGrouping = "status" | "assignee" | `property:${string}`;
export type SwimlaneGrouping = "parent" | "project" | "assignee";
-export type SortField = "position" | "priority" | "start_date" | "due_date" | "created_at" | "title";
+/**
+ * Sort key. `property:<definitionId>` sorts client-side by a custom property
+ * value (number/date types); the server sort param only understands the
+ * static fields, so property sorts fall back to `position` server-side and
+ * re-sort in the surface data hook.
+ */
+export type SortField = "position" | "priority" | "start_date" | "due_date" | "created_at" | "title" | `property:${string}`;
export type SortDirection = "asc" | "desc";
export type IssueDateField = "created_at" | "updated_at";
@@ -41,7 +53,16 @@ export interface ActorFilterValue {
id: string;
}
-export const SORT_OPTIONS: { value: SortField; label: string }[] = [
+export const PROPERTY_VIEW_PREFIX = "property:";
+
+export function propertyIdFromViewKey(key: string): string | null {
+ return key.startsWith(PROPERTY_VIEW_PREFIX) ? key.slice(PROPERTY_VIEW_PREFIX.length) : null;
+}
+
+export type StaticSortField = Exclude<SortField, `property:${string}`>;
+export type StaticIssueGrouping = Exclude<IssueGrouping, `property:${string}`>;
+
+export const SORT_OPTIONS: { value: StaticSortField; label: string }[] = [
{ value: "position", label: "Manual" },
{ value: "priority", label: "Priority" },
{ value: "start_date", label: "Start date" },
@@ -50,7 +71,7 @@ export const SORT_OPTIONS: { value: SortField; label: string }[] = [
{ value: "title", label: "Title" },
];
-export const GROUPING_OPTIONS: { value: IssueGrouping; label: string }[] = [
+export const GROUPING_OPTIONS: { value: StaticIssueGrouping; label: string }[] = [
{ value: "status", label: "Status" },
{ value: "assignee", label: "Assignee" },
];
@@ -77,6 +98,13 @@ export interface IssueViewState {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
+ /**
+ * Custom-property filters: definition id → selected option ids (checkbox
+ * definitions use the pseudo-options "true"/"false"). Empty array = no
+ * filter for that definition; matching is OR within a definition and AND
+ * across definitions, mirroring the other filter groups.
+ */
+ propertyFilters: Record<string, string[]>;
dateFilter: IssueDateFilter | null;
// When true, the list only shows issues that currently have at least one
// agent task in `running` status. Drives the workspace "agents working"
@@ -87,6 +115,8 @@ export interface IssueViewState {
sortBy: SortField;
sortDirection: SortDirection;
cardProperties: CardProperties;
+ /** Custom property definition ids whose values render on board/list cards. */
+ cardPropertyIds: string[];
// When false, issues that have a parent (sub-issues) are hidden from the
// board / list / swimlane so users can focus on top-level parent issues.
// Purely a display filter — it never touches the parent/child relationship.
@@ -115,6 +145,7 @@ export interface IssueViewState {
toggleProjectFilter: (projectId: string) => void;
toggleNoProject: () => void;
toggleLabelFilter: (labelId: string) => void;
+ togglePropertyFilter: (propertyId: string, optionId: string) => void;
setDateFilter: (filter: IssueDateFilter | null) => void;
toggleAgentRunningFilter: () => void;
hideStatus: (status: IssueStatus) => void;
@@ -123,6 +154,7 @@ export interface IssueViewState {
setSortBy: (field: SortField) => void;
setSortDirection: (dir: SortDirection) => void;
toggleCardProperty: (key: keyof CardProperties) => void;
+ toggleCardPropertyId: (propertyId: string) => void;
toggleShowSubIssues: () => void;
toggleListCollapsed: (status: IssueStatus) => void;
setSwimlaneGrouping: (grouping: SwimlaneGrouping) => void;
@@ -143,6 +175,7 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
projectFilters: [],
includeNoProject: false,
labelFilters: [],
+ propertyFilters: {},
dateFilter: null,
agentRunningFilter: false,
sortBy: "position",
@@ -157,6 +190,7 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
childProgress: true,
labels: true,
},
+ cardPropertyIds: [],
showSubIssues: true,
listCollapsedStatuses: [],
ganttZoom: "week",
@@ -224,6 +258,17 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
? state.labelFilters.filter((id) => id !== labelId)
: [...state.labelFilters, labelId],
})),
+ togglePropertyFilter: (propertyId, optionId) =>
+ set((state) => {
+ const current = state.propertyFilters[propertyId] ?? [];
+ const next = current.includes(optionId)
+ ? current.filter((id) => id !== optionId)
+ : [...current, optionId];
+ const propertyFilters = { ...state.propertyFilters };
+ if (next.length === 0) delete propertyFilters[propertyId];
+ else propertyFilters[propertyId] = next;
+ return { propertyFilters };
+ }),
setDateFilter: (filter) => set({ dateFilter: filter }),
toggleAgentRunningFilter: () =>
set((state) => ({ agentRunningFilter: !state.agentRunningFilter })),
@@ -253,6 +298,7 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
projectFilters: [],
includeNoProject: false,
labelFilters: [],
+ propertyFilters: {},
dateFilter: null,
agentRunningFilter: false,
}),
@@ -265,6 +311,12 @@ export const viewStoreSlice = (set: StoreApi<IssueViewState>["setState"]): Issue
[key]: !state.cardProperties[key],
},
})),
+ toggleCardPropertyId: (propertyId) =>
+ set((state) => ({
+ cardPropertyIds: state.cardPropertyIds.includes(propertyId)
+ ? state.cardPropertyIds.filter((id) => id !== propertyId)
+ : [...state.cardPropertyIds, propertyId],
+ })),
toggleShowSubIssues: () =>
set((state) => ({ showSubIssues: !state.showSubIssues })),
toggleListCollapsed: (status) =>
@@ -311,9 +363,11 @@ export const viewStorePersistOptions = (name: string) => ({
projectFilters: state.projectFilters,
includeNoProject: state.includeNoProject,
labelFilters: state.labelFilters,
+ propertyFilters: state.propertyFilters,
sortBy: state.sortBy,
sortDirection: state.sortDirection,
cardProperties: state.cardProperties,
+ cardPropertyIds: state.cardPropertyIds,
showSubIssues: state.showSubIssues,
listCollapsedStatuses: state.listCollapsedStatuses,
ganttZoom: state.ganttZoom,
diff --git a/packages/core/issues/surface/membership.test.ts b/packages/core/issues/surface/membership.test.ts
index e707475798..19f3fd2a8c 100644
--- a/packages/core/issues/surface/membership.test.ts
+++ b/packages/core/issues/surface/membership.test.ts
@@ -28,6 +28,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
due_date: null,
labels: [],
metadata: {},
+ properties: {},
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
...overrides,
diff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.ts
index 9a66a88259..1bb4364807 100644
--- a/packages/core/issues/ws-updaters.test.ts
+++ b/packages/core/issues/ws-updaters.test.ts
@@ -76,6 +76,7 @@ const baseIssue: Issue = {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
labels: [labelA],
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.ts
index 004e1a613d..4e2856d670 100644
--- a/packages/core/issues/ws-updaters.ts
+++ b/packages/core/issues/ws-updaters.ts
@@ -13,7 +13,7 @@ import {
patchIssueInBuckets,
} from "./cache-helpers";
import { cleanupDeletedIssueCaches } from "./delete-cache";
-import type { Issue, IssueLabelsResponse, IssueMetadata, Label } from "../types";
+import type { Issue, IssueLabelsResponse, IssueMetadata, IssuePropertyValues, Label } from "../types";
import type { ListIssuesCache } from "../types";
export function onIssueCreated(
@@ -205,6 +205,60 @@ export function onIssueMetadataChanged(
qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
}
+/**
+ * Apply a custom-property bag snapshot to the issue detail + list caches.
+ * Mirrors onIssueMetadataChanged: the server emits the FULL post-mutation
+ * bag on every single-key write, so we replace rather than merge. Also used
+ * directly by the useSetIssueProperty/useUnsetIssueProperty optimistic path.
+ */
+export function onIssuePropertiesChanged(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ properties: IssuePropertyValues,
+) {
+ for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (data) qc.setQueryData<ListIssuesCache>(key, patchIssueInBuckets(data, issueId, { properties }));
+ }
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issueId), (old) =>
+ old ? { ...old, properties } : old,
+ );
+ qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });
+ // Plain assignee-group caches are never patched in place (their bucket
+ // shape differs) and would otherwise hold stale chips forever under
+ // staleTime:Infinity (clean-room review F2).
+ qc.invalidateQueries({ queryKey: issueKeys.assigneeGroupsAll(wsId) });
+ qc.invalidateQueries({ queryKey: issueKeys.myAssigneeGroupsAll(wsId) });
+ invalidatePropertyWindowQueries(qc, wsId);
+}
+
+/**
+ * Refetch every issue window whose SERVER-side shape depends on property
+ * values: queries filtered by `properties` or sorted by `property:<id>`.
+ * In-place patching keeps them stale under staleTime:Infinity — a value
+ * edit can change an issue's page membership and ordering, and grouped
+ * caches never self-heal (review round 3). Windows without property params
+ * keep the cheap in-place patch above.
+ */
+export function invalidatePropertyWindowQueries(qc: QueryClient, wsId: string) {
+ qc.invalidateQueries({
+ queryKey: issueKeys.all(wsId),
+ predicate: (query) =>
+ query.queryKey.some((part) => {
+ if (!part || typeof part !== "object" || Array.isArray(part)) return false;
+ const rec = part as Record<string, unknown>;
+ if (
+ rec.properties &&
+ typeof rec.properties === "object" &&
+ Object.keys(rec.properties as Record<string, unknown>).length > 0
+ ) {
+ return true;
+ }
+ return typeof rec.sort_by === "string" && rec.sort_by.startsWith("property:");
+ }),
+ });
+}
+
export function onIssueDeleted(
qc: QueryClient,
wsId: string,
diff --git a/packages/core/package.json b/packages/core/package.json
index a8f6ffecc8..3fa25b646f 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -75,6 +75,9 @@
"./labels": "./labels/index.ts",
"./labels/queries": "./labels/queries.ts",
"./labels/mutations": "./labels/mutations.ts",
+ "./properties": "./properties/index.ts",
+ "./properties/queries": "./properties/queries.ts",
+ "./properties/mutations": "./properties/mutations.ts",
"./autopilots": "./autopilots/index.ts",
"./autopilots/queries": "./autopilots/queries.ts",
"./autopilots/mutations": "./autopilots/mutations.ts",
diff --git a/packages/core/properties/index.ts b/packages/core/properties/index.ts
new file mode 100644
index 0000000000..1354c1797f
--- /dev/null
+++ b/packages/core/properties/index.ts
@@ -0,0 +1,7 @@
+export { propertyKeys, propertyListOptions } from "./queries";
+export {
+ useCreateProperty,
+ useUpdateProperty,
+ useSetIssueProperty,
+ useUnsetIssueProperty,
+} from "./mutations";
diff --git a/packages/core/properties/mutations.ts b/packages/core/properties/mutations.ts
new file mode 100644
index 0000000000..04ef1c3d1d
--- /dev/null
+++ b/packages/core/properties/mutations.ts
@@ -0,0 +1,181 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import { propertyKeys } from "./queries";
+import { useWorkspaceId } from "../hooks";
+import { issueKeys } from "../issues/queries";
+import { invalidatePropertyWindowQueries, onIssuePropertiesChanged } from "../issues/ws-updaters";
+import { findIssueLocation } from "../issues/cache-helpers";
+import type {
+ CreatePropertyRequest,
+ UpdatePropertyRequest,
+ Issue,
+ IssuePropertyValue,
+ IssuePropertyValues,
+ ListIssuesCache,
+} from "../types";
+
+export function useCreateProperty() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: (data: CreatePropertyRequest) => api.createProperty(data),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ },
+ });
+}
+
+/**
+ * Definition updates (rename, options, archive). No optimistic patch: edits
+ * happen in the settings dialog where a round-trip is acceptable, and config
+ * canonicalization (option id assignment) is server-side anyway.
+ */
+export function useUpdateProperty() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ id, ...data }: { id: string } & UpdatePropertyRequest) =>
+ api.updateProperty(id, data),
+ onSettled: () => {
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ // Issue caches embed the value bag; a definition change (rename,
+ // option edits) changes how values render, and rows referencing an
+ // archived definition must drop out of "+ Add property" menus.
+ qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
+ },
+ });
+}
+
+/**
+ * Read the issue's current property bag from whichever cache holds it: the
+ * detail cache first, then any list cache bucket. Board/list surfaces never
+ * populate the detail cache, so stopping there would make the optimistic
+ * merge below overwrite the whole bag with a single key.
+ */
+function readIssueProperties(qc: ReturnType<typeof useQueryClient>, wsId: string, issueId: string): IssuePropertyValues | undefined {
+ const detail = qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId));
+ if (detail) return detail.properties ?? {};
+ for (const [, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {
+ if (!data) continue;
+ const location = findIssueLocation(data, issueId);
+ if (location) return location.issue.properties ?? {};
+ }
+ return undefined;
+}
+
+
+/**
+ * Optimistic single-property write on an issue.
+ *
+ * Concurrency contract (MUL-4463 review round 1/2):
+ * - Mutations for the SAME issue serialize via TanStack's mutation
+ * `scope`, so full-bag responses cannot land out of order and rapid
+ * multi-select toggles cannot interleave.
+ * - The optimistic patch merges into the bag read from ANY cache
+ * (detail or list) — never replaces it — so board-only surfaces keep
+ * the issue's other property values.
+ * - Failure restores the snapshot; if no snapshot existed, it falls back
+ * to invalidation.
+ * - The LAST settled mutation for the issue does an authoritative
+ * invalidate of the detail cache plus the definition catalog (usage
+ * counts), reconciling any raced WS snapshots under staleTime:Infinity.
+ */
+export function useSetIssueProperty() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ issueId, propertyId, value }: { issueId: string; propertyId: string; value: IssuePropertyValue }) =>
+ api.setIssueProperty(issueId, propertyId, value),
+ scope: { id: `issue-properties:${wsId}` },
+ mutationKey: ["issue-properties", wsId],
+ onMutate: async ({ issueId, propertyId, value }) => {
+ // Cancel in-flight list refetches too: a response snapshotted before
+ // this write would land after the optimistic patch and revert it.
+ await Promise.all([
+ qc.cancelQueries({ queryKey: issueKeys.detail(wsId, issueId) }),
+ qc.cancelQueries({ queryKey: issueKeys.list(wsId) }),
+ ]);
+ const prev = readIssueProperties(qc, wsId, issueId);
+ onIssuePropertiesChanged(qc, wsId, issueId, { ...(prev ?? {}), [propertyId]: value });
+ return { prevValue: prev?.[propertyId], hadBag: prev !== undefined, issueId, propertyId };
+ },
+ onError: (_err, _vars, ctx) => {
+ if (!ctx) return;
+ rollbackSingleKey(qc, wsId, ctx);
+ },
+ onSuccess: (data, { issueId }) => {
+ onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {});
+ },
+ onSettled: (_data, _err, { issueId }) => {
+ settleIssuePropertyCaches(qc, wsId, issueId);
+ },
+ });
+}
+
+export function useUnsetIssueProperty() {
+ const qc = useQueryClient();
+ const wsId = useWorkspaceId();
+ return useMutation({
+ mutationFn: ({ issueId, propertyId }: { issueId: string; propertyId: string }) =>
+ api.unsetIssueProperty(issueId, propertyId),
+ scope: { id: `issue-properties:${wsId}` },
+ mutationKey: ["issue-properties", wsId],
+ onMutate: async ({ issueId, propertyId }) => {
+ await Promise.all([
+ qc.cancelQueries({ queryKey: issueKeys.detail(wsId, issueId) }),
+ qc.cancelQueries({ queryKey: issueKeys.list(wsId) }),
+ ]);
+ const prev = readIssueProperties(qc, wsId, issueId);
+ if (prev) {
+ const next = { ...prev };
+ delete next[propertyId];
+ onIssuePropertiesChanged(qc, wsId, issueId, next);
+ }
+ return { prevValue: prev?.[propertyId], hadBag: prev !== undefined, issueId, propertyId };
+ },
+ onError: (_err, _vars, ctx) => {
+ if (!ctx) return;
+ rollbackSingleKey(qc, wsId, ctx);
+ },
+ onSuccess: (data, { issueId }) => {
+ onIssuePropertiesChanged(qc, wsId, issueId, data.properties ?? {});
+ },
+ onSettled: (_data, _err, { issueId }) => {
+ settleIssuePropertyCaches(qc, wsId, issueId);
+ },
+ });
+}
+
+/**
+ * Roll back exactly the key this mutation touched, against the CURRENT bag.
+ * Restoring the whole onMutate snapshot would erase concurrent remote writes
+ * to other keys that landed via WS while this request was in flight
+ * (clean-room review F2 interleave B).
+ */
+function rollbackSingleKey(
+ qc: ReturnType<typeof useQueryClient>,
+ wsId: string,
+ ctx: { prevValue: IssuePropertyValue | undefined; hadBag: boolean; issueId: string; propertyId: string },
+) {
+ if (!ctx.hadBag) {
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, ctx.issueId) });
+ return;
+ }
+ const current = readIssueProperties(qc, wsId, ctx.issueId) ?? {};
+ const next = { ...current };
+ if (ctx.prevValue === undefined) delete next[ctx.propertyId];
+ else next[ctx.propertyId] = ctx.prevValue;
+ onIssuePropertiesChanged(qc, wsId, ctx.issueId, next);
+}
+
+/** Authoritative reconcile once the LAST in-flight property write settles. */
+function settleIssuePropertyCaches(qc: ReturnType<typeof useQueryClient>, wsId: string, issueId: string) {
+ if (qc.isMutating({ mutationKey: ["issue-properties", wsId] }) > 1) return;
+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ // Server-filtered/-sorted windows must refetch: the write may have moved
+ // this issue across pages or reordered it (onIssuePropertiesChanged
+ // already fires this for the WS path; local mutations need it on settle
+ // because the self-emitted WS event may be suppressed or raced).
+ invalidatePropertyWindowQueries(qc, wsId);
+}
diff --git a/packages/core/properties/queries.ts b/packages/core/properties/queries.ts
new file mode 100644
index 0000000000..2e42b24c05
--- /dev/null
+++ b/packages/core/properties/queries.ts
@@ -0,0 +1,16 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+export const propertyKeys = {
+ all: (wsId: string) => ["properties", wsId] as const,
+ list: (wsId: string, includeArchived = false) =>
+ [...propertyKeys.all(wsId), "list", includeArchived] as const,
+};
+
+export function propertyListOptions(wsId: string, includeArchived = false) {
+ return queryOptions({
+ queryKey: propertyKeys.list(wsId, includeArchived),
+ queryFn: () => api.listProperties(includeArchived),
+ select: (data) => data.properties,
+ });
+}
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index 612de3584c..a282a9d2e5 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -108,9 +108,10 @@ describe("useRealtimeSync — ws instance change", () => {
rerender({ ws: ws2 });
// Should have called invalidateQueries for all workspace-scoped keys
- // (15 workspace-scoped + 6 per-issue prefixes + 5 per-chat prefixes
- // + 1 workspaceKeys.list() + 1 cross-workspace inbox unread summary = 28 calls)
- expect(invalidateSpy).toHaveBeenCalledTimes(28);
+ // (16 workspace-scoped [incl. property definitions] + 6 per-issue
+ // prefixes + 5 per-chat prefixes + 1 workspaceKeys.list() + 1
+ // cross-workspace inbox unread summary = 29 calls)
+ expect(invalidateSpy).toHaveBeenCalledTimes(29);
});
it("does not re-invalidate when rerendered with the same ws instance", () => {
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 3bb1692fc8..ad7c100a02 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -15,6 +15,7 @@ import { pinKeys } from "../pins/queries";
import { autopilotKeys } from "../autopilots/queries";
import { runtimeKeys } from "../runtimes/queries";
import { labelKeys } from "../labels/queries";
+import { propertyKeys } from "../properties/queries";
import {
agentTaskSnapshotKeys,
agentActivityKeys,
@@ -29,6 +30,7 @@ import {
onIssueUpdated,
onIssueDeleted,
onIssueLabelsChanged,
+ onIssuePropertiesChanged,
onIssueMetadataChanged,
} from "../issues/ws-updaters";
import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";
@@ -57,6 +59,7 @@ import type {
IssueDeletedPayload,
IssueLabelsChangedPayload,
IssueMetadataChangedPayload,
+ IssuePropertiesChangedPayload,
InboxNewPayload,
InboxItem,
NotificationPreferenceResponse,
@@ -494,6 +497,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
qc.invalidateQueries({ queryKey: agentRunCountsKeys.all(wsId) });
qc.invalidateQueries({ queryKey: chatKeys.all(wsId) });
qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
}
// Cross-workspace, so outside the wsId guard: a reconnect may have missed
// inbox events from any workspace, so re-pull the switcher-dot summary.
@@ -748,7 +752,7 @@ export function useRealtimeSync(
// Event types handled by specific handlers below -- skip generic refresh
const specificEvents = new Set([
"workspace:updated",
- "issue:updated", "issue:created", "issue:deleted", "issue_labels:changed", "issue_metadata:changed", "inbox:new",
+ "issue:updated", "issue:created", "issue:deleted", "issue_labels:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new",
"comment:created", "comment:updated", "comment:deleted",
"comment:resolved", "comment:unresolved",
"activity:created",
@@ -831,6 +835,28 @@ export function useRealtimeSync(
if (wsId) onIssueMetadataChanged(qc, wsId, issue_id, metadata ?? {});
});
+ const unsubIssuePropertiesChanged = ws.on("issue_properties:changed", (p) => {
+ const { issue_id, properties } = p as IssuePropertiesChangedPayload;
+ if (!issue_id) return;
+ const wsId = getCurrentWsId();
+ if (wsId) {
+ onIssuePropertiesChanged(qc, wsId, issue_id, properties ?? {});
+ // The catalog embeds per-definition usage counts; every value
+ // set/unset shifts them. The list is tiny, so a refetch beats
+ // trying to patch counts client-side.
+ qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ }
+ });
+
+ // Definition changes (create / rename / options / archive) — refetch the
+ // catalog; issue caches keep raw value bags so they stay valid.
+ const unsubPropertyChanged = ["property:created", "property:updated"].map((event) =>
+ ws.on(event as "property:created" | "property:updated", () => {
+ const wsId = getCurrentWsId();
+ if (wsId) qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
+ }),
+ );
+
const unsubInboxNew = ws.on("inbox:new", async (p) => {
const { item } = p as InboxNewPayload;
if (!item) return;
@@ -1332,6 +1358,8 @@ export function useRealtimeSync(
unsubIssueDeleted();
unsubIssueLabelsChanged();
unsubIssueMetadataChanged();
+ unsubIssuePropertiesChanged();
+ unsubPropertyChanged.forEach((unsub) => unsub());
unsubInboxNew();
unsubCommentCreated();
unsubCommentUpdated();
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 001c75e218..798779ab5e 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -100,6 +100,9 @@ export interface ListIssuesParams {
involves_user_id?: string;
/** JSONB containment filter on `issue.metadata`. AND across keys. */
metadata?: IssueMetadata;
+ /** Custom-property filter: definition id → accepted values (option ids or
+ * "true"/"false" for checkbox). OR within a definition, AND across. */
+ properties?: Record<string, string[]>;
open_only?: boolean;
/**
* Restrict the result to issues with at least one of `start_date` /
@@ -111,7 +114,7 @@ export interface ListIssuesParams {
date_field?: "created_at" | "updated_at";
date_start?: string;
date_end?: string;
- sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date";
+ sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date" | `property:${string}`;
sort_direction?: "asc" | "desc";
}
@@ -136,6 +139,9 @@ export interface ListGroupedIssuesParams {
involves_user_id?: string;
/** JSONB containment filter on `issue.metadata`. AND across keys. */
metadata?: IssueMetadata;
+ /** Custom-property filter: definition id → accepted values (option ids or
+ * "true"/"false" for checkbox). OR within a definition, AND across. */
+ properties?: Record<string, string[]>;
assignee_filters?: IssueActorRef[];
include_no_assignee?: boolean;
creator_filters?: IssueActorRef[];
@@ -147,7 +153,7 @@ export interface ListGroupedIssuesParams {
date_field?: "created_at" | "updated_at";
date_start?: string;
date_end?: string;
- sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date";
+ sort_by?: "position" | "priority" | "title" | "created_at" | "start_date" | "due_date" | `property:${string}`;
sort_direction?: "asc" | "desc";
}
diff --git a/packages/core/types/events.ts b/packages/core/types/events.ts
index bb0c0624da..5cf3e5cdf8 100644
--- a/packages/core/types/events.ts
+++ b/packages/core/types/events.ts
@@ -1,4 +1,5 @@
import type { Issue, IssueMetadata, IssueReaction } from "./issue";
+import type { IssueProperty, IssuePropertyValues } from "./property";
import type { Agent } from "./agent";
import type { InboxItem } from "./inbox";
import type { Comment, Reaction } from "./comment";
@@ -69,6 +70,9 @@ export type WSEventType =
| "label:deleted"
| "issue_labels:changed"
| "issue_metadata:changed"
+ | "issue_properties:changed"
+ | "property:created"
+ | "property:updated"
| "pin:created"
| "pin:deleted"
| "pin:reordered"
@@ -123,6 +127,15 @@ export interface IssueMetadataChangedPayload {
metadata: IssueMetadata;
}
+export interface IssuePropertiesChangedPayload {
+ issue_id: string;
+ properties: IssuePropertyValues;
+}
+
+export interface PropertyChangedPayload {
+ property: IssueProperty;
+}
+
export interface AgentStatusPayload {
agent: Agent;
}
@@ -446,6 +459,9 @@ export interface WSEventPayloadMap {
"issue:updated": IssueUpdatedPayload;
"issue:deleted": IssueDeletedPayload;
"issue_labels:changed": IssueLabelsChangedPayload;
+ "issue_properties:changed": IssuePropertiesChangedPayload;
+ "property:created": PropertyChangedPayload;
+ "property:updated": PropertyChangedPayload;
"issue_reaction:added": IssueReactionAddedPayload;
"issue_reaction:removed": IssueReactionRemovedPayload;
"comment:created": CommentCreatedPayload;
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 0714f228cb..a005696b26 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -73,6 +73,8 @@ export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } fr
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
export type { Label, LabelResourceType, CreateLabelRequest, UpdateLabelRequest, ListLabelsResponse, IssueLabelsResponse, ResourceLabelsResponse } from "./label";
+export type { IssueProperty, IssuePropertyType, IssuePropertyOption, IssuePropertyConfig, IssuePropertyValue, IssuePropertyValues, CreatePropertyRequest, UpdatePropertyRequest, ListPropertiesResponse, IssuePropertiesResponse } from "./property";
+export { ISSUE_PROPERTY_TYPES, isKnownPropertyType } from "./property";
export type {
TimelineEntry,
AssigneeFrequencyEntry,
diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.ts
index adc857aa5f..e5b64c0fb2 100644
--- a/packages/core/types/issue.ts
+++ b/packages/core/types/issue.ts
@@ -1,4 +1,5 @@
import type { Label } from "./label";
+import type { IssuePropertyValues } from "./property";
export type IssueStatus =
| "backlog"
@@ -58,6 +59,9 @@ export interface Issue {
start_date: string | null;
due_date: string | null;
metadata: IssueMetadata;
+ // Custom property values keyed by property definition id. Always present
+ // in responses (empty object when unset), mirroring `metadata`.
+ properties: IssuePropertyValues;
reactions?: IssueReaction[];
labels?: Label[];
created_at: string;
diff --git a/packages/core/types/property.ts b/packages/core/types/property.ts
new file mode 100644
index 0000000000..2b45b5a08f
--- /dev/null
+++ b/packages/core/types/property.ts
@@ -0,0 +1,86 @@
+/**
+ * Custom issue properties — workspace-defined, typed fields on issues
+ * (MUL-4463). Definitions live in a workspace catalog (managed by owner/admin
+ * only); values live on each issue in a bag keyed by definition id, so
+ * renames never touch issue rows.
+ *
+ * Values are typed per definition: select stores an option id, multi_select
+ * an array of option ids (config order), date a "YYYY-MM-DD" string, checkbox
+ * a boolean, number a number, text/url strings.
+ */
+export type IssuePropertyType =
+ | "text"
+ | "number"
+ | "select"
+ | "multi_select"
+ | "date"
+ | "checkbox"
+ | "url";
+
+export const ISSUE_PROPERTY_TYPES: IssuePropertyType[] = [
+ "text",
+ "number",
+ "select",
+ "multi_select",
+ "date",
+ "checkbox",
+ "url",
+];
+
+export function isKnownPropertyType(type: string): type is IssuePropertyType {
+ return (ISSUE_PROPERTY_TYPES as string[]).includes(type);
+}
+
+export interface IssuePropertyOption {
+ id: string;
+ name: string;
+ /** Normalized lowercase hex color, e.g. `#3b82f6`. */
+ color: string;
+}
+
+export interface IssuePropertyConfig {
+ options?: IssuePropertyOption[];
+}
+
+export interface IssueProperty {
+ id: string;
+ workspace_id: string;
+ name: string;
+ /** Lenient string: newer servers may ship types this client doesn't know. */
+ type: string;
+ description?: string;
+ config: IssuePropertyConfig;
+ position: number;
+ archived: boolean;
+ archived_at?: string | null;
+ usage_count?: number;
+ created_at: string;
+ updated_at: string;
+}
+
+export type IssuePropertyValue = string | number | boolean | string[];
+export type IssuePropertyValues = Record<string, IssuePropertyValue>;
+
+export interface CreatePropertyRequest {
+ name: string;
+ type: IssuePropertyType;
+ description?: string;
+ config?: IssuePropertyConfig;
+}
+
+export interface UpdatePropertyRequest {
+ name?: string;
+ description?: string;
+ config?: IssuePropertyConfig;
+ archived?: boolean;
+}
+
+export interface ListPropertiesResponse {
+ properties: IssueProperty[];
+ total: number;
+}
+
+/** Response of PUT/DELETE /api/issues/{id}/properties/{propertyId}: the full post-mutation bag. */
+export interface IssuePropertiesResponse {
+ properties: IssuePropertyValues;
+}
diff --git a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
index 4025c200bc..f8deac1746 100644
--- a/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.confirm.test.tsx
@@ -85,6 +85,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...overrides,
diff --git a/packages/views/issues/components/batch-action-toolbar.test.tsx b/packages/views/issues/components/batch-action-toolbar.test.tsx
index fed43cba28..498f2a6ce4 100644
--- a/packages/views/issues/components/batch-action-toolbar.test.tsx
+++ b/packages/views/issues/components/batch-action-toolbar.test.tsx
@@ -73,6 +73,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...overrides,
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 0ba600fde2..45942b7987 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -5,7 +5,11 @@ import { AppLink } from "../../navigation";
import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";
import type { AnimateLayoutChanges } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
-import type { Issue, Project, UpdateIssueRequest } from "@multica/core/types";
+import type { Issue, IssueProperty, Project, UpdateIssueRequest } from "@multica/core/types";
+import { useQuery } from "@tanstack/react-query";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { propertyListOptions } from "@multica/core/properties";
+import { CustomPropertyValueDisplay } from "./pickers/custom-property-picker";
import { formatDateOnly, isPastDateOnly } from "@multica/core/issues/date";
import { CalendarClock, CalendarDays } from "lucide-react";
import { ActorAvatar } from "../../common/actor-avatar";
@@ -66,6 +70,14 @@ export const BoardCardContent = memo(function BoardCardContent({
const { t } = useT("issues");
const timeAgo = useTimeAgo();
const storeProperties = useViewStore((s) => s.cardProperties);
+ const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
+ const cardWsId = useWorkspaceId();
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(cardWsId));
+ // Custom properties toggled on in Display options, in toggle order, only
+ // when this issue actually carries a value.
+ const cardCustomProperties = cardPropertyIds
+ .map((id) => workspaceProperties.find((p) => p.id === id))
+ .filter((p): p is IssueProperty => !!p && issue.properties?.[p.id] !== undefined);
const labels = issue.labels ?? [];
const surfaceActions = useIssueSurfaceActionsOptional();
@@ -189,8 +201,8 @@ export const BoardCardContent = memo(function BoardCardContent({
);
})()}
- {/* Chip row: project + labels */}
- {(showProject || showLabels) && (
+ {/* Chip row: project + labels + custom property values */}
+ {(showProject || showLabels || cardCustomProperties.length > 0) && (
<div className="mt-1.5 flex items-center gap-1.5 flex-wrap">
{showProject && (
<span className="inline-flex items-center gap-1 rounded-full bg-muted/60 px-1.5 py-0.5 text-[11px] text-muted-foreground max-w-[160px]">
@@ -201,6 +213,14 @@ export const BoardCardContent = memo(function BoardCardContent({
{showLabels && labels.map((label) => (
<LabelChip key={label.id} label={label} />
))}
+ {cardCustomProperties.map((property) => (
+ <span
+ key={property.id}
+ className="inline-flex max-w-[160px] items-center rounded-full bg-muted/60 px-1.5 py-0.5 text-[11px] text-muted-foreground"
+ >
+ <CustomPropertyValueDisplay property={property} value={issue.properties?.[property.id]} />
+ </span>
+ ))}
</div>
)}
diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsx
index be6f5f64c3..012b6b876f 100644
--- a/packages/views/issues/components/board-column.tsx
+++ b/packages/views/issues/components/board-column.tsx
@@ -41,6 +41,11 @@ export interface BoardColumnGroup {
status?: IssueStatus;
assigneeType?: IssueAssigneeType | null;
assigneeId?: string | null;
+ /** Set when the board is grouped by a select-type custom property. */
+ propertyId?: string;
+ /** Option id for this column; null = the "No value" column. */
+ propertyOptionId?: string | null;
+ propertyOptionColor?: string;
totalCount?: number;
createData?: IssueCreateDefaults;
}
@@ -188,6 +193,23 @@ function BoardGroupHeading({
return <StatusHeading status={group.status} count={count} />;
}
+ if (group.propertyId !== undefined) {
+ return (
+ <div className="flex min-w-0 items-center gap-2">
+ <span
+ className="size-2.5 shrink-0 rounded-full bg-muted-foreground/30"
+ style={group.propertyOptionColor ? { backgroundColor: group.propertyOptionColor } : undefined}
+ />
+ <span className="truncate text-sm font-medium" title={group.title}>
+ {group.title}
+ </span>
+ <span className="shrink-0 rounded-full bg-background px-1.5 py-0.5 text-[11px] font-medium tabular-nums text-muted-foreground">
+ {count}
+ </span>
+ </div>
+ );
+ }
+
const actorIcon =
group.assigneeType && group.assigneeId ? (
<ActorAvatar
diff --git a/packages/views/issues/components/board-view.tsx b/packages/views/issues/components/board-view.tsx
index 0de0278107..b747d389bd 100644
--- a/packages/views/issues/components/board-view.tsx
+++ b/packages/views/issues/components/board-view.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState, useCallback, useMemo, useEffect, useRef, memo } from "react";
+import { useQuery } from "@tanstack/react-query";
import {
DndContext,
DragOverlay,
@@ -13,15 +14,20 @@ import {
} from "@dnd-kit/core";
import type { QueryKey } from "@tanstack/react-query";
import { arrayMove } from "@dnd-kit/sortable";
+import { toast } from "sonner";
import type {
Issue,
IssueAssigneeGroup,
IssueStatus,
Project,
+ IssueProperty,
} from "@multica/core/types";
import { useLoadMoreByAssigneeGroup, useLoadMoreByStatus } from "@multica/core/issues/mutations";
import type { AssigneeGroupedIssuesFilter, IssueSortParam, MyIssuesFilter } from "@multica/core/issues/queries";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
+import { propertyListOptions, useSetIssueProperty, useUnsetIssueProperty } from "@multica/core/properties";
+import { useWorkspaceId } from "@multica/core/hooks";
import type { IssueGrouping } from "@multica/core/issues/stores/view-store";
import { useActorName } from "@multica/core/workspace/hooks";
import { BoardColumn, BOARD_CARD_WIDTH, type BoardColumnGroup } from "./board-column";
@@ -43,6 +49,7 @@ import {
insertIdByPosition,
issueMatchesGroup,
getMoveUpdates,
+ propertyGroupId,
} from "../utils/drag-utils";
function isStatusGroup(
@@ -57,6 +64,8 @@ function buildGroups(
grouping: IssueGrouping,
getActorName: (type: string, id: string) => string,
noAssigneeLabel: string,
+ groupingProperty: IssueProperty | null,
+ noValueLabel: string,
): BoardColumnGroup[] {
if (grouping === "status") {
return visibleStatuses.map((status) => ({
@@ -67,6 +76,28 @@ function buildGroups(
}));
}
+ // Select-property board: one column per option (definition order) plus a
+ // trailing "No value" column. Empty columns stay visible — they are drop
+ // targets for assigning the value.
+ if (groupingProperty) {
+ const columns: BoardColumnGroup[] = (groupingProperty.config.options ?? []).map(
+ (option) => ({
+ id: propertyGroupId(groupingProperty.id, option.id),
+ title: option.name,
+ propertyId: groupingProperty.id,
+ propertyOptionId: option.id,
+ propertyOptionColor: option.color,
+ }),
+ );
+ columns.push({
+ id: propertyGroupId(groupingProperty.id, null),
+ title: noValueLabel,
+ propertyId: groupingProperty.id,
+ propertyOptionId: null,
+ });
+ return columns;
+ }
+
const groups = new Map<string, BoardColumnGroup>();
for (const issue of issues) {
const id = assigneeGroupId(issue.assignee_type, issue.assignee_id);
@@ -151,11 +182,66 @@ export function BoardView({
onCreateIssue?: (defaults: IssueCreateDefaults) => void;
}) {
const { t } = useT("issues");
- const grouping = useViewStore((s) => s.grouping);
+ const storeGrouping = useViewStore((s) => s.grouping);
const sortBy = useViewStore((s) => s.sortBy);
+ const boardWsId = useWorkspaceId();
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(boardWsId));
+ const groupingPropertyId = propertyIdFromViewKey(storeGrouping);
+ const groupingProperty = groupingPropertyId
+ ? workspaceProperties.find((p) => p.id === groupingPropertyId && p.type === "select") ?? null
+ : null;
+ // A persisted `property:<id>` grouping whose definition is gone (archived,
+ // deleted, other workspace) falls back to status columns.
+ const grouping: IssueGrouping =
+ groupingPropertyId && !groupingProperty ? "status" : storeGrouping;
+ const groupingOptionIds = useMemo(
+ () =>
+ groupingProperty
+ ? new Set((groupingProperty.config.options ?? []).map((option) => option.id))
+ : undefined,
+ [groupingProperty],
+ );
+ const setIssuePropertyMutation = useSetIssueProperty();
+ const unsetIssuePropertyMutation = useUnsetIssueProperty();
+ const applyPropertyGroupValue = useCallback(
+ (group: BoardColumnGroup, issueId: string) => {
+ if (group.propertyId === undefined) return;
+ // Surface failures like status/assignee drags do (use-issue-surface-
+ // actions): the mutation rolls the card back, but without a toast the
+ // snap-back reads as a UI glitch instead of a rejected write.
+ const onError = (err: unknown) => {
+ toast.error(
+ err instanceof Error && err.message
+ ? err.message
+ : t(($) => $.page.move_failed),
+ );
+ };
+ if (group.propertyOptionId === null) {
+ unsetIssuePropertyMutation.mutate(
+ { issueId, propertyId: group.propertyId },
+ { onError },
+ );
+ } else if (group.propertyOptionId !== undefined) {
+ setIssuePropertyMutation.mutate(
+ {
+ issueId,
+ propertyId: group.propertyId,
+ value: group.propertyOptionId,
+ },
+ { onError },
+ );
+ }
+ },
+ [setIssuePropertyMutation, t, unsetIssuePropertyMutation],
+ );
const sortFieldKey = sortBy === "created_at" ? "created" : sortBy;
+ const sortPropertyId = propertyIdFromViewKey(sortBy);
const sortLabel = sortBy !== "position"
- ? t(($) => $.board.ordered_by, { field: t(($) => $.display[`sort_${sortFieldKey}` as keyof typeof $.display]) })
+ ? t(($) => $.board.ordered_by, {
+ field: sortPropertyId
+ ? workspaceProperties.find((p) => p.id === sortPropertyId)?.name ?? ""
+ : t(($) => $.display[`sort_${sortFieldKey}` as keyof typeof $.display]),
+ })
: null;
const { getActorName } = useActorName();
const myIssuesOpts = myIssuesScope
@@ -207,8 +293,10 @@ export function BoardView({
grouping,
getActorName,
t(($) => $.filters.no_assignee),
+ groupingProperty,
+ t(($) => $.board.no_value),
),
- [hydratedAssigneeGroups, issues, visibleStatuses, grouping, getActorName, t],
+ [hydratedAssigneeGroups, issues, visibleStatuses, grouping, getActorName, groupingProperty, t],
);
const groupIds = useMemo(
() => new Set(groups.map((group) => group.id)),
@@ -239,13 +327,13 @@ export function BoardView({
recentlyMovedRef,
settleVersion,
beginSettle,
- } = useDragSettle(() => buildColumns(groupedIssues, groups, grouping));
+ } = useDragSettle(() => buildColumns(groupedIssues, groups, grouping, groupingOptionIds));
useEffect(() => {
if (!isDraggingRef.current && !isSettlingRef.current) {
- setColumns(buildColumns(groupedIssues, groups, grouping));
+ setColumns(buildColumns(groupedIssues, groups, grouping, groupingOptionIds));
}
- }, [groupedIssues, groups, grouping, settleVersion, setColumns, isDraggingRef, isSettlingRef]);
+ }, [groupedIssues, groups, grouping, groupingOptionIds, settleVersion, setColumns, isDraggingRef, isSettlingRef]);
// --- Issue map ---
// Frozen during drag so BoardColumn/DraggableBoardCard props stay
@@ -310,7 +398,7 @@ export function BoardView({
setActiveIssue(null);
const resetColumns = () =>
- setColumns(buildColumns(groupedIssues, groups, grouping));
+ setColumns(buildColumns(groupedIssues, groups, grouping, groupingOptionIds));
if (!over) {
resetColumns();
@@ -381,6 +469,7 @@ export function BoardView({
return { ...prev, [activeCol]: fromIds, [overCol]: toIds };
});
onMoveIssue(activeId, getMoveUpdates(finalGroup, currentIssue.position), beginSettle());
+ applyPropertyGroupValue(finalGroup, activeId);
return;
}
@@ -402,8 +491,9 @@ export function BoardView({
// on error (onError restored the snapshot). Without it a failed move would
// strand the card at the drop target, since onSettled no longer refetches.
onMoveIssue(activeId, getMoveUpdates(finalGroup, newPosition), beginSettle());
+ applyPropertyGroupValue(finalGroup, activeId);
},
- [groupedIssues, groups, grouping, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns],
+ [groupedIssues, groups, grouping, groupingOptionIds, onMoveIssue, groupIds, groupMap, sortBy, beginSettle, columnsRef, isDraggingRef, setColumns, applyPropertyGroupValue],
);
return (
@@ -469,6 +559,14 @@ export function BoardView({
)
)}
+ {groupingProperty && (
+ <PropertyBoardPoolLoader
+ statuses={visibleStatuses}
+ myIssuesOpts={myIssuesOpts}
+ sort={sort}
+ />
+ )}
+
{grouping === "status" && hiddenStatuses.length > 0 && (
<BoardHiddenColumnsPanel
hiddenStatuses={hiddenStatuses}
@@ -607,6 +705,46 @@ const PaginatedBoardColumn = memo(function PaginatedBoardColumn({
* free of `useLoadMoreByStatus` / `myIssuesOpts` coupling — the swimlane
* uses an in-memory total instead.
*/
+/**
+ * The property-grouped board derives its columns from the status-bucketed
+ * pool, which pages per status. Property columns have no per-column
+ * pagination yet (tracked in MUL-4493), so this strip keeps every issue
+ * REACHABLE: one sentinel per status that still has server rows loads the
+ * pool further and the property columns re-derive. Without it, rows beyond
+ * a status's loaded page silently never join any column (review round 3).
+ */
+function PropertyBoardPoolLoader({
+ statuses,
+ myIssuesOpts,
+ sort,
+}: {
+ statuses: IssueStatus[];
+ myIssuesOpts?: { scope: string; filter: MyIssuesFilter };
+ sort?: IssueSortParam;
+}) {
+ return (
+ <div className="col-span-full flex justify-center py-1">
+ {statuses.map((status) => (
+ <PropertyBoardPoolSentinel key={status} status={status} myIssuesOpts={myIssuesOpts} sort={sort} />
+ ))}
+ </div>
+ );
+}
+
+function PropertyBoardPoolSentinel({
+ status,
+ myIssuesOpts,
+ sort,
+}: {
+ status: IssueStatus;
+ myIssuesOpts?: { scope: string; filter: MyIssuesFilter };
+ sort?: IssueSortParam;
+}) {
+ const { loadMore, hasMore, isLoading } = useLoadMoreByStatus(status, myIssuesOpts, sort);
+ if (!hasMore) return null;
+ return <InfiniteScrollSentinel onVisible={loadMore} loading={isLoading} />;
+}
+
function BoardHiddenColumnRow({
status,
myIssuesOpts,
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 00ac4ded8a..9e60e445f5 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -427,6 +427,7 @@ const mockIssue: Issue = {
start_date: null,
due_date: "2026-06-01T00:00:00Z",
metadata: {},
+ properties: {},
created_at: "2026-01-15T00:00:00Z",
updated_at: "2026-01-20T00:00:00Z",
};
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index d27ac0316f..0942dd9cb0 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -20,6 +20,7 @@ import {
Pin,
PinOff,
Plus,
+ SlidersHorizontal,
Tag,
Unlink,
Users,
@@ -52,6 +53,7 @@ import { useUpdateIssue } from "@multica/core/issues/mutations";
import { toast } from "sonner";
import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, StagePicker, StartDatePicker, DueDatePicker, AssigneePicker, LabelPicker } from ".";
import { maxSiblingStage } from "./pickers/stage-picker";
+import { CustomPropertyValueEditor } from "./pickers/custom-property-picker";
import { IssueActionsDropdown, useIssueActions } from "../actions";
import { ProjectPicker } from "../../projects/components/project-picker";
import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";
@@ -74,6 +76,7 @@ import { issueListOptions, issueDetailOptions, childIssuesOptions, issueUsageOpt
import { projectDetailOptions } from "@multica/core/projects/queries";
import { ProjectIcon } from "../../projects/components/project-icon";
import { issueLabelsOptions } from "@multica/core/labels";
+import { propertyListOptions } from "@multica/core/properties";
import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";
import {
selectExpandedResolved,
@@ -765,6 +768,10 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const [visibleOptionalProps, setVisibleOptionalProps] = useState<Set<OptionalPropKey>>(
() => new Set(),
);
+ // Same progressive-disclosure machinery for custom properties, keyed by
+ // property definition id instead of a static key union.
+ const [visibleCustomProps, setVisibleCustomProps] = useState<Set<string>>(() => new Set());
+ const [autoOpenCustomProp, setAutoOpenCustomProp] = useState<string | null>(null);
// Optional property to auto-open as soon as it's mounted (the user just
// picked it from "+ Add property" and we want them dropped straight into
// edit state). Consumed by the row that matches this key, cleared after.
@@ -1334,6 +1341,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const { data: attachedLabels = [] } = useQuery(issueLabelsOptions(wsId, id));
const attachedLabelsCount = attachedLabels.length;
+ // Custom property catalog. Includes archived definitions: an issue can
+ // still carry a value written before the archive, and that row must stay
+ // renderable (read-only) until someone clears it.
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId, true));
+
// Seed the visible-optional-props set:
// - on issue switch, reset to whichever fields are currently set
// - on the SAME issue, additively pick up fields the user just set
@@ -1345,11 +1357,13 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
if (seededIssueIdRef.current !== issue.id) {
seededIssueIdRef.current = issue.id;
setAutoOpenProp(null);
+ setAutoOpenCustomProp(null);
const seed = new Set<OptionalPropKey>();
for (const k of OPTIONAL_PROP_KEYS) {
if (isOptionalPropSet(issue, k, attachedLabelsCount)) seed.add(k);
}
setVisibleOptionalProps(seed);
+ setVisibleCustomProps(new Set(Object.keys(issue.properties ?? {})));
return;
}
setVisibleOptionalProps((prev) => {
@@ -1362,6 +1376,16 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
}
return next;
});
+ setVisibleCustomProps((prev) => {
+ let next = prev;
+ for (const propertyId of Object.keys(issue.properties ?? {})) {
+ if (!next.has(propertyId)) {
+ if (next === prev) next = new Set(prev);
+ next.add(propertyId);
+ }
+ }
+ return next;
+ });
}, [issue, attachedLabelsCount]);
const addOptionalProp = useCallback(
@@ -1380,6 +1404,17 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
[],
);
+ const addCustomProp = useCallback((propertyId: string) => {
+ setVisibleCustomProps((prev) => {
+ if (prev.has(propertyId)) return prev;
+ const next = new Set(prev);
+ next.add(propertyId);
+ return next;
+ });
+ setAutoOpenCustomProp(propertyId);
+ setAddPropPopoverOpen(false);
+ }, []);
+
// Clear the auto-open flag after the next render so pickers (which read
// `defaultOpen` once via a useState initializer) keep the open state they
// captured on mount, but later interactions don't re-trigger it.
@@ -1388,6 +1423,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
setAutoOpenProp(null);
}, [autoOpenProp]);
+ useEffect(() => {
+ if (autoOpenCustomProp === null) return;
+ setAutoOpenCustomProp(null);
+ }, [autoOpenCustomProp]);
+
const handleToggleSidebar = useCallback(() => {
if (isMobile) {
setMobileSidebarOpen((open) => !open);
@@ -1556,11 +1596,32 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</PropRow>
)}
+ {/* Custom properties — same progressive disclosure as the
+ built-in optional props: a row renders when the issue has a
+ value OR the user added the property this session. Archived
+ definitions render read-only until their value is cleared. */}
+ {workspaceProperties
+ .filter(
+ (p) =>
+ issue.properties?.[p.id] !== undefined ||
+ (!p.archived && visibleCustomProps.has(p.id)),
+ )
+ .map((p) => (
+ <PropRow key={p.id} label={p.name}>
+ <CustomPropertyValueEditor
+ issue={issue}
+ property={p}
+ defaultOpen={autoOpenCustomProp === p.id}
+ />
+ </PropRow>
+ ))}
+
{/* "+ Add property" — opens a Popover listing optional fields
not yet displayed. Hidden once every optional field is on
screen. Sits inside the same grid as a full-row, with its
own padding so the visual rhythm follows the rows above. */}
- {OPTIONAL_PROP_KEYS.some((k) => !visibleOptionalProps.has(k) && (k !== "stage" || issue.parent_issue_id != null)) && (
+ {(OPTIONAL_PROP_KEYS.some((k) => !visibleOptionalProps.has(k) && (k !== "stage" || issue.parent_issue_id != null)) ||
+ workspaceProperties.some((p) => !p.archived && !visibleCustomProps.has(p.id) && issue.properties?.[p.id] === undefined)) && (
<div className="col-span-2 mt-1">
<Popover open={addPropPopoverOpen} onOpenChange={setAddPropPopoverOpen}>
<PopoverTrigger
@@ -1605,6 +1666,31 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
</span>
</button>
))}
+ {(() => {
+ const addable = workspaceProperties.filter(
+ (p) =>
+ !p.archived &&
+ !visibleCustomProps.has(p.id) &&
+ issue.properties?.[p.id] === undefined,
+ );
+ if (addable.length === 0) return null;
+ return (
+ <>
+ <div className="my-1 h-px bg-border" />
+ {addable.map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ onClick={() => addCustomProp(p.id)}
+ className="flex w-full items-center gap-2 rounded-md px-2 py-1 text-xs text-foreground/90 transition-colors hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
+ >
+ <SlidersHorizontal className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{p.name}</span>
+ </button>
+ ))}
+ </>
+ );
+ })()}
</PopoverContent>
</Popover>
</div>
diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsx
index f515c9453b..fbdd0c76eb 100644
--- a/packages/views/issues/components/issues-header.tsx
+++ b/packages/views/issues/components/issues-header.tsx
@@ -56,6 +56,9 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { memberListOptions, agentListOptions, squadListOptions } from "@multica/core/workspace/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import { labelListOptions } from "@multica/core/labels/queries";
+import { propertyListOptions } from "@multica/core/properties";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
+import type { IssueProperty } from "@multica/core/types";
import { ProjectIcon } from "../../projects/components/project-icon";
import { ActorAvatar } from "../../common/actor-avatar";
import { LabelChip } from "../../labels/label-chip";
@@ -103,6 +106,7 @@ function getActiveFilterCount(state: {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
+ propertyFilters?: Record<string, string[]>;
dateFilter?: IssueDateFilter | null;
}) {
let count = 0;
@@ -112,6 +116,9 @@ function getActiveFilterCount(state: {
if (state.creatorFilters.length > 0) count++;
if (state.projectFilters.length > 0 || state.includeNoProject) count++;
if (state.labelFilters.length > 0) count++;
+ for (const selected of Object.values(state.propertyFilters ?? {})) {
+ if (selected.length > 0) count++;
+ }
if (state.dateFilter) count++;
return count;
}
@@ -137,6 +144,9 @@ function useIssueCounts(allIssues: Issue[]) {
const creator = new Map<string, number>();
const project = new Map<string, number>();
const label = new Map<string, number>();
+ // property definition id → option key → count. Checkbox values count
+ // under the "true"/"false" pseudo-option keys the filter store uses.
+ const property = new Map<string, Map<string, number>>();
let noAssignee = 0;
let noProject = 0;
@@ -165,9 +175,29 @@ function useIssueCounts(allIssues: Issue[]) {
label.set(l.id, (label.get(l.id) ?? 0) + 1);
}
}
+
+ for (const [propertyId, value] of Object.entries(issue.properties ?? {})) {
+ const optionKeys =
+ typeof value === "string"
+ ? [value]
+ : Array.isArray(value)
+ ? value
+ : typeof value === "boolean"
+ ? [String(value)]
+ : [];
+ if (optionKeys.length === 0) continue;
+ let perOption = property.get(propertyId);
+ if (!perOption) {
+ perOption = new Map<string, number>();
+ property.set(propertyId, perOption);
+ }
+ for (const key of optionKeys) {
+ perOption.set(key, (perOption.get(key) ?? 0) + 1);
+ }
+ }
}
- return { status, priority, assignee, creator, noAssignee, project, noProject, label };
+ return { status, priority, assignee, creator, noAssignee, project, noProject, label, property };
}, [allIssues]);
}
@@ -505,6 +535,67 @@ function LabelSubContent({
);
}
+/**
+ * Option checkboxes for one custom property inside the Filter dropdown.
+ * Select/multi_select list the definition's options (dot + name); checkbox
+ * definitions expose the "true"/"false" pseudo-options with Yes/No labels.
+ */
+function PropertyFilterOptions({
+ property,
+ counts,
+ selected,
+ onToggle,
+}: {
+ property: IssueProperty;
+ counts: Map<string, number> | undefined;
+ selected: string[];
+ onToggle: (optionId: string) => void;
+}) {
+ const { t } = useT("issues");
+ const options =
+ property.type === "checkbox"
+ ? [
+ { id: "true", name: t(($) => $.pickers.custom_property.true_label), color: undefined },
+ { id: "false", name: t(($) => $.pickers.custom_property.false_label), color: undefined },
+ ]
+ : (property.config.options ?? []).map((option) => ({
+ id: option.id,
+ name: option.name,
+ color: option.color as string | undefined,
+ }));
+
+ return (
+ <>
+ {options.map((option) => {
+ const checked = selected.includes(option.id);
+ const count = counts?.get(option.id) ?? 0;
+ return (
+ <DropdownMenuCheckboxItem
+ key={option.id}
+ checked={checked}
+ onCheckedChange={() => onToggle(option.id)}
+ className={FILTER_ITEM_CLASS}
+ >
+ <HoverCheck checked={checked} />
+ {option.color && (
+ <span
+ className="size-2.5 shrink-0 rounded-full"
+ style={{ backgroundColor: option.color }}
+ />
+ )}
+ <span className="truncate">{option.name}</span>
+ {count > 0 && (
+ <span className="ml-auto text-xs text-muted-foreground">
+ {count}
+ </span>
+ )}
+ </DropdownMenuCheckboxItem>
+ );
+ })}
+ </>
+ );
+}
+
// ---------------------------------------------------------------------------
// Date sub-menu content
// ---------------------------------------------------------------------------
@@ -796,6 +887,8 @@ export function IssueDisplayControls({
const projectFilters = useViewStore((s) => s.projectFilters);
const includeNoProject = useViewStore((s) => s.includeNoProject);
const labelFilters = useViewStore((s) => s.labelFilters);
+ const propertyFilters = useViewStore((s) => s.propertyFilters);
+ const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
const sortBy = useViewStore((s) => s.sortBy);
const sortDirection = useViewStore((s) => s.sortDirection);
const grouping = useViewStore((s) => s.grouping);
@@ -803,13 +896,47 @@ export function IssueDisplayControls({
const cardProperties = useViewStore((s) => s.cardProperties);
const showSubIssues = useViewStore((s) => s.showSubIssues);
const act = useViewStoreApi().getState();
+ const headerWsId = useWorkspaceId();
+ // Active custom-property catalog: drives the filter sections, dynamic
+ // sort/grouping options, and the card-property toggles below.
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(headerWsId));
+ const propertyById = useMemo(
+ () => new Map(workspaceProperties.map((p) => [p.id, p])),
+ [workspaceProperties],
+ );
+ const filterableProperties = useMemo(
+ () =>
+ workspaceProperties.filter((p) =>
+ p.type === "select" || p.type === "multi_select" || p.type === "checkbox",
+ ),
+ [workspaceProperties],
+ );
+ const sortableProperties = useMemo(
+ () => workspaceProperties.filter((p) => p.type === "number" || p.type === "date"),
+ [workspaceProperties],
+ );
+ const groupableProperties = useMemo(
+ () => workspaceProperties.filter((p) => p.type === "select"),
+ [workspaceProperties],
+ );
const counts = useIssueCounts(scopedIssues);
const showDateFilter = !!onDateFilterChange;
+ // Only count filters whose definition is still active — a filter pinned to
+ // an archived definition is stripped by the surface controller and must
+ // not light the badge for an effect that no longer exists.
+ const effectivePropertyFilters = useMemo(() => {
+ const activeIds = new Set(filterableProperties.map((p) => p.id));
+ return Object.fromEntries(
+ Object.entries(propertyFilters).filter(([id, selected]) => selected.length > 0 && activeIds.has(id)),
+ );
+ }, [filterableProperties, propertyFilters]);
+
const activeFilterCount = getActiveFilterCount({
statusFilters,
priorityFilters,
+ propertyFilters: effectivePropertyFilters,
assigneeFilters,
includeNoAssignee,
creatorFilters,
@@ -854,8 +981,17 @@ export function IssueDisplayControls({
: `${shortDateLabel(dateFilter.from)} - ${shortDateLabel(dateFilter.to)}`
}`
: null;
- const sortLabel = t(($) => $.display[SORT_LABEL_KEY[sortBy]]);
- const groupingLabel = t(($) => $.display[GROUPING_LABEL_KEY[grouping]]);
+ const sortPropertyId = propertyIdFromViewKey(sortBy);
+ const groupingPropertyId = propertyIdFromViewKey(grouping);
+ // Property-backed sort/grouping label straight from the definition name;
+ // a stale persisted id (archived/deleted definition) falls back to the
+ // manual/status default label.
+ const sortLabel = sortPropertyId
+ ? propertyById.get(sortPropertyId)?.name ?? t(($) => $.display.sort_manual)
+ : t(($) => $.display[SORT_LABEL_KEY[sortBy as keyof typeof SORT_LABEL_KEY]]);
+ const groupingLabel = groupingPropertyId
+ ? propertyById.get(groupingPropertyId)?.name ?? t(($) => $.display.group_status)
+ : t(($) => $.display[GROUPING_LABEL_KEY[grouping as keyof typeof GROUPING_LABEL_KEY]]);
const swimlaneGroupingLabel = t(($) => $.display[SWIMLANE_GROUPING_LABEL_KEY[swimlaneGrouping]]);
const controlButtonClass = "h-8 w-8 gap-1 px-0 text-muted-foreground md:h-7 md:w-auto md:px-2.5";
@@ -1090,6 +1226,33 @@ export function IssueDisplayControls({
</DropdownMenuSubContent>
</DropdownMenuSub>
+ {/* Custom properties — one sub per filterable definition */}
+ {filterableProperties.length > 0 && <DropdownMenuSeparator />}
+ {filterableProperties.map((property) => {
+ const selected = propertyFilters[property.id] ?? [];
+ return (
+ <DropdownMenuSub key={property.id}>
+ <DropdownMenuSubTrigger>
+ <SlidersHorizontal className="size-3.5" />
+ <span className="flex-1 truncate">{property.name}</span>
+ {selected.length > 0 && (
+ <span className="text-xs text-primary font-medium">
+ {selected.length}
+ </span>
+ )}
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="w-auto min-w-44 p-1">
+ <PropertyFilterOptions
+ property={property}
+ counts={counts.property.get(property.id)}
+ selected={selected}
+ onToggle={(optionId) => act.togglePropertyFilter(property.id, optionId)}
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ );
+ })}
+
{/* Reset */}
{hasActiveFilters && (
<>
@@ -1157,6 +1320,11 @@ export function IssueDisplayControls({
{t(($) => $.display[GROUPING_LABEL_KEY[opt.value]])}
</DropdownMenuRadioItem>
))}
+ {groupableProperties.map((property) => (
+ <DropdownMenuRadioItem key={property.id} value={`property:${property.id}`}>
+ {property.name}
+ </DropdownMenuRadioItem>
+ ))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
@@ -1221,7 +1389,12 @@ export function IssueDisplayControls({
<DropdownMenuRadioGroup value={sortBy} onValueChange={(v) => act.setSortBy(v as SortField)}>
{SORT_OPTIONS.map((opt) => (
<DropdownMenuRadioItem key={opt.value} value={opt.value}>
- {t(($) => $.display[SORT_LABEL_KEY[opt.value]])}
+ {t(($) => $.display[SORT_LABEL_KEY[opt.value as keyof typeof SORT_LABEL_KEY]])}
+ </DropdownMenuRadioItem>
+ ))}
+ {sortableProperties.map((property) => (
+ <DropdownMenuRadioItem key={property.id} value={`property:${property.id}`}>
+ {property.name}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
@@ -1273,6 +1446,19 @@ export function IssueDisplayControls({
/>
</label>
))}
+ {workspaceProperties.map((property) => (
+ <label
+ key={property.id}
+ className="flex cursor-pointer items-center justify-between"
+ >
+ <span className="truncate text-sm">{property.name}</span>
+ <Switch
+ size="sm"
+ checked={cardPropertyIds.includes(property.id)}
+ onCheckedChange={() => act.toggleCardPropertyId(property.id)}
+ />
+ </label>
+ ))}
</div>
</div>
</PopoverContent>
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index 45bd818464..cdb6d35afa 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -169,6 +169,8 @@ const mockViewState = {
projectFilters: [] as string[],
includeNoProject: false,
labelFilters: [] as string[],
+ propertyFilters: {} as Record<string, string[]>,
+ cardPropertyIds: [] as string[],
sortBy: "position" as const,
sortDirection: "asc" as const,
cardProperties: { priority: true, description: true, assignee: true, dueDate: true, project: true, childProgress: true, labels: true },
@@ -183,6 +185,8 @@ const mockViewState = {
toggleProjectFilter: vi.fn(),
toggleNoProject: vi.fn(),
toggleLabelFilter: vi.fn(),
+ togglePropertyFilter: vi.fn(),
+ toggleCardPropertyId: vi.fn(),
hideStatus: vi.fn(),
showStatus: vi.fn(),
clearFilters: vi.fn(),
@@ -194,6 +198,9 @@ const mockViewState = {
vi.mock("@multica/core/issues/stores/view-store", () => ({
useClearFiltersOnWorkspaceChange: () => {},
+ PROPERTY_VIEW_PREFIX: "property:",
+ propertyIdFromViewKey: (key: string) =>
+ key.startsWith("property:") ? key.slice("property:".length) : null,
viewStorePersistOptions: () => ({ name: "test", storage: undefined, partialize: (s: any) => s }),
mergeViewStatePersisted: (_p: unknown, c: any) => c,
viewStoreSlice: vi.fn(),
@@ -339,6 +346,7 @@ const issueDefaults = {
position: 0,
stage: null,
metadata: {},
+ properties: {},
};
const mockIssues: Issue[] = [
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index 3ed3b7ab81..293b98226c 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -5,11 +5,17 @@ import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";
import type { AnimateLayoutChanges } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { AppLink } from "../../navigation";
-import type { Issue, Project } from "@multica/core/types";
+import type { Issue, Project,
+ IssueProperty,
+} from "@multica/core/types";
import { formatDateOnly } from "@multica/core/issues/date";
import { ActorAvatar } from "../../common/actor-avatar";
import { useWorkspacePaths } from "@multica/core/paths";
+import { useQuery } from "@tanstack/react-query";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { propertyListOptions } from "@multica/core/properties";
+import { CustomPropertyValueDisplay } from "./pickers/custom-property-picker";
import { ProjectIcon } from "../../projects/components/project-icon";
import { PriorityIcon } from "./priority-icon";
import { ProgressRing } from "./progress-ring";
@@ -51,6 +57,12 @@ function ListRowContent({
const toggle = selection.toggle;
const p = useWorkspacePaths();
const storeProperties = useViewStore((s) => s.cardProperties);
+ const cardPropertyIds = useViewStore((s) => s.cardPropertyIds);
+ const rowWsId = useWorkspaceId();
+ const { data: workspaceProperties = [] } = useQuery(propertyListOptions(rowWsId));
+ const cardCustomProperties = cardPropertyIds
+ .map((id) => workspaceProperties.find((p) => p.id === id))
+ .filter((p): p is IssueProperty => !!p && issue.properties?.[p.id] !== undefined);
const labels = issue.labels ?? [];
const showProject = storeProperties.project && project;
@@ -120,6 +132,18 @@ function ListRowContent({
)}
</span>
)}
+ {cardCustomProperties.length > 0 && (
+ <span className="ml-1.5 hidden md:inline-flex shrink-0 items-center gap-1 max-w-[260px] overflow-hidden">
+ {cardCustomProperties.slice(0, 3).map((property) => (
+ <span
+ key={property.id}
+ className="inline-flex max-w-[120px] items-center rounded-full bg-muted/60 px-1.5 py-0.5 text-[11px] text-muted-foreground"
+ >
+ <CustomPropertyValueDisplay property={property} value={issue.properties?.[property.id]} />
+ </span>
+ ))}
+ </span>
+ )}
</span>
{showProject && (
<span className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground max-w-[140px]">
diff --git a/packages/views/issues/components/pickers/custom-property-picker.tsx b/packages/views/issues/components/pickers/custom-property-picker.tsx
new file mode 100644
index 0000000000..7eee204d47
--- /dev/null
+++ b/packages/views/issues/components/pickers/custom-property-picker.tsx
@@ -0,0 +1,436 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { CalendarDays, ExternalLink } from "lucide-react";
+import { toast } from "sonner";
+import type { Issue, IssueProperty, IssuePropertyValue } from "@multica/core/types";
+import {
+ useSetIssueProperty,
+ useUnsetIssueProperty,
+} from "@multica/core/properties";
+import {
+ toDateOnly,
+ dateOnlyToLocalDate,
+ formatDateOnly,
+} from "@multica/core/issues/date";
+import { Calendar } from "@multica/ui/components/ui/calendar";
+import {
+ Popover,
+ PopoverTrigger,
+ PopoverContent,
+} from "@multica/ui/components/ui/popover";
+import { Button } from "@multica/ui/components/ui/button";
+import { Input } from "@multica/ui/components/ui/input";
+import { useT } from "../../../i18n";
+import { PropertyPicker, PickerItem } from "./property-picker";
+
+/**
+ * Value editor for one custom property on one issue. The editor shape
+ * follows the definition type:
+ *
+ * select → PropertyPicker with one PickerItem per option
+ * multi_select → PropertyPicker with toggling items (stays open)
+ * date → Calendar popover (mirrors DueDatePicker)
+ * checkbox → Yes / No picker
+ * text/number/url → popover with an input, Enter commits
+ *
+ * Archived definitions render read-only: the popover only offers Clear
+ * (the server rejects new values on archived properties but always allows
+ * unset). Unknown types from newer servers degrade to the read-only view.
+ */
+export function CustomPropertyValueEditor({
+ issue,
+ property,
+ defaultOpen = false,
+}: {
+ issue: Issue;
+ property: IssueProperty;
+ defaultOpen?: boolean;
+}) {
+ const { t } = useT("issues");
+ const [open, setOpen] = useState(defaultOpen);
+ const setProperty = useSetIssueProperty();
+ const unsetProperty = useUnsetIssueProperty();
+
+ const value = issue.properties[property.id];
+ const hasValue = value !== undefined;
+
+ const onError = (error: unknown) =>
+ toast.error(error instanceof Error ? error.message : String(error));
+
+ const commit = (next: IssuePropertyValue) =>
+ setProperty.mutate(
+ { issueId: issue.id, propertyId: property.id, value: next },
+ { onError },
+ );
+ const clear = () =>
+ unsetProperty.mutate({ issueId: issue.id, propertyId: property.id }, { onError });
+
+ const emptyLabel = (
+ <span className="text-muted-foreground">
+ {t(($) => $.pickers.custom_property.empty)}
+ </span>
+ );
+
+ const clearFooter = hasValue ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ clear();
+ setOpen(false);
+ }}
+ className="w-full justify-start text-muted-foreground hover:text-foreground"
+ >
+ {t(($) => $.pickers.custom_property.clear_action)}
+ </Button>
+ ) : undefined;
+
+ // Archived (or unknown-type) definitions: read-only display; the only
+ // offered action is Clear so stale values can still be cleaned up.
+ const readOnly =
+ property.archived ||
+ !["select", "multi_select", "date", "checkbox", "text", "number", "url"].includes(
+ property.type,
+ );
+
+ if (readOnly) {
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ align="start"
+ trigger={<CustomPropertyValueDisplay property={property} value={value} />}
+ footer={clearFooter}
+ >
+ <p className="px-2 py-1.5 text-xs text-muted-foreground">
+ {t(($) => $.pickers.custom_property.archived_hint)}
+ </p>
+ </PropertyPicker>
+ );
+ }
+
+ switch (property.type) {
+ case "select": {
+ const options = property.config.options ?? [];
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ align="start"
+ searchable={options.length > 7}
+ trigger={<CustomPropertyValueDisplay property={property} value={value} />}
+ footer={clearFooter}
+ >
+ {options.map((option) => (
+ <PickerItem
+ key={option.id}
+ selected={value === option.id}
+ onClick={() => {
+ commit(option.id);
+ setOpen(false);
+ }}
+ >
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="truncate">{option.name}</span>
+ </PickerItem>
+ ))}
+ </PropertyPicker>
+ );
+ }
+ case "multi_select": {
+ const options = property.config.options ?? [];
+ const selected = Array.isArray(value) ? value : [];
+ const toggle = (optionId: string) => {
+ const next = selected.includes(optionId)
+ ? selected.filter((id) => id !== optionId)
+ : [...selected, optionId];
+ if (next.length === 0) clear();
+ else commit(next);
+ };
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ align="start"
+ searchable={options.length > 7}
+ trigger={<CustomPropertyValueDisplay property={property} value={value} />}
+ footer={clearFooter}
+ >
+ {options.map((option) => (
+ <PickerItem
+ key={option.id}
+ selected={selected.includes(option.id)}
+ onClick={() => toggle(option.id)}
+ >
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="truncate">{option.name}</span>
+ </PickerItem>
+ ))}
+ </PropertyPicker>
+ );
+ }
+ case "date": {
+ const date = typeof value === "string" ? dateOnlyToLocalDate(value) : undefined;
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger className="flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden">
+ <CustomPropertyValueDisplay property={property} value={value} />
+ </PopoverTrigger>
+ <PopoverContent className="w-auto p-0" align="start">
+ <Calendar
+ mode="single"
+ selected={date}
+ onSelect={(d: Date | undefined) => {
+ if (d) commit(toDateOnly(d));
+ else clear();
+ setOpen(false);
+ }}
+ />
+ {date && (
+ <div className="border-t px-3 py-2">
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => {
+ clear();
+ setOpen(false);
+ }}
+ className="text-muted-foreground hover:text-foreground"
+ >
+ {t(($) => $.pickers.custom_property.clear_action)}
+ </Button>
+ </div>
+ )}
+ </PopoverContent>
+ </Popover>
+ );
+ }
+ case "checkbox":
+ return (
+ <PropertyPicker
+ open={open}
+ onOpenChange={setOpen}
+ align="start"
+ trigger={<CustomPropertyValueDisplay property={property} value={value} />}
+ footer={clearFooter}
+ >
+ <PickerItem
+ selected={value === true}
+ onClick={() => {
+ commit(true);
+ setOpen(false);
+ }}
+ >
+ {t(($) => $.pickers.custom_property.true_label)}
+ </PickerItem>
+ <PickerItem
+ selected={value === false}
+ onClick={() => {
+ commit(false);
+ setOpen(false);
+ }}
+ >
+ {t(($) => $.pickers.custom_property.false_label)}
+ </PickerItem>
+ </PropertyPicker>
+ );
+ default:
+ return (
+ <TextishPropertyEditor
+ property={property}
+ value={value}
+ open={open}
+ onOpenChange={setOpen}
+ onCommit={commit}
+ onClear={clear}
+ emptyLabel={emptyLabel}
+ />
+ );
+ }
+}
+
+/** Popover-with-input editor shared by text / number / url. */
+function TextishPropertyEditor({
+ property,
+ value,
+ open,
+ onOpenChange,
+ onCommit,
+ onClear,
+ emptyLabel,
+}: {
+ property: IssueProperty;
+ value: IssuePropertyValue | undefined;
+ open: boolean;
+ onOpenChange: (v: boolean) => void;
+ onCommit: (next: IssuePropertyValue) => void;
+ onClear: () => void;
+ emptyLabel: React.ReactNode;
+}) {
+ const { t } = useT("issues");
+ const [draft, setDraft] = useState("");
+
+ useEffect(() => {
+ if (open) setDraft(value === undefined ? "" : String(value));
+ }, [open, value]);
+
+ const placeholder =
+ property.type === "url"
+ ? t(($) => $.pickers.custom_property.url_placeholder)
+ : property.type === "number"
+ ? t(($) => $.pickers.custom_property.number_placeholder)
+ : t(($) => $.pickers.custom_property.value_placeholder);
+
+ const submit = () => {
+ const trimmed = draft.trim();
+ if (!trimmed) {
+ if (value !== undefined) onClear();
+ onOpenChange(false);
+ return;
+ }
+ if (property.type === "number") {
+ const parsed = Number(trimmed);
+ if (Number.isNaN(parsed)) return;
+ onCommit(parsed);
+ } else {
+ onCommit(trimmed);
+ }
+ onOpenChange(false);
+ };
+
+ return (
+ <Popover open={open} onOpenChange={onOpenChange}>
+ <PopoverTrigger className="flex items-center gap-1.5 cursor-pointer rounded px-1 -mx-1 hover:bg-accent/30 transition-colors overflow-hidden">
+ {value === undefined ? (
+ emptyLabel
+ ) : (
+ <CustomPropertyValueDisplay property={property} value={value} />
+ )}
+ </PopoverTrigger>
+ <PopoverContent className="w-64 p-2" align="start">
+ <form
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ className="flex items-center gap-2"
+ >
+ <Input
+ autoFocus
+ type={property.type === "number" ? "number" : "text"}
+ step={property.type === "number" ? "any" : undefined}
+ inputMode={property.type === "number" ? "decimal" : undefined}
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ placeholder={placeholder}
+ className="h-8"
+ />
+ {property.type === "url" && typeof value === "string" && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.pickers.custom_property.open_link)}
+ onClick={() => window.open(value, "_blank", "noopener,noreferrer")}
+ >
+ <ExternalLink className="size-3.5" />
+ </Button>
+ )}
+ </form>
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+/**
+ * Read view of a custom property value, shared by row triggers everywhere
+ * (sidebar rows now; cards/filters later). Option ids resolve to named,
+ * colored chips; unknown ids (option deleted from the definition) are
+ * silently dropped rather than rendering raw UUIDs.
+ */
+export function CustomPropertyValueDisplay({
+ property,
+ value,
+}: {
+ property: IssueProperty;
+ value: IssuePropertyValue | undefined;
+}) {
+ const { t } = useT("issues");
+ if (value === undefined) {
+ return (
+ <span className="text-muted-foreground">
+ {t(($) => $.pickers.custom_property.empty)}
+ </span>
+ );
+ }
+ const options = property.config.options ?? [];
+ switch (property.type) {
+ case "select": {
+ const option = options.find((o) => o.id === value);
+ if (!option) {
+ return (
+ <span className="text-muted-foreground">
+ {t(($) => $.pickers.custom_property.empty)}
+ </span>
+ );
+ }
+ return (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <span className="size-2.5 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="truncate">{option.name}</span>
+ </span>
+ );
+ }
+ case "multi_select": {
+ const ids = Array.isArray(value) ? value : [];
+ const selected = options.filter((o) => ids.includes(o.id));
+ if (selected.length === 0) {
+ return (
+ <span className="text-muted-foreground">
+ {t(($) => $.pickers.custom_property.empty)}
+ </span>
+ );
+ }
+ return (
+ <span className="flex min-w-0 flex-wrap items-center gap-1">
+ {selected.map((option) => (
+ <span
+ key={option.id}
+ className="inline-flex max-w-32 items-center gap-1 rounded-full border border-surface-border px-1.5 py-px text-[11px]"
+ >
+ <span className="size-2 shrink-0 rounded-full" style={{ backgroundColor: option.color }} />
+ <span className="truncate">{option.name}</span>
+ </span>
+ ))}
+ </span>
+ );
+ }
+ case "date":
+ return (
+ <span className="flex items-center gap-1.5">
+ <CalendarDays className="h-3.5 w-3.5 text-muted-foreground" />
+ {typeof value === "string"
+ ? formatDateOnly(value, { month: "short", day: "numeric" }, "en-US")
+ : String(value)}
+ </span>
+ );
+ case "checkbox":
+ return (
+ <span>
+ {value === true
+ ? t(($) => $.pickers.custom_property.true_label)
+ : t(($) => $.pickers.custom_property.false_label)}
+ </span>
+ );
+ case "url":
+ return (
+ <span className="flex min-w-0 items-center gap-1.5">
+ <ExternalLink className="h-3 w-3 shrink-0 text-muted-foreground" />
+ <span className="truncate">{String(value)}</span>
+ </span>
+ );
+ default:
+ return <span className="truncate tabular-nums">{String(value)}</span>;
+ }
+}
diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsx
index a20b12d71f..381957e8e8 100644
--- a/packages/views/issues/components/swimlane-view.test.tsx
+++ b/packages/views/issues/components/swimlane-view.test.tsx
@@ -163,6 +163,8 @@ const mockViewState: {
projectFilters?: string[];
includeNoProject?: boolean;
labelFilters?: string[];
+ propertyFilters?: Record<string, string[]>;
+ cardPropertyIds?: string[];
agentRunningFilter?: boolean;
} = {
sortBy: "position",
@@ -183,6 +185,8 @@ const mockViewState: {
projectFilters: [],
includeNoProject: false,
labelFilters: [],
+ propertyFilters: {},
+ cardPropertyIds: [],
agentRunningFilter: false,
};
const mockSetSwimlaneOrder = mockViewState.setSwimlaneOrder as ReturnType<typeof vi.fn>;
@@ -269,6 +273,7 @@ const mockIssues: Issue[] = [
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -292,6 +297,7 @@ const mockIssues: Issue[] = [
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -315,6 +321,7 @@ const mockIssues: Issue[] = [
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -395,6 +402,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -542,6 +550,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -840,6 +849,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -863,6 +873,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -886,6 +897,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -909,6 +921,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
},
@@ -1365,6 +1378,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -1439,6 +1453,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -1520,6 +1535,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -1614,6 +1630,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
@@ -1710,6 +1727,7 @@ describe("SwimLaneView", () => {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
diff --git a/packages/views/issues/hooks/issue-delete-mutations.test.tsx b/packages/views/issues/hooks/issue-delete-mutations.test.tsx
index 417348b881..c8893827ff 100644
--- a/packages/views/issues/hooks/issue-delete-mutations.test.tsx
+++ b/packages/views/issues/hooks/issue-delete-mutations.test.tsx
@@ -65,6 +65,7 @@ const baseIssue: Issue = {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
labels: [],
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 686c3f0c6a..66ca188788 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -83,6 +83,7 @@ function makeIssue(id: string, title: string, projectId: string): Issue {
due_date: null,
labels: [],
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
};
diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
index eb9d8541cb..d9d194b888 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx
+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx
@@ -43,6 +43,7 @@ function makeIssue(
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2026-01-01T00:00:00Z",
updated_at: "2026-01-01T00:00:00Z",
...overrides,
diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.ts
index f43e8d7654..bc819f266a 100644
--- a/packages/views/issues/surface/use-issue-surface-controller.ts
+++ b/packages/views/issues/surface/use-issue-surface-controller.ts
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useMemo } from "react";
+import { useQuery } from "@tanstack/react-query";
import type { QueryKey } from "@tanstack/react-query";
import type {
Issue,
@@ -20,7 +21,9 @@ import {
type IssueSurfaceQueryPlan,
} from "@multica/core/issues/surface/query-plan";
import type { IssueScope } from "@multica/core/issues/surface/scope";
-import type { IssueDateFilter } from "@multica/core/issues/stores/view-store";
+import type { IssueDateFilter, SortField } from "@multica/core/issues/stores/view-store";
+import { propertyListOptions } from "@multica/core/properties";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import { useViewStore } from "@multica/core/issues/stores/view-store-context";
import type { IssueFilters } from "../utils/filter";
import type { ChildProgress } from "../components/list-row";
@@ -129,6 +132,7 @@ export function useIssueSurfaceController({
const projectFilters = useViewStore((s) => s.projectFilters);
const includeNoProject = useViewStore((s) => s.includeNoProject);
const labelFilters = useViewStore((s) => s.labelFilters);
+ const propertyFilters = useViewStore((s) => s.propertyFilters);
const agentRunningFilter = useViewStore((s) => s.agentRunningFilter);
const showSubIssues = useViewStore((s) => s.showSubIssues);
const cardProperties = useViewStore((s) => s.cardProperties);
@@ -155,14 +159,54 @@ export function useIssueSurfaceController({
() => issueDateFilterToApiParams(dateFilter),
[dateFilter],
);
- const sort = useMemo<IssueSortParam>(
- () => ({
- sort_by: sortBy,
- sort_direction: sortBy !== "position" ? sortDirection : undefined,
- ...dateParams,
- }),
- [dateParams, sortBy, sortDirection],
+ // Active property catalog. Persisted view state can outlive definitions
+ // (archive/delete): filters keyed by a non-active definition are stripped
+ // before they reach the predicates, and a sort on a non-active definition
+ // degrades to manual order — matching what the header already shows.
+ const { data: workspaceProperties = [], isSuccess: catalogSettled } = useQuery(propertyListOptions(wsId));
+ const activePropertyIds = useMemo(
+ () => new Set(workspaceProperties.map((p) => p.id)),
+ [workspaceProperties],
);
+ const effectivePropertyFilters = useMemo(() => {
+ // While the catalog is still loading (or errored), persisted filters are
+ // passed through UNCHANGED: treating a cold catalog as confirmed-empty
+ // would silently drop the user's filters on first paint (clean-room
+ // review F6). Old servers 404 into a SETTLED empty catalog, so the
+ // stripping below still protects that path.
+ if (!catalogSettled) return propertyFilters;
+ const entries = Object.entries(propertyFilters).filter(
+ ([propertyId, selected]) => selected.length > 0 && activePropertyIds.has(propertyId),
+ );
+ if (entries.length === Object.keys(propertyFilters).length) return propertyFilters;
+ return Object.fromEntries(entries);
+ }, [activePropertyIds, catalogSettled, propertyFilters]);
+
+ // Custom-property sorts and filters are served by the backend: the sort
+ // param carries `property:<id>` (typed ORDER BY expression server-side)
+ // and the window bag carries the property filter, so results are correct
+ // across pagination — not just the loaded window. A sort pinned to a
+ // non-active definition degrades to position order.
+ const rawPropertySortId = propertyIdFromViewKey(sortBy);
+ const propertySortId =
+ rawPropertySortId && (!catalogSettled || activePropertyIds.has(rawPropertySortId))
+ ? rawPropertySortId
+ : null;
+ const sort = useMemo<IssueSortParam>(() => {
+ const sortBy_: IssueSortParam["sort_by"] = propertySortId
+ ? `property:${propertySortId}`
+ : rawPropertySortId
+ ? "position"
+ : (sortBy as Exclude<SortField, `property:${string}`>);
+ return {
+ sort_by: sortBy_,
+ sort_direction: sortBy_ !== "position" ? sortDirection : undefined,
+ ...dateParams,
+ ...(Object.keys(effectivePropertyFilters).length > 0
+ ? { properties: effectivePropertyFilters }
+ : {}),
+ };
+ }, [dateParams, effectivePropertyFilters, propertySortId, rawPropertySortId, sortBy, sortDirection]);
const selection = useCreateIssueSurfaceSelection(
scopeKey,
@@ -198,6 +242,7 @@ export function useIssueSurfaceController({
projectFilters: viewProjectFilters,
includeNoProject: viewIncludeNoProject,
labelFilters,
+ propertyFilters: effectivePropertyFilters,
agentRunningFilter,
showSubIssues,
loadProjects:
diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.ts
index 5fe8c201fd..3018bed2e4 100644
--- a/packages/views/issues/surface/use-issue-surface-data.ts
+++ b/packages/views/issues/surface/use-issue-surface-data.ts
@@ -77,6 +77,7 @@ export function useIssueSurfaceData({
projectFilters,
includeNoProject,
labelFilters,
+ propertyFilters,
agentRunningFilter,
showSubIssues,
loadProjects,
@@ -95,6 +96,7 @@ export function useIssueSurfaceData({
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
+ propertyFilters: Record<string, string[]>;
agentRunningFilter: boolean;
showSubIssues: boolean;
loadProjects: boolean;
@@ -174,6 +176,7 @@ export function useIssueSurfaceData({
projectFilters,
includeNoProject,
labelFilters,
+ propertyFilters,
workingOnly: agentRunningFilter,
showSubIssues,
}),
@@ -186,6 +189,7 @@ export function useIssueSurfaceData({
labelFilters,
priorityFilters,
projectFilters,
+ propertyFilters,
showSubIssues,
statusFilters,
],
@@ -223,11 +227,13 @@ export function useIssueSurfaceData({
showSubIssues,
agentRunningFilter,
runningIssueIds: activity.runningIssueIds,
+ propertyFilters,
}),
[
activity.runningIssueIds,
agentRunningFilter,
assigneeGroupsQuery.data?.groups,
+ propertyFilters,
showSubIssues,
],
);
@@ -271,6 +277,7 @@ export function useIssueSurfaceData({
projectFilters,
includeNoProject,
labelFilters,
+ propertyFilters,
agentRunningFilter,
showSubIssues,
}),
@@ -281,6 +288,7 @@ export function useIssueSurfaceData({
includeNoAssignee,
includeNoProject,
labelFilters,
+ propertyFilters,
priorityFilters,
projectFilters,
showSubIssues,
diff --git a/packages/views/issues/utils/drag-utils.test.ts b/packages/views/issues/utils/drag-utils.test.ts
index a6fbb7621b..faa9e4785a 100644
--- a/packages/views/issues/utils/drag-utils.test.ts
+++ b/packages/views/issues/utils/drag-utils.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { Issue } from "@multica/core/types";
-import { insertIdByPosition } from "./drag-utils";
+import { getIssueGroupId, getMoveUpdates, insertIdByPosition, issueMatchesGroup, propertyGroupId } from "./drag-utils";
function mk(id: string, position: number): Issue {
return {
@@ -23,6 +23,7 @@ function mk(id: string, position: number): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
labels: [],
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
@@ -70,3 +71,42 @@ describe("insertIdByPosition", () => {
]);
});
});
+
+describe("property grouping", () => {
+ const propertyId = "prop-env";
+ const withValue = { id: "A", properties: { [propertyId]: "opt-staging" } } as unknown as Issue;
+ const withoutValue = { id: "B", properties: {} } as unknown as Issue;
+
+ it("getIssueGroupId buckets by option id, no-value issues into the none column", () => {
+ expect(getIssueGroupId(withValue, `property:${propertyId}`)).toBe(
+ propertyGroupId(propertyId, "opt-staging"),
+ );
+ expect(getIssueGroupId(withoutValue, `property:${propertyId}`)).toBe(
+ propertyGroupId(propertyId, null),
+ );
+ });
+
+ it("issueMatchesGroup distinguishes option and no-value columns", () => {
+ const optionColumn = { id: "c1", title: "Staging", propertyId, propertyOptionId: "opt-staging" };
+ const noneColumn = { id: "c2", title: "No value", propertyId, propertyOptionId: null };
+ expect(issueMatchesGroup(withValue, optionColumn)).toBe(true);
+ expect(issueMatchesGroup(withValue, noneColumn)).toBe(false);
+ expect(issueMatchesGroup(withoutValue, noneColumn)).toBe(true);
+ });
+
+ it("unknown option values bucket into the none column when the catalog is known", () => {
+ const stale = { id: "C", properties: { [propertyId]: "opt-deleted" } } as unknown as Issue;
+ const known = new Set(["opt-staging"]);
+ expect(getIssueGroupId(stale, `property:${propertyId}`, known)).toBe(
+ propertyGroupId(propertyId, null),
+ );
+ // Without the catalog, the raw bucket is preserved (caller may still map it).
+ expect(getIssueGroupId(stale, `property:${propertyId}`)).toBe(
+ propertyGroupId(propertyId, "opt-deleted"),
+ );
+ });
+
+ it("getMoveUpdates for property columns only carries position", () => {
+ expect(getMoveUpdates({ id: "c1", title: "Staging", propertyId, propertyOptionId: "opt-staging" }, 5)).toEqual({ position: 5 });
+ });
+});
diff --git a/packages/views/issues/utils/drag-utils.ts b/packages/views/issues/utils/drag-utils.ts
index 854a3a4102..2c26885c42 100644
--- a/packages/views/issues/utils/drag-utils.ts
+++ b/packages/views/issues/utils/drag-utils.ts
@@ -5,6 +5,7 @@ import {
} from "@dnd-kit/core";
import type { Issue, IssueAssigneeType, IssueStatus, UpdateIssueRequest } from "@multica/core/types";
import type { IssueGrouping } from "@multica/core/issues/stores/view-store";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
import type { BoardColumnGroup } from "../components/board-column";
export type DragMoveUpdates = Pick<
@@ -30,6 +31,10 @@ export function statusGroupId(status: IssueStatus): string {
return `status:${status}`;
}
+export function propertyGroupId(propertyId: string, optionId: string | null): string {
+ return `property:${propertyId}:${optionId ?? "none"}`;
+}
+
export function assigneeGroupId(
type: IssueAssigneeType | null,
id: string | null,
@@ -37,8 +42,25 @@ export function assigneeGroupId(
return type && id ? `assignee:${type}:${id}` : UNASSIGNED_GROUP_ID;
}
-export function getIssueGroupId(issue: Issue, grouping: IssueGrouping): string {
+export function getIssueGroupId(
+ issue: Issue,
+ grouping: IssueGrouping,
+ knownOptionIds?: ReadonlySet<string>,
+): string {
if (grouping === "status") return statusGroupId(issue.status);
+ const propertyId = propertyIdFromViewKey(grouping);
+ if (propertyId) {
+ const value = issue.properties?.[propertyId];
+ let optionId = typeof value === "string" ? value : null;
+ // A value referencing an option no longer in the definition (removed
+ // before the in-use guard existed, or by a newer server) must bucket
+ // into the No-value column — an unmatched column id would silently drop
+ // the issue from the board.
+ if (optionId !== null && knownOptionIds && !knownOptionIds.has(optionId)) {
+ optionId = null;
+ }
+ return propertyGroupId(propertyId, optionId);
+ }
return assigneeGroupId(issue.assignee_type, issue.assignee_id);
}
@@ -46,11 +68,12 @@ export function buildColumns(
issues: Issue[],
groups: BoardColumnGroup[],
grouping: IssueGrouping,
+ knownOptionIds?: ReadonlySet<string>,
): Record<string, string[]> {
const cols: Record<string, string[]> = {};
for (const group of groups) cols[group.id] = [];
for (const issue of issues) {
- const gid = getIssueGroupId(issue, grouping);
+ const gid = getIssueGroupId(issue, grouping, knownOptionIds);
if (cols[gid]) cols[gid].push(issue.id);
}
return cols;
@@ -101,6 +124,11 @@ export function findColumn(
export function issueMatchesGroup(issue: Issue, group: BoardColumnGroup): boolean {
if (group.status) return issue.status === group.status;
+ if (group.propertyId !== undefined) {
+ const value = issue.properties?.[group.propertyId];
+ const optionId = typeof value === "string" ? value : null;
+ return optionId === (group.propertyOptionId ?? null);
+ }
return (
(issue.assignee_type ?? null) === (group.assigneeType ?? null) &&
(issue.assignee_id ?? null) === (group.assigneeId ?? null)
@@ -112,6 +140,9 @@ export function getMoveUpdates(
position: number,
): DragMoveUpdates {
if (group.status) return { status: group.status, position };
+ // Property columns: the value change is not part of UpdateIssueRequest —
+ // the board applies it through useSetIssueProperty after the position move.
+ if (group.propertyId !== undefined) return { position };
return {
assignee_type: group.assigneeType ?? null,
assignee_id: group.assigneeId ?? null,
diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.ts
index d7688d01cc..34cb60a29f 100644
--- a/packages/views/issues/utils/filter.test.ts
+++ b/packages/views/issues/utils/filter.test.ts
@@ -39,6 +39,7 @@ function makeIssue(overrides: Partial<Issue> = {}): Issue {
start_date: null,
due_date: null,
metadata: {},
+ properties: {},
created_at: "2025-01-01T00:00:00Z",
updated_at: "2025-01-01T00:00:00Z",
...overrides,
@@ -383,3 +384,72 @@ describe("filterAssigneeGroups", () => {
expect(result).toEqual([]);
});
});
+
+describe("property filters", () => {
+ const sevId = "prop-severity";
+ const platId = "prop-platforms";
+ const doneId = "prop-done";
+ const critical = makeIssue({ id: "P1", properties: { [sevId]: "opt-critical" } });
+ const minor = makeIssue({ id: "P2", properties: { [sevId]: "opt-minor", [platId]: ["opt-ios", "opt-web"] } });
+ const unset = makeIssue({ id: "P3" });
+ const checked = makeIssue({ id: "P4", properties: { [doneId]: true } });
+
+ it("select values match by option id (OR within the definition)", () => {
+ const result = filterIssues([critical, minor, unset], {
+ ...NO_FILTER,
+ propertyFilters: { [sevId]: ["opt-critical", "opt-minor"] },
+ });
+ expect(result.map((i) => i.id)).toEqual(["P1", "P2"]);
+ });
+
+ it("issues without a value never match a filtered definition", () => {
+ const result = filterIssues([critical, unset], {
+ ...NO_FILTER,
+ propertyFilters: { [sevId]: ["opt-critical"] },
+ });
+ expect(result.map((i) => i.id)).toEqual(["P1"]);
+ });
+
+ it("multi_select matches on intersection", () => {
+ const result = filterIssues([critical, minor], {
+ ...NO_FILTER,
+ propertyFilters: { [platId]: ["opt-web"] },
+ });
+ expect(result.map((i) => i.id)).toEqual(["P2"]);
+ });
+
+ it("checkbox values match the true/false pseudo-options", () => {
+ const result = filterIssues([checked, unset], {
+ ...NO_FILTER,
+ propertyFilters: { [doneId]: ["true"] },
+ });
+ expect(result.map((i) => i.id)).toEqual(["P4"]);
+ });
+
+ it("ANDs across definitions", () => {
+ const result = filterIssues([critical, minor], {
+ ...NO_FILTER,
+ propertyFilters: { [sevId]: ["opt-minor"], [platId]: ["opt-ios"] },
+ });
+ expect(result.map((i) => i.id)).toEqual(["P2"]);
+ });
+
+ it("empty selections are inert", () => {
+ const result = filterIssues([critical, minor, unset], {
+ ...NO_FILTER,
+ propertyFilters: { [sevId]: [] },
+ });
+ expect(result).toHaveLength(3);
+ });
+
+ it("filterAssigneeGroups applies property filters per group", () => {
+ const groups: IssueAssigneeGroup[] = [
+ { id: "assignee:member:u-1", assignee_type: "member", assignee_id: "u-1", issues: [critical, minor], total: 2 },
+ ];
+ const result = filterAssigneeGroups(groups, {
+ propertyFilters: { [sevId]: ["opt-critical"] },
+ });
+ expect(result?.[0]?.issues.map((i) => i.id)).toEqual(["P1"]);
+ expect(result?.[0]?.total).toBe(1);
+ });
+});
diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.ts
index 44729f2ac8..1a43b53570 100644
--- a/packages/views/issues/utils/filter.ts
+++ b/packages/views/issues/utils/filter.ts
@@ -11,6 +11,9 @@ export interface IssueFilters {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
+ /** Custom-property filters: definition id → selected option ids (OR within
+ * a definition, AND across definitions; checkbox uses "true"/"false"). */
+ propertyFilters?: Record<string, string[]>;
// When `agentRunningFilter` is true, only keep issues whose id is in
// `runningIssueIds`. The set is derived by the caller from
// `agentTaskSnapshot` (one pass over running tasks) so filter.ts stays
@@ -33,6 +36,7 @@ export interface IssueFilterState {
projectFilters: string[];
includeNoProject: boolean;
labelFilters: string[];
+ propertyFilters?: Record<string, string[]>;
workingOnly: boolean;
/** See IssueFilters.showSubIssues — only an explicit `false` hides. */
showSubIssues?: boolean;
@@ -43,6 +47,34 @@ export interface IssueFilterContext {
runningIssueIds?: ReadonlySet<string>;
}
+/**
+ * Match one issue against the property filters. Select values are single
+ * option-id strings, multi_select values are option-id arrays, checkbox
+ * values are booleans compared against the "true"/"false" pseudo-options.
+ * An issue with no value for a filtered definition never matches it.
+ */
+export function issueMatchesPropertyFilters(
+ issue: Issue,
+ propertyFilters: Record<string, string[]> | undefined,
+): boolean {
+ if (!propertyFilters) return true;
+ for (const [propertyId, selected] of Object.entries(propertyFilters)) {
+ if (selected.length === 0) continue;
+ const value = issue.properties?.[propertyId];
+ if (value === undefined) return false;
+ if (typeof value === "string") {
+ if (!selected.includes(value)) return false;
+ } else if (Array.isArray(value)) {
+ if (!value.some((id) => selected.includes(id))) return false;
+ } else if (typeof value === "boolean") {
+ if (!selected.includes(String(value))) return false;
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
function issueIsWorking(issueId: string, context: IssueFilterContext) {
if (context.activityByIssueId) {
return context.activityByIssueId.get(issueId)?.isWorking === true;
@@ -128,6 +160,8 @@ export function applyIssueFilters(
if (!issueLabels.some((l) => labelFilters.includes(l.id))) return false;
}
+ if (!issueMatchesPropertyFilters(issue, filters.propertyFilters)) return false;
+
return true;
});
}
@@ -144,6 +178,7 @@ export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {
projectFilters: filters.projectFilters,
includeNoProject: filters.includeNoProject,
labelFilters: filters.labelFilters,
+ propertyFilters: filters.propertyFilters,
workingOnly: filters.agentRunningFilter === true,
showSubIssues: filters.showSubIssues,
},
@@ -165,11 +200,15 @@ export function filterAssigneeGroups(
showSubIssues?: boolean;
agentRunningFilter?: boolean;
runningIssueIds?: ReadonlySet<string>;
+ propertyFilters?: Record<string, string[]>;
},
): IssueAssigneeGroup[] | undefined {
const applyRunning = filters.agentRunningFilter === true;
const hideSubIssues = filters.showSubIssues === false;
- if (!groups || (!applyRunning && !hideSubIssues)) return groups;
+ const hasPropertyFilters = Object.values(filters.propertyFilters ?? {}).some(
+ (selected) => selected.length > 0,
+ );
+ if (!groups || (!applyRunning && !hideSubIssues && !hasPropertyFilters)) return groups;
const { runningIssueIds } = filters;
return groups
@@ -178,6 +217,8 @@ export function filterAssigneeGroups(
if (applyRunning && !(runningIssueIds?.has(issue.id) ?? false))
return false;
if (hideSubIssues && issue.parent_issue_id) return false;
+ if (hasPropertyFilters && !issueMatchesPropertyFilters(issue, filters.propertyFilters))
+ return false;
return true;
});
return { ...group, issues, total: issues.length };
diff --git a/packages/views/issues/utils/sort.test.ts b/packages/views/issues/utils/sort.test.ts
new file mode 100644
index 0000000000..3fb8dac78b
--- /dev/null
+++ b/packages/views/issues/utils/sort.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import type { Issue } from "@multica/core/types";
+import { sortIssues } from "./sort";
+
+const propertyId = "prop-effort";
+
+function issueWith(id: string, value?: number | string, position = 0): Issue {
+ return {
+ id,
+ position,
+ properties: value === undefined ? {} : { [propertyId]: value },
+ } as unknown as Issue;
+}
+
+describe("sortIssues property sorts", () => {
+ it("sorts number values numerically, missing values last", () => {
+ const sorted = sortIssues(
+ [issueWith("big", 10), issueWith("none"), issueWith("small", 2)],
+ `property:${propertyId}`,
+ "asc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["small", "big", "none"]);
+ });
+
+ it("desc reverses values but keeps missing values last", () => {
+ const sorted = sortIssues(
+ [issueWith("none"), issueWith("small", 2), issueWith("big", 10)],
+ `property:${propertyId}`,
+ "desc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["big", "small", "none"]);
+ });
+
+ it("sorts date-only strings chronologically via lexical compare", () => {
+ const sorted = sortIssues(
+ [issueWith("later", "2026-08-01"), issueWith("earlier", "2026-07-13")],
+ `property:${propertyId}`,
+ "asc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["earlier", "later"]);
+ });
+
+ it("falls back to position order for the static fields", () => {
+ const sorted = sortIssues(
+ [issueWith("b", undefined, 2), issueWith("a", undefined, 1)],
+ "position",
+ "asc",
+ );
+ expect(sorted.map((i) => i.id)).toEqual(["a", "b"]);
+ });
+});
diff --git a/packages/views/issues/utils/sort.ts b/packages/views/issues/utils/sort.ts
index 818dda569f..9b6c574a01 100644
--- a/packages/views/issues/utils/sort.ts
+++ b/packages/views/issues/utils/sort.ts
@@ -1,6 +1,7 @@
import type { Issue } from "@multica/core/types";
import { PRIORITY_ORDER } from "@multica/core/issues/config";
import type { SortField, SortDirection } from "@multica/core/issues/stores/view-store";
+import { propertyIdFromViewKey } from "@multica/core/issues/stores/view-store";
const PRIORITY_RANK: Record<string, number> = Object.fromEntries(
PRIORITY_ORDER.map((p, i) => [p, i])
@@ -11,6 +12,27 @@ export function sortIssues(
field: SortField,
direction: SortDirection
): Issue[] {
+ // `property:<id>` sorts by the custom-property value. Number values sort
+ // numerically; date values are date-only "YYYY-MM-DD" strings, which sort
+ // correctly lexically. Direction applies to the VALUE comparison only —
+ // issues without a value sort last in both directions (a whole-array
+ // reverse would flip them to the front on desc).
+ const propertyId = propertyIdFromViewKey(field);
+ if (propertyId) {
+ const dir = direction === "desc" ? -1 : 1;
+ return issues.toSorted((a, b) => {
+ const av = a.properties?.[propertyId];
+ const bv = b.properties?.[propertyId];
+ const aMissing = av === undefined || Array.isArray(av);
+ const bMissing = bv === undefined || Array.isArray(bv);
+ if (aMissing && bMissing) return 0;
+ if (aMissing) return 1;
+ if (bMissing) return -1;
+ if (typeof av === "number" && typeof bv === "number") return dir * (av - bv);
+ return dir * String(av).localeCompare(String(bv));
+ });
+ }
+
const sorted = issues.toSorted((a, b) => {
switch (field) {
case "priority":
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index a8ee40e866..a52d871068 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -156,6 +156,7 @@
"add_issue_tooltip": "Add issue",
"empty_column": "No issues",
"empty_grouping": "No matching issues",
+ "no_value": "No value",
"ordered_by": "Board ordered by {{field}}"
},
"detail": {
@@ -475,6 +476,17 @@
"delete_issue": "Delete issue"
},
"pickers": {
+ "custom_property": {
+ "empty": "Empty",
+ "clear_action": "Clear",
+ "true_label": "Yes",
+ "false_label": "No",
+ "value_placeholder": "Enter value…",
+ "url_placeholder": "https://…",
+ "number_placeholder": "0",
+ "open_link": "Open link",
+ "archived_hint": "Archived property — value is read-only"
+ },
"filter_options_aria": "Filter options",
"no_results": "No results",
"assignee": {
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 8f922bb9ae..f9b86b6c20 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -112,7 +112,71 @@
"integrations": "Integrations",
"labs": "Labs",
"members": "Members",
- "labels": "Labels"
+ "labels": "Labels",
+ "properties": "Properties"
+ }
+ },
+ "properties": {
+ "title": "Properties",
+ "description": "Define typed custom properties for issues in this workspace. Values are set on each issue and are readable and writable by agents.",
+ "search_placeholder": "Filter by name...",
+ "new_property": "New property",
+ "show_archived": "Show archived",
+ "columns": {
+ "name": "Name",
+ "type": "Type",
+ "options": "Options",
+ "usage": "Used by",
+ "updated": "Updated"
+ },
+ "usage_count_one": "{{count}} issue",
+ "usage_count_other": "{{count}} issues",
+ "loading": "Loading properties...",
+ "empty": "No properties yet",
+ "empty_hint": "Create typed fields like Severity or Environment — agents can read and write them with validation.",
+ "no_results": "No matching properties",
+ "save_failed": "Couldn't save property",
+ "limit_hint": "{{count}}/{{max}} active properties",
+ "archived_badge": "Archived",
+ "types": {
+ "text": "Text",
+ "number": "Number",
+ "select": "Select",
+ "multi_select": "Multi-select",
+ "date": "Date",
+ "checkbox": "Checkbox",
+ "url": "URL"
+ },
+ "actions": {
+ "open": "Actions for {{name}}",
+ "edit": "Edit",
+ "archive": "Archive",
+ "unarchive": "Restore"
+ },
+ "editor": {
+ "create_title": "New property",
+ "edit_title": "Edit property",
+ "admin_hint": "Only workspace owners and admins can manage property definitions.",
+ "name": "Name",
+ "name_placeholder": "e.g. Severity",
+ "type": "Type",
+ "type_locked_hint": "Type can't be changed after creation.",
+ "description": "Description",
+ "description_placeholder": "What this property means and when to set it",
+ "options": "Options",
+ "option_name_placeholder": "Option name",
+ "add_option": "Add option",
+ "remove_option": "Remove option",
+ "cancel": "Cancel",
+ "save": "Save property",
+ "saving": "Saving..."
+ },
+ "archive_dialog": {
+ "title": "Archive property?",
+ "description": "\"{{name}}\" will be hidden from pickers and filters. Existing values on issues are preserved. You can restore it later.",
+ "cancel": "Cancel",
+ "confirm": "Archive property",
+ "failed": "Couldn't archive property"
}
},
"labels": {
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 6cf0a6ed90..6f879a2167 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -154,6 +154,7 @@
"add_issue_tooltip": "イシューを追加",
"empty_column": "イシューなし",
"empty_grouping": "一致するイシューがありません",
+ "no_value": "値なし",
"ordered_by": "{{field}} 順に並べたボード"
},
"detail": {
@@ -453,6 +454,17 @@
"delete_issue": "イシューを削除"
},
"pickers": {
+ "custom_property": {
+ "empty": "空",
+ "clear_action": "クリア",
+ "true_label": "はい",
+ "false_label": "いいえ",
+ "value_placeholder": "値を入力…",
+ "url_placeholder": "https://…",
+ "number_placeholder": "0",
+ "open_link": "リンクを開く",
+ "archived_hint": "アーカイブ済みプロパティ — 値は読み取り専用です"
+ },
"filter_options_aria": "フィルターオプション",
"no_results": "結果なし",
"assignee": {
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index c8565ed210..ca6109f44f 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -109,7 +109,70 @@
"integrations": "連携",
"labs": "ラボ",
"members": "メンバー",
- "labels": "ラベル"
+ "labels": "ラベル",
+ "properties": "プロパティ"
+ }
+ },
+ "properties": {
+ "title": "プロパティ",
+ "description": "このワークスペースの Issue に型付きカスタムプロパティを定義します。値は各 Issue に設定され、エージェントが読み書きできます。",
+ "search_placeholder": "名前で絞り込み...",
+ "new_property": "新規プロパティ",
+ "show_archived": "アーカイブ済みを表示",
+ "columns": {
+ "name": "名前",
+ "type": "タイプ",
+ "options": "オプション",
+ "usage": "使用数",
+ "updated": "更新日時"
+ },
+ "usage_count_other": "{{count}} 件の Issue",
+ "loading": "プロパティを読み込み中...",
+ "empty": "プロパティはまだありません",
+ "empty_hint": "Severity や Environment のような型付きフィールドを作成できます。エージェントはバリデーション付きで読み書きします。",
+ "no_results": "一致するプロパティがありません",
+ "save_failed": "プロパティを保存できませんでした",
+ "limit_hint": "{{count}}/{{max}} 個の有効なプロパティ",
+ "archived_badge": "アーカイブ済み",
+ "types": {
+ "text": "テキスト",
+ "number": "数値",
+ "select": "選択",
+ "multi_select": "複数選択",
+ "date": "日付",
+ "checkbox": "チェックボックス",
+ "url": "URL"
+ },
+ "actions": {
+ "open": "{{name}} の操作",
+ "edit": "編集",
+ "archive": "アーカイブ",
+ "unarchive": "復元"
+ },
+ "editor": {
+ "create_title": "新規プロパティ",
+ "edit_title": "プロパティを編集",
+ "admin_hint": "プロパティ定義を管理できるのはワークスペースのオーナーと管理者のみです。",
+ "name": "名前",
+ "name_placeholder": "例: Severity",
+ "type": "タイプ",
+ "type_locked_hint": "作成後にタイプは変更できません。",
+ "description": "説明",
+ "description_placeholder": "このプロパティの意味と設定するタイミング",
+ "options": "オプション",
+ "option_name_placeholder": "オプション名",
+ "add_option": "オプションを追加",
+ "remove_option": "オプションを削除",
+ "cancel": "キャンセル",
+ "save": "プロパティを保存",
+ "saving": "保存中..."
+ },
+ "archive_dialog": {
+ "title": "プロパティをアーカイブしますか?",
+ "description": "「{{name}}」はピッカーとフィルターから非表示になります。Issue 上の既存の値は保持され、後で復元できます。",
+ "cancel": "キャンセル",
+ "confirm": "プロパティをアーカイブ",
+ "failed": "プロパティをアーカイブできませんでした"
}
},
"labels": {
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 51093f66ca..335e6dda1c 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -154,6 +154,7 @@
"add_issue_tooltip": "이슈 추가",
"empty_column": "이슈 없음",
"empty_grouping": "일치하는 이슈가 없습니다",
+ "no_value": "값 없음",
"ordered_by": "{{field}} 기준으로 정렬된 보드"
},
"detail": {
@@ -453,6 +454,17 @@
"delete_issue": "이슈 삭제"
},
"pickers": {
+ "custom_property": {
+ "empty": "비어 있음",
+ "clear_action": "지우기",
+ "true_label": "예",
+ "false_label": "아니요",
+ "value_placeholder": "값 입력…",
+ "url_placeholder": "https://…",
+ "number_placeholder": "0",
+ "open_link": "링크 열기",
+ "archived_hint": "보관된 속성 — 값은 읽기 전용입니다"
+ },
"filter_options_aria": "필터 옵션",
"no_results": "결과 없음",
"assignee": {
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 76ba30ec42..d4659111e4 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -109,7 +109,70 @@
"integrations": "연동",
"labs": "실험실",
"members": "멤버",
- "labels": "레이블"
+ "labels": "레이블",
+ "properties": "속성"
+ }
+ },
+ "properties": {
+ "title": "속성",
+ "description": "이 워크스페이스의 Issue에 타입이 있는 사용자 지정 속성을 정의합니다. 값은 각 Issue에 설정되며 에이전트가 읽고 쓸 수 있습니다.",
+ "search_placeholder": "이름으로 필터...",
+ "new_property": "새 속성",
+ "show_archived": "보관된 항목 표시",
+ "columns": {
+ "name": "이름",
+ "type": "유형",
+ "options": "옵션",
+ "usage": "사용",
+ "updated": "업데이트"
+ },
+ "usage_count_other": "{{count}}개 Issue",
+ "loading": "속성을 불러오는 중...",
+ "empty": "아직 속성이 없습니다",
+ "empty_hint": "Severity, Environment 같은 타입 필드를 만들어 보세요. 에이전트가 검증과 함께 읽고 씁니다.",
+ "no_results": "일치하는 속성이 없습니다",
+ "save_failed": "속성을 저장하지 못했습니다",
+ "limit_hint": "활성 속성 {{count}}/{{max}}",
+ "archived_badge": "보관됨",
+ "types": {
+ "text": "텍스트",
+ "number": "숫자",
+ "select": "선택",
+ "multi_select": "다중 선택",
+ "date": "날짜",
+ "checkbox": "체크박스",
+ "url": "URL"
+ },
+ "actions": {
+ "open": "{{name}} 작업",
+ "edit": "편집",
+ "archive": "보관",
+ "unarchive": "복원"
+ },
+ "editor": {
+ "create_title": "새 속성",
+ "edit_title": "속성 편집",
+ "admin_hint": "워크스페이스 소유자와 관리자만 속성 정의를 관리할 수 있습니다.",
+ "name": "이름",
+ "name_placeholder": "예: Severity",
+ "type": "유형",
+ "type_locked_hint": "생성 후에는 유형을 변경할 수 없습니다.",
+ "description": "설명",
+ "description_placeholder": "이 속성의 의미와 설정 시점",
+ "options": "옵션",
+ "option_name_placeholder": "옵션 이름",
+ "add_option": "옵션 추가",
+ "remove_option": "옵션 제거",
+ "cancel": "취소",
+ "save": "속성 저장",
+ "saving": "저장 중..."
+ },
+ "archive_dialog": {
+ "title": "속성을 보관할까요?",
+ "description": "\"{{name}}\"이(가) 선택기와 필터에서 숨겨집니다. Issue의 기존 값은 유지되며 나중에 복원할 수 있습니다.",
+ "cancel": "취소",
+ "confirm": "속성 보관",
+ "failed": "속성을 보관하지 못했습니다"
}
},
"labels": {
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index 65da60527f..fd992cb8a9 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -154,6 +154,7 @@
"add_issue_tooltip": "新建 issue",
"empty_column": "无 issue",
"empty_grouping": "没有匹配的 issue",
+ "no_value": "未设置",
"ordered_by": "按{{field}}排序"
},
"detail": {
@@ -453,6 +454,17 @@
"delete_issue": "删除 issue"
},
"pickers": {
+ "custom_property": {
+ "empty": "空",
+ "clear_action": "清除",
+ "true_label": "是",
+ "false_label": "否",
+ "value_placeholder": "输入值…",
+ "url_placeholder": "https://…",
+ "number_placeholder": "0",
+ "open_link": "打开链接",
+ "archived_hint": "已归档属性——值为只读"
+ },
"filter_options_aria": "筛选选项",
"no_results": "无结果",
"assignee": {
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index e59b3866e2..3377bb5814 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -112,7 +112,70 @@
"integrations": "集成",
"labs": "实验室",
"members": "成员",
- "labels": "标签"
+ "labels": "标签",
+ "properties": "属性"
+ }
+ },
+ "properties": {
+ "title": "属性",
+ "description": "为该工作区的 Issue 定义类型化的自定义属性。属性值设置在每个 Issue 上,agent 可读写。",
+ "search_placeholder": "按名称筛选...",
+ "new_property": "新建属性",
+ "show_archived": "显示已归档",
+ "columns": {
+ "name": "名称",
+ "type": "类型",
+ "options": "选项",
+ "usage": "使用",
+ "updated": "更新时间"
+ },
+ "usage_count_other": "{{count}} 个 Issue",
+ "loading": "正在加载属性...",
+ "empty": "还没有属性",
+ "empty_hint": "创建 Severity、Environment 这类类型化字段——agent 可带校验地读写它们。",
+ "no_results": "没有匹配的属性",
+ "save_failed": "保存属性失败",
+ "limit_hint": "{{count}}/{{max}} 个启用中属性",
+ "archived_badge": "已归档",
+ "types": {
+ "text": "文本",
+ "number": "数字",
+ "select": "单选",
+ "multi_select": "多选",
+ "date": "日期",
+ "checkbox": "勾选",
+ "url": "链接"
+ },
+ "actions": {
+ "open": "{{name}} 的操作",
+ "edit": "编辑",
+ "archive": "归档",
+ "unarchive": "恢复"
+ },
+ "editor": {
+ "create_title": "新建属性",
+ "edit_title": "编辑属性",
+ "admin_hint": "仅工作区 Owner 和 Admin 可以管理属性定义。",
+ "name": "名称",
+ "name_placeholder": "例如 Severity",
+ "type": "类型",
+ "type_locked_hint": "创建后类型不可修改。",
+ "description": "描述",
+ "description_placeholder": "这个属性的含义以及何时设置",
+ "options": "选项",
+ "option_name_placeholder": "选项名称",
+ "add_option": "添加选项",
+ "remove_option": "移除选项",
+ "cancel": "取消",
+ "save": "保存属性",
+ "saving": "保存中..."
+ },
+ "archive_dialog": {
+ "title": "归档属性?",
+ "description": "“{{name}}”将从选择器和筛选中隐藏,Issue 上已有的值会保留。之后可以恢复。",
+ "cancel": "取消",
+ "confirm": "归档属性",
+ "failed": "归档属性失败"
}
},
"labels": {
diff --git a/packages/views/settings/components/properties-tab.tsx b/packages/views/settings/components/properties-tab.tsx
new file mode 100644
index 0000000000..3b21492b1b
--- /dev/null
+++ b/packages/views/settings/components/properties-tab.tsx
@@ -0,0 +1,648 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import {
+ Archive,
+ ArchiveRestore,
+ GripVertical,
+ MoreHorizontal,
+ Pencil,
+ Plus,
+ Search,
+ SlidersHorizontal,
+ X,
+} from "lucide-react";
+import { toast } from "sonner";
+import { useAuthStore } from "@multica/core/auth";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { memberListOptions } from "@multica/core/workspace/queries";
+import {
+ propertyListOptions,
+ useCreateProperty,
+ useUpdateProperty,
+} from "@multica/core/properties";
+import type {
+ IssueProperty,
+ IssuePropertyOption,
+ IssuePropertyType,
+} from "@multica/core/types";
+import { ISSUE_PROPERTY_TYPES } from "@multica/core/types";
+import { Button } from "@multica/ui/components/ui/button";
+import { Badge } from "@multica/ui/components/ui/badge";
+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 { Switch } from "@multica/ui/components/ui/switch";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+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 { useT } from "../../i18n";
+import { SettingsTab } from "./settings-layout";
+
+const MAX_ACTIVE_PROPERTIES = 20;
+const OPTION_COLORS = [
+ "#6b7280",
+ "#ef4444",
+ "#f97316",
+ "#eab308",
+ "#22c55e",
+ "#14b8a6",
+ "#3b82f6",
+ "#6366f1",
+ "#a855f7",
+ "#ec4899",
+] as const;
+
+interface OptionDraft {
+ id?: string;
+ name: string;
+ color: string;
+}
+
+interface PropertyDraft {
+ name: string;
+ type: IssuePropertyType;
+ description: string;
+ options: OptionDraft[];
+}
+
+const EMPTY_DRAFT: PropertyDraft = {
+ name: "",
+ type: "select",
+ description: "",
+ options: [{ name: "", color: OPTION_COLORS[6] }],
+};
+
+function typeHasOptions(type: string): boolean {
+ return type === "select" || type === "multi_select";
+}
+
+export function PropertiesTab() {
+ const { t } = useT("settings");
+ const wsId = useWorkspaceId();
+ const user = useAuthStore((s) => s.user);
+
+ const [query, setQuery] = useState("");
+ const [showArchived, setShowArchived] = useState(false);
+ const [editing, setEditing] = useState<IssueProperty | null>(null);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [pendingArchive, setPendingArchive] = useState<IssueProperty | null>(null);
+
+ const { data: members = [] } = useQuery(memberListOptions(wsId));
+ const currentMember = members.find((m) => m.user_id === user?.id) ?? null;
+ const canManage = currentMember?.role === "owner" || currentMember?.role === "admin";
+
+ const { data: properties = [], isLoading } = useQuery(propertyListOptions(wsId, true));
+ const update = useUpdateProperty();
+
+ const activeCount = useMemo(
+ () => properties.filter((p) => !p.archived).length,
+ [properties],
+ );
+ const visible = useMemo(() => {
+ const normalized = query.trim().toLowerCase();
+ return properties
+ .filter((p) => (showArchived ? true : !p.archived))
+ .filter((p) => !normalized || p.name.toLowerCase().includes(normalized));
+ }, [properties, query, showArchived]);
+
+ return (
+ <SettingsTab
+ title={t(($) => $.properties.title)}
+ description={t(($) => $.properties.description)}
+ >
+ <div className="space-y-5">
+ <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(($) => $.properties.search_placeholder)}
+ className="pl-9"
+ />
+ </div>
+ <div className="flex items-center gap-4">
+ <label className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Switch checked={showArchived} onCheckedChange={setShowArchived} />
+ {t(($) => $.properties.show_archived)}
+ </label>
+ <span className="text-xs tabular-nums text-muted-foreground">
+ {t(($) => $.properties.limit_hint, {
+ count: activeCount,
+ max: MAX_ACTIVE_PROPERTIES,
+ })}
+ </span>
+ {canManage && (
+ <Button
+ className="gap-2"
+ onClick={() => setCreateOpen(true)}
+ disabled={activeCount >= MAX_ACTIVE_PROPERTIES}
+ >
+ <Plus className="size-4" />
+ {t(($) => $.properties.new_property)}
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {!canManage && (
+ <p className="text-xs text-muted-foreground">
+ {t(($) => $.properties.editor.admin_hint)}
+ </p>
+ )}
+
+ <div className="overflow-hidden rounded-lg border border-surface-border bg-card">
+ <div className="hidden grid-cols-[minmax(10rem,1fr)_6rem_minmax(10rem,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(($) => $.properties.columns.name)}</span>
+ <span>{t(($) => $.properties.columns.type)}</span>
+ <span>{t(($) => $.properties.columns.options)}</span>
+ <span>{t(($) => $.properties.columns.usage)}</span>
+ <span>{t(($) => $.properties.columns.updated)}</span>
+ <span />
+ </div>
+
+ {isLoading ? (
+ <div className="px-4 py-12 text-center text-sm text-muted-foreground">
+ {t(($) => $.properties.loading)}
+ </div>
+ ) : visible.length === 0 ? (
+ <div className="px-4 py-12 text-center">
+ <SlidersHorizontal className="mx-auto size-6 text-muted-foreground/60" />
+ <p className="mt-3 text-sm font-medium">
+ {query
+ ? t(($) => $.properties.no_results)
+ : t(($) => $.properties.empty)}
+ </p>
+ {!query && (
+ <p className="mx-auto mt-1 max-w-sm text-xs text-muted-foreground">
+ {t(($) => $.properties.empty_hint)}
+ </p>
+ )}
+ </div>
+ ) : (
+ <div className="divide-y divide-surface-border">
+ {visible.map((property) => (
+ <div
+ key={property.id}
+ className="grid gap-2 px-4 py-3 md:grid-cols-[minmax(10rem,1fr)_6rem_minmax(10rem,1.4fr)_6rem_7rem_2rem] md:items-center md:gap-4"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate text-sm font-medium">{property.name}</span>
+ {property.archived && (
+ <Badge variant="outline" className="shrink-0 text-[10px]">
+ {t(($) => $.properties.archived_badge)}
+ </Badge>
+ )}
+ </div>
+ <span className="text-xs text-muted-foreground md:text-sm">
+ <PropertyTypeLabel type={property.type} />
+ </span>
+ <div className="flex min-w-0 flex-wrap items-center gap-1">
+ {(property.config.options ?? []).slice(0, 6).map((option) => (
+ <span
+ key={option.id}
+ className="inline-flex items-center gap-1.5 rounded-full border border-surface-border px-2 py-0.5 text-xs"
+ >
+ <span
+ className="size-2 rounded-full"
+ style={{ backgroundColor: option.color }}
+ />
+ {option.name}
+ </span>
+ ))}
+ {(property.config.options?.length ?? 0) > 6 && (
+ <span className="text-xs text-muted-foreground">
+ +{(property.config.options?.length ?? 0) - 6}
+ </span>
+ )}
+ {!typeHasOptions(property.type) && (
+ <span className="text-xs text-muted-foreground">—</span>
+ )}
+ </div>
+ <span className="text-xs tabular-nums text-muted-foreground md:text-sm">
+ {t(($) => $.properties.usage_count, { count: property.usage_count ?? 0 })}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {new Date(property.updated_at).toLocaleDateString()}
+ </span>
+ {canManage ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.properties.actions.open, { name: property.name })}
+ >
+ <MoreHorizontal className="size-4" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(property)}>
+ <Pencil className="size-4" />
+ {t(($) => $.properties.actions.edit)}
+ </DropdownMenuItem>
+ {property.archived ? (
+ <DropdownMenuItem
+ onClick={() =>
+ update.mutate(
+ { id: property.id, archived: false },
+ {
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.properties.save_failed),
+ ),
+ },
+ )
+ }
+ >
+ <ArchiveRestore className="size-4" />
+ {t(($) => $.properties.actions.unarchive)}
+ </DropdownMenuItem>
+ ) : (
+ <DropdownMenuItem
+ variant="destructive"
+ onClick={() => setPendingArchive(property)}
+ >
+ <Archive className="size-4" />
+ {t(($) => $.properties.actions.archive)}
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <span />
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <PropertyEditorDialog open={createOpen} onOpenChange={setCreateOpen} />
+ <PropertyEditorDialog
+ open={Boolean(editing)}
+ onOpenChange={(open) => !open && setEditing(null)}
+ property={editing}
+ />
+ <ArchivePropertyDialog
+ property={pendingArchive}
+ onClose={() => setPendingArchive(null)}
+ />
+ </SettingsTab>
+ );
+}
+
+export function PropertyTypeLabel({ type }: { type: string }) {
+ const { t } = useT("settings");
+ switch (type) {
+ case "text":
+ return <>{t(($) => $.properties.types.text)}</>;
+ case "number":
+ return <>{t(($) => $.properties.types.number)}</>;
+ case "select":
+ return <>{t(($) => $.properties.types.select)}</>;
+ case "multi_select":
+ return <>{t(($) => $.properties.types.multi_select)}</>;
+ case "date":
+ return <>{t(($) => $.properties.types.date)}</>;
+ case "checkbox":
+ return <>{t(($) => $.properties.types.checkbox)}</>;
+ case "url":
+ return <>{t(($) => $.properties.types.url)}</>;
+ default:
+ // Forward compat: newer servers may ship types this build doesn't know.
+ return <>{type}</>;
+ }
+}
+
+function PropertyEditorDialog({
+ open,
+ onOpenChange,
+ property,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ property?: IssueProperty | null;
+}) {
+ const { t } = useT("settings");
+ const create = useCreateProperty();
+ const update = useUpdateProperty();
+ const [draft, setDraft] = useState<PropertyDraft>(EMPTY_DRAFT);
+
+ useEffect(() => {
+ if (!open) return;
+ setDraft(
+ property
+ ? {
+ name: property.name,
+ type: (property.type as IssuePropertyType) ?? "text",
+ description: property.description ?? "",
+ options: (property.config.options ?? []).map((option: IssuePropertyOption) => ({
+ id: option.id,
+ name: option.name,
+ color: option.color,
+ })),
+ }
+ : EMPTY_DRAFT,
+ );
+ }, [property, open]);
+
+ const showOptions = typeHasOptions(draft.type);
+ const validOptions = draft.options.filter((option) => option.name.trim());
+ const canSubmit =
+ draft.name.trim().length > 0 && (!showOptions || validOptions.length > 0);
+
+ const submit = () => {
+ if (!canSubmit) return;
+ const config = showOptions
+ ? {
+ options: validOptions.map((option) => ({
+ id: option.id ?? "",
+ name: option.name.trim(),
+ color: option.color,
+ })),
+ }
+ : undefined;
+ const onError = (error: unknown) =>
+ toast.error(
+ error instanceof Error ? error.message : t(($) => $.properties.save_failed),
+ );
+ if (property) {
+ update.mutate(
+ {
+ id: property.id,
+ name: draft.name.trim(),
+ description: draft.description.trim(),
+ ...(config ? { config } : {}),
+ },
+ { onSuccess: () => onOpenChange(false), onError },
+ );
+ return;
+ }
+ create.mutate(
+ {
+ name: draft.name.trim(),
+ type: draft.type,
+ description: draft.description.trim(),
+ ...(config ? { config } : {}),
+ },
+ { onSuccess: () => onOpenChange(false), onError },
+ );
+ };
+
+ const setOption = (index: number, patch: Partial<OptionDraft>) => {
+ setDraft((current) => ({
+ ...current,
+ options: current.options.map((option, i) =>
+ i === index ? { ...option, ...patch } : option,
+ ),
+ }));
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>
+ {property
+ ? t(($) => $.properties.editor.edit_title)
+ : t(($) => $.properties.editor.create_title)}
+ </DialogTitle>
+ <DialogDescription>
+ {t(($) => $.properties.editor.admin_hint)}
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5 py-2">
+ <div className="grid grid-cols-[1fr_10rem] gap-3">
+ <div className="space-y-2">
+ <FieldLabel htmlFor="property-name">
+ {t(($) => $.properties.editor.name)}
+ </FieldLabel>
+ <Input
+ id="property-name"
+ autoFocus
+ maxLength={32}
+ value={draft.name}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, name: event.target.value }))
+ }
+ placeholder={t(($) => $.properties.editor.name_placeholder)}
+ />
+ </div>
+ <div className="space-y-2">
+ <FieldLabel>{t(($) => $.properties.editor.type)}</FieldLabel>
+ {property ? (
+ <div
+ className="flex h-9 items-center rounded-md border border-surface-border px-3 text-sm text-muted-foreground"
+ title={t(($) => $.properties.editor.type_locked_hint)}
+ >
+ <PropertyTypeLabel type={property.type} />
+ </div>
+ ) : (
+ <Select
+ value={draft.type}
+ onValueChange={(value) =>
+ value &&
+ setDraft((current) => ({
+ ...current,
+ type: value as IssuePropertyType,
+ options:
+ typeHasOptions(value) && current.options.length === 0
+ ? [{ name: "", color: OPTION_COLORS[6] }]
+ : current.options,
+ }))
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {ISSUE_PROPERTY_TYPES.map((type) => (
+ <SelectItem key={type} value={type}>
+ <PropertyTypeLabel type={type} />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </div>
+ </div>
+ <div className="space-y-2">
+ <FieldLabel htmlFor="property-description">
+ {t(($) => $.properties.editor.description)}
+ </FieldLabel>
+ <Textarea
+ id="property-description"
+ rows={2}
+ value={draft.description}
+ onChange={(event) =>
+ setDraft((current) => ({ ...current, description: event.target.value }))
+ }
+ placeholder={t(($) => $.properties.editor.description_placeholder)}
+ />
+ </div>
+ {showOptions && (
+ <div className="space-y-2">
+ <FieldLabel>{t(($) => $.properties.editor.options)}</FieldLabel>
+ <div className="space-y-2">
+ {draft.options.map((option, index) => (
+ <div key={option.id ?? index} className="flex items-center gap-2">
+ <GripVertical className="size-4 shrink-0 text-muted-foreground/40" />
+ <label
+ className="relative size-6 shrink-0 cursor-pointer overflow-hidden rounded-full border border-surface-border"
+ style={{ backgroundColor: option.color }}
+ >
+ <input
+ type="color"
+ value={option.color}
+ onChange={(event) => setOption(index, { color: event.target.value })}
+ className="absolute inset-0 cursor-pointer opacity-0"
+ aria-label={option.color}
+ />
+ </label>
+ <Input
+ value={option.name}
+ maxLength={32}
+ onChange={(event) => setOption(index, { name: event.target.value })}
+ placeholder={t(($) => $.properties.editor.option_name_placeholder)}
+ className="h-8"
+ />
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.properties.editor.remove_option)}
+ disabled={draft.options.length <= 1}
+ onClick={() =>
+ setDraft((current) => ({
+ ...current,
+ options: current.options.filter((_, i) => i !== index),
+ }))
+ }
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="gap-2"
+ onClick={() =>
+ setDraft((current) => ({
+ ...current,
+ options: [
+ ...current.options,
+ {
+ name: "",
+ color: OPTION_COLORS[current.options.length % OPTION_COLORS.length] ?? OPTION_COLORS[6],
+ },
+ ],
+ }))
+ }
+ >
+ <Plus className="size-3.5" />
+ {t(($) => $.properties.editor.add_option)}
+ </Button>
+ </div>
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => onOpenChange(false)}>
+ {t(($) => $.properties.editor.cancel)}
+ </Button>
+ <Button
+ onClick={submit}
+ disabled={!canSubmit || create.isPending || update.isPending}
+ >
+ {create.isPending || update.isPending
+ ? t(($) => $.properties.editor.saving)
+ : t(($) => $.properties.editor.save)}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function ArchivePropertyDialog({
+ property,
+ onClose,
+}: {
+ property: IssueProperty | null;
+ onClose: () => void;
+}) {
+ const { t } = useT("settings");
+ const update = useUpdateProperty();
+ return (
+ <AlertDialog open={Boolean(property)} onOpenChange={(open) => !open && onClose()}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t(($) => $.properties.archive_dialog.title)}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(($) => $.properties.archive_dialog.description, {
+ name: property?.name ?? "",
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>{t(($) => $.properties.archive_dialog.cancel)}</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={() => {
+ if (!property) return;
+ update.mutate(
+ { id: property.id, archived: true },
+ {
+ onSuccess: onClose,
+ onError: (error) =>
+ toast.error(
+ error instanceof Error
+ ? error.message
+ : t(($) => $.properties.archive_dialog.failed),
+ ),
+ },
+ );
+ }}
+ >
+ {t(($) => $.properties.archive_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 480e6f972b..67f9e49b60 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -32,6 +32,7 @@ import { IntegrationsTab } from "./integrations-tab";
import { LabsTab } from "./labs-tab";
import { NotificationsTab } from "./notifications-tab";
import { LabelsTab } from "./labels-tab";
+import { PropertiesTab } from "./properties-tab";
import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
import { useT } from "../../i18n";
@@ -53,6 +54,7 @@ const WORKSPACE_TAB_KEYS = [
"labs",
"members",
"labels",
+ "properties",
] as const;
const WORKSPACE_TAB_VALUES = {
general: "workspace",
@@ -62,6 +64,7 @@ const WORKSPACE_TAB_VALUES = {
labs: "labs",
members: "members",
labels: "labels",
+ properties: "properties",
} as const;
const WORKSPACE_TAB_ICONS = {
general: Settings,
@@ -71,6 +74,7 @@ const WORKSPACE_TAB_ICONS = {
labs: FlaskConical,
members: Users,
labels: Tags,
+ properties: SlidersHorizontal,
} as const;
const DEFAULT_TAB = "profile";
@@ -200,7 +204,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 p-4 sm:p-6 md:p-8 ${activeTab === "labels" ? "max-w-5xl" : "max-w-3xl"}`}>
+ <div className={`mx-auto w-full p-4 sm:p-6 md:p-8 ${activeTab === "labels" || activeTab === "properties" ? "max-w-5xl" : "max-w-3xl"}`}>
<TabsContent value="profile"><AccountTab /></TabsContent>
<TabsContent value="preferences"><PreferencesTab /></TabsContent>
<TabsContent value="shortcuts"><KeyboardShortcutsTab /></TabsContent>
@@ -214,6 +218,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<TabsContent value="labs"><LabsTab /></TabsContent>
<TabsContent value="members"><MembersTab /></TabsContent>
<TabsContent value="labels"><LabelsTab /></TabsContent>
+ <TabsContent value="properties"><PropertiesTab /></TabsContent>
{extraAccountTabs?.map((tab) => (
<TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>
))}
diff --git a/server/cmd/multica/cmd_property.go b/server/cmd/multica/cmd_property.go
new file mode 100644
index 0000000000..e39444c7f3
--- /dev/null
+++ b/server/cmd/multica/cmd_property.go
@@ -0,0 +1,686 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// multica property {list|get|create|update|archive|unarchive} — workspace
+// custom property definitions, and multica issue property {list|set|unset} —
+// typed values on a single issue. See server/internal/handler/property.go
+// for the validation contract (7 types, 20 active definitions/workspace,
+// owner/admin-only definition management, agents rejected on definition
+// writes).
+//
+// CLI ergonomics: properties and select options are addressed BY NAME
+// (case-insensitive); the CLI translates names to the UUIDs the API expects,
+// so agents never have to juggle option ids.
+
+type propertyOptionDTO struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Color string `json:"color"`
+}
+
+type propertyDTO struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config struct {
+ Options []propertyOptionDTO `json:"options"`
+ } `json:"config"`
+ Position float64 `json:"position"`
+ Archived bool `json:"archived"`
+ UsageCount int64 `json:"usage_count"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+var propertyCmd = &cobra.Command{
+ Use: "property",
+ Short: "Manage workspace custom issue properties",
+}
+
+var propertyListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List property definitions",
+ Args: exactArgs(0),
+ RunE: runPropertyList,
+}
+
+var propertyGetCmd = &cobra.Command{
+ Use: "get <id-or-name>",
+ Short: "Show one property definition",
+ Args: exactArgs(1),
+ RunE: runPropertyGet,
+}
+
+var propertyCreateCmd = &cobra.Command{
+ Use: "create",
+ Short: "Create a property definition (workspace owner/admin only)",
+ Long: `Create a property definition. Types: text, number, select, multi_select,
+date, checkbox, url. Select types take repeatable --option flags:
+ multica property create --name Severity --type select \
+ --option "Critical:#ef4444" --option "Major:#f59e0b" --option "Minor:#6b7280"
+The ":#rrggbb" color suffix is optional.`,
+ Args: exactArgs(0),
+ RunE: runPropertyCreate,
+}
+
+var propertyUpdateCmd = &cobra.Command{
+ Use: "update <id-or-name>",
+ Short: "Update a property definition (owner/admin only; type is immutable)",
+ Long: `Update a property definition. --option flags REPLACE the full option list;
+existing options are matched by name so their ids (and issue values) survive.`,
+ Args: exactArgs(1),
+ RunE: runPropertyUpdate,
+}
+
+var propertyArchiveCmd = &cobra.Command{
+ Use: "archive <id-or-name>",
+ Short: "Archive a property definition (hidden from pickers; values preserved)",
+ Args: exactArgs(1),
+ RunE: makePropertyArchiveRun(true),
+}
+
+var propertyUnarchiveCmd = &cobra.Command{
+ Use: "unarchive <id-or-name>",
+ Short: "Restore an archived property definition",
+ Args: exactArgs(1),
+ RunE: makePropertyArchiveRun(false),
+}
+
+var issuePropertyCmd = &cobra.Command{
+ Use: "property",
+ Short: "Manage custom property values on an issue",
+}
+
+var issuePropertyListCmd = &cobra.Command{
+ Use: "list <issue-id>",
+ Short: "List custom property values set on an issue",
+ Args: exactArgs(1),
+ RunE: runIssuePropertyList,
+}
+
+var issuePropertySetCmd = &cobra.Command{
+ Use: "set <issue-id>",
+ Short: "Set a custom property value on an issue",
+ Long: `Set a custom property value. The property is addressed by --name
+(case-insensitive) or UUID. Value forms by type:
+ select --value Staging (option name or id)
+ multi_select --value "iOS,Android" (comma-separated option names or ids)
+ checkbox --value true|false
+ number --value 3.5
+ date --value 2026-07-13
+ text / url --value "any string"`,
+ Args: exactArgs(1),
+ RunE: runIssuePropertySet,
+}
+
+var issuePropertyUnsetCmd = &cobra.Command{
+ Use: "unset <issue-id>",
+ Short: "Remove a custom property value from an issue",
+ Args: exactArgs(1),
+ RunE: runIssuePropertyUnset,
+}
+
+func init() {
+ propertyCmd.AddCommand(propertyListCmd)
+ propertyCmd.AddCommand(propertyGetCmd)
+ propertyCmd.AddCommand(propertyCreateCmd)
+ propertyCmd.AddCommand(propertyUpdateCmd)
+ propertyCmd.AddCommand(propertyArchiveCmd)
+ propertyCmd.AddCommand(propertyUnarchiveCmd)
+
+ propertyListCmd.Flags().String("output", "table", "Output format: table or json")
+ propertyListCmd.Flags().Bool("include-archived", false, "Include archived properties")
+ propertyGetCmd.Flags().String("output", "json", "Output format: table or json")
+ propertyCreateCmd.Flags().String("output", "table", "Output format: table or json")
+ propertyCreateCmd.Flags().String("name", "", "Property name (required)")
+ propertyCreateCmd.Flags().String("type", "", "Property type: text, number, select, multi_select, date, checkbox, url (required)")
+ propertyCreateCmd.Flags().String("description", "", "Property description")
+ propertyCreateCmd.Flags().StringArray("option", nil, `Select option as "Name" or "Name:#rrggbb" (repeatable; select types only)`)
+ propertyUpdateCmd.Flags().String("output", "table", "Output format: table or json")
+ propertyUpdateCmd.Flags().String("name", "", "New property name")
+ propertyUpdateCmd.Flags().String("description", "", "New property description")
+ propertyUpdateCmd.Flags().StringArray("option", nil, `Replacement option list as "Name" or "Name:#rrggbb" (repeatable)`)
+ propertyArchiveCmd.Flags().String("output", "table", "Output format: table or json")
+ propertyUnarchiveCmd.Flags().String("output", "table", "Output format: table or json")
+
+ issuePropertyCmd.AddCommand(issuePropertyListCmd)
+ issuePropertyCmd.AddCommand(issuePropertySetCmd)
+ issuePropertyCmd.AddCommand(issuePropertyUnsetCmd)
+
+ issuePropertyListCmd.Flags().String("output", "table", "Output format: table or json")
+ issuePropertySetCmd.Flags().String("output", "table", "Output format: table or json")
+ issuePropertySetCmd.Flags().String("name", "", "Property name or UUID (required)")
+ issuePropertySetCmd.Flags().String("value", "", "Property value (required; see --help for per-type forms)")
+ issuePropertyUnsetCmd.Flags().String("output", "table", "Output format: table or json")
+ issuePropertyUnsetCmd.Flags().String("name", "", "Property name or UUID (required)")
+
+ issueCmd.AddCommand(issuePropertyCmd)
+}
+
+// fetchProperties loads the full definition catalog (including archived — the
+// callers that must exclude archived filter locally, and value resolution for
+// display needs archived definitions too).
+func fetchProperties(ctx context.Context, client *cli.APIClient) ([]propertyDTO, error) {
+ var result struct {
+ Properties []propertyDTO `json:"properties"`
+ }
+ if err := client.GetJSON(ctx, "/api/properties?include_archived=true", &result); err != nil {
+ return nil, fmt.Errorf("list properties: %w", err)
+ }
+ return result.Properties, nil
+}
+
+// resolvePropertyRef matches a CLI ref against the catalog by UUID first,
+// then case-insensitive name.
+func resolvePropertyRef(properties []propertyDTO, ref string) (propertyDTO, error) {
+ for _, p := range properties {
+ if p.ID == ref {
+ return p, nil
+ }
+ }
+ lower := strings.ToLower(strings.TrimSpace(ref))
+ for _, p := range properties {
+ if strings.ToLower(p.Name) == lower {
+ return p, nil
+ }
+ }
+ names := make([]string, len(properties))
+ for i, p := range properties {
+ names[i] = p.Name
+ }
+ return propertyDTO{}, fmt.Errorf("property %q not found; available: %s", ref, strings.Join(names, ", "))
+}
+
+// parseOptionFlags converts repeatable --option flags ("Name" or
+// "Name:#rrggbb") into config options. When updating, pass the existing
+// options so same-named options keep their ids (issue values reference ids).
+const defaultOptionColor = "#6b7280"
+
+func parseOptionFlags(flags []string, existing []propertyOptionDTO) []map[string]string {
+ byName := make(map[string]string, len(existing))
+ for _, opt := range existing {
+ byName[strings.ToLower(opt.Name)] = opt.ID
+ }
+ out := make([]map[string]string, 0, len(flags))
+ for _, raw := range flags {
+ name := raw
+ color := defaultOptionColor
+ if idx := strings.LastIndex(raw, ":#"); idx > 0 {
+ name = raw[:idx]
+ color = raw[idx+1:]
+ }
+ name = strings.TrimSpace(name)
+ opt := map[string]string{"name": name, "color": color}
+ if id, ok := byName[strings.ToLower(name)]; ok {
+ opt["id"] = id
+ }
+ out = append(out, opt)
+ }
+ return out
+}
+
+func printPropertyTable(properties []propertyDTO) {
+ headers := []string{"ID", "NAME", "TYPE", "OPTIONS", "USED", "ARCHIVED"}
+ rows := make([][]string, 0, len(properties))
+ for _, p := range properties {
+ names := make([]string, len(p.Config.Options))
+ for i, opt := range p.Config.Options {
+ names[i] = opt.Name
+ }
+ archived := ""
+ if p.Archived {
+ archived = "yes"
+ }
+ rows = append(rows, []string{p.ID, p.Name, p.Type, strings.Join(names, ", "), strconv.FormatInt(p.UsageCount, 10), archived})
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+}
+
+func runPropertyList(cmd *cobra.Command, _ []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ includeArchived, _ := cmd.Flags().GetBool("include-archived")
+ path := "/api/properties"
+ if includeArchived {
+ path += "?include_archived=true"
+ }
+ var result struct {
+ Properties []propertyDTO `json:"properties"`
+ }
+ if err := client.GetJSON(ctx, path, &result); err != nil {
+ return fmt.Errorf("list properties: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, result.Properties)
+ }
+ printPropertyTable(result.Properties)
+ return nil
+}
+
+func runPropertyGet(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ property, err := resolvePropertyRef(properties, args[0])
+ if err != nil {
+ return err
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, property)
+ }
+ printPropertyTable([]propertyDTO{property})
+ return nil
+}
+
+func runPropertyCreate(cmd *cobra.Command, _ []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ propType, _ := cmd.Flags().GetString("type")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if propType == "" {
+ return fmt.Errorf("--type is required")
+ }
+ description, _ := cmd.Flags().GetString("description")
+ optionFlags, _ := cmd.Flags().GetStringArray("option")
+
+ body := map[string]any{"name": name, "type": propType, "description": description}
+ if len(optionFlags) > 0 {
+ body["config"] = map[string]any{"options": parseOptionFlags(optionFlags, nil)}
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ var created propertyDTO
+ if err := client.PostJSON(ctx, "/api/properties", body, &created); err != nil {
+ return fmt.Errorf("create property: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, created)
+ }
+ fmt.Fprintf(os.Stdout, "Property %q created.\n", created.Name)
+ printPropertyTable([]propertyDTO{created})
+ return nil
+}
+
+func runPropertyUpdate(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ property, err := resolvePropertyRef(properties, args[0])
+ if err != nil {
+ return err
+ }
+
+ body := map[string]any{}
+ if cmd.Flags().Changed("name") {
+ name, _ := cmd.Flags().GetString("name")
+ body["name"] = name
+ }
+ if cmd.Flags().Changed("description") {
+ description, _ := cmd.Flags().GetString("description")
+ body["description"] = description
+ }
+ if cmd.Flags().Changed("option") {
+ optionFlags, _ := cmd.Flags().GetStringArray("option")
+ body["config"] = map[string]any{"options": parseOptionFlags(optionFlags, property.Config.Options)}
+ }
+ if len(body) == 0 {
+ return fmt.Errorf("nothing to update; pass --name, --description, or --option")
+ }
+
+ var updated propertyDTO
+ if err := client.PatchJSON(ctx, "/api/properties/"+property.ID, body, &updated); err != nil {
+ return fmt.Errorf("update property: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, updated)
+ }
+ fmt.Fprintf(os.Stdout, "Property %q updated.\n", updated.Name)
+ printPropertyTable([]propertyDTO{updated})
+ return nil
+}
+
+func makePropertyArchiveRun(archive bool) func(*cobra.Command, []string) error {
+ return func(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ property, err := resolvePropertyRef(properties, args[0])
+ if err != nil {
+ return err
+ }
+ var updated propertyDTO
+ if err := client.PatchJSON(ctx, "/api/properties/"+property.ID, map[string]any{"archived": archive}, &updated); err != nil {
+ if archive {
+ return fmt.Errorf("archive property: %w", err)
+ }
+ return fmt.Errorf("unarchive property: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, updated)
+ }
+ if archive {
+ fmt.Fprintf(os.Stdout, "Property %q archived.\n", updated.Name)
+ } else {
+ fmt.Fprintf(os.Stdout, "Property %q restored.\n", updated.Name)
+ }
+ return nil
+ }
+}
+
+// ---------------------------------------------------------------------------
+// issue property {list|set|unset}
+// ---------------------------------------------------------------------------
+
+// encodeIssuePropertyValue converts the CLI --value string into the typed
+// JSON the API expects, translating option names to ids for select types.
+func encodeIssuePropertyValue(property propertyDTO, raw string) (json.RawMessage, error) {
+ optionNames := make([]string, len(property.Config.Options))
+ for i, opt := range property.Config.Options {
+ optionNames[i] = opt.Name
+ }
+ resolveOption := func(ref string) (string, error) {
+ ref = strings.TrimSpace(ref)
+ for _, opt := range property.Config.Options {
+ if opt.ID == ref || strings.EqualFold(opt.Name, ref) {
+ return opt.ID, nil
+ }
+ }
+ return "", fmt.Errorf("option %q not found on property %q; valid options: %s", ref, property.Name, strings.Join(optionNames, ", "))
+ }
+
+ switch property.Type {
+ case "select":
+ id, err := resolveOption(raw)
+ if err != nil {
+ return nil, err
+ }
+ return json.Marshal(id)
+ case "multi_select":
+ parts := strings.Split(raw, ",")
+ ids := make([]string, 0, len(parts))
+ for _, part := range parts {
+ if strings.TrimSpace(part) == "" {
+ continue
+ }
+ id, err := resolveOption(part)
+ if err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ if len(ids) == 0 {
+ return nil, fmt.Errorf("--value must list at least one option; valid options: %s", strings.Join(optionNames, ", "))
+ }
+ return json.Marshal(ids)
+ case "number":
+ if _, err := strconv.ParseFloat(raw, 64); err != nil {
+ return nil, fmt.Errorf("value %q is not a valid number", raw)
+ }
+ return json.RawMessage(raw), nil
+ case "checkbox":
+ if raw != "true" && raw != "false" {
+ return nil, fmt.Errorf("value %q is not a valid bool (expected true or false)", raw)
+ }
+ return json.RawMessage(raw), nil
+ default: // text, date, url — validated server-side
+ return json.Marshal(raw)
+ }
+}
+
+// formatIssuePropertyValue renders a stored value for humans: option ids
+// become option names, everything else prints via formatMetadataValue.
+func formatIssuePropertyValue(property propertyDTO, value any) string {
+ optionName := func(id string) string {
+ for _, opt := range property.Config.Options {
+ if opt.ID == id {
+ return opt.Name
+ }
+ }
+ return id
+ }
+ switch property.Type {
+ case "select":
+ if s, ok := value.(string); ok {
+ return optionName(s)
+ }
+ case "multi_select":
+ if items, ok := value.([]any); ok {
+ names := make([]string, 0, len(items))
+ for _, item := range items {
+ if s, ok := item.(string); ok {
+ names = append(names, optionName(s))
+ }
+ }
+ return strings.Join(names, ", ")
+ }
+ case "checkbox":
+ if b, ok := value.(bool); ok {
+ if b {
+ return "✓"
+ }
+ return "✗"
+ }
+ }
+ return formatMetadataValue(value)
+}
+
+type issuePropertyValueRow struct {
+ PropertyID string `json:"property_id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Value any `json:"value"`
+ Display string `json:"display"`
+ Archived bool `json:"archived,omitempty"`
+}
+
+func buildIssuePropertyRows(properties []propertyDTO, bag map[string]any) []issuePropertyValueRow {
+ rows := make([]issuePropertyValueRow, 0, len(bag))
+ for _, p := range properties {
+ value, present := bag[p.ID]
+ if !present {
+ continue
+ }
+ rows = append(rows, issuePropertyValueRow{
+ PropertyID: p.ID,
+ Name: p.Name,
+ Type: p.Type,
+ Value: value,
+ Display: formatIssuePropertyValue(p, value),
+ Archived: p.Archived,
+ })
+ }
+ return rows
+}
+
+func fetchIssuePropertyBag(ctx context.Context, client *cli.APIClient, issueID string) (map[string]any, error) {
+ var issue struct {
+ Properties map[string]any `json:"properties"`
+ }
+ if err := client.GetJSON(ctx, "/api/issues/"+issueID, &issue); err != nil {
+ return nil, fmt.Errorf("get issue: %w", err)
+ }
+ if issue.Properties == nil {
+ return map[string]any{}, nil
+ }
+ return issue.Properties, nil
+}
+
+func printIssuePropertyRows(rows []issuePropertyValueRow) {
+ headers := []string{"NAME", "VALUE", "TYPE"}
+ tableRows := make([][]string, len(rows))
+ for i, row := range rows {
+ tableRows[i] = []string{row.Name, row.Display, row.Type}
+ }
+ cli.PrintTable(os.Stdout, headers, tableRows)
+}
+
+func runIssuePropertyList(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ bag, err := fetchIssuePropertyBag(ctx, client, issueRef.ID)
+ if err != nil {
+ return err
+ }
+ rows := buildIssuePropertyRows(properties, bag)
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, rows)
+ }
+ printIssuePropertyRows(rows)
+ return nil
+}
+
+func runIssuePropertySet(cmd *cobra.Command, args []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+ if !cmd.Flags().Changed("value") {
+ return fmt.Errorf("--value is required")
+ }
+ rawValue, _ := cmd.Flags().GetString("value")
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ property, err := resolvePropertyRef(properties, name)
+ if err != nil {
+ return err
+ }
+ value, err := encodeIssuePropertyValue(property, rawValue)
+ if err != nil {
+ return err
+ }
+
+ var result struct {
+ Properties map[string]any `json:"properties"`
+ }
+ path := "/api/issues/" + issueRef.ID + "/properties/" + property.ID
+ if err := client.PutJSON(ctx, path, map[string]any{"value": value}, &result); err != nil {
+ return fmt.Errorf("set property: %w", err)
+ }
+ rows := buildIssuePropertyRows(properties, result.Properties)
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, rows)
+ }
+ printIssuePropertyRows(rows)
+ return nil
+}
+
+func runIssuePropertyUnset(cmd *cobra.Command, args []string) error {
+ name, _ := cmd.Flags().GetString("name")
+ if name == "" {
+ return fmt.Errorf("--name is required")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return err
+ }
+ property, err := resolvePropertyRef(properties, name)
+ if err != nil {
+ return err
+ }
+
+ path := "/api/issues/" + issueRef.ID + "/properties/" + property.ID
+ if err := client.DeleteJSON(ctx, path); err != nil {
+ return fmt.Errorf("unset property: %w", err)
+ }
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, map[string]any{"deleted": true})
+ }
+ fmt.Fprintf(os.Stdout, "Property %q unset.\n", property.Name)
+ return nil
+}
diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.go
index e0415ba82c..7491fd18da 100644
--- a/server/cmd/multica/main.go
+++ b/server/cmd/multica/main.go
@@ -46,6 +46,7 @@ func init() {
issueCmd.GroupID = groupCore
projectCmd.GroupID = groupCore
labelCmd.GroupID = groupCore
+ propertyCmd.GroupID = groupCore
agentCmd.GroupID = groupCore
autopilotCmd.GroupID = groupCore
workspaceCmd.GroupID = groupCore
@@ -71,6 +72,7 @@ func init() {
rootCmd.AddCommand(issueCmd)
rootCmd.AddCommand(projectCmd)
rootCmd.AddCommand(labelCmd)
+ rootCmd.AddCommand(propertyCmd)
rootCmd.AddCommand(agentCmd)
rootCmd.AddCommand(autopilotCmd)
rootCmd.AddCommand(workspaceCmd)
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3ee7d1751f..93f91f651a 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1068,6 +1068,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/metadata", h.ListIssueMetadata)
r.Put("/metadata/{key}", h.SetIssueMetadataKey)
r.Delete("/metadata/{key}", h.DeleteIssueMetadataKey)
+ r.Put("/properties/{propertyId}", h.SetIssueProperty)
+ r.Delete("/properties/{propertyId}", h.DeleteIssueProperty)
r.Get("/pull-requests", h.ListPullRequestsForIssue)
})
})
@@ -1075,6 +1077,16 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Task messages (user-facing, not daemon auth)
r.Get("/api/tasks/{taskId}/messages", h.ListTaskMessagesByUser)
+ // Custom issue properties (definitions; values live under /api/issues/{id}/properties)
+ r.Route("/api/properties", func(r chi.Router) {
+ r.Get("/", h.ListProperties)
+ r.Post("/", h.CreateProperty)
+ r.Route("/{id}", func(r chi.Router) {
+ r.Get("/", h.GetProperty)
+ r.Patch("/", h.UpdateProperty)
+ })
+ })
+
// Labels
r.Route("/api/labels", func(r chi.Router) {
r.Get("/", h.ListLabels)
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index df41dd0ea2..1ccccadcf1 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -56,7 +56,10 @@ type IssueResponse struct {
// Metadata is the per-issue KV map (see issue_metadata.go). Always emitted
// (empty object when unset) so frontend code can `issue.metadata[key]`
// without nil-guarding the parent field.
- Metadata map[string]any `json:"metadata"`
+ Metadata map[string]any `json:"metadata"`
+ // Properties is the custom-property value bag keyed by property definition
+ // UUID (see property.go). Always emitted, mirroring Metadata.
+ Properties map[string]any `json:"properties"`
Reactions []IssueReactionResponse `json:"reactions,omitempty"`
Attachments []AttachmentResponse `json:"attachments,omitempty"`
// Labels are bulk-attached by list/detail endpoints so the client can render
@@ -109,6 +112,7 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Metadata: parseIssueMetadata(i.Metadata),
+ Properties: parseIssueProperties(i.Properties),
}
}
@@ -137,6 +141,7 @@ func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueRespons
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Metadata: parseIssueMetadata(i.Metadata),
+ Properties: parseIssueProperties(i.Properties),
}
}
@@ -197,6 +202,7 @@ func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueRes
CreatedAt: timestampToString(i.CreatedAt),
UpdatedAt: timestampToString(i.UpdatedAt),
Metadata: parseIssueMetadata(i.Metadata),
+ Properties: parseIssueProperties(i.Properties),
}
}
@@ -819,6 +825,10 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ propertiesFilter, ok := parsePropertiesFilterParam(w, r.URL.Query().Get("properties"))
+ if !ok {
+ return
+ }
dateFilter, ok := parseIssueDateFilter(w, r.URL.Query())
if !ok {
return
@@ -826,15 +836,27 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
// open_only=true returns all non-done/cancelled issues (no limit).
if r.URL.Query().Get("open_only") == "true" {
+ // Serialize the parsed AND-of-ORs groups into the single jsonb param
+ // the static query unrolls (see properties_filter in ListOpenIssues).
+ var openPropertiesFilter []byte
+ if len(propertiesFilter) > 0 {
+ marshaled, marshalErr := json.Marshal(propertiesFilter)
+ if marshalErr != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list issues")
+ return
+ }
+ openPropertiesFilter = marshaled
+ }
issues, err := h.Queries.ListOpenIssues(ctx, db.ListOpenIssuesParams{
- WorkspaceID: wsUUID,
- Priority: priorityFilter,
- AssigneeID: assigneeFilter,
- AssigneeIds: assigneeIdsFilter,
- CreatorID: creatorFilter,
- ProjectID: projectFilter,
- InvolvesUserID: involvesUserFilter,
- MetadataFilter: metadataFilter,
+ WorkspaceID: wsUUID,
+ Priority: priorityFilter,
+ AssigneeID: assigneeFilter,
+ AssigneeIds: assigneeIdsFilter,
+ CreatorID: creatorFilter,
+ ProjectID: projectFilter,
+ InvolvesUserID: involvesUserFilter,
+ MetadataFilter: metadataFilter,
+ PropertiesFilter: openPropertiesFilter,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list issues")
@@ -910,15 +932,38 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
// the user defines order through drag-and-drop, reversing it has no
// product meaning.
sortCol := "position"
+ sortIsExpr := false
+ sortIsProperty := false
if s := r.URL.Query().Get("sort"); s != "" {
switch s {
case "position", "title", "created_at", "start_date", "due_date":
sortCol = s
case "priority":
sortCol = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
+ sortIsExpr = true
default:
- writeError(w, http.StatusBadRequest, "invalid sort value")
- return
+ // property:<definitionId> sorts by the custom-property value
+ // (typed expression); unknown/archived definitions degrade to
+ // position order instead of erroring stale clients.
+ expr, handled, sortErr := h.propertySortExpr(r, workspaceID, s)
+ if !handled {
+ writeError(w, http.StatusBadRequest, "invalid sort value")
+ return
+ }
+ if sortErr != nil {
+ if sortErr.Error() == "invalid sort value" || sortErr.Error() == "invalid workspace id" {
+ writeError(w, http.StatusBadRequest, sortErr.Error())
+ return
+ }
+ slog.Warn("propertySortExpr failed", append(logger.RequestAttrs(r), "error", sortErr)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve sort")
+ return
+ }
+ if expr != "" {
+ sortCol = expr
+ sortIsExpr = true
+ sortIsProperty = true
+ }
}
}
sortDir := "ASC"
@@ -971,6 +1016,9 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
if metadataFilter != nil {
where = append(where, fmt.Sprintf("i.metadata @> %s::jsonb", addArg(string(metadataFilter))))
}
+ if propertiesFilter != nil {
+ where = append(where, propertiesFilterPredicate(propertiesFilter, addArg))
+ }
where = appendIssueDateFilter(where, addArg, dateFilter)
if involvesUserFilter.Valid {
ref := addArg(involvesUserFilter)
@@ -1011,11 +1059,13 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
// Build ORDER BY clause.
orderBy := sortCol
- if !strings.HasPrefix(sortCol, "CASE") {
+ if !sortIsExpr {
orderBy = "i." + sortCol
}
orderBy += " " + sortDir
- if sortCol == "start_date" || sortCol == "due_date" {
+ if sortCol == "start_date" || sortCol == "due_date" || sortIsProperty {
+ // Property values are sparse: issues without one sort last in both
+ // directions (mirrors the client comparator).
orderBy += " NULLS LAST"
}
orderBy += ", i.created_at DESC"
@@ -1025,7 +1075,7 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
query := fmt.Sprintf(`SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
FROM issue i
WHERE %s
ORDER BY %s
@@ -1063,6 +1113,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)
&row.ProjectID,
&row.Metadata,
&row.Stage,
+ &row.Properties,
); err != nil {
slog.Warn("ListIssues scan failed", "error", err)
writeError(w, http.StatusInternalServerError, "failed to list issues")
@@ -1339,6 +1390,11 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
} else if filter != nil {
where = append(where, fmt.Sprintf("i.metadata @> %s::jsonb", addArg(string(filter))))
}
+ if filter, ok := parsePropertiesFilterParam(w, r.URL.Query().Get("properties")); !ok {
+ return
+ } else if filter != nil {
+ where = append(where, propertiesFilterPredicate(filter, addArg))
+ }
// Mirror the involves_user_id 4-branch UNION from sqlc's ListIssues /
// ListOpenIssues / CountIssues. ListGroupedIssues is a hand-written dynamic
// SQL builder that does not share parameters with sqlc, so the fragment is
@@ -1479,15 +1535,38 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
}
sortCol := "position"
+ sortIsExpr := false
+ sortIsProperty := false
if s := r.URL.Query().Get("sort"); s != "" {
switch s {
case "position", "title", "created_at", "start_date", "due_date":
sortCol = s
case "priority":
sortCol = "CASE i.priority WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 4 END"
+ sortIsExpr = true
default:
- writeError(w, http.StatusBadRequest, "invalid sort value")
- return
+ // property:<definitionId> sorts by the custom-property value
+ // (typed expression); unknown/archived definitions degrade to
+ // position order instead of erroring stale clients.
+ expr, handled, sortErr := h.propertySortExpr(r, workspaceID, s)
+ if !handled {
+ writeError(w, http.StatusBadRequest, "invalid sort value")
+ return
+ }
+ if sortErr != nil {
+ if sortErr.Error() == "invalid sort value" || sortErr.Error() == "invalid workspace id" {
+ writeError(w, http.StatusBadRequest, sortErr.Error())
+ return
+ }
+ slog.Warn("propertySortExpr failed", append(logger.RequestAttrs(r), "error", sortErr)...)
+ writeError(w, http.StatusInternalServerError, "failed to resolve sort")
+ return
+ }
+ if expr != "" {
+ sortCol = expr
+ sortIsExpr = true
+ sortIsProperty = true
+ }
}
}
sortDir := "ASC"
@@ -1506,11 +1585,11 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {
}
intraGroupOrder := sortCol
- if !strings.HasPrefix(sortCol, "CASE") {
+ if !sortIsExpr {
intraGroupOrder = "i." + sortCol
}
intraGroupOrder += " " + sortDir
- if sortCol == "start_date" || sortCol == "due_date" {
+ if sortCol == "start_date" || sortCol == "due_date" || sortIsProperty {
intraGroupOrder += " NULLS LAST"
}
intraGroupOrder += ", i.created_at DESC"
@@ -1523,7 +1602,7 @@ WITH ranked AS (
i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at,
- i.number, i.project_id, i.metadata, i.stage,
+ i.number, i.project_id, i.metadata, i.stage, i.properties,
COUNT(*) OVER (PARTITION BY i.assignee_type, i.assignee_id) AS group_total,
ROW_NUMBER() OVER (
PARTITION BY i.assignee_type, i.assignee_id
@@ -1536,7 +1615,7 @@ SELECT
id, workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, created_at, updated_at,
- number, project_id, metadata, stage, group_total
+ number, project_id, metadata, stage, properties, group_total
FROM ranked
WHERE rn > %s AND rn <= %s + %s
ORDER BY
@@ -1582,6 +1661,7 @@ ORDER BY
&row.ProjectID,
&row.Metadata,
&row.Stage,
+ &row.Properties,
&row.GroupTotal,
); err != nil {
slog.Warn("ListGroupedIssues scan failed", "error", err)
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
new file mode 100644
index 0000000000..42d985030e
--- /dev/null
+++ b/server/internal/handler/property.go
@@ -0,0 +1,980 @@
+package handler
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/logger"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// Custom issue properties (MUL-4463): workspace-level typed property
+// definitions plus a per-issue value bag.
+//
+// Contract highlights (decided on MUL-4463):
+// - Definitions are managed by human owner/admin members only. Agent actors
+// are rejected even when the runtime owner has the role — otherwise field
+// sprawl becomes something agents can mass-produce.
+// - Values are writable by every member and agent; validation is typed per
+// definition, and errors enumerate legal values so agents can self-correct.
+// - Value writes are single-key atomic (mirror of issue metadata): two
+// agents writing different properties never clobber each other.
+// - Definitions archive instead of delete; archived definitions reject new
+// values but keep existing ones resolvable.
+const (
+ maxActivePropertiesPerWorkspace = 20
+ maxPropertySelectOptions = 50
+ maxPropertyNameLen = 32
+ maxPropertyDescriptionLen = 500
+ maxPropertyTextValueLen = 2000
+ maxPropertyURLValueLen = 2048
+)
+
+var validPropertyTypes = []string{"text", "number", "select", "multi_select", "date", "checkbox", "url"}
+
+// errClientRejected marks lock-closure failures already translated to an
+// HTTP status by the caller-side fail() capture.
+var errClientRejected = errors.New("client rejected")
+
+// reservedPropertyNames blocks definitions that would collide with built-in
+// issue fields ("system properties"). Comparison happens on the normalized
+// form: lowercased, spaces collapsed to underscores — so "Due Date", "due
+// date", and "due_date" are all rejected.
+var reservedPropertyNames = map[string]struct{}{
+ "status": {}, "priority": {}, "assignee": {}, "project": {}, "parent": {},
+ "stage": {}, "label": {}, "labels": {}, "start_date": {}, "due_date": {},
+ "title": {}, "description": {}, "creator": {}, "created_at": {}, "updated_at": {},
+ "metadata": {}, "properties": {},
+}
+
+// ---------------------------------------------------------------------------
+// Types
+// ---------------------------------------------------------------------------
+
+type PropertyOption struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Color string `json:"color"`
+}
+
+type PropertyConfig struct {
+ Options []PropertyOption `json:"options,omitempty"`
+}
+
+type PropertyResponse struct {
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config PropertyConfig `json:"config"`
+ Position float64 `json:"position"`
+ Archived bool `json:"archived"`
+ ArchivedAt *string `json:"archived_at"`
+ UsageCount int64 `json:"usage_count"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func parsePropertyConfig(raw []byte) PropertyConfig {
+ var cfg PropertyConfig
+ if len(raw) == 0 {
+ return cfg
+ }
+ if err := json.Unmarshal(raw, &cfg); err != nil {
+ return PropertyConfig{}
+ }
+ return cfg
+}
+
+func propertyToResponse(p db.IssueProperty, usageCount int64) PropertyResponse {
+ resp := PropertyResponse{
+ ID: uuidToString(p.ID),
+ WorkspaceID: uuidToString(p.WorkspaceID),
+ Name: p.Name,
+ Type: p.Type,
+ Description: p.Description,
+ Config: parsePropertyConfig(p.Config),
+ Position: p.Position,
+ Archived: p.ArchivedAt.Valid,
+ UsageCount: usageCount,
+ CreatedAt: timestampToString(p.CreatedAt),
+ UpdatedAt: timestampToString(p.UpdatedAt),
+ }
+ if p.ArchivedAt.Valid {
+ s := timestampToString(p.ArchivedAt)
+ resp.ArchivedAt = &s
+ }
+ return resp
+}
+
+func propertyListRowToResponse(row db.ListIssuePropertiesRow) PropertyResponse {
+ return propertyToResponse(db.IssueProperty{
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ Name: row.Name,
+ Type: row.Type,
+ Description: row.Description,
+ Config: row.Config,
+ Position: row.Position,
+ ArchivedAt: row.ArchivedAt,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt,
+ }, row.UsageCount)
+}
+
+type CreatePropertyRequest struct {
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config *PropertyConfig `json:"config"`
+}
+
+type UpdatePropertyRequest struct {
+ Name *string `json:"name"`
+ Description *string `json:"description"`
+ Config *PropertyConfig `json:"config"`
+ Archived *bool `json:"archived"`
+}
+
+// ---------------------------------------------------------------------------
+// Validation
+// ---------------------------------------------------------------------------
+
+func normalizePropertyName(name string) string {
+ return strings.ReplaceAll(strings.ToLower(strings.TrimSpace(name)), " ", "_")
+}
+
+func validatePropertyName(raw string) (string, error) {
+ for _, r := range raw {
+ if unicode.IsControl(r) {
+ return "", errors.New("name cannot contain tabs, newlines, or control characters")
+ }
+ }
+ name := strings.TrimSpace(raw)
+ if name == "" {
+ return "", errors.New("name is required")
+ }
+ if utf8.RuneCountInString(name) > maxPropertyNameLen {
+ return "", fmt.Errorf("name must be %d characters or fewer", maxPropertyNameLen)
+ }
+ if _, reserved := reservedPropertyNames[normalizePropertyName(name)]; reserved {
+ return "", fmt.Errorf("%q is reserved for a built-in issue field", name)
+ }
+ return name, nil
+}
+
+func validatePropertyType(t string) error {
+ for _, v := range validPropertyTypes {
+ if t == v {
+ return nil
+ }
+ }
+ return fmt.Errorf("invalid type %q; valid types: %s", t, strings.Join(validPropertyTypes, ", "))
+}
+
+func propertyTypeHasOptions(t string) bool {
+ return t == "select" || t == "multi_select"
+}
+
+// validatePropertyConfig canonicalizes the config for storage. Select-type
+// properties require 1..50 options; each option gets a stable server-assigned
+// UUID if the caller didn't provide one (values reference option IDs, so
+// option renames never touch issue rows). Non-select types must not carry
+// options and are stored as {}.
+func validatePropertyConfig(propType string, cfg *PropertyConfig) ([]byte, error) {
+ if !propertyTypeHasOptions(propType) {
+ if cfg != nil && len(cfg.Options) > 0 {
+ return nil, fmt.Errorf("type %q does not accept options", propType)
+ }
+ return []byte(`{}`), nil
+ }
+ if cfg == nil || len(cfg.Options) == 0 {
+ return nil, errors.New("select properties require at least one option")
+ }
+ if len(cfg.Options) > maxPropertySelectOptions {
+ return nil, fmt.Errorf("a property cannot have more than %d options", maxPropertySelectOptions)
+ }
+ seenIDs := make(map[string]struct{}, len(cfg.Options))
+ seenNames := make(map[string]struct{}, len(cfg.Options))
+ out := PropertyConfig{Options: make([]PropertyOption, 0, len(cfg.Options))}
+ for _, opt := range cfg.Options {
+ name, err := validateLabelName(opt.Name)
+ if err != nil {
+ return nil, fmt.Errorf("option %w", err)
+ }
+ lower := strings.ToLower(name)
+ if _, dup := seenNames[lower]; dup {
+ return nil, fmt.Errorf("duplicate option name %q", name)
+ }
+ seenNames[lower] = struct{}{}
+ color, err := normalizeColor(opt.Color)
+ if err != nil {
+ return nil, fmt.Errorf("option %q: %w", name, err)
+ }
+ id := strings.TrimSpace(opt.ID)
+ if id == "" {
+ id = uuid.NewString()
+ } else if _, err := uuid.Parse(id); err != nil {
+ return nil, fmt.Errorf("option %q: id must be a UUID", name)
+ }
+ if _, dup := seenIDs[id]; dup {
+ return nil, fmt.Errorf("duplicate option id %q", id)
+ }
+ seenIDs[id] = struct{}{}
+ out.Options = append(out.Options, PropertyOption{ID: id, Name: name, Color: color})
+ }
+ return json.Marshal(out)
+}
+
+func propertyOptionIDs(cfg PropertyConfig) map[string]int {
+ ids := make(map[string]int, len(cfg.Options))
+ for i, opt := range cfg.Options {
+ ids[opt.ID] = i
+ }
+ return ids
+}
+
+func selectOptionsHint(cfg PropertyConfig) string {
+ parts := make([]string, len(cfg.Options))
+ for i, opt := range cfg.Options {
+ parts[i] = fmt.Sprintf("%s (%s)", opt.ID, opt.Name)
+ }
+ return strings.Join(parts, ", ")
+}
+
+// validatePropertyValue checks a raw JSON value against the definition's type
+// and returns the canonical JSON to store. Error strings enumerate the legal
+// values where possible — agents consume these directly to self-correct.
+func validatePropertyValue(def db.IssueProperty, raw json.RawMessage) ([]byte, error) {
+ if len(raw) == 0 {
+ return nil, errors.New("value is required")
+ }
+ var v any
+ if err := json.Unmarshal(raw, &v); err != nil {
+ return nil, fmt.Errorf("value must be valid JSON: %w", err)
+ }
+ if v == nil {
+ return nil, errors.New("value cannot be null (use DELETE to unset a property)")
+ }
+
+ cfg := parsePropertyConfig(def.Config)
+ switch def.Type {
+ case "text":
+ s, ok := v.(string)
+ if !ok {
+ return nil, errors.New("value must be a string")
+ }
+ if strings.TrimSpace(s) == "" {
+ return nil, errors.New("value cannot be empty (use DELETE to unset a property)")
+ }
+ if utf8.RuneCountInString(s) > maxPropertyTextValueLen {
+ return nil, fmt.Errorf("value must be %d characters or fewer", maxPropertyTextValueLen)
+ }
+ return json.Marshal(sanitizeNullBytes(s))
+ case "url":
+ s, ok := v.(string)
+ if !ok {
+ return nil, errors.New("value must be a URL string")
+ }
+ s = strings.TrimSpace(s)
+ if len(s) > maxPropertyURLValueLen {
+ return nil, fmt.Errorf("value must be %d characters or fewer", maxPropertyURLValueLen)
+ }
+ u, err := url.Parse(s)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return nil, errors.New("value must be an http(s) URL")
+ }
+ return json.Marshal(s)
+ case "number":
+ if _, ok := v.(float64); !ok {
+ return nil, errors.New("value must be a number")
+ }
+ return json.Marshal(v)
+ case "checkbox":
+ if _, ok := v.(bool); !ok {
+ return nil, errors.New("value must be true or false")
+ }
+ return json.Marshal(v)
+ case "date":
+ s, ok := v.(string)
+ if !ok {
+ return nil, errors.New("value must be a date string in YYYY-MM-DD format")
+ }
+ if _, err := time.Parse("2006-01-02", s); err != nil {
+ return nil, errors.New("value must be a date string in YYYY-MM-DD format")
+ }
+ return json.Marshal(s)
+ case "select":
+ s, ok := v.(string)
+ if !ok {
+ return nil, fmt.Errorf("value must be one of the option ids: %s", selectOptionsHint(cfg))
+ }
+ if _, exists := propertyOptionIDs(cfg)[s]; !exists {
+ return nil, fmt.Errorf("value must be one of the option ids: %s", selectOptionsHint(cfg))
+ }
+ return json.Marshal(s)
+ case "multi_select":
+ items, ok := v.([]any)
+ if !ok || len(items) == 0 {
+ return nil, fmt.Errorf("value must be a non-empty array of option ids: %s", selectOptionsHint(cfg))
+ }
+ order := propertyOptionIDs(cfg)
+ seen := make(map[string]struct{}, len(items))
+ ids := make([]string, 0, len(items))
+ for _, item := range items {
+ s, ok := item.(string)
+ if !ok {
+ return nil, fmt.Errorf("value must be a non-empty array of option ids: %s", selectOptionsHint(cfg))
+ }
+ if _, exists := order[s]; !exists {
+ return nil, fmt.Errorf("unknown option id %q; valid option ids: %s", s, selectOptionsHint(cfg))
+ }
+ if _, dup := seen[s]; dup {
+ continue
+ }
+ seen[s] = struct{}{}
+ ids = append(ids, s)
+ }
+ // Canonicalize to config order so equal selections serialize equally
+ // (stable @> containment filtering and change detection).
+ sort.SliceStable(ids, func(a, b int) bool { return order[ids[a]] < order[ids[b]] })
+ return json.Marshal(ids)
+ default:
+ return nil, fmt.Errorf("unsupported property type %q", def.Type)
+ }
+}
+
+// removedOptionIDs returns option ids present in the stored config but
+// absent from the incoming replacement.
+func removedOptionIDs(existingConfig, nextConfig []byte) []string {
+ next := propertyOptionIDs(parsePropertyConfig(nextConfig))
+ var removed []string
+ for _, opt := range parsePropertyConfig(existingConfig).Options {
+ if _, kept := next[opt.ID]; !kept {
+ removed = append(removed, opt.ID)
+ }
+ }
+ return removed
+}
+
+// describeOptionsInUse renders the 409 body for in-use option removal, e.g.
+// `cannot remove options still in use: "Critical" (3 issues); clear or
+// change those values first`.
+func describeOptionsInUse(existingConfig []byte, rows []db.CountIssuesUsingPropertyOptionsRow) string {
+ names := make(map[string]string)
+ for _, opt := range parsePropertyConfig(existingConfig).Options {
+ names[opt.ID] = opt.Name
+ }
+ parts := make([]string, len(rows))
+ for i, row := range rows {
+ name := names[row.OptionID]
+ if name == "" {
+ name = row.OptionID
+ }
+ parts[i] = fmt.Sprintf("%q (%d issues)", name, row.UsageCount)
+ }
+ sort.Strings(parts)
+ return "cannot remove options still in use: " + strings.Join(parts, ", ") + "; clear or change those values first"
+}
+
+// parseIssueProperties mirrors parseIssueMetadata for the properties bag.
+func parseIssueProperties(raw []byte) map[string]any {
+ if len(raw) == 0 {
+ return map[string]any{}
+ }
+ var out map[string]any
+ if err := json.Unmarshal(raw, &out); err != nil || out == nil {
+ return map[string]any{}
+ }
+ return out
+}
+
+// ---------------------------------------------------------------------------
+// Definition handlers
+// ---------------------------------------------------------------------------
+
+// requirePropertyAdmin gates definition writes: human owner/admin members
+// only. Agent actors are rejected before the role check — an agent inherits
+// its runtime owner's credentials, and without this check an admin's agent
+// could mass-create definitions (MUL-4463 decision: agents propose via
+// comments, humans confirm).
+func (h *Handler) requirePropertyAdmin(w http.ResponseWriter, r *http.Request) (workspaceID, userID string, ok bool) {
+ workspaceID = h.resolveWorkspaceID(r)
+ userID, ok = requireUserID(w, r)
+ if !ok {
+ return "", "", false
+ }
+ if actorType, _ := h.resolveActor(r, userID, workspaceID); actorType == "agent" {
+ writeError(w, http.StatusForbidden, "agents cannot manage property definitions")
+ return "", "", false
+ }
+ if _, roleOK := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !roleOK {
+ return "", "", false
+ }
+ return workspaceID, userID, true
+}
+
+func (h *Handler) ListProperties(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ includeArchived := r.URL.Query().Get("include_archived") == "true"
+ rows, err := h.Queries.ListIssueProperties(r.Context(), db.ListIssuePropertiesParams{
+ WorkspaceID: wsUUID,
+ IncludeArchived: includeArchived,
+ })
+ if err != nil {
+ slog.Warn("ListIssueProperties failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to list properties")
+ return
+ }
+ resp := make([]PropertyResponse, len(rows))
+ for i, row := range rows {
+ resp[i] = propertyListRowToResponse(row)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"properties": resp, "total": len(resp)})
+}
+
+func (h *Handler) GetProperty(w http.ResponseWriter, r *http.Request) {
+ workspaceID := h.resolveWorkspaceID(r)
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "property id")
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ property, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "property not found")
+ return
+ }
+ slog.Warn("GetIssueProperty failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to get property")
+ return
+ }
+ writeJSON(w, http.StatusOK, propertyToResponse(property, 0))
+}
+
+func (h *Handler) CreateProperty(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requirePropertyAdmin(w, r)
+ if !ok {
+ return
+ }
+ var req CreatePropertyRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ name, err := validatePropertyName(req.Name)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if err := validatePropertyType(req.Type); err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if utf8.RuneCountInString(req.Description) > maxPropertyDescriptionLen {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("description must be %d characters or fewer", maxPropertyDescriptionLen))
+ return
+ }
+ configJSON, err := validatePropertyConfig(req.Type, req.Config)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, err.Error())
+ return
+ }
+
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ var property db.IssueProperty
+ var capErr error
+ err = h.withPropertyLock(r, []string{"props:" + workspaceID}, func(q *db.Queries) error {
+ active, err := q.CountActiveIssueProperties(r.Context(), wsUUID)
+ if err != nil {
+ return err
+ }
+ if active >= maxActivePropertiesPerWorkspace {
+ capErr = fmt.Errorf("a workspace cannot have more than %d active properties; archive unused ones first", maxActivePropertiesPerWorkspace)
+ return capErr
+ }
+ property, err = q.CreateIssueProperty(r.Context(), db.CreateIssuePropertyParams{
+ WorkspaceID: wsUUID,
+ Name: name,
+ Type: req.Type,
+ Description: sanitizeNullBytes(strings.TrimSpace(req.Description)),
+ Config: configJSON,
+ })
+ return err
+ })
+ if capErr != nil {
+ writeError(w, http.StatusBadRequest, capErr.Error())
+ return
+ }
+ if err != nil {
+ if isUniqueViolation(err) {
+ writeError(w, http.StatusConflict, "a property with that name already exists")
+ return
+ }
+ slog.Warn("CreateIssueProperty failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to create property")
+ return
+ }
+ resp := propertyToResponse(property, 0)
+ h.publish(protocol.EventPropertyCreated, workspaceID, "member", userID, map[string]any{"property": resp})
+ writeJSON(w, http.StatusCreated, resp)
+}
+
+func (h *Handler) UpdateProperty(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requirePropertyAdmin(w, r)
+ if !ok {
+ return
+ }
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "property id")
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ var req UpdatePropertyRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ // The whole read → validate → census → write flow runs under advisory
+ // locks (workspace, then property): a concurrent value write on this
+ // property serializes behind the property lock, so the in-use census
+ // cannot race a value that would reference a removed option (TOCTOU,
+ // clean-room review F1); the workspace lock makes the unarchive cap
+ // check atomic against creates (F5).
+ var property db.IssueProperty
+ var httpStatus int
+ var httpMsg string
+ fail := func(status int, msg string) error {
+ httpStatus, httpMsg = status, msg
+ return errClientRejected
+ }
+ err := h.withPropertyLock(r, []string{"props:" + workspaceID, "prop:" + uuidToString(idUUID)}, func(q *db.Queries) error {
+ existing, err := q.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: idUUID, WorkspaceID: wsUUID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return fail(http.StatusNotFound, "property not found")
+ }
+ return err
+ }
+
+ params := db.UpdateIssuePropertyParams{ID: idUUID, WorkspaceID: wsUUID}
+ if req.Name != nil {
+ name, err := validatePropertyName(*req.Name)
+ if err != nil {
+ return fail(http.StatusBadRequest, err.Error())
+ }
+ params.Name = pgtype.Text{String: name, Valid: true}
+ }
+ if req.Description != nil {
+ if utf8.RuneCountInString(*req.Description) > maxPropertyDescriptionLen {
+ return fail(http.StatusBadRequest, fmt.Sprintf("description must be %d characters or fewer", maxPropertyDescriptionLen))
+ }
+ params.Description = pgtype.Text{String: sanitizeNullBytes(strings.TrimSpace(*req.Description)), Valid: true}
+ }
+ if req.Config != nil {
+ configJSON, err := validatePropertyConfig(existing.Type, req.Config)
+ if err != nil {
+ return fail(http.StatusBadRequest, err.Error())
+ }
+ if removed := removedOptionIDs(existing.Config, configJSON); len(removed) > 0 {
+ rows, err := q.CountIssuesUsingPropertyOptions(r.Context(), db.CountIssuesUsingPropertyOptionsParams{
+ OptionIds: removed,
+ WorkspaceID: wsUUID,
+ PropertyKey: uuidToString(existing.ID),
+ })
+ if err != nil {
+ return err
+ }
+ if len(rows) > 0 {
+ return fail(http.StatusConflict, describeOptionsInUse(existing.Config, rows))
+ }
+ }
+ params.Config = configJSON
+ }
+ if req.Archived != nil {
+ params.ArchivedSet = true
+ if *req.Archived {
+ params.ArchivedAt = pgtype.Timestamptz{Time: time.Now().UTC(), Valid: true}
+ } else if existing.ArchivedAt.Valid {
+ active, err := q.CountActiveIssueProperties(r.Context(), wsUUID)
+ if err != nil {
+ return err
+ }
+ if active >= maxActivePropertiesPerWorkspace {
+ return fail(http.StatusBadRequest, fmt.Sprintf("a workspace cannot have more than %d active properties; archive unused ones first", maxActivePropertiesPerWorkspace))
+ }
+ }
+ }
+
+ property, err = q.UpdateIssueProperty(r.Context(), params)
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return fail(http.StatusNotFound, "property not found")
+ }
+ if isUniqueViolation(err) {
+ return fail(http.StatusConflict, "a property with that name already exists")
+ }
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ if errors.Is(err, errClientRejected) {
+ writeError(w, httpStatus, httpMsg)
+ return
+ }
+ slog.Warn("UpdateProperty failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to update property")
+ return
+ }
+ resp := propertyToResponse(property, 0)
+ h.publish(protocol.EventPropertyUpdated, workspaceID, "member", userID, map[string]any{"property": resp})
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// ---------------------------------------------------------------------------
+// Issue value handlers
+// ---------------------------------------------------------------------------
+
+type SetIssuePropertyRequest struct {
+ Value json.RawMessage `json:"value"`
+}
+
+func (h *Handler) SetIssueProperty(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ propertyID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "propertyId"), "property id")
+ if !ok {
+ return
+ }
+ var req SetIssuePropertyRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+
+ issue, ok := h.loadIssueForUser(w, r, issueID)
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ // Validation and write share the property advisory lock with definition
+ // updates: the value written is guaranteed to reference the definition
+ // state that a concurrent config edit's usage census will see (TOCTOU,
+ // clean-room review F1).
+ var updated db.Issue
+ var httpStatus int
+ var httpMsg string
+ fail := func(status int, msg string) error {
+ httpStatus, httpMsg = status, msg
+ return errClientRejected
+ }
+ err := h.withPropertyLock(r, []string{"prop:" + uuidToString(propertyID)}, func(q *db.Queries) error {
+ def, err := q.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: propertyID, WorkspaceID: issue.WorkspaceID})
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return fail(http.StatusNotFound, "property not found")
+ }
+ return err
+ }
+ if def.ArchivedAt.Valid {
+ return fail(http.StatusBadRequest, fmt.Sprintf("property %q is archived and cannot receive new values", def.Name))
+ }
+ value, err := validatePropertyValue(def, req.Value)
+ if err != nil {
+ return fail(http.StatusBadRequest, err.Error())
+ }
+ updated, err = q.SetIssuePropertyValue(r.Context(), db.SetIssuePropertyValueParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ Key: uuidToString(def.ID),
+ Value: value,
+ })
+ if err != nil {
+ if isCheckViolation(err) {
+ return fail(http.StatusBadRequest, "issue properties exceed the 16KB size limit")
+ }
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ if errors.Is(err, errClientRejected) {
+ writeError(w, httpStatus, httpMsg)
+ return
+ }
+ slog.Warn("SetIssueProperty failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
+ writeError(w, http.StatusInternalServerError, "failed to set property")
+ return
+ }
+
+ workspaceID := uuidToString(updated.WorkspaceID)
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ properties := parseIssueProperties(updated.Properties)
+ h.publish(protocol.EventIssuePropertiesChanged, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": uuidToString(updated.ID),
+ "properties": properties,
+ })
+ writeJSON(w, http.StatusOK, map[string]any{"properties": properties})
+}
+
+func (h *Handler) DeleteIssueProperty(w http.ResponseWriter, r *http.Request) {
+ issueID := chi.URLParam(r, "id")
+ propertyID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "propertyId"), "property id")
+ if !ok {
+ return
+ }
+
+ issue, ok := h.loadIssueForUser(w, r, issueID)
+ if !ok {
+ return
+ }
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
+
+ // Deleting a value is allowed even for archived definitions — cleanup
+ // must never be blocked. Unknown property ids only need to belong to the
+ // workspace; `properties - key` is a no-op when the key is absent.
+ if _, err := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: propertyID, WorkspaceID: issue.WorkspaceID}); err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ writeError(w, http.StatusNotFound, "property not found")
+ return
+ }
+ slog.Warn("GetIssueProperty in DeleteIssueProperty failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to unset property")
+ return
+ }
+
+ updated, err := h.Queries.DeleteIssuePropertyValue(r.Context(), db.DeleteIssuePropertyValueParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ Key: uuidToString(propertyID),
+ })
+ if err != nil {
+ slog.Warn("DeleteIssuePropertyValue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
+ writeError(w, http.StatusInternalServerError, "failed to unset property")
+ return
+ }
+
+ workspaceID := uuidToString(updated.WorkspaceID)
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ properties := parseIssueProperties(updated.Properties)
+ h.publish(protocol.EventIssuePropertiesChanged, workspaceID, actorType, actorID, map[string]any{
+ "issue_id": uuidToString(updated.ID),
+ "properties": properties,
+ })
+ writeJSON(w, http.StatusOK, map[string]any{"properties": properties})
+}
+
+// withPropertyLock runs fn inside a transaction holding the advisory lock
+// for the given key, serializing definition mutations against value writes
+// (TOCTOU: a config update's usage census and a concurrent value write could
+// otherwise interleave into a permanently orphaned option reference) and
+// definition creates/unarchives against each other (the 20-active cap and
+// MAX(position)+1 are read-then-write). Locks are transaction-scoped.
+func (h *Handler) withPropertyLock(r *http.Request, lockKeys []string, fn func(q *db.Queries) error) error {
+ tx, err := h.TxStarter.Begin(r.Context())
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback(r.Context())
+ // Callers pass keys in a fixed global order (workspace before property)
+ // so overlapping lock sets cannot deadlock.
+ for _, key := range lockKeys {
+ if _, err := tx.Exec(r.Context(), "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key); err != nil {
+ return err
+ }
+ }
+ if err := fn(h.Queries.WithTx(tx)); err != nil {
+ return err
+ }
+ return tx.Commit(r.Context())
+}
+
+// ---------------------------------------------------------------------------
+// List-endpoint support: properties filter + property sort expressions
+// ---------------------------------------------------------------------------
+
+const (
+ maxPropertiesFilterDefinitions = 20
+ maxPropertiesFilterValues = 50
+)
+
+// parsePropertiesFilterParam reads the `properties` query parameter — a JSON
+// object of {<definitionId>: [<value>, ...]} — and compiles it into OR-groups
+// of containment objects: OR within a definition, AND across definitions.
+//
+// Values are option ids for select/multi_select and "true"/"false" for
+// checkbox. The stored value shape differs per type (string, array element,
+// boolean), so each value expands to every containment form it could match;
+// forms that can't match are simply never satisfied.
+//
+// Returns (nil, true) when the parameter is empty.
+func parsePropertiesFilterParam(w http.ResponseWriter, raw string) ([][]json.RawMessage, bool) {
+ if raw == "" {
+ return nil, true
+ }
+ var parsed map[string][]string
+ if err := json.Unmarshal([]byte(raw), &parsed); err != nil {
+ writeError(w, http.StatusBadRequest, "properties filter must be a JSON object of {definitionId: [values]}")
+ return nil, false
+ }
+ if len(parsed) > maxPropertiesFilterDefinitions {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter cannot cover more than %d definitions", maxPropertiesFilterDefinitions))
+ return nil, false
+ }
+ groups := make([][]json.RawMessage, 0, len(parsed))
+ totalAlternatives := 0
+ for definitionID, values := range parsed {
+ if _, err := uuid.Parse(definitionID); err != nil {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter key %q is not a definition id", definitionID))
+ return nil, false
+ }
+ if len(values) == 0 {
+ continue
+ }
+ if len(values) > maxPropertiesFilterValues {
+ writeError(w, http.StatusBadRequest, fmt.Sprintf("properties filter for %s cannot list more than %d values", definitionID, maxPropertiesFilterValues))
+ return nil, false
+ }
+ alternatives := make([]json.RawMessage, 0, len(values)*3)
+ appendAlt := func(v any) bool {
+ buf, err := json.Marshal(map[string]any{definitionID: v})
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "properties filter is invalid")
+ return false
+ }
+ alternatives = append(alternatives, buf)
+ return true
+ }
+ for _, value := range values {
+ if value == "" {
+ writeError(w, http.StatusBadRequest, "properties filter values cannot be empty")
+ return nil, false
+ }
+ if !appendAlt(value) || !appendAlt([]string{value}) { // select string / multi_select element
+ return nil, false
+ }
+ if value == "true" || value == "false" {
+ if !appendAlt(value == "true") { // checkbox boolean
+ return nil, false
+ }
+ }
+ }
+ totalAlternatives += len(alternatives)
+ groups = append(groups, alternatives)
+ }
+ if len(groups) == 0 {
+ return nil, true
+ }
+ // Bound the OR fan-out: each alternative becomes one bind parameter in
+ // the SQL below, and a runaway filter would bloat the statement.
+ if totalAlternatives > 256 {
+ writeError(w, http.StatusBadRequest, "properties filter is too large")
+ return nil, false
+ }
+ return groups, true
+}
+
+// propertiesFilterPredicate renders the AND-of-ORs containment check for a
+// compiled filter as plain `i.properties @> $n` disjunctions with one bind
+// parameter per alternative. Constant containment operands are what lets the
+// planner drive the jsonb_path_ops GIN index (a correlated
+// jsonb_array_elements form defeats it — verified via EXPLAIN in review).
+func propertiesFilterPredicate(groups [][]json.RawMessage, addArg func(any) string) string {
+ groupSQL := make([]string, 0, len(groups))
+ for _, alternatives := range groups {
+ ors := make([]string, 0, len(alternatives))
+ for _, alt := range alternatives {
+ ors = append(ors, fmt.Sprintf("i.properties @> %s::jsonb", addArg(string(alt))))
+ }
+ groupSQL = append(groupSQL, "("+strings.Join(ors, " OR ")+")")
+ }
+ return "(" + strings.Join(groupSQL, " AND ") + ")"
+}
+
+// propertySortExpr resolves a `property:<definitionId>` sort value into a SQL
+// ORDER BY expression. Returns handled=false when sortValue is not
+// property-shaped (caller falls through to its static whitelist). A malformed
+// id writes a 400 (ok=false). An unknown/archived definition or a type that
+// has no meaningful order degrades to empty expr — callers keep position
+// order, mirroring the frontend's stale-persisted-sort fallback rather than
+// breaking installed clients with a 400.
+func (h *Handler) propertySortExpr(r *http.Request, workspaceID string, sortValue string) (expr string, handled bool, err error) {
+ const prefix = "property:"
+ if !strings.HasPrefix(sortValue, prefix) {
+ return "", false, nil
+ }
+ rawID := strings.TrimPrefix(sortValue, prefix)
+ parsedID, parseErr := uuid.Parse(rawID)
+ if parseErr != nil {
+ return "", true, errors.New("invalid sort value")
+ }
+ wsUUID, wsErr := util.ParseUUID(workspaceID)
+ if wsErr != nil {
+ return "", true, errors.New("invalid workspace id")
+ }
+ var defUUID pgtype.UUID
+ copy(defUUID.Bytes[:], parsedID[:])
+ defUUID.Valid = true
+ def, dbErr := h.Queries.GetIssueProperty(r.Context(), db.GetIssuePropertyParams{ID: defUUID, WorkspaceID: wsUUID})
+ if dbErr != nil {
+ if errors.Is(dbErr, pgx.ErrNoRows) {
+ return "", true, nil // stale sort → position order
+ }
+ return "", true, fmt.Errorf("resolve sort property: %w", dbErr)
+ }
+ // Archived definitions degrade to position order like unknown ones —
+ // their values are hidden from the UI, so sorting by them would order
+ // the list by invisible data.
+ if def.ArchivedAt.Valid {
+ return "", true, nil
+ }
+ // uuidToString re-serializes the parsed UUID: hex and dashes only, safe
+ // to embed in the ORDER BY string.
+ id := uuidToString(def.ID)
+ switch def.Type {
+ case "number":
+ return fmt.Sprintf("CASE WHEN jsonb_typeof(i.properties->'%s') = 'number' THEN (i.properties->>'%s')::numeric END", id, id), true, nil
+ case "date", "text", "url", "select":
+ return fmt.Sprintf("NULLIF(i.properties->>'%s', '')", id), true, nil
+ default: // multi_select, checkbox, future types: no meaningful order
+ return "", true, nil
+ }
+}
diff --git a/server/internal/handler/property_test.go b/server/internal/handler/property_test.go
new file mode 100644
index 0000000000..907867f9f0
--- /dev/null
+++ b/server/internal/handler/property_test.go
@@ -0,0 +1,563 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/google/uuid"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func makePropertyDef(propType string, options []PropertyOption) db.IssueProperty {
+ cfg, _ := json.Marshal(PropertyConfig{Options: options})
+ return db.IssueProperty{Type: propType, Config: cfg}
+}
+
+// withIssuePropertyParams sets both chi URL params in one route context —
+// withURLParam builds a fresh context per call, so chaining it would drop
+// the first param.
+func withIssuePropertyParams(req *http.Request, issueID, propertyID string) *http.Request {
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", issueID)
+ rctx.URLParams.Add("propertyId", propertyID)
+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+}
+
+func createTestProperty(t *testing.T, body map[string]any) PropertyResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/properties", body)
+ testHandler.CreateProperty(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateProperty: expected 201, got %d: %s", w.Code, w.Body.String())
+ }
+ var created PropertyResponse
+ json.NewDecoder(w.Body).Decode(&created)
+ t.Cleanup(func() { deleteTestProperty(t, created.ID) })
+ return created
+}
+
+// deleteTestProperty removes the row directly — the API only archives, but
+// tests must not leak definitions into the shared workspace fixture (the
+// 20-active cap and list assertions would couple unrelated tests).
+func deleteTestProperty(t *testing.T, id string) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, id); err != nil {
+ t.Fatalf("cleanup property %s: %v", id, err)
+ }
+}
+
+func createPropertyTestIssue(t *testing.T, title string) string {
+ t.Helper()
+ var issueID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)
+ VALUES ($1, $2, 'todo', 'none', 'member', $3,
+ COALESCE((SELECT MAX(number) FROM issue WHERE workspace_id = $1), 0) + 1)
+ RETURNING id
+ `, testWorkspaceID, title, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create test issue: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+ return issueID
+}
+
+func setIssuePropertyRaw(t *testing.T, issueID, propertyID string, value any) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ req := newRequest("PUT", "/api/issues/"+issueID+"/properties/"+propertyID, map[string]any{"value": value})
+ req = withIssuePropertyParams(req, issueID, propertyID)
+ testHandler.SetIssueProperty(w, req)
+ return w
+}
+
+func TestPropertyDefinitionCRUD(t *testing.T) {
+ created := createTestProperty(t, map[string]any{
+ "name": "Severity",
+ "type": "select",
+ "description": "How bad it is",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "Critical", "color": "EF4444"},
+ {"name": "Minor", "color": "#6b7280"},
+ }},
+ })
+ if created.Type != "select" || len(created.Config.Options) != 2 {
+ t.Fatalf("unexpected created property: %+v", created)
+ }
+ // Server assigns option ids and normalizes colors to lowercase #rrggbb.
+ if created.Config.Options[0].ID == "" {
+ t.Fatalf("option id not assigned: %+v", created.Config.Options[0])
+ }
+ if created.Config.Options[0].Color != "#ef4444" {
+ t.Fatalf("color not normalized: %q", created.Config.Options[0].Color)
+ }
+
+ // Duplicate name (case-insensitive) → 409.
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/properties", map[string]any{
+ "name": "severity", "type": "text",
+ })
+ testHandler.CreateProperty(w, req)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("duplicate name: expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Rename + replace options, keeping the first option's id: values that
+ // reference it must survive option-list edits.
+ keepID := created.Config.Options[0].ID
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/properties/"+created.ID, map[string]any{
+ "name": "Sev",
+ "config": map[string]any{"options": []map[string]any{
+ {"id": keepID, "name": "Blocker", "color": "#ef4444"},
+ {"name": "Trivial", "color": "#a1a1aa"},
+ }},
+ })
+ req = withURLParam(req, "id", created.ID)
+ testHandler.UpdateProperty(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("UpdateProperty: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var updated PropertyResponse
+ json.NewDecoder(w.Body).Decode(&updated)
+ if updated.Name != "Sev" || updated.Config.Options[0].ID != keepID || updated.Config.Options[0].Name != "Blocker" {
+ t.Fatalf("option id not preserved on update: %+v", updated.Config.Options)
+ }
+
+ // Archive → default list hides it, include_archived shows it.
+ w = httptest.NewRecorder()
+ req = newRequest("PATCH", "/api/properties/"+created.ID, map[string]any{"archived": true})
+ req = withURLParam(req, "id", created.ID)
+ testHandler.UpdateProperty(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("archive: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ listProperties := func(query string) []PropertyResponse {
+ w := httptest.NewRecorder()
+ testHandler.ListProperties(w, newRequest("GET", "/api/properties"+query, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListProperties%s: expected 200, got %d: %s", query, w.Code, w.Body.String())
+ }
+ var resp struct {
+ Properties []PropertyResponse `json:"properties"`
+ }
+ json.NewDecoder(w.Body).Decode(&resp)
+ return resp.Properties
+ }
+ contains := func(list []PropertyResponse, id string) bool {
+ for _, p := range list {
+ if p.ID == id {
+ return true
+ }
+ }
+ return false
+ }
+ if contains(listProperties(""), created.ID) {
+ t.Fatalf("archived property still in default list")
+ }
+ if !contains(listProperties("?include_archived=true"), created.ID) {
+ t.Fatalf("archived property missing from include_archived list")
+ }
+}
+
+func TestPropertyDefinitionValidation(t *testing.T) {
+ cases := []struct {
+ name string
+ body map[string]any
+ want string
+ }{
+ {"reserved name", map[string]any{"name": "Due Date", "type": "text"}, "reserved"},
+ {"invalid type", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "formula"}, "invalid type"},
+ {"options on text", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "text",
+ "config": map[string]any{"options": []map[string]any{{"name": "a", "color": "#000000"}}}}, "does not accept options"},
+ {"select without options", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "select"}, "at least one option"},
+ {"duplicate option names", map[string]any{"name": "X" + uuid.NewString()[:8], "type": "select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "One", "color": "#000000"}, {"name": "one", "color": "#111111"},
+ }}}, "duplicate option name"},
+ }
+ for _, tc := range cases {
+ w := httptest.NewRecorder()
+ testHandler.CreateProperty(w, newRequest("POST", "/api/properties", tc.body))
+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), tc.want) {
+ t.Fatalf("%s: expected 400 containing %q, got %d: %s", tc.name, tc.want, w.Code, w.Body.String())
+ }
+ }
+}
+
+// TestPropertyAdminGate verifies the two definition-management gates: agent
+// actors are rejected outright (even though the fixture user is the workspace
+// owner), while value writes from the same agent context succeed.
+func TestPropertyAdminGate(t *testing.T) {
+ // Agent actor (task_token path is trusted directly by resolveActor).
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/properties", map[string]any{"name": "AgentMade", "type": "text"})
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", uuid.NewString())
+ testHandler.CreateProperty(w, req)
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("agent CreateProperty: expected 403, got %d: %s", w.Code, w.Body.String())
+ }
+
+ property := createTestProperty(t, map[string]any{"name": "AgentWritable" + uuid.NewString()[:8], "type": "text"})
+ issueID := createPropertyTestIssue(t, "agent value write")
+
+ w = httptest.NewRecorder()
+ req = newRequest("PUT", "/api/issues/"+issueID+"/properties/"+property.ID, map[string]any{"value": "set by agent"})
+ req.Header.Set("X-Actor-Source", "task_token")
+ req.Header.Set("X-Agent-ID", uuid.NewString())
+ req = withIssuePropertyParams(req, issueID, property.ID)
+ testHandler.SetIssueProperty(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("agent SetIssueProperty: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestIssuePropertyValues(t *testing.T) {
+ sel := createTestProperty(t, map[string]any{
+ "name": "Env" + uuid.NewString()[:8], "type": "select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "Staging", "color": "#22c55e"},
+ {"name": "Production", "color": "#ef4444"},
+ }},
+ })
+ multi := createTestProperty(t, map[string]any{
+ "name": "Platforms" + uuid.NewString()[:8], "type": "multi_select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "iOS", "color": "#3b82f6"},
+ {"name": "Android", "color": "#22c55e"},
+ {"name": "Web", "color": "#f59e0b"},
+ }},
+ })
+ date := createTestProperty(t, map[string]any{"name": "Reviewed" + uuid.NewString()[:8], "type": "date"})
+ link := createTestProperty(t, map[string]any{"name": "Spec" + uuid.NewString()[:8], "type": "url"})
+ num := createTestProperty(t, map[string]any{"name": "Effort" + uuid.NewString()[:8], "type": "number"})
+
+ issueID := createPropertyTestIssue(t, "property value matrix")
+
+ // select: valid option id.
+ if w := setIssuePropertyRaw(t, issueID, sel.ID, sel.Config.Options[0].ID); w.Code != http.StatusOK {
+ t.Fatalf("select set: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ // select: unknown option → 400 listing legal ids (agents self-correct on this).
+ if w := setIssuePropertyRaw(t, issueID, sel.ID, "nope"); w.Code != http.StatusBadRequest ||
+ !strings.Contains(w.Body.String(), sel.Config.Options[0].ID) {
+ t.Fatalf("select invalid: expected 400 listing option ids, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // multi_select: duplicates dropped, order canonicalized to config order.
+ webID, iosID := multi.Config.Options[2].ID, multi.Config.Options[0].ID
+ w := setIssuePropertyRaw(t, issueID, multi.ID, []string{webID, iosID, webID})
+ if w.Code != http.StatusOK {
+ t.Fatalf("multi_select set: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp struct {
+ Properties map[string]any `json:"properties"`
+ }
+ json.NewDecoder(w.Body).Decode(&resp)
+ stored, _ := resp.Properties[multi.ID].([]any)
+ if len(stored) != 2 || stored[0] != iosID || stored[1] != webID {
+ t.Fatalf("multi_select not canonicalized to config order: %v", stored)
+ }
+
+ // date / url / number validation.
+ if w := setIssuePropertyRaw(t, issueID, date.ID, "13/07/2026"); w.Code != http.StatusBadRequest {
+ t.Fatalf("bad date: expected 400, got %d", w.Code)
+ }
+ if w := setIssuePropertyRaw(t, issueID, date.ID, "2026-07-13"); w.Code != http.StatusOK {
+ t.Fatalf("good date: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, issueID, link.ID, "javascript:alert(1)"); w.Code != http.StatusBadRequest {
+ t.Fatalf("bad url: expected 400, got %d", w.Code)
+ }
+ if w := setIssuePropertyRaw(t, issueID, link.ID, "https://example.com/spec"); w.Code != http.StatusOK {
+ t.Fatalf("good url: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, issueID, num.ID, "3"); w.Code != http.StatusBadRequest {
+ t.Fatalf("string into number: expected 400, got %d", w.Code)
+ }
+ if w := setIssuePropertyRaw(t, issueID, num.ID, 3.5); w.Code != http.StatusOK {
+ t.Fatalf("good number: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Archived definitions reject new values but allow unset.
+ warch := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/properties/"+sel.ID, map[string]any{"archived": true})
+ req = withURLParam(req, "id", sel.ID)
+ testHandler.UpdateProperty(warch, req)
+ if warch.Code != http.StatusOK {
+ t.Fatalf("archive: expected 200, got %d: %s", warch.Code, warch.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, issueID, sel.ID, sel.Config.Options[1].ID); w.Code != http.StatusBadRequest {
+ t.Fatalf("set on archived: expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+ wdel := httptest.NewRecorder()
+ req = newRequest("DELETE", "/api/issues/"+issueID+"/properties/"+sel.ID, nil)
+ req = withIssuePropertyParams(req, issueID, sel.ID)
+ testHandler.DeleteIssueProperty(wdel, req)
+ if wdel.Code != http.StatusOK {
+ t.Fatalf("unset on archived: expected 200, got %d: %s", wdel.Code, wdel.Body.String())
+ }
+ // Fresh struct: json.Decode merges into a pre-populated map, which would
+ // leave the earlier bag contents (including sel.ID) in place.
+ var afterDelete struct {
+ Properties map[string]any `json:"properties"`
+ }
+ json.NewDecoder(wdel.Body).Decode(&afterDelete)
+ if _, present := afterDelete.Properties[sel.ID]; present {
+ t.Fatalf("value not removed: %v", afterDelete.Properties)
+ }
+}
+
+func TestValidatePropertyValueUnit(t *testing.T) {
+ textDef := makePropertyDef("text", nil)
+ if _, err := validatePropertyValue(textDef, json.RawMessage(`" "`)); err == nil {
+ t.Fatalf("blank text accepted")
+ }
+ if _, err := validatePropertyValue(textDef, json.RawMessage(`"`+strings.Repeat("x", 2001)+`"`)); err == nil {
+ t.Fatalf("overlong text accepted")
+ }
+ if _, err := validatePropertyValue(textDef, json.RawMessage(`null`)); err == nil {
+ t.Fatalf("null accepted")
+ }
+ boolDef := makePropertyDef("checkbox", nil)
+ if _, err := validatePropertyValue(boolDef, json.RawMessage(`"true"`)); err == nil {
+ t.Fatalf("string into checkbox accepted")
+ }
+ if _, err := validatePropertyValue(boolDef, json.RawMessage(`false`)); err != nil {
+ t.Fatalf("false rejected: %v", err)
+ }
+}
+
+func TestValidatePropertyNameReserved(t *testing.T) {
+ for _, name := range []string{"status", "Priority", "due date", "Due_Date", "START DATE", "labels"} {
+ if _, err := validatePropertyName(name); err == nil {
+ t.Fatalf("reserved name %q accepted", name)
+ }
+ }
+ if _, err := validatePropertyName("Severity"); err != nil {
+ t.Fatalf("legit name rejected: %v", err)
+ }
+}
+
+// TestPropertyOptionRemovalGuard: removing a select option still referenced
+// by issues is rejected with a usage census; renames (same id) and removal
+// of unused options pass.
+func TestPropertyOptionRemovalGuard(t *testing.T) {
+ property := createTestProperty(t, map[string]any{
+ "name": "Guard" + uuid.NewString()[:8], "type": "select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "Used", "color": "#ef4444"},
+ {"name": "Unused", "color": "#6b7280"},
+ }},
+ })
+ usedID := property.Config.Options[0].ID
+ unusedID := property.Config.Options[1].ID
+ issueID := createPropertyTestIssue(t, "option removal guard")
+ if w := setIssuePropertyRaw(t, issueID, property.ID, usedID); w.Code != http.StatusOK {
+ t.Fatalf("seed value: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ patchConfig := func(options []map[string]any) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ req := newRequest("PATCH", "/api/properties/"+property.ID, map[string]any{
+ "config": map[string]any{"options": options},
+ })
+ req = withURLParam(req, "id", property.ID)
+ testHandler.UpdateProperty(w, req)
+ return w
+ }
+
+ // Dropping the in-use option → 409 naming it with the census.
+ w := patchConfig([]map[string]any{{"id": unusedID, "name": "Unused", "color": "#6b7280"}})
+ if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), "Used") || !strings.Contains(w.Body.String(), "1 issues") {
+ t.Fatalf("in-use removal: expected 409 with census, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Renaming the in-use option (id preserved) → 200.
+ w = patchConfig([]map[string]any{
+ {"id": usedID, "name": "Used (renamed)", "color": "#ef4444"},
+ {"id": unusedID, "name": "Unused", "color": "#6b7280"},
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("rename: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+
+ // Dropping only the unused option → 200.
+ w = patchConfig([]map[string]any{{"id": usedID, "name": "Used (renamed)", "color": "#ef4444"}})
+ if w.Code != http.StatusOK {
+ t.Fatalf("unused removal: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// TestListIssuesPropertyFilterAndSort covers the server-side list support:
+// containment filtering (select / multi_select / checkbox) beyond the first
+// page window, and typed property sort expressions with missing-last
+// semantics. The shared workspace fixture may hold foreign issues, so
+// assertions check relative order / membership rather than exact lists.
+func TestListIssuesPropertyFilterAndSort(t *testing.T) {
+ sel := createTestProperty(t, map[string]any{
+ "name": "FS" + uuid.NewString()[:8], "type": "select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "Hit", "color": "#ef4444"},
+ {"name": "Miss", "color": "#6b7280"},
+ }},
+ })
+ hitID := sel.Config.Options[0].ID
+ multi := createTestProperty(t, map[string]any{
+ "name": "FM" + uuid.NewString()[:8], "type": "multi_select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "A", "color": "#3b82f6"},
+ {"name": "B", "color": "#22c55e"},
+ }},
+ })
+ multiB := multi.Config.Options[1].ID
+ box := createTestProperty(t, map[string]any{"name": "FB" + uuid.NewString()[:8], "type": "checkbox"})
+ num := createTestProperty(t, map[string]any{"name": "FN" + uuid.NewString()[:8], "type": "number"})
+
+ // 54 padding issues at explicit ascending positions, then the matching
+ // issue at the highest position — genuinely beyond the 50-row first page
+ // (review round 3: without explicit positions everything ties at 0 and
+ // the created_at DESC tie-breaker put the target on page one).
+ setPosition := func(issueID string, position float64) {
+ t.Helper()
+ if _, err := testPool.Exec(context.Background(),
+ `UPDATE issue SET position = $1 WHERE id = $2`, position, issueID); err != nil {
+ t.Fatalf("set position: %v", err)
+ }
+ }
+ for i := 0; i < 54; i++ {
+ setPosition(createPropertyTestIssue(t, fmt.Sprintf("filter pad %02d", i)), float64(i))
+ }
+ target := createPropertyTestIssue(t, "filter target beyond page one")
+ setPosition(target, 1000)
+ if w := setIssuePropertyRaw(t, target, sel.ID, hitID); w.Code != http.StatusOK {
+ t.Fatalf("seed select: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, target, multi.ID, []string{multiB}); w.Code != http.StatusOK {
+ t.Fatalf("seed multi: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, target, box.ID, true); w.Code != http.StatusOK {
+ t.Fatalf("seed checkbox: %d %s", w.Code, w.Body.String())
+ }
+
+ numLow := createPropertyTestIssue(t, "sort low")
+ numHigh := createPropertyTestIssue(t, "sort high")
+ if w := setIssuePropertyRaw(t, numLow, num.ID, 1); w.Code != http.StatusOK {
+ t.Fatalf("seed low: %d %s", w.Code, w.Body.String())
+ }
+ if w := setIssuePropertyRaw(t, numHigh, num.ID, 9.5); w.Code != http.StatusOK {
+ t.Fatalf("seed high: %d %s", w.Code, w.Body.String())
+ }
+
+ listIssues := func(query string) []IssueResponse {
+ t.Helper()
+ w := httptest.NewRecorder()
+ testHandler.ListIssues(w, newRequest("GET", "/api/issues"+query, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("ListIssues%s: expected 200, got %d: %s", query, w.Code, w.Body.String())
+ }
+ var resp struct {
+ Issues []IssueResponse `json:"issues"`
+ }
+ json.NewDecoder(w.Body).Decode(&resp)
+ return resp.Issues
+ }
+ ids := func(list []IssueResponse) map[string]int {
+ out := make(map[string]int, len(list))
+ for i, issue := range list {
+ out[issue.ID] = i
+ }
+ return out
+ }
+ filterQuery := func(defID string, values ...string) string {
+ buf, _ := json.Marshal(map[string][]string{defID: values})
+ return "?limit=50&properties=" + url.QueryEscape(string(buf))
+ }
+
+ // Preconditions: the UNFILTERED first page must not contain the target
+ // (otherwise the assertions below prove nothing about windowing).
+ if _, present := ids(listIssues("?limit=50&sort=position&status=todo"))[target]; present {
+ t.Fatalf("windowing precondition broken: target already on the unfiltered first page")
+ }
+
+ // Select filter finds the issue past the 50-row window.
+ got := listIssues(filterQuery(sel.ID, hitID))
+ if _, present := ids(got)[target]; !present {
+ t.Fatalf("select filter missed the issue beyond page one")
+ }
+ for _, issue := range got {
+ if issue.Properties[sel.ID] != hitID {
+ t.Fatalf("select filter returned non-matching issue %s", issue.ID)
+ }
+ }
+
+ // Multi and checkbox containment forms.
+ if _, present := ids(listIssues(filterQuery(multi.ID, multiB)))[target]; !present {
+ t.Fatalf("multi_select filter missed the issue")
+ }
+ if _, present := ids(listIssues(filterQuery(box.ID, "true")))[target]; !present {
+ t.Fatalf("checkbox filter missed the issue")
+ }
+ // AND across definitions: matching select + non-matching checkbox → empty of target.
+ buf, _ := json.Marshal(map[string][]string{sel.ID: {hitID}, box.ID: {"false"}})
+ if _, present := ids(listIssues("?limit=50&properties=" + url.QueryEscape(string(buf))))[target]; present {
+ t.Fatalf("AND semantics failed: target matched with contradictory checkbox filter")
+ }
+
+ // The open_only branch honors the same filter via the static
+ // properties_filter param in ListOpenIssues (clean-room review: it used
+ // to be parsed and then silently dropped on this path).
+ openGot := listIssues(filterQuery(sel.ID, hitID) + "&open_only=true")
+ if _, present := ids(openGot)[target]; !present {
+ t.Fatalf("open_only ignored the properties filter: target missing")
+ }
+ for _, issue := range openGot {
+ if issue.Properties[sel.ID] != hitID {
+ t.Fatalf("open_only properties filter returned non-matching issue %s", issue.ID)
+ }
+ }
+ openBuf, _ := json.Marshal(map[string][]string{sel.ID: {hitID}, box.ID: {"false"}})
+ if _, present := ids(listIssues("?open_only=true&properties=" + url.QueryEscape(string(openBuf))))[target]; present {
+ t.Fatalf("open_only AND semantics failed: target matched contradictory filter")
+ }
+
+ // Property sort: asc = low before high, valueless after both (missing last).
+ sorted := listIssues("?limit=200&sort=property:" + num.ID + "&direction=asc")
+ pos := ids(sorted)
+ lowIdx, lowOK := pos[numLow]
+ highIdx, highOK := pos[numHigh]
+ padIdx, padOK := pos[target]
+ if !lowOK || !highOK || !padOK {
+ t.Fatalf("sorted list missing seeded issues (low=%v high=%v pad=%v)", lowOK, highOK, padOK)
+ }
+ if !(lowIdx < highIdx && highIdx < padIdx) {
+ t.Fatalf("asc property sort order wrong: low=%d high=%d valueless=%d", lowIdx, highIdx, padIdx)
+ }
+ sorted = listIssues("?limit=200&sort=property:" + num.ID + "&direction=desc")
+ pos = ids(sorted)
+ if !(pos[numHigh] < pos[numLow] && pos[numLow] < pos[target]) {
+ t.Fatalf("desc property sort order wrong: high=%d low=%d valueless=%d", pos[numHigh], pos[numLow], pos[target])
+ }
+
+ // Malformed property sort id → 400; unknown definition → 200 position order.
+ w := httptest.NewRecorder()
+ testHandler.ListIssues(w, newRequest("GET", "/api/issues?sort=property:nope", nil))
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("malformed property sort: expected 400, got %d", w.Code)
+ }
+ if got := listIssues("?limit=5&sort=property:" + uuid.NewString()); len(got) == 0 {
+ t.Fatalf("unknown-definition sort should fall back to position order, got empty")
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
index 8133ca1fb9..50155efb7f 100644
--- a/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
+++ b/server/internal/service/builtin_skills/multica-working-on-issues/SKILL.md
@@ -146,6 +146,30 @@ multica issue metadata delete <issue-id> --key <stale-key>
`--value` is JSON-parsed by default (bool/number are sniffed); pass `--type
string|number|bool` to force a type.
+## Custom properties: typed workflow state
+
+Workspaces may define custom issue properties (Severity, Environment, QA
+Status, ...). Properties are the typed, user-visible sibling of metadata:
+values are validated against the definition (select options, date format,
+http(s) URL), visible in the issue sidebar, and addressed by name.
+
+- Read what exists before writing: `multica property list` shows the catalog;
+ `multica issue property list <issue-id>` shows values set on the issue.
+- Set values by property name and option name — the CLI translates to ids:
+
+```bash
+multica issue property set <issue-id> --name Environment --value staging
+multica issue property set <issue-id> --name Platforms --value "iOS,Android"
+multica issue property unset <issue-id> --name Environment
+```
+
+- A validation error lists the legal options — fix the value and retry.
+- Agents cannot create or edit property definitions (owner/admin humans only).
+ If a needed property does not exist, propose it in a comment instead.
+- Property vs metadata: if the value is workflow state a human should see and
+ filter by, and a definition exists, prefer the property. Metadata stays the
+ free-form scratchpad for run state (`pr_url`, `waiting_on`, ...).
+
## Status changes have server side effects
A status change is not cosmetic — the server enqueues or skips agent work based
diff --git a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
index 9ddbf702ab..ef45b98720 100644
--- a/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
+++ b/server/internal/service/builtin_skills/multica-working-on-issues/references/working-on-issues-source-map.md
@@ -159,6 +159,16 @@ wakes the parent assignee. Promoting the next stage's `backlog` sub-issues to
`--value` is JSON-parsed by default (bool/number sniff); `--type` forces
`string`/`number`/`bool`.
+## Custom properties CLI
+
+| Behavior | File:line |
+|---|---|
+| `multica property list/get/create/update/archive/unarchive` | `server/cmd/multica/cmd_property.go` |
+| `multica issue property list/set/unset` (name→id translation) | `server/cmd/multica/cmd_property.go` (`encodeIssuePropertyValue`) |
+| Definition CRUD, admin gate, agent-actor rejection | `server/internal/handler/property.go` (`requirePropertyAdmin`) |
+| Per-type value validation (self-correcting errors) | `server/internal/handler/property.go` (`validatePropertyValue`) |
+| API routes (`/api/properties`, PUT/DELETE `/api/issues/{id}/properties/{propertyId}`) | `server/cmd/server/router.go` |
+
## Verification command
Re-derive any line above before depending on it:
diff --git a/server/migrations/191_issue_properties.down.sql b/server/migrations/191_issue_properties.down.sql
new file mode 100644
index 0000000000..48f6341a31
--- /dev/null
+++ b/server/migrations/191_issue_properties.down.sql
@@ -0,0 +1,7 @@
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_properties_size_limit;
+ALTER TABLE issue DROP CONSTRAINT IF EXISTS issue_properties_is_object;
+ALTER TABLE issue DROP COLUMN IF EXISTS properties;
+
+DROP INDEX IF EXISTS idx_issue_property_workspace;
+DROP INDEX IF EXISTS idx_issue_property_ws_name;
+DROP TABLE IF EXISTS issue_property;
diff --git a/server/migrations/191_issue_properties.up.sql b/server/migrations/191_issue_properties.up.sql
new file mode 100644
index 0000000000..d5b5ec9886
--- /dev/null
+++ b/server/migrations/191_issue_properties.up.sql
@@ -0,0 +1,47 @@
+-- Custom issue properties (MUL-4463).
+--
+-- Two-part model:
+-- 1. issue_property — workspace-level property definitions (the catalog),
+-- structurally a sibling of issue_label.
+-- 2. issue.properties — JSONB value bag on each issue keyed by property
+-- definition UUID, structurally a sibling of issue.metadata. Values are
+-- typed per the definition and validated in the handler; keys are UUIDs
+-- so definition renames never require value migrations.
+--
+-- Definitions are archived (archived_at), never deleted — historical values
+-- stay resolvable. The active-definition cap (20/workspace) and per-type value
+-- validation live in the handler.
+
+CREATE TABLE issue_property (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
+ name TEXT NOT NULL,
+ type TEXT NOT NULL CHECK (type IN ('text', 'number', 'select', 'multi_select', 'date', 'checkbox', 'url')),
+ description TEXT NOT NULL DEFAULT '',
+ -- select / multi_select: {"options": [{"id", "name", "color"}]}; {} for other types.
+ config JSONB NOT NULL DEFAULT '{}'::jsonb CHECK (jsonb_typeof(config) = 'object'),
+ position FLOAT NOT NULL DEFAULT 0,
+ archived_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE UNIQUE INDEX idx_issue_property_ws_name ON issue_property (workspace_id, LOWER(name));
+CREATE INDEX idx_issue_property_workspace ON issue_property (workspace_id);
+
+ALTER TABLE issue ADD COLUMN properties JSONB NOT NULL DEFAULT '{}'::jsonb;
+-- NOT VALID + VALIDATE keeps the ACCESS EXCLUSIVE lock instantaneous; the
+-- validation pass then runs under SHARE UPDATE EXCLUSIVE without blocking
+-- writes (zero-downtime deploys, review round 3).
+ALTER TABLE issue ADD CONSTRAINT issue_properties_is_object
+ CHECK (jsonb_typeof(properties) = 'object') NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_properties_is_object;
+-- Larger than metadata's 8KB: multi_select arrays and text values are bigger
+-- than metadata primitives, but the bag is still bounded by the definition cap.
+ALTER TABLE issue ADD CONSTRAINT issue_properties_size_limit
+ CHECK (pg_column_size(properties) <= 16384) NOT VALID;
+ALTER TABLE issue VALIDATE CONSTRAINT issue_properties_size_limit;
+-- The GIN index on issue.properties lives in the follow-up migration
+-- (192_issue_properties_gin_index): CREATE INDEX CONCURRENTLY cannot share a
+-- migration with other statements, and a plain CREATE INDEX would lock writes
+-- on the hot issue table for the duration of the build.
diff --git a/server/migrations/192_issue_properties_gin_index.down.sql b/server/migrations/192_issue_properties_gin_index.down.sql
new file mode 100644
index 0000000000..8f55601e53
--- /dev/null
+++ b/server/migrations/192_issue_properties_gin_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_issue_properties_gin;
diff --git a/server/migrations/192_issue_properties_gin_index.up.sql b/server/migrations/192_issue_properties_gin_index.up.sql
new file mode 100644
index 0000000000..f86914c4bc
--- /dev/null
+++ b/server/migrations/192_issue_properties_gin_index.up.sql
@@ -0,0 +1,6 @@
+-- Containment index for custom-property value filtering (MUL-4463).
+-- Separate single-statement migration: CREATE INDEX CONCURRENTLY cannot run
+-- inside a transaction or share a migration, and a non-concurrent build would
+-- block writes on the hot issue table for the duration of the scan.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_issue_properties_gin
+ ON issue USING GIN (properties jsonb_path_ops);
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 71ae4b8460..2c94c82b14 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -179,7 +179,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type CreateIssueParams struct {
@@ -247,6 +247,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
@@ -260,7 +261,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
$16, $17, $18
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type CreateIssueWithOriginParams struct {
@@ -332,6 +333,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
@@ -360,7 +362,7 @@ UPDATE issue SET
metadata = metadata - $1::text,
updated_at = now()
WHERE id = $2 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type DeleteIssueMetadataKeyParams struct {
@@ -400,12 +402,13 @@ func (q *Queries) DeleteIssueMetadataKey(ctx context.Context, arg DeleteIssueMet
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const findActiveDuplicateIssue = `-- name: FindActiveDuplicateIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE workspace_id = $1
AND status NOT IN ('done', 'cancelled')
AND project_id IS NOT DISTINCT FROM $2::uuid
@@ -456,12 +459,13 @@ func (q *Queries) FindActiveDuplicateIssue(ctx context.Context, arg FindActiveDu
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const findRecentAutopilotDuplicateIssue = `-- name: FindRecentAutopilotDuplicateIssue :one
-SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage FROM issue i
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.origin_type, i.origin_id, i.first_executed_at, i.start_date, i.metadata, i.stage, i.properties FROM issue i
WHERE i.workspace_id = $1
AND i.status NOT IN ('done', 'cancelled')
AND i.origin_type = 'autopilot'
@@ -523,12 +527,13 @@ func (q *Queries) FindRecentAutopilotDuplicateIssue(ctx context.Context, arg Fin
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const getIssue = `-- name: GetIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE id = $1
`
@@ -561,12 +566,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const getIssueByNumber = `-- name: GetIssueByNumber :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE workspace_id = $1 AND number = $2
`
@@ -604,12 +610,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const getIssueByOrigin = `-- name: GetIssueByOrigin :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE workspace_id = $1
AND origin_type = $2
AND origin_id = $3
@@ -656,12 +663,13 @@ func (q *Queries) GetIssueByOrigin(ctx context.Context, arg GetIssueByOriginPara
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE id = $1 AND workspace_id = $2
`
@@ -699,12 +707,13 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
const listChildIssues = `-- name: ListChildIssues :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE parent_issue_id = $1
ORDER BY number ASC
`
@@ -750,6 +759,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
); err != nil {
return nil, err
}
@@ -762,7 +772,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
}
const listChildrenByParents = `-- name: ListChildrenByParents :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
WHERE workspace_id = $1
AND parent_issue_id = ANY($2::uuid[])
ORDER BY parent_issue_id, number ASC
@@ -815,6 +825,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
); err != nil {
return nil, err
}
@@ -829,7 +840,7 @@ func (q *Queries) ListChildrenByParents(ctx context.Context, arg ListChildrenByP
const listIssues = `-- name: ListIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
FROM issue i
WHERE i.workspace_id = $1
AND ($4::text IS NULL OR i.status = $4)
@@ -920,6 +931,7 @@ type ListIssuesRow struct {
ProjectID pgtype.UUID `json:"project_id"`
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
}
// involves_user_id widens the assignee filter to surface issues where the user
@@ -971,6 +983,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
&i.ProjectID,
&i.Metadata,
&i.Stage,
+ &i.Properties,
); err != nil {
return nil, err
}
@@ -985,7 +998,7 @@ func (q *Queries) ListIssues(ctx context.Context, arg ListIssuesParams) ([]ListI
const listOpenIssues = `-- name: ListOpenIssues :many
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
FROM issue i
WHERE i.workspace_id = $1
AND i.status NOT IN ('done', 'cancelled')
@@ -995,12 +1008,29 @@ WHERE i.workspace_id = $1
AND ($5::uuid IS NULL OR i.creator_id = $5)
AND ($6::uuid IS NULL OR i.project_id = $6)
AND ($7::jsonb IS NULL OR i.metadata @> $7::jsonb)
+ -- properties_filter is a jsonb array of groups, each group an array of
+ -- containment patterns (built by parsePropertiesFilterParam): the issue
+ -- must match at least one pattern from EVERY group (AND of ORs). The
+ -- correlated form skips the GIN index, which is fine here: open_only is
+ -- an unpaginated workspace scan already narrowed by status.
AND (
- $8::uuid IS NULL
+ $8::jsonb IS NULL
+ OR NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements($8::jsonb) AS pf(alternatives)
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(pf.alternatives) AS alt(pattern)
+ WHERE i.properties @> alt.pattern
+ )
+ )
+ )
+ AND (
+ $9::uuid IS NULL
OR (i.assignee_type = 'agent' AND i.assignee_id IN (
SELECT a.id FROM agent a
WHERE a.workspace_id = $1
- AND a.owner_id = $8::uuid
+ AND a.owner_id = $9::uuid
))
OR (i.assignee_type = 'squad' AND i.assignee_id IN (
SELECT sm.squad_id
@@ -1008,14 +1038,14 @@ WHERE i.workspace_id = $1
JOIN squad s ON s.id = sm.squad_id
WHERE s.workspace_id = $1
AND sm.member_type = 'member'
- AND sm.member_id = $8::uuid
+ AND sm.member_id = $9::uuid
UNION
SELECT s.id
FROM squad s
JOIN agent a ON a.id = s.leader_id
WHERE s.workspace_id = $1
AND a.workspace_id = $1
- AND a.owner_id = $8::uuid
+ AND a.owner_id = $9::uuid
UNION
SELECT sm.squad_id
FROM squad_member sm
@@ -1024,21 +1054,22 @@ WHERE i.workspace_id = $1
WHERE s.workspace_id = $1
AND sm.member_type = 'agent'
AND a.workspace_id = $1
- AND a.owner_id = $8::uuid
+ AND a.owner_id = $9::uuid
))
)
ORDER BY i.position ASC, i.created_at DESC
`
type ListOpenIssuesParams struct {
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- Priority pgtype.Text `json:"priority"`
- AssigneeID pgtype.UUID `json:"assignee_id"`
- AssigneeIds []pgtype.UUID `json:"assignee_ids"`
- CreatorID pgtype.UUID `json:"creator_id"`
- ProjectID pgtype.UUID `json:"project_id"`
- MetadataFilter []byte `json:"metadata_filter"`
- InvolvesUserID pgtype.UUID `json:"involves_user_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Priority pgtype.Text `json:"priority"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ AssigneeIds []pgtype.UUID `json:"assignee_ids"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ ProjectID pgtype.UUID `json:"project_id"`
+ MetadataFilter []byte `json:"metadata_filter"`
+ PropertiesFilter []byte `json:"properties_filter"`
+ InvolvesUserID pgtype.UUID `json:"involves_user_id"`
}
type ListOpenIssuesRow struct {
@@ -1062,6 +1093,7 @@ type ListOpenIssuesRow struct {
ProjectID pgtype.UUID `json:"project_id"`
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
}
// See ListIssues for the semantics of involves_user_id (mirrors the 4-branch
@@ -1075,6 +1107,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
arg.CreatorID,
arg.ProjectID,
arg.MetadataFilter,
+ arg.PropertiesFilter,
arg.InvolvesUserID,
)
if err != nil {
@@ -1105,6 +1138,7 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
&i.ProjectID,
&i.Metadata,
&i.Stage,
+ &i.Properties,
); err != nil {
return nil, err
}
@@ -1163,7 +1197,7 @@ UPDATE issue SET
metadata = jsonb_set(metadata, ARRAY[$1::text], $2::jsonb),
updated_at = now()
WHERE id = $3 AND workspace_id = $4
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type SetIssueMetadataKeyParams struct {
@@ -1211,6 +1245,7 @@ func (q *Queries) SetIssueMetadataKey(ctx context.Context, arg SetIssueMetadataK
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
@@ -1231,7 +1266,7 @@ UPDATE issue SET
stage = $13,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type UpdateIssueParams struct {
@@ -1293,6 +1328,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
@@ -1302,7 +1338,7 @@ UPDATE issue SET
status = $2,
updated_at = now()
WHERE id = $1 AND workspace_id = $3
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
`
type UpdateIssueStatusParams struct {
@@ -1341,6 +1377,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa
&i.StartDate,
&i.Metadata,
&i.Stage,
+ &i.Properties,
)
return i, err
}
diff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.go
new file mode 100644
index 0000000000..2a20d8c55c
--- /dev/null
+++ b/server/pkg/db/generated/issue_property.sql.go
@@ -0,0 +1,361 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: issue_property.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const countActiveIssueProperties = `-- name: CountActiveIssueProperties :one
+SELECT COUNT(*) FROM issue_property
+WHERE workspace_id = $1 AND archived_at IS NULL
+`
+
+func (q *Queries) CountActiveIssueProperties(ctx context.Context, workspaceID pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countActiveIssueProperties, workspaceID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countIssuesUsingPropertyOptions = `-- name: CountIssuesUsingPropertyOptions :many
+SELECT opt::text AS option_id, COUNT(i.id) AS usage_count
+FROM unnest($1::text[]) AS opt
+LEFT JOIN issue i
+ ON i.workspace_id = $2::uuid
+ AND (i.properties -> $3::text) ? opt
+GROUP BY opt
+HAVING COUNT(i.id) > 0
+`
+
+type CountIssuesUsingPropertyOptionsParams struct {
+ OptionIds []string `json:"option_ids"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ PropertyKey string `json:"property_key"`
+}
+
+type CountIssuesUsingPropertyOptionsRow struct {
+ OptionID string `json:"option_id"`
+ UsageCount int64 `json:"usage_count"`
+}
+
+// Usage census for specific option ids of one property. jsonb `?` matches
+// both value shapes: array element for multi_select, string equality for
+// select. Only options with at least one referencing issue come back.
+func (q *Queries) CountIssuesUsingPropertyOptions(ctx context.Context, arg CountIssuesUsingPropertyOptionsParams) ([]CountIssuesUsingPropertyOptionsRow, error) {
+ rows, err := q.db.Query(ctx, countIssuesUsingPropertyOptions, arg.OptionIds, arg.WorkspaceID, arg.PropertyKey)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []CountIssuesUsingPropertyOptionsRow{}
+ for rows.Next() {
+ var i CountIssuesUsingPropertyOptionsRow
+ if err := rows.Scan(&i.OptionID, &i.UsageCount); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const createIssueProperty = `-- name: CreateIssueProperty :one
+INSERT INTO issue_property (workspace_id, name, type, description, config, position)
+SELECT $1::uuid,
+ $2::text,
+ $3::text,
+ $4::text,
+ $5::jsonb,
+ COALESCE((SELECT MAX(position) FROM issue_property WHERE workspace_id = $1::uuid), 0) + 1
+RETURNING id, workspace_id, name, type, description, config, position, archived_at, created_at, updated_at
+`
+
+type CreateIssuePropertyParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config []byte `json:"config"`
+}
+
+// New definitions append to the end of the catalog: position = max + 1.
+func (q *Queries) CreateIssueProperty(ctx context.Context, arg CreateIssuePropertyParams) (IssueProperty, error) {
+ row := q.db.QueryRow(ctx, createIssueProperty,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Type,
+ arg.Description,
+ arg.Config,
+ )
+ var i IssueProperty
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Type,
+ &i.Description,
+ &i.Config,
+ &i.Position,
+ &i.ArchivedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const deleteIssuePropertyValue = `-- name: DeleteIssuePropertyValue :one
+UPDATE issue
+SET properties = properties - $1::text,
+ updated_at = now()
+WHERE id = $2::uuid AND workspace_id = $3::uuid
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+`
+
+type DeleteIssuePropertyValueParams struct {
+ Key string `json:"key"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssuePropertyValueParams) (Issue, error) {
+ row := q.db.QueryRow(ctx, deleteIssuePropertyValue, arg.Key, arg.ID, arg.WorkspaceID)
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ )
+ return i, err
+}
+
+const getIssueProperty = `-- name: GetIssueProperty :one
+SELECT id, workspace_id, name, type, description, config, position, archived_at, created_at, updated_at FROM issue_property
+WHERE id = $1 AND workspace_id = $2
+`
+
+type GetIssuePropertyParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+func (q *Queries) GetIssueProperty(ctx context.Context, arg GetIssuePropertyParams) (IssueProperty, error) {
+ row := q.db.QueryRow(ctx, getIssueProperty, arg.ID, arg.WorkspaceID)
+ var i IssueProperty
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Type,
+ &i.Description,
+ &i.Config,
+ &i.Position,
+ &i.ArchivedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
+
+const listIssueProperties = `-- name: ListIssueProperties :many
+SELECT p.id, p.workspace_id, p.name, p.type, p.description, p.config, p.position, p.archived_at, p.created_at, p.updated_at,
+ (
+ SELECT COUNT(*) FROM issue i
+ WHERE i.workspace_id = p.workspace_id
+ AND i.properties ? p.id::text
+ )::bigint AS usage_count
+FROM issue_property p
+WHERE p.workspace_id = $1::uuid
+ AND ($2::bool OR p.archived_at IS NULL)
+ORDER BY p.position ASC, LOWER(p.name) ASC
+`
+
+type ListIssuePropertiesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IncludeArchived bool `json:"include_archived"`
+}
+
+type ListIssuePropertiesRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config []byte `json:"config"`
+ Position float64 `json:"position"`
+ ArchivedAt pgtype.Timestamptz `json:"archived_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ UsageCount int64 `json:"usage_count"`
+}
+
+// usage_count = number of issues in the workspace that currently carry a
+// value for this property. `properties ? id` is a seq scan today; fine at
+// the 20-definition / small-workspace scale this feature targets.
+func (q *Queries) ListIssueProperties(ctx context.Context, arg ListIssuePropertiesParams) ([]ListIssuePropertiesRow, error) {
+ rows, err := q.db.Query(ctx, listIssueProperties, arg.WorkspaceID, arg.IncludeArchived)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssuePropertiesRow{}
+ for rows.Next() {
+ var i ListIssuePropertiesRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Type,
+ &i.Description,
+ &i.Config,
+ &i.Position,
+ &i.ArchivedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.UsageCount,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const setIssuePropertyValue = `-- name: SetIssuePropertyValue :one
+UPDATE issue
+SET properties = jsonb_set(properties, ARRAY[$1::text], $2::jsonb, true),
+ updated_at = now()
+WHERE id = $3::uuid AND workspace_id = $4::uuid
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+`
+
+type SetIssuePropertyValueParams struct {
+ Key string `json:"key"`
+ Value []byte `json:"value"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Single-key atomic write (mirror of SetIssueMetadataKey): concurrent writers
+// on different property keys never clobber each other.
+func (q *Queries) SetIssuePropertyValue(ctx context.Context, arg SetIssuePropertyValueParams) (Issue, error) {
+ row := q.db.QueryRow(ctx, setIssuePropertyValue,
+ arg.Key,
+ arg.Value,
+ arg.ID,
+ arg.WorkspaceID,
+ )
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ )
+ return i, err
+}
+
+const updateIssueProperty = `-- name: UpdateIssueProperty :one
+UPDATE issue_property SET
+ name = COALESCE($3, name),
+ description = COALESCE($4, description),
+ config = COALESCE($5, config),
+ archived_at = CASE WHEN $6::bool THEN $7 ELSE archived_at END,
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING id, workspace_id, name, type, description, config, position, archived_at, created_at, updated_at
+`
+
+type UpdateIssuePropertyParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name pgtype.Text `json:"name"`
+ Description pgtype.Text `json:"description"`
+ Config []byte `json:"config"`
+ ArchivedSet bool `json:"archived_set"`
+ ArchivedAt pgtype.Timestamptz `json:"archived_at"`
+}
+
+// `type` is deliberately immutable — changing it would silently invalidate
+// existing values. archived_set/archived_at implement tri-state semantics:
+// archived_set=false leaves archived_at untouched.
+func (q *Queries) UpdateIssueProperty(ctx context.Context, arg UpdateIssuePropertyParams) (IssueProperty, error) {
+ row := q.db.QueryRow(ctx, updateIssueProperty,
+ arg.ID,
+ arg.WorkspaceID,
+ arg.Name,
+ arg.Description,
+ arg.Config,
+ arg.ArchivedSet,
+ arg.ArchivedAt,
+ )
+ var i IssueProperty
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.Type,
+ &i.Description,
+ &i.Config,
+ &i.Position,
+ &i.ArchivedAt,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ )
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index 73e9db07b2..92ac469620 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -577,6 +577,7 @@ type Issue struct {
StartDate pgtype.Date `json:"start_date"`
Metadata []byte `json:"metadata"`
Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
}
type IssueDependency struct {
@@ -597,6 +598,19 @@ type IssueLabel struct {
Description string `json:"description"`
}
+type IssueProperty struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ Description string `json:"description"`
+ Config []byte `json:"config"`
+ Position float64 `json:"position"`
+ ArchivedAt pgtype.Timestamptz `json:"archived_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type IssuePullRequest struct {
IssueID pgtype.UUID `json:"issue_id"`
PullRequestID pgtype.UUID `json:"pull_request_id"`
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 1ae6c1c4be..0d60346320 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -7,7 +7,7 @@
-- "Assigned to me"), and the two filters must produce disjoint result sets.
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
FROM issue i
WHERE i.workspace_id = $1
AND (sqlc.narg('status')::text IS NULL OR i.status = sqlc.narg('status'))
@@ -166,7 +166,7 @@ DELETE FROM issue WHERE id = $1 AND workspace_id = $2;
-- filter; member-direct assignment is intentionally excluded).
SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,
i.assignee_type, i.assignee_id, i.creator_type, i.creator_id,
- i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage
+ i.parent_issue_id, i.position, i.start_date, i.due_date, i.created_at, i.updated_at, i.number, i.project_id, i.metadata, i.stage, i.properties
FROM issue i
WHERE i.workspace_id = $1
AND i.status NOT IN ('done', 'cancelled')
@@ -176,6 +176,23 @@ WHERE i.workspace_id = $1
AND (sqlc.narg('creator_id')::uuid IS NULL OR i.creator_id = sqlc.narg('creator_id'))
AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))
AND (sqlc.narg('metadata_filter')::jsonb IS NULL OR i.metadata @> sqlc.narg('metadata_filter')::jsonb)
+ -- properties_filter is a jsonb array of groups, each group an array of
+ -- containment patterns (built by parsePropertiesFilterParam): the issue
+ -- must match at least one pattern from EVERY group (AND of ORs). The
+ -- correlated form skips the GIN index, which is fine here: open_only is
+ -- an unpaginated workspace scan already narrowed by status.
+ AND (
+ sqlc.narg('properties_filter')::jsonb IS NULL
+ OR NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(sqlc.narg('properties_filter')::jsonb) AS pf(alternatives)
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM jsonb_array_elements(pf.alternatives) AS alt(pattern)
+ WHERE i.properties @> alt.pattern
+ )
+ )
+ )
AND (
sqlc.narg('involves_user_id')::uuid IS NULL
OR (i.assignee_type = 'agent' AND i.assignee_id IN (
diff --git a/server/pkg/db/queries/issue_property.sql b/server/pkg/db/queries/issue_property.sql
new file mode 100644
index 0000000000..3f8bdb5a23
--- /dev/null
+++ b/server/pkg/db/queries/issue_property.sql
@@ -0,0 +1,74 @@
+-- name: ListIssueProperties :many
+-- usage_count = number of issues in the workspace that currently carry a
+-- value for this property. `properties ? id` is a seq scan today; fine at
+-- the 20-definition / small-workspace scale this feature targets.
+SELECT p.*,
+ (
+ SELECT COUNT(*) FROM issue i
+ WHERE i.workspace_id = p.workspace_id
+ AND i.properties ? p.id::text
+ )::bigint AS usage_count
+FROM issue_property p
+WHERE p.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND (sqlc.arg('include_archived')::bool OR p.archived_at IS NULL)
+ORDER BY p.position ASC, LOWER(p.name) ASC;
+
+-- name: GetIssueProperty :one
+SELECT * FROM issue_property
+WHERE id = $1 AND workspace_id = $2;
+
+-- name: CountActiveIssueProperties :one
+SELECT COUNT(*) FROM issue_property
+WHERE workspace_id = $1 AND archived_at IS NULL;
+
+-- name: CreateIssueProperty :one
+-- New definitions append to the end of the catalog: position = max + 1.
+INSERT INTO issue_property (workspace_id, name, type, description, config, position)
+SELECT sqlc.arg('workspace_id')::uuid,
+ sqlc.arg('name')::text,
+ sqlc.arg('type')::text,
+ sqlc.arg('description')::text,
+ sqlc.arg('config')::jsonb,
+ COALESCE((SELECT MAX(position) FROM issue_property WHERE workspace_id = sqlc.arg('workspace_id')::uuid), 0) + 1
+RETURNING *;
+
+-- name: UpdateIssueProperty :one
+-- `type` is deliberately immutable — changing it would silently invalidate
+-- existing values. archived_set/archived_at implement tri-state semantics:
+-- archived_set=false leaves archived_at untouched.
+UPDATE issue_property SET
+ name = COALESCE(sqlc.narg('name'), name),
+ description = COALESCE(sqlc.narg('description'), description),
+ config = COALESCE(sqlc.narg('config'), config),
+ archived_at = CASE WHEN sqlc.arg('archived_set')::bool THEN sqlc.narg('archived_at') ELSE archived_at END,
+ updated_at = now()
+WHERE id = $1 AND workspace_id = $2
+RETURNING *;
+
+-- name: SetIssuePropertyValue :one
+-- Single-key atomic write (mirror of SetIssueMetadataKey): concurrent writers
+-- on different property keys never clobber each other.
+UPDATE issue
+SET properties = jsonb_set(properties, ARRAY[sqlc.arg('key')::text], sqlc.arg('value')::jsonb, true),
+ updated_at = now()
+WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
+RETURNING *;
+
+-- name: DeleteIssuePropertyValue :one
+UPDATE issue
+SET properties = properties - sqlc.arg('key')::text,
+ updated_at = now()
+WHERE id = sqlc.arg('id')::uuid AND workspace_id = sqlc.arg('workspace_id')::uuid
+RETURNING *;
+
+-- name: CountIssuesUsingPropertyOptions :many
+-- Usage census for specific option ids of one property. jsonb `?` matches
+-- both value shapes: array element for multi_select, string equality for
+-- select. Only options with at least one referencing issue come back.
+SELECT opt::text AS option_id, COUNT(i.id) AS usage_count
+FROM unnest(sqlc.arg('option_ids')::text[]) AS opt
+LEFT JOIN issue i
+ ON i.workspace_id = sqlc.arg('workspace_id')::uuid
+ AND (i.properties -> sqlc.arg('property_key')::text) ? opt
+GROUP BY opt
+HAVING COUNT(i.id) > 0;
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 9cbf273c87..d6e0d8d2fc 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -95,6 +95,12 @@ const (
EventLabelDeleted = "label:deleted"
EventIssueLabelsChanged = "issue_labels:changed"
+ // Custom property events. Definitions are archived, never deleted, so
+ // there is no property:deleted — archive arrives as property:updated.
+ EventPropertyCreated = "property:created"
+ EventPropertyUpdated = "property:updated"
+ EventIssuePropertiesChanged = "issue_properties:changed"
+
// Pin events
EventPinCreated = "pin:created"
EventPinDeleted = "pin:deleted"