Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
refactor(editor): remove hardcoded CDN domain, unify file card rendering
Naiyuan Qing53cb01cc9125
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 2f672f6553..8edaf5b6a4 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -534,6 +534,11 @@ export class ApiClient {return this.fetch("/api/inbox/archive-completed", { method: "POST" });}+ // App Config+ async getConfig(): Promise<{ cdn_domain: string }> {+ return this.fetch("/api/config");+ }+// Workspacesasync listWorkspaces(): Promise<Workspace[]> {return this.fetch("/api/workspaces");diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsnew file mode 100644index 0000000000..18817e7780--- /dev/null+++ b/packages/core/config/index.ts@@ -0,0 +1,18 @@+import { createStore } from "zustand/vanilla";+import { useStore } from "zustand";++interface ConfigState {+ cdnDomain: string;+ setCdnDomain: (domain: string) => void;+}++export const configStore = createStore<ConfigState>((set) => ({+ cdnDomain: "",+ setCdnDomain: (domain) => set({ cdnDomain: domain }),+}));++export function useConfigStore(): ConfigState;+export function useConfigStore<T>(selector: (state: ConfigState) => T): T;+export function useConfigStore<T>(selector?: (state: ConfigState) => T) {+ return useStore(configStore, selector as (state: ConfigState) => T);+}diff --git a/packages/core/package.json b/packages/core/package.jsonindex 706784cab3..37f63bbafe 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -15,6 +15,7 @@"./api": "./api/index.ts","./api/client": "./api/client.ts","./api/ws-client": "./api/ws-client.ts",+ "./config": "./config/index.ts","./auth": "./auth/index.ts","./workspace": "./workspace/index.ts","./workspace/queries": "./workspace/queries.ts",diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex ff216d2664..1340df6120 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -5,6 +5,7 @@ import { useQueryClient } from "@tanstack/react-query";import { getApi } from "../api";import { useAuthStore } from "../auth";import { useWorkspaceStore } from "../workspace";+import { configStore } from "../config";import { workspaceKeys } from "../workspace/queries";import { createLogger } from "../logger";import { defaultStorage } from "./storage";@@ -31,6 +32,11 @@ export function AuthInitializer({const api = getApi();const wsId = storage.getItem("multica_workspace_id");+ // Fetch app config (CDN domain, etc.) in the background — non-blocking.+ api.getConfig().then((cfg) => {+ if (cfg.cdn_domain) configStore.getState().setCdnDomain(cfg.cdn_domain);+ }).catch(() => { /* config is optional — legacy file card matching degrades gracefully */ });+if (cookieAuth) {// Cookie mode: the HttpOnly cookie is sent automatically by the browser.// Call the API to check if the session is still valid.diff --git a/packages/ui/markdown/Markdown.tsx b/packages/ui/markdown/Markdown.tsxindex 1716a35aff..c1ef072d8b 100644--- a/packages/ui/markdown/Markdown.tsx+++ b/packages/ui/markdown/Markdown.tsx@@ -3,8 +3,10 @@ import ReactMarkdown, { type Components, defaultUrlTransform } from 'react-markdimport rehypeRaw from 'rehype-raw'import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'import remarkGfm from 'remark-gfm'+import { FileText, Download } from 'lucide-react'import { cn } from '@multica/ui/lib/utils'import { CodeBlock, InlineCode } from './CodeBlock'+import { preprocessFileCards } from './file-cards'import { preprocessLinks } from './linkify'import { preprocessMentionShortcodes } from './mentions'@@ -48,6 +50,11 @@ export interface MarkdownProps {* When not provided, mentions render as a simple styled span.*/renderMention?: (props: { type: string; id: string }) => React.ReactNode+ /**+ * CDN hostname for file card detection (e.g. "multica-static.copilothub.ai").+ * When provided, enables file card preprocessing and rendering.+ */+ cdnDomain?: string}// Sanitization schema — extends GitHub defaults to allow code highlighting classes@@ -60,6 +67,12 @@ const sanitizeSchema = {},attributes: {...defaultSchema.attributes,+ div: [+ ...(defaultSchema.attributes?.div ?? []),+ 'dataType',+ 'dataHref',+ 'dataFilename',+ ],code: [...(defaultSchema.attributes?.code ?? []),['className', /^language-/],@@ -93,9 +106,37 @@ function createComponents(mode: RenderMode,onUrlClick?: (url: string) => void,onFileClick?: (path: string) => void,- renderMention?: (props: { type: string; id: string }) => React.ReactNode+ renderMention?: (props: { type: string; id: string }) => React.ReactNode,): Partial<Components> {const baseComponents: Partial<Components> = {+ // FileCard: intercept <div data-type="fileCard"> from preprocessFileCards+ div: ({ node, children, ...props }) => {+ const dataType = node?.properties?.dataType as string | undefined+ if (dataType === 'fileCard') {+ const rawHref = (node?.properties?.dataHref as string) || ''+ // Only allow http(s) URLs to prevent javascript: and other dangerous schemes.+ const href = /^https?:\/\//i.test(rawHref) ? rawHref : ''+ const filename = (node?.properties?.dataFilename as string) || ''+ return (+ <div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">+ <FileText className="size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm">{filename}</p>+ </div>+ {href && (+ <button+ type="button"+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ onClick={() => window.open(href, '_blank', 'noopener,noreferrer')}+ >+ <Download className="size-3.5" />+ </button>+ )}+ </div>+ )+ }+ return <div {...props}>{children}</div>+ },// Images: render uploaded images with constrained sizingimg: ({ src, alt }) => (<img@@ -337,17 +378,23 @@ export function Markdown({className,onUrlClick,onFileClick,- renderMention+ renderMention,+ cdnDomain}: MarkdownProps): React.JSX.Element {const components = React.useMemo(() => createComponents(mode, onUrlClick, onFileClick, renderMention),[mode, onUrlClick, onFileClick, renderMention])- // Preprocess: convert mention shortcodes and raw URLs/file paths to markdown links+ // Preprocess: convert mention shortcodes, raw URLs, and file cards to renderable contentconst processedContent = React.useMemo(- () => preprocessLinks(preprocessMentionShortcodes(children)),- [children]+ () => {+ let result = preprocessMentionShortcodes(children)+ result = preprocessLinks(result)+ result = preprocessFileCards(result, cdnDomain ?? '')+ return result+ },+ [children, cdnDomain])return (diff --git a/packages/ui/markdown/StreamingMarkdown.tsx b/packages/ui/markdown/StreamingMarkdown.tsxindex d0e7051e98..8cfdeda6dc 100644--- a/packages/ui/markdown/StreamingMarkdown.tsx+++ b/packages/ui/markdown/StreamingMarkdown.tsx@@ -9,6 +9,7 @@ export interface StreamingMarkdownProps {onUrlClick?: (url: string) => voidonFileClick?: (path: string) => voidrenderMention?: (props: { type: string; id: string }) => React.ReactNode+ cdnDomain?: string}interface Block {@@ -136,7 +137,8 @@ const MemoizedBlock = React.memo(className,onUrlClick,onFileClick,- renderMention+ renderMention,+ cdnDomain}: {content: stringmode: RenderMode@@ -144,9 +146,10 @@ const MemoizedBlock = React.memo(onUrlClick?: (url: string) => voidonFileClick?: (path: string) => voidrenderMention?: (props: { type: string; id: string }) => React.ReactNode+ cdnDomain?: string}) {return (- <Markdown mode={mode} className={className} onUrlClick={onUrlClick} onFileClick={onFileClick} renderMention={renderMention}>+ <Markdown mode={mode} className={className} onUrlClick={onUrlClick} onFileClick={onFileClick} renderMention={renderMention} cdnDomain={cdnDomain}>{content}</Markdown>)@@ -181,7 +184,8 @@ export function StreamingMarkdown({className,onUrlClick,onFileClick,- renderMention+ renderMention,+ cdnDomain}: StreamingMarkdownProps): React.JSX.Element {// Split into blocks - memoized to avoid recomputation// Must be called unconditionally to satisfy Rules of Hooks@@ -193,7 +197,7 @@ export function StreamingMarkdown({// Not streaming - use simple Markdown (no block splitting needed)if (!isStreaming) {return (- <Markdown mode={mode} className={className} onUrlClick={onUrlClick} onFileClick={onFileClick} renderMention={renderMention}>+ <Markdown mode={mode} className={className} onUrlClick={onUrlClick} onFileClick={onFileClick} renderMention={renderMention} cdnDomain={cdnDomain}>{content}</Markdown>)@@ -222,6 +226,7 @@ export function StreamingMarkdown({onUrlClick={onUrlClick}onFileClick={onFileClick}renderMention={renderMention}+ cdnDomain={cdnDomain}/>)})}diff --git a/packages/ui/markdown/file-cards.ts b/packages/ui/markdown/file-cards.tsnew file mode 100644index 0000000000..63bf101a6d--- /dev/null+++ b/packages/ui/markdown/file-cards.ts@@ -0,0 +1,89 @@+/**+ * File card preprocessing for markdown content.+ *+ * Converts file-card syntax into HTML divs that can be rendered by+ * react-markdown with a custom `div` component.+ *+ * Two syntaxes are supported:+ * 1. `!file[name](url)` — new unambiguous syntax (no hostname check needed)+ * 2. `[name](cdnUrl)` — legacy syntax, matched by CDN hostname on own line+ *+ * Output: `<div data-type="fileCard" data-href="url" data-filename="name"></div>`+ *+ * All functions are pure — no global state, no imports from core/ or views/.+ */++const IMAGE_EXTS = /\.(png|jpe?g|gif|webp|svg|ico|bmp|tiff?)$/i++/** New syntax: !file[name](url) — unambiguous, no hostname matching needed. */+const NEW_FILE_CARD_RE = /^!file\[([^\]]*)\]\((https?:\/\/[^)]+)\)$/++/** Legacy syntax: [name](cdnUrl) on its own line — matched by CDN hostname. */+const FILE_LINK_LINE = /^\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/++function escapeAttr(s: string): string {+ return s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<')+}++function toFileCardHtml(filename: string, url: string): string {+ return `<div data-type="fileCard" data-href="${escapeAttr(url)}" data-filename="${escapeAttr(filename)}"></div>`+}++/**+ * Check if a URL points to our upload CDN.+ *+ * Uses exact hostname match against `cdnDomain` (e.g. "multica-static.copilothub.ai"),+ * and also matches any `.amazonaws.com` subdomain as a fallback for direct S3 URLs.+ */+export function isCdnUrl(url: string, cdnDomain: string): boolean {+ try {+ const u = new URL(url)+ return u.hostname === cdnDomain || u.hostname.endsWith('.amazonaws.com')+ } catch {+ return false+ }+}++/**+ * Check if a CDN URL is a non-image file that should render as a file card.+ * Image URLs (png, jpg, etc.) are excluded — they render as inline images.+ */+export function isFileCardUrl(url: string, cdnDomain: string): boolean {+ try {+ return isCdnUrl(url, cdnDomain) && !IMAGE_EXTS.test(new URL(url).pathname)+ } catch {+ return false+ }+}++/**+ * Preprocess markdown to convert file-card syntax into HTML divs.+ *+ * Handles both `!file[name](url)` (new syntax) and legacy `[name](cdnUrl)`+ * lines. Only standalone lines are matched — inline links are left untouched.+ *+ * @param markdown Raw markdown string+ * @param cdnDomain CDN hostname for legacy link detection (e.g. "multica-static.copilothub.ai")+ */+export function preprocessFileCards(markdown: string, cdnDomain: string): string {+ return markdown+ .split('\n')+ .map((line) => {+ const trimmed = line.trim()++ // New syntax: !file[name](url) — always a file card, no hostname check needed.+ const newMatch = trimmed.match(NEW_FILE_CARD_RE)+ if (newMatch) {+ return toFileCardHtml(newMatch[1]!, newMatch[2]!)+ }++ // Legacy: [name](cdnUrl) on its own line — CDN hostname matching.+ const match = trimmed.match(FILE_LINK_LINE)+ if (!match) return line+ const filename = match[1]!+ const url = match[2]!+ if (!isFileCardUrl(url, cdnDomain)) return line+ return toFileCardHtml(filename, url)+ })+ .join('\n')+}diff --git a/packages/ui/markdown/index.ts b/packages/ui/markdown/index.tsindex 7d05984d00..7f4a068509 100644--- a/packages/ui/markdown/index.ts+++ b/packages/ui/markdown/index.ts@@ -3,3 +3,4 @@ export { CodeBlock, InlineCode, type CodeBlockProps } from './CodeBlock'export { StreamingMarkdown, type StreamingMarkdownProps } from './StreamingMarkdown'export { preprocessLinks, detectLinks, hasLinks } from './linkify'export { preprocessMentionShortcodes } from './mentions'+export { preprocessFileCards, isCdnUrl, isFileCardUrl } from './file-cards'diff --git a/packages/views/common/markdown.tsx b/packages/views/common/markdown.tsxindex 23dc20b3a8..1be0b15153 100644--- a/packages/views/common/markdown.tsx+++ b/packages/views/common/markdown.tsx@@ -6,6 +6,7 @@ import {type MarkdownProps as MarkdownBaseProps,type RenderMode,} from "@multica/ui/markdown";+import { useConfigStore } from "@multica/core/config";import { IssueMentionCard } from "../issues/components/issue-mention-card";export type { RenderMode };@@ -30,27 +31,13 @@ function defaultRenderMention({}/**- * App-level Markdown wrapper that injects IssueMentionCard via renderMention.- * Callers that need custom mention rendering can pass their own renderMention prop.+ * App-level Markdown wrapper that injects IssueMentionCard via renderMention+ * and cdnDomain from the config store for file card rendering.*/export function Markdown(props: MarkdownProps): React.JSX.Element {- return <MarkdownBase renderMention={defaultRenderMention} {...props} />;+ const cdnDomain = useConfigStore((s) => s.cdnDomain);+ return <MarkdownBase renderMention={defaultRenderMention} cdnDomain={cdnDomain} {...props} />;}-export const MemoizedMarkdown = React.memo(- Markdown,- (prevProps, nextProps) => {- if (prevProps.id && nextProps.id) {- return (- prevProps.id === nextProps.id &&- prevProps.children === nextProps.children &&- prevProps.mode === nextProps.mode- );- }- return (- prevProps.children === nextProps.children &&- prevProps.mode === nextProps.mode- );- },-);+export const MemoizedMarkdown = React.memo(Markdown);MemoizedMarkdown.displayName = "MemoizedMarkdown";diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsxindex 3dc44102b1..4117b23445 100644--- a/packages/views/editor/extensions/file-card.tsx+++ b/packages/views/editor/extensions/file-card.tsx@@ -20,30 +20,6 @@ import type { NodeViewProps } from "@tiptap/react";import { FileText, Loader2, Download } from "lucide-react";-// ----------------------------------------------------------------------------// CDN URL detection-// -----------------------------------------------------------------------------const IMAGE_EXTS = /\.(png|jpe?g|gif|webp|svg|ico|bmp|tiff?)$/i;--/** Check if a URL points to our upload CDN (CloudFront or S3 bucket). */-export function isCdnUrl(url: string): boolean {- try {- const u = new URL(url);- return (- u.hostname.endsWith(".copilothub.ai") ||- u.hostname.endsWith(".amazonaws.com")- );- } catch {- return false;- }-}--/** Check if a CDN URL is a non-image file that should render as a file card. */-export function isFileCardUrl(url: string): boolean {- return isCdnUrl(url) && !IMAGE_EXTS.test(new URL(url).pathname);-}-// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------diff --git a/packages/views/editor/utils/preprocess.ts b/packages/views/editor/utils/preprocess.tsindex c9bf326a3a..2f4d546a7f 100644--- a/packages/views/editor/utils/preprocess.ts+++ b/packages/views/editor/utils/preprocess.ts@@ -1,6 +1,5 @@-import { preprocessLinks } from "@multica/ui/markdown";-import { preprocessMentionShortcodes } from "@multica/ui/markdown";-import { isFileCardUrl } from "../extensions/file-card";+import { preprocessLinks, preprocessMentionShortcodes, preprocessFileCards } from "@multica/ui/markdown";+import { configStore } from "@multica/core/config";/*** Preprocess a markdown string before loading into Tiptap via contentType: 'markdown'.@@ -13,63 +12,14 @@ import { isFileCardUrl } from "../extensions/file-card";* 1. Legacy mention shortcodes [@ id="..." label="..."] → [@Label](mention://member/id)* (old serialization format in database, migrated on read)* 2. Raw URLs → markdown links via linkify-it (so they render as clickable Link nodes)- * 3. CDN file links on their own line → HTML div for fileCard node parsing+ * 3. File card syntax (new !file[name](url) + legacy [name](cdnUrl)) → HTML div for+ * fileCard node parsing*/export function preprocessMarkdown(markdown: string): string {if (!markdown) return "";+ const cdnDomain = configStore.getState().cdnDomain;const step1 = preprocessMentionShortcodes(markdown);const step2 = preprocessLinks(step1);- const step3 = preprocessFileCards(step2);+ const step3 = preprocessFileCards(step2, cdnDomain);return step3;}--/**- * LEGACY MIGRATION: Convert standalone `[name](cdnUrl)` lines into HTML that- * Tiptap's fileCard parseHTML can recognise. Only matches non-image CDN URLs- * on their own line.- *- * New file cards are saved as `!file[name](url)` via the fileCard extension's- * markdownTokenizer, which is unambiguous and doesn't need this preprocessing.- * This function remains for backward compatibility with content saved before- * the `!file` syntax was introduced. As users edit old content, it auto-migrates- * to the new syntax on save.- *- * Input: `[report.pdf](https://multica-static.copilothub.ai/xxx.pdf)`- * Output: `<div data-type="fileCard" data-href="url" data-filename="report.pdf"></div>`- */-/** New syntax: !file[name](url) — unambiguous, no hostname matching needed. */-const NEW_FILE_CARD_RE = /^!file\[([^\]]*)\]\((https?:\/\/[^)]+)\)$/;--/** Legacy syntax: [name](cdnUrl) on its own line — matched by CDN hostname. */-const FILE_LINK_LINE = /^\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/;--function escapeAttr(s: string): string {- return s.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");-}--function toFileCardHtml(filename: string, url: string): string {- return `<div data-type="fileCard" data-href="${escapeAttr(url)}" data-filename="${escapeAttr(filename)}"></div>`;-}--function preprocessFileCards(markdown: string): string {- return markdown- .split("\n")- .map((line) => {- const trimmed = line.trim();-- // New syntax: !file[name](url) — always a file card, no hostname check needed.- const newMatch = trimmed.match(NEW_FILE_CARD_RE);- if (newMatch) {- return toFileCardHtml(newMatch[1]!, newMatch[2]!);- }-- // Legacy: [name](cdnUrl) on its own line — CDN hostname matching.- const match = trimmed.match(FILE_LINK_LINE);- if (!match) return line;- const filename = match[1]!;- const url = match[2]!;- if (!isFileCardUrl(url)) return line;- return toFileCardHtml(filename, url);- })- .join("\n");-}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex fed3c63b8e..5692d69740 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -151,6 +151,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Router.Use(middleware.RefreshCloudFrontCookies(cfSigner))// --- User-scoped routes (no workspace context required) ---+ r.Get("/api/config", h.GetConfig)r.Get("/api/me", h.GetMe)r.Patch("/api/me", h.UpdateMe)r.Post("/api/cli-token", h.IssueCliToken)diff --git a/server/internal/handler/config.go b/server/internal/handler/config.gonew file mode 100644index 0000000000..0736cec77c--- /dev/null+++ b/server/internal/handler/config.go@@ -0,0 +1,15 @@+package handler++import "net/http"++type AppConfig struct {+ CdnDomain string `json:"cdn_domain"`+}++func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {+ config := AppConfig{}+ if h.Storage != nil {+ config.CdnDomain = h.Storage.CdnDomain()+ }+ writeJSON(w, http.StatusOK, config)+}diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex 1e9823da3c..88ec384798 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -19,6 +19,7 @@ func (m *mockStorage) Upload(_ context.Context, key string, _ []byte, _ string,func (m *mockStorage) Delete(_ context.Context, _ string) {}func (m *mockStorage) DeleteKeys(_ context.Context, _ []string) {}func (m *mockStorage) KeyFromURL(rawURL string) string { return rawURL }+func (m *mockStorage) CdnDomain() string { return "cdn.example.com" }func TestUploadFileForeignWorkspace(t *testing.T) {origStorage := testHandler.Storagediff --git a/server/internal/storage/local.go b/server/internal/storage/local.goindex cc2950207f..e42947f53a 100644--- a/server/internal/storage/local.go+++ b/server/internal/storage/local.go@@ -6,6 +6,7 @@ import ("io""log/slog""net/http"+ "net/url""os""path/filepath""strings"@@ -42,6 +43,17 @@ func NewLocalStorageFromEnv() *LocalStorage {}}+func (s *LocalStorage) CdnDomain() string {+ if s.baseURL == "" {+ return ""+ }+ u, err := url.Parse(s.baseURL)+ if err != nil {+ return ""+ }+ return u.Hostname()+}+func (s *LocalStorage) KeyFromURL(rawURL string) string {if s.baseURL != "" && strings.HasPrefix(rawURL, s.baseURL) {rawURL = strings.TrimPrefix(rawURL, s.baseURL)diff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.goindex 6ac13e537a..80d498bdcb 100644--- a/server/internal/storage/s3.go+++ b/server/internal/storage/s3.go@@ -79,6 +79,10 @@ func NewS3StorageFromEnv() *S3Storage {}}+func (s *S3Storage) CdnDomain() string {+ return s.cdnDomain+}+// storageClass returns the appropriate S3 storage class.// Custom endpoints (e.g. MinIO) only support STANDARD; real AWS defaults to INTELLIGENT_TIERING.func (s *S3Storage) storageClass() types.StorageClass {diff --git a/server/internal/storage/storage.go b/server/internal/storage/storage.goindex b35fd222c3..ef9816ac08 100644--- a/server/internal/storage/storage.go+++ b/server/internal/storage/storage.go@@ -9,4 +9,5 @@ type Storage interface {Delete(ctx context.Context, key string)DeleteKeys(ctx context.Context, keys []string)KeyFromURL(rawURL string) string+ CdnDomain() string}