Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(mentions): render users from id-only mention payloads (#9452)

gbirmanba49f3ee4db7
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 5fd37a8f7b..db503ee0f0 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -23,6 +23,10 @@
## Verifying a change in a real browser
+ID-only user mention rendering, name lookup failure, and composer save/reopen
+are covered on desktop/tablet/phone by `user-mentions.browser.e2e.ts` in the
+LexicalMarkdown core browser suite (see its README).
+
During iterative visual tweaks, use focused browser verification; defer full typechecks and CI checks until the batch is ready or the user requests them.
Any user-visible change should be exercised in a browser before you call it fixed — type-check, biome, and vitest all pass on code that still has the interaction bug.
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md
index 43db14f851..2431fe0329 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/README.md
@@ -33,6 +33,12 @@ the local fixture are intercepted. Run just this case by adding
Screenshots: [desktop](proof/autolinks-desktop.png) and
[phone](proof/autolinks-mobile.png).
+## User mentions
+
+`user-mentions.browser.e2e.ts` checks ID-only user mentions in the production
+renderer and composer, including name lookup success/failure and save/reopen,
+on desktop, tablet, and phone.
+
## Ordered list start
`lists.browser.e2e.ts` types `6.` then Enter in the production channel
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx
index 790030e8b3..86069a2211 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.tsx
@@ -6,13 +6,18 @@ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { createSignal, onCleanup } from 'solid-js';
import { render } from 'solid-js/web';
import { buildConfig } from '../../../builder/MarkdownConfigBuilder';
+import { initializeLexical } from '../../../init';
import { ComposerEditor } from '../../ComposerEditor';
import { StaticMarkdown, StaticMarkdownContext } from '../StaticMarkdown';
+initializeLexical();
+
const url = 'https://apps.apple.com/us/app/macro-app/id6743133649';
const original = `hey! can you rate the Macro app on the App Store (5 stars if you're feeling it) and leave a quick review if you can? takes 30 seconds:\n${url}\n\n(sent by @macro on behalf of Jacob)`;
function Fixture() {
+ const initialValue =
+ new URLSearchParams(location.search).get('markdown') ?? url;
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
@@ -55,10 +60,13 @@ function Fixture() {
/>
</section>
<section class="border border-edge rounded p-4 space-y-3">
- <h2>Edit and save a link</h2>
+ <div data-testid="input">
+ <StaticMarkdown markdown={initialValue} />
+ </div>
+ <h2>Edit and save a message</h2>
<ComposerEditor
config={editor}
- initialValue={url}
+ initialValue={initialValue}
ariaLabel="Message"
/>
<button
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/user-mentions.browser.e2e.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/user-mentions.browser.e2e.ts
new file mode 100644
index 0000000000..2dae1d76f3
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/browser-test/user-mentions.browser.e2e.ts
@@ -0,0 +1,75 @@
+import { expect, test } from '@playwright/test';
+
+for (const resolveName of [true, false]) {
+ test(`ID-only mentions render and survive editing (name lookup ${resolveName ? 'succeeds' : 'fails'})`, async ({
+ page,
+ context,
+ }, testInfo) => {
+ await context.route('**/*', async (route) => {
+ const url = new URL(route.request().url());
+ if (url.pathname.endsWith('/user/get_names_with_email')) {
+ await route.fulfill({
+ status: resolveName ? 200 : 500,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ names: [
+ {
+ id: 'macro|[email protected]',
+ first_name: 'Example',
+ last_name: 'User',
+ },
+ ],
+ }),
+ });
+ } else if (
+ url.hostname === 'localhost' &&
+ !url.pathname.includes('/__macro_dev/')
+ ) {
+ await route.continue();
+ } else {
+ await route.fulfill({
+ status: 401,
+ contentType: 'application/json',
+ body: '{}',
+ });
+ }
+ });
+ await page.routeWebSocket('**/*', (socket) => socket.close());
+ const errors: string[] = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ const markdown =
+ '<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention>';
+ const nameRequest = page.waitForResponse((response) =>
+ response.url().endsWith('/user/get_names_with_email')
+ );
+ await page.goto(
+ `/src/lib/core/component/LexicalMarkdown/component/core/browser-test/links.html?markdown=${encodeURIComponent(markdown)}`
+ );
+ await nameRequest;
+
+ const label = resolveName ? '@Example' : '@user';
+ const rendered = page.getByTestId('input').locator('[data-user-mention]');
+ const editor = page.getByRole('textbox', { name: 'Message' });
+ await expect(rendered).toHaveText(label);
+ await expect(rendered).toHaveAttribute(
+ 'data-user-id',
+ );
+ await expect(editor.locator('[data-user-mention]')).toHaveText(label);
+ await page
+ .getByRole('button', { name: 'Save message', exact: true })
+ .click();
+ await expect(
+ page.getByTestId('saved').locator('[data-user-mention]')
+ ).toHaveText(label);
+ await page.getByRole('button', { name: 'Reopen saved message' }).click();
+ await expect(editor.locator('[data-user-mention]')).toHaveText(label);
+ expect(errors).toEqual([]);
+ await page
+ .getByTestId('input')
+ .locator('..')
+ .screenshot({
+ path: testInfo.outputPath('user-mention.png'),
+ });
+ });
+}
diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.md
index a1e58ee18e..52fc786e42 100644
--- a/docs/agent-guide/channels.md
+++ b/docs/agent-guide/channels.md
@@ -1,5 +1,10 @@
# Channels and Messaging
+User mentions sent by integrations may contain only `userId`. For human user
+IDs, messages and editors resolve the current name and fall back to the email
+local part when lookup fails. Verify that these mentions remain intact when
+editing and saving a message; integrations need not supply email or displayName.
+
## Channel list previews
Message text in channel rows and Home cards is display-only, including quoted
diff --git a/packages/lexical-core/AGENTS.md b/packages/lexical-core/AGENTS.md
index a71a54f731..0d560f6319 100644
--- a/packages/lexical-core/AGENTS.md
+++ b/packages/lexical-core/AGENTS.md
@@ -28,6 +28,10 @@ composer imports the URL matcher from this package; do not duplicate it.
## Gotchas
+Human user mention Markdown requires only a nonempty string `userId`; the importer
+derives a missing email from `macro|` IDs so web name lookup and clipboard round
+trips can resolve the user. Other identities still need an email or display name.
+
Keep URLs protected from inline formatting during import; matching rendered
text is too late. Preserve code, mention payloads, existing links, and escaped
literal URLs. Keep unlink state through both Markdown and Lexical JSON saves.
diff --git a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
index a07b34ecc1..93244fa091 100644
--- a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
+++ b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
@@ -96,9 +96,37 @@ describe('internal transformer fallbacks', () => {
});
});
+ it.each([
+ ['{"userId":"macro|[email protected]"}', '@user'],
+ ['{"userId":"macro|[email protected]","displayName":"Example"}', '@Example'],
+ ])('imports ID-only user mentions: %s', async (payload, text) => {
+ const editor = await importMarkdown(
+ `<m-user-mention>${payload}</m-user-mention>`
+ );
+
+ editor.getEditorState().read(() => {
+ const paragraph = $getRoot().getFirstChild();
+ const node = $isParagraphNode(paragraph)
+ ? paragraph.getFirstChild()
+ : null;
+ expect($isUserMentionNode(node)).toBe(true);
+ if (!$isUserMentionNode(node)) throw new Error('Missing user mention');
+ expect(node.getUserId()).toBe('macro|[email protected]');
+ expect(node.getEmail()).toBe('[email protected]');
+ expect(node.getTextContent()).toBe(text);
+ });
+ });
+
it.each([
['<m-user-mention>{bad}</m-user-mention>', 'Unknown User'],
['<m-user-mention>{"email":"[email protected]"}</m-user-mention>', 'Unknown User'],
+ ['<m-user-mention>{"userId":null}</m-user-mention>', 'Unknown User'],
+ ['<m-user-mention>{"userId":42}</m-user-mention>', 'Unknown User'],
+ ['<m-user-mention>{"userId":""}</m-user-mention>', 'Unknown User'],
+ [
+ '<m-user-mention>{"userId":"bot|unknown"}</m-user-mention>',
+ 'Unknown User',
+ ],
['<m-katex-equation>{bad}</m-katex-equation>', 'Unknown Equation'],
[
'<m-katex-equation>{"equation":"x"}</m-katex-equation>',
diff --git a/packages/lexical-core/transformers/mentions.ts b/packages/lexical-core/transformers/mentions.ts
index b6cdf9b0ff..12c29b45d3 100644
--- a/packages/lexical-core/transformers/mentions.ts
+++ b/packages/lexical-core/transformers/mentions.ts
@@ -58,12 +58,20 @@ export const I_USER_MENTION: TextMatchTransformer = {
replace: (node: TextNode, match: RegExpMatchArray) => {
try {
const data = JSON.parse(match[1]);
- for (const field of ['userId', 'email']) {
- if (!(field in data)) throw new Error(`Missing field ${field}`);
+ if (typeof data?.userId !== 'string' || !data.userId.trim()) {
+ throw new Error('Missing or invalid userId');
+ }
+ let email = typeof data.email === 'string' ? data.email : '';
+ if (!email && data.userId.startsWith('macro|')) {
+ email = data.userId.slice('macro|'.length);
}
+
const displayName =
typeof data.displayName === 'string' ? data.displayName : undefined;
- const userMentionNode = new UserMentionNode(data.userId, data.email, {
+ if (!email && !displayName?.trim()) {
+ throw new Error('Missing user mention label');
+ }
+ const userMentionNode = new UserMentionNode(data.userId, email, {
displayName,
});
node.replace(userMentionNode);