Skip to content

Commit 1794048

Browse files
committed
fix: [#976] clicking a truncated URL now opens the full URL
Session output either linkified only the visible (truncated) text or let the terminal auto-detect links from truncated display text. Add `util/terminal-link.tsx`: - markdown (assistant + reasoning): attach a chunk transform that keeps the full URL as the link target while middle-ellipsizing the display text to the available width - shell + generic tool output: wrap detected URLs in explicit link elements with the full `href` from the untruncated source text Unit tests cover full-target preservation when display text is shortened or collapsed.
1 parent c4a474f commit 1794048

3 files changed

Lines changed: 307 additions & 2 deletions

File tree

‎packages/tui/src/routes/session/index.tsx‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ import { useClipboard } from "../../context/clipboard"
7676
import { nextThinkingMode, reasoningSummary, useThinkingMode, type ThinkingMode } from "../../context/thinking"
7777
import { getScrollAcceleration } from "../../util/scroll"
7878
import { collapseToolOutput } from "../../util/collapse-tool-output"
79+
// altimate_change start — preserve full URL hyperlink targets in session output
80+
import { linkTerminalChunks, TerminalLinkText, terminalLinkMarkdownRenderNode } from "../../util/terminal-link"
81+
// altimate_change end
7982
import { usePluginRuntime } from "../../plugin/runtime"
8083
import { DialogRetryAction } from "../../component/dialog-retry-action"
8184
import { getRevertDiffFiles } from "../../util/revert-diff"
@@ -1611,6 +1614,10 @@ function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: Ass
16111614
})
16121615
const summary = createMemo(() => reasoningSummary(content()))
16131616
const syntax = createSyntaxStyleMemo(() => generateSubtleSyntax(theme))
1617+
// altimate_change start — preserve full URL hyperlink targets in reasoning markdown
1618+
const maxUrlDisplayWidth = createMemo(() => Math.max(12, Math.min(80, ctx.width - 6)))
1619+
const onChunks = linkTerminalChunks(maxUrlDisplayWidth)
1620+
// altimate_change end
16141621

16151622
const toggle = () => {
16161623
if (!inMinimal()) return
@@ -1644,6 +1651,9 @@ function ReasoningPart(props: { last: boolean; part: ReasoningPart; message: Ass
16441651
syntaxStyle={syntax()}
16451652
content={summary().body}
16461653
conceal={ctx.conceal()}
1654+
// altimate_change start — preserve full URL hyperlink targets in reasoning markdown
1655+
onChunks={onChunks}
1656+
// altimate_change end
16471657
fg={theme.textMuted}
16481658
/>
16491659
</box>
@@ -1711,6 +1721,10 @@ function TextPart(props: { last: boolean; part: TextPart; message: AssistantMess
17111721
return available <= desired ? undefined : desired
17121722
})
17131723
// altimate_change end
1724+
// altimate_change start — preserve full URL hyperlink targets in assistant markdown
1725+
const maxUrlDisplayWidth = createMemo(() => Math.max(12, Math.min(80, (cappedWidth() ?? ctx.width) - 6)))
1726+
const renderNode = terminalLinkMarkdownRenderNode(maxUrlDisplayWidth)
1727+
// altimate_change end
17141728
return (
17151729
<Show when={props.part.text.trim()}>
17161730
<box
@@ -1729,6 +1743,9 @@ function TextPart(props: { last: boolean; part: TextPart; message: AssistantMess
17291743
content={props.part.text.trim()}
17301744
tableOptions={{ style: "grid" }}
17311745
conceal={ctx.conceal()}
1746+
// altimate_change start — preserve full URL hyperlink targets in assistant markdown
1747+
renderNode={renderNode}
1748+
// altimate_change end
17321749
fg={theme.markdownText}
17331750
bg={theme.background}
17341751
/>
@@ -1837,6 +1854,9 @@ function GenericTool(props: ToolProps) {
18371854
if (expanded() || !collapsed().overflow) return output()
18381855
return collapsed().output
18391856
})
1857+
// altimate_change start — preserve full URL hyperlink targets in generic tool output
1858+
const maxUrlDisplayWidth = createMemo(() => Math.max(12, Math.min(80, ctx.width - 6)))
1859+
// altimate_change end
18401860

18411861
return (
18421862
<Show
@@ -1853,7 +1873,11 @@ function GenericTool(props: ToolProps) {
18531873
onClick={collapsed().overflow ? () => setExpanded((prev) => !prev) : undefined}
18541874
>
18551875
<box gap={1}>
1856-
<text fg={theme.text}>{limited()}</text>
1876+
{/* altimate_change start — preserve full URL hyperlink targets in generic tool output */}
1877+
<text fg={theme.text}>
1878+
<TerminalLinkText text={limited()} sourceText={output()} maxUrlDisplayWidth={maxUrlDisplayWidth()} />
1879+
</text>
1880+
{/* altimate_change end */}
18571881
<Show when={collapsed().overflow}>
18581882
<text fg={theme.textMuted}>{expanded() ? "Click to collapse" : "Click to expand"}</text>
18591883
</Show>
@@ -2083,6 +2107,9 @@ function Shell(props: ToolProps) {
20832107
if (expanded() || !collapsed().overflow) return output()
20842108
return collapsed().output
20852109
})
2110+
// altimate_change start — preserve full URL hyperlink targets in shell output
2111+
const maxUrlDisplayWidth = createMemo(() => Math.max(12, Math.min(80, ctx.width - 6)))
2112+
// altimate_change end
20862113

20872114
const workdirDisplay = createMemo(() => {
20882115
const workdir = stringValue(props.input.workdir)
@@ -2110,7 +2137,11 @@ function Shell(props: ToolProps) {
21102137
<box gap={1}>
21112138
<text fg={theme.text}>$ {stringValue(props.input.command)}</text>
21122139
<Show when={output()}>
2113-
<text fg={theme.text}>{limited()}</text>
2140+
{/* altimate_change start — preserve full URL hyperlink targets in shell output */}
2141+
<text fg={theme.text}>
2142+
<TerminalLinkText text={limited()} sourceText={output()} maxUrlDisplayWidth={maxUrlDisplayWidth()} />
2143+
</text>
2144+
{/* altimate_change end */}
21142145
</Show>
21152146
<Show when={collapsed().overflow}>
21162147
<text fg={theme.textMuted}>{expanded() ? "Click to collapse" : "Click to expand"}</text>
Lines changed: 241 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,241 @@
1+
// altimate_change start — preserve full URL hyperlink targets
2+
import { For } from "solid-js"
3+
import { CodeRenderable, detectLinks, type MarkdownOptions, type Renderable, type TextChunk } from "@opentui/core"
4+
5+
const URL_PATTERN = /\bhttps?:\/\/[^\s<>"'`]+/g
6+
const DEFAULT_MAX_URL_DISPLAY_WIDTH = 64
7+
const ELLIPSIS = "…"
8+
const transformedCodeRenderables = new WeakSet<CodeRenderable>()
9+
10+
export type TerminalLinkSegment = {
11+
text: string
12+
href?: string
13+
}
14+
15+
type UrlMatch = {
16+
href: string
17+
start: number
18+
end: number
19+
}
20+
21+
export function splitTerminalLinks(
22+
displayText: string,
23+
options: { sourceText?: string; maxUrlDisplayWidth?: number } = {},
24+
): TerminalLinkSegment[] {
25+
if (!displayText) return []
26+
27+
const sourceText = options.sourceText ?? displayText
28+
const maxUrlDisplayWidth = options.maxUrlDisplayWidth ?? DEFAULT_MAX_URL_DISPLAY_WIDTH
29+
const matches = findUrlMatches(sourceText)
30+
if (matches.length === 0) return [{ text: displayText }]
31+
32+
const segments: TerminalLinkSegment[] = []
33+
let displayOffset = 0
34+
35+
for (const match of matches) {
36+
if (match.end <= displayOffset) continue
37+
if (match.start >= displayText.length) break
38+
39+
const visibleStart = Math.max(match.start, displayOffset)
40+
const visibleEnd = Math.min(match.end, displayText.length)
41+
if (visibleEnd <= visibleStart) continue
42+
43+
if (visibleStart > displayOffset) {
44+
segments.push({ text: displayText.slice(displayOffset, visibleStart) })
45+
}
46+
47+
const visibleText = displayText.slice(visibleStart, visibleEnd)
48+
const isSourceDisplay = sourceText === displayText
49+
segments.push({
50+
text: formatUrlDisplay(isSourceDisplay ? match.href : visibleText, maxUrlDisplayWidth),
51+
href: match.href,
52+
})
53+
displayOffset = visibleEnd
54+
}
55+
56+
if (displayOffset < displayText.length) {
57+
segments.push({ text: displayText.slice(displayOffset) })
58+
}
59+
60+
return mergeAdjacentPlainSegments(segments)
61+
}
62+
63+
export function TerminalLinkText(props: {
64+
text: string
65+
sourceText?: string
66+
maxUrlDisplayWidth?: number
67+
}) {
68+
return (
69+
<For each={splitTerminalLinks(props.text, { sourceText: props.sourceText, maxUrlDisplayWidth: props.maxUrlDisplayWidth })}>
70+
{(segment) => (segment.href ? <a href={segment.href}>{segment.text}</a> : segment.text)}
71+
</For>
72+
)
73+
}
74+
75+
export function attachTerminalLinkChunkTransform(
76+
renderable: Renderable | null | undefined,
77+
maxUrlDisplayWidth: () => number,
78+
) {
79+
if (!renderable) return renderable
80+
81+
if (renderable instanceof CodeRenderable && !transformedCodeRenderables.has(renderable)) {
82+
transformedCodeRenderables.add(renderable)
83+
const previous = renderable.onChunks
84+
renderable.onChunks = async (chunks, context) => {
85+
const linked = previous ? ((await previous(chunks, context)) ?? chunks) : detectLinks(chunks, context)
86+
return shortenLinkedChunks(linked, maxUrlDisplayWidth())
87+
}
88+
}
89+
90+
for (const child of renderable.getChildren()) {
91+
attachTerminalLinkChunkTransform(child, maxUrlDisplayWidth)
92+
}
93+
94+
return renderable
95+
}
96+
97+
export function terminalLinkMarkdownRenderNode(
98+
maxUrlDisplayWidth: () => number,
99+
): NonNullable<MarkdownOptions["renderNode"]> {
100+
return (_token, context) => attachTerminalLinkChunkTransform(context.defaultRender(), maxUrlDisplayWidth) ?? null
101+
}
102+
103+
export function linkTerminalChunks(maxUrlDisplayWidth: () => number) {
104+
return (chunks: TextChunk[], context: Parameters<NonNullable<CodeRenderable["onChunks"]>>[1]) => {
105+
return shortenLinkedChunks(detectLinks(chunks, context), maxUrlDisplayWidth())
106+
}
107+
}
108+
109+
export function shortenLinkedChunks(chunks: TextChunk[], maxUrlDisplayWidth = DEFAULT_MAX_URL_DISPLAY_WIDTH) {
110+
return chunks.map((chunk) => {
111+
const href = chunk.link?.url
112+
if (!href) return chunk
113+
114+
const text = formatLinkedText(chunk.text, href, maxUrlDisplayWidth)
115+
if (text === chunk.text) return chunk
116+
return { ...chunk, text }
117+
})
118+
}
119+
120+
export function formatUrlDisplay(url: string, maxWidth = DEFAULT_MAX_URL_DISPLAY_WIDTH) {
121+
if (maxWidth <= 0 || Bun.stringWidth(url) <= maxWidth) return url
122+
if (maxWidth <= Bun.stringWidth(ELLIPSIS)) return ELLIPSIS
123+
124+
const budget = maxWidth - Bun.stringWidth(ELLIPSIS)
125+
const startWidth = Math.max(1, Math.ceil(budget * 0.58))
126+
const endWidth = Math.max(1, budget - startWidth)
127+
128+
return takeColumns(url, startWidth) + ELLIPSIS + takeColumnsEnd(url, endWidth)
129+
}
130+
131+
function formatLinkedText(text: string, href: string, maxUrlDisplayWidth: number) {
132+
if (text === href || looksLikeUrl(text)) return formatUrlDisplay(text, maxUrlDisplayWidth)
133+
134+
const index = text.indexOf(href)
135+
if (index === -1) return text
136+
137+
return text.slice(0, index) + formatUrlDisplay(href, maxUrlDisplayWidth) + text.slice(index + href.length)
138+
}
139+
140+
function findUrlMatches(text: string): UrlMatch[] {
141+
const matches: UrlMatch[] = []
142+
URL_PATTERN.lastIndex = 0
143+
144+
let match: RegExpExecArray | null
145+
while ((match = URL_PATTERN.exec(text))) {
146+
const raw = match[0]
147+
const suffix = trailingUrlPunctuation(raw)
148+
const href = raw.slice(0, raw.length - suffix.length)
149+
if (!href) continue
150+
151+
matches.push({
152+
href,
153+
start: match.index,
154+
end: match.index + href.length,
155+
})
156+
}
157+
158+
return matches
159+
}
160+
161+
function trailingUrlPunctuation(value: string) {
162+
let suffix = ""
163+
let rest = value
164+
165+
while (/[.,!?;:]$/.test(rest)) {
166+
suffix = rest.at(-1)! + suffix
167+
rest = rest.slice(0, -1)
168+
}
169+
170+
while (rest.endsWith(")") && count(rest, "(") < count(rest, ")")) {
171+
suffix = ")" + suffix
172+
rest = rest.slice(0, -1)
173+
}
174+
175+
while (rest.endsWith("]") && count(rest, "[") < count(rest, "]")) {
176+
suffix = "]" + suffix
177+
rest = rest.slice(0, -1)
178+
}
179+
180+
return suffix
181+
}
182+
183+
function looksLikeUrl(text: string) {
184+
URL_PATTERN.lastIndex = 0
185+
const match = URL_PATTERN.exec(text)
186+
return match?.index === 0
187+
}
188+
189+
function takeColumns(value: string, maxWidth: number) {
190+
let width = 0
191+
let output = ""
192+
193+
for (const char of value) {
194+
const next = width + Bun.stringWidth(char)
195+
if (next > maxWidth) break
196+
width = next
197+
output += char
198+
}
199+
200+
return output
201+
}
202+
203+
function takeColumnsEnd(value: string, maxWidth: number) {
204+
let width = 0
205+
let output = ""
206+
const chars = Array.from(value)
207+
208+
for (let index = chars.length - 1; index >= 0; index--) {
209+
const char = chars[index]!
210+
const next = width + Bun.stringWidth(char)
211+
if (next > maxWidth) break
212+
width = next
213+
output = char + output
214+
}
215+
216+
return output
217+
}
218+
219+
function count(value: string, needle: string) {
220+
let total = 0
221+
for (const char of value) {
222+
if (char === needle) total++
223+
}
224+
return total
225+
}
226+
227+
function mergeAdjacentPlainSegments(segments: TerminalLinkSegment[]) {
228+
const merged: TerminalLinkSegment[] = []
229+
230+
for (const segment of segments) {
231+
const previous = merged.at(-1)
232+
if (previous && !previous.href && !segment.href) {
233+
previous.text += segment.text
234+
continue
235+
}
236+
merged.push(segment)
237+
}
238+
239+
return merged
240+
}
241+
// altimate_change end
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { describe, expect, test } from "bun:test"
2+
import type { TextChunk } from "@opentui/core"
3+
import { formatUrlDisplay, shortenLinkedChunks, splitTerminalLinks } from "../../src/util/terminal-link"
4+
5+
describe("terminal links", () => {
6+
test("shortens the displayed URL without changing the target", () => {
7+
const url = "https://example.com/really/long/path/with/query?alpha=one&beta=two&gamma=three"
8+
const [segment] = splitTerminalLinks(url, { maxUrlDisplayWidth: 32 })
9+
10+
expect(segment?.href).toBe(url)
11+
expect(segment?.text).toBe(formatUrlDisplay(url, 32))
12+
expect(segment?.text).toContain("…")
13+
})
14+
15+
test("uses the full source URL when display text was already collapsed", () => {
16+
const url = "https://example.com/really/long/path/with/query?alpha=one&beta=two&gamma=three"
17+
const display = url.slice(0, 30) + "…"
18+
const [segment] = splitTerminalLinks(display, { sourceText: url })
19+
20+
expect(segment?.href).toBe(url)
21+
expect(segment?.text).toBe(display)
22+
})
23+
24+
test("preserves full link targets on shortened text chunks", () => {
25+
const url = "https://example.com/really/long/path/with/query?alpha=one&beta=two&gamma=three"
26+
const chunks: TextChunk[] = [{ __isChunk: true, text: url, link: { url } }]
27+
const [chunk] = shortenLinkedChunks(chunks, 28)
28+
29+
expect(chunk?.link?.url).toBe(url)
30+
expect(chunk?.text).toBe(formatUrlDisplay(url, 28))
31+
expect(chunk?.text).toContain("…")
32+
})
33+
})

0 commit comments

Comments
 (0)