Open links and workspace paths from replies with a click

Links come from OpenTUI's markdown link detection (renderer.getLinkAt) and open
with xdg-open or open; a path under the click that names a workspace file opens
it in the editor pane. A drag still selects.
This commit is contained in:
Callum Alpass committed 2026-11-03 03:15:59 +11:00
1 parent aa865e24eb
commit c1a7376aa8
8 files changed
+206 -16

No files matched your search

+25
View File
@@ -0,0 +1,25 @@
/** Characters a file path on screen is made of, with an optional `:line` or `:line:col` after it. */
const PATH_CHARS = /[\w.~/@+-]/;
/**
* The file path the text has at `index`, as an agent writes them: `src/ui/App.tsx`,
* `./bin.ts:12`, `~/notes.md`. Null for words, URLs and anything else without a folder
* or an extension.
*/
export function pathAt(text: string, index: number): string | null {
if (!PATH_CHARS.test(text[index] ?? "")) return null;
let start = index;
let end = index + 1;
while (start > 0 && PATH_CHARS.test(text[start - 1]!)) start--;
while (end < text.length && (PATH_CHARS.test(text[end]!) || (text[end] === ":" && /\d/.test(text[end + 1] ?? "")))) end++;
if (text[start - 1] === ":" || text.slice(end, end + 3) === "://") return null;
const token = text.slice(start, end).replace(/[.,]+$/, "");
const path = token.replace(/(:\d+){1,2}$/, "");
if (!/[\w~]/.test(path[0] ?? "") && !path.startsWith("./") && !path.startsWith("../") && !path.startsWith("/")) return null;
return path.includes("/") || /\.[A-Za-z]\w*$/.test(path) ? path : null;
}
/** A link's target is a web page unless it is a bare path. */
export function isWebUrl(url: string): boolean {
return /^[a-z][a-z\d+.-]*:/i.test(url) && !url.toLowerCase().startsWith("file:");
}
+17 -2
View File
@@ -3,15 +3,16 @@ import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"
import { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { existsSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts";
import { pastedImagePath } from "../model/attachments.ts";
import { isWebUrl, pathAt } from "../model/links.ts";
import { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts";
import { saveLayout, type Layout } from "../layout.ts";
@@ -47,6 +48,7 @@ import { SettingsView } from "./SettingsView.tsx";
import { useWorkspace } from "./useWorkspace.ts";
import { usePullRequests } from "./usePullRequests.ts";
import { rendererClipboard, type Clipboard } from "./clipboard.ts";
import { openInBrowser, screenTextAt } from "./links.ts";
import { desktopNotify, ring } from "./terminalOut.ts";
import { colors, statusColor } from "./theme.ts";
import { BAR, NO_BORDER } from "./edges.ts";
@@ -583,6 +585,18 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
showPane({ kind: "local", id: `edit:${file}`, title: `Editing ${path}`, command: editorCommand(file), cwd: cwd ?? undefined, onExit: () => {} });
};
/** A click on a link opens it in the browser; on a path to a workspace file, in the editor pane. A drag doesn't. */
const openAt = (x: number, y: number) => {
if (renderer.getSelection()?.getSelectedText()) return;
const url = renderer.getLinkAt(x, y);
if (url && isWebUrl(url)) return openInBrowser(url, (reason) => say(`Could not open the browser (${reason}): ${url}`, true));
const shown = url ? null : screenTextAt(renderer, x, y);
const raw = url ? (url.startsWith("file:") ? decodeURIComponent(parseFileUrlHref(url)?.path ?? "") : url) : shown && pathAt(shown.text, shown.index);
if (!raw || !attachCwd) return;
const { path } = splitFilePathPosition(resolvePathLinkTarget(raw, attachCwd));
if (existsSync(path) && statSync(path).isFile()) editFile(path, attachCwd);
};
const settingsRows = settingRows(config);
const cycleSetting = (index: number) => {
const row = settingsRows[index];
@@ -1025,6 +1039,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
loadEarlier: useEvent(() => loadEarlier()),
menu: useEvent((target: ConversationTarget) => openConversationMenu(target)),
openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)),
click: useEvent((x: number, y: number) => openAt(x, y)),
};
const copy = (label: string, text: string) => {
void clipboard.copy(text);
+3 -1
View File
@@ -35,6 +35,8 @@ export interface ConversationMouse {
readonly menu: (target: ConversationTarget) => void;
/** A click on a changed file: that turn's diff. */
readonly openTurnDiff: (checkpointTurnCount: number) => void;
/** A click in a reply's text, at its screen position, for the link or path under it. */
readonly click: (x: number, y: number) => void;
}
/** Prose stops at this width on wide terminals, left-aligned. */
@@ -179,7 +181,7 @@ const Row = memo(function Row(props: {
if (message.role === "system") return <text marginTop={1} fg={colors.muted} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>{message.text}</text>;
return (
<box marginTop={1} flexDirection="column" onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>
<markdown content={message.text || "…"} syntaxStyle={markdownStyle} streaming={message.streaming} conceal tableOptions={{ widthMode: "content", wrapMode: "word", cellPaddingX: 1, borderColor: colors.border }} />
<markdown content={message.text || "…"} syntaxStyle={markdownStyle} streaming={message.streaming} conceal tableOptions={{ widthMode: "content", wrapMode: "word", cellPaddingX: 1, borderColor: colors.border }} onMouseUp={(event: MouseEvent) => isLeftClick(event) && mouse.click(event.x, event.y)} />
{summary && summary.files.length > 0 ? <ChangedFiles summary={summary} onOpenTurnDiff={mouse.openTurnDiff} /> : null}
{props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null}
</box>
+30
View File
@@ -0,0 +1,30 @@
import type { CliRenderer } from "@opentui/core";
/** Opens a web link in the desktop's browser; `fail` hears why it couldn't, as over SSH. */
export function openInBrowser(url: string, fail: (reason: string) => void): void {
try {
const opener = process.platform === "darwin" ? "open" : "xdg-open";
// The environment as it is now: Bun otherwise looks the opener up on the PATH it started with.
const child = Bun.spawn([opener, url], { env: process.env, stdin: "ignore", stdout: "ignore", stderr: "ignore" });
void child.exited.then((code) => {
if (code !== 0) fail(`${opener} exited with ${code}`);
});
} catch (error) {
fail(error instanceof Error ? error.message : String(error));
}
}
/** The screen row `y` as drawn, and the index in it of the character in column `x`. */
export function screenTextAt(renderer: CliRenderer, x: number, y: number): { readonly text: string; readonly index: number } | null {
const row = new TextDecoder().decode(renderer.currentRenderBuffer.getRealCharBytes(true)).split("\n")[y];
if (row === undefined) return null;
// Wide characters take two columns but one place in the text.
let column = 0;
let index = 0;
for (const char of row) {
column += Bun.stringWidth(char);
if (column > x) return { text: row, index };
index += char.length;
}
return null;
}
+5 -12
View File
@@ -40,6 +40,7 @@ import {
import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts";
import type { Clipboard } from "./clipboard.ts";
import { openInBrowser } from "./links.ts";
import { firstLine } from "./text.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx";
@@ -158,7 +159,7 @@ export function usePullRequests(deps: PullRequestDeps) {
})();
};
const openInBrowser = () => {
const openPullRequest = () => {
const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
if (!url) return;
// Over SSH or without a desktop there may be no browser to open: copy the link instead.
@@ -166,15 +167,7 @@ export function usePullRequests(deps: PullRequestDeps) {
void deps.clipboard.copy(url);
deps.say(`Could not open the browser (${reason}); link copied: ${url}`, true);
};
try {
const opener = process.platform === "darwin" ? "open" : "xdg-open";
const child = Bun.spawn([opener, url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
void child.exited.then((code) => {
if (code !== 0) fallBack(`${opener} exited with ${code}`);
});
} catch (error) {
fallBack(messageOf(error));
}
openInBrowser(url, fallBack);
};
const reloadQuietly = () => {
@@ -433,7 +426,7 @@ export function usePullRequests(deps: PullRequestDeps) {
const current = loaded;
const viewKeys: Binding[] = current
? keys(
{ keys: ["o"], run: openInBrowser, hint: "open" },
{ keys: ["o"], run: openPullRequest, hint: "open" },
{ keys: ["r"], run: refresh, hint: "refresh" },
current.detail && [
{ keys: ["c"], run: comment, hint: "comment" },
@@ -479,7 +472,7 @@ export function usePullRequests(deps: PullRequestDeps) {
commands.push({ id: "pr-comment", title: `Comment on pull request #${number}`, shortcut: "c", keywords: ["comment", "pull request"], run: comment });
commands.push({ id: "pr-review", title: `Review pull request #${number}…`, shortcut: "R", keywords: ["review", "approve", "request changes"], run: review });
commands.push({ id: "pr-actions", title: `Pull request #${number} actions…`, shortcut: "a", keywords: ["merge", "close", "ready", "draft"], run: actions });
commands.push({ id: "pr-open", title: `Open pull request #${number} in browser`, shortcut: "o", keywords: ["open", "browser"], run: openInBrowser });
commands.push({ id: "pr-open", title: `Open pull request #${number} in browser`, shortcut: "o", keywords: ["open", "browser"], run: openPullRequest });
commands.push({ id: "pr-refresh", title: "Refresh pull request", shortcut: "r", keywords: ["refresh", "reload"], run: refresh });
}