feat(web): enable rich text composer by default #12160
Mergedjuliusmarmingemerged 11 commits into
main fromrefs/pull/12160/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/ComposerPromptEditorTiptap.tsx line 1140Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +900,21 @@900+901+ useImperativeHandle(902+ editorRef,903+ () => ({904+ focus: () => {905+ focusAt(snapshotRef.current.cursor);906+ },907+ focusAt,908+ focusAtEnd: () => {909+ focusAt(910+ collapseExpandedComposerCursor(911+ snapshotRef.current.value,912+ snapshotRef.current.value.length,913+ ),914+ );915+ },916+ readSelectionRange: () => {917+ readSnapshot();918+ return selectionRangeRef.current;919+ },920+ requestCitationComment: (request) => {apps/web/src/composer-rich-text-doc.ts lines 260 to 276OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +256,21 @@256+ for (;;) {257+ const top = stack[stack.length - 1];258+ if (!top) {259+ // A leading indented item with no parent flattens but keeps indent.260+ stack.push({ indent: "", items: [] });261+ continue;262+ }263+ if (top.indent === item.indent) {264+ top.items.push(item);265+ break;266+ }267+ if (top.indent !== "" && !item.indent.startsWith(top.indent)) {268+ stack.pop();269+ continue;270+ }271+ const parent = top.items[top.items.length - 1];272+ if (!parent) {273+ top.items.push(item);274+ break;275+ }276+ parent.children.push(item);apps/web/src/composer-rich-text-doc.ts line 445OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +425,21 @@425+ inlineOffset += child.nodeSize;426+ } else {427+ inlineOffset += child.nodeSize;428+ }429+ });430+}431+432+function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {433+ let itemPos = listStart + 1;434+ let firstItem = true;435+ list.content.forEach((item) => {436+ // Sibling items are separated by one newline in every coordinate space.437+ if (!firstItem) pushBreakRun(acc, itemPos - 1);438+ firstItem = false;439+ const itemContentStart = itemPos + 1;440+ const first = item.firstChild;441+ const empty =442+ item.childCount === 1 && first?.type.name === "paragraph" && first.content.childCount === 0;443+ const attrs = item.attrs as { checked?: unknown; indent?: unknown };444+ const indent = typeof attrs.indent === "string" ? attrs.indent : "";445+ const prefix = `${indent}- [${attrs.checked === true ? "x" : " "}]${empty ? "" : " "}`;apps/web/src/components/ComposerPromptEditorTiptap.tsx line 762OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +742,21 @@742+ const startMd = flatToMarkdown(map, pmToFlat(map, from));743+ const endMd = flatToMarkdown(map, pmToFlat(map, to));744+ if (selectionTouchesMentionBoundary(map.value, startMd, endMd)) return false;745+ const tr = view.state.tr.insertText(closer, to).insertText(text, from);746+ tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));747+ view.dispatch(tr);748+ return true;749+ },750+ handlePaste: (view, event) => {751+ const clipboardData = event.clipboardData;752+ if (!clipboardData || clipboardData.files.length > 0) return false;753+ const pastedText = clipboardData.getData("text/plain");754+ if (!pastedText) return false;755+ event.preventDefault();756+ const importFragment = importFragmentRef.current;757+ const text = importFragment758+ ? importPastedComposerText(clipboardData, importFragment)759+ : pastedText;760+ const editorInstance = editorHolder.current;761+ if (editorInstance) {762+ insertMarkdownParagraphs(text, skillLabelFor, (content) => {apps/web/src/composer-rich-text-doc.ts lines 437 to 437OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +417,21 @@417+ mdStart: acc.md,418+ collapsedStart: acc.collapsed,419+ nodeName: child.type.name,420+ });421+ acc.value += source;422+ acc.flat += 1;423+ acc.collapsed += 1;424+ acc.md += source.length;425+ inlineOffset += child.nodeSize;426+ } else {427+ inlineOffset += child.nodeSize;428+ }429+ });430+}431+432+function walkTaskList(list: ProseMirrorNode, listStart: number, acc: RichAccumulator): void {433+ let itemPos = listStart + 1;434+ let firstItem = true;435+ list.content.forEach((item) => {436+ // Sibling items are separated by one newline in every coordinate space.437+ if (!firstItem) pushBreakRun(acc, itemPos - 1);apps/web/src/components/ComposerPromptEditorTiptap.tsx line 762OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +742,21 @@742+ const startMd = flatToMarkdown(map, pmToFlat(map, from));743+ const endMd = flatToMarkdown(map, pmToFlat(map, to));744+ if (selectionTouchesMentionBoundary(map.value, startMd, endMd)) return false;745+ const tr = view.state.tr.insertText(closer, to).insertText(text, from);746+ tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));747+ view.dispatch(tr);748+ return true;749+ },750+ handlePaste: (view, event) => {751+ const clipboardData = event.clipboardData;752+ if (!clipboardData || clipboardData.files.length > 0) return false;753+ const pastedText = clipboardData.getData("text/plain");754+ if (!pastedText) return false;755+ event.preventDefault();756+ const importFragment = importFragmentRef.current;757+ const text = importFragment758+ ? importPastedComposerText(clipboardData, importFragment)759+ : pastedText;760+ const editorInstance = editorHolder.current;761+ if (editorInstance) {762+ insertMarkdownParagraphs(text, skillLabelFor, (content) => {apps/web/src/index.css line 2181OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2122,0 +2161,21 @@2161+ outline-offset: 1px;2162+ border-radius: 6px;2163+}2164+2165+/* Rich-text task lists render as real checkboxes. Tiptap's TaskItem NodeView2166+ builds the <li> imperatively with only a data-checked attribute (no2167+ data-type), so items are targeted that way. Indentation comes from list2168+ nesting (two spaces per level from Tab), matching the stored Markdown. */2169+.composer-tiptap ul[data-type="taskList"] {2170+ list-style: none;2171+ margin: 0;2172+ padding: 0;2173+}2174+2175+.composer-tiptap ul[data-type="taskList"] ul[data-type="taskList"] {2176+ padding-left: 1.375rem;2177+}2178+2179+.composer-tiptap li[data-checked] {2180+ display: flex;2181+ align-items: center;apps/web/src/components/ComposerPromptEditorTiptap.tsx line 408OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +388,21 @@388+389+// ── Marker reveal (show ** when the cursor is on styled text) ──────────────390+391+type StyledRange = {392+ from: number;393+ to: number;394+ delimiter: string;395+};396+397+function collectStyledRanges(doc: ProseMirrorNode): StyledRange[] {398+ const ranges: StyledRange[] = [];399+ doc.descendants((node, pos) => {400+ if (!node.isText || !node.text) return true;401+ const marks = (node.marks ?? [])402+ .map((mark) => TIPTAP_TO_MARK[mark.type.name])403+ .filter((mark): mark is RichTextMark => Boolean(mark));404+ if (marks.length === 0) return false;405+ const ordered = [...marks].sort(406+ (a, b) => MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),407+ );408+ const delimiter = ordered.map((mark) => RICH_TEXT_DELIMITERS[mark]).join("");apps/web/src/composer-rich-text.ts lines 64 to 95OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +75,21 @@75+ let literalStart = 0;76+ const flushLiteral = (end: number) => {77+ if (end > literalStart) pushSpan(spans, text.slice(literalStart, end), outer);78+ literalStart = end;79+ };80+81+ while (index < text.length) {82+ const bold = matchAt(BOLD_PATTERN, text, index);83+ if (bold) {84+ flushLiteral(index);85+ const inner = bold[2] ?? bold[3] ?? "";86+ // Recurse so `**a *b* c**` keeps the italic on `b`.87+ parseNonCodeSpans(inner, spans, [...outer, "bold"]);88+ index += bold[0].length;89+ literalStart = index;90+ continue;91+ }92+ const strike = matchAt(STRIKE_PATTERN, text, index);93+ if (strike) {94+ flushLiteral(index);95+ parseNonCodeSpans(strike[1] ?? "", spans, [...outer, "strike"]);apps/web/src/composer-rich-text-doc.ts line 211OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +191,21 @@191+ return;192+ }193+ pushSpans(currentLine().inline, piece);194+ };195+196+ for (const segment of splitPromptIntoComposerSegments(value)) {197+ if (segment.type === "text") {198+ const parts = segment.text.split("\n");199+ parts.forEach((part, index) => {200+ if (index > 0) endLine();201+ appendTextPiece(part);202+ });203+ } else {204+ if (head !== null) {205+ const line = currentLine();206+ const parsed = parseTaskPrefix(head);207+ if (parsed) {208+ line.task = parsed.prefix;209+ pushSpans(line.inline, head.slice(parsed.markerLength).replace(/^[ \t]*/, ""));210+ } else {211+ pushSpans(line.inline, head);apps/web/src/composer-rich-text.ts line 70OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+ ) {51+ last.text += text;52+ return;53+ }54+ spans.push({ text, marks: sorted });55+}56+57+function matchAt(pattern: RegExp, text: string, index: number): RegExpMatchArray | null {58+ pattern.lastIndex = index;59+ const match = pattern.exec(text);60+ return match && match.index === index ? match : null;61+}62+63+// Code spans are parsed first so `**` inside backticks stays literal.64+const CODE_PATTERN = /`([^`\n]+?)`/gy;65+const BOLD_PATTERN = /(\*\*(?=[^\s*])(.+?)(?<=[^\s*])\*\*|__(?=[^\s_])(.+?)(?<=[^\s_])__)/gy;66+const STRIKE_PATTERN = /~~(?=[^\s~])(.+?)(?<=[^\s~])~~/gy;67+// Single `*` emphasis. Bold is consumed before this runs, so a leftover `*`68+// pair is italic. Underscore emphasis requires non-word boundaries on both69+// sides so snake_case identifiers keep their underscores.70+const ITALIC_STAR_PATTERN = /\*(?=[^\s*])(.+?)(?<=[^\s*])\*/gy;
- apps/web/src/composer-list-continuation.ts lines 127 to 137Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +117,21 @@117+ end: cursor,118+ replacement: `\n${nextMarkerText(parsed.marker)}`,119+ };120+}121+122+/**123+ * Tab on a list item line: indent by two spaces. Ranged selections, non-list124+ * lines, and carets inside an inline chip fall through (Shift+Tab stays the125+ * plan-mode toggle and is handled before this is consulted).126+ */127+export function listIndentForTab(128+ value: string,129+ start: number,130+ end: number,131+): ComposerListEdit | null {132+ if (!Number.isInteger(start) || start !== end || start < 0 || start > value.length) return null;133+ const line = currentLine(value, start);134+ if (!parseListMarker(line.text)) return null;135+ if (isInsideInlineToken(value, start)) return null;136+ return { start: line.start, end: line.start, replacement: " " };137+}apps/web/src/composer-rich-text-doc.ts line 30OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +10,21 @@10+ *11+ * The stored prompt stays markdown (`**bold**`, `@file` chips as canonical12+ * links). The Tiptap document holds styled text plus inline atom chips, so13+ * this module translates both ways and maps cursor offsets between the three14+ * coordinate spaces the composer speaks:15+ *16+ * - flat document offsets (styled markers excluded, chips count 1),17+ * - collapsed cursor offsets (markers literal, chips count 1 — the coordinate18+ * the draft store and mention detection use),19+ * - markdown offsets (markers literal, chips expand to their source).20+ *21+ * DOM-free on purpose: unit tests build a real ProseMirror document from the22+ * JSON this produces and assert the round trip without a browser.23+ */24+25+export type SkillMeta = { label: string; description: string | null };26+27+/** Outermost mark first, so closers mirror openers when nested. */28+export const MARK_NESTING_ORDER: RichTextMark[] = ["strike", "bold", "italic", "code"];29+30+export const MARK_TO_TIPTAP: Record<RichTextMark, string> = {
- apps/web/src/composer-rich-text-doc.ts lines 623 to 625Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +558,21 @@558+ // Marker characters clamp to the styled edge: they are shown, never edited.559+ if (within <= run.openLen) return run.flatStart;560+ if (within >= run.openLen + run.docLen) return run.flatStart + run.docLen;561+ return run.flatStart + (within - run.openLen);562+ }563+ return run.flatStart + (collapsedOffset - run.collapsedStart);564+ }565+ }566+ return map.docLength;567+}568+569+export function flatToPm(map: RichDocMap, flatOffset: number): number {570+ const bounded = Math.max(0, Math.min(flatOffset, map.docLength));571+ for (const run of map.runs) {572+ if (bounded < run.flatStart + run.docLen) {573+ return run.pmPos + (bounded - run.flatStart);574+ }575+ }576+ const last = map.runs[map.runs.length - 1];577+ if (!last) return 0;578+ return last.pmPos + last.docLen;apps/web/src/components/ComposerPromptEditorTiptap.tsx line 899Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +776,21 @@776+ event.preventDefault();777+ event.stopPropagation();778+ return true;779+ }780+ // A newline the parent declined (Shift+Enter, or Enter while the781+ // shortcut says otherwise) must be one visible line. Letting it782+ // fall through inserts a native trailing `<br>`, which renders783+ // no visible line, so the caret looks stuck until a second press.784+ // Splitting the paragraph gives one press, one visible line:785+ // letting it fall through would insert a native trailing `<br>`,786+ // which renders no visible line. Enter on a list line never gets787+ // here — the parent claims it for continuation — so Tiptap's788+ // list splitting stays shadowed.789+ event.preventDefault();790+ return splitBlockKeepMarks(view.state, (tr) => {791+ // The split is programmatic, so the browser won't follow the792+ // caret into view on its own.793+ view.dispatch(tr.scrollIntoView());794+ });795+ }796+ if (!handler) return false;apps/web/src/components/ComposerPromptEditor.tsx line 16Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2118,19 +15,2 @@2118- skills={skills}2119- disabled={disabled}2120- placeholder={placeholder}2121- {...(containerClassName ? { containerClassName } : {})}2122- onChange={onChange}2123- {...(onVisibleSelectionChange ? { onVisibleSelectionChange } : {})}2124- onPaste={onPaste}2125- {...(onCitationSubmitAndSend ? { onCitationSubmitAndSend } : {})}2126- editorRef={editorRef}2127- {...(onCommandKeyDown ? { onCommandKeyDown } : {})}2128- {...(onPageScrollKeyDown ? { onPageScrollKeyDown } : {})}2129- {...(onPageScrollKeyUp ? { onPageScrollKeyUp } : {})}2130- {...(onPageScrollRelease ? { onPageScrollRelease } : {})}2131- {...(className ? { className } : {})}2132- {...(placeholderClassName ? { placeholderClassName } : {})}2133- />2134- </LexicalComposer>2135- </ComposerSkillsContext>2136- );15+export function ComposerPromptEditor(props: ComposerPromptEditorProps) {16+ return <ComposerPromptEditorTiptap {...props} />;
github-actions[bot](GitHub profile, opens in a new tab) added labels📱 Native Change
- apps/web/src/components/chat/ChatComposer.tsx lines 3980 to 3980OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3970,3 +3975,6 @@39703975 submitComposer(undefined, submissionIntent);39713976 return true;39723977 }3978+ // List continuation and indentation run as store replacements so both3979+ // composer modes behave (and serialize) identically.3980+ if (key === "Enter" || (key === "Tab" && !event.shiftKey)) {apps/web/src/composer-rich-text-doc.ts line 420Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +355,21 @@355+ : child.marks356+ .map((mark) => TIPTAP_TO_MARK[mark.type.name])357+ .filter((mark): mark is RichTextMark => Boolean(mark));358+ for (const mark of MARK_NESTING_ORDER) {359+ if (!marks.includes(mark)) markEnds.delete(mark);360+ else if (!markEnds.has(mark)) markEnds.set(mark, index);361+ }362+ orderedMarks[index] = marks.sort(363+ (a, b) =>364+ markEnds.get(b)! - markEnds.get(a)! ||365+ MARK_NESTING_ORDER.indexOf(a) - MARK_NESTING_ORDER.indexOf(b),366+ );367+ }368+ for (let index = 1; index < orderedMarks.length; index += 1) {369+ const marks = orderedMarks[index]!;370+ const retained: RichTextMark[] = [];371+ for (const mark of orderedMarks[index - 1]!) {372+ if (!marks.includes(mark)) break;373+ retained.push(mark);374+ }375+ orderedMarks[index] = [...retained, ...marks.filter((mark) => !retained.includes(mark))];apps/web/src/composer-rich-text.ts lines 103 to 103Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +74,21 @@74+ index += 1;75+ continue;76+ }77+ let end = index;78+ while (text[end] === char) end += 1;79+ const before = text[index - 1] ?? "";80+ const after = text[end] ?? "";81+ const canClose = before !== "" && !/\s/.test(before) && (char !== "_" || !/\w/.test(after));82+ const canOpen = after !== "" && !/\s/.test(after) && (char !== "_" || !/\w/.test(before));83+ while (index < end) {84+ const top = stack.at(-1);85+ if (86+ canClose &&87+ top &&88+ text.startsWith(top.delimiter, index) &&89+ index + top.delimiter.length <= end90+ ) {91+ stack.pop();92+ for (const span of top.spans) pushSpan(current(), span.text, [top.mark, ...span.marks]);93+ index += top.delimiter.length;94+ } else if (canOpen && (char !== "~" || end - index >= 2)) {
- apps/web/src/components/ComposerPromptEditorTiptap.tsx line 1019OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +999,21 @@999+ const next: typeof snapshot = {1000+ value: map.value,1001+ cursor: clampCollapsedComposerCursor(map.value, flatToCollapsed(map, fromFlat)),1002+ expandedCursor: Math.max(0, Math.min(map.value.length, flatToMarkdown(map, fromFlat))),1003+ contextIds: map.contextIds,1004+ };1005+ const toFlat = pmToFlat(map, to);1006+ selectionRangeRef.current = {1007+ start: Math.min(next.expandedCursor, flatToMarkdown(map, toFlat)),1008+ end: Math.max(next.expandedCursor, flatToMarkdown(map, toFlat)),1009+ };1010+ snapshotRef.current = next;1011+ return next;1012+ }, [editor]);1013+1014+ // Controlled value/cursor from the store (history recall, chip insertion…).1015+ useLayoutEffect(() => {1016+ if (!editor) return;1017+ const normalizedCursor = clampCollapsedComposerCursor(value, cursor);1018+ const previousSnapshot = snapshotRef.current;1019+ if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
- apps/web/src/components/ComposerPromptEditorTiptap.tsx lines 219 to 219OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +199,21 @@199+ return {200+ path: { default: "" },201+ source: { default: "" },202+ };203+ },204+ parseHTML() {205+ return [{ tag: "span[data-composer-mention]" }];206+ },207+ renderHTML({ HTMLAttributes }) {208+ return ["span", { "data-composer-mention": "", ...HTMLAttributes }];209+ },210+ addNodeView() {211+ return ReactNodeViewRenderer(ComposerMentionNodeView);212+ },213+});214+215+function ComposerMentionNodeView({ node }: NodeViewProps) {216+ const actions = use(ComposerContextActionsContext);217+ const path = (node.attrs.path as string) ?? "";218+ const chip = (219+ <button
- apps/web/src/components/ComposerPromptEditorTiptap.tsx line 940Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +920,21 @@920+ // Never wrap chips or other atoms, and never wrap styled text: the921+ // default replace keeps marks intact, wrapping would drop them.922+ let touchesSpecial = false;923+ view.state.doc.nodesBetween(from, to, (node) => {924+ if (925+ (node.isAtom && node.isInline && !node.isText) ||926+ (node.isText && node.marks.length > 0)927+ ) {928+ touchesSpecial = true;929+ return false;930+ }931+ return true;932+ });933+ if (touchesSpecial) return false;934+ const map = serializeEditorDoc(view.state.doc);935+ const startMd = flatToMarkdown(map, pmToFlat(map, from));936+ const endMd = flatToMarkdown(map, pmToFlat(map, to));937+ if (selectionTouchesMentionBoundary(map.value, startMd, endMd)) return false;938+ const tr = view.state.tr.insertText(closer, to).insertText(text, from);939+ tr.setSelection(TextSelection.create(tr.doc, from + text.length, to + text.length));940+ view.dispatch(tr);apps/web/src/components/ComposerPromptEditorTiptap.tsx line 876Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +856,21 @@856+ )857+ .scrollIntoView(),858+ );859+ return true;860+ }861+ }862+ if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) {863+ event.stopPropagation();864+ return true;865+ }866+ // Enter on a focused task checkbox must not send the prompt (or867+ // split anything): Space toggles it, Enter does nothing.868+ if (event.key === "Enter" && event.target instanceof HTMLInputElement) {869+ event.preventDefault();870+ return true;871+ }872+ const handler = onCommandKeyDownRef.current;873+ if (event.key === "Enter") {874+ const instance = editorHolder.current;875+ const isTaskItem = richText && (instance?.isActive("taskItem") ?? false);876+ const handled = handler?.("Enter", event, isTaskItem) ?? false;
maria-rcks changed the title
maria-rcks merged thisd359e94
maria-rcks closed this
Sign in to join this conversation.







Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline:
394af73· PR result:d6d6b70· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.