Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions packages/tui/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
TuiStartupProvider,
TuiTerminalEnvironmentProvider,
useTuiApp,
useTuiPaths,
useTuiStartup,
useTuiTerminalEnvironment,
type TuiApp,
Expand Down Expand Up @@ -84,7 +85,7 @@ import { Toast, ToastProvider, useToast } from "./ui/toast"
import { isFallbackTitle } from "@opencode/util/session-title-fallback"
import * as Model from "./util/model"
import { ArgsProvider, useArgs, type Args } from "./context/args"
import { openUrl } from "@opencode/util/open"
import { openHref, openUrl, resolveOpenTarget } from "@opencode/util/open"
import { PromptRefProvider, usePromptRef } from "./context/prompt"
import { Config, ConfigProvider, useConfig } from "./config"
import { newSessionLocation } from "./config/new-session-location"
Expand Down Expand Up @@ -453,6 +454,7 @@ export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {

function App() {
const app = useTuiApp()
const paths = useTuiPaths()
const startup = useTuiStartup()
const config = useConfig()
const devtools = createMemo(() => config.data.debug?.devtools ?? app.channel === "local")
Expand All @@ -477,6 +479,7 @@ function App() {
const plugins = usePlugin()
const clipboard = useClipboard()
const terminalEnvironment = useTuiTerminalEnvironment()
const linkBase = () => location.current?.directory || paths.cwd
let paletteTimer: ReturnType<typeof setTimeout> | undefined
const afterFrame = () => {
// The native writer can still be flushing the frame when FRAME fires. Keep OSC probes behind visible app output.
Expand Down Expand Up @@ -1334,7 +1337,11 @@ function App() {
}}
onMouseUp={(event) => {
const url = clickedLink(renderer, event)
if (url) return void openUrl(url).catch(toast.error)
if (url) {
const base = linkBase()
// Skip links we cannot open so the terminal/IDE can handle them (e.g. Cmd-click).
if (resolveOpenTarget(url, base)) return void openHref(url, base).catch(toast.error)
}
if (copyOnSelectEnabled()) Selection.copyOnSelectRelease(event, renderer, toast, clipboard)
}}
>
Expand Down
11 changes: 6 additions & 5 deletions packages/tui/src/ui/link.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { JSX } from "solid-js"
import type { CliRenderer, MouseEvent, RGBA } from "@opentui/core"
import { openUrl } from "@opencode/util/open"
import { openHref } from "@opencode/util/open"

export interface LinkProps {
href: string
Expand All @@ -13,7 +13,7 @@ export interface LinkProps {

/**
* Link component that renders clickable hyperlinks.
* Clicking anywhere on the link text opens the URL in the default browser.
* Clicking anywhere on the link text opens http(s) URLs in the browser, or local file paths with the OS handler.
*/
export function Link(props: LinkProps) {
const displayText = props.children ?? props.href
Expand All @@ -25,7 +25,7 @@ export function Link(props: LinkProps) {
width={props.width}
wrapMode={props.wrapMode}
onMouseUp={() => {
openUrl(props.href).catch(() => {})
openHref(props.href).catch(() => {})
}}
>
<a href={props.href}>{displayText}</a>
Expand All @@ -37,10 +37,11 @@ export function Link(props: LinkProps) {
* Returns the hyperlink under a plain left click. opentui marks the release that ends a selection gesture with
* `isDragging`, and a fresh "cell" selection means the pointer never moved; other releases, such as the end of a drag
* that started outside text, are not clicks. Each rendered cell stores its full URL, so a click on any row of a wrapped
* link resolves the whole link. Modified clicks are left to the terminal's own hyperlink handling.
* link resolves the whole link. Modified clicks (including Cmd/meta when the terminal reports it) are left to the
* terminal's own hyperlink handling.
*/
export function clickedLink(renderer: CliRenderer, event: MouseEvent) {
if (!event.isDragging || event.modifiers.ctrl || event.modifiers.alt || event.modifiers.shift) return
if (!event.isDragging || Object.values(event.modifiers).some(Boolean)) return
const selection = renderer.getSelection()
if (!selection?.isStart || selection.behavior !== "cell") return
return renderer.getLinkAt(event.x, event.y) ?? undefined
Expand Down
2 changes: 2 additions & 0 deletions packages/tui/test/ui/link.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ test("plain clicks on any row of a wrapped Markdown link resolve the full URL",
await app.mockMouse.click(0, head)
await app.mockMouse.click(x, head, 0, { modifiers: { ctrl: true } })
await app.mockMouse.click(x, head, 0, { modifiers: { shift: true } })
await app.mockMouse.click(x, head, 0, { modifiers: { alt: true } })
await app.mockMouse.click(x, head, 0, { modifiers: { meta: true } as never })
await app.mockMouse.click(x, head, 2)
await app.mockMouse.drag(0, head, x + 2, head)
await app.mockMouse.drag(0, 0, x + 2, head)
Expand Down
32 changes: 31 additions & 1 deletion packages/util/src/open.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { describe, expect, test } from "bun:test"
import { openUrl } from "./open.js"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { openUrl, resolveOpenTarget } from "./open.js"

describe("openUrl", () => {
test("rejects values that are not URLs", async () => {
Expand All @@ -14,3 +16,31 @@ describe("openUrl", () => {
await expect(openUrl("\\\\server\\share\\file.html")).rejects.toThrow("Only http and https links")
})
})

describe("resolveOpenTarget", () => {
test("keeps http and https URLs for the browser", () => {
expect(resolveOpenTarget("https://example.com/docs")).toBe("https://example.com/docs")
expect(resolveOpenTarget("http://127.0.0.1:4096")).toBe("http://127.0.0.1:4096/")
})

test("maps local file URLs and absolute paths to filesystem paths", () => {
const file = path.join(path.resolve("/tmp"), "example.md")
expect(resolveOpenTarget(pathToFileURL(file).href)).toBe(file)
expect(resolveOpenTarget(file)).toBe(file)
})

test("resolves relative paths against a session directory base", () => {
const base = path.resolve("/repo")
expect(resolveOpenTarget("plan/example.md", base)).toBe(path.join(base, "plan/example.md"))
expect(resolveOpenTarget("./src/foo.ts", base)).toBe(path.join(base, "src/foo.ts"))
expect(resolveOpenTarget("../sibling.md", base)).toBe(path.resolve(base, "../sibling.md"))
})

test("rejects remote file URLs, anchors, and unsafe schemes", () => {
expect(resolveOpenTarget("file://example.com/share/index.html")).toBeUndefined()
expect(resolveOpenTarget("javascript:alert(1)")).toBeUndefined()
expect(resolveOpenTarget("#section", "/repo")).toBeUndefined()
expect(resolveOpenTarget("packages/tui/src/ui/link.tsx")).toBeUndefined()
expect(resolveOpenTarget("not a url")).toBeUndefined()
})
})
33 changes: 31 additions & 2 deletions packages/util/src/open.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import open from "open"
import path from "node:path"
import { fileURLToPath } from "node:url"

export function openUrl(input: string) {
const url = URL.canParse(input) ? new URL(input) : undefined
Expand All @@ -7,6 +9,33 @@ export function openUrl(input: string) {
return open(url.href)
}

export function openPath(path: string) {
return open(path)
export function openPath(target: string) {
return open(target)
}

/** Open an http(s) URL in the browser, or a local file path / file:// link with the OS handler. */
export function openHref(input: string, base?: string) {
const target = resolveOpenTarget(input, base)
if (!target) return Promise.reject(new Error(`Only http, https, and local file links can be opened: ${input}`))
return open(target)
}

/** @internal */
export function resolveOpenTarget(input: string, base?: string) {
if (URL.canParse(input)) {
const url = new URL(input)
if (url.protocol === "http:" || url.protocol === "https:") return url.href
// Match desktop: only local file URLs (no host) become filesystem paths.
if (url.protocol === "file:" && !url.hostname) {
try {
return fileURLToPath(url.href)
} catch {
return undefined
}
}
return undefined
}
if (path.isAbsolute(input)) return input

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Models usually link project files relatively, e.g. [plan](plan/example.md) or src/foo.ts. Those still fail here and end in an error toast, just with different wording, and the test fixes that behaviour in place. Could the TUI resolve relative paths against the session directory before calling openHref, or at least not intercept links it can't handle, so the click falls through to the terminal? Otherwise #54816 is only fixed for absolute paths.

// Resolve project-relative Markdown links such as plan/example.md against the session directory.
if (base !== undefined && input.length > 0 && !input.startsWith("#")) return path.resolve(base, input)
}
Loading