From 5c0840c73564587fabdd4ae588b98b7f08246347 Mon Sep 17 00:00:00 2001 From: Mihail Duchev <8217099+mduchev@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:49:31 +0200 Subject: [PATCH 1/4] Open composer URLs with a modifier click --- apps/web/package.json | 1 + ...rPromptEditorTiptap.input.browser.test.tsx | 15 +++++ .../components/ComposerPromptEditorTiptap.tsx | 61 ++++++++++++++++++- pnpm-lock.yaml | 3 + 4 files changed, 79 insertions(+), 1 deletion(-) diff --git a/apps/web/package.json b/apps/web/package.json index 9e6f0f475b3d0..240c38310750e 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -72,6 +72,7 @@ "jsonc-parser": "3.3.1", "jszip": "3.10.1", "katex": "^0.18.2", + "linkifyjs": "^4.3.3", "lucide-react": "^0.564.0", "mdast-util-from-markdown": "^2.0.3", "micromark-util-combine-extensions": "^2.0.1", diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 15547f5e4e8f8..02f3d7df108ee 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -1128,3 +1128,18 @@ it.each(["other field", "document body"])( ); }, ); + +it("opens a draft URL only on a modified primary click", async () => { + await using screen = await mountEditor("Visit www.example.com."); + using open = vi.spyOn(window, "open").mockReturnValue(null); + const link = screen.container.querySelector("[data-composer-url]"); + expect(link?.textContent).toBe("www.example.com"); + for (const options of [{}, { button: 1, ctrlKey: true }, { ctrlKey: true }, { metaKey: true }]) { + link?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...options })); + } + expect(open.mock.calls).toEqual([ + ["https://www.example.com", "_blank", "noopener,noreferrer"], + ["https://www.example.com", "_blank", "noopener,noreferrer"], + ]); + expect(screen.editor.getText()).toBe("Visit www.example.com."); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 21074670e64cf..97e43cc46bf45 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -14,8 +14,10 @@ import { type TiptapEditorHTMLElement, } from "@tiptap/core"; import { ReactNodeViewRenderer, NodeViewWrapper, type NodeViewProps } from "@tiptap/react"; +import { find as findLinks } from "linkifyjs"; import StarterKit from "@tiptap/starter-kit"; -import { useGT } from "gt-react"; +import { m } from "~/i18n/messages"; +import { msg, useGT } from "gt-react"; import { newlineInCode, splitBlockKeepMarks } from "@tiptap/pm/commands"; import { isHistoryTransaction } from "@tiptap/pm/history"; import { @@ -117,6 +119,7 @@ import { import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { isRichTextFormattingShortcut } from "~/keybindings"; +import { readLocalApi } from "~/localApi"; import { cn, isMacPlatform } from "~/lib/utils"; import { isThreadNavigationShortcut } from "~/keybindings"; import { appAtomRegistry } from "~/rpc/atomRegistry"; @@ -727,6 +730,61 @@ function isInCodeBlock(view: EditorView): boolean { return view.state.selection.$from.parent.type.spec.code === true; } +const ComposerUrlExtension = Extension.create({ + name: "composer-url", + addProseMirrorPlugins() { + const key = new PluginKey("composer-url"); + return [ + new Plugin({ + key, + state: { + init: (_, state) => composerUrlDecorations(state), + apply: (tr, old, _, state) => (tr.docChanged ? composerUrlDecorations(state) : old), + }, + props: { + decorations: (state) => key.getState(state), + handleDOMEvents: { + click: (_, event) => { + if (event.button !== 0 || !(event.metaKey || event.ctrlKey)) return false; + const link = + event.target instanceof Element + ? event.target.closest("[data-composer-url]") + : null; + const text = link?.textContent; + if (!text || !/^(?:https?:\/\/|www\.)/i.test(text)) return false; + event.preventDefault(); + const url = /^www\./i.test(text) ? `https://${text}` : text; + void readLocalApi()?.shell.openExternal(url).catch(console.error); + return true; + }, + }, + }, + }), + ]; + }, +}); + +function composerUrlDecorations({ doc }: EditorState): DecorationSet { + const decorations: Decoration[] = []; + doc.descendants((node, pos) => { + if (node.type.spec.code) return false; + if (!node.text || node.marks.some((mark) => mark.type.spec.code)) return; + if (!/https?:\/\/|www\./i.test(node.text)) return; + for (const { start, end, value } of findLinks(node.text, "url")) { + if (/^(?:https?:\/\/|www\.)/i.test(value)) { + decorations.push( + Decoration.inline(pos + start, pos + end, { + class: "text-info-foreground", + "data-composer-url": "", + title: `${m(msg("Open link"))} (${isMacPlatform(navigator.platform) ? "⌘-click" : "Ctrl-click"})`, + }), + ); + } + } + }); + return DecorationSet.create(doc, decorations); +} + const ChipSelectionPluginKey = new PluginKey("composer-chip-range-selection"); /** Highlights chips inside a text selection; their node views draw no native highlight. */ @@ -855,6 +913,7 @@ function createComposerExtensions(richText: boolean) { ComposerCitationExtension, ComposerContextReferenceExtension, ComposerChipSelectionExtension, + ComposerUrlExtension, ...(richText ? [ ComposerMarkdownSourceExtension, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fcda530d433e3..535b114a466df 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1223,6 +1223,9 @@ importers: katex: specifier: ^0.18.2 version: 0.18.10 + linkifyjs: + specifier: ^4.3.3 + version: 4.3.3 lucide-react: specifier: ^0.564.0 version: 0.564.0(react@19.3.0) From baa8aa16681ccaf678e6e7a764defa36278a033c Mon Sep 17 00:00:00 2001 From: Mihail Duchev <8217099+mduchev@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:57:42 +0200 Subject: [PATCH 2/4] Update Linkify and combine composer URL guards --- apps/web/package.json | 2 +- .../src/components/ComposerPromptEditorTiptap.tsx | 10 +++++++--- pnpm-lock.yaml | 12 ++++++------ 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/apps/web/package.json b/apps/web/package.json index 240c38310750e..d7e4c979860e6 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -72,7 +72,7 @@ "jsonc-parser": "3.3.1", "jszip": "3.10.1", "katex": "^0.18.2", - "linkifyjs": "^4.3.3", + "linkifyjs": "^4.4.0", "lucide-react": "^0.564.0", "mdast-util-from-markdown": "^2.0.3", "micromark-util-combine-extensions": "^2.0.1", diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 97e43cc46bf45..ef5eab72c57ef 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -767,9 +767,13 @@ const ComposerUrlExtension = Extension.create({ function composerUrlDecorations({ doc }: EditorState): DecorationSet { const decorations: Decoration[] = []; doc.descendants((node, pos) => { - if (node.type.spec.code) return false; - if (!node.text || node.marks.some((mark) => mark.type.spec.code)) return; - if (!/https?:\/\/|www\./i.test(node.text)) return; + if ( + node.type.spec.code || + !node.text || + node.marks.some((mark) => mark.type.spec.code) || + !/https?:\/\/|www\./i.test(node.text) + ) + return !node.type.spec.code; for (const { start, end, value } of findLinks(node.text, "url")) { if (/^(?:https?:\/\/|www\.)/i.test(value)) { decorations.push( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 535b114a466df..632ff70ce0be1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1224,8 +1224,8 @@ importers: specifier: ^0.18.2 version: 0.18.10 linkifyjs: - specifier: ^4.3.3 - version: 4.3.3 + specifier: ^4.4.0 + version: 4.4.0 lucide-react: specifier: ^0.564.0 version: 0.564.0(react@19.3.0) @@ -10424,8 +10424,8 @@ packages: resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} - linkifyjs@4.3.3: - resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==} + linkifyjs@4.4.0: + resolution: {integrity: sha512-InTexvtbai+2c+dEVGcc6O6P2DMVIiwD9a/i4zFroazOIYLOS6FSVmAJ7kFeumnCMx6/gQqNAkbUvgMubV4+MA==} locate-path@3.0.0: resolution: {integrity: sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A==} @@ -17241,7 +17241,7 @@ snapshots: dependencies: '@tiptap/core': 3.31.3(@tiptap/pm@3.31.3) '@tiptap/pm': 3.31.3 - linkifyjs: 4.3.3 + linkifyjs: 4.4.0 '@tiptap/extension-list-item@3.31.3(@tiptap/extension-list@3.31.3(@tiptap/core@3.31.3(@tiptap/pm@3.31.3))(@tiptap/pm@3.31.3))': dependencies: @@ -20774,7 +20774,7 @@ snapshots: lightningcss-win32-arm64-msvc: 1.33.0 lightningcss-win32-x64-msvc: 1.33.0 - linkifyjs@4.3.3: {} + linkifyjs@4.4.0: {} locate-path@3.0.0: dependencies: From 879a82b17d8d8094e94f3401aa95b605b53a7514 Mon Sep 17 00:00:00 2001 From: Mihail Duchev <8217099+mduchev@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:10:12 +0200 Subject: [PATCH 3/4] Share the message link context menu with composer URLs --- apps/web/src/components/ChatMarkdown.tsx | 132 +---------------- ...rPromptEditorTiptap.input.browser.test.tsx | 10 +- .../components/ComposerPromptEditorTiptap.tsx | 24 ++- apps/web/src/components/chat/ChatComposer.tsx | 1 + .../components/chat/useExternalLinkActions.ts | 138 ++++++++++++++++++ .../src/components/composerContextActions.ts | 3 +- 6 files changed, 172 insertions(+), 136 deletions(-) create mode 100644 apps/web/src/components/chat/useExternalLinkActions.ts diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index f6062475ac25b..19b4d752e1c63 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -15,7 +15,7 @@ import { } from "@t3tools/shared/markdownLinks"; import { taskListMarkerOffset } from "@t3tools/shared/markdownTaskList"; import { isHostPath, resolveWorkspaceFilePath } from "@t3tools/shared/path"; -import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; +import { useExternalLinkActions } from "./chat/useExternalLinkActions"; import { AuthFilesystemReadScope, AuthOrchestrationOperateScope, @@ -58,7 +58,6 @@ import { type ServerConfig, type ScopedThreadRef, type ServerProviderSkill, - type ThreadPullRequestKey, } from "@t3tools/contracts"; import { isAtomCommandInterrupted, @@ -127,15 +126,10 @@ import { revealInFileExplorerLabelForKind, revealInFileExplorerLabelForOs, } from "./preview/fileExplorerLabel"; -import { - resolveExternalWebLinkHost, - showExternalLinkContextMenu, -} from "./chat/externalLinkContextMenu"; +import { resolveExternalWebLinkHost } from "./chat/externalLinkContextMenu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; import { stackedThreadToast, toastManager } from "./ui/toast"; -import { recordVisitForThread } from "../browserHistoryStore"; -import { contextMenuSourceOf } from "../contextMenuSource"; import { PreferredEditorEnvironmentRequiredError, useOpenInPreferredEditor, @@ -200,12 +194,10 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink"; import { textDirection } from "~/textDirection"; import { useOpenLink } from "../browser/useOpenLink"; -import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; import { isPreviewAvailableFor } from "../browser/previewRuntime"; import { isBrowserPreviewFile, openFileInPreview, - openUrlInPreview, BrowserPreviewUnavailableError, isBrowserSettingsReadError, } from "../browser/openFileInPreview"; @@ -596,7 +588,6 @@ function useChatMarkdownState({ const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false, }); - const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId); const environmentId = threadRef?.environmentId ?? explicitEnvironmentId ?? null; const canOperateHost = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); const canOperatePreview = useEnvironmentScope(environmentId, AuthPreviewOperateScope); @@ -746,58 +737,7 @@ function useChatMarkdownState({ const fileLinksKey = `${fileLinkSourcesKey(text, cwd, imageBaseDir)}`; const { markdownFileLinkMetaByHref, inlineCodeFileLinkMetaByText, fileLinkParentSuffixByPath } = resolveFileLinkSources(fileLinksKey, cwd, imageBaseDir); - const resolveThreadPullRequest = ( - href: string, - ): (ThreadPullRequestKey & { readonly url: string }) | null => { - if ( - threadRef === undefined || - readThreadShell(threadRef) === null || - !pullRequestLinking.canLink(href) - ) - return null; - const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link; - return parsed === undefined ? null : { ...parsed, url: href }; - }; - const linkedThreadPullRequestFor = (href: string) => { - if (threadRef === undefined || !pullRequestLinking.isLinked(readThreadShell(threadRef), href)) - return null; - const parsed = sourceControlClients.parseChangeRequestUrl(href)?.link; - return parsed === undefined ? null : { ...parsed, url: href }; - }; - const updateThreadPullRequestLink = async (href: string, linked: boolean) => { - if (threadRef === undefined || (!linked && linkedThreadPullRequestFor(href) === null)) return; - if (!readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope)) return; - await pullRequestLinking.changeLink(threadRef, href, linked); - }; - const openExternalLinkInPreview = (url: string) => { - if (!threadRef || !canOperatePreview) { - return Promise.resolve( - AsyncResult.failure( - Cause.fail( - new BrowserPreviewUnavailableError({ - message: gt("Preview access is unavailable for this client."), - }), - ), - ), - ); - } - return openUrlInPreview({ threadRef, url, openPreview }).then((result) => { - if (result._tag === "Success") recordVisitForThread(threadRef, url); - else if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - if (isBrowserSettingsReadError(error)) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: gt("Unable to open link in browser"), - description: error.message, - }), - ); - } - } - return result; - }); - }; + const { openExternalLinkInPreview, showLinkMenu } = useExternalLinkActions(threadRef); const openMarkdownFileInPreview = (path: string) => { const preparedConnection = threadRef ? readPreparedConnection(threadRef.environmentId) : null; if (!threadRef || !canOperatePreview || preparedConnection === null) { @@ -1018,7 +958,6 @@ function useChatMarkdownState({ }; const componentState = { - canOperateHost, canOperatePreview, cwd, diffThemeName, @@ -1048,14 +987,12 @@ function useChatMarkdownState({ projects, issueProjects, issueTrackers, - linkedThreadPullRequestFor, - resolveThreadPullRequest, resolvedTheme, pullRequestsEnabled, issuesEnabled, skills, threadRef, - updateThreadPullRequestLink, + showLinkMenu, }; return { componentState, @@ -1204,7 +1141,6 @@ const CHAT_MARKDOWN_COMPONENTS = { a: function MarkdownAnchor({ node, href, children, title: _title, ...props }) { const gt = useGT(); const { - canOperateHost, canOperatePreview, cwd, environmentId, @@ -1220,11 +1156,9 @@ const CHAT_MARKDOWN_COMPONENTS = { projects, issueProjects, issueTrackers, - linkedThreadPullRequestFor, - resolveThreadPullRequest, pullRequestsEnabled, issuesEnabled, - updateThreadPullRequestLink, + showLinkMenu, fileLinkChip, renderContextReference, } = use(ChatMarkdownRendererContext); @@ -1386,61 +1320,7 @@ const CHAT_MARKDOWN_COMPONENTS = { }); }} onContextMenu={(event) => { - if (!href || !faviconHost) return; - event.preventDefault(); - event.stopPropagation(); - const api = readLocalApi(); - if (!api) return; - const source = contextMenuSourceOf(event); - const threadLinkAction = !canOperateHost - ? undefined - : linkedThreadPullRequestFor(href) !== null - ? "unlink-from-thread" - : resolveThreadPullRequest(href) === null - ? undefined - : "link-to-thread"; - void showExternalLinkContextMenu({ - href, - canOpenInPreview, - threadLinkAction, - position: { x: event.clientX, y: event.clientY }, - showContextMenu: (items, position) => api.contextMenu.show(items, position, source), - openInPreview: async (target) => { - const result = await openExternalLinkInPreview(target); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - reportMarkdownActionFailure( - { operation: "open-link-in-preview", target }, - result.cause, - ); - } - }, - openExternal: (target) => api.shell.openExternal(target), - copyLink: (target) => - writeTextToClipboard(target, { - target: "link", - unavailableMessage: msg("Clipboard API is unavailable while copying link."), - failureMessage: msg("Failed to copy link to the clipboard."), - }), - updateThreadLink: updateThreadPullRequestLink, - reportFailure: (operation, cause) => { - reportMarkdownActionFailure({ operation, target: href }, cause); - if ( - operation === "link-pull-request-to-thread" || - operation === "unlink-pull-request-from-thread" - ) { - toastManager.add( - stackedThreadToast({ - type: "error", - title: - operation === "link-pull-request-to-thread" - ? gt("Unable to link pull request") - : gt("Unable to unlink pull request"), - description: thrownErrorMessage(cause, m) ?? gt("The request failed."), - }), - ); - } - }, - }); + if (href && faviconHost) showLinkMenu(event, href); }} > {faviconHost && hasText && !isPullRequestAutolink ? ( diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 02f3d7df108ee..503302308ad45 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -28,6 +28,7 @@ import { userEvent } from "vite-plus/test/browser"; import { act, fakeTimers, render } from "../../test/render"; import { flatToMarkdown, pmToFlat, serializeEditorDoc } from "~/composer-rich-text-doc"; +import { ensureLocalApi } from "~/localApi"; import { isMacPlatform } from "~/lib/utils"; import { registerCommands } from "~/shortcuts/dispatcher"; import { @@ -1129,7 +1130,7 @@ it.each(["other field", "document body"])( }, ); -it("opens a draft URL only on a modified primary click", async () => { +it("opens a draft URL by modifier click or context menu", async () => { await using screen = await mountEditor("Visit www.example.com."); using open = vi.spyOn(window, "open").mockReturnValue(null); const link = screen.container.querySelector("[data-composer-url]"); @@ -1141,5 +1142,12 @@ it("opens a draft URL only on a modified primary click", async () => { ["https://www.example.com", "_blank", "noopener,noreferrer"], ["https://www.example.com", "_blank", "noopener,noreferrer"], ]); + using menu = vi.spyOn(ensureLocalApi().contextMenu, "show").mockResolvedValue("open-external"); + link?.dispatchEvent( + new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2 }), + ); + await vi.waitFor(() => expect(open).toHaveBeenCalledTimes(3)); + expect(menu.mock.calls[0]?.[0].map((item) => item.id)).toEqual(["open-external", "copy-link"]); + expect(open.mock.lastCall?.[0]).toBe("https://www.example.com"); expect(screen.editor.getText()).toBe("Visit www.example.com."); }); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index ef5eab72c57ef..58ac8ce68a550 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -119,6 +119,7 @@ import { import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { isRichTextFormattingShortcut } from "~/keybindings"; +import { useExternalLinkActions } from "./chat/useExternalLinkActions"; import { readLocalApi } from "~/localApi"; import { cn, isMacPlatform } from "~/lib/utils"; import { isThreadNavigationShortcut } from "~/keybindings"; @@ -730,6 +731,13 @@ function isInCodeBlock(view: EditorView): boolean { return view.state.selection.$from.parent.type.spec.code === true; } +function composerUrlFromTarget(target: EventTarget | null) { + const text = + target instanceof Element ? target.closest("[data-composer-url]")?.textContent : null; + if (!text || !/^(?:https?:\/\/|www\.)/i.test(text)) return null; + return /^www\./i.test(text) ? `https://${text}` : text; +} + const ComposerUrlExtension = Extension.create({ name: "composer-url", addProseMirrorPlugins() { @@ -746,14 +754,9 @@ const ComposerUrlExtension = Extension.create({ handleDOMEvents: { click: (_, event) => { if (event.button !== 0 || !(event.metaKey || event.ctrlKey)) return false; - const link = - event.target instanceof Element - ? event.target.closest("[data-composer-url]") - : null; - const text = link?.textContent; - if (!text || !/^(?:https?:\/\/|www\.)/i.test(text)) return false; + const url = composerUrlFromTarget(event.target); + if (!url) return false; event.preventDefault(); - const url = /^www\./i.test(text) ? `https://${text}` : text; void readLocalApi()?.shell.openExternal(url).catch(console.error); return true; }, @@ -1055,7 +1058,8 @@ function ComposerPromptEditorTiptapInner( importContextFragment, })); - const { environmentId } = use(ComposerContextActionsContext); + const { environmentId, threadRef } = use(ComposerContextActionsContext); + const { showLinkMenu } = useExternalLinkActions(threadRef); const modelKeys = useAtomValue(modelMentionKeysAtom(environmentId ?? "")); // Stable so a skills or models refresh does not rerun the controlled-value effect. const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name)); @@ -1956,6 +1960,10 @@ function ComposerPromptEditorTiptapInner( )} > { + const url = composerUrlFromTarget(event.target); + if (url) showLinkMenu(event, url); + }} editor={editor} onKeyDown={(event) => { if ( diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 603edc067dba8..255a650e76048 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -723,6 +723,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const [previewFileId, setPreviewFileId] = useState(null); const previewFile = composerFiles.find((file) => file.id === previewFileId); const composerContextActions = { + threadRef: routeThreadRef, environmentId, cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, diff --git a/apps/web/src/components/chat/useExternalLinkActions.ts b/apps/web/src/components/chat/useExternalLinkActions.ts new file mode 100644 index 0000000000000..d4eb0c6dbfe9d --- /dev/null +++ b/apps/web/src/components/chat/useExternalLinkActions.ts @@ -0,0 +1,138 @@ +import type { MouseEvent } from "react"; +import { + AuthOrchestrationOperateScope, + AuthPreviewOperateScope, + type ScopedThreadRef, +} from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import * as Cause from "effect/Cause"; +import { AsyncResult } from "effect/reactivity"; +import { msg, useGT } from "gt-react"; +import { m } from "~/i18n/messages"; +import { recordVisitForThread } from "~/browserHistoryStore"; +import { contextMenuSourceOf } from "~/contextMenuSource"; +import { readLocalApi } from "~/localApi"; +import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; +import { usePullRequestLinking } from "~/hooks/usePullRequestLinking"; +import { readThreadShell } from "~/state/entities"; +import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; +import { previewEnvironment } from "~/state/preview"; +import { useAtomCommand } from "~/state/use-atom-command"; +import { isPreviewAvailableFor } from "~/browser/previewRuntime"; +import { + openUrlInPreview, + BrowserPreviewUnavailableError, + isBrowserSettingsReadError, +} from "~/browser/openFileInPreview"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { reportMarkdownActionFailure } from "./markdownActionFailure"; +import { showExternalLinkContextMenu } from "./externalLinkContextMenu"; + +export function useExternalLinkActions(threadRef?: ScopedThreadRef) { + const gt = useGT(); + const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); + const canOperatePreview = useEnvironmentScope( + threadRef?.environmentId ?? null, + AuthPreviewOperateScope, + ); + const pullRequestLinking = usePullRequestLinking(threadRef?.environmentId); + const openExternalLinkInPreview = (url: string) => { + if (!threadRef || !canOperatePreview) { + return Promise.resolve( + AsyncResult.failure( + Cause.fail( + new BrowserPreviewUnavailableError({ + message: gt("Preview access is unavailable for this client."), + }), + ), + ), + ); + } + return openUrlInPreview({ threadRef, url, openPreview }).then((result) => { + if (result._tag === "Success") recordVisitForThread(threadRef, url); + else if (!isAtomCommandInterrupted(result)) { + const error = squashAtomCommandFailure(result); + if (isBrowserSettingsReadError(error)) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: gt("Unable to open link in browser"), + description: error.message, + }), + ); + } + } + return result; + }); + }; + const showLinkMenu = (event: MouseEvent, href: string) => { + event.preventDefault(); + event.stopPropagation(); + const api = readLocalApi(); + if (!api) return; + const source = contextMenuSourceOf(event); + const thread = threadRef ? readThreadShell(threadRef) : null; + const threadLinkAction = + thread && + threadRef && + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) && + pullRequestLinking.canLink(href) + ? pullRequestLinking.isLinked(thread, href) + ? "unlink-from-thread" + : "link-to-thread" + : undefined; + void showExternalLinkContextMenu({ + href, + canOpenInPreview: + !!threadRef && canOperatePreview && isPreviewAvailableFor(threadRef.environmentId), + threadLinkAction, + position: { x: event.clientX, y: event.clientY }, + showContextMenu: (items, position) => api.contextMenu.show(items, position, source), + openInPreview: async (target) => { + const result = await openExternalLinkInPreview(target); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + reportMarkdownActionFailure({ operation: "open-link-in-preview", target }, result.cause); + } + }, + openExternal: (target) => api.shell.openExternal(target), + copyLink: (target) => + writeTextToClipboard(target, { + target: "link", + unavailableMessage: msg("Clipboard API is unavailable while copying link."), + failureMessage: msg("Failed to copy link to the clipboard."), + }), + updateThreadLink: async (url, linked) => { + if ( + !threadRef || + !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) + ) + return; + if (!linked && !pullRequestLinking.isLinked(readThreadShell(threadRef), url)) return; + await pullRequestLinking.changeLink(threadRef, url, linked); + }, + reportFailure: (operation, cause) => { + reportMarkdownActionFailure({ operation, target: href }, cause); + if ( + operation === "link-pull-request-to-thread" || + operation === "unlink-pull-request-from-thread" + ) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: + operation === "link-pull-request-to-thread" + ? gt("Unable to link pull request") + : gt("Unable to unlink pull request"), + description: thrownErrorMessage(cause, m) ?? gt("The request failed."), + }), + ); + } + }, + }); + }; + return { openExternalLinkInPreview, showLinkMenu }; +} diff --git a/apps/web/src/components/composerContextActions.ts b/apps/web/src/components/composerContextActions.ts index b5df31ea2b26c..44bc00613e60e 100644 --- a/apps/web/src/components/composerContextActions.ts +++ b/apps/web/src/components/composerContextActions.ts @@ -1,8 +1,9 @@ -import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; +import type { EnvironmentId, ProjectId, ScopedThreadRef } from "@t3tools/contracts"; import { createContext, type MouseEvent } from "react"; export interface ComposerContextActions { environmentId: EnvironmentId | null; + threadRef?: ScopedThreadRef | undefined; cwd?: string | undefined; projectId?: ProjectId | undefined; expandImage: (imageId: string) => void; From dddc18888d4bdba6e76f5e51aae456ac212b4076 Mon Sep 17 00:00:00 2001 From: Mihail Duchev <8217099+mduchev@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:16:03 +0200 Subject: [PATCH 4/4] Keep composer URLs intact across formatting changes --- ...rPromptEditorTiptap.input.browser.test.tsx | 23 +++++++++---- .../components/ComposerPromptEditorTiptap.tsx | 33 ++++++++++++------- 2 files changed, 37 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 503302308ad45..c69fc3da05025 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -1131,23 +1131,32 @@ it.each(["other field", "document body"])( ); it("opens a draft URL by modifier click or context menu", async () => { - await using screen = await mountEditor("Visit www.example.com."); + const draft = "Visit www.example.com/docs."; + await using screen = await mountEditor(draft); + const { editor } = screen; + const pathStart = draft.indexOf("/docs") + 1; + await act(async () => { + editor.view.dispatch( + editor.state.tr.addMark(pathStart, pathStart + 5, editor.schema.marks.bold!.create()), + ); + }); using open = vi.spyOn(window, "open").mockReturnValue(null); const link = screen.container.querySelector("[data-composer-url]"); - expect(link?.textContent).toBe("www.example.com"); + const path = screen.container.querySelector("strong"); + expect(path?.textContent).toBe("/docs"); for (const options of [{}, { button: 1, ctrlKey: true }, { ctrlKey: true }, { metaKey: true }]) { link?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ...options })); } expect(open.mock.calls).toEqual([ - ["https://www.example.com", "_blank", "noopener,noreferrer"], - ["https://www.example.com", "_blank", "noopener,noreferrer"], + ["https://www.example.com/docs", "_blank", "noopener,noreferrer"], + ["https://www.example.com/docs", "_blank", "noopener,noreferrer"], ]); using menu = vi.spyOn(ensureLocalApi().contextMenu, "show").mockResolvedValue("open-external"); - link?.dispatchEvent( + (path?.querySelector("[data-composer-url]") ?? path)?.dispatchEvent( new MouseEvent("contextmenu", { bubbles: true, cancelable: true, button: 2 }), ); await vi.waitFor(() => expect(open).toHaveBeenCalledTimes(3)); expect(menu.mock.calls[0]?.[0].map((item) => item.id)).toEqual(["open-external", "copy-link"]); - expect(open.mock.lastCall?.[0]).toBe("https://www.example.com"); - expect(screen.editor.getText()).toBe("Visit www.example.com."); + expect(open.mock.lastCall?.[0]).toBe("https://www.example.com/docs"); + expect(screen.editor.getText()).toBe(draft); }); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 58ac8ce68a550..6c99060609f92 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -733,7 +733,9 @@ function isInCodeBlock(view: EditorView): boolean { function composerUrlFromTarget(target: EventTarget | null) { const text = - target instanceof Element ? target.closest("[data-composer-url]")?.textContent : null; + target instanceof Element + ? target.closest("[data-composer-url]")?.getAttribute("data-composer-url") + : null; if (!text || !/^(?:https?:\/\/|www\.)/i.test(text)) return null; return /^www\./i.test(text) ? `https://${text}` : text; } @@ -769,26 +771,33 @@ const ComposerUrlExtension = Extension.create({ function composerUrlDecorations({ doc }: EditorState): DecorationSet { const decorations: Decoration[] = []; - doc.descendants((node, pos) => { - if ( - node.type.spec.code || - !node.text || - node.marks.some((mark) => mark.type.spec.code) || - !/https?:\/\/|www\./i.test(node.text) - ) - return !node.type.spec.code; - for (const { start, end, value } of findLinks(node.text, "url")) { + let text = ""; + let from = 0; + const decorateRun = () => { + if (!/https?:\/\/|www\./i.test(text)) return; + for (const { start, end, value } of findLinks(text, "url")) { if (/^(?:https?:\/\/|www\.)/i.test(value)) { decorations.push( - Decoration.inline(pos + start, pos + end, { + Decoration.inline(from + start, from + end, { class: "text-info-foreground", - "data-composer-url": "", + "data-composer-url": value, title: `${m(msg("Open link"))} (${isMacPlatform(navigator.platform) ? "⌘-click" : "Ctrl-click"})`, }), ); } } + }; + doc.descendants((node, pos) => { + if (node.type.spec.code || !node.text || node.marks.some((mark) => mark.type.spec.code)) + return !node.type.spec.code; + if (pos !== from + text.length) { + decorateRun(); + from = pos; + text = ""; + } + text += node.text; }); + decorateRun(); return DecorationSet.create(doc, decorations); }