Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Links: rows under a picture for its links, file paths and commands

razorback162da4b1bbf7bc
diff --git a/README.md b/README.md
index 2fa4531..427151d 100644
--- a/README.md
+++ b/README.md
@@ -44,6 +44,7 @@ In other terminals, the mod shows the normal text. Refer to [Install](docs/insta
- **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline.
- **Images and files.** Images in an answer, images that Claude sends, Markdown files that Claude sends, and images that you paste show in the transcript.
- **Copy text from pictures.** Select and copy text with the mouse, as you do with normal text.
+- **Links you can click.** The links, file paths and commands of an answer show in rows under its picture. A cmd+click on a link opens it. A click on a command copies it.
- **Plans you can read.** In plan mode, the plan shows rendered, with an approve, edit or reject question under it.
- **Themes that follow light and dark.** Claude Code's own colours by default, or VS Code's Markdown preview. You can make your own.
diff --git a/docs/development.md b/docs/development.md
index a4898ea..cf51f0b 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -21,7 +21,7 @@ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines
## Module layout
-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.
+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.
The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index fd39480..df324a6 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -10,8 +10,9 @@
4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.
5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.
6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/`. Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.
-7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.
-8. Copy: one long-lived `perl` process watches the terminal size (at each SIGWINCH) and, on macOS, the clipboard. For the clipboard, it uses `/usr/bin/perl` with Apple's PerlObjCBridge and reads the change counter of the clipboard (`NSPasteboard changeCount`) every 0.3 s. This read is in the process and starts no other process (approximately 0.05% of one CPU core). The clipboard part starts only while the mod is on and after the mod drew its first picture in this session; then the mod starts the process again with the clipboard part (and again without it after `/iui off`). When the counter changes, the mod reads the clipboard one time (`pbpaste`). The first counter after a start is not a change, so an old clipboard is not copied. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) for the selected pages only. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells. Immediately before it writes the text with `$.ui.copy`, it reads the clipboard again. If the clipboard has a newer copy, the mod does not write over it, and it reads that copy next. If the process stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the process continues without the clipboard part. At other session ends (for example `/exit`), the mod stops the process and does not start a new one. A `ui.copy` hook also changes a copy with picture cells to the text.
+7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select.
+8. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.
+9. Copy: one long-lived `perl` process watches the terminal size (at each SIGWINCH) and, on macOS, the clipboard. For the clipboard, it uses `/usr/bin/perl` with Apple's PerlObjCBridge and reads the change counter of the clipboard (`NSPasteboard changeCount`) every 0.3 s. This read is in the process and starts no other process (approximately 0.05% of one CPU core). The clipboard part starts only while the mod is on and after the mod drew its first picture in this session; then the mod starts the process again with the clipboard part (and again without it after `/iui off`). When the counter changes, the mod reads the clipboard one time (`pbpaste`). The first counter after a start is not a change, so an old clipboard is not copied. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) for the selected pages only. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells. Immediately before it writes the text with `$.ui.copy`, it reads the clipboard again. If the clipboard has a newer copy, the mod does not write over it, and it reads that copy next. If the process stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the process continues without the clipboard part. At other session ends (for example `/exit`), the mod stops the process and does not start a new one. A `ui.copy` hook also changes a copy with picture cells to the text.
## How `auto` is resolved
diff --git a/docs/limitations.md b/docs/limitations.md
index 28ad25d..fa7aeae 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -11,6 +11,7 @@
- The mod knows only the last 64 answers, plans or files that it drew in this session.
- With two Claude Code sessions on one computer, a session that has no selection can change a copy from the other session, with the text of its own picture.
- To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either, because it acts only when the clipboard changes. It changes only a clipboard that has picture cells (for example, after a copy with a key).
+- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.
- **Search does not find text in a picture.**
- **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.
- **Short summaries** between tool calls stay as text.
diff --git a/docs/usage.md b/docs/usage.md
index 078b50b..0923aa0 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -51,6 +51,23 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr
| `/iui dump` | Shows the last clipboard text with picture cells and how the mod read it (for a bug report). It also writes this to `copy-debug.json` in the cache folder. |
| `/iui probe` | Asks the terminal for its background colour with OSC 11 and shows the raw answers. Refer to [How `auto` is resolved](how-it-works.md#how-auto-is-resolved). |
+## Links, file paths and commands
+
+A picture has no text for the terminal, so a click on a link in the picture does not open it. Thus the mod shows the links, file paths and commands of an answer, a plan or a Markdown file that Claude sent in dim rows under its picture. These rows show only when the text has links, file paths or commands. Each item uses one row:
+
+```
+↗ Typst docs https://typst.app/docs
+↗ https://github.com/o/r/pull/42
+↗ hooks/lib/copy.ts:42
+$ brew install typst
+```
+
+- **A web link** (`http:`, `https:` or `mailto:`): the link text, then the URL. If the link text is the URL, the URL shows one time. A cmd+click on the link (or the click that your terminal uses for links) opens it.
+- **A file path**, for example `hooks/lib/copy.ts:42`: a cmd+click opens the file. A relative path starts from the session's folder (for a Markdown file that Claude sent, from the folder of that file). A row shows only when the file exists.
+- **A command** from a `bash`, `sh`, `zsh`, `shell`, `console` or `shell-session` code block, or from inline code that starts with `! `: a click on the row copies the full command, and a toast shows "Copied". A command with more lines shows its first line and the number of the other lines. The click works only where Claude Code gets mouse clicks (fullscreen mode).
+
+The mod does not take web links from code blocks, inline code or math. It takes file paths from the text and from inline code, but not from code blocks.
+
## Copy text from a picture
Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, while the mod is on and has drawn a picture in this session, the mod sees each change of the clipboard (in 0.3 s or less). When the clipboard has picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. Wait for this toast, then paste. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. The mod does not change a clipboard that has no picture cells.
diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsx
index d821256..969845e 100644
--- a/hooks/lib/draw.tsx
+++ b/hooks/lib/draw.tsx
@@ -1,14 +1,16 @@
// The pictures of an answer: the key of its inputs, the page width and ppi
// that match the terminal's text, where its first line sits, and the
-// drawing of its pages beside the reply bullet.
-import type { EngineInterface, RenderComponent, RenderViewport, ResolveInput } from 'claude-code'
+// drawing of its pages beside the reply bullet, with the rows of its links
+// under them.
+import type { EngineInterface, RenderComponent, RenderSurface, RenderViewport, ResolveInput } from 'claude-code'
import type { IuiTheme } from '../../types'
-import { BODY_PT, bulletOf, GUTTER, MARGIN_TOP, TEMPLATE_VERSION } from './settings'
-import { INLINE_KEPT, inlined, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'
-import { FENCE } from './markdown'
+import { BODY_PT, bulletOf, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, TEMPLATE_VERSION } from './settings'
+import { INLINE_KEPT, inlined, keep, linkFiles, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'
+import { FENCE, imagePathOf } from './markdown'
+import { linksOf, type LinkItem } from './links'
import { fitBox, fitsInline, roomColumns } from './terminal'
-import { fsRead, uiResolve } from './api'
+import { fsExists, fsRead, uiCopy, uiResolve, uiToast } from './api'
// FNV-1a over the parts, twice with different offsets: 16 hex digits.
export function hashOf(parts: readonly (string | number)[]): string {
@@ -144,8 +146,9 @@ export async function inlineOf($: EngineInterface, result: Result): Promise<stri
// How a set of pages sits: `bullet` the reply bullet in the gutter (on the
// first line's row), `gutter` its width (0: none), `marginTop` the rows above,
-// `keys` a prefix for its Images' keys (several sets in one tree).
-export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number; keys?: string }
+// `keys` a prefix for its Images' and Buttons' keys (several sets in one
+// tree), `links` the link rows under the pages (one row each).
+export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number; keys?: string; links?: readonly ShownLink[] }
// The bullet's row when the page is drawn `factor` as wide.
export function scaledBulletRow(bulletRow: number, factor: number): number {
@@ -187,7 +190,83 @@ export function drawPages(
)
})}
{result.note ? <Text dimColor wrap="truncate-end">Typst error: {result.note}</Text> : null}
+ {layout.links?.length ? drawLinks($, e, layout.links, layout.keys ?? '') : null}
</Box>
</Box>
)
}
+
+// ---- Links ------------------------------------------------------------------
+// A click on a picture cannot open a link (an Image is a leaf: no Link holds
+// it, and a press on it gives no cell). So the links, file paths and commands
+// of a text are drawn under its pages, one row each.
+
+// A link row: a web link, a file found (`path` its absolute path, `href` its
+// file:// URL), or a command.
+export type ShownLink = Exclude<LinkItem, { kind: 'file' }> | { kind: 'file'; label: string; path: string; href: string }
+
+// The file:// URL of an absolute path, percent-encoded (`#` and `?` too).
+export const fileHref = (path: string) => `file://${encodeURI(path).replace(/[?#]/g, encodeURIComponent)}`
+
+// The items as link rows: each file path made absolute from `base` (the
+// folder relative paths start from; `~/` is the home folder) and kept only
+// when it is a file now (each path checked once: linkFiles).
+export async function resolveLinks($: EngineInterface, items: readonly LinkItem[], base: string, home = S.env?.home ?? ''): Promise<ShownLink[]> {
+ const shown: ShownLink[] = []
+ for (const item of items) {
+ if (item.kind !== 'file') {
+ shown.push(item)
+ continue
+ }
+ const path = home && item.path.startsWith('~/') ? `${home.replace(/\/+$/, '')}${item.path.slice(1)}` : imagePathOf(item.path, base)
+ let isFile = linkFiles.get(path)
+ if (isFile === undefined) {
+ isFile = await fsExists($, path).catch(() => false)
+ keep(linkFiles, path, isFile, LINK_FILES_KEPT)
+ }
+ if (isFile) shown.push({ kind: 'file', label: item.label, path, href: fileHref(path) })
+ }
+ return shown
+}
+
+// The link rows of a Markdown text (`base` as resolveLinks); none when it
+// cannot be read for them.
+export async function linksFor($: EngineInterface, text: string, base: string): Promise<ShownLink[]> {
+ try {
+ return await resolveLinks($, linksOf(text), base)
+ } catch {
+ return []
+ }
+}
+
+// Copies a command at a press of its row, with a toast.
+async function copyCommand($: EngineInterface, text: string, surface: RenderSurface) {
+ const copied = await uiCopy($, { text, surface }).catch(() => null)
+ uiToast($, copied?.isCopied ? 'Copied' : `Could not copy${copied ? `: ${copied.reason}` : ''}`)
+}
+
+// One row per link, all dim and cut at the row's end (the copy counts them
+// as one row each): a web link (its URL after it when the label is not the
+// URL), a file, or a command as a Button that copies it.
+export function drawLinks($: EngineInterface, e: ResolveInput<RenderComponent, 'terminal'>, links: readonly ShownLink[], keys: string) {
+ const { Box, Text, Link, Button } = uiResolve($, e)
+ return links.map(link => {
+ if (link.kind === 'command') {
+ const { text } = link
+ return (
+ <Box height={1} overflow="hidden">
+ <Button key={`${keys}link-${hashOf([text]).slice(0, 8)}`} plain dimColor onPress={press => void copyCommand($, text, press.surface)}>
+ <Text wrap="truncate-end">$ {link.label}</Text>
+ </Button>
+ </Box>
+ )
+ }
+ const href = link.href
+ return (
+ <Text dimColor wrap="truncate-end">
+ ↗ <Link href={href}>{link.label}</Link>
+ {link.kind === 'web' && link.label !== href ? ` ${href}` : null}
+ </Text>
+ )
+ })
+}
diff --git a/hooks/lib/links.ts b/hooks/lib/links.ts
new file mode 100644
index 0000000..99a8235
--- /dev/null
+++ b/hooks/lib/links.ts
@@ -0,0 +1,221 @@
+// The links, file paths and commands of an answer (pure), for the rows under
+// its picture: a picture has no URL text, so the terminal can not click it.
+import { blocksOf, FENCE } from './markdown'
+
+export type LinkItem =
+ | { kind: 'web'; label: string; href: string }
+ | { kind: 'file'; label: string; path: string }
+ | { kind: 'command'; label: string; text: string }
+
+// The fence infos of shell commands; in a session block, only the prompt
+// lines are commands (the other lines are output).
+const SHELL = /^(bash|sh|zsh|shell|console|shell-session)$/i
+const SESSION = /^(console|shell-session)$/i
+const PROMPT = /^[$%] /
+
+const DEF = /^ {0,3}\[(?!\^)([^\]]+)\]:\s*<?([^\s>]+)>?(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*$/
+const CODE = /(?<!`)(`+)(?!`)([\s\S]*?[^`])\1(?!`)/g
+const BLOCK_MATH = /\$\$[\s\S]*?\$\$/g
+const INLINE_MATH = /(?<![\\$])\$(?![\s$])(?:\\.|[^$\\\n])+?(?<!\s)\$(?!\d)/g
+const INLINE = /\[((?:[^[\]]|\[[^[\]]*\])*)\]\(\s*(?:<([^>\n]*)>|((?:[^\s()]|\([^\s()]*\))*))(?:\s+(?:"[^"\n]*"|'[^'\n]*'|\([^)\n]*\)))?\s*\)/g
+const REF = /\[((?:[^[\]]|\[[^[\]]*\])*)\](?:\[([^[\]]*)\])?/g
+const AUTO = /<((?:https?|mailto):[^\s<>]+|[^\s<>@]+@[^\s<>@]+\.[a-z]{2,})>/gi
+const BARE = /\bhttps?:\/\/[^\s<>"`]+/gi
+
+// File paths. A path is segments of `[\w.@+-]` joined by `/` (it may start
+// with `/`, `./`, `../` or `~/`) whose last segment has an extension, with
+// an optional `:line` or `:line:col`. It counts when it has a `/` (and its
+// first segment is not a host name such as `example.com`), or when its
+// extension is in EXTS (lower case). So `e.g.`, `1.2.3`, `v0.15` and
+// `typst.app` are not paths. In bare text, a word such as `Node.js` is a
+// name, not a path.
+const PATH = String.raw`((?:~\/|\.{1,2}\/|\/)?(?:\.?[\w@+-][\w.@+-]*\/)*\.?[\w@+-][\w.@+-]*\.([A-Za-z][A-Za-z0-9]*))(?::(\d+)(?::(\d+))?)?`
+const FILE = new RegExp(`^${PATH}$`)
+const BARE_FILE = new RegExp(`(?<![\\w./~@+:-])${PATH}(?![\\w/])`, 'g')
+const HOST = /^[\w-]+(?:\.[\w-]+)+$/
+const EXTS = new Set(
+ ('ts tsx js jsx mjs cjs json jsonc md mdx markdown txt rst adoc py pyi rb go rs java kt kts swift c h cc cpp cxx hpp hh cs fs php ' +
+ 'sh bash zsh fish ps1 lua pl scala clj ex exs erl hs ml sql html htm css scss sass less vue svelte astro yml yaml toml ini cfg conf ' +
+ 'xml csv tsv lock log typ tex bib png jpg jpeg gif svg webp pdf ipynb gradle proto graphql dart zig nim tf hcl patch diff').split(' '),
+)
+
+// A path and its label (the path with its `:line:col`), or null.
+function fileOf(token: string, bare = false): { path: string; label: string } | null {
+ const m = FILE.exec(token)
+ if (!m || token.includes('://')) return null
+ const path = m[1]!
+ if (!path.includes('/')) {
+ if (!EXTS.has(m[2]!) || (bare && /^[A-Z][a-z]+\.js$/.test(path))) return null
+ } else if (!/^[./~]/.test(path) && HOST.test(path.split('/')[0]!)) return null
+ return { path, label: token }
+}
+
+const isWeb = (url: string) => /^(https?:\/\/|mailto:)\S/i.test(url)
+const refKey = (label: string) => label.trim().replace(/\s+/g, ' ').toLowerCase()
+
+// The item a link target makes: a web link, a local file (a relative path
+// or a file:// URL), or null (an anchor, another scheme).
+function targetOf(label: string, url: string): LinkItem | null {
+ if (isWeb(url)) return { kind: 'web', label: label || url, href: url }
+ const file = fileOf(url.replace(/^file:\/\//i, '').replace(/[?#].*$/, ''))
+ return file ? { kind: 'file', ...file } : null
+}
+
+// A link text as one plain line: no images, links, code ticks, emphasis
+// or escapes.
+const labelOf = (md: string) =>
+ md
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
+ .replace(/<[^>\n]+>/g, '')
+ .replace(/`+/g, '')
+ .replace(/(\*\*|__|~~)(?=\S)([\s\S]*?\S)\1/g, '$2')
+ .replace(/(^|[^\w*])[*_](?=\S)([\s\S]*?\S)[*_](?![\w*])/g, '$1$2')
+ .replace(/\\([!-/:-@[-`{-~])/g, '$1')
+ .replace(/\s+/g, ' ')
+ .trim()
+
+// A bare URL less the punctuation after it: `.,;:!?'"*` and a `)` or `]`
+// that closes nothing in the URL.
+function trimUrl(url: string): string {
+ const count = (c: string) => url.split(c).length - 1
+ for (;;) {
+ const last = url.at(-1)!
+ if (`.,;:!?'"*`.includes(last)) url = url.slice(0, -1)
+ else if (last === ')' && count('(') < count(')')) url = url.slice(0, -1)
+ else if (last === ']' && count('[') < count(']')) url = url.slice(0, -1)
+ else return url
+ }
+}
+
+// Whether a line closes a fence that opened with `mark`.
+function closes(line: string, mark: string): boolean {
+ const m = FENCE.exec(line)
+ return !!m && m[2]![0] === mark[0] && m[2]!.length >= mark.length && line.trim() === m[2]
+}
+
+// The command of a fenced block (its lines, the fences too) with a shell
+// info: prompts dropped, in a session block only the prompt lines (and
+// their `\` continuations). Null for another info or an empty block.
+function commandOf(info: string, lines: string[]): LinkItem | null {
+ if (!SHELL.test(info)) return null
+ const open = FENCE.exec(lines[0] ?? '')
+ if (!open) return null
+ const indent = new RegExp(`^ {0,${open[1]!.length}}`)
+ let body = lines.slice(1)
+ if (body.length && closes(body.at(-1)!, open[2]!)) body.pop()
+ body = body.map(l => l.replace(indent, '').trimEnd())
+ if (SESSION.test(info)) {
+ let more = false
+ body = body.filter(l => {
+ const keep = PROMPT.test(l) || more
+ more = keep && l.endsWith('\\')
+ return keep
+ })
+ }
+ body = body.map(l => l.replace(PROMPT, ''))
+ while (body.length && !body[0]!.trim()) body.shift()
+ while (body.length && !body.at(-1)!.trim()) body.pop()
+ if (!body.length) return null
+ const more = body.filter(l => l.trim()).length - 1
+ const first = body[0]!.trim()
+ return { kind: 'command', label: more ? `${first} (+${more} ${more === 1 ? 'line' : 'lines'})` : first, text: body.join('\n') }
+}
+
+type Hit = { at: number; item: LinkItem }
+
+// The items of a block outside a margin fence, in their order: the
+// commands of its indented fences, then links, code spans and bare text.
+// Each part found is blanked, so a later rule does not see it again.
+function textItems(lines: string[], defs: Map<string, string>): LinkItem[] {
+ const hits: Hit[] = []
+ const text: string[] = []
+ let offset = 0
+ const put = (line: string) => {
+ text.push(line)
+ offset += line.length + 1
+ }
+ for (let i = 0; i < lines.length; i++) {
+ const m = FENCE.exec(lines[i]!)
+ if (m) {
+ let j = i + 1
+ while (j < lines.length && !closes(lines[j]!, m[2]!)) j++
+ const cmd = commandOf(m[3] ?? '', lines.slice(i, j + 1))
+ if (cmd) hits.push({ at: offset, item: cmd })
+ for (const l of lines.slice(i, j + 1)) put(' '.repeat(l.length))
+ i = j
+ } else put(DEF.test(lines[i]!) ? ' '.repeat(lines[i]!.length) : lines[i]!)
+ }
+ const src = text.join('\n')
+ let masked = src
+ const hide = (from: number, to: number) => {
+ masked = masked.slice(0, from) + masked.slice(from, to).replace(/[^\n]/g, ' ') + masked.slice(to)
+ }
+ const add = (at: number, item: LinkItem | null) => item && hits.push({ at, item })
+
+ for (const m of src.matchAll(CODE)) {
+ const code = m[2]!.replace(/\s+/g, ' ').trim()
+ if (code.startsWith('! ')) add(m.index, { kind: 'command', label: code, text: code })
+ else {
+ const file = fileOf(code)
+ if (file) add(m.index, { kind: 'file', ...file })
+ }
+ hide(m.index, m.index + m[0].length)
+ }
+ for (const re of [BLOCK_MATH, INLINE_MATH]) for (const m of masked.matchAll(re)) hide(m.index, m.index + m[0].length)
+ for (const m of masked.matchAll(INLINE)) {
+ const end = m.index + m[0].length
+ if (masked[m.index - 1] !== '!') add(m.index, targetOf(labelOf(src.slice(m.index + 1, m.index + 1 + m[1]!.length)), m[2] ?? m[3] ?? ''))
+ hide(m.index, end)
+ }
+ for (const m of masked.matchAll(REF)) {
+ if (m[1]!.startsWith('^') || masked[m.index + m[0].length] === '(') continue
+ const url = defs.get(refKey(m[2] || m[1]!))
+ if (url === undefined) continue
+ if (masked[m.index - 1] !== '!') add(m.index, targetOf(labelOf(src.slice(m.index + 1, m.index + 1 + m[1]!.length)), url))
+ hide(m.index, m.index + m[0].length)
+ }
+ for (const m of masked.matchAll(AUTO)) {
+ const url = m[1]!
+ const href = /^(https?|mailto):/i.test(url) ? url : `mailto:${url}`
+ add(m.index, { kind: 'web', label: url, href })
+ hide(m.index, m.index + m[0].length)
+ }
+ for (const m of masked.matchAll(BARE)) {
+ const url = trimUrl(m[0])
+ add(m.index, { kind: 'web', label: url, href: url })
+ hide(m.index, m.index + url.length)
+ }
+ for (const m of masked.matchAll(BARE_FILE)) {
+ const file = fileOf(m[0], true)
+ if (file) add(m.index, { kind: 'file', ...file })
+ }
+ return hits.sort((a, b) => a.at - b.at).map(h => h.item)
+}
+
+// The web links, file paths and commands of some Markdown, each once (the
+// first), in the order they first show.
+export function linksOf(md: string): LinkItem[] {
+ const blocks = blocksOf(md)
+ const defs = new Map<string, string>()
+ for (const block of blocks) {
+ if (block.fence) continue
+ for (const line of block.lines) {
+ const m = DEF.exec(line)
+ if (m && !defs.has(refKey(m[1]!))) defs.set(refKey(m[1]!), m[2]!)
+ }
+ }
+ const seen = new Set<string>()
+ return blocks
+ .flatMap(block => {
+ if (!block.fence) return textItems(block.lines, defs)
+ const cmd = commandOf(block.fence.info, block.lines)
+ return cmd ? [cmd] : []
+ })
+ .filter(item => {
+ const key = `${item.kind} ${item.kind === 'web' ? item.href : item.kind === 'file' ? item.path : item.text}`
+ if (seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+}
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index 87c2e09..f508554 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -10,7 +10,7 @@ import { jobDone } from './epoch'
import { fitBox, fitsInline, INLINE_MAX_BYTES, roomColumns } from './terminal'
import { convertBox, convertedPath, folderOf, onScreenOf, pasteDirOf, pictureCells, pictureRowsFor, type PixelBox, type SentFile } from './images'
import { imagePathOf } from './markdown'
-import { drawPages, hashOf } from './draw'
+import { drawPages, hashOf, linksFor, type ShownLink } from './draw'
import { convertCall, logDebug, parseOd, pngSize } from './typst'
import { pagesOf, type Drawing } from './answer'
import { HEADERS_SH } from './host'
@@ -21,8 +21,9 @@ export type Picture = { file: string; stamp: string; bytes: number; width: numbe
export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }
// What draws under a SendUserFile row: a picture, or a Markdown file's
// pages (`blank`: an empty space while they compile; an older, wider page
-// draws smaller to fit) with its pagesOf id (a copy reads them by it).
-export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; id: string }
+// draws smaller to fit) with its pagesOf id (a copy reads them by it) and
+// the link rows under its pages (none while blank).
+export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; id: string; links?: readonly ShownLink[] }
export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>
// Where a stat is read: the `done` value the row read and the row's
@@ -231,7 +232,8 @@ export async function sentOf(
id, text, frame: frameFor(e.viewport), env: o.markdown, canStream: false, base: folderOf(full),
onScreen: onScreenOf(e.props.onScreen),
})
- if (drawing.kind !== 'text') under.push({ drawing, id })
+ if (drawing.kind === 'pages') under.push({ drawing, id, links: await linksFor($, text, folderOf(full)) })
+ else if (drawing.kind !== 'text') under.push({ drawing, id })
continue
}
if (f.kind !== 'png' && next && (next.width !== box.width || next.height !== box.height)) {
@@ -251,18 +253,23 @@ export async function sentOf(
const boxOf = (frame: Frame, inline: boolean, height: Height): PixelBox =>
convertBox(pictureColumns(frame, inline), pictureRowsFor(frame.rows, height), frame.cell)
-// The rows underRow draws after `under[i]`: a picture its rows, a Markdown
-// file its pages at their drawn box (fitBox in `room`, as drawPages) and a
-// Typst error line, a blank none.
+// The rows underRow draws under the pages of `under[i]` besides its Typst
+// error line: its link rows, then all after it (a picture its rows, a
+// Markdown file its pages at their drawn box (fitBox in `room`, as
+// drawPages), a Typst error line and its link rows, a blank none).
export function rowsAfter(under: readonly Under[], i: number, room: number): number {
- return under.slice(i + 1).reduce((sum, u) => {
+ const own = under[i]
+ return linkRows(own) + under.slice(i + 1).reduce((sum, u) => {
if ('source' in u) return sum + u.rows
if (u.drawing.kind !== 'pages') return sum
const { pages, note } = u.drawing.result
- return sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0)
+ return sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0) + linkRows(u)
}, 0)
}
+// The link rows drawn under a Markdown file's pages (one row each).
+const linkRows = (u: Under | undefined) => (u && 'drawing' in u && u.drawing.kind === 'pages' ? (u.links?.length ?? 0) : 0)
+
// The engine's row, then the pictures under it.
export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {
const { Box, Image } = uiResolve($, e)
@@ -276,7 +283,7 @@ export function underRow($: EngineInterface, e: RowInput, row: RenderElement, un
if (drawing.kind === 'blank') return <Box key={`blank-${i}`} />
return (
<Box key={`pages-${i}`} flexDirection="column">
- {drawPages($, e, drawing.result, drawing.bytes, { gutter: 0, marginTop: 0, keys: `file${i}-` })}
+ {drawPages($, e, drawing.result, drawing.bytes, { gutter: 0, marginTop: 0, keys: `file${i}-`, links: s.links })}
</Box>
)
})}
diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsx
index 7f0fa6a..91a3ee6 100644
--- a/hooks/lib/plan.tsx
+++ b/hooks/lib/plan.tsx
@@ -14,7 +14,7 @@ import { GUTTER, bulletOf } from './settings'
import { S, writesLive } from './state'
import { firstLine } from './markdown'
import type { Drawing } from './answer'
-import { drawPages } from './draw'
+import { drawPages, type ShownLink } from './draw'
import { clockAfter, commandRun, fsRead, processRun, promptSubmit, turnAbort, uiAsk, uiResolve } from './api'
// The question's chip and its two wordings.
@@ -241,16 +241,17 @@ export function scheduleClear($: EngineInterface, plan: string, turnId: string)
type Terminal = ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderViewport }
-// The ExitPlanMode ToolUse row: the engine's row, then the plan's pages (a
-// dim line while they compile; the engine's row alone when they fail).
-export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement, drawing: Drawing): RenderElement {
+// The ExitPlanMode ToolUse row: the engine's row, then the plan's pages and
+// their link rows (a dim line while they compile; the engine's row alone
+// when they fail).
+export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement, drawing: Drawing, links: readonly ShownLink[] = []): RenderElement {
if (drawing.kind === 'text') return row
const { Box, Text } = uiResolve($, e)
return (
<Box flexDirection="column">
{row}
{drawing.kind === 'pages' ? (
- drawPages($, e, drawing.result, drawing.bytes, { bullet: true })
+ drawPages($, e, drawing.result, drawing.bytes, { bullet: true, links })
) : (
<Box marginTop={1} marginLeft={GUTTER}>
<Text dimColor>{PLAN_DRAWING}</Text>
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index f6aeb76..182adcf 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -101,6 +101,9 @@ export const heightText = (height: Height) =>
: height === 'full' ? `full (the terminal height less ${PICTURE_ROOM_ROWS} rows)`
: `${height} rows`
export const PICTURES_KEPT = 64
+// The file paths of the link rows under a picture: whether each one is a
+// file, kept for this many paths (the oldest go).
+export const LINK_FILES_KEPT = 512
// The compile results kept in memory (an LRU); the oldest go past this.
export const RESULTS_KEPT = 1024
// A resize or a font size change is settled when no new tty line and no
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index f0c6fd7..1c61272 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -209,6 +209,9 @@ export const converted = new Map<string, string | null>()
export const converting = new Map<string, Promise<string | null>>()
export const lastConverted = new Map<string, { stamp: string; png: string }>()
export const sentTexts = new Map<string, { stamp: string; text: string | null }>()
+// The link rows (draw.tsx): whether each absolute path is a file (at most
+// LINK_FILES_KEPT).
+export const linkFiles = new Map<string, boolean>()
// The plan: the text edited in Intelligent UI's flow, by the call's tool_use_id
// (its rows draw it), and the ExitPlanMode calls of subagents (drawn as the
// engine draws them).
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 8784797..d518103 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -32,7 +32,7 @@ import { commandSuggestions, parseCommand, registerCommand } from './lib/command
import { runSetup } from './lib/setup'
import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'
import { measureFonts } from './lib/typst'
-import { drawPages } from './lib/draw'
+import { drawPages, linksFor, type ShownLink } from './lib/draw'
import { finalizeAll } from './lib/stream'
import { noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from './lib/probe'
import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'
@@ -76,7 +76,9 @@ export { OSC11_PL, perlFor, WATCH_PL } from './lib/host'
export {
convertCall, isSafePage, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, typstInputs,
} from './lib/typst'
-export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, scaledBulletRow, sizing, type FirstLine } from './lib/draw'
+export {
+ alignFirstLine, fileHref, firstLineOf, fontFit, hashOf, renderKey, resolveLinks, scaledBulletRow, sizing, type FirstLine, type ShownLink,
+} from './lib/draw'
export { nextJob } from './lib/stream'
export * from './lib/images'
export * from './lib/copy'
@@ -134,8 +136,10 @@ const stampOf = (ready: { env: Env; done: number }, view?: RenderViewport) =>
// `text` the row's text (a string kept as given, so the compare is mostly
// one pointer), `extra` its other inputs.
type Memo<T> = { text: string; extra: string; stamp: string; onScreen: boolean | undefined; value: T }
-const answers = new Map<string, Memo<RenderElement>>()
-const plans = new Map<string, Memo<Drawing>>()
+// An answer's tree is kept with its link rows' count (the copy counts them
+// under its pages), a plan's drawing with its link rows.
+const answers = new Map<string, Memo<{ tree: RenderElement; links: number }>>()
+const plans = new Map<string, Memo<{ drawing: Drawing; links: ShownLink[] }>>()
const unders = new Map<string, Memo<Under[]>>()
const pasted = new Map<string, Memo<Shown[]>>()
@@ -160,20 +164,24 @@ function memoSet<T>(memo: Map<string, Memo<T>>, id: string, k: MemoKey, value: T
keep(memo, id, { ...k, value }, RESULTS_KEPT)
}
-// A plan's drawing (both its rows: ToolUse and ToolResult), kept while it
-// is drawn pages (memoOf).
+// A plan's drawing (both its rows: ToolUse and ToolResult) and the link
+// rows under its pages, kept while it is drawn pages (memoOf).
async function planDrawing(
$: EngineInterface, e: { viewport?: RenderViewport; props: { onScreen?: unknown } }, toolUseId: string, plan: string, ready: { env: Env; done: number },
-): Promise<Drawing> {
+): Promise<{ drawing: Drawing; links: ShownLink[] }> {
const id = `plan:${toolUseId}`
const onScreen = onScreenOf(e.props.onScreen)
const k = { text: plan, extra: '', stamp: stampOf(ready, e.viewport), onScreen }
const kept = memoOf(plans, id, k)
if (kept) return kept
const drawing = await pagesOf($, { id, text: plan, frame: frameFor(e.viewport), env: ready.env, canStream: false, onScreen })
- if (drawing.kind === 'pages') memoSet(plans, id, k, drawing)
- else plans.delete(id)
- return drawing
+ if (drawing.kind !== 'pages') {
+ plans.delete(id)
+ return { drawing, links: [] }
+ }
+ const drawn = { drawing, links: await linksFor($, plan, ready.env.cwd) }
+ memoSet(plans, id, k, drawn)
+ return drawn
}
// Intelligent UI's own plan question: only on the main loop of a session drawn
@@ -620,25 +628,25 @@ export const register: Register = on => {
const onScreen = onScreenOf(e.props.onScreen)
const k = { text: e.props.text, extra: bullet ? 'bullet' : '', stamp: stampOf(ready, e.viewport), onScreen }
const kept = memoOf(answers, e.requestId, k)
- // Its pages are under the top margin (drawPages); the rows on screen at
- // each draw, a memo hit too.
- const at = { top: MARGIN_TOP }
+ // Its pages are under the top margin (drawPages) with its link rows
+ // under them; the rows on screen at each draw, a memo hit too.
if (kept) {
noteCopy($, () => {
- noteDrawnAgain(e.requestId, roomColumns(e.viewport), at)
+ noteDrawnAgain(e.requestId, roomColumns(e.viewport), { top: MARGIN_TOP, after: kept.links })
noteOnScreen(e.requestId, e.props.onScreen)
})
- return kept
+ return kept.tree
}
const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, frame: frameFor(e.viewport), env: ready.env, canStream: true, onScreen })
if (drawing.kind === 'pages') {
- const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet })
+ const links = await linksFor($, e.props.text, ready.env.cwd)
+ const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet, links })
const { result } = drawing
noteCopy($, () => {
- noteDrawn(e.requestId, result, roomColumns(e.viewport), at)
+ noteDrawn(e.requestId, result, roomColumns(e.viewport), { top: MARGIN_TOP, after: links.length })
noteOnScreen(e.requestId, e.props.onScreen)
})
- memoSet(answers, e.requestId, k, tree)
+ memoSet(answers, e.requestId, k, { tree, links: links.length })
return tree
}
answers.delete(e.requestId)
@@ -755,19 +763,20 @@ export const register: Register = on => {
const plan = planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, e.props.input)
const ready = plan ? await answerEnv($, e) : null
if (!ready) return row
- const drawing = await planDrawing($, e, e.props.tool_use_id, plan, ready)
+ const { drawing, links } = await planDrawing($, e, e.props.tool_use_id, plan, ready)
// Its pages can be copied as an answer's, by the call's id (the row's
// requestId can be an answer's own). The engine's row is above them:
- // their place is read from the bottom (pageTopsOf).
+ // their place is read from the bottom (pageTopsOf), under them its
+ // link rows.
if (drawing.kind === 'pages') {
const { result } = drawing
const id = `plan:${e.props.tool_use_id}`
noteCopy($, () => {
- noteDrawn(id, result, roomColumns(e.viewport))
+ noteDrawn(id, result, roomColumns(e.viewport), { after: links.length })
noteOnScreen(id, e.props.onScreen)
})
}
- return drawPlanUse($, e, row, drawing)
+ return drawPlanUse($, e, row, drawing, links)
} catch {
return row
}
@@ -783,7 +792,7 @@ export const register: Register = on => {
try {
const plan = planOf(e.props.output) ? planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, undefined) : ''
const ready = plan ? await answerEnv($, e) : null
- const drawing = ready ? await planDrawing($, e, e.props.tool_use_id, plan, ready) : null
+ const drawing = ready ? (await planDrawing($, e, e.props.tool_use_id, plan, ready)).drawing : null
const filePath = (e.props.output as { filePath?: unknown }).filePath
if (drawing && drawing.kind !== 'text') drawn = drawPlanResult($, e, typeof filePath === 'string' ? filePath : undefined)
} catch {
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index c020a13..1b57746 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -231,6 +231,18 @@ test("a sent file's pages have the rows of the pictures and files after it under
expect(rowsAfter([pages, picture], 1, 50)).toBe(0)
})
+test("a sent file's link rows are under its pages too, and under the pages of each file before it", () => {
+ const result = { pages: [{ file: '/a-1.png', width: 1600, height: 640, alt: '', columns: 100, rows: 20 }], bulletRow: 0 }
+ const links = [{ kind: 'web', label: 'x', href: 'https://x.org' }, { kind: 'command', label: 'ls', text: 'ls' }] as const
+ const linked = { id: 'file:t:a.md', drawing: { kind: 'pages', result }, links } as Under
+ const blank = { id: 'file:t:b.md', drawing: { kind: 'blank' }, links } as Under
+ // Its own 2 link rows; then the next file's 10 page rows and 2 link rows.
+ expect(rowsAfter([linked, linked], 0, 50)).toBe(2 + 10 + 2)
+ expect(rowsAfter([linked, linked], 1, 50)).toBe(2)
+ // A blank draws no link rows.
+ expect(rowsAfter([linked, blank], 0, 50)).toBe(2)
+})
+
// ---- A real probe -----------------------------------------------------------
const REAL = positionsOf(SMALL_MARKS as unknown as Mark[], SMALL_PPI)
@@ -483,6 +495,24 @@ test('a compile writes no probe file and runs no probe; a copy probes only its p
expect(names(w.files)).toEqual(['doc.json', 'pages.json'])
})
+test("an answer's link rows are under its pages: the page on screen is found above them", async ($, on) => {
+ const w = world(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const long = Array.from({ length: 240 }, (_, i) => `Paragraph ${i} with a few words in it.`).join('\n\n')
+ const text = `${long}\n\nSee https://typst.app/docs.\n\n\`\`\`sh\nbrew install typst\n\`\`\``
+ const ui = await drawAnswer($, w, 'ans-1', text)
+ const pages = (JSON.parse(w.files.get([...w.files.keys()].find(k => k.endsWith('/doc.json'))!)!) as { segments: string[] }).segments.length
+ // 16 rows a page under the top margin, then 2 link rows: page 2 is rows 17 to 32.
+ const of = 1 + 16 * pages + 2
+ await ui.redraw({ ...props(text), onScreen: { first: 17, last: 32, of } })
+ await w.clock.settle()
+ w.copy([cells(2, 0, 97), cells(3, 0, 97)].join('\n'))
+ await w.clock.settle()
+ expect(w.queries.map(q => q.page)).toEqual(['2'])
+ const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)
+ expect(dumped.text).toContain(`-> answer ans-1 page 1 (rows 17-32 of ${of} on screen, page top 17)`)
+})
+
test('a compile retried in safe mode gives the probe safe=1 (its page files say so)', async ($, on) => {
const w = world(on, { failFirst: true })
await $.command.run({ command: 'iui', args: '' } as any)
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 0a79b26..838cc0d 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -1,7 +1,8 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey, RESIZE_QUIET_MS, SEGMENT_ROWS, WATCH_PL,
+ scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fileHref, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey,
+ RESIZE_QUIET_MS, resolveLinks, SEGMENT_ROWS, WATCH_PL,
} from '../hooks/register'
// ---- Where pictures draw ----------------------------------------------------
@@ -197,6 +198,8 @@ function world(on: any, vars: Record<string, string>, head = HEAD, stored: Recor
})
on('fs.exists', async ($: any, e: any, next: any) => {
calls.push('fs.exists')
+ // The project's files (the link rows' paths): the ones written.
+ if (e.path.startsWith('/w/app/')) return { value: files.has(e.path) }
return e.path.includes('/designs/') ? { value: design !== undefined || files.has(e.path) } : next(e)
})
on('fs.list', async ($: any, e: any, next: any) => {
@@ -207,9 +210,10 @@ function world(on: any, vars: Record<string, string>, head = HEAD, stored: Recor
calls.push('fs.stat')
return next(e)
})
- on('ui.toast', async () => ({ value: undefined }))
+ const toasts: string[] = []
+ on('ui.toast', async ($: any, e: any) => (toasts.push(String(e.text)), { value: undefined }))
on('ui.render', () => ENGINE as any)
- return { clock, reads, kept, compiles, files, hold, release, emit, sizeReads, kills, calls, logs }
+ return { clock, reads, kept, compiles, files, hold, release, emit, sizeReads, kills, calls, logs, toasts }
}
const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
@@ -716,3 +720,98 @@ test('a diagram with a kept design scales from it, and the design is not written
expect(compiles[0]!['design-h']).toBe('200')
expect([...files.keys()].filter(path => path.includes('/designs/'))).toEqual([])
})
+
+// ---- Link rows --------------------------------------------------------------
+
+// The elements of a type in a drawn tree, outermost first.
+const all = (tree: any, type: string): any[] =>
+ tree && typeof tree === 'object' ? [...(tree.type === type ? [tree] : []), ...(tree.children ?? []).flatMap((c: any) => all(c, type))] : []
+const textOf = (tree: any): string => (typeof tree === 'string' ? tree : (tree?.children ?? []).map(textOf).join(''))
+
+test('a file path is made absolute and kept only when it is a file; ~/ is the home folder; the href is encoded', async () => {
+ const asked: string[] = []
+ const $ = { fs: { exists: async (path: string) => (asked.push(path), path !== '/w/app/gone.ts') } } as any
+ const items = [
+ { kind: 'web', label: 'Docs', href: 'https://typst.app/docs' },
+ { kind: 'file', label: 'src/a b.ts:42', path: 'src/a b.ts' },
+ { kind: 'file', label: 'gone.ts', path: 'gone.ts' },
+ { kind: 'file', label: '~/x#1.md', path: '~/x#1.md' },
+ { kind: 'file', label: '/abs/y.md', path: '/abs/y.md' },
+ { kind: 'command', label: 'npm test', text: 'npm test' },
+ ] as const
+ const shown = await resolveLinks($, items, '/w/app/', '/h')
+ expect(shown).toEqual([
+ items[0],
+ { kind: 'file', label: 'src/a b.ts:42', path: '/w/app/src/a b.ts', href: 'file:///w/app/src/a%20b.ts' },
+ { kind: 'file', label: '~/x#1.md', path: '/h/x#1.md', href: 'file:///h/x%231.md' },
+ { kind: 'file', label: '/abs/y.md', path: '/abs/y.md', href: 'file:///abs/y.md' },
+ items[5],
+ ])
+ // Each path is checked once.
+ await resolveLinks($, items, '/w/app', '/h')
+ expect(asked).toEqual(['/w/app/src/a b.ts', '/w/app/gone.ts', '/h/x#1.md', '/abs/y.md'])
+ expect(fileHref('/a/b?c.md')).toBe('file:///a/b%3Fc.md')
+})
+
+const LINKED = [
+ 'See [Typst docs](https://typst.app/docs) and https://github.com/o/r/pull/42.',
+ '',
+ 'The copy is in `hooks/lib/copy.ts:42`; `hooks/lib/gone.ts` is not.',
+ '',
+ '```bash',
+ '$ brew install typst',
+ '```',
+ '',
+ '```sh',
+ 'npm test',
+ 'npm run lint',
+ '```',
+].join('\n')
+
+test('an answer draws its links, files and commands under its pages, one dim row each; a press copies the command', async ($, on) => {
+ const { clock, files, toasts } = world(on, { TERM: 'xterm-kitty' })
+ files.set('/w/app/hooks/lib/copy.ts', '')
+ on('session.cwd', async () => ({ value: '/w/app' }))
+ const copies: string[] = []
+ on('ui.copy', async ($: any, e: any) => (copies.push(`${e.surface}:${e.text}`), { value: { isCopied: true } }))
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await $.ui.mount(message('links-1', LINKED))
+ await clock.settle()
+ await ui.redraw(props(LINKED))
+ const tree: any = await ui.drawn()
+ // The column of the pages: the page, then one row per item.
+ const column = tree.children.at(-1)
+ expect(column.children.length).toBe(images(tree).length + 5)
+ const rows = column.children.slice(images(tree).length)
+ expect(rows.map(textOf)).toEqual([
+ '↗ Typst docs https://typst.app/docs',
+ '↗ https://github.com/o/r/pull/42',
+ '↗ hooks/lib/copy.ts:42',
+ '$ brew install typst',
+ '$ npm test (+1 line)',
+ ])
+ for (const row of rows.slice(0, 3)) expect(row.props).toMatchObject({ dimColor: true, wrap: 'truncate-end' })
+ expect(all(tree, 'Link').map(l => l.props.href)).toEqual(['https://typst.app/docs', 'https://github.com/o/r/pull/42', 'file:///w/app/hooks/lib/copy.ts'])
+ const buttons = all(tree, 'Button')
+ expect(buttons.length).toBe(2)
+ for (const b of buttons) expect(b.props).toMatchObject({ plain: true, dimColor: true })
+ expect(buttons[0].props.key).toMatch(/^link-[0-9a-f]{8}$/)
+ // A command row is one row: a Box one row high, its text cut at the end.
+ expect(rows[4].props).toMatchObject({ height: 1, overflow: 'hidden' })
+ expect(all(rows[4], 'Text')[0].props).toMatchObject({ wrap: 'truncate-end' })
+ await ui.press({ key: buttons[1].props.key })
+ expect(copies).toEqual(['terminal:npm test\nnpm run lint'])
+ expect(toasts).toContain('Copied')
+})
+
+test('an answer with no links draws as before: no row under its pages', async ($, on) => {
+ const { clock } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await $.ui.mount(message('links-2', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const tree: any = await ui.drawn()
+ expect(tree.children.at(-1).children.length).toBe(1)
+ expect(all(tree, 'Link')).toEqual([])
+ expect(all(tree, 'Button')).toEqual([])
+})
diff --git a/tests/images.test.ts b/tests/images.test.ts
index 986e556..1aa5dd6 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -567,6 +567,21 @@ test('a Markdown file Claude sends draws as pictures under the row, its images b
expect(docs).toEqual([{ base: '/t/docs', segments: [text], images: ['pic.png', '/t/docs/pic.png'] }])
})
+test("a Markdown file's links, files and commands draw under its pages; its relative paths start from its own folder", async ($, on) => {
+ const text = '# Notes\n\nSee `pic.png`, `gone.ts` and https://typst.app.\n\n```sh\nnpm test\n```'
+ const { clock } = world(on, { typst: true, files: { '/t/docs/pic.png': HEAD }, texts: { '/t/docs/notes.md': text } })
+ await ready($)
+ const ui = await $.ui.mount(sent(attachAll('/t/docs/notes.md')))
+ await clock.settle()
+ await ui.redraw(sent(attachAll('/t/docs/notes.md')).props)
+ const tree: any = await ui.drawn()
+ const all = (t: any, type: string): any[] =>
+ t && typeof t === 'object' ? [...(t.type === type ? [t] : []), ...(t.children ?? []).flatMap((c: any) => all(c, type))] : []
+ expect(all(tree, 'Link').map(l => l.props.href)).toEqual(['file:///t/docs/pic.png', 'https://typst.app'])
+ const [button] = all(tree, 'Button')
+ expect(button.props.key).toMatch(/^file0-link-[0-9a-f]{8}$/)
+})
+
test('the same Markdown in two folders compiles twice; an answer still uses the session folder', async ($, on) => {
const { clock, docs } = world(on, { typst: true, texts: { '/t/a/n.md': '# Same', '/t/b/n.md': '# Same' } })
await ready($)
diff --git a/tests/links.test.ts b/tests/links.test.ts
new file mode 100644
index 0000000..78a3665
--- /dev/null
+++ b/tests/links.test.ts
@@ -0,0 +1,104 @@
+import { expect, test } from 'claude-code/testing'
+
+import { linksOf } from '../hooks/lib/links'
+
+const web = (label: string, href = label) => ({ kind: 'web', label, href })
+const file = (path: string, label = path) => ({ kind: 'file', label, path })
+const command = (label: string, text = label) => ({ kind: 'command', label, text })
+
+test('a Markdown link is a web link; its label is plain text', () => {
+ expect(linksOf('See [Typst docs](https://typst.app/docs).')).toEqual([web('Typst docs', 'https://typst.app/docs')])
+ expect(linksOf('[**The** `api` _guide_](https://x.dev/a "Title")')).toEqual([web('The api guide', 'https://x.dev/a')])
+ expect(linksOf('[mail](mailto:[email protected]) and <https://a.io/x> and <[email protected]>')).toEqual([
+ web('mail', 'mailto:[email protected]'),
+ web('https://a.io/x'),
+ ])
+})
+
+test('an image is not a link, but a link around an image is', () => {
+ expect(linksOf('![a cat](https://x.io/cat.png)')).toEqual([])
+ expect(linksOf('[![CI](https://x.io/badge.svg)](https://x.io/ci)')).toEqual([web('CI', 'https://x.io/ci')])
+})
+
+test('anchors, other schemes and relative links are not web links', () => {
+ expect(linksOf('[top](#intro) [ftp](ftp://x.org/a) [js](javascript:alert)')).toEqual([])
+ expect(linksOf('[the docs](docs/a.md#setup)')).toEqual([file('docs/a.md')])
+})
+
+test('reference links use their definitions; a footnote is not a link', () => {
+ const md = 'Read [the guide][g], [Docs][] and [home].\n\nA note[^1].\n\n[g]: https://x.io/guide "Guide"\n[docs]: <https://x.io/docs>\n[Home]: https://x.io\n[^1]: Some note text.'
+ expect(linksOf(md)).toEqual([web('the guide', 'https://x.io/guide'), web('Docs', 'https://x.io/docs'), web('home', 'https://x.io')])
+ expect(linksOf('A [label][nope] with no definition.')).toEqual([])
+})
+
+test('a bare URL loses the punctuation after it and a ) that closes nothing', () => {
+ expect(linksOf('Go to https://x.io/a, then https://x.io/b.')).toEqual([web('https://x.io/a'), web('https://x.io/b')])
+ expect(linksOf('(see https://x.io/c)')).toEqual([web('https://x.io/c')])
+ expect(linksOf('https://en.wikipedia.org/wiki/Rust_(language)!')).toEqual([web('https://en.wikipedia.org/wiki/Rust_(language)')])
+ expect(linksOf('"https://x.io/q?a=1";')).toEqual([web('https://x.io/q?a=1')])
+})
+
+test('no links from fences, inline code or math', () => {
+ expect(linksOf('```js\nfetch("https://x.io/api")\n```')).toEqual([])
+ expect(linksOf('Run `curl https://x.io/api` now.')).toEqual([])
+ expect(linksOf('$a = [b](https://x.io)$ and\n\n$$\nhttps://x.io/m\n$$')).toEqual([])
+ expect(linksOf('~~~\nsee hooks/lib/copy.ts:42\n~~~')).toEqual([])
+})
+
+test('a file path in inline code or bare text, with a line and a column', () => {
+ expect(linksOf('Look at `hooks/lib/copy.ts:42` and src/app.py:10:5.')).toEqual([
+ file('hooks/lib/copy.ts', 'hooks/lib/copy.ts:42'),
+ file('src/app.py', 'src/app.py:10:5'),
+ ])
+ expect(linksOf('Edit /abs/x.md, ./a/b.tsx and README.md; also `.github/ci.yml`.')).toEqual([
+ file('/abs/x.md'),
+ file('./a/b.tsx'),
+ file('README.md'),
+ file('.github/ci.yml'),
+ ])
+})
+
+test('versions, abbreviations, domains and names are not file paths', () => {
+ expect(linksOf('Version 1.2.3 (or v0.15), e.g. on typst.app with Node.js at 3.5 p.m.')).toEqual([])
+ expect(linksOf('`1.2.3` `e.g.` `typst.app` `example.com/a/b.md` `done.`')).toEqual([])
+ expect(linksOf('Clone github.com/o/r/blob/main/x.ts today.')).toEqual([])
+})
+
+test('a shell fence is one command, prompts dropped; the label shows the first line', () => {
+ expect(linksOf('```bash\n$ brew install typst\n```')).toEqual([command('brew install typst')])
+ expect(linksOf('```sh\nnpm i\n\nnpm test\n% npm run build\n```')).toEqual([command('npm i (+2 lines)', 'npm i\n\nnpm test\nnpm run build')])
+ expect(linksOf('```ZSH\ncd a\nls\n```')).toEqual([command('cd a (+1 line)', 'cd a\nls')])
+ expect(linksOf('```bash\n\n```\n\n```python\nprint(1)\n```')).toEqual([])
+})
+
+test('a console block keeps only its prompt lines', () => {
+ const md = '```console\n$ npm test\n> ok 12 tests\n3 passed\n$ git push \\\n origin main\nTo github.com\n```'
+ expect(linksOf(md)).toEqual([command('npm test (+2 lines)', 'npm test\ngit push \\\n origin main')])
+ expect(linksOf('```shell-session\nno prompt here\n```')).toEqual([])
+})
+
+test('a fence inside a list item is a command too', () => {
+ expect(linksOf('1. Install:\n ```bash\n $ npm i\n ```\n2. Done, see https://x.io')).toEqual([command('npm i'), web('https://x.io')])
+})
+
+test('inline code that starts with ! is a command as written', () => {
+ expect(linksOf('Type `! git status` in the prompt; `!x` is not.')).toEqual([command('! git status')])
+})
+
+test('each item once, the first, in the order of the text', () => {
+ const md = [
+ 'Open README.md and [the site](https://x.io).',
+ '',
+ '```bash',
+ 'npm test',
+ '```',
+ '',
+ 'Again: https://x.io, `README.md:3` and',
+ '',
+ '```sh',
+ '$ npm test',
+ '```',
+ ].join('\n')
+ expect(linksOf(md)).toEqual([file('README.md'), web('the site', 'https://x.io'), command('npm test')])
+})
diff --git a/tests/plan.test.ts b/tests/plan.test.ts
index 167e941..88c033e 100644
--- a/tests/plan.test.ts
+++ b/tests/plan.test.ts
@@ -264,6 +264,20 @@ test('the ExitPlanMode row draws the plan as pictures under the engine row, at a
expect(texts(tree).join('\n')).not.toContain(PLAN_DRAWING)
})
+test("the plan's links and commands draw under its pictures", async ($, on) => {
+ const { clock } = world($, on)
+ await ready($)
+ const plan = `${PLAN}\n\nRead https://typst.app/docs first.\n\n\`\`\`sh\nnpm test\n\`\`\``
+ const row = use({ input: { plan, planFilePath: FILE } })
+ const ui = await $.ui.mount(row)
+ await clock.settle()
+ await ui.redraw(row.props)
+ const tree: any = await ui.drawn()
+ expect(images(tree).length).toBe(1)
+ expect(texts(tree)).toContain('https://typst.app/docs')
+ expect((await ui.findAll({ type: 'Button' })).length).toBe(1)
+})
+
test('a redraw of the plan row with a new onScreen draws the engine row again and compiles nothing', async ($, on) => {
let rows = 0
on('ui.render', { component: 'ToolUse' }, async ($: any, e: any, next: any) => (rows++, next(e)))