Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop/message-editor): markdown lists and code in the composer (#83969)

Adam Leith828d1f479cf5
diff --git a/products/desktop/packages/ui/src/features/message-editor/components/message-editor.css b/products/desktop/packages/ui/src/features/message-editor/components/message-editor.css
index baea558c5332..0f067b685062 100644
--- a/products/desktop/packages/ui/src/features/message-editor/components/message-editor.css
+++ b/products/desktop/packages/ui/src/features/message-editor/components/message-editor.css
@@ -17,6 +17,71 @@
content: attr(data-placeholder);
}
+/* Markdown blocks, styled to match how the chat thread renders the same markdown
+ (ChatMarkdown). Written as CSS rather than classes on the nodes so it applies to
+ every editor instance, including ones built before an extension change. Tailwind
+ preflight strips list styling, hence the list-style declarations. */
+.cli-editor ul,
+.cli-editor ol,
+.cli-editor pre {
+ margin: 0.25em 0;
+}
+
+.cli-editor ul,
+.cli-editor ol {
+ padding-inline-start: 1rem;
+}
+
+.cli-editor ul {
+ list-style: disc;
+}
+
+.cli-editor ul ul {
+ list-style: circle;
+}
+
+.cli-editor ol {
+ padding-inline-start: 1.25rem;
+ list-style: decimal;
+}
+
+.cli-editor li + li {
+ margin-top: 0.125rem;
+}
+
+.cli-editor li > p {
+ margin: 0;
+}
+
+.cli-editor code {
+ padding-inline: 0.25rem;
+ background: color-mix(in oklab, var(--muted) 50%, transparent);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ font-size: 0.75rem;
+ font-family: var(--font-mono);
+}
+
+.cli-editor pre {
+ padding: 0.75rem;
+ overflow-x: auto;
+ background: color-mix(in oklab, var(--muted) 50%, transparent);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-lg);
+ font-size: 0.75rem;
+ font-family: var(--font-mono);
+ line-height: 1.5;
+}
+
+/* pre already paints the box; the inner code element must not paint a second one. */
+.cli-editor pre code {
+ padding: 0;
+ background: none;
+ border: none;
+ border-radius: 0;
+ font-size: inherit;
+}
+
/* Ensure Tiptap NodeView wrappers render inline for mention chips */
.cli-editor [data-node-view-wrapper] {
display: inline;
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/blockShortcuts.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/blockShortcuts.ts
new file mode 100644
index 000000000000..d7df35d7f976
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/blockShortcuts.ts
@@ -0,0 +1,26 @@
+import { Extension } from "@tiptap/core";
+
+/**
+ * Enter is the send key, so the list and code-block keymaps StarterKit binds to
+ * it never fire. Shift+Enter carries them instead: a new list item inside a
+ * list, a newline inside a fence, its usual hard break everywhere else.
+ */
+export const BlockShortcuts = Extension.create({
+ name: "blockShortcuts",
+
+ addKeyboardShortcuts() {
+ return {
+ "Shift-Enter": () => {
+ const { editor } = this;
+ if (editor.isActive("codeBlock")) {
+ return editor.commands.insertContent("\n");
+ }
+ if (!editor.isActive("listItem")) return false;
+ return (
+ editor.commands.splitListItem("listItem") ||
+ editor.commands.liftListItem("listItem")
+ );
+ },
+ };
+ },
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.test.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.test.ts
new file mode 100644
index 000000000000..a6fd7508277a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.test.ts
@@ -0,0 +1,50 @@
+import { Editor } from "@tiptap/core";
+import { describe, expect, it } from "vitest";
+import { isBashModeDoc, markdownFragment } from "./composerDocument";
+import { getEditorExtensions } from "./extensions";
+import { tiptapJsonToEditorContent } from "./markdownDoc";
+
+function makeEditor(): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ return new Editor({
+ element,
+ extensions: getEditorExtensions({ sessionId: "session-1" }),
+ });
+}
+
+function setMarkdown(editor: Editor, text: string): void {
+ const fragment = markdownFragment(editor.schema, text);
+ editor.view.dispatch(
+ editor.state.tr.replaceWith(0, editor.state.doc.content.size, fragment),
+ );
+}
+
+function markdown(editor: Editor): string {
+ return tiptapJsonToEditorContent(editor.getJSON())
+ .segments.map((segment) => (segment.type === "text" ? segment.text : ""))
+ .join("");
+}
+
+describe("composer document helpers", () => {
+ it.each([
+ ["a list", "- milk\n- eggs"],
+ ["a fenced block", "```ts\nconst a = 1\n```"],
+ ["prose", "just some words"],
+ ])("recalls %s as the markdown it was sent as", (_name, text) => {
+ const editor = makeEditor();
+ setMarkdown(editor, text);
+ expect(markdown(editor)).toBe(text);
+ });
+
+ it.each([
+ ["plain text", "!ls", true],
+ ["inline code", "`!ls`", false],
+ ["a fenced block", "```\n!ls\n```", false],
+ ["a list", "- !ls", false],
+ ])("reads %s as bash mode: %s", (_name, text, expected) => {
+ const editor = makeEditor();
+ setMarkdown(editor, text);
+ expect(isBashModeDoc(editor, editor.getText())).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.ts
new file mode 100644
index 000000000000..6a5cf3f0c892
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/composerDocument.ts
@@ -0,0 +1,38 @@
+import { isBashModeText } from "@posthog/core/message-editor/paste";
+import type { Editor } from "@tiptap/core";
+import {
+ Fragment,
+ Node as ProseMirrorNode,
+ type Schema,
+} from "@tiptap/pm/model";
+import { editorContentToTiptapJson } from "./markdownDoc";
+
+/**
+ * Recalled prompts, history entries and queued messages arrive as markdown, so
+ * they get parsed back into nodes the way a restored draft does. Without this a
+ * recalled list comes back as literal dashes.
+ */
+export function markdownFragment(schema: Schema, text: string): Fragment {
+ try {
+ const json = editorContentToTiptapJson({
+ segments: [{ type: "text", text }],
+ });
+ return ProseMirrorNode.fromJSON(schema, json).content;
+ } catch {
+ return Fragment.from(
+ schema.nodes.paragraph.create(null, schema.text(text)),
+ );
+ }
+}
+
+/**
+ * `getText()` drops backticks and fences, so `!rm -rf` written as code reads as
+ * a shell command. Bash mode needs the leading `!` to be plain text.
+ */
+export function isBashModeDoc(editor: Editor, text: string): boolean {
+ if (!isBashModeText(text)) return false;
+ const first = editor.state.doc.firstChild;
+ if (first?.type.name !== "paragraph") return false;
+ const leading = first.firstChild;
+ return !leading?.marks.some((mark) => mark.type.name === "code");
+}
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/extensions.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/extensions.ts
index 64330e77ba1b..89be3acee346 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/extensions.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/extensions.ts
@@ -1,9 +1,11 @@
import Placeholder from "@tiptap/extension-placeholder";
import StarterKit from "@tiptap/starter-kit";
+import { BlockShortcuts } from "./blockShortcuts";
import { createCommandMention } from "./CommandMention";
import { createFileMention } from "./FileMention";
import { createIssueMention } from "./IssueMention";
import { MentionChipNode } from "./MentionChipNode";
+import { MarkdownLineStartRules } from "./markdownInputRules";
export interface EditorExtensionsOptions {
sessionId: string;
@@ -26,17 +28,14 @@ export function getEditorExtensions(options: EditorExtensionsOptions) {
StarterKit.configure({
heading: false,
blockquote: false,
- codeBlock: false,
- bulletList: false,
- orderedList: false,
- listItem: false,
horizontalRule: false,
bold: false,
italic: false,
strike: false,
- code: false,
}),
Placeholder.configure({ placeholder }),
+ BlockShortcuts,
+ MarkdownLineStartRules,
MentionChipNode,
];
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.test.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.test.ts
new file mode 100644
index 000000000000..2b6802afeae6
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.test.ts
@@ -0,0 +1,160 @@
+import type { EditorContent } from "@posthog/core/message-editor/content";
+import type { JSONContent } from "@tiptap/core";
+import { describe, expect, it } from "vitest";
+import {
+ editorContentToTiptapJson,
+ tiptapJsonToEditorContent,
+} from "./markdownDoc";
+
+function text(content: EditorContent): string {
+ return content.segments
+ .map((segment) => (segment.type === "text" ? segment.text : "@chip"))
+ .join("");
+}
+
+function doc(...content: JSONContent[]): JSONContent {
+ return { type: "doc", content };
+}
+
+function paragraph(...content: JSONContent[]): JSONContent {
+ return { type: "paragraph", content };
+}
+
+function item(...content: JSONContent[]): JSONContent {
+ return { type: "listItem", content };
+}
+
+describe("markdownDoc", () => {
+ it.each([
+ [
+ "bullet list",
+ doc({
+ type: "bulletList",
+ content: [
+ item(paragraph({ type: "text", text: "milk" })),
+ item(paragraph({ type: "text", text: "eggs" })),
+ ],
+ }),
+ "- milk\n- eggs",
+ ],
+ [
+ "nested bullet list",
+ doc({
+ type: "bulletList",
+ content: [
+ item(paragraph({ type: "text", text: "eggs" }), {
+ type: "bulletList",
+ content: [item(paragraph({ type: "text", text: "free range" }))],
+ }),
+ ],
+ }),
+ "- eggs\n - free range",
+ ],
+ [
+ "ordered list",
+ doc({
+ type: "orderedList",
+ attrs: { start: 1 },
+ content: [
+ item(paragraph({ type: "text", text: "first" })),
+ item(paragraph({ type: "text", text: "second" })),
+ ],
+ }),
+ "1. first\n2. second",
+ ],
+ [
+ "code block",
+ doc({
+ type: "codeBlock",
+ attrs: { language: "ts" },
+ content: [{ type: "text", text: "const a = 1\nconst b = 2" }],
+ }),
+ "```ts\nconst a = 1\nconst b = 2\n```",
+ ],
+ [
+ "paragraph before a list",
+ doc(paragraph({ type: "text", text: "shopping" }), {
+ type: "bulletList",
+ content: [item(paragraph({ type: "text", text: "milk" }))],
+ }),
+ "shopping\n\n- milk",
+ ],
+ [
+ "hard break inside a paragraph",
+ doc(
+ paragraph(
+ { type: "text", text: "one" },
+ { type: "hardBreak" },
+ { type: "text", text: "two" },
+ ),
+ ),
+ "one \ntwo",
+ ],
+ [
+ "inline code",
+ doc(
+ paragraph(
+ { type: "text", text: "run " },
+ { type: "text", text: "pnpm dev", marks: [{ type: "code" }] },
+ ),
+ ),
+ "run `pnpm dev`",
+ ],
+ ])("serializes %s to markdown", (_name, json, expected) => {
+ expect(text(tiptapJsonToEditorContent(json))).toBe(expected);
+ });
+
+ it.each([
+ ["bullet list", "- milk\n- eggs"],
+ ["nested bullet list", "- eggs\n - free range"],
+ ["ordered list", "1. first\n2. second"],
+ ["code block", "```ts\nconst a = 1\n```"],
+ ["list after a paragraph", "shopping\n\n- milk\n- eggs"],
+ ["list before a paragraph", "- milk\n\ndone"],
+ ["hard break inside a paragraph", "one \ntwo"],
+ ["two paragraphs", "one\n\ntwo"],
+ ["inline code", "run `pnpm dev` now"],
+ ["inline code inside a list item", "- run `pnpm dev`"],
+ ["backticks inside a fence", "```\na = `b`\n```"],
+ ])("round-trips %s through the document model", (_name, markdown) => {
+ const parsed = editorContentToTiptapJson({
+ segments: [{ type: "text", text: markdown }],
+ });
+ expect(text(tiptapJsonToEditorContent(parsed))).toBe(markdown);
+ });
+
+ it("keeps mention chips attached to the list item they sit in", () => {
+ const parsed = editorContentToTiptapJson({
+ segments: [
+ { type: "text", text: "- look at " },
+ {
+ type: "chip",
+ chip: { type: "file", id: "/src/app.ts", label: "src/app.ts" },
+ },
+ { type: "text", text: "\n- then ship" },
+ ],
+ });
+
+ const list = parsed.content?.[0];
+ expect(list?.type).toBe("bulletList");
+ expect(list?.content).toHaveLength(2);
+ expect(list?.content?.[0].content?.[0].content?.[1]).toMatchObject({
+ type: "mentionChip",
+ attrs: { id: "/src/app.ts" },
+ });
+ });
+
+ it("treats a lone marker as text, not a list", () => {
+ const parsed = editorContentToTiptapJson({
+ segments: [{ type: "text", text: "2 * 3 = 6" }],
+ });
+
+ expect(parsed.content?.[0].type).toBe("paragraph");
+ });
+
+ it("returns an empty paragraph for empty content", () => {
+ expect(editorContentToTiptapJson({ segments: [] })).toEqual(
+ doc(paragraph()),
+ );
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.ts
new file mode 100644
index 000000000000..64a2fbeef0c4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownDoc.ts
@@ -0,0 +1,408 @@
+import type {
+ EditorContent,
+ MentionChip,
+} from "@posthog/core/message-editor/content";
+import type { JSONContent } from "@tiptap/core";
+
+type Segment = EditorContent["segments"][number];
+
+const LIST_ITEM_PATTERN = /^(\s*)(?:([-*+])|(\d+)[.)])[ \t]+(.*)$/;
+const FENCE_PATTERN = /^(\s*)```(\S*)\s*$/;
+
+class SegmentBuilder {
+ private readonly segments: Segment[] = [];
+
+ text(text: string): void {
+ if (!text) return;
+ const last = this.segments[this.segments.length - 1];
+ if (last?.type === "text") {
+ last.text += text;
+ return;
+ }
+ this.segments.push({ type: "text", text });
+ }
+
+ chip(chip: MentionChip): void {
+ this.segments.push({ type: "chip", chip });
+ }
+
+ build(): Segment[] {
+ return this.segments;
+ }
+}
+
+function chipFromAttrs(attrs: Record<string, unknown>): MentionChip {
+ return {
+ type: attrs.type as MentionChip["type"],
+ id: attrs.id as string,
+ label: attrs.label as string,
+ pastedText: attrs.pastedText as boolean | undefined,
+ skillPath: attrs.skillPath as string | undefined,
+ skillSource: attrs.skillSource as MentionChip["skillSource"],
+ skillName: attrs.skillName as string | undefined,
+ };
+}
+
+function chipToPlainText(chip: MentionChip): string {
+ return chip.type === "command" ? `/${chip.label}` : `@${chip.label}`;
+}
+
+function hasCodeMark(node: JSONContent): boolean {
+ return (node.marks ?? []).some((mark) => mark.type === "code");
+}
+
+function collectPlainText(node: JSONContent): string {
+ if (node.type === "text") return node.text ?? "";
+ if (node.type === "hardBreak") return "\n";
+ if (node.type === "mentionChip" && node.attrs) {
+ return chipToPlainText(chipFromAttrs(node.attrs));
+ }
+ return (node.content ?? []).map(collectPlainText).join("");
+}
+
+function emitInline(
+ node: JSONContent,
+ out: SegmentBuilder,
+ indent: string,
+): void {
+ if (node.type === "text") {
+ const text = node.text ?? "";
+ out.text(hasCodeMark(node) ? `\`${text}\`` : text);
+ return;
+ }
+ if (node.type === "hardBreak") {
+ // Two trailing spaces make it a markdown line break rather than a soft wrap.
+ out.text(` \n${indent}`);
+ return;
+ }
+ if (node.type === "mentionChip" && node.attrs) {
+ out.chip(chipFromAttrs(node.attrs));
+ return;
+ }
+ for (const child of node.content ?? []) {
+ emitInline(child, out, indent);
+ }
+}
+
+function emitCodeBlock(
+ node: JSONContent,
+ out: SegmentBuilder,
+ indent: string,
+): void {
+ const language =
+ typeof node.attrs?.language === "string" ? node.attrs.language : "";
+ out.text(`\`\`\`${language}`);
+ for (const line of collectPlainText(node).split("\n")) {
+ out.text(`\n${indent}${line}`);
+ }
+ out.text(`\n${indent}\`\`\``);
+}
+
+function emitListItem(
+ item: JSONContent,
+ out: SegmentBuilder,
+ contentIndent: string,
+): void {
+ const children = item.content ?? [];
+ children.forEach((child, index) => {
+ if (index > 0) {
+ const tight = child.type === "bulletList" || child.type === "orderedList";
+ out.text(`${tight ? "\n" : "\n\n"}${contentIndent}`);
+ }
+ emitBlock(child, out, contentIndent);
+ });
+}
+
+function emitList(
+ node: JSONContent,
+ out: SegmentBuilder,
+ indent: string,
+): void {
+ const ordered = node.type === "orderedList";
+ const start = typeof node.attrs?.start === "number" ? node.attrs.start : 1;
+ const items = node.content ?? [];
+ items.forEach((item, index) => {
+ if (index > 0) out.text(`\n${indent}`);
+ const marker = ordered ? `${start + index}. ` : "- ";
+ out.text(marker);
+ emitListItem(item, out, indent + " ".repeat(marker.length));
+ });
+}
+
+function emitBlock(
+ node: JSONContent,
+ out: SegmentBuilder,
+ indent: string,
+): void {
+ if (node.type === "codeBlock") {
+ emitCodeBlock(node, out, indent);
+ return;
+ }
+ if (node.type === "bulletList" || node.type === "orderedList") {
+ emitList(node, out, indent);
+ return;
+ }
+ emitInline(node, out, indent);
+}
+
+function isEmptyParagraph(node: JSONContent): boolean {
+ return node.type === "paragraph" && !collectPlainText(node).trim();
+}
+
+/** Serialize an editor document to markdown text segments plus mention chips. */
+export function tiptapJsonToEditorContent(json: JSONContent): EditorContent {
+ const out = new SegmentBuilder();
+ const blocks = [...(json.type === "doc" ? (json.content ?? []) : [json])];
+ // A doc ending in a list or code block gets a trailing paragraph so the caret
+ // can escape the block; it is not part of the message.
+ while (blocks.length > 1 && isEmptyParagraph(blocks[blocks.length - 1])) {
+ blocks.pop();
+ }
+ blocks.forEach((block, index) => {
+ // Blank line between blocks: a single newline would collapse to a space.
+ if (index > 0) out.text("\n\n");
+ emitBlock(block, out, "");
+ });
+ return { segments: out.build() };
+}
+
+interface Line {
+ nodes: JSONContent[];
+}
+
+function segmentsToLines(segments: Segment[]): Line[] {
+ const lines: Line[] = [{ nodes: [] }];
+
+ const pushText = (text: string) => {
+ if (!text) return;
+ const line = lines[lines.length - 1];
+ const last = line.nodes[line.nodes.length - 1];
+ if (last?.type === "text") {
+ last.text = (last.text ?? "") + text;
+ return;
+ }
+ line.nodes.push({ type: "text", text });
+ };
+
+ for (const segment of segments) {
+ if (segment.type === "chip") {
+ lines[lines.length - 1].nodes.push({
+ type: "mentionChip",
+ attrs: {
+ type: segment.chip.type,
+ id: segment.chip.id,
+ label: segment.chip.label,
+ pastedText: segment.chip.pastedText ?? false,
+ skillPath: segment.chip.skillPath,
+ skillSource: segment.chip.skillSource,
+ skillName: segment.chip.skillName,
+ },
+ });
+ continue;
+ }
+ const parts = segment.text.split("\n");
+ parts.forEach((part, index) => {
+ if (index > 0) lines.push({ nodes: [] });
+ pushText(part);
+ });
+ }
+
+ return lines;
+}
+
+function leadingText(line: Line): string {
+ const first = line.nodes[0];
+ return first?.type === "text" ? (first.text ?? "") : "";
+}
+
+function lineText(line: Line): string {
+ return line.nodes.map(collectPlainText).join("");
+}
+
+function isBlank(line: Line): boolean {
+ return line.nodes.length === 0 || !lineText(line).trim();
+}
+
+interface ListItemMatch {
+ indent: number;
+ ordered: boolean;
+ start: number;
+ nodes: JSONContent[];
+}
+
+function matchListItem(line: Line): ListItemMatch | null {
+ const match = LIST_ITEM_PATTERN.exec(leadingText(line));
+ if (!match) return null;
+ const [, indent, bullet, ordinal, rest] = match;
+ const nodes: JSONContent[] = rest ? [{ type: "text", text: rest }] : [];
+ nodes.push(...line.nodes.slice(1));
+ return {
+ indent: indent.length,
+ ordered: !bullet,
+ start: ordinal ? Number.parseInt(ordinal, 10) : 1,
+ nodes,
+ };
+}
+
+const INLINE_CODE_PATTERN = /`([^`\n]+)`/g;
+
+function splitInlineCode(text: string): JSONContent[] {
+ const nodes: JSONContent[] = [];
+ let cursor = 0;
+ for (const match of text.matchAll(INLINE_CODE_PATTERN)) {
+ const index = match.index ?? 0;
+ if (index > cursor) {
+ nodes.push({ type: "text", text: text.slice(cursor, index) });
+ }
+ nodes.push({ type: "text", text: match[1], marks: [{ type: "code" }] });
+ cursor = index + match[0].length;
+ }
+ if (cursor < text.length) {
+ nodes.push({ type: "text", text: text.slice(cursor) });
+ }
+ return nodes;
+}
+
+function paragraphFrom(lines: Line[]): JSONContent {
+ const content: JSONContent[] = [];
+ lines.forEach((line, index) => {
+ if (index > 0) content.push({ type: "hardBreak" });
+ line.nodes.forEach((node, nodeIndex) => {
+ const isLastText =
+ node.type === "text" && nodeIndex === line.nodes.length - 1;
+ // The trailing double space is the hard-break marker, not content.
+ const text = isLastText
+ ? (node.text ?? "").replace(/ {2}$/, "")
+ : node.text;
+ if (node.type === "text") {
+ if (text) content.push(...splitInlineCode(text));
+ return;
+ }
+ content.push(node);
+ });
+ });
+ return { type: "paragraph", content };
+}
+
+function parseCodeBlock(
+ lines: Line[],
+ start: number,
+): { node: JSONContent; next: number } {
+ const match = FENCE_PATTERN.exec(leadingText(lines[start]));
+ const indent = match?.[1] ?? "";
+ const language = match?.[2] ?? "";
+ const body: string[] = [];
+ let index = start + 1;
+ while (index < lines.length) {
+ const text = lineText(lines[index]);
+ if (text.trim() === "```") {
+ index += 1;
+ break;
+ }
+ body.push(text.startsWith(indent) ? text.slice(indent.length) : text);
+ index += 1;
+ }
+ const code = body.join("\n");
+ return {
+ node: {
+ type: "codeBlock",
+ attrs: { language: language || null },
+ content: code ? [{ type: "text", text: code }] : [],
+ },
+ next: index,
+ };
+}
+
+function parseList(
+ lines: Line[],
+ start: number,
+): { node: JSONContent; next: number } {
+ const first = matchListItem(lines[start]) as ListItemMatch;
+ const baseIndent = first.indent;
+ const ordered = first.ordered;
+ const items: JSONContent[] = [];
+ let index = start;
+
+ while (index < lines.length) {
+ const match = matchListItem(lines[index]);
+ if (!match || match.indent < baseIndent) break;
+
+ if (match.indent > baseIndent) {
+ const nested = parseList(lines, index);
+ const lastItem = items[items.length - 1];
+ if (lastItem) {
+ lastItem.content = [...(lastItem.content ?? []), nested.node];
+ } else {
+ items.push({ type: "listItem", content: [nested.node] });
+ }
+ index = nested.next;
+ continue;
+ }
+
+ if (match.ordered !== ordered) break;
+
+ items.push({
+ type: "listItem",
+ content: [paragraphFrom([{ nodes: match.nodes }])],
+ });
+ index += 1;
+ }
+
+ return {
+ node: ordered
+ ? { type: "orderedList", attrs: { start: first.start }, content: items }
+ : { type: "bulletList", content: items },
+ next: index,
+ };
+}
+
+/** Parse markdown text segments plus mention chips back into an editor document. */
+export function editorContentToTiptapJson(content: EditorContent): JSONContent {
+ const lines = segmentsToLines(content.segments);
+ const blocks: JSONContent[] = [];
+ let index = 0;
+
+ while (index < lines.length) {
+ const line = lines[index];
+
+ if (isBlank(line)) {
+ index += 1;
+ continue;
+ }
+
+ if (FENCE_PATTERN.test(leadingText(line))) {
+ const { node, next } = parseCodeBlock(lines, index);
+ blocks.push(node);
+ index = next;
+ continue;
+ }
+
+ if (matchListItem(line)) {
+ const { node, next } = parseList(lines, index);
+ blocks.push(node);
+ index = next;
+ continue;
+ }
+
+ const paragraphLines: Line[] = [];
+ while (index < lines.length) {
+ const current = lines[index];
+ if (
+ isBlank(current) ||
+ matchListItem(current) ||
+ FENCE_PATTERN.test(leadingText(current))
+ ) {
+ break;
+ }
+ paragraphLines.push(current);
+ index += 1;
+ }
+ blocks.push(paragraphFrom(paragraphLines));
+ }
+
+ if (blocks.length === 0) {
+ blocks.push({ type: "paragraph", content: [] });
+ }
+
+ return { type: "doc", content: blocks };
+}
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.test.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.test.ts
new file mode 100644
index 000000000000..9c5f89ccfb90
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.test.ts
@@ -0,0 +1,79 @@
+import { Editor } from "@tiptap/core";
+import { describe, expect, it } from "vitest";
+import { getEditorExtensions } from "./extensions";
+import { tiptapJsonToEditorContent } from "./markdownDoc";
+
+/** Stands in for a Shift+Enter press inside the typed strings below. */
+const BREAK = "\n";
+
+function makeEditor(): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ return new Editor({
+ element,
+ extensions: getEditorExtensions({ sessionId: "session-1" }),
+ });
+}
+
+/** Types character by character so input rules see the stream a user produces. */
+function type(editor: Editor, input: string): void {
+ for (const char of input) {
+ if (char === BREAK) {
+ editor.view.someProp("handleKeyDown", (fn) =>
+ fn(
+ editor.view,
+ new KeyboardEvent("keydown", { key: "Enter", shiftKey: true }),
+ ),
+ );
+ continue;
+ }
+ const { from, to } = editor.state.selection;
+ const insert = () => editor.state.tr.insertText(char, from, to);
+ const handled = editor.view.someProp("handleTextInput", (fn) =>
+ fn(editor.view, from, to, char, insert),
+ );
+ if (!handled) {
+ editor.view.dispatch(insert());
+ }
+ }
+}
+
+function markdown(editor: Editor): string {
+ return tiptapJsonToEditorContent(editor.getJSON())
+ .segments.map((segment) => (segment.type === "text" ? segment.text : ""))
+ .join("");
+}
+
+describe("markdown input rules", () => {
+ it.each([
+ ["bullet on the first line", `* milk${BREAK}eggs`, "- milk\n- eggs"],
+ [
+ "bullet after a hard break",
+ `hello${BREAK}* milk${BREAK}eggs`,
+ "hello\n\n- milk\n- eggs",
+ ],
+ [
+ "numbered list after a hard break",
+ `intro${BREAK}3. three`,
+ "intro\n\n3. three",
+ ],
+ [
+ "code fence after a hard break",
+ `look:${BREAK}\`\`\`ts const a = 1`,
+ "look:\n\n```ts\nconst a = 1\n```",
+ ],
+ ["a star that is not a marker", "2 * 3 = 6", "2 * 3 = 6"],
+ ["a star mid-line", `hello${BREAK}a * b`, "hello \na * b"],
+ ["inline code mid-line", "run `pnpm dev` now", "run `pnpm dev` now"],
+ [
+ "inline code after a hard break",
+ `hello${BREAK}\`pnpm dev\` now`,
+ "hello \n`pnpm dev` now",
+ ],
+ ["a lone backtick", "a ` b", "a ` b"],
+ ])("%s", (_name, typed, expected) => {
+ const editor = makeEditor();
+ type(editor, typed);
+ expect(markdown(editor)).toBe(expected);
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.ts
new file mode 100644
index 000000000000..ec7782974334
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownInputRules.ts
@@ -0,0 +1,77 @@
+import { type ChainedCommands, Extension, InputRule } from "@tiptap/core";
+
+type BlockStarter = (chain: ChainedCommands, match: RegExpMatchArray) => void;
+
+/**
+ * Shift+Enter inserts a hard break rather than a new paragraph, so every line
+ * after the first shares one textblock. StarterKit's list and code-block input
+ * rules only match at the start of a textblock, which leaves `* ` inert on any
+ * line but the first. These fire at a hard break instead, dropping the break so
+ * the new block starts on its own line.
+ */
+function startBlockAfterHardBreak(find: RegExp, run: BlockStarter): InputRule {
+ return new InputRule({
+ find,
+ handler: ({ state, range, match, chain }) => {
+ const $start = state.doc.resolve(range.from);
+ if ($start.nodeBefore?.type.name !== "hardBreak") return null;
+ run(
+ chain()
+ .deleteRange({ from: range.from - 1, to: range.to })
+ .splitBlock(),
+ match,
+ );
+ return undefined;
+ },
+ });
+}
+
+/**
+ * The `code` mark's own rule needs the opening backtick to follow whitespace or
+ * a block start; a hard break is neither, so `x` at the head of a wrapped line
+ * stays literal without this.
+ */
+function inlineCodeAfterHardBreak(): InputRule {
+ return new InputRule({
+ find: /`(?!\s)([^`]+)`$/,
+ handler: ({ state, range, match, chain }) => {
+ const $start = state.doc.resolve(range.from);
+ if ($start.nodeBefore?.type.name !== "hardBreak") return null;
+ chain()
+ .deleteRange(range)
+ .insertContent({
+ type: "text",
+ text: match[1],
+ marks: [{ type: "code" }],
+ })
+ .unsetMark("code")
+ .run();
+ return undefined;
+ },
+ });
+}
+
+export const MarkdownLineStartRules = Extension.create({
+ name: "markdownLineStartRules",
+
+ addInputRules() {
+ return [
+ startBlockAfterHardBreak(/([-+*])\s$/, (chain) =>
+ chain.toggleBulletList().run(),
+ ),
+ startBlockAfterHardBreak(/(\d+)[.)]\s$/, (chain, match) => {
+ chain
+ .toggleOrderedList()
+ .updateAttributes("orderedList", {
+ start: Number.parseInt(match[1], 10) || 1,
+ })
+ .run();
+ }),
+ startBlockAfterHardBreak(/```([a-zA-Z0-9+#-]*)\s$/, (chain, match) => {
+ const language = match[1];
+ chain.setCodeBlock(language ? { language } : undefined).run();
+ }),
+ inlineCodeAfterHardBreak(),
+ ];
+ },
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.test.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.test.ts
new file mode 100644
index 000000000000..6a92d462cc9b
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.test.ts
@@ -0,0 +1,63 @@
+import { Editor } from "@tiptap/core";
+import { describe, expect, it } from "vitest";
+import { getEditorExtensions } from "./extensions";
+import { tiptapJsonToEditorContent } from "./markdownDoc";
+import { insertPastedMarkdown } from "./markdownPaste";
+
+function makeEditor(): Editor {
+ const element = document.createElement("div");
+ document.body.appendChild(element);
+ return new Editor({
+ element,
+ extensions: getEditorExtensions({ sessionId: "session-1" }),
+ });
+}
+
+function markdown(editor: Editor): string {
+ return tiptapJsonToEditorContent(editor.getJSON())
+ .segments.map((segment) => (segment.type === "text" ? segment.text : ""))
+ .join("");
+}
+
+describe("pasted markdown", () => {
+ it.each([
+ ["a bullet list", "- milk\n- eggs", "- milk\n- eggs"],
+ ["a numbered list", "1. one\n2. two", "1. one\n2. two"],
+ ["a nested list", "- milk\n - skimmed", "- milk\n - skimmed"],
+ [
+ "a fenced code block",
+ "look:\n\n```ts\nconst a = 1\n```",
+ "look:\n\n```ts\nconst a = 1\n```",
+ ],
+ ["inline code", "run `pnpm dev` now", "run `pnpm dev` now"],
+ ])("%s becomes nodes", (_name, pasted, expected) => {
+ const editor = makeEditor();
+ expect(insertPastedMarkdown(editor.view, pasted)).toBe(true);
+ expect(markdown(editor)).toBe(expected);
+ });
+
+ it.each([
+ ["prose", "just some words"],
+ ["prose over two lines", "first line\nsecond line"],
+ ])("leaves %s to the default paste", (_name, pasted) => {
+ const editor = makeEditor();
+ expect(insertPastedMarkdown(editor.view, pasted)).toBe(false);
+ });
+
+ it("leaves a paste inside a code block literal", () => {
+ const editor = makeEditor();
+ editor.commands.setContent({
+ type: "doc",
+ content: [{ type: "codeBlock", content: [{ type: "text", text: "x" }] }],
+ });
+ editor.commands.setTextSelection(2);
+ expect(insertPastedMarkdown(editor.view, "- milk\n- eggs")).toBe(false);
+ });
+
+ it("keeps text already in the paragraph", () => {
+ const editor = makeEditor();
+ editor.commands.insertContent("shopping:");
+ expect(insertPastedMarkdown(editor.view, "\n- milk\n- eggs")).toBe(true);
+ expect(markdown(editor)).toBe("shopping:\n\n- milk\n- eggs");
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.ts
new file mode 100644
index 000000000000..49e49fff0cfd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/markdownPaste.ts
@@ -0,0 +1,56 @@
+import type { JSONContent } from "@tiptap/core";
+import { Node as ProseMirrorNode, Slice } from "@tiptap/pm/model";
+import type { EditorView } from "@tiptap/pm/view";
+import { editorContentToTiptapJson } from "./markdownDoc";
+
+function hasCodeMark(node: JSONContent): boolean {
+ return (node.marks ?? []).some((mark) => mark.type === "code");
+}
+
+/**
+ * Plain paragraphs are what the default paste already produces, so only
+ * markdown that turns into list, code-block or inline-code nodes is worth
+ * taking over the paste for.
+ */
+function hasMarkdownNodes(node: JSONContent): boolean {
+ if (node.type === "bulletList") return true;
+ if (node.type === "orderedList") return true;
+ if (node.type === "codeBlock") return true;
+ if (hasCodeMark(node)) return true;
+ return (node.content ?? []).some(hasMarkdownNodes);
+}
+
+/**
+ * Insert pasted markdown as real nodes. Input rules only fire on typing, so
+ * without this a pasted `- milk` stays a literal dash.
+ *
+ * Returns false when the text carries no markdown, or when the caret sits in a
+ * code block, leaving the paste to ProseMirror's default text handling.
+ */
+export function insertPastedMarkdown(view: EditorView, text: string): boolean {
+ if (!text.trim()) return false;
+ if (view.state.selection.$from.parent.type.spec.code) return false;
+
+ const json = editorContentToTiptapJson({
+ segments: [{ type: "text", text }],
+ });
+ if (!(json.content ?? []).some(hasMarkdownNodes)) return false;
+
+ let doc: ProseMirrorNode;
+ try {
+ doc = ProseMirrorNode.fromJSON(view.state.schema, json);
+ } catch {
+ return false;
+ }
+
+ // Open ends let a leading or trailing paragraph merge into the paragraph the
+ // caret is in, rather than splitting it.
+ const openStart = doc.firstChild?.type.name === "paragraph" ? 1 : 0;
+ const openEnd = doc.lastChild?.type.name === "paragraph" ? 1 : 0;
+ view.dispatch(
+ view.state.tr
+ .replaceSelection(new Slice(doc.content, openStart, openEnd))
+ .scrollIntoView(),
+ );
+ return true;
+}
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
index a3072c47ffb7..1968aa957963 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useDraftSync.ts
@@ -4,105 +4,12 @@ import {
isContentEmpty,
} from "@posthog/core/message-editor/content";
import { useDraftStore } from "@posthog/ui/features/message-editor/draftStore";
-import type { Editor, JSONContent } from "@tiptap/core";
+import type { Editor } from "@tiptap/core";
import { useCallback, useLayoutEffect, useRef, useState } from "react";
-
-function tiptapJsonToEditorContent(json: JSONContent): EditorContent {
- const segments: EditorContent["segments"] = [];
-
- const traverse = (node: JSONContent) => {
- if (node.type === "text" && node.text) {
- segments.push({ type: "text", text: node.text });
- } else if (node.type === "hardBreak") {
- // Shift+Enter creates a hard break within a paragraph
- // Use two trailing spaces + newline for markdown line break (<br>)
- segments.push({ type: "text", text: " \n" });
- } else if (node.type === "mentionChip" && node.attrs) {
- segments.push({
- type: "chip",
- chip: {
- type: node.attrs.type,
- id: node.attrs.id,
- label: node.attrs.label,
- pastedText: node.attrs.pastedText,
- skillPath: node.attrs.skillPath,
- skillSource: node.attrs.skillSource,
- skillName: node.attrs.skillName,
- },
- });
- } else if (node.type === "doc" && node.content) {
- // Add double newlines between paragraphs for markdown rendering
- // (single newlines in markdown become spaces, double newlines create paragraph breaks)
- for (let i = 0; i < node.content.length; i++) {
- if (i > 0) {
- segments.push({ type: "text", text: "\n\n" });
- }
- traverse(node.content[i]);
- }
- } else if (node.content) {
- for (const child of node.content) {
- traverse(child);
- }
- }
- };
-
- traverse(json);
- return { segments };
-}
-
-export function editorContentToTiptapJson(content: EditorContent): JSONContent {
- const paragraphs: JSONContent[] = [];
- let currentParagraphContent: JSONContent[] = [];
-
- const flushParagraph = () => {
- paragraphs.push({ type: "paragraph", content: currentParagraphContent });
- currentParagraphContent = [];
- };
-
- for (const seg of content.segments) {
- if (seg.type === "text") {
- const paragraphParts = seg.text.split("\n\n");
- for (let i = 0; i < paragraphParts.length; i++) {
- if (i > 0) {
- flushParagraph();
- }
- const lineParts = paragraphParts[i].split(/ {2}\n|\n/);
- for (let j = 0; j < lineParts.length; j++) {
- if (j > 0) {
- currentParagraphContent.push({ type: "hardBreak" });
- }
- if (lineParts[j]) {
- currentParagraphContent.push({ type: "text", text: lineParts[j] });
- }
- }
- }
- } else {
- currentParagraphContent.push({
- type: "mentionChip",
- attrs: {
- type: seg.chip.type,
- id: seg.chip.id,
- label: seg.chip.label,
- pastedText: seg.chip.pastedText ?? false,
- skillPath: seg.chip.skillPath,
- skillSource: seg.chip.skillSource,
- skillName: seg.chip.skillName,
- },
- });
- }
- }
-
- flushParagraph();
-
- if (paragraphs.length === 0) {
- paragraphs.push({ type: "paragraph", content: [] });
- }
-
- return {
- type: "doc",
- content: paragraphs,
- };
-}
+import {
+ editorContentToTiptapJson,
+ tiptapJsonToEditorContent,
+} from "./markdownDoc";
export interface DraftContext {
taskId?: string;
diff --git a/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts b/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
index 99ff528bfe07..76936b3612ac 100644
--- a/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
+++ b/products/desktop/packages/ui/src/features/message-editor/tiptap/useTiptapEditor.ts
@@ -15,7 +15,6 @@ import {
buildMarkdownLink,
buildPastedTextLabel,
extractBashCommand,
- isBashModeText,
isRepeatOfAutoConvertedPaste,
isUrlOnly,
shouldAutoConvertLongText,
@@ -31,7 +30,7 @@ import { TIP_KEYS } from "@posthog/ui/features/settings/tipKeys";
import { hintToast } from "@posthog/ui/primitives/hintToast";
import { toast } from "@posthog/ui/primitives/toast";
import { isSendMessageSubmitKey } from "@posthog/ui/utils/sendMessageKey";
-import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { Fragment, type Node as ProseMirrorNode } from "@tiptap/pm/model";
import { TextSelection } from "@tiptap/pm/state";
import type { EditorView } from "@tiptap/pm/view";
import { useEditor } from "@tiptap/react";
@@ -42,18 +41,17 @@ import { usePasteUndoStore } from "../pasteUndoStore";
import { usePromptHistoryStore } from "../promptHistoryStore";
import { findChipRangeById } from "../tiptap/chipRange";
import { getEditorExtensions } from "../tiptap/extensions";
+import { editorContentToTiptapJson } from "../tiptap/markdownDoc";
+import { insertPastedMarkdown } from "../tiptap/markdownPaste";
import { getPromptEditorAttributes } from "../tiptap/promptEditorAttributes";
-import {
- type DraftContext,
- editorContentToTiptapJson,
- useDraftSync,
-} from "../tiptap/useDraftSync";
+import { type DraftContext, useDraftSync } from "../tiptap/useDraftSync";
import { htmlToMarkdown } from "../utils/htmlToMarkdown";
import {
persistImageFile,
persistTextContent,
resolveAndAttachDroppedFiles,
} from "../utils/persistFile";
+import { isBashModeDoc, markdownFragment } from "./composerDocument";
export interface UseTiptapEditorOptions {
sessionId: string;
@@ -201,8 +199,13 @@ async function resolveGithubRefChip(
}
function replaceComposerText(view: EditorView, text = "") {
- const tr = view.state.tr.delete(1, view.state.doc.content.size - 1);
- return text ? tr.insertText(text, 1) : tr;
+ const { schema, doc, tr } = view.state;
+ // Replaces whole blocks, not just their text, so the recalled document
+ // replaces whatever block the composer held.
+ const content = text
+ ? markdownFragment(schema, text)
+ : Fragment.from(schema.nodes.paragraph.create());
+ return tr.replaceWith(0, doc.content.size, content);
}
function hasVisibleSuggestionPopup(sessionId: string): boolean {
@@ -460,7 +463,9 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
// Recalling up parks the caret at the start so the next Up
// press keeps cycling; recalling down parks it at the end.
if (event.key === "ArrowUp") {
- tr.setSelection(TextSelection.create(tr.doc, 1));
+ // atStart, not position 1: a recalled list or fence puts the
+ // first text position deeper than the first paragraph would.
+ tr.setSelection(TextSelection.atStart(tr.doc));
}
view.dispatch(tr);
return true;
@@ -669,6 +674,13 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
return true;
}
+ // Lists, fences and inline code paste as nodes; input rules only fire
+ // while typing, so without this they would stay literal text.
+ if (effectiveText && insertPastedMarkdown(view, effectiveText)) {
+ event.preventDefault();
+ return true;
+ }
+
// Insert inline; ProseMirror would otherwise drop the HTML formatting.
if (markdown) {
event.preventDefault();
@@ -696,7 +708,7 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
},
onUpdate: ({ editor: e }) => {
const text = e.getText();
- const newBashMode = enableBashMode && isBashModeText(text);
+ const newBashMode = enableBashMode && isBashModeDoc(e, text);
if (newBashMode !== prevBashModeRef.current) {
prevBashModeRef.current = newBashMode;
@@ -784,7 +796,7 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
draft.clearDraft();
};
- if (enableBashMode && isBashModeText(text)) {
+ if (enableBashMode && isBashModeDoc(editor, text)) {
// Bash mode requires immediate execution, can't be queued.
// Intentionally bypasses onBeforeSubmit — bash commands run inline and
// cannot be deferred the way normal prompts can.
@@ -940,7 +952,8 @@ export function useTiptapEditor(options: UseTiptapEditorOptions) {
const isEmpty = !editor || (isEmptyState && attachments.length === 0);
const isBashMode =
- enableBashMode && (editor ? isBashModeText(editor.getText()) : false);
+ enableBashMode &&
+ (editor ? isBashModeDoc(editor, editor.getText()) : false);
return {
editor,