Skip to content

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

Go

MUL-7586 Atomically create issues with custom properties (#8689)

Multica Eve90e0bdf83043
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 5eac0b1ca9..a18d8dd128 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -547,6 +547,30 @@ function assertAgentConversationStartersWriteSupported(data: {
}
}
+function requestedIssueCreateProperties(
+ data: CreateIssueRequest,
+): NonNullable<CreateIssueRequest["properties"]> | undefined {
+ const properties = data.properties;
+ return properties && Object.keys(properties).length > 0 ? properties : undefined;
+}
+
+function assertIssueCreatePropertiesSnapshot(
+ requested: NonNullable<CreateIssueRequest["properties"]> | undefined,
+ issue: Issue,
+): void {
+ if (!requested) return;
+ for (const propertyId of Object.keys(requested)) {
+ // The server may canonicalize a valid request (trim a URL, order and
+ // de-duplicate a multi-select, normalize an actor UUID). Presence is the
+ // integrity signal here; IssueSchema has already validated the value type.
+ if (!Object.prototype.hasOwnProperty.call(issue.properties, propertyId)) {
+ throw new Error(
+ `Issue ${issue.identifier || issue.id} was created, but the server did not confirm its custom properties. Review the issue before retrying.`,
+ );
+ }
+ }
+}
+
// errorCode extracts the stable `code` a handler attaches to a failure
// (writeErrorCode), so a caller can render its own localized sentence instead
// of toasting the server's English one. Returns undefined for a non-ApiError,
@@ -1276,6 +1300,15 @@ export class ApiClient {
}
async createIssue(data: CreateIssueRequest): Promise<Issue> {
+ const requestedProperties = requestedIssueCreateProperties(data);
+ if (requestedProperties) {
+ const config = await this.getConfig();
+ if (config.issue_create_properties_supported !== true) {
+ throw new Error(
+ "This server version does not support atomic custom properties on issue creation. Update the server before creating this issue.",
+ );
+ }
+ }
// Parse through a schema (not a raw cast): the create modal keys its
// label-attach compatibility fallback off `labels` being absent vs a
// validated Label[], so an unvalidated wrong shape must not slip through.
@@ -1295,6 +1328,7 @@ export class ApiClient {
if (!issue) {
throw new Error();
}
+ assertIssueCreatePropertiesSnapshot(requestedProperties, issue);
return issue;
}
@@ -1339,6 +1373,16 @@ export class ApiClient {
data: CreateCommentSubIssueRequest,
): Promise<Issue | { task_id: string }> {
try {
+ const requestedProperties =
+ data.mode === "manual" ? requestedIssueCreateProperties(data.issue) : undefined;
+ if (requestedProperties) {
+ const config = await this.getConfig();
+ if (config.issue_create_properties_supported !== true) {
+ throw new Error(
+ "This server version does not support atomic custom properties on issue creation. Update the server before creating this issue.",
+ );
+ }
+ }
const raw = await this.fetch<unknown>(`/api/comments/${anchorCommentId}/sub-issues`, {
method: "POST",
body: JSON.stringify(data),
@@ -1348,6 +1392,7 @@ export class ApiClient {
endpoint: "POST /api/comments/:id/sub-issues (manual)",
});
if (!issue) throw new Error("Invalid sub-issue response");
+ assertIssueCreatePropertiesSnapshot(requestedProperties, issue);
return issue;
}
const task = parseWithFallback<{ task_id: string } | null>(
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 68abbf9e73..a6b31550b9 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -337,9 +337,136 @@ describe("ApiClient schema fallback", () => {
const client = new ApiClient("https://api.example.test");
await expect(client.createIssue({ title: "Created" })).rejects.toThrow();
});
+
+ it("fails closed before POST when create properties are unsupported", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({}), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(
+ client.createIssue({ title: "Created", properties: { "property-1": "value" } }),
+ ).rejects.toThrow("does not support atomic custom properties");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[0]).toBe("https://api.example.test/api/config");
+ expect(fetchMock.mock.calls.some(([, init]) => init?.method === "POST")).toBe(false);
+ });
+
+ it("preflights properties and requires the canonical response snapshot", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ issue_create_properties_supported: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ ...validIssue,
+ properties: { "property-1": ["first", "second"] },
+ }),
+ { status: 201, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(
+ client.createIssue({
+ title: "Created",
+ properties: { "property-1": ["second", "first", "second"] },
+ }),
+ ).resolves.toMatchObject({ properties: { "property-1": ["first", "second"] } });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ method: "POST" });
+ });
+
+ it("reports a created identifier when the response property snapshot mismatches", async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ issue_create_properties_supported: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify(validIssue), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(
+ client.createIssue({ title: "Created", properties: { "property-1": "value" } }),
+ ).rejects.toThrow("Issue MUL-1 was created");
+ });
});
describe("comment source-context sub-issues", () => {
+ it("preflights manual sub-issue properties and validates their snapshot", async () => {
+ const issue = {
+ id: "issue-2",
+ workspace_id: "ws-1",
+ number: 2,
+ identifier: "MUL-2",
+ title: "Child",
+ description: null,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "user-1",
+ parent_issue_id: "issue-1",
+ project_id: null,
+ position: 0,
+ stage: null,
+ start_date: null,
+ due_date: null,
+ metadata: {},
+ properties: { "property-1": true },
+ created_at: "2025-01-01T00:00:00Z",
+ updated_at: "2025-01-01T00:00:00Z",
+ };
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify({ issue_create_properties_supported: true }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(JSON.stringify(issue), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ await expect(
+ client.createCommentSubIssue("comment-1", {
+ mode: "manual",
+ capture_token: "token",
+ issue: { title: "Child", properties: { "property-1": true } },
+ }),
+ ).resolves.toMatchObject({ id: "issue-2" });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[1]?.[0]).toBe(
+ "https://api.example.test/api/comments/comment-1/sub-issues",
+ );
+ });
+
it("uses the dedicated endpoint for agent creation", async () => {
stubFetchJson({ task_id: "task-1" }, 202);
const client = new ApiClient("https://api.example.test");
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 62163e9954..23f4122407 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1280,6 +1280,26 @@ describe("AppConfigSchema agent_conversation_starters_supported drift", () => {
});
});
+describe("AppConfigSchema issue_create_properties_supported drift", () => {
+ it("defaults to false when the server predates atomic create properties", () => {
+ expect(AppConfigSchema.parse({}).issue_create_properties_supported).toBe(false);
+ });
+
+ it("coerces a malformed declaration to false", () => {
+ expect(
+ AppConfigSchema.parse({ issue_create_properties_supported: "yes" })
+ .issue_create_properties_supported,
+ ).toBe(false);
+ });
+
+ it("carries a genuine declaration through", () => {
+ expect(
+ AppConfigSchema.parse({ issue_create_properties_supported: true })
+ .issue_create_properties_supported,
+ ).toBe(true);
+ });
+});
+
describe("AppConfigSchema cdn_signed drift", () => {
it("defaults cdn_signed to false when the server omits it (pre-MUL-3254 servers)", () => {
const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 6edb9541a1..26afa7fdd1 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -756,6 +756,9 @@ export interface AppConfigResponse {
/** Whether agent create/update persists `conversation_starters`. Older servers
* silently ignored the unknown field, so absent must be treated as false. */
agent_conversation_starters_supported?: boolean;
+ /** Whether issue create atomically validates and persists `properties`.
+ * Older servers silently ignore the field, so absent means unsupported. */
+ issue_create_properties_supported?: boolean;
/** Whether deleting a comment keeps its replies and the server routes
* DELETE /api/comments/{id}/keep-replies. Older servers deleted the replies
* too, so absent must be treated as false (#8296). */
@@ -998,6 +1001,7 @@ export const AppConfigSchema = z.object({
feature_flags: FeatureFlagsSchema,
local_worktree_supported: BooleanWithDefaultSchema(false),
agent_conversation_starters_supported: BooleanWithDefaultSchema(false),
+ issue_create_properties_supported: BooleanWithDefaultSchema(false),
comment_delete_keep_replies_supported: BooleanWithDefaultSchema(false),
server_version: OptionalStringSchema,
}).loose();
@@ -1016,6 +1020,8 @@ export const EMPTY_APP_CONFIG: AppConfigResponse = {
local_worktree_supported: false,
// Fail closed: old servers returned success while dropping the field.
agent_conversation_starters_supported: false,
+ // Fail closed: old servers returned success while dropping create properties.
+ issue_create_properties_supported: false,
// Fail closed: old servers delete a comment's replies with it.
comment_delete_keep_replies_supported: false,
feature_flags: {},
diff --git a/packages/core/config/index.ts b/packages/core/config/index.ts
index 43ea146172..40d1208213 100644
--- a/packages/core/config/index.ts
+++ b/packages/core/config/index.ts
@@ -36,6 +36,9 @@ interface ConfigState {
// Older handlers accepted the unknown field and returned success while
// dropping it, so absent must fail closed.
agentConversationStartersSupported: boolean;
+ // Whether POST /api/issues atomically persists custom-property values.
+ // Older servers silently drop the field, so absent must fail closed.
+ issueCreatePropertiesSupported: boolean;
// Whether deleting a comment keeps its replies (#8296). Older servers
// deleted the replies too, so absent must fail closed: the client then
// promises nothing about replies and uses the legacy delete route.
@@ -55,6 +58,7 @@ interface ConfigState {
setServerVersion: (version?: string) => void;
setLocalWorktreeSupported: (supported?: boolean) => void;
setAgentConversationStartersSupported: (supported?: boolean) => void;
+ setIssueCreatePropertiesSupported: (supported?: boolean) => void;
setCommentDeleteKeepRepliesSupported: (supported?: boolean) => void;
}
@@ -71,6 +75,7 @@ export const configStore = createStore<ConfigState>((set) => ({
serverVersion: "",
localWorktreeSupported: false,
agentConversationStartersSupported: false,
+ issueCreatePropertiesSupported: false,
commentDeleteKeepRepliesSupported: false,
setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),
setAuthConfig: ({
@@ -87,6 +92,8 @@ export const configStore = createStore<ConfigState>((set) => ({
set({ localWorktreeSupported: supported === true }),
setAgentConversationStartersSupported: (supported = false) =>
set({ agentConversationStartersSupported: supported === true }),
+ setIssueCreatePropertiesSupported: (supported = false) =>
+ set({ issueCreatePropertiesSupported: supported === true }),
setCommentDeleteKeepRepliesSupported: (supported = false) =>
set({ commentDeleteKeepRepliesSupported: supported === true }),
}));
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 70d8c1014a..c768b2c8c1 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -94,6 +94,11 @@ export function AuthInitializer({
.setAgentConversationStartersSupported(
cfg.agent_conversation_starters_supported === true,
);
+ configStore
+ .getState()
+ .setIssueCreatePropertiesSupported(
+ cfg.issue_create_properties_supported === true,
+ );
// Older servers delete a comment's replies with it; promise nothing
// about replies unless the server declares otherwise.
configStore
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index a665265a0d..178a667c00 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -1,5 +1,5 @@
import type { Issue, IssueMetadata, IssueStatus, IssueStatusCategory, IssuePriority, IssueAssigneeType } from "./issue";
-import type { PropertyFilterValue } from "./property";
+import type { IssuePropertyValues, PropertyFilterValue } from "./property";
import type { MemberRole } from "./workspace";
import type { Project, ProjectStatus } from "./project";
@@ -21,6 +21,9 @@ export interface CreateIssueRequest {
/** Issue-scoped label IDs to attach in the same transaction as the create.
* Unknown or non-issue ids are rejected by the server with 400. */
label_ids?: string[];
+ /** ID-keyed custom-property values validated and persisted atomically with
+ * the issue. */
+ properties?: IssuePropertyValues;
}
export interface CreateCommentSubIssueManualRequest {
diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.json
index 022cd3e1b7..aa3384b5c6 100644
--- a/packages/views/locales/en/modals.json
+++ b/packages/views/locales/en/modals.json
@@ -186,6 +186,7 @@
"toast_link_subissues_partial": "Failed to link {{failed}} of {{total}} sub-issues",
"toast_link_labels_failed": "Failed to attach labels",
"toast_set_properties_failed": "Could not set {{count}} custom property values",
+ "unavailable_property_removed": "An unavailable custom property was removed from the draft. Review it before submitting again.",
"switch_to_agent": "Switch to Agent",
"switch_to_agent_tooltip": "Switch to create with agent — describe in one line and let the agent file it",
"switch_to_manual": "Switch to Manual",
diff --git a/packages/views/locales/fr/modals.json b/packages/views/locales/fr/modals.json
index 86963cd30d..b063b3f277 100644
--- a/packages/views/locales/fr/modals.json
+++ b/packages/views/locales/fr/modals.json
@@ -186,6 +186,7 @@
"toast_link_subissues_partial": "Échec de la liaison de {{failed}} sous-tâches sur {{total}}",
"toast_link_labels_failed": "Échec du rattachement des étiquettes",
"toast_set_properties_failed": "Impossible de définir {{count}} valeurs de propriétés personnalisées",
+ "unavailable_property_removed": "Une propriété personnalisée qui n’est plus disponible a été retirée du brouillon. Vérifiez-le avant de le soumettre à nouveau.",
"switch_to_agent": "Passer en mode agent",
"switch_to_agent_tooltip": "Passer à la création avec un agent — décrivez en une ligne et laissez l'agent rédiger la tâche",
"switch_to_manual": "Passer en mode manuel",
diff --git a/packages/views/locales/ja/modals.json b/packages/views/locales/ja/modals.json
index 5e25d98aee..df4f13ef19 100644
--- a/packages/views/locales/ja/modals.json
+++ b/packages/views/locales/ja/modals.json
@@ -184,6 +184,7 @@
"toast_link_subissues_partial": "サブタスク {{total}} 件中 {{failed}} 件をリンクできませんでした",
"toast_link_labels_failed": "ラベルを付けられませんでした",
"toast_set_properties_failed": "{{count}} 件のカスタムプロパティを設定できませんでした",
+ "unavailable_property_removed": "利用できなくなったカスタムプロパティを下書きから削除しました。内容を確認してから再度送信してください。",
"switch_to_agent": "エージェントに切り替え",
"switch_to_agent_tooltip": "エージェントで作成に切り替えます。一行で説明すれば、エージェントがタスクを作成します",
"switch_to_manual": "手動に切り替え",
diff --git a/packages/views/locales/ko/modals.json b/packages/views/locales/ko/modals.json
index a53e2957dd..f90b53fd4e 100644
--- a/packages/views/locales/ko/modals.json
+++ b/packages/views/locales/ko/modals.json
@@ -184,6 +184,7 @@
"toast_link_subissues_partial": "하위 태스크 {{total}}개 중 {{failed}}개를 연결하지 못했습니다",
"toast_link_labels_failed": "라벨을 연결하지 못했습니다",
"toast_set_properties_failed": "사용자 지정 속성 값 {{count}}개를 설정하지 못했습니다",
+ "unavailable_property_removed": "더 이상 사용할 수 없는 사용자 지정 속성이 초안에서 제거되었습니다. 내용을 확인한 후 다시 제출해 주세요.",
"switch_to_agent": "에이전트로 전환",
"switch_to_agent_tooltip": "에이전트로 만들기로 전환합니다. 한 줄로 설명하면 에이전트가 태스크를 작성합니다.",
"switch_to_manual": "직접 만들기로 전환",
diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.json
index 804c1238d1..25ec2f9283 100644
--- a/packages/views/locales/zh-Hans/modals.json
+++ b/packages/views/locales/zh-Hans/modals.json
@@ -184,6 +184,7 @@
"toast_link_subissues_partial": "{{total}} 个子任务中有 {{failed}} 个关联失败",
"toast_link_labels_failed": "关联标签失败",
"toast_set_properties_failed": "有 {{count}} 个自定义属性设置失败",
+ "unavailable_property_removed": "一个已不可用的自定义属性已从草稿移除,请确认后重新提交。",
"switch_to_agent": "切换到智能体",
"switch_to_agent_tooltip": "切换到通过智能体创建——一句话描述,让它替你建",
"switch_to_manual": "切换到手动",
diff --git a/packages/views/modals/create-issue.test.tsx b/packages/views/modals/create-issue.test.tsx
index 002e282e62..0f5de7f878 100644
--- a/packages/views/modals/create-issue.test.tsx
+++ b/packages/views/modals/create-issue.test.tsx
@@ -7,7 +7,7 @@ import {
type ReactElement,
type ReactNode,
} from "react";
-import { describe, it, expect, vi, beforeEach } from "vitest";
+import { describe, it, expect, vi, beforeEach, onTestFinished } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
@@ -474,10 +474,11 @@ vi.mock("../issues/components", () => ({
}));
vi.mock("../issues/components/pickers/custom-property-picker", () => ({
- CustomPropertyValueInput: ({ property, onChange }: any) => (
+ CustomPropertyValueInput: ({ property, onChange, open }: any) => (
<button
type="button"
aria-label={`Edit ${property.name}`}
+ data-open={open ? "true" : "false"}
onClick={() => onChange("option-enterprise")}
>
{property.name}
@@ -874,7 +875,7 @@ describe("CreateIssueModal", () => {
});
});
- it("sets configured custom property values after the issue is created", async () => {
+ it("includes configured custom properties in the atomic create request", async () => {
const user = userEvent.setup();
renderModal(<CreateIssueModal onClose={vi.fn()} />);
@@ -885,14 +886,260 @@ describe("CreateIssueModal", () => {
await user.type(screen.getByPlaceholderText("Issue title"), "Enterprise follow-up");
await user.click(screen.getByRole("button", { name: "Create Issue" }));
- await waitFor(() => {
- expect(mockSetIssueProperty).toHaveBeenCalledWith(
- "issue-123",
- "property-tier",
- "option-enterprise",
+ await waitFor(() => expect(mockCreateIssue).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Enterprise follow-up",
+ properties: { "property-tier": "option-enterprise" },
+ }),
+ ));
+ expect(mockSetIssueProperty).not.toHaveBeenCalled();
+ expect(mockClearDraft).toHaveBeenCalled();
+ });
+
+ it("keeps the draft open and highlights the rejected custom property", async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ mockDraftStore.draft.manual.propertyValues = {
+ "property-tier": "option-enterprise",
+ };
+ mockCreateIssue.mockRejectedValueOnce(
+ new ApiError("Customer tier is invalid", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: "property-tier",
+ error: "Customer tier is invalid",
+ }),
+ );
+
+ renderModal(<CreateIssueModal onClose={onClose} />);
+ await user.type(screen.getByPlaceholderText("Issue title"), "Keep this draft");
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("Customer tier is invalid"));
+ expect(onClose).not.toHaveBeenCalled();
+ expect(mockClearDraft).not.toHaveBeenCalled();
+ expect(screen.getByPlaceholderText("Issue title")).toHaveValue("Keep this draft");
+ expect(document.querySelector('[data-property-error="true"]')).not.toBeNull();
+ expect(screen.getByRole("button", { name: "Edit Customer tier" })).toHaveAttribute(
+ "data-open",
+ "true",
+ );
+ expect(mockDraftStore.draft.manual.propertyValues).toEqual({
+ "property-tier": "option-enterprise",
+ });
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(mockSetManual).not.toHaveBeenCalledWith(
+ expect.objectContaining({ propertyValues: expect.anything() }),
+ );
+ expect(mockSetIssueProperty).not.toHaveBeenCalled();
+ });
+
+ it.each(["ordinary", "comment-source"] as const)(
+ "removes only the rejected unavailable property from the %s draft before a manual retry",
+ async (path) => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+ mockDraftStore.draft.manual = {
+ ...mockDraftStore.draft.manual,
+ title: "Keep this draft",
+ description: "Keep this body",
+ assigneeType: "member",
+ assigneeId: "user-1",
+ propertyValues: {
+ "property-stale": "old value",
+ "property-tier": "option-enterprise",
+ },
+ };
+ mockDraftStore.draft.shared.priority = "high";
+ const originalDraft = structuredClone(mockDraftStore.draft);
+ if (path === "ordinary") {
+ // Forward the modal's draft writes to the real persisted store, so
+ // this regression also checks the workspace storage boundary.
+ const { useIssueDraftStore: persistedStore } = await vi.importActual<
+ typeof import("@multica/core/issues/stores/draft-store")
+ >("@multica/core/issues/stores/draft-store");
+ const { setCurrentWorkspace } = await import("@multica/core/platform");
+ setCurrentWorkspace("property-recovery", "ws-test");
+ onTestFinished(() => {
+ setCurrentWorkspace(null, null);
+ localStorage.removeItem("multica_issue_draft:property-recovery");
+ });
+ await Promise.resolve();
+ persistedStore.setState({
+ draft: { ...structuredClone(originalDraft), shared: { ...originalDraft.shared, attachments: [] } },
+ isolatedDraftBackup: undefined,
+ });
+ mockSetManual.mockImplementation((patch: Partial<typeof mockDraftStore.draft.manual>) => {
+ persistedStore.getState().setManual(patch);
+ mockDraftStore.draft.manual = { ...mockDraftStore.draft.manual, ...patch };
+ });
+ }
+ const create = path === "ordinary" ? mockCreateIssue : mockCreateCommentSubIssue;
+ create.mockRejectedValueOnce(
+ new ApiError("Property is unavailable", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: "property-stale",
+ }),
+ );
+ const panel = (
+ <ManualCreatePanel
+ data={path === "comment-source" ? sourceContextPanelData() : undefined}
+ onClose={onClose}
+ onSwitchMode={vi.fn()}
+ isExpanded={false}
+ setIsExpanded={vi.fn()}
+ />
);
+ const view = renderModal(panel);
+ await screen.findByRole("button", { name: "Edit Customer tier" });
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "An unavailable custom property was removed from the draft. Review it before submitting again.",
+ );
+ const submittedIssue = (index: number) => path === "ordinary"
+ ? create.mock.calls[index]?.[0]
+ : create.mock.calls[index]?.[1].issue;
+ // Nothing is filtered before the server identifies the invalid field.
+ expect(submittedIssue(0).properties).toEqual(originalDraft.manual.propertyValues);
+ expect(create).toHaveBeenCalledTimes(1);
+ expect(onClose).not.toHaveBeenCalled();
+ expect(mockClearDraft).not.toHaveBeenCalled();
+ expect(mockToastError).not.toHaveBeenCalled();
+ expect(screen.getByPlaceholderText("Issue title")).toHaveValue("Keep this draft");
+ expect(screen.getByPlaceholderText("Add description...")).toHaveValue("Keep this body");
+ const remainingProperties = { "property-tier": "option-enterprise" };
+ expect(mockSetManual).toHaveBeenCalledWith({ propertyValues: remainingProperties });
+ expect(mockDraftStore.draft).toEqual({
+ ...originalDraft,
+ manual: { ...originalDraft.manual, propertyValues: remainingProperties },
+ });
+ if (path === "ordinary") {
+ const persisted = JSON.parse(localStorage.getItem("multica_issue_draft:property-recovery")!);
+ expect(persisted.state.draft).toEqual(mockDraftStore.draft);
+ }
+
+ // A user-initiated retry reads the updated local selection, not the
+ // rejected payload. Keep this retry open so reopening can check the store.
+ create.mockRejectedValueOnce(new Error("Try again later"));
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));
+ expect(submittedIssue(1)).toMatchObject({
+ title: "Keep this draft",
+ description: "Keep this body",
+ assignee_type: "member",
+ assignee_id: "user-1",
+ status: "todo",
+ priority: "high",
+ properties: remainingProperties,
+ });
+ view.unmount();
+ renderModal(panel);
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(3));
+ expect(submittedIssue(2).properties).toEqual(remainingProperties);
+ expect(mockSetIssueProperty).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([undefined, "", 42, "property-not-submitted", "toString"])(
+ "does not change the draft for an unlocatable property error (%s)",
+ async (propertyId) => {
+ const user = userEvent.setup();
+ mockDraftStore.draft.manual.title = "Keep this draft";
+ mockDraftStore.draft.manual.propertyValues = { "property-stale": "old value" };
+ const originalDraft = structuredClone(mockDraftStore.draft);
+ mockCreateIssue.mockRejectedValueOnce(
+ new ApiError("Invalid property", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: propertyId,
+ }),
+ );
+ renderModal(<CreateIssueModal onClose={vi.fn()} />);
+ await screen.findByText("Customer tier");
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("Invalid property"));
+ expect(mockDraftStore.draft).toEqual(originalDraft);
+ expect(mockSetManual).not.toHaveBeenCalledWith(
+ expect.objectContaining({ propertyValues: expect.anything() }),
+ );
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ expect(document.querySelector('[data-property-error="true"]')).toBeNull();
+ },
+ );
+
+ it("does not treat an unloaded property catalog as an unavailable property", async () => {
+ const user = userEvent.setup();
+ mockDraftStore.draft.manual.title = "Keep this draft";
+ mockDraftStore.draft.manual.propertyValues = { "property-tier": "option-enterprise" };
+ mockListProperties.mockReturnValueOnce(new Promise(() => {}));
+ mockCreateIssue.mockRejectedValueOnce(
+ new ApiError("Invalid property", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: "property-tier",
+ }),
+ );
+ renderModal(<CreateIssueModal onClose={vi.fn()} />);
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith("Invalid property"));
+ expect(mockDraftStore.draft.manual.propertyValues).toEqual({ "property-tier": "option-enterprise" });
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
+ it("preserves edits made while the unavailable-property error is pending", async () => {
+ const user = userEvent.setup();
+ mockDraftStore.draft.manual.title = "Draft before submit";
+ mockDraftStore.draft.manual.propertyValues = {
+ "property-stale": "old value",
+ "property-tier": "option-old",
+ };
+ let rejectCreate!: (error: Error) => void;
+ mockCreateIssue.mockImplementationOnce(() => new Promise((_, reject) => { rejectCreate = reject; }));
+ renderModal(<CreateIssueModal onClose={vi.fn()} />);
+ await screen.findByRole("button", { name: "Edit Customer tier" });
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+ await user.type(screen.getByPlaceholderText("Issue title"), " with new edits");
+ await user.click(screen.getByRole("button", { name: "Edit Customer tier" }));
+ await act(async () => {
+ rejectCreate(new ApiError("Property is unavailable", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: "property-stale",
+ }));
});
- expect(mockClearDraft).toHaveBeenCalled();
+
+ expect(await screen.findByRole("alert")).toBeInTheDocument();
+ expect(mockDraftStore.draft.manual.title).toBe("Draft before submit with new edits");
+ expect(mockDraftStore.draft.manual.propertyValues).toEqual({ "property-tier": "option-enterprise" });
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+ expect(mockCreateIssue).toHaveBeenNthCalledWith(2, expect.objectContaining({
+ title: "Draft before submit with new edits",
+ properties: { "property-tier": "option-enterprise" },
+ }));
+ });
+
+ it("does not remove a property from a reopened draft after a late rejection", async () => {
+ const user = userEvent.setup();
+ mockDraftStore.draft.manual.title = "Draft before submit";
+ mockDraftStore.draft.manual.propertyValues = { "property-stale": "old value" };
+ let rejectCreate!: (error: Error) => void;
+ mockCreateIssue.mockImplementationOnce(() => new Promise((_, reject) => { rejectCreate = reject; }));
+ const view = renderModal(<CreateIssueModal onClose={vi.fn()} />);
+ await screen.findByText("Customer tier");
+ await user.click(screen.getByRole("button", { name: "Create Issue" }));
+ view.unmount();
+ mockDraftStore.draft.manual.title = "Reopened draft";
+ const reopenedDraft = structuredClone(mockDraftStore.draft);
+ renderModal(<CreateIssueModal onClose={vi.fn()} />);
+ await act(async () => {
+ rejectCreate(new ApiError("Property is unavailable", 400, "Bad Request", {
+ code: "invalid_issue_property",
+ property_id: "property-stale",
+ }));
+ });
+
+ expect(mockDraftStore.draft).toEqual(reopenedDraft);
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("persists manual-mode uploads in the issue draft", async () => {
@@ -1352,6 +1599,9 @@ describe("CreateIssueModal", () => {
it("submits source-context manual create through the dedicated endpoint", async () => {
const user = userEvent.setup();
+ mockDraftStore.draft.manual.propertyValues = {
+ "property-tier": "option-enterprise",
+ };
renderModal(
<ManualCreatePanel
onClose={vi.fn()}
@@ -1370,10 +1620,14 @@ describe("CreateIssueModal", () => {
{
mode: "manual",
capture_token: "sha256:preview-token",
- issue: expect.objectContaining({ title: "Create from source comment" }),
+ issue: expect.objectContaining({
+ title: "Create from source comment",
+ properties: { "property-tier": "option-enterprise" },
+ }),
},
));
expect(mockCreateIssue).not.toHaveBeenCalled();
+ expect(mockSetIssueProperty).not.toHaveBeenCalled();
});
// Start date is a low-frequency field — by default it lives behind the
diff --git a/packages/views/modals/create-issue.tsx b/packages/views/modals/create-issue.tsx
index eafcb2d167..7260bd1628 100644
--- a/packages/views/modals/create-issue.tsx
+++ b/packages/views/modals/create-issue.tsx
@@ -2,7 +2,7 @@
import { issueStatusCategory } from "@multica/core/issues";
import { useState, useRef, useEffect, useLayoutEffect } from "react";
-import { useQuery } from "@tanstack/react-query";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
import { AppLink, resolveClickIntent, useNavigation } from "../navigation";
import {
AlertTriangle,
@@ -77,10 +77,7 @@ import {
useUpdateIssue,
} from "@multica/core/issues/mutations";
import { useAttachLabelToIssue } from "@multica/core/labels";
-import {
- propertyListOptions,
- useSetIssueProperty,
-} from "@multica/core/properties";
+import { propertyListOptions } from "@multica/core/properties";
import {
ApiError,
DuplicateIssueErrorBodySchema,
@@ -279,6 +276,8 @@ export function ManualCreatePanel({
const [labelIds, setLabelIds] = useState<string[]>(draft.manual.labelIds);
const [propertyValues, setPropertyValues] = useState(draft.manual.propertyValues ?? {});
const [customPropertyPickerId, setCustomPropertyPickerId] = useState<string | null>(null);
+ const [propertyErrorId, setPropertyErrorId] = useState<string | null>(null);
+ const [unavailablePropertyRemoved, setUnavailablePropertyRemoved] = useState(false);
const [projectId, setProjectId] = useState<string | undefined>(() => {
if (data && "project_id" in data) {
return (data.project_id as string | null) ?? undefined;
@@ -322,6 +321,7 @@ export function ManualCreatePanel({
// Fetch parent issue details for the chip (status/identifier/title).
// List cache usually has it already, so this resolves synchronously.
const wsId = useWorkspaceId();
+ const queryClient = useQueryClient();
const { categoryOf: draftStatusCategory, colorOf, iconOf } = useIssueStatuses(wsId);
const { data: workspaceProperties = [] } = useQuery(propertyListOptions(wsId));
const { data: parentIssue } = useQuery({
@@ -395,6 +395,7 @@ export function ManualCreatePanel({
else next[propertyId] = value;
setPropertyValues(next);
setManual({ propertyValues: next });
+ if (propertyErrorId === propertyId) setPropertyErrorId(null);
};
// Inline pill reveal per toolbar field: kept by Settings → Preferences → Issue creation, holding a
@@ -415,7 +416,6 @@ export function ManualCreatePanel({
const createCommentSubIssueMutation = useCreateCommentSubIssue();
const updateIssueMutation = useUpdateIssue();
const attachLabelMutation = useAttachLabelToIssue();
- const setIssuePropertyMutation = useSetIssueProperty();
const resetForNextIssue = () => {
setTitle("");
setStatus("todo");
@@ -425,6 +425,8 @@ export function ManualCreatePanel({
setLabelIds([]);
setPropertyValues({});
setCustomPropertyPickerId(null);
+ setPropertyErrorId(null);
+ setUnavailablePropertyRemoved(false);
setProjectId(undefined);
setParentIssueId(undefined);
setStage(null);
@@ -475,6 +477,7 @@ export function ManualCreatePanel({
uploadGate: gate,
normalize: () => title.trim(),
onSubmit: async (): Promise<boolean> => {
+ setUnavailablePropertyRemoved(false);
// Flush the description editor's pending debounce into the store BEFORE
// snapshotting, so a late flush of pre-submit typing cannot masquerade
// as an edit made during the request.
@@ -504,6 +507,7 @@ export function ManualCreatePanel({
due_date: dueDate || undefined,
attachment_ids: activeAttachmentIds.length > 0 ? activeAttachmentIds : undefined,
label_ids: labelIds.length > 0 ? labelIds : undefined,
+ ...(Object.keys(propertyValues).length > 0 ? { properties: propertyValues } : {}),
stage: parentIssueId && stage != null ? stage : undefined,
project_id: projectId,
},
@@ -526,6 +530,7 @@ export function ManualCreatePanel({
// backend that predates this ignores the field — handled by the
// compatibility fallback below.
label_ids: labelIds.length > 0 ? labelIds : undefined,
+ ...(Object.keys(propertyValues).length > 0 ? { properties: propertyValues } : {}),
parent_issue_id: parentIssueId,
// Stage is only meaningful for a sub-issue (relative to its siblings).
stage: parentIssueId && stage != null ? stage : undefined,
@@ -533,34 +538,6 @@ export function ManualCreatePanel({
});
}
- // Custom-property values can only be addressed once the issue has an
- // id. Keep the modal in its submitting state until every value settles
- // so closing or "Create another" cannot race the fan-out.
- const propertyEntries = Object.entries(propertyValues);
- if (propertyEntries.length > 0) {
- const results = await Promise.allSettled(
- propertyEntries.map(([propertyId, value]) =>
- setIssuePropertyMutation.mutateAsync({
- issueId: issue.id,
- propertyId,
- value,
- }),
- ),
- );
- let failed = 0;
- for (const result of results) {
- if (result.status === "rejected") {
- failed += 1;
- console.error("[create-issue] custom property set failed", result.reason);
- }
- }
- if (failed > 0) {
- toast.error(
- t(($) => $.create_issue.toast_set_properties_failed, { count: failed }),
- );
- }
- }
-
// Link queued children to the new parent. Deferred to after create
// because the new issue's ID doesn't exist yet. Partial failures don't
// roll back the new issue — it's already committed.
@@ -685,6 +662,47 @@ export function ManualCreatePanel({
showIssueLimitUpgradePrompt();
return false;
}
+ if (sourceCode === "invalid_issue_property" && err instanceof ApiError) {
+ const propertyId =
+ err.body && typeof err.body === "object"
+ ? (err.body as { property_id?: unknown }).property_id
+ : undefined;
+ if (
+ mountedRef.current &&
+ typeof propertyId === "string" &&
+ Object.prototype.hasOwnProperty.call(propertyValues, propertyId)
+ ) {
+ // Read the current catalog, not the submit-time snapshot. An
+ // unloaded catalog is not evidence that a property is unavailable.
+ const availableProperties = queryClient.getQueryData(
+ propertyListOptions(wsId).queryKey,
+ )?.properties;
+ if (availableProperties?.some((property) => property.id === propertyId)) {
+ setPropertyErrorId(propertyId);
+ setCustomPropertyPickerId(propertyId);
+ } else if (availableProperties) {
+ const currentValues = useIssueDraftStore.getState().draft.manual.propertyValues ?? {};
+ if (Object.prototype.hasOwnProperty.call(currentValues, propertyId)) {
+ // Preserve edits made while the request was pending in both the
+ // local selection and the workspace-persisted draft.
+ setPropertyValues((current) => {
+ const next = { ...current };
+ delete next[propertyId];
+ return next;
+ });
+ const next = { ...currentValues };
+ delete next[propertyId];
+ setManual({ propertyValues: next });
+ setPropertyErrorId(null);
+ setCustomPropertyPickerId(null);
+ setUnavailablePropertyRemoved(true);
+ return false;
+ }
+ }
+ }
+ toast.error(err.message || t(($) => $.create_issue.toast_failed));
+ return false;
+ }
// Duplicate-issue is the only structured 409 the create endpoint
// returns. We schema-guard the body (ApiError.body is `unknown`) so a
// future server-side rename / drop of `code` / `issue` degrades to the
@@ -1106,28 +1124,36 @@ export function ManualCreatePanel({
.map((property) => {
const value = propertyValues[property.id];
return (
- <CustomPropertyValueInput
+ <div
key={property.id}
- property={property}
- value={value}
- onChange={(next) => updatePropertyValue(property.id, next)}
- open={customPropertyPickerId === property.id}
- onOpenChange={(open) =>
- setCustomPropertyPickerId(open ? property.id : null)
- }
- triggerRender={<PillButton />}
- trigger={
- <>
- <PropertyIcon property={property} className="size-3.5 text-caption" />
- <span className="max-w-32 truncate">{property.name}</span>
- {value !== undefined && (
- <span className="max-w-40 truncate text-muted-foreground">
- <CustomPropertyValueDisplay property={property} value={value} />
- </span>
- )}
- </>
- }
- />
+ data-property-error={propertyErrorId === property.id || undefined}
+ className={cn(
+ propertyErrorId === property.id &&
+ "rounded-full ring-2 ring-destructive",
+ )}
+ >
+ <CustomPropertyValueInput
+ property={property}
+ value={value}
+ onChange={(next) => updatePropertyValue(property.id, next)}
+ open={customPropertyPickerId === property.id}
+ onOpenChange={(open) =>
+ setCustomPropertyPickerId(open ? property.id : null)
+ }
+ triggerRender={<PillButton />}
+ trigger={
+ <>
+ <PropertyIcon property={property} className="size-3.5 text-caption" />
+ <span className="max-w-32 truncate">{property.name}</span>
+ {value !== undefined && (
+ <span className="max-w-40 truncate text-muted-foreground">
+ <CustomPropertyValueDisplay property={property} value={value} />
+ </span>
+ )}
+ </>
+ }
+ />
+ </div>
);
})}
@@ -1334,6 +1360,12 @@ export function ManualCreatePanel({
</DropdownMenu>
</div>
+ {unavailablePropertyRemoved && (
+ <p role="alert" className="px-5 pb-3 text-caption text-destructive">
+ {t(($) => $.create_issue.unavailable_property_removed)}
+ </p>
+ )}
+
{/* Parent / child pickers — rendered inline so they stack over this
modal instead of replacing it via useModalStore. */}
<IssuePickerModal
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 3fc152baec..b0448241f3 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -10,6 +10,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "reflect"
"regexp"
"sort"
"strconv"
@@ -627,6 +628,7 @@ func init() {
issueCreateCmd.Flags().String("output", "json", "Output format: table or json")
issueCreateCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times)")
issueCreateCmd.Flags().StringSlice("attachment-id", nil, "Existing attachment UUID(s) to bind to the created issue (can be specified multiple times)")
+ issueCreateCmd.Flags().StringArray("property", nil, `Set a custom property atomically with creation as "Name=Value" (repeatable, one distinct property per flag). Multi-value properties use comma-separated values inside one flag. Property and option/member names are case-insensitive; UUIDs are accepted. Filter-only __none__, >=, <=, and != forms are rejected.`)
// issue update
issueUpdateCmd.Flags().String("title", "", "New title")
@@ -1396,6 +1398,24 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
defer cancel()
body := map[string]any{"title": title}
+ propertyFlags, _ := cmd.Flags().GetStringArray("property")
+ var createProperties map[string]json.RawMessage
+ if len(propertyFlags) > 0 {
+ var config struct {
+ IssueCreatePropertiesSupported bool `json:"issue_create_properties_supported"`
+ }
+ if err := client.GetJSON(ctx, "/api/config", &config); err != nil {
+ return fmt.Errorf("check issue-create property support: %w", err)
+ }
+ if !config.IssueCreatePropertiesSupported {
+ return errors.New("this server version does not support atomic custom properties on issue creation; update the server before using --property")
+ }
+ createProperties, err = buildIssueCreateProperties(ctx, client, propertyFlags)
+ if err != nil {
+ return err
+ }
+ body["properties"] = createProperties
+ }
desc, hasDesc, err := resolveTextFlag(cmd, "description")
if err != nil {
return err
@@ -1491,6 +1511,9 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
}
return fmt.Errorf("create issue: %w", err)
}
+ if err := verifyIssueCreateProperties(createProperties, result); err != nil {
+ return fmt.Errorf("issue %s was created, but the server did not confirm its custom properties; review it before retrying: %w", issueDisplayKey(result), err)
+ }
// Upload attachments and link them to the newly created issue.
// Failures here are partial-success: the issue exists already, so
@@ -1522,6 +1545,30 @@ func runIssueCreate(cmd *cobra.Command, _ []string) error {
return cli.PrintJSON(os.Stdout, result)
}
+func verifyIssueCreateProperties(expected map[string]json.RawMessage, issue map[string]any) error {
+ if len(expected) == 0 {
+ return nil
+ }
+ bag, ok := issue["properties"].(map[string]any)
+ if !ok {
+ return errors.New("response omitted the properties snapshot")
+ }
+ for propertyID, encoded := range expected {
+ actual, exists := bag[propertyID]
+ if !exists {
+ return fmt.Errorf("response omitted property %s", propertyID)
+ }
+ var want any
+ if err := json.Unmarshal(encoded, &want); err != nil {
+ return fmt.Errorf("decode expected property %s: %w", propertyID, err)
+ }
+ if !reflect.DeepEqual(actual, want) {
+ return fmt.Errorf("response property %s does not match the canonical value", propertyID)
+ }
+ }
+ return nil
+}
+
func activeDuplicateIssueCreateMessage(err error) (string, bool) {
var httpErr *cli.HTTPError
if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusConflict {
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 5464645c15..80d2ad4b9c 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -10,12 +10,14 @@ import (
"net/url"
"os"
"path/filepath"
+ "reflect"
"slices"
"strconv"
"strings"
"testing"
"time"
+ "github.com/google/uuid"
"github.com/spf13/cobra"
"github.com/multica-ai/multica/server/internal/cli"
@@ -844,9 +846,149 @@ func newIssueCreateTestCmd() *cobra.Command {
cmd.Flags().String("output", "json", "")
cmd.Flags().StringSlice("attachment", nil, "")
cmd.Flags().StringSlice("attachment-id", nil, "")
+ cmd.Flags().StringArray("property", nil, "")
return cmd
}
+func TestRunIssueCreatePropertiesFailClosedBeforePost(t *testing.T) {
+ t.Chdir(t.TempDir())
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/config":
+ json.NewEncoder(w).Encode(map[string]any{})
+ case "/api/issues":
+ posts++
+ w.WriteHeader(http.StatusCreated)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ cmd := newIssueCreateTestCmd()
+ _ = cmd.Flags().Set("title", "Must stay atomic")
+ _ = cmd.Flags().Set("property", "Owner=Alice")
+ err := runIssueCreate(cmd, nil)
+ if err == nil || !strings.Contains(err.Error(), "does not support atomic custom properties") {
+ t.Fatalf("error = %v, want capability failure", err)
+ }
+ if posts != 0 {
+ t.Fatalf("old server received %d create POST(s), want zero", posts)
+ }
+}
+
+func TestRunIssueCreateSendsCanonicalIDKeyedProperties(t *testing.T) {
+ t.Chdir(t.TempDir())
+ textID := uuid.NewString()
+ multiID := uuid.NewString()
+ firstID := uuid.NewString()
+ secondID := uuid.NewString()
+ var createBody map[string]any
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/config":
+ json.NewEncoder(w).Encode(map[string]any{"issue_create_properties_supported": true})
+ case "/api/properties":
+ json.NewEncoder(w).Encode(map[string]any{"properties": []map[string]any{
+ {"id": textID, "name": "Summary", "type": "text", "config": map[string]any{}, "archived": false},
+ {"id": multiID, "name": "Platforms", "type": "multi_select", "config": map[string]any{"options": []map[string]any{
+ {"id": firstID, "name": "One"}, {"id": secondID, "name": "Two"},
+ }}, "archived": false},
+ }})
+ case "/api/issues":
+ posts++
+ if err := json.NewDecoder(r.Body).Decode(&createBody); err != nil {
+ t.Errorf("decode create body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": "issue-1", "identifier": "MUL-1", "title": "With properties",
+ "status": "todo", "priority": "none", "properties": createBody["properties"],
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ cmd := newIssueCreateTestCmd()
+ _ = cmd.Flags().Set("title", "With properties")
+ _ = cmd.Flags().Set("property", "Summary= exact text ")
+ _ = cmd.Flags().Set("property", "Platforms=Two,One,Two")
+ if err := runIssueCreate(cmd, nil); err != nil {
+ t.Fatalf("runIssueCreate: %v", err)
+ }
+ if posts != 1 {
+ t.Fatalf("create POST count = %d, want 1", posts)
+ }
+ properties, ok := createBody["properties"].(map[string]any)
+ if !ok {
+ t.Fatalf("properties body = %#v", createBody["properties"])
+ }
+ if properties[textID] != " exact text " {
+ t.Fatalf("text property = %#v", properties[textID])
+ }
+ if got := properties[multiID]; !reflect.DeepEqual(got, []any{firstID, secondID}) {
+ t.Fatalf("multi property = %#v, want config-order dedupe", got)
+ }
+}
+
+func TestRunIssueCreateRejectsDuplicateAndFilterPropertySyntaxBeforePost(t *testing.T) {
+ t.Chdir(t.TempDir())
+ propertyID := uuid.NewString()
+ posts := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/config":
+ json.NewEncoder(w).Encode(map[string]any{"issue_create_properties_supported": true})
+ case "/api/properties":
+ json.NewEncoder(w).Encode(map[string]any{"properties": []map[string]any{{
+ "id": propertyID, "name": "Owner", "type": "text", "config": map[string]any{}, "archived": false,
+ }}})
+ case "/api/issues":
+ posts++
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "mat_test-token")
+
+ for _, test := range []struct {
+ name string
+ flags []string
+ want string
+ }{
+ {name: "same definition by name and id", flags: []string{"Owner=Alice", propertyID + "=Bob"}, want: "provided more than once"},
+ {name: "none sentinel", flags: []string{"Owner=__none__"}, want: "list-filter value"},
+ {name: "comparison operator", flags: []string{"Owner>=Alice"}, want: "comparison operators"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ cmd := newIssueCreateTestCmd()
+ _ = cmd.Flags().Set("title", "Rejected properties")
+ for _, flag := range test.flags {
+ _ = cmd.Flags().Set("property", flag)
+ }
+ err := runIssueCreate(cmd, nil)
+ if err == nil || !strings.Contains(err.Error(), test.want) {
+ t.Fatalf("error = %v, want %q", err, test.want)
+ }
+ })
+ }
+ if posts != 0 {
+ t.Fatalf("invalid property flags sent %d create POST(s)", posts)
+ }
+}
+
func TestRunIssueCreateSendsAllowDuplicate(t *testing.T) {
var body map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/server/cmd/multica/cmd_property.go b/server/cmd/multica/cmd_property.go
index 53a48e036f..fb7fb3f851 100644
--- a/server/cmd/multica/cmd_property.go
+++ b/server/cmd/multica/cmd_property.go
@@ -17,6 +17,8 @@ import (
"github.com/spf13/cobra"
"github.com/multica-ai/multica/server/internal/cli"
+ "github.com/multica-ai/multica/server/internal/issueproperty"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// multica property {list|get|create|update|archive|unarchive} — workspace
@@ -587,6 +589,58 @@ func encodeIssuePropertyValue(ctx context.Context, client *cli.APIClient, direct
}
}
+// buildIssueCreateProperties resolves repeatable Name=Value flags into the
+// API's ID-keyed typed bag. A definition may appear only once, including when
+// one flag uses its name and another its UUID.
+func buildIssueCreateProperties(ctx context.Context, client *cli.APIClient, pairs []string) (map[string]json.RawMessage, error) {
+ properties, err := fetchProperties(ctx, client)
+ if err != nil {
+ return nil, err
+ }
+ result := make(map[string]json.RawMessage, len(pairs))
+ var members memberDirectory
+ for _, pair := range pairs {
+ name, rawValue, found := strings.Cut(pair, "=")
+ name = strings.TrimSpace(name)
+ if !found || name == "" {
+ return nil, fmt.Errorf(`--property %q must be in "Name=Value" form`, pair)
+ }
+ if strings.HasSuffix(name, "<") || strings.HasSuffix(name, ">") || strings.HasSuffix(name, "!") {
+ return nil, fmt.Errorf(`--property %q: filter comparison operators are not valid when creating an issue; use a property UUID if its name ends with that character`, pair)
+ }
+ if strings.TrimSpace(rawValue) == "" {
+ return nil, fmt.Errorf("--property %s: value cannot be empty", name)
+ }
+ if strings.TrimSpace(rawValue) == propertyNoValueSentinel {
+ return nil, fmt.Errorf("--property %s: %s is a list-filter value and cannot unset a property during create", name, propertyNoValueSentinel)
+ }
+ property, err := resolvePropertyRef(properties, name)
+ if err != nil {
+ return nil, err
+ }
+ if property.Archived {
+ return nil, fmt.Errorf("property %q is archived and cannot receive new values", property.Name)
+ }
+ if _, duplicate := result[property.ID]; duplicate {
+ return nil, fmt.Errorf("property %q was provided more than once", property.Name)
+ }
+ encoded, err := encodeIssuePropertyValue(ctx, client, &members, property, rawValue)
+ if err != nil {
+ return nil, fmt.Errorf("--property %s: %w", name, err)
+ }
+ config, err := json.Marshal(property.Config)
+ if err != nil {
+ return nil, fmt.Errorf("encode property %q config: %w", property.Name, err)
+ }
+ canonical, err := issueproperty.ValidateValue(db.IssueProperty{Type: property.Type, Config: config}, encoded)
+ if err != nil {
+ return nil, fmt.Errorf("--property %s: %w", name, err)
+ }
+ result[property.ID] = canonical
+ }
+ return result, nil
+}
+
// propertyOptionName maps a stored option id to its name, or returns the id
// when the option is no longer in the definition (the server sorts such a
// value as NULL rather than failing; display does the same).
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index 8ec6468190..f5857c8782 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -81,6 +81,12 @@ type AppConfig struct {
// must fail closed when this declaration is absent.
AgentConversationStartersSupported bool `json:"agent_conversation_starters_supported"`
+ // IssueCreatePropertiesSupported tells independently deployed clients that
+ // POST /api/issues validates and persists the optional properties bag.
+ // Older handlers silently ignore unknown fields, so clients with values must
+ // fail closed when this declaration is absent.
+ IssueCreatePropertiesSupported bool `json:"issue_create_properties_supported"`
+
// CommentDeleteKeepRepliesSupported tells clients that deleting a comment
// removes only that comment and keeps its replies (#8296), and that
// DELETE /api/comments/{id}/keep-replies exists. Older servers deleted the
@@ -106,6 +112,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
// running, the save gate is running with it.
LocalWorktreeSupported: true,
AgentConversationStartersSupported: true,
+ IssueCreatePropertiesSupported: true,
CommentDeleteKeepRepliesSupported: true,
AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",
GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index a158289971..a8353ce6a0 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -558,6 +558,29 @@ func TestGetConfigDeclaresAgentConversationStartersSupport(t *testing.T) {
}
}
+func TestGetConfigDeclaresIssueCreatePropertiesSupport(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ if !cfg.IssueCreatePropertiesSupported {
+ t.Fatal("this build atomically persists issue create properties but does not advertise the contract")
+ }
+ var raw map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &raw); err != nil {
+ t.Fatalf("decode raw config: %v", err)
+ }
+ if _, ok := raw["issue_create_properties_supported"]; !ok {
+ t.Fatal("issue_create_properties_supported missing from the JSON body")
+ }
+}
+
// Web/Desktop, mobile and the CLI promise that a delete keeps the replies only
// when the server declares it (#8296). Older servers omit the field and delete
// the replies too, so this build must advertise the contract explicitly.
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 9717f5a6c5..c1b36e2470 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -1,6 +1,7 @@
package handler
import (
+ "bytes"
"context"
"encoding/json"
"errors"
@@ -2913,6 +2914,9 @@ type CreateIssueRequest struct {
// transaction as the create. Unknown or non-issue ids are rejected with
// 400 (service.ErrIssueLabelNotFound) rather than silently dropped.
LabelIDs []string `json:"label_ids,omitempty"`
+ // Properties is an ID-keyed bag whose values use the same typed wire shape
+ // as Issue.properties and the standalone property PUT endpoint.
+ Properties map[string]json.RawMessage `json:"properties,omitempty"`
// OriginType / OriginID stamp the new issue with its provenance so
// platform-internal flows can deterministically locate it later. Only
// trusted callers should set these — currently the daemon CLI passes
@@ -2924,6 +2928,126 @@ type CreateIssueRequest struct {
AllowDuplicate bool `json:"allow_duplicate,omitempty"`
}
+// UnmarshalJSON rejects duplicate object members before Go's ordinary map
+// decoding can silently apply last-wins semantics. This is especially
+// important for properties: two values for one definition must reject the
+// whole create, never choose one implicitly.
+func (r *CreateIssueRequest) UnmarshalJSON(data []byte) error {
+ if err := rejectDuplicateJSONKeys(data); err != nil {
+ return err
+ }
+ type createIssueRequestAlias CreateIssueRequest
+ var decoded createIssueRequestAlias
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ return err
+ }
+ *r = CreateIssueRequest(decoded)
+ return nil
+}
+
+func rejectDuplicateJSONKeys(data []byte) error {
+ decoder := json.NewDecoder(bytes.NewReader(data))
+ decoder.UseNumber()
+ if err := rejectDuplicateJSONValue(decoder); err != nil {
+ return err
+ }
+ if _, err := decoder.Token(); !errors.Is(err, io.EOF) {
+ if err == nil {
+ return errors.New("request body must contain one JSON value")
+ }
+ return err
+ }
+ return nil
+}
+
+func rejectDuplicateJSONValue(decoder *json.Decoder) error {
+ token, err := decoder.Token()
+ if err != nil {
+ return err
+ }
+ delimiter, ok := token.(json.Delim)
+ if !ok {
+ return nil
+ }
+ switch delimiter {
+ case '{':
+ seen := make(map[string]struct{})
+ for decoder.More() {
+ keyToken, err := decoder.Token()
+ if err != nil {
+ return err
+ }
+ key, ok := keyToken.(string)
+ if !ok {
+ return errors.New("object key must be a string")
+ }
+ if _, duplicate := seen[key]; duplicate {
+ return fmt.Errorf("duplicate JSON key %q", key)
+ }
+ seen[key] = struct{}{}
+ if err := rejectDuplicateJSONValue(decoder); err != nil {
+ return err
+ }
+ }
+ _, err = decoder.Token()
+ return err
+ case '[':
+ for decoder.More() {
+ if err := rejectDuplicateJSONValue(decoder); err != nil {
+ return err
+ }
+ }
+ _, err = decoder.Token()
+ return err
+ default:
+ return errors.New("invalid JSON delimiter")
+ }
+}
+
+func parseIssueCreateProperties(w http.ResponseWriter, values map[string]json.RawMessage) (map[pgtype.UUID]json.RawMessage, bool) {
+ if len(values) == 0 {
+ return nil, true
+ }
+ parsed := make(map[pgtype.UUID]json.RawMessage, len(values))
+ for propertyID, value := range values {
+ id, err := util.ParseUUID(propertyID)
+ if err != nil {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": "invalid_issue_property", "property_id": propertyID,
+ "error": "property id must be a UUID",
+ })
+ return nil, false
+ }
+ if _, duplicate := parsed[id]; duplicate {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": "invalid_issue_property", "property_id": propertyID,
+ "error": "property was provided more than once",
+ })
+ return nil, false
+ }
+ parsed[id] = value
+ }
+ return parsed, true
+}
+
+func writeIssueCreatePropertyError(w http.ResponseWriter, err error) bool {
+ var propertyErr *service.IssuePropertyValidationError
+ if errors.As(err, &propertyErr) {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": "invalid_issue_property", "property_id": propertyErr.PropertyID,
+ "error": propertyErr.Message,
+ })
+ return true
+ }
+ if errors.Is(err, service.ErrIssuePropertiesTooLarge) {
+ writeJSON(w, http.StatusBadRequest, map[string]any{
+ "code": "issue_properties_too_large", "error": err.Error(),
+ })
+ return true
+ }
+ return false
+}
+
func duplicateIssueMessage(issue IssueResponse) string {
return issueguard.DuplicateMessage(issue.Identifier, issue.Title, issue.Status)
}
@@ -3037,6 +3161,10 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ properties, ok := parseIssueCreateProperties(w, req.Properties)
+ if !ok {
+ return
+ }
var startDate pgtype.Date
if req.StartDate != nil && *req.StartDate != "" {
@@ -3163,6 +3291,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
Stage: ptrToInt4(req.Stage),
AttachmentIDs: attachmentIDs,
LabelIDs: labelIDs,
+ Properties: properties,
AllowDuplicate: req.AllowDuplicate,
}, service.IssueCreateOpts{
ActorID: actualCreatorID,
@@ -3215,6 +3344,9 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
"the target status was archived while this request was in flight; reload the status list and retry")
return
}
+ if writeIssueCreatePropertyError(w, err) {
+ return
+ }
if writeIssueLimitReached(w, err) {
return
}
diff --git a/server/internal/handler/issue_create_properties_test.go b/server/internal/handler/issue_create_properties_test.go
new file mode 100644
index 0000000000..80122471a7
--- /dev/null
+++ b/server/internal/handler/issue_create_properties_test.go
@@ -0,0 +1,313 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func createIssueWithPropertyBody(t *testing.T, body map[string]any) IssueResponse {
+ t.Helper()
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, body),
+ ).Want(http.StatusCreated)
+ var issue IssueResponse
+ if err := json.NewDecoder(response.Body).Decode(&issue); err != nil {
+ t.Fatalf("decode create response: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issue.ID)
+ })
+ return issue
+}
+
+func countIssuesWithAtomicPropertyTitle(t *testing.T, title string) int {
+ t.Helper()
+ var count int
+ if err := testPool.QueryRow(context.Background(), `SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = $2`, testWorkspaceID, title).Scan(&count); err != nil {
+ t.Fatalf("count issues: %v", err)
+ }
+ return count
+}
+
+func TestCreateIssueWithPropertiesCanonicalizesEveryType(t *testing.T) {
+ suffix := uuid.NewString()[:8]
+ text := createTestProperty(t, map[string]any{"name": "CreateText" + suffix, "type": "text"})
+ number := createTestProperty(t, map[string]any{"name": "CreateNumber" + suffix, "type": "number"})
+ selectOne := createTestProperty(t, map[string]any{
+ "name": "CreateSelect" + suffix, "type": "select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "First", "color": "#3b82f6"},
+ {"name": "Second", "color": "#22c55e"},
+ }},
+ })
+ multiSelect := createTestProperty(t, map[string]any{
+ "name": "CreateMulti" + suffix, "type": "multi_select",
+ "config": map[string]any{"options": []map[string]any{
+ {"name": "One", "color": "#3b82f6"},
+ {"name": "Two", "color": "#22c55e"},
+ }},
+ })
+ date := createTestProperty(t, map[string]any{"name": "CreateDate" + suffix, "type": "date"})
+ checkbox := createTestProperty(t, map[string]any{"name": "CreateCheck" + suffix, "type": "checkbox"})
+ urlProperty := createTestProperty(t, map[string]any{"name": "CreateURL" + suffix, "type": "url"})
+ actor := createTestProperty(t, map[string]any{"name": "CreateActor" + suffix, "type": "actor"})
+ multiActor := createTestProperty(t, map[string]any{"name": "CreateActors" + suffix, "type": "multi_actor"})
+
+ memberRef := "member:" + testUserID
+ issue := createIssueWithPropertyBody(t, map[string]any{
+ "title": "atomic all property types " + suffix,
+ "properties": map[string]any{
+ text.ID: "value",
+ number.ID: 3.5,
+ selectOne.ID: selectOne.Config.Options[1].ID,
+ multiSelect.ID: []string{multiSelect.Config.Options[1].ID, multiSelect.Config.Options[0].ID, multiSelect.Config.Options[1].ID},
+ date.ID: "2026-09-22",
+ checkbox.ID: true,
+ urlProperty.ID: " https://example.com/spec ",
+ actor.ID: memberRef,
+ multiActor.ID: []string{memberRef, memberRef},
+ },
+ })
+
+ wantMulti := []any{multiSelect.Config.Options[0].ID, multiSelect.Config.Options[1].ID}
+ if got := issue.Properties[multiSelect.ID]; !reflect.DeepEqual(got, wantMulti) {
+ t.Fatalf("multi_select = %#v, want canonical config order %#v", got, wantMulti)
+ }
+ if got := issue.Properties[multiActor.ID]; !reflect.DeepEqual(got, []any{memberRef}) {
+ t.Fatalf("multi_actor = %#v, want first-occurrence dedupe", got)
+ }
+ if got := issue.Properties[urlProperty.ID]; got != "https://example.com/spec" {
+ t.Fatalf("url = %#v, want trimmed canonical value", got)
+ }
+
+ var stored []byte
+ if err := testPool.QueryRow(context.Background(), `SELECT properties FROM issue WHERE id = $1`, issue.ID).Scan(&stored); err != nil {
+ t.Fatalf("load stored properties: %v", err)
+ }
+ var bag map[string]any
+ if err := json.Unmarshal(stored, &bag); err != nil {
+ t.Fatalf("decode stored properties: %v", err)
+ }
+ if !reflect.DeepEqual(bag, issue.Properties) {
+ t.Fatalf("response properties differ from stored snapshot: response=%#v stored=%#v", issue.Properties, bag)
+ }
+ if len(issue.Properties) != 9 {
+ t.Fatalf("response property count = %d, want all 9 supported types", len(issue.Properties))
+ }
+}
+
+func TestCreateIssuePropertiesInvalidSecondValueRollsBack(t *testing.T) {
+ suffix := uuid.NewString()[:8]
+ first := createTestProperty(t, map[string]any{
+ "name": "RollbackFirst" + suffix, "type": "select",
+ "config": map[string]any{"options": []map[string]any{{"name": "Valid", "color": "#3b82f6"}}},
+ })
+ second := createTestProperty(t, map[string]any{
+ "name": "RollbackSecond" + suffix, "type": "select",
+ "config": map[string]any{"options": []map[string]any{{"name": "Valid", "color": "#3b82f6"}}},
+ })
+ if first.ID > second.ID {
+ first, second = second, first
+ }
+ title := "atomic property rollback " + suffix
+
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title,
+ "properties": map[string]any{first.ID: first.Config.Options[0].ID, second.ID: uuid.NewString()},
+ }),
+ ).Want(http.StatusBadRequest)
+ var body map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&body)
+ if body["code"] != "invalid_issue_property" || body["property_id"] != second.ID {
+ t.Fatalf("unexpected error body: %#v", body)
+ }
+ if got := countIssuesWithAtomicPropertyTitle(t, title); got != 0 {
+ t.Fatalf("invalid atomic create persisted %d issue(s)", got)
+ }
+}
+
+func TestCreateIssuePropertiesRejectDefinitionAndActorBoundaries(t *testing.T) {
+ suffix := uuid.NewString()[:8]
+ archived := createTestProperty(t, map[string]any{"name": "ArchivedCreate" + suffix, "type": "text"})
+ archive := testutil.Call(t, testHandler.UpdateProperty,
+ withURLParam(newRequest(http.MethodPatch, "/api/properties/"+archived.ID, map[string]any{"archived": true}), "id", archived.ID),
+ ).Want(http.StatusOK)
+ _ = archive
+ actor := createTestProperty(t, map[string]any{"name": "ForeignActor" + suffix, "type": "actor"})
+
+ foreignWorkspaceID := uuid.NewString()
+ foreignPropertyID := uuid.NewString()
+ if _, err := testPool.Exec(context.Background(), `INSERT INTO workspace (id, name, slug, issue_prefix) VALUES ($1, $2, $3, 'F')`, foreignWorkspaceID, "Foreign create test", "foreign-create-"+suffix); err != nil {
+ t.Fatalf("create foreign workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, foreignPropertyID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID)
+ })
+ if _, err := testPool.Exec(context.Background(), `INSERT INTO issue_property (id, workspace_id, name, type, config) VALUES ($1, $2, 'Foreign', 'text', '{}')`, foreignPropertyID, foreignWorkspaceID); err != nil {
+ t.Fatalf("create foreign property: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ propertyID string
+ value any
+ }{
+ {name: "unknown", propertyID: uuid.NewString(), value: "x"},
+ {name: "foreign", propertyID: foreignPropertyID, value: "x"},
+ {name: "archived", propertyID: archived.ID, value: "x"},
+ {name: "foreign actor", propertyID: actor.ID, value: "member:" + uuid.NewString()},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ title := "reject " + test.name + " " + uuid.NewString()
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title, "properties": map[string]any{test.propertyID: test.value},
+ }),
+ ).Want(http.StatusBadRequest)
+ var body map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&body)
+ if body["code"] != "invalid_issue_property" || body["property_id"] != test.propertyID {
+ t.Fatalf("unexpected error body: %#v", body)
+ }
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("rejected create persisted an issue")
+ }
+ })
+ }
+}
+
+func TestCreateIssuePropertiesRejectsDuplicateJSONKey(t *testing.T) {
+ property := createTestProperty(t, map[string]any{"name": "DuplicateCreate" + uuid.NewString()[:8], "type": "text"})
+ title := "duplicate property JSON " + uuid.NewString()
+ body := fmt.Sprintf(`{"title":%q,"properties":{"%s":"first","%s":"second"}}`, title, property.ID, property.ID)
+ req := httptest.NewRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("duplicate-key create persisted an issue")
+ }
+}
+
+func TestCreateIssuePropertiesRejectsDuplicateCanonicalPropertyID(t *testing.T) {
+ property := createTestProperty(t, map[string]any{"name": "DuplicateCanonical" + uuid.NewString()[:8], "type": "text"})
+ title := "duplicate canonical property " + uuid.NewString()
+ body := fmt.Sprintf(
+ `{"title":%q,"properties":{"%s":"first","%s":"second"}}`,
+ title,
+ property.ID,
+ strings.ReplaceAll(property.ID, "-", ""),
+ )
+ req := httptest.NewRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ response := testutil.Call(t, testHandler.CreateIssue, req).Want(http.StatusBadRequest)
+ var errorBody map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&errorBody)
+ if errorBody["code"] != "invalid_issue_property" {
+ t.Fatalf("unexpected error body: %#v", errorBody)
+ }
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("duplicate canonical property create persisted an issue")
+ }
+}
+
+func TestCreateIssuePropertiesRejectsEmptyMultiValue(t *testing.T) {
+ property := createTestProperty(t, map[string]any{
+ "name": "EmptyMultiCreate" + uuid.NewString()[:8],
+ "type": "multi_select",
+ "config": map[string]any{"options": []map[string]any{{
+ "name": "Only", "color": "#3b82f6",
+ }}},
+ })
+ title := "empty multi property " + uuid.NewString()
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title, "properties": map[string]any{property.ID: []string{}},
+ }),
+ ).Want(http.StatusBadRequest)
+ var body map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&body)
+ if body["code"] != "invalid_issue_property" || body["property_id"] != property.ID {
+ t.Fatalf("unexpected error body: %#v", body)
+ }
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("empty multi-value create persisted an issue")
+ }
+}
+
+func TestCreateIssuePropertiesAllowsPlainWorkspaceMember(t *testing.T) {
+ property := createTestProperty(t, map[string]any{
+ "name": "MemberCreate" + uuid.NewString()[:8], "type": "text",
+ })
+ memberID := createPropertyTestMember(t)
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequestAs(memberID, http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "plain member property create " + uuid.NewString(),
+ "properties": map[string]any{property.ID: "allowed"},
+ }),
+ ).Want(http.StatusCreated)
+ var issue IssueResponse
+ if err := json.NewDecoder(response.Body).Decode(&issue); err != nil {
+ t.Fatalf("decode create response: %v", err)
+ }
+ t.Cleanup(func() { _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issue.ID) })
+ if issue.Properties[property.ID] != "allowed" {
+ t.Fatalf("plain member property snapshot = %#v", issue.Properties)
+ }
+}
+
+func TestCreateIssuePropertiesPreservesAssignmentPermissionBoundary(t *testing.T) {
+ property := createTestProperty(t, map[string]any{
+ "name": "PermissionCreate" + uuid.NewString()[:8], "type": "text",
+ })
+ privateAgentID, _, plainMemberID := privateAgentTestFixture(t)
+ title := "property create permission " + uuid.NewString()
+ testutil.Call(t, testHandler.CreateIssue,
+ newRequestAs(plainMemberID, http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title, "assignee_type": "agent", "assignee_id": privateAgentID,
+ "properties": map[string]any{property.ID: "must roll back"},
+ }),
+ ).Want(http.StatusForbidden)
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("permission-denied property create persisted an issue")
+ }
+}
+
+func TestCreateIssuePropertiesEnforcesSharedBagSizeLimit(t *testing.T) {
+ properties := make(map[string]any)
+ for index := 0; index < 9; index++ {
+ property := createTestProperty(t, map[string]any{
+ "name": fmt.Sprintf("LargeCreate%d%s", index, uuid.NewString()[:8]), "type": "text",
+ })
+ properties[property.ID] = strings.Repeat("x", 2000)
+ }
+ title := "large property bag " + uuid.NewString()
+ response := testutil.Call(t, testHandler.CreateIssue,
+ newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": title, "properties": properties,
+ }),
+ ).Want(http.StatusBadRequest)
+ var body map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&body)
+ if body["code"] != "issue_properties_too_large" {
+ t.Fatalf("unexpected error body: %#v", body)
+ }
+ if countIssuesWithAtomicPropertyTitle(t, title) != 0 {
+ t.Fatal("oversized property-bag create persisted an issue")
+ }
+}
diff --git a/server/internal/handler/property.go b/server/internal/handler/property.go
index b18917ed6b..bbd506fcdc 100644
--- a/server/internal/handler/property.go
+++ b/server/internal/handler/property.go
@@ -7,7 +7,6 @@ import (
"log/slog"
"math"
"net/http"
- "net/url"
"sort"
"strconv"
"strings"
@@ -19,6 +18,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issueproperty"
"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"
@@ -307,126 +307,20 @@ func selectOptionsHint(cfg PropertyConfig) string {
// Actor values (MUL-6286)
// ---------------------------------------------------------------------------
-// actorPropertyKinds is the V1 value range for actor properties: workspace
-// members only. The issue assignee also accepts "agent" and "squad", but
-// neither belongs in a passive reference yet — an agent reference drags in the
-// whole agent-visibility question (private / non-allow-listed agents must not
-// become discoverable by id) for no demonstrated use case, and a squad is a
-// routing target rather than a person.
-//
-// The stored form is "<kind>:<uuid>", so widening this list is a one-line
-// change: no migration, no new property type, and existing definitions gain
-// the new kind in place. Anything added here that is NOT universally visible
-// to every workspace member (an agent, for one) must also restore a visibility
-// gate on both the write path and the table-facet read path.
-var actorPropertyKinds = []string{"member"}
-
-// actorRef is a parsed "<kind>:<uuid>" property value.
-type actorRef struct {
- Kind string
- ID string
-}
-
-func (a actorRef) String() string { return a.Kind + ":" + a.ID }
-
-func propertyTypeIsActor(t string) bool {
- return t == "actor" || t == "multi_actor"
-}
-
-func actorKindsHint() string {
- return strings.Join(actorPropertyKinds, " / ")
-}
+// Compatibility aliases keep the focused handler tests on the same helper
+// names while the implementation is shared with IssueService.Create.
+type actorRef = issueproperty.ActorRef
-// parseActorRef splits a stored actor value. Members are referenced by
-// user_id — the same id the assignee pair uses — so "who is this" resolves
-// identically everywhere in the product.
+func propertyTypeIsActor(t string) bool { return issueproperty.IsActor(t) }
+func actorKindsHint() string { return issueproperty.ActorKindsHint() }
func parseActorRef(s string) (actorRef, error) {
- kind, id, found := strings.Cut(s, ":")
- if !found {
- return actorRef{}, fmt.Errorf("value must look like \"<kind>:<uuid>\" where kind is one of: %s", actorKindsHint())
- }
- valid := false
- for _, k := range actorPropertyKinds {
- if kind == k {
- valid = true
- break
- }
- }
- if !valid {
- return actorRef{}, fmt.Errorf("unknown actor kind %q; valid kinds: %s", kind, actorKindsHint())
- }
- parsed, err := uuid.Parse(id)
- if err != nil {
- return actorRef{}, fmt.Errorf("actor id in %q must be a UUID", s)
- }
- // Store the canonical lowercase-hyphenated form. uuid.Parse also accepts
- // uppercase, braces and the urn: prefix; every consumer downstream (the
- // member directory lookup in the client, the "= me" filter, @> containment)
- // compares reference strings exactly, so an unnormalized id would store
- // fine and then render as Unknown and never match a filter.
- return actorRef{Kind: kind, ID: parsed.String()}, nil
+ return issueproperty.ParseActorRef(s)
}
-
-// parseActorRefList validates a multi_actor array: every element must parse,
-// duplicates are dropped, and the caller's order is preserved. Unlike
-// multi_select there is no config order to canonicalize against, and sorting
-// by id would make the avatar row reshuffle on every edit. @> containment is
-// order-insensitive, so filtering is unaffected either way.
func parseActorRefList(items []any) ([]actorRef, error) {
- if len(items) == 0 {
- return nil, errors.New("value must be a non-empty array of actor references")
- }
- if len(items) > maxPropertyActorValues {
- return nil, fmt.Errorf("value cannot list more than %d actors", maxPropertyActorValues)
- }
- seen := make(map[string]struct{}, len(items))
- refs := make([]actorRef, 0, len(items))
- for _, item := range items {
- s, ok := item.(string)
- if !ok {
- return nil, errors.New("value must be an array of actor reference strings")
- }
- ref, err := parseActorRef(s)
- if err != nil {
- return nil, err
- }
- if _, dup := seen[ref.String()]; dup {
- continue
- }
- seen[ref.String()] = struct{}{}
- refs = append(refs, ref)
- }
- return refs, nil
+ return issueproperty.ParseActorRefList(items)
}
-
-// actorRefsInValue re-reads the canonical stored JSON for an actor property.
-// SetIssueProperty uses it to resolve references against the workspace after
-// the pure shape validation has run.
func actorRefsInValue(propType string, stored []byte) ([]actorRef, error) {
- if propType == "actor" {
- var s string
- if err := json.Unmarshal(stored, &s); err != nil {
- return nil, err
- }
- ref, err := parseActorRef(s)
- if err != nil {
- return nil, err
- }
- return []actorRef{ref}, nil
- }
- var list []string
- if err := json.Unmarshal(stored, &list); err != nil {
- return nil, err
- }
- refs := make([]actorRef, 0, len(list))
- for _, s := range list {
- ref, err := parseActorRef(s)
- if err != nil {
- return nil, err
- }
- refs = append(refs, ref)
- }
- return refs, nil
+ return issueproperty.ActorRefsInValue(propType, stored)
}
// resolveActorRefs checks that every reference points at a real member of this
@@ -458,126 +352,7 @@ func (h *Handler) resolveActorRefs(r *http.Request, workspaceID string, refs []a
// 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)
- case "actor":
- s, ok := v.(string)
- if !ok {
- return nil, fmt.Errorf("value must be an actor reference string like \"member:<uuid>\" (kinds: %s)", actorKindsHint())
- }
- ref, err := parseActorRef(s)
- if err != nil {
- return nil, err
- }
- return json.Marshal(ref.String())
- case "multi_actor":
- items, ok := v.([]any)
- if !ok {
- return nil, fmt.Errorf("value must be an array of actor reference strings like \"member:<uuid>\" (kinds: %s)", actorKindsHint())
- }
- refs, err := parseActorRefList(items)
- if err != nil {
- return nil, err
- }
- out := make([]string, len(refs))
- for i, ref := range refs {
- out[i] = ref.String()
- }
- return json.Marshal(out)
- default:
- return nil, fmt.Errorf("unsupported property type %q", def.Type)
- }
+ return issueproperty.ValidateValue(def, raw)
}
// removedOptionIDs returns option ids present in the stored config but
diff --git a/server/internal/handler/source_context.go b/server/internal/handler/source_context.go
index 6f687fb488..104552298c 100644
--- a/server/internal/handler/source_context.go
+++ b/server/internal/handler/source_context.go
@@ -690,6 +690,10 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Req
if !ok {
return errSourceContextResponseWritten
}
+ properties, ok := parseIssueCreateProperties(w, input.Properties)
+ if !ok {
+ return errSourceContextResponseWritten
+ }
var startDate, dueDate pgtype.Date
if input.StartDate != nil && *input.StartDate != "" {
parsed, err := util.ParseCalendarDate(*input.StartDate)
@@ -720,7 +724,7 @@ func (h *Handler) createManualCommentSubIssue(w http.ResponseWriter, r *http.Req
WorkspaceID: workspaceID, Title: title, Description: ptrToText(input.Description), Status: status, Priority: priority,
AssigneeType: assigneeType, AssigneeID: assigneeID, CreatorType: "member", CreatorID: userID,
ParentIssueID: capture.SourceIssueID, ProjectID: projectID, StartDate: startDate, DueDate: dueDate,
- AttachmentIDs: attachmentIDs, LabelIDs: labelIDs, Stage: stage,
+ AttachmentIDs: attachmentIDs, LabelIDs: labelIDs, Properties: properties, Stage: stage,
AllowDuplicate: input.AllowDuplicate, SourceContext: &capture,
}, service.IssueCreateOpts{
ActorID: util.UUIDToString(userID),
@@ -868,6 +872,7 @@ func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limi
status := http.StatusInternalServerError
code := "source_context_capture_failed"
message := "failed to capture source context"
+ var propertyErr *service.IssuePropertyValidationError
switch {
case errors.Is(err, service.ErrSourceContextChanged):
status, code = http.StatusConflict, "source_context_changed"
@@ -893,6 +898,12 @@ func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limi
case errors.Is(err, service.ErrParentIssueNotFound), errors.Is(err, service.ErrProjectNotFound):
status = http.StatusBadRequest
message = err.Error()
+ case errors.As(err, &propertyErr):
+ status, code = http.StatusBadRequest, "invalid_issue_property"
+ message = propertyErr.Message
+ case errors.Is(err, service.ErrIssuePropertiesTooLarge):
+ status, code = http.StatusBadRequest, "issue_properties_too_large"
+ message = err.Error()
case errors.Is(err, errSourceContextBadRequest):
status, code = http.StatusBadRequest, "invalid_request"
message = err.Error()
@@ -900,6 +911,9 @@ func (h *Handler) writeSourceContextError(w http.ResponseWriter, err error, limi
return
}
payload := map[string]any{"code": code, "error": message}
+ if propertyErr != nil {
+ payload["property_id"] = propertyErr.PropertyID
+ }
if errors.Is(err, service.ErrSourceContextTooLarge) {
payload["limits"] = limits
}
diff --git a/server/internal/issueproperty/value.go b/server/internal/issueproperty/value.go
new file mode 100644
index 0000000000..1fc3bc3b28
--- /dev/null
+++ b/server/internal/issueproperty/value.go
@@ -0,0 +1,284 @@
+// Package issueproperty owns the transport-independent validation contract for
+// values stored in an issue's custom-property bag. HTTP PUT and atomic issue
+// creation both call this package so the accepted types and canonical form
+// cannot drift between write paths.
+package issueproperty
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "sort"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ maxTextValueLen = 2000
+ maxURLValueLen = 2048
+ // MaxActorValues is exported so the handler's existing focused tests can
+ // continue to pin the public multi-actor limit after validation moved here.
+ MaxActorValues = 20
+)
+
+var actorKinds = []string{"member"}
+
+type propertyOption struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+type propertyConfig struct {
+ Options []propertyOption `json:"options,omitempty"`
+}
+
+// ActorRef is the canonical parsed form of a "<kind>:<uuid>" property value.
+type ActorRef struct {
+ Kind string
+ ID string
+}
+
+func (a ActorRef) String() string { return a.Kind + ":" + a.ID }
+
+// IsActor reports whether a definition needs workspace-member resolution in
+// addition to pure JSON shape validation.
+func IsActor(propertyType string) bool {
+ return propertyType == "actor" || propertyType == "multi_actor"
+}
+
+func ActorKindsHint() string { return strings.Join(actorKinds, " / ") }
+
+// ParseActorRef validates and canonicalizes an actor reference. Members use
+// user_id, matching the assignee contract and client-side member directory.
+func ParseActorRef(value string) (ActorRef, error) {
+ kind, id, found := strings.Cut(value, ":")
+ if !found {
+ return ActorRef{}, fmt.Errorf("value must look like \"<kind>:<uuid>\" where kind is one of: %s", ActorKindsHint())
+ }
+ valid := false
+ for _, candidate := range actorKinds {
+ if kind == candidate {
+ valid = true
+ break
+ }
+ }
+ if !valid {
+ return ActorRef{}, fmt.Errorf("unknown actor kind %q; valid kinds: %s", kind, ActorKindsHint())
+ }
+ parsed, err := uuid.Parse(id)
+ if err != nil {
+ return ActorRef{}, fmt.Errorf("actor id in %q must be a UUID", value)
+ }
+ return ActorRef{Kind: kind, ID: parsed.String()}, nil
+}
+
+// ParseActorRefList validates a multi_actor array, removes duplicates, and
+// preserves first-occurrence order.
+func ParseActorRefList(items []any) ([]ActorRef, error) {
+ if len(items) == 0 {
+ return nil, errors.New("value must be a non-empty array of actor references")
+ }
+ if len(items) > MaxActorValues {
+ return nil, fmt.Errorf("value cannot list more than %d actors", MaxActorValues)
+ }
+ seen := make(map[string]struct{}, len(items))
+ refs := make([]ActorRef, 0, len(items))
+ for _, item := range items {
+ value, ok := item.(string)
+ if !ok {
+ return nil, errors.New("value must be an array of actor reference strings")
+ }
+ ref, err := ParseActorRef(value)
+ if err != nil {
+ return nil, err
+ }
+ if _, duplicate := seen[ref.String()]; duplicate {
+ continue
+ }
+ seen[ref.String()] = struct{}{}
+ refs = append(refs, ref)
+ }
+ return refs, nil
+}
+
+// ActorRefsInValue decodes canonical actor JSON for tenant-scoped reference
+// resolution by the caller.
+func ActorRefsInValue(propertyType string, stored []byte) ([]ActorRef, error) {
+ if propertyType == "actor" {
+ var value string
+ if err := json.Unmarshal(stored, &value); err != nil {
+ return nil, err
+ }
+ ref, err := ParseActorRef(value)
+ if err != nil {
+ return nil, err
+ }
+ return []ActorRef{ref}, nil
+ }
+ var values []string
+ if err := json.Unmarshal(stored, &values); err != nil {
+ return nil, err
+ }
+ refs := make([]ActorRef, 0, len(values))
+ for _, value := range values {
+ ref, err := ParseActorRef(value)
+ if err != nil {
+ return nil, err
+ }
+ refs = append(refs, ref)
+ }
+ return refs, nil
+}
+
+func parseConfig(raw []byte) propertyConfig {
+ var config propertyConfig
+ if len(raw) != 0 {
+ _ = json.Unmarshal(raw, &config)
+ }
+ return config
+}
+
+func optionOrder(config propertyConfig) map[string]int {
+ order := make(map[string]int, len(config.Options))
+ for index, option := range config.Options {
+ order[option.ID] = index
+ }
+ return order
+}
+
+func optionsHint(config propertyConfig) string {
+ parts := make([]string, len(config.Options))
+ for index, option := range config.Options {
+ parts[index] = fmt.Sprintf("%s (%s)", option.ID, option.Name)
+ }
+ return strings.Join(parts, ", ")
+}
+
+// ValidateValue checks a raw JSON value against the definition's type and
+// returns the canonical JSON stored by every issue-property write path.
+func ValidateValue(def db.IssueProperty, raw json.RawMessage) ([]byte, error) {
+ if len(raw) == 0 {
+ return nil, errors.New("value is required")
+ }
+ var value any
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return nil, fmt.Errorf("value must be valid JSON: %w", err)
+ }
+ if value == nil {
+ return nil, errors.New("value cannot be null (use DELETE to unset a property)")
+ }
+
+ config := parseConfig(def.Config)
+ switch def.Type {
+ case "text":
+ text, ok := value.(string)
+ if !ok {
+ return nil, errors.New("value must be a string")
+ }
+ if strings.TrimSpace(text) == "" {
+ return nil, errors.New("value cannot be empty (use DELETE to unset a property)")
+ }
+ if utf8.RuneCountInString(text) > maxTextValueLen {
+ return nil, fmt.Errorf("value must be %d characters or fewer", maxTextValueLen)
+ }
+ return json.Marshal(util.SanitizeTextForPostgres(text))
+ case "url":
+ text, ok := value.(string)
+ if !ok {
+ return nil, errors.New("value must be a URL string")
+ }
+ text = strings.TrimSpace(text)
+ if len(text) > maxURLValueLen {
+ return nil, fmt.Errorf("value must be %d characters or fewer", maxURLValueLen)
+ }
+ parsed, err := url.Parse(text)
+ if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" {
+ return nil, errors.New("value must be an http(s) URL")
+ }
+ return json.Marshal(text)
+ case "number":
+ if _, ok := value.(float64); !ok {
+ return nil, errors.New("value must be a number")
+ }
+ return json.Marshal(value)
+ case "checkbox":
+ if _, ok := value.(bool); !ok {
+ return nil, errors.New("value must be true or false")
+ }
+ return json.Marshal(value)
+ case "date":
+ text, ok := value.(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", text); err != nil {
+ return nil, errors.New("value must be a date string in YYYY-MM-DD format")
+ }
+ return json.Marshal(text)
+ case "select":
+ id, ok := value.(string)
+ if !ok {
+ return nil, fmt.Errorf("value must be one of the option ids: %s", optionsHint(config))
+ }
+ if _, exists := optionOrder(config)[id]; !exists {
+ return nil, fmt.Errorf("value must be one of the option ids: %s", optionsHint(config))
+ }
+ return json.Marshal(id)
+ case "multi_select":
+ items, ok := value.([]any)
+ if !ok || len(items) == 0 {
+ return nil, fmt.Errorf("value must be a non-empty array of option ids: %s", optionsHint(config))
+ }
+ order := optionOrder(config)
+ seen := make(map[string]struct{}, len(items))
+ ids := make([]string, 0, len(items))
+ for _, item := range items {
+ id, ok := item.(string)
+ if !ok {
+ return nil, fmt.Errorf("value must be a non-empty array of option ids: %s", optionsHint(config))
+ }
+ if _, exists := order[id]; !exists {
+ return nil, fmt.Errorf("unknown option id %q; valid option ids: %s", id, optionsHint(config))
+ }
+ if _, duplicate := seen[id]; duplicate {
+ continue
+ }
+ seen[id] = struct{}{}
+ ids = append(ids, id)
+ }
+ sort.SliceStable(ids, func(left, right int) bool { return order[ids[left]] < order[ids[right]] })
+ return json.Marshal(ids)
+ case "actor":
+ text, ok := value.(string)
+ if !ok {
+ return nil, fmt.Errorf("value must be an actor reference string like \"member:<uuid>\" (kinds: %s)", ActorKindsHint())
+ }
+ ref, err := ParseActorRef(text)
+ if err != nil {
+ return nil, err
+ }
+ return json.Marshal(ref.String())
+ case "multi_actor":
+ items, ok := value.([]any)
+ if !ok {
+ return nil, fmt.Errorf("value must be an array of actor reference strings like \"member:<uuid>\" (kinds: %s)", ActorKindsHint())
+ }
+ refs, err := ParseActorRefList(items)
+ if err != nil {
+ return nil, err
+ }
+ out := make([]string, len(refs))
+ for index, ref := range refs {
+ out[index] = ref.String()
+ }
+ return json.Marshal(out)
+ default:
+ return nil, fmt.Errorf("unsupported property type %q", def.Type)
+ }
+}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 45a9346349..7a3c3d0404 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -6,15 +6,18 @@ import (
"errors"
"fmt"
"log/slog"
+ "sort"
"time"
"github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/entitlement"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/issueposition"
+ "github.com/multica-ai/multica/server/internal/issueproperty"
"github.com/multica-ai/multica/server/internal/issuestatus"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/util"
@@ -80,7 +83,11 @@ type IssueCreateParams struct {
// so the issue is never committed with a partial or wrong label set. An
// unknown or non-issue label id fails the whole create with
// ErrIssueLabelNotFound rather than being silently dropped.
- LabelIDs []pgtype.UUID
+ LabelIDs []pgtype.UUID
+ // Properties is keyed only by property-definition UUID. Create validates
+ // and canonicalizes every value while holding the same per-definition locks
+ // used by the standalone PUT path, then inserts the complete bag atomically.
+ Properties map[pgtype.UUID]json.RawMessage
AllowDuplicate bool
// Stage groups this issue into an ordered barrier group under its parent
// (NULL = unstaged). See issue_child_done.go for the staged-barrier wake.
@@ -158,6 +165,21 @@ var ErrProjectNotFound = errors.New("project not found in this workspace")
// label set. Callers translate this into their transport's 400.
var ErrIssueLabelNotFound = errors.New("issue label not found in this workspace")
+// ErrIssuePropertiesTooLarge is the existing row-level 16KB properties-bag
+// constraint surfaced as a client error. The same database constraint applies
+// to standalone PUT and atomic create writes.
+var ErrIssuePropertiesTooLarge = errors.New("issue properties exceed the 16KB size limit")
+
+// IssuePropertyValidationError identifies the definition whose value made an
+// atomic create invalid. Unknown and foreign-workspace IDs intentionally share
+// the same message so the API does not expose tenant existence.
+type IssuePropertyValidationError struct {
+ PropertyID string
+ Message string
+}
+
+func (e *IssuePropertyValidationError) Error() string { return e.Message }
+
// ErrIssueStatusUnavailable signals that the requested custom status was
// archived between the caller's pre-flight validation and the create
// transaction. Callers translate this into a 409 — the request was valid when
@@ -219,6 +241,11 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
defer tx.Rollback(ctx)
qtx := s.Queries.WithTx(tx)
+ properties, err := validateIssueCreateProperties(ctx, tx, qtx, p.WorkspaceID, p.Properties)
+ if err != nil {
+ return IssueCreateResult{}, err
+ }
+
if p.SourceContext != nil {
if _, err := qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
ID: p.SourceContext.SourceIssueID, WorkspaceID: p.WorkspaceID,
@@ -356,6 +383,7 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
OriginType: p.OriginType,
OriginID: p.OriginID,
Stage: p.Stage,
+ Properties: properties,
})
} else {
issue, err = qtx.CreateIssue(ctx, db.CreateIssueParams{
@@ -376,9 +404,14 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
Number: issueNumber,
ProjectID: projectID,
Stage: p.Stage,
+ Properties: properties,
})
}
if err != nil {
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.ConstraintName == "issue_properties_size_limit" {
+ return IssueCreateResult{}, ErrIssuePropertiesTooLarge
+ }
return IssueCreateResult{}, fmt.Errorf("create issue: %w", err)
}
@@ -510,6 +543,77 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss
return IssueCreateResult{Issue: issue, Attachments: attachments, Labels: labels, AssignedTaskID: assignedTaskID}, nil
}
+// validateIssueCreateProperties returns the canonical JSONB bag to put on the
+// issue row. Locks are acquired for every definition in UUID order before any
+// definition is read, matching definition updates and preventing two
+// multi-property creates from choosing opposite lock orders.
+func validateIssueCreateProperties(ctx context.Context, tx pgx.Tx, qtx *db.Queries, workspaceID pgtype.UUID, values map[pgtype.UUID]json.RawMessage) ([]byte, error) {
+ if len(values) == 0 {
+ return []byte(`{}`), nil
+ }
+
+ ids := make([]pgtype.UUID, 0, len(values))
+ for id := range values {
+ ids = append(ids, id)
+ }
+ sort.Slice(ids, func(left, right int) bool {
+ return util.UUIDToString(ids[left]) < util.UUIDToString(ids[right])
+ })
+ for _, id := range ids {
+ key := "prop:" + util.UUIDToString(id)
+ if _, err := tx.Exec(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key); err != nil {
+ return nil, fmt.Errorf("lock issue property: %w", err)
+ }
+ }
+
+ canonical := make(map[string]json.RawMessage, len(ids))
+ for _, id := range ids {
+ propertyID := util.UUIDToString(id)
+ definition, err := qtx.GetIssueProperty(ctx, db.GetIssuePropertyParams{
+ ID: id, WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: "property not found in this workspace"}
+ }
+ return nil, fmt.Errorf("get issue property: %w", err)
+ }
+ if definition.ArchivedAt.Valid {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: fmt.Sprintf("property %q is archived and cannot receive new values", definition.Name)}
+ }
+ value, err := issueproperty.ValidateValue(definition, values[id])
+ if err != nil {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: err.Error()}
+ }
+ if issueproperty.IsActor(definition.Type) {
+ refs, err := issueproperty.ActorRefsInValue(definition.Type, value)
+ if err != nil {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: err.Error()}
+ }
+ for _, ref := range refs {
+ actorID, parseErr := util.ParseUUID(ref.ID)
+ if parseErr != nil {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: fmt.Sprintf("actor id in %q must be a UUID", ref)}
+ }
+ if _, lookupErr := qtx.GetMemberByUserAndWorkspace(ctx, db.GetMemberByUserAndWorkspaceParams{
+ UserID: actorID, WorkspaceID: workspaceID,
+ }); lookupErr != nil {
+ if errors.Is(lookupErr, pgx.ErrNoRows) {
+ return nil, &IssuePropertyValidationError{PropertyID: propertyID, Message: fmt.Sprintf("%q does not refer to a member of this workspace", ref)}
+ }
+ return nil, fmt.Errorf("resolve issue property actor: %w", lookupErr)
+ }
+ }
+ }
+ canonical[propertyID] = value
+ }
+ encoded, err := json.Marshal(canonical)
+ if err != nil {
+ return nil, fmt.Errorf("encode issue properties: %w", err)
+ }
+ return encoded, nil
+}
+
// validateIssueLabels checks that every requested label exists in the
// workspace and is issue-scoped, returning the de-duplicated label rows to
// attach. Returning the full rows (not just ids) lets Create echo an
diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.go
index 69b7346fed..3258bd51d1 100644
--- a/server/internal/service/issue_channel_media_test.go
+++ b/server/internal/service/issue_channel_media_test.go
@@ -12,6 +12,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -36,6 +37,39 @@ type afterCommitTx struct {
afterCommit func()
}
+type rejectIssueCommitTxStarter struct {
+ pool *pgxpool.Pool
+ err error
+}
+
+func (s *rejectIssueCommitTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &rejectIssueCommitTx{Tx: tx, err: s.err}, nil
+}
+
+type rejectIssueCommitTx struct {
+ pgx.Tx
+ err error
+}
+
+type recordingIssueAnalytics struct {
+ events []analytics.Event
+}
+
+func (a *recordingIssueAnalytics) Capture(event analytics.Event) {
+ a.events = append(a.events, event)
+}
+
+func (*recordingIssueAnalytics) Close() {}
+
+func (t *rejectIssueCommitTx) Commit(ctx context.Context) error {
+ _ = t.Tx.Rollback(ctx)
+ return t.err
+}
+
func (t *afterCommitTx) Commit(ctx context.Context) error {
if err := t.Tx.Commit(ctx); err != nil {
return err
@@ -281,6 +315,151 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(t
}
}
+func TestCreateIssuePropertiesCommitFailureHasNoSideEffects(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+ userUUID := util.MustParseUUID(userID)
+ agentUUID := util.MustParseUUID(agentID)
+ propertyID := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_property (id, workspace_id, name, type, config) VALUES ($1, $2, 'Commit property', 'text', '{}')`, propertyID, workspaceUUID); err != nil {
+ t.Fatalf("insert property: %v", err)
+ }
+ t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, propertyID) })
+
+ bus := events.New()
+ createdEvents := 0
+ bus.Subscribe(protocol.EventIssueCreated, func(events.Event) { createdEvents++ })
+ taskService := &TaskService{Queries: q, TxStarter: pool, Bus: bus}
+ analyticsSink := &recordingIssueAnalytics{}
+ injected := errors.New("injected issue commit failure")
+ issueService := NewIssueService(q, &rejectIssueCommitTxStarter{pool: pool, err: injected}, bus, analyticsSink, taskService)
+ var taskCountBefore int
+ if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM agent_task_queue WHERE agent_id = $1`, agentUUID).Scan(&taskCountBefore); err != nil {
+ t.Fatalf("count tasks before create: %v", err)
+ }
+ if taskCountBefore != 0 {
+ t.Fatalf("fixture agent has %d tasks before create, want 0", taskCountBefore)
+ }
+
+ _, err := issueService.Create(ctx, IssueCreateParams{
+ WorkspaceID: workspaceUUID,
+ Title: "properties commit failure",
+ Status: "todo",
+ Priority: "none",
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: agentUUID,
+ CreatorType: "member",
+ CreatorID: userUUID,
+ Properties: map[pgtype.UUID]json.RawMessage{
+ propertyID: json.RawMessage(`"kept only if committed"`),
+ },
+ }, IssueCreateOpts{})
+ if !errors.Is(err, injected) {
+ t.Fatalf("Create error = %v, want injected commit failure", err)
+ }
+ if createdEvents != 0 {
+ t.Fatalf("published %d issue:created events after failed commit", createdEvents)
+ }
+ if len(analyticsSink.events) != 0 {
+ t.Fatalf("captured %d analytics events after failed commit", len(analyticsSink.events))
+ }
+ var issueCount, taskCountAfter int
+ if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM issue WHERE workspace_id = $1 AND title = 'properties commit failure'`, workspaceUUID).Scan(&issueCount); err != nil {
+ t.Fatalf("count issues: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM agent_task_queue WHERE agent_id = $1`, agentUUID).Scan(&taskCountAfter); err != nil {
+ t.Fatalf("count tasks: %v", err)
+ }
+ if issueCount != 0 || taskCountAfter != 0 {
+ t.Fatalf("failed commit left side effects: issues=%d tasks_before=%d tasks_after=%d", issueCount, taskCountBefore, taskCountAfter)
+ }
+}
+
+func TestCreateIssuePropertiesAreVisibleAtCommitBeforeEnqueue(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+ userUUID := util.MustParseUUID(userID)
+ agentUUID := util.MustParseUUID(agentID)
+ propertyID := pgtype.UUID{Bytes: [16]byte{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}, Valid: true}
+ if _, err := pool.Exec(ctx, `INSERT INTO issue_property (id, workspace_id, name, type, config) VALUES ($1, $2, 'Enqueue property', 'text', '{}')`, propertyID, workspaceUUID); err != nil {
+ t.Fatalf("insert property: %v", err)
+ }
+ t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM issue_property WHERE id = $1`, propertyID) })
+
+ var atCommit map[string]any
+ txStarter := &afterCommitTxStarter{pool: pool, afterCommit: func() {
+ var raw []byte
+ if err := pool.QueryRow(ctx, `SELECT properties FROM issue WHERE workspace_id = $1 AND title = 'properties before enqueue'`, workspaceUUID).Scan(&raw); err != nil {
+ atCommit = map[string]any{"error": err.Error()}
+ return
+ }
+ _ = json.Unmarshal(raw, &atCommit)
+ }}
+ bus := events.New()
+ var createdEvents []events.Event
+ propertyChangedEvents := 0
+ bus.Subscribe(protocol.EventIssueCreated, func(event events.Event) {
+ createdEvents = append(createdEvents, event)
+ })
+ bus.Subscribe(protocol.EventIssuePropertiesChanged, func(events.Event) {
+ propertyChangedEvents++
+ })
+ taskService := &TaskService{Queries: q, TxStarter: pool, Bus: bus}
+ issueService := NewIssueService(q, txStarter, bus, nil, taskService)
+
+ result, err := issueService.Create(ctx, IssueCreateParams{
+ WorkspaceID: workspaceUUID,
+ Title: "properties before enqueue",
+ Status: "todo",
+ Priority: "none",
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: agentUUID,
+ CreatorType: "member",
+ CreatorID: userUUID,
+ Properties: map[pgtype.UUID]json.RawMessage{
+ propertyID: json.RawMessage(`"ready"`),
+ },
+ }, IssueCreateOpts{
+ BroadcastPayload: func(issue db.Issue, _ []db.Attachment, _ []db.IssueLabel) map[string]any {
+ var properties map[string]any
+ if err := json.Unmarshal(issue.Properties, &properties); err != nil {
+ return map[string]any{"error": err.Error()}
+ }
+ return map[string]any{"issue": map[string]any{"properties": properties}}
+ },
+ })
+ if err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ if atCommit[util.UUIDToString(propertyID)] != "ready" {
+ t.Fatalf("properties visible immediately after commit = %#v", atCommit)
+ }
+ if !result.AssignedTaskID.Valid {
+ t.Fatal("assigned task was not enqueued after property-bearing commit")
+ }
+ if len(createdEvents) != 1 || propertyChangedEvents != 0 {
+ t.Fatalf("create events = %d issue:created, %d property-changed; want 1 and 0", len(createdEvents), propertyChangedEvents)
+ }
+ payload, ok := createdEvents[0].Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("issue:created payload = %#v", createdEvents[0].Payload)
+ }
+ issueSnapshot, ok := payload["issue"].(map[string]any)
+ if !ok {
+ t.Fatalf("issue:created issue snapshot = %#v", payload["issue"])
+ }
+ properties, ok := issueSnapshot["properties"].(map[string]any)
+ if !ok || properties[util.UUIDToString(propertyID)] != "ready" {
+ t.Fatalf("issue:created properties = %#v", issueSnapshot["properties"])
+ }
+}
+
func TestHydrateDeferredChannelIssueTaskOverlayDoesNotOverwriteMergedCommentPlan(t *testing.T) {
pool := newResolveOriginatorPool(t)
ctx := context.Background()
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 57f621021e..9b074e160f 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -226,10 +226,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage, last_activity_at, id
+ stage, properties, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16, now(), COALESCE($17::uuid, gen_random_uuid())
+ $16, COALESCE($17::jsonb, '{}'::jsonb), now(), COALESCE($18::uuid, gen_random_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, revision, last_activity_at, triage_state
`
@@ -250,6 +250,7 @@ type CreateIssueParams struct {
Number int32 `json:"number"`
ProjectID pgtype.UUID `json:"project_id"`
Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
ID pgtype.UUID `json:"id"`
}
@@ -271,6 +272,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
arg.Number,
arg.ProjectID,
arg.Stage,
+ arg.Properties,
arg.ID,
)
var i Issue
@@ -313,10 +315,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage, last_activity_at, id
+ origin_type, origin_id, stage, properties, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- $16, $17, $18, now(), COALESCE($19::uuid, gen_random_uuid())
+ $16, $17, $18, COALESCE($19::jsonb, '{}'::jsonb), now(), COALESCE($20::uuid, gen_random_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, revision, last_activity_at, triage_state
`
@@ -339,6 +341,7 @@ type CreateIssueWithOriginParams struct {
OriginType pgtype.Text `json:"origin_type"`
OriginID pgtype.UUID `json:"origin_id"`
Stage pgtype.Int4 `json:"stage"`
+ Properties []byte `json:"properties"`
ID pgtype.UUID `json:"id"`
}
@@ -362,6 +365,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
arg.OriginType,
arg.OriginID,
arg.Stage,
+ arg.Properties,
arg.ID,
)
var i Issue
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index f8085fb2f8..041ffa105a 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -182,10 +182,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- stage, last_activity_at, id
+ stage, properties, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('stage'), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
+ sqlc.narg('stage'), COALESCE(sqlc.narg('properties')::jsonb, '{}'::jsonb), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: GetIssueByNumber :one
@@ -317,10 +317,10 @@ INSERT INTO issue (
workspace_id, title, description, status, priority,
assignee_type, assignee_id, creator_type, creator_id,
parent_issue_id, position, start_date, due_date, number, project_id,
- origin_type, origin_id, stage, last_activity_at, id
+ origin_type, origin_id, stage, properties, last_activity_at, id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15,
- sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage'), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
+ sqlc.narg('origin_type'), sqlc.narg('origin_id'), sqlc.narg('stage'), COALESCE(sqlc.narg('properties')::jsonb, '{}'::jsonb), now(), COALESCE(sqlc.narg('id')::uuid, gen_random_uuid())
) RETURNING *;
-- name: LockIssueDuplicateKey :exec