The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
refactor(web): chat markdown links and file chips live in their own modules (#22693)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:32 UTC
827f6d4f4a363e646f47f320285d28c3885113b7
6 files changed
+745
-715
apps/web/src/components/ChatMarkdown.tsx
+7
-715
@@ -1,9 +1,4 @@
1
-import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2
-import {
3
- buildFileLinkParentSuffixByPath,
4
- fileLinkLabel,
5
- splitFilePathPosition,
6
-} from "@t3tools/shared/fileLinks";
1
+import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks";
2
import {
3
isWindowsDrivePathHref,
4
normalizeMarkdownLinkDestination,
@@ -51,12 +46,10 @@ import {
46
type ServerProviderSkill,
47
type ThreadPullRequestKey,
48
} from "@t3tools/contracts";
54
-import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
49
import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
50
import {
51
isAtomCommandInterrupted,
52
squashAtomCommandFailure,
59
- type AtomCommandResult,
53
} from "@t3tools/client-runtime/state/runtime";
54
import {
55
codexArtifactTemplatePresentationLabel,
@@ -75,7 +68,6 @@ import * as Option from "effect/Option";
68
import * as Schema from "effect/Schema";
69
import { AsyncResult, Atom } from "effect/reactivity";
70
import React, {
78
- Children,
71
Suspense,
72
type CSSProperties,
73
type ComponentProps,
@@ -120,8 +112,6 @@ import { markdownImageGallery, markdownImageItems } from "./chat/markdownImageGa
112
import { MediaVideoPlayer } from "./media/MediaVideoPlayer";
113
import { MediaActions, type MediaActionSource } from "./media/MediaActions";
114
import { resolveProtocolRelativeMediaUrl } from "./media/mediaContent";
123
-import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon";
124
-import { FileTagChipContent } from "./chat/FileTagChip";
115
import {
116
revealInFileExplorerLabelForKind,
117
revealInFileExplorerLabelForOs,
@@ -132,7 +122,6 @@ import {
122
} from "./chat/externalLinkContextMenu";
123
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
124
import { Button } from "./ui/button";
135
-import { ContextChip } from "./ContextChip";
125
import { stackedThreadToast, toastManager } from "./ui/toast";
126
import { recordVisitForThread } from "../browserHistoryStore";
127
import {
@@ -142,7 +131,6 @@ import {
131
} from "../editorPreferences";
132
import { openInEditorMenuLabel } from "../editorLabels";
133
import { resolveDiffThemeName } from "../lib/diffRendering";
145
-import { GitHubIcon } from "./Icons";
134
import { RenderErrorBoundary } from "./RenderErrorBoundary";
135
import { useRenderedAppearance } from "../hooks/useTheme";
136
import { useClientSettings } from "../hooks/useSettings";
@@ -151,8 +139,6 @@ import {
139
resolveInlineCodeFileLinkMeta,
140
resolveMarkdownFileLinkMeta,
141
rewriteMarkdownFileUriHref,
154
- shouldOpenMarkdownFileLinkInBrowserByDefault,
155
- shouldOpenMarkdownFileLinkInEditor,
142
type MarkdownFileLinkMeta,
143
} from "../markdown-links";
144
import {
@@ -165,11 +151,7 @@ import { isElectron } from "../env";
151
import { readLocalApi } from "../localApi";
152
import { useAssetUrlRefresh, useAssetUrlState } from "../assets/assetUrls";
153
import { cn } from "../lib/utils";
168
-import {
169
- resolveRemoteOpenState,
170
- useRemoteOpenResolution,
171
- type RemoteOpenMode,
172
-} from "../remoteOpen";
154
+import { resolveRemoteOpenState, useRemoteOpenResolution } from "../remoteOpen";
155
import { useRightPanelStore } from "../rightPanelStore";
156
import { readThreadShell, useProjects } from "../state/entities";
157
import { serverEnvironment } from "../state/server";
@@ -216,6 +198,11 @@ import { MarkdownCodeBlock, SuspenseShikiCodeBlock } from "./chat/MarkdownCodeBl
198
import { MarkdownMermaidCodeBlock } from "./chat/MarkdownMermaidCodeBlock";
199
import { MarkdownTable } from "./chat/MarkdownTable";
200
import { MarkdownDetails } from "./chat/MarkdownDetails";
201
+import { MarkdownExternalLinkContent } from "./chat/MarkdownExternalLink";
202
+import { MarkdownFileLink } from "./chat/MarkdownFileLink";
203
+import { canUseMarkdownFileShellActions } from "./chat/MarkdownFileLink.logic";
204
+import { handleMarkdownFragmentClick, rehypeHeadingIds } from "./chat/markdownFragments";
205
+import { hastHasText, hastPlainTextDeep, plainHastText } from "./chat/markdownHast.logic";
206
import {
207
extractCodeBlock,
208
extractFenceLanguage,
@@ -261,60 +248,6 @@ export interface ChatMarkdownContextReference {
248
label: string;
249
}
250
264
-export function canUseMarkdownFileShellActions(
265
- environmentId: EnvironmentId | null,
266
- remoteOpenMode: RemoteOpenMode,
267
- isRemoteOpenResolved: boolean,
268
-): boolean {
269
- return environmentId !== null && isRemoteOpenResolved && remoteOpenMode === "local-exec";
270
-}
271
-
272
-function hasMarkdownFilePrimaryAction(input: {
273
- canOpenInEditor: boolean;
274
- canOpenInBrowser: boolean;
275
- canOpenInPanel: boolean;
276
- canOpenMedia?: boolean;
277
-}): boolean {
278
- return (
279
- input.canOpenInEditor ||
280
- input.canOpenInBrowser ||
281
- input.canOpenInPanel ||
282
- input.canOpenMedia === true
283
- );
284
-}
285
-
286
-export function markdownFileCopyMenuItems({
287
- targetPath,
288
- workspaceRelativePath,
289
-}: Pick<MarkdownFileLinkMeta, "targetPath" | "workspaceRelativePath">) {
290
- const items = [
291
- { id: "copy-full", label: "Copy full path", value: targetPath, title: "Full path" },
292
- ];
293
- if (workspaceRelativePath !== null) {
294
- const position = targetPath.slice(splitFilePathPosition(targetPath).path.length);
295
- items.unshift({
296
- id: "copy-relative",
297
- label: "Copy relative path",
298
- value: `${workspaceRelativePath}${position}`,
299
- title: "Relative path",
300
- });
301
- }
302
- return items;
303
-}
304
-
305
-export function shouldUseMarkdownFileBrowserPrimaryAction(input: {
306
- iconPath: string;
307
- canOpenInEditor: boolean;
308
- canOpenInBrowser: boolean;
309
- canOpenInPanel: boolean;
310
-}): boolean {
311
- return (
312
- input.canOpenInBrowser &&
313
- (shouldOpenMarkdownFileLinkInBrowserByDefault(input.iconPath) ||
314
- (!input.canOpenInEditor && !input.canOpenInPanel))
315
- );
316
-}
317
-
251
const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
252
const EMPTY_REMARK_PLUGINS: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = [];
253
@@ -439,30 +372,6 @@ const GITHUB_ALERT_PRESENTATIONS: Record<
372
},
373
};
374
442
-interface MarkdownFileLinkProps {
443
- environmentId: EnvironmentId | null;
444
- href: string;
445
- targetPath: string;
446
- iconPath: string;
447
- workspaceRelativePath: string | null;
448
- panelPath: string | null;
449
- line?: number | undefined;
450
- label: string;
451
- copyMarkdown: string;
452
- theme: "light" | "dark";
453
- threadRef?: ScopedThreadRef | undefined;
454
- onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
455
- onOpenInPanel: (panelPath: string, line: number | undefined) => void;
456
- resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;
457
- openInEditorMenuLabel: string;
458
- onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
459
- onOpenMedia?: (() => void) | undefined;
460
- onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
461
- revealLabel?: string | undefined;
462
-}
463
-
464
-const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";
465
-
375
function normalizeMarkdownLinkHrefKey(href: string): string {
376
const normalizedHref = normalizeMarkdownLinkDestination(href);
377
const rewrittenHref = rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
@@ -471,45 +380,6 @@ function normalizeMarkdownLinkHrefKey(href: string): string {
380
: rewrittenHref;
381
}
382
474
-const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
475
-
476
-const failedFaviconHosts = new Set<string>();
477
-
478
-function isGitHubHost(host: string): boolean {
479
- const hostname = host.toLowerCase();
480
- return hostname === "github.com" || hostname.endsWith(".github.com");
481
-}
482
-
483
-const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
484
- const [failedHost, setFailedHost] = useState<string | null>(null);
485
- const brandIcon = isGitHubHost(host);
486
- const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
487
- return (
488
- <span
489
- className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
490
- aria-hidden
491
- >
492
- {brandIcon ? (
493
- <GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
494
- ) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
495
- <GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
496
- ) : (
497
- <img
498
- src={faviconUrl}
499
- alt=""
500
- loading="lazy"
501
- draggable={false}
502
- className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
503
- onError={() => {
504
- failedFaviconHosts.add(host);
505
- setFailedHost(host);
506
- }}
507
- />
508
- )}
509
- </span>
510
- );
511
-});
512
-
383
const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]";
384
const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn(
385
"max-h-[30rem]",
@@ -952,171 +822,6 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
822
);
823
});
824
955
-function leadingExternalLinkTextLength(text: string): number {
956
- const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0];
957
- if (protocol) return protocol.length;
958
- return Math.min(text.length, 1);
959
-}
960
-
961
-function breakableExternalLinkText(text: string): ReactNode[] {
962
- return Array.from(text, (character, index) => (
963
- <React.Fragment key={`${index}:${character}`}>
964
- {character}
965
- <wbr />
966
- </React.Fragment>
967
- ));
968
-}
969
-
970
-function plainHastText(node: unknown): string | null {
971
- if (!node || typeof node !== "object" || !("children" in node) || !Array.isArray(node.children)) {
972
- return null;
973
- }
974
- const parts = node.children.map((child) => {
975
- if (
976
- child &&
977
- typeof child === "object" &&
978
- "type" in child &&
979
- child.type === "text" &&
980
- "value" in child &&
981
- typeof child.value === "string"
982
- ) {
983
- return child.value;
984
- }
985
- return null;
986
- });
987
- return parts.every((part) => part !== null) ? parts.join("") : null;
988
-}
989
-
990
-function hastPlainTextDeep(node: unknown): string {
991
- if (!node || typeof node !== "object") return "";
992
- if ("type" in node && node.type === "text" && "value" in node && typeof node.value === "string") {
993
- return node.value;
994
- }
995
- if (!("children" in node) || !Array.isArray(node.children)) return "";
996
- return node.children.map(hastPlainTextDeep).join("");
997
-}
998
-
999
-function hastHasText(node: unknown): boolean {
1000
- if (!node || typeof node !== "object") return false;
1001
- if (
1002
- "type" in node &&
1003
- node.type === "text" &&
1004
- "value" in node &&
1005
- typeof node.value === "string" &&
1006
- node.value.trim().length > 0
1007
- ) {
1008
- return true;
1009
- }
1010
- return "children" in node && Array.isArray(node.children) && node.children.some(hastHasText);
1011
-}
1012
-
1013
-const SANITIZED_FRAGMENT_PREFIX = "user-content-";
1014
-
1015
-function decodeMarkdownFragmentId(href: string): string {
1016
- const encodedId = href.slice(1);
1017
- try {
1018
- return decodeURIComponent(encodedId);
1019
- } catch {
1020
- return encodedId;
1021
- }
1022
-}
1023
-
1024
-function normalizeSanitizedFragmentId(id: string): string {
1025
- let normalizedId = id;
1026
- while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
1027
- normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
1028
- }
1029
- return normalizedId;
1030
-}
1031
-
1032
-function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
1033
- const decodedId = decodeMarkdownFragmentId(href);
1034
- const normalizedId = normalizeSanitizedFragmentId(decodedId);
1035
- const matchesFragment = (element: HTMLElement) =>
1036
- element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
1037
- const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
1038
- if (markdownRoot) {
1039
- const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
1040
- const localTarget = localTargets.find(matchesFragment);
1041
- if (localTarget) return localTarget;
1042
- }
1043
-
1044
- return (
1045
- document.getElementById(decodedId) ??
1046
- Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
1047
- null
1048
- );
1049
-}
1050
-
1051
-function handleMarkdownFragmentClick(event: ReactMouseEvent<HTMLAnchorElement>, href: string) {
1052
- if (
1053
- event.defaultPrevented ||
1054
- event.button !== 0 ||
1055
- event.metaKey ||
1056
- event.ctrlKey ||
1057
- event.shiftKey ||
1058
- event.altKey
1059
- ) {
1060
- return;
1061
- }
1062
-
1063
- // Never let the browser follow the fragment or write it to the URL: desktop keeps
1064
- // its route in the hash, so replacing the hash navigates away from the thread.
1065
- event.preventDefault();
1066
- findMarkdownFragmentTarget(event.currentTarget, href)?.scrollIntoView({ block: "start" });
1067
-}
1068
-
1069
-type HeadingHastNode = {
1070
- type?: string;
1071
- tagName?: string;
1072
- properties?: Record<string, unknown>;
1073
- children?: HeadingHastNode[];
1074
-};
1075
-
1076
-function githubHeadingSlug(text: string): string {
1077
- return text
1078
- .trim()
1079
- .toLowerCase()
1080
- .replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "")
1081
- .replace(/ /g, "-");
1082
-}
1083
-
1084
-/**
1085
- * Like the sanitizer's ids, they carry the `user-content-` prefix so they cannot clobber app
1086
- * element ids; fragment lookup strips it.
1087
- */
1088
-function rehypeHeadingIds() {
1089
- return (tree: HeadingHastNode) => {
1090
- const taken = new Set<string>();
1091
- const collect = (node: HeadingHastNode) => {
1092
- const id = node.properties?.id;
1093
- if (typeof id === "string") taken.add(id);
1094
- node.children?.forEach(collect);
1095
- };
1096
- collect(tree);
1097
- const nextSuffix = new Map<string, number>();
1098
- const visit = (node: HeadingHastNode) => {
1099
- if (node.type === "element" && node.tagName && /^h[1-6]$/.test(node.tagName)) {
1100
- const slug = githubHeadingSlug(hastPlainTextDeep(node));
1101
- if (node.properties?.id === undefined && slug) {
1102
- let count = nextSuffix.get(slug) ?? 0;
1103
- let id = `${SANITIZED_FRAGMENT_PREFIX}${slug}`;
1104
- while (taken.has(id)) {
1105
- count += 1;
1106
- id = `${SANITIZED_FRAGMENT_PREFIX}${slug}-${count}`;
1107
- }
1108
- nextSuffix.set(slug, count);
1109
- taken.add(id);
1110
- node.properties = { ...node.properties, id };
1111
- }
1112
- return;
1113
- }
1114
- node.children?.forEach(visit);
1115
- };
1116
- visit(tree);
1117
- };
1118
-}
1119
-
825
// Heading ids are added after sanitizing, which would prefix them a second time.
826
const CHAT_MARKDOWN_RENDER_REHYPE_PLUGINS = [
827
...CHAT_MARKDOWN_REHYPE_PLUGINS,
@@ -1127,419 +832,6 @@ const CHAT_MARKDOWN_LITERAL_HTML_REHYPE_PLUGINS = [rehypeHeadingIds] satisfies N
832
ReactMarkdownOptions["rehypePlugins"]
833
>;
834
1130
-function MarkdownExternalLinkContent({
1131
- host,
1132
- plainText,
1133
- children,
1134
-}: {
1135
- host: string;
1136
- plainText: string | null;
1137
- children: ReactNode;
1138
-}) {
1139
- if (plainText) {
1140
- const leadingLength = leadingExternalLinkTextLength(plainText);
1141
- return (
1142
- <>
1143
- <span className="whitespace-nowrap">
1144
- <MarkdownLinkFavicon host={host} />
1145
- {plainText.slice(0, leadingLength)}
1146
- </span>
1147
- {breakableExternalLinkText(plainText.slice(leadingLength))}
1148
- </>
1149
- );
1150
- }
1151
-
1152
- const childNodes = Children.toArray(children);
1153
- const firstChild = childNodes[0];
1154
-
1155
- if (typeof firstChild === "string" && firstChild.length > 0) {
1156
- const leadingLength = leadingExternalLinkTextLength(firstChild);
1157
- return (
1158
- <>
1159
- <span className="whitespace-nowrap">
1160
- <MarkdownLinkFavicon host={host} />
1161
- {firstChild.slice(0, leadingLength)}
1162
- </span>
1163
- {breakableExternalLinkText(firstChild.slice(leadingLength))}
1164
- {childNodes.slice(1)}
1165
- </>
1166
- );
1167
- }
1168
-
1169
- return (
1170
- <>
1171
- <span className="whitespace-nowrap">
1172
- <MarkdownLinkFavicon host={host} />
1173
- {firstChild}
1174
- </span>
1175
- {childNodes.slice(1)}
1176
- </>
1177
- );
1178
-}
1179
-
1180
-const MarkdownFileLink = memo(function MarkdownFileLink({
1181
- environmentId,
1182
- href,
1183
- targetPath,
1184
- iconPath,
1185
- workspaceRelativePath,
1186
- panelPath,
1187
- line,
1188
- label,
1189
- copyMarkdown,
1190
- theme,
1191
- threadRef,
1192
- onOpen,
1193
- onOpenInPanel,
1194
- openInEditorMenuLabel,
1195
- onOpenInBrowser,
1196
- onOpenMedia,
1197
- onReveal,
1198
- revealLabel,
1199
- resolveCopyPaths,
1200
-}: MarkdownFileLinkProps) {
1201
- const handleOpenInEditor = () => {
1202
- if (!onOpen) {
1203
- return;
1204
- }
1205
- void (async () => {
1206
- try {
1207
- const result = await onOpen();
1208
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1209
- return;
1210
- }
1211
- reportMarkdownActionFailure(
1212
- { operation: "open-file-in-editor", target: targetPath },
1213
- result.cause,
1214
- );
1215
- const error = squashAtomCommandFailure(result);
1216
- toastManager.add(
1217
- stackedThreadToast({
1218
- type: "error",
1219
- title: "Unable to open file",
1220
- description: error instanceof Error ? error.message : "An error occurred.",
1221
- }),
1222
- );
1223
- } catch (cause) {
1224
- reportMarkdownActionFailure(
1225
- { operation: "open-file-in-editor", target: targetPath },
1226
- cause,
1227
- );
1228
- toastManager.add(
1229
- stackedThreadToast({
1230
- type: "error",
1231
- title: "Unable to open file",
1232
- description: cause instanceof Error ? cause.message : "An error occurred.",
1233
- }),
1234
- );
1235
- }
1236
- })();
1237
- };
1238
-
1239
- const handleOpenInFilePreview = () => {
1240
- if (threadRef && panelPath) {
1241
- onOpenInPanel(panelPath, line);
1242
- return;
1243
- }
1244
- if (onOpenMedia) {
1245
- onOpenMedia();
1246
- return;
1247
- }
1248
- handleOpenInEditor();
1249
- };
1250
-
1251
- const handleOpenInBrowser = () => {
1252
- if (!onOpenInBrowser) {
1253
- return;
1254
- }
1255
- void (async () => {
1256
- try {
1257
- const result = await onOpenInBrowser();
1258
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1259
- return;
1260
- }
1261
- reportMarkdownActionFailure(
1262
- { operation: "open-file-in-browser", target: targetPath },
1263
- result.cause,
1264
- );
1265
- const error = squashAtomCommandFailure(result);
1266
- toastManager.add(
1267
- stackedThreadToast({
1268
- type: "error",
1269
- title: "Unable to open file in browser",
1270
- description: error instanceof Error ? error.message : "An error occurred.",
1271
- }),
1272
- );
1273
- } catch (cause) {
1274
- reportMarkdownActionFailure(
1275
- { operation: "open-file-in-browser", target: targetPath },
1276
- cause,
1277
- );
1278
- toastManager.add(
1279
- stackedThreadToast({
1280
- type: "error",
1281
- title: "Unable to open file in browser",
1282
- description: cause instanceof Error ? cause.message : "An error occurred.",
1283
- }),
1284
- );
1285
- }
1286
- })();
1287
- };
1288
-
1289
- const handleRevealInFileManager = () => {
1290
- if (!onReveal) {
1291
- return;
1292
- }
1293
- void (async () => {
1294
- try {
1295
- const result = await onReveal();
1296
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1297
- return;
1298
- }
1299
- reportMarkdownActionFailure(
1300
- { operation: "reveal-file-in-file-manager", target: targetPath },
1301
- result.cause,
1302
- );
1303
- const error = squashAtomCommandFailure(result);
1304
- toastManager.add(
1305
- stackedThreadToast({
1306
- type: "error",
1307
- title: "Unable to reveal file",
1308
- description: error instanceof Error ? error.message : "An error occurred.",
1309
- }),
1310
- );
1311
- } catch (cause) {
1312
- reportMarkdownActionFailure(
1313
- { operation: "reveal-file-in-file-manager", target: targetPath },
1314
- cause,
1315
- );
1316
- toastManager.add(
1317
- stackedThreadToast({
1318
- type: "error",
1319
- title: "Unable to reveal file",
1320
- description: cause instanceof Error ? cause.message : "An error occurred.",
1321
- }),
1322
- );
1323
- }
1324
- })();
1325
- };
1326
-
1327
- const handleCopy = (resolveValue: () => Promise<string>, title: string) => {
1328
- if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
1329
- toastManager.add(
1330
- stackedThreadToast({
1331
- type: "error",
1332
- title: `Failed to copy ${title.toLowerCase()}`,
1333
- description: "Clipboard API unavailable.",
1334
- }),
1335
- );
1336
- return;
1337
- }
1338
-
1339
- const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath));
1340
- // Start the write before workspace lookup finishes so Safari retains the user gesture.
1341
- const write =
1342
- typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"
1343
- ? navigator.clipboard.write([
1344
- new ClipboardItem({
1345
- "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),
1346
- }),
1347
- ])
1348
- : value.then((text) => navigator.clipboard.writeText(text));
1349
- void Promise.all([write, value]).then(
1350
- ([, text]) => {
1351
- toastManager.add({
1352
- type: "success",
1353
- title: `${title} copied`,
1354
- description: text,
1355
- });
1356
- },
1357
- (error) => {
1358
- reportMarkdownActionFailure(
1359
- { operation: "copy-file-path", target: targetPath, copyTarget: title },
1360
- error,
1361
- );
1362
- toastManager.add(
1363
- stackedThreadToast({
1364
- type: "error",
1365
- title: `Failed to copy ${title.toLowerCase()}`,
1366
- description: error instanceof Error ? error.message : "An error occurred.",
1367
- }),
1368
- );
1369
- },
1370
- );
1371
- };
1372
-
1373
- const showFileContextMenu = async (position: { x: number; y: number }) => {
1374
- const api = readLocalApi();
1375
- if (!api) return;
1376
-
1377
- try {
1378
- const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath });
1379
- const clicked = await api.contextMenu.show(
1380
- [
1381
- ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),
1382
- ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
1383
- ...(onOpenInBrowser
1384
- ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)
1385
- : []),
1386
- ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),
1387
- ...copyItems.map(({ id, label }) => ({ id, label })),
1388
- ] as const,
1389
- position,
1390
- );
1391
-
1392
- if (clicked === "preview-media") {
1393
- onOpenMedia?.();
1394
- return;
1395
- }
1396
- if (clicked === "open") {
1397
- handleOpenInEditor();
1398
- return;
1399
- }
1400
- if (clicked === "open-in-browser") {
1401
- handleOpenInBrowser();
1402
- return;
1403
- }
1404
- if (clicked === "reveal") {
1405
- handleRevealInFileManager();
1406
- return;
1407
- }
1408
- if (clicked === "copy-relative" || clicked === "copy-full") {
1409
- handleCopy(
1410
- () =>
1411
- resolveCopyPaths().then((paths) =>
1412
- clicked === "copy-relative" ? paths.relativePath : paths.fullPath,
1413
- ),
1414
- clicked === "copy-relative" ? "Relative path" : "Full path",
1415
- );
1416
- }
1417
- } catch (cause) {
1418
- reportMarkdownActionFailure(
1419
- { operation: "show-file-context-menu", target: targetPath },
1420
- cause,
1421
- );
1422
- }
1423
- };
1424
-
1425
- const handleContextMenu = (event: ReactMouseEvent<HTMLElement>) => {
1426
- event.preventDefault();
1427
- event.stopPropagation();
1428
- const position =
1429
- event.clientX === 0 && event.clientY === 0
1430
- ? (() => {
1431
- const bounds = event.currentTarget.getBoundingClientRect();
1432
- return { x: bounds.left, y: bounds.bottom };
1433
- })()
1434
- : { x: event.clientX, y: event.clientY };
1435
- void showFileContextMenu(position);
1436
- };
1437
-
1438
- const canOpenInEditor = onOpen !== undefined;
1439
- const canOpenInBrowser = onOpenInBrowser !== undefined;
1440
- const canOpenInPanel = threadRef !== undefined && Boolean(panelPath);
1441
- const hasPrimaryAction = hasMarkdownFilePrimaryAction({
1442
- canOpenInEditor,
1443
- canOpenInBrowser,
1444
- canOpenInPanel,
1445
- canOpenMedia: onOpenMedia !== undefined,
1446
- });
1447
- const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({
1448
- iconPath,
1449
- canOpenInEditor,
1450
- canOpenInBrowser,
1451
- canOpenInPanel,
1452
- });
1453
-
1454
- return (
1455
- <Tooltip>
1456
- <TooltipTrigger
1457
- render={
1458
- hasPrimaryAction ? (
1459
- <ContextChip
1460
- kind="mention"
1461
- render={<a href={href} />}
1462
- className={MARKDOWN_FILE_LINK_CLASS_NAME}
1463
- data-markdown-copy={copyMarkdown}
1464
- onClick={(event) => {
1465
- event.preventDefault();
1466
- event.stopPropagation();
1467
- if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) {
1468
- handleOpenInEditor();
1469
- return;
1470
- }
1471
- if (useBrowserPrimaryAction) {
1472
- handleOpenInBrowser();
1473
- return;
1474
- }
1475
- handleOpenInFilePreview();
1476
- }}
1477
- onContextMenu={handleContextMenu}
1478
- >
1479
- <FileTagChipContent
1480
- path={iconPath}
1481
- environmentId={environmentId}
1482
- label={label}
1483
- theme={theme}
1484
- />
1485
- </ContextChip>
1486
- ) : (
1487
- <ContextChip
1488
- kind="mention"
1489
- render={<button type="button" />}
1490
- aria-label={`File options for ${label}`}
1491
- aria-haspopup="menu"
1492
- className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
1493
- data-markdown-copy={copyMarkdown}
1494
- onClick={handleContextMenu}
1495
- onContextMenu={handleContextMenu}
1496
- >
1497
- <FileTagChipContent
1498
- path={iconPath}
1499
- environmentId={environmentId}
1500
- label={label}
1501
- theme={theme}
1502
- />
1503
- </ContextChip>
1504
- )
1505
- }
1506
- />
1507
- <TooltipPopup side="top" variant="code">
1508
- <div className="overflow-x-auto whitespace-nowrap scrollbar-thumb-border/78 scrollbar-track-transparent [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/78 [&::-webkit-scrollbar-track]:bg-transparent">
1509
- <WorkspaceEntryTooltip path={iconPath} label={targetPath} environmentId={environmentId} />
1510
- </div>
1511
- </TooltipPopup>
1512
- </Tooltip>
1513
- );
1514
-}, areMarkdownFileLinkPropsEqual);
1515
-
1516
-function areMarkdownFileLinkPropsEqual(
1517
- previous: Readonly<MarkdownFileLinkProps>,
1518
- next: Readonly<MarkdownFileLinkProps>,
1519
-): boolean {
1520
- return (
1521
- previous.href === next.href &&
1522
- previous.targetPath === next.targetPath &&
1523
- previous.iconPath === next.iconPath &&
1524
- previous.environmentId === next.environmentId &&
1525
- previous.workspaceRelativePath === next.workspaceRelativePath &&
1526
- previous.panelPath === next.panelPath &&
1527
- previous.line === next.line &&
1528
- previous.label === next.label &&
1529
- previous.copyMarkdown === next.copyMarkdown &&
1530
- previous.theme === next.theme &&
1531
- previous.threadRef === next.threadRef &&
1532
- previous.onOpen === next.onOpen &&
1533
- previous.onOpenInPanel === next.onOpenInPanel &&
1534
- previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
1535
- previous.onOpenInBrowser === next.onOpenInBrowser &&
1536
- previous.onOpenMedia === next.onOpenMedia &&
1537
- previous.onReveal === next.onReveal &&
1538
- previous.resolveCopyPaths === next.resolveCopyPaths &&
1539
- previous.revealLabel === next.revealLabel
1540
- );
1541
-}
1542
-
835
const NO_MARKDOWN_EDITORS: ReadonlyArray<EditorId> = [];
836
837
type MarkdownServerConfigFields = ReturnType<typeof markdownServerConfigFields>;
apps/web/src/components/chat/MarkdownExternalLink.tsx
new
+110
@@ -0,0 +1,110 @@
1
+import { faviconUrlForOrigin } from "@t3tools/shared/favicon";
2
+import { GlobeIcon } from "lucide-react";
3
+import { Children, Fragment, memo, useState, type ReactNode } from "react";
4
+
5
+import { cn } from "../../lib/utils";
6
+import { GitHubIcon } from "../Icons";
7
+
8
+const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
9
+
10
+const failedFaviconHosts = new Set<string>();
11
+
12
+function isGitHubHost(host: string): boolean {
13
+ const hostname = host.toLowerCase();
14
+ return hostname === "github.com" || hostname.endsWith(".github.com");
15
+}
16
+
17
+const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
18
+ const [failedHost, setFailedHost] = useState<string | null>(null);
19
+ const brandIcon = isGitHubHost(host);
20
+ const faviconUrl = brandIcon ? null : faviconUrlForOrigin(`https://${host}`);
21
+ return (
22
+ <span
23
+ className="ms-[0.25em] me-[0.2em] inline-flex size-[14px] [vertical-align:-0.125em]"
24
+ aria-hidden
25
+ >
26
+ {brandIcon ? (
27
+ <GitHubIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
28
+ ) : faviconUrl === null || failedHost === host || failedFaviconHosts.has(host) ? (
29
+ <GlobeIcon className={MARKDOWN_LINK_FAVICON_CLASS_NAME} />
30
+ ) : (
31
+ <img
32
+ src={faviconUrl}
33
+ alt=""
34
+ loading="lazy"
35
+ draggable={false}
36
+ className={cn(MARKDOWN_LINK_FAVICON_CLASS_NAME, "rounded-sm")}
37
+ onError={() => {
38
+ failedFaviconHosts.add(host);
39
+ setFailedHost(host);
40
+ }}
41
+ />
42
+ )}
43
+ </span>
44
+ );
45
+});
46
+
47
+function leadingExternalLinkTextLength(text: string): number {
48
+ const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0];
49
+ if (protocol) return protocol.length;
50
+ return Math.min(text.length, 1);
51
+}
52
+
53
+function breakableExternalLinkText(text: string): ReactNode[] {
54
+ return Array.from(text, (character, index) => (
55
+ <Fragment key={`${index}:${character}`}>
56
+ {character}
57
+ <wbr />
58
+ </Fragment>
59
+ ));
60
+}
61
+
62
+export function MarkdownExternalLinkContent({
63
+ host,
64
+ plainText,
65
+ children,
66
+}: {
67
+ host: string;
68
+ plainText: string | null;
69
+ children: ReactNode;
70
+}) {
71
+ if (plainText) {
72
+ const leadingLength = leadingExternalLinkTextLength(plainText);
73
+ return (
74
+ <>
75
+ <span className="whitespace-nowrap">
76
+ <MarkdownLinkFavicon host={host} />
77
+ {plainText.slice(0, leadingLength)}
78
+ </span>
79
+ {breakableExternalLinkText(plainText.slice(leadingLength))}
80
+ </>
81
+ );
82
+ }
83
+
84
+ const childNodes = Children.toArray(children);
85
+ const firstChild = childNodes[0];
86
+
87
+ if (typeof firstChild === "string" && firstChild.length > 0) {
88
+ const leadingLength = leadingExternalLinkTextLength(firstChild);
89
+ return (
90
+ <>
91
+ <span className="whitespace-nowrap">
92
+ <MarkdownLinkFavicon host={host} />
93
+ {firstChild.slice(0, leadingLength)}
94
+ </span>
95
+ {breakableExternalLinkText(firstChild.slice(leadingLength))}
96
+ {childNodes.slice(1)}
97
+ </>
98
+ );
99
+ }
100
+
101
+ return (
102
+ <>
103
+ <span className="whitespace-nowrap">
104
+ <MarkdownLinkFavicon host={host} />
105
+ {firstChild}
106
+ </span>
107
+ {childNodes.slice(1)}
108
+ </>
109
+ );
110
+}
apps/web/src/components/chat/MarkdownFileLink.logic.ts
new
+62
@@ -0,0 +1,62 @@
1
+import type { EnvironmentId } from "@t3tools/contracts";
2
+import { splitFilePathPosition } from "@t3tools/shared/fileLinks";
3
+
4
+import {
5
+ shouldOpenMarkdownFileLinkInBrowserByDefault,
6
+ type MarkdownFileLinkMeta,
7
+} from "../../markdown-links";
8
+import type { RemoteOpenMode } from "../../remoteOpen";
9
+
10
+export function canUseMarkdownFileShellActions(
11
+ environmentId: EnvironmentId | null,
12
+ remoteOpenMode: RemoteOpenMode,
13
+ isRemoteOpenResolved: boolean,
14
+): boolean {
15
+ return environmentId !== null && isRemoteOpenResolved && remoteOpenMode === "local-exec";
16
+}
17
+
18
+export function hasMarkdownFilePrimaryAction(input: {
19
+ canOpenInEditor: boolean;
20
+ canOpenInBrowser: boolean;
21
+ canOpenInPanel: boolean;
22
+ canOpenMedia?: boolean;
23
+}): boolean {
24
+ return (
25
+ input.canOpenInEditor ||
26
+ input.canOpenInBrowser ||
27
+ input.canOpenInPanel ||
28
+ input.canOpenMedia === true
29
+ );
30
+}
31
+
32
+export function markdownFileCopyMenuItems({
33
+ targetPath,
34
+ workspaceRelativePath,
35
+}: Pick<MarkdownFileLinkMeta, "targetPath" | "workspaceRelativePath">) {
36
+ const items = [
37
+ { id: "copy-full", label: "Copy full path", value: targetPath, title: "Full path" },
38
+ ];
39
+ if (workspaceRelativePath !== null) {
40
+ const position = targetPath.slice(splitFilePathPosition(targetPath).path.length);
41
+ items.unshift({
42
+ id: "copy-relative",
43
+ label: "Copy relative path",
44
+ value: `${workspaceRelativePath}${position}`,
45
+ title: "Relative path",
46
+ });
47
+ }
48
+ return items;
49
+}
50
+
51
+export function shouldUseMarkdownFileBrowserPrimaryAction(input: {
52
+ iconPath: string;
53
+ canOpenInEditor: boolean;
54
+ canOpenInBrowser: boolean;
55
+ canOpenInPanel: boolean;
56
+}): boolean {
57
+ return (
58
+ input.canOpenInBrowser &&
59
+ (shouldOpenMarkdownFileLinkInBrowserByDefault(input.iconPath) ||
60
+ (!input.canOpenInEditor && !input.canOpenInPanel))
61
+ );
62
+}
apps/web/src/components/chat/MarkdownFileLink.tsx
new
+411
@@ -0,0 +1,411 @@
1
+import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
2
+import {
3
+ isAtomCommandInterrupted,
4
+ squashAtomCommandFailure,
5
+ type AtomCommandResult,
6
+} from "@t3tools/client-runtime/state/runtime";
7
+import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
8
+import { memo, type MouseEvent as ReactMouseEvent } from "react";
9
+
10
+import { readLocalApi } from "../../localApi";
11
+import { cn } from "../../lib/utils";
12
+import { shouldOpenMarkdownFileLinkInEditor } from "../../markdown-links";
13
+import type { markdownFileCopyPaths } from "../../markdownFileHostPath";
14
+import { ContextChip } from "../ContextChip";
15
+import { stackedThreadToast, toastManager } from "../ui/toast";
16
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
17
+import { FileTagChipContent } from "./FileTagChip";
18
+import {
19
+ hasMarkdownFilePrimaryAction,
20
+ markdownFileCopyMenuItems,
21
+ shouldUseMarkdownFileBrowserPrimaryAction,
22
+} from "./MarkdownFileLink.logic";
23
+import { reportMarkdownActionFailure } from "./markdownActionFailure";
24
+import { WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
25
+
26
+interface MarkdownFileLinkProps {
27
+ environmentId: EnvironmentId | null;
28
+ href: string;
29
+ targetPath: string;
30
+ iconPath: string;
31
+ workspaceRelativePath: string | null;
32
+ panelPath: string | null;
33
+ line?: number | undefined;
34
+ label: string;
35
+ copyMarkdown: string;
36
+ theme: "light" | "dark";
37
+ threadRef?: ScopedThreadRef | undefined;
38
+ onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
39
+ onOpenInPanel: (panelPath: string, line: number | undefined) => void;
40
+ resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;
41
+ openInEditorMenuLabel: string;
42
+ onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
43
+ onOpenMedia?: (() => void) | undefined;
44
+ onReveal?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;
45
+ revealLabel?: string | undefined;
46
+}
47
+
48
+const MARKDOWN_FILE_LINK_CLASS_NAME = "chat-markdown-file-link";
49
+
50
+export const MarkdownFileLink = memo(function MarkdownFileLink({
51
+ environmentId,
52
+ href,
53
+ targetPath,
54
+ iconPath,
55
+ workspaceRelativePath,
56
+ panelPath,
57
+ line,
58
+ label,
59
+ copyMarkdown,
60
+ theme,
61
+ threadRef,
62
+ onOpen,
63
+ onOpenInPanel,
64
+ openInEditorMenuLabel,
65
+ onOpenInBrowser,
66
+ onOpenMedia,
67
+ onReveal,
68
+ revealLabel,
69
+ resolveCopyPaths,
70
+}: MarkdownFileLinkProps) {
71
+ const handleOpenInEditor = () => {
72
+ if (!onOpen) {
73
+ return;
74
+ }
75
+ void (async () => {
76
+ try {
77
+ const result = await onOpen();
78
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
79
+ return;
80
+ }
81
+ reportMarkdownActionFailure(
82
+ { operation: "open-file-in-editor", target: targetPath },
83
+ result.cause,
84
+ );
85
+ const error = squashAtomCommandFailure(result);
86
+ toastManager.add(
87
+ stackedThreadToast({
88
+ type: "error",
89
+ title: "Unable to open file",
90
+ description: error instanceof Error ? error.message : "An error occurred.",
91
+ }),
92
+ );
93
+ } catch (cause) {
94
+ reportMarkdownActionFailure(
95
+ { operation: "open-file-in-editor", target: targetPath },
96
+ cause,
97
+ );
98
+ toastManager.add(
99
+ stackedThreadToast({
100
+ type: "error",
101
+ title: "Unable to open file",
102
+ description: cause instanceof Error ? cause.message : "An error occurred.",
103
+ }),
104
+ );
105
+ }
106
+ })();
107
+ };
108
+
109
+ const handleOpenInFilePreview = () => {
110
+ if (threadRef && panelPath) {
111
+ onOpenInPanel(panelPath, line);
112
+ return;
113
+ }
114
+ if (onOpenMedia) {
115
+ onOpenMedia();
116
+ return;
117
+ }
118
+ handleOpenInEditor();
119
+ };
120
+
121
+ const handleOpenInBrowser = () => {
122
+ if (!onOpenInBrowser) {
123
+ return;
124
+ }
125
+ void (async () => {
126
+ try {
127
+ const result = await onOpenInBrowser();
128
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
129
+ return;
130
+ }
131
+ reportMarkdownActionFailure(
132
+ { operation: "open-file-in-browser", target: targetPath },
133
+ result.cause,
134
+ );
135
+ const error = squashAtomCommandFailure(result);
136
+ toastManager.add(
137
+ stackedThreadToast({
138
+ type: "error",
139
+ title: "Unable to open file in browser",
140
+ description: error instanceof Error ? error.message : "An error occurred.",
141
+ }),
142
+ );
143
+ } catch (cause) {
144
+ reportMarkdownActionFailure(
145
+ { operation: "open-file-in-browser", target: targetPath },
146
+ cause,
147
+ );
148
+ toastManager.add(
149
+ stackedThreadToast({
150
+ type: "error",
151
+ title: "Unable to open file in browser",
152
+ description: cause instanceof Error ? cause.message : "An error occurred.",
153
+ }),
154
+ );
155
+ }
156
+ })();
157
+ };
158
+
159
+ const handleRevealInFileManager = () => {
160
+ if (!onReveal) {
161
+ return;
162
+ }
163
+ void (async () => {
164
+ try {
165
+ const result = await onReveal();
166
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
167
+ return;
168
+ }
169
+ reportMarkdownActionFailure(
170
+ { operation: "reveal-file-in-file-manager", target: targetPath },
171
+ result.cause,
172
+ );
173
+ const error = squashAtomCommandFailure(result);
174
+ toastManager.add(
175
+ stackedThreadToast({
176
+ type: "error",
177
+ title: "Unable to reveal file",
178
+ description: error instanceof Error ? error.message : "An error occurred.",
179
+ }),
180
+ );
181
+ } catch (cause) {
182
+ reportMarkdownActionFailure(
183
+ { operation: "reveal-file-in-file-manager", target: targetPath },
184
+ cause,
185
+ );
186
+ toastManager.add(
187
+ stackedThreadToast({
188
+ type: "error",
189
+ title: "Unable to reveal file",
190
+ description: cause instanceof Error ? cause.message : "An error occurred.",
191
+ }),
192
+ );
193
+ }
194
+ })();
195
+ };
196
+
197
+ const handleCopy = (resolveValue: () => Promise<string>, title: string) => {
198
+ if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
199
+ toastManager.add(
200
+ stackedThreadToast({
201
+ type: "error",
202
+ title: `Failed to copy ${title.toLowerCase()}`,
203
+ description: "Clipboard API unavailable.",
204
+ }),
205
+ );
206
+ return;
207
+ }
208
+
209
+ const value = resolveValue().then((text) => formatFilePathForClipboard(text, targetPath));
210
+ // Start the write before workspace lookup finishes so Safari retains the user gesture.
211
+ const write =
212
+ typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"
213
+ ? navigator.clipboard.write([
214
+ new ClipboardItem({
215
+ "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),
216
+ }),
217
+ ])
218
+ : value.then((text) => navigator.clipboard.writeText(text));
219
+ void Promise.all([write, value]).then(
220
+ ([, text]) => {
221
+ toastManager.add({
222
+ type: "success",
223
+ title: `${title} copied`,
224
+ description: text,
225
+ });
226
+ },
227
+ (error) => {
228
+ reportMarkdownActionFailure(
229
+ { operation: "copy-file-path", target: targetPath, copyTarget: title },
230
+ error,
231
+ );
232
+ toastManager.add(
233
+ stackedThreadToast({
234
+ type: "error",
235
+ title: `Failed to copy ${title.toLowerCase()}`,
236
+ description: error instanceof Error ? error.message : "An error occurred.",
237
+ }),
238
+ );
239
+ },
240
+ );
241
+ };
242
+
243
+ const showFileContextMenu = async (position: { x: number; y: number }) => {
244
+ const api = readLocalApi();
245
+ if (!api) return;
246
+
247
+ try {
248
+ const copyItems = markdownFileCopyMenuItems({ targetPath, workspaceRelativePath });
249
+ const clicked = await api.contextMenu.show(
250
+ [
251
+ ...(onOpenMedia ? ([{ id: "preview-media", label: "Preview media" }] as const) : []),
252
+ ...(onOpen ? ([{ id: "open", label: openInEditorMenuLabel }] as const) : []),
253
+ ...(onOpenInBrowser
254
+ ? ([{ id: "open-in-browser", label: "Open in integrated browser" }] as const)
255
+ : []),
256
+ ...(onReveal && revealLabel ? ([{ id: "reveal", label: revealLabel }] as const) : []),
257
+ ...copyItems.map(({ id, label }) => ({ id, label })),
258
+ ] as const,
259
+ position,
260
+ );
261
+
262
+ if (clicked === "preview-media") {
263
+ onOpenMedia?.();
264
+ return;
265
+ }
266
+ if (clicked === "open") {
267
+ handleOpenInEditor();
268
+ return;
269
+ }
270
+ if (clicked === "open-in-browser") {
271
+ handleOpenInBrowser();
272
+ return;
273
+ }
274
+ if (clicked === "reveal") {
275
+ handleRevealInFileManager();
276
+ return;
277
+ }
278
+ if (clicked === "copy-relative" || clicked === "copy-full") {
279
+ handleCopy(
280
+ () =>
281
+ resolveCopyPaths().then((paths) =>
282
+ clicked === "copy-relative" ? paths.relativePath : paths.fullPath,
283
+ ),
284
+ clicked === "copy-relative" ? "Relative path" : "Full path",
285
+ );
286
+ }
287
+ } catch (cause) {
288
+ reportMarkdownActionFailure(
289
+ { operation: "show-file-context-menu", target: targetPath },
290
+ cause,
291
+ );
292
+ }
293
+ };
294
+
295
+ const handleContextMenu = (event: ReactMouseEvent<HTMLElement>) => {
296
+ event.preventDefault();
297
+ event.stopPropagation();
298
+ const position =
299
+ event.clientX === 0 && event.clientY === 0
300
+ ? (() => {
301
+ const bounds = event.currentTarget.getBoundingClientRect();
302
+ return { x: bounds.left, y: bounds.bottom };
303
+ })()
304
+ : { x: event.clientX, y: event.clientY };
305
+ void showFileContextMenu(position);
306
+ };
307
+
308
+ const canOpenInEditor = onOpen !== undefined;
309
+ const canOpenInBrowser = onOpenInBrowser !== undefined;
310
+ const canOpenInPanel = threadRef !== undefined && Boolean(panelPath);
311
+ const hasPrimaryAction = hasMarkdownFilePrimaryAction({
312
+ canOpenInEditor,
313
+ canOpenInBrowser,
314
+ canOpenInPanel,
315
+ canOpenMedia: onOpenMedia !== undefined,
316
+ });
317
+ const useBrowserPrimaryAction = shouldUseMarkdownFileBrowserPrimaryAction({
318
+ iconPath,
319
+ canOpenInEditor,
320
+ canOpenInBrowser,
321
+ canOpenInPanel,
322
+ });
323
+
324
+ return (
325
+ <Tooltip>
326
+ <TooltipTrigger
327
+ render={
328
+ hasPrimaryAction ? (
329
+ <ContextChip
330
+ kind="mention"
331
+ render={<a href={href} />}
332
+ className={MARKDOWN_FILE_LINK_CLASS_NAME}
333
+ data-markdown-copy={copyMarkdown}
334
+ onClick={(event) => {
335
+ event.preventDefault();
336
+ event.stopPropagation();
337
+ if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) {
338
+ handleOpenInEditor();
339
+ return;
340
+ }
341
+ if (useBrowserPrimaryAction) {
342
+ handleOpenInBrowser();
343
+ return;
344
+ }
345
+ handleOpenInFilePreview();
346
+ }}
347
+ onContextMenu={handleContextMenu}
348
+ >
349
+ <FileTagChipContent
350
+ path={iconPath}
351
+ environmentId={environmentId}
352
+ label={label}
353
+ theme={theme}
354
+ />
355
+ </ContextChip>
356
+ ) : (
357
+ <ContextChip
358
+ kind="mention"
359
+ render={<button type="button" />}
360
+ aria-label={`File options for ${label}`}
361
+ aria-haspopup="menu"
362
+ className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")}
363
+ data-markdown-copy={copyMarkdown}
364
+ onClick={handleContextMenu}
365
+ onContextMenu={handleContextMenu}
366
+ >
367
+ <FileTagChipContent
368
+ path={iconPath}
369
+ environmentId={environmentId}
370
+ label={label}
371
+ theme={theme}
372
+ />
373
+ </ContextChip>
374
+ )
375
+ }
376
+ />
377
+ <TooltipPopup side="top" variant="code">
378
+ <div className="overflow-x-auto whitespace-nowrap scrollbar-thumb-border/78 scrollbar-track-transparent [scrollbar-width:thin] [&::-webkit-scrollbar]:h-1.5 [&::-webkit-scrollbar-thumb]:rounded-full [&::-webkit-scrollbar-thumb]:bg-border/78 [&::-webkit-scrollbar-track]:bg-transparent">
379
+ <WorkspaceEntryTooltip path={iconPath} label={targetPath} environmentId={environmentId} />
380
+ </div>
381
+ </TooltipPopup>
382
+ </Tooltip>
383
+ );
384
+}, areMarkdownFileLinkPropsEqual);
385
+
386
+function areMarkdownFileLinkPropsEqual(
387
+ previous: Readonly<MarkdownFileLinkProps>,
388
+ next: Readonly<MarkdownFileLinkProps>,
389
+): boolean {
390
+ return (
391
+ previous.href === next.href &&
392
+ previous.targetPath === next.targetPath &&
393
+ previous.iconPath === next.iconPath &&
394
+ previous.environmentId === next.environmentId &&
395
+ previous.workspaceRelativePath === next.workspaceRelativePath &&
396
+ previous.panelPath === next.panelPath &&
397
+ previous.line === next.line &&
398
+ previous.label === next.label &&
399
+ previous.copyMarkdown === next.copyMarkdown &&
400
+ previous.theme === next.theme &&
401
+ previous.threadRef === next.threadRef &&
402
+ previous.onOpen === next.onOpen &&
403
+ previous.onOpenInPanel === next.onOpenInPanel &&
404
+ previous.openInEditorMenuLabel === next.openInEditorMenuLabel &&
405
+ previous.onOpenInBrowser === next.onOpenInBrowser &&
406
+ previous.onOpenMedia === next.onOpenMedia &&
407
+ previous.onReveal === next.onReveal &&
408
+ previous.resolveCopyPaths === next.resolveCopyPaths &&
409
+ previous.revealLabel === next.revealLabel
410
+ );
411
+}
apps/web/src/components/chat/markdownFragments.ts
new
+113
@@ -0,0 +1,113 @@
1
+import type { MouseEvent as ReactMouseEvent } from "react";
2
+
3
+import { hastPlainTextDeep } from "./markdownHast.logic";
4
+
5
+const SANITIZED_FRAGMENT_PREFIX = "user-content-";
6
+
7
+function decodeMarkdownFragmentId(href: string): string {
8
+ const encodedId = href.slice(1);
9
+ try {
10
+ return decodeURIComponent(encodedId);
11
+ } catch {
12
+ return encodedId;
13
+ }
14
+}
15
+
16
+function normalizeSanitizedFragmentId(id: string): string {
17
+ let normalizedId = id;
18
+ while (normalizedId.startsWith(SANITIZED_FRAGMENT_PREFIX)) {
19
+ normalizedId = normalizedId.slice(SANITIZED_FRAGMENT_PREFIX.length);
20
+ }
21
+ return normalizedId;
22
+}
23
+
24
+function findMarkdownFragmentTarget(anchor: HTMLAnchorElement, href: string): HTMLElement | null {
25
+ const decodedId = decodeMarkdownFragmentId(href);
26
+ const normalizedId = normalizeSanitizedFragmentId(decodedId);
27
+ const matchesFragment = (element: HTMLElement) =>
28
+ element.id === decodedId || normalizeSanitizedFragmentId(element.id) === normalizedId;
29
+ const markdownRoot = anchor.closest<HTMLElement>(".chat-markdown");
30
+ if (markdownRoot) {
31
+ const localTargets = Array.from(markdownRoot.querySelectorAll<HTMLElement>("[id]"));
32
+ const localTarget = localTargets.find(matchesFragment);
33
+ if (localTarget) return localTarget;
34
+ }
35
+
36
+ return (
37
+ document.getElementById(decodedId) ??
38
+ Array.from(document.querySelectorAll<HTMLElement>("[id]")).find(matchesFragment) ??
39
+ null
40
+ );
41
+}
42
+
43
+export function handleMarkdownFragmentClick(
44
+ event: ReactMouseEvent<HTMLAnchorElement>,
45
+ href: string,
46
+) {
47
+ if (
48
+ event.defaultPrevented ||
49
+ event.button !== 0 ||
50
+ event.metaKey ||
51
+ event.ctrlKey ||
52
+ event.shiftKey ||
53
+ event.altKey
54
+ ) {
55
+ return;
56
+ }
57
+
58
+ // Never let the browser follow the fragment or write it to the URL: desktop keeps
59
+ // its route in the hash, so replacing the hash navigates away from the thread.
60
+ event.preventDefault();
61
+ findMarkdownFragmentTarget(event.currentTarget, href)?.scrollIntoView({ block: "start" });
62
+}
63
+
64
+type HeadingHastNode = {
65
+ type?: string;
66
+ tagName?: string;
67
+ properties?: Record<string, unknown>;
68
+ children?: HeadingHastNode[];
69
+};
70
+
71
+function githubHeadingSlug(text: string): string {
72
+ return text
73
+ .trim()
74
+ .toLowerCase()
75
+ .replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, "")
76
+ .replace(/ /g, "-");
77
+}
78
+
79
+/**
80
+ * Like the sanitizer's ids, they carry the `user-content-` prefix so they cannot clobber app
81
+ * element ids; fragment lookup strips it.
82
+ */
83
+export function rehypeHeadingIds() {
84
+ return (tree: HeadingHastNode) => {
85
+ const taken = new Set<string>();
86
+ const collect = (node: HeadingHastNode) => {
87
+ const id = node.properties?.id;
88
+ if (typeof id === "string") taken.add(id);
89
+ node.children?.forEach(collect);
90
+ };
91
+ collect(tree);
92
+ const nextSuffix = new Map<string, number>();
93
+ const visit = (node: HeadingHastNode) => {
94
+ if (node.type === "element" && node.tagName && /^h[1-6]$/.test(node.tagName)) {
95
+ const slug = githubHeadingSlug(hastPlainTextDeep(node));
96
+ if (node.properties?.id === undefined && slug) {
97
+ let count = nextSuffix.get(slug) ?? 0;
98
+ let id = `${SANITIZED_FRAGMENT_PREFIX}${slug}`;
99
+ while (taken.has(id)) {
100
+ count += 1;
101
+ id = `${SANITIZED_FRAGMENT_PREFIX}${slug}-${count}`;
102
+ }
103
+ nextSuffix.set(slug, count);
104
+ taken.add(id);
105
+ node.properties = { ...node.properties, id };
106
+ }
107
+ return;
108
+ }
109
+ node.children?.forEach(visit);
110
+ };
111
+ visit(tree);
112
+ };
113
+}
apps/web/src/components/chat/markdownHast.logic.ts
new
+42
@@ -0,0 +1,42 @@
1
+export function plainHastText(node: unknown): string | null {
2
+ if (!node || typeof node !== "object" || !("children" in node) || !Array.isArray(node.children)) {
3
+ return null;
4
+ }
5
+ const parts = node.children.map((child) => {
6
+ if (
7
+ child &&
8
+ typeof child === "object" &&
9
+ "type" in child &&
10
+ child.type === "text" &&
11
+ "value" in child &&
12
+ typeof child.value === "string"
13
+ ) {
14
+ return child.value;
15
+ }
16
+ return null;
17
+ });
18
+ return parts.every((part) => part !== null) ? parts.join("") : null;
19
+}
20
+
21
+export function hastPlainTextDeep(node: unknown): string {
22
+ if (!node || typeof node !== "object") return "";
23
+ if ("type" in node && node.type === "text" && "value" in node && typeof node.value === "string") {
24
+ return node.value;
25
+ }
26
+ if (!("children" in node) || !Array.isArray(node.children)) return "";
27
+ return node.children.map(hastPlainTextDeep).join("");
28
+}
29
+
30
+export function hastHasText(node: unknown): boolean {
31
+ if (!node || typeof node !== "object") return false;
32
+ if (
33
+ "type" in node &&
34
+ node.type === "text" &&
35
+ "value" in node &&
36
+ typeof node.value === "string" &&
37
+ node.value.trim().length > 0
38
+ ) {
39
+ return true;
40
+ }
41
+ return "children" in node && Array.isArray(node.children) && node.children.some(hastHasText);
42
+}