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.

feat: pr preview block - dev only v1 (#4218)

Seamus86248d3ad62c
diff --git a/js/app/packages/app/component/command/CommandMenu.tsx b/js/app/packages/app/component/command/CommandMenu.tsx
index 7fa56355da..2e23dfcfaa 100644
--- a/js/app/packages/app/component/command/CommandMenu.tsx
+++ b/js/app/packages/app/component/command/CommandMenu.tsx
@@ -6,6 +6,7 @@ import { isListViewID } from '@app/constants/list-views';
import { globalSplitManager } from '@app/signal/splitLayout';
import { TabsInset } from '@core/component/TabsInset';
import { itemToBlockName } from '@core/constant/allBlocks';
+import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
import { getActiveCommandsFromScope } from '@core/hotkey/getCommands';
import {
hotkeyScopeTree,
@@ -242,9 +243,15 @@ export function CommandMenuInner(props: {
// Handle entity items (documents, channels, chats, etc.)
if (isEntityItem(item)) {
- // TODO(dev-rb/github): Route GitHub PRs to /pr.
if (isGithubPrEntity(item.data)) {
- openExternalUrl(item.data.metadata.url);
+ if (USE_MACRO_PR_SUMMARY_BLOCK) {
+ openWithSplit(
+ { type: 'pr', id: item.data.id },
+ { referredFrom: 'kommand-menu', preferNewSplit: openInNewSplit }
+ );
+ } else {
+ openExternalUrl(item.data.metadata.url);
+ }
CommandState.close();
CommandState.setQuery('');
return;
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index 82d63d3f43..a5338bc25e 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -11,6 +11,7 @@ import { URL_PARAMS as EMAIL_PARAMS } from '@block-email/constants';
import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
import {
ENTITY_ID_DATA_ATTRIBUTE,
entityIdSelector,
@@ -340,9 +341,21 @@ export const openEntityInSplitFromUnifiedList = async (
return;
}
- // TODO(dev-rb/github): Route GitHub PRs to /pr.
if (isGithubPrEntity(entity)) {
- openExternalUrl(entity.metadata.url);
+ if (USE_MACRO_PR_SUMMARY_BLOCK) {
+ splitManager.openWithSplit(
+ { type: 'pr', id: entity.id },
+ {
+ referredFrom: options.referredFrom,
+ activate: true,
+ preferNewSplit: openInNewSplit,
+ handle: splitHandle,
+ mergeHistory,
+ }
+ );
+ } else {
+ openExternalUrl(entity.metadata.url);
+ }
return;
}
if (entity.type === 'foreign') return;
diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
index 0270d907a2..ac10bb404a 100644
--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx
@@ -1,6 +1,7 @@
import { useGlobalNotificationSource } from '@app/component/GlobalAppState';
import { SidePanel } from '@app/component/side-panel';
import { EntityPropertiesSection } from '@app/component/side-panel/properties';
+import { useSplitLayout } from '@app/component/split-layout/layout';
import { useBlockAliasedName, useBlockId, useBlockName } from '@core/block';
import { EntityIcon } from '@core/component/EntityIcon';
import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
@@ -13,13 +14,16 @@ import {
import { Notifications } from '@core/component/Notifications';
import { References } from '@core/component/References';
import { UserIcon } from '@core/component/UserIcon';
+import { USE_MACRO_PR_SUMMARY_BLOCK } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import type { Entity, EntityType } from '@core/types';
import { tryMacroId, useDisplayName } from '@core/user';
import { type DateValue, formatDate } from '@core/util/date';
+import { openExternalUrl } from '@core/util/url';
import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
import GithubIcon from '@icon/mcp-github.svg';
import { useNotificationsForEntity } from '@notifications';
+import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';
import ClockIcon from '@phosphor/clock.svg';
import {
getDefaultPinnedProperties,
@@ -481,6 +485,7 @@ function GithubSectionConditional(props: {
props.documentId,
props.isTask
);
+ const { openWithSplit } = useSplitLayout();
const pullRequests = createMemo((): GithubPullRequest[] => {
if (!props.isTask || query.isLoading || query.isError) return [];
@@ -504,16 +509,32 @@ function GithubSectionConditional(props: {
<Show when={i() > 0}>
<span class="text-ink-extra-muted">,</span>
</Show>
- <a
- href={pr.url}
- target="_blank"
- rel="noopener noreferrer"
- class="inline-flex min-w-0 items-center gap-1 text-ink hover:text-ink"
+ <button
+ type="button"
+ disabled={!pr.url}
+ class={cn(
+ 'inline-flex min-w-0 items-center gap-1 text-ink hover:text-ink',
+ !pr.url &&
+ 'cursor-not-allowed text-ink-placeholder hover:text-ink-placeholder'
+ )}
title={
pr.name?.trim()
? `${pr.name.trim()} ${pr.displayName}`
: pr.displayName
}
+ onClick={() => {
+ if (USE_MACRO_PR_SUMMARY_BLOCK && pr.foreignEntityId) {
+ openWithSplit(
+ {
+ type: 'pr',
+ id: pr.foreignEntityId,
+ },
+ { referredFrom: null }
+ );
+ return;
+ }
+ if (pr.url) openExternalUrl(pr.url);
+ }}
>
<GithubIcon
class="size-3 shrink-0 text-ink-extra-muted"
@@ -522,6 +543,15 @@ function GithubSectionConditional(props: {
<span class="truncate underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2 hover:decoration-current">
{pr.displayName}
</span>
+ </button>
+ <a
+ href={pr.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ aria-label={`Open ${pr.displayName} on GitHub`}
+ class="shrink-0 text-ink-extra-muted hover:text-ink"
+ >
+ <ArrowSquareOutIcon class="size-3" aria-hidden="true" />
</a>
</>
)}
diff --git a/js/app/packages/block-pr/component/Block.tsx b/js/app/packages/block-pr/component/Block.tsx
new file mode 100644
index 0000000000..aa0f8d346d
--- /dev/null
+++ b/js/app/packages/block-pr/component/Block.tsx
@@ -0,0 +1,201 @@
+import { SidePanel } from '@app/component/side-panel';
+import { useBlockId } from '@core/block';
+import {
+ StaticMarkdown,
+ StaticMarkdownContext,
+} from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
+import { cn, Layer, Scroll } from '@ui';
+import { type Accessor, createMemo, Show } from 'solid-js';
+
+import { createPrDiscussionSource } from '../data/prDiscussionSource';
+import { usePrForeignEntityQuery } from '../data/queries';
+import {
+ cleanGithubMarkdown,
+ githubAvatarUrl,
+ githubDisplayLogin,
+} from '../util/githubMarkdown';
+import type { PrRef } from '../util/prKey';
+import { prDisplayName } from '../util/prKey';
+import {
+ PrDescriptionSkeleton,
+ PrMetadataSkeleton,
+ PrTimelineSkeleton,
+ PrTitleSkeleton,
+} from './PrSkeletons';
+import { PR_PILL_CLASS, PrSplitHeader, PrStatusChip } from './PrSplitHeader';
+import { PrTimeline } from './PrTimeline';
+import { PrSidePanelSections } from './sidepanel/PrSidePanelSections';
+
+export default function PrBlock() {
+ const blockId = useBlockId();
+
+ return (
+ <Show when={blockId}>
+ {(id) => <PrBlockContent foreignEntityId={id()} />}
+ </Show>
+ );
+}
+
+function PrBlockContent(props: { foreignEntityId: string }) {
+ const foreignEntityQuery = usePrForeignEntityQuery(
+ () => props.foreignEntityId
+ );
+
+ const prRef = createMemo(() => foreignEntityQuery.data?.prRef);
+ const pullRequest = createMemo(() => foreignEntityQuery.data?.pullRequest);
+
+ const loadFailed = createMemo(
+ () => !pullRequest() && !!foreignEntityQuery.error
+ );
+
+ // Block-lifetime local Macro discussion (prototype-only, lost on reload).
+ const discussionSource = createPrDiscussionSource();
+
+ return (
+ <div class="size-full overflow-hidden flex flex-col relative">
+ <SidePanel.Layout>
+ <PrSidePanelSections enrichment={pullRequest} />
+ <div class="flex flex-col size-full min-w-0">
+ <Show when={prRef()}>
+ {(ref) => (
+ <PrSplitHeader prRef={ref()} enrichment={pullRequest()} />
+ )}
+ </Show>
+
+ <Scroll class="flex-1 min-h-0">
+ <div class="max-w-3xl mx-auto px-6 pt-12 pb-12 min-w-0">
+ <Show
+ when={prRef()}
+ fallback={
+ <>
+ <PrTitleSkeleton />
+ <div class="spacer h-3" />
+ <PrMetadataSkeleton />
+ <PrDescriptionSkeleton />
+ <PrTimelineSkeleton />
+ </>
+ }
+ >
+ {(ref) => (
+ <>
+ <PrTitle prRef={ref()} pullRequest={pullRequest} />
+ <div class="spacer h-3" />
+ <PrMetadata prRef={ref()} pullRequest={pullRequest} />
+ <PrDescription pullRequest={pullRequest} />
+ <PrLoadErrorBanner loadFailed={loadFailed} />
+ <PrTimeline
+ githubItems={pullRequest()?.comments ?? []}
+ source={discussionSource}
+ />
+ </>
+ )}
+ </Show>
+ </div>
+ </Scroll>
+ </div>
+ </SidePanel.Layout>
+ </div>
+ );
+}
+
+function PrTitle(props: {
+ prRef: PrRef;
+ pullRequest: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ return (
+ <h1 class="ph-no-capture text-2xl font-semibold">
+ {props.pullRequest()?.name ?? prDisplayName(props.prRef)}
+ </h1>
+ );
+}
+
+function PrMetadata(props: {
+ prRef: PrRef;
+ pullRequest: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ const pullRequest = () => props.pullRequest();
+
+ return (
+ <div class="mb-6 flex flex-row flex-wrap items-center gap-2 text-sm empty:hidden">
+ <Show when={pullRequest()?.status}>
+ {(status) => <PrStatusChip status={status()} />}
+ </Show>
+ <Show when={pullRequest()?.authorLogin}>
+ {(authorLogin) => (
+ <Layer depth={2}>
+ <a
+ href={`https://github.com/${githubDisplayLogin(authorLogin())}`}
+ target="_blank"
+ rel="noreferrer"
+ class={cn(PR_PILL_CLASS, 'text-ink-muted hover:bg-hover')}
+ >
+ <img
+ src={githubAvatarUrl(authorLogin())}
+ alt=""
+ class="size-3.5 rounded-full shrink-0"
+ loading="lazy"
+ />
+ <span class="truncate">{githubDisplayLogin(authorLogin())}</span>
+ </a>
+ </Layer>
+ )}
+ </Show>
+ <Layer depth={2}>
+ <a
+ href={pullRequest()?.url}
+ target="_blank"
+ rel="noreferrer"
+ class={cn(PR_PILL_CLASS, 'text-ink-muted hover:bg-hover')}
+ >
+ {prDisplayName(props.prRef)}
+ </a>
+ </Layer>
+ <Show
+ when={
+ pullRequest()?.additions != null || pullRequest()?.deletions != null
+ }
+ >
+ <Layer depth={2}>
+ <span class={PR_PILL_CLASS}>
+ <span class="text-success">+{pullRequest()?.additions ?? 0}</span>
+ <span class="text-failure">−{pullRequest()?.deletions ?? 0}</span>
+ </span>
+ </Layer>
+ </Show>
+ </div>
+ );
+}
+
+function PrDescription(props: {
+ pullRequest: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ const description = createMemo(() => {
+ const raw = props.pullRequest()?.description;
+ if (!raw) return null;
+ const cleaned = cleanGithubMarkdown(raw);
+ return cleaned || null;
+ });
+
+ return (
+ <Show when={description()}>
+ {(markdown) => (
+ <StaticMarkdownContext>
+ <div class="ph-no-capture text-sm wrap-break-word max-w-full overflow-x-auto">
+ <StaticMarkdown markdown={markdown()} target="internal" />
+ </div>
+ </StaticMarkdownContext>
+ )}
+ </Show>
+ );
+}
+
+function PrLoadErrorBanner(props: { loadFailed: Accessor<boolean> }) {
+ return (
+ <Show when={props.loadFailed()}>
+ <div class="mt-6 px-3 py-2 rounded-lg border border-edge-muted text-xs text-ink-muted">
+ Couldn't load this pull request from cached GitHub data.
+ </div>
+ </Show>
+ );
+}
diff --git a/js/app/packages/block-pr/component/GithubMessageView.tsx b/js/app/packages/block-pr/component/GithubMessageView.tsx
new file mode 100644
index 0000000000..7c11321588
--- /dev/null
+++ b/js/app/packages/block-pr/component/GithubMessageView.tsx
@@ -0,0 +1,188 @@
+import { Message } from '@channel/Message/Message';
+import type { MessageData } from '@channel/Message/types';
+import { Thread } from '@channel/Thread/Thread';
+import MacroLogo from '@icon/macro-logo.svg';
+import type { GithubPullRequestComment } from '@service-storage/generated/schemas';
+import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';
+import { createResizeObserver } from '@solid-primitives/resize-observer';
+import { Button, cn } from '@ui';
+import { createSignal, onMount, Show } from 'solid-js';
+
+import { githubAvatarUrl, githubDisplayLogin } from '../util/githubMarkdown';
+
+/** Collapsed preview height for long comments (px). */
+const PREVIEW_MAX_HEIGHT = 180;
+
+function GithubAvatarFallback() {
+ return (
+ <div class="size-full rounded-full bg-surface flex items-center justify-center">
+ <MacroLogo class="size-6 text-edge" />
+ </div>
+ );
+}
+
+function GithubAvatar(props: { login: string }) {
+ const [failed, setFailed] = createSignal(false);
+
+ return (
+ <div class="shrink-0 size-(--user-icon-width)">
+ <Show when={!failed()} fallback={<GithubAvatarFallback />}>
+ <img
+ src={githubAvatarUrl(props.login)}
+ alt={githubDisplayLogin(props.login)}
+ class="size-full rounded-full bg-surface object-cover"
+ loading="lazy"
+ onError={() => setFailed(true)}
+ />
+ </Show>
+ </div>
+ );
+}
+
+function sourceLabel(source: string): string | null {
+ switch (source) {
+ case 'review':
+ return 'review';
+ case 'review_comment':
+ return 'on diff';
+ default:
+ return null;
+ }
+}
+
+/**
+ * Fudge a GitHub comment into the channel message shape: GitHub authors ride
+ * the bot-sender path, which carries an explicit display name through
+ * `Message.SenderName`.
+ */
+function toMessageData(comment: GithubPullRequestComment): MessageData {
+ const login = comment.authorLogin ?? 'github';
+ return {
+ id: `github-${comment.id}`,
+ content: comment.body,
+ sender_id: `bot|github:${login}`,
+ sender: {
+ type: 'bot',
+ id: `github:${login}`,
+ name: githubDisplayLogin(login),
+ avatar_url: githubAvatarUrl(login),
+ },
+ created_at: comment.createdAt ?? '',
+ updated_at: comment.updatedAt ?? comment.createdAt ?? '',
+ deleted_at: null,
+ edited_at: null,
+ attachments: [],
+ reactions: [],
+ };
+}
+
+function toThreadRowMessage(
+ comment: GithubPullRequestComment
+): ApiChannelMessage {
+ const message = toMessageData(comment);
+ const login = comment.authorLogin ?? 'github';
+ return {
+ ...message,
+ channel_id: '',
+ sender: {
+ type: 'bot',
+ id: `github:${login}`,
+ name: githubDisplayLogin(login),
+ avatar_url: githubAvatarUrl(login),
+ },
+ thread: {
+ reply_count: 0,
+ latest_reply_at: null,
+ preview: [],
+ },
+ };
+}
+
+/**
+ * A read-only GitHub comment rendered with the channel message components,
+ * collapsed to a preview when long (bot comments tend to be walls of text).
+ */
+export function GithubMessageView(props: {
+ comment: GithubPullRequestComment;
+}) {
+ const messageData = () => toMessageData(props.comment);
+ const threadRowMessage = () => toThreadRowMessage(props.comment);
+ const login = () => props.comment.authorLogin ?? 'github';
+
+ const [expanded, setExpanded] = createSignal(false);
+ const [overflowing, setOverflowing] = createSignal(false);
+ const truncated = () => !expanded() && overflowing();
+ let contentRef: HTMLDivElement | undefined;
+
+ onMount(() => {
+ // The markdown renders asynchronously — track its real height.
+ createResizeObserver(
+ () => contentRef,
+ () => {
+ if (!contentRef) return;
+ setOverflowing(contentRef.scrollHeight > PREVIEW_MAX_HEIGHT + 60);
+ }
+ );
+ });
+
+ return (
+ <Thread.Row message={threadRowMessage()}>
+ <Message.Root message={messageData()}>
+ <Message.Layout class="pt-(--regular-message-padding-t)">
+ <Message.Slot placement="icon">
+ <GithubAvatar login={login()} />
+ </Message.Slot>
+ <Message.Slot
+ placement="header"
+ class="flex items-center gap-1 min-w-0 w-full"
+ >
+ <Message.SenderName />
+ <Show when={sourceLabel(props.comment.source)}>
+ {(label) => (
+ <span class="inline-flex shrink-0 items-center rounded-sm bg-hover px-2 py-0.5 text-xs font-medium leading-none text-ink-muted">
+ {label()}
+ </span>
+ )}
+ </Show>
+ <div class="grow shrink-0 min-w-0 flex items-center gap-1.5 justify-end">
+ <Message.Timestamp
+ class="ml-auto shrink-0"
+ format="dateAndTime"
+ />
+ </div>
+ </Message.Slot>
+ <Message.Slot placement="content" class="ph-no-capture">
+ <div
+ ref={contentRef}
+ class={cn('relative', truncated() && 'overflow-hidden')}
+ style={
+ truncated()
+ ? {
+ 'max-height': `${PREVIEW_MAX_HEIGHT}px`,
+ 'mask-image':
+ 'linear-gradient(to bottom, black calc(100% - 32px), transparent 100%)',
+ '-webkit-mask-image':
+ 'linear-gradient(to bottom, black calc(100% - 32px), transparent 100%)',
+ }
+ : undefined
+ }
+ >
+ <Message.Content class="overflow-x-auto" />
+ </div>
+ <Show when={overflowing()}>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ class="mt-2"
+ onClick={() => setExpanded(!expanded())}
+ >
+ {expanded() ? 'Show less' : 'Show more'}
+ </Button>
+ </Show>
+ </Message.Slot>
+ </Message.Layout>
+ </Message.Root>
+ </Thread.Row>
+ );
+}
diff --git a/js/app/packages/block-pr/component/PrSkeletons.tsx b/js/app/packages/block-pr/component/PrSkeletons.tsx
new file mode 100644
index 0000000000..e2b88228f9
--- /dev/null
+++ b/js/app/packages/block-pr/component/PrSkeletons.tsx
@@ -0,0 +1,84 @@
+import { cn } from '@ui';
+import { For } from 'solid-js';
+
+import type { PrRef } from '../util/prKey';
+import { prDisplayName } from '../util/prKey';
+
+export function SkeletonBar(props: { class?: string }) {
+ return (
+ <div
+ class={cn('skeleton-shimmer rounded-full bg-edge-muted/50', props.class)}
+ />
+ );
+}
+
+function MessageSkeleton() {
+ return (
+ <div class="flex gap-2 py-3">
+ <div class="animate-pulse size-6 rounded-full bg-edge-muted/50 shrink-0" />
+ <div class="flex flex-col gap-2 grow min-w-0 pt-1">
+ <SkeletonBar class="h-2.5 w-32" />
+ <SkeletonBar class="h-2 w-full max-w-md" />
+ <SkeletonBar class="h-2 w-3/4 max-w-sm" />
+ </div>
+ </div>
+ );
+}
+
+export function PrTitleSkeleton() {
+ return <SkeletonBar class="h-8 w-full max-w-xl" />;
+}
+
+export function PrMetadataSkeleton() {
+ return (
+ <div class="mb-6 flex flex-row flex-wrap items-center gap-2">
+ <SkeletonBar class="h-6 w-20" />
+ <SkeletonBar class="h-6 w-28" />
+ <SkeletonBar class="h-6 w-36" />
+ <SkeletonBar class="h-6 w-24" />
+ </div>
+ );
+}
+
+export function PrDescriptionSkeleton() {
+ return (
+ <div class="flex flex-col gap-2">
+ <SkeletonBar class="h-2 w-full max-w-lg" />
+ <SkeletonBar class="h-2 w-full max-w-md" />
+ <SkeletonBar class="h-2 w-2/3 max-w-sm" />
+ </div>
+ );
+}
+
+export function PrTimelineSkeleton() {
+ return (
+ <section class="mt-8">
+ <div class="flex items-center gap-2 pt-2">
+ <div class="w-6 border-t border-edge-muted" />
+ <span class="px-2 text-xs">Discussion</span>
+ <div class="flex-1 border-t border-edge-muted" />
+ </div>
+ <div class="py-2">
+ <For each={[0, 1, 2]}>{() => <MessageSkeleton />}</For>
+ </div>
+ </section>
+ );
+}
+
+/**
+ * Loading shell for the PR content column: the real title (derived from the
+ * URL, no fetch needed) over pulsing pill and comment placeholders.
+ */
+export function PrContentSkeleton(props: { prRef: PrRef }) {
+ return (
+ <>
+ <h1 class="ph-no-capture text-2xl font-semibold">
+ {prDisplayName(props.prRef)}
+ </h1>
+ <div class="spacer h-3" />
+ <PrMetadataSkeleton />
+ <PrDescriptionSkeleton />
+ <PrTimelineSkeleton />
+ </>
+ );
+}
diff --git a/js/app/packages/block-pr/component/PrSplitHeader.tsx b/js/app/packages/block-pr/component/PrSplitHeader.tsx
new file mode 100644
index 0000000000..adb0e60efc
--- /dev/null
+++ b/js/app/packages/block-pr/component/PrSplitHeader.tsx
@@ -0,0 +1,177 @@
+import {
+ type BlockTool,
+ ResponsiveBlockToolbar,
+} from '@app/component/ResponsiveBlockToolbar';
+import { SidePanel, useSidePanel } from '@app/component/side-panel';
+import type { FileOperation } from '@app/component/split-layout/components/SplitFileMenu';
+import { SplitHeaderLeft } from '@app/component/split-layout/components/SplitHeader';
+import { StaticSplitLabel } from '@app/component/split-layout/components/SplitLabel';
+import { SplitToolbarLeft } from '@app/component/split-layout/components/SplitToolbar';
+import { useBlockId } from '@core/block';
+import { toast } from '@core/component/Toast/Toast';
+import { TOKENS } from '@core/hotkey/tokens';
+import { buildSimpleEntityUrl, openExternalUrl } from '@core/util/url';
+import GithubIcon from '@icon/mcp-github.svg';
+import GitMerge from '@phosphor/git-merge.svg';
+import GitPullRequest from '@phosphor/git-pull-request.svg';
+import LinkIcon from '@phosphor/link.svg';
+import SidePanelIcon from '@phosphor/square-half.svg';
+import type { GithubPullRequest } from '@service-storage/generated/schemas';
+import { Button, cn, Layer } from '@ui';
+import { Show } from 'solid-js';
+
+import type { PrRef } from '../util/prKey';
+import { prDisplayName, prHtmlUrl } from '../util/prKey';
+
+// Status icon colors follow the soup PR rows (entity-icon.tsx):
+// open → green pull-request icon, merged → purple merge icon, closed → red.
+const STATUS_ICON_CLASS: Record<string, string> = {
+ open: 'text-success',
+ merged: 'text-note',
+ closed: 'text-failure',
+};
+
+const STATUS_TEXT_CLASS: Record<string, string> = {
+ open: 'text-success',
+ merged: 'text-note',
+ closed: 'text-failure',
+};
+
+function capitalize(value: string): string {
+ return value.charAt(0).toUpperCase() + value.slice(1);
+}
+
+/** Pill surface matching the task block's inline property pills. */
+export const PR_PILL_CLASS =
+ 'inline-flex items-center gap-1.5 min-w-0 ring ring-edge-muted px-2 py-1 leading-tight text-left rounded-full bg-surface';
+
+export function PrStatusIcon(props: { status: string; class?: string }) {
+ return (
+ <Show
+ when={props.status === 'merged'}
+ fallback={
+ <GitPullRequest
+ class={cn('size-3.5', STATUS_ICON_CLASS[props.status], props.class)}
+ />
+ }
+ >
+ <GitMerge class={cn('size-3.5 text-note', props.class)} />
+ </Show>
+ );
+}
+
+/** Status pill matching the task block's inline property pills. */
+export function PrStatusChip(props: { status: string; class?: string }) {
+ return (
+ <Layer depth={2}>
+ <span
+ class={cn(
+ PR_PILL_CLASS,
+ 'shrink-0',
+ STATUS_TEXT_CLASS[props.status],
+ props.class
+ )}
+ >
+ <PrStatusIcon status={props.status} class="size-3 shrink-0" />
+ {capitalize(props.status)}
+ </span>
+ </Layer>
+ );
+}
+
+/**
+ * PR identity in the split header chrome plus the standard split toolbar:
+ * file menu (open on GitHub), side panel toggle, and narrow content/info
+ * tabs — matching the other block types.
+ */
+export function PrSplitHeader(props: {
+ prRef: PrRef;
+ enrichment: GithubPullRequest | undefined;
+}) {
+ const blockId = useBlockId();
+ const sidePanel = useSidePanel();
+ const title = () => props.enrichment?.name ?? prDisplayName(props.prRef);
+ const githubUrl = () => props.enrichment?.url ?? prHtmlUrl(props.prRef);
+
+ const copyLink = async () => {
+ await navigator.clipboard.writeText(
+ buildSimpleEntityUrl({ type: 'pr', id: blockId })
+ );
+ toast.success('Link copied to clipboard');
+ };
+
+ const ops: FileOperation[] = [
+ {
+ label: 'Open on GitHub',
+ icon: GithubIcon,
+ action: () => openExternalUrl(githubUrl()),
+ },
+ ];
+
+ const tools: BlockTool[] = [
+ {
+ label: 'Copy link',
+ icon: LinkIcon,
+ action: copyLink,
+ },
+ {
+ label: () =>
+ sidePanel?.isOpen() ? 'Hide Side Panel' : 'Show Side Panel',
+ icon: SidePanelIcon,
+ action: () => sidePanel?.toggle(),
+ isActive: () => sidePanel?.isOpen() ?? false,
+ condition: () => !(sidePanel?.isNarrow() ?? false),
+ buttonComponent: () => (
+ <Show when={sidePanel}>
+ {(panel) => (
+ <Button
+ depth={2}
+ variant="base"
+ size="icon-sm"
+ class={cn('bg-surface order-20', {
+ 'bg-active': sidePanel?.isOpen(),
+ })}
+ tooltip={
+ sidePanel?.isOpen() ? 'Hide Side Panel' : 'Show Side Panel'
+ }
+ hotkey={TOKENS.block.toggleSidePanel}
+ onClick={() => {
+ panel().toggle();
+ }}
+ >
+ <SidePanelIcon />
+ </Button>
+ )}
+ </Show>
+ ),
+ },
+ ];
+
+ return (
+ <>
+ <SplitHeaderLeft>
+ <StaticSplitLabel
+ label={title()}
+ icon={
+ <PrStatusIcon
+ status={props.enrichment?.status ?? 'open'}
+ class="size-3.5"
+ />
+ }
+ />
+ </SplitHeaderLeft>
+
+ <ResponsiveBlockToolbar
+ tools={tools}
+ ops={ops}
+ id={blockId}
+ itemType="foreign"
+ name={title()}
+ />
+
+ <SplitToolbarLeft>
+ <SidePanel.NarrowTabs />
+ </SplitToolbarLeft>
+ </>
+ );
+}
diff --git a/js/app/packages/block-pr/component/PrTimeline.tsx b/js/app/packages/block-pr/component/PrTimeline.tsx
new file mode 100644
index 0000000000..9db377ff59
--- /dev/null
+++ b/js/app/packages/block-pr/component/PrTimeline.tsx
@@ -0,0 +1,126 @@
+import type { InputSnapshot } from '@channel/Input/types';
+import type { DiscussionSource } from '@core/comments/discussion';
+import {
+ DiscussionInput,
+ DiscussionProvider,
+ DiscussionThreadView,
+} from '@core/comments/discussion';
+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { ENABLE_PR_DISCUSSION_INPUT } from '@core/constant/featureFlags';
+import CaretDown from '@phosphor/caret-down.svg';
+import CaretRight from '@phosphor/caret-right.svg';
+import type { GithubPullRequestComment } from '@service-storage/generated/schemas';
+import { ToggleSwitch } from '@ui';
+import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
+
+import { buildTimeline } from '../data/timeline';
+import { isGithubBotLogin } from '../util/githubMarkdown';
+import { GithubMessageView } from './GithubMessageView';
+
+/**
+ * Unified PR discussion section, styled like the task block's: a collapsible
+ * "Discussion" divider over read-only GitHub comments interleaved by
+ * timestamp with editable Macro discussion threads, plus a composer.
+ */
+export function PrTimeline(props: {
+ githubItems: GithubPullRequestComment[];
+ source: DiscussionSource;
+}) {
+ const [isExpanded, setIsExpanded] = createSignal(true);
+ const [hideBots, setHideBots] = createSignal(false);
+
+ const visibleGithubItems = createMemo(() =>
+ hideBots()
+ ? props.githubItems.filter((item) => !isGithubBotLogin(item.authorLogin))
+ : props.githubItems
+ );
+ const botCount = createMemo(
+ () =>
+ props.githubItems.filter((item) => isGithubBotLogin(item.authorLogin))
+ .length
+ );
+
+ const entries = createMemo(() =>
+ buildTimeline(visibleGithubItems(), props.source.threads())
+ );
+
+ let composerHandle: { clear: () => void } | undefined;
+
+ const handleCreateThread = async (snapshot: InputSnapshot) => {
+ const text = snapshot.value.trim();
+ if (!text) return;
+ await props.source.createThread(text, snapshot.mentions);
+ composerHandle?.clear();
+ };
+
+ return (
+ <section class="mt-8 pb-12">
+ <div class="flex items-center gap-2 pt-2">
+ <div class="w-6 border-t border-edge-muted" />
+ <button
+ type="button"
+ class="flex items-center gap-1 px-2 hover:opacity-70 transition-opacity"
+ onClick={() => setIsExpanded(!isExpanded())}
+ >
+ {isExpanded() ? (
+ <CaretDown class="size-3" />
+ ) : (
+ <CaretRight class="size-3" />
+ )}
+ <span class="text-xs">Discussion</span>
+ </button>
+ <div class="flex-1 border-t border-edge-muted" />
+ <Show when={botCount() > 0}>
+ <ToggleSwitch
+ class="shrink-0"
+ checked={hideBots()}
+ onChange={setHideBots}
+ label={`Hide bots (${botCount()})`}
+ labelClass="text-xs text-ink-muted"
+ />
+ </Show>
+ </div>
+
+ <Show when={isExpanded()}>
+ <DiscussionProvider source={props.source}>
+ <StaticMarkdownContext>
+ <div class="py-2 flex flex-col text-xs">
+ <For each={entries()}>
+ {(entry) => (
+ <Switch>
+ <Match when={entry.kind === 'github-comment' && entry}>
+ {(commentEntry) => (
+ <GithubMessageView comment={commentEntry().item} />
+ )}
+ </Match>
+ <Match when={entry.kind === 'macro-thread' && entry}>
+ {(threadEntry) => (
+ <DiscussionThreadView thread={threadEntry().thread} />
+ )}
+ </Match>
+ </Switch>
+ )}
+ </For>
+
+ <Show when={ENABLE_PR_DISCUSSION_INPUT && props.source.canEdit()}>
+ <div class="pt-2">
+ <DiscussionInput
+ input={{
+ mode: 'channel',
+ placeholder: 'Leave a comment...',
+ }}
+ onSend={handleCreateThread}
+ onReady={(handle) => {
+ composerHandle = handle;
+ }}
+ autofocus={false}
+ />
+ </div>
+ </Show>
+ </div>
+ </StaticMarkdownContext>
+ </DiscussionProvider>
+ </Show>
+ </section>
+ );
+}
diff --git a/js/app/packages/block-pr/component/sidepanel/PrSidePanelSections.tsx b/js/app/packages/block-pr/component/sidepanel/PrSidePanelSections.tsx
new file mode 100644
index 0000000000..db8bf270c0
--- /dev/null
+++ b/js/app/packages/block-pr/component/sidepanel/PrSidePanelSections.tsx
@@ -0,0 +1,180 @@
+import { SidePanel } from '@app/component/side-panel';
+import ArrowSquareOut from '@phosphor/arrow-square-out.svg';
+import CheckCircle from '@phosphor/check-circle.svg';
+import Circle from '@phosphor/circle.svg';
+import CircleNotch from '@phosphor/circle-notch.svg';
+import MinusCircle from '@phosphor/minus-circle.svg';
+import XCircle from '@phosphor/x-circle.svg';
+import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
+import type { GithubPullRequestCheckRun } from '@service-storage/generated/schemas';
+import { type Accessor, For, Match, Show, Switch } from 'solid-js';
+
+import { githubAvatarUrl } from '../../util/githubMarkdown';
+import { PrStatusChip } from '../PrSplitHeader';
+
+function checksPassedCount(checks: GithubPullRequestCheckRun[]): number {
+ return checks.filter((check) => check.conclusion === 'success').length;
+}
+
+function checkDuration(check: GithubPullRequestCheckRun): string | null {
+ if (!check.startedAt || !check.completedAt) return null;
+ const ms = Date.parse(check.completedAt) - Date.parse(check.startedAt);
+ if (Number.isNaN(ms) || ms < 0) return null;
+ const seconds = Math.round(ms / 1000);
+ if (seconds < 60) return `${seconds}s`;
+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
+}
+
+function CheckStatusIcon(props: { check: GithubPullRequestCheckRun }) {
+ return (
+ <Switch fallback={<Circle class="size-3.5 text-ink-placeholder" />}>
+ <Match when={props.check.status !== 'completed'}>
+ <CircleNotch class="size-3.5 text-ink-placeholder animate-spin" />
+ </Match>
+ <Match when={props.check.conclusion === 'success'}>
+ <CheckCircle class="size-3.5 text-success" />
+ </Match>
+ <Match
+ when={
+ props.check.conclusion === 'failure' ||
+ props.check.conclusion === 'timed_out'
+ }
+ >
+ <XCircle class="size-3.5 text-failure" />
+ </Match>
+ <Match
+ when={
+ props.check.conclusion === 'skipped' ||
+ props.check.conclusion === 'cancelled' ||
+ props.check.conclusion === 'neutral'
+ }
+ >
+ <MinusCircle class="size-3.5 text-ink-placeholder" />
+ </Match>
+ </Switch>
+ );
+}
+
+function PrDetailsSectionContent(props: {
+ enrichment: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ return (
+ <Show when={props.enrichment()} fallback={<SidePanel.Loading />}>
+ {(enrichment) => (
+ <SidePanel.Grid>
+ <Show when={enrichment().authorLogin}>
+ {(authorLogin) => (
+ <SidePanel.Row label="Author">
+ <SidePanel.Pill>
+ <img
+ src={githubAvatarUrl(authorLogin())}
+ alt={authorLogin()}
+ class="size-3.5 rounded-full shrink-0"
+ loading="lazy"
+ />
+ <span class="truncate">{authorLogin()}</span>
+ </SidePanel.Pill>
+ </SidePanel.Row>
+ )}
+ </Show>
+ <SidePanel.Row label="Repository">
+ <span class="truncate">
+ {enrichment().owner}/{enrichment().repo}
+ </span>
+ </SidePanel.Row>
+ <Show when={enrichment().status}>
+ {(status) => (
+ <SidePanel.Row label="Status">
+ <PrStatusChip
+ status={status()}
+ class="text-xs px-1.5 py-0.5 gap-1"
+ />
+ </SidePanel.Row>
+ )}
+ </Show>
+ <Show
+ when={
+ enrichment().additions != null || enrichment().deletions != null
+ }
+ >
+ <SidePanel.Row label="Changes">
+ <span class="text-success">+{enrichment().additions ?? 0}</span>
+ <span class="text-ink-extra-muted">/</span>
+ <span class="text-failure">−{enrichment().deletions ?? 0}</span>
+ </SidePanel.Row>
+ </Show>
+ <SidePanel.Row label="GitHub">
+ <a
+ href={enrichment().url}
+ target="_blank"
+ rel="noreferrer"
+ class="min-w-0 truncate underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2 hover:decoration-current"
+ >
+ {enrichment().displayName}
+ </a>
+ </SidePanel.Row>
+ </SidePanel.Grid>
+ )}
+ </Show>
+ );
+}
+
+function PrChecksSectionContent(props: {
+ enrichment: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ const checks = () => props.enrichment()?.checks ?? [];
+ return (
+ <Show
+ when={checks().length > 0}
+ fallback={<div class="text-ink-placeholder">No checks</div>}
+ >
+ <div class="flex flex-col gap-1 text-xs">
+ <div class="text-xs text-ink-muted">
+ {checksPassedCount(checks())} passed
+ </div>
+ <For each={checks()}>
+ {(check) => (
+ <div class="flex items-center gap-2 min-w-0 h-6">
+ <CheckStatusIcon check={check} />
+ <span class="truncate">{check.name}</span>
+ <span class="ml-auto flex items-center gap-1.5 shrink-0 text-ink-placeholder">
+ <Show when={checkDuration(check)}>
+ {(duration) => <span>{duration()}</span>}
+ </Show>
+ <Show when={check.url}>
+ {(url) => (
+ <a
+ href={url()}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={`Open ${check.name} on GitHub`}
+ class="hover:opacity-70 transition-opacity"
+ >
+ <ArrowSquareOut class="size-3" />
+ </a>
+ )}
+ </Show>
+ </span>
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
+ );
+}
+
+export function PrSidePanelSections(props: {
+ enrichment: Accessor<GithubPullRequestWithDetails | undefined>;
+}) {
+ return (
+ <>
+ <SidePanel.Section id="pr-details" title="Details" defaultOpen order={10}>
+ <PrDetailsSectionContent enrichment={props.enrichment} />
+ </SidePanel.Section>
+
+ <SidePanel.Section id="pr-checks" title="Checks" order={20}>
+ <PrChecksSectionContent enrichment={props.enrichment} />
+ </SidePanel.Section>
+ </>
+ );
+}
diff --git a/js/app/packages/block-pr/constants.ts b/js/app/packages/block-pr/constants.ts
new file mode 100644
index 0000000000..bb598907cf
--- /dev/null
+++ b/js/app/packages/block-pr/constants.ts
@@ -0,0 +1,8 @@
+export const URL_PARAMS = {
+ /**
+ * Document id of the task this PR was opened from. When present, PR data
+ * loads from the task's stored GitHub data (team-visible, populated by the
+ * GitHub App installation) instead of requiring a personal GitHub link.
+ */
+ task: 'task',
+} as const;
diff --git a/js/app/packages/block-pr/data/prDiscussionSource.ts b/js/app/packages/block-pr/data/prDiscussionSource.ts
new file mode 100644
index 0000000000..87da72328c
--- /dev/null
+++ b/js/app/packages/block-pr/data/prDiscussionSource.ts
@@ -0,0 +1,93 @@
+import type {
+ DiscussionComment,
+ DiscussionSource,
+ DiscussionThread,
+} from '@core/comments/discussion';
+import { useUserId } from '@core/context/user';
+import { createSignal } from 'solid-js';
+
+// THROWAWAY (prototype): in-memory Macro discussion threads, lost on reload.
+// The production implementation follows the CRM-comments pattern
+// (rust/cloud-storage/crm/src/domain/comment.rs) with a `github_pr` entity
+// type keyed by github_key; only this file changes when it lands.
+export function createPrDiscussionSource(): DiscussionSource {
+ const userId = useUserId();
+ const [threads, setThreads] = createSignal<DiscussionThread[]>([]);
+
+ const makeComment = (threadId: string, text: string): DiscussionComment => {
+ const now = new Date().toISOString();
+ return {
+ id: crypto.randomUUID(),
+ threadId,
+ authorId: userId() ?? '',
+ text,
+ createdAt: now,
+ updatedAt: now,
+ deletedAt: null,
+ };
+ };
+
+ return {
+ threads,
+ canEdit: () => true,
+ currentUserId: userId,
+ targetCommentId: () => null,
+ async createThread(text, _mentions) {
+ const threadId = crypto.randomUUID();
+ const thread: DiscussionThread = {
+ id: threadId,
+ resolved: false,
+ comments: [makeComment(threadId, text)],
+ };
+ setThreads((prev) => [...prev, thread]);
+ },
+ async createReply(threadId, text, _mentions) {
+ setThreads((prev) =>
+ prev.map((thread) =>
+ thread.id === threadId
+ ? {
+ ...thread,
+ comments: [...thread.comments, makeComment(threadId, text)],
+ }
+ : thread
+ )
+ );
+ },
+ async editComment(comment, text) {
+ setThreads((prev) =>
+ prev.map((thread) =>
+ thread.id === comment.threadId
+ ? {
+ ...thread,
+ comments: thread.comments.map((existing) =>
+ existing.id === comment.id
+ ? {
+ ...existing,
+ text,
+ updatedAt: new Date().toISOString(),
+ }
+ : existing
+ ),
+ }
+ : thread
+ )
+ );
+ },
+ async deleteComment(comment) {
+ setThreads((prev) =>
+ prev
+ .map((thread) =>
+ thread.id === comment.threadId
+ ? {
+ ...thread,
+ comments: thread.comments.filter(
+ (existing) => existing.id !== comment.id
+ ),
+ }
+ : thread
+ )
+ .filter((thread) => thread.comments.length > 0)
+ );
+ },
+ };
+}
diff --git a/js/app/packages/block-pr/data/queries.ts b/js/app/packages/block-pr/data/queries.ts
new file mode 100644
index 0000000000..6495ff9085
--- /dev/null
+++ b/js/app/packages/block-pr/data/queries.ts
@@ -0,0 +1,120 @@
+import { throwOnErr } from '@core/util/result';
+import type { GithubPullRequestWithDetails } from '@queries/storage/github-pull-requests';
+import { storageServiceClient } from '@service-storage/client';
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+import type { PrRef } from '../util/prKey';
+import {
+ parseGithubKey,
+ prDisplayName,
+ prHtmlUrl,
+ toGithubKey,
+} from '../util/prKey';
+
+const PR_STALE_TIME = 60 * 1000;
+const GITHUB_PULL_REQUEST_SOURCE = 'github_pull_request';
+
+export type PrForeignEntityData = {
+ id: string;
+ prRef: PrRef;
+ pullRequest: GithubPullRequestWithDetails;
+};
+
+export function prForeignEntityQueryKey(id: string): string[] {
+ return ['github-pr', 'foreign-entity', id];
+}
+
+function metadataRecord(metadata: unknown): Record<string, unknown> {
+ if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {
+ return metadata as Record<string, unknown>;
+ }
+ return {};
+}
+
+function optionalString(value: unknown): string | null | undefined {
+ return typeof value === 'string' ? value : undefined;
+}
+
+function optionalNumber(value: unknown): number | null | undefined {
+ return typeof value === 'number' ? value : undefined;
+}
+
+function optionalArray<T>(value: unknown): T[] | null | undefined {
+ return Array.isArray(value) ? (value as T[]) : undefined;
+}
+
+function prForeignEntityDataFromParts(args: {
+ id: string;
+ foreignId: string;
+ metadata: unknown;
+}): PrForeignEntityData {
+ const metadata = metadataRecord(args.metadata);
+ const owner = optionalString(metadata.owner);
+ const repo = optionalString(metadata.repo);
+ const number = optionalNumber(metadata.number);
+ const refFromMetadata =
+ owner && repo && number != null ? { owner, repo, number } : null;
+ const prRef = refFromMetadata ?? parseGithubKey(args.foreignId);
+
+ if (!prRef) {
+ throw new Error(`Invalid GitHub pull request metadata for ${args.id}`);
+ }
+
+ const githubKey =
+ optionalString(metadata.githubKey) ?? args.foreignId ?? toGithubKey(prRef);
+
+ return {
+ id: args.id,
+ prRef,
+ pullRequest: {
+ additions: optionalNumber(metadata.additions),
+ authorLogin: optionalString(metadata.authorLogin),
+ description: optionalString(metadata.description),
+ checks: optionalArray(metadata.checks),
+ comments: optionalArray(metadata.comments),
+ deletions: optionalNumber(metadata.deletions),
+ displayName: optionalString(metadata.displayName) ?? prDisplayName(prRef),
+ foreignEntityId: args.id,
+ githubKey,
+ name: optionalString(metadata.name),
+ number: prRef.number,
+ owner: prRef.owner,
+ repo: prRef.repo,
+ status: optionalString(metadata.status),
+ url: optionalString(metadata.url) ?? prHtmlUrl(prRef),
+ },
+ };
+}
+
+function prForeignEntityDataFromForeignEntity(
+ entity: ForeignEntity
+): PrForeignEntityData {
+ if (entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
+ throw new Error(`Foreign entity ${entity.id} is not a GitHub pull request`);
+ }
+
+ return prForeignEntityDataFromParts({
+ id: entity.id,
+ foreignId: entity.foreignEntityId,
+ metadata: entity.metadata,
+ });
+}
+
+export function usePrForeignEntityQuery(id: Accessor<string>) {
+ return useQuery(() => {
+ const currentId = id();
+ return {
+ queryKey: prForeignEntityQueryKey(currentId),
+ queryFn: async (): Promise<PrForeignEntityData> => {
+ const entity = await throwOnErr(() =>
+ storageServiceClient.getForeignEntity({ id: currentId })
+ );
+ return prForeignEntityDataFromForeignEntity(entity);
+ },
+ staleTime: PR_STALE_TIME,
+ retry: 1,
+ };
+ });
+}
diff --git a/js/app/packages/block-pr/data/timeline.ts b/js/app/packages/block-pr/data/timeline.ts
new file mode 100644
index 0000000000..2d8202c8fd
--- /dev/null
+++ b/js/app/packages/block-pr/data/timeline.ts
@@ -0,0 +1,47 @@
+import type { DiscussionThread } from '@core/comments/discussion';
+import type { GithubPullRequestComment } from '@service-storage/generated/schemas';
+
+import { cleanGithubMarkdown } from '../util/githubMarkdown';
+
+export type TimelineEntry =
+ | { kind: 'github-comment'; ts: number; item: GithubPullRequestComment }
+ | { kind: 'macro-thread'; ts: number; thread: DiscussionThread };
+
+function timestamp(value: string | null | undefined): number {
+ if (!value) return 0;
+ const parsed = Date.parse(value);
+ return Number.isNaN(parsed) ? 0 : parsed;
+}
+
+/**
+ * Merge GitHub comments (issue comments, review comments, and reviews, as the
+ * enrich endpoint returns them) with Macro discussion threads into a single
+ * timestamp-ordered timeline. Empty bodies (e.g. approve-only reviews) are
+ * dropped.
+ */
+export function buildTimeline(
+ githubItems: GithubPullRequestComment[],
+ macroThreads: DiscussionThread[]
+): TimelineEntry[] {
+ const entries: TimelineEntry[] = [];
+
+ for (const item of githubItems) {
+ const body = cleanGithubMarkdown(item.body);
+ if (!body) continue;
+ entries.push({
+ kind: 'github-comment',
+ ts: timestamp(item.createdAt),
+ item: { ...item, body },
+ });
+ }
+
+ for (const thread of macroThreads) {
+ entries.push({
+ kind: 'macro-thread',
+ ts: timestamp(thread.comments[0]?.createdAt),
+ thread,
+ });
+ }
+
+ return entries.sort((a, b) => a.ts - b.ts);
+}
diff --git a/js/app/packages/block-pr/definition.ts b/js/app/packages/block-pr/definition.ts
new file mode 100644
index 0000000000..0e534d0b4e
--- /dev/null
+++ b/js/app/packages/block-pr/definition.ts
@@ -0,0 +1,21 @@
+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
+import { ok } from 'neverthrow';
+import { lazy } from 'solid-js';
+
+export const definition = defineBlock({
+ name: 'pr',
+ description: 'View a GitHub pull request',
+ // Lazy so the Pierre/shiki diff stack stays out of the main chunk.
+ component: lazy(() => import('./component/Block')),
+ liveTrackingEnabled: false,
+ async load(source, _intent) {
+ if (source.type === 'dss') {
+ if (!source.id) return LoadErrors.INVALID;
+ return ok({ id: source.id });
+ }
+ return LoadErrors.MISSING;
+ },
+ accepted: {},
+});
+
+export type PrData = ExtractLoadType<(typeof definition)['load']>;
diff --git a/js/app/packages/block-pr/package.json b/js/app/packages/block-pr/package.json
new file mode 100644
index 0000000000..ffcbf70fc6
--- /dev/null
+++ b/js/app/packages/block-pr/package.json
@@ -0,0 +1,6 @@
+{
+ "name": "block-pr",
+ "private": true,
+ "scripts": {},
+ "dependencies": {}
+}
diff --git a/js/app/packages/block-pr/tsconfig.json b/js/app/packages/block-pr/tsconfig.json
new file mode 100644
index 0000000000..d9677aefea
--- /dev/null
+++ b/js/app/packages/block-pr/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "jsx": "preserve",
+ "jsxImportSource": "solid-js",
+ "verbatimModuleSyntax": true,
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "composite": true
+ }
+}
diff --git a/js/app/packages/block-pr/util/githubMarkdown.test.ts b/js/app/packages/block-pr/util/githubMarkdown.test.ts
new file mode 100644
index 0000000000..c3531536fb
--- /dev/null
+++ b/js/app/packages/block-pr/util/githubMarkdown.test.ts
@@ -0,0 +1,15 @@
+import { describe, expect, it } from 'vitest';
+
+import { cleanGithubMarkdown } from './githubMarkdown';
+
+describe('cleanGithubMarkdown', () => {
+ it('renders CodeRabbit svg badges as regular links', () => {
+ expect(
+ cleanGithubMarkdown(
+ '![Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)'
+ )
+ ).toBe(
+ '[Review Change Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)'
+ );
+ });
+});
diff --git a/js/app/packages/block-pr/util/githubMarkdown.ts b/js/app/packages/block-pr/util/githubMarkdown.ts
new file mode 100644
index 0000000000..3c00196fb3
--- /dev/null
+++ b/js/app/packages/block-pr/util/githubMarkdown.ts
@@ -0,0 +1,41 @@
+export function isGithubBotLogin(login: string | null | undefined): boolean {
+ return !!login?.endsWith('[bot]');
+}
+
+export function githubDisplayLogin(login: string): string {
+ return login.replace(/\[bot\]$/, '');
+}
+
+export function githubAvatarUrl(login: string): string {
+ return `https://github.com/${githubDisplayLogin(login)}.png?size=48`;
+}
+
+/**
+ * GitHub comment bodies — especially from bots like CodeRabbit — are littered
+ * with HTML that our markdown renderer shows literally: marker comments
+ * (`<!-- ... -->`), collapsible `<details>/<summary>` wrappers, `<sub>` fine
+ * print. Strip the tags but keep the human-readable content.
+ */
+export function cleanGithubMarkdown(body: string): string {
+ return (
+ body
+ // Marker/annotation comments carry no content.
+ .replace(/<!--[\s\S]*?-->/g, '')
+ // Collapsible sections: promote the summary line, drop the wrappers.
+ .replace(/<summary>([\s\S]*?)<\/summary>/gi, '**$1**\n\n')
+ .replace(/<\/?details[^>]*>/gi, '')
+ // CodeRabbit's decorative SVG badges are inline image markdown. Our image
+ // transformer only handles image-only blocks, so render these as normal
+ // text links instead of a stray "!" plus a giant URL.
+ .replace(
+ /!\[([^\]]*)\]\((https?:\/\/storage\.googleapis\.com\/coderabbit_public_assets\/[^)\s]+)(?:\s"[^"]*")?\)/g,
+ '[$1]($2)'
+ )
+ // Inline formatting tags whose content should stay.
+ .replace(/<\/?(?:sub|sup|b|i|em|strong|kbd)>/gi, '')
+ .replace(/<br\s*\/?>/gi, '\n')
+ // Collapse the blank-line runs left behind by removals.
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+ );
+}
diff --git a/js/app/packages/block-pr/util/prKey.ts b/js/app/packages/block-pr/util/prKey.ts
new file mode 100644
index 0000000000..97b21dda45
--- /dev/null
+++ b/js/app/packages/block-pr/util/prKey.ts
@@ -0,0 +1,37 @@
+export type PrRef = {
+ owner: string;
+ repo: string;
+ number: number;
+};
+
+const GITHUB_PR_URL_PATTERN =
+ /github\.com\/([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)/;
+
+/** Extract a PR reference from a github.com pull request URL, if present. */
+export function parseGithubPrUrl(text: string): PrRef | null {
+ const match = text.match(GITHUB_PR_URL_PATTERN);
+ if (!match) return null;
+ return { owner: match[1], repo: match[2], number: Number(match[3]) };
+}
+
+/** Extract a PR reference from the backend `github_key` format. */
+export function parseGithubKey(key: string): PrRef | null {
+ const match = key.match(
+ /^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)$/
+ );
+ if (!match) return null;
+ return { owner: match[1], repo: match[2], number: Number(match[3]) };
+}
+
+/** The backend `github_key` format used by `github_pr_tasks` et al. */
+export function toGithubKey(ref: PrRef): string {
+ return `${ref.owner}/${ref.repo}/pull/${ref.number}`;
+}
+
+export function prDisplayName(ref: PrRef): string {
+ return `${ref.owner}/${ref.repo}#${ref.number}`;
+}
+
+export function prHtmlUrl(ref: PrRef): string {
+ return `https://github.com/${ref.owner}/${ref.repo}/pull/${ref.number}`;
+}
diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.ts
index 1397775e41..4323539c29 100644
--- a/js/app/packages/core/block.ts
+++ b/js/app/packages/core/block.ts
@@ -64,6 +64,7 @@ export const BlockRegistry = [
'contact',
'company',
'automation',
+ 'pr',
] as const;
type BlockNameKeys = keyof typeof BlockRegistry & number;
@@ -99,6 +100,7 @@ export const NonDocumentBlockTypes = [
'contact',
'company',
'automation',
+ 'pr',
] as const as (BlockName | BlockAlias)[];
/**
@@ -153,6 +155,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {
snippet: allBlockNames,
automation: allBlockNames,
csv: allBlockNames,
+ pr: allBlockNames,
} as const;
// maps block name to valid parents
@@ -176,6 +179,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {
snippet: new Set([]),
automation: new Set([]),
csv: new Set([]),
+ pr: new Set([]),
};
export const LoadErrors = {
diff --git a/js/app/packages/core/blockMethodRegistry.ts b/js/app/packages/core/blockMethodRegistry.ts
index b61f99f0a1..7d69ea8c7f 100644
--- a/js/app/packages/core/blockMethodRegistry.ts
+++ b/js/app/packages/core/blockMethodRegistry.ts
@@ -36,6 +36,7 @@ export interface BlockMethodRegistry {
component: EmptySpec;
task: EmptySpec;
automation: EmptySpec;
+ pr: EmptySpec;
}
// Type helper to get the method spec for a block name
diff --git a/js/app/packages/core/comments/discussion/Discussion.tsx b/js/app/packages/core/comments/discussion/Discussion.tsx
index 0f1cf1c25b..910abf21df 100644
--- a/js/app/packages/core/comments/discussion/Discussion.tsx
+++ b/js/app/packages/core/comments/discussion/Discussion.tsx
@@ -92,7 +92,7 @@ export function Discussion() {
);
}
-function DiscussionThreadView(props: { thread: ViewThread }) {
+export function DiscussionThreadView(props: { thread: ViewThread }) {
const source = useDiscussion();
const canEdit = source.canEdit;
diff --git a/js/app/packages/core/comments/discussion/index.ts b/js/app/packages/core/comments/discussion/index.ts
index 9414599333..68f702c00e 100644
--- a/js/app/packages/core/comments/discussion/index.ts
+++ b/js/app/packages/core/comments/discussion/index.ts
@@ -1,5 +1,6 @@
export { DiscussionProvider, useDiscussion } from './context';
-export { Discussion } from './Discussion';
+export { Discussion, DiscussionThreadView } from './Discussion';
+export { DiscussionInput } from './DiscussionInput';
export {
discussionCommentToApiChannelMessage,
discussionCommentToMessageData,
diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsx
index 548bff26ed..c62a62a34b 100644
--- a/js/app/packages/core/component/EntityIcon.tsx
+++ b/js/app/packages/core/component/EntityIcon.tsx
@@ -262,6 +262,12 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {
background: 'bg-default/20',
prettyName: 'GitHub Pull Request',
},
+ pr: {
+ icon: GithubIcon,
+ foreground: 'text-default',
+ background: 'bg-default/20',
+ prettyName: 'Pull Request',
+ },
task: {
icon: Check,
foreground: 'text-task',
@@ -351,6 +357,7 @@ const WIDE_ICONS: Record<
emailRead: WideEmail,
emailInvite: WideCalendar,
githubPullRequest: GithubIcon,
+ pr: GithubIcon,
task: WideTask,
snippet: WideSnippet,
automation: Robot,
diff --git a/js/app/packages/core/component/FileList/constants.tsx b/js/app/packages/core/component/FileList/constants.tsx
index ad8eeffb2b..b5d4da3f83 100644
--- a/js/app/packages/core/component/FileList/constants.tsx
+++ b/js/app/packages/core/component/FileList/constants.tsx
@@ -77,4 +77,5 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {
task: defaultFileColor,
snippet: 'bg-snippet/20 group/item',
automation: defaultFileColor,
+ pr: defaultFileColor,
};
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
new file mode 100644
index 0000000000..4f8d72eddb
--- /dev/null
+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/PullRequestMention.tsx
@@ -0,0 +1,483 @@
+import { useSplitLayout } from '@app/component/split-layout/layout';
+import { HoverCard } from '@core/component/HoverCard';
+import { openInNewSplitForMention } from '@core/util/openInNewSplit';
+import { useSplitNavigationHandler } from '@core/util/useSplitNavigationHandler';
+import {
+ $isPullRequestMentionNode,
+ type PullRequestMentionDecoratorProps,
+} from '@lexical-core';
+import OpenIcon from '@phosphor/arrows-out.svg';
+import ChatCircle from '@phosphor/chat-circle.svg';
+import GitMerge from '@phosphor/git-merge.svg';
+import GitPullRequest from '@phosphor/git-pull-request.svg';
+import { usePrMentionQuery } from '@queries/storage/pr-mention';
+import type {
+ ForeignEntity,
+ GithubPullRequestCheckRun,
+ GithubPullRequestComment,
+} from '@service-storage/generated/schemas';
+import { cn, Surface } from '@ui';
+import {
+ $getNodeByKey,
+ COMMAND_PRIORITY_NORMAL,
+ KEY_ENTER_COMMAND,
+} from 'lexical';
+import {
+ createEffect,
+ createMemo,
+ type JSX,
+ Show,
+ Suspense,
+ useContext,
+} from 'solid-js';
+import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';
+import { autoRegister } from '../../plugins';
+import { MentionTooltip } from './MentionTooltip';
+
+const GITHUB_PULL_REQUEST_SOURCE = 'github_pull_request';
+const STATUS_ICON_CLASS: Record<string, string> = {
+ open: 'text-success',
+ merged: 'text-note',
+ closed: 'text-failure',
+};
+
+function metadataRecord(metadata: unknown): Record<string, unknown> {
+ if (metadata && typeof metadata === 'object' && !Array.isArray(metadata)) {
+ return metadata as Record<string, unknown>;
+ }
+ return {};
+}
+
+function optionalString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim() ? value : undefined;
+}
+
+function optionalNumber(value: unknown): number | undefined {
+ return typeof value === 'number' ? value : undefined;
+}
+
+function displayNameFromGithubKey(key: string): string | undefined {
+ const match = key.match(
+ /^([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+)\/pull\/([1-9][0-9]*)$/
+ );
+ if (!match) return undefined;
+ return `${match[1]}/${match[2]}#${match[3]}`;
+}
+
+function pullRequestLabel(
+ entity: ForeignEntity | undefined
+): string | undefined {
+ if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
+ return undefined;
+ }
+
+ const metadata = metadataRecord(entity.metadata);
+ const title = optionalString(metadata.name);
+ const displayName = optionalString(metadata.displayName);
+ const owner = optionalString(metadata.owner);
+ const repo = optionalString(metadata.repo);
+ const number = optionalNumber(metadata.number);
+ const refLabel =
+ owner && repo && number != null
+ ? `${owner}/${repo}#${number}`
+ : displayNameFromGithubKey(entity.foreignEntityId);
+
+ if (title && refLabel) return `${refLabel} ${title}`;
+ return title ?? displayName ?? refLabel;
+}
+
+function pullRequestStatus(entity: ForeignEntity | undefined): string {
+ if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
+ return 'open';
+ }
+ return optionalString(metadataRecord(entity.metadata).status) ?? 'open';
+}
+
+interface PullRequestParts {
+ name: string;
+ number?: string;
+}
+
+function pullRequestParts(
+ entity: ForeignEntity | undefined,
+ props: PullRequestMentionDecoratorProps
+): PullRequestParts {
+ if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
+ return { name: fallbackLabel(props) };
+ }
+
+ const metadata = metadataRecord(entity.metadata);
+ const title = optionalString(metadata.name);
+ const displayName = optionalString(metadata.displayName);
+ const number = optionalNumber(metadata.number);
+ const ref =
+ number != null
+ ? `#${number}`
+ : displayNameFromGithubKey(entity.foreignEntityId);
+ const name = title ?? displayName ?? ref ?? fallbackLabel(props);
+
+ return { name, number: name === ref ? undefined : ref };
+}
+
+function fallbackLabel(props: PullRequestMentionDecoratorProps): string {
+ return props.label || 'Pull request';
+}
+
+function PullRequestStatusIcon(props: { status: string }) {
+ return (
+ <Show
+ when={props.status === 'merged'}
+ fallback={
+ <GitPullRequest
+ class={cn(
+ 'size-full',
+ STATUS_ICON_CLASS[props.status] ?? 'text-ink-muted'
+ )}
+ />
+ }
+ >
+ <GitMerge class="size-full text-note" />
+ </Show>
+ );
+}
+
+const STATUS_PILL_CLASS: Record<string, string> = {
+ open: 'bg-success/15 text-success',
+ merged: 'bg-note/15 text-note',
+ closed: 'bg-failure/15 text-failure',
+};
+
+interface ChecksSummary {
+ passed: number;
+ failed: number;
+ total: number;
+}
+
+interface PullRequestPreview {
+ title: string;
+ ref?: string;
+ url?: string;
+ status: string;
+ additions?: number;
+ deletions?: number;
+ commentCount?: number;
+ checks?: ChecksSummary;
+}
+
+function checksSummary(
+ checks: GithubPullRequestCheckRun[] | undefined
+): ChecksSummary | undefined {
+ if (!checks || checks.length === 0) return undefined;
+ let passed = 0;
+ let failed = 0;
+ for (const run of checks) {
+ const conclusion = optionalString(run.conclusion)?.toLowerCase();
+ if (conclusion === 'success') passed += 1;
+ else if (
+ conclusion === 'failure' ||
+ conclusion === 'timed_out' ||
+ conclusion === 'cancelled' ||
+ conclusion === 'action_required'
+ ) {
+ failed += 1;
+ }
+ }
+ return { passed, failed, total: checks.length };
+}
+
+function pullRequestPreview(
+ entity: ForeignEntity | undefined,
+ props: PullRequestMentionDecoratorProps
+): PullRequestPreview | undefined {
+ if (!entity || entity.foreignEntitySource !== GITHUB_PULL_REQUEST_SOURCE) {
+ return undefined;
+ }
+
+ const metadata = metadataRecord(entity.metadata);
+ const title = optionalString(metadata.name);
+ const displayName = optionalString(metadata.displayName);
+ const owner = optionalString(metadata.owner);
+ const repo = optionalString(metadata.repo);
+ const number = optionalNumber(metadata.number);
+ const ref =
+ owner && repo && number != null
+ ? `${owner}/${repo}#${number}`
+ : displayNameFromGithubKey(entity.foreignEntityId);
+ const comments = Array.isArray(metadata.comments)
+ ? (metadata.comments as GithubPullRequestComment[])
+ : undefined;
+ const checks = Array.isArray(metadata.checks)
+ ? (metadata.checks as GithubPullRequestCheckRun[])
+ : undefined;
+
+ return {
+ title: title ?? displayName ?? ref ?? fallbackLabel(props),
+ ref,
+ url: optionalString(metadata.url),
+ status: optionalString(metadata.status) ?? 'open',
+ additions: optionalNumber(metadata.additions),
+ deletions: optionalNumber(metadata.deletions),
+ commentCount: comments?.length || undefined,
+ checks: checksSummary(checks),
+ };
+}
+
+function PreviewStat(props: { children: JSX.Element; class?: string }) {
+ return (
+ <span class={cn('flex items-center gap-1 font-mono', props.class)}>
+ {props.children}
+ </span>
+ );
+}
+
+function PullRequestPreviewBody(props: {
+ id: string;
+ fallbackProps: PullRequestMentionDecoratorProps;
+}) {
+ const query = usePrMentionQuery(() => props.id);
+ const preview = createMemo(() =>
+ pullRequestPreview(query.data, props.fallbackProps)
+ );
+
+ return (
+ <Show
+ when={preview()}
+ fallback={
+ <div class="p-3 text-sm text-ink-muted">
+ {fallbackLabel(props.fallbackProps)}
+ </div>
+ }
+ >
+ {(pr) => (
+ <div class="w-full flex flex-col">
+ <div class="flex items-center justify-between gap-2 p-2">
+ <div class="flex items-center gap-2 min-w-0">
+ <span class="relative size-4 shrink-0 inline-flex">
+ <PullRequestStatusIcon status={pr().status} />
+ </span>
+ <Show when={pr().ref}>
+ {(ref) => (
+ <span class="text-[0.8em] text-ink-muted font-mono truncate">
+ {ref()}
+ </span>
+ )}
+ </Show>
+ <span
+ class={cn(
+ 'shrink-0 rounded-full px-1.5 py-0.5 text-xxs font-medium uppercase tracking-wide',
+ STATUS_PILL_CLASS[pr().status] ?? 'bg-edge text-ink-muted'
+ )}
+ >
+ {pr().status}
+ </span>
+ </div>
+ <Show when={pr().url}>
+ {(url) => (
+ <a
+ href={url()}
+ target="_blank"
+ rel="noreferrer"
+ class="shrink-0 text-ink-muted hover:text-ink"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <OpenIcon class="size-4" />
+ </a>
+ )}
+ </Show>
+ </div>
+
+ <div class="line-clamp-2 wrap-break-word px-2 mb-2 text-sm font-semibold select-text">
+ {pr().title}
+ </div>
+
+ <Show
+ when={
+ pr().additions != null ||
+ pr().deletions != null ||
+ pr().commentCount ||
+ pr().checks
+ }
+ >
+ <div class="p-2 border-t border-edge-muted flex items-center gap-3 text-xs text-ink-muted">
+ <Show when={pr().additions != null || pr().deletions != null}>
+ <PreviewStat>
+ <Show when={pr().additions != null}>
+ <span class="text-success">{`+${pr().additions}`}</span>
+ </Show>
+ <Show when={pr().deletions != null}>
+ <span class="text-failure">{`-${pr().deletions}`}</span>
+ </Show>
+ </PreviewStat>
+ </Show>
+
+ <Show when={pr().commentCount}>
+ {(count) => (
+ <PreviewStat>
+ <ChatCircle class="size-3.5" />
+ {count()}
+ </PreviewStat>
+ )}
+ </Show>
+
+ <Show when={pr().checks}>
+ {(checks) => (
+ <PreviewStat class="ml-auto">
+ <Show when={checks().passed}>
+ <span class="text-success">{`${checks().passed} passed`}</span>
+ </Show>
+ <Show when={checks().failed}>
+ <span class="text-failure">{`${checks().failed} failed`}</span>
+ </Show>
+ </PreviewStat>
+ )}
+ </Show>
+ </div>
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+}
+
+function PullRequestPreviewCard(props: {
+ id: string;
+ fallbackProps: PullRequestMentionDecoratorProps;
+}) {
+ return (
+ <div class="select-none overflow-hidden w-80 text-ink">
+ <Surface active depth={3} class="rounded-xl shadow-lg shadow-drop-shadow">
+ <Suspense
+ fallback={
+ <div class="p-3 flex items-center justify-center text-sm text-ink-muted">
+ Fetching PR...
+ </div>
+ }
+ >
+ <PullRequestPreviewBody
+ id={props.id}
+ fallbackProps={props.fallbackProps}
+ />
+ </Suspense>
+ </Surface>
+ </div>
+ );
+}
+
+function PullRequestMentionContent(props: PullRequestMentionDecoratorProps) {
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = lexicalWrapper?.editor;
+
+ const query = usePrMentionQuery(
+ () => props.id,
+ () => !lexicalWrapper?.skipPreviewFetch
+ );
+
+ const label = createMemo(
+ () => pullRequestLabel(query.data) ?? fallbackLabel(props)
+ );
+ const parts = createMemo(() => pullRequestParts(query.data, props));
+ const status = createMemo(() => pullRequestStatus(query.data));
+
+ createEffect(() => {
+ const nextLabel = pullRequestLabel(query.data);
+ if (!editor || !nextLabel || nextLabel === props.label) return;
+
+ editor.update(
+ () => {
+ const node = $getNodeByKey(props.key);
+ if ($isPullRequestMentionNode(node)) {
+ node.setLabel(nextLabel);
+ }
+ },
+ { tag: 'historic', discrete: true }
+ );
+ });
+
+ return (
+ <span
+ data-pr-mention="true"
+ data-pr-id={props.id}
+ data-pr-label={label()}
+ class="pointer-events-auto"
+ >
+ <span class="relative top-[0.125em] size-[1em] inline-flex mx-1">
+ <PullRequestStatusIcon status={status()} />
+ </span>
+ <span class="underline decoration-current/20 decoration-[max(1px,0.1em)] underline-offset-2">
+ {parts().name}
+ <Show when={parts().number}>
+ {(number) => (
+ <span class="text-ink-extra-muted text-[0.8em]">{` ${number()}`}</span>
+ )}
+ </Show>
+ </span>
+ </span>
+ );
+}
+
+export function PullRequestMention(props: PullRequestMentionDecoratorProps) {
+ const lexicalWrapper = useContext(LexicalWrapperContext);
+ const editor = lexicalWrapper?.editor;
+ const selection = () => lexicalWrapper?.selection;
+ const { openWithSplit } = useSplitLayout()!;
+
+ const isSelectedAsNode = () => {
+ const sel = selection();
+ if (!sel) return false;
+ return sel.type === 'node' && sel.nodeKeys.has(props.key);
+ };
+
+ const open = (e: MouseEvent | KeyboardEvent | null) => {
+ openWithSplit(
+ { type: 'pr', id: props.id },
+ { preferNewSplit: openInNewSplitForMention(e?.shiftKey, e != null) }
+ );
+ };
+
+ if (editor) {
+ autoRegister(
+ editor.registerCommand(
+ KEY_ENTER_COMMAND,
+ (e) => {
+ if (isSelectedAsNode()) {
+ open(e);
+ return true;
+ }
+ return false;
+ },
+ COMMAND_PRIORITY_NORMAL
+ )
+ );
+ }
+
+ const navHandlers = useSplitNavigationHandler<HTMLSpanElement>((e) => {
+ e.stopPropagation();
+ open(e);
+ });
+
+ return (
+ <HoverCard
+ trigger={
+ <span class="relative">
+ <span
+ class={cn(
+ 'size-full py-0.5 cursor-default rounded-xs hover:bg-hover focus:bg-active',
+ isSelectedAsNode() && 'bg-active text-ink'
+ )}
+ {...navHandlers}
+ >
+ <Suspense
+ fallback={
+ <span class="text-ink-placeholder">Fetching PR...</span>
+ }
+ >
+ <PullRequestMentionContent {...props} />
+ </Suspense>
+ </span>
+ <MentionTooltip show={isSelectedAsNode()} text="Open" />
+ </span>
+ }
+ content={<PullRequestPreviewCard id={props.id} fallbackProps={props} />}
+ />
+ );
+}
diff --git a/js/app/packages/core/component/LexicalMarkdown/init.ts b/js/app/packages/core/component/LexicalMarkdown/init.ts
index 86a590dba0..b26adced0e 100644
--- a/js/app/packages/core/component/LexicalMarkdown/init.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/init.ts
@@ -10,6 +10,7 @@ import {
HorizontalRuleNode,
HtmlRenderNode,
ImageNode,
+ PullRequestMentionNode,
SnapshotNode,
ThemeMentionNode,
UnknownMentionNode,
@@ -30,6 +31,7 @@ import { HorizontalRule } from './component/decorator/HorizontalRule';
import { HtmlRender } from './component/decorator/HtmlRender';
import { MarkdownImage } from './component/decorator/MarkdownImage';
import { MarkdownVideo } from './component/decorator/MarkdownVideo';
+import { PullRequestMention } from './component/decorator/PullRequestMention';
import { Snapshot } from './component/decorator/Snapshot';
import { ThemeMention } from './component/decorator/ThemeMention';
import { UnknownMention } from './component/decorator/UnknownMention';
@@ -47,6 +49,7 @@ export function initializeLexical() {
setDecorator(GroupMentionNode, GroupMention);
setDecorator(DocumentMentionNode, DocumentMention);
setDecorator(DocumentCardNode, DocumentCard);
+ setDecorator(PullRequestMentionNode, PullRequestMention);
setDecorator(ContactMentionNode, ContactMention);
setDecorator(DateMentionNode, DateMention);
setDecorator(DiffInsertNode, DiffInsert);
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
index b20ad9a499..27b308737d 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts
@@ -9,6 +9,7 @@ import {
$createDocumentMentionNode,
$createGroupMentionNode,
$createInlineSearchNode,
+ $createPullRequestMentionNode,
$createSnapshotNode,
$createThemeMentionNode,
$createUserMentionNode,
@@ -18,6 +19,7 @@ import {
$isDateMentionNode,
$isDocumentMentionNode,
$isGroupMentionNode,
+ $isPullRequestMentionNode,
$isUserMentionNode,
$removeInlineSearch,
type ContactMentionInfo,
@@ -30,6 +32,8 @@ import {
GroupMentionNode,
InlineSearchNode,
InlineSearchNodesType,
+ type PullRequestMentionInfo,
+ PullRequestMentionNode,
type SnapshotNodeInfo,
type ThemeMentionInfo,
type UserMentionInfo,
@@ -105,6 +109,9 @@ export const INSERT_USER_MENTION_COMMAND: LexicalCommand<UserMentionInfo> =
export const INSERT_GROUP_MENTION_COMMAND: LexicalCommand<GroupMentionInfo> =
createCommand('INSERT_GROUP_MENTION_COMMAND');
+export const INSERT_PR_MENTION_COMMAND: LexicalCommand<PullRequestMentionInfo> =
+ createCommand('INSERT_PR_MENTION_COMMAND');
+
export const INSERT_THEME_MENTION_COMMAND: LexicalCommand<ThemeMentionInfo> =
createCommand('INSERT_THEME_MENTION_COMMAND');
@@ -122,6 +129,7 @@ export type ItemMention = {
| 'unknown'
| 'color'
| 'call'
+ | 'foreign'
| 'group'
| 'automation'
| 'crm_company'
@@ -140,12 +148,14 @@ function $isMentionNode(
| DocumentMentionNode
| ContactMentionNode
| DateMentionNode
+ | PullRequestMentionNode
| GroupMentionNode {
return (
$isUserMentionNode(node) ||
$isDocumentMentionNode(node) ||
$isContactMentionNode(node) ||
$isDateMentionNode(node) ||
+ $isPullRequestMentionNode(node) ||
$isGroupMentionNode(node)
);
}
@@ -215,6 +225,13 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {
itemId: node.getGroupAlias(),
groupAlias: node.getGroupAlias(),
};
+ } else if ($isPullRequestMentionNode(node)) {
+ return {
+ itemType: 'foreign',
+ itemId: node.getId(),
+ fileType: 'github_pull_request',
+ documentName: node.getLabel(),
+ };
} else {
return {
itemType: 'date',
@@ -301,6 +318,7 @@ function registerMentionsPlugin(
GroupMentionNode,
ContactMentionNode,
DateMentionNode,
+ PullRequestMentionNode,
InlineSearchNode,
])
) {
@@ -488,6 +506,27 @@ function registerMentionsPlugin(
COMMAND_PRIORITY_NORMAL
),
+ editor.registerCommand(
+ INSERT_PR_MENTION_COMMAND,
+ (payload) => {
+ editor.update(() => {
+ const mentionNode = $createPullRequestMentionNode(payload);
+
+ if (payload.mentionUuid) {
+ mentionNode.setMentionUuid(payload.mentionUuid);
+ }
+
+ $insertNodes([mentionNode]);
+ if ($isRootOrShadowRoot(mentionNode.getParentOrThrow())) {
+ $wrapNodeInElement(mentionNode, $createParagraphNode);
+ }
+ mentionNode.selectEnd();
+ });
+ return true;
+ },
+ COMMAND_PRIORITY_NORMAL
+ ),
+
editor.registerCommand(
INSERT_THEME_MENTION_COMMAND,
(payload) => {
@@ -828,6 +867,33 @@ function registerMentionsPlugin(
}
updateMentionsSignal();
}
+ ),
+
+ editor.registerMutationListener(
+ PullRequestMentionNode,
+ (mutatedNodes, { prevEditorState }) => {
+ for (const [nodeKey, mutation] of mutatedNodes) {
+ const node = nodeByKey(
+ mutation === 'destroyed'
+ ? prevEditorState
+ : editor.getEditorState(),
+ nodeKey
+ ) as PullRequestMentionNode | null;
+
+ if (!node) continue;
+
+ if (mutation === 'destroyed') {
+ const mentionUuid = node.getMentionUuid();
+ if (mentionUuid && sourceDocumentId) {
+ untrackMention(sourceDocumentId, mentionUuid);
+ }
+ onRemoveMention?.($mentionItemFromNode(node));
+ } else if (mutation === 'created') {
+ onCreateMention?.($mentionItemFromNode(node));
+ }
+ }
+ updateMentionsSignal();
+ }
)
);
}
diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
index c949cdb8f9..0a165650fc 100644
--- a/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.ts
@@ -16,6 +16,7 @@ import {
} from 'lexical';
import {
INSERT_DOCUMENT_MENTION_COMMAND,
+ INSERT_PR_MENTION_COMMAND,
INSERT_THEME_MENTION_COMMAND,
} from '../mentions';
@@ -169,6 +170,13 @@ function registerTextPastePlugin(editor: LexicalEditor) {
return false;
event.preventDefault();
+ if (parsedMacroAppUrl.block === 'pr') {
+ editor.dispatchCommand(INSERT_PR_MENTION_COMMAND, {
+ id: parsedMacroAppUrl.id,
+ });
+ return true;
+ }
+
editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {
documentId: parsedMacroAppUrl.id,
documentName: '',
diff --git a/js/app/packages/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts b/js/app/packages/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
index 958db9b9f7..d7e4c3d84c 100644
--- a/js/app/packages/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts
@@ -73,6 +73,7 @@ import {
INSERT_DATE_MENTION_COMMAND,
INSERT_DOCUMENT_MENTION_COMMAND,
INSERT_GROUP_MENTION_COMMAND,
+ INSERT_PR_MENTION_COMMAND,
INSERT_USER_MENTION_COMMAND,
type ItemMention,
mentionsPlugin,
@@ -153,7 +154,14 @@ describe('mentionsPlugin callbacks', () => {
});
flush();
- expect(created).toHaveLength(5);
+ editor.dispatchCommand(INSERT_PR_MENTION_COMMAND, {
+ id: 'foreign-1',
+ label: 'macro/macro#123',
+ mentionUuid: 'uuid-pr',
+ });
+ flush();
+
+ expect(created).toHaveLength(6);
expect(created).toContainEqual(
expect.objectContaining({ itemType: 'document', itemId: 'doc-1' })
);
@@ -173,6 +181,14 @@ describe('mentionsPlugin callbacks', () => {
groupAlias: 'engineering',
})
);
+ expect(created).toContainEqual(
+ expect.objectContaining({
+ itemType: 'foreign',
+ itemId: 'foreign-1',
+ fileType: 'github_pull_request',
+ documentName: 'macro/macro#123',
+ })
+ );
// Clear editor to trigger destroy mutations.
created.length = 0;
@@ -185,7 +201,7 @@ describe('mentionsPlugin callbacks', () => {
);
flush();
- expect(removed).toHaveLength(5);
+ expect(removed).toHaveLength(6);
expect(removed).toContainEqual(
expect.objectContaining({ itemType: 'document', itemId: 'doc-1' })
);
@@ -205,6 +221,14 @@ describe('mentionsPlugin callbacks', () => {
groupAlias: 'engineering',
})
);
+ expect(removed).toContainEqual(
+ expect.objectContaining({
+ itemType: 'foreign',
+ itemId: 'foreign-1',
+ fileType: 'github_pull_request',
+ documentName: 'macro/macro#123',
+ })
+ );
cleanup();
});
diff --git a/js/app/packages/core/component/LexicalMarkdown/version.ts b/js/app/packages/core/component/LexicalMarkdown/version.ts
index d3e0858207..a3520debc3 100644
--- a/js/app/packages/core/component/LexicalMarkdown/version.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/version.ts
@@ -10,5 +10,6 @@
* Version 1.21 - Feb 4, 2026. Added fallback-xml tag node.
* Version 1.3 - Apr 30, 2026. Added AwaitNode.
* Version 1.4 - Jun 2, 2026. Added persisted await placeholders for pending agent messages.
+ * Version 2.0 - Jun 19, 2026. Added PullRequestMentionNode.
*/
-export const MARKDOWN_VERSION_COUNTER = 1.4;
+export const MARKDOWN_VERSION_COUNTER = 2.0;
diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.ts
index b0e8a04bc7..3a9a1978e6 100644
--- a/js/app/packages/core/constant/featureFlags.ts
+++ b/js/app/packages/core/constant/featureFlags.ts
@@ -332,6 +332,16 @@ export const ENABLE_RAIL_CHAT_TASK_COMMENTS = resolveFeatureFlag(
true
);
+export const ENABLE_PR_DISCUSSION_INPUT = resolveFeatureFlag(
+ 'ENABLE_PR_DISCUSSION_INPUT',
+ false
+);
+
+export const USE_MACRO_PR_SUMMARY_BLOCK = resolveFeatureFlag(
+ 'USE_MACRO_PR_SUMMARY_BLOCK',
+ true
+);
+
// skips over posthog and sets the ENABLE_TEAMS feature to true if we are in dev mode
// can also be overridden via VITE_ENABLE_TEAMS env var
export const ENABLE_TEAMS_OVERRIDE =
diff --git a/js/app/packages/entity/src/utils/buildEntityData.ts b/js/app/packages/entity/src/utils/buildEntityData.ts
index ff841a5af6..7776ca1531 100644
--- a/js/app/packages/entity/src/utils/buildEntityData.ts
+++ b/js/app/packages/entity/src/utils/buildEntityData.ts
@@ -163,6 +163,8 @@ export function buildEntityData(
})
// CRM companies/contacts aren't constructed from block args; soup is the source.
.with('company', 'contact', (): undefined => undefined)
+ // PRs are virtual blocks backed by GitHub, not Macro entities.
+ .with('pr', (): undefined => undefined)
.exhaustive()
);
}
diff --git a/js/app/packages/queries/storage/github-pull-requests.ts b/js/app/packages/queries/storage/github-pull-requests.ts
index babc89247d..49fc6a716c 100644
--- a/js/app/packages/queries/storage/github-pull-requests.ts
+++ b/js/app/packages/queries/storage/github-pull-requests.ts
@@ -14,6 +14,7 @@ import type { Accessor } from 'solid-js';
import { documentGithubPullRequestsKeys } from './keys';
const DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME = 60 * 1000;
+
type DocumentIdInput =
| string
| null
@@ -36,6 +37,16 @@ function readEnabled(enabled: EnabledInput | undefined): boolean {
return typeof enabled === 'function' ? enabled() : enabled;
}
+/**
+ * Storage pull request extended with enrichment-only fields. The documents
+ * service doesn't expose body/author yet, so they only arrive via the live
+ * enrich merge and must stay optional.
+ */
+export type GithubPullRequestWithDetails = GithubPullRequest & {
+ description?: string | null;
+ authorLogin?: string | null;
+};
+
function toGithubPullRequestRef(
pullRequest: GithubPullRequest
): GithubPullRequestRef {
@@ -51,10 +62,12 @@ function toGithubPullRequestRef(
function toStorageGithubPullRequest(
pullRequest: EnrichedGithubPullRequest,
- fallbackPullRequest: GithubPullRequest | undefined
-): GithubPullRequest {
+ fallbackPullRequest: GithubPullRequestWithDetails | undefined
+): GithubPullRequestWithDetails {
return {
additions: pullRequest.additions ?? fallbackPullRequest?.additions,
+ authorLogin: pullRequest.authorLogin ?? fallbackPullRequest?.authorLogin,
+ description: pullRequest.description ?? fallbackPullRequest?.description,
checks: pullRequest.checks ?? fallbackPullRequest?.checks,
comments: pullRequest.comments ?? fallbackPullRequest?.comments,
deletions: pullRequest.deletions ?? fallbackPullRequest?.deletions,
@@ -97,10 +110,14 @@ function hasStoredEnrichedGithubPullRequests(
return response.pullRequests.some(hasStoredEnrichedGithubPullRequestData);
}
+export type GithubPullRequestsWithDetailsResponse = {
+ pullRequests: GithubPullRequestWithDetails[];
+};
+
export async function fetchDocumentGithubPullRequests(
documentId: string,
options?: FetchDocumentGithubPullRequestsOptions
-): Promise<GithubPullRequestsResponse> {
+): Promise<GithubPullRequestsWithDetailsResponse> {
const rawResponse = await throwOnErr(() =>
storageServiceClient.getDocumentGithubPullRequests({ documentId })
);
@@ -125,7 +142,7 @@ export async function fetchDocumentGithubPullRequests(
rawResponse.pullRequests
);
- return {
+ const mergedResponse = {
pullRequests: enrichedResponse.value.pullRequests.map(
(pullRequest, index) =>
toStorageGithubPullRequest(
@@ -135,6 +152,7 @@ export async function fetchDocumentGithubPullRequests(
)
),
};
+ return mergedResponse;
}
export function useDocumentGithubPullRequestsQuery(
@@ -145,6 +163,7 @@ export function useDocumentGithubPullRequestsQuery(
return useQuery(() => {
const currentDocumentId = readDocumentId(documentId);
+ const currentEnabled = !!currentDocumentId && readEnabled(enabled);
const queryKey = currentDocumentId
? documentGithubPullRequestsKeys.list(currentDocumentId).queryKey
: documentGithubPullRequestsKeys.list._def;
@@ -164,7 +183,7 @@ export function useDocumentGithubPullRequestsQuery(
});
},
staleTime: DOCUMENT_GITHUB_PULL_REQUESTS_STALE_TIME,
- enabled: !!currentDocumentId && readEnabled(enabled),
+ enabled: currentEnabled,
};
});
}
diff --git a/js/app/packages/queries/storage/keys.ts b/js/app/packages/queries/storage/keys.ts
index 59d2fcd908..a5cf10dc46 100644
--- a/js/app/packages/queries/storage/keys.ts
+++ b/js/app/packages/queries/storage/keys.ts
@@ -46,6 +46,12 @@ export const documentGithubPullRequestsKeys = createQueryKeys(
}
);
+export const pullRequestMentionKeys = createQueryKeys('pullRequestMention', {
+ foreignEntity: (id: string) => ({
+ queryKey: [id],
+ }),
+});
+
export const attachmentReferencesKeys = createQueryKeys(
'attachmentReferences',
{
diff --git a/js/app/packages/queries/storage/pr-mention.ts b/js/app/packages/queries/storage/pr-mention.ts
new file mode 100644
index 0000000000..6be38afb5a
--- /dev/null
+++ b/js/app/packages/queries/storage/pr-mention.ts
@@ -0,0 +1,35 @@
+import { throwOnErr } from '@core/util/result';
+import { storageServiceClient } from '@service-storage/client';
+import type { ForeignEntity } from '@service-storage/generated/schemas';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+import { pullRequestMentionKeys } from './keys';
+
+const PR_MENTION_STALE_TIME = 60 * 1000;
+
+type EnabledInput = boolean | Accessor<boolean>;
+
+function readEnabled(enabled: EnabledInput | undefined): boolean {
+ if (enabled === undefined) return true;
+ return typeof enabled === 'function' ? enabled() : enabled;
+}
+
+function prMentionQueryOptions(id: string) {
+ return {
+ queryKey: pullRequestMentionKeys.foreignEntity(id).queryKey,
+ queryFn: async (): Promise<ForeignEntity> =>
+ await throwOnErr(() => storageServiceClient.getForeignEntity({ id })),
+ staleTime: PR_MENTION_STALE_TIME,
+ retry: 1,
+ };
+}
+
+export function usePrMentionQuery(
+ id: Accessor<string>,
+ enabled?: EnabledInput
+) {
+ return useQuery(() => ({
+ ...prMentionQueryOptions(id()),
+ enabled: !!id() && readEnabled(enabled),
+ }));
+}
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.ts
index 146c7d886f..53b8db4c77 100644
--- a/js/app/packages/service-clients/service-storage/client.ts
+++ b/js/app/packages/service-clients/service-storage/client.ts
@@ -33,6 +33,7 @@ import type { ApiChannelWithLatest } from './channel-list-types';
import type {
AccessLevel,
CallRecordPreview,
+ ForeignEntity,
GithubPullRequestsResponse,
GroupedSoupGroupPage,
GroupedSoupInitialPage,
@@ -1324,6 +1325,16 @@ export const storageServiceClient = {
);
},
+ async getForeignEntity({
+ id,
+ }: {
+ id: string;
+ }): Promise<Result<ForeignEntity, ResultError<FetchWithTokenErrorCode>[]>> {
+ return await dssFetch<ForeignEntity>(`/foreign_entity/${id}`, {
+ method: 'GET',
+ });
+ },
+
async exportDocument({ documentId }) {
return (
await dssFetch<ExportDocumentResponse>(
diff --git a/js/app/tsconfig.json b/js/app/tsconfig.json
index 07d6463c18..d4d7af7cfc 100644
--- a/js/app/tsconfig.json
+++ b/js/app/tsconfig.json
@@ -153,6 +153,9 @@
"@block-email/*": [
"./packages/block-email/*"
],
+ "@block-pr/*": [
+ "./packages/block-pr/*"
+ ],
"@block-md/*": [
"./packages/block-md/*"
],
diff --git a/js/app/vitest.config.ts b/js/app/vitest.config.ts
index 0d91590e4f..e1af975076 100644
--- a/js/app/vitest.config.ts
+++ b/js/app/vitest.config.ts
@@ -68,6 +68,13 @@ export default defineConfig({
name: 'block-call',
},
},
+ {
+ extends: './packages/core/vitest.config.ts',
+ test: {
+ include: ['packages/block-pr/**/*.{test,spec}.{ts,tsx}'],
+ name: 'block-pr',
+ },
+ },
{
extends: './packages/core/vitest.config.ts',
test: {
diff --git a/js/bun.lock b/js/bun.lock
index ab75f4ccc7..0978f5e969 100644
--- a/js/bun.lock
+++ b/js/bun.lock
@@ -205,6 +205,9 @@
"zod-validation-error": "^5.0.0",
},
},
+ "app/packages/block-pr": {
+ "name": "block-pr",
+ },
"app/packages/block-project": {
"name": "block-project",
},
@@ -1656,6 +1659,8 @@
"block-pdf": ["block-pdf@workspace:app/packages/block-pdf"],
+ "block-pr": ["block-pr@workspace:app/packages/block-pr"],
+
"block-project": ["block-project@workspace:app/packages/block-project"],
"block-unknown": ["block-unknown@workspace:app/packages/block-unknown"],
diff --git a/js/lexical-core/decoratorRegistry.ts b/js/lexical-core/decoratorRegistry.ts
index 98db423468..d0c94c5783 100644
--- a/js/lexical-core/decoratorRegistry.ts
+++ b/js/lexical-core/decoratorRegistry.ts
@@ -37,6 +37,10 @@ import type {
HtmlRenderNode,
} from './nodes/HtmlRenderNode';
import type { ImageDecoratorProps, ImageNode } from './nodes/ImageNode';
+import type {
+ PullRequestMentionDecoratorProps,
+ PullRequestMentionNode,
+} from './nodes/PullRequestMentionNode';
import type {
SnapshotDecoratorProps,
SnapshotNode,
@@ -98,6 +102,10 @@ export interface NodeDecoratorMap {
klass: typeof DateMentionNode;
props: DateMentionDecoratorProps;
};
+ PullRequestMentionNode: {
+ klass: typeof PullRequestMentionNode;
+ props: PullRequestMentionDecoratorProps;
+ };
EquationNode: {
klass: typeof EquationNode;
props: EquationDecoratorProps;
diff --git a/js/lexical-core/index.ts b/js/lexical-core/index.ts
index 003232990d..a12f2dd684 100644
--- a/js/lexical-core/index.ts
+++ b/js/lexical-core/index.ts
@@ -22,6 +22,7 @@ export * from './nodes/HtmlRenderNode';
export * from './nodes/ImageNode';
export * from './nodes/InlineSearchNode';
export * from './nodes/MediaNode';
+export * from './nodes/PullRequestMentionNode';
export * from './nodes/SnapshotNode';
export * from './nodes/ThemeMentionNode';
export * from './nodes/UnknownMentionNode';
diff --git a/js/lexical-core/node-list.ts b/js/lexical-core/node-list.ts
index 0c4d3fed69..d3c0deac70 100644
--- a/js/lexical-core/node-list.ts
+++ b/js/lexical-core/node-list.ts
@@ -31,6 +31,7 @@ import { HorizontalRuleNode } from './nodes/HorizontalRuleNode';
import { HtmlRenderNode } from './nodes/HtmlRenderNode';
import { ImageNode } from './nodes/ImageNode';
import { InlineSearchNode } from './nodes/InlineSearchNode';
+import { PullRequestMentionNode } from './nodes/PullRequestMentionNode';
import { SearchMatchNode } from './nodes/SearchMatchNode';
import { SnapshotNode } from './nodes/SnapshotNode';
import { ThemeMentionNode } from './nodes/ThemeMentionNode';
@@ -73,6 +74,7 @@ export const SupportedNodeTypes = [
UserMentionNode,
ContactMentionNode,
DateMentionNode,
+ PullRequestMentionNode,
GroupMentionNode,
InlineSearchNode,
UnlinkedTextNode,
diff --git a/js/lexical-core/nodes/PullRequestMentionNode.ts b/js/lexical-core/nodes/PullRequestMentionNode.ts
new file mode 100644
index 0000000000..9584586063
--- /dev/null
+++ b/js/lexical-core/nodes/PullRequestMentionNode.ts
@@ -0,0 +1,216 @@
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMConversion,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+const VERSION = 1;
+
+export type PullRequestMentionInfo = {
+ id: string;
+ label?: string;
+ mentionUuid?: string;
+};
+
+export type SerializedPullRequestMentionNode = Spread<
+ PullRequestMentionInfo,
+ SerializedLexicalNode
+>;
+
+export type PullRequestMentionDecoratorProps = PullRequestMentionInfo & {
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+export class PullRequestMentionNode extends DecoratorNode<
+ DecoratorComponent<PullRequestMentionDecoratorProps> | undefined
+> {
+ __id: string;
+ __label: string | undefined;
+ __mentionUuid: string | undefined;
+
+ static getType() {
+ return 'pr-mention';
+ }
+
+ isInline(): boolean {
+ return true;
+ }
+
+ isKeyboardSelectable(): boolean {
+ return true;
+ }
+
+ static clone(node: PullRequestMentionNode) {
+ return new PullRequestMentionNode(
+ node.__id,
+ node.__label,
+ node.__mentionUuid,
+ node.__key
+ );
+ }
+
+ constructor(id: string, label?: string, mentionUuid?: string, key?: NodeKey) {
+ super(key);
+ this.__id = id;
+ this.__label = label;
+ this.__mentionUuid = mentionUuid;
+ }
+
+ static importJSON(serializedNode: SerializedPullRequestMentionNode) {
+ const node = $createPullRequestMentionNode({
+ id: serializedNode.id,
+ label: serializedNode.label,
+ mentionUuid: serializedNode.mentionUuid,
+ });
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedPullRequestMentionNode {
+ return {
+ ...super.exportJSON(),
+ id: this.__id,
+ label: this.__label,
+ mentionUuid: this.__mentionUuid,
+ type: PullRequestMentionNode.getType(),
+ version: VERSION,
+ };
+ }
+
+ exportComponentProps(): PullRequestMentionInfo {
+ return {
+ id: this.__id,
+ label: this.__label,
+ mentionUuid: this.__mentionUuid,
+ };
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const span = document.createElement('span');
+ span.setAttribute('data-pr-mention', 'true');
+ return span;
+ }
+
+ updateDOM(_prevNode: PullRequestMentionNode, _dom: HTMLElement): boolean {
+ return false;
+ }
+
+ static importDOM(): DOMConversionMap<HTMLElement> | null {
+ const convert = (domNode: HTMLElement) => {
+ const id = domNode.getAttribute('data-pr-id');
+ const label = domNode.getAttribute('data-pr-label') || undefined;
+ const mentionUuid =
+ domNode.getAttribute('data-mention-uuid') || undefined;
+
+ if (id) {
+ return {
+ node: $createPullRequestMentionNode({ id, label, mentionUuid }),
+ };
+ }
+
+ return null;
+ };
+
+ const wrapInCheck = (conversion: DOMConversion) => {
+ return (node: HTMLElement) =>
+ node.hasAttribute('data-pr-mention') ? conversion : null;
+ };
+
+ return {
+ span: wrapInCheck({ conversion: convert, priority: 1 }),
+ a: wrapInCheck({ conversion: convert, priority: 1 }),
+ };
+ }
+
+ getDataAttrs(): Record<string, string> {
+ return {
+ 'data-pr-mention': 'true',
+ 'data-pr-id': this.__id,
+ 'data-pr-label': this.__label || '',
+ 'data-mention-uuid': this.__mentionUuid || '',
+ };
+ }
+
+ exportDOM() {
+ const element = document.createElement('span');
+ const attrs = this.getDataAttrs();
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v) {
+ element.setAttribute(k, v);
+ }
+ }
+ element.textContent = this.getTextContent();
+ return { element };
+ }
+
+ getTextContent(): string {
+ return this.__label || 'Pull request';
+ }
+
+ getSearchText(): string {
+ return this.getTextContent();
+ }
+
+ getId(): string {
+ return this.__id;
+ }
+
+ getLabel(): string | undefined {
+ return this.__label;
+ }
+
+ setLabel(label: string | undefined) {
+ const self = this.getWritable();
+ self.__label = label;
+ }
+
+ getMentionUuid(): string | undefined {
+ return this.__mentionUuid;
+ }
+
+ setMentionUuid(mentionUuid: string | undefined) {
+ const self = this.getWritable();
+ self.__mentionUuid = mentionUuid;
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const Component = getDecorator<PullRequestMentionDecoratorProps>(
+ PullRequestMentionNode
+ );
+
+ if (!Component) return undefined;
+
+ return () =>
+ Component({
+ ...this.exportComponentProps(),
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ }
+}
+
+export function $createPullRequestMentionNode(params: PullRequestMentionInfo) {
+ const node = new PullRequestMentionNode(
+ params.id,
+ params.label,
+ params.mentionUuid
+ );
+ return $applyNodeReplacement(node);
+}
+
+export function $isPullRequestMentionNode(
+ node: PullRequestMentionNode | LexicalNode | null | undefined
+): node is PullRequestMentionNode {
+ return node instanceof PullRequestMentionNode;
+}
diff --git a/js/lexical-core/tests/classedBlock.test.ts b/js/lexical-core/tests/classedBlock.test.ts
index 5cf99671aa..88c72cec1f 100644
--- a/js/lexical-core/tests/classedBlock.test.ts
+++ b/js/lexical-core/tests/classedBlock.test.ts
@@ -2,6 +2,7 @@ import {
$convertFromMarkdownString,
$convertToMarkdownString,
} from '@lexical/markdown';
+import { $isQuoteNode } from '@lexical/rich-text';
import {
$createParagraphNode,
$createTextNode,
@@ -14,7 +15,11 @@ import {
$createClassedBlockNode,
$isClassedBlockNode,
} from '../nodes/ClassedBlockNode';
-import { INTERNAL_TRANSFORMERS } from '../transformers';
+import {
+ ALL_TRANSFORMERS,
+ EXTERNAL_TRANSFORMERS,
+ INTERNAL_TRANSFORMERS,
+} from '../transformers';
describe('ClassedBlockNode - macro_quote transformer', () => {
it('serializes and deserializes a simple macro_quote block', async () => {
@@ -241,3 +246,97 @@ describe('ClassedBlockNode - macro_quote transformer', () => {
});
});
});
+
+describe('HTML blockquote transformer', () => {
+ it('imports multiline html blockquotes as quote nodes', async () => {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: console.error,
+ });
+
+ const markdown =
+ '<blockquote>\n[!IMPORTANT]\n## Review skipped\n\nDisabled.\n</blockquote>';
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $convertFromMarkdownString(markdown, ALL_TRANSFORMERS);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ const firstChild = $getRoot().getFirstChild();
+ expect($isQuoteNode(firstChild)).toBe(true);
+ expect(firstChild?.getTextContent()).toContain('[!IMPORTANT]');
+ expect(firstChild?.getTextContent()).toContain('Review skipped');
+ expect(firstChild?.getTextContent()).toContain('Disabled.');
+ });
+ });
+
+ it('exports imported html blockquotes as markdown blockquotes', async () => {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: console.error,
+ });
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $convertFromMarkdownString(
+ '<blockquote>\nReview skipped\n</blockquote>',
+ ALL_TRANSFORMERS
+ );
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ let markdown = '';
+ editor.getEditorState().read(() => {
+ markdown = $convertToMarkdownString(EXTERNAL_TRANSFORMERS);
+ });
+
+ expect(markdown).toContain('> Review skipped');
+ });
+
+ it('imports nested html blockquotes as nested quote nodes', async () => {
+ const editor = createEditor({
+ nodes: SupportedNodeTypes,
+ onError: console.error,
+ });
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $convertFromMarkdownString(
+ [
+ '<blockquote>',
+ 'Outer',
+ '<blockquote>',
+ 'Inner',
+ '</blockquote>',
+ 'After',
+ '</blockquote>',
+ ].join('\n'),
+ ALL_TRANSFORMERS
+ );
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ const outer = $getRoot().getFirstChild();
+ expect($isQuoteNode(outer)).toBe(true);
+ if (!$isQuoteNode(outer)) return;
+
+ const nested = outer.getChildren().find((child) => $isQuoteNode(child));
+ expect($isQuoteNode(nested)).toBe(true);
+ expect(outer.getTextContent()).toContain('Outer');
+ expect(outer.getTextContent()).toContain('After');
+ expect(nested?.getTextContent()).toContain('Inner');
+ });
+ });
+});
diff --git a/js/lexical-core/tests/mentions.test.ts b/js/lexical-core/tests/mentions.test.ts
index b73120179c..b022e3e2a7 100644
--- a/js/lexical-core/tests/mentions.test.ts
+++ b/js/lexical-core/tests/mentions.test.ts
@@ -7,6 +7,7 @@ import {
parseDocumentMentions,
parseGroupMentions,
parseLinks,
+ parsePullRequestMentions,
parseUserMentions,
} from '../utils/parsers';
@@ -99,6 +100,24 @@ describe('parseDocumentMentions', () => {
});
});
+describe('parsePullRequestMentions', () => {
+ it('extracts the label from a PR mention', () => {
+ const input =
+ '<m-pr-mention>{"id":"foreign-1","label":"macro/macro#123 Fix bug"}</m-pr-mention>';
+ expect(parsePullRequestMentions(input)).toBe('macro/macro#123 Fix bug');
+ });
+
+ it('falls back to the id when label is missing', () => {
+ const input = '<m-pr-mention>{"id":"foreign-1"}</m-pr-mention>';
+ expect(parsePullRequestMentions(input)).toBe('foreign-1');
+ });
+
+ it('returns empty string for invalid JSON', () => {
+ const input = '<m-pr-mention>???</m-pr-mention>';
+ expect(parsePullRequestMentions(input)).toBe('');
+ });
+});
+
describe('parseLinks', () => {
it('extracts text from link', () => {
const input =
@@ -182,6 +201,12 @@ describe('markdownToPlainText', () => {
expect(markdownToPlainText(input)).toBe('Hey @here, check this out!');
});
+ it('handles text with PR mentions', () => {
+ const input =
+ 'See <m-pr-mention>{"id":"foreign-1","label":"macro/macro#123"}</m-pr-mention>.';
+ expect(markdownToPlainText(input)).toBe('See macro/macro#123.');
+ });
+
it('returns original text when no mentions present', () => {
const input = 'Just plain text here.';
expect(markdownToPlainText(input)).toBe('Just plain text here.');
@@ -219,6 +244,14 @@ describe('markdownToEmbeddingText', () => {
expect(markdownToEmbeddingText(input)).toBe('[Spec](md:doc-2)');
});
+ it('keeps ids from PR mentions', () => {
+ const input =
+ 'See <m-pr-mention>{"id":"foreign-1","label":"macro/macro#123"}</m-pr-mention>.';
+ expect(markdownToEmbeddingText(input)).toBe(
+ 'See [macro/macro#123](pr:foreign-1).'
+ );
+ });
+
it('keeps link urls', () => {
const input =
'See <m-link>{"url":"https://example.com","text":"this link"}</m-link>.';
@@ -254,9 +287,9 @@ describe('markdownToEmbeddingText', () => {
const payload = btoa(
'{"documentId":"doc-3","documentName":"Spec","blockName":"md"}'
);
- expect(
- markdownToEmbeddingText(`<m-snapshot>${payload}</m-snapshot>`)
- ).toBe('[Spec](md:doc-3)');
+ expect(markdownToEmbeddingText(`<m-snapshot>${payload}</m-snapshot>`)).toBe(
+ '[Spec](md:doc-3)'
+ );
});
it('keeps stable ids for dss images and urls for videos', () => {
@@ -289,9 +322,7 @@ describe('markdownToEmbeddingText', () => {
it('unwraps email thread embeds and resolves mentions inside them', () => {
const input =
'<m-email-thread-embed>{"tag":"div","classes":["macro_quote"]}From <m-contact-mention>{"name":"Ness Chu"}</m-contact-mention>:\\nplease fix</m-email-thread-embed>';
- expect(markdownToEmbeddingText(input)).toBe(
- 'From Ness Chu:\nplease fix'
- );
+ expect(markdownToEmbeddingText(input)).toBe('From Ness Chu:\nplease fix');
});
it('drops watermarks and unrecognized m-* tags entirely', () => {
diff --git a/js/lexical-core/transformers/classedBlock.ts b/js/lexical-core/transformers/classedBlock.ts
index ff7fe5edf4..3c82d29d49 100644
--- a/js/lexical-core/transformers/classedBlock.ts
+++ b/js/lexical-core/transformers/classedBlock.ts
@@ -2,9 +2,11 @@ import {
$convertFromMarkdownString,
$convertToMarkdownString,
type ElementTransformer,
+ type MultilineElementTransformer,
TRANSFORMERS,
} from '@lexical/markdown';
-import type { LexicalNode } from 'lexical';
+import { $createQuoteNode, QuoteNode } from '@lexical/rich-text';
+import type { ElementNode, LexicalNode } from 'lexical';
import {
$createClassedBlockNode,
$isClassedBlockNode,
@@ -21,6 +23,9 @@ import { xmlMatcher } from './transformers';
const TAG_MACRO_QUOTE = 'm-email-thread-embed';
const REG_EXP_XML_MACRO_QUOTE = xmlMatcher(TAG_MACRO_QUOTE, '');
+const REG_EXP_HTML_BLOCKQUOTE_START = /^\s*<blockquote\b[^>]*>\s*(.*)$/i;
+const REG_EXP_HTML_BLOCKQUOTE_END = /^(.*?)\s*<\/blockquote>\s*$/i;
+const REG_EXP_HTML_BLOCKQUOTE_TAG = /<\/?blockquote\b[^>]*>/gi;
// Transformers used inside macro_quote blocks
const MACRO_QUOTE_TRANSFORMERS = [
@@ -32,6 +37,149 @@ const MACRO_QUOTE_TRANSFORMERS = [
...TRANSFORMERS,
];
+function htmlBlockquoteTransformers() {
+ return [
+ HTML_BLOCKQUOTE,
+ ...CUSTOM_TRANSFORMERS,
+ I_EQUATION_NODE,
+ I_USER_MENTION,
+ I_DOCUMENT_MENTION,
+ I_CONTACT_MENTION,
+ ...TRANSFORMERS,
+ ];
+}
+
+function htmlBlockquoteContent(
+ startMatch: Array<string>,
+ endMatch: Array<string> | null,
+ linesInBetween: Array<string> | null
+): string {
+ return [startMatch[1] ?? '', ...(linesInBetween ?? []), endMatch?.[1] ?? '']
+ .join('\n')
+ .replace(/<br\s*\/?>/gi, '\n')
+ .trim();
+}
+
+function consumeHtmlBlockquoteLine(
+ line: string,
+ startingDepth: number
+): {
+ closed: boolean;
+ depth: number;
+ text: string;
+} {
+ let depth = startingDepth;
+ let cursor = 0;
+ let text = '';
+ REG_EXP_HTML_BLOCKQUOTE_TAG.lastIndex = 0;
+
+ for (const match of line.matchAll(REG_EXP_HTML_BLOCKQUOTE_TAG)) {
+ const tag = match[0];
+ const index = match.index ?? 0;
+ const isClosingTag = tag.startsWith('</');
+
+ if (isClosingTag) {
+ depth -= 1;
+ if (depth === 0) {
+ text += line.slice(cursor, index);
+ return { closed: true, depth, text };
+ }
+ text += line.slice(cursor, index + tag.length);
+ cursor = index + tag.length;
+ continue;
+ }
+
+ depth += 1;
+ text += line.slice(cursor, index + tag.length);
+ cursor = index + tag.length;
+ }
+
+ text += line.slice(cursor);
+ return { closed: false, depth, text };
+}
+
+function createHtmlBlockquoteNode(content: string): LexicalNode | false {
+ const quoteNode = $createQuoteNode();
+ const normalized = content.replace(/<br\s*\/?>/gi, '\n').trim();
+ if (!normalized) return false;
+
+ $convertFromMarkdownString(
+ normalized,
+ htmlBlockquoteTransformers(),
+ quoteNode
+ );
+ return quoteNode;
+}
+
+function importHtmlBlockquote(
+ lines: Array<string>,
+ rootNode: ElementNode,
+ startLineIndex: number,
+ startMatch: RegExpMatchArray
+): [boolean, number] | null {
+ let depth = 1;
+ const contentLines: string[] = [];
+
+ for (let index = startLineIndex; index < lines.length; index++) {
+ const line =
+ index === startLineIndex ? (startMatch[1] ?? '') : lines[index];
+ const consumed = consumeHtmlBlockquoteLine(line, depth);
+ depth = consumed.depth;
+ contentLines.push(consumed.text);
+
+ if (consumed.closed) {
+ const quoteNode = createHtmlBlockquoteNode(contentLines.join('\n'));
+ if (!quoteNode) return null;
+ rootNode.append(quoteNode);
+ return [true, index];
+ }
+ }
+
+ return null;
+}
+
+export const HTML_BLOCKQUOTE: MultilineElementTransformer = {
+ dependencies: [QuoteNode],
+ type: 'multiline-element',
+ regExpStart: REG_EXP_HTML_BLOCKQUOTE_START,
+ regExpEnd: REG_EXP_HTML_BLOCKQUOTE_END,
+ export: () => null,
+ handleImportAfterStartMatch: ({
+ lines,
+ rootNode,
+ startLineIndex,
+ startMatch,
+ }) => importHtmlBlockquote(lines, rootNode, startLineIndex, startMatch),
+ replace: (
+ rootNode,
+ children,
+ startMatch,
+ endMatch,
+ linesInBetween,
+ _isImport
+ ) => {
+ const quoteNode = $createQuoteNode();
+
+ if (children?.length) {
+ quoteNode.append(...children);
+ } else {
+ const content = htmlBlockquoteContent(
+ startMatch,
+ endMatch,
+ linesInBetween
+ );
+ if (!content) return false;
+ $convertFromMarkdownString(
+ content,
+ htmlBlockquoteTransformers(),
+ quoteNode
+ );
+ }
+
+ rootNode.append(quoteNode);
+ },
+};
+
export const I_MACRO_QUOTE: ElementTransformer = {
dependencies: [ClassedBlockNode],
type: 'element',
diff --git a/js/lexical-core/transformers/index.ts b/js/lexical-core/transformers/index.ts
index 61def58cf3..43a0e3afb4 100644
--- a/js/lexical-core/transformers/index.ts
+++ b/js/lexical-core/transformers/index.ts
@@ -1,6 +1,6 @@
import type { Transformer } from '@lexical/markdown';
import { I_AWAIT_NODE } from './await';
-import { I_MACRO_QUOTE } from './classedBlock';
+import { HTML_BLOCKQUOTE, I_MACRO_QUOTE } from './classedBlock';
import { CUSTOM_TRANSFORMERS } from './customTransformers';
import { I_IMAGE_CONSTRAINED, IMAGE } from './image';
import {
@@ -15,12 +15,14 @@ import {
E_DOCUMENT_CARD,
E_DOCUMENT_MENTION,
E_GROUP_MENTION,
+ E_PR_MENTION,
E_USER_MENTION,
I_CONTACT_MENTION,
I_DATE_MENTION,
I_DOCUMENT_CARD,
I_DOCUMENT_MENTION,
I_GROUP_MENTION,
+ I_PR_MENTION,
I_THEME_MENTION,
I_USER_MENTION,
} from './mentions';
@@ -61,10 +63,12 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_GROUP_MENTION,
I_DOCUMENT_MENTION,
I_DOCUMENT_CARD,
+ I_PR_MENTION,
I_CONTACT_MENTION,
I_DATE_MENTION,
I_AWAIT_NODE,
I_TABLE_NODE,
+ HTML_BLOCKQUOTE,
I_MACRO_QUOTE,
I_EQUATION_NODE,
I_THEME_MENTION,
@@ -83,12 +87,15 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
IMAGE,
BR_TAG_TO_LINE_BREAK,
E_TABLE_NODE,
+ HTML_BLOCKQUOTE,
E_USER_MENTION,
E_GROUP_MENTION,
I_DOCUMENT_MENTION, // for chat attachments
E_DOCUMENT_MENTION,
I_DOCUMENT_CARD, // for internal representation
E_DOCUMENT_CARD,
+ I_PR_MENTION,
+ E_PR_MENTION,
E_CONTACT_MENTION,
E_DATE_MENTION,
// order matters
@@ -118,6 +125,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
BR_TAG_TO_LINE_BREAK,
I_TABLE_NODE,
E_TABLE_NODE,
+ HTML_BLOCKQUOTE,
E_SNAPSHOT_NODE,
I_USER_MENTION,
E_USER_MENTION,
@@ -127,6 +135,8 @@ export const ALL_TRANSFORMERS: Transformer[] = [
E_DOCUMENT_MENTION,
I_DOCUMENT_CARD,
E_DOCUMENT_CARD,
+ I_PR_MENTION,
+ E_PR_MENTION,
I_CONTACT_MENTION,
E_CONTACT_MENTION,
I_DATE_MENTION,
diff --git a/js/lexical-core/transformers/mentions.ts b/js/lexical-core/transformers/mentions.ts
index b3589cd68b..460371e80b 100644
--- a/js/lexical-core/transformers/mentions.ts
+++ b/js/lexical-core/transformers/mentions.ts
@@ -8,6 +8,7 @@ import { DateMentionNode } from '../nodes/DateMentionNode';
import { DocumentCardNode } from '../nodes/DocumentCardNode';
import { DocumentMentionNode } from '../nodes/DocumentMentionNode';
import { GroupMentionNode } from '../nodes/GroupMentionNode';
+import { PullRequestMentionNode } from '../nodes/PullRequestMentionNode';
import { ThemeMentionNode } from '../nodes/ThemeMentionNode';
import { UserMentionNode } from '../nodes/UserMentionNode';
@@ -237,6 +238,17 @@ function cleanHostname(rawHostname: string): string {
return hostname;
}
+function currentBrowserHostname(): string | null {
+ if (
+ typeof window === 'undefined' ||
+ !window.location ||
+ !window.location.hostname
+ ) {
+ return null;
+ }
+ return cleanHostname(window.location.hostname);
+}
+
export const E_DOCUMENT_MENTION: ElementTransformer = {
dependencies: [DocumentMentionNode],
type: 'element',
@@ -266,6 +278,69 @@ export const E_DOCUMENT_MENTION: ElementTransformer = {
},
};
+// Internal Pull Request Mentions
+
+export const I_PR_MENTION: TextMatchTransformer = {
+ dependencies: [PullRequestMentionNode],
+ type: 'text-match',
+ regExp: /<m-pr-mention>(.*?)<\/m-pr-mention>/,
+ importRegExp: /<m-pr-mention>(.*?)<\/m-pr-mention>/,
+ export: (node) => {
+ if (!(node instanceof PullRequestMentionNode)) return null;
+ const data = JSON.stringify({
+ id: node.getId(),
+ label: node.getLabel(),
+ mentionUuid: node.getMentionUuid(),
+ });
+ return `<m-pr-mention>${data}</m-pr-mention>`;
+ },
+ replace: (node: TextNode, match: RegExpMatchArray) => {
+ try {
+ const data = JSON.parse(match[1]);
+ if (!('id' in data) || typeof data.id !== 'string') {
+ throw new Error('Missing field id');
+ }
+ const prMentionNode = new PullRequestMentionNode(
+ data.id,
+ typeof data.label === 'string' ? data.label : undefined,
+ typeof data.mentionUuid === 'string' ? data.mentionUuid : undefined
+ );
+ node.replace(prMentionNode);
+ } catch (e) {
+ console.error('Error in I_PR_MENTION replace:', e);
+ }
+ },
+};
+
+// External Pull Request Mentions
+
+export const E_PR_MENTION: ElementTransformer = {
+ dependencies: [PullRequestMentionNode],
+ type: 'element',
+ regExp: /$^/,
+ export: (node) => {
+ if (!(node instanceof PullRequestMentionNode)) return null;
+
+ const id = node.getId();
+ if (!id) return null;
+
+ const label = node.getLabel() || 'Pull request';
+ const hostname = currentBrowserHostname();
+ if (!hostname) return label;
+
+ const prUrl = `https://${hostname}/app/pr/${id}`;
+ return `[${label}](${prUrl})`;
+ },
+ replace: (
+ _parentNode: ElementNode,
+ _children: Array<LexicalNode>,
+ _match: Array<string>,
+ _isImport: boolean
+ ) => {
+ return false;
+ },
+};
+
// Internal Group Mentions (e.g., @here)
export const I_GROUP_MENTION: TextMatchTransformer = {
dependencies: [GroupMentionNode],
diff --git a/js/lexical-core/utils/mentions.ts b/js/lexical-core/utils/mentions.ts
index e0e3c47ab4..c353aab66b 100644
--- a/js/lexical-core/utils/mentions.ts
+++ b/js/lexical-core/utils/mentions.ts
@@ -18,6 +18,11 @@ import {
$isGroupMentionNode,
type GroupMentionNode,
} from '../nodes/GroupMentionNode';
+import {
+ $isPullRequestMentionNode,
+ type PullRequestMentionInfo,
+ type PullRequestMentionNode,
+} from '../nodes/PullRequestMentionNode';
import {
$isUserMentionNode,
type UserMentionInfo,
@@ -39,6 +44,7 @@ export type MentionNode =
| DocumentMentionNode
| ContactMentionNode
| DateMentionNode
+ | PullRequestMentionNode
| GroupMentionNode;
export function $isMentionNode(node: LexicalNode): node is MentionNode {
@@ -47,6 +53,7 @@ export function $isMentionNode(node: LexicalNode): node is MentionNode {
$isDocumentMentionNode(node) ||
$isContactMentionNode(node) ||
$isDateMentionNode(node) ||
+ $isPullRequestMentionNode(node) ||
$isGroupMentionNode(node)
);
}
@@ -65,6 +72,7 @@ export function $extractAllMentions(): MentionNode[] {
export type MentionInfo =
| (UserMentionInfo & { type: 'user' })
| (DocumentMentionInfo & { type: 'document' })
+ | (PullRequestMentionInfo & { type: 'pr' })
| (ContactMentionInfo & { type: 'contact' })
| (DateMentionInfo & { type: 'date' });
@@ -74,6 +82,8 @@ export function buildMentionMarkdownString(info: MentionInfo): string {
return wrapXml('m-user-mention', dropKey(info, 'type'));
case 'document':
return wrapXml('m-document-mention', dropKey(info, 'type'));
+ case 'pr':
+ return wrapXml('m-pr-mention', dropKey(info, 'type'));
case 'contact':
return wrapXml('m-contact-mention', dropKey(info, 'type'));
case 'date':
@@ -89,5 +99,6 @@ export {
parseDocumentMentions,
parseGroupMentions,
parseLinks,
+ parsePullRequestMentions,
parseUserMentions,
} from './parsers';
diff --git a/js/lexical-core/utils/parsers.ts b/js/lexical-core/utils/parsers.ts
index 441d995041..51ee7f9f2f 100644
--- a/js/lexical-core/utils/parsers.ts
+++ b/js/lexical-core/utils/parsers.ts
@@ -48,6 +48,17 @@ export function parseDocumentMentions(text: string): string {
);
}
+export function parsePullRequestMentions(text: string): string {
+ return text.replace(/<m-pr-mention>(.*?)<\/m-pr-mention>/g, (_, json) => {
+ try {
+ const data = JSON.parse(json);
+ return data.label || data.id || '';
+ } catch {
+ return '';
+ }
+ });
+}
+
export function parseLinks(text: string): string {
return text.replace(/<m-link>(.*?)<\/m-link>/g, (_, json) => {
try {
@@ -120,9 +131,13 @@ export function markdownToPlainText(markdown: string): string {
return parseLinks(
parseDocumentCards(
parseSnapshots(
- parseDocumentMentions(
- parseGroupMentions(
- parseDateMentions(parseContactMentions(parseUserMentions(markdown)))
+ parsePullRequestMentions(
+ parseDocumentMentions(
+ parseGroupMentions(
+ parseDateMentions(
+ parseContactMentions(parseUserMentions(markdown))
+ )
+ )
)
)
)
@@ -139,6 +154,7 @@ type MentionTagPayload = {
documentName?: string;
blockName?: string;
blockParams?: { channel_message_id?: string };
+ label?: string;
url?: string;
text?: string;
alt?: string;
@@ -161,16 +177,13 @@ function replaceJsonTag(
tag: string,
render: (data: MentionTagPayload) => string
): string {
- return text.replace(
- new RegExp(`<${tag}>(.*?)</${tag}>`, 'gs'),
- (_, json) => {
- try {
- return render(JSON.parse(json));
- } catch {
- return '';
- }
+ return text.replace(new RegExp(`<${tag}>(.*?)</${tag}>`, 'gs'), (_, json) => {
+ try {
+ return render(JSON.parse(json));
+ } catch {
+ return '';
}
- );
+ });
}
function documentRefToEmbeddingText(data: MentionTagPayload): string {
@@ -261,6 +274,11 @@ export function markdownToEmbeddingText(markdown: string): string {
// Leaf tags.
text = replaceJsonTag(text, 'm-document-mention', documentRefToEmbeddingText);
text = replaceJsonTag(text, 'm-document-card', documentRefToEmbeddingText);
+ text = replaceJsonTag(text, 'm-pr-mention', (data) =>
+ data.id
+ ? `[${data.label || 'Pull request'}](pr:${data.id})`
+ : data.label || ''
+ );
text = replaceJsonTag(text, 'm-link', (data) =>
data.url ? `[${data.text || data.url}](${data.url})` : data.text || ''
);
@@ -273,15 +291,27 @@ export function markdownToEmbeddingText(markdown: string): string {
text = replaceJsonTag(text, 'm-video', (data) =>
data.url ? `[video](${data.url})` : ''
);
- text = replaceJsonTag(text, 'm-katex-equation', (data) => data.equation || '');
+ text = replaceJsonTag(
+ text,
+ 'm-katex-equation',
+ (data) => data.equation || ''
+ );
text = replaceJsonTag(text, 'm-user-mention', (data) => data.email || '');
text = replaceJsonTag(
text,
'm-contact-mention',
(data) => data.name || data.emailOrDomain || ''
);
- text = replaceJsonTag(text, 'm-date-mention', (data) => data.displayFormat || '');
- text = replaceJsonTag(text, 'm-group-mention', (data) => `@${data.groupAlias || ''}`);
+ text = replaceJsonTag(
+ text,
+ 'm-date-mention',
+ (data) => data.displayFormat || ''
+ );
+ text = replaceJsonTag(
+ text,
+ 'm-group-mention',
+ (data) => `@${data.groupAlias || ''}`
+ );
text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');
text = replaceJsonTag(text, 'm-await', (data) => data.text || '');
text = replaceJsonTag(text, 'm-watermark', () => '');