TypeScript
fix(web): Open in editor on a chat file chip opens the file the chip names (#18389)
chickenputtyfc4319cea758
diff --git a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsxindex 51d380a4e35..3edfa7696c8 100644--- a/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx+++ b/apps/web/src/components/ChatMarkdown.permissions.browser.test.tsx@@ -146,6 +146,10 @@ beforeEach(() => {state.copy.mockReset().mockResolvedValue(undefined);useRightPanelStore.setState({ openFile: state.openFile });vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy);+ vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {+ const item = items[0]!;+ await state.copy(await (await item.getType("text/plain")).text());+ });vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);});@@ -202,6 +206,26 @@ it("removes host actions after revocation while keeping file preview and copyingexpect(state.openEditor).not.toHaveBeenCalled();});+it("starts copying before the nested-file lookup finishes", async () => {+ let finishLookup: () => void = () => {+ throw new Error("Lookup not started");+ };+ state.search.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ finishLookup = () =>+ resolve(AsyncResult.success({ entries: [{ path: "src/readme.md", kind: "file" }] }));+ }),+ );+ state.choose.mockResolvedValue("copy-full");+ await renderMarkdown("`readme.md:10:2`");+ await openContextMenu();+ expect(navigator.clipboard.write).toHaveBeenCalledOnce();+ expect(state.copy).not.toHaveBeenCalled();+ await act(async () => finishLookup());+ await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/src/readme.md:10:2"));+});+it("does not launch an editor after revocation during a native context menu", async () => {let choose: (action: string) => void = () => {throw new Error("Menu not opened");diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex fbba770f5b6..e7cbf2aea36 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -180,6 +180,11 @@ import {shouldOpenMarkdownFileLinkInEditor,type MarkdownFileLinkMeta,} from "../markdown-links";+import {+ markdownFileCopyPaths,+ markdownFileEditorTarget,+ resolveMarkdownFileHostPath,+} from "../markdownFileHostPath";import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";import { isElectron } from "../env";import { readLocalApi } from "../localApi";@@ -1253,8 +1258,9 @@ interface MarkdownFileLinkProps {copyMarkdown: string;theme: "light" | "dark";threadRef?: ScopedThreadRef | undefined;- onOpen?: ((targetPath: string) => Promise<AtomCommandResult<unknown, unknown>>) | undefined;+ onOpen?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;onOpenInPanel: (panelPath: string, line: number | undefined) => void;+ resolveCopyPaths: () => Promise<ReturnType<typeof markdownFileCopyPaths>>;openInEditorMenuLabel: string;onOpenInBrowser?: (() => Promise<AtomCommandResult<unknown, unknown>>) | undefined;onOpenMedia?: (() => void) | undefined;@@ -1997,6 +2003,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({onOpenMedia,onReveal,revealLabel,+ resolveCopyPaths,}: MarkdownFileLinkProps) {const handleOpenInEditor = () => {if (!onOpen) {@@ -2004,7 +2011,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({}void (async () => {try {- const result = await onOpen(targetPath);+ const result = await onOpen();if (result._tag === "Success" || isAtomCommandInterrupted(result)) {return;}@@ -2124,7 +2131,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({})();};- const handleCopy = (value: string, title: string) => {+ const handleCopy = (resolveValue: () => Promise<string>, title: string) => {if (typeof window === "undefined" || !navigator.clipboard?.writeText) {toastManager.add(stackedThreadToast({@@ -2136,12 +2143,22 @@ const MarkdownFileLink = memo(function MarkdownFileLink({return;}- void navigator.clipboard.writeText(value).then(- () => {+ const value = resolveValue();+ // Start the write before workspace lookup finishes so Safari retains the user gesture.+ const write =+ typeof navigator.clipboard.write === "function" && typeof ClipboardItem !== "undefined"+ ? navigator.clipboard.write([+ new ClipboardItem({+ "text/plain": value.then((text) => new Blob([text], { type: "text/plain" })),+ }),+ ])+ : value.then((text) => navigator.clipboard.writeText(text));+ void Promise.all([write, value]).then(+ ([, text]) => {toastManager.add({type: "success",title: `${title} copied`,- description: value,+ description: text,});},(error) => {@@ -2195,9 +2212,14 @@ const MarkdownFileLink = memo(function MarkdownFileLink({handleRevealInFileManager();return;}- const copyItem = copyItems.find(({ id }) => id === clicked);- if (copyItem) {- handleCopy(copyItem.value, copyItem.title);+ if (clicked === "copy-relative" || clicked === "copy-full") {+ handleCopy(+ () =>+ resolveCopyPaths().then((paths) =>+ clicked === "copy-relative" ? paths.relativePath : paths.fullPath,+ ),+ clicked === "copy-relative" ? "Relative path" : "Full path",+ );}} catch (cause) {reportMarkdownActionFailure(@@ -2320,6 +2342,7 @@ function areMarkdownFileLinkPropsEqual(previous.onOpenInBrowser === next.onOpenInBrowser &&previous.onOpenMedia === next.onOpenMedia &&previous.onReveal === next.onReveal &&+ previous.resolveCopyPaths === next.resolveCopyPaths &&previous.revealLabel === next.revealLabel);}@@ -2735,16 +2758,17 @@ function useChatMarkdownState({openAt(match ?? panelPath);})();};- const revealMarkdownFileInFileManager = async (fileLinkMeta: MarkdownFileLinkMeta) => {- const match = await findWorkspaceFileMatch(fileLinkMeta);- const filePath = match && cwd ? resolvePathLinkTarget(match, cwd) : fileLinkMeta.filePath;- return revealFileInFileManager(filePath);- };const fileLinkChip = (fileLinkMeta: MarkdownFileLinkMeta,copyMarkdown: string,mediaSource?: string,) => {+ const resolveHostPath = () =>+ resolveMarkdownFileHostPath({+ meta: fileLinkMeta,+ cwd,+ findWorkspaceMatch: () => findWorkspaceFileMatch(fileLinkMeta),+ });const mediaPath = mediaSource ?? fileLinkMeta.filePath;const canPreviewMedia =mediaMimeTypeFromExtension(@@ -2774,7 +2798,17 @@ function useChatMarkdownState({copyMarkdown={copyMarkdown}theme={resolvedTheme}threadRef={threadRef}- {...(canUseShellActions ? { onOpen: openInPreferredEditor } : {})}+ onOpen={+ canUseShellActions+ ? async () =>+ openInPreferredEditor(+ markdownFileEditorTarget(fileLinkMeta, await resolveHostPath()),+ )+ : undefined+ }+ resolveCopyPaths={async () =>+ markdownFileCopyPaths(fileLinkMeta, await resolveHostPath(), cwd)+ }onOpenInPanel={(path) => openFileInPanel(fileLinkMeta, path)}onOpenMedia={threadRef && canPreviewMedia@@ -2784,7 +2818,7 @@ function useChatMarkdownState({openInEditorMenuLabel={preferredEditorMenuLabel}onReveal={canUseShellActions && revealInFileManagerLabel !== undefined- ? () => revealMarkdownFileInFileManager(fileLinkMeta)+ ? async () => revealFileInFileManager((await resolveHostPath()).absolutePath): undefined}revealLabel={revealInFileManagerLabel}diff --git a/apps/web/src/markdown-links.test.ts b/apps/web/src/markdown-links.test.tsindex 3aaed9058c0..3bdf77d7324 100644--- a/apps/web/src/markdown-links.test.ts+++ b/apps/web/src/markdown-links.test.ts@@ -7,6 +7,11 @@ import {shouldOpenMarkdownFileLinkInBrowserByDefault,shouldOpenMarkdownFileLinkInEditor,} from "./markdown-links";+import {+ markdownFileCopyPaths,+ markdownFileEditorTarget,+ resolveMarkdownFileHostPath,+} from "./markdownFileHostPath";describe("shouldOpenMarkdownFileLinkInEditor", () => {it("uses command-click on macOS", () => {@@ -299,3 +304,43 @@ it("routes the project-root code link to the workspace explorer", () => {filePath: cwd,});});++describe("chat file chip paths", () => {+ const cwd = String.raw`C:\Users\alice\project`;++ it("opens and copies the indexed file for a bare filename, preserving its line and column", async () => {+ const meta = resolveMarkdownFileLinkMeta("user.ts:261:7", cwd);+ if (!meta) throw new Error("Expected a file link");+ const hostPath = await resolveMarkdownFileHostPath({+ meta,+ cwd,+ findWorkspaceMatch: async () => "src/discord/events/user.ts",+ });++ expect(markdownFileEditorTarget(meta, hostPath)).toBe(+ String.raw`C:\Users\alice\project\src\discord\events\user.ts:261:7`,+ );+ expect(markdownFileCopyPaths(meta, hostPath, cwd)).toEqual({+ fullPath: String.raw`C:\Users\alice\project\src\discord\events\user.ts:261:7`,+ relativePath: "src/discord/events/user.ts:261:7",+ });+ });++ it("keeps the authored path and position when the workspace index has no match", async () => {+ const meta = resolveMarkdownFileLinkMeta("missing.ts:12:3", cwd);+ if (!meta) throw new Error("Expected a file link");+ const hostPath = await resolveMarkdownFileHostPath({+ meta,+ cwd,+ findWorkspaceMatch: async () => null,+ });++ expect(markdownFileEditorTarget(meta, hostPath)).toBe(+ String.raw`C:\Users\alice\project\missing.ts:12:3`,+ );+ expect(markdownFileCopyPaths(meta, hostPath, cwd)).toEqual({+ fullPath: String.raw`C:\Users\alice\project\missing.ts:12:3`,+ relativePath: "missing.ts:12:3",+ });+ });+});diff --git a/apps/web/src/markdownFileHostPath.ts b/apps/web/src/markdownFileHostPath.tsnew file mode 100644index 00000000000..26f3aaa3481--- /dev/null+++ b/apps/web/src/markdownFileHostPath.ts@@ -0,0 +1,48 @@+import { formatFilePathPosition, resolvePathLinkTarget } from "@t3tools/shared/fileLinks";++import { workspaceRelativeFilePath } from "@t3tools/shared/path";+import type { MarkdownFileLinkMeta } from "./markdown-links";++interface MarkdownFileHostPath {+ absolutePath: string;+ matched: boolean;+}++export async function resolveMarkdownFileHostPath(input: {+ meta: MarkdownFileLinkMeta;+ cwd: string | undefined;+ findWorkspaceMatch: (workspaceRelativePath: string) => Promise<string | null>;+}) {+ const { meta, cwd } = input;+ const match =+ meta.workspaceLookupPath && cwd+ ? await input.findWorkspaceMatch(meta.workspaceLookupPath)+ : null;+ return match && cwd+ ? { absolutePath: resolvePathLinkTarget(match, cwd), matched: true }+ : { absolutePath: meta.filePath, matched: false };+}++export function markdownFileEditorTarget(+ meta: MarkdownFileLinkMeta,+ hostPath: MarkdownFileHostPath,+) {+ return hostPath.matched+ ? formatFilePathPosition({ ...meta, path: hostPath.absolutePath })+ : meta.targetPath;+}++export function markdownFileCopyPaths(+ meta: MarkdownFileLinkMeta,+ hostPath: MarkdownFileHostPath,+ cwd: string | undefined,+) {+ const fullPath = markdownFileEditorTarget(meta, hostPath);+ return {+ fullPath,+ relativePath: formatFilePathPosition({+ ...meta,+ path: workspaceRelativeFilePath(hostPath.absolutePath, cwd) ?? meta.filePath,+ }),+ };+}