Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(channels): keep blank lines in composer drafts (#8619)
Peter Chinman0421b6f06611
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex e600a74aad..3eabe72050 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -70,6 +70,10 @@ Gate event notes and document Share meeting-link controls withon in dev and uses PostHog in production.See `docs/agent-guide/calendar.md` at the repo root.+Channel composer draft persistence has a backend-free browser regression:+`bunx playwright test --config src/features/channel/Input/browser-test/playwright.config.ts`.+It types a draft, remounts the composer over it, and checks the blank lines survive.+A frontend dev server runs against the **dev** backend, so this needs no local stack, Docker, Rust build, or `sudo`:```shdiff --git a/apps/web/src/features/channel/Input/browser-test/README.md b/apps/web/src/features/channel/Input/browser-test/README.mdnew file mode 100644index 0000000000..582a1cc81b--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/README.md@@ -0,0 +1,17 @@+# Channel composer draft browser regression++From `apps/web`, run:++```sh+bunx playwright test --config src/features/channel/Input/browser-test/playwright.config.ts+```++Install Playwright Chromium first, or set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`+to an existing Chromium/Chrome executable. `CHANNEL_DRAFT_TEST_PORT` overrides+port 3006; the harness owns and stops its Vite server.++The fixture mounts the production `ChannelInput` over the app shell's providers+and blocks hosted API traffic, so it needs no backend. It types a draft with a+blank line, unmounts the composer and mounts it again over the persisted draft,+which is the round trip through internal markdown that used to drop every blank+line.diff --git a/apps/web/src/features/channel/Input/browser-test/draft.browser.e2e.ts b/apps/web/src/features/channel/Input/browser-test/draft.browser.e2e.tsnew file mode 100644index 0000000000..95ee2a6909--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/draft.browser.e2e.ts@@ -0,0 +1,45 @@+import { expect, test } from '@playwright/test';++/** The composer's visible lines, with an empty string per blank line. */+const lines = () =>+ Array.from(+ document.querySelectorAll('[data-markdown-editable] > p'),+ (paragraph) => paragraph.textContent ?? ''+ );++test('a draft keeps its blank line across leaving and reopening the channel', async ({+ page,+}) => {+ // The composer renders over synthetic props; no hosted data is read or written.+ await page.route('**/*', async (route) => {+ const url = new URL(route.request().url());+ if (url.hostname === 'localhost') {+ await route.continue();+ } else {+ await route.fulfill({+ status: 401,+ contentType: 'application/json',+ body: JSON.stringify({ responses: [] }),+ });+ }+ });+ await page.routeWebSocket('**/*', (socket) => socket.close());+ await page.goto('/src/features/channel/Input/browser-test/draft.html');++ const editor = page.locator('[data-markdown-editable]');+ await expect(editor).toBeVisible({ timeout: 30_000 });+ await editor.click();+ await page.keyboard.type('hello');+ // Shift+Enter is the composer's newline; Enter sends.+ await page.keyboard.press('Shift+Enter');+ await page.keyboard.press('Shift+Enter');+ await page.keyboard.type('world');+ await expect.poll(() => page.evaluate(lines)).toEqual(['hello', '', 'world']);++ await page.getByRole('button', { name: 'Leave channel' }).click();+ await expect(editor).toHaveCount(0);+ await page.getByRole('button', { name: 'Open channel' }).click();+ await expect(editor).toBeVisible();++ await expect.poll(() => page.evaluate(lines)).toEqual(['hello', '', 'world']);+});diff --git a/apps/web/src/features/channel/Input/browser-test/draft.html b/apps/web/src/features/channel/Input/browser-test/draft.htmlnew file mode 100644index 0000000000..f0c66935df--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/draft.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en">+ <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Channel composer draft</title></head>+ <body><div id="root"></div><script type="module" src="./draft.tsx"></script></body>+</html>diff --git a/apps/web/src/features/channel/Input/browser-test/draft.tsx b/apps/web/src/features/channel/Input/browser-test/draft.tsxnew file mode 100644index 0000000000..0423edcbfb--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/draft.tsx@@ -0,0 +1,69 @@+import '@app/index.css';+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';+import { PosthogProvider } from '@app/lib/analytics/posthog';+import { ChannelsContextProvider } from '@core/context/channels';+import { QuickAccessProvider } from '@core/context/quickAccess/QuickAccessProvider';+import { UserContextProvider } from '@core/context/user';+import { useHotKeyRoot } from '@core/hotkey/hotkeys';+import { EntityProvider } from '@entity';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { createSignal, onCleanup, Show } from 'solid-js';+import { render } from 'solid-js/web';+import { ChannelInput } from '../ChannelInput';+import { makeInputValuePersistenceKey } from '../utils/persistence';++const channelId = 'draft-fixture-channel';++/**+ * The real channel composer over the app shell's providers, in the order+ * `routes/Root.tsx` mounts them. Leaving the channel unmounts the composer;+ * opening it again mounts a fresh one over the persisted draft.+ */+function Fixture() {+ useHotKeyRoot();+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ onCleanup(() => client.clear());+ const [open, setOpen] = createSignal(true);+ return (+ <QueryClientProvider client={client}>+ <AnalyticsContextProvider>+ <PosthogProvider>+ <EntityProvider>+ <UserContextProvider>+ <ChannelsContextProvider>+ <QuickAccessProvider>+ <main class="min-h-screen bg-page p-4 text-ink space-y-4">+ <h1>Channel composer draft</h1>+ <button type="button" onClick={() => setOpen(!open())}>+ {open() ? 'Leave channel' : 'Open channel'}+ </button>+ <Show when={open()}>+ <ChannelInput+ input={{+ mode: 'channel',+ id: `channel-input-${channelId}`,+ placeholder: 'Message #draft-fixture',+ }}+ participants={() => []}+ bots={() => []}+ persistenceKey={makeInputValuePersistenceKey({+ channelId,+ })}+ />+ </Show>+ </main>+ </QuickAccessProvider>+ </ChannelsContextProvider>+ </UserContextProvider>+ </EntityProvider>+ </PosthogProvider>+ </AnalyticsContextProvider>+ </QueryClientProvider>+ );+}++const root = document.getElementById('root');+if (!root) throw new Error('Fixture root missing');+render(() => <Fixture />, root);diff --git a/apps/web/src/features/channel/Input/browser-test/playwright.config.ts b/apps/web/src/features/channel/Input/browser-test/playwright.config.tsnew file mode 100644index 0000000000..8e66b4b27b--- /dev/null+++ b/apps/web/src/features/channel/Input/browser-test/playwright.config.ts@@ -0,0 +1,26 @@+import { fileURLToPath } from 'node:url';+import { defineConfig } from '@playwright/test';++const port = process.env.CHANNEL_DRAFT_TEST_PORT ?? '3006';+export default defineConfig({+ testDir: fileURLToPath(new URL('.', import.meta.url)),+ testMatch: '*.browser.e2e.ts',+ workers: 1,+ timeout: 120_000,+ use: {+ baseURL: `http://localhost:${port}`,+ launchOptions: {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+ },+ },+ projects: [+ { name: 'desktop', use: { viewport: { width: 1280, height: 900 } } },+ ],+ webServer: {+ command: `MACRO_DEV_HTTPS=false bunx vite --port ${port} --strictPort`,+ cwd: fileURLToPath(new URL('../../../../../', import.meta.url)),+ url: `http://localhost:${port}/app/`,+ reuseExistingServer: false,+ timeout: 60_000,+ },+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.tsindex 568f47060b..a660a622d1 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils.test.ts@@ -2,7 +2,11 @@import { SupportedNodeTypes } from '@macro-inc/lexical-core';import { $getRoot, $isParagraphNode, createEditor } from 'lexical';import { describe, expect, it, vi } from 'vitest';-import { setEditorStateFromHtml } from './utils';+import {+ editorStateAsMarkdown,+ setEditorStateFromHtml,+ setEditorStateFromMarkdown,+} from './utils';// utils.ts imports the plugin barrel, whose leaves open the storage and// connection-gateway sockets on import.@@ -56,3 +60,28 @@ describe('setEditorStateFromHtml', () => {]);});});++describe('setEditorStateFromMarkdown', () => {+ it('keeps the blank line a restored composer draft was written with', () => {+ const editor = makeEditor();+ const draft = 'hello\n\n \n\nworld';++ setEditorStateFromMarkdown(editor, draft);++ expect(topLevel(editor)).toEqual([+ { paragraph: true, text: 'hello' },+ { paragraph: true, text: '' },+ { paragraph: true, text: 'world' },+ ]);+ expect(editorStateAsMarkdown(editor)).toBe(draft);+ });+ it('imports external markdown without the empty-paragraph sentinel', () => {+ const editor = makeEditor();++ setEditorStateFromMarkdown(editor, 'hello\n\n \n\nworld', 'external');++ expect(+ editor.read(() => $getRoot().getTextContent()).includes('\u200b')+ ).toBe(false);+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/utils.tsindex d6929ce654..a22b934752 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/utils.ts@@ -27,6 +27,7 @@ import {EXTERNAL_TRANSFORMERS,INITIALIZE_LOCAL_STATUS,INTERNAL_TRANSFORMERS,+ protectEmptyParagraphLines,stripDraftCommentMarks,} from '@macro-inc/lexical-core';import { SKIP_SCROLL_INTO_VIEW_TAG } from '@macro-inc/lexical-core/constants';@@ -342,21 +343,17 @@ export function setEditorStateFromMarkdown(});}const transformers = weakTransformersByEditor.get(editor)![target];+ const source = protectEmptyParagraphLines(markdown, transformers);if (!inUpdate) {editor.update(() => {$addUpdateTag(SKIP_DOM_SELECTION_TAG);- $convertFromMarkdownString(- markdown,- transformers,- node,- preserveNewLines- );+ $convertFromMarkdownString(source, transformers, node, preserveNewLines);});editor.read(() => {});return editor.getEditorState();} else {- $convertFromMarkdownString(markdown, transformers, node, preserveNewLines);+ $convertFromMarkdownString(source, transformers, node, preserveNewLines);}}diff --git a/packages/lexical-core/tests/preserve-lines.test.ts b/packages/lexical-core/tests/preserve-lines.test.tsnew file mode 100644index 0000000000..27f7b02e2c--- /dev/null+++ b/packages/lexical-core/tests/preserve-lines.test.ts@@ -0,0 +1,133 @@+import {+ $convertFromMarkdownString,+ $convertToMarkdownString,+} from '@lexical/markdown';+import {+ $createParagraphNode,+ $createTextNode,+ $getRoot,+ $isParagraphNode,+ createEditor,+ type LexicalEditor,+} from 'lexical';+import { describe, expect, it } from 'vitest';+import { SupportedNodeTypes } from '../node-list';+import {+ ALL_TRANSFORMERS,+ EXTERNAL_TRANSFORMERS,+ INTERNAL_TRANSFORMERS,+} from '../transformers';+import { protectEmptyParagraphLines } from '../transformers/transformers';++function makeEditor() {+ return createEditor({+ nodes: SupportedNodeTypes,+ onError: (error) => {+ throw error;+ },+ });+}++/** The paragraph structure a composer builds from the given lines. */+function withParagraphs(lines: string[]): LexicalEditor {+ const editor = makeEditor();+ editor.update(+ () => {+ const root = $getRoot();+ root.clear();+ for (const line of lines) {+ const paragraph = $createParagraphNode();+ if (line) paragraph.append($createTextNode(line));+ root.append(paragraph);+ }+ },+ { discrete: true }+ );+ return editor;+}++function exportMarkdown(editor: LexicalEditor): string {+ return editor.read(() => $convertToMarkdownString(INTERNAL_TRANSFORMERS));+}++function importMarkdown(markdown: string, protect = true): LexicalEditor {+ const editor = makeEditor();+ editor.update(+ () => {+ $convertFromMarkdownString(+ protect+ ? protectEmptyParagraphLines(markdown, ALL_TRANSFORMERS)+ : markdown,+ ALL_TRANSFORMERS+ );+ },+ { discrete: true }+ );+ return editor;+}++function textContent(editor: LexicalEditor): string {+ return editor.read(() => $getRoot().getTextContent());+}++function paragraphs(editor: LexicalEditor): string[] {+ return editor.read(() =>+ $getRoot()+ .getChildren()+ .filter($isParagraphNode)+ .map((node) => node.getTextContent())+ );+}++describe('empty paragraphs in internal markdown', () => {+ it.each([+ ['between paragraphs', ['hello', '', 'world']],+ ['repeated', ['hello', '', '', 'world']],+ ['leading', ['', 'hello']],+ ['trailing', ['hello', '']],+ ])('survives an export and import round trip: %s', (_name, lines) => {+ const markdown = exportMarkdown(withParagraphs(lines));+ const reloaded = importMarkdown(markdown);++ expect(paragraphs(reloaded)).toEqual(lines);+ expect(exportMarkdown(reloaded)).toBe(markdown);+ });++ it('leaves a lone space inside fenced code as content', () => {+ const markdown = '```\na\n \nb\n```';++ expect(protectEmptyParagraphLines(markdown, ALL_TRANSFORMERS)).toBe(+ markdown+ );+ expect(textContent(importMarkdown(markdown))).toBe('a\n \nb');+ });++ it.each([+ ['a shorter fence inside a longer one', '````\n```\n \n````'],+ ['an unclosed fence', '```\na\n \nb'],+ ])('keeps the sentinel out of %s', (_name, markdown) => {+ expect(protectEmptyParagraphLines(markdown, ALL_TRANSFORMERS)).toBe(+ markdown+ );+ // Lexical's own normalizer decides what happens to the space from here.+ expect(textContent(importMarkdown(markdown))).toBe(+ textContent(importMarkdown(markdown, false))+ );+ });++ it('protects a blank line after a fence that closes on its own line', () => {+ expect(protectEmptyParagraphLines('```a```\n \nb', ALL_TRANSFORMERS)).toBe(+ '```a```\n\u200b\nb'+ );+ });++ it('leaves markdown alone when nothing will read the sentinel', () => {+ expect(+ protectEmptyParagraphLines('a\n\n \n\nb', EXTERNAL_TRANSFORMERS)+ ).toBe('a\n\n \n\nb');+ });++ it('keeps a soft line break inside one paragraph', () => {+ expect(paragraphs(importMarkdown('a\nb'))).toEqual(['a\nb']);+ });+});diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.tsindex b55cbffc75..0781d9de50 100644--- a/packages/lexical-core/transformers/index.ts+++ b/packages/lexical-core/transformers/index.ts@@ -53,6 +53,7 @@ import {LINK_XML,MARK_XML,PRESERVE_LINES,+ protectEmptyParagraphLines,SEARCH_MATCH,UNLINKED_TEXT,} from './transformers';@@ -60,7 +61,7 @@ import { UNKNOWN_MENTION } from './unknownMention';import { I_VIDEO, VIDEO_LINK } from './video';import { E_WATERMARK, I_WATERMARK } from './watermark';-export { isConversionOnlyTransformer };+export { isConversionOnlyTransformer, protectEmptyParagraphLines };/*** Internal transformers for converting markdown between Lexical state and markdown.diff --git a/packages/lexical-core/transformers/transformers.ts b/packages/lexical-core/transformers/transformers.tsindex 37afad9ee9..f002c92041 100644--- a/packages/lexical-core/transformers/transformers.ts+++ b/packages/lexical-core/transformers/transformers.ts@@ -14,6 +14,7 @@ import type {MultilineElementTransformer,TextFormatTransformer,TextMatchTransformer,+ Transformer,} from '@lexical/markdown';import {$createLineBreakNode,@@ -73,7 +74,65 @@ export function isConversionOnlyTransformer<T extends LexicalTransformer>(return 'conversionOnly' in transformer;}-// See https://github.com/facebook/lexical/issues/4271/ for the reasoning behind this.+/**+ * An empty paragraph written as a line holding a single space, so that a blank+ * line survives a markdown round trip. Internal markdown keeps this form; see+ * https://github.com/facebook/lexical/issues/4271/ for the reasoning.+ */+const EMPTY_PARAGRAPH_LINE = ' ';++/**+ * The form `protectEmptyParagraphLines` rewrites `EMPTY_PARAGRAPH_LINE` to+ * before handing markdown to Lexical. A zero-width space is not whitespace to+ * `String.prototype.trimEnd`, so Lexical's normalizer leaves it intact.+ */+const EMPTY_PARAGRAPH_SENTINEL = '\u200b';++// Lexical's CODE import opens a fence on any line starting with three or more+// backticks and closes it at the first later line of at least as many+// backticks; a fence that never closes runs to the end. Fence lines reach it+// with trailing whitespace already trimmed.+const CODE_FENCE_START = /^[ \t]*`{3,}/;++/**+ * Rewrite every empty-paragraph line outside fenced code to a sentinel Lexical+ * will not erase. `$convertFromMarkdownString` normalizes its input before any+ * transformer runs, and that normalizer trims trailing whitespace off every+ * line, which turns `EMPTY_PARAGRAPH_LINE` into an ordinary blank separator and+ * drops the paragraph. Inside a fence a lone space is content, so those lines+ * are left alone. Only `PRESERVE_LINES` turns the sentinel back into an empty+ * paragraph, so markdown imported without it is returned unchanged.+ */+export function protectEmptyParagraphLines(+ markdown: string,+ transformers: readonly Transformer[]+): string {+ if (!transformers.includes(PRESERVE_LINES)) return markdown;+ const lines = markdown.split('\n');+ let closingFence: RegExp | undefined;+ for (let index = 0; index < lines.length; index++) {+ const line = lines[index];+ if (closingFence) {+ if (closingFence.test(line.trimEnd())) closingFence = undefined;+ continue;+ }+ const fence = CODE_FENCE_START.exec(line.trimEnd())?.[0];+ if (fence !== undefined) {+ const length = fence.trim().length;+ const rest = line.trimEnd().slice(fence.length);+ // A fence that also closes on its own line is a one-line code block.+ if (!new RegExp(`\`{${length},}$`).test(rest)) {+ closingFence = new RegExp(`^[ \\t]*\`{${length},}$`);+ }+ continue;+ }+ if (line === EMPTY_PARAGRAPH_LINE) {+ lines[index] = EMPTY_PARAGRAPH_SENTINEL;+ }+ }+ return lines.join('\n');+}+export const PRESERVE_LINES: ConversionOnlyTransformer<ElementTransformer> = {type: 'element',dependencies: [ParagraphNode],@@ -83,14 +142,18 @@ export const PRESERVE_LINES: ConversionOnlyTransformer<ElementTransformer> = {// A decorator with no text content - an await spinner, say - is still// a child worth exporting, not a blank line.if (!content.trim() && !node.getChildren().some($isDecoratorNode)) {- return '\n \n';+ return `\n${EMPTY_PARAGRAPH_LINE}\n`;}}return null;},- regExp: /^ $/, // a line with only a space+ // A line holding only the empty-paragraph marker, in either form.+ regExp: new RegExp(`^[${EMPTY_PARAGRAPH_LINE}${EMPTY_PARAGRAPH_SENTINEL}]$`),replace: (textNode, nodes, _, isImport) => {if (isImport && nodes.length === 1) {+ // The second empty child keeps Lexical's import from reading the+ // paragraph as a blank separator and removing it; both collapse away+ // when the editor normalizes the imported state.textNode.append($createTextNode(''));}},