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(pr-mention): keep PR mentions a fixed height in channels (#7974)

teo271cdb46da05
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.test.tsx
new file mode 100644
index 0000000000..aa6617bef0
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.test.tsx
@@ -0,0 +1,120 @@
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import { render, screen } from '@solidjs/testing-library';
+import { createSignal } from 'solid-js';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@components/app/split-layout/layout', () => ({
+ useSplitLayout: () => ({ openWithSplit: vi.fn() }),
+}));
+vi.mock('@queries/storage/pr-mention', () => ({
+ usePrMentionQuery: () => idQuery,
+ usePullRequestByGithubKeyQuery: () => githubKeyQuery,
+}));
+vi.mock('@core/component/HoverCard', () => ({
+ HoverCard: (props: { trigger: import('solid-js').JSX.Element }) =>
+ props.trigger,
+}));
+vi.mock('../../plugins', () => ({ autoRegister: vi.fn() }));
+
+import { PullRequestMention } from './PullRequestMention';
+
+const title = 'feat(text-paste): smart paste for GitHub pull request URLs';
+const url = 'https://github.com/macro-inc/macro/pull/7956';
+const pullRequest: ForeignEntity = {
+ id: 'pr-1',
+ foreignEntityId: 'macro-inc/macro/pull/7956',
+ foreignEntitySource: 'github_pull_request',
+ metadata: {
+ name: title,
+ owner: 'macro-inc',
+ repo: 'macro',
+ number: 7956,
+ url,
+ status: 'merged',
+ },
+ createdAt: '',
+ updatedAt: '',
+ storedForAuthEntity: '',
+ storedForId: '',
+};
+
+const [resolved, setResolved] = createSignal<ForeignEntity>();
+// Reading a pending solid-query `data` suspends the caller, so it throws here.
+const idQuery = {
+ get isSuccess() {
+ return resolved() !== undefined;
+ },
+ get data() {
+ const entity = resolved();
+ if (!entity) throw new Error('unguarded resource read');
+ return entity;
+ },
+};
+const githubKeyQuery = {
+ get isSuccess() {
+ return resolved() !== undefined;
+ },
+ get data() {
+ return resolved() ?? null;
+ },
+};
+
+beforeEach(() => {
+ setResolved(undefined);
+});
+
+describe('pull request mention face', () => {
+ it('shows a stored label exactly as the resolved PR before its lookup settles', () => {
+ const view = render(() => (
+ <PullRequestMention
+ id={pullRequest.id}
+ label={`macro-inc/macro#7956 ${title}`}
+ key="node"
+ theme={{}}
+ />
+ ));
+ const name = screen.getByText(title);
+ const before = view.container.textContent;
+ expect(before).toBe(`${title} #7956`);
+
+ setResolved(pullRequest);
+
+ expect(view.container.textContent).toBe(before);
+ expect(screen.getByText(title)).toBe(name);
+ });
+
+ it('truncates only the title so a long one never wraps or hides the number', () => {
+ setResolved(pullRequest);
+ render(() => (
+ <PullRequestMention id={pullRequest.id} key="node" theme={{}} />
+ ));
+ const name = screen.getByText(title);
+ expect(name.classList.contains('truncate')).toBe(true);
+ expect(name.closest('[data-pr-mention]')?.textContent).toContain('#7956');
+ expect(name.textContent).not.toContain('#7956');
+ });
+
+ it('reserves the title width for an agent-written URL mention until and after it resolves', () => {
+ const view = render(() => (
+ <>
+ <PullRequestMention id="" url={url} label="" key="agent" theme={{}} />
+ <PullRequestMention
+ id={pullRequest.id}
+ label={`macro-inc/macro#7956 ${title}`}
+ key="composed"
+ theme={{}}
+ />
+ </>
+ ));
+ const [agentWritten, composed] =
+ view.container.querySelectorAll('[data-pr-mention]');
+ expect(agentWritten.textContent).toBe('macro-inc/macro#7956');
+ expect(agentWritten.classList.contains('w-[20em]')).toBe(true);
+ expect(composed.classList.contains('w-[20em]')).toBe(false);
+
+ setResolved(pullRequest);
+
+ expect(agentWritten.textContent).toBe(`${title} #7956`);
+ expect(agentWritten.classList.contains('w-[20em]')).toBe(true);
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
index 3983f2b06a..b451adcfee 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
@@ -123,12 +123,27 @@ interface PullRequestParts {
number?: string;
}
+/** The `owner/repo#N title` label `pullRequestLabel` writes to the node. */
+const RESOLVED_LABEL_PATTERN =
+ /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+#([1-9][0-9]*) (.+)$/;
+
+/**
+ * Split a stored label into the face a resolved PR shows, so a mention whose
+ * label already names the PR renders the same text before and after its
+ * lookup settles.
+ */
+function labelParts(label: string | undefined): PullRequestParts {
+ const match = label?.match(RESOLVED_LABEL_PATTERN);
+ if (match) return { name: match[2], number: `#${match[1]}` };
+ return { name: fallbackLabel(label) };
+}
+
function pullRequestParts(
entity: ForeignEntity | undefined,
label: string | undefined
): PullRequestParts {
if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
- return { name: fallbackLabel(label) };
+ return labelParts(label);
}
const metadata = metadataRecord(entity.metadata);
@@ -456,8 +471,10 @@ function PullRequestMentionContent(props: PullRequestMentionDecoratorProps) {
const query = usePrMentionQuery(() => props.id, fetchEnabled);
const urlEntity = useGithubUrlMentionEntity(props, fetchEnabled);
- // Only an id mention reads `query.data`, which suspends until it loads.
- const entity = () => (props.id ? query.data : urlEntity());
+ const entity = () => {
+ if (!props.id) return urlEntity();
+ return query.isSuccess ? query.data : undefined;
+ };
const label = createMemo(
() =>
@@ -466,10 +483,10 @@ function PullRequestMentionContent(props: PullRequestMentionDecoratorProps) {
const parts = createMemo(() =>
pullRequestParts(entity(), mentionFallbackLabel(props))
);
- // An unresolved GitHub URL mention has no known state yet.
+ // An unresolved mention has no known state yet.
const status = createMemo(() => {
const resolved = entity();
- return resolved || props.id ? pullRequestStatus(resolved) : 'unknown';
+ return resolved ? pullRequestStatus(resolved) : 'unknown';
});
// Keep the node's label and GitHub URL current, so the Markdown this editor
@@ -496,21 +513,30 @@ function PullRequestMentionContent(props: PullRequestMentionDecoratorProps) {
);
});
+ // A sent message must not change height when the PR resolves after it
+ // mounts: the face stays on one line, and one whose markup lacks the title
+ // (an agent's URL-only mention) takes the full width the title will fill.
+ const reservesTitleWidth = () =>
+ !labelParts(mentionFallbackLabel(props)).number;
+
return (
<span
data-pr-mention="true"
data-pr-id={props.id}
data-pr-label={label()}
- class="pointer-events-auto"
+ class={cn(
+ 'pointer-events-auto inline-flex max-w-[min(20em,100%)] items-baseline',
+ reservesTitleWidth() && 'w-[20em]'
+ )}
>
- <span class="relative top-[0.125em] size-[1em] inline-flex mx-1">
+ <span class="relative top-[0.125em] size-[1em] shrink-0 inline-flex mx-1">
<PullRequestStatusIcon status={status()} />
</span>
- <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
- {parts().name}
+ <span class="flex min-w-0 items-baseline underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
+ <span class="min-w-0 truncate">{parts().name}</span>
<Show when={parts().number}>
{(number) => (
- <span class="text-ink-extra-muted text-[0.8em]">{` ${number()}`}</span>
+ <span class="shrink-0 whitespace-pre text-ink-extra-muted text-[0.8em]">{` ${number()}`}</span>
)}
</Show>
</span>
@@ -581,13 +607,7 @@ export function PullRequestMention(props: PullRequestMentionDecoratorProps) {
)}
{...navHandlers}
>
- <Suspense
- fallback={
- <span class="text-ink-placeholder">Fetching PR...</span>
- }
- >
- <PullRequestMentionContent {...props} />
- </Suspense>
+ <PullRequestMentionContent {...props} />
</span>
<MentionTooltip show={isSelectedAsNode()} text="Open" />
</span>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.html b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.html
new file mode 100644
index 0000000000..5a022b3f9d
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8"><title>Pull request mention fixture</title></head>
+ <body><div id="root"></div><script type="module" src="./pr-mention.tsx"></script></body>
+</html>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.tsx
new file mode 100644
index 0000000000..a090eed2fc
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/browser-test/pr-mention.tsx
@@ -0,0 +1,174 @@
+import '@app/index.css';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
+import { PullRequestMentionNode } from '@macro-inc/lexical-core';
+import { setDecorator } from '@macro-inc/lexical-core/decoratorRegistry';
+import { pullRequestMentionKeys } from '@queries/storage/keys';
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import { onElementConnect } from '@solid-primitives/lifecycle';
+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
+import { createSignal, For, onCleanup } from 'solid-js';
+import { render } from 'solid-js/web';
+import {
+ createLexicalWrapper,
+ LexicalWrapperContext,
+} from '../../../context/LexicalWrapperContext';
+import { selectionDataPlugin } from '../../../plugins';
+import { channelTheme } from '../../../theme';
+import { setEditorStateFromMarkdown } from '../../../utils';
+import { DecoratorRenderer } from '../../core/DecoratorRenderer';
+import {
+ StaticMarkdown,
+ StaticMarkdownContext,
+} from '../../core/StaticMarkdown';
+import { PullRequestMention } from '../PullRequestMention';
+
+setDecorator(PullRequestMentionNode, PullRequestMention);
+
+const title = 'feat(text-paste): smart paste for GitHub pull request URLs';
+const url = 'https://github.com/macro-inc/macro/pull/7956';
+const githubKey = 'macro-inc/macro/pull/7956';
+const pullRequest: ForeignEntity = {
+ id: 'pr-mention-fixture',
+ foreignEntityId: githubKey,
+ foreignEntitySource: 'github_pull_request',
+ metadata: {
+ name: title,
+ owner: 'macro-inc',
+ repo: 'macro',
+ number: 7956,
+ url,
+ status: 'merged',
+ },
+ createdAt: '',
+ updatedAt: '',
+ storedForAuthEntity: '',
+ storedForId: '',
+};
+
+const mention = (data: Record<string, string>) =>
+ `<m-pr-mention>${JSON.stringify(data)}</m-pr-mention>`;
+// Sent from a Macro composer, which writes the resolved label to the node.
+const composed = mention({
+ id: pullRequest.id,
+ label: `macro-inc/macro#7956 ${title}`,
+});
+// Written by an agent, which knows only the GitHub URL.
+const agentWritten = mention({ url, label: '' });
+
+/** Records every height a sent message takes, starting at mount. */
+function SentMessage(props: { markdown: string }) {
+ const [heights, setHeights] = createSignal<number[]>([]);
+ const observer = new ResizeObserver(([entry]) => {
+ const height = Math.round(entry.borderBoxSize[0].blockSize);
+ setHeights((prev) => (prev.at(-1) === height ? prev : [...prev, height]));
+ });
+ onCleanup(() => observer.disconnect());
+ return (
+ <div class="space-y-1">
+ <div
+ ref={(element) => observer.observe(element)}
+ data-testid="sent-message"
+ class="w-96 border border-edge-muted p-2"
+ >
+ <StaticMarkdown markdown={props.markdown} target="internal" />
+ </div>
+ <div data-testid="height-history" class="text-xs text-ink-muted">
+ {`Height since mount: ${heights()
+ .map((height) => `${height}px`)
+ .join(' → ')}`}
+ </div>
+ </div>
+ );
+}
+
+/** An editable editor with only the PR mention decorator registered. */
+function Composer(props: { markdown: string }) {
+ const wrapper = createLexicalWrapper({
+ type: 'chat',
+ namespace: 'pr-mention-composer',
+ isInteractable: () => true,
+ });
+ wrapper.plugins.richText().use(selectionDataPlugin(wrapper));
+ setEditorStateFromMarkdown(wrapper.editor, props.markdown);
+ onCleanup(() => wrapper.cleanup());
+ return (
+ <LexicalWrapperContext.Provider value={wrapper}>
+ <div data-testid="composer" class="w-96 border border-edge-muted p-2">
+ <div
+ ref={(element) =>
+ onElementConnect(element, () =>
+ wrapper.editor.setRootElement(element)
+ )
+ }
+ contentEditable
+ role="textbox"
+ class="outline-none"
+ />
+ <DecoratorRenderer editor={wrapper.editor} />
+ </div>
+ </LexicalWrapperContext.Provider>
+ );
+}
+
+function Fixture() {
+ const client = new QueryClient();
+ const wrapper = createLexicalWrapper({
+ type: 'chat',
+ namespace: 'pr-mention-fixture',
+ isInteractable: () => false,
+ });
+ onCleanup(() => {
+ wrapper.cleanup();
+ client.clear();
+ });
+ const resolve = () => {
+ client.setQueryData(
+ pullRequestMentionKeys.foreignEntity(pullRequest.id).queryKey,
+ pullRequest
+ );
+ client.setQueryData(
+ pullRequestMentionKeys.byGithubKey(githubKey).queryKey,
+ pullRequest
+ );
+ };
+ return (
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <QueryClientProvider client={client}>
+ <LexicalWrapperContext.Provider
+ value={{ ...wrapper, skipPreviewFetch: true }}
+ >
+ <StaticMarkdownContext theme={channelTheme}>
+ <main class="p-4 text-ink bg-page space-y-4">
+ <For
+ each={[
+ composed,
+ `Just merged ${composed}, after next deploy we'll have nice mention nodes`,
+ agentWritten,
+ `Opened ${agentWritten} for the paste fix.`,
+ ]}
+ >
+ {(markdown) => <SentMessage markdown={markdown} />}
+ </For>
+ <Composer
+ markdown={`Opened ${agentWritten} and ${composed} today`}
+ />
+ <button
+ type="button"
+ data-testid="resolve"
+ class="rounded-md border border-edge-muted px-2 py-1"
+ onClick={resolve}
+ >
+ Resolve pull request
+ </button>
+ </main>
+ </StaticMarkdownContext>
+ </LexicalWrapperContext.Provider>
+ </QueryClientProvider>
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ );
+}
+
+render(() => <Fixture />, document.getElementById('root')!);
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index 1e6a98278e..ffbdec7051 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -1990,8 +1990,12 @@ Pasting a bare GitHub pull request URL (`github.com/<owner>/<repo>/pull/<n>`,
including subpages such as `/files`) inserts a link that becomes a PR mention
once Macro finds the synced PR, usually within a moment. Hovering the mention
shows its status, diff size, comments, and checks; clicking opens the PR in a
-split. A PR Macro has not synced stays an ordinary link, and pasting inside a
-code block or over a selection keeps the default behavior.
+split. A PR mention always stays on one line: a long title truncates with an
+ellipsis before the `#N`, so read the full title from the hover card. In a sent
+message, a mention an agent wrote by URL alone shows `owner/repo#N` until its
+title loads and keeps the same width either way. A PR Macro has not synced
+stays an ordinary link, and pasting inside a code block or over a selection
+keeps the default behavior.
1. `Create` → `Document D`. The app navigates to `/app/md/<uuid>` with the **title field
focused**.