Skip to content

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

Go

MUL-5839: preserve media in /issue descriptions (#6536)

YYClawd09019cd9549
diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
index 5bf890a44c..1890f86936 100644
--- a/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/edit.tsx
@@ -30,6 +30,7 @@ import {
} from "react-native";
import { Stack, router, useLocalSearchParams } from "expo-router";
import { useQuery } from "@tanstack/react-query";
+import { stripChannelMediaMarkers } from "@multica/core/types";
import { Text } from "@/components/ui/text";
import { DescriptionField } from "@/components/issue/description-field";
import { MentionSuggestionBar } from "@/components/issue/mention-suggestion-bar";
@@ -46,6 +47,7 @@ export default function EditIssue() {
const update = useUpdateIssue(id);
const [title, setTitle] = useState("");
+ const [descriptionBase, setDescriptionBase] = useState("");
const description = useMentionInput();
const [seeded, setSeeded] = useState(false);
// `useMentionInput` returns `setText` from `useState`, which is a stable
@@ -58,20 +60,22 @@ export default function EditIssue() {
useEffect(() => {
if (!detail.data || seeded) return;
setTitle(detail.data.title);
- setDescriptionText(detail.data.description ?? "");
+ const initial = detail.data.description ?? "";
+ setDescriptionText(stripChannelMediaMarkers(initial));
+ setDescriptionBase(initial);
setSeeded(true);
}, [detail.data, seeded, setDescriptionText]);
- const initialDescription = detail.data?.description ?? "";
const currentDescription = description.serialize();
const dirty = useMemo(() => {
if (!detail.data || !seeded) return false;
return (
title.trim() !== detail.data.title ||
- currentDescription.trim() !== initialDescription
+ currentDescription.trim() !==
+ stripChannelMediaMarkers(descriptionBase).trim()
);
- }, [detail.data, seeded, title, currentDescription, initialDescription]);
+ }, [detail.data, seeded, title, currentDescription, descriptionBase]);
const canSave =
seeded && title.trim().length > 0 && dirty && !update.isPending;
@@ -103,6 +107,7 @@ export default function EditIssue() {
const patch = {
title: title.trim(),
description: currentDescription.trim(),
+ description_base: descriptionBase,
};
update.mutate(patch, {
onSuccess: () => router.back(),
@@ -113,7 +118,7 @@ export default function EditIssue() {
);
},
});
- }, [canSave, title, currentDescription, update]);
+ }, [canSave, title, currentDescription, descriptionBase, update]);
const headerLeft = useCallback(
() => (
diff --git a/apps/mobile/data/mutations/issues.ts b/apps/mobile/data/mutations/issues.ts
index 35f0c58ad2..208b1fd270 100644
--- a/apps/mobile/data/mutations/issues.ts
+++ b/apps/mobile/data/mutations/issues.ts
@@ -410,7 +410,9 @@ export function useToggleIssueReaction(issueId: string) {
/**
* Update an issue's editable fields (status / priority / assignee / due_date /
- * project_id / etc). Optimistic merge into the detail cache; settle invalidates
+ * project_id / etc). Predictable fields merge optimistically into the detail
+ * cache; description stays authoritative because the server resolves it
+ * against description_base and hidden channel-media markers. Settle invalidates
* the my-issues list so a status change re-buckets the SectionList in
* (tabs)/my-issues.tsx automatically.
*
@@ -430,7 +432,12 @@ export function useUpdateIssue(issueId: string) {
await qc.cancelQueries({ queryKey: key });
const prev = qc.getQueryData<Issue>(key);
if (prev) {
- qc.setQueryData<Issue>(key, { ...prev, ...patch });
+ const {
+ description: _description,
+ description_base: _descriptionBase,
+ ...optimisticPatch
+ } = patch;
+ qc.setQueryData<Issue>(key, { ...prev, ...optimisticPatch });
}
return { prev, key };
},
diff --git a/apps/mobile/lib/markdown/preprocess.test.ts b/apps/mobile/lib/markdown/preprocess.test.ts
index bed209e3a3..b709cc4e4f 100644
--- a/apps/mobile/lib/markdown/preprocess.test.ts
+++ b/apps/mobile/lib/markdown/preprocess.test.ts
@@ -6,6 +6,13 @@ const ABS_URL = `https://multica-app.copilothub.ai/api/attachments/${UUID}/downl
const REL_URL = `/api/attachments/${UUID}/download`;
describe("preprocessMobileMarkdown — !file file cards", () => {
+ it("keeps channel images visible while hiding their provenance marker", () => {
+ const image = `![](${REL_URL})`;
+ const marker = `<!-- multica:channel-media:${UUID} -->`;
+
+ expect(preprocessMobileMarkdown(`${image}\n\n${marker}`)).toBe(`${image}\n\n`);
+ });
+
it("matches the CLI's escaped-bracket label and keeps it markdown-safe", () => {
// CLI emits `a]b.pdf` escaped as `a\]b.pdf` (cmd_attachment.go
// escapeMarkdownLabel). The old regex stopped at the first `]` and left the
diff --git a/packages/core/issues/mutations.test.tsx b/packages/core/issues/mutations.test.tsx
index b9708f4da6..76ca4f5dcb 100644
--- a/packages/core/issues/mutations.test.tsx
+++ b/packages/core/issues/mutations.test.tsx
@@ -479,6 +479,43 @@ describe("useUpdateIssue — optimistic move keeps every bucketed board in sync"
}
});
+ it("keeps the authoritative description base while a description update is pending", async () => {
+ let resolve!: (issue: Issue) => void;
+ updateIssue.mockReturnValue(
+ new Promise<Issue>((r) => {
+ resolve = r;
+ }),
+ );
+ const detailKey = issueKeys.detail(WS_ID, "issue-1");
+ qc.setQueryData<Issue>(detailKey, makeIssue(1, { description: "base" }));
+ const { result } = renderHook(() => useUpdateIssue(), {
+ wrapper: createWrapper(qc),
+ });
+
+ act(() => {
+ result.current.mutate({
+ id: "issue-1",
+ description: "local edit",
+ description_base: "base",
+ });
+ });
+
+ await waitFor(() => {
+ expect(updateIssue).toHaveBeenCalledWith("issue-1", {
+ description: "local edit",
+ description_base: "base",
+ });
+ });
+ const optimistic = qc.getQueryData<Issue & { description_base?: string }>(detailKey);
+ expect(optimistic?.description).toBe("base");
+ expect(optimistic).not.toHaveProperty("description_base");
+
+ await act(async () => {
+ resolve(makeIssue(1, { description: "local edit" }));
+ });
+ expect(qc.getQueryData<Issue>(detailKey)?.description).toBe("local edit");
+ });
+
it("uses server move intent while keeping provisional position optimistic-only", async () => {
moveIssue.mockResolvedValue(
makeIssue(1, { status: "in_progress", position: 15 }),
@@ -812,6 +849,48 @@ describe("useBatchUpdateIssues — optimistic patch covers filtered boards too",
}
});
+ it("does not optimistically replace description merge bases", async () => {
+ let resolve!: (r: { updated: number }) => void;
+ batchUpdateIssues.mockReturnValue(
+ new Promise<{ updated: number }>((r) => {
+ resolve = r;
+ }),
+ );
+ const detailKey = issueKeys.detail(WS_ID, "issue-1");
+ qc.setQueryData<Issue>(
+ detailKey,
+ makeIssue(1, { description: "base with marker" }),
+ );
+
+ const { result } = renderHook(() => useBatchUpdateIssues(), {
+ wrapper: createWrapper(qc),
+ });
+
+ act(() => {
+ result.current.mutate({
+ ids: ["issue-1"],
+ updates: {
+ description: "local edit",
+ description_base: "base with marker",
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(batchUpdateIssues).toHaveBeenCalledWith(["issue-1"], {
+ description: "local edit",
+ description_base: "base with marker",
+ });
+ });
+ expect(qc.getQueryData<Issue>(detailKey)?.description).toBe(
+ "base with marker",
+ );
+
+ await act(async () => {
+ resolve({ updated: 1 });
+ });
+ });
+
it("rolls both caches back when the request fails", async () => {
batchUpdateIssues.mockRejectedValue(new Error("boom"));
diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.ts
index 5862af2aa3..f16f302ab1 100644
--- a/packages/core/issues/mutations.ts
+++ b/packages/core/issues/mutations.ts
@@ -239,10 +239,18 @@ export function useUpdateIssue() {
},
onMutate: ({ id, move_intent: _moveIntent, ...data }) => {
// suppress_run / handoff_note are write-time control fields, not Issue
- // columns — they steer enqueue/injection on the server and must never be
- // written into the query cache (MUL-3375). Strip them from the patch; the
- // mutationFn above still sends the full payload to the API.
- const { suppress_run: _suppressRun, handoff_note: _handoffNote, ...patch } = data;
+ // columns. description_base is merge metadata, while description itself
+ // is resolved against that base on the server and therefore is not safe
+ // to predict optimistically. Keep the authoritative raw description in
+ // cache so hidden channel-media markers remain available as the base for
+ // a rapid follow-up edit. mutationFn still sends the full payload.
+ const {
+ suppress_run: _suppressRun,
+ handoff_note: _handoffNote,
+ description: _description,
+ description_base: _descriptionBase,
+ ...patch
+ } = data;
// Fire-and-forget cancelQueries — keeps onMutate synchronous so the
// cache update happens in the same tick as mutate(). Awaiting would
// yield to the event loop, letting @dnd-kit reset its visual state
@@ -338,6 +346,7 @@ export function useUpdateIssue() {
const {
suppress_run: _suppressRun,
handoff_note: _handoffNote,
+ description_base: _descriptionBase,
move_intent: _moveIntent,
id: _id,
...intent
@@ -510,9 +519,17 @@ export function useBatchUpdateIssues() {
updates: UpdateIssueRequest;
}) => api.batchUpdateIssues(ids, updates),
onMutate: async ({ ids, updates }) => {
- // Control fields steer the server; they are not Issue columns and must
- // not enter the cache (MUL-3375). mutationFn still sends them.
- const { suppress_run: _suppressRun, handoff_note: _handoffNote, ...patch } = updates;
+ // Control and description-merge fields are not safe optimistic cache
+ // patches. The server resolves description against description_base, so
+ // preserve the authoritative raw description (including media markers)
+ // until a refetch returns the committed result.
+ const {
+ suppress_run: _suppressRun,
+ handoff_note: _handoffNote,
+ description: _description,
+ description_base: _descriptionBase,
+ ...patch
+ } = updates;
await qc.cancelQueries({ queryKey: issueKeys.list(wsId) });
await qc.cancelQueries({ queryKey: issueKeys.myAll(wsId) });
await qc.cancelQueries({ queryKey: issueKeys.flatAll(wsId) });
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index 8ac5151690..262cf4f496 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -25,6 +25,9 @@ export interface CreateIssueRequest {
export interface UpdateIssueRequest {
title?: string;
description?: string;
+ /** Authoritative description the editor had adopted before producing this
+ * update. The server uses it to merge channel media that landed meanwhile. */
+ description_base?: string;
status?: IssueStatus;
priority?: IssuePriority;
assignee_type?: IssueAssigneeType | null;
diff --git a/packages/core/types/attachment-url.test.ts b/packages/core/types/attachment-url.test.ts
index 9e3fb5861c..ad3f2cd2bb 100644
--- a/packages/core/types/attachment-url.test.ts
+++ b/packages/core/types/attachment-url.test.ts
@@ -3,6 +3,7 @@ import {
attachmentDownloadPath,
attachmentIdFromDownloadURL,
contentReferencesAttachment,
+ stripChannelMediaMarkers,
} from "./attachment-url";
const ID = "11111111-2222-3333-4444-555555555555";
@@ -13,6 +14,21 @@ describe("attachmentDownloadPath", () => {
});
});
+describe("stripChannelMediaMarkers", () => {
+ it("removes provenance while retaining the visible channel image", () => {
+ const image = `![](${attachmentDownloadPath(ID)})`;
+ const marker = `<!-- multica:channel-media:${ID} -->`;
+
+ expect(stripChannelMediaMarkers(`${image}\n\n${marker}`)).toBe(`${image}\n\n`);
+ });
+
+ it("leaves unrelated HTML comments untouched", () => {
+ expect(stripChannelMediaMarkers("before <!-- user note --> after")).toBe(
+ "before <!-- user note --> after",
+ );
+ });
+});
+
describe("attachmentIdFromDownloadURL", () => {
it("extracts the id from a site-relative path", () => {
expect(attachmentIdFromDownloadURL(`/api/attachments/${ID}/download`)).toBe(ID);
diff --git a/packages/core/types/attachment-url.ts b/packages/core/types/attachment-url.ts
index 9d93753d4c..9f73af8854 100644
--- a/packages/core/types/attachment-url.ts
+++ b/packages/core/types/attachment-url.ts
@@ -23,6 +23,14 @@
const DOWNLOAD_PREFIX = "/api/attachments/";
const DOWNLOAD_SUFFIX = "/download";
+const CHANNEL_MEDIA_MARKER_RE =
+ /<!-- multica:channel-media:[0-9a-fA-F-]{36} -->/g;
+
+/** Remove server-owned channel-media merge metadata from editable or rendered
+ * Markdown while leaving the visible attachment link untouched. */
+export function stripChannelMediaMarkers(content: string): string {
+ return content.replace(CHANNEL_MEDIA_MARKER_RE, "");
+}
/**
* UUID literal regex (RFC 4122 form). Used to extract an attachment id
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 2fcd3904c3..a1bbe74c16 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -111,7 +111,12 @@ export type { IssueSubscriber } from "./subscriber";
export type * from "./events";
export type * from "./api";
export type { Attachment } from "./attachment";
-export { attachmentDownloadPath, attachmentIdFromDownloadURL, contentReferencesAttachment } from "./attachment-url";
+export {
+ attachmentDownloadPath,
+ attachmentIdFromDownloadURL,
+ contentReferencesAttachment,
+ stripChannelMediaMarkers,
+} from "./attachment-url";
export type {
ChatSession,
ChatLastMessage,
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsx
index 98b2028b42..ee99da5a77 100644
--- a/packages/views/editor/content-editor.test.tsx
+++ b/packages/views/editor/content-editor.test.tsx
@@ -360,6 +360,33 @@ describe("ContentEditor", () => {
expect(mockSetContent).not.toHaveBeenCalled();
});
+ it("emits the adopted base when a dirty editor skips a newer server value", () => {
+ vi.useFakeTimers();
+ const onUpdate = vi.fn();
+ editorState.markdown = "old content";
+ const { rerender } = render(
+ <ContentEditor value="old content" onUpdate={onUpdate} debounceMs={100} />,
+ );
+
+ editorState.isFocused = true;
+ editorState.markdown = "local edit";
+ rerender(
+ <ContentEditor
+ value="old content\n\nremote channel image"
+ onUpdate={onUpdate}
+ debounceMs={100}
+ />,
+ );
+ expect(mockSetContent).not.toHaveBeenCalled();
+
+ act(() => {
+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(onUpdate).toHaveBeenCalledWith("local edit", "old content");
+ });
+
// flushPendingUpdate exists for hosts that re-point ONE editor instance at a
// different destination mid-debounce (chat swapping draftKey between
// sessions). Without it the armed debounce fires after the switch and, since
@@ -503,6 +530,7 @@ describe("ContentEditor", () => {
expect(onUpdate).toHaveBeenCalledTimes(1);
expect(onUpdate).toHaveBeenCalledWith(
"old content\n\n![shot](/api/attachments/att-1/download)",
+ "old content",
);
act(() => {
vi.advanceTimersByTime(1500);
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 1ab3155c24..54d0298bc5 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -120,7 +120,13 @@ function hasUploadingNode(editor: Editor): boolean {
// ---------------------------------------------------------------------------
interface ContentEditorBaseProps {
- onUpdate?: (markdown: string) => void;
+ /**
+ * `baseMarkdown` is the last authoritative controlled value this editor
+ * actually adopted before producing `markdown`. A dirty-editor realtime
+ * guard may intentionally skip newer server content, so callers must not
+ * substitute the latest prop value for this base.
+ */
+ onUpdate?: (markdown: string, baseMarkdown: string) => void;
placeholder?: string;
className?: string;
debounceMs?: number;
@@ -382,6 +388,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// unmount flush emits this cached copy — it runs mid-teardown and can't
// assume the editor instance is still readable.
const pendingFlushRef = useRef<string | null>(null);
+ const pendingBaseRef = useRef<string | null>(null);
const onUpdateRef = useRef(onUpdate);
const onSubmitRef = useRef(onSubmit);
const onBlurRef = useRef(onBlur);
@@ -404,6 +411,11 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// mounts. Track later changes separately so the sync effect does not parse
// the initial document twice when Markdown serialization canonicalizes it.
const lastSyncedValueRef = useRef(value);
+ // Authoritative Markdown behind the document the user is editing. Keep the
+ // raw controlled value rather than the editor serialization: Tiptap may
+ // omit invisible channel-media provenance comments while retaining the
+ // visible image, and the server needs those comments in the merge base.
+ const documentBaseRef = useRef(normalizeMarkdown(value ?? defaultValue ?? ""));
// Live placeholder text. Passed into the Placeholder extension as a getter
// (not a static string) so the plugin re-reads it on every decoration pass —
// the sync effect below updates this ref and nudges a repaint. Tiptap
@@ -608,6 +620,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
}),
onUpdate: ({ editor: ed }) => {
if (!onUpdateRef.current) return;
+ pendingBaseRef.current = documentBaseRef.current;
if (flushPendingOnUnmountRef.current) {
pendingFlushRef.current = normalizeEditorMarkdown(ed);
}
@@ -615,10 +628,12 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
debounceRef.current = setTimeout(() => {
debounceRef.current = undefined;
pendingFlushRef.current = null;
+ const base = pendingBaseRef.current ?? documentBaseRef.current;
+ pendingBaseRef.current = null;
const md = normalizeEditorMarkdown(ed);
if (md === lastEmittedRef.current) return;
lastEmittedRef.current = md;
- onUpdateRef.current?.(md);
+ onUpdateRef.current?.(md, base);
}, debounceMs);
},
onBlur: () => {
@@ -705,10 +720,12 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
debounceRef.current = undefined;
if (!flushPendingOnUnmountRef.current) return;
const pending = pendingFlushRef.current;
+ const base = pendingBaseRef.current ?? documentBaseRef.current;
pendingFlushRef.current = null;
+ pendingBaseRef.current = null;
if (pending === null || pending === lastEmittedRef.current) return;
lastEmittedRef.current = pending;
- onUpdateRef.current?.(pending);
+ onUpdateRef.current?.(pending, base);
};
}, []);
@@ -720,6 +737,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const applyExternalContent = useCallback(
(markdown: string) => {
if (!editor || editor.isDestroyed) return;
+ documentBaseRef.current = normalizeMarkdown(markdown);
const before = normalizeEditorMarkdown(editor);
// A controlled host commonly echoes the exact Markdown this editor
@@ -916,6 +934,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
clearTimeout(debounceRef.current);
debounceRef.current = undefined;
pendingFlushRef.current = null;
+ pendingBaseRef.current = null;
if (!editor || editor.isDestroyed) return null;
// Read the live document: unlike the unmount flush, the instance is
// still alive here, so this is the freshest possible copy.
diff --git a/packages/views/editor/utils/preprocess-channel-media.test.ts b/packages/views/editor/utils/preprocess-channel-media.test.ts
new file mode 100644
index 0000000000..e33e32b187
--- /dev/null
+++ b/packages/views/editor/utils/preprocess-channel-media.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from "vitest";
+
+import { preprocessMarkdown } from "./preprocess";
+
+describe("preprocessMarkdown channel-media provenance", () => {
+ it("keeps the image visible while hiding its merge marker", () => {
+ const id = "22222222-2222-4222-8222-222222222222";
+ const image = `![](/api/attachments/${id}/download)`;
+ const marker = `<!-- multica:channel-media:${id} -->`;
+
+ const result = preprocessMarkdown(`${image}\n\n${marker}`, { cdnDomain: "" });
+
+ expect(result).toContain(image);
+ expect(result).not.toContain("multica:channel-media");
+ });
+});
diff --git a/packages/views/editor/utils/preprocess.ts b/packages/views/editor/utils/preprocess.ts
index 61f5aefa7e..66738a1068 100644
--- a/packages/views/editor/utils/preprocess.ts
+++ b/packages/views/editor/utils/preprocess.ts
@@ -4,6 +4,7 @@ import {
preprocessFileCards,
preprocessIssueIdentifiers,
} from "@multica/ui/markdown";
+import { stripChannelMediaMarkers } from "@multica/core/types";
/**
* Preprocess a markdown string before loading into Tiptap via contentType: 'markdown'.
@@ -43,7 +44,12 @@ export function preprocessMarkdown(
): string {
if (!markdown) return "";
const { cdnDomain } = opts;
- const step1 = preprocessMentionShortcodes(markdown);
+ // Channel-media provenance is persisted for optimistic merge safety, not
+ // authored content. Remove only this namespaced comment before either the
+ // editable Tiptap parser or readonly renderer sees it; the ContentEditor
+ // separately retains the raw controlled value as its server merge base.
+ const visibleMarkdown = stripChannelMediaMarkers(markdown);
+ const step1 = preprocessMentionShortcodes(visibleMarkdown);
const step2 = opts?.autolinkIssueIdentifiers
? preprocessIssueIdentifiers(step1)
: step1;
diff --git a/packages/views/issues/components/board-card-description-preview.test.ts b/packages/views/issues/components/board-card-description-preview.test.ts
new file mode 100644
index 0000000000..901760bfff
--- /dev/null
+++ b/packages/views/issues/components/board-card-description-preview.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+
+import { descriptionPreview } from "./board-card";
+
+const ATTACHMENT_ID = "0f8a1b2c-3d4e-4f50-9a6b-7c8d9e0f1a2b";
+const IMAGE = `![](/api/attachments/${ATTACHMENT_ID}/download)`;
+const MARKER = `<!-- multica:channel-media:${ATTACHMENT_ID} -->`;
+
+describe("descriptionPreview", () => {
+ // A `/issue` message carrying an image materializes into image Markdown plus
+ // an invisible provenance marker. The image pass drops the picture, so the
+ // marker must be stripped too or it becomes the card's visible preview text.
+ it("hides the channel-media marker that outlives the image it annotates", () => {
+ expect(descriptionPreview(`Ordered rich text\n\n${IMAGE}\n\n${MARKER}`)).toBe(
+ "Ordered rich text",
+ );
+ });
+
+ it("previews nothing for an image-only channel description", () => {
+ expect(descriptionPreview(`${IMAGE}\n\n${MARKER}`)).toBe("");
+ });
+
+ it("still flattens ordinary markdown to a single line", () => {
+ expect(
+ descriptionPreview("# Title\n\n**bold** text and [a link](https://example.com)"),
+ ).toBe("Title bold text and a link");
+ });
+});
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 9ca760412b..46f209a790 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -6,6 +6,7 @@ import { useSortable, defaultAnimateLayoutChanges } from "@dnd-kit/sortable";
import type { AnimateLayoutChanges } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import type { Issue, IssueProperty, Project, UpdateIssueRequest } from "@multica/core/types";
+import { stripChannelMediaMarkers } from "@multica/core/types";
import { useQuery } from "@tanstack/react-query";
import { useWorkspaceId } from "@multica/core/hooks";
import { propertyListOptions } from "@multica/core/properties";
@@ -33,8 +34,13 @@ function formatDate(date: string): string {
return formatDateOnly(date, { month: "short", day: "numeric" }, "en-US");
}
-function descriptionPreview(markdown: string): string {
- return markdown
+// Flatten description Markdown into the card's one-line preview. Channel-media
+// provenance is server-owned merge metadata, not authored content, so it is
+// stripped first: the image Markdown it annotates is removed a line below, and
+// without this the bare HTML comment survives every remaining pass and becomes
+// visible preview text. Exported for tests.
+export function descriptionPreview(markdown: string): string {
+ return stripChannelMediaMarkers(markdown)
.replace(/!file\[[^\]]*\]\([^)]*\)/g, "")
.replace(/!\[[^\]]*\]\([^)]*\)/g, "")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 7a9a364059..2e16456506 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -180,6 +180,7 @@ vi.mock("../../editor", async () => ({
) {
const initialValue = syncedValue ?? defaultValue ?? "";
const valueRef = useRef(initialValue);
+ const baseRef = useRef(initialValue);
const [editorValue, setEditorValue] = useState(initialValue);
useEffect(() => {
contentEditorMounts.count += 1;
@@ -189,6 +190,7 @@ vi.mock("../../editor", async () => ({
useEffect(() => {
if (syncedValue === undefined) return;
valueRef.current = syncedValue;
+ baseRef.current = syncedValue;
setEditorValue(syncedValue);
}, [syncedValue]);
useImperativeHandle(ref, () => ({
@@ -213,7 +215,7 @@ vi.mock("../../editor", async () => ({
onChange={(e) => {
valueRef.current = e.target.value;
setEditorValue(e.target.value);
- onUpdate?.(e.target.value);
+ onUpdate?.(e.target.value, baseRef.current);
}}
placeholder={placeholder}
data-testid="rich-text-editor"
@@ -1589,7 +1591,10 @@ describe("IssueDetail (shared)", () => {
await waitFor(() => {
expect(mockApiObj.updateIssue).toHaveBeenCalledWith(
"issue-1",
- expect.objectContaining({ description: "" }),
+ expect.objectContaining({
+ description: "",
+ description_base: "Add JWT auth to the backend",
+ }),
);
});
});
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 78a545eb74..b194b5dc1e 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -2603,7 +2603,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
key={id}
value={issue.description || ""}
placeholder={t(($) => $.detail.desc_placeholder)}
- onUpdate={(md) => {
+ onUpdate={(md, baseMarkdown) => {
// Bind any pending uploads still referenced in the markdown
// so they appear in `issueAttachments` after refresh and the
// editor's text/code preview keeps working past reload.
@@ -2624,7 +2624,11 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const ids = descPendingAttachmentsRef.current
.filter((a) => contentReferencesAttachment(md, a))
.map((a) => a.id);
- handleUpdateField({ description: md, attachment_ids: ids.length > 0 ? ids : undefined });
+ handleUpdateField({
+ description: md,
+ description_base: baseMarkdown,
+ attachment_ids: ids.length > 0 ? ids : undefined,
+ });
}}
onUploadFile={handleDescriptionUpload}
debounceMs={1500}
diff --git a/server/internal/channelmedia/markdown.go b/server/internal/channelmedia/markdown.go
new file mode 100644
index 0000000000..dbc095e425
--- /dev/null
+++ b/server/internal/channelmedia/markdown.go
@@ -0,0 +1,83 @@
+package channelmedia
+
+import (
+ "regexp"
+ "strings"
+
+ "github.com/google/uuid"
+)
+
+const markerPrefix = "<!-- multica:channel-media:"
+
+var markerPattern = regexp.MustCompile(`<!-- multica:channel-media:([0-9a-fA-F-]{36}) -->`)
+
+// DownloadPath is the durable, authorization-aware attachment URL persisted in
+// issue and chat Markdown.
+func DownloadPath(id string) string {
+ return "/api/attachments/" + id + "/download"
+}
+
+// Marker records that a Markdown attachment was materialized asynchronously by
+// channel ingestion. Markdown renderers ignore the comment, while issue updates
+// use it to distinguish a late channel-media write from an intentional edit.
+func Marker(id string) string {
+ return markerPrefix + id + " -->"
+}
+
+// Block renders one channel attachment plus its durable provenance marker.
+func Block(id, filename string, image bool) string {
+ downloadPath := DownloadPath(id)
+ var markdown string
+ if image {
+ markdown = "![](" + downloadPath + ")"
+ } else {
+ label := strings.NewReplacer(
+ "\\", "\\\\",
+ "[", "\\[",
+ "]", "\\]",
+ "\r", " ",
+ "\n", " ",
+ ).Replace(filename)
+ if label == "" {
+ label = "attachment"
+ }
+ markdown = "[" + label + "](" + downloadPath + ")"
+ }
+ return markdown + "\n\n" + Marker(id)
+}
+
+// MarkedIDs returns valid channel-media attachment ids in document order,
+// de-duplicated. Invalid marker-shaped comments are ignored.
+func MarkedIDs(markdown string) []string {
+ matches := markerPattern.FindAllStringSubmatch(markdown, -1)
+ ids := make([]string, 0, len(matches))
+ seen := make(map[string]bool, len(matches))
+ for _, match := range matches {
+ parsed, err := uuid.Parse(match[1])
+ if err != nil {
+ continue
+ }
+ id := parsed.String()
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+ ids = append(ids, id)
+ }
+ return ids
+}
+
+// HasMarker reports whether markdown already carries the provenance marker for
+// id. It deliberately does not treat a bare attachment URL as provenance.
+func HasMarker(markdown, id string) bool {
+ return strings.Contains(markdown, Marker(id))
+}
+
+// Append adds a Markdown block using the same spacing contract as issue media
+// materialization.
+func Append(markdown, block string) string {
+ if markdown == "" {
+ return block
+ }
+ return markdown + "\n\n" + block
+}
diff --git a/server/internal/channelmedia/markdown_test.go b/server/internal/channelmedia/markdown_test.go
new file mode 100644
index 0000000000..bbffad8c17
--- /dev/null
+++ b/server/internal/channelmedia/markdown_test.go
@@ -0,0 +1,38 @@
+package channelmedia
+
+import (
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func TestBlockCarriesInvisibleProvenance(t *testing.T) {
+ const id = "22222222-2222-4222-8222-222222222222"
+ block := Block(id, "diagram.png", true)
+ if !strings.Contains(block, "![]("+DownloadPath(id)+")") {
+ t.Fatalf("image block = %q", block)
+ }
+ if !HasMarker(block, id) {
+ t.Fatalf("image block has no provenance marker: %q", block)
+ }
+ if got := MarkedIDs(block); !reflect.DeepEqual(got, []string{id}) {
+ t.Fatalf("marked ids = %v, want [%s]", got, id)
+ }
+}
+
+func TestBlockEscapesFileLabelAndFlattensNewlines(t *testing.T) {
+ const id = "33333333-3333-4333-8333-333333333333"
+ block := Block(id, "a[b]\nreport.pdf", false)
+ wantLink := "[a\\[b\\] report.pdf](" + DownloadPath(id) + ")"
+ if !strings.Contains(block, wantLink) {
+ t.Fatalf("file block = %q, want link %q", block, wantLink)
+ }
+}
+
+func TestMarkedIDsIgnoresInvalidAndDeduplicates(t *testing.T) {
+ const id = "44444444-4444-4444-8444-444444444444"
+ markdown := Marker(id) + "\n" + Marker("not-a-uuid") + "\n" + Marker(id)
+ if got := MarkedIDs(markdown); !reflect.DeepEqual(got, []string{id}) {
+ t.Fatalf("marked ids = %v, want [%s]", got, id)
+ }
+}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index d4935b4de4..4e0979b132 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -18,6 +18,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/dispatch"
"github.com/multica-ai/multica/server/internal/issueguard"
"github.com/multica-ai/multica/server/internal/logger"
@@ -2707,18 +2708,24 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
}
type UpdateIssueRequest struct {
- Title *string `json:"title"`
- Description *string `json:"description"`
- Status *string `json:"status"`
- Priority *string `json:"priority"`
- AssigneeType *string `json:"assignee_type"`
- AssigneeID *string `json:"assignee_id"`
- Position *float64 `json:"position"`
- StartDate *string `json:"start_date"`
- DueDate *string `json:"due_date"`
- ParentIssueID *string `json:"parent_issue_id"`
- ProjectID *string `json:"project_id"`
- Stage *int32 `json:"stage"`
+ Title *string `json:"title"`
+ Description *string `json:"description"`
+ // DescriptionBase is the authoritative Markdown the editor had adopted
+ // before producing Description. It lets the server preserve channel media
+ // that landed asynchronously after that base without making media already
+ // present in the base impossible for the user to delete. Older clients omit
+ // it and receive conservative channel-media preservation.
+ DescriptionBase *string `json:"description_base,omitempty"`
+ Status *string `json:"status"`
+ Priority *string `json:"priority"`
+ AssigneeType *string `json:"assignee_type"`
+ AssigneeID *string `json:"assignee_id"`
+ Position *float64 `json:"position"`
+ StartDate *string `json:"start_date"`
+ DueDate *string `json:"due_date"`
+ ParentIssueID *string `json:"parent_issue_id"`
+ ProjectID *string `json:"project_id"`
+ Stage *int32 `json:"stage"`
// AttachmentIDs lets the description editor bind newly uploaded files to
// this issue so they surface in `GET /api/issues/:id/attachments` and the
// editor's preview Eye keeps working past a refresh. Existing bindings
@@ -2737,6 +2744,133 @@ type UpdateIssueRequest struct {
HandoffNote string `json:"handoff_note,omitempty"`
}
+func mergeIssueChannelMediaDescription(current, incoming string, base *string, attachments []db.Attachment) string {
+ currentIDs := channelmedia.MarkedIDs(current)
+ if len(currentIDs) == 0 {
+ return incoming
+ }
+
+ baseIDs := map[string]bool{}
+ if base != nil {
+ for _, id := range channelmedia.MarkedIDs(*base) {
+ baseIDs[id] = true
+ }
+ }
+ attachmentsByID := make(map[string]db.Attachment, len(attachments))
+ for _, attachment := range attachments {
+ attachmentsByID[uuidToString(attachment.ID)] = attachment
+ }
+
+ merged := incoming
+ for _, id := range currentIDs {
+ attachment, exists := attachmentsByID[id]
+ if !exists {
+ // A deleted attachment must not be resurrected from stale Markdown.
+ continue
+ }
+ downloadPath := channelmedia.DownloadPath(id)
+ hasLink := strings.Contains(merged, downloadPath)
+ knownToEditor := base != nil && baseIDs[id]
+ if knownToEditor && !hasLink {
+ // The editor adopted this media and then removed its link: preserve
+ // the user's explicit deletion rather than treating it as a race.
+ continue
+ }
+ if !hasLink {
+ merged = channelmedia.Append(merged, channelmedia.Block(
+ id,
+ attachment.Filename,
+ strings.HasPrefix(attachment.ContentType, "image/"),
+ ))
+ continue
+ }
+ // Tiptap may omit HTML comments when serializing an otherwise intact
+ // image. Restore provenance without duplicating the visible link.
+ if !channelmedia.HasMarker(merged, id) {
+ merged = channelmedia.Append(merged, channelmedia.Marker(id))
+ }
+ }
+ return merged
+}
+
+func refreshUntouchedNullableIssueParams(params *db.UpdateIssueParams, current db.Issue, rawFields map[string]json.RawMessage) {
+ _, assigneeTypeTouched := rawFields["assignee_type"]
+ _, assigneeIDTouched := rawFields["assignee_id"]
+ // Assignee type and id form one validated value. If either half was
+ // supplied, retain the pre-validation counterpart in params rather than
+ // combining the supplied half with a concurrently-written counterpart that
+ // has never been validated with it.
+ if !assigneeTypeTouched && !assigneeIDTouched {
+ params.AssigneeType = current.AssigneeType
+ params.AssigneeID = current.AssigneeID
+ }
+ if _, touched := rawFields["start_date"]; !touched {
+ params.StartDate = current.StartDate
+ }
+ if _, touched := rawFields["due_date"]; !touched {
+ params.DueDate = current.DueDate
+ }
+ if _, touched := rawFields["parent_issue_id"]; !touched {
+ params.ParentIssueID = current.ParentIssueID
+ }
+ if _, touched := rawFields["project_id"]; !touched {
+ params.ProjectID = current.ProjectID
+ }
+ if _, touched := rawFields["stage"]; !touched {
+ params.Stage = current.Stage
+ }
+}
+
+func (h *Handler) updateIssueWithDescriptionMerge(ctx context.Context, workspaceID pgtype.UUID, params db.UpdateIssueParams, rawFields map[string]json.RawMessage, base *string) (db.Issue, db.Issue, error) {
+ if h.TxStarter == nil {
+ return db.Issue{}, db.Issue{}, errors.New("issue description update requires transaction starter")
+ }
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.Issue{}, db.Issue{}, fmt.Errorf("begin issue description update: %w", err)
+ }
+ defer tx.Rollback(ctx)
+
+ qtx := h.Queries.WithTx(tx)
+ current, err := qtx.LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
+ ID: params.ID,
+ WorkspaceID: workspaceID,
+ })
+ if err != nil {
+ return db.Issue{}, db.Issue{}, fmt.Errorf("lock issue description: %w", err)
+ }
+ attachments, err := qtx.ListAttachmentsByIssue(ctx, db.ListAttachmentsByIssueParams{
+ IssueID: current.ID,
+ WorkspaceID: current.WorkspaceID,
+ })
+ if err != nil {
+ return db.Issue{}, db.Issue{}, fmt.Errorf("list issue attachments for description merge: %w", err)
+ }
+
+ currentDescription := ""
+ if current.Description.Valid {
+ currentDescription = current.Description.String
+ }
+ incomingDescription := ""
+ if params.Description.Valid {
+ incomingDescription = params.Description.String
+ }
+ params.Description = pgtype.Text{
+ String: mergeIssueChannelMediaDescription(currentDescription, incomingDescription, base, attachments),
+ Valid: true,
+ }
+ refreshUntouchedNullableIssueParams(&params, current, rawFields)
+
+ issue, err := qtx.UpdateIssue(ctx, params)
+ if err != nil {
+ return db.Issue{}, db.Issue{}, fmt.Errorf("update locked issue description: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.Issue{}, db.Issue{}, fmt.Errorf("commit issue description update: %w", err)
+ }
+ return issue, current, nil
+}
+
func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
prevIssue, ok := h.loadIssueForUser(w, r, id)
@@ -2919,7 +3053,18 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
return
}
- issue, err := h.Queries.UpdateIssue(r.Context(), params)
+ var issue db.Issue
+ if req.Description != nil {
+ var lockedPrev db.Issue
+ issue, lockedPrev, err = h.updateIssueWithDescriptionMerge(
+ r.Context(), prevIssue.WorkspaceID, params, rawFields, req.DescriptionBase,
+ )
+ if err == nil {
+ prevIssue = lockedPrev
+ }
+ } else {
+ issue, err = h.Queries.UpdateIssue(r.Context(), params)
+ }
if err != nil {
slog.Warn("update issue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", id, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to update issue: "+err.Error())
@@ -3491,7 +3636,21 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
}
}
- issue, err := h.Queries.UpdateIssue(r.Context(), params)
+ var issue db.Issue
+ if req.Updates.Description != nil {
+ // One batch-level base cannot describe multiple issue documents.
+ // Preserve every marked channel-media block conservatively, matching
+ // legacy single-update clients that omit description_base.
+ var lockedPrev db.Issue
+ issue, lockedPrev, err = h.updateIssueWithDescriptionMerge(
+ r.Context(), prevIssue.WorkspaceID, params, rawUpdates, nil,
+ )
+ if err == nil {
+ prevIssue = lockedPrev
+ }
+ } else {
+ issue, err = h.Queries.UpdateIssue(r.Context(), params)
+ }
if err != nil {
slog.Warn("batch update issue failed", "issue_id", issueID, "error", err)
continue
diff --git a/server/internal/handler/issue_channel_media_merge_test.go b/server/internal/handler/issue_channel_media_merge_test.go
new file mode 100644
index 0000000000..e421da8f33
--- /dev/null
+++ b/server/internal/handler/issue_channel_media_merge_test.go
@@ -0,0 +1,327 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/channelmedia"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestMergeIssueChannelMediaDescriptionProtectsLegacyClient(t *testing.T) {
+ const id = "22222222-2222-4222-8222-222222222222"
+ block := channelmedia.Block(id, "diagram.png", true)
+ current := channelmedia.Append("Original", block)
+ attachmentID := pgtype.UUID{Bytes: uuid.MustParse(id), Valid: true}
+
+ got := mergeIssueChannelMediaDescription(current, "Original with local edit", nil, []db.Attachment{{
+ ID: attachmentID, Filename: "diagram.png", ContentType: "image/png",
+ }})
+ want := channelmedia.Append("Original with local edit", block)
+ if got != want {
+ t.Fatalf("merged description = %q, want %q", got, want)
+ }
+}
+
+func TestMergeIssueChannelMediaDescriptionAllowsKnownMediaDeletion(t *testing.T) {
+ const id = "33333333-3333-4333-8333-333333333333"
+ current := channelmedia.Append("Original", channelmedia.Block(id, "diagram.png", true))
+ attachmentID := pgtype.UUID{Bytes: uuid.MustParse(id), Valid: true}
+
+ got := mergeIssueChannelMediaDescription(current, "Original without image", &current, []db.Attachment{{
+ ID: attachmentID, Filename: "diagram.png", ContentType: "image/png",
+ }})
+ if got != "Original without image" {
+ t.Fatalf("explicit deletion was not preserved: %q", got)
+ }
+}
+
+func TestMergeIssueChannelMediaDescriptionRestoresMarkerForRetainedLink(t *testing.T) {
+ const id = "55555555-5555-4555-8555-555555555555"
+ current := channelmedia.Append("Original", channelmedia.Block(id, "diagram.png", true))
+ attachmentID := pgtype.UUID{Bytes: uuid.MustParse(id), Valid: true}
+ incoming := channelmedia.Append("Local edit", "![]("+channelmedia.DownloadPath(id)+")")
+
+ got := mergeIssueChannelMediaDescription(current, incoming, &current, []db.Attachment{{
+ ID: attachmentID, Filename: "diagram.png", ContentType: "image/png",
+ }})
+ if !strings.Contains(got, incoming) || !channelmedia.HasMarker(got, id) {
+ t.Fatalf("retained media lost provenance: %q", got)
+ }
+}
+
+func TestMergeIssueChannelMediaDescriptionDoesNotResurrectDeletedAttachment(t *testing.T) {
+ const id = "66666666-6666-4666-8666-666666666666"
+ current := channelmedia.Append("Original", channelmedia.Block(id, "diagram.png", true))
+
+ got := mergeIssueChannelMediaDescription(current, "Local edit", nil, nil)
+ if got != "Local edit" {
+ t.Fatalf("deleted attachment was resurrected: %q", got)
+ }
+}
+
+func TestRefreshUntouchedNullableIssueParamsKeepsValidatedAssigneePair(t *testing.T) {
+ oldID := pgtype.UUID{Bytes: uuid.MustParse("77777777-7777-4777-8777-777777777777"), Valid: true}
+ concurrentID := pgtype.UUID{Bytes: uuid.MustParse("88888888-8888-4888-8888-888888888888"), Valid: true}
+ params := db.UpdateIssueParams{
+ AssigneeType: pgtype.Text{String: "member", Valid: true},
+ AssigneeID: oldID,
+ }
+ current := db.Issue{
+ AssigneeType: pgtype.Text{String: "agent", Valid: true},
+ AssigneeID: concurrentID,
+ }
+
+ refreshUntouchedNullableIssueParams(&params, current, map[string]json.RawMessage{
+ "assignee_id": json.RawMessage(`"77777777-7777-4777-8777-777777777777"`),
+ })
+
+ if params.AssigneeType.String != "member" || params.AssigneeID != oldID {
+ t.Fatalf("validated assignee pair was recombined: type=%#v id=%#v", params.AssigneeType, params.AssigneeID)
+ }
+}
+
+func TestUpdateIssueMergesChannelMediaAppendedAfterEditorBase(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("requires test database")
+ }
+ ctx := context.Background()
+
+ create := httptest.NewRecorder()
+ createReq := newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Channel media description merge",
+ "description": "Original",
+ "status": "todo",
+ "priority": "none",
+ })
+ testHandler.CreateIssue(create, createReq)
+ if create.Code != http.StatusCreated {
+ t.Fatalf("create issue: status %d: %s", create.Code, create.Body.String())
+ }
+ var created IssueResponse
+ if err := json.NewDecoder(create.Body).Decode(&created); err != nil {
+ t.Fatalf("decode created issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, created.ID)
+ })
+
+ attachmentID := uuid.New().String()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO attachment (
+ id, workspace_id, issue_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ ) VALUES ($1, $2, $3, 'member', $4, 'diagram.png', $5, 'image/png', 3)
+ `, attachmentID, testWorkspaceID, created.ID, testUserID, "https://cdn.example.test/"+attachmentID); err != nil {
+ t.Fatalf("insert channel attachment: %v", err)
+ }
+ block := channelmedia.Block(attachmentID, "diagram.png", true)
+ remoteDescription := channelmedia.Append("Original", block)
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET description = $1, updated_at = now() WHERE id = $2`, remoteDescription, created.ID); err != nil {
+ t.Fatalf("append remote channel media: %v", err)
+ }
+
+ update := httptest.NewRecorder()
+ updateReq := newRequest(http.MethodPut, "/api/issues/"+created.ID, map[string]any{
+ "description": "Original with local edit",
+ "description_base": "Original",
+ })
+ updateReq = withURLParam(updateReq, "id", created.ID)
+ testHandler.UpdateIssue(update, updateReq)
+ if update.Code != http.StatusOK {
+ t.Fatalf("update issue: status %d: %s", update.Code, update.Body.String())
+ }
+ var merged IssueResponse
+ if err := json.NewDecoder(update.Body).Decode(&merged); err != nil {
+ t.Fatalf("decode merged issue: %v", err)
+ }
+ if merged.Description == nil || !strings.Contains(*merged.Description, "Original with local edit") || !strings.Contains(*merged.Description, channelmedia.DownloadPath(attachmentID)) {
+ t.Fatalf("merged description = %#v", merged.Description)
+ }
+
+ // Once the client has adopted the media-bearing description as its base,
+ // removing the image is an explicit edit and must remain possible.
+ remove := httptest.NewRecorder()
+ removeReq := newRequest(http.MethodPut, "/api/issues/"+created.ID, map[string]any{
+ "description": "Original with local edit",
+ "description_base": *merged.Description,
+ })
+ removeReq = withURLParam(removeReq, "id", created.ID)
+ testHandler.UpdateIssue(remove, removeReq)
+ if remove.Code != http.StatusOK {
+ t.Fatalf("remove image: status %d: %s", remove.Code, remove.Body.String())
+ }
+ var removed IssueResponse
+ if err := json.NewDecoder(remove.Body).Decode(&removed); err != nil {
+ t.Fatalf("decode image removal: %v", err)
+ }
+ if removed.Description == nil || *removed.Description != "Original with local edit" {
+ t.Fatalf("description after explicit image removal = %#v", removed.Description)
+ }
+}
+
+func TestBatchUpdateIssuePreservesMarkedChannelMedia(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("requires test database")
+ }
+ ctx := context.Background()
+
+ create := httptest.NewRecorder()
+ createReq := newRequest(http.MethodPost, "/api/issues?workspace_id="+testWorkspaceID, map[string]any{
+ "title": "Batch channel media merge",
+ "description": "Original",
+ "status": "todo",
+ "priority": "none",
+ })
+ testHandler.CreateIssue(create, createReq)
+ if create.Code != http.StatusCreated {
+ t.Fatalf("create issue: status %d: %s", create.Code, create.Body.String())
+ }
+ var created IssueResponse
+ if err := json.NewDecoder(create.Body).Decode(&created); err != nil {
+ t.Fatalf("decode created issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, created.ID)
+ })
+
+ attachmentID := uuid.New().String()
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO attachment (
+ id, workspace_id, issue_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ ) VALUES ($1, $2, $3, 'member', $4, 'diagram.png', $5, 'image/png', 3)
+ `, attachmentID, testWorkspaceID, created.ID, testUserID, "https://cdn.example.test/"+attachmentID); err != nil {
+ t.Fatalf("insert channel attachment: %v", err)
+ }
+ block := channelmedia.Block(attachmentID, "diagram.png", true)
+ if _, err := testPool.Exec(ctx, `UPDATE issue SET description = $1 WHERE id = $2`, channelmedia.Append("Original", block), created.ID); err != nil {
+ t.Fatalf("append channel media: %v", err)
+ }
+
+ update := httptest.NewRecorder()
+ updateReq := newRequest(http.MethodPut, "/api/issues/batch?workspace_id="+testWorkspaceID, map[string]any{
+ "issue_ids": []string{created.ID},
+ "updates": map[string]any{
+ "description": "Batch edit",
+ },
+ })
+ testHandler.BatchUpdateIssues(update, updateReq)
+ if update.Code != http.StatusOK {
+ t.Fatalf("batch update: status %d: %s", update.Code, update.Body.String())
+ }
+
+ var description string
+ if err := testPool.QueryRow(ctx, `SELECT description FROM issue WHERE id = $1`, created.ID).Scan(&description); err != nil {
+ t.Fatalf("load batch-updated description: %v", err)
+ }
+ want := channelmedia.Append("Batch edit", block)
+ if description != want {
+ t.Fatalf("batch-updated description = %q, want %q", description, want)
+ }
+}
+
+func TestDescriptionUpdateLockSerializesLaterChannelMediaAppend(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("requires test database")
+ }
+ ctx := context.Background()
+ var issueID pgtype.UUID
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (
+ workspace_id, title, description, status, priority,
+ creator_type, creator_id, number
+ ) VALUES ($1, 'Description/media lock race', 'Original', 'todo', 'none', 'member', $2,
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)
+ })
+ workspaceID := pgtype.UUID{Bytes: uuid.MustParse(testWorkspaceID), Valid: true}
+
+ descriptionTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin description transaction: %v", err)
+ }
+ defer descriptionTx.Rollback(ctx)
+ if _, err := db.New(testPool).WithTx(descriptionTx).LockIssueForDescriptionUpdate(ctx, db.LockIssueForDescriptionUpdateParams{
+ ID: issueID, WorkspaceID: workspaceID,
+ }); err != nil {
+ t.Fatalf("lock issue for description update: %v", err)
+ }
+ if _, err := descriptionTx.Exec(ctx, `UPDATE issue SET description = 'Local edit' WHERE id = $1`, issueID); err != nil {
+ t.Fatalf("write local description under lock: %v", err)
+ }
+
+ bindTx, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin media bind transaction: %v", err)
+ }
+ defer bindTx.Rollback(ctx)
+ var bindPID int32
+ if err := bindTx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&bindPID); err != nil {
+ t.Fatalf("load bind backend pid: %v", err)
+ }
+ bindResult := make(chan error, 1)
+ go func() {
+ _, lockErr := db.New(testPool).WithTx(bindTx).LockIssueForChannelMediaBind(context.Background(), db.LockIssueForChannelMediaBindParams{
+ ID: issueID, WorkspaceID: workspaceID,
+ })
+ bindResult <- lockErr
+ }()
+
+ blocked := false
+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); {
+ if err := testPool.QueryRow(ctx, `SELECT cardinality(pg_blocking_pids($1)) > 0`, bindPID).Scan(&blocked); err != nil {
+ t.Fatalf("inspect media lock wait: %v", err)
+ }
+ if blocked {
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !blocked {
+ t.Fatal("channel media bind did not block behind description update")
+ }
+ if err := descriptionTx.Commit(ctx); err != nil {
+ t.Fatalf("commit description update: %v", err)
+ }
+ select {
+ case err := <-bindResult:
+ if err != nil {
+ t.Fatalf("acquire media bind lock: %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("media bind stayed blocked after description commit")
+ }
+
+ const attachmentID = "44444444-4444-4444-8444-444444444444"
+ block := channelmedia.Block(attachmentID, "diagram.png", true)
+ if _, err := db.New(testPool).WithTx(bindTx).MaterializeIssueChannelMediaMarkdown(ctx, db.MaterializeIssueChannelMediaMarkdownParams{
+ ID: issueID, WorkspaceID: workspaceID, Markdown: pgtype.Text{String: block, Valid: true},
+ }); err != nil {
+ t.Fatalf("append channel media after description commit: %v", err)
+ }
+ if err := bindTx.Commit(ctx); err != nil {
+ t.Fatalf("commit media append: %v", err)
+ }
+
+ var description string
+ if err := testPool.QueryRow(ctx, `SELECT description FROM issue WHERE id = $1`, issueID).Scan(&description); err != nil {
+ t.Fatalf("load final description: %v", err)
+ }
+ want := channelmedia.Append("Local edit", block)
+ if description != want {
+ t.Fatalf("final description = %q, want %q", description, want)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/issue_command.go b/server/internal/integrations/channel/engine/issue_command.go
index 1f7f67e370..647f9e6ae8 100644
--- a/server/internal/integrations/channel/engine/issue_command.go
+++ b/server/internal/integrations/channel/engine/issue_command.go
@@ -58,6 +58,98 @@ func ParseIssueCommand(body string) (*IssueCommand, bool) {
return &IssueCommand{Title: title, Description: description}, true
}
+// issueDescriptionFromCommandBody removes the /issue directive line from the
+// full normalized message while preserving the layout that follows it. Unlike
+// CommandText, the full body may still contain adapter-generated inline media
+// placeholders. Keeping those placeholders in the initial issue description
+// gives the detached media binder stable positions to materialize later.
+//
+// Content before the directive is deliberately excluded. Some adapters enrich
+// Body with quoted context while keeping CommandText as the user's own command;
+// copying that prefix into the issue would change the existing command contract.
+func issueDescriptionFromCommandBody(body, commandText, fallback string) string {
+ _, end, ok := issueCommandLineBounds(body, commandText)
+ if !ok {
+ return fallback
+ }
+ return strings.TrimSpace(body[end:])
+}
+
+type textLineBounds struct {
+ start int
+ end int
+}
+
+// issueCommandLineBounds locates the actual user-authored /issue directive in
+// the normalized body. Adapters may prepend enriched history containing older
+// /issue lines, so matching the first token-bounded directive is insufficient.
+// CommandText is the un-enriched command source: count identical directive
+// lines there, then select the corresponding first occurrence in the body's
+// user-authored suffix. This also remains stable when the description repeats
+// the exact directive line.
+func issueCommandLineBounds(body, commandText string) (start, end int, ok bool) {
+ expected, ok := firstIssueCommandLine(commandText)
+ if !ok {
+ return 0, 0, false
+ }
+ commandOccurrences := countMatchingLines(commandText, expected)
+ candidates := matchingLineBounds(body, expected)
+ target := len(candidates) - commandOccurrences
+ if target < 0 || target >= len(candidates) {
+ return 0, 0, false
+ }
+ return candidates[target].start, candidates[target].end, true
+}
+
+func firstIssueCommandLine(commandText string) (string, bool) {
+ for _, line := range strings.Split(commandText, "\n") {
+ trimmed := strings.TrimSpace(line)
+ if strings.HasPrefix(trimmed, issueCommandPrefix) {
+ rest := trimmed[len(issueCommandPrefix):]
+ if rest == "" || rest[0] == ' ' || rest[0] == '\t' {
+ return trimmed, true
+ }
+ }
+ if trimmed != "" {
+ return "", false
+ }
+ }
+ return "", false
+}
+
+func countMatchingLines(text, expected string) int {
+ count := 0
+ for _, line := range strings.Split(text, "\n") {
+ if strings.TrimSpace(line) == expected {
+ count++
+ }
+ }
+ return count
+}
+
+func matchingLineBounds(body, expected string) []textLineBounds {
+ bounds := make([]textLineBounds, 0, 1)
+ for offset := 0; offset <= len(body); {
+ lineEnd := strings.IndexByte(body[offset:], '\n')
+ next := len(body)
+ line := body[offset:]
+ if lineEnd >= 0 {
+ lineEnd += offset
+ line = body[offset:lineEnd]
+ next = lineEnd + 1
+ }
+
+ if strings.TrimSpace(line) == expected {
+ bounds = append(bounds, textLineBounds{start: offset, end: next})
+ }
+ if lineEnd < 0 {
+ break
+ }
+ offset = next
+ }
+ return bounds
+}
+
// titleFromPreviousMessage derives a title from a prior chat message, used for
// the bare `/issue` fallback. The previous message may itself be an `/issue …`
// invocation (two commands in a row), in which case stripping the prefix yields
diff --git a/server/internal/integrations/channel/engine/issue_command_test.go b/server/internal/integrations/channel/engine/issue_command_test.go
index 6592dd02c0..1ea70cc4af 100644
--- a/server/internal/integrations/channel/engine/issue_command_test.go
+++ b/server/internal/integrations/channel/engine/issue_command_test.go
@@ -52,3 +52,39 @@ func TestTitleFromPreviousMessage(t *testing.T) {
t.Errorf("blank prev → empty: %q", got)
}
}
+
+func TestIssueDescriptionFromCommandBodyPreservesInlineLayout(t *testing.T) {
+ body := "/issue explain below questions\nWhat is this?\n[Image]\nAnd what is this?\n[Image]"
+ want := "What is this?\n[Image]\nAnd what is this?\n[Image]"
+ if got := issueDescriptionFromCommandBody(body, "/issue explain below questions\nWhat is this?And what is this?", "flattened fallback"); got != want {
+ t.Fatalf("description = %q, want %q", got, want)
+ }
+}
+
+func TestIssueDescriptionFromCommandBodyExcludesEnrichedPrefix(t *testing.T) {
+ body := "> quoted context\n/issue Real intent\nrepro steps"
+ if got := issueDescriptionFromCommandBody(body, "/issue Real intent\nrepro steps", "fallback"); got != "repro steps" {
+ t.Fatalf("description = %q, want %q", got, "repro steps")
+ }
+}
+
+func TestIssueDescriptionFromCommandBodyIgnoresIssueLinesInEnrichedPrefix(t *testing.T) {
+ body := "<quoted_message>\n/issue Old intent\n</quoted_message>\n/issue Real intent\nrepro steps"
+ if got := issueDescriptionFromCommandBody(body, "/issue Real intent\nrepro steps", "fallback"); got != "repro steps" {
+ t.Fatalf("description = %q, want %q", got, "repro steps")
+ }
+}
+
+func TestIssueDescriptionFromCommandBodyHandlesRepeatedDirectiveLine(t *testing.T) {
+ body := "<quoted_message>\n/issue Same\n</quoted_message>\n/issue Same\nDetails\n/issue Same"
+ commandText := "/issue Same\nDetails\n/issue Same"
+ if got := issueDescriptionFromCommandBody(body, commandText, "fallback"); got != "Details\n/issue Same" {
+ t.Fatalf("description = %q, want %q", got, "Details\\n/issue Same")
+ }
+}
+
+func TestIssueDescriptionFromCommandBodyFallsBackWithoutDirective(t *testing.T) {
+ if got := issueDescriptionFromCommandBody("rewritten body", "/issue Missing", "parsed description"); got != "parsed description" {
+ t.Fatalf("description = %q, want parsed fallback", got)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index f8c6b00caf..4265fbbaea 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -125,16 +125,20 @@ type AppendResult struct {
// BindMediaParams carries stored media references to the post-append
// attachment transaction. MessageID is the durable chat_message whose pending
// marker the binder clears. IssueID selects issue ownership for an /issue turn;
-// otherwise the references bind to MessageID. Media downloads must never run
-// inside this transaction.
+// otherwise the references bind to MessageID. IssueDescriptionBase is valid
+// only for an issue created by this turn and lets the binder replace inline
+// placeholders iff nobody edited the description first. Media downloads must
+// never run inside this transaction.
type BindMediaParams struct {
- MessageID pgtype.UUID
- SessionID pgtype.UUID
- WorkspaceID pgtype.UUID
- Sender pgtype.UUID
- IssueID pgtype.UUID
- Body string
- MediaRefs []channel.MediaRef
+ MessageID pgtype.UUID
+ SessionID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ Sender pgtype.UUID
+ IssueID pgtype.UUID
+ IssueDescriptionBase pgtype.Text
+ IssueCommandText string
+ Body string
+ MediaRefs []channel.MediaRef
}
// IssueCommand is the parsed /issue command.
@@ -317,7 +321,7 @@ type ResolverSet struct {
// for the /issue command. Shared across platforms.
type IssueCreator interface {
Create(ctx context.Context, p service.IssueCreateParams, opts service.IssueCreateOpts) (service.IssueCreateResult, error)
- PublishAttachmentsChanged(issue db.Issue, actorID pgtype.UUID)
+ PublishAttachmentsChanged(ctx context.Context, issue db.Issue, actorID pgtype.UUID)
}
// TaskEnqueuer is the narrow subset of service.TaskService the Router needs to
diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.go
index 34cb268e4b..afedd8ef92 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -407,6 +407,18 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// 7. /issue command, if present. chat_message is already durable; all
// error returns from here signal finalizeNone (or the defensive Mark).
if appendRes.IssueCommand != nil {
+ if resolveMedia {
+ // CommandText intentionally omits adapter-generated media placeholders so
+ // image-before-command layouts still classify as /issue. Restore the
+ // description from the full normalized body after classification so the
+ // created issue retains the inline positions that detached media binding
+ // will materialize. Text-only commands retain their existing parser output.
+ appendRes.IssueCommand.Description = issueDescriptionFromCommandBody(
+ msg.Text,
+ msg.CommandText,
+ appendRes.IssueCommand.Description,
+ )
+ }
// One lookup feeds both the broadcast payload's identifier and the
// chat reply's.
prefix := r.issuePrefix(ctx, inst.WorkspaceID)
@@ -429,7 +441,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// failure and not a chat prompt. Media binding remains independent,
// exactly like the successful direct-create path below.
if resolveMedia {
- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, duplicate, pgtype.UUID{}, localMediaDeadline)
+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, duplicate, pgtype.Text{}, "", pgtype.UUID{}, localMediaDeadline)
}
return res, postAppendFinalize, nil
}
@@ -448,7 +460,10 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// Scheduling the command as a chat run too makes the agent execute the
// same /issue input again. A synchronous issue command is terminal.
if resolveMedia {
- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, deferredIssueTaskID, localMediaDeadline)
+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, pgtype.Text{
+ String: appendRes.IssueCommand.Description,
+ Valid: true,
+ }, msg.CommandText, deferredIssueTaskID, localMediaDeadline)
}
return res, postAppendFinalize, nil
}
@@ -471,7 +486,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
res.runScheduled = true
}
if resolveMedia {
- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, deferredIssueTaskID, localMediaDeadline)
+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, pgtype.Text{}, "", deferredIssueTaskID, localMediaDeadline)
}
return res, postAppendFinalize, nil
}
@@ -480,7 +495,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// order within a chat session. Run scheduling is independent and durable: the
// task service defers a task to the persisted media deadline, then media
// completion promotes it early.
-func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueTaskID pgtype.UUID, deadline time.Time) {
+func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, deadline time.Time) {
key := keyForSession(sessionID)
done := make(chan struct{})
@@ -535,13 +550,13 @@ func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identi
// sees the dead deadline and runs only the empty finalize.
}
}
- r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, issue, issueTaskID, deadline)
+ r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, issue, issueDescriptionBase, issueCommandText, issueTaskID, deadline)
}()
}
const mediaFinalizeTimeout = 5 * time.Second
-func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueTaskID pgtype.UUID, deadline time.Time) {
+func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueDescriptionBase pgtype.Text, issueCommandText string, issueTaskID pgtype.UUID, deadline time.Time) {
ctx, cancel := context.WithDeadline(r.mediaCtx, deadline)
defer cancel()
@@ -567,13 +582,15 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,
"error", err)
}
bindErr := set.Session.BindMedia(finalizeCtx, BindMediaParams{
- MessageID: chatMessageID,
- SessionID: sessionID,
- WorkspaceID: inst.WorkspaceID,
- Sender: identity.UserID,
- IssueID: issue.ID,
- Body: resolved.Text,
- MediaRefs: resolved.MediaRefs,
+ MessageID: chatMessageID,
+ SessionID: sessionID,
+ WorkspaceID: inst.WorkspaceID,
+ Sender: identity.UserID,
+ IssueID: issue.ID,
+ IssueDescriptionBase: issueDescriptionBase,
+ IssueCommandText: issueCommandText,
+ Body: resolved.Text,
+ MediaRefs: resolved.MediaRefs,
})
if bindErr != nil {
// Never delete inline: the attachments may or may not have landed
@@ -587,7 +604,7 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,
"err", bindErr)
}
if bindErr == nil && issue.ID.Valid && len(resolved.MediaRefs) > 0 {
- r.issues.PublishAttachmentsChanged(issue, identity.UserID)
+ r.issues.PublishAttachmentsChanged(finalizeCtx, issue, identity.UserID)
}
if issueTaskID.Valid {
if err := r.tasks.PromoteDeferredChannelIssueTask(finalizeCtx, issueTaskID); err != nil {
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index 2d7aaebf9b..4bef62d28b 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -247,7 +248,7 @@ type fakeIssues struct {
opts service.IssueCreateOpts
result service.IssueCreateResult
err error
- attachmentsChanged int
+ attachmentsChanged atomic.Int64
}
func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, o service.IssueCreateOpts) (service.IssueCreateResult, error) {
@@ -257,8 +258,8 @@ func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, o se
return f.result, f.err
}
-func (f *fakeIssues) PublishAttachmentsChanged(db.Issue, pgtype.UUID) {
- f.attachmentsChanged++
+func (f *fakeIssues) PublishAttachmentsChanged(context.Context, db.Issue, pgtype.UUID) {
+ f.attachmentsChanged.Add(1)
}
type fakeTasks struct {
@@ -922,48 +923,74 @@ func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {
}
func TestRouter_IssueCommand_MediaTargetsCreatedIssue(t *testing.T) {
- h := newHarness(t)
- issueID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")
- issueTaskID := uuidFromString(t, "88888888-8888-4888-8888-888888888888")
- h.binder.appendResult = AppendResult{
- MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),
- DedupMarked: true,
- IssueCommand: &IssueCommand{
- Title: "Fix broken layout",
- },
- }
- h.issues.result = service.IssueCreateResult{
- Issue: db.Issue{ID: issueID, Number: 42, Title: "Fix broken layout"},
- AssignedTaskID: issueTaskID,
- }
+ for _, tc := range []struct {
+ name string
+ text string
+ commandText string
+ title string
+ description string
+ }{
+ {name: "image before command", text: "[Image]\n/issue 解读该架构图", commandText: "/issue 解读该架构图", title: "解读该架构图", description: ""},
+ {name: "command before image", text: "/issue 解读这个架构图\n[Image]", commandText: "/issue 解读这个架构图", title: "解读这个架构图", description: "[Image]"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := newHarness(t)
+ issueID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")
+ issueTaskID := uuidFromString(t, "88888888-8888-4888-8888-888888888888")
+ h.binder.parseIssue = true
+ h.binder.appendResult = AppendResult{
+ MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),
+ DedupMarked: true,
+ }
+ h.issues.result = service.IssueCreateResult{
+ Issue: db.Issue{ID: issueID, Number: 42, Title: tc.title},
+ AssignedTaskID: issueTaskID,
+ }
+ msg := p2pMessage(t)
+ msg.Type = channel.MsgTypeImage
+ msg.Text = tc.text
+ // DingTalk omits its adapter-generated image marker from the command
+ // source, regardless of whether the image precedes or follows the text.
+ msg.CommandText = tc.commandText
- if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
- t.Fatalf("Handle: %v", err)
- }
- if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {
- t.Fatalf("resolved media not bound: %+v", h.binder.boundMedia())
- }
- if got := h.binder.boundMedia().IssueID; got != issueID {
- t.Fatalf("media target issue = %v, want %v", got, issueID)
- }
- if h.issues.opts.AssignedAgentRunFireAt.IsZero() {
- t.Fatal("media-backed /issue must defer its assigned-agent task")
- }
- if !waitFor(time.Second, func() bool {
- h.tasks.mu.Lock()
- defer h.tasks.mu.Unlock()
- return len(h.tasks.issueTaskPromotions) == 1
- }) {
- t.Fatal("deferred issue task was not promoted after media binding")
- }
- h.tasks.mu.Lock()
- gotTaskID := h.tasks.issueTaskPromotions[0]
- h.tasks.mu.Unlock()
- if gotTaskID != issueTaskID {
- t.Fatalf("promoted issue task = %v, want %v", gotTaskID, issueTaskID)
- }
- if h.issues.attachmentsChanged != 1 {
- t.Fatalf("attachment change events = %d, want 1", h.issues.attachmentsChanged)
+ if err := h.router.Handle(context.Background(), msg); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if h.issues.params.Title != tc.title {
+ t.Fatalf("created issue title = %q, want %q", h.issues.params.Title, tc.title)
+ }
+ if h.issues.params.Description.String != tc.description || h.issues.params.Description.Valid != (tc.description != "") {
+ t.Fatalf("created issue description = %#v, want %q", h.issues.params.Description, tc.description)
+ }
+ if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {
+ t.Fatalf("resolved media not bound: %+v", h.binder.boundMedia())
+ }
+ if got := h.binder.boundMedia().IssueID; got != issueID {
+ t.Fatalf("media target issue = %v, want %v", got, issueID)
+ }
+ if got := h.binder.boundMedia().IssueDescriptionBase; !got.Valid || got.String != tc.description {
+ t.Fatalf("media description base = %#v, want valid %q", got, tc.description)
+ }
+ if h.issues.opts.AssignedAgentRunFireAt.IsZero() {
+ t.Fatal("media-backed /issue must defer its assigned-agent task")
+ }
+ if !waitFor(time.Second, func() bool {
+ h.tasks.mu.Lock()
+ defer h.tasks.mu.Unlock()
+ return len(h.tasks.issueTaskPromotions) == 1
+ }) {
+ t.Fatal("deferred issue task was not promoted after media binding")
+ }
+ h.tasks.mu.Lock()
+ gotTaskID := h.tasks.issueTaskPromotions[0]
+ h.tasks.mu.Unlock()
+ if gotTaskID != issueTaskID {
+ t.Fatalf("promoted issue task = %v, want %v", gotTaskID, issueTaskID)
+ }
+ if !waitFor(time.Second, func() bool { return h.issues.attachmentsChanged.Load() == 1 }) {
+ t.Fatalf("attachment change events = %d, want 1", h.issues.attachmentsChanged.Load())
+ }
+ })
}
}
@@ -1019,8 +1046,8 @@ func TestRouter_IssueCommand_BindFailurePromotesDeferredTaskWithoutAttachmentEve
}) {
t.Fatal("failed attachment bind left the issue task deferred")
}
- if h.issues.attachmentsChanged != 0 {
- t.Fatalf("attachment change events after failed bind = %d, want 0", h.issues.attachmentsChanged)
+ if h.issues.attachmentsChanged.Load() != 0 {
+ t.Fatalf("attachment change events after failed bind = %d, want 0", h.issues.attachmentsChanged.Load())
}
}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index 3e858964b6..88e38ed30f 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/integrations/channel"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -49,6 +50,7 @@ type SessionQueries interface {
ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error
LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)
UpdateChatMessageContentForChannelMedia(ctx context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error)
+ MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg db.MaterializeIssueChannelMediaMarkdownParams) (db.Issue, error)
CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)
LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error)
ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error)
@@ -90,6 +92,9 @@ func (a dbSessionQueries) LockIssueForChannelMediaBind(ctx context.Context, arg
func (a dbSessionQueries) UpdateChatMessageContentForChannelMedia(ctx context.Context, arg db.UpdateChatMessageContentForChannelMediaParams) (int64, error) {
return a.q.UpdateChatMessageContentForChannelMedia(ctx, arg)
}
+func (a dbSessionQueries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg db.MaterializeIssueChannelMediaMarkdownParams) (db.Issue, error) {
+ return a.q.MaterializeIssueChannelMediaMarkdown(ctx, arg)
+}
func (a dbSessionQueries) CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
return a.q.CreateAttachment(ctx, arg)
}
@@ -281,16 +286,21 @@ type AppendInput struct {
}
// BindMediaInput links already-uploaded media to either an /issue target or a
-// durable chat message in a short database-only transaction. Remote downloads/
-// uploads happen before this call and outside the connector ACK path.
+// durable chat message in a short database-only transaction. A valid
+// IssueDescriptionBase permits inline replacement only while the issue still
+// has its exact creation-time description; otherwise issue media appends as a
+// concurrency-safe fallback. Remote downloads/uploads happen before this call
+// and outside the connector ACK path.
type BindMediaInput struct {
- MessageID pgtype.UUID
- SessionID pgtype.UUID
- WorkspaceID pgtype.UUID
- Sender pgtype.UUID
- IssueID pgtype.UUID
- Body string
- MediaRefs []channel.MediaRef
+ MessageID pgtype.UUID
+ SessionID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ Sender pgtype.UUID
+ IssueID pgtype.UUID
+ IssueDescriptionBase pgtype.Text
+ IssueCommandText string
+ Body string
+ MediaRefs []channel.MediaRef
}
// channelCommandMessageKind marks a visible user turn handled synchronously by
@@ -467,8 +477,9 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
claimed[k] = true
}
type createdMedia struct {
- id pgtype.UUID
- ref channel.MediaRef
+ id pgtype.UUID
+ ref channel.MediaRef
+ filename string
}
created := make([]createdMedia, 0, len(in.MediaRefs))
ids := make([]pgtype.UUID, 0, len(in.MediaRefs))
@@ -510,9 +521,52 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in
return fmt.Errorf("create channel attachment: %w", err)
}
ids = append(ids, att.ID)
- created = append(created, createdMedia{id: att.ID, ref: ref})
+ created = append(created, createdMedia{id: att.ID, ref: ref, filename: filename})
}
- if len(ids) == 0 || in.IssueID.Valid {
+ if len(ids) == 0 {
+ return nil
+ }
+ if in.IssueID.Valid {
+ issueMarkdown := make([]string, 0, len(created))
+ replacements := make([]inlineMediaReplacement, 0, len(created))
+ for _, media := range created {
+ block := channelmedia.Block(
+ uuid.UUID(media.id.Bytes).String(),
+ media.filename,
+ media.ref.Type == channel.MsgTypeImage,
+ )
+ issueMarkdown = append(issueMarkdown, block)
+ if media.ref.InlinePlaceholder != "" {
+ replacements = append(replacements, inlineMediaReplacement{
+ placeholder: media.ref.InlinePlaceholder,
+ index: media.ref.InlineIndex,
+ markdown: block,
+ })
+ }
+ }
+
+ base := pgtype.Text{}
+ description := pgtype.Text{}
+ if in.IssueDescriptionBase.Valid {
+ if composed, changed := composeIssueCommandMediaDescription(
+ in.Body,
+ in.IssueCommandText,
+ replacements,
+ in.IssueDescriptionBase.String,
+ ); changed {
+ base = in.IssueDescriptionBase
+ description = pgtype.Text{String: composed, Valid: true}
+ }
+ }
+ if _, err := qtx.MaterializeIssueChannelMediaMarkdown(ctx, db.MaterializeIssueChannelMediaMarkdownParams{
+ ID: in.IssueID,
+ WorkspaceID: in.WorkspaceID,
+ BaseDescription: base,
+ Description: description.String,
+ Markdown: pgtype.Text{String: strings.Join(issueMarkdown, "\n\n"), Valid: true},
+ }); err != nil {
+ return fmt.Errorf("materialize issue channel media markdown: %w", err)
+ }
return nil
}
linkedIDs, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{
@@ -604,6 +658,59 @@ func composeInlineMediaBody(body string, replacements []inlineMediaReplacement)
return out.String(), true
}
+// composeIssueCommandMediaDescription materializes media in the same positions
+// as the normalized inbound body, then removes the /issue directive line. Only
+// resolved media before the command is retained from the prefix; adapter-added
+// quoted context remains excluded from the issue description contract.
+func composeIssueCommandMediaDescription(body, commandText string, replacements []inlineMediaReplacement, fallback string) (string, bool) {
+ commandStart, _, ok := issueCommandLineBounds(body, commandText)
+ if !ok {
+ return fallback, false
+ }
+
+ type positionedMarkdown struct {
+ start int
+ markdown string
+ }
+ prefix := make([]positionedMarkdown, 0, len(replacements))
+ for _, replacement := range replacements {
+ start := nthSubstringIndex(body, replacement.placeholder, replacement.index)
+ if start >= 0 && start < commandStart {
+ prefix = append(prefix, positionedMarkdown{start: start, markdown: replacement.markdown})
+ }
+ }
+ sort.Slice(prefix, func(i, j int) bool { return prefix[i].start < prefix[j].start })
+
+ composed, changed := composeInlineMediaBody(body, replacements)
+ if !changed {
+ return fallback, false
+ }
+ _, commandEnd, ok := issueCommandLineBounds(composed, commandText)
+ if !ok {
+ return fallback, false
+ }
+
+ parts := make([]string, 0, len(prefix)+1)
+ for _, item := range prefix {
+ if markdown := strings.TrimSpace(item.markdown); markdown != "" {
+ parts = append(parts, markdown)
+ }
+ }
+ if suffix := strings.TrimSpace(composed[commandEnd:]); suffix != "" {
+ parts = append(parts, suffix)
+ }
+ description := strings.Join(parts, "\n\n")
+ for _, replacement := range replacements {
+ if replacement.markdown != "" && strings.Contains(description, replacement.markdown) {
+ return description, true
+ }
+ }
+ // A malformed adapter layout placed every matched marker inside the command
+ // line that is removed above. Fall back to append so attachments never become
+ // invisible merely to preserve an unusable inline layout.
+ return fallback, false
+}
+
func nthSubstringIndex(body, marker string, target int) int {
offset := 0
for index := 0; ; index++ {
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
index a4d696d946..5e282e2b64 100644
--- a/server/internal/integrations/channel/engine/session_db_test.go
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -13,6 +13,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/integrations/channel"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -273,6 +274,14 @@ func TestBindMediaRefs_IssueAttachmentSurvivesChatSessionDeletion(t *testing.T)
if gotIssueID != issueID || chatSessionID.Valid || chatMessageID.Valid {
t.Fatalf("attachment ownership = issue:%v session:%v message:%v", gotIssueID, chatSessionID, chatMessageID)
}
+ var description string
+ if err := pool.QueryRow(ctx, `SELECT description FROM issue WHERE id = $1`, issueID).Scan(&description); err != nil {
+ t.Fatalf("load issue description: %v", err)
+ }
+ wantDescription := channelmedia.Block(uuidString(attachmentID), "issue-image.png", true)
+ if description != wantDescription {
+ t.Fatalf("issue description = %q, want %q", description, wantDescription)
+ }
if _, err := pool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, fixture.sessionID); err != nil {
t.Fatalf("delete chat session: %v", err)
@@ -286,6 +295,155 @@ func TestBindMediaRefs_IssueAttachmentSurvivesChatSessionDeletion(t *testing.T)
}
}
+func TestBindMediaRefs_MaterializesIssueImagesInOriginalRichTextOrder(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := NewChatSession(db.New(pool), pool, channel.Type("dingtalk"), SessionTitles{})
+ ctx := context.Background()
+ body := "/issue explain below questions\nWhat is this?\n[Image]\nAnd what is this?\n[Image]"
+ commandText := "/issue explain below questions\nWhat is this?And what is this?"
+ base := issueDescriptionFromCommandBody(body, commandText, "")
+
+ appendRes, err := session.AppendUserMessage(ctx, AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: body,
+ CommandText: commandText,
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ var issueID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, description, status, priority, creator_type, creator_id, number)
+ VALUES ($1, 'explain below questions', $2, 'todo', 'none', 'member', $3, 4)
+ RETURNING id
+ `, fixture.workspaceID, base, fixture.userID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+
+ const firstKey = "workspaces/ws/dingtalk/issue-first"
+ const secondKey = "workspaces/ws/dingtalk/issue-second"
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, firstKey, "https://cdn.example.test/issue-first", "pending")
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, secondKey, "https://cdn.example.test/issue-second", "pending")
+ if err := session.BindMediaRefs(ctx, BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ IssueID: issueID,
+ IssueDescriptionBase: pgtype.Text{String: base, Valid: true},
+ IssueCommandText: commandText,
+ Body: body,
+ MediaRefs: []channel.MediaRef{
+ {
+ Type: channel.MsgTypeImage, StorageKey: firstKey, StorageURL: "https://cdn.example.test/issue-first",
+ Filename: "first.png", MimeType: "image/png", InlinePlaceholder: "[Image]", InlineIndex: 0,
+ },
+ {
+ Type: channel.MsgTypeImage, StorageKey: secondKey, StorageURL: "https://cdn.example.test/issue-second",
+ Filename: "second.png", MimeType: "image/png", InlinePlaceholder: "[Image]", InlineIndex: 1,
+ },
+ },
+ }); err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+
+ rows, err := pool.Query(ctx, `
+ SELECT filename, id::text
+ FROM attachment
+ WHERE issue_id = $1
+ `, issueID)
+ if err != nil {
+ t.Fatalf("list issue attachments: %v", err)
+ }
+ defer rows.Close()
+ ids := map[string]string{}
+ for rows.Next() {
+ var filename, id string
+ if err := rows.Scan(&filename, &id); err != nil {
+ t.Fatalf("scan issue attachment: %v", err)
+ }
+ ids[filename] = id
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("iterate issue attachments: %v", err)
+ }
+
+ var description string
+ if err := pool.QueryRow(ctx, `SELECT description FROM issue WHERE id = $1`, issueID).Scan(&description); err != nil {
+ t.Fatalf("load issue description: %v", err)
+ }
+ want := "What is this?\n" + channelmedia.Block(ids["first.png"], "first.png", true) +
+ "\nAnd what is this?\n" + channelmedia.Block(ids["second.png"], "second.png", true)
+ if description != want {
+ t.Fatalf("issue description = %q, want %q", description, want)
+ }
+}
+
+func TestMaterializeIssueChannelMediaMarkdownPreservesEditedDescription(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+
+ var issueID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, description, status, priority, creator_type, creator_id, number)
+ VALUES ($1, 'Keep description', 'Reproduction steps', 'todo', 'none', 'member', $2, 2)
+ RETURNING id
+ `, fixture.workspaceID, fixture.userID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+
+ const markdown = "![](/api/attachments/22222222-2222-4222-8222-222222222222/download)"
+ issue, err := db.New(pool).MaterializeIssueChannelMediaMarkdown(ctx, db.MaterializeIssueChannelMediaMarkdownParams{
+ ID: issueID,
+ WorkspaceID: fixture.workspaceID,
+ BaseDescription: pgtype.Text{String: "creation base", Valid: true},
+ Description: "inline layout",
+ Markdown: pgtype.Text{String: markdown, Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("MaterializeIssueChannelMediaMarkdown: %v", err)
+ }
+ want := "Reproduction steps\n\n" + markdown
+ if !issue.Description.Valid || issue.Description.String != want {
+ t.Fatalf("issue description = %#v, want %q", issue.Description, want)
+ }
+}
+
+func TestMaterializeIssueChannelMediaMarkdownReplacesUnchangedBase(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ ctx := context.Background()
+
+ const base = "What is this?\n[Image]\nAnd what is this?\n[Image]"
+ const composed = "What is this?\n![](first)\n\nAnd what is this?\n![](second)"
+ var issueID pgtype.UUID
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, description, status, priority, creator_type, creator_id, number)
+ VALUES ($1, 'Keep layout', $2, 'todo', 'none', 'member', $3, 3)
+ RETURNING id
+ `, fixture.workspaceID, base, fixture.userID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+
+ issue, err := db.New(pool).MaterializeIssueChannelMediaMarkdown(ctx, db.MaterializeIssueChannelMediaMarkdownParams{
+ ID: issueID,
+ WorkspaceID: fixture.workspaceID,
+ BaseDescription: pgtype.Text{String: base, Valid: true},
+ Description: composed,
+ Markdown: pgtype.Text{String: "fallback", Valid: true},
+ })
+ if err != nil {
+ t.Fatalf("MaterializeIssueChannelMediaMarkdown: %v", err)
+ }
+ if !issue.Description.Valid || issue.Description.String != composed {
+ t.Fatalf("issue description = %#v, want %q", issue.Description, composed)
+ }
+}
+
func TestIssueDeleteLockPreventsLateMediaBindFromOrphaningObject(t *testing.T) {
pool := sessionPersistenceTestDB(t)
fixture := seedSessionPersistenceFixture(t, pool)
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 4000c59cac..2e03684393 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -10,6 +10,7 @@ import (
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/channelmedia"
"github.com/multica-ai/multica/server/internal/integrations/channel"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -36,23 +37,26 @@ func (fakeTxStarter) Begin(context.Context) (pgx.Tx, error) { return fakeTx{}, n
// fakeSessionQueries is an in-memory SessionQueries for unit tests.
type fakeSessionQueries struct {
- bindings map[string]pgtype.UUID
- nextSession byte
- createdSessions int
- messages []string
- messageID pgtype.UUID
- lastCreate db.CreateChatMessageParams
- touched int
- replyTargets int
- lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
- lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
- attachments []db.CreateAttachmentParams
- linked db.LinkAttachmentsToChatMessageParams
- mediaCleared int
- updatedMediaContent string
- updateMediaRows int64
- reconcilerOwnedKeys map[string]bool
- issueLookupErr error
+ bindings map[string]pgtype.UUID
+ nextSession byte
+ createdSessions int
+ messages []string
+ messageID pgtype.UUID
+ lastCreate db.CreateChatMessageParams
+ touched int
+ replyTargets int
+ lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
+ lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
+ attachments []db.CreateAttachmentParams
+ linked db.LinkAttachmentsToChatMessageParams
+ mediaCleared int
+ updatedMediaContent string
+ updateMediaRows int64
+ issueMediaMarkdown string
+ issueMediaBase pgtype.Text
+ issueMediaDescription string
+ reconcilerOwnedKeys map[string]bool
+ issueLookupErr error
prevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRows
markRows int64 // MarkChannelInboundDedupProcessed result
@@ -120,6 +124,13 @@ func (f *fakeSessionQueries) UpdateChatMessageContentForChannelMedia(_ context.C
return f.updateMediaRows, nil
}
+func (f *fakeSessionQueries) MaterializeIssueChannelMediaMarkdown(_ context.Context, arg db.MaterializeIssueChannelMediaMarkdownParams) (db.Issue, error) {
+ f.issueMediaMarkdown = arg.Markdown.String
+ f.issueMediaBase = arg.BaseDescription
+ f.issueMediaDescription = arg.Description
+ return db.Issue{ID: arg.ID, WorkspaceID: arg.WorkspaceID}, nil
+}
+
func (f *fakeSessionQueries) CreateAttachment(_ context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
f.attachments = append(f.attachments, arg)
return db.Attachment{ID: arg.ID}, nil
@@ -452,6 +463,100 @@ func TestComposeInlineMediaBody_ReplacesMarkersWithoutAddingWhitespace(t *testin
}
}
+func TestComposeIssueCommandMediaDescriptionPreservesRichTextOrder(t *testing.T) {
+ body := "/issue explain below questions\nWhat is this?\n[Image]\nAnd what is this?\n[Image]"
+ got, changed := composeIssueCommandMediaDescription(body, "/issue explain below questions\nWhat is this?And what is this?", []inlineMediaReplacement{
+ {placeholder: "[Image]", index: 0, markdown: "![](first)\n\n<!-- first -->"},
+ {placeholder: "[Image]", index: 1, markdown: "![](second)\n\n<!-- second -->"},
+ }, "flattened fallback")
+ if !changed {
+ t.Fatal("expected issue description media to be materialized")
+ }
+ want := "What is this?\n![](first)\n\n<!-- first -->\nAnd what is this?\n![](second)\n\n<!-- second -->"
+ if got != want {
+ t.Fatalf("description = %q, want %q", got, want)
+ }
+}
+
+func TestComposeIssueCommandMediaDescriptionKeepsOnlyMediaBeforeCommand(t *testing.T) {
+ body := "> quoted context\n[Image]\n/issue explain\nDetails"
+ got, changed := composeIssueCommandMediaDescription(body, "/issue explain\nDetails", []inlineMediaReplacement{
+ {placeholder: "[Image]", index: 0, markdown: "![](first)\n\n<!-- first -->"},
+ }, "Details")
+ if !changed {
+ t.Fatal("expected leading media to be materialized")
+ }
+ want := "![](first)\n\n<!-- first -->\n\nDetails"
+ if got != want {
+ t.Fatalf("description = %q, want %q", got, want)
+ }
+}
+
+func TestComposeIssueCommandMediaDescriptionFallsBackWhenMarkerIsInsideDirective(t *testing.T) {
+ got, changed := composeIssueCommandMediaDescription(
+ "/issue explain [Image]\nDetails",
+ "/issue explain [Image]\nDetails",
+ []inlineMediaReplacement{{placeholder: "[Image]", index: 0, markdown: "![](first)"}},
+ "Details",
+ )
+ if changed || got != "Details" {
+ t.Fatalf("compose = %q, changed=%v; want fallback", got, changed)
+ }
+}
+
+func TestComposeIssueCommandMediaDescriptionIgnoresEnrichedIssueLine(t *testing.T) {
+ body := "<quoted_message>\n/issue Old intent\n</quoted_message>\n/issue Real intent\nDetails\n[Image]"
+ got, changed := composeIssueCommandMediaDescription(
+ body,
+ "/issue Real intent\nDetails",
+ []inlineMediaReplacement{{placeholder: "[Image]", index: 0, markdown: "![](first)"}},
+ "Details\n[Image]",
+ )
+ if !changed || got != "Details\n![](first)" {
+ t.Fatalf("compose = %q, changed=%v; want real command suffix", got, changed)
+ }
+}
+
+func TestBindMediaRefs_MaterializesIssueImagesInOriginalOrder(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ body := "/issue explain below questions\nWhat is this?\n[Image]\nAnd what is this?\n[Image]"
+ commandText := "/issue explain below questions\nWhat is this?And what is this?"
+ base := issueDescriptionFromCommandBody(body, commandText, "")
+ err := s.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: uid(42),
+ SessionID: uid(1),
+ WorkspaceID: uid(9),
+ Sender: uid(7),
+ IssueID: uid(8),
+ IssueDescriptionBase: pgtype.Text{String: base, Valid: true},
+ IssueCommandText: commandText,
+ Body: body,
+ MediaRefs: []channel.MediaRef{
+ {
+ Type: channel.MsgTypeImage, StorageKey: "dingtalk/first", StorageURL: "https://cdn.test/first",
+ Filename: "first.png", MimeType: "image/png", InlinePlaceholder: "[Image]", InlineIndex: 0,
+ },
+ {
+ Type: channel.MsgTypeImage, StorageKey: "dingtalk/second", StorageURL: "https://cdn.test/second",
+ Filename: "second.png", MimeType: "image/png", InlinePlaceholder: "[Image]", InlineIndex: 1,
+ },
+ },
+ })
+ if err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+ if f.issueMediaBase != (pgtype.Text{String: base, Valid: true}) {
+ t.Fatalf("issue media base = %#v, want %q", f.issueMediaBase, base)
+ }
+ first := channelmedia.Block(uuidString(f.attachments[0].ID), "first.png", true)
+ second := channelmedia.Block(uuidString(f.attachments[1].ID), "second.png", true)
+ want := "What is this?\n" + first + "\nAnd what is this?\n" + second
+ if f.issueMediaDescription != want {
+ t.Fatalf("issue media description = %q, want %q", f.issueMediaDescription, want)
+ }
+}
+
func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {
f := newFake()
s := newTestSession(f)
@@ -491,11 +596,45 @@ func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {
if f.updatedMediaContent != "" {
t.Fatalf("issue-owned media must not rewrite the chat command body: %q", f.updatedMediaContent)
}
+ wantMarkdown := channelmedia.Block(uuidString(att.ID), "issue.png", true)
+ if f.issueMediaMarkdown != wantMarkdown {
+ t.Fatalf("issue media markdown = %q, want %q", f.issueMediaMarkdown, wantMarkdown)
+ }
if f.mediaCleared != 1 {
t.Fatalf("media pending marker clears = %d, want 1", f.mediaCleared)
}
}
+func TestBindMediaRefs_UsesGeneratedFilenameInIssueMarkdown(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ err := s.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: uid(42),
+ SessionID: uid(1),
+ WorkspaceID: uid(9),
+ Sender: uid(7),
+ IssueID: uid(8),
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeFile,
+ StorageKey: "dingtalk/file",
+ StorageURL: "https://cdn.example.test/dingtalk/file",
+ MimeType: "application/pdf",
+ }},
+ })
+ if err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+ att := f.attachments[0]
+ wantFilename := defaultMediaFilename(channel.MsgTypeFile, uuidString(att.ID), "application/pdf")
+ if att.Filename != wantFilename {
+ t.Fatalf("attachment filename = %q, want %q", att.Filename, wantFilename)
+ }
+ wantMarkdown := channelmedia.Block(uuidString(att.ID), wantFilename, false)
+ if f.issueMediaMarkdown != wantMarkdown {
+ t.Fatalf("issue media markdown = %q, want %q", f.issueMediaMarkdown, wantMarkdown)
+ }
+}
+
func TestBindMediaRefs_MissingIssueRollsBackAndClearsPendingMarker(t *testing.T) {
f := newFake()
f.issueLookupErr = pgx.ErrNoRows
diff --git a/server/internal/integrations/dingtalk/resolvers.go b/server/internal/integrations/dingtalk/resolvers.go
index ff1f3c957b..8c5af1c448 100644
--- a/server/internal/integrations/dingtalk/resolvers.go
+++ b/server/internal/integrations/dingtalk/resolvers.go
@@ -270,13 +270,15 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
- MessageID: p.MessageID,
- SessionID: p.SessionID,
- WorkspaceID: p.WorkspaceID,
- Sender: p.Sender,
- IssueID: p.IssueID,
- Body: p.Body,
- MediaRefs: p.MediaRefs,
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ IssueDescriptionBase: p.IssueDescriptionBase,
+ IssueCommandText: p.IssueCommandText,
+ Body: p.Body,
+ MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/integrations/dingtalk/resolvers_test.go b/server/internal/integrations/dingtalk/resolvers_test.go
index f1d42e77fa..50dbcbe96c 100644
--- a/server/internal/integrations/dingtalk/resolvers_test.go
+++ b/server/internal/integrations/dingtalk/resolvers_test.go
@@ -66,16 +66,17 @@ func TestSessionBinder_MapsMediaBodyAndIssueTarget(t *testing.T) {
message.Bytes[0], session.Bytes[0], workspace.Bytes[0], sender.Bytes[0], issue.Bytes[0] = 1, 2, 3, 4, 5
message.Valid, session.Valid, workspace.Valid, sender.Valid, issue.Valid = true, true, true, true, true
ref := channel.MediaRef{Type: channel.MsgTypeImage, InlinePlaceholder: "[Image]", InlineIndex: 0}
+ base := pgtype.Text{String: "[Image]\nfix login", Valid: true}
capture := &captureChatSession{}
binder := &sessionBinder{session: capture}
if err := binder.BindMedia(context.Background(), engine.BindMediaParams{
MessageID: message, SessionID: session, WorkspaceID: workspace, Sender: sender,
- IssueID: issue, Body: "[Image]\nfix login", MediaRefs: []channel.MediaRef{ref},
+ IssueID: issue, IssueDescriptionBase: base, IssueCommandText: "/issue fix login", Body: "[Image]\nfix login", MediaRefs: []channel.MediaRef{ref},
}); err != nil {
t.Fatal(err)
}
got := capture.media
- if got.MessageID != message || got.SessionID != session || got.WorkspaceID != workspace || got.Sender != sender || got.IssueID != issue || got.Body != "[Image]\nfix login" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
+ if got.MessageID != message || got.SessionID != session || got.WorkspaceID != workspace || got.Sender != sender || got.IssueID != issue || got.IssueDescriptionBase != base || got.IssueCommandText != "/issue fix login" || got.Body != "[Image]\nfix login" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
t.Fatalf("mapped media input = %+v", got)
}
}
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 5ec14e6afe..ef115c7c67 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -222,13 +222,15 @@ func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.Append
func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
- MessageID: p.MessageID,
- SessionID: p.SessionID,
- WorkspaceID: p.WorkspaceID,
- Sender: p.Sender,
- IssueID: p.IssueID,
- Body: p.Body,
- MediaRefs: p.MediaRefs,
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ IssueDescriptionBase: p.IssueDescriptionBase,
+ IssueCommandText: p.IssueCommandText,
+ Body: p.Body,
+ MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index 99abae9028..5ccce649c1 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -161,18 +161,19 @@ func TestFeishuSessionBinder_BindMediaMapping(t *testing.T) {
b := &feishuSessionBinder{session: f}
ref := channel.MediaRef{Type: channel.MsgTypeImage, StorageURL: "https://cdn.example.test/image.png"}
if err := b.BindMedia(context.Background(), engine.BindMediaParams{
- MessageID: binderUUID(4),
- SessionID: binderUUID(1),
- WorkspaceID: binderUUID(2),
- Sender: binderUUID(7),
- IssueID: binderUUID(8),
- Body: "[Image]",
- MediaRefs: []channel.MediaRef{ref},
+ MessageID: binderUUID(4),
+ SessionID: binderUUID(1),
+ WorkspaceID: binderUUID(2),
+ Sender: binderUUID(7),
+ IssueID: binderUUID(8),
+ IssueCommandText: "/issue Real intent",
+ Body: "[Image]",
+ MediaRefs: []channel.MediaRef{ref},
}); err != nil {
t.Fatalf("BindMedia: %v", err)
}
got := f.mediaIn
- if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || got.IssueID != binderUUID(8) || got.Body != "[Image]" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
+ if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || got.IssueID != binderUUID(8) || got.IssueCommandText != "/issue Real intent" || got.Body != "[Image]" || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {
t.Fatalf("media mapping wrong: %+v", got)
}
}
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index bb4e5a26db..bdec49848c 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -353,13 +353,15 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
- MessageID: p.MessageID,
- SessionID: p.SessionID,
- WorkspaceID: p.WorkspaceID,
- Sender: p.Sender,
- IssueID: p.IssueID,
- Body: p.Body,
- MediaRefs: p.MediaRefs,
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ IssueID: p.IssueID,
+ IssueDescriptionBase: p.IssueDescriptionBase,
+ IssueCommandText: p.IssueCommandText,
+ Body: p.Body,
+ MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/service/issue.go b/server/internal/service/issue.go
index 67a5c45625..6bac136339 100644
--- a/server/internal/service/issue.go
+++ b/server/internal/service/issue.go
@@ -478,11 +478,13 @@ func (s *IssueService) publishIssueCreated(issue db.Issue, attachments []db.Atta
})
}
-// PublishAttachmentsChanged refreshes the per-issue attachment cache after a
-// detached channel media transaction. Issue creation is broadcast before the
-// remote download finishes, so this follow-up event closes the realtime gap
-// for a detail page opened from the immediate /issue confirmation.
-func (s *IssueService) PublishAttachmentsChanged(issue db.Issue, actorID pgtype.UUID) {
+// PublishAttachmentsChanged refreshes attachments and the issue projection
+// after a detached channel media transaction. Issue creation is broadcast
+// before the remote download finishes, so the attachment event closes the
+// cache gap for current clients. The issue:updated event carries the newly
+// materialized description through a pre-existing protocol that installed
+// desktop clients already understand.
+func (s *IssueService) PublishAttachmentsChanged(ctx context.Context, issue db.Issue, actorID pgtype.UUID) {
if s.Bus == nil {
return
}
@@ -495,6 +497,37 @@ func (s *IssueService) PublishAttachmentsChanged(issue db.Issue, actorID pgtype.
"issue_id": util.UUIDToString(issue.ID),
},
})
+ if s.Queries == nil {
+ return
+ }
+
+ current, err := s.Queries.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{
+ ID: issue.ID,
+ WorkspaceID: issue.WorkspaceID,
+ })
+ if err != nil {
+ slog.Warn("failed to load issue after channel media bind",
+ "issue_id", util.UUIDToString(issue.ID), "error", err)
+ return
+ }
+ workspace, err := s.Queries.GetWorkspace(ctx, issue.WorkspaceID)
+ if err != nil {
+ slog.Warn("failed to load workspace after channel media bind",
+ "workspace_id", util.UUIDToString(issue.WorkspaceID), "error", err)
+ return
+ }
+ s.Bus.Publish(events.Event{
+ Type: protocol.EventIssueUpdated,
+ WorkspaceID: util.UUIDToString(issue.WorkspaceID),
+ ActorType: "member",
+ ActorID: util.UUIDToString(actorID),
+ Payload: map[string]any{
+ "issue": IssueToMap(current, workspace.IssuePrefix),
+ "assignee_changed": false,
+ "status_changed": false,
+ "project_changed": false,
+ },
+ })
}
func (s *IssueService) captureCreatedAnalytics(issue db.Issue, creatorType, actorID string, opts IssueCreateOpts) {
diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.go
index 9d6c096980..587aae36dd 100644
--- a/server/internal/service/issue_channel_media_test.go
+++ b/server/internal/service/issue_channel_media_test.go
@@ -55,7 +55,7 @@ func TestPublishAttachmentsChangedCarriesIssueScope(t *testing.T) {
var got events.Event
bus.Subscribe(protocol.EventIssueAttachmentsChanged, func(e events.Event) { got = e })
- svc.PublishAttachmentsChanged(db.Issue{ID: issueID, WorkspaceID: workspaceID}, actorID)
+ svc.PublishAttachmentsChanged(context.Background(), db.Issue{ID: issueID, WorkspaceID: workspaceID}, actorID)
if got.Type != protocol.EventIssueAttachmentsChanged || got.WorkspaceID != util.UUIDToString(workspaceID) || got.ActorType != "member" || got.ActorID != util.UUIDToString(actorID) {
t.Fatalf("event envelope = %+v", got)
@@ -66,6 +66,54 @@ func TestPublishAttachmentsChangedCarriesIssueScope(t *testing.T) {
}
}
+func TestPublishAttachmentsChangedAlsoBroadcastsUpdatedDescription(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, _, issueID := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+ issueUUID := util.MustParseUUID(issueID)
+ actorID := util.MustParseUUID(userID)
+ const description = "![](/api/attachments/22222222-2222-4222-8222-222222222222/download)"
+ if _, err := pool.Exec(ctx, `UPDATE issue SET description = $1 WHERE id = $2`, description, issueUUID); err != nil {
+ t.Fatalf("update issue description: %v", err)
+ }
+ issue, err := q.GetIssueInWorkspace(ctx, db.GetIssueInWorkspaceParams{
+ ID: issueUUID, WorkspaceID: workspaceUUID,
+ })
+ if err != nil {
+ t.Fatalf("load issue: %v", err)
+ }
+
+ bus := events.New()
+ svc := &IssueService{Bus: bus, Queries: q}
+ var updated events.Event
+ bus.Subscribe(protocol.EventIssueUpdated, func(e events.Event) { updated = e })
+
+ svc.PublishAttachmentsChanged(ctx, issue, actorID)
+
+ if updated.Type != protocol.EventIssueUpdated || updated.WorkspaceID != workspaceID || updated.ActorType != "member" || updated.ActorID != userID {
+ t.Fatalf("issue update envelope = %+v", updated)
+ }
+ payload, ok := updated.Payload.(map[string]any)
+ if !ok {
+ t.Fatalf("issue update payload = %#v", updated.Payload)
+ }
+ issuePayload, ok := payload["issue"].(map[string]any)
+ if !ok {
+ t.Fatalf("issue update body = %#v", payload["issue"])
+ }
+ gotDescription, ok := issuePayload["description"].(*string)
+ if !ok || gotDescription == nil || *gotDescription != description {
+ t.Fatalf("broadcast description = %#v, want %q", issuePayload["description"], description)
+ }
+ for _, key := range []string{"assignee_changed", "status_changed", "project_changed"} {
+ if changed, ok := payload[key].(bool); !ok || changed {
+ t.Fatalf("%s = %#v, want false", key, payload[key])
+ }
+ }
+}
+
func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(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 0b24fb5dea..3408dca076 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -1276,6 +1276,54 @@ func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDelete
return id, err
}
+const lockIssueForDescriptionUpdate = `-- name: LockIssueForDescriptionUpdate :one
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties FROM issue
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE
+`
+
+type LockIssueForDescriptionUpdateParams struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Serialize user description saves with detached channel-media appends. The
+// handler merges channel media that landed after the editor's submitted base
+// while holding this lock, then performs UpdateIssue in the same transaction.
+func (q *Queries) LockIssueForDescriptionUpdate(ctx context.Context, arg LockIssueForDescriptionUpdateParams) (Issue, error) {
+ row := q.db.QueryRow(ctx, lockIssueForDescriptionUpdate, arg.ID, arg.WorkspaceID)
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ )
+ return i, err
+}
+
const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :one
UPDATE issue
SET first_executed_at = now()
@@ -1308,6 +1356,74 @@ func (q *Queries) MarkIssueFirstExecuted(ctx context.Context, id pgtype.UUID) (M
return i, err
}
+const materializeIssueChannelMediaMarkdown = `-- name: MaterializeIssueChannelMediaMarkdown :one
+UPDATE issue
+SET description = CASE
+ WHEN $1::text IS NOT NULL
+ AND COALESCE(description, '') = $1::text
+ THEN $2::text
+ WHEN description IS NULL OR description = '' THEN $3
+ ELSE description || E'\n\n' || $3
+ END,
+ updated_at = now()
+WHERE id = $4
+ AND workspace_id = $5
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties
+`
+
+type MaterializeIssueChannelMediaMarkdownParams struct {
+ BaseDescription pgtype.Text `json:"base_description"`
+ Description string `json:"description"`
+ Markdown pgtype.Text `json:"markdown"`
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Detached channel media resolves after /issue creation. When the description
+// still equals the exact creation-time base, replace its inline placeholders
+// with the fully composed Markdown so rich-text ordering survives. If a user
+// edited concurrently (or the adapter has no inline layout), append instead;
+// preserving user-authored bytes takes precedence over layout fidelity.
+func (q *Queries) MaterializeIssueChannelMediaMarkdown(ctx context.Context, arg MaterializeIssueChannelMediaMarkdownParams) (Issue, error) {
+ row := q.db.QueryRow(ctx, materializeIssueChannelMediaMarkdown,
+ arg.BaseDescription,
+ arg.Description,
+ arg.Markdown,
+ arg.ID,
+ arg.WorkspaceID,
+ )
+ var i Issue
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ )
+ return i, err
+}
+
const setIssueMetadataKey = `-- name: SetIssueMetadataKey :one
UPDATE issue SET
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 9d0823329d..867b60b133 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -88,6 +88,33 @@ SELECT id FROM issue
WHERE id = $1 AND workspace_id = $2
FOR KEY SHARE;
+-- name: LockIssueForDescriptionUpdate :one
+-- Serialize user description saves with detached channel-media appends. The
+-- handler merges channel media that landed after the editor's submitted base
+-- while holding this lock, then performs UpdateIssue in the same transaction.
+SELECT * FROM issue
+WHERE id = $1 AND workspace_id = $2
+FOR UPDATE;
+
+-- name: MaterializeIssueChannelMediaMarkdown :one
+-- Detached channel media resolves after /issue creation. When the description
+-- still equals the exact creation-time base, replace its inline placeholders
+-- with the fully composed Markdown so rich-text ordering survives. If a user
+-- edited concurrently (or the adapter has no inline layout), append instead;
+-- preserving user-authored bytes takes precedence over layout fidelity.
+UPDATE issue
+SET description = CASE
+ WHEN sqlc.narg('base_description')::text IS NOT NULL
+ AND COALESCE(description, '') = sqlc.narg('base_description')::text
+ THEN sqlc.arg('description')::text
+ WHEN description IS NULL OR description = '' THEN sqlc.arg(markdown)
+ ELSE description || E'\n\n' || sqlc.arg(markdown)
+ END,
+ updated_at = now()
+WHERE id = sqlc.arg(id)
+ AND workspace_id = sqlc.arg(workspace_id)
+RETURNING *;
+
-- name: LockIssueForDelete :one
-- Issue deletion must collect every attachment URL after it has won the same
-- row-lock race used by channel media binding. FOR UPDATE conflicts with the