The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { m } from "../i18n/messages"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { msg, T, useGT, useMessages } from "gt-react"; |
| 4 | import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks"; |
| 5 | import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment"; |
| 6 | import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks"; |
| 7 | import { |
| 8 | isMarkdownFileLinkLabel, |
| 9 | isWindowsDrivePathHref, |
| 10 | shouldRenderMarkdownImageAsFileLink, |
| 11 | normalizeMarkdownLinkDestination, |
| 12 | extractInlineCodeSpans, |
| 13 | extractMarkdownLinkHrefs, |
| 14 | inlineCodeFilePathCandidate, |
| 15 | } from "@t3tools/shared/markdownLinks"; |
| 16 | import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; |
| 17 | import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; |
| 18 | import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; |
| 19 | import { |
| 20 | AuthFilesystemReadScope, |
| 21 | AuthOrchestrationOperateScope, |
| 22 | SOURCE_CONTROL_MEDIA_ASSET, |
| 23 | } from "@t3tools/contracts"; |
| 24 | import { |
| 25 | CHAT_MARKDOWN_REMARK_PLUGINS, |
| 26 | CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, |
| 27 | CHAT_MARKDOWN_REHYPE_PLUGINS, |
| 28 | chatMarkdownImageSource, |
| 29 | decodeMarkdownLinkEscapes, |
| 30 | remarkAssistantInsights, |
| 31 | } from "@t3tools/shared/markdownPipeline"; |
| 32 | import { useAtomValue } from "@effect/atom-react"; |
| 33 | import { |
| 34 | COMPOSER_CONTEXT_CLIPBOARD_MIME, |
| 35 | encodeComposerContextClipboardHtml, |
| 36 | } from "@t3tools/shared/composerContextClipboard"; |
| 37 | import { |
| 38 | FileSpreadsheetIcon, |
| 39 | FileTextIcon, |
| 40 | GlobeIcon, |
| 41 | ImageIcon, |
| 42 | InfoIcon, |
| 43 | LightbulbIcon, |
| 44 | MailIcon, |
| 45 | MessageSquareIcon, |
| 46 | MessageSquareWarningIcon, |
| 47 | OctagonAlertIcon, |
| 48 | PresentationIcon, |
| 49 | StarIcon, |
| 50 | TriangleAlertIcon, |
| 51 | type LucideIcon, |
| 52 | } from "lucide-react"; |
| 53 | import { |
| 54 | AssetWorkspaceAssetNotFoundError, |
| 55 | AuthPreviewOperateScope, |
| 56 | type EditorId, |
| 57 | type EnvironmentId, |
| 58 | type ServerConfig, |
| 59 | type ScopedThreadRef, |
| 60 | type ServerProviderSkill, |
| 61 | type ThreadPullRequestKey, |
| 62 | } from "@t3tools/contracts"; |
| 63 | import { |
| 64 | isAtomCommandInterrupted, |
| 65 | squashAtomCommandFailure, |
| 66 | } from "@t3tools/client-runtime/state/runtime"; |
| 67 | import { scopedThreadKey } from "@t3tools/client-runtime/environment"; |
| 68 | import type { |
| 69 | CodexArtifactTemplate, |
| 70 | CodexArtifactTemplateKind, |
| 71 | } from "@t3tools/shared/codexArtifactTemplates"; |
| 72 | import { codexArtifactTemplatePresentationLabel } from "@t3tools/shared/codexArtifactTemplatesCopy"; |
| 73 | import { |
| 74 | classifyMarkdownImageSource, |
| 75 | markdownImageSourceFragment, |
| 76 | } from "@t3tools/client-runtime/markdown-images"; |
| 77 | import { mediaUrlReference } from "@t3tools/client-runtime/media-reference"; |
| 78 | import { mediaKindFromPath, mediaMimeTypeFromExtension } from "@t3tools/shared/mediaPreview"; |
| 79 | import { InlineAudioPreview } from "./files/InlineAudioPreview"; |
| 80 | import { HostImageUrlContext } from "./chat/hostImageUrl"; |
| 81 | import * as Cause from "effect/Cause"; |
| 82 | import * as Option from "effect/Option"; |
| 83 | import * as Schema from "effect/Schema"; |
| 84 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 85 | import React, { |
| 86 | Suspense, |
| 87 | type ComponentProps, |
| 88 | type ClipboardEvent as ReactClipboardEvent, |
| 89 | use, |
| 90 | memo, |
| 91 | useEffect, |
| 92 | useLayoutEffect, |
| 93 | useRef, |
| 94 | useState, |
| 95 | type ReactNode, |
| 96 | } from "react"; |
| 97 | import type { |
| 98 | Components, |
| 99 | ExtraProps as ReactMarkdownExtraProps, |
| 100 | Options as ReactMarkdownOptions, |
| 101 | } from "react-markdown"; |
| 102 | import { createIncrementalMarkdownPlugin } from "../markdown-incremental"; |
| 103 | import type { Pluggable, PluggableList } from "unified"; |
| 104 | import { defaultUrlTransform } from "react-markdown"; |
| 105 | import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations"; |
| 106 | import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences"; |
| 107 | import { parseThreadLinkHref } from "@t3tools/shared/threadLinks"; |
| 108 | import { AssistantCitationEmbed } from "./chat/AssistantCitationChip"; |
| 109 | import { MarkdownThreadLink } from "./chat/MarkdownThreadLink"; |
| 110 | import { mathKind } from "@t3tools/shared/markdownMath"; |
| 111 | import remarkMath from "remark-math"; |
| 112 | import { |
| 113 | artifactTemplateFromHastProperties, |
| 114 | renderCodexInlineDirectivesAsMarkdown, |
| 115 | } from "@t3tools/shared/codexMarkdownDirectives"; |
| 116 | import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; |
| 117 | import { MarkdownMath } from "./chat/MarkdownMath"; |
| 118 | import { |
| 119 | resolveMarkdownMediaPreview, |
| 120 | type ExpandedImagePreview, |
| 121 | } from "./chat/ExpandedImagePreview"; |
| 122 | import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; |
| 123 | import { markdownImageGallery } from "./chat/markdownImageGallery"; |
| 124 | import { type MediaActionSource } from "./media/MediaActions"; |
| 125 | import { resolveProtocolRelativeMediaUrl } from "./media/mediaContent"; |
| 126 | import { |
| 127 | revealInFileExplorerLabelForKind, |
| 128 | revealInFileExplorerLabelForOs, |
| 129 | } from "./preview/fileExplorerLabel"; |
| 130 | import { |
| 131 | resolveExternalWebLinkHost, |
| 132 | showExternalLinkContextMenu, |
| 133 | } from "./chat/externalLinkContextMenu"; |
| 134 | import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; |
| 135 | import { Button } from "./ui/button"; |
| 136 | import { stackedThreadToast, toastManager } from "./ui/toast"; |
| 137 | import { recordVisitForThread } from "../browserHistoryStore"; |
| 138 | import { contextMenuSourceOf } from "../contextMenuSource"; |
| 139 | import { |
| 140 | PreferredEditorEnvironmentRequiredError, |
| 141 | useOpenInPreferredEditor, |
| 142 | usePreferredEditor, |
| 143 | } from "../editorPreferences"; |
| 144 | import { openInEditorMenuLabel } from "../editorLabels"; |
| 145 | import { resolveDiffThemeName } from "../lib/diffRendering"; |
| 146 | import { RenderErrorBoundary } from "./RenderErrorBoundary"; |
| 147 | import { useRenderedAppearance } from "../hooks/useTheme"; |
| 148 | import { useClientSettings } from "../hooks/useSettings"; |
| 149 | import { chatMarkdownClipboardPayload } from "../markdown-clipboard"; |
| 150 | import { |
| 151 | isLocalEditorFileHref, |
| 152 | resolveInlineCodeFileLinkMeta, |
| 153 | resolveMarkdownFileLinkMeta, |
| 154 | rewriteMarkdownFileUriHref, |
| 155 | type MarkdownFileLinkMeta, |
| 156 | } from "../markdown-links"; |
| 157 | import { |
| 158 | markdownFileCopyPaths, |
| 159 | markdownFileEditorTarget, |
| 160 | resolveMarkdownFileHostPath, |
| 161 | } from "../markdownFileHostPath"; |
| 162 | import { isElectron } from "../env"; |
| 163 | import { readLocalApi } from "../localApi"; |
| 164 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 165 | import { hostEnvironmentIdAtom } from "../state/primaryEnvironment"; |
| 166 | import { cn } from "../lib/utils"; |
| 167 | import { resolveRemoteOpenState, useRemoteOpenResolution } from "../remoteOpen"; |
| 168 | import { rightPanelHostRef, useRightPanelStore } from "../rightPanelStore"; |
| 169 | import { useOpenIssueLink } from "../lib/openIssueLink"; |
| 170 | import { issueTrackerEnvironment } from "../state/issueTrackers"; |
| 171 | import { useEnvironmentQuery } from "../state/query"; |
| 172 | import { readThreadShell, useProjects } from "../state/entities"; |
| 173 | import { serverEnvironment } from "../state/server"; |
| 174 | import { shellEnvironment } from "../state/shell"; |
| 175 | import { assetEnvironment } from "../state/assets"; |
| 176 | import { |
| 177 | readEnvironmentScope, |
| 178 | readPreparedConnection, |
| 179 | useEnvironmentScope, |
| 180 | } from "../state/session"; |
| 181 | import { previewEnvironment } from "../state/preview"; |
| 182 | import { useAtomCommand } from "../state/use-atom-command"; |
| 183 | import { useAtomQueryRunner } from "../state/use-atom-query-runner"; |
| 184 | import { projectEnvironment } from "../state/projects"; |
| 185 | import { filesystemEnvironment } from "../state/filesystem"; |
| 186 | import { |
| 187 | findAgentDirectoryMatch, |
| 188 | needsWorkspaceBasenameLookup, |
| 189 | pickProjectLinkMatch, |
| 190 | pickWorkspaceLinkMatch, |
| 191 | WORKSPACE_BASENAME_LOOKUP_LIMIT, |
| 192 | workspaceLinkLookupQuery, |
| 193 | } from "@t3tools/client-runtime/workspace-basename-lookup"; |
| 194 | import { resolvePullRequestPreviewTarget } from "@t3tools/client-runtime/change-request-links"; |
| 195 | import { |
| 196 | mayContainStandaloneIssueLink, |
| 197 | resolveIssueLinkTarget, |
| 198 | } from "@t3tools/client-runtime/issue-links"; |
| 199 | import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; |
| 200 | import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink"; |
| 201 | import { textDirection } from "~/textDirection"; |
| 202 | import { useOpenLink } from "../browser/useOpenLink"; |
| 203 | import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; |
| 204 | import { isPreviewAvailableFor } from "../browser/previewRuntime"; |
| 205 | import { |
| 206 | isBrowserPreviewFile, |
| 207 | openFileInPreview, |
| 208 | openUrlInPreview, |
| 209 | BrowserPreviewUnavailableError, |
| 210 | isBrowserSettingsReadError, |
| 211 | } from "../browser/openFileInPreview"; |
| 212 | import { resolveLinkTarget } from "../browser/browserLinkTarget"; |
| 213 | import { PullRequestLinkPreview } from "./pullRequest/PullRequestLinkPreview"; |
| 214 | import { IssueLinkPreview, IssueLinkPreviewFallback } from "./issue/IssueLinkPreview"; |
| 215 | import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBlock"; |
| 216 | import { createMarkdownRenderer } from "./chat/markdownRenderer"; |
| 217 | import { splitMarkdownBlocks } from "./chat/markdownStreamBlocks"; |
| 218 | import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock"; |
| 219 | import { MarkdownTable } from "./chat/MarkdownTable"; |
| 220 | import { MarkdownDetails } from "./chat/MarkdownDetails"; |
| 221 | import { |
| 222 | authoredImageSizeStyle, |
| 223 | ChatMarkdownAssetImage, |
| 224 | ChatMarkdownImage, |
| 225 | ChatMarkdownImageFallback, |
| 226 | ChatMarkdownVideo, |
| 227 | MarkdownLinkContext, |
| 228 | markdownImageCopy, |
| 229 | } from "./chat/ChatMarkdownMedia"; |
| 230 | import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink"; |
| 231 | import { MarkdownFileLink } from "./chat/MarkdownFileLink"; |
| 232 | import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic"; |
| 233 | import { rehypeChipPunctuation } from "./chat/markdownChipPunctuation"; |
| 234 | import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments"; |
| 235 | import { rehypeTextDirection } from "./chat/markdownTextDirection"; |
| 236 | import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic"; |
| 237 | import { |
| 238 | extractCodeBlock, |
| 239 | extractFenceLanguage, |
| 240 | extractFenceTitle, |
| 241 | extractPreCodeMeta, |
| 242 | isClosedCodeFence, |
| 243 | nodeToPlainText, |
| 244 | } from "./chat/MarkdownCodeBlock.logic"; |
| 245 | import { reportMarkdownActionFailure } from "./chat/markdownActionFailure"; |
| 246 | |
| 247 | const isAssetNotFoundError = Schema.is(AssetWorkspaceAssetNotFoundError); |
| 248 | |
| 249 | interface ChatMarkdownProps { |
| 250 | renderInsights?: boolean; |
| 251 | /** Compact markdown transforms remove blocks before rendering inside a label. */ |
| 252 | inline?: boolean; |
| 253 | text: string; |
| 254 | cwd: string | undefined; |
| 255 | /** Folders the agent worked in before writing `text`, the latest first; read when a link opens. */ |
| 256 | agentDirectories?: (() => ReadonlyArray<string>) | undefined; |
| 257 | threadRef?: ScopedThreadRef | undefined; |
| 258 | pullRequestPanelRef?: ScopedThreadRef | undefined; |
| 259 | environmentId?: EnvironmentId | undefined; |
| 260 | onTaskListChange?: ((input: { markerOffset: number; checked: boolean }) => void) | undefined; |
| 261 | isStreaming?: boolean; |
| 262 | skills?: ReadonlyArray<ServerProviderSkill>; |
| 263 | className?: string; |
| 264 | lineBreaks?: boolean; |
| 265 | parseRawHtml?: boolean; |
| 266 | onUseArtifactTemplate?: ((template: CodexArtifactTemplate) => void) | undefined; |
| 267 | onRunShellCommand?: ((command: string) => void) | undefined; |
| 268 | imageBaseDir?: string | undefined; |
| 269 | workspaceMutationId?: string | null | undefined; |
| 270 | onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; |
| 271 | /** Keep one list per configuration (a module constant): it keys the shared parse cache. */ |
| 272 | extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>; |
| 273 | renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined; |
| 274 | /** Loads media a source control host keeps behind a credential through the server, which holds |
| 275 | `cwd`'s; without it a private repository's uploads load unauthenticated and 404. */ |
| 276 | sourceControlMedia?: boolean | undefined; |
| 277 | /** The change request's repository, when it can differ from the checkout at `cwd`. */ |
| 278 | sourceControlMediaRepository?: string | undefined; |
| 279 | headingLevelOffset?: number | undefined; |
| 280 | } |
| 281 | |
| 282 | export interface ChatMarkdownContextReference { |
| 283 | kind: string; |
| 284 | contextId: string; |
| 285 | label: string; |
| 286 | /** Whether it starts or ends its block, for a reference that renders as a block. */ |
| 287 | leading?: boolean; |
| 288 | trailing?: boolean; |
| 289 | } |
| 290 | |
| 291 | const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<ServerProviderSkill> = []; |
| 292 | const EMPTY_REMARK_PLUGINS: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = []; |
| 293 | |
| 294 | const ARTIFACT_TEMPLATE_ICON_BY_KIND = { |
| 295 | document: FileTextIcon, |
| 296 | presentation: PresentationIcon, |
| 297 | spreadsheet: FileSpreadsheetIcon, |
| 298 | site: GlobeIcon, |
| 299 | "google-docs": FileTextIcon, |
| 300 | "google-slides": PresentationIcon, |
| 301 | "google-sheets": FileSpreadsheetIcon, |
| 302 | image: ImageIcon, |
| 303 | email: MailIcon, |
| 304 | slack: MessageSquareIcon, |
| 305 | } satisfies Record<CodexArtifactTemplateKind, LucideIcon>; |
| 306 | |
| 307 | function CodexArtifactTemplateCard(props: { |
| 308 | readonly template: CodexArtifactTemplate; |
| 309 | readonly onUse?: ((template: CodexArtifactTemplate) => void) | undefined; |
| 310 | }) { |
| 311 | const gt = useGT(); |
| 312 | const messages = useMessages(); |
| 313 | const Icon = ARTIFACT_TEMPLATE_ICON_BY_KIND[props.template.artifactKind]; |
| 314 | const presentationLabel = codexArtifactTemplatePresentationLabel( |
| 315 | props.template.artifactKind, |
| 316 | messages, |
| 317 | ); |
| 318 | |
| 319 | return ( |
| 320 | <div |
| 321 | role="group" |
| 322 | aria-label={gt("{name} template", { name: props.template.displayName })} |
| 323 | dir={textDirection(props.template.displayName)} |
| 324 | data-chat-markdown-artifact-template |
| 325 | className="my-[0.65rem] flex w-full min-w-0 items-center gap-3 rounded-xl border border-border/70 bg-card/60 px-3 py-2.5 text-foreground shadow-xs" |
| 326 | data-artifact-kind={props.template.artifactKind} |
| 327 | data-markdown-copy={`${props.template.displayName} (${presentationLabel})\n\n`} |
| 328 | data-skill-name={props.template.skillName} |
| 329 | > |
| 330 | <div className="flex min-w-0 flex-1 items-center gap-3"> |
| 331 | <span className="flex size-9 shrink-0 items-center justify-center rounded-lg border border-border/70 bg-background text-muted-foreground shadow-xs"> |
| 332 | <Icon aria-hidden className="size-5" /> |
| 333 | </span> |
| 334 | <div className="min-w-0"> |
| 335 | <div className="truncate text-sm font-medium text-foreground"> |
| 336 | {props.template.displayName} |
| 337 | </div> |
| 338 | <div className="text-xs text-muted-foreground">{presentationLabel}</div> |
| 339 | </div> |
| 340 | </div> |
| 341 | {props.onUse ? ( |
| 342 | <Button |
| 343 | data-thread-find-ignore |
| 344 | type="button" |
| 345 | size="sm" |
| 346 | variant="outline" |
| 347 | className="shrink-0" |
| 348 | onClick={() => props.onUse?.(props.template)} |
| 349 | > |
| 350 | <T>Use template</T> |
| 351 | </Button> |
| 352 | ) : null} |
| 353 | </div> |
| 354 | ); |
| 355 | } |
| 356 | |
| 357 | const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/; |
| 358 | |
| 359 | function orderedListGutterStyle( |
| 360 | itemValues: ReadonlyArray<unknown>, |
| 361 | start: unknown, |
| 362 | ): { "--list-gutter": string } | undefined { |
| 363 | const parsedStart = Number.parseInt(String(start ?? 1), 10); |
| 364 | let number = Number.isNaN(parsedStart) ? 1 : parsedStart; |
| 365 | let markerWidth = String(number).length; |
| 366 | for (const value of itemValues) { |
| 367 | const written = Number.parseInt(String(value ?? ""), 10); |
| 368 | if (!Number.isNaN(written)) number = written; |
| 369 | markerWidth = Math.max(markerWidth, String(number).length); |
| 370 | number += 1; |
| 371 | } |
| 372 | if (markerWidth <= 1) return undefined; |
| 373 | return { "--list-gutter": `${markerWidth + 2}ch` }; |
| 374 | } |
| 375 | |
| 376 | const GITHUB_ALERT_PRESENTATIONS: Record< |
| 377 | string, |
| 378 | { label: string; Icon: typeof InfoIcon; borderClassName: string; titleClassName: string } |
| 379 | > = { |
| 380 | insight: { |
| 381 | label: msg("Insight"), |
| 382 | Icon: StarIcon, |
| 383 | borderClassName: "border-info", |
| 384 | titleClassName: "text-info", |
| 385 | }, |
| 386 | note: { |
| 387 | label: msg("Note"), |
| 388 | Icon: InfoIcon, |
| 389 | borderClassName: "border-blue-500/70", |
| 390 | titleClassName: "text-blue-600 dark:text-blue-400", |
| 391 | }, |
| 392 | tip: { |
| 393 | label: msg("Tip"), |
| 394 | Icon: LightbulbIcon, |
| 395 | borderClassName: "border-emerald-500/70", |
| 396 | titleClassName: "text-emerald-600 dark:text-emerald-400", |
| 397 | }, |
| 398 | important: { |
| 399 | label: msg("Important"), |
| 400 | Icon: MessageSquareWarningIcon, |
| 401 | borderClassName: "border-purple-500/70", |
| 402 | titleClassName: "text-purple-600 dark:text-purple-400", |
| 403 | }, |
| 404 | warning: { |
| 405 | label: msg("Warning"), |
| 406 | Icon: TriangleAlertIcon, |
| 407 | borderClassName: "border-amber-500/70", |
| 408 | titleClassName: "text-amber-600 dark:text-amber-500", |
| 409 | }, |
| 410 | caution: { |
| 411 | label: msg("Caution"), |
| 412 | Icon: OctagonAlertIcon, |
| 413 | borderClassName: "border-red-500/70", |
| 414 | titleClassName: "text-red-600 dark:text-red-400", |
| 415 | }, |
| 416 | }; |
| 417 | |
| 418 | function normalizeMarkdownLinkHrefKey(href: string): string { |
| 419 | const normalizedHref = normalizeMarkdownLinkDestination(href); |
| 420 | const rewrittenHref = rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref; |
| 421 | return WINDOWS_DRIVE_PATH_REGEX.test(rewrittenHref) |
| 422 | ? rewrittenHref.replaceAll("\\", "/") |
| 423 | : rewrittenHref; |
| 424 | } |
| 425 | |
| 426 | // Heading ids are added after sanitizing, which would prefix them a second time. |
| 427 | const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [ |
| 428 | ...CHAT_MARKDOWN_REHYPE_PLUGINS, |
| 429 | rehypeHeadingIds, |
| 430 | rehypeTextDirection, |
| 431 | rehypeChipPunctuation, |
| 432 | ] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>; |
| 433 | |
| 434 | const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [ |
| 435 | rehypeHeadingIds, |
| 436 | rehypeTextDirection, |
| 437 | rehypeChipPunctuation, |
| 438 | ] satisfies NonNullable<ReactMarkdownOptions["rehypePlugins"]>; |
| 439 | |
| 440 | function markdownUrlTransform(href: string) { |
| 441 | if (parseAssistantCitationHref(href)) return href; |
| 442 | if (parseComposerContextHref(href)) return href; |
| 443 | if (parseThreadLinkHref(href)) return href; |
| 444 | if (isWindowsDrivePathHref(href)) return href; |
| 445 | if (isLocalEditorFileHref(href)) return href; |
| 446 | return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href); |
| 447 | } |
| 448 | |
| 449 | const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = []; |
| 450 | |
| 451 | type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>; |
| 452 | |
| 453 | function markdownServerConfigFields(config: ServerConfig | null) { |
| 454 | return { |
| 455 | pullRequestsEnabled: config !== null, |
| 456 | issuesEnabled: config?.environment.capabilities.issues === true, |
| 457 | isMacOS: config?.environment.platform.os === "darwin", |
| 458 | availableEditors: config?.availableEditors ?? NO_MARKDOWN_EDITORS, |
| 459 | revealInFileManager: |
| 460 | config?.shellRevealInFileManager === true && config.availableEditors.includes("file-manager") |
| 461 | ? (config.shellRevealInFileManagerKind ?? config.environment.platform.os) |
| 462 | : undefined, |
| 463 | }; |
| 464 | } |
| 465 | |
| 466 | function markdownServerConfigFieldsEqual( |
| 467 | previous: MarkdownServerConfigFields, |
| 468 | next: MarkdownServerConfigFields, |
| 469 | ): boolean { |
| 470 | return ( |
| 471 | previous.pullRequestsEnabled === next.pullRequestsEnabled && |
| 472 | previous.issuesEnabled === next.issuesEnabled && |
| 473 | previous.isMacOS === next.isMacOS && |
| 474 | previous.revealInFileManager === next.revealInFileManager && |
| 475 | previous.availableEditors.length === next.availableEditors.length && |
| 476 | previous.availableEditors.every((editor, index) => editor === next.availableEditors[index]) |
| 477 | ); |
| 478 | } |
| 479 | |
| 480 | // Compare only markdown config fields to avoid rerendering replies on every provider status push. |
| 481 | const markdownServerConfigFieldsAtom = Atom.family((environmentId: EnvironmentId | null) => |
| 482 | Atom.make((get) => { |
| 483 | const next = markdownServerConfigFields(get(serverEnvironment.configValueAtom(environmentId))); |
| 484 | const previous = Option.getOrNull(get.self<MarkdownServerConfigFields>()); |
| 485 | return previous !== null && markdownServerConfigFieldsEqual(previous, next) ? previous : next; |
| 486 | }).pipe(Atom.withLabel("markdown-server-config-fields")), |
| 487 | ); |
| 488 | |
| 489 | function fileLinkSourcesKey( |
| 490 | text: string, |
| 491 | cwd: string | undefined, |
| 492 | imageBaseDir: string | undefined, |
| 493 | ): string { |
| 494 | const hrefs = extractMarkdownLinkHrefs(renderCodexInlineDirectivesAsMarkdown(text)) |
| 495 | .filter((href) => !parseComposerContextHref(href)) |
| 496 | .map(decodeMarkdownLinkEscapes) |
| 497 | .map(normalizeMarkdownLinkHrefKey) |
| 498 | .filter((href) => resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd)); |
| 499 | const spans = extractInlineCodeSpans(text).filter((span) => |
| 500 | resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd), |
| 501 | ); |
| 502 | return JSON.stringify([[...new Set(hrefs)], [...new Set(spans)]]); |
| 503 | } |
| 504 | |
| 505 | function resolveFileLinkSources( |
| 506 | key: string, |
| 507 | cwd: string | undefined, |
| 508 | imageBaseDir: string | undefined, |
| 509 | ) { |
| 510 | const [hrefs, spans] = JSON.parse(key) as [string[], string[]]; |
| 511 | const markdownFileLinkMetaByHref = new Map<string, MarkdownFileLinkMeta>(); |
| 512 | for (const href of hrefs) { |
| 513 | const meta = resolveMarkdownFileLinkMeta(href, cwd, imageBaseDir ?? cwd); |
| 514 | if (meta) markdownFileLinkMetaByHref.set(href, meta); |
| 515 | } |
| 516 | const inlineCodeFileLinkMetaByText = new Map<string, MarkdownFileLinkMeta>(); |
| 517 | for (const span of spans) { |
| 518 | const meta = resolveInlineCodeFileLinkMeta(span, cwd, imageBaseDir ?? cwd); |
| 519 | if (meta) inlineCodeFileLinkMetaByText.set(span, meta); |
| 520 | } |
| 521 | const fileLinkParentSuffixByPath = buildFileLinkParentSuffixByPath([ |
| 522 | ...[...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath), |
| 523 | ...[...inlineCodeFileLinkMetaByText.values()].map((meta) => meta.filePath), |
| 524 | ]); |
| 525 | return { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath }; |
| 526 | } |
| 527 | |
| 528 | function useChatMarkdownState({ |
| 529 | text, |
| 530 | inline = false, |
| 531 | cwd, |
| 532 | agentDirectories, |
| 533 | threadRef, |
| 534 | pullRequestPanelRef, |
| 535 | environmentId: explicitEnvironmentId, |
| 536 | onTaskListChange, |
| 537 | isStreaming = false, |
| 538 | skills = EMPTY_MARKDOWN_SKILLS, |
| 539 | onUseArtifactTemplate, |
| 540 | onRunShellCommand, |
| 541 | imageBaseDir, |
| 542 | workspaceMutationId, |
| 543 | onImageExpand, |
| 544 | renderContextReference, |
| 545 | headingLevelOffset = 0, |
| 546 | sourceControlMedia = false, |
| 547 | sourceControlMediaRepository, |
| 548 | }: ChatMarkdownProps) { |
| 549 | const gt = useGT(); |
| 550 | const messages = useMessages(); |
| 551 | const resolvedTheme = useRenderedAppearance(); |
| 552 | const markdownRef = useRef<HTMLElement>(null); |
| 553 | const mediaRequestId = useRef(0); |
| 554 | const mediaScopeKey = [ |
| 555 | threadRef?.environmentId, |
| 556 | threadRef?.threadId, |
| 557 | explicitEnvironmentId, |
| 558 | cwd, |
| 559 | imageBaseDir, |
| 560 | ].join("\u0000"); |
| 561 | // Hide requests from an old scope even if they resolve before effect cleanup. |
| 562 | const [localMedia, setLocalMedia] = useState<{ |
| 563 | scope: string; |
| 564 | preview: ExpandedImagePreview; |
| 565 | } | null>(null); |
| 566 | const localMediaPreview = localMedia?.scope === mediaScopeKey ? localMedia.preview : null; |
| 567 | const closeLocalMediaPreview = () => setLocalMedia(null); |
| 568 | const expandMedia = |
| 569 | onImageExpand ?? |
| 570 | ((preview: ExpandedImagePreview) => setLocalMedia({ scope: mediaScopeKey, preview })); |
| 571 | const [mediaScope, setMediaScope] = useState(mediaScopeKey); |
| 572 | if (mediaScope !== mediaScopeKey) { |
| 573 | setMediaScope(mediaScopeKey); |
| 574 | setLocalMedia(null); |
| 575 | } |
| 576 | // Layout cleanup blocks stale requests from reaching onImageExpand before paint. |
| 577 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- layout cleanup invalidates media requests still loading for the old scope before paint |
| 578 | useLayoutEffect( |
| 579 | () => () => { |
| 580 | mediaRequestId.current += 1; |
| 581 | }, |
| 582 | // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Leaving the scope invalidates media requests still loading for it. |
| 583 | [mediaScopeKey], |
| 584 | ); |
| 585 | const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, { |
| 586 | reportFailure: false, |
| 587 | refresh: true, |
| 588 | }); |
| 589 | const searchProjectEntries = useAtomQueryRunner(projectEnvironment.searchEntries, { |
| 590 | reportFailure: false, |
| 591 | }); |
| 592 | const getFilesystemMetadata = useAtomQueryRunner(filesystemEnvironment.getMetadata, { |
| 593 | reportFailure: false, |
| 594 | refresh: true, |
| 595 | }); |
| 596 | const openPreview = useAtomCommand(previewEnvironment.open, { |
| 597 | reportFailure: false, |
| 598 | }); |
| 599 | const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId); |
| 600 | const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null; |
| 601 | const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); |
| 602 | const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope); |
| 603 | const isClientHost = useAtomValue(clientHostEnvironmentAtom(environmentId)); |
| 604 | const remoteOpen = useRemoteOpenResolution(environmentId); |
| 605 | const canUseShellActions = |
| 606 | canOperateHost && |
| 607 | canUseMarkdownFileShellActions(environmentId, remoteOpen.state.mode, remoteOpen.isResolved); |
| 608 | const openMarkdownMedia = ( |
| 609 | source: string, |
| 610 | resolvedFilePath?: string, |
| 611 | clickedImage?: HTMLImageElement | null, |
| 612 | ) => { |
| 613 | const requestId = ++mediaRequestId.current; |
| 614 | void resolveMarkdownMediaPreview({ |
| 615 | source, |
| 616 | resolvedFilePath, |
| 617 | cwd, |
| 618 | threadRef, |
| 619 | // Read the connection on click; reconnect replaces it, and subscriptions would refresh every markdown |
| 620 | // context. |
| 621 | httpBaseUrl: |
| 622 | environmentId === null ? undefined : readPreparedConnection(environmentId)?.httpBaseUrl, |
| 623 | createAssetUrl, |
| 624 | onOpenFile: threadRef |
| 625 | ? (path) => useRightPanelStore.getState().openFile(threadRef, path) |
| 626 | : undefined, |
| 627 | }).then( |
| 628 | (preview) => { |
| 629 | if (preview && mediaRequestId.current === requestId) { |
| 630 | const selected = preview.images[preview.index]; |
| 631 | expandMedia( |
| 632 | selected && selected.type !== "video" && markdownRef.current |
| 633 | ? markdownImageGallery(clickedImage ?? markdownRef.current, selected) |
| 634 | : preview, |
| 635 | ); |
| 636 | } |
| 637 | }, |
| 638 | (error: unknown) => { |
| 639 | if (mediaRequestId.current !== requestId) return; |
| 640 | let description = |
| 641 | thrownErrorMessage(error, m) ?? |
| 642 | gt("The file could not be loaded. It may have been moved or deleted."); |
| 643 | if ( |
| 644 | isAssetNotFoundError(error) && |
| 645 | error.resource._tag === "media-file" && |
| 646 | environmentId !== null |
| 647 | ) { |
| 648 | // The connection may resolve while the media lookup is pending. |
| 649 | const target = readPreparedConnection(environmentId)?.target ?? null; |
| 650 | if ( |
| 651 | target !== null && |
| 652 | resolveRemoteOpenState({ |
| 653 | target, |
| 654 | sshTarget: null, |
| 655 | remoteOpenTargets: undefined, |
| 656 | isDesktopRenderer: window.desktopBridge !== undefined, |
| 657 | hostEnvironmentId: appAtomRegistry.get(hostEnvironmentIdAtom), |
| 658 | }).mode !== "local-exec" |
| 659 | ) { |
| 660 | description = gt("The file was not found on {machine} at {path}.", { |
| 661 | machine: target.label, |
| 662 | path: error.checkedPath ?? error.resource.path, |
| 663 | }); |
| 664 | } |
| 665 | } |
| 666 | toastManager.add( |
| 667 | stackedThreadToast({ |
| 668 | type: "error", |
| 669 | title: gt("Media unavailable"), |
| 670 | description, |
| 671 | }), |
| 672 | ); |
| 673 | }, |
| 674 | ); |
| 675 | }; |
| 676 | const { pullRequestsEnabled, issuesEnabled, availableEditors, revealInFileManager, isMacOS } = |
| 677 | useAtomValue(markdownServerConfigFieldsAtom(environmentId)); |
| 678 | const revealInFileManagerLabel = |
| 679 | revealInFileManager === undefined |
| 680 | ? undefined |
| 681 | : revealInFileManager === "finder" || |
| 682 | revealInFileManager === "file-explorer" || |
| 683 | revealInFileManager === "files" |
| 684 | ? revealInFileExplorerLabelForKind(revealInFileManager, messages) |
| 685 | : revealInFileExplorerLabelForOs(revealInFileManager, messages); |
| 686 | const projects = useProjects(); |
| 687 | const issueProjects = projects.filter((project) => project.environmentId === environmentId); |
| 688 | // Only text naming a standalone tracker asks for its bindings, whose read probes the tracker. |
| 689 | const issueTrackers = |
| 690 | useEnvironmentQuery( |
| 691 | issuesEnabled && environmentId !== null && mayContainStandaloneIssueLink(text) |
| 692 | ? issueTrackerEnvironment.connections({ environmentId, input: {} }) |
| 693 | : null, |
| 694 | ).data ?? undefined; |
| 695 | const [preferredEditor] = usePreferredEditor(availableEditors); |
| 696 | const preferredEditorMenuLabel = openInEditorMenuLabel(preferredEditor, messages); |
| 697 | const openInPreferredEditor = useOpenInPreferredEditor(environmentId, availableEditors, cwd); |
| 698 | const openInEditor = useAtomCommand(shellEnvironment.openInEditor, { |
| 699 | reportFailure: false, |
| 700 | }); |
| 701 | const revealFileInFileManager = (filePath: string) => { |
| 702 | if (environmentId === null) { |
| 703 | return Promise.resolve( |
| 704 | AsyncResult.failure<void, PreferredEditorEnvironmentRequiredError>( |
| 705 | Cause.fail(new PreferredEditorEnvironmentRequiredError({ targetPath: filePath })), |
| 706 | ), |
| 707 | ); |
| 708 | } |
| 709 | if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { |
| 710 | return Promise.resolve( |
| 711 | AsyncResult.failure<void, Error>( |
| 712 | Cause.fail(new Error(gt("This connection cannot reveal files on this environment."))), |
| 713 | ), |
| 714 | ); |
| 715 | } |
| 716 | return openInEditor({ |
| 717 | environmentId, |
| 718 | input: { cwd: filePath, editor: "file-manager", reveal: true }, |
| 719 | }); |
| 720 | }; |
| 721 | const diffThemeName = resolveDiffThemeName(resolvedTheme); |
| 722 | const handleCopy = (event: ReactClipboardEvent<HTMLElement>) => { |
| 723 | const selection = window.getSelection(); |
| 724 | if (!selection || selection.isCollapsed || !event.clipboardData) return; |
| 725 | const payload = chatMarkdownClipboardPayload(selection); |
| 726 | if (!payload) return; |
| 727 | event.preventDefault(); |
| 728 | event.clipboardData.setData("text/plain", payload.text); |
| 729 | const fragment = event.clipboardData.getData(COMPOSER_CONTEXT_CLIPBOARD_MIME); |
| 730 | event.clipboardData.setData( |
| 731 | "text/html", |
| 732 | fragment |
| 733 | ? encodeComposerContextClipboardHtml(payload.text, fragment, payload.html) |
| 734 | : payload.html, |
| 735 | ); |
| 736 | }; |
| 737 | const openChangeRequestLink = useOpenChangeRequestLink(threadRef, pullRequestPanelRef); |
| 738 | const openIssueLink = useOpenIssueLink(threadRef, pullRequestPanelRef); |
| 739 | const openDeferredMarkdownLink = useOpenLink(threadRef); |
| 740 | // Subscribe so hydrated settings apply before the anchor synchronously decides whether to intercept _blank. |
| 741 | const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget); |
| 742 | const mathEnabled = useClientSettings((settings) => settings.mathRenderingEnabled); |
| 743 | // Keyed by the file links found, not the text, so streamed text that adds none keeps the |
| 744 | // renderer context, and every block reading it, unchanged. |
| 745 | // A template literal marks the key as a string, so the compiler memoizes the maps on its value. |
| 746 | const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; |
| 747 | const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = |
| 748 | resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); |
| 749 | const resolveThreadPullRequest = ( |
| 750 | href: string, |
| 751 | ): (ThreadPullRequestKey & { readonly url: string }) | null => { |
| 752 | if ( |
| 753 | threadRef === undefined || |
| 754 | readThreadShell(threadRef) === null || |
| 755 | !pullRequestLinking.canLink(href) |
| 756 | ) |
| 757 | return null; |
| 758 | const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link; |
| 759 | return parsed === undefined ? null : { ...parsed, url: href }; |
| 760 | }; |
| 761 | const linkedThreadPullRequestFor = (href: string) => { |
| 762 | if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href)) |
| 763 | return null; |
| 764 | const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link; |
| 765 | return parsed === undefined ? null : { ...parsed, url: href }; |
| 766 | }; |
| 767 | const updateThreadPullRequestLink = async (href: string, linked: boolean) => { |
| 768 | if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return; |
| 769 | if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return; |
| 770 | await pullRequestLinking.changeLink(threadRef, href, linked); |
| 771 | }; |
| 772 | const openExternalLinkInPreview = (url: string) => { |
| 773 | if (!threadRef || !canOperatePreview) { |
| 774 | return Promise.resolve( |
| 775 | AsyncResult.failure<void, BrowserPreviewUnavailableError>( |
| 776 | Cause.fail( |
| 777 | new BrowserPreviewUnavailableError({ |
| 778 | message: gt("Preview access is unavailable for this client."), |
| 779 | }), |
| 780 | ), |
| 781 | ), |
| 782 | ); |
| 783 | } |
| 784 | return openUrlInPreview({ threadRef, url, openPreview }).then((result) => { |
| 785 | if (result._tag === "Success") recordVisitForThread(threadRef, url); |
| 786 | else if (!isAtomCommandInterrupted(result)) { |
| 787 | const error = squashAtomCommandFailure(result); |
| 788 | if (isBrowserSettingsReadError(error)) { |
| 789 | toastManager.add( |
| 790 | stackedThreadToast({ |
| 791 | type: "error", |
| 792 | title: gt("Unable to open link in browser"), |
| 793 | description: error.message, |
| 794 | }), |
| 795 | ); |
| 796 | } |
| 797 | } |
| 798 | return result; |
| 799 | }); |
| 800 | }; |
| 801 | const openMarkdownFileInPreview = (path: string) => { |
| 802 | const preparedConnection = threadRef ? readPreparedConnection(threadRef.environmentId) : null; |
| 803 | if (!threadRef || !canOperatePreview || preparedConnection === null) { |
| 804 | return Promise.resolve( |
| 805 | AsyncResult.failure<void, BrowserPreviewUnavailableError>( |
| 806 | Cause.fail( |
| 807 | new BrowserPreviewUnavailableError({ |
| 808 | message: gt("Environment is not connected."), |
| 809 | }), |
| 810 | ), |
| 811 | ), |
| 812 | ); |
| 813 | } |
| 814 | return openFileInPreview({ |
| 815 | threadRef, |
| 816 | filePath: path, |
| 817 | workspaceRoot: cwd, |
| 818 | httpBaseUrl: preparedConnection.httpBaseUrl, |
| 819 | createAssetUrl, |
| 820 | openPreview, |
| 821 | }); |
| 822 | }; |
| 823 | const findWorkspaceFileMatch = async (fileLinkMeta: MarkdownFileLinkMeta) => { |
| 824 | const workspaceRelativePath = fileLinkMeta.workspaceLookupPath; |
| 825 | if ( |
| 826 | !workspaceRelativePath || |
| 827 | !cwd || |
| 828 | environmentId === null || |
| 829 | !readEnvironmentScope(environmentId, AuthFilesystemReadScope) |
| 830 | ) { |
| 831 | return null; |
| 832 | } |
| 833 | const query = workspaceLinkLookupQuery(workspaceRelativePath, cwd); |
| 834 | if (query === null) return null; |
| 835 | // Search can be truncated or still scanning, so it cannot rule out the literal |
| 836 | // path. A path with a folder opens as written whenever it exists. |
| 837 | if (!needsWorkspaceBasenameLookup(workspaceRelativePath)) { |
| 838 | const metadata = await getFilesystemMetadata({ |
| 839 | environmentId, |
| 840 | input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, |
| 841 | }); |
| 842 | if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null; |
| 843 | } |
| 844 | const searchRoot = async (root: string) => { |
| 845 | const rootQuery = workspaceLinkLookupQuery(workspaceRelativePath, root); |
| 846 | if (rootQuery === null) return { root, entries: [] }; |
| 847 | const result = await searchProjectEntries({ |
| 848 | environmentId, |
| 849 | input: { |
| 850 | cwd: root, |
| 851 | query: rootQuery, |
| 852 | limit: WORKSPACE_BASENAME_LOOKUP_LIMIT, |
| 853 | kind: "file", |
| 854 | }, |
| 855 | }); |
| 856 | return { root, entries: result._tag === "Success" ? result.value.entries : [] }; |
| 857 | }; |
| 858 | const own = await searchRoot(cwd); |
| 859 | const ownMatch = pickWorkspaceLinkMatch(workspaceRelativePath, cwd, own.entries); |
| 860 | if (ownMatch !== null) return ownMatch; |
| 861 | const threadProjectId = threadRef ? readThreadShell(threadRef)?.projectId : undefined; |
| 862 | const otherRoots = projects.flatMap((project) => |
| 863 | project.environmentId === environmentId && |
| 864 | project.id !== threadProjectId && |
| 865 | project.workspaceRoot !== cwd |
| 866 | ? [project.workspaceRoot] |
| 867 | : [], |
| 868 | ); |
| 869 | const agentRoots = (agentDirectories?.() ?? []).filter((root) => root !== cwd); |
| 870 | if (otherRoots.length === 0 && agentRoots.length === 0) return null; |
| 871 | // Another project's file never replaces a thread-local file the search missed. |
| 872 | if (needsWorkspaceBasenameLookup(workspaceRelativePath)) { |
| 873 | const metadata = await getFilesystemMetadata({ |
| 874 | environmentId, |
| 875 | input: { paths: [resolveWorkspaceFilePath(workspaceRelativePath, cwd)] }, |
| 876 | }); |
| 877 | if (metadata._tag !== "Success" || metadata.value.entries[0] !== null) return null; |
| 878 | } |
| 879 | const projectMatch = pickProjectLinkMatch( |
| 880 | workspaceRelativePath, |
| 881 | await Promise.all(otherRoots.map(searchRoot)), |
| 882 | ); |
| 883 | if (projectMatch !== null || agentRoots.length === 0) return projectMatch; |
| 884 | // No project has the file, so it opens where the agent last worked, as written. |
| 885 | const agentPaths = agentRoots.map((root) => |
| 886 | resolveWorkspaceFilePath(workspaceRelativePath, root), |
| 887 | ); |
| 888 | const metadata = await getFilesystemMetadata({ environmentId, input: { paths: agentPaths } }); |
| 889 | if (metadata._tag !== "Success") return null; |
| 890 | const literal = agentPaths.find((_, index) => metadata.value.entries[index]?.kind === "file"); |
| 891 | if (literal !== undefined || !needsWorkspaceBasenameLookup(workspaceRelativePath)) { |
| 892 | return literal ?? null; |
| 893 | } |
| 894 | return findAgentDirectoryMatch(workspaceRelativePath, agentRoots, searchRoot); |
| 895 | }; |
| 896 | const openFileInPanel = (fileLinkMeta: MarkdownFileLinkMeta, panelPath: string) => { |
| 897 | if (!threadRef) return; |
| 898 | const openAt = (path: string) => |
| 899 | useRightPanelStore.getState().openFile(threadRef, path, fileLinkMeta.line); |
| 900 | if ( |
| 901 | fileLinkMeta.workspaceLookupPath === null || |
| 902 | !cwd || |
| 903 | workspaceLinkLookupQuery(panelPath, cwd) === null |
| 904 | ) { |
| 905 | openAt(panelPath); |
| 906 | return; |
| 907 | } |
| 908 | // Anything the user opens in this panel meanwhile, such as a file from the picker, wins. |
| 909 | const panelRef = rightPanelHostRef(threadRef); |
| 910 | const panelKey = scopedThreadKey(panelRef); |
| 911 | const userActionRevision = useRightPanelStore.getState().markUserAction(panelRef); |
| 912 | void (async () => { |
| 913 | const match = await findWorkspaceFileMatch(fileLinkMeta); |
| 914 | if ( |
| 915 | scopedThreadKey(rightPanelHostRef(threadRef)) !== panelKey || |
| 916 | useRightPanelStore.getState().getUserActionRevision(panelRef) !== userActionRevision |
| 917 | ) |
| 918 | return; |
| 919 | openAt(match ?? panelPath); |
| 920 | })(); |
| 921 | }; |
| 922 | const fileLinkChip = ( |
| 923 | fileLinkMeta: MarkdownFileLinkMeta, |
| 924 | copyMarkdown: string, |
| 925 | mediaSource?: string, |
| 926 | ) => { |
| 927 | const resolveHostPath = () => |
| 928 | resolveMarkdownFileHostPath({ |
| 929 | meta: fileLinkMeta, |
| 930 | cwd, |
| 931 | findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta), |
| 932 | }); |
| 933 | const isAppBundle = isMacOS && fileLinkMeta.filePath.endsWith(".app"); |
| 934 | const canOpenApp = |
| 935 | environmentId !== null && |
| 936 | isAppBundle && |
| 937 | isClientHost && |
| 938 | canOperateHost && |
| 939 | availableEditors.includes("file-manager"); |
| 940 | const mediaPath = mediaSource ?? fileLinkMeta.filePath; |
| 941 | const canPreviewMedia = |
| 942 | mediaMimeTypeFromExtension( |
| 943 | fileLinkMeta.basename.slice(fileLinkMeta.basename.lastIndexOf(".")), |
| 944 | ) !== null; |
| 945 | const panelPath = |
| 946 | fileLinkMeta.workspaceRelativePath ?? |
| 947 | (!canPreviewMedia && isHostPath(fileLinkMeta.filePath) ? fileLinkMeta.filePath : null); |
| 948 | |
| 949 | return ( |
| 950 | <MarkdownFileLink |
| 951 | environmentId={environmentId} |
| 952 | href={fileLinkMeta.targetPath} |
| 953 | targetPath={fileLinkMeta.targetPath} |
| 954 | iconPath={ |
| 955 | isAppBundle && cwd |
| 956 | ? resolveWorkspaceFilePath(fileLinkMeta.filePath, cwd) |
| 957 | : fileLinkMeta.filePath |
| 958 | } |
| 959 | isAppBundle={isAppBundle} |
| 960 | workspaceRelativePath={fileLinkMeta.workspaceRelativePath} |
| 961 | panelPath={isAppBundle ? null : panelPath} |
| 962 | line={fileLinkMeta.line} |
| 963 | label={fileLinkLabel( |
| 964 | { |
| 965 | path: fileLinkMeta.filePath, |
| 966 | ...(fileLinkMeta.line !== undefined ? { line: fileLinkMeta.line } : {}), |
| 967 | ...(fileLinkMeta.column !== undefined ? { column: fileLinkMeta.column } : {}), |
| 968 | ...(fileLinkMeta.endLine !== undefined ? { endLine: fileLinkMeta.endLine } : {}), |
| 969 | }, |
| 970 | fileLinkParentSuffixByPath, |
| 971 | )} |
| 972 | copyMarkdown={copyMarkdown} |
| 973 | theme={resolvedTheme} |
| 974 | threadRef={threadRef} |
| 975 | onOpen={ |
| 976 | canOpenApp |
| 977 | ? async () => |
| 978 | openInEditor({ |
| 979 | environmentId, |
| 980 | input: { cwd: (await resolveHostPath()).absolutePath, editor: "file-manager" }, |
| 981 | }) |
| 982 | : canUseShellActions |
| 983 | ? async () => |
| 984 | openInPreferredEditor( |
| 985 | markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()), |
| 986 | ) |
| 987 | : undefined |
| 988 | } |
| 989 | resolveDragPath={async () => |
| 990 | resolvePathLinkTarget((await resolveHostPath()).absolutePath, cwd ?? "") |
| 991 | } |
| 992 | resolveCopyPaths={async () => |
| 993 | markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd) |
| 994 | } |
| 995 | onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)} |
| 996 | onOpenMedia={ |
| 997 | threadRef && canPreviewMedia |
| 998 | ? () => openMarkdownMedia(mediaPath, fileLinkMeta.filePath) |
| 999 | : undefined |
| 1000 | } |
| 1001 | openInEditorMenuLabel={canOpenApp ? gt("Open app") : preferredEditorMenuLabel} |
| 1002 | onReveal={ |
| 1003 | canUseShellActions && revealInFileManagerLabel !== undefined |
| 1004 | ? async () => revealFileInFileManager((await resolveHostPath()).absolutePath) |
| 1005 | : undefined |
| 1006 | } |
| 1007 | revealLabel={revealInFileManagerLabel} |
| 1008 | onOpenInBrowser={ |
| 1009 | threadRef && |
| 1010 | canOperatePreview && |
| 1011 | isPreviewAvailableFor(threadRef.environmentId) && |
| 1012 | isBrowserPreviewFile(fileLinkMeta.filePath) |
| 1013 | ? () => openMarkdownFileInPreview(fileLinkMeta.filePath) |
| 1014 | : undefined |
| 1015 | } |
| 1016 | /> |
| 1017 | ); |
| 1018 | }; |
| 1019 | |
| 1020 | const componentState = { |
| 1021 | canOperateHost, |
| 1022 | canOperatePreview, |
| 1023 | cwd, |
| 1024 | diffThemeName, |
| 1025 | environmentId, |
| 1026 | expandMedia, |
| 1027 | fileLinkChip, |
| 1028 | sourceControlMedia, |
| 1029 | sourceControlMediaRepository, |
| 1030 | renderContextReference, |
| 1031 | headingLevelOffset, |
| 1032 | imageBaseDir, |
| 1033 | workspaceMutationId, |
| 1034 | inlineCodeFileLinkMetaByText, |
| 1035 | inline, |
| 1036 | mathEnabled, |
| 1037 | isStreaming, |
| 1038 | linkTargetPreference, |
| 1039 | markdownFileLinkMetaByHref, |
| 1040 | onTaskListChange, |
| 1041 | onUseArtifactTemplate, |
| 1042 | onRunShellCommand, |
| 1043 | openChangeRequestLink, |
| 1044 | openIssueLink, |
| 1045 | openDeferredMarkdownLink, |
| 1046 | openExternalLinkInPreview, |
| 1047 | openMarkdownMedia, |
| 1048 | projects, |
| 1049 | issueProjects, |
| 1050 | issueTrackers, |
| 1051 | linkedThreadPullRequestFor, |
| 1052 | resolveThreadPullRequest, |
| 1053 | resolvedTheme, |
| 1054 | pullRequestsEnabled, |
| 1055 | issuesEnabled, |
| 1056 | skills, |
| 1057 | threadRef, |
| 1058 | updateThreadPullRequestLink, |
| 1059 | }; |
| 1060 | return { |
| 1061 | componentState, |
| 1062 | handleCopy, |
| 1063 | markdownRef, |
| 1064 | localMediaPreview, |
| 1065 | closeLocalMediaPreview, |
| 1066 | }; |
| 1067 | } |
| 1068 | |
| 1069 | const ChatMarkdownRendererContext = React.createContext< |
| 1070 | ReturnType<typeof useChatMarkdownState>["componentState"] |
| 1071 | >(null!); |
| 1072 | |
| 1073 | // Isolate streamed source text from the renderer context; only offset-based renderers need it. |
| 1074 | const ChatMarkdownTextContext = React.createContext(""); |
| 1075 | |
| 1076 | // A quote card is a block. These say nothing else shares its paragraph or list item on that side. |
| 1077 | const LIST_MARKER = String.raw`(?:[-*+]|\d+[.)])[ \t]+`; |
| 1078 | const CITATION_LEADS_BLOCK = new RegExp( |
| 1079 | String.raw`(?:(?:^|\n[ \t]*\n)[ \t>]*(?:${LIST_MARKER})?|\n[ \t>]*${LIST_MARKER})$`, |
| 1080 | ); |
| 1081 | const CITATION_ENDS_BLOCK = new RegExp( |
| 1082 | String.raw`^[ \t]*(?:$|\n[ \t]*(?:\n|$)|\n[ \t>]*${LIST_MARKER})`, |
| 1083 | ); |
| 1084 | |
| 1085 | function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) { |
| 1086 | const Tag = `h${level}` as const; |
| 1087 | return function MarkdownHeading({ |
| 1088 | node: _node, |
| 1089 | ...props |
| 1090 | }: ComponentProps<typeof Tag> & ReactMarkdownExtraProps) { |
| 1091 | const { headingLevelOffset } = use(ChatMarkdownRendererContext); |
| 1092 | return ( |
| 1093 | <Tag |
| 1094 | {...props} |
| 1095 | aria-level={headingLevelOffset > 0 ? Math.min(level + headingLevelOffset, 6) : undefined} |
| 1096 | /> |
| 1097 | ); |
| 1098 | }; |
| 1099 | } |
| 1100 | |
| 1101 | const CHAT_MARKDOWN_COMPONENTS = { |
| 1102 | h1: markdownHeadingRenderer(1), |
| 1103 | h2: markdownHeadingRenderer(2), |
| 1104 | h3: markdownHeadingRenderer(3), |
| 1105 | h4: markdownHeadingRenderer(4), |
| 1106 | h5: markdownHeadingRenderer(5), |
| 1107 | h6: markdownHeadingRenderer(6), |
| 1108 | div: function MarkdownDiv({ node, children, ...props }) { |
| 1109 | const { onUseArtifactTemplate } = use(ChatMarkdownRendererContext); |
| 1110 | const artifactTemplate = artifactTemplateFromHastProperties(node?.properties); |
| 1111 | if (artifactTemplate) { |
| 1112 | return ( |
| 1113 | <CodexArtifactTemplateCard template={artifactTemplate} onUse={onUseArtifactTemplate} /> |
| 1114 | ); |
| 1115 | } |
| 1116 | return <div {...props}>{children}</div>; |
| 1117 | }, |
| 1118 | p: function MarkdownParagraph({ node: _node, children, ...props }) { |
| 1119 | const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext); |
| 1120 | return ( |
| 1121 | <p {...props}> |
| 1122 | {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)} |
| 1123 | </p> |
| 1124 | ); |
| 1125 | }, |
| 1126 | blockquote: function MarkdownBlockquote({ node: _node, children, ...props }) { |
| 1127 | const m = useMessages(); |
| 1128 | const alertKind = String((props as Record<string, unknown>)["data-alert"] ?? ""); |
| 1129 | const alert = GITHUB_ALERT_PRESENTATIONS[alertKind]; |
| 1130 | if (!alert) { |
| 1131 | return <blockquote {...props}>{children}</blockquote>; |
| 1132 | } |
| 1133 | return ( |
| 1134 | <div |
| 1135 | role="note" |
| 1136 | data-markdown-alert={alertKind} |
| 1137 | dir={props.dir} |
| 1138 | className={cn("my-1 border-s-2 ps-3", alert.borderClassName)} |
| 1139 | > |
| 1140 | <p |
| 1141 | data-thread-find-ignore="true" |
| 1142 | data-markdown-alert-label="" |
| 1143 | className={cn("flex items-center gap-1.5 font-medium", alert.titleClassName)} |
| 1144 | > |
| 1145 | <alert.Icon aria-hidden className="size-3.5 shrink-0" /> |
| 1146 | {m(alert.label)} |
| 1147 | </p> |
| 1148 | {children} |
| 1149 | </div> |
| 1150 | ); |
| 1151 | }, |
| 1152 | ol: function MarkdownOrderedList({ node, start, style, ...props }) { |
| 1153 | const itemValues = |
| 1154 | node?.children?.flatMap((child) => |
| 1155 | child.type === "element" && child.tagName === "li" ? [child.properties.value] : [], |
| 1156 | ) ?? []; |
| 1157 | const gutterStyle = orderedListGutterStyle(itemValues, start); |
| 1158 | return ( |
| 1159 | <ol {...props} start={start} style={gutterStyle ? { ...style, ...gutterStyle } : style} /> |
| 1160 | ); |
| 1161 | }, |
| 1162 | li: function MarkdownListItem({ node, children, ...props }) { |
| 1163 | const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext); |
| 1164 | // Resolve checkbox markers by offset to avoid rerendering list items on every streamed token. |
| 1165 | const isTaskItem = String(props.className ?? "").includes("task-list-item"); |
| 1166 | return ( |
| 1167 | <li {...props} data-list-item-offset={isTaskItem ? node?.position?.start.offset : undefined}> |
| 1168 | {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)} |
| 1169 | </li> |
| 1170 | ); |
| 1171 | }, |
| 1172 | input: function MarkdownInput({ node: _node, type, checked, disabled: _disabled, ...props }) { |
| 1173 | const gt = useGT(); |
| 1174 | const { onTaskListChange } = use(ChatMarkdownRendererContext); |
| 1175 | const text = use(ChatMarkdownTextContext); |
| 1176 | if (type !== "checkbox" || !onTaskListChange) { |
| 1177 | return ( |
| 1178 | <input |
| 1179 | {...props} |
| 1180 | type={type} |
| 1181 | checked={type === "checkbox" ? checked === true : checked} |
| 1182 | disabled={_disabled} |
| 1183 | readOnly={type === "checkbox"} |
| 1184 | /> |
| 1185 | ); |
| 1186 | } |
| 1187 | return ( |
| 1188 | <input |
| 1189 | {...props} |
| 1190 | type="checkbox" |
| 1191 | name="markdown-task" |
| 1192 | aria-label={gt("Toggle task")} |
| 1193 | checked={checked === true} |
| 1194 | onChange={(event) => { |
| 1195 | const listItemStart = Number(event.currentTarget.closest("li")?.dataset.listItemOffset); |
| 1196 | if (!Number.isSafeInteger(listItemStart)) return; |
| 1197 | const markerOffset = taskListMarkerOffset(text, listItemStart); |
| 1198 | if (markerOffset === null) return; |
| 1199 | onTaskListChange({ markerOffset, checked: event.currentTarget.checked }); |
| 1200 | }} |
| 1201 | /> |
| 1202 | ); |
| 1203 | }, |
| 1204 | a: function MarkdownAnchor({ node, href, children, title: _title, ...props }) { |
| 1205 | const gt = useGT(); |
| 1206 | const { |
| 1207 | canOperateHost, |
| 1208 | canOperatePreview, |
| 1209 | cwd, |
| 1210 | environmentId, |
| 1211 | imageBaseDir, |
| 1212 | markdownFileLinkMetaByHref, |
| 1213 | threadRef, |
| 1214 | openMarkdownMedia, |
| 1215 | openChangeRequestLink, |
| 1216 | openIssueLink, |
| 1217 | openDeferredMarkdownLink, |
| 1218 | linkTargetPreference, |
| 1219 | openExternalLinkInPreview, |
| 1220 | projects, |
| 1221 | issueProjects, |
| 1222 | issueTrackers, |
| 1223 | linkedThreadPullRequestFor, |
| 1224 | resolveThreadPullRequest, |
| 1225 | pullRequestsEnabled, |
| 1226 | issuesEnabled, |
| 1227 | updateThreadPullRequestLink, |
| 1228 | fileLinkChip, |
| 1229 | renderContextReference, |
| 1230 | } = use(ChatMarkdownRendererContext); |
| 1231 | const text = use(ChatMarkdownTextContext); |
| 1232 | const citation = href ? parseAssistantCitationHref(href) : null; |
| 1233 | const before = node?.position?.start.offset; |
| 1234 | const after = node?.position?.end.offset; |
| 1235 | const leading = before !== undefined && CITATION_LEADS_BLOCK.test(text.slice(0, before)); |
| 1236 | const trailing = after !== undefined && CITATION_ENDS_BLOCK.test(text.slice(after)); |
| 1237 | if (citation) { |
| 1238 | return <AssistantCitationEmbed citation={citation} leading={leading} trailing={trailing} />; |
| 1239 | } |
| 1240 | const threadLink = href ? parseThreadLinkHref(href) : null; |
| 1241 | if (threadLink) { |
| 1242 | const written = hastPlainTextDeep(node); |
| 1243 | // An autolink's text is its own URL, which is no label. |
| 1244 | const label = written && parseThreadLinkHref(written) === null ? written : null; |
| 1245 | return environmentId ? ( |
| 1246 | <MarkdownThreadLink |
| 1247 | environmentId={environmentId} |
| 1248 | threadRef={threadRef} |
| 1249 | link={threadLink} |
| 1250 | label={label} |
| 1251 | /> |
| 1252 | ) : ( |
| 1253 | <span>{label ?? gt("Thread")}</span> |
| 1254 | ); |
| 1255 | } |
| 1256 | const contextReference = href ? parseComposerContextHref(href) : null; |
| 1257 | if (contextReference) { |
| 1258 | const label = hastPlainTextDeep(node) || contextReference.contextId; |
| 1259 | return renderContextReference ? ( |
| 1260 | renderContextReference({ ...contextReference, label, leading, trailing }) |
| 1261 | ) : ( |
| 1262 | <span>{label}</span> |
| 1263 | ); |
| 1264 | } |
| 1265 | const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; |
| 1266 | const fileLinkMeta = normalizedHref |
| 1267 | ? (markdownFileLinkMetaByHref.get(normalizedHref) ?? |
| 1268 | resolveMarkdownFileLinkMeta(normalizedHref, cwd, imageBaseDir ?? cwd)) |
| 1269 | : null; |
| 1270 | if (!fileLinkMeta) { |
| 1271 | const faviconHost = resolveExternalWebLinkHost(href); |
| 1272 | const hasText = hastHasText(node); |
| 1273 | const pullRequestAutolink = String( |
| 1274 | (props as Record<string, unknown>)["data-pull-request-autolink"] ?? "", |
| 1275 | ); |
| 1276 | const pullRequestCopy = |
| 1277 | pullRequestAutolink === "commit" |
| 1278 | ? /\/commit\/([0-9a-f]{7,40})$/iu.exec(href ?? "")?.[1] |
| 1279 | : pullRequestAutolink === "reference" || pullRequestAutolink === "mention" |
| 1280 | ? plainHastText(node) |
| 1281 | : undefined; |
| 1282 | const isPullRequestAutolink = pullRequestCopy !== undefined; |
| 1283 | const confirmBeforeOpen = pullRequestAutolink === "reference"; |
| 1284 | const pullRequestCandidateUrl = |
| 1285 | confirmBeforeOpen && href |
| 1286 | ? sourceControlClients.changeRequestUrlFromReferenceAutolink(href) |
| 1287 | : href; |
| 1288 | const pullRequestPreviewTarget = pullRequestCandidateUrl |
| 1289 | ? resolvePullRequestPreviewTarget({ |
| 1290 | environmentId, |
| 1291 | projects, |
| 1292 | pullRequestsEnabled, |
| 1293 | url: pullRequestCandidateUrl, |
| 1294 | }) |
| 1295 | : null; |
| 1296 | const issueTarget = |
| 1297 | issuesEnabled && environmentId !== null && href |
| 1298 | ? resolveIssueLinkTarget({ |
| 1299 | url: href, |
| 1300 | projects: issueProjects, |
| 1301 | trackers: issueTrackers, |
| 1302 | }) |
| 1303 | : null; |
| 1304 | const issuePreviewTarget = |
| 1305 | issueTarget === null || environmentId === null |
| 1306 | ? null |
| 1307 | : { environmentId, input: issueTarget.ref }; |
| 1308 | const isSameDocumentLink = href?.startsWith("#") ?? false; |
| 1309 | const onClick = props.onClick; |
| 1310 | const canOpenInPreview = |
| 1311 | canOperatePreview && Boolean(threadRef && isPreviewAvailableFor(threadRef.environmentId)); |
| 1312 | const linkChildren = <MarkdownLinkContext value>{children}</MarkdownLinkContext>; |
| 1313 | const link = ( |
| 1314 | <a |
| 1315 | {...props} |
| 1316 | className={cn(props.className, pullRequestAutolink === "commit" && "font-mono")} |
| 1317 | data-markdown-copy={pullRequestCopy} |
| 1318 | data-markdown-image-link={!hasText || undefined} |
| 1319 | href={href} |
| 1320 | target={isSameDocumentLink ? undefined : "_blank"} |
| 1321 | rel={isSameDocumentLink ? undefined : "noopener noreferrer"} |
| 1322 | onClick={(event) => { |
| 1323 | onClick?.(event); |
| 1324 | if (isSameDocumentLink && href) { |
| 1325 | handleMarkdownFragmentClick(event, href); |
| 1326 | return; |
| 1327 | } |
| 1328 | if ( |
| 1329 | href && |
| 1330 | faviconHost !== null && |
| 1331 | mediaKindFromPath(href) !== null && |
| 1332 | mediaKindFromPath(href) !== "audio" && |
| 1333 | !event.defaultPrevented && |
| 1334 | !event.metaKey && |
| 1335 | !event.ctrlKey && |
| 1336 | !event.shiftKey && |
| 1337 | !event.altKey |
| 1338 | ) { |
| 1339 | event.preventDefault(); |
| 1340 | event.stopPropagation(); |
| 1341 | openMarkdownMedia( |
| 1342 | href, |
| 1343 | undefined, |
| 1344 | event.target instanceof HTMLImageElement |
| 1345 | ? event.target |
| 1346 | : event.currentTarget.querySelector("img"), |
| 1347 | ); |
| 1348 | return; |
| 1349 | } |
| 1350 | if ( |
| 1351 | !href || |
| 1352 | openChangeRequestLink(event, href, undefined, environmentId ?? undefined) || |
| 1353 | openIssueLink(event, href, environmentId ?? undefined, issueTrackers) |
| 1354 | ) { |
| 1355 | return; |
| 1356 | } |
| 1357 | if (event.defaultPrevented) return; |
| 1358 | if ( |
| 1359 | resolveLinkTarget({ |
| 1360 | url: href, |
| 1361 | event, |
| 1362 | preference: linkTargetPreference, |
| 1363 | canOpenInApp: canOpenInPreview, |
| 1364 | }) !== "app" |
| 1365 | ) { |
| 1366 | // Open desktop Alt-clicks before Chromium downloads them so link routers can read the held key. |
| 1367 | if (isElectron && event.altKey) { |
| 1368 | event.preventDefault(); |
| 1369 | event.stopPropagation(); |
| 1370 | void readLocalApi() |
| 1371 | ?.shell.openExternal(href) |
| 1372 | .catch((cause) => |
| 1373 | reportMarkdownActionFailure( |
| 1374 | { operation: "open-link-external", target: href }, |
| 1375 | cause, |
| 1376 | ), |
| 1377 | ); |
| 1378 | } |
| 1379 | return; |
| 1380 | } |
| 1381 | event.preventDefault(); |
| 1382 | event.stopPropagation(); |
| 1383 | void openExternalLinkInPreview(href).then((result) => { |
| 1384 | if (result._tag === "Success" || isAtomCommandInterrupted(result)) return; |
| 1385 | reportMarkdownActionFailure( |
| 1386 | { operation: "open-link-in-preview", target: href }, |
| 1387 | result.cause, |
| 1388 | ); |
| 1389 | if (isBrowserSettingsReadError(squashAtomCommandFailure(result))) return; |
| 1390 | void readLocalApi()?.shell.openExternal(href); |
| 1391 | }); |
| 1392 | }} |
| 1393 | onContextMenu={(event) => { |
| 1394 | if (!href || !faviconHost) return; |
| 1395 | event.preventDefault(); |
| 1396 | event.stopPropagation(); |
| 1397 | const api = readLocalApi(); |
| 1398 | if (!api) return; |
| 1399 | const source = contextMenuSourceOf(event); |
| 1400 | const threadLinkAction = !canOperateHost |
| 1401 | ? undefined |
| 1402 | : linkedThreadPullRequestFor(href) !== null |
| 1403 | ? "unlink-from-thread" |
| 1404 | : resolveThreadPullRequest(href) === null |
| 1405 | ? undefined |
| 1406 | : "link-to-thread"; |
| 1407 | void showExternalLinkContextMenu({ |
| 1408 | href, |
| 1409 | canOpenInPreview, |
| 1410 | threadLinkAction, |
| 1411 | position: { x: event.clientX, y: event.clientY }, |
| 1412 | showContextMenu: (items, position) => api.contextMenu.show(items, position, source), |
| 1413 | openInPreview: async (target) => { |
| 1414 | const result = await openExternalLinkInPreview(target); |
| 1415 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 1416 | reportMarkdownActionFailure( |
| 1417 | { operation: "open-link-in-preview", target }, |
| 1418 | result.cause, |
| 1419 | ); |
| 1420 | } |
| 1421 | }, |
| 1422 | openExternal: (target) => api.shell.openExternal(target), |
| 1423 | copyLink: (target) => |
| 1424 | writeTextToClipboard(target, { |
| 1425 | target: "link", |
| 1426 | unavailableMessage: msg("Clipboard API is unavailable while copying link."), |
| 1427 | failureMessage: msg("Failed to copy link to the clipboard."), |
| 1428 | }), |
| 1429 | updateThreadLink: updateThreadPullRequestLink, |
| 1430 | reportFailure: (operation, cause) => { |
| 1431 | reportMarkdownActionFailure({ operation, target: href }, cause); |
| 1432 | if ( |
| 1433 | operation === "link-pull-request-to-thread" || |
| 1434 | operation === "unlink-pull-request-from-thread" |
| 1435 | ) { |
| 1436 | toastManager.add( |
| 1437 | stackedThreadToast({ |
| 1438 | type: "error", |
| 1439 | title: |
| 1440 | operation === "link-pull-request-to-thread" |
| 1441 | ? gt("Unable to link pull request") |
| 1442 | : gt("Unable to unlink pull request"), |
| 1443 | description: thrownErrorMessage(cause, m) ?? gt("The request failed."), |
| 1444 | }), |
| 1445 | ); |
| 1446 | } |
| 1447 | }, |
| 1448 | }); |
| 1449 | }} |
| 1450 | > |
| 1451 | {faviconHost && hasText && !isPullRequestAutolink ? ( |
| 1452 | <MarkdownExternalLinkContent host={faviconHost} plainText={plainHastText(node)}> |
| 1453 | {linkChildren} |
| 1454 | </MarkdownExternalLinkContent> |
| 1455 | ) : ( |
| 1456 | linkChildren |
| 1457 | )} |
| 1458 | </a> |
| 1459 | ); |
| 1460 | if (!faviconHost || !href) { |
| 1461 | return link; |
| 1462 | } |
| 1463 | if (pullRequestPreviewTarget !== null) { |
| 1464 | return ( |
| 1465 | <PullRequestLinkPreview |
| 1466 | link={link} |
| 1467 | originalUrl={href} |
| 1468 | target={pullRequestPreviewTarget} |
| 1469 | confirmBeforeOpen={confirmBeforeOpen} |
| 1470 | onOpenPullRequest={(targetUrl) => |
| 1471 | openChangeRequestLink( |
| 1472 | { |
| 1473 | metaKey: false, |
| 1474 | ctrlKey: false, |
| 1475 | preventDefault: () => undefined, |
| 1476 | stopPropagation: () => undefined, |
| 1477 | }, |
| 1478 | targetUrl, |
| 1479 | undefined, |
| 1480 | environmentId ?? undefined, |
| 1481 | ) |
| 1482 | } |
| 1483 | // A reference that is not a pull request may still be an issue this app can show. |
| 1484 | onOpenFallback={async (url) => { |
| 1485 | const opened = openIssueLink( |
| 1486 | { |
| 1487 | metaKey: false, |
| 1488 | ctrlKey: false, |
| 1489 | preventDefault: () => undefined, |
| 1490 | stopPropagation: () => undefined, |
| 1491 | }, |
| 1492 | url, |
| 1493 | environmentId ?? undefined, |
| 1494 | issueTrackers, |
| 1495 | ); |
| 1496 | if (!opened) await openDeferredMarkdownLink(url); |
| 1497 | }} |
| 1498 | fallback={ |
| 1499 | issuePreviewTarget === null ? undefined : ( |
| 1500 | <IssueLinkPreviewFallback originalUrl={href} target={issuePreviewTarget} /> |
| 1501 | ) |
| 1502 | } |
| 1503 | /> |
| 1504 | ); |
| 1505 | } |
| 1506 | if (issuePreviewTarget !== null) { |
| 1507 | return <IssueLinkPreview link={link} originalUrl={href} target={issuePreviewTarget} />; |
| 1508 | } |
| 1509 | return ( |
| 1510 | <Tooltip> |
| 1511 | <TooltipTrigger render={link} /> |
| 1512 | <TooltipPopup side="top">{href}</TooltipPopup> |
| 1513 | </Tooltip> |
| 1514 | ); |
| 1515 | } |
| 1516 | |
| 1517 | const label = nodeToPlainText(children); |
| 1518 | const start = node?.position?.start.offset; |
| 1519 | const end = node?.position?.end.offset; |
| 1520 | const source = start !== undefined && end !== undefined ? text.slice(start, end) : ""; |
| 1521 | const copyMarkdown = |
| 1522 | source.startsWith("[") && source.includes("](") |
| 1523 | ? source |
| 1524 | : `[${(label || fileLinkMeta.basename).replace(/[\\[\]]/g, "\\$&")}](${normalizedHref})`; |
| 1525 | const chip = fileLinkChip(fileLinkMeta, copyMarkdown, normalizedHref); |
| 1526 | return isMarkdownFileLinkLabel(label, normalizedHref) ? ( |
| 1527 | chip |
| 1528 | ) : ( |
| 1529 | <span data-markdown-copy={copyMarkdown}> |
| 1530 | <span className="whitespace-normal">{children} </span> |
| 1531 | {chip} |
| 1532 | </span> |
| 1533 | ); |
| 1534 | }, |
| 1535 | code: function MarkdownCode({ node, children, className, ...props }) { |
| 1536 | const { cwd, imageBaseDir, inlineCodeFileLinkMetaByText, fileLinkChip, mathEnabled, inline } = |
| 1537 | use(ChatMarkdownRendererContext); |
| 1538 | const math = mathEnabled ? mathKind(className) : null; |
| 1539 | if (math) { |
| 1540 | return ( |
| 1541 | <MarkdownMath |
| 1542 | tex={nodeToPlainText(children)} |
| 1543 | display={math === "display"} |
| 1544 | focusable={!inline} |
| 1545 | /> |
| 1546 | ); |
| 1547 | } |
| 1548 | if (node?.properties?.dataInlineCode != null) { |
| 1549 | const codeText = nodeToPlainText(children); |
| 1550 | const fileLinkMeta = |
| 1551 | inlineCodeFileLinkMetaByText.get(codeText.trim()) ?? |
| 1552 | resolveInlineCodeFileLinkMeta(codeText, cwd, imageBaseDir ?? cwd); |
| 1553 | if (fileLinkMeta) { |
| 1554 | return fileLinkChip( |
| 1555 | fileLinkMeta, |
| 1556 | `\`${codeText}\``, |
| 1557 | inlineCodeFilePathCandidate(codeText) ?? codeText.trim(), |
| 1558 | ); |
| 1559 | } |
| 1560 | return ( |
| 1561 | <code {...props} className={className}> |
| 1562 | {children} |
| 1563 | </code> |
| 1564 | ); |
| 1565 | } |
| 1566 | return ( |
| 1567 | <code {...props} className={className}> |
| 1568 | {children} |
| 1569 | </code> |
| 1570 | ); |
| 1571 | }, |
| 1572 | img: function MarkdownImage({ node, title, src, alt, ...props }) { |
| 1573 | const { |
| 1574 | expandMedia, |
| 1575 | cwd, |
| 1576 | environmentId, |
| 1577 | sourceControlMedia, |
| 1578 | sourceControlMediaRepository, |
| 1579 | imageBaseDir, |
| 1580 | threadRef, |
| 1581 | workspaceMutationId, |
| 1582 | renderContextReference, |
| 1583 | fileLinkChip, |
| 1584 | resolvedTheme, |
| 1585 | } = use(ChatMarkdownRendererContext); |
| 1586 | const imageExpand = use(MarkdownLinkContext) ? undefined : expandMedia; |
| 1587 | const contextReference = typeof src === "string" ? parseComposerContextHref(src) : null; |
| 1588 | if (contextReference) { |
| 1589 | const label = alt || contextReference.contextId; |
| 1590 | return renderContextReference ? ( |
| 1591 | renderContextReference({ ...contextReference, label }) |
| 1592 | ) : ( |
| 1593 | <span>{label}</span> |
| 1594 | ); |
| 1595 | } |
| 1596 | const { authoredSrc: srcString = "", classifiedSrc = "" } = |
| 1597 | chatMarkdownImageSource(node?.properties ?? { src }, resolvedTheme) ?? {}; |
| 1598 | const markdownTitle = node?.properties?.dataMarkdownTitle; |
| 1599 | const standalone = node?.properties?.dataStandalone === true; |
| 1600 | const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title; |
| 1601 | const altText = alt ?? ""; |
| 1602 | const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle); |
| 1603 | const { className, style: _style, width, height, ...imageProps } = props; |
| 1604 | const authoredSizeStyle = authoredImageSizeStyle(width, height); |
| 1605 | const imageSource = classifyMarkdownImageSource(classifiedSrc, imageBaseDir ?? cwd); |
| 1606 | const mediaKind = mediaKindFromPath(classifiedSrc); |
| 1607 | if (mediaKind === "audio") { |
| 1608 | const filePath = imageSource._tag === "WorkspaceFile" ? imageSource.path : null; |
| 1609 | const name = |
| 1610 | (filePath ?? classifiedSrc.split(/[?#]/, 1)[0] ?? "").split(/[\\/]/).at(-1) || |
| 1611 | altText || |
| 1612 | "Audio"; |
| 1613 | if (imageSource._tag !== "Direct" && !(filePath && threadRef)) { |
| 1614 | return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind="audio" />; |
| 1615 | } |
| 1616 | return ( |
| 1617 | <InlineAudioPreview |
| 1618 | key={classifiedSrc} |
| 1619 | name={name} |
| 1620 | copyMarkdown={copyMarkdown} |
| 1621 | {...(filePath && threadRef |
| 1622 | ? { |
| 1623 | environmentId: threadRef.environmentId, |
| 1624 | resource: { |
| 1625 | _tag: "media-file" as const, |
| 1626 | threadId: threadRef.threadId, |
| 1627 | path: filePath, |
| 1628 | }, |
| 1629 | onOpen: () => useRightPanelStore.getState().openFile(threadRef, filePath), |
| 1630 | } |
| 1631 | : imageSource._tag === "Direct" |
| 1632 | ? { src: resolveProtocolRelativeMediaUrl(imageSource.uri) } |
| 1633 | : {})} |
| 1634 | /> |
| 1635 | ); |
| 1636 | } |
| 1637 | if (shouldRenderMarkdownImageAsFileLink(imageSource, mediaKind)) { |
| 1638 | const fileLinkMeta = resolveMarkdownFileLinkMeta(srcString, cwd, imageBaseDir ?? cwd); |
| 1639 | if (fileLinkMeta) return fileLinkChip(fileLinkMeta, copyMarkdown, srcString); |
| 1640 | } |
| 1641 | const kind = mediaKind ?? "image"; |
| 1642 | const directUri = imageSource._tag === "Direct" ? imageSource.uri : null; |
| 1643 | const hostMediaUrl = |
| 1644 | directUri === null |
| 1645 | ? null |
| 1646 | : (sourceControlClients.mediaUrl(resolveProtocolRelativeMediaUrl(directUri))?.fetchUrl ?? |
| 1647 | null); |
| 1648 | if ( |
| 1649 | sourceControlMedia && |
| 1650 | cwd !== undefined && |
| 1651 | environmentId !== null && |
| 1652 | directUri !== null && |
| 1653 | hostMediaUrl !== null |
| 1654 | ) { |
| 1655 | return ( |
| 1656 | <ChatMarkdownAssetImage |
| 1657 | environmentId={environmentId} |
| 1658 | resource={{ |
| 1659 | _tag: SOURCE_CONTROL_MEDIA_ASSET, |
| 1660 | cwd, |
| 1661 | url: hostMediaUrl, |
| 1662 | ...(sourceControlMediaRepository ? { repository: sourceControlMediaRepository } : {}), |
| 1663 | }} |
| 1664 | alt={altText} |
| 1665 | kind={kind} |
| 1666 | copyMarkdown={copyMarkdown} |
| 1667 | standalone={standalone} |
| 1668 | className={className} |
| 1669 | style={authoredSizeStyle} |
| 1670 | imageProps={imageProps} |
| 1671 | srcFragment={markdownImageSourceFragment(classifiedSrc)} |
| 1672 | originalUrl={resolveProtocolRelativeMediaUrl(directUri)} |
| 1673 | framed={false} |
| 1674 | fallbackSrc={hostMediaUrl} |
| 1675 | onImageExpand={imageExpand} |
| 1676 | /> |
| 1677 | ); |
| 1678 | } |
| 1679 | if (imageSource._tag === "Direct") { |
| 1680 | const mediaSrc = resolveProtocolRelativeMediaUrl(imageSource.uri); |
| 1681 | const originalUrl = |
| 1682 | resolveExternalWebLinkHost(imageSource.uri) !== null ? imageSource.uri : undefined; |
| 1683 | const reference = mediaUrlReference(imageSource.uri); |
| 1684 | const actionsSource: MediaActionSource = { |
| 1685 | kind, |
| 1686 | name: altText || kind, |
| 1687 | src: mediaSrc, |
| 1688 | ...(reference ? { reference } : {}), |
| 1689 | }; |
| 1690 | if (kind === "video") { |
| 1691 | return ( |
| 1692 | <ChatMarkdownVideo |
| 1693 | src={mediaSrc} |
| 1694 | alt={altText} |
| 1695 | copyMarkdown={copyMarkdown} |
| 1696 | originalUrl={originalUrl} |
| 1697 | style={authoredSizeStyle} |
| 1698 | actionsSource={actionsSource} |
| 1699 | /> |
| 1700 | ); |
| 1701 | } |
| 1702 | return ( |
| 1703 | <ChatMarkdownImage |
| 1704 | key={mediaSrc} |
| 1705 | src={mediaSrc} |
| 1706 | alt={altText} |
| 1707 | copyMarkdown={copyMarkdown} |
| 1708 | standalone={standalone} |
| 1709 | className={className} |
| 1710 | style={authoredSizeStyle} |
| 1711 | imageProps={imageProps} |
| 1712 | actionsSource={actionsSource} |
| 1713 | originalUrl={originalUrl} |
| 1714 | onImageExpand={imageExpand} |
| 1715 | /> |
| 1716 | ); |
| 1717 | } |
| 1718 | const hostImageUrl = use(HostImageUrlContext); |
| 1719 | if (imageSource._tag === "WorkspaceFile" && kind === "image" && hostImageUrl !== null) { |
| 1720 | const hostSrc = hostImageUrl(imageSource.path); |
| 1721 | return ( |
| 1722 | <ChatMarkdownImage |
| 1723 | key={hostSrc} |
| 1724 | src={hostSrc} |
| 1725 | alt={altText} |
| 1726 | copyMarkdown={copyMarkdown} |
| 1727 | standalone={standalone} |
| 1728 | className={className} |
| 1729 | style={authoredSizeStyle} |
| 1730 | imageProps={imageProps} |
| 1731 | actionsSource={{ kind, name: altText || kind, src: hostSrc }} |
| 1732 | onImageExpand={imageExpand} |
| 1733 | /> |
| 1734 | ); |
| 1735 | } |
| 1736 | if (imageSource._tag === "WorkspaceFile" && threadRef) { |
| 1737 | return ( |
| 1738 | <ChatMarkdownAssetImage |
| 1739 | environmentId={threadRef.environmentId} |
| 1740 | resource={{ |
| 1741 | _tag: "media-file", |
| 1742 | threadId: threadRef.threadId, |
| 1743 | path: imageSource.path, |
| 1744 | ...(imageSource.relative ? { hostOnly: true as const } : {}), |
| 1745 | }} |
| 1746 | alt={altText} |
| 1747 | kind={kind} |
| 1748 | copyMarkdown={copyMarkdown} |
| 1749 | srcFragment={markdownImageSourceFragment(classifiedSrc)} |
| 1750 | standalone={standalone} |
| 1751 | style={authoredSizeStyle} |
| 1752 | workspaceRoot={cwd} |
| 1753 | workspaceMutationId={workspaceMutationId} |
| 1754 | onImageExpand={imageExpand} |
| 1755 | /> |
| 1756 | ); |
| 1757 | } |
| 1758 | return <ChatMarkdownImageFallback alt={altText} copyMarkdown={copyMarkdown} kind={kind} />; |
| 1759 | }, |
| 1760 | table: function MarkdownTableRenderer({ node: _node, ...props }) { |
| 1761 | return <MarkdownTable {...props} />; |
| 1762 | }, |
| 1763 | details: function MarkdownDetailsRenderer({ node: _node, children, open: detailsOpen, dir }) { |
| 1764 | return ( |
| 1765 | <MarkdownDetails open={detailsOpen} dir={dir}> |
| 1766 | {children} |
| 1767 | </MarkdownDetails> |
| 1768 | ); |
| 1769 | }, |
| 1770 | pre: function MarkdownPre({ node, children, ...props }) { |
| 1771 | const gt = useGT(); |
| 1772 | const { |
| 1773 | resolvedTheme, |
| 1774 | diffThemeName, |
| 1775 | expandMedia, |
| 1776 | isStreaming, |
| 1777 | onRunShellCommand, |
| 1778 | inline, |
| 1779 | mathEnabled, |
| 1780 | } = use(ChatMarkdownRendererContext); |
| 1781 | const text = use(ChatMarkdownTextContext); |
| 1782 | const codeBlock = extractCodeBlock(children); |
| 1783 | if (!codeBlock) { |
| 1784 | return <pre {...props}>{children}</pre>; |
| 1785 | } |
| 1786 | |
| 1787 | const language = extractFenceLanguage(codeBlock.className); |
| 1788 | if ( |
| 1789 | mathEnabled && |
| 1790 | language === "math" && |
| 1791 | (!isStreaming || |
| 1792 | mathKind(codeBlock.className) === "display" || |
| 1793 | isClosedCodeFence(node, text, codeBlock.code)) |
| 1794 | ) { |
| 1795 | return <MarkdownMath tex={codeBlock.code} display focusable={!inline} />; |
| 1796 | } |
| 1797 | const fenceTitle = extractFenceTitle(extractPreCodeMeta(node)); |
| 1798 | const highlightedCode = ( |
| 1799 | <RenderErrorBoundary |
| 1800 | resetKeys={[codeBlock.code, language, diffThemeName, isStreaming]} |
| 1801 | fallback={<pre {...props}>{children}</pre>} |
| 1802 | > |
| 1803 | <Suspense |
| 1804 | fallback={ |
| 1805 | <pre {...props} className="invisible" aria-hidden> |
| 1806 | {children} |
| 1807 | </pre> |
| 1808 | } |
| 1809 | > |
| 1810 | <SuspenseShikiCodeBlock |
| 1811 | className={codeBlock.className} |
| 1812 | code={codeBlock.code} |
| 1813 | themeName={diffThemeName} |
| 1814 | isStreaming={isStreaming} |
| 1815 | /> |
| 1816 | </Suspense> |
| 1817 | </RenderErrorBoundary> |
| 1818 | ); |
| 1819 | if (language === "mermaid") { |
| 1820 | return ( |
| 1821 | <MarkdownMermaidCodeBlock |
| 1822 | code={codeBlock.code} |
| 1823 | fenceTitle={fenceTitle} |
| 1824 | theme={resolvedTheme} |
| 1825 | isStreaming={isStreaming && !isClosedCodeFence(node, text, codeBlock.code)} |
| 1826 | onExpand={(src) => |
| 1827 | expandMedia({ |
| 1828 | images: [{ src, name: gt("Mermaid diagram"), mimeType: "image/svg+xml" }], |
| 1829 | index: 0, |
| 1830 | }) |
| 1831 | } |
| 1832 | > |
| 1833 | {highlightedCode} |
| 1834 | </MarkdownMermaidCodeBlock> |
| 1835 | ); |
| 1836 | } |
| 1837 | return ( |
| 1838 | <MarkdownCodeBlock |
| 1839 | code={codeBlock.code} |
| 1840 | language={language} |
| 1841 | fenceTitle={fenceTitle} |
| 1842 | theme={resolvedTheme} |
| 1843 | onRunShellCommand={ |
| 1844 | onRunShellCommand && !isStreaming && isClosedCodeFence(node, text, codeBlock.code) |
| 1845 | ? onRunShellCommand |
| 1846 | : undefined |
| 1847 | } |
| 1848 | isStreaming={isStreaming} |
| 1849 | > |
| 1850 | {highlightedCode} |
| 1851 | </MarkdownCodeBlock> |
| 1852 | ); |
| 1853 | }, |
| 1854 | } satisfies Components; |
| 1855 | |
| 1856 | const REMARK_MATH: Pluggable = [remarkMath, { singleDollarTextMath: true }]; |
| 1857 | // Shared lists, so every message with the same options shares a processor and its cache. |
| 1858 | const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = { |
| 1859 | plain: CHAT_MARKDOWN_REMARK_PLUGINS, |
| 1860 | breaks: CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, |
| 1861 | math: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS], |
| 1862 | mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], |
| 1863 | } satisfies Record<string, PluggableList>; |
| 1864 | |
| 1865 | const combinedPlugins = new WeakMap<PluggableList, WeakMap<PluggableList, PluggableList>>(); |
| 1866 | |
| 1867 | // One combined list per pair, so a stable extra list shares a renderer and its parse cache. |
| 1868 | const INSIGHT_REMARK_PLUGINS: PluggableList = [remarkAssistantInsights]; |
| 1869 | |
| 1870 | function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList { |
| 1871 | if (extra.length === 0) return shared; |
| 1872 | let byShared = combinedPlugins.get(extra); |
| 1873 | if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap())); |
| 1874 | let combined = byShared.get(shared); |
| 1875 | if (!combined) byShared.set(shared, (combined = [...shared, ...extra])); |
| 1876 | return combined; |
| 1877 | } |
| 1878 | |
| 1879 | const markdownRenderers = new WeakMap< |
| 1880 | PluggableList, |
| 1881 | WeakMap<PluggableList, ReturnType<typeof createMarkdownRenderer>> |
| 1882 | >(); |
| 1883 | |
| 1884 | function markdownRenderer(remarkPlugins: PluggableList, rehypePlugins: PluggableList) { |
| 1885 | let byRehype = markdownRenderers.get(remarkPlugins); |
| 1886 | if (!byRehype) markdownRenderers.set(remarkPlugins, (byRehype = new WeakMap())); |
| 1887 | let renderer = byRehype.get(rehypePlugins); |
| 1888 | if (!renderer) { |
| 1889 | renderer = createMarkdownRenderer({ |
| 1890 | remarkPlugins, |
| 1891 | rehypePlugins, |
| 1892 | components: CHAT_MARKDOWN_COMPONENTS, |
| 1893 | urlTransform: markdownUrlTransform, |
| 1894 | }); |
| 1895 | byRehype.set(rehypePlugins, renderer); |
| 1896 | } |
| 1897 | return renderer; |
| 1898 | } |
| 1899 | |
| 1900 | const MarkdownSource = memo(function MarkdownSource({ |
| 1901 | text, |
| 1902 | remarkPlugins, |
| 1903 | rehypePlugins, |
| 1904 | shared, |
| 1905 | cache, |
| 1906 | }: { |
| 1907 | text: string; |
| 1908 | remarkPlugins: PluggableList; |
| 1909 | rehypePlugins: PluggableList; |
| 1910 | /** The plugins are one of the shared sets. */ |
| 1911 | shared: boolean; |
| 1912 | /** The text will not change again; streamed text would only fill the cache with prefixes. */ |
| 1913 | cache: boolean; |
| 1914 | }) { |
| 1915 | // Per-instance plugins, such as the incremental parser, set up their state on every render. |
| 1916 | const render = shared |
| 1917 | ? markdownRenderer(remarkPlugins, rehypePlugins) |
| 1918 | : createMarkdownRenderer({ |
| 1919 | remarkPlugins, |
| 1920 | rehypePlugins, |
| 1921 | components: CHAT_MARKDOWN_COMPONENTS, |
| 1922 | urlTransform: markdownUrlTransform, |
| 1923 | }); |
| 1924 | const element = render(text); |
| 1925 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Caching during render would make React Compiler rebuild the element when `cache` flips. |
| 1926 | useEffect(() => { |
| 1927 | if (shared && cache) render.remember(text, element); |
| 1928 | }, [render, text, element, shared, cache]); |
| 1929 | return <ChatMarkdownTextContext value={text}>{element}</ChatMarkdownTextContext>; |
| 1930 | }); |
| 1931 | |
| 1932 | function ChatMarkdown({ |
| 1933 | text, |
| 1934 | className, |
| 1935 | inline = false, |
| 1936 | lineBreaks = false, |
| 1937 | parseRawHtml = true, |
| 1938 | extraRemarkPlugins = EMPTY_REMARK_PLUGINS, |
| 1939 | renderInsights = false, |
| 1940 | ...props |
| 1941 | }: ChatMarkdownProps) { |
| 1942 | const { componentState, handleCopy, markdownRef, localMediaPreview, closeLocalMediaPreview } = |
| 1943 | useChatMarkdownState({ text, inline, ...props }); |
| 1944 | const hasInsights = renderInsights && text.includes("★ Insight"); |
| 1945 | // Streaming re-renders only the last block; offsets for task edits need the whole text. |
| 1946 | const streamingBlocks = |
| 1947 | props.isStreaming === true && |
| 1948 | !inline && |
| 1949 | extraRemarkPlugins.length === 0 && |
| 1950 | !props.onTaskListChange |
| 1951 | ? splitMarkdownBlocks(text) |
| 1952 | : null; |
| 1953 | const incrementalParsing = |
| 1954 | props.isStreaming === true && |
| 1955 | !hasInsights && |
| 1956 | streamingBlocks === null && |
| 1957 | extraRemarkPlugins.length === 0 && |
| 1958 | /(?:^|\n) {0,3}(?:`{3}|~{3})/.test(text); |
| 1959 | const Root = inline ? "span" : "div"; |
| 1960 | const bindMarkdownRef = (node: HTMLElement | null) => { |
| 1961 | markdownRef.current = node; |
| 1962 | }; |
| 1963 | const sharedRemarkPlugins = |
| 1964 | CHAT_MARKDOWN_REMARK_PLUGIN_SETS[ |
| 1965 | componentState.mathEnabled |
| 1966 | ? lineBreaks |
| 1967 | ? "mathBreaks" |
| 1968 | : "math" |
| 1969 | : lineBreaks |
| 1970 | ? "breaks" |
| 1971 | : "plain" |
| 1972 | ]; |
| 1973 | // The incremental parser keeps per-instance state, so its output is not shared. |
| 1974 | const uncachedPlugins = incrementalParsing; |
| 1975 | const remarkPlugins = incrementalParsing |
| 1976 | ? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()] |
| 1977 | : withExtraPlugins( |
| 1978 | hasInsights |
| 1979 | ? withExtraPlugins(INSIGHT_REMARK_PLUGINS, sharedRemarkPlugins) |
| 1980 | : sharedRemarkPlugins, |
| 1981 | extraRemarkPlugins, |
| 1982 | ); |
| 1983 | const blocks = streamingBlocks ?? [text]; |
| 1984 | |
| 1985 | return ( |
| 1986 | <Root |
| 1987 | ref={bindMarkdownRef} |
| 1988 | className={cn( |
| 1989 | "chat-markdown w-full min-w-0 [overflow-wrap:anywhere] [word-break:break-word]", |
| 1990 | !inline && |
| 1991 | "text-sm leading-relaxed text-foreground/[calc(90%+var(--appearance-contrast-boost)/10)]", |
| 1992 | className, |
| 1993 | )} |
| 1994 | data-streaming={componentState.isStreaming ? "" : undefined} |
| 1995 | onCopy={handleCopy} |
| 1996 | > |
| 1997 | <ChatMarkdownRendererContext value={componentState}> |
| 1998 | {blocks.map((source, index) => ( |
| 1999 | <MarkdownSource |
| 2000 | // oxlint-disable-next-line react/no-array-index-key -- streamed blocks only change at the end |
| 2001 | key={index} |
| 2002 | text={source} |
| 2003 | remarkPlugins={remarkPlugins} |
| 2004 | rehypePlugins={ |
| 2005 | parseRawHtml |
| 2006 | ? CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS |
| 2007 | : CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS |
| 2008 | } |
| 2009 | shared={!uncachedPlugins} |
| 2010 | // Every block before the last is finished, so its parse can be reused. |
| 2011 | cache={!props.isStreaming || index < blocks.length - 1} |
| 2012 | /> |
| 2013 | ))} |
| 2014 | </ChatMarkdownRendererContext> |
| 2015 | {localMediaPreview ? ( |
| 2016 | <ExpandedImageDialog preview={localMediaPreview} onClose={closeLocalMediaPreview} /> |
| 2017 | ) : null} |
| 2018 | </Root> |
| 2019 | ); |
| 2020 | } |
| 2021 | |
| 2022 | export default memo(ChatMarkdown); |