From 1ea4cb2b4c3b9bcf1fcbcc11cb0d73c4ed78fe08 Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Sat, 21 Nov 2026 15:23:07 -0800 Subject: [PATCH 1/2] fix(desktop): open terminal file links the way chat does Plain click on a file path in a terminal showed 'Not bound' while the same path in chat opened. Chat carried its own link rules inline; the terminal never got them. Both now share them: - unbound plain click opens the file (folders reveal), from the click policy hooks; Settings shows that default instead of 'Do nothing' - a path that does not exist as written resolves to the file it most plausibly means (useWorkspacePathHost, one host adapter for both) - #L12 anchors and :12-20 ranges parse in one place (lib/fileLocation) - schemeless sites that are not files open as websites - a drag that selects text no longer activates the link under it --- .../bareWebUrl/bareWebUrl.test.ts | 0 .../utils => lib}/bareWebUrl/bareWebUrl.ts | 0 .../utils => lib}/bareWebUrl/index.ts | 0 .../src/renderer/lib/clickPolicy/index.ts | 6 +- .../clickPolicy/policies/agentOutputLinks.ts | 9 +++ .../lib/clickPolicy/policies/folderPolicy.ts | 7 +- .../lib/clickPolicy/policies/policy.ts | 9 ++- .../policies/useInlineFilePolicy.ts | 3 +- .../policies/useTerminalFilePolicy.ts | 3 +- .../policies/useTerminalFolderPolicy.ts | 24 ++++--- .../renderer/lib/clickPolicy/tiers.test.ts | 18 ++++- .../src/renderer/lib/clickPolicy/tiers.ts | 10 +++ .../lib/fileLocation/fileLocation.test.ts | 39 +++++++++++ .../renderer/lib/fileLocation/fileLocation.ts | 26 +++++++ .../src/renderer/lib/fileLocation/index.ts | 5 ++ .../src/renderer/lib/terminal/links/index.ts | 2 + .../terminal/links/link-detector-adapter.ts | 14 ++-- .../links/local-link-detector.test.ts | 70 ++++++++++++++++++- .../lib/terminal/links/local-link-detector.ts | 69 +++++++++++++----- .../terminal/terminal-link-manager.test.ts | 26 ++++++- .../lib/terminal/terminal-link-manager.ts | 67 ++++++++++++++---- .../hooks/useOpenChatLink/useOpenChatLink.ts | 33 +++------ .../utils/locateChatLink/locateChatLink.ts | 2 +- .../utils/parseFileHref/parseFileHref.test.ts | 4 ++ .../utils/parseFileHref/parseFileHref.ts | 54 +++++--------- .../components/FileLinkMenu/FileLinkMenu.tsx | 2 +- .../ChatSession/utils/pathText/pathText.ts | 5 +- .../components/TerminalPane/TerminalPane.tsx | 29 ++------ .../hooks/useWorkspacePathHost/index.ts | 4 ++ .../useWorkspacePathHost.ts | 42 +++++++++++ .../LinkTierMapper/LinkTierMapper.tsx | 22 +++--- .../FilesSettings/FilesSettings.tsx | 7 +- .../FolderLinkTierMapper.tsx | 13 ++-- 33 files changed, 467 insertions(+), 157 deletions(-) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/bareWebUrl/bareWebUrl.test.ts (100%) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/bareWebUrl/bareWebUrl.ts (100%) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/bareWebUrl/index.ts (100%) create mode 100644 apps/desktop/src/renderer/lib/clickPolicy/policies/agentOutputLinks.ts create mode 100644 apps/desktop/src/renderer/lib/fileLocation/fileLocation.test.ts create mode 100644 apps/desktop/src/renderer/lib/fileLocation/fileLocation.ts create mode 100644 apps/desktop/src/renderer/lib/fileLocation/index.ts create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/index.ts create mode 100644 apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/useWorkspacePathHost.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/bareWebUrl.test.ts b/apps/desktop/src/renderer/lib/bareWebUrl/bareWebUrl.test.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/bareWebUrl.test.ts rename to apps/desktop/src/renderer/lib/bareWebUrl/bareWebUrl.test.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/bareWebUrl.ts b/apps/desktop/src/renderer/lib/bareWebUrl/bareWebUrl.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/bareWebUrl.ts rename to apps/desktop/src/renderer/lib/bareWebUrl/bareWebUrl.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/index.ts b/apps/desktop/src/renderer/lib/bareWebUrl/index.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/bareWebUrl/index.ts rename to apps/desktop/src/renderer/lib/bareWebUrl/index.ts diff --git a/apps/desktop/src/renderer/lib/clickPolicy/index.ts b/apps/desktop/src/renderer/lib/clickPolicy/index.ts index a8b8bb269a9..f4bc8ed4c14 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/index.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/index.ts @@ -8,6 +8,10 @@ export { LinkHoverHint } from "./components/LinkHoverHint"; export { ShadowClickHint } from "./components/ShadowClickHint"; export { buildHint, unboundHint } from "./hint"; export { modifierLabel } from "./modifierLabel"; +export { + FILE_LINK_PLAIN_DEFAULT, + FOLDER_LINK_PLAIN_DEFAULT, +} from "./policies/agentOutputLinks"; export { buildChangesSidebarFileHint, type ChangesSidebarFileIntent, @@ -43,7 +47,7 @@ export { type UrlLinkAction, useUrlLinkAction, } from "./policies/useUrlLinkAction"; -export { tierFor } from "./tiers"; +export { tierFor, withPlainDefault } from "./tiers"; export type { LinkAction, LinkTier, diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/agentOutputLinks.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/agentOutputLinks.ts new file mode 100644 index 00000000000..1c53d534efb --- /dev/null +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/agentOutputLinks.ts @@ -0,0 +1,9 @@ +import type { LinkAction } from "../types"; +import type { FolderLinkAction } from "./folderPolicy"; + +/** + * File and folder paths in agent output (terminal, chat) open on a plain + * click, unless the user bound plain click to another action. + */ +export const FILE_LINK_PLAIN_DEFAULT: LinkAction = "pane"; +export const FOLDER_LINK_PLAIN_DEFAULT: FolderLinkAction = "reveal"; diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/folderPolicy.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/folderPolicy.ts index 850ba829a0b..f3c3718cd9f 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/policies/folderPolicy.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/folderPolicy.ts @@ -6,7 +6,7 @@ import type { FolderTierMap, } from "renderer/routes/_authenticated/providers/CollectionsProvider/dashboardSidebarLocal/schema"; import { tierFor } from "../tiers"; -import type { ModifierEvent } from "../types"; +import type { ModifierEvent, TierMode } from "../types"; export type { FolderLinkAction, FolderTierMap }; @@ -15,7 +15,7 @@ export type { FolderLinkAction, FolderTierMap }; * links): each click tier maps to reveal-in-sidebar, external editor, * Finder, or unbound. Defaults: * - * plain → null (caller decides — toggle/hint) + * plain → null (reveals in sidebar, see agentOutputLinks) * shift → open in Finder * meta / ctrl → reveal in sidebar * meta+shift → open in external editor @@ -25,8 +25,9 @@ export type FolderIntent = FolderLinkAction | null; export function folderIntentForMap( event: ModifierEvent, map: FolderTierMap, + mode: TierMode = "4-tier", ): FolderIntent { - return map[tierFor(event, "4-tier")]; + return map[tierFor(event, mode)]; } /** diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/policy.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/policy.ts index 23335a471cc..46ee8c94d37 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/policies/policy.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/policy.ts @@ -1,7 +1,7 @@ import { useCallback, useMemo } from "react"; import { useUserPreferences } from "renderer/hooks/useUserPreferences"; import { buildHint } from "../hint"; -import { tierFor } from "../tiers"; +import { tierFor, withPlainDefault } from "../tiers"; import type { LinkAction, LinkTierMap, @@ -65,9 +65,14 @@ export function usePolicy( key: MapKey, surface: Surface, mode: TierMode, + plainDefault?: LinkAction, ): ClickPolicy { const { preferences } = useUserPreferences(); - const map = preferences[key]; + const stored = preferences[key]; + const map = useMemo( + () => (plainDefault ? withPlainDefault(stored, plainDefault) : stored), + [stored, plainDefault], + ); const resolve = useCallback( (event: ModifierEvent): ResolvedClick => { const tier = tierFor(event, mode); diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/useInlineFilePolicy.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/useInlineFilePolicy.ts index 96a1948e518..e036a3b5371 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/policies/useInlineFilePolicy.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/useInlineFilePolicy.ts @@ -1,5 +1,6 @@ +import { FILE_LINK_PLAIN_DEFAULT } from "./agentOutputLinks"; import { type ClickPolicy, usePolicy } from "./policy"; export function useInlineFilePolicy(): ClickPolicy { - return usePolicy("fileLinks", "file", "2-tier"); + return usePolicy("fileLinks", "file", "2-tier", FILE_LINK_PLAIN_DEFAULT); } diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFilePolicy.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFilePolicy.ts index 8c48115d071..9487cf8ca8e 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFilePolicy.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFilePolicy.ts @@ -1,5 +1,6 @@ +import { FILE_LINK_PLAIN_DEFAULT } from "./agentOutputLinks"; import { type ClickPolicy, usePolicy } from "./policy"; export function useTerminalFilePolicy(): ClickPolicy { - return usePolicy("fileLinks", "file", "4-tier"); + return usePolicy("fileLinks", "file", "4-tier", FILE_LINK_PLAIN_DEFAULT); } diff --git a/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFolderPolicy.ts b/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFolderPolicy.ts index ed12ac39b29..ac661e90f72 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFolderPolicy.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/policies/useTerminalFolderPolicy.ts @@ -1,6 +1,8 @@ -import { useCallback } from "react"; +import { useCallback, useMemo } from "react"; import { useUserPreferences } from "renderer/hooks/useUserPreferences"; -import type { ModifierEvent } from "../types"; +import { withPlainDefault } from "../tiers"; +import type { ModifierEvent, TierMode } from "../types"; +import { FOLDER_LINK_PLAIN_DEFAULT } from "./agentOutputLinks"; import { type FolderIntent, type FolderTierMap, @@ -12,13 +14,19 @@ export interface FolderClickPolicy { map: FolderTierMap; } -/** Settings-driven click policy for folder links in terminal output. */ -export function useTerminalFolderPolicy(): FolderClickPolicy { +/** Settings-driven click policy for folder links in terminal and chat output. */ +export function useTerminalFolderPolicy( + mode: TierMode = "4-tier", +): FolderClickPolicy { const { preferences } = useUserPreferences(); - const map = preferences.folderLinks; + const stored = preferences.folderLinks; + const map = useMemo( + () => withPlainDefault(stored, FOLDER_LINK_PLAIN_DEFAULT), + [stored], + ); const getIntent = useCallback( - (event: ModifierEvent) => folderIntentForMap(event, map), - [map], + (event: ModifierEvent) => folderIntentForMap(event, map, mode), + [map, mode], ); - return { getIntent, map }; + return useMemo(() => ({ getIntent, map }), [getIntent, map]); } diff --git a/apps/desktop/src/renderer/lib/clickPolicy/tiers.test.ts b/apps/desktop/src/renderer/lib/clickPolicy/tiers.test.ts index 5d4c14b0a3e..7d324546385 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/tiers.test.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/tiers.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test"; -import { tierFor } from "./tiers"; +import { tierFor, withPlainDefault } from "./tiers"; import type { ModifierEvent } from "./types"; function event(init: Partial = {}): ModifierEvent { @@ -36,3 +36,19 @@ describe("tierFor 2-tier", () => { ); }); }); + +describe("withPlainDefault", () => { + const unbound = { plain: null, shift: null, meta: "pane", metaShift: null }; + + it("fills an unbound plain click and leaves other tiers alone", () => { + expect(withPlainDefault(unbound, "newTab")).toEqual({ + ...unbound, + plain: "newTab", + }); + }); + + it("keeps a plain click the user bound", () => { + const bound = { ...unbound, plain: "external" }; + expect(withPlainDefault(bound, "newTab")).toBe(bound); + }); +}); diff --git a/apps/desktop/src/renderer/lib/clickPolicy/tiers.ts b/apps/desktop/src/renderer/lib/clickPolicy/tiers.ts index df020374347..5e511af917a 100644 --- a/apps/desktop/src/renderer/lib/clickPolicy/tiers.ts +++ b/apps/desktop/src/renderer/lib/clickPolicy/tiers.ts @@ -1,5 +1,7 @@ import type { LinkTier, ModifierEvent, TierMode } from "./types"; +type TierMap = Record; + /** * Resolve a click event to a tier under the given mode. * @@ -17,3 +19,11 @@ export function tierFor(event: ModifierEvent, mode: TierMode): LinkTier { if (meta) return event.shiftKey ? "metaShift" : "meta"; return event.shiftKey ? "shift" : "plain"; } + +/** A map where an unbound plain click runs `action`. Bound tiers are kept. */ +export function withPlainDefault( + map: TierMap, + action: Action, +): TierMap { + return map.plain === null ? { ...map, plain: action } : map; +} diff --git a/apps/desktop/src/renderer/lib/fileLocation/fileLocation.test.ts b/apps/desktop/src/renderer/lib/fileLocation/fileLocation.test.ts new file mode 100644 index 00000000000..1f94916eddf --- /dev/null +++ b/apps/desktop/src/renderer/lib/fileLocation/fileLocation.test.ts @@ -0,0 +1,39 @@ +import { expect, test } from "bun:test"; +import { splitFileLocation, splitLineAnchor } from "./fileLocation"; + +test("splits the line forms agents write", () => { + expect(splitFileLocation("src/app.ts")).toEqual({ path: "src/app.ts" }); + expect(splitFileLocation("src/app.ts:12")).toEqual({ + path: "src/app.ts", + row: 12, + }); + expect(splitFileLocation("src/app.ts:12:3")).toEqual({ + path: "src/app.ts", + row: 12, + col: 3, + }); + expect(splitFileLocation("src/app.ts#L12C3")).toEqual({ + path: "src/app.ts", + row: 12, + col: 3, + }); +}); + +test("keeps the start of a range", () => { + expect(splitFileLocation("src/app.ts:17-33")).toEqual({ + path: "src/app.ts", + row: 17, + }); + expect(splitFileLocation("src/app.ts#L12-L20")).toEqual({ + path: "src/app.ts", + row: 12, + }); +}); + +test("splitLineAnchor ignores colon suffixes", () => { + expect(splitLineAnchor("src/app.ts:12")).toBeNull(); + expect(splitLineAnchor("src/app.ts#L12")).toEqual({ + path: "src/app.ts", + row: 12, + }); +}); diff --git a/apps/desktop/src/renderer/lib/fileLocation/fileLocation.ts b/apps/desktop/src/renderer/lib/fileLocation/fileLocation.ts new file mode 100644 index 00000000000..d2e8e09411f --- /dev/null +++ b/apps/desktop/src/renderer/lib/fileLocation/fileLocation.ts @@ -0,0 +1,26 @@ +export interface FileLocation { + path: string; + row?: number; + col?: number; +} + +const LINE_ANCHOR = /#L(\d+)(?:C(\d+))?(?:-L?\d+(?:C\d+)?)?$/; +const LINE_SUFFIX = /:(\d+)(?::(\d+))?(?:-\d+(?::\d+)?)?$/; + +/** + * Splits `path:12`, `path:12:3`, `path:12-20`, `path#L12` and `path#L12-L20` + * into the path and where it points. A range keeps its start. + */ +export function splitFileLocation(text: string): FileLocation { + const match = text.match(LINE_ANCHOR) ?? text.match(LINE_SUFFIX); + if (!match) return { path: text }; + return { + path: text.slice(0, match.index), + row: Number(match[1]), + ...(match[2] ? { col: Number(match[2]) } : {}), + }; +} + +export function splitLineAnchor(text: string): FileLocation | null { + return LINE_ANCHOR.test(text) ? splitFileLocation(text) : null; +} diff --git a/apps/desktop/src/renderer/lib/fileLocation/index.ts b/apps/desktop/src/renderer/lib/fileLocation/index.ts new file mode 100644 index 00000000000..66f6c9fcdab --- /dev/null +++ b/apps/desktop/src/renderer/lib/fileLocation/index.ts @@ -0,0 +1,5 @@ +export { + type FileLocation, + splitFileLocation, + splitLineAnchor, +} from "./fileLocation"; diff --git a/apps/desktop/src/renderer/lib/terminal/links/index.ts b/apps/desktop/src/renderer/lib/terminal/links/index.ts index 620610f08c3..b64a9101041 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/index.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/index.ts @@ -4,6 +4,8 @@ export { type StatCallback, TerminalLinkResolver } from "./link-resolver"; export { type DetectedLink, + type DetectedTerminalLink, + isWebLink, LocalLinkDetector, } from "./local-link-detector"; diff --git a/apps/desktop/src/renderer/lib/terminal/links/link-detector-adapter.ts b/apps/desktop/src/renderer/lib/terminal/links/link-detector-adapter.ts index 7f5da9edc2f..ca69780d4c0 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/link-detector-adapter.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/link-detector-adapter.ts @@ -13,7 +13,10 @@ import { getXtermLineContent, getXtermRangesByAttr, } from "./buffer-helpers"; -import type { DetectedLink, LocalLinkDetector } from "./local-link-detector"; +import type { + DetectedTerminalLink, + LocalLinkDetector, +} from "./local-link-detector"; /** Maximum characters of context to gather around the hovered line. */ const MAX_LINK_LENGTH = 500; @@ -43,9 +46,12 @@ export class LinkDetectorAdapter implements ILinkProvider { private readonly _detector: LocalLinkDetector, private readonly _onActivate?: ( event: MouseEvent, - link: DetectedLink, + link: DetectedTerminalLink, + ) => void, + private readonly _onHover?: ( + event: MouseEvent, + link: DetectedTerminalLink, ) => void, - private readonly _onHover?: (event: MouseEvent, link: DetectedLink) => void, private readonly _onLeave?: () => void, ) {} @@ -208,7 +214,7 @@ export class LinkDetectorAdapter implements ILinkProvider { } private _mapDetectedLinks( - detectedLinks: DetectedLink[], + detectedLinks: DetectedTerminalLink[], lines: IBufferLine[], cols: number, startLine: number, diff --git a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts index 63513ae777f..c35bf846097 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts @@ -6,7 +6,11 @@ import { describe, expect, it } from "bun:test"; import type { StatCallback } from "./link-resolver"; import { TerminalLinkResolver } from "./link-resolver"; -import { LocalLinkDetector } from "./local-link-detector"; +import { + type DetectedLink, + isWebLink, + LocalLinkDetector, +} from "./local-link-detector"; // --------------------------------------------------------------------------- // Helpers @@ -50,10 +54,17 @@ function createDetector(validPaths: string[], workspaceRoot = "/parent/cwd") { } return null; }; - const resolver = new TerminalLinkResolver(statMock); - return new LocalLinkDetector(resolver); + const detector = new LocalLinkDetector(new TerminalLinkResolver(statMock)); + return { + detect: async (text: string) => + (await detector.detect(text)).filter( + (link): link is DetectedLink => !isWebLink(link), + ), + }; } +const noFile: StatCallback = async () => null; + function formatLink( fmt: string, path: string, @@ -277,6 +288,59 @@ describe("LocalLinkDetector", () => { }); }); + describe("paths that do not exist as written", () => { + it("reads a #L line anchor", async () => { + const detector = createDetector(["/parent/cwd/src/file.ts"]); + const result = await detector.detect("see src/file.ts#L12-L20 here"); + expect(result).toHaveLength(1); + expect(result[0]?.resolvedPath).toBe("/parent/cwd/src/file.ts"); + expect(result[0]?.row).toBe(12); + expect(result[0]?.text).toBe("src/file.ts#L12-L20"); + }); + + it("asks the file finder for a shortened path, without its line", async () => { + const asked: string[] = []; + const detector = new LocalLinkDetector( + new TerminalLinkResolver(noFile), + new TerminalLinkResolver(async (path) => { + asked.push(path); + return { isDirectory: false, resolvedPath: "/repo/apps/api/a.ts" }; + }), + ); + const result = await detector.detect("in api/a.ts:17-33 now"); + expect(asked).toEqual(["api/a.ts"]); + expect(result).toMatchObject([ + { resolvedPath: "/repo/apps/api/a.ts", row: 17 }, + ]); + }); + + it("links a schemeless website that is not a file", async () => { + const detector = new LocalLinkDetector(new TerminalLinkResolver(noFile)); + const result = await detector.detect("docs at example.com/docs/intro ok"); + expect(result).toEqual([ + { + text: "example.com/docs/intro", + startIndex: 8, + endIndex: 30, + url: "https://example.com/docs/intro", + }, + ]); + }); + + it("keeps a file over a website of the same name", async () => { + const detector = new LocalLinkDetector( + new TerminalLinkResolver(async (path) => ({ + isDirectory: false, + resolvedPath: `/repo/${path}`, + })), + ); + const result = await detector.detect("docs at example.com/docs/intro ok"); + expect(result).toMatchObject([ + { resolvedPath: "/repo/example.com/docs/intro" }, + ]); + }); + }); + describe("trimmed candidates", () => { it("should try trimmed path when original has trailing punctuation", async () => { // Path followed by a bracket that gets included in the match — diff --git a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts index a125f8a78c9..5b1c438bd40 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts @@ -14,6 +14,8 @@ import { type IParsedLink, removeLinkSuffix, } from "@superset/shared/terminal-link-parsing"; +import { bareWebUrl } from "renderer/lib/bareWebUrl"; +import { splitLineAnchor } from "renderer/lib/fileLocation"; import type { TerminalLinkResolver } from "./link-resolver"; const MAX_LINE_LENGTH = 2000; @@ -46,6 +48,20 @@ export interface DetectedLink { parsedLink?: IParsedLink; } +/** Path-like text that is no file on the host but names a website. */ +export interface DetectedWebLink { + text: string; + startIndex: number; + endIndex: number; + url: string; +} + +export type DetectedTerminalLink = DetectedLink | DetectedWebLink; + +export function isWebLink(link: DetectedTerminalLink): link is DetectedWebLink { + return "url" in link; +} + /** * Detects local file-system links in a line of terminal text. * @@ -60,14 +76,21 @@ export interface DetectedLink { * host service, not in the renderer. */ export class LocalLinkDetector { - constructor(private readonly _resolver: TerminalLinkResolver) {} + /** + * @param _resolver checks that a path exists as written + * @param _fileFinder finds the file a shortened path most plausibly means + */ + constructor( + private readonly _resolver: TerminalLinkResolver, + private readonly _fileFinder?: TerminalLinkResolver, + ) {} - async detect(text: string): Promise { + async detect(text: string): Promise { if (!text || text.length > MAX_LINE_LENGTH) { return []; } - const links: DetectedLink[] = []; + const links: DetectedTerminalLink[] = []; let resolvedCount = 0; const os = getCurrentOS(); @@ -83,8 +106,12 @@ export class LocalLinkDetector { continue; } - // Build candidate paths to try - const candidates = this._buildCandidates(parsedLink.path.text); + const anchor = parsedLink.suffix + ? null + : splitLineAnchor(parsedLink.path.text); + const candidates = this._buildCandidates( + anchor?.path ?? parsedLink.path.text, + ); // Also generate trimmed candidates (strip trailing punctuation) const trimmedCandidates: string[] = []; @@ -96,23 +123,33 @@ export class LocalLinkDetector { const allCandidates = [...candidates, ...trimmedCandidates]; const resolved = - await this._resolver.resolveMultipleCandidates(allCandidates); - - if (resolved) { - const linkStart = parsedLink.prefix?.index ?? parsedLink.path.index; - const linkEnd = parsedLink.suffix - ? parsedLink.suffix.suffix.index + - parsedLink.suffix.suffix.text.length - : parsedLink.path.index + parsedLink.path.text.length; - + (await this._resolver.resolveMultipleCandidates(allCandidates)) ?? + (candidates[0] + ? await this._fileFinder?.resolveLink(candidates[0]) + : null); + + const linkStart = parsedLink.prefix?.index ?? parsedLink.path.index; + const linkEnd = parsedLink.suffix + ? parsedLink.suffix.suffix.index + parsedLink.suffix.suffix.text.length + : parsedLink.path.index + parsedLink.path.text.length; + const url = resolved ? null : bareWebUrl(parsedLink.path.text); + + if (url) { + links.push({ + text: parsedLink.path.text, + startIndex: parsedLink.path.index, + endIndex: parsedLink.path.index + parsedLink.path.text.length, + url, + }); + } else if (resolved) { links.push({ text: text.substring(linkStart, linkEnd), startIndex: linkStart, endIndex: linkEnd, resolvedPath: resolved.path, isDirectory: resolved.isDirectory, - row: parsedLink.suffix?.row, - col: parsedLink.suffix?.col, + row: parsedLink.suffix?.row ?? anchor?.row, + col: parsedLink.suffix?.col ?? anchor?.col, rowEnd: parsedLink.suffix?.rowEnd, colEnd: parsedLink.suffix?.colEnd, parsedLink, diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.test.ts b/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.test.ts index 59d3124f2d9..3fe84a68815 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.test.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it, mock } from "bun:test"; import type { ILinkProvider, Terminal as XTerm } from "@xterm/xterm"; import { TerminalLinkManager } from "./terminal-link-manager"; -function createMockTerminal() { +function createMockTerminal({ hasSelection = false } = {}) { const registeredProviders: ILinkProvider[] = []; const disposedProviders: ILinkProvider[] = []; const terminal = { @@ -23,6 +23,7 @@ function createMockTerminal() { }, }, cols: 80, + hasSelection: () => hasSelection, } as unknown as XTerm; return { terminal, registeredProviders, disposedProviders }; @@ -69,6 +70,29 @@ describe("TerminalLinkManager", () => { expect(onLinkLeave).toHaveBeenCalled(); }); + it("ignores a plain click that ends a text selection", () => { + const { terminal } = createMockTerminal({ hasSelection: true }); + const manager = new TerminalLinkManager(terminal); + const onUrlClick = mock(); + manager.setHandlers({ stat: async () => null, onUrlClick }); + const range = { start: { x: 1, y: 1 }, end: { x: 20, y: 1 } }; + + terminal.options.linkHandler?.activate( + {} as MouseEvent, + "https://example.com", + range, + ); + expect(onUrlClick).not.toHaveBeenCalled(); + + const modified = { metaKey: true } as MouseEvent; + terminal.options.linkHandler?.activate( + modified, + "https://example.com", + range, + ); + expect(onUrlClick).toHaveBeenCalledWith(modified, "https://example.com"); + }); + it("clears only the OSC link handler it installed", () => { const { terminal, disposedProviders } = createMockTerminal(); const manager = new TerminalLinkManager(terminal); diff --git a/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.ts b/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.ts index 36b3173e163..2163f8e110a 100644 --- a/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.ts +++ b/apps/desktop/src/renderer/lib/terminal/terminal-link-manager.ts @@ -10,6 +10,7 @@ import type { ILinkHandler, Terminal as XTerm } from "@xterm/xterm"; import type { DetectedLink } from "./links"; import { + isWebLink, LinkDetectorAdapter, LocalLinkDetector, type StatCallback, @@ -45,6 +46,11 @@ export interface TerminalLinkHandlers { * which handles all path resolution (relative, tilde, etc.) server-side. */ stat?: StatCallback; + /** + * Finds the file a path most plausibly means when it does not exist as + * written. Asked only for path-like text, never for single words. + */ + resolveFile?: (reference: string) => Promise<{ resolvedPath: string } | null>; } interface LinkProviderDisposable { @@ -62,6 +68,7 @@ interface LinkProviderDisposable { export class TerminalLinkManager { private _disposables: LinkProviderDisposable[] = []; private _resolver: TerminalLinkResolver | null = null; + private _fileFinder: TerminalLinkResolver | null = null; private _handlers: TerminalLinkHandlers | null = null; private _oscLinkHandler: ILinkHandler | null = null; @@ -93,6 +100,8 @@ export class TerminalLinkManager { this._clearOscLinkHandler(); this._resolver?.clearCache(); this._resolver = null; + this._fileFinder?.clearCache(); + this._fileFinder = null; this._handlers = null; } @@ -116,33 +125,65 @@ export class TerminalLinkManager { if (!this._resolver) { this._resolver = new TerminalLinkResolver(handlers.stat); } + if (!this._fileFinder) { + this._fileFinder = new TerminalLinkResolver(async (path) => { + const file = await this._handlers?.resolveFile?.(path); + return file + ? { isDirectory: false, resolvedPath: file.resolvedPath } + : null; + }); + } + + // xterm reports a text-selection drag that ends on a link as a click. + const isClick = (event: MouseEvent) => + event.metaKey || + event.ctrlKey || + event.shiftKey || + !this._terminal.hasSelection(); + const onFileLinkClick = + handlers.onFileLinkClick && + ((event: MouseEvent, link: DetectedLink) => { + if (isClick(event)) handlers.onFileLinkClick?.(event, link); + }); + const onUrlClick = + handlers.onUrlClick && + ((event: MouseEvent, url: string) => { + if (isClick(event)) handlers.onUrlClick?.(event, url); + }); const onLinkHover = handlers.onLinkHover; const onLinkLeave = handlers.onLinkLeave; // 1. File path detector (highest priority) - const detector = new LocalLinkDetector(this._resolver); + const detector = new LocalLinkDetector(this._resolver, this._fileFinder); const adapter = new LinkDetectorAdapter( this._terminal, detector, - handlers.onFileLinkClick, + (event, link) => { + if (isWebLink(link)) onUrlClick?.(event, link.url); + else onFileLinkClick?.(event, link); + }, onLinkHover ? (event, link) => - onLinkHover(event, { - kind: "file", - isDirectory: link.isDirectory, - resolvedPath: link.resolvedPath, - row: link.row, - col: link.col, - }) + onLinkHover( + event, + isWebLink(link) + ? { kind: "url", url: link.url } + : { + kind: "file", + isDirectory: link.isDirectory, + resolvedPath: link.resolvedPath, + row: link.row, + col: link.col, + }, + ) : undefined, onLinkLeave, ); this._disposables.push(this._terminal.registerLinkProvider(adapter)); // 2. URL link provider (handles terminal-wrapped URLs) - if (handlers.onUrlClick) { - const onUrlClick = handlers.onUrlClick; + if (onUrlClick) { const urlProvider = new UrlLinkProvider( this._terminal, (event, uri) => { @@ -177,8 +218,8 @@ export class TerminalLinkManager { // exists (validated via stat). Catches bare filenames like // "AGENTS.md" that have no path separator or line suffix. // To disable: remove or comment out this block. - if (handlers.onFileLinkClick) { - const onFileClick = handlers.onFileLinkClick; + if (onFileLinkClick) { + const onFileClick = onFileLinkClick; const wordDetector = new WordLinkDetector( this._terminal, this._resolver, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/useOpenChatLink.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/useOpenChatLink.ts index 83e0285ee9e..037af5b8136 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/useOpenChatLink.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/useOpenChatLink.ts @@ -10,7 +10,7 @@ import { useUrlLinkAction, } from "renderer/lib/clickPolicy"; import { useOpenInExternalEditor } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useOpenInExternalEditor"; -import { useRecentlyViewedFiles } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useRecentlyViewedFiles"; +import { useWorkspacePathHost } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost"; import { useRevealInFinder } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useRevealInFinder"; import { useRightPaneLinkTarget } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/providers/RightPaneLinkTargetProvider"; import type { @@ -25,7 +25,7 @@ import { type TerminalLinkActionDeps, } from "../../../../utils/runTerminalLinkAction"; import type { OpenLink } from "../../../ChatSession/providers/ChatPaneActionsProvider"; -import { type ChatLinkTarget, locateChatLink } from "./utils/locateChatLink"; +import { locateChatLink } from "./utils/locateChatLink"; import { parseFileHref } from "./utils/parseFileHref"; const WEB_URL = /^https?:\/\//i; @@ -45,7 +45,7 @@ export function useOpenChatLink({ }): OpenLink { const { t } = useLingui(); const filePolicy = useInlineFilePolicy(); - const folderPolicy = useTerminalFolderPolicy(); + const folderPolicy = useTerminalFolderPolicy("2-tier"); const getUrlAction = useUrlLinkAction("2-tier"); const openInExternalEditor = useOpenInExternalEditor(workspaceId); const revealInFinder = useRevealInFinder(workspaceId); @@ -53,22 +53,7 @@ export function useOpenChatLink({ const { data: workspace } = workspaceTrpc.workspace.get.useQuery({ id: workspaceId, }); - const statPath = workspaceTrpc.filesystem.statPath.useMutation(); - const hostClient = workspaceTrpc.useUtils().client; - const { recentFiles } = useRecentlyViewedFiles(workspaceId); - const locateRef = useRef< - (href: string, path: string) => Promise - >(async () => null); - locateRef.current = (href, path) => - locateChatLink(href, path, { - stat: (target) => statPath.mutateAsync({ workspaceId, path: target }), - resolveFile: (reference) => - hostClient.filesystem.resolveFileReference.query({ - workspaceId, - reference, - preferredRelativePaths: recentFiles.map((file) => file.relativePath), - }), - }); + const pathHost = useWorkspacePathHost(workspaceId); const depsRef = useRef({ store, @@ -106,7 +91,7 @@ export function useOpenChatLink({ const file = parseFileHref(href); if (!file) return false; - void locateRef.current(href, file.path).then( + void locateChatLink(href, file.path, pathHost).then( (stat) => { if (!stat) { const { path } = file; @@ -122,15 +107,13 @@ export function useOpenChatLink({ ? chosen === "external" ? "external" : "reveal" - : (folderPolicy.map[tierFor(event, "2-tier")] ?? - (isPlain ? "reveal" : null)); + : folderPolicy.getIntent(event); if (intent === null) showHint(event.clientX, event.clientY); else runFolderLinkAction(depsRef.current, stat.resolvedPath, intent); return; } - const action = - chosen ?? filePolicy.getAction(event) ?? (isPlain ? "pane" : null); + const action = chosen ?? filePolicy.getAction(event); if (action === null) { showHint(event.clientX, event.clientY); return; @@ -148,6 +131,6 @@ export function useOpenChatLink({ ); return true; }, - [getUrlAction, filePolicy, folderPolicy, showHint, t], + [getUrlAction, filePolicy, folderPolicy, pathHost, showHint, t], ); } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/locateChatLink/locateChatLink.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/locateChatLink/locateChatLink.ts index 22c48d64daa..4f1c106d378 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/locateChatLink/locateChatLink.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/locateChatLink/locateChatLink.ts @@ -1,4 +1,4 @@ -import { bareWebUrl } from "../../../../../ChatSession/utils/bareWebUrl"; +import { bareWebUrl } from "renderer/lib/bareWebUrl"; import { type LocatedPath, locatePath } from "../locatePath"; export type ChatLinkTarget = diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.test.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.test.ts index 367e61ce43a..83cc36d6d24 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.test.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.test.ts @@ -16,6 +16,10 @@ test("reads paths and line positions the way agents write them", () => { path: "src/app.ts", row: 12, }); + expect(parseFileHref("src/app.ts:17-33")).toEqual({ + path: "src/app.ts", + row: 17, + }); expect(parseFileHref("src/app.ts#L12-L20")).toEqual({ path: "src/app.ts", row: 12, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.ts index 65fb57c7495..6817bc59a49 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatPane/hooks/useOpenChatLink/utils/parseFileHref/parseFileHref.ts @@ -1,17 +1,17 @@ -export interface FileHref { - path: string; - row?: number; - col?: number; -} +import { + type FileLocation, + splitFileLocation, +} from "renderer/lib/fileLocation"; + +export type FileHref = FileLocation; -const OTHER_SCHEME = /^[a-z][a-z0-9+.-]*:(?!\d+(?::\d+)?$)/i; +const OTHER_SCHEME = /^[a-z][a-z0-9+.-]*:/i; const BROWSER_SCHEME = /^(mailto|tel):/i; -const LINE_ANCHOR = /#L(\d+)(?:C(\d+))?(?:-L?\d+(?:C\d+)?)?$/; -const LINE_SUFFIX = /:(\d+)(?::(\d+))?$/; export function parseFileHref(href: string): FileHref | null { let rest = href.trim(); - if (rest.startsWith("file://")) { + const isFileUrl = rest.startsWith("file://"); + if (isFileUrl) { try { const url = new URL(rest); if (url.hostname !== "" && url.hostname !== "localhost") return null; @@ -19,42 +19,20 @@ export function parseFileHref(href: string): FileHref | null { } catch { return null; } - } else if ( - rest === "" || - rest.startsWith("#") || - BROWSER_SCHEME.test(rest) || - OTHER_SCHEME.test(rest) - ) { + } else if (rest === "" || rest.startsWith("#") || BROWSER_SCHEME.test(rest)) { return null; } - let row: number | undefined; - let col: number | undefined; - const anchor = rest.match(LINE_ANCHOR); - if (anchor) { - row = Number(anchor[1]); - col = anchor[2] ? Number(anchor[2]) : undefined; - rest = rest.slice(0, anchor.index); - } else { - const suffix = rest.match(LINE_SUFFIX); - if (suffix) { - row = Number(suffix[1]); - col = suffix[2] ? Number(suffix[2]) : undefined; - rest = rest.slice(0, suffix.index); - } - } - rest = rest.replace(/[?#].*$/, ""); + const location = splitFileLocation(rest); + if (!isFileUrl && OTHER_SCHEME.test(location.path)) return null; + const encoded = location.path.replace(/[?#].*$/, ""); let path: string; try { - path = decodeURIComponent(rest); + path = decodeURIComponent(encoded); } catch { - path = rest; + path = encoded; } if (path === "") return null; - return { - path, - ...(row !== undefined ? { row } : {}), - ...(col !== undefined ? { col } : {}), - }; + return { ...location, path }; } diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/FileLinkMenu/FileLinkMenu.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/FileLinkMenu/FileLinkMenu.tsx index d7fd6445bee..349ab196183 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/FileLinkMenu/FileLinkMenu.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/FileLinkMenu/FileLinkMenu.tsx @@ -13,9 +13,9 @@ import { toast } from "@superset/ui/sonner"; import { Clipboard, ExternalLink } from "lucide-react"; import type { ReactNode } from "react"; import { useCopyToClipboard } from "renderer/hooks/useCopyToClipboard"; +import { bareWebUrl } from "renderer/lib/bareWebUrl"; import type { LinkAction } from "renderer/lib/clickPolicy"; import { useChatPaneActions } from "../../providers/ChatPaneActionsProvider"; -import { bareWebUrl } from "../../utils/bareWebUrl"; const NO_MODIFIERS = { metaKey: false, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts index 11a30b72c64..92d2b453c24 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts @@ -1,12 +1,13 @@ +import { splitFileLocation } from "renderer/lib/fileLocation"; + const MAX_PATH_TEXT_LENGTH = 240; -const LOCATION_SUFFIX = /(?::\d+(?::\d+)?|#L\d+(?:C\d+)?(?:-L?\d+(?:C\d+)?)?)$/; const FILE_NAME = /^[\w%@+().-]+$/; const EXTENSIONLESS_FILE_NAME = /^(dockerfile|makefile|gemfile|license)$/i; const EXTENSION = /^[a-z][a-z0-9+-]{0,11}$/i; const NON_FILE_SCHEME = /^(?!file:\/\/)[a-z][a-z0-9+.-]*:\/\//i; export function stripLocation(text: string): string { - return text.replace(LOCATION_SUFFIX, ""); + return splitFileLocation(text).path; } export function pathFileName(text: string): string | null { diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/TerminalPane.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/TerminalPane.tsx index e39fb31bfe9..10409d8392c 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/TerminalPane.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/TerminalPane/TerminalPane.tsx @@ -49,6 +49,7 @@ import { resolveTerminalThemeType } from "renderer/stores/theme/utils"; import { isWithinWorkspacePath } from "shared/absolute-paths"; import { useLinkClickHint } from "../../hooks/useLinkClickHint"; import { useSendAttachments } from "../../hooks/useSendAttachments"; +import { useWorkspacePathHost } from "../../hooks/useWorkspacePathHost"; import { runFileLinkAction, runFolderLinkAction, @@ -327,33 +328,15 @@ export function TerminalPane({ ); }, [terminalId, terminalInstanceId, appearance]); - // --- Link handlers --- - // All filesystem operations go through the host service. - // statPath is a mutation (POST) to avoid tRPC GET URL encoding issues - // with paths containing special characters like (). - const statPathMutation = workspaceTrpc.filesystem.statPath.useMutation(); - const statPathRef = useRef(statPathMutation.mutateAsync); - statPathRef.current = statPathMutation.mutateAsync; + const pathHost = useWorkspacePathHost(workspaceId); useEffect(() => { terminalRuntimeRegistry.setLinkHandlers( terminalId, { - stat: async (path) => { - try { - const result = await statPathRef.current({ - workspaceId, - path, - }); - if (!result) return null; - return { - isDirectory: result.isDirectory, - resolvedPath: result.resolvedPath, - }; - } catch { - return null; - } - }, + stat: (path) => pathHost.stat(path).catch(() => null), + resolveFile: (reference) => + pathHost.resolveFile(reference).catch(() => null), onFileLinkClick: (event, link) => { if (link.isDirectory) { const intent = folderPolicy.getIntent(event); @@ -404,7 +387,7 @@ export function TerminalPane({ }, [ terminalId, terminalInstanceId, - workspaceId, + pathHost, onLinkHover, onLinkLeave, showHint, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/index.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/index.ts new file mode 100644 index 00000000000..8e6acb0390e --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/index.ts @@ -0,0 +1,4 @@ +export { + useWorkspacePathHost, + type WorkspacePathHost, +} from "./useWorkspacePathHost"; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/useWorkspacePathHost.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/useWorkspacePathHost.ts new file mode 100644 index 00000000000..3bfab95b40f --- /dev/null +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/hooks/useWorkspacePathHost/useWorkspacePathHost.ts @@ -0,0 +1,42 @@ +import { workspaceTrpc } from "@superset/workspace-client"; +import { useMemo, useRef } from "react"; +import { useRecentlyViewedFiles } from "renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/useRecentlyViewedFiles"; + +export interface WorkspacePathHost { + stat: ( + path: string, + ) => Promise<{ resolvedPath: string; isDirectory: boolean } | null>; + /** The file a shortened or misplaced path most plausibly means. */ + resolveFile: (reference: string) => Promise<{ resolvedPath: string } | null>; +} + +/** + * How agent output (terminal, chat) asks the workspace host about a path. + * The returned object is stable, so link handlers can keep it. + */ +export function useWorkspacePathHost(workspaceId: string): WorkspacePathHost { + // statPath is a mutation (POST): a GET puts the path in the URL, and tRPC + // mangles paths with characters like (). + const statPath = workspaceTrpc.filesystem.statPath.useMutation(); + const hostClient = workspaceTrpc.useUtils().client; + const { recentFiles } = useRecentlyViewedFiles(workspaceId); + + const calls: WorkspacePathHost = { + stat: (path) => statPath.mutateAsync({ workspaceId, path }), + resolveFile: (reference) => + hostClient.filesystem.resolveFileReference.query({ + workspaceId, + reference, + preferredRelativePaths: recentFiles.map((file) => file.relativePath), + }), + }; + const latest = useRef(calls); + latest.current = calls; + return useMemo( + () => ({ + stat: (path) => latest.current.stat(path), + resolveFile: (reference) => latest.current.resolveFile(reference), + }), + [], + ); +} diff --git a/apps/desktop/src/renderer/routes/_authenticated/settings/components/LinkTierMapper/LinkTierMapper.tsx b/apps/desktop/src/renderer/routes/_authenticated/settings/components/LinkTierMapper/LinkTierMapper.tsx index 1efedcc0229..54f76172cc5 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/settings/components/LinkTierMapper/LinkTierMapper.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/settings/components/LinkTierMapper/LinkTierMapper.tsx @@ -40,6 +40,8 @@ interface LinkTierMapperProps { onChange: (next: LinkTierMap) => void; idPrefix: string; surface: Surface; + /** What an unbound plain click does here. Hides "Do nothing" for it. */ + plainDefault?: LinkAction; } export function LinkTierMapper({ @@ -49,6 +51,7 @@ export function LinkTierMapper({ onChange, idPrefix, surface, + plainDefault, }: LinkTierMapperProps) { const searchQuery = useSettingsSearchQuery(); const isRightPaneAreaEnabled = useRightPaneAreaEnabled() === true; @@ -72,6 +75,7 @@ export function LinkTierMapper({
{TIERS.map((tier) => { const id = `${idPrefix}-${tier}`; + const fallback = tier === "plain" ? plainDefault : undefined; const actions: LinkAction[] = surface === "url" && (isRightPaneAreaEnabled || value[tier] === "rightPane") @@ -86,7 +90,7 @@ export function LinkTierMapper({ {modifierLabel(tier)} pick(tier, v as SlotValue)} > - - Do nothing - + {!fallback && ( + + Do nothing + + )} {ACTIONS.map((action) => ( {folderIntentLabel(action)} From f3bd9c12595e7a8e6445f02308d81c828122cad5 Mon Sep 17 00:00:00 2001 From: Kiet Ho Date: Sat, 21 Nov 2026 16:54:45 -0800 Subject: [PATCH 2/2] fix(desktop): keep bare words and file locations out of terminal link fallbacks The shortened-path lookup ran for any parsed path, so `version 12` could open a file named `version`. It now asks only for file-like names, with the gate chat already uses (pathText moves to renderer/lib). A path with a line suffix that is not a file, such as `main.io:12:4`, no longer links as a website. --- .../utils => lib}/pathText/index.ts | 0 .../utils => lib}/pathText/pathText.test.ts | 0 .../utils => lib}/pathText/pathText.ts | 0 .../terminal/links/local-link-detector.test.ts | 18 ++++++++++++++++++ .../lib/terminal/links/local-link-detector.ts | 6 ++++-- .../utils/fencedCode/fencedCode.ts | 2 +- .../ChatInlineCode/ChatInlineCode.tsx | 2 +- .../ShellIntentTitle/ShellIntentTitle.tsx | 2 +- .../ChatSession/utils/linkUnfurl/linkUnfurl.ts | 2 +- 9 files changed, 26 insertions(+), 6 deletions(-) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/pathText/index.ts (100%) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/pathText/pathText.test.ts (100%) rename apps/desktop/src/renderer/{routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils => lib}/pathText/pathText.ts (100%) diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/index.ts b/apps/desktop/src/renderer/lib/pathText/index.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/index.ts rename to apps/desktop/src/renderer/lib/pathText/index.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.test.ts b/apps/desktop/src/renderer/lib/pathText/pathText.test.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.test.ts rename to apps/desktop/src/renderer/lib/pathText/pathText.test.ts diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts b/apps/desktop/src/renderer/lib/pathText/pathText.ts similarity index 100% rename from apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/pathText/pathText.ts rename to apps/desktop/src/renderer/lib/pathText/pathText.ts diff --git a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts index c35bf846097..c80dcf83d1e 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.test.ts @@ -314,6 +314,24 @@ describe("LocalLinkDetector", () => { ]); }); + it("does not ask the file finder for a bare word", async () => { + const asked: string[] = []; + const detector = new LocalLinkDetector( + new TerminalLinkResolver(noFile), + new TerminalLinkResolver(async (path) => { + asked.push(path); + return { isDirectory: false, resolvedPath: `/repo/src/${path}` }; + }), + ); + expect(await detector.detect("version 12")).toEqual([]); + expect(asked).toEqual([]); + }); + + it("does not link a file location as a website", async () => { + const detector = new LocalLinkDetector(new TerminalLinkResolver(noFile)); + expect(await detector.detect("error at main.io:12:4 here")).toEqual([]); + }); + it("links a schemeless website that is not a file", async () => { const detector = new LocalLinkDetector(new TerminalLinkResolver(noFile)); const result = await detector.detect("docs at example.com/docs/intro ok"); diff --git a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts index 5b1c438bd40..dee0bc8e209 100644 --- a/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts +++ b/apps/desktop/src/renderer/lib/terminal/links/local-link-detector.ts @@ -16,6 +16,7 @@ import { } from "@superset/shared/terminal-link-parsing"; import { bareWebUrl } from "renderer/lib/bareWebUrl"; import { splitLineAnchor } from "renderer/lib/fileLocation"; +import { pathFileName } from "renderer/lib/pathText"; import type { TerminalLinkResolver } from "./link-resolver"; const MAX_LINE_LENGTH = 2000; @@ -124,7 +125,7 @@ export class LocalLinkDetector { const resolved = (await this._resolver.resolveMultipleCandidates(allCandidates)) ?? - (candidates[0] + (candidates[0] && pathFileName(candidates[0]) ? await this._fileFinder?.resolveLink(candidates[0]) : null); @@ -132,7 +133,8 @@ export class LocalLinkDetector { const linkEnd = parsedLink.suffix ? parsedLink.suffix.suffix.index + parsedLink.suffix.suffix.text.length : parsedLink.path.index + parsedLink.path.text.length; - const url = resolved ? null : bareWebUrl(parsedLink.path.text); + const url = + resolved || parsedLink.suffix ? null : bareWebUrl(parsedLink.path.text); if (url) { links.push({ diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatCodeBlock/utils/fencedCode/fencedCode.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatCodeBlock/utils/fencedCode/fencedCode.ts index 8b44d84fef0..46f5947ee2c 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatCodeBlock/utils/fencedCode/fencedCode.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatCodeBlock/utils/fencedCode/fencedCode.ts @@ -4,7 +4,7 @@ import { isLocalPathText, pathFileName, stripLocation, -} from "../../../../utils/pathText"; +} from "renderer/lib/pathText"; const LANGUAGE_CLASS = /(?:^|\s)language-([^\s]+)/; const LINE_RANGE_PATH = /^(\d+):\d+:(.+)$/; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatInlineCode/ChatInlineCode.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatInlineCode/ChatInlineCode.tsx index 8249c761952..8969c425fa2 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatInlineCode/ChatInlineCode.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/ChatInlineCode/ChatInlineCode.tsx @@ -2,9 +2,9 @@ import { chatMarkdownComponents } from "@superset/chat-ui/ChatMarkdown"; import { cn } from "@superset/ui/utils"; import type { ComponentProps, KeyboardEvent } from "react"; import { FileIcon } from "renderer/lib/fileIcons"; +import { isLocalPathText, pathFileName } from "renderer/lib/pathText"; import { useIsInsideChatLink } from "../../providers/ChatLinkProvider"; import { useChatPaneActions } from "../../providers/ChatPaneActionsProvider"; -import { isLocalPathText, pathFileName } from "../../utils/pathText"; import { FileLinkMenu } from "../FileLinkMenu"; const PlainInlineCode = chatMarkdownComponents.inlineCode; diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ToolCallRow/components/ShellIntentTitle/ShellIntentTitle.tsx b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ToolCallRow/components/ShellIntentTitle/ShellIntentTitle.tsx index 49bd3d34624..203cc75ac0e 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ToolCallRow/components/ShellIntentTitle/ShellIntentTitle.tsx +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/components/Transcript/components/ToolCallRow/components/ShellIntentTitle/ShellIntentTitle.tsx @@ -2,8 +2,8 @@ import { Trans } from "@lingui/react/macro"; import { ShimmerLabel } from "@superset/ui/ai-elements/shimmer-label"; import { cn } from "@superset/ui/utils"; import { FileIcon } from "renderer/lib/fileIcons"; +import { isLocalPathText } from "renderer/lib/pathText"; import { useChatPaneActions } from "../../../../../../providers/ChatPaneActionsProvider"; -import { isLocalPathText } from "../../../../../../utils/pathText"; import { fileName } from "../../../../utils/fileChange"; import { intentLocation, diff --git a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/linkUnfurl/linkUnfurl.ts b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/linkUnfurl/linkUnfurl.ts index a5ad72eb576..e58a2452a11 100644 --- a/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/linkUnfurl/linkUnfurl.ts +++ b/apps/desktop/src/renderer/routes/_authenticated/_dashboard/workspace/$workspaceId/hooks/usePaneRegistry/components/ChatSession/utils/linkUnfurl/linkUnfurl.ts @@ -1,5 +1,5 @@ +import { stripLocation } from "renderer/lib/pathText"; import { parseGithubWorkItemUrl } from "../githubWorkItem"; -import { stripLocation } from "../pathText"; import { parseSupersetAppLink } from "../supersetAppLink"; export type LinkUnfurl = {