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

+1 -1
View File
@@ -116,7 +116,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
- **Select and copy:** drag across any text, in the conversation or the terminal pane, to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally) and `Copied` shows at the bottom. A program in the pane that takes the mouse itself, like an editor with mouse support, gets the drag instead. A single click still does what it did. A key press clears the highlight. Your terminal's own selection still works with shift held. - **Select and copy:** drag across any text, in the conversation or the terminal pane, to select it; it's copied when you let go (through the terminal with OSC 52, and the desktop clipboard locally) and `Copied` shows at the bottom. A program in the pane that takes the mouse itself, like an editor with mouse support, gets the drag instead. A single click still does what it did. A key press clears the highlight. Your terminal's own selection still works with shift held.
- **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top. - **Buttons:** approvals, questions (click an option), secret requests, confirmations, queued messages (click one to send it now, edit or remove it), attached files (✕ removes one) and the PR view have buttons, each with its key beside it. Every hint along the bottom that names one key is clickable, and so is `commands` at the top.
- **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser. - **Conversation:** a click on a prompt selects that turn, as `[`/`]` do; a click on a folded turn or work group opens just that one; a click on a command shows its output; "Load earlier turns" loads them. In a reply, links are underlined in the accent colour and a click opens them in the browser (`xdg-open`, or `open` on macOS); a click on a path to a file in the workspace, like `src/ui/App.tsx:12`, opens it in the editor pane. In a diff, a click on a file selects it and a second click shows the whole file. In the PR view, the URL opens in the browser.
- **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions). - **Right-click menus:** on a thread (its actions), a prompt (copy, view its changes, revert), a reply (copy), a command (copy the command or its output) and the PR view (its actions).
- **Panes:** clicking the conversation takes the keys out of the message box or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, or the details column's left edge, to resize it; right-click the edge to reset it. - **Panes:** clicking the conversation takes the keys out of the message box or details; clicking the message box types. The wheel scrolls the conversation, the thread list (without moving the selection) and the palette. Drag the thread list's right edge, or the details column's left edge, to resize it; right-click the edge to reset it.
+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 { resolveComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; 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 { 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts"; import type { ChatAttachment, OrchestrationMessageContext } from "@t3tools/contracts";
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts"; import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts"; import { createAlerts, type Alert } from "../model/alerts.ts";
import { pastedImagePath } from "../model/attachments.ts"; import { pastedImagePath } from "../model/attachments.ts";
import { isWebUrl, pathAt } from "../model/links.ts";
import { modelSummary } from "../model/models.ts"; import { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts"; import { configPath, cycleConfig, saveConfig, type T3tuiConfig } from "../config.ts";
import { saveLayout, type Layout } from "../layout.ts"; import { saveLayout, type Layout } from "../layout.ts";
@@ -47,6 +48,7 @@ import { SettingsView } from "./SettingsView.tsx";
import { useWorkspace } from "./useWorkspace.ts"; import { useWorkspace } from "./useWorkspace.ts";
import { usePullRequests } from "./usePullRequests.ts"; import { usePullRequests } from "./usePullRequests.ts";
import { rendererClipboard, type Clipboard } from "./clipboard.ts"; import { rendererClipboard, type Clipboard } from "./clipboard.ts";
import { openInBrowser, screenTextAt } from "./links.ts";
import { desktopNotify, ring } from "./terminalOut.ts"; import { desktopNotify, ring } from "./terminalOut.ts";
import { colors, statusColor } from "./theme.ts"; import { colors, statusColor } from "./theme.ts";
import { BAR, NO_BORDER } from "./edges.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: () => {} }); 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 settingsRows = settingRows(config);
const cycleSetting = (index: number) => { const cycleSetting = (index: number) => {
const row = settingsRows[index]; const row = settingsRows[index];
@@ -1025,6 +1039,7 @@ export function App(props: { readonly session: T3Session; readonly config: T3tui
loadEarlier: useEvent(() => loadEarlier()), loadEarlier: useEvent(() => loadEarlier()),
menu: useEvent((target: ConversationTarget) => openConversationMenu(target)), menu: useEvent((target: ConversationTarget) => openConversationMenu(target)),
openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)), openTurnDiff: useEvent((checkpointTurnCount: number) => turns.openTurnDiff(checkpointTurnCount)),
click: useEvent((x: number, y: number) => openAt(x, y)),
}; };
const copy = (label: string, text: string) => { const copy = (label: string, text: string) => {
void clipboard.copy(text); void clipboard.copy(text);
+3 -1
View File
@@ -35,6 +35,8 @@ export interface ConversationMouse {
readonly menu: (target: ConversationTarget) => void; readonly menu: (target: ConversationTarget) => void;
/** A click on a changed file: that turn's diff. */ /** A click on a changed file: that turn's diff. */
readonly openTurnDiff: (checkpointTurnCount: number) => void; 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. */ /** 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>; if (message.role === "system") return <text marginTop={1} fg={colors.muted} onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}>{message.text}</text>;
return ( return (
<box marginTop={1} flexDirection="column" onMouseDown={(event: MouseEvent) => isRightClick(event) && mouse.menu(menu)}> <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} {summary && summary.files.length > 0 ? <ChangedFiles summary={summary} onOpenTurnDiff={mouse.openTurnDiff} /> : null}
{props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null} {props.footer ? <text marginTop={1} fg={colors.faint}>{props.footer}</text> : null}
</box> </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 type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts"; import { editInEditor } from "./editor.ts";
import type { Clipboard } from "./clipboard.ts"; import type { Clipboard } from "./clipboard.ts";
import { openInBrowser } from "./links.ts";
import { firstLine } from "./text.ts"; import { firstLine } from "./text.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx"; 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; const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
if (!url) return; if (!url) return;
// Over SSH or without a desktop there may be no browser to open: copy the link instead. // 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); void deps.clipboard.copy(url);
deps.say(`Could not open the browser (${reason}); link copied: ${url}`, true); deps.say(`Could not open the browser (${reason}); link copied: ${url}`, true);
}; };
try { openInBrowser(url, fallBack);
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));
}
}; };
const reloadQuietly = () => { const reloadQuietly = () => {
@@ -433,7 +426,7 @@ export function usePullRequests(deps: PullRequestDeps) {
const current = loaded; const current = loaded;
const viewKeys: Binding[] = current const viewKeys: Binding[] = current
? keys( ? keys(
{ keys: ["o"], run: openInBrowser, hint: "open" }, { keys: ["o"], run: openPullRequest, hint: "open" },
{ keys: ["r"], run: refresh, hint: "refresh" }, { keys: ["r"], run: refresh, hint: "refresh" },
current.detail && [ current.detail && [
{ keys: ["c"], run: comment, hint: "comment" }, { 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-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-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-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 }); commands.push({ id: "pr-refresh", title: "Refresh pull request", shortcut: "r", keywords: ["refresh", "reload"], run: refresh });
} }
+89
View File
@@ -0,0 +1,89 @@
import { afterEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { v2ShellSnapshot } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
import { withReply } from "./fixtures.ts";
import { fakeSession, renderApp } from "./harness.tsx";
let app: Awaited<ReturnType<typeof renderApp>> | null = null;
const open = async (...args: Parameters<typeof renderApp>) => (app = await renderApp(...args));
const saved = { path: process.env.PATH, visual: process.env.VISUAL, editor: process.env.EDITOR };
afterEach(() => {
app?.destroy();
app = null;
process.env.PATH = saved.path;
for (const [key, value] of [["VISUAL", saved.visual], ["EDITOR", saved.editor]] as const) {
if (value === undefined) delete process.env[key];
else process.env[key] = value;
}
});
/** A workspace on this machine holding src/a.ts, as the thread's worktree. */
function workspace() {
const root = mkdtempSync(join(tmpdir(), "t3tui-links-"));
mkdirSync(join(root, "src"));
writeFileSync(join(root, "src/a.ts"), "export const a = 1;\n");
const snapshot = { ...v2ShellSnapshot, threads: v2ShellSnapshot.threads.map((thread) => ({ ...thread, worktreePath: root })) };
return { root, snapshot };
}
/** xdg-open and open, replaced by a script that writes down what it was asked to open. */
function fakeOpener() {
const bin = mkdtempSync(join(tmpdir(), "t3tui-opener-"));
const log = join(bin, "opened");
for (const name of ["xdg-open", "open"]) {
writeFileSync(join(bin, name), `#!/bin/sh\nprintf '%s\\n' "$1" >> '${log}'\n`);
chmodSync(join(bin, name), 0o755);
}
process.env.PATH = `${bin}:${process.env.PATH}`;
return () => {
try {
return readFileSync(log, "utf8").trim().split("\n");
} catch {
return [];
}
};
}
const waitFor = async (check: () => boolean) => {
for (let tries = 0; tries < 40 && !check(); tries++) await app?.settle(25);
};
describe("links and paths in replies", () => {
test("a click on a link opens it in the browser, whether written as a link or bare", async () => {
const opened = fakeOpener();
const app = await open({ session: fakeSession({ projection: withReply("See [the docs](https://example.com/docs) or https://bare.example.org/x now.", false) }) });
const label = app.find("the docs");
await app.click(label.x + 2, label.y);
const bare = app.find("bare.example");
await app.click(bare.x, bare.y);
await waitFor(() => opened().length === 2);
expect(opened()).toEqual(["https://example.com/docs", "https://bare.example.org/x"]);
});
test("a click on a workspace file's path opens it in the editor pane", async () => {
delete process.env.VISUAL;
process.env.EDITOR = "sleep 3; :";
const { snapshot } = workspace();
const app = await open({ width: 200, session: fakeSession({ snapshot, projection: withReply("I changed `src/a.ts:3` and left src/missing.ts alone.", false) }) });
const missing = app.find("missing.ts");
await app.click(missing.x, missing.y);
expect(app.frame()).not.toContain("Editing");
const path = app.find("a.ts:3");
await app.click(path.x, path.y);
expect(app.frame()).toContain("Editing ");
expect(app.frame()).toContain("src/a.ts");
});
test("a drag over a link selects it rather than opening it", async () => {
const opened = fakeOpener();
const app = await open({ session: fakeSession({ projection: withReply("Go to https://example.com/page please.", false) }) });
const link = app.find("https://example.com/page");
await app.mockMouse.drag(link.x, link.y, link.x + 10, link.y);
await app.settle(100);
expect(opened()).toEqual([]);
expect(app.calls("copy")).toHaveLength(1);
});
});
+36
View File
@@ -0,0 +1,36 @@
import { describe, expect, test } from "bun:test";
import { isWebUrl, pathAt } from "../src/model/links.ts";
const at = (text: string, word: string) => pathAt(text, text.indexOf(word));
describe("paths in text", () => {
test("a click anywhere in a path finds the whole path", () => {
const text = "I changed src/ui/App.tsx and test/app.test.tsx.";
expect(at(text, "src")).toBe("src/ui/App.tsx");
expect(at(text, "App")).toBe("src/ui/App.tsx");
expect(at(text, "app.test")).toBe("test/app.test.tsx");
});
test("line numbers and leading dots are path syntax", () => {
expect(at("see ./bin.ts:12:4 for it", "bin")).toBe("./bin.ts");
expect(at("in ../shared/x.ts, line 3", "shared")).toBe("../shared/x.ts");
expect(at("open ~/notes.md now", "notes")).toBe("~/notes.md");
expect(at("(README.md)", "README")).toBe("README.md");
});
test("words, URLs and punctuation are not paths", () => {
expect(at("the build is done", "build")).toBeNull();
expect(at("see https://example.com/a.html", "example")).toBeNull();
expect(at("see https://example.com/a.html", "https")).toBeNull();
expect(at("a, b", ",")).toBeNull();
expect(at("version 1.2", "1.2")).toBeNull();
});
test("web links open in the browser; file: links and bare targets are files", () => {
expect(isWebUrl("https://example.com")).toBe(true);
expect(isWebUrl("mailto:me@example.com")).toBe(true);
expect(isWebUrl("file:///tmp/a.ts")).toBe(false);
expect(isWebUrl("src/ui/App.tsx")).toBe(false);
});
});