Skip to content

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

Go

fix(editor): prevent incorrect comment autolinks (#5665)

Naiyuan Qing41315989bd53
diff --git a/packages/ui/markdown/index.ts b/packages/ui/markdown/index.ts
index 795872a030..ce609eb5d5 100644
--- a/packages/ui/markdown/index.ts
+++ b/packages/ui/markdown/index.ts
@@ -1,7 +1,7 @@
export { Markdown, MemoizedMarkdown, type MarkdownProps, type RenderMode } from './Markdown'
export { CodeBlock, InlineCode, type CodeBlockProps } from './CodeBlock'
export { StreamingMarkdown, type StreamingMarkdownProps } from './StreamingMarkdown'
-export { preprocessLinks, detectLinks, hasLinks } from './linkify'
+export { preprocessLinks, detectLinks, hasLinks, shouldAutoLink } from './linkify'
export {
preprocessIssueIdentifiers,
isIssueIdentifier,
diff --git a/packages/ui/markdown/linkify.ts b/packages/ui/markdown/linkify.ts
index 88e29de118..fab1ba7a5d 100644
--- a/packages/ui/markdown/linkify.ts
+++ b/packages/ui/markdown/linkify.ts
@@ -7,11 +7,11 @@ import LinkifyIt from 'linkify-it'
* plus custom regex for local file paths.
*/
-// Initialize linkify-it with default settings (fuzzy URLs, emails enabled)
+// Keep fuzzy detection enabled so linkify-it can recognize `www.` URLs.
+// collectLinkifyMatches applies the stricter shared product policy below.
const linkify = new LinkifyIt()
-// Common source/config file extensions. Shared between the file-path detector
-// and the bare-filename guard below so the two never drift.
+// Common source/config file extensions used by the file-path detector.
const FILE_EXTENSIONS =
'ts|tsx|js|jsx|mjs|cjs|md|json|yaml|yml|py|go|rs|css|scss|less|html|htm|txt|log|sh|bash|zsh|swift|kt|java|c|cpp|h|hpp|rb|php|xml|toml|ini|cfg|conf|env|sql|graphql|vue|svelte|astro|prisma|dockerfile|makefile|gitignore'
@@ -22,13 +22,6 @@ const FILE_PATH_REGEX = new RegExp(
'gi'
)
-// A bare filename token like "plan.md" or "vite.config.ts": a single path
-// segment ending in a known file extension, with no slash, scheme, or port.
-// linkify-it fuzzy-matches these as domains because several of the extensions
-// (md, sh, rs, py, …) are also valid TLDs. We use this to stop bare
-// filenames from being auto-linked to dead external sites like https://plan.md.
-const BARE_FILENAME_REGEX = new RegExp(`^[\\w.-]+\\.(?:${FILE_EXTENSIONS})$`, 'i')
-
// CJK full-width punctuation that should terminate a URL.
// linkify-it only treats ASCII punctuation as URL boundaries, so in Chinese /
// Japanese text a URL followed by e.g. "。" gets the punctuation and every
@@ -60,6 +53,26 @@ export interface CodeRange {
end: number
}
+/**
+ * Product policy for automatic external links.
+ *
+ * Detectors call this only after validating a candidate. This function decides
+ * which validated text forms are safe to turn into a link without an explicit
+ * user action: HTTP(S) URLs, `www.` URLs, and email addresses. In particular,
+ * all other scheme-less domains stay plain text, which also prevents filenames
+ * such as `plan.md` from being mistaken for websites.
+ *
+ * Keep this predicate shared by the editor and markdown renderer so typing,
+ * paste, and read-only display cannot drift again.
+ */
+export function shouldAutoLink(value: string): boolean {
+ return (
+ /^https?:\/\//i.test(value) ||
+ /^www\./i.test(value) ||
+ /^[^\s@/:]+@[^\s@/:]+\.[^\s@/:]+$/.test(value)
+ )
+}
+
/**
* Find all code block and inline code ranges in text
* These ranges should be excluded from link detection
@@ -255,18 +268,18 @@ function collectLinkifyMatches(text: string, offset: number, out: DetectedLink[]
''
)
- // Bare filenames such as "plan.md" or "README.md" are fuzzy-matched as
- // domains because their extension is also a valid TLD. They are file
- // references, not URLs — leave them as plain text rather than link to a
- // dead external site. Only schemeless (fuzzy) matches are suppressed; an
- // explicit "https://plan.md" the author typed is still honored.
- if (matchText.length > 0 && !(match.schema === '' && BARE_FILENAME_REGEX.test(matchText))) {
+ if (matchText.length > 0 && shouldAutoLink(matchText)) {
// When we trimmed the raw match, rebuild the href from the scheme prefix
// linkify-it added (e.g. "http://" / "mailto:") plus the trimmed text;
// otherwise keep linkify-it's normalized url as-is.
const trimmed = matchText.length !== match.text.length
const schemePrefix = match.url.slice(0, match.url.length - match.text.length)
- const matchUrl = trimmed ? schemePrefix + matchText : match.url
+ const matchUrl =
+ match.schema === '' && /^www\./i.test(matchText)
+ ? `https://${matchText}`
+ : trimmed
+ ? schemePrefix + matchText
+ : match.url
out.push({
type: match.schema === 'mailto:' ? 'email' : 'url',
diff --git a/packages/views/chat/components/chat-input.test.tsx b/packages/views/chat/components/chat-input.test.tsx
index b97074378e..b5f7c2031c 100644
--- a/packages/views/chat/components/chat-input.test.tsx
+++ b/packages/views/chat/components/chat-input.test.tsx
@@ -1,4 +1,4 @@
-import { forwardRef, useRef, useImperativeHandle } from "react";
+import { forwardRef, useEffect, useRef, useImperativeHandle } from "react";
import { beforeEach, describe, it, expect, vi } from "vitest";
import { act, render, screen, fireEvent, waitFor } from "@testing-library/react";
import { I18nProvider } from "@multica/core/i18n/react";
@@ -57,6 +57,7 @@ vi.mock("../../editor", async () => ({
ContentEditor: forwardRef(function MockContentEditor(
props: {
defaultValue?: string;
+ value?: string;
onUpdate?: (md: string) => void;
placeholder?: string;
onUploadFile?: (file: File) => Promise<UploadResult | null>;
@@ -68,14 +69,18 @@ vi.mock("../../editor", async () => ({
) {
const {
defaultValue,
+ value,
onUpdate,
placeholder,
onUploadFile,
onUploadingChange,
} = props;
editorProps.last = props as unknown as Record<string, unknown>;
- const valueRef = useRef<string>(defaultValue ?? "");
+ const valueRef = useRef<string>(value ?? defaultValue ?? "");
const uploadingRef = useRef(0);
+ useEffect(() => {
+ if (value !== undefined) valueRef.current = value;
+ }, [value]);
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
clearContent: () => {
@@ -128,6 +133,7 @@ vi.mock("../../editor", async () => ({
return (
<textarea
data-testid="editor"
+ defaultValue={value ?? defaultValue}
placeholder={placeholder}
onChange={(e) => {
valueRef.current = e.target.value;
@@ -542,7 +548,7 @@ describe("ChatInput async send", () => {
"__draft_new__",
"bring this back",
);
- expect(editorProps.last?.defaultValue).toBe("bring this back");
+ expect(editorProps.last?.value).toBe("bring this back");
// The single terminal transition — the owner may now delete the server row.
expect(onRestoreDraftApplied).toHaveBeenCalledTimes(1);
});
@@ -568,7 +574,7 @@ describe("ChatInput async send", () => {
);
await waitFor(() => {
- expect(editorProps.last?.defaultValue).toBe("already typing");
+ expect(editorProps.last?.value).toBe("already typing");
});
expect(onRestoreDraftApplied).not.toHaveBeenCalled();
expect(state.setInputDraft).not.toHaveBeenCalledWith(
@@ -730,7 +736,7 @@ describe("ChatInput async send", () => {
// A failed fire-and-forget send must restore into the session it was sent
// FROM, never into whatever session the user navigated to in the meantime.
// The send affordance must not hang off `isEmpty` alone. ChatInput does not
-// remount on a session switch and ContentEditor's defaultValue-sync uses
+// remount on a session switch and ContentEditor's synchronized value uses
// emitUpdate:false, so a draft that arrives from the store — a restore parked
// by useChatDraftRestore, or any draft typed in another session — never moves
// `isEmpty`. Pinning the button to it left the user staring at their own text
@@ -756,7 +762,7 @@ describe("ChatInput send affordance", () => {
expect(sendButton()).toBeDisabled();
// Switch to the session holding the parked draft. The editor adopts it via
- // the defaultValue sync (emitUpdate:false → no onUpdate → isEmpty untouched).
+ // the value sync (emitUpdate:false → no onUpdate → isEmpty untouched).
state.activeSessionId = "session-b";
rerender(element({}));
diff --git a/packages/views/chat/components/chat-input.tsx b/packages/views/chat/components/chat-input.tsx
index cf3d4bb1ec..db006c925a 100644
--- a/packages/views/chat/components/chat-input.tsx
+++ b/packages/views/chat/components/chat-input.tsx
@@ -148,7 +148,7 @@ export function ChatInput({
// - Placeholder: ContentEditor's placeholder-sync effect refreshes it live,
// so it never needed a remount.
// - Draft restore (a cancelled run, a failed send): writes into
- // `inputDraft`, and the editor's defaultValue-sync effect pushes it into
+ // `inputDraft`, and the editor's synchronized-value effect pushes it into
// the live instance. There is no second copy to drift or resurface.
// - Session switch / lazy create: when the user uploads a file in a
// brand-new chat, `handleUploadFile` awaits `ensureSession`, which flips
@@ -175,7 +175,7 @@ export function ChatInput({
// debounce, so the send affordance cannot be derived from `inputDraft` alone.
// But `isEmpty` is never re-derived when the composer switches draft slots
// either: ChatInput does not remount on a session switch, and ContentEditor's
- // defaultValue-sync pushes the incoming draft in with `emitUpdate: false`, so
+ // synchronized-value effect pushes the incoming draft in with `emitUpdate: false`, so
// no onUpdate fires. Read BOTH signals — a draft `isEmpty` has not seen yet (a
// restored or parked one, or any persisted draft the user typed in another
// session) still enables the button. A false enable costs nothing: handleSend
@@ -230,7 +230,7 @@ export function ChatInput({
// Move the editor from the draft it holds to the draft that is selected.
//
- // Two hazards make this more than "let the defaultValue sync handle it":
+ // Two hazards make this more than "let the value sync handle it":
//
// 1. Unflushed keystrokes. `onUpdate` is debounced, and by the time a
// debounce armed under draft A fires, `onUpdate` resolves to the latest
@@ -243,7 +243,7 @@ export function ChatInput({
// a worse trade — the user waits on a network round-trip to change tabs.
//
// Case 2 also has to force the adopt afterwards: ContentEditor's sync effect
- // CONSUMED the defaultValue change while Guard 0 was up (lastDefaultValueRef
+ // CONSUMED the value change while Guard 0 was up (lastSyncedValueRef
// advances before the guard), so it will never re-run for that value and the
// target draft would never load on its own.
//
@@ -520,7 +520,7 @@ export function ChatInput({
// intentionally tracks neither the session nor the agent.
key={editorKey}
ref={editorRef}
- defaultValue={inputDraft}
+ value={inputDraft}
placeholder={placeholder}
onUpdate={(md) => {
setIsEmpty(!md.trim());
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsx
index 302c9a968e..fd9ceb3c00 100644
--- a/packages/views/editor/content-editor.test.tsx
+++ b/packages/views/editor/content-editor.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
-import { createRef } from "react";
+import { createRef, useState } from "react";
import type { Attachment } from "@multica/core/types";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
@@ -33,6 +33,7 @@ const providerProps = vi.hoisted<{ attachments: Attachment[] | undefined }>(
);
const uploadAndInsertFileMock = vi.hoisted(() => vi.fn());
+const preprocessMarkdownMock = vi.hoisted(() => vi.fn((value: string) => value));
vi.mock("@tanstack/react-query", () => ({
useQueryClient: () => ({}),
@@ -52,7 +53,7 @@ vi.mock("./extensions/file-upload", () => ({
}));
vi.mock("./utils/preprocess", () => ({
- preprocessMarkdown: (value: string) => value,
+ preprocessMarkdown: preprocessMarkdownMock,
}));
// Empty-list repair needs a live ProseMirror doc (covered by
@@ -167,6 +168,7 @@ describe("ContentEditor", () => {
latestEditorOptions.current = undefined;
providerProps.attachments = undefined;
capturedExtOptions.current = undefined;
+ preprocessMarkdownMock.mockImplementation((value: string) => value);
});
afterEach(() => {
@@ -192,15 +194,15 @@ describe("ContentEditor", () => {
expect(mockFocus).not.toHaveBeenCalled();
});
- it("syncs editor content when defaultValue changes externally and editor is unfocused", () => {
+ it("syncs editor content when value changes externally and editor is unfocused", () => {
editorState.markdown = "old content";
- const { rerender } = render(<ContentEditor defaultValue="old content" />);
+ const { rerender } = render(<ContentEditor value="old content" />);
expect(mockSetContent).not.toHaveBeenCalled();
// Editor still holds the old, in-sync content; external value changes.
editorState.markdown = "old content";
- rerender(<ContentEditor defaultValue="new content from server" />);
+ rerender(<ContentEditor value="new content from server" />);
expect(mockSetContent).toHaveBeenCalledTimes(1);
expect(mockSetContent).toHaveBeenCalledWith(
@@ -209,6 +211,15 @@ describe("ContentEditor", () => {
);
});
+ it("treats defaultValue as mount-only", () => {
+ editorState.markdown = "initial draft";
+ const { rerender } = render(<ContentEditor defaultValue="initial draft" />);
+
+ rerender(<ContentEditor defaultValue="draft store echo" />);
+
+ expect(mockSetContent).not.toHaveBeenCalled();
+ });
+
it("does not parse the initial defaultValue twice when markdown round-trip canonicalizes it", () => {
// useEditor already parsed defaultValue through its `content` option. The
// editor's canonical Markdown can legitimately differ from the source, so
@@ -222,35 +233,87 @@ describe("ContentEditor", () => {
expect(mockSetContent).not.toHaveBeenCalled();
});
- it("does not sync while a file upload is in flight (in-flight upload node must survive external defaultValue changes)", () => {
+ it("does not feed a locally emitted draft back through preprocessing", () => {
+ vi.useFakeTimers();
+ preprocessMarkdownMock.mockImplementation((value: string) =>
+ value === "dev.de" ? "[dev.de](http://dev.de)" : value,
+ );
+
+ function EchoingDraftHost() {
+ const [draft, setDraft] = useState("");
+ return (
+ <ContentEditor
+ defaultValue={draft}
+ onUpdate={setDraft}
+ debounceMs={100}
+ />
+ );
+ }
+
+ render(<EchoingDraftHost />);
+ editorState.markdown = "dev.de";
+
+ act(() => {
+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(mockSetContent).not.toHaveBeenCalled();
+ });
+
+ it("recognizes a synchronized value echo before preprocessing it", () => {
+ vi.useFakeTimers();
+ preprocessMarkdownMock.mockImplementation((value: string) =>
+ value === "dev.de" ? "[dev.de](http://dev.de)" : value,
+ );
+
+ function SynchronizedDraftHost() {
+ const [draft, setDraft] = useState("");
+ return (
+ <ContentEditor value={draft} onUpdate={setDraft} debounceMs={100} />
+ );
+ }
+
+ render(<SynchronizedDraftHost />);
+ editorState.markdown = "dev.de";
+
+ act(() => {
+ latestEditorOptions.current?.onUpdate?.({ editor: editorRef.current });
+ vi.advanceTimersByTime(100);
+ });
+
+ expect(mockSetContent).not.toHaveBeenCalled();
+ });
+
+ it("does not sync while a file upload is in flight (in-flight upload node must survive external value changes)", () => {
editorState.markdown = "old content";
- const { rerender } = render(<ContentEditor defaultValue="old content" />);
+ const { rerender } = render(<ContentEditor value="old content" />);
// A file is uploading: the doc holds a node with attrs.uploading. An
- // external defaultValue change (e.g. chat lazy-creating a session mid-upload
- // flips the draft key → defaultValue) must NOT setContent over it, or the
+ // external value change (e.g. chat lazy-creating a session mid-upload
+ // flips the draft key → value) must NOT setContent over it, or the
// uploading node is wiped and the upload's finalize can't find it.
editorState.uploadingNodes = [{ attrs: { uploading: true } }];
- rerender(<ContentEditor defaultValue="" />);
+ rerender(<ContentEditor value="" />);
expect(mockSetContent).not.toHaveBeenCalled();
// Once the upload settles (no uploading node), a later external change syncs.
editorState.uploadingNodes = [];
- rerender(<ContentEditor defaultValue="new content from server" />);
+ rerender(<ContentEditor value="new content from server" />);
expect(mockSetContent).toHaveBeenCalledTimes(1);
});
it("does not sync when editor is focused and has unsaved local edits", () => {
editorState.markdown = "old content";
- const { rerender } = render(<ContentEditor defaultValue="old content" />);
+ const { rerender } = render(<ContentEditor value="old content" />);
// User is typing — focused AND dirty (markdown diverges from
// lastEmittedRef, which was seeded with "old content" by onCreate).
editorState.isFocused = true;
editorState.markdown = "user-typed-content";
- rerender(<ContentEditor defaultValue="incoming external change" />);
+ rerender(<ContentEditor value="incoming external change" />);
expect(mockSetContent).not.toHaveBeenCalled();
});
@@ -262,12 +325,12 @@ describe("ContentEditor", () => {
// With an unconditional `if (isFocused) return`, this sync would be lost
// forever because onBlur has no replay path.
editorState.markdown = "old content";
- const { rerender } = render(<ContentEditor defaultValue="old content" />);
+ const { rerender } = render(<ContentEditor value="old content" />);
editorState.isFocused = true;
editorState.markdown = "old content"; // clean — no typing happened
- rerender(<ContentEditor defaultValue="new content from server" />);
+ rerender(<ContentEditor value="new content from server" />);
expect(mockSetContent).toHaveBeenCalledTimes(1);
expect(mockSetContent).toHaveBeenCalledWith(
@@ -279,7 +342,7 @@ describe("ContentEditor", () => {
it("does not sync when editor is unfocused but has unsaved local edits (blur-before-debounce window)", () => {
editorState.markdown = "old content";
const { rerender } = render(
- <ContentEditor defaultValue="old content" onUpdate={() => {}} />,
+ <ContentEditor value="old content" onUpdate={() => {}} />,
);
// User typed locally, then blurred. Debounce hasn't flushed yet so
@@ -289,7 +352,7 @@ describe("ContentEditor", () => {
rerender(
<ContentEditor
- defaultValue="external update from another agent"
+ value="external update from another agent"
onUpdate={() => {}}
/>,
);
@@ -337,12 +400,12 @@ describe("ContentEditor", () => {
expect(ref.current?.flushPendingUpdate()).toBeNull();
});
- it("leaves the editor clean so the next defaultValue sync is no longer blocked by the dirty guard", () => {
+ it("leaves the editor clean so the next value sync is no longer blocked by the dirty guard", () => {
vi.useFakeTimers();
const ref = createRef<ContentEditorRef>();
editorState.markdown = "draft A text";
const { rerender } = render(
- <ContentEditor ref={ref} defaultValue="draft A text" onUpdate={vi.fn()} debounceMs={100} />,
+ <ContentEditor ref={ref} value="draft A text" onUpdate={vi.fn()} debounceMs={100} />,
);
// Unflushed local edits — this is what makes the editor dirty.
@@ -357,7 +420,7 @@ describe("ContentEditor", () => {
// Host has taken the bytes, so switching destination must now load the
// incoming draft rather than leaving the old document on screen.
rerender(
- <ContentEditor ref={ref} defaultValue="draft B text" onUpdate={vi.fn()} debounceMs={100} />,
+ <ContentEditor ref={ref} value="draft B text" onUpdate={vi.fn()} debounceMs={100} />,
);
expect(mockSetContent).toHaveBeenCalled();
});
@@ -366,7 +429,7 @@ describe("ContentEditor", () => {
vi.useFakeTimers();
editorState.markdown = "draft A text";
const { rerender } = render(
- <ContentEditor defaultValue="draft A text" onUpdate={vi.fn()} debounceMs={100} />,
+ <ContentEditor value="draft A text" onUpdate={vi.fn()} debounceMs={100} />,
);
editorState.markdown = "draft A text, still typing";
@@ -375,19 +438,19 @@ describe("ContentEditor", () => {
});
// No flush → dirty → the guard must still protect the unsaved bytes.
- rerender(<ContentEditor defaultValue="draft B text" onUpdate={vi.fn()} debounceMs={100} />);
+ rerender(<ContentEditor value="draft B text" onUpdate={vi.fn()} debounceMs={100} />);
expect(mockSetContent).not.toHaveBeenCalled();
});
});
- it("does not sync when defaultValue normalizes to the current editor markdown", () => {
+ it("does not sync when value normalizes to the current editor markdown", () => {
editorState.markdown = "same content";
- const { rerender } = render(<ContentEditor defaultValue="same content" />);
+ const { rerender } = render(<ContentEditor value="same content" />);
- // Different `defaultValue` string forces the effect to re-run (the dep
+ // Different `value` string forces the effect to re-run (the dep
// array sees a new value), but the trailing whitespace normalises away
// via `trimEnd()`, so `setContent` must still short-circuit.
- rerender(<ContentEditor defaultValue={"same content\n"} />);
+ rerender(<ContentEditor value={"same content\n"} />);
expect(mockSetContent).not.toHaveBeenCalled();
});
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index a666462cce..3ee8e4ba79 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -111,8 +111,7 @@ function hasUploadingNode(editor: Editor): boolean {
// Types
// ---------------------------------------------------------------------------
-interface ContentEditorProps {
- defaultValue?: string;
+interface ContentEditorBaseProps {
onUpdate?: (markdown: string) => void;
placeholder?: string;
className?: string;
@@ -192,6 +191,24 @@ interface ContentEditorProps {
onReady?: () => void;
}
+type ContentEditorValueProps =
+ | {
+ /** Initial markdown, read once when the editor mounts. */
+ defaultValue?: string;
+ value?: never;
+ }
+ | {
+ /**
+ * Externally synchronized markdown. Use only when changes from outside
+ * this editor must replace its document (for example realtime server
+ * updates or switching the document held by a stable editor instance).
+ */
+ value: string;
+ defaultValue?: never;
+ };
+
+type ContentEditorProps = ContentEditorBaseProps & ContentEditorValueProps;
+
interface ContentEditorRef {
getMarkdown: () => string;
clearContent: () => void;
@@ -231,18 +248,18 @@ interface ContentEditorRef {
* always resolves to the latest render's closure, write the old document
* into the NEW destination. Taking the markdown back lets the host commit it
* where it was actually typed. Flushing also marks the editor clean, so the
- * dirty guard stops suppressing the incoming `defaultValue` sync.
+ * dirty guard stops suppressing the incoming synchronized `value`.
*
* Distinct from `flushPendingOnUnmount`: this is for a LIVE editor changing
* targets, so it reads the current document rather than a cached copy.
*/
flushPendingUpdate: () => string | null;
/**
- * Force `markdown` into the document, bypassing the `defaultValue` sync
+ * Force `markdown` into the document, bypassing the synchronized `value`
* guards.
*
- * Those guards SKIP permanently rather than defer: `lastDefaultValueRef`
- * advances before they run, so a `defaultValue` they refuse is never
+ * Those guards SKIP permanently rather than defer: `lastSyncedValueRef`
+ * advances before they run, so a `value` they refuse is never
* re-applied. That is correct for their usual case (the cache will send
* another value), but not for a host that re-points ONE instance at a
* different document and must land it exactly once — chat's draft switch,
@@ -262,7 +279,8 @@ interface ContentEditorRef {
const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
function ContentEditor(
{
- defaultValue = "",
+ defaultValue,
+ value,
onUpdate,
placeholder: placeholderText = "",
className,
@@ -300,11 +318,10 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
>(undefined);
const mentionContextItemsRef = useRef<MentionItem[]>(mentionContextItems ?? []);
const lastEmittedRef = useRef<string | null>(null);
- // `content` already consumes the initial defaultValue when Tiptap mounts.
- // Track the prop separately so the external-sync effect only handles real
- // changes after mount, not Markdown serializer canonicalization from that
- // first parse.
- const lastDefaultValueRef = useRef(defaultValue);
+ // `content` already consumes the initial synchronized value when Tiptap
+ // 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);
// 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
@@ -420,7 +437,10 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
return issue ? { id: issue.id, identifier: issue.identifier } : null;
};
- const initialContent = defaultValue ? preprocessMarkdown(defaultValue) : "";
+ const initialMarkdown = value ?? defaultValue ?? "";
+ const initialContent = initialMarkdown
+ ? preprocessMarkdown(initialMarkdown)
+ : "";
// With `immediatelyRender: false` the Tiptap instance is created after
// mount, so an imperative `focus()` fired on the same tick (e.g. chat
// auto-focusing a brand-new conversation) would hit a null editor and no-op.
@@ -466,7 +486,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
content: mountChunked ? "" : initialContent,
contentType: mountChunked
? undefined
- : defaultValue
+ : initialMarkdown
? "markdown"
: undefined,
extensions: createEditorExtensions({
@@ -588,18 +608,26 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
}, []);
// Replace the live document with external markdown. Shared by the
- // `defaultValue` sync effect below and the imperative `adoptContent`, so
+ // synchronized `value` effect below and the imperative `adoptContent`, so
// both land content identically — chunked parse for large docs, no
// onUpdate echo, caret preserved. Callers own the decision to apply;
// the guards live in the effect, not here.
const applyExternalContent = useCallback(
(markdown: string) => {
if (!editor || editor.isDestroyed) return;
+ const before = normalizeEditorMarkdown(editor);
+
+ // A controlled host commonly echoes the exact Markdown this editor
+ // just emitted. Recognize that acknowledgment before preprocessing:
+ // preprocessing a half-typed token can change its meaning (for
+ // example `dev.de` used to become a link during a debounce pause).
+ if (normalizeMarkdown(markdown) === before) return;
+
const incoming = markdown ? preprocessMarkdown(markdown) : "";
const incomingNormalized = normalizeMarkdown(incoming);
// Normalized-equal short-circuit. Avoids a no-op transaction when the
- // cache reflects a write this same editor just emitted.
- if (incomingNormalized === normalizeEditorMarkdown(editor)) return;
+ // preprocessed input serializes to the document already on screen.
+ if (incomingNormalized === before) return;
// `emitUpdate: false`. Tiptap v3's setContent defaults to
// `emitUpdate: true`; without this we would re-trigger onUpdate →
@@ -639,34 +667,37 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
[editor],
);
- // Sync external `defaultValue` changes into the editor.
+ // Sync explicit external `value` changes into the editor. `defaultValue`
+ // is deliberately mount-only, matching React's normal uncontrolled-input
+ // contract; drafts therefore cannot feed their own debounced writes back
+ // into the live editor.
// Tiptap v3 `useEditor` reads `content` only at mount (ueberdosis/tiptap#5831);
// without this effect, a WS-driven description update keeps the editor
// showing stale content until the issue is closed and reopened.
useEffect(() => {
- if (!editor || editor.isDestroyed) return;
+ if (!editor || editor.isDestroyed || value === undefined) return;
- const previousDefaultValue = lastDefaultValueRef.current;
- lastDefaultValueRef.current = defaultValue;
+ const previousValue = lastSyncedValueRef.current;
+ lastSyncedValueRef.current = value;
- // The initial defaultValue was already parsed through useEditor's
+ // The initial value was already parsed through useEditor's
// `content` option (or in onCreate for the chunked path). Comparing that
// source Markdown to Tiptap's canonical serialization can differ even
// when they represent the same document, and used to cause an immediate
// second full parse. Only later prop changes belong to this sync effect.
- if (defaultValue === previousDefaultValue) return;
+ if (value === previousValue) return;
- // Guard 0: never clobber an in-flight upload. An external `defaultValue`
+ // Guard 0: never clobber an in-flight upload. An external `value`
// change can arrive mid-upload — e.g. chat lazy-creates a session on the
// first file upload, which flips `activeSessionId` → the draft key →
- // `defaultValue`. If we `setContent` over a document that still holds an
+ // `value`. If we `setContent` over a document that still holds an
// `uploading` image/fileCard node, that node is wiped and the upload's
// finalize can no longer find it (the file vanishes, leaving an empty
// `!file[name]()`). Like the dirty guards below, an uploading node is
// local state that an external sync must not overwrite.
//
// NOTE: this (like every guard here) SKIPS the sync permanently for this
- // value — `lastDefaultValueRef` has already advanced, so the effect will
+ // value — `lastSyncedValueRef` has already advanced, so the effect will
// not re-run for it. A host that must still land this content once the
// block clears has to say so explicitly, via `adoptContent`.
if (hasUploadingNode(editor)) return;
@@ -691,8 +722,8 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
// here avoids overwriting unsaved local edits.
if (isDirty) return;
- applyExternalContent(defaultValue);
- }, [defaultValue, editor, applyExternalContent]);
+ applyExternalContent(value);
+ }, [value, editor, applyExternalContent]);
// Sync external `placeholder` changes into the mounted editor.
// The Placeholder extension is configured with a getter over `placeholderRef`
@@ -765,7 +796,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (md === lastEmittedRef.current) return null;
// Advance the emit watermark so the editor reads as clean — the host
// is taking responsibility for these bytes, and the dirty guard must
- // now let the incoming defaultValue through.
+ // now let the incoming synchronized value through.
lastEmittedRef.current = md;
return md;
},
diff --git a/packages/views/editor/extensions/autolink-email-repair.test.ts b/packages/views/editor/extensions/autolink-email-repair.test.ts
deleted file mode 100644
index 86164b4d2e..0000000000
--- a/packages/views/editor/extensions/autolink-email-repair.test.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { afterEach, describe, expect, it } from "vitest";
-import { Editor } from "@tiptap/core";
-import StarterKit from "@tiptap/starter-kit";
-import Link from "@tiptap/extension-link";
-import { Markdown } from "@tiptap/markdown";
-import { AutolinkEmailRepairExtension } from "./autolink-email-repair";
-
-const LinkExtension = Link.extend({ inclusive: false }).configure({
- openOnClick: false,
- autolink: true,
- linkOnPaste: true,
- defaultProtocol: "https",
-});
-
-let editor: Editor | null = null;
-
-function makeEditor(): Editor {
- const element = document.createElement("div");
- document.body.appendChild(element);
- return new Editor({
- element,
- extensions: [
- StarterKit.configure({ link: false }),
- LinkExtension,
- AutolinkEmailRepairExtension,
- Markdown.configure({ indentation: { style: "space", size: 3 } }),
- ],
- });
-}
-
-/**
- * Simulate the split-link scenario: a mailto: link followed by trailing plain
- * text in the same paragraph. This mirrors what happens when autolink fires on
- * `[email protected]` and the user then types `m`.
- */
-function setSplitEmailLink(
- ed: Editor,
- linkText: string,
- trailingText: string,
-): void {
- const linkMark = ed.schema.marks.link!.create({
- href: `mailto:${linkText}`,
- });
- const { tr } = ed.state;
- const linkedNode = ed.schema.text(linkText, [linkMark]);
- const trailingNode = ed.schema.text(trailingText);
- const paragraph = ed.schema.nodes.paragraph!.create(null, [
- linkedNode,
- trailingNode,
- ]);
- tr.replaceWith(0, ed.state.doc.content.size, paragraph);
- ed.view.dispatch(tr);
-}
-
-afterEach(() => {
- editor?.destroy();
- editor = null;
- document.body.innerHTML = "";
-});
-
-describe("AutolinkEmailRepairExtension", () => {
- it("extends .co link when trailing text completes .com", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", "m");
-
- const markdown = editor.getMarkdown().trim();
- expect(markdown).toBe("[[email protected]](mailto:[email protected])");
- });
-
- it("extends .co link when trailing text completes .co.uk", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", ".uk");
-
- const markdown = editor.getMarkdown().trim();
- expect(markdown).toBe(
- );
- });
-
- it("extends .i link when trailing text completes .io", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", "o");
-
- const markdown = editor.getMarkdown().trim();
- expect(markdown).toBe("[[email protected]](mailto:[email protected])");
- });
-
- it("does NOT absorb random text after an email link", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", " hello");
-
- const markdown = editor.getMarkdown().trim();
- // The link should stay as-is; " hello" should remain outside.
- expect(markdown).toContain("[[email protected]](mailto:[email protected])");
- expect(markdown).toContain("hello");
- expect(markdown).not.toBe(
- "[[email protected] hello](mailto:[email protected] hello)",
- );
- });
-
- it("does NOT affect regular URL links", () => {
- editor = makeEditor();
- const linkMark = editor.schema.marks.link!.create({
- href: "https://example.co",
- });
- const { tr } = editor.state;
- const linkedNode = editor.schema.text("example.co", [linkMark]);
- const trailingNode = editor.schema.text("m");
- const paragraph = editor.schema.nodes.paragraph!.create(null, [
- linkedNode,
- trailingNode,
- ]);
- tr.replaceWith(0, editor.state.doc.content.size, paragraph);
- editor.view.dispatch(tr);
-
- const markdown = editor.getMarkdown().trim();
- // The trailing "m" should NOT be absorbed into the URL link.
- expect(markdown).toContain("[example.co](https://example.co)");
- expect(markdown).toMatch(/\)m/);
- });
-
- it("does NOT extend when no prefix of trailing text forms a valid email", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", "random");
-
- const markdown = editor.getMarkdown().trim();
- // "[email protected]" — no prefix of "random" makes a valid email.
- expect(markdown).toContain("[[email protected]](mailto:[email protected])");
- expect(markdown).toContain("random");
- });
-
- it("finds the longest valid extension (.co + .uk, not just .co + .)", () => {
- editor = makeEditor();
- setSplitEmailLink(editor, "[email protected]", ".uk extra");
-
- const markdown = editor.getMarkdown().trim();
- expect(markdown).toContain(
- );
- expect(markdown).toContain("extra");
- });
-});
diff --git a/packages/views/editor/extensions/autolink-email-repair.ts b/packages/views/editor/extensions/autolink-email-repair.ts
deleted file mode 100644
index 7366b7d111..0000000000
--- a/packages/views/editor/extensions/autolink-email-repair.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * AutolinkEmailRepair — fixes split email links caused by TipTap autolink.
- *
- * Problem: when a user types `[email protected]`, TipTap's autolink fires
- * because `.co` is a valid TLD. With `inclusive: false` on the Link extension,
- * the next character typed (e.g. `m` to complete `.com`) lands outside the link
- * mark. The markdown output becomes `[[email protected]](mailto:…)m` instead
- * of `[[email protected]](mailto:…)`.
- *
- * Fix: an `appendTransaction` plugin that runs after every doc change. It scans
- * for `mailto:` link marks that are immediately followed by plain text. If the
- * combined string (link text + trailing text) forms a valid email according to
- * the shared link detector, the plugin extends the link mark to cover the full
- * address and updates the href.
- *
- * Only `mailto:` links are affected — regular URL links are left untouched.
- */
-import { Extension } from "@tiptap/core";
-import { Plugin, PluginKey } from "@tiptap/pm/state";
-import { detectLinks } from "@multica/ui/markdown/linkify";
-
-export const AutolinkEmailRepairExtension = Extension.create({
- name: "autolinkEmailRepair",
-
- addProseMirrorPlugins() {
- const linkType = this.editor.schema.marks.link;
- if (!linkType) return [];
-
- return [
- new Plugin({
- key: new PluginKey("autolinkEmailRepair"),
- appendTransaction(_transactions, _oldState, newState) {
- const { tr } = newState;
- let modified = false;
-
- newState.doc.descendants((node, pos) => {
- if (!node.isTextblock) return;
-
- // Walk children of this text block looking for link-mark boundaries.
- for (let i = 0; i < node.childCount - 1; i++) {
- const child = node.child(i);
- const nextChild = node.child(i + 1);
-
- // Find a text node with a mailto: link mark followed by a plain
- // text node (no link mark).
- const linkMark = child.marks.find(
- (m) =>
- m.type === linkType &&
- typeof m.attrs.href === "string" &&
- m.attrs.href.startsWith("mailto:"),
- );
- if (!linkMark) continue;
- if (!nextChild.isText || !nextChild.text) continue;
- if (nextChild.marks.some((m) => m.type === linkType)) continue;
-
- const linkText = child.text || "";
- const trailingText = nextChild.text!;
-
- // Try progressively longer slices of the trailing text to find the
- // longest valid email extension (e.g. `.co` + `.uk` → `.co.uk`).
- let bestLen = 0;
- let bestHref = "";
- for (let len = 1; len <= trailingText.length; len++) {
- const candidate = linkText + trailingText.slice(0, len);
- const matches = detectLinks(candidate);
- const match = matches[0];
- if (
- matches.length === 1 &&
- match &&
- match.type === "email" &&
- match.text === candidate
- ) {
- bestLen = len;
- bestHref = match.url;
- }
- }
-
- if (bestLen > 0) {
- // Compute absolute positions. `pos` is the position before the
- // text block node; content starts at pos + 1. We need the offset
- // of `child` within the text block.
- let childOffset = 0;
- for (let j = 0; j < i; j++) {
- childOffset += node.child(j).nodeSize;
- }
- const linkFrom = pos + 1 + childOffset;
- const linkEnd = linkFrom + linkText.length;
- const extendTo = linkEnd + bestLen;
-
- const newMark = linkType.create({ href: bestHref });
- tr.addMark(linkFrom, extendTo, newMark);
- modified = true;
- }
- }
- });
-
- return modified ? tr : undefined;
- },
- }),
- ];
- },
-});
diff --git a/packages/views/editor/extensions/autolink-policy.test.ts b/packages/views/editor/extensions/autolink-policy.test.ts
new file mode 100644
index 0000000000..0c456e31f8
--- /dev/null
+++ b/packages/views/editor/extensions/autolink-policy.test.ts
@@ -0,0 +1,135 @@
+import { afterEach, describe, expect, it } from "vitest";
+import { Editor } from "@tiptap/core";
+import { createEditorExtensions } from ".";
+
+let editor: Editor | null = null;
+
+function makeProductionEditor(): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+
+ return new Editor({
+ element,
+ extensions: createEditorExtensions({
+ placeholder: "",
+ disableMentions: true,
+ enableSlashCommands: false,
+ onUploadFileRef: { current: undefined },
+ }),
+ });
+}
+
+function typeText(ed: Editor, text: string): void {
+ for (const char of text) {
+ const { from, to } = ed.state.selection;
+ const handled = ed.view.someProp("handleTextInput", (handler) =>
+ handler(ed.view, from, to, char, () => ed.state.tr),
+ );
+ if (!handled) {
+ ed.view.dispatch(ed.state.tr.insertText(char, from, to));
+ }
+ }
+}
+
+function pastePlainText(ed: Editor, text: string): void {
+ const event = new Event("paste", { bubbles: false, cancelable: true });
+ Object.defineProperty(event, "clipboardData", {
+ value: {
+ files: [],
+ getData: (type: string) => (type === "text/plain" ? text : ""),
+ },
+ });
+ ed.view.dom.dispatchEvent(event);
+}
+
+afterEach(() => {
+ editor?.destroy();
+ editor = null;
+ document.body.innerHTML = "";
+});
+
+describe("editor autolink policy", () => {
+ it.each(["ai.md", "build.sh", "main.rs", "app.py", "4399.com"])(
+ "keeps bare token %s as plain text",
+ (token) => {
+ editor = makeProductionEditor();
+
+ typeText(editor, `${token} `);
+
+ expect(editor.getMarkdown().trim()).toBe(token);
+ },
+ );
+
+ it.each([
+ ["http://4399.com", "http://4399.com"],
+ ["https://4399.com", "https://4399.com"],
+ ["www.4399.com", "https://www.4399.com"],
+ ])("auto-links %s", (text, href) => {
+ editor = makeProductionEditor();
+
+ typeText(editor, `${text} `);
+
+ expect(editor.getMarkdown().trim()).toBe(`[${text}](${href})`);
+ });
+
+ it("does not auto-link unsupported URL schemes", () => {
+ editor = makeProductionEditor();
+
+ typeText(editor, "ftp://example.com ");
+
+ expect(editor.getMarkdown().trim()).toBe("ftp://example.com");
+ });
+
+ it("does not link an incomplete email during a pause and links it only after completion", () => {
+ editor = makeProductionEditor();
+
+ typeText(editor, "[email protected]");
+ expect(editor.getMarkdown().trim()).toBe("[email protected]");
+
+ typeText(editor, "m ");
+ expect(editor.getMarkdown().trim()).toBe(
+ );
+ });
+
+ it("does not split a slowly completed bare domain", () => {
+ editor = makeProductionEditor();
+
+ typeText(editor, "test.de");
+ expect(editor.getMarkdown().trim()).toBe("test.de");
+
+ typeText(editor, "v ");
+ expect(editor.getMarkdown().trim()).toBe("test.dev");
+ });
+
+ it("does not turn a selection into a link when a bare domain is pasted", () => {
+ editor = makeProductionEditor();
+ editor.commands.setContent("selected text", {
+ emitUpdate: false,
+ contentType: "markdown",
+ });
+ editor.commands.setTextSelection({ from: 1, to: 14 });
+
+ pastePlainText(editor, "ai.md");
+
+ expect(editor.getMarkdown().trim()).toBe("ai.md");
+ });
+
+ it.each([
+ ["https://4399.com", "https://4399.com"],
+ ["www.4399.com", "https://www.4399.com"],
+ ])("turns a selection into a link when %s is pasted", (text, href) => {
+ editor = makeProductionEditor();
+ editor.commands.setContent("selected text", {
+ emitUpdate: false,
+ contentType: "markdown",
+ });
+ editor.commands.setTextSelection({ from: 1, to: 14 });
+
+ pastePlainText(editor, text);
+
+ expect(editor.getMarkdown().trim()).toBe(`[selected text](${href})`);
+ });
+});
diff --git a/packages/views/editor/extensions/index.ts b/packages/views/editor/extensions/index.ts
index 307dc7c382..7bf3619275 100644
--- a/packages/views/editor/extensions/index.ts
+++ b/packages/views/editor/extensions/index.ts
@@ -35,6 +35,7 @@ import { Markdown } from "@tiptap/markdown";
import { ReactNodeViewRenderer } from "@tiptap/react";
import type { AnyExtension } from "@tiptap/core";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
+import { shouldAutoLink } from "@multica/ui/markdown";
import { escapeMarkdownLabel } from "../utils/escape-markdown-label";
import { BaseMentionExtension } from "./mention-extension";
import { createMentionSuggestion, type MentionItem } from "./mention-suggestion";
@@ -55,7 +56,6 @@ import { FileCardExtension } from "./file-card";
import { ImageView } from "./image-view";
import { BlockMathExtension, InlineMathExtension } from "./math";
import { HighlightExtension } from "./highlight";
-import { AutolinkEmailRepairExtension } from "./autolink-email-repair";
import { codeLowlight } from "../syntax-highlight";
const LinkExtension = Link.extend({ inclusive: false }).configure({
@@ -63,6 +63,7 @@ const LinkExtension = Link.extend({ inclusive: false }).configure({
autolink: true,
linkOnPaste: true,
defaultProtocol: "https",
+ shouldAutoLink,
});
export const ImageExtension = Image.extend({
@@ -202,7 +203,6 @@ export function createEditorExtensions(
// linkOnPaste relies on Link's handlePaste plugin firing first;
// markdownPaste's handlePaste is a catch-all that returns true.
LinkExtension,
- AutolinkEmailRepairExtension,
ImageExtension,
// renderWrapper wraps the table in `<div class="tableWrapper">` (the same
// wrapper the resizable NodeView emits), which prose.css styles with
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 883396c72b..13fb8bed9b 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -145,6 +145,34 @@ describe("ReadonlyContent line breaks", () => {
});
});
+describe("ReadonlyContent autolink policy", () => {
+ it("keeps historical bare filenames and domains as plain text", () => {
+ const { container } = render(
+ <ReadonlyContent content="plan.md 4399.com ai.md" />,
+ );
+
+ expect(container.textContent).toContain("plan.md 4399.com ai.md");
+ expect(container.querySelector("a")).toBeNull();
+ });
+
+ it("still links explicit web URLs, www URLs, and email addresses", () => {
+ const { container } = render(
+ <ReadonlyContent
+ content="https://4399.com www.4399.com [email protected]"
+ />,
+ );
+
+ const hrefs = Array.from(container.querySelectorAll("a"), (anchor) =>
+ anchor.getAttribute("href"),
+ );
+ expect(hrefs).toEqual([
+ "https://4399.com",
+ "https://www.4399.com",
+ "mailto:[email protected]",
+ ]);
+ });
+});
+
describe("ReadonlyContent task lists", () => {
it("renders `- [ ]` / `- [x]` as checkboxes and preserves the checked state", () => {
const { container } = render(
diff --git a/packages/views/editor/utils/preprocess-links.test.ts b/packages/views/editor/utils/preprocess-links.test.ts
index db9a62623e..3f021a820d 100644
--- a/packages/views/editor/utils/preprocess-links.test.ts
+++ b/packages/views/editor/utils/preprocess-links.test.ts
@@ -85,12 +85,10 @@ describe("preprocessLinks — CJK punctuation boundary", () => {
expect(preprocessLinks(input)).toBe(input);
});
- it("still linkifies fuzzy domains outside existing markdown links", () => {
+ it("leaves bare domains outside existing markdown links as plain text", () => {
const input = "数据来源:[NBA.com Schedule](https://www.nba.com/schedule),官网 NBA.com";
- expect(preprocessLinks(input)).toBe(
- "数据来源:[NBA.com Schedule](https://www.nba.com/schedule),官网 [NBA.com](http://NBA.com)",
- );
+ expect(preprocessLinks(input)).toBe(input);
});
});
@@ -120,13 +118,21 @@ describe("preprocessLinks — bare filenames are not auto-linked as URLs", () =>
);
});
- it("still linkifies real fuzzy domains whose TLD is not a file extension", () => {
- expect(preprocessLinks("官网 NBA.com")).toBe("官网 [NBA.com](http://NBA.com)");
+ it("leaves bare domains as plain text regardless of their TLD", () => {
+ expect(preprocessLinks("官网 NBA.com")).toBe("官网 NBA.com");
+ });
+
+ it("leaves both a bare filename and a bare domain as plain text", () => {
+ expect(preprocessLinks("plan.md,example.com")).toBe("plan.md,example.com");
});
- it("suppresses the bare filename but still linkifies a real domain after it", () => {
- expect(preprocessLinks("plan.md,example.com")).toBe(
- "plan.md,[example.com](http://example.com)",
+ it("auto-links only explicit web URLs, www URLs, and email addresses", () => {
+ expect(
+ preprocessLinks(
+ "http://4399.com https://4399.com www.4399.com [email protected] 4399.com ai.md ftp://example.com",
+ ),
+ ).toBe(
+ "[http://4399.com](http://4399.com) [https://4399.com](https://4399.com) [www.4399.com](https://www.4399.com) [[email protected]](mailto:[email protected]) 4399.com ai.md ftp://example.com",
);
});
diff --git a/packages/views/issues/components/comment-card-edit-gate.test.tsx b/packages/views/issues/components/comment-card-edit-gate.test.tsx
index 37cf6470e7..cbe7b2a868 100644
--- a/packages/views/issues/components/comment-card-edit-gate.test.tsx
+++ b/packages/views/issues/components/comment-card-edit-gate.test.tsx
@@ -8,6 +8,9 @@ import { useCommentDraftStore } from "@multica/core/issues/stores";
import { renderWithI18n } from "../../test/i18n";
const uploadWithToast = vi.hoisted(() => vi.fn());
+const editorDefaultValues = vi.hoisted(() => ({
+ values: [] as Array<string | undefined>,
+}));
vi.mock("@multica/core/api", () => ({
api: {},
@@ -69,6 +72,7 @@ vi.mock("../../editor", async () => ({
},
ref: Ref<unknown>,
) {
+ editorDefaultValues.values.push(defaultValue);
const valueRef = useRef(defaultValue ?? "");
// Mirrors the real editor's `uploading` node attrs — see the sibling
// composer suite for the same stand-in.
@@ -169,6 +173,25 @@ function getSaveButton() {
beforeEach(() => {
uploadWithToast.mockReset();
useCommentDraftStore.setState({ drafts: {} });
+ editorDefaultValues.values = [];
+});
+
+describe("comment edit — draft snapshot", () => {
+ it("does not feed the persisted edit draft back as a new editor default", async () => {
+ renderCard();
+ await startEditing();
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "test.de" },
+ });
+
+ expect(
+ useCommentDraftStore
+ .getState()
+ .getDraft("edit:issue-1:comment-1"),
+ ).toBe("test.de");
+ expect(editorDefaultValues.values.at(-1)).toBe("Original body");
+ });
});
// MUL-4808 — comment edit had no upload gate: saving mid-upload persisted the
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 896b6fbf35..e2d0419120 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -325,6 +325,7 @@ function useEditAttachmentState(
const { uploadWithToast } = useEditorUpload();
const [editing, setEditing] = useState(false);
const [saving, setSaving] = useState(false);
+ const [initialValue, setInitialValue] = useState(entry.content ?? "");
const editorRef = useRef<ContentEditorRef>(null);
// Saving mid-upload would persist the edit without the file the user just
// pasted in — same failure as posting a new comment.
@@ -366,10 +367,6 @@ function useEditAttachmentState(
const setDraft = useCommentDraftStore((s) => s.setDraft);
const clearDraft = useCommentDraftStore((s) => s.clearDraft);
- const initialValue = editing
- ? (getDraft(draftKey) ?? entry.content ?? "")
- : (entry.content ?? "");
-
useEffect(() => {
const visible = new Set(triggerPreview.agents.map((agent) => agent.id));
setSuppressedAgentIds((prev) => {
@@ -402,7 +399,9 @@ function useEditAttachmentState(
const startEdit = () => {
cancelledRef.current = false;
- setContent(getDraft(draftKey) ?? entry.content ?? "");
+ const draft = getDraft(draftKey) ?? entry.content ?? "";
+ setInitialValue(draft);
+ setContent(draft);
setRetainedStandaloneIds(initialStandaloneAttachmentIds(entry));
setEditing(true);
};
diff --git a/packages/views/issues/components/comment-composers.test.tsx b/packages/views/issues/components/comment-composers.test.tsx
index 0bc189104d..d74ed2a97c 100644
--- a/packages/views/issues/components/comment-composers.test.tsx
+++ b/packages/views/issues/components/comment-composers.test.tsx
@@ -9,6 +9,9 @@ import { CommentInput } from "./comment-input";
import { ReplyInput } from "./reply-input";
const uploadWithToast = vi.hoisted(() => vi.fn());
+const editorDefaultValues = vi.hoisted(() => ({
+ values: [] as Array<string | undefined>,
+}));
vi.mock("@multica/core/api", () => ({
api: {},
@@ -63,6 +66,7 @@ vi.mock("../../editor", async () => ({
},
ref: Ref<unknown>,
) {
+ editorDefaultValues.values.push(defaultValue);
const valueRef = useRef(defaultValue ?? "");
// Mirrors the real editor's `uploading` node attrs: the placeholder exists
// from before the await until the upload settles, `hasActiveUploads` reads
@@ -136,9 +140,11 @@ function renderCommentInput(onSubmit = vi.fn().mockResolvedValue(true)) {
function renderReplyInput({
onSubmit = vi.fn().mockResolvedValue(true),
size = "sm",
+ draftKey,
}: {
onSubmit?: (content: string, attachmentIds?: string[], suppressAgentIds?: string[]) => Promise<boolean>;
size?: "sm" | "default";
+ draftKey?: `reply:${string}:${string}`;
} = {}) {
const view = renderWithProviders(
<ReplyInput
@@ -148,6 +154,7 @@ function renderReplyInput({
avatarId="user-1"
onSubmit={onSubmit}
size={size}
+ draftKey={draftKey}
/>,
);
return { ...view, onSubmit };
@@ -176,6 +183,7 @@ beforeEach(() => {
// (e.g. the failed-send case) would trip the composers' draft-direct-mount
// path and hide the shell the next test expects.
useCommentDraftStore.setState({ drafts: {} });
+ editorDefaultValues.values = [];
});
describe("comment composers", () => {
@@ -248,6 +256,34 @@ describe("comment composers", () => {
});
});
+ it("keeps the main comment editor's initial draft snapshot after persistence rerenders", () => {
+ renderCommentInput();
+ activateComposer("comment-composer-shell");
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "test.de" },
+ });
+
+ expect(useCommentDraftStore.getState().getDraft("new:issue-1")).toBe("test.de");
+ expect(editorDefaultValues.values.at(-1)).toBeUndefined();
+ });
+
+ it("keeps the reply editor's initial draft snapshot after persistence rerenders", () => {
+ renderReplyInput({ draftKey: "reply:issue-1:comment-1" });
+ activateComposer("reply-composer-shell");
+
+ fireEvent.change(screen.getByTestId("editor"), {
+ target: { value: "test.de" },
+ });
+
+ expect(
+ useCommentDraftStore
+ .getState()
+ .getDraft("reply:issue-1:comment-1"),
+ ).toBe("test.de");
+ expect(editorDefaultValues.values.at(-1)).toBeUndefined();
+ });
+
it("locks the editor while the send is in flight, then clears on success", async () => {
let resolveSubmit: (ok: boolean) => void = () => {};
const onSubmit = vi.fn(
diff --git a/packages/views/issues/components/comment-input.tsx b/packages/views/issues/components/comment-input.tsx
index 907d5bd0ef..1f9f36b6a0 100644
--- a/packages/views/issues/components/comment-input.tsx
+++ b/packages/views/issues/components/comment-input.tsx
@@ -34,7 +34,9 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// initial content and the submit-button enable state — without this the
// button would be disabled even though the editor visibly contains text.
const draftKey = `new:${issueId}` as const;
- const initialDraft = useCommentDraftStore.getState().getDraft(draftKey);
+ const [initialDraft] = useState(() =>
+ useCommentDraftStore.getState().getDraft(draftKey),
+ );
const [content, setContent] = useState(initialDraft ?? "");
const [isEmpty, setIsEmpty] = useState(() => !initialDraft?.trim());
const [submitting, setSubmitting] = useState(false);
@@ -46,6 +48,7 @@ function CommentInput({ issueId, onSubmit }: CommentInputProps) {
// resolve text/code/markdown previews that require the attachment id.
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const { uploadWithToast } = useEditorUpload();
+
// Readonly-first: the composer renders as a same-looking static shell until
// the user shows intent (click / keyboard / file drop). An unsent draft is
// standing intent — mount the real editor immediately so the draft is
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 494a17db0c..69eaf821bb 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -148,29 +148,42 @@ vi.mock("../../editor", async () => ({
<div data-testid="readonly-content">{content}</div>
),
ContentEditor: forwardRef(function MockContentEditor(
- { defaultValue, onUpdate, placeholder, flushPendingOnUnmount, onReady }: any,
+ {
+ defaultValue,
+ value: syncedValue,
+ onUpdate,
+ placeholder,
+ flushPendingOnUnmount,
+ onReady,
+ }: any,
ref: any,
) {
- const valueRef = useRef(defaultValue || "");
- const [value, setValue] = useState(defaultValue || "");
+ const initialValue = syncedValue ?? defaultValue ?? "";
+ const valueRef = useRef(initialValue);
+ const [editorValue, setEditorValue] = useState(initialValue);
useEffect(() => {
contentEditorMounts.count += 1;
onReady?.();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ useEffect(() => {
+ if (syncedValue === undefined) return;
+ valueRef.current = syncedValue;
+ setEditorValue(syncedValue);
+ }, [syncedValue]);
useImperativeHandle(ref, () => ({
getMarkdown: () => valueRef.current,
- clearContent: () => { valueRef.current = ""; setValue(""); },
+ clearContent: () => { valueRef.current = ""; setEditorValue(""); },
focus: () => {},
focusAtCoords: () => {},
uploadFile: () => {},
}));
return (
<textarea
- value={value}
+ value={editorValue}
onChange={(e) => {
valueRef.current = e.target.value;
- setValue(e.target.value);
+ setEditorValue(e.target.value);
onUpdate?.(e.target.value);
}}
placeholder={placeholder}
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 6e584e1e74..cffa2b3412 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -882,8 +882,8 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
const didHighlightRef = useRef<string | null>(null);
// Issue data from TQ — uses detail query, seeded from list cache if available.
- // Only seed when description is present; list API omits it, and ContentEditor
- // reads defaultValue on mount only — seeding null description shows an empty editor.
+ // Only seed when description is present; the list API omits it, so a partial
+ // list row must not masquerade as a hydrated issue detail.
const { data: issue = null, isLoading: issueLoading } = useQuery({
...issueDetailOptions(wsId, id),
initialData: () => {
@@ -2160,7 +2160,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
<ContentEditor
ref={descEditorRef}
key={id}
- defaultValue={issue.description || ""}
+ value={issue.description || ""}
placeholder={t(($) => $.detail.desc_placeholder)}
onUpdate={(md) => {
// Bind any pending uploads still referenced in the markdown
diff --git a/packages/views/issues/components/reply-input.tsx b/packages/views/issues/components/reply-input.tsx
index c0d85c56a6..199b685fdd 100644
--- a/packages/views/issues/components/reply-input.tsx
+++ b/packages/views/issues/components/reply-input.tsx
@@ -58,9 +58,9 @@ function ReplyInput({
const uploadGate = useUploadGate(editorRef);
// If a draft key is provided, hydrate from store on mount (defaultValue is
// the only injection point on ContentEditorRef) and flush on every onUpdate.
- const initialDraft = draftKey
- ? useCommentDraftStore.getState().getDraft(draftKey)
- : undefined;
+ const [initialDraft] = useState(() =>
+ draftKey ? useCommentDraftStore.getState().getDraft(draftKey) : undefined,
+ );
const [content, setContent] = useState(initialDraft ?? "");
const setDraft = useCommentDraftStore((s) => s.setDraft);
const clearDraft = useCommentDraftStore((s) => s.clearDraft);
@@ -72,6 +72,7 @@ function ReplyInput({
// rationale (drives both submit-time attachment_ids and editor previews).
const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);
const { uploadWithToast } = useEditorUpload();
+
// Readonly-first: static shell until intent; an unsent draft mounts the
// real editor immediately (see CommentInput). This is also what keeps the
// reply box working across Virtuoso scroll-out — a typed draft rehydrates
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index 2a9b81466b..e266a1e576 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -451,7 +451,7 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
<ContentEditor
ref={descEditorRef}
key={projectId}
- defaultValue={project.description || ""}
+ value={project.description || ""}
placeholder={t(($) => $.detail.description_placeholder)}
onUpdate={(md) => handleUpdateField({ description: md || null })}
debounceMs={1500}
diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsx
index ac720c0216..595d50a204 100644
--- a/packages/views/squads/components/squad-detail-page.tsx
+++ b/packages/views/squads/components/squad-detail-page.tsx
@@ -1353,7 +1353,7 @@ function SquadInstructionsTab({
>
<ContentEditor
key={squad.id}
- defaultValue={value}
+ value={value}
onUpdate={canManage ? setValue : () => {}}
placeholder={
canManage