Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(terminal): https URLs in agent output are not clickable

ketan0095218b4ddf2c87
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index 669b175e..9d03113c 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -22,7 +22,7 @@ import { arabicJoinRanges } from '@/terminal/arabicJoiner';
import { attachArabicSpacingFix } from '@/terminal/arabicSpacingFix';
import { isArabicTerminalEnabled } from '@/terminal/arabicSetting';
import {
- classifyPathToken, isPathToken, pathTokenMatcher, stripPathToken, type PathAction
+ classifyPathToken, isPathToken, stripPathToken, terminalLinkSpans, type PathAction
} from '@shared/terminalPaths';
import {
createTerminalRecoveryState,
@@ -970,21 +970,40 @@ function registerMarkdownLinkProvider(term: Terminal, ptyId: string): void {
provideLinks(bufferLineNumber, callback) {
const line = term.buffer.active.getLine(bufferLineNumber - 1);
const text = line ? line.translateToString(true) : '';
- if (!text || !text.includes('.')) { callback(undefined); return; }
+ // A URL host need not carry a dot (`https://localhost:3000/x`), so the
+ // cheap bail-out has to let `://` through as well.
+ if (!text || (!text.includes('.') && !text.includes('://'))) { callback(undefined); return; }
const links: Parameters<typeof callback>[0] = [];
- const re = pathTokenMatcher();
- let m: RegExpExecArray | null;
- while ((m = re.exec(text)) !== null) {
- const raw = m[0];
- const abs = resolvePathCandidate(ptyId, raw);
+
+ // Ordering (URLs win overlaps with path tokens) lives in
+ // @shared/terminalPaths so it can be unit-tested; this only turns a
+ // span into an xterm link and decides what a click does.
+ for (const span of terminalLinkSpans(text)) {
+ const range = {
+ start: { x: span.start + 1, y: bufferLineNumber },
+ end: { x: span.start + span.raw.length, y: bufferLineNumber }
+ };
+ if (span.kind === 'url') {
+ const url = span.token;
+ links!.push({
+ range, text: url,
+ decorations: { underline: true, pointerCursor: true },
+ activate: (event: MouseEvent | undefined) => {
+ // ⌘/Ctrl+click only, like the path links: a plain click must
+ // keep going to the TUI.
+ if (event && !(event.metaKey || event.ctrlKey)) return;
+ // The URL is agent output. It reaches nothing but the opener,
+ // which is https-only and re-checks in the main process.
+ void window.cth.openExternal?.(url).catch(() => { /* opener refused */ });
+ }
+ });
+ continue;
+ }
+ const abs = resolvePathCandidate(ptyId, span.raw);
if (!abs) continue;
- const action = classifyPathToken(stripPathToken(raw));
+ const action = classifyPathToken(span.token);
links!.push({
- range: {
- start: { x: m.index + 1, y: bufferLineNumber },
- end: { x: m.index + raw.length, y: bufferLineNumber }
- },
- text: raw,
+ range, text: span.raw,
decorations: { underline: true, pointerCursor: true },
activate: (event: MouseEvent | undefined) => {
// ⌘/Ctrl+click only — a plain click must keep going to the TUI.
diff --git a/src/shared/terminalPaths.ts b/src/shared/terminalPaths.ts
index 0358d568..e60a2de2 100644
--- a/src/shared/terminalPaths.ts
+++ b/src/shared/terminalPaths.ts
@@ -94,6 +94,106 @@ export function pathTokenMatcher(): RegExp {
return new RegExp(PATH_TOKEN_RE.source, 'g');
}
+/**
+ * URL tokens in terminal output.
+ *
+ * `https` only, deliberately. The main-process opener (`app:openExternal`)
+ * accepts nothing else, so underlining an `http://` would hand back a link that
+ * cannot open — which is the complaint in #281, not a fix for it.
+ *
+ * A matched URL is offered as-is. Punycode homographs and embedded credentials
+ * (`https://user:[email protected]@good.com/x`) therefore reach the opener intact —
+ * the same as every terminal linkifier, with the browser as the mitigation.
+ * Filtering here would only give a false sense that the string was vetted.
+ *
+ * These must be matched BEFORE path tokens, and their spans skipped there. The
+ * path matcher's Windows-drive branch reads the `s:/` inside `https://` as
+ * drive `s:`, so a URL currently matches as an absolute path on a drive nobody
+ * has, resolves to nothing, and silently does nothing on click.
+ */
+const URL_TOKEN_RE = /https:\/\/[^\s<>"'`{}|\\^]+/gi;
+
+/** A fresh matcher. The regex is stateful (`g`), so callers must never share one. */
+export function urlTokenMatcher(): RegExp {
+ return new RegExp(URL_TOKEN_RE.source, 'gi');
+}
+
+const URL_TRAILING_PROSE = /["'`>,.;:!?]+$/;
+
+/**
+ * Strip the prose a URL picked up from a sentence: `(see https://x.com/a).`
+ *
+ * A closing bracket is only prose when the URL does not open it — Wikipedia and
+ * MSDN links carry balanced ones (`/wiki/Foo_(bar)`), and eating that character
+ * lands the user on a 404 with nothing to show why.
+ *
+ * The scheme is lowercased because the main-process opener matches `^https://`
+ * case-sensitively; a terminal that printed `HTTPS://` would otherwise be
+ * refused after we had already underlined it.
+ */
+export function stripUrlToken(raw: string): string {
+ let out = raw.replace(URL_TRAILING_PROSE, '');
+ const unbalanced = (open: string, close: string): boolean =>
+ (out.split(open).length - 1) < (out.split(close).length - 1);
+ let trimmed = true;
+ while (trimmed) {
+ trimmed = false;
+ if (out.endsWith(')') && unbalanced('(', ')')) { out = out.slice(0, -1); trimmed = true; }
+ if (out.endsWith(']') && unbalanced('[', ']')) { out = out.slice(0, -1); trimmed = true; }
+ const next = out.replace(URL_TRAILING_PROSE, '');
+ if (next !== out) { out = next; trimmed = true; }
+ }
+ return out.replace(/^https:\/\//i, 'https://');
+}
+
+/** One underlinable token on a line, with its 0-based half-open span. */
+export interface TerminalLinkSpan {
+ kind: 'url' | 'path';
+ /** The cleaned token: the URL, or the path with wrapping and `:line` stripped. */
+ token: string;
+ /** Raw matched text, so a caller can size the underline. */
+ raw: string;
+ start: number;
+ end: number;
+}
+
+/**
+ * Every token on one line of terminal output that is worth underlining.
+ *
+ * URLs are resolved FIRST and win any overlap, because the path matcher's
+ * Windows-drive branch reads the `s:/` inside `https://` as drive `s:` — so
+ * without this ordering a URL is offered as an absolute path on a drive nobody
+ * has, resolves to nothing, and the click silently does nothing (issue #281).
+ *
+ * Path tokens are returned unfiltered by `isPathToken`; the caller still decides
+ * whether a path is worth offering, since only it can resolve a relative one.
+ */
+export function terminalLinkSpans(text: string): TerminalLinkSpan[] {
+ const out: TerminalLinkSpan[] = [];
+
+ const ure = urlTokenMatcher();
+ let um: RegExpExecArray | null;
+ while ((um = ure.exec(text)) !== null) {
+ const token = stripUrlToken(um[0]);
+ // `https://)` strips down to the bare scheme; underlining that would open
+ // the browser on nothing.
+ if (!/^https:\/\/./.test(token)) continue;
+ out.push({ kind: 'url', token, raw: token, start: um.index, end: um.index + token.length });
+ }
+
+ const pre = pathTokenMatcher();
+ let pm: RegExpExecArray | null;
+ while ((pm = pre.exec(text)) !== null) {
+ const raw = pm[0];
+ const start = pm.index;
+ const end = start + raw.length;
+ if (out.some((u) => start < u.end && end > u.start)) continue;
+ out.push({ kind: 'path', token: stripPathToken(raw), raw, start, end });
+ }
+
+ return out.sort((a, b) => a.start - b.start);
+}
+
/** Strip shell/prose wrapping and any trailing `:line` from a raw match. */
export function stripPathToken(raw: string): string {
return raw
diff --git a/test/terminal-link-activation.test.cjs b/test/terminal-link-activation.test.cjs
new file mode 100644
index 00000000..6cc1c279
--- /dev/null
+++ b/test/terminal-link-activation.test.cjs
@@ -0,0 +1,63 @@
+'use strict';
+
+/**
+ * A terminal link must never act on a plain click.
+ *
+ * The provider underlines tokens found in agent output, so the text is hostile
+ * by assumption. Both verdicts are therefore gated on ⌘/Ctrl: a path goes to a
+ * metadata-only stat, and a URL goes to the https-only main-process opener.
+ * Losing either gate turns printed agent output into a one-click browser
+ * navigation or file open, which is why this is pinned rather than left to
+ * review.
+ *
+ * `terminalPool.ts` imports xterm and React, so it cannot be require()d here.
+ * This reads it as source, the same approach test/arabic-terminal.test.cjs uses
+ * for this exact file.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+
+const root = path.join(__dirname, '..');
+const src = fs.readFileSync(path.join(root, 'src/renderer/src/components/terminalPool.ts'), 'utf8');
+
+/** The body of the link provider, where every activate() lives. */
+function providerBody() {
+ const i = src.indexOf('function registerMarkdownLinkProvider');
+ assert.ok(i > 0, 'the link provider has been renamed — this test needs updating');
+ const rest = src.slice(i);
+ return rest.slice(0, rest.indexOf('\n}\n'));
+}
+
+test('every activate() in the provider is gated on a Cmd/Ctrl modifier', () => {
+ const body = providerBody();
+ const activates = body.split('activate:').length - 1;
+ assert.ok(activates >= 2, `expected a path and a URL activate, found ${activates}`);
+ const gates = body.split('metaKey').length - 1;
+ assert.equal(gates, activates,
+ `${activates} activate() handlers but ${gates} modifier gates — one path acts on a plain click`);
+});
+
+test('the URL branch opens only through the guarded opener, and only once', () => {
+ // A second openExternal call site would be a way around the gate above.
+ assert.equal(src.split('openExternal').length - 1, 1,
+ 'openExternal appears more than once in terminalPool.ts');
+ const body = providerBody();
+ const call = body.indexOf('openExternal');
+ const gate = body.lastIndexOf('metaKey', call);
+ assert.ok(gate > 0 && call - gate < 400,
+ 'the openExternal call is not behind a modifier gate');
+});
+
+test('the URL branch never reaches the filesystem verdicts', () => {
+ // A URL is not a path: it must not reach statAbs, revealPath or the IDE.
+ const body = providerBody();
+ const url = body.indexOf("span.kind === 'url'");
+ assert.ok(url > 0, "the url branch has moved — this test needs updating");
+ const branch = body.slice(url, body.indexOf('continue;', url));
+ for (const forbidden of ['statAbs', 'revealPath', 'openFileInIde', 'activatePath']) {
+ assert.ok(!branch.includes(forbidden), `the url branch reaches ${forbidden}`);
+ }
+});
diff --git a/test/terminal-paths.test.cjs b/test/terminal-paths.test.cjs
index 54d6774d..996ac235 100644
--- a/test/terminal-paths.test.cjs
+++ b/test/terminal-paths.test.cjs
@@ -11,7 +11,8 @@ const assert = require('node:assert/strict');
const loadTs = require('./load-ts.cjs');
const {
- classifyPathToken, isPathToken, pathTokenMatcher, stripPathToken
+ classifyPathToken, isPathToken, pathTokenMatcher, stripPathToken,
+ stripUrlToken, urlTokenMatcher, terminalLinkSpans
} = loadTs('src/shared/terminalPaths.ts');
/** Every token the provider would underline on one line of output. */
@@ -113,3 +114,98 @@ test('case does not decide the verdict', () => {
assert.equal(classifyPathToken('README.MD'), 'preview');
assert.equal(classifyPathToken('src/App.TSX'), 'edit');
});
+
+/* ---------------------------------------------------------------- *
+ * URLs (issue #281)
+ * ---------------------------------------------------------------- */
+
+/** Every URL the provider would underline on one line of output. */
+function urlsIn(line) {
+ const re = urlTokenMatcher();
+ const out = [];
+ let m;
+ while ((m = re.exec(line)) !== null) {
+ const u = stripUrlToken(m[0]);
+ if (u) out.push(u);
+ }
+ return out;
+}
+
+test('a bare https URL in agent output is matched', () => {
+ assert.deepEqual(urlsIn('docs at https://example.com/guide'), ['https://example.com/guide']);
+});
+
+test('prose punctuation after a URL is not part of it', () => {
+ assert.deepEqual(urlsIn('(see https://a.io/b).'), ['https://a.io/b']);
+ assert.deepEqual(urlsIn('read https://a.io/b, then stop'), ['https://a.io/b']);
+});
+
+test('http is deliberately not matched — the opener would refuse it', () => {
+ // app:openExternal accepts https (plus the two settings schemes) and nothing
+ // else, so underlining http:// would promise a click that cannot work.
+ assert.deepEqual(urlsIn('http://insecure.example/x'), []);
+});
+
+test('a plain path is not a URL, and a URL is not a path token', () => {
+ assert.deepEqual(urlsIn('fails at src/main/updater.ts:165'), []);
+ // The bug: the path matcher's Windows-drive branch reads the `s:/` inside
+ // `https://` as drive `s:`, so the URL matches as an absolute path. That is
+ // why the provider must scan URLs first and skip their spans — otherwise the
+ // URL underlines as a path, resolves nowhere, and the click does nothing.
+ assert.deepEqual(tokensIn('https://x.com/docs/guide.html'), ['s://x.com/docs/guide.html']);
+});
+
+test('a dotless host still matches, so localhost URLs are clickable', () => {
+ assert.deepEqual(urlsIn('serving https://localhost:3000/app'), ['https://localhost:3000/app']);
+});
+
+/* ---------------------------------------------------------------- *
+ * span composition — URLs must win overlaps with path tokens
+ * ---------------------------------------------------------------- */
+
+const kinds = (line) => terminalLinkSpans(line).map((s) => `${s.kind}:${s.token}`);
+
+test('a URL yields exactly one span, and it is a url — not a path', () => {
+ // Without the URL-first ordering the path matcher claims this same text as
+ // drive `s:`, which is the whole defect: one underline that goes nowhere.
+ assert.deepEqual(kinds('https://x.com/docs/guide.html'), ['url:https://x.com/docs/guide.html']);
+});
+
+test('a path and a URL on one line both survive, in reading order', () => {
+ assert.deepEqual(
+ kinds('edit src/app.ts:12 then read https://x.com/g.html'),
+ ['path:src/app.ts', 'url:https://x.com/g.html']
+ );
+});
+
+test('spans never overlap each other', () => {
+ const spans = terminalLinkSpans('see https://a.io/b.html and src/x.ts:1 now');
+ for (let i = 1; i < spans.length; i++) {
+ assert.ok(spans[i].start >= spans[i - 1].end, 'spans must be disjoint and ordered');
+ }
+});
+
+test('a line with neither yields nothing', () => {
+ assert.deepEqual(terminalLinkSpans('just some prose, nothing to click'), []);
+});
+
+test('an uppercase scheme is still a URL, and reaches the opener lowercased', () => {
+ // HTTPS:// used to fall through to the path matcher as drive `S:` — the exact
+ // #281 symptom. The scheme is lowercased because the main-process opener
+ // matches `^https://` case-sensitively; the rest of the URL is left alone.
+ assert.deepEqual(kinds('HTTPS://UPPER.COM/x'), ['url:https://UPPER.COM/x']);
+ assert.deepEqual(kinds('Https://Mixed.com/a'), ['url:https://Mixed.com/a']);
+});
+
+test('a balanced bracket belongs to the URL, an unbalanced one is prose', () => {
+ assert.deepEqual(urlsIn('https://en.wikipedia.org/wiki/Foo_(bar)'),
+ ['https://en.wikipedia.org/wiki/Foo_(bar)']);
+ assert.deepEqual(urlsIn('(see https://a.io/b)'), ['https://a.io/b']);
+ assert.deepEqual(urlsIn('(see https://en.wikipedia.org/wiki/Foo_(bar)).'),
+ ['https://en.wikipedia.org/wiki/Foo_(bar)']);
+});
+
+test('a bare scheme with nothing after it is not a link', () => {
+ assert.deepEqual(kinds('see https://)'), []);
+ assert.deepEqual(kinds('https://'), []);
+});