✨ Window: finished answers drawn as Markdown (#274)
An answer streams raw; once its part is complete (the model's next tool call, or the end of the turn) it is drawn as Markdown: headings, lists, quotes, rules, aligned tables, fenced code, bold, italic, code, links. Hand-written subset, no dependency; a closed answer is laid out once per width. `renderMarkdown: false` keeps every answer raw (on by default). Window only. Tests, docs EN+FR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7541a8e parent: d73650d added
.tickets/issues/0274-window-render-markdown-in-closed-answers-experiment.yaml +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 274 | |
| 3 | +title: "Window: render the Markdown of an answer once it is complete (experiment)" | |
| 4 | +state: closed | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-27T10:00:00.000Z | |
| 9 | +updatedAt: 2026-11-27T11:00:00.000Z | |
| 10 | +closedAt: 2026-11-27T11:00:00.000Z | |
| 11 | +labels: | |
| 12 | + - enhancement | |
| 13 | + - kind::feature | |
| 14 | +epic: Improve TUI | |
| 15 | +body: | | |
| 16 | + ## Asked (user, 2026-11-27) | |
| 17 | + Cost of rendering Markdown in the window; then: render it at the end of | |
| 18 | + each completion, on a separate branch (experiment/tui-markdown) so that | |
| 19 | + it can be dropped easily. Window (`mm -tui`) ONLY: the line mode, `-p` | |
| 20 | + and ACP are untouched. | |
| 21 | + | |
| 22 | + ## Design (as built on the branch) | |
| 23 | + - An answer streams raw, as before; its entry is rendered once CLOSED — | |
| 24 | + the model's next tool call, or the end of the turn (Transcript.Close). | |
| 25 | + `Entries()` marks the open one (`Entry.Open`, on the copy). | |
| 26 | + - Closed entries never change: laid out once per width (mdCache). | |
| 27 | + - `Line` gains `Spans` (runs with their own style + bold / italic / | |
| 28 | + strike / underline / dim); a line without spans is drawn as before. | |
| 29 | + - Hand-written subset (internal/tui/markdown.go, no dependency): ATX | |
| 30 | + headings, - * + and numbered lists (nested, tasks), > quotes, rules, | |
| 31 | + fenced code (language shown dim, fences dropped), GFM tables (aligned; | |
| 32 | + too wide → widest column narrowed, cells cut with …); inline bold, | |
| 33 | + italic, both, strike, code, links (text underlined + dim url), | |
| 34 | + autolinks, escapes. Unclosed markers stay literal; the author's line | |
| 35 | + breaks are kept. | |
| 36 | + | |
| 37 | + ## Open points | |
| 38 | + - The jump when an entry closes (line count changes); scroll anchoring | |
| 39 | + while the user reads higher up not done. | |
| 40 | + - Mouse selection (F2 off) copies the rendered text; Ctrl-Y still copies | |
| 41 | + the raw Markdown. | |
| 42 | + - No syntax highlighting in code blocks. | |
| 43 | + - Docs EN+FR: written with the switch (configuration reference row, | |
| 44 | + window how-to bullet). | |
| 45 | +tasks: [] | |
| 46 | +comments: | |
| 47 | + - id: 1 | |
| 48 | + author: | |
| 49 | + name: k33g | |
| 50 | + email: ph.charriere@gmail.com | |
| 51 | + createdAt: 2026-11-27T10:30:00.000Z | |
| 52 | + body: | | |
| 53 | + User (2026-11-27): "works rather well" — add a switch in the config | |
| 54 | + file, ON by default. Done: `renderMarkdown` (bool, default true; | |
| 55 | + config.go field + default), read by View.lines(); `false` passes no | |
| 56 | + renderer, every answer stays raw. Tests: tui TestRenderMarkdownSwitch, | |
| 57 | + config TestRenderMarkdownKey. Docs EN+FR: configuration.md row, | |
| 58 | + how-to/use-the-window-mode.md bullet. go test ./..., vet, gofmt clean. | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 274 | ||
| 3 | +title: "Window: render the Markdown of an answer once it is complete (experiment)" | ||
| 4 | +state: closed | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-27T10:00:00.000Z | ||
| 9 | +updatedAt: 2026-11-27T11:00:00.000Z | ||
| 10 | +closedAt: 2026-11-27T11:00:00.000Z | ||
| 11 | +labels: | ||
| 12 | + - enhancement | ||
| 13 | + - kind::feature | ||
| 14 | +epic: Improve TUI | ||
| 15 | +body: | | ||
| 16 | + ## Asked (user, 2026-11-27) | ||
| 17 | + Cost of rendering Markdown in the window; then: render it at the end of | ||
| 18 | + each completion, on a separate branch (experiment/tui-markdown) so that | ||
| 19 | + it can be dropped easily. Window (`mm -tui`) ONLY: the line mode, `-p` | ||
| 20 | + and ACP are untouched. | ||
| 21 | + | ||
| 22 | + ## Design (as built on the branch) | ||
| 23 | + - An answer streams raw, as before; its entry is rendered once CLOSED — | ||
| 24 | + the model's next tool call, or the end of the turn (Transcript.Close). | ||
| 25 | + `Entries()` marks the open one (`Entry.Open`, on the copy). | ||
| 26 | + - Closed entries never change: laid out once per width (mdCache). | ||
| 27 | + - `Line` gains `Spans` (runs with their own style + bold / italic / | ||
| 28 | + strike / underline / dim); a line without spans is drawn as before. | ||
| 29 | + - Hand-written subset (internal/tui/markdown.go, no dependency): ATX | ||
| 30 | + headings, - * + and numbered lists (nested, tasks), > quotes, rules, | ||
| 31 | + fenced code (language shown dim, fences dropped), GFM tables (aligned; | ||
| 32 | + too wide → widest column narrowed, cells cut with …); inline bold, | ||
| 33 | + italic, both, strike, code, links (text underlined + dim url), | ||
| 34 | + autolinks, escapes. Unclosed markers stay literal; the author's line | ||
| 35 | + breaks are kept. | ||
| 36 | + | ||
| 37 | + ## Open points | ||
| 38 | + - The jump when an entry closes (line count changes); scroll anchoring | ||
| 39 | + while the user reads higher up not done. | ||
| 40 | + - Mouse selection (F2 off) copies the rendered text; Ctrl-Y still copies | ||
| 41 | + the raw Markdown. | ||
| 42 | + - No syntax highlighting in code blocks. | ||
| 43 | + - Docs EN+FR: written with the switch (configuration reference row, | ||
| 44 | + window how-to bullet). | ||
| 45 | +tasks: [] | ||
| 46 | +comments: | ||
| 47 | + - id: 1 | ||
| 48 | + author: | ||
| 49 | + name: k33g | ||
| 50 | + email: ph.charriere@gmail.com | ||
| 51 | + createdAt: 2026-11-27T10:30:00.000Z | ||
| 52 | + body: | | ||
| 53 | + User (2026-11-27): "works rather well" — add a switch in the config | ||
| 54 | + file, ON by default. Done: `renderMarkdown` (bool, default true; | ||
| 55 | + config.go field + default), read by View.lines(); `false` passes no | ||
| 56 | + renderer, every answer stays raw. Tests: tui TestRenderMarkdownSwitch, | ||
| 57 | + config TestRenderMarkdownKey. Docs EN+FR: configuration.md row, | ||
| 58 | + how-to/use-the-window-mode.md bullet. go test ./..., vet, gofmt clean. | ||
modified
docs/en/how-to/use-the-window-mode.md +1 -0 | @@ -27,6 +27,7 @@ This guide shows how to run mini-me as a single full-screen window — the conve | ||
| 27 | 27 | ## Variants |
| 28 | 28 | |
| 29 | 29 | - **Ask before every `bash` and file tool.** Set `yolo: false` in the YAML. The box is replaced by the question `? bash: rm -rf build` and four keys answer it: `a` allow once, `s` allow this tool for the session, `r` (or Esc) reject, `n` never allow this tool in this session. A rejected tool tells the model `[command rejected by the user]`. The default, `yolo: true`, runs tools without asking. See [How to confirm tool calls](confirm-tool-calls.md). |
| 30 | +- **Read answers as Markdown, or raw.** A finished answer is drawn as Markdown — tables aligned, lists, headings, code — while the one being written stays raw until its part is complete. `renderMarkdown: false` in the YAML keeps every answer raw. See [configuration](../reference/configuration.md). | |
| 30 | 31 | - **Ask for an answer in a given form.** Type `[` at the start of the box: a list of 13 meta-prompts opens — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Enter puts the prefix in the box, type the question after it. See [The four pickers](../reference/slash-commands.md#the-four-pickers). |
| 31 | 32 | - **Point the model at a file.** `@path` works exactly as in the line mode: existing paths are attached and echoed as `📎` lines. See [Point the model at a file with `@path`](attach-a-file.md). |
| 32 | 33 | - **See which agent answers.** The header and the label above each answer name the agent: `mm`, or `mm [<acp.title>]` when the config gives a title. While another agent works — `/ask-<name>`, or the `ask_agent` tool — the header names it with its model and `asked by` your agent, and its answer is labelled with its title (or its `mmConfigs` name); then both come back to your agent. See [How to let your agent call other agents](let-the-agent-call-other-agents.md). |
| @@ -27,6 +27,7 @@ This guide shows how to run mini-me as a single full-screen window — the conve | |||
| 27 | ## Variants | 27 | ## Variants |
| 28 | 28 | ||
| 29 | - **Ask before every `bash` and file tool.** Set `yolo: false` in the YAML. The box is replaced by the question `? bash: rm -rf build` and four keys answer it: `a` allow once, `s` allow this tool for the session, `r` (or Esc) reject, `n` never allow this tool in this session. A rejected tool tells the model `[command rejected by the user]`. The default, `yolo: true`, runs tools without asking. See [How to confirm tool calls](confirm-tool-calls.md). | 29 | - **Ask before every `bash` and file tool.** Set `yolo: false` in the YAML. The box is replaced by the question `? bash: rm -rf build` and four keys answer it: `a` allow once, `s` allow this tool for the session, `r` (or Esc) reject, `n` never allow this tool in this session. A rejected tool tells the model `[command rejected by the user]`. The default, `yolo: true`, runs tools without asking. See [How to confirm tool calls](confirm-tool-calls.md). |
| 30 | +- **Read answers as Markdown, or raw.** A finished answer is drawn as Markdown — tables aligned, lists, headings, code — while the one being written stays raw until its part is complete. `renderMarkdown: false` in the YAML keeps every answer raw. See [configuration](../reference/configuration.md). | ||
| 30 | - **Ask for an answer in a given form.** Type `[` at the start of the box: a list of 13 meta-prompts opens — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Enter puts the prefix in the box, type the question after it. See [The four pickers](../reference/slash-commands.md#the-four-pickers). | 31 | - **Ask for an answer in a given form.** Type `[` at the start of the box: a list of 13 meta-prompts opens — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Enter puts the prefix in the box, type the question after it. See [The four pickers](../reference/slash-commands.md#the-four-pickers). |
| 31 | - **Point the model at a file.** `@path` works exactly as in the line mode: existing paths are attached and echoed as `📎` lines. See [Point the model at a file with `@path`](attach-a-file.md). | 32 | - **Point the model at a file.** `@path` works exactly as in the line mode: existing paths are attached and echoed as `📎` lines. See [Point the model at a file with `@path`](attach-a-file.md). |
| 32 | - **See which agent answers.** The header and the label above each answer name the agent: `mm`, or `mm [<acp.title>]` when the config gives a title. While another agent works — `/ask-<name>`, or the `ask_agent` tool — the header names it with its model and `asked by` your agent, and its answer is labelled with its title (or its `mmConfigs` name); then both come back to your agent. See [How to let your agent call other agents](let-the-agent-call-other-agents.md). | 33 | - **See which agent answers.** The header and the label above each answer name the agent: `mm`, or `mm [<acp.title>]` when the config gives a title. While another agent works — `/ask-<name>`, or the `ask_agent` tool — the header names it with its model and `asked by` your agent, and its answer is labelled with its title (or its `mmConfigs` name); then both come back to your agent. See [How to let your agent call other agents](let-the-agent-call-other-agents.md). |
modified
docs/en/reference/configuration.md +1 -0 | @@ -22,6 +22,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | ||
| 22 | 22 | | `displayHooks` | bool | `false` | Show every hook that ran: event, command, tool or agent, decision, size of the context added (never its text). After each answer in the line mode, `-p` and the window; as a finished tool call per hook in an editor. See [hooks](hooks.md#display). | |
| 23 | 23 | | `showThinking` | bool | `true` | Show what a thinking model reasons about before it answers. Only the display is optional: the reasoning is always read off the wire, because it is what keeps the watchdog alive while the model thinks. See [Thinking models](../explanation/thinking-models.md). | |
| 24 | 24 | | `showCompletionTime` | bool | `true` | Window mode: show `⏱ <duration>` in the status bar, ticking while a turn or an `/ask` runs, then the final duration until the next question. `false` keeps the status bar to its counters. See [the window mode](cli.md). | |
| 25 | +| `renderMarkdown` | bool | `true` | Window mode: draw a finished answer as Markdown — headings, lists, block quotes, rules, tables (aligned; a column too wide is cut with `…`), fenced code, **bold**, *italic*, `code`, links (text underlined, address dimmed). The answer being written stays raw; its part is rendered once it is complete: at the model's next tool call, or at the end of the turn. `false` keeps every answer raw. The line mode, `-p` and an editor always show the text as it is; `Ctrl-Y` copies the raw Markdown. | | |
| 25 | 26 | | `showSpeed` | bool | `true` | The model's generation speed in tokens per second. Window mode: `⚡ ~58 tok/s` in the status bar while a model call streams (an estimate, refreshed every half second), then `⚡ 59.9 tok/s`, the turn's average, until the next answer starts. The turn's average is its tokens over the time the model spent generating them: the tools' run time and the prompt reading are left out. Source: the server's own `timings` when it sends them (llama-server, MLX-Serve), otherwise measured by mm from the first streamed token to the last. Editor (ACP): each finished call and turn goes in a `usage_update`'s `_meta.mm` (`tokensPerSecond`, `scope` `call` or `turn`, `source` `server` or `measured`), which a client that does not know the key ignores. The line mode shows nothing. `false` turns it off. | |
| 26 | 27 | | `system` | string | built-in prompt | The system prompt, first message of every history. Three variables are replaced each time a conversation starts (a new session, `/new`, a resumed one — not before every question, so the server's prompt cache holds): `{{date}}` today's date, `YYYY-MM-DD`, local time; `{{cwd}}` the directory the conversation works in (over ACP, the session's own); `{{env.NAME}}` the variable NAME — unset, replaced by nothing, with a banner warning; `{{config.NAME}}` the value NAME of the `variables` section. A NAME that looks like a secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) is a configuration error: the prompt goes to the model, the sessions and the traces. Spaces inside the braces are allowed (`{{ date }}`). Any other `{{…}}` is left as written; `\{{date}}` writes `{{date}}`. Not replaced in AGENTS.md. A session that crosses midnight keeps its date until `/new`. | |
| 27 | 28 | | `variables` | map name → string | none | The file's own values for the system prompt, used there as `{{config.NAME}}`. A value may hold `{{date}}`, `{{cwd}}` and `{{env.NAME}}` (expanded, the same secret check), not another `{{config.…}}`. Names: letters, digits, `_` and `-`, not starting with a digit. A `{{config.NAME}}` the section does not have is a configuration error. Example: `variables: {project: "mini-me, a coding agent written in Go"}`, then `You help with {{config.project}}.` in `system`. | |
| @@ -22,6 +22,7 @@ Where `mm` looks for this file: [Configuration file resolution](cli.md#configura | |||
| 22 | | `displayHooks` | bool | `false` | Show every hook that ran: event, command, tool or agent, decision, size of the context added (never its text). After each answer in the line mode, `-p` and the window; as a finished tool call per hook in an editor. See [hooks](hooks.md#display). | | 22 | | `displayHooks` | bool | `false` | Show every hook that ran: event, command, tool or agent, decision, size of the context added (never its text). After each answer in the line mode, `-p` and the window; as a finished tool call per hook in an editor. See [hooks](hooks.md#display). | |
| 23 | | `showThinking` | bool | `true` | Show what a thinking model reasons about before it answers. Only the display is optional: the reasoning is always read off the wire, because it is what keeps the watchdog alive while the model thinks. See [Thinking models](../explanation/thinking-models.md). | | 23 | | `showThinking` | bool | `true` | Show what a thinking model reasons about before it answers. Only the display is optional: the reasoning is always read off the wire, because it is what keeps the watchdog alive while the model thinks. See [Thinking models](../explanation/thinking-models.md). | |
| 24 | | `showCompletionTime` | bool | `true` | Window mode: show `⏱ <duration>` in the status bar, ticking while a turn or an `/ask` runs, then the final duration until the next question. `false` keeps the status bar to its counters. See [the window mode](cli.md). | | 24 | | `showCompletionTime` | bool | `true` | Window mode: show `⏱ <duration>` in the status bar, ticking while a turn or an `/ask` runs, then the final duration until the next question. `false` keeps the status bar to its counters. See [the window mode](cli.md). | |
| 25 | +| `renderMarkdown` | bool | `true` | Window mode: draw a finished answer as Markdown — headings, lists, block quotes, rules, tables (aligned; a column too wide is cut with `…`), fenced code, **bold**, *italic*, `code`, links (text underlined, address dimmed). The answer being written stays raw; its part is rendered once it is complete: at the model's next tool call, or at the end of the turn. `false` keeps every answer raw. The line mode, `-p` and an editor always show the text as it is; `Ctrl-Y` copies the raw Markdown. | | ||
| 25 | | `showSpeed` | bool | `true` | The model's generation speed in tokens per second. Window mode: `⚡ ~58 tok/s` in the status bar while a model call streams (an estimate, refreshed every half second), then `⚡ 59.9 tok/s`, the turn's average, until the next answer starts. The turn's average is its tokens over the time the model spent generating them: the tools' run time and the prompt reading are left out. Source: the server's own `timings` when it sends them (llama-server, MLX-Serve), otherwise measured by mm from the first streamed token to the last. Editor (ACP): each finished call and turn goes in a `usage_update`'s `_meta.mm` (`tokensPerSecond`, `scope` `call` or `turn`, `source` `server` or `measured`), which a client that does not know the key ignores. The line mode shows nothing. `false` turns it off. | | 26 | | `showSpeed` | bool | `true` | The model's generation speed in tokens per second. Window mode: `⚡ ~58 tok/s` in the status bar while a model call streams (an estimate, refreshed every half second), then `⚡ 59.9 tok/s`, the turn's average, until the next answer starts. The turn's average is its tokens over the time the model spent generating them: the tools' run time and the prompt reading are left out. Source: the server's own `timings` when it sends them (llama-server, MLX-Serve), otherwise measured by mm from the first streamed token to the last. Editor (ACP): each finished call and turn goes in a `usage_update`'s `_meta.mm` (`tokensPerSecond`, `scope` `call` or `turn`, `source` `server` or `measured`), which a client that does not know the key ignores. The line mode shows nothing. `false` turns it off. | |
| 26 | | `system` | string | built-in prompt | The system prompt, first message of every history. Three variables are replaced each time a conversation starts (a new session, `/new`, a resumed one — not before every question, so the server's prompt cache holds): `{{date}}` today's date, `YYYY-MM-DD`, local time; `{{cwd}}` the directory the conversation works in (over ACP, the session's own); `{{env.NAME}}` the variable NAME — unset, replaced by nothing, with a banner warning; `{{config.NAME}}` the value NAME of the `variables` section. A NAME that looks like a secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) is a configuration error: the prompt goes to the model, the sessions and the traces. Spaces inside the braces are allowed (`{{ date }}`). Any other `{{…}}` is left as written; `\{{date}}` writes `{{date}}`. Not replaced in AGENTS.md. A session that crosses midnight keeps its date until `/new`. | | 27 | | `system` | string | built-in prompt | The system prompt, first message of every history. Three variables are replaced each time a conversation starts (a new session, `/new`, a resumed one — not before every question, so the server's prompt cache holds): `{{date}}` today's date, `YYYY-MM-DD`, local time; `{{cwd}}` the directory the conversation works in (over ACP, the session's own); `{{env.NAME}}` the variable NAME — unset, replaced by nothing, with a banner warning; `{{config.NAME}}` the value NAME of the `variables` section. A NAME that looks like a secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) is a configuration error: the prompt goes to the model, the sessions and the traces. Spaces inside the braces are allowed (`{{ date }}`). Any other `{{…}}` is left as written; `\{{date}}` writes `{{date}}`. Not replaced in AGENTS.md. A session that crosses midnight keeps its date until `/new`. | |
| 27 | | `variables` | map name → string | none | The file's own values for the system prompt, used there as `{{config.NAME}}`. A value may hold `{{date}}`, `{{cwd}}` and `{{env.NAME}}` (expanded, the same secret check), not another `{{config.…}}`. Names: letters, digits, `_` and `-`, not starting with a digit. A `{{config.NAME}}` the section does not have is a configuration error. Example: `variables: {project: "mini-me, a coding agent written in Go"}`, then `You help with {{config.project}}.` in `system`. | | 28 | | `variables` | map name → string | none | The file's own values for the system prompt, used there as `{{config.NAME}}`. A value may hold `{{date}}`, `{{cwd}}` and `{{env.NAME}}` (expanded, the same secret check), not another `{{config.…}}`. Names: letters, digits, `_` and `-`, not starting with a digit. A `{{config.NAME}}` the section does not have is a configuration error. Example: `variables: {project: "mini-me, a coding agent written in Go"}`, then `You help with {{config.project}}.` in `system`. | |
modified
docs/fr/how-to/use-the-window-mode.md +1 -0 | @@ -27,6 +27,7 @@ Ce guide montre comment lancer mini-me dans une fenêtre unique en plein écran | ||
| 27 | 27 | ## Variantes |
| 28 | 28 | |
| 29 | 29 | - **Demander avant chaque `bash` et chaque outil de fichier.** Mettez `yolo: false` dans le YAML. La zone de saisie est remplacée par la question `? bash: rm -rf build` et quatre touches y répondent : `a` autoriser une fois, `s` autoriser cet outil pour la session, `r` (ou Échap) refuser, `n` ne jamais autoriser cet outil dans cette session. Un outil refusé dit au modèle `[command rejected by the user]`. La valeur par défaut, `yolo: true`, exécute les outils sans demander. Voir [Confirmer les appels d'outils](confirm-tool-calls.md). |
| 30 | +- **Lire les réponses en Markdown, ou brutes.** Une réponse terminée est affichée en Markdown — tableaux alignés, listes, titres, code — tandis que celle en cours d'écriture reste brute jusqu'à ce que sa partie soit terminée. `renderMarkdown: false` dans le YAML garde toutes les réponses brutes. Voir [configuration](../reference/configuration.md). | |
| 30 | 31 | - **Demander une réponse sous une forme donnée.** Tapez `[` en début de zone : une liste de 13 méta-prompts s'ouvre — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Entrée met le préfixe dans la zone, tapez la question après. Voir [Les quatre sélecteurs](../reference/slash-commands.md#les-quatre-sélecteurs). |
| 31 | 32 | - **Désigner un fichier au modèle.** `@chemin` fonctionne exactement comme dans le mode ligne : les chemins existants sont attachés et repris en lignes `📎`. Voir [Désigner un fichier au modèle avec `@chemin`](attach-a-file.md). |
| 32 | 33 | - **Voir quel agent répond.** L'en-tête et l'étiquette au-dessus de chaque réponse nomment l'agent : `mm`, ou `mm [<acp.title>]` quand la configuration donne un titre. Pendant qu'un autre agent travaille — `/ask-<nom>`, ou l'outil `ask_agent` — l'en-tête le nomme avec son modèle et `asked by` votre agent, et sa réponse porte son titre (ou son nom dans `mmConfigs`) ; puis les deux reviennent à votre agent. Voir [Laisser votre agent appeler d'autres agents](let-the-agent-call-other-agents.md). |
| @@ -27,6 +27,7 @@ Ce guide montre comment lancer mini-me dans une fenêtre unique en plein écran | |||
| 27 | ## Variantes | 27 | ## Variantes |
| 28 | 28 | ||
| 29 | - **Demander avant chaque `bash` et chaque outil de fichier.** Mettez `yolo: false` dans le YAML. La zone de saisie est remplacée par la question `? bash: rm -rf build` et quatre touches y répondent : `a` autoriser une fois, `s` autoriser cet outil pour la session, `r` (ou Échap) refuser, `n` ne jamais autoriser cet outil dans cette session. Un outil refusé dit au modèle `[command rejected by the user]`. La valeur par défaut, `yolo: true`, exécute les outils sans demander. Voir [Confirmer les appels d'outils](confirm-tool-calls.md). | 29 | - **Demander avant chaque `bash` et chaque outil de fichier.** Mettez `yolo: false` dans le YAML. La zone de saisie est remplacée par la question `? bash: rm -rf build` et quatre touches y répondent : `a` autoriser une fois, `s` autoriser cet outil pour la session, `r` (ou Échap) refuser, `n` ne jamais autoriser cet outil dans cette session. Un outil refusé dit au modèle `[command rejected by the user]`. La valeur par défaut, `yolo: true`, exécute les outils sans demander. Voir [Confirmer les appels d'outils](confirm-tool-calls.md). |
| 30 | +- **Lire les réponses en Markdown, ou brutes.** Une réponse terminée est affichée en Markdown — tableaux alignés, listes, titres, code — tandis que celle en cours d'écriture reste brute jusqu'à ce que sa partie soit terminée. `renderMarkdown: false` dans le YAML garde toutes les réponses brutes. Voir [configuration](../reference/configuration.md). | ||
| 30 | - **Demander une réponse sous une forme donnée.** Tapez `[` en début de zone : une liste de 13 méta-prompts s'ouvre — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Entrée met le préfixe dans la zone, tapez la question après. Voir [Les quatre sélecteurs](../reference/slash-commands.md#les-quatre-sélecteurs). | 31 | - **Demander une réponse sous une forme donnée.** Tapez `[` en début de zone : une liste de 13 méta-prompts s'ouvre — `[Brief]`, `[Step-by-Step]`, `[For Kids]`… Entrée met le préfixe dans la zone, tapez la question après. Voir [Les quatre sélecteurs](../reference/slash-commands.md#les-quatre-sélecteurs). |
| 31 | - **Désigner un fichier au modèle.** `@chemin` fonctionne exactement comme dans le mode ligne : les chemins existants sont attachés et repris en lignes `📎`. Voir [Désigner un fichier au modèle avec `@chemin`](attach-a-file.md). | 32 | - **Désigner un fichier au modèle.** `@chemin` fonctionne exactement comme dans le mode ligne : les chemins existants sont attachés et repris en lignes `📎`. Voir [Désigner un fichier au modèle avec `@chemin`](attach-a-file.md). |
| 32 | - **Voir quel agent répond.** L'en-tête et l'étiquette au-dessus de chaque réponse nomment l'agent : `mm`, ou `mm [<acp.title>]` quand la configuration donne un titre. Pendant qu'un autre agent travaille — `/ask-<nom>`, ou l'outil `ask_agent` — l'en-tête le nomme avec son modèle et `asked by` votre agent, et sa réponse porte son titre (ou son nom dans `mmConfigs`) ; puis les deux reviennent à votre agent. Voir [Laisser votre agent appeler d'autres agents](let-the-agent-call-other-agents.md). | 33 | - **Voir quel agent répond.** L'en-tête et l'étiquette au-dessus de chaque réponse nomment l'agent : `mm`, ou `mm [<acp.title>]` quand la configuration donne un titre. Pendant qu'un autre agent travaille — `/ask-<nom>`, ou l'outil `ask_agent` — l'en-tête le nomme avec son modèle et `asked by` votre agent, et sa réponse porte son titre (ou son nom dans `mmConfigs`) ; puis les deux reviennent à votre agent. Voir [Laisser votre agent appeler d'autres agents](let-the-agent-call-other-agents.md). |
modified
docs/fr/reference/configuration.md +1 -0 | @@ -22,6 +22,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | ||
| 22 | 22 | | `displayHooks` | booléen | `false` | Affiche chaque hook exécuté : événement, commande, outil ou agent, décision, taille du contexte ajouté (jamais son texte). Après chaque réponse en mode ligne, en `-p` et dans la fenêtre ; sous forme d'appel d'outil terminé, un par hook, dans un éditeur. Voir [hooks](hooks.md#affichage). | |
| 23 | 23 | | `showThinking` | booléen | `true` | Affiche ce qu'un modèle à raisonnement réfléchit avant de répondre. Seul l'affichage est optionnel : le raisonnement est toujours lu sur le fil, car c'est lui qui maintient le chien de garde en vie pendant que le modèle réfléchit. Voir [Modèles à raisonnement](../explanation/thinking-models.md). | |
| 24 | 24 | | `showCompletionTime` | booléen | `true` | Mode fenêtre : afficher `⏱ <durée>` dans la barre d'état, qui défile pendant un tour ou un `/ask`, puis la durée finale jusqu'à la question suivante. `false` limite la barre d'état à ses compteurs. Voir [le mode fenêtre](cli.md). | |
| 25 | +| `renderMarkdown` | booléen | `true` | Mode fenêtre : affiche une réponse terminée en Markdown — titres, listes, citations, séparateurs, tableaux (alignés ; une colonne trop large est coupée avec `…`), code délimité, **gras**, *italique*, `code`, liens (texte souligné, adresse en grisé). La réponse en cours d'écriture reste brute ; sa partie est rendue une fois terminée : au prochain appel d'outil du modèle, ou à la fin du tour. `false` garde toutes les réponses brutes. Le mode ligne, `-p` et un éditeur montrent toujours le texte tel quel ; `Ctrl-Y` copie le Markdown brut. | | |
| 25 | 26 | | `showSpeed` | booléen | `true` | La vitesse de génération du modèle, en tokens par seconde. Mode fenêtre : `⚡ ~58 tok/s` dans la barre d'état pendant qu'un appel au modèle est en cours (une estimation, mise à jour toutes les demi-secondes), puis `⚡ 59.9 tok/s`, la moyenne du tour, jusqu'au début de la réponse suivante. La moyenne du tour est le nombre de tokens divisé par le temps passé par le modèle à les générer : le temps des outils et celui de la lecture du prompt sont exclus. Source : les `timings` du serveur quand il en envoie (llama-server, MLX-Serve), sinon une mesure de mm entre le premier et le dernier token reçus. Éditeur (ACP) : chaque appel et chaque tour terminés vont dans le `_meta.mm` d'un `usage_update` (`tokensPerSecond`, `scope` `call` ou `turn`, `source` `server` ou `measured`), qu'un client qui ne connaît pas la clé ignore. Le mode ligne n'affiche rien. `false` le désactive. | |
| 26 | 27 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. Trois variables sont remplacées à chaque début de conversation (une nouvelle session, `/new`, une session reprise — pas avant chaque question, pour que le cache de prompt du serveur tienne) : `{{date}}` la date du jour, `AAAA-MM-JJ`, heure locale ; `{{cwd}}` le dossier où la conversation travaille (en ACP, celui de la session) ; `{{env.NAME}}` la variable NAME — non définie, remplacée par rien, avec un avertissement dans la bannière ; `{{config.NAME}}` la valeur NAME de la section `variables`. Un NAME qui ressemble à un secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) est une erreur de configuration : le prompt va au modèle, dans les sessions et les traces. Les espaces dans les accolades sont acceptés (`{{ date }}`). Tout autre `{{…}}` est laissé tel quel ; `\{{date}}` écrit `{{date}}`. Non remplacées dans AGENTS.md. Une session qui passe minuit garde sa date jusqu'à `/new`. | |
| 27 | 28 | | `variables` | dictionnaire nom → chaîne | aucune | Les valeurs propres au fichier pour le prompt système, utilisées comme `{{config.NAME}}`. Une valeur peut contenir `{{date}}`, `{{cwd}}` et `{{env.NAME}}` (remplacées, avec le même contrôle des secrets), pas une autre `{{config.…}}`. Noms : lettres, chiffres, `_` et `-`, sans commencer par un chiffre. Un `{{config.NAME}}` absent de la section est une erreur de configuration. Exemple : `variables: {project: "mini-me, a coding agent written in Go"}`, puis `You help with {{config.project}}.` dans `system`. | |
| @@ -22,6 +22,7 @@ Où `mm` cherche ce fichier : [Résolution du fichier de configuration](cli.md#r | |||
| 22 | | `displayHooks` | booléen | `false` | Affiche chaque hook exécuté : événement, commande, outil ou agent, décision, taille du contexte ajouté (jamais son texte). Après chaque réponse en mode ligne, en `-p` et dans la fenêtre ; sous forme d'appel d'outil terminé, un par hook, dans un éditeur. Voir [hooks](hooks.md#affichage). | | 22 | | `displayHooks` | booléen | `false` | Affiche chaque hook exécuté : événement, commande, outil ou agent, décision, taille du contexte ajouté (jamais son texte). Après chaque réponse en mode ligne, en `-p` et dans la fenêtre ; sous forme d'appel d'outil terminé, un par hook, dans un éditeur. Voir [hooks](hooks.md#affichage). | |
| 23 | | `showThinking` | booléen | `true` | Affiche ce qu'un modèle à raisonnement réfléchit avant de répondre. Seul l'affichage est optionnel : le raisonnement est toujours lu sur le fil, car c'est lui qui maintient le chien de garde en vie pendant que le modèle réfléchit. Voir [Modèles à raisonnement](../explanation/thinking-models.md). | | 23 | | `showThinking` | booléen | `true` | Affiche ce qu'un modèle à raisonnement réfléchit avant de répondre. Seul l'affichage est optionnel : le raisonnement est toujours lu sur le fil, car c'est lui qui maintient le chien de garde en vie pendant que le modèle réfléchit. Voir [Modèles à raisonnement](../explanation/thinking-models.md). | |
| 24 | | `showCompletionTime` | booléen | `true` | Mode fenêtre : afficher `⏱ <durée>` dans la barre d'état, qui défile pendant un tour ou un `/ask`, puis la durée finale jusqu'à la question suivante. `false` limite la barre d'état à ses compteurs. Voir [le mode fenêtre](cli.md). | | 24 | | `showCompletionTime` | booléen | `true` | Mode fenêtre : afficher `⏱ <durée>` dans la barre d'état, qui défile pendant un tour ou un `/ask`, puis la durée finale jusqu'à la question suivante. `false` limite la barre d'état à ses compteurs. Voir [le mode fenêtre](cli.md). | |
| 25 | +| `renderMarkdown` | booléen | `true` | Mode fenêtre : affiche une réponse terminée en Markdown — titres, listes, citations, séparateurs, tableaux (alignés ; une colonne trop large est coupée avec `…`), code délimité, **gras**, *italique*, `code`, liens (texte souligné, adresse en grisé). La réponse en cours d'écriture reste brute ; sa partie est rendue une fois terminée : au prochain appel d'outil du modèle, ou à la fin du tour. `false` garde toutes les réponses brutes. Le mode ligne, `-p` et un éditeur montrent toujours le texte tel quel ; `Ctrl-Y` copie le Markdown brut. | | ||
| 25 | | `showSpeed` | booléen | `true` | La vitesse de génération du modèle, en tokens par seconde. Mode fenêtre : `⚡ ~58 tok/s` dans la barre d'état pendant qu'un appel au modèle est en cours (une estimation, mise à jour toutes les demi-secondes), puis `⚡ 59.9 tok/s`, la moyenne du tour, jusqu'au début de la réponse suivante. La moyenne du tour est le nombre de tokens divisé par le temps passé par le modèle à les générer : le temps des outils et celui de la lecture du prompt sont exclus. Source : les `timings` du serveur quand il en envoie (llama-server, MLX-Serve), sinon une mesure de mm entre le premier et le dernier token reçus. Éditeur (ACP) : chaque appel et chaque tour terminés vont dans le `_meta.mm` d'un `usage_update` (`tokensPerSecond`, `scope` `call` ou `turn`, `source` `server` ou `measured`), qu'un client qui ne connaît pas la clé ignore. Le mode ligne n'affiche rien. `false` le désactive. | | 26 | | `showSpeed` | booléen | `true` | La vitesse de génération du modèle, en tokens par seconde. Mode fenêtre : `⚡ ~58 tok/s` dans la barre d'état pendant qu'un appel au modèle est en cours (une estimation, mise à jour toutes les demi-secondes), puis `⚡ 59.9 tok/s`, la moyenne du tour, jusqu'au début de la réponse suivante. La moyenne du tour est le nombre de tokens divisé par le temps passé par le modèle à les générer : le temps des outils et celui de la lecture du prompt sont exclus. Source : les `timings` du serveur quand il en envoie (llama-server, MLX-Serve), sinon une mesure de mm entre le premier et le dernier token reçus. Éditeur (ACP) : chaque appel et chaque tour terminés vont dans le `_meta.mm` d'un `usage_update` (`tokensPerSecond`, `scope` `call` ou `turn`, `source` `server` ou `measured`), qu'un client qui ne connaît pas la clé ignore. Le mode ligne n'affiche rien. `false` le désactive. | |
| 26 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. Trois variables sont remplacées à chaque début de conversation (une nouvelle session, `/new`, une session reprise — pas avant chaque question, pour que le cache de prompt du serveur tienne) : `{{date}}` la date du jour, `AAAA-MM-JJ`, heure locale ; `{{cwd}}` le dossier où la conversation travaille (en ACP, celui de la session) ; `{{env.NAME}}` la variable NAME — non définie, remplacée par rien, avec un avertissement dans la bannière ; `{{config.NAME}}` la valeur NAME de la section `variables`. Un NAME qui ressemble à un secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) est une erreur de configuration : le prompt va au modèle, dans les sessions et les traces. Les espaces dans les accolades sont acceptés (`{{ date }}`). Tout autre `{{…}}` est laissé tel quel ; `\{{date}}` écrit `{{date}}`. Non remplacées dans AGENTS.md. Une session qui passe minuit garde sa date jusqu'à `/new`. | | 27 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. Trois variables sont remplacées à chaque début de conversation (une nouvelle session, `/new`, une session reprise — pas avant chaque question, pour que le cache de prompt du serveur tienne) : `{{date}}` la date du jour, `AAAA-MM-JJ`, heure locale ; `{{cwd}}` le dossier où la conversation travaille (en ACP, celui de la session) ; `{{env.NAME}}` la variable NAME — non définie, remplacée par rien, avec un avertissement dans la bannière ; `{{config.NAME}}` la valeur NAME de la section `variables`. Un NAME qui ressemble à un secret (`…_KEY`, `…_TOKEN`, `…_SECRET`, `…PASSWORD…`, `…CREDENTIALS…`) est une erreur de configuration : le prompt va au modèle, dans les sessions et les traces. Les espaces dans les accolades sont acceptés (`{{ date }}`). Tout autre `{{…}}` est laissé tel quel ; `\{{date}}` écrit `{{date}}`. Non remplacées dans AGENTS.md. Une session qui passe minuit garde sa date jusqu'à `/new`. | |
| 27 | | `variables` | dictionnaire nom → chaîne | aucune | Les valeurs propres au fichier pour le prompt système, utilisées comme `{{config.NAME}}`. Une valeur peut contenir `{{date}}`, `{{cwd}}` et `{{env.NAME}}` (remplacées, avec le même contrôle des secrets), pas une autre `{{config.…}}`. Noms : lettres, chiffres, `_` et `-`, sans commencer par un chiffre. Un `{{config.NAME}}` absent de la section est une erreur de configuration. Exemple : `variables: {project: "mini-me, a coding agent written in Go"}`, puis `You help with {{config.project}}.` dans `system`. | | 28 | | `variables` | dictionnaire nom → chaîne | aucune | Les valeurs propres au fichier pour le prompt système, utilisées comme `{{config.NAME}}`. Une valeur peut contenir `{{date}}`, `{{cwd}}` et `{{env.NAME}}` (remplacées, avec le même contrôle des secrets), pas une autre `{{config.…}}`. Noms : lettres, chiffres, `_` et `-`, sans commencer par un chiffre. Un `{{config.NAME}}` absent de la section est une erreur de configuration. Exemple : `variables: {project: "mini-me, a coding agent written in Go"}`, puis `You help with {{config.project}}.` dans `system`. | |
modified
internal/config/config.go +16 -8 | @@ -96,6 +96,12 @@ type Config struct { | ||
| 96 | 96 | // 158). Display only: nothing else depends on it. |
| 97 | 97 | ShowCompletionTime bool `yaml:"showCompletionTime"` |
| 98 | 98 | |
| 99 | + // RenderMarkdown: the window draws a finished answer as Markdown — | |
| 100 | + // headings, lists, tables, bold, code… (ticket 274) — while the answer | |
| 101 | + // being written stays raw. Window only: the line mode, -p and an editor | |
| 102 | + // show the text as it is. `false` keeps every answer raw. | |
| 103 | + RenderMarkdown bool `yaml:"renderMarkdown"` | |
| 104 | + | |
| 99 | 105 | // AutoPull: at start-up, download the models this mm will use and the |
| 100 | 106 | // server does not have yet — its own, its mmConfigs agents', its routing |
| 101 | 107 | // deciders' — showing the progress (ticket 61). Off by default: a |
| @@ -870,14 +876,16 @@ var Cfg = Config{ | ||
| 870 | 876 | // On by default: asked for (ticket 158); `showCompletionTime: false` |
| 871 | 877 | // keeps the status bar to its counters. |
| 872 | 878 | ShowCompletionTime: true, |
| 873 | - SkillsDir: "skills", | |
| 874 | - BashTool: true, | |
| 875 | - EditTools: true, | |
| 876 | - PlanTool: true, | |
| 877 | - AskUserTool: true, | |
| 878 | - UnloadModels: true, | |
| 879 | - UnloadOnExit: true, | |
| 880 | - ShowSpeed: true, | |
| 879 | + // On by default (ticket 274); `renderMarkdown: false` shows raw text. | |
| 880 | + RenderMarkdown: true, | |
| 881 | + SkillsDir: "skills", | |
| 882 | + BashTool: true, | |
| 883 | + EditTools: true, | |
| 884 | + PlanTool: true, | |
| 885 | + AskUserTool: true, | |
| 886 | + UnloadModels: true, | |
| 887 | + UnloadOnExit: true, | |
| 888 | + ShowSpeed: true, | |
| 881 | 889 | // FetchContentTool stays false (the zero value): see its field comment. |
| 882 | 890 | System: `You are a coding agent working in a terminal. |
| 883 | 891 | You have a "bash" tool to run shell commands. |
| @@ -96,6 +96,12 @@ type Config struct { | |||
| 96 | // 158). Display only: nothing else depends on it. | 96 | // 158). Display only: nothing else depends on it. |
| 97 | ShowCompletionTime bool `yaml:"showCompletionTime"` | 97 | ShowCompletionTime bool `yaml:"showCompletionTime"` |
| 98 | 98 | ||
| 99 | + // RenderMarkdown: the window draws a finished answer as Markdown — | ||
| 100 | + // headings, lists, tables, bold, code… (ticket 274) — while the answer | ||
| 101 | + // being written stays raw. Window only: the line mode, -p and an editor | ||
| 102 | + // show the text as it is. `false` keeps every answer raw. | ||
| 103 | + RenderMarkdown bool `yaml:"renderMarkdown"` | ||
| 104 | + | ||
| 99 | // AutoPull: at start-up, download the models this mm will use and the | 105 | // AutoPull: at start-up, download the models this mm will use and the |
| 100 | // server does not have yet — its own, its mmConfigs agents', its routing | 106 | // server does not have yet — its own, its mmConfigs agents', its routing |
| 101 | // deciders' — showing the progress (ticket 61). Off by default: a | 107 | // deciders' — showing the progress (ticket 61). Off by default: a |
| @@ -870,14 +876,16 @@ var Cfg = Config{ | |||
| 870 | // On by default: asked for (ticket 158); `showCompletionTime: false` | 876 | // On by default: asked for (ticket 158); `showCompletionTime: false` |
| 871 | // keeps the status bar to its counters. | 877 | // keeps the status bar to its counters. |
| 872 | ShowCompletionTime: true, | 878 | ShowCompletionTime: true, |
| 873 | - SkillsDir: "skills", | 879 | + // On by default (ticket 274); `renderMarkdown: false` shows raw text. |
| 874 | - BashTool: true, | 880 | + RenderMarkdown: true, |
| 875 | - EditTools: true, | 881 | + SkillsDir: "skills", |
| 876 | - PlanTool: true, | 882 | + BashTool: true, |
| 877 | - AskUserTool: true, | 883 | + EditTools: true, |
| 878 | - UnloadModels: true, | 884 | + PlanTool: true, |
| 879 | - UnloadOnExit: true, | 885 | + AskUserTool: true, |
| 880 | - ShowSpeed: true, | 886 | + UnloadModels: true, |
| 887 | + UnloadOnExit: true, | ||
| 888 | + ShowSpeed: true, | ||
| 881 | // FetchContentTool stays false (the zero value): see its field comment. | 889 | // FetchContentTool stays false (the zero value): see its field comment. |
| 882 | System: `You are a coding agent working in a terminal. | 890 | System: `You are a coding agent working in a terminal. |
| 883 | You have a "bash" tool to run shell commands. | 891 | You have a "bash" tool to run shell commands. |
modified
internal/config/metaprompts_test.go +19 -0 | @@ -43,3 +43,22 @@ func TestMetaPromptsConfig(t *testing.T) { | ||
| 43 | 43 | } |
| 44 | 44 | } |
| 45 | 45 | } |
| 46 | + | |
| 47 | +// renderMarkdown (ticket 274): on by default, read from the file. | |
| 48 | +func TestRenderMarkdownKey(t *testing.T) { | |
| 49 | + defaults := Cfg | |
| 50 | + t.Cleanup(func() { Cfg = defaults }) | |
| 51 | + if !Cfg.RenderMarkdown { | |
| 52 | + t.Fatal("default must be true") | |
| 53 | + } | |
| 54 | + path := filepath.Join(t.TempDir(), "agent.yaml") | |
| 55 | + if err := os.WriteFile(path, []byte("renderMarkdown: false\n"), 0o644); err != nil { | |
| 56 | + t.Fatal(err) | |
| 57 | + } | |
| 58 | + if _, err := Load(path); err != nil { | |
| 59 | + t.Fatal(err) | |
| 60 | + } | |
| 61 | + if Cfg.RenderMarkdown { | |
| 62 | + t.Error("renderMarkdown: false not read") | |
| 63 | + } | |
| 64 | +} | |
| @@ -43,3 +43,22 @@ func TestMetaPromptsConfig(t *testing.T) { | |||
| 43 | } | 43 | } |
| 44 | } | 44 | } |
| 45 | } | 45 | } |
| 46 | + | ||
| 47 | +// renderMarkdown (ticket 274): on by default, read from the file. | ||
| 48 | +func TestRenderMarkdownKey(t *testing.T) { | ||
| 49 | + defaults := Cfg | ||
| 50 | + t.Cleanup(func() { Cfg = defaults }) | ||
| 51 | + if !Cfg.RenderMarkdown { | ||
| 52 | + t.Fatal("default must be true") | ||
| 53 | + } | ||
| 54 | + path := filepath.Join(t.TempDir(), "agent.yaml") | ||
| 55 | + if err := os.WriteFile(path, []byte("renderMarkdown: false\n"), 0o644); err != nil { | ||
| 56 | + t.Fatal(err) | ||
| 57 | + } | ||
| 58 | + if _, err := Load(path); err != nil { | ||
| 59 | + t.Fatal(err) | ||
| 60 | + } | ||
| 61 | + if Cfg.RenderMarkdown { | ||
| 62 | + t.Error("renderMarkdown: false not read") | ||
| 63 | + } | ||
| 64 | +} | ||
modified
internal/tui/draw.go +20 -0 | @@ -60,6 +60,10 @@ func (v *View) drawTranscript(p painter) { | ||
| 60 | 60 | if at >= len(lines) { |
| 61 | 61 | break |
| 62 | 62 | } |
| 63 | + if spans := lines[at].Spans; len(spans) > 0 { | |
| 64 | + drawSpans(p, 1, row, width, spans) | |
| 65 | + continue | |
| 66 | + } | |
| 63 | 67 | p.textLimited(1, row, width, lines[at].Text, styleOf(lines[at].Style)) |
| 64 | 68 | } |
| 65 | 69 | v.drawScrollBar(p, height, len(lines)) |
| @@ -251,3 +255,19 @@ func pickerFirst(n, rows, selected int) int { | ||
| 251 | 255 | selected = min(selected, n-1) |
| 252 | 256 | return max(0, selected-rows+1) |
| 253 | 257 | } |
| 258 | + | |
| 259 | +// drawSpans draws a rendered line run by run, each in its style, cut at | |
| 260 | +// width with an ellipsis as textLimited does. | |
| 261 | +func drawSpans(p painter, x, y, width int, spans []Span) { | |
| 262 | + left := width | |
| 263 | + for i, s := range spans { | |
| 264 | + r := []rune(s.Text) | |
| 265 | + last := i == len(spans)-1 | |
| 266 | + if len(r) > left || (len(r) == left && !last && len([]rune(spansText(spans[i+1:]))) > 0) { | |
| 267 | + p.text(x, y, clip(s.Text, left), spanStyle(s)) | |
| 268 | + return | |
| 269 | + } | |
| 270 | + x = p.text(x, y, s.Text, spanStyle(s)) | |
| 271 | + left -= len(r) | |
| 272 | + } | |
| 273 | +} | |
| @@ -60,6 +60,10 @@ func (v *View) drawTranscript(p painter) { | |||
| 60 | if at >= len(lines) { | 60 | if at >= len(lines) { |
| 61 | break | 61 | break |
| 62 | } | 62 | } |
| 63 | + if spans := lines[at].Spans; len(spans) > 0 { | ||
| 64 | + drawSpans(p, 1, row, width, spans) | ||
| 65 | + continue | ||
| 66 | + } | ||
| 63 | p.textLimited(1, row, width, lines[at].Text, styleOf(lines[at].Style)) | 67 | p.textLimited(1, row, width, lines[at].Text, styleOf(lines[at].Style)) |
| 64 | } | 68 | } |
| 65 | v.drawScrollBar(p, height, len(lines)) | 69 | v.drawScrollBar(p, height, len(lines)) |
| @@ -251,3 +255,19 @@ func pickerFirst(n, rows, selected int) int { | |||
| 251 | selected = min(selected, n-1) | 255 | selected = min(selected, n-1) |
| 252 | return max(0, selected-rows+1) | 256 | return max(0, selected-rows+1) |
| 253 | } | 257 | } |
| 258 | + | ||
| 259 | +// drawSpans draws a rendered line run by run, each in its style, cut at | ||
| 260 | +// width with an ellipsis as textLimited does. | ||
| 261 | +func drawSpans(p painter, x, y, width int, spans []Span) { | ||
| 262 | + left := width | ||
| 263 | + for i, s := range spans { | ||
| 264 | + r := []rune(s.Text) | ||
| 265 | + last := i == len(spans)-1 | ||
| 266 | + if len(r) > left || (len(r) == left && !last && len([]rune(spansText(spans[i+1:]))) > 0) { | ||
| 267 | + p.text(x, y, clip(s.Text, left), spanStyle(s)) | ||
| 268 | + return | ||
| 269 | + } | ||
| 270 | + x = p.text(x, y, s.Text, spanStyle(s)) | ||
| 271 | + left -= len(r) | ||
| 272 | + } | ||
| 273 | +} | ||
added
internal/tui/markdown.go +563 -0 | new file mode 100644 | ||
| @@ -0,0 +1,563 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strconv" | |
| 5 | + "strings" | |
| 6 | + "unicode" | |
| 7 | +) | |
| 8 | + | |
| 9 | +// Markdown in the window (experiment, branch experiment/tui-markdown): an | |
| 10 | +// answer is shown as raw text while it streams, and rendered once its entry | |
| 11 | +// is closed — the model's next tool call, or the end of the turn. A closed | |
| 12 | +// entry never changes again, so it is parsed once and cached (mdCache); the | |
| 13 | +// entry being written is laid out raw, as before, so nothing flickers while | |
| 14 | +// a `**` waits for its other half. | |
| 15 | +// | |
| 16 | +// A hand-written subset, the one models actually write: | |
| 17 | +// | |
| 18 | +// blocks # headings, - * + and 1. lists (nested, [ ] [x] tasks), | |
| 19 | +// > quotes, --- rules, ``` fenced code, | tables | | |
| 20 | +// inline **bold**, *italic* / _italic_, ***both***, ~~struck~~, | |
| 21 | +// `code`, [text](url), <https://…>, \ escapes | |
| 22 | +// | |
| 23 | +// Anything else — HTML, footnotes, reference links — stays as written. An | |
| 24 | +// unclosed marker is literal text. The source's own line breaks are kept, | |
| 25 | +// as the raw view keeps them: models break lines on purpose. | |
| 26 | + | |
| 27 | +// attr is what a span adds on top of its line's style. | |
| 28 | +type attr uint8 | |
| 29 | + | |
| 30 | +const ( | |
| 31 | + attrBold attr = 1 << iota | |
| 32 | + attrItalic | |
| 33 | + attrStrike | |
| 34 | + attrUnderline | |
| 35 | + attrDim | |
| 36 | +) | |
| 37 | + | |
| 38 | +// Span is a run of a line drawn in one style. | |
| 39 | +type Span struct { | |
| 40 | + Text string | |
| 41 | + Style styleKind | |
| 42 | + Attr attr | |
| 43 | +} | |
| 44 | + | |
| 45 | +// spansText is the plain text of spans, what Line.Text carries beside them. | |
| 46 | +func spansText(spans []Span) string { | |
| 47 | + var b strings.Builder | |
| 48 | + for _, s := range spans { | |
| 49 | + b.WriteString(s.Text) | |
| 50 | + } | |
| 51 | + return b.String() | |
| 52 | +} | |
| 53 | + | |
| 54 | +// spanLine is a Line drawn from spans; its Text is their plain text. | |
| 55 | +func spanLine(spans []Span) Line { | |
| 56 | + return Line{Text: spansText(spans), Spans: spans} | |
| 57 | +} | |
| 58 | + | |
| 59 | +// --- inline ------------------------------------------------------------------ | |
| 60 | + | |
| 61 | +// inline parses one line of Markdown text into spans, all at base style. | |
| 62 | +// | |
| 63 | +// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | |
| 64 | +func inline(text string, base styleKind) []Span { | |
| 65 | + var out []Span | |
| 66 | + var plain strings.Builder | |
| 67 | + flush := func() { | |
| 68 | + if plain.Len() > 0 { | |
| 69 | + out = append(out, Span{Text: plain.String(), Style: base}) | |
| 70 | + plain.Reset() | |
| 71 | + } | |
| 72 | + } | |
| 73 | + add := func(spans ...Span) { | |
| 74 | + flush() | |
| 75 | + out = append(out, spans...) | |
| 76 | + } | |
| 77 | + r := []rune(text) | |
| 78 | + for i := 0; i < len(r); { | |
| 79 | + c := r[i] | |
| 80 | + switch { | |
| 81 | + case c == '\\' && i+1 < len(r) && isMarkdownPunct(r[i+1]): | |
| 82 | + plain.WriteRune(r[i+1]) | |
| 83 | + i += 2 | |
| 84 | + continue | |
| 85 | + case c == '`': | |
| 86 | + if end, n := closingTicks(r, i); end > 0 { | |
| 87 | + code := strings.TrimSpace(string(r[i+n : end])) | |
| 88 | + add(Span{Text: code, Style: styleCode}) | |
| 89 | + i = end + n | |
| 90 | + continue | |
| 91 | + } | |
| 92 | + case c == '[': | |
| 93 | + if label, url, next, ok := link(r, i); ok { | |
| 94 | + spans := inline(label, base) | |
| 95 | + for k := range spans { | |
| 96 | + spans[k].Attr |= attrUnderline | |
| 97 | + } | |
| 98 | + if url != "" && url != label { | |
| 99 | + spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | |
| 100 | + } | |
| 101 | + add(spans...) | |
| 102 | + i = next | |
| 103 | + continue | |
| 104 | + } | |
| 105 | + case c == '<': | |
| 106 | + if end := strings.IndexRune(string(r[i+1:]), '>'); end > 0 { | |
| 107 | + inner := string(r[i+1 : i+1+end]) | |
| 108 | + if strings.HasPrefix(inner, "http://") || strings.HasPrefix(inner, "https://") { | |
| 109 | + add(Span{Text: inner, Style: base, Attr: attrUnderline}) | |
| 110 | + i += end + 2 | |
| 111 | + continue | |
| 112 | + } | |
| 113 | + } | |
| 114 | + case c == '*' || c == '_' || c == '~': | |
| 115 | + if spans, next, ok := emphasis(r, i, base); ok { | |
| 116 | + add(spans...) | |
| 117 | + i = next | |
| 118 | + continue | |
| 119 | + } | |
| 120 | + } | |
| 121 | + plain.WriteRune(c) | |
| 122 | + i++ | |
| 123 | + } | |
| 124 | + flush() | |
| 125 | + return out | |
| 126 | +} | |
| 127 | + | |
| 128 | +// isMarkdownPunct is what a backslash may escape. | |
| 129 | +func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | |
| 130 | + | |
| 131 | +// closingTicks finds the run of backticks closing the one at i: the index of | |
| 132 | +// the closing run and the run's length, or 0 when there is none. | |
| 133 | +func closingTicks(r []rune, i int) (int, int) { | |
| 134 | + n := 0 | |
| 135 | + for i+n < len(r) && r[i+n] == '`' { | |
| 136 | + n++ | |
| 137 | + } | |
| 138 | + for j := i + n; j < len(r); j++ { | |
| 139 | + if r[j] != '`' { | |
| 140 | + continue | |
| 141 | + } | |
| 142 | + m := 0 | |
| 143 | + for j+m < len(r) && r[j+m] == '`' { | |
| 144 | + m++ | |
| 145 | + } | |
| 146 | + if m == n { | |
| 147 | + return j, n | |
| 148 | + } | |
| 149 | + j += m - 1 | |
| 150 | + } | |
| 151 | + return 0, n | |
| 152 | +} | |
| 153 | + | |
| 154 | +// link reads [label](url) at i. | |
| 155 | +func link(r []rune, i int) (label, url string, next int, ok bool) { | |
| 156 | + depth := 0 | |
| 157 | + for j := i; j < len(r); j++ { | |
| 158 | + switch r[j] { | |
| 159 | + case '[': | |
| 160 | + depth++ | |
| 161 | + case ']': | |
| 162 | + depth-- | |
| 163 | + if depth == 0 { | |
| 164 | + if j+1 >= len(r) || r[j+1] != '(' { | |
| 165 | + return "", "", 0, false | |
| 166 | + } | |
| 167 | + end := strings.IndexRune(string(r[j+2:]), ')') | |
| 168 | + if end < 0 { | |
| 169 | + return "", "", 0, false | |
| 170 | + } | |
| 171 | + url = strings.TrimSpace(string(r[j+2 : j+2+end])) | |
| 172 | + if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | |
| 173 | + url = url[:k] | |
| 174 | + } | |
| 175 | + return string(r[i+1 : j]), url, j + 3 + end, true | |
| 176 | + } | |
| 177 | + } | |
| 178 | + } | |
| 179 | + return "", "", 0, false | |
| 180 | +} | |
| 181 | + | |
| 182 | +// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | |
| 183 | +// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | |
| 184 | +// neither is a marker followed by a space ("2 * 3"). | |
| 185 | +func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | |
| 186 | + c := r[i] | |
| 187 | + n := 0 | |
| 188 | + for i+n < len(r) && r[i+n] == c && n < 3 { | |
| 189 | + n++ | |
| 190 | + } | |
| 191 | + if c == '~' && n != 2 { | |
| 192 | + return nil, 0, false | |
| 193 | + } | |
| 194 | + if c == '_' && i > 0 && isWordRune(r[i-1]) { | |
| 195 | + return nil, 0, false | |
| 196 | + } | |
| 197 | + open := i + n | |
| 198 | + if open >= len(r) || unicode.IsSpace(r[open]) { | |
| 199 | + return nil, 0, false | |
| 200 | + } | |
| 201 | + marker := strings.Repeat(string(c), n) | |
| 202 | + rest := string(r[open:]) | |
| 203 | + for from := 0; ; { | |
| 204 | + at := strings.Index(rest[from:], marker) | |
| 205 | + if at < 0 { | |
| 206 | + return nil, 0, false | |
| 207 | + } | |
| 208 | + at += from | |
| 209 | + inner := []rune(rest[:at]) | |
| 210 | + after := open + len(inner) + n | |
| 211 | + closes := len(inner) > 0 && !unicode.IsSpace(inner[len(inner)-1]) && | |
| 212 | + (after >= len(r) || r[after] != c) && | |
| 213 | + (c != '_' || after >= len(r) || !isWordRune(r[after])) | |
| 214 | + if closes { | |
| 215 | + var a attr | |
| 216 | + switch { | |
| 217 | + case c == '~': | |
| 218 | + a = attrStrike | |
| 219 | + case n == 1: | |
| 220 | + a = attrItalic | |
| 221 | + case n == 2: | |
| 222 | + a = attrBold | |
| 223 | + default: | |
| 224 | + a = attrBold | attrItalic | |
| 225 | + } | |
| 226 | + spans := inline(string(inner), base) | |
| 227 | + for k := range spans { | |
| 228 | + spans[k].Attr |= a | |
| 229 | + } | |
| 230 | + return spans, after, true | |
| 231 | + } | |
| 232 | + from = at + len(marker) | |
| 233 | + } | |
| 234 | +} | |
| 235 | + | |
| 236 | +func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | |
| 237 | + | |
| 238 | +// --- wrapping spans -------------------------------------------------------------- | |
| 239 | + | |
| 240 | +// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | |
| 241 | +// does for plain text. first goes before the first line, rest before the | |
| 242 | +// others — a list item's bullet, then its hanging indent. | |
| 243 | +func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | |
| 244 | + type cell struct { | |
| 245 | + r rune | |
| 246 | + at int // index of the span it came from | |
| 247 | + } | |
| 248 | + var cells []cell | |
| 249 | + for k, s := range spans { | |
| 250 | + for _, r := range s.Text { | |
| 251 | + cells = append(cells, cell{r, k}) | |
| 252 | + } | |
| 253 | + } | |
| 254 | + build := func(prefix []Span, part []cell) []Span { | |
| 255 | + line := append([]Span(nil), prefix...) | |
| 256 | + for i := 0; i < len(part); { | |
| 257 | + j := i | |
| 258 | + for j < len(part) && part[j].at == part[i].at { | |
| 259 | + j++ | |
| 260 | + } | |
| 261 | + var b strings.Builder | |
| 262 | + for _, c := range part[i:j] { | |
| 263 | + b.WriteRune(c.r) | |
| 264 | + } | |
| 265 | + src := spans[part[i].at] | |
| 266 | + line = append(line, Span{Text: b.String(), Style: src.Style, Attr: src.Attr}) | |
| 267 | + i = j | |
| 268 | + } | |
| 269 | + return line | |
| 270 | + } | |
| 271 | + var out [][]Span | |
| 272 | + prefix := first | |
| 273 | + for { | |
| 274 | + room := max(width-len([]rune(spansText(prefix))), 1) | |
| 275 | + if len(cells) <= room { | |
| 276 | + return append(out, build(prefix, cells)) | |
| 277 | + } | |
| 278 | + runes := make([]rune, len(cells)) | |
| 279 | + for i, c := range cells { | |
| 280 | + runes[i] = c.r | |
| 281 | + } | |
| 282 | + at := breakPoint(runes, room) | |
| 283 | + end := at | |
| 284 | + for end > 0 && cells[end-1].r == ' ' { | |
| 285 | + end-- | |
| 286 | + } | |
| 287 | + out = append(out, build(prefix, cells[:end])) | |
| 288 | + cells = cells[at:] | |
| 289 | + for len(cells) > 0 && cells[0].r == ' ' { | |
| 290 | + cells = cells[1:] | |
| 291 | + } | |
| 292 | + prefix = rest | |
| 293 | + if len(cells) == 0 { | |
| 294 | + return out | |
| 295 | + } | |
| 296 | + } | |
| 297 | +} | |
| 298 | + | |
| 299 | +// --- blocks ------------------------------------------------------------------ | |
| 300 | + | |
| 301 | +// markdown lays a closed answer out at width: blocks, then inline spans, | |
| 302 | +// wrapped. Every line is indented like the raw body. | |
| 303 | +func markdown(text string, width int) []Line { | |
| 304 | + src := strings.Split(strings.TrimRight(text, "\n"), "\n") | |
| 305 | + var out []Line | |
| 306 | + emit := func(spans []Span) { out = append(out, spanLine(append([]Span{{Text: pad}}, spans...))) } | |
| 307 | + wrapped := func(spans []Span, first, rest []Span) { | |
| 308 | + for _, l := range wrapSpans(spans, max(width-indent, 1), first, rest) { | |
| 309 | + emit(l) | |
| 310 | + } | |
| 311 | + } | |
| 312 | + blank := false | |
| 313 | + for i := 0; i < len(src); i++ { | |
| 314 | + line := src[i] | |
| 315 | + trim := strings.TrimSpace(line) | |
| 316 | + if trim == "" { | |
| 317 | + if !blank && len(out) > 0 { | |
| 318 | + out = append(out, Line{}) | |
| 319 | + } | |
| 320 | + blank = true | |
| 321 | + continue | |
| 322 | + } | |
| 323 | + blank = false | |
| 324 | + switch { | |
| 325 | + case strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~"): | |
| 326 | + fence := trim[:3] | |
| 327 | + lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])) | |
| 328 | + if lang != "" { | |
| 329 | + emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) | |
| 330 | + } | |
| 331 | + for i++; i < len(src) && !strings.HasPrefix(strings.TrimSpace(src[i]), fence); i++ { | |
| 332 | + out = append(out, Line{Text: pad + " " + src[i], Style: styleCode}) | |
| 333 | + } | |
| 334 | + case heading(trim) > 0: | |
| 335 | + level := heading(trim) | |
| 336 | + spans := inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading) | |
| 337 | + for k := range spans { | |
| 338 | + spans[k].Attr |= attrBold | |
| 339 | + if level == 1 { | |
| 340 | + spans[k].Attr |= attrUnderline | |
| 341 | + } | |
| 342 | + } | |
| 343 | + wrapped(spans, nil, nil) | |
| 344 | + case isRule(trim): | |
| 345 | + emit([]Span{{Text: strings.Repeat("─", max(min(width-indent, 60), 1)), Style: styleRule}}) | |
| 346 | + case strings.HasPrefix(trim, ">"): | |
| 347 | + quote := strings.TrimSpace(strings.TrimPrefix(trim, ">")) | |
| 348 | + bar := []Span{{Text: "│ ", Style: styleQuote}} | |
| 349 | + wrapped(inline(quote, styleQuote), bar, bar) | |
| 350 | + case isTableStart(src, i): | |
| 351 | + var rows []string | |
| 352 | + for ; i < len(src) && strings.HasPrefix(strings.TrimSpace(src[i]), "|"); i++ { | |
| 353 | + rows = append(rows, strings.TrimSpace(src[i])) | |
| 354 | + } | |
| 355 | + i-- | |
| 356 | + for _, l := range table(rows, max(width-indent, 1)) { | |
| 357 | + emit(l) | |
| 358 | + } | |
| 359 | + default: | |
| 360 | + if bullet, body, depth, ok := listItem(line); ok { | |
| 361 | + lead := strings.Repeat(" ", depth) | |
| 362 | + first := []Span{{Text: lead + bullet, Style: styleBullet}} | |
| 363 | + rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | |
| 364 | + wrapped(inline(body, styleBody), first, rest) | |
| 365 | + continue | |
| 366 | + } | |
| 367 | + wrapped(inline(line, styleBody), nil, nil) | |
| 368 | + } | |
| 369 | + } | |
| 370 | + return out | |
| 371 | +} | |
| 372 | + | |
| 373 | +// heading is the level of an ATX heading line ("## Title" → 2), 0 if none. | |
| 374 | +func heading(trim string) int { | |
| 375 | + n := 0 | |
| 376 | + for n < len(trim) && trim[n] == '#' { | |
| 377 | + n++ | |
| 378 | + } | |
| 379 | + if n == 0 || n > 6 || (n < len(trim) && trim[n] != ' ') || n == len(trim) { | |
| 380 | + return 0 | |
| 381 | + } | |
| 382 | + return n | |
| 383 | +} | |
| 384 | + | |
| 385 | +// isRule reports a thematic break: three or more of one of - * _, spaces | |
| 386 | +// allowed between them. | |
| 387 | +func isRule(trim string) bool { | |
| 388 | + s := strings.ReplaceAll(trim, " ", "") | |
| 389 | + if len(s) < 3 { | |
| 390 | + return false | |
| 391 | + } | |
| 392 | + c := s[0] | |
| 393 | + return (c == '-' || c == '*' || c == '_') && strings.Count(s, string(c)) == len(s) | |
| 394 | +} | |
| 395 | + | |
| 396 | +// listItem reads a bullet or numbered list line: the bullet as shown, the | |
| 397 | +// text, and the nesting depth (two leading spaces a level). | |
| 398 | +func listItem(line string) (bullet, body string, depth int, ok bool) { | |
| 399 | + lead := len(line) - len(strings.TrimLeft(line, " \t")) | |
| 400 | + trim := line[lead:] | |
| 401 | + depth = min(lead/2, 6) | |
| 402 | + if len(trim) >= 2 && strings.ContainsRune("-*+", rune(trim[0])) && trim[1] == ' ' { | |
| 403 | + body = trim[2:] | |
| 404 | + switch { | |
| 405 | + case strings.HasPrefix(body, "[ ] "): | |
| 406 | + return "☐ ", body[4:], depth, true | |
| 407 | + case strings.HasPrefix(body, "[x] "), strings.HasPrefix(body, "[X] "): | |
| 408 | + return "☑ ", body[4:], depth, true | |
| 409 | + } | |
| 410 | + return "• ", body, depth, true | |
| 411 | + } | |
| 412 | + n := 0 | |
| 413 | + for n < len(trim) && trim[n] >= '0' && trim[n] <= '9' { | |
| 414 | + n++ | |
| 415 | + } | |
| 416 | + if n > 0 && n <= 9 && n+1 < len(trim) && (trim[n] == '.' || trim[n] == ')') && trim[n+1] == ' ' { | |
| 417 | + num, _ := strconv.Atoi(trim[:n]) | |
| 418 | + return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | |
| 419 | + } | |
| 420 | + return "", "", 0, false | |
| 421 | +} | |
| 422 | + | |
| 423 | +// isTableStart reports a table: a `|` row followed by a |---|---| line. | |
| 424 | +func isTableStart(src []string, i int) bool { | |
| 425 | + if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | |
| 426 | + return false | |
| 427 | + } | |
| 428 | + sep := strings.TrimSpace(src[i+1]) | |
| 429 | + return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | |
| 430 | +} | |
| 431 | + | |
| 432 | +// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | |
| 433 | +func cells(row string) []string { | |
| 434 | + row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | |
| 435 | + row = strings.ReplaceAll(row, `\|`, "\x00") | |
| 436 | + var out []string | |
| 437 | + for _, c := range strings.Split(row, "|") { | |
| 438 | + out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | |
| 439 | + } | |
| 440 | + return out | |
| 441 | +} | |
| 442 | + | |
| 443 | +// table lays a table out: columns as wide as their widest cell, the header | |
| 444 | +// bold, a ─┼─ line under it. A table wider than width has its widest columns | |
| 445 | +// narrowed and their cells cut with "…" — a table is read across, wrapping | |
| 446 | +// its cells would break that. | |
| 447 | +func table(rows []string, width int) [][]Span { | |
| 448 | + var grid [][][]Span | |
| 449 | + cols := 0 | |
| 450 | + for k, r := range rows { | |
| 451 | + if k == 1 { // the |---| line | |
| 452 | + continue | |
| 453 | + } | |
| 454 | + var row [][]Span | |
| 455 | + for _, c := range cells(r) { | |
| 456 | + row = append(row, inline(c, styleBody)) | |
| 457 | + } | |
| 458 | + cols = max(cols, len(row)) | |
| 459 | + grid = append(grid, row) | |
| 460 | + } | |
| 461 | + widths := make([]int, cols) | |
| 462 | + for _, row := range grid { | |
| 463 | + for c, cell := range row { | |
| 464 | + widths[c] = max(widths[c], len([]rune(spansText(cell)))) | |
| 465 | + } | |
| 466 | + } | |
| 467 | + for total(widths) > width { | |
| 468 | + widest := 0 | |
| 469 | + for c := range widths { | |
| 470 | + if widths[c] > widths[widest] { | |
| 471 | + widest = c | |
| 472 | + } | |
| 473 | + } | |
| 474 | + if widths[widest] <= 3 { | |
| 475 | + break | |
| 476 | + } | |
| 477 | + widths[widest]-- | |
| 478 | + } | |
| 479 | + var out [][]Span | |
| 480 | + for r, row := range grid { | |
| 481 | + var line []Span | |
| 482 | + for c := 0; c < cols; c++ { | |
| 483 | + if c > 0 { | |
| 484 | + line = append(line, Span{Text: " │ ", Style: styleRule}) | |
| 485 | + } | |
| 486 | + var cell []Span | |
| 487 | + if c < len(row) { | |
| 488 | + cell = row[c] | |
| 489 | + } | |
| 490 | + cell = clipSpans(cell, widths[c]) | |
| 491 | + if r == 0 { | |
| 492 | + for k := range cell { | |
| 493 | + cell[k].Attr |= attrBold | |
| 494 | + } | |
| 495 | + } | |
| 496 | + line = append(line, cell...) | |
| 497 | + if fill := widths[c] - len([]rune(spansText(cell))); fill > 0 { | |
| 498 | + line = append(line, Span{Text: strings.Repeat(" ", fill)}) | |
| 499 | + } | |
| 500 | + } | |
| 501 | + out = append(out, line) | |
| 502 | + if r == 0 { | |
| 503 | + var sep []string | |
| 504 | + for _, w := range widths { | |
| 505 | + sep = append(sep, strings.Repeat("─", w)) | |
| 506 | + } | |
| 507 | + out = append(out, []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}}) | |
| 508 | + } | |
| 509 | + } | |
| 510 | + return out | |
| 511 | +} | |
| 512 | + | |
| 513 | +// total is the drawn width of a table's columns, separators included. | |
| 514 | +func total(widths []int) int { | |
| 515 | + n := 3 * max(len(widths)-1, 0) | |
| 516 | + for _, w := range widths { | |
| 517 | + n += w | |
| 518 | + } | |
| 519 | + return n | |
| 520 | +} | |
| 521 | + | |
| 522 | +// clipSpans cuts spans to width runes, the last one ending with "…". | |
| 523 | +func clipSpans(spans []Span, width int) []Span { | |
| 524 | + if len([]rune(spansText(spans))) <= width { | |
| 525 | + return append([]Span(nil), spans...) | |
| 526 | + } | |
| 527 | + var out []Span | |
| 528 | + left := width - 1 | |
| 529 | + for _, s := range spans { | |
| 530 | + r := []rune(s.Text) | |
| 531 | + if len(r) > left { | |
| 532 | + s.Text = string(r[:max(left, 0)]) | |
| 533 | + out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | |
| 534 | + return out | |
| 535 | + } | |
| 536 | + out = append(out, s) | |
| 537 | + left -= len(r) | |
| 538 | + } | |
| 539 | + return out | |
| 540 | +} | |
| 541 | + | |
| 542 | +// --- cache ------------------------------------------------------------------- | |
| 543 | + | |
| 544 | +// mdCache keeps the layout of closed answers: their text never changes, so | |
| 545 | +// only a new width (a resize) lays one out again. Read and written on the | |
| 546 | +// drawing goroutine only. | |
| 547 | +type mdCache struct { | |
| 548 | + width int | |
| 549 | + lines map[string][]Line | |
| 550 | +} | |
| 551 | + | |
| 552 | +// get returns text laid out at width, from the cache when it can. | |
| 553 | +func (c *mdCache) get(text string, width int) []Line { | |
| 554 | + if c.width != width || c.lines == nil { | |
| 555 | + c.width, c.lines = width, map[string][]Line{} | |
| 556 | + } | |
| 557 | + if l, ok := c.lines[text]; ok { | |
| 558 | + return l | |
| 559 | + } | |
| 560 | + l := markdown(text, width) | |
| 561 | + c.lines[text] = l | |
| 562 | + return l | |
| 563 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,563 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strconv" | ||
| 5 | + "strings" | ||
| 6 | + "unicode" | ||
| 7 | +) | ||
| 8 | + | ||
| 9 | +// Markdown in the window (experiment, branch experiment/tui-markdown): an | ||
| 10 | +// answer is shown as raw text while it streams, and rendered once its entry | ||
| 11 | +// is closed — the model's next tool call, or the end of the turn. A closed | ||
| 12 | +// entry never changes again, so it is parsed once and cached (mdCache); the | ||
| 13 | +// entry being written is laid out raw, as before, so nothing flickers while | ||
| 14 | +// a `**` waits for its other half. | ||
| 15 | +// | ||
| 16 | +// A hand-written subset, the one models actually write: | ||
| 17 | +// | ||
| 18 | +// blocks # headings, - * + and 1. lists (nested, [ ] [x] tasks), | ||
| 19 | +// > quotes, --- rules, ``` fenced code, | tables | | ||
| 20 | +// inline **bold**, *italic* / _italic_, ***both***, ~~struck~~, | ||
| 21 | +// `code`, [text](url), <https://…>, \ escapes | ||
| 22 | +// | ||
| 23 | +// Anything else — HTML, footnotes, reference links — stays as written. An | ||
| 24 | +// unclosed marker is literal text. The source's own line breaks are kept, | ||
| 25 | +// as the raw view keeps them: models break lines on purpose. | ||
| 26 | + | ||
| 27 | +// attr is what a span adds on top of its line's style. | ||
| 28 | +type attr uint8 | ||
| 29 | + | ||
| 30 | +const ( | ||
| 31 | + attrBold attr = 1 << iota | ||
| 32 | + attrItalic | ||
| 33 | + attrStrike | ||
| 34 | + attrUnderline | ||
| 35 | + attrDim | ||
| 36 | +) | ||
| 37 | + | ||
| 38 | +// Span is a run of a line drawn in one style. | ||
| 39 | +type Span struct { | ||
| 40 | + Text string | ||
| 41 | + Style styleKind | ||
| 42 | + Attr attr | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +// spansText is the plain text of spans, what Line.Text carries beside them. | ||
| 46 | +func spansText(spans []Span) string { | ||
| 47 | + var b strings.Builder | ||
| 48 | + for _, s := range spans { | ||
| 49 | + b.WriteString(s.Text) | ||
| 50 | + } | ||
| 51 | + return b.String() | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// spanLine is a Line drawn from spans; its Text is their plain text. | ||
| 55 | +func spanLine(spans []Span) Line { | ||
| 56 | + return Line{Text: spansText(spans), Spans: spans} | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +// --- inline ------------------------------------------------------------------ | ||
| 60 | + | ||
| 61 | +// inline parses one line of Markdown text into spans, all at base style. | ||
| 62 | +// | ||
| 63 | +// inline("a **b** `c`", styleBody) // "a " · "b" bold · " " · "c" code | ||
| 64 | +func inline(text string, base styleKind) []Span { | ||
| 65 | + var out []Span | ||
| 66 | + var plain strings.Builder | ||
| 67 | + flush := func() { | ||
| 68 | + if plain.Len() > 0 { | ||
| 69 | + out = append(out, Span{Text: plain.String(), Style: base}) | ||
| 70 | + plain.Reset() | ||
| 71 | + } | ||
| 72 | + } | ||
| 73 | + add := func(spans ...Span) { | ||
| 74 | + flush() | ||
| 75 | + out = append(out, spans...) | ||
| 76 | + } | ||
| 77 | + r := []rune(text) | ||
| 78 | + for i := 0; i < len(r); { | ||
| 79 | + c := r[i] | ||
| 80 | + switch { | ||
| 81 | + case c == '\\' && i+1 < len(r) && isMarkdownPunct(r[i+1]): | ||
| 82 | + plain.WriteRune(r[i+1]) | ||
| 83 | + i += 2 | ||
| 84 | + continue | ||
| 85 | + case c == '`': | ||
| 86 | + if end, n := closingTicks(r, i); end > 0 { | ||
| 87 | + code := strings.TrimSpace(string(r[i+n : end])) | ||
| 88 | + add(Span{Text: code, Style: styleCode}) | ||
| 89 | + i = end + n | ||
| 90 | + continue | ||
| 91 | + } | ||
| 92 | + case c == '[': | ||
| 93 | + if label, url, next, ok := link(r, i); ok { | ||
| 94 | + spans := inline(label, base) | ||
| 95 | + for k := range spans { | ||
| 96 | + spans[k].Attr |= attrUnderline | ||
| 97 | + } | ||
| 98 | + if url != "" && url != label { | ||
| 99 | + spans = append(spans, Span{Text: " (" + url + ")", Style: base, Attr: attrDim}) | ||
| 100 | + } | ||
| 101 | + add(spans...) | ||
| 102 | + i = next | ||
| 103 | + continue | ||
| 104 | + } | ||
| 105 | + case c == '<': | ||
| 106 | + if end := strings.IndexRune(string(r[i+1:]), '>'); end > 0 { | ||
| 107 | + inner := string(r[i+1 : i+1+end]) | ||
| 108 | + if strings.HasPrefix(inner, "http://") || strings.HasPrefix(inner, "https://") { | ||
| 109 | + add(Span{Text: inner, Style: base, Attr: attrUnderline}) | ||
| 110 | + i += end + 2 | ||
| 111 | + continue | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + case c == '*' || c == '_' || c == '~': | ||
| 115 | + if spans, next, ok := emphasis(r, i, base); ok { | ||
| 116 | + add(spans...) | ||
| 117 | + i = next | ||
| 118 | + continue | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + plain.WriteRune(c) | ||
| 122 | + i++ | ||
| 123 | + } | ||
| 124 | + flush() | ||
| 125 | + return out | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +// isMarkdownPunct is what a backslash may escape. | ||
| 129 | +func isMarkdownPunct(r rune) bool { return strings.ContainsRune("\\`*_{}[]()#+-.!|~<>", r) } | ||
| 130 | + | ||
| 131 | +// closingTicks finds the run of backticks closing the one at i: the index of | ||
| 132 | +// the closing run and the run's length, or 0 when there is none. | ||
| 133 | +func closingTicks(r []rune, i int) (int, int) { | ||
| 134 | + n := 0 | ||
| 135 | + for i+n < len(r) && r[i+n] == '`' { | ||
| 136 | + n++ | ||
| 137 | + } | ||
| 138 | + for j := i + n; j < len(r); j++ { | ||
| 139 | + if r[j] != '`' { | ||
| 140 | + continue | ||
| 141 | + } | ||
| 142 | + m := 0 | ||
| 143 | + for j+m < len(r) && r[j+m] == '`' { | ||
| 144 | + m++ | ||
| 145 | + } | ||
| 146 | + if m == n { | ||
| 147 | + return j, n | ||
| 148 | + } | ||
| 149 | + j += m - 1 | ||
| 150 | + } | ||
| 151 | + return 0, n | ||
| 152 | +} | ||
| 153 | + | ||
| 154 | +// link reads [label](url) at i. | ||
| 155 | +func link(r []rune, i int) (label, url string, next int, ok bool) { | ||
| 156 | + depth := 0 | ||
| 157 | + for j := i; j < len(r); j++ { | ||
| 158 | + switch r[j] { | ||
| 159 | + case '[': | ||
| 160 | + depth++ | ||
| 161 | + case ']': | ||
| 162 | + depth-- | ||
| 163 | + if depth == 0 { | ||
| 164 | + if j+1 >= len(r) || r[j+1] != '(' { | ||
| 165 | + return "", "", 0, false | ||
| 166 | + } | ||
| 167 | + end := strings.IndexRune(string(r[j+2:]), ')') | ||
| 168 | + if end < 0 { | ||
| 169 | + return "", "", 0, false | ||
| 170 | + } | ||
| 171 | + url = strings.TrimSpace(string(r[j+2 : j+2+end])) | ||
| 172 | + if k := strings.IndexAny(url, " \t"); k >= 0 { // [x](url "title") | ||
| 173 | + url = url[:k] | ||
| 174 | + } | ||
| 175 | + return string(r[i+1 : j]), url, j + 3 + end, true | ||
| 176 | + } | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + return "", "", 0, false | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +// emphasis reads **bold**, *italic*, ***both***, __bold__, _italic_ or | ||
| 183 | +// ~~struck~~ at i. An underscore inside a word (snake_case) is not one, and | ||
| 184 | +// neither is a marker followed by a space ("2 * 3"). | ||
| 185 | +func emphasis(r []rune, i int, base styleKind) ([]Span, int, bool) { | ||
| 186 | + c := r[i] | ||
| 187 | + n := 0 | ||
| 188 | + for i+n < len(r) && r[i+n] == c && n < 3 { | ||
| 189 | + n++ | ||
| 190 | + } | ||
| 191 | + if c == '~' && n != 2 { | ||
| 192 | + return nil, 0, false | ||
| 193 | + } | ||
| 194 | + if c == '_' && i > 0 && isWordRune(r[i-1]) { | ||
| 195 | + return nil, 0, false | ||
| 196 | + } | ||
| 197 | + open := i + n | ||
| 198 | + if open >= len(r) || unicode.IsSpace(r[open]) { | ||
| 199 | + return nil, 0, false | ||
| 200 | + } | ||
| 201 | + marker := strings.Repeat(string(c), n) | ||
| 202 | + rest := string(r[open:]) | ||
| 203 | + for from := 0; ; { | ||
| 204 | + at := strings.Index(rest[from:], marker) | ||
| 205 | + if at < 0 { | ||
| 206 | + return nil, 0, false | ||
| 207 | + } | ||
| 208 | + at += from | ||
| 209 | + inner := []rune(rest[:at]) | ||
| 210 | + after := open + len(inner) + n | ||
| 211 | + closes := len(inner) > 0 && !unicode.IsSpace(inner[len(inner)-1]) && | ||
| 212 | + (after >= len(r) || r[after] != c) && | ||
| 213 | + (c != '_' || after >= len(r) || !isWordRune(r[after])) | ||
| 214 | + if closes { | ||
| 215 | + var a attr | ||
| 216 | + switch { | ||
| 217 | + case c == '~': | ||
| 218 | + a = attrStrike | ||
| 219 | + case n == 1: | ||
| 220 | + a = attrItalic | ||
| 221 | + case n == 2: | ||
| 222 | + a = attrBold | ||
| 223 | + default: | ||
| 224 | + a = attrBold | attrItalic | ||
| 225 | + } | ||
| 226 | + spans := inline(string(inner), base) | ||
| 227 | + for k := range spans { | ||
| 228 | + spans[k].Attr |= a | ||
| 229 | + } | ||
| 230 | + return spans, after, true | ||
| 231 | + } | ||
| 232 | + from = at + len(marker) | ||
| 233 | + } | ||
| 234 | +} | ||
| 235 | + | ||
| 236 | +func isWordRune(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) } | ||
| 237 | + | ||
| 238 | +// --- wrapping spans -------------------------------------------------------------- | ||
| 239 | + | ||
| 240 | +// wrapSpans wraps spans to width runes, at spaces where it can, the way wrap | ||
| 241 | +// does for plain text. first goes before the first line, rest before the | ||
| 242 | +// others — a list item's bullet, then its hanging indent. | ||
| 243 | +func wrapSpans(spans []Span, width int, first, rest []Span) [][]Span { | ||
| 244 | + type cell struct { | ||
| 245 | + r rune | ||
| 246 | + at int // index of the span it came from | ||
| 247 | + } | ||
| 248 | + var cells []cell | ||
| 249 | + for k, s := range spans { | ||
| 250 | + for _, r := range s.Text { | ||
| 251 | + cells = append(cells, cell{r, k}) | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | + build := func(prefix []Span, part []cell) []Span { | ||
| 255 | + line := append([]Span(nil), prefix...) | ||
| 256 | + for i := 0; i < len(part); { | ||
| 257 | + j := i | ||
| 258 | + for j < len(part) && part[j].at == part[i].at { | ||
| 259 | + j++ | ||
| 260 | + } | ||
| 261 | + var b strings.Builder | ||
| 262 | + for _, c := range part[i:j] { | ||
| 263 | + b.WriteRune(c.r) | ||
| 264 | + } | ||
| 265 | + src := spans[part[i].at] | ||
| 266 | + line = append(line, Span{Text: b.String(), Style: src.Style, Attr: src.Attr}) | ||
| 267 | + i = j | ||
| 268 | + } | ||
| 269 | + return line | ||
| 270 | + } | ||
| 271 | + var out [][]Span | ||
| 272 | + prefix := first | ||
| 273 | + for { | ||
| 274 | + room := max(width-len([]rune(spansText(prefix))), 1) | ||
| 275 | + if len(cells) <= room { | ||
| 276 | + return append(out, build(prefix, cells)) | ||
| 277 | + } | ||
| 278 | + runes := make([]rune, len(cells)) | ||
| 279 | + for i, c := range cells { | ||
| 280 | + runes[i] = c.r | ||
| 281 | + } | ||
| 282 | + at := breakPoint(runes, room) | ||
| 283 | + end := at | ||
| 284 | + for end > 0 && cells[end-1].r == ' ' { | ||
| 285 | + end-- | ||
| 286 | + } | ||
| 287 | + out = append(out, build(prefix, cells[:end])) | ||
| 288 | + cells = cells[at:] | ||
| 289 | + for len(cells) > 0 && cells[0].r == ' ' { | ||
| 290 | + cells = cells[1:] | ||
| 291 | + } | ||
| 292 | + prefix = rest | ||
| 293 | + if len(cells) == 0 { | ||
| 294 | + return out | ||
| 295 | + } | ||
| 296 | + } | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +// --- blocks ------------------------------------------------------------------ | ||
| 300 | + | ||
| 301 | +// markdown lays a closed answer out at width: blocks, then inline spans, | ||
| 302 | +// wrapped. Every line is indented like the raw body. | ||
| 303 | +func markdown(text string, width int) []Line { | ||
| 304 | + src := strings.Split(strings.TrimRight(text, "\n"), "\n") | ||
| 305 | + var out []Line | ||
| 306 | + emit := func(spans []Span) { out = append(out, spanLine(append([]Span{{Text: pad}}, spans...))) } | ||
| 307 | + wrapped := func(spans []Span, first, rest []Span) { | ||
| 308 | + for _, l := range wrapSpans(spans, max(width-indent, 1), first, rest) { | ||
| 309 | + emit(l) | ||
| 310 | + } | ||
| 311 | + } | ||
| 312 | + blank := false | ||
| 313 | + for i := 0; i < len(src); i++ { | ||
| 314 | + line := src[i] | ||
| 315 | + trim := strings.TrimSpace(line) | ||
| 316 | + if trim == "" { | ||
| 317 | + if !blank && len(out) > 0 { | ||
| 318 | + out = append(out, Line{}) | ||
| 319 | + } | ||
| 320 | + blank = true | ||
| 321 | + continue | ||
| 322 | + } | ||
| 323 | + blank = false | ||
| 324 | + switch { | ||
| 325 | + case strings.HasPrefix(trim, "```") || strings.HasPrefix(trim, "~~~"): | ||
| 326 | + fence := trim[:3] | ||
| 327 | + lang := strings.TrimSpace(strings.TrimLeft(trim, fence[:1])) | ||
| 328 | + if lang != "" { | ||
| 329 | + emit([]Span{{Text: lang, Style: styleCode, Attr: attrDim}}) | ||
| 330 | + } | ||
| 331 | + for i++; i < len(src) && !strings.HasPrefix(strings.TrimSpace(src[i]), fence); i++ { | ||
| 332 | + out = append(out, Line{Text: pad + " " + src[i], Style: styleCode}) | ||
| 333 | + } | ||
| 334 | + case heading(trim) > 0: | ||
| 335 | + level := heading(trim) | ||
| 336 | + spans := inline(strings.TrimSpace(strings.TrimRight(trim[level:], "# ")), styleHeading) | ||
| 337 | + for k := range spans { | ||
| 338 | + spans[k].Attr |= attrBold | ||
| 339 | + if level == 1 { | ||
| 340 | + spans[k].Attr |= attrUnderline | ||
| 341 | + } | ||
| 342 | + } | ||
| 343 | + wrapped(spans, nil, nil) | ||
| 344 | + case isRule(trim): | ||
| 345 | + emit([]Span{{Text: strings.Repeat("─", max(min(width-indent, 60), 1)), Style: styleRule}}) | ||
| 346 | + case strings.HasPrefix(trim, ">"): | ||
| 347 | + quote := strings.TrimSpace(strings.TrimPrefix(trim, ">")) | ||
| 348 | + bar := []Span{{Text: "│ ", Style: styleQuote}} | ||
| 349 | + wrapped(inline(quote, styleQuote), bar, bar) | ||
| 350 | + case isTableStart(src, i): | ||
| 351 | + var rows []string | ||
| 352 | + for ; i < len(src) && strings.HasPrefix(strings.TrimSpace(src[i]), "|"); i++ { | ||
| 353 | + rows = append(rows, strings.TrimSpace(src[i])) | ||
| 354 | + } | ||
| 355 | + i-- | ||
| 356 | + for _, l := range table(rows, max(width-indent, 1)) { | ||
| 357 | + emit(l) | ||
| 358 | + } | ||
| 359 | + default: | ||
| 360 | + if bullet, body, depth, ok := listItem(line); ok { | ||
| 361 | + lead := strings.Repeat(" ", depth) | ||
| 362 | + first := []Span{{Text: lead + bullet, Style: styleBullet}} | ||
| 363 | + rest := []Span{{Text: lead + strings.Repeat(" ", len([]rune(bullet)))}} | ||
| 364 | + wrapped(inline(body, styleBody), first, rest) | ||
| 365 | + continue | ||
| 366 | + } | ||
| 367 | + wrapped(inline(line, styleBody), nil, nil) | ||
| 368 | + } | ||
| 369 | + } | ||
| 370 | + return out | ||
| 371 | +} | ||
| 372 | + | ||
| 373 | +// heading is the level of an ATX heading line ("## Title" → 2), 0 if none. | ||
| 374 | +func heading(trim string) int { | ||
| 375 | + n := 0 | ||
| 376 | + for n < len(trim) && trim[n] == '#' { | ||
| 377 | + n++ | ||
| 378 | + } | ||
| 379 | + if n == 0 || n > 6 || (n < len(trim) && trim[n] != ' ') || n == len(trim) { | ||
| 380 | + return 0 | ||
| 381 | + } | ||
| 382 | + return n | ||
| 383 | +} | ||
| 384 | + | ||
| 385 | +// isRule reports a thematic break: three or more of one of - * _, spaces | ||
| 386 | +// allowed between them. | ||
| 387 | +func isRule(trim string) bool { | ||
| 388 | + s := strings.ReplaceAll(trim, " ", "") | ||
| 389 | + if len(s) < 3 { | ||
| 390 | + return false | ||
| 391 | + } | ||
| 392 | + c := s[0] | ||
| 393 | + return (c == '-' || c == '*' || c == '_') && strings.Count(s, string(c)) == len(s) | ||
| 394 | +} | ||
| 395 | + | ||
| 396 | +// listItem reads a bullet or numbered list line: the bullet as shown, the | ||
| 397 | +// text, and the nesting depth (two leading spaces a level). | ||
| 398 | +func listItem(line string) (bullet, body string, depth int, ok bool) { | ||
| 399 | + lead := len(line) - len(strings.TrimLeft(line, " \t")) | ||
| 400 | + trim := line[lead:] | ||
| 401 | + depth = min(lead/2, 6) | ||
| 402 | + if len(trim) >= 2 && strings.ContainsRune("-*+", rune(trim[0])) && trim[1] == ' ' { | ||
| 403 | + body = trim[2:] | ||
| 404 | + switch { | ||
| 405 | + case strings.HasPrefix(body, "[ ] "): | ||
| 406 | + return "☐ ", body[4:], depth, true | ||
| 407 | + case strings.HasPrefix(body, "[x] "), strings.HasPrefix(body, "[X] "): | ||
| 408 | + return "☑ ", body[4:], depth, true | ||
| 409 | + } | ||
| 410 | + return "• ", body, depth, true | ||
| 411 | + } | ||
| 412 | + n := 0 | ||
| 413 | + for n < len(trim) && trim[n] >= '0' && trim[n] <= '9' { | ||
| 414 | + n++ | ||
| 415 | + } | ||
| 416 | + if n > 0 && n <= 9 && n+1 < len(trim) && (trim[n] == '.' || trim[n] == ')') && trim[n+1] == ' ' { | ||
| 417 | + num, _ := strconv.Atoi(trim[:n]) | ||
| 418 | + return strconv.Itoa(num) + ". ", trim[n+2:], depth, true | ||
| 419 | + } | ||
| 420 | + return "", "", 0, false | ||
| 421 | +} | ||
| 422 | + | ||
| 423 | +// isTableStart reports a table: a `|` row followed by a |---|---| line. | ||
| 424 | +func isTableStart(src []string, i int) bool { | ||
| 425 | + if i+1 >= len(src) || !strings.HasPrefix(strings.TrimSpace(src[i]), "|") { | ||
| 426 | + return false | ||
| 427 | + } | ||
| 428 | + sep := strings.TrimSpace(src[i+1]) | ||
| 429 | + return strings.HasPrefix(sep, "|") && strings.Trim(sep, "|-: ") == "" && strings.Contains(sep, "-") | ||
| 430 | +} | ||
| 431 | + | ||
| 432 | +// cells splits a table row: "| a | b |" → ["a", "b"]. An escaped \| stays. | ||
| 433 | +func cells(row string) []string { | ||
| 434 | + row = strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(row), "|"), "|") | ||
| 435 | + row = strings.ReplaceAll(row, `\|`, "\x00") | ||
| 436 | + var out []string | ||
| 437 | + for _, c := range strings.Split(row, "|") { | ||
| 438 | + out = append(out, strings.ReplaceAll(strings.TrimSpace(c), "\x00", "|")) | ||
| 439 | + } | ||
| 440 | + return out | ||
| 441 | +} | ||
| 442 | + | ||
| 443 | +// table lays a table out: columns as wide as their widest cell, the header | ||
| 444 | +// bold, a ─┼─ line under it. A table wider than width has its widest columns | ||
| 445 | +// narrowed and their cells cut with "…" — a table is read across, wrapping | ||
| 446 | +// its cells would break that. | ||
| 447 | +func table(rows []string, width int) [][]Span { | ||
| 448 | + var grid [][][]Span | ||
| 449 | + cols := 0 | ||
| 450 | + for k, r := range rows { | ||
| 451 | + if k == 1 { // the |---| line | ||
| 452 | + continue | ||
| 453 | + } | ||
| 454 | + var row [][]Span | ||
| 455 | + for _, c := range cells(r) { | ||
| 456 | + row = append(row, inline(c, styleBody)) | ||
| 457 | + } | ||
| 458 | + cols = max(cols, len(row)) | ||
| 459 | + grid = append(grid, row) | ||
| 460 | + } | ||
| 461 | + widths := make([]int, cols) | ||
| 462 | + for _, row := range grid { | ||
| 463 | + for c, cell := range row { | ||
| 464 | + widths[c] = max(widths[c], len([]rune(spansText(cell)))) | ||
| 465 | + } | ||
| 466 | + } | ||
| 467 | + for total(widths) > width { | ||
| 468 | + widest := 0 | ||
| 469 | + for c := range widths { | ||
| 470 | + if widths[c] > widths[widest] { | ||
| 471 | + widest = c | ||
| 472 | + } | ||
| 473 | + } | ||
| 474 | + if widths[widest] <= 3 { | ||
| 475 | + break | ||
| 476 | + } | ||
| 477 | + widths[widest]-- | ||
| 478 | + } | ||
| 479 | + var out [][]Span | ||
| 480 | + for r, row := range grid { | ||
| 481 | + var line []Span | ||
| 482 | + for c := 0; c < cols; c++ { | ||
| 483 | + if c > 0 { | ||
| 484 | + line = append(line, Span{Text: " │ ", Style: styleRule}) | ||
| 485 | + } | ||
| 486 | + var cell []Span | ||
| 487 | + if c < len(row) { | ||
| 488 | + cell = row[c] | ||
| 489 | + } | ||
| 490 | + cell = clipSpans(cell, widths[c]) | ||
| 491 | + if r == 0 { | ||
| 492 | + for k := range cell { | ||
| 493 | + cell[k].Attr |= attrBold | ||
| 494 | + } | ||
| 495 | + } | ||
| 496 | + line = append(line, cell...) | ||
| 497 | + if fill := widths[c] - len([]rune(spansText(cell))); fill > 0 { | ||
| 498 | + line = append(line, Span{Text: strings.Repeat(" ", fill)}) | ||
| 499 | + } | ||
| 500 | + } | ||
| 501 | + out = append(out, line) | ||
| 502 | + if r == 0 { | ||
| 503 | + var sep []string | ||
| 504 | + for _, w := range widths { | ||
| 505 | + sep = append(sep, strings.Repeat("─", w)) | ||
| 506 | + } | ||
| 507 | + out = append(out, []Span{{Text: strings.Join(sep, "─┼─"), Style: styleRule}}) | ||
| 508 | + } | ||
| 509 | + } | ||
| 510 | + return out | ||
| 511 | +} | ||
| 512 | + | ||
| 513 | +// total is the drawn width of a table's columns, separators included. | ||
| 514 | +func total(widths []int) int { | ||
| 515 | + n := 3 * max(len(widths)-1, 0) | ||
| 516 | + for _, w := range widths { | ||
| 517 | + n += w | ||
| 518 | + } | ||
| 519 | + return n | ||
| 520 | +} | ||
| 521 | + | ||
| 522 | +// clipSpans cuts spans to width runes, the last one ending with "…". | ||
| 523 | +func clipSpans(spans []Span, width int) []Span { | ||
| 524 | + if len([]rune(spansText(spans))) <= width { | ||
| 525 | + return append([]Span(nil), spans...) | ||
| 526 | + } | ||
| 527 | + var out []Span | ||
| 528 | + left := width - 1 | ||
| 529 | + for _, s := range spans { | ||
| 530 | + r := []rune(s.Text) | ||
| 531 | + if len(r) > left { | ||
| 532 | + s.Text = string(r[:max(left, 0)]) | ||
| 533 | + out = append(out, s, Span{Text: "…", Style: s.Style, Attr: s.Attr}) | ||
| 534 | + return out | ||
| 535 | + } | ||
| 536 | + out = append(out, s) | ||
| 537 | + left -= len(r) | ||
| 538 | + } | ||
| 539 | + return out | ||
| 540 | +} | ||
| 541 | + | ||
| 542 | +// --- cache ------------------------------------------------------------------- | ||
| 543 | + | ||
| 544 | +// mdCache keeps the layout of closed answers: their text never changes, so | ||
| 545 | +// only a new width (a resize) lays one out again. Read and written on the | ||
| 546 | +// drawing goroutine only. | ||
| 547 | +type mdCache struct { | ||
| 548 | + width int | ||
| 549 | + lines map[string][]Line | ||
| 550 | +} | ||
| 551 | + | ||
| 552 | +// get returns text laid out at width, from the cache when it can. | ||
| 553 | +func (c *mdCache) get(text string, width int) []Line { | ||
| 554 | + if c.width != width || c.lines == nil { | ||
| 555 | + c.width, c.lines = width, map[string][]Line{} | ||
| 556 | + } | ||
| 557 | + if l, ok := c.lines[text]; ok { | ||
| 558 | + return l | ||
| 559 | + } | ||
| 560 | + l := markdown(text, width) | ||
| 561 | + c.lines[text] = l | ||
| 562 | + return l | ||
| 563 | +} | ||
added
internal/tui/markdown_test.go +261 -0 | new file mode 100644 | ||
| @@ -0,0 +1,261 @@ | ||
| 1 | +package tui | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "testing" | |
| 6 | + | |
| 7 | + "mm/internal/config" | |
| 8 | + "mm/internal/ui" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// show renders spans as "text" with their attributes marked, for tests: | |
| 12 | +// **bold**, *italic*, `code`, _under_, ~strike~, (dim). | |
| 13 | +func show(spans []Span) string { | |
| 14 | + var b strings.Builder | |
| 15 | + for _, s := range spans { | |
| 16 | + t := s.Text | |
| 17 | + if s.Style == styleCode { | |
| 18 | + t = "`" + t + "`" | |
| 19 | + } | |
| 20 | + if s.Attr&attrBold != 0 { | |
| 21 | + t = "**" + t + "**" | |
| 22 | + } | |
| 23 | + if s.Attr&attrItalic != 0 { | |
| 24 | + t = "*" + t + "*" | |
| 25 | + } | |
| 26 | + if s.Attr&attrUnderline != 0 { | |
| 27 | + t = "_" + t + "_" | |
| 28 | + } | |
| 29 | + if s.Attr&attrStrike != 0 { | |
| 30 | + t = "~" + t + "~" | |
| 31 | + } | |
| 32 | + if s.Attr&attrDim != 0 { | |
| 33 | + t = "(" + t + ")" | |
| 34 | + } | |
| 35 | + b.WriteString(t) | |
| 36 | + } | |
| 37 | + return b.String() | |
| 38 | +} | |
| 39 | + | |
| 40 | +func TestInline(t *testing.T) { | |
| 41 | + cases := map[string]string{ | |
| 42 | + "plain text": "plain text", | |
| 43 | + "a **bold** word": "a **bold** word", | |
| 44 | + "an *italic* and _also_": "an *italic* and *also*", | |
| 45 | + "***both***": "***both***", | |
| 46 | + "~~gone~~ now": "~gone~ now", | |
| 47 | + "run `go test ./...` here": "run `go test ./...` here", | |
| 48 | + "``a ` tick``": "`a ` tick`", | |
| 49 | + "see [the docs](https://x.org/a)": "see _the docs_( (https://x.org/a))", | |
| 50 | + "[https://x.org](https://x.org)": "_https://x.org_", | |
| 51 | + "<https://x.org/b>": "_https://x.org/b_", | |
| 52 | + "**bold with `code` inside**": "**bold with ****`code`**** inside**", | |
| 53 | + "snake_case_name stays": "snake_case_name stays", | |
| 54 | + "2 * 3 * 4": "2 * 3 * 4", | |
| 55 | + "an **unclosed marker": "an **unclosed marker", | |
| 56 | + `not \*italic\*`: "not *italic*", | |
| 57 | + "a [label] without url": "a [label] without url", | |
| 58 | + "`unclosed code": "`unclosed code", | |
| 59 | + "**a** and **b**": "**a** and **b**", | |
| 60 | + } | |
| 61 | + for in, want := range cases { | |
| 62 | + if got := show(inline(in, styleBody)); got != want { | |
| 63 | + t.Errorf("inline(%q) = %q, want %q", in, got, want) | |
| 64 | + } | |
| 65 | + } | |
| 66 | +} | |
| 67 | + | |
| 68 | +// Wrapping keeps each run's style across the break, and the hanging indent. | |
| 69 | +func TestWrapSpans(t *testing.T) { | |
| 70 | + spans := inline("one **two three** four", styleBody) | |
| 71 | + lines := wrapSpans(spans, 10, []Span{{Text: "• "}}, []Span{{Text: " "}}) | |
| 72 | + var got []string | |
| 73 | + for _, l := range lines { | |
| 74 | + got = append(got, show(l)) | |
| 75 | + } | |
| 76 | + want := []string{"• one **two**", " **three**", " four"} | |
| 77 | + if strings.Join(got, "|") != strings.Join(want, "|") { | |
| 78 | + t.Errorf("wrapSpans = %q, want %q", got, want) | |
| 79 | + } | |
| 80 | + if l := wrapSpans(nil, 10, nil, nil); len(l) != 1 || len(l[0]) != 0 { | |
| 81 | + t.Errorf("empty: %+v", l) | |
| 82 | + } | |
| 83 | + long := wrapSpans(inline("abcdefghijklmnop", styleBody), 5, nil, nil) | |
| 84 | + if len(long) != 4 || spansText(long[0]) != "abcde" || spansText(long[3]) != "p" { | |
| 85 | + t.Errorf("a word longer than the line is cut: %+v", long) | |
| 86 | + } | |
| 87 | +} | |
| 88 | + | |
| 89 | +func texts(lines []Line) []string { | |
| 90 | + var out []string | |
| 91 | + for _, l := range lines { | |
| 92 | + out = append(out, l.Text) | |
| 93 | + } | |
| 94 | + return out | |
| 95 | +} | |
| 96 | + | |
| 97 | +func TestMarkdownBlocks(t *testing.T) { | |
| 98 | + text := strings.Join([]string{ | |
| 99 | + "# Title", | |
| 100 | + "Some **bold** text.", | |
| 101 | + "", | |
| 102 | + "", | |
| 103 | + "## Steps", | |
| 104 | + "1. first", | |
| 105 | + "2. second", | |
| 106 | + " - nested", | |
| 107 | + "- [ ] todo", | |
| 108 | + "- [x] done", | |
| 109 | + "> a quote", | |
| 110 | + "---", | |
| 111 | + "```go", | |
| 112 | + "fmt.Println(\"hi\")", | |
| 113 | + "```", | |
| 114 | + "End.", | |
| 115 | + }, "\n") | |
| 116 | + got := texts(markdown(text, 40)) | |
| 117 | + want := []string{ | |
| 118 | + " Title", | |
| 119 | + " Some bold text.", | |
| 120 | + "", | |
| 121 | + " Steps", | |
| 122 | + " 1. first", | |
| 123 | + " 2. second", | |
| 124 | + " • nested", | |
| 125 | + " ☐ todo", | |
| 126 | + " ☑ done", | |
| 127 | + " │ a quote", | |
| 128 | + " " + strings.Repeat("─", 38), | |
| 129 | + " go", | |
| 130 | + " fmt.Println(\"hi\")", | |
| 131 | + " End.", | |
| 132 | + } | |
| 133 | + if strings.Join(got, "\n") != strings.Join(want, "\n") { | |
| 134 | + t.Errorf("markdown =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) | |
| 135 | + } | |
| 136 | + lines := markdown(text, 40) | |
| 137 | + if s := lines[0].Spans[1]; s.Style != styleHeading || s.Attr&attrBold == 0 || s.Attr&attrUnderline == 0 { | |
| 138 | + t.Errorf("h1 span: %+v", s) | |
| 139 | + } | |
| 140 | + if s := lines[3].Spans[1]; s.Attr&attrUnderline != 0 { | |
| 141 | + t.Errorf("h2 is not underlined: %+v", s) | |
| 142 | + } | |
| 143 | + if lines[12].Style != styleCode || lines[12].Spans != nil { | |
| 144 | + t.Errorf("code line: %+v", lines[12]) | |
| 145 | + } | |
| 146 | + // A long list item wraps under its text, not under its bullet. | |
| 147 | + item := texts(markdown("- one two three four five six", 16)) | |
| 148 | + if strings.Join(item, "|") != " • one two| three four| five six" { | |
| 149 | + t.Errorf("hanging indent: %q", item) | |
| 150 | + } | |
| 151 | +} | |
| 152 | + | |
| 153 | +func TestMarkdownTable(t *testing.T) { | |
| 154 | + text := "| Name | Port |\n|---|--:|\n| llamacpp | 9931 |\n| ollama | 11434 |" | |
| 155 | + got := texts(markdown(text, 40)) | |
| 156 | + want := []string{ | |
| 157 | + " Name │ Port ", | |
| 158 | + " ─────────┼──────", | |
| 159 | + " llamacpp │ 9931 ", | |
| 160 | + " ollama │ 11434", | |
| 161 | + } | |
| 162 | + if strings.Join(got, "\n") != strings.Join(want, "\n") { | |
| 163 | + t.Errorf("table =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) | |
| 164 | + } | |
| 165 | + if s := markdown(text, 40)[0].Spans[1]; s.Attr&attrBold == 0 { | |
| 166 | + t.Errorf("header not bold: %+v", s) | |
| 167 | + } | |
| 168 | + // Too wide: the widest column is narrowed and cut with "…". | |
| 169 | + wide := "| Key | Description |\n|---|---|\n| model | the model identifier in the provider's naming |" | |
| 170 | + for _, l := range texts(markdown(wide, 30)) { | |
| 171 | + if n := len([]rune(l)); n > 30 { | |
| 172 | + t.Errorf("line wider than the window (%d): %q", n, l) | |
| 173 | + } | |
| 174 | + } | |
| 175 | + if !strings.Contains(strings.Join(texts(markdown(wide, 30)), "\n"), "…") { | |
| 176 | + t.Error("no cut mark in a narrowed table") | |
| 177 | + } | |
| 178 | + // A `|` line without its |---| line is a paragraph. | |
| 179 | + if got := texts(markdown("| not a table", 40)); len(got) != 1 || got[0] != " | not a table" { | |
| 180 | + t.Errorf("not a table: %q", got) | |
| 181 | + } | |
| 182 | +} | |
| 183 | + | |
| 184 | +// The answer being written stays raw; once closed it is rendered. | |
| 185 | +func TestLayoutRendersOnlyClosedAnswers(t *testing.T) { | |
| 186 | + var c mdCache | |
| 187 | + open := layoutWith([]Entry{{Kind: KindAgent, Text: "a **b**", Open: true}}, "mm", 40, 0, c.get) | |
| 188 | + if open[1].Text != " a **b**" || open[1].Spans != nil { | |
| 189 | + t.Errorf("open answer: %+v", open[1]) | |
| 190 | + } | |
| 191 | + closed := layoutWith([]Entry{{Kind: KindAgent, Text: "a **b**"}}, "mm", 40, 0, c.get) | |
| 192 | + if closed[0].Text != "‣ mm" || closed[1].Text != " a b" || closed[1].Spans == nil { | |
| 193 | + t.Errorf("closed answer: %+v", closed) | |
| 194 | + } | |
| 195 | + user := layoutWith([]Entry{{Kind: KindUser, Text: "a **b**"}}, "mm", 40, 0, c.get) | |
| 196 | + if user[1].Text != " a **b**" { | |
| 197 | + t.Errorf("a question is never rendered: %+v", user[1]) | |
| 198 | + } | |
| 199 | +} | |
| 200 | + | |
| 201 | +// The cache lays an answer out once per width. | |
| 202 | +func TestMdCache(t *testing.T) { | |
| 203 | + var c mdCache | |
| 204 | + a := c.get("**x**", 40) | |
| 205 | + b := c.get("**x**", 40) | |
| 206 | + if &a[0] != &b[0] { | |
| 207 | + t.Error("same text, same width: not taken from the cache") | |
| 208 | + } | |
| 209 | + if d := c.get("**x**", 20); &d[0] == &a[0] { | |
| 210 | + t.Error("another width must lay it out again") | |
| 211 | + } | |
| 212 | +} | |
| 213 | + | |
| 214 | +// Transcript.Entries marks the answer being written, and only it. | |
| 215 | +func TestEntriesMarksTheOpenAnswer(t *testing.T) { | |
| 216 | + tr := &Transcript{} | |
| 217 | + tr.Chunk("first") | |
| 218 | + if e := tr.Entries(); !e[0].Open { | |
| 219 | + t.Fatal("streaming answer not open") | |
| 220 | + } | |
| 221 | + tr.Close() | |
| 222 | + if e := tr.Entries(); e[0].Open { | |
| 223 | + t.Error("closed answer still open") | |
| 224 | + } | |
| 225 | + tr.Chunk("second") | |
| 226 | + tr.ToolStart(ui.ToolEvent{ID: "1", Tool: "bash", Title: "bash: ls"}) | |
| 227 | + if e := tr.Entries(); e[1].Open { | |
| 228 | + t.Error("a tool call closes the answer before it") | |
| 229 | + } | |
| 230 | +} | |
| 231 | + | |
| 232 | +// On screen: a closed answer is drawn without its markers, in its styles. | |
| 233 | +func TestScreenDrawsRenderedAnswer(t *testing.T) { | |
| 234 | + hs := newHarness(t, 60, 12) | |
| 235 | + hs.v.t.Chunk("Use **yolo: false** and `mm -tui`.") | |
| 236 | + if text := hs.screenText(); !strings.Contains(text, "Use **yolo: false** and `mm -tui`.") { | |
| 237 | + t.Fatalf("while open, raw:\n%s", text) | |
| 238 | + } | |
| 239 | + hs.v.t.Close() | |
| 240 | + text := hs.screenText() | |
| 241 | + if !strings.Contains(text, "Use yolo: false and mm -tui.") || strings.Contains(text, "**") { | |
| 242 | + t.Errorf("closed, rendered:\n%s", text) | |
| 243 | + } | |
| 244 | +} | |
| 245 | + | |
| 246 | +// renderMarkdown: false keeps every answer raw, closed or not (ticket 274); | |
| 247 | +// it is on by default. | |
| 248 | +func TestRenderMarkdownSwitch(t *testing.T) { | |
| 249 | + saved := config.Cfg.RenderMarkdown | |
| 250 | + t.Cleanup(func() { config.Cfg.RenderMarkdown = saved }) | |
| 251 | + if !saved { | |
| 252 | + t.Fatal("renderMarkdown must be on by default") | |
| 253 | + } | |
| 254 | + config.Cfg.RenderMarkdown = false | |
| 255 | + hs := newHarness(t, 60, 12) | |
| 256 | + hs.v.t.Chunk("Use **yolo: false**.") | |
| 257 | + hs.v.t.Close() | |
| 258 | + if text := hs.screenText(); !strings.Contains(text, "Use **yolo: false**.") { | |
| 259 | + t.Errorf("off: the closed answer must stay raw:\n%s", text) | |
| 260 | + } | |
| 261 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,261 @@ | |||
| 1 | +package tui | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "testing" | ||
| 6 | + | ||
| 7 | + "mm/internal/config" | ||
| 8 | + "mm/internal/ui" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// show renders spans as "text" with their attributes marked, for tests: | ||
| 12 | +// **bold**, *italic*, `code`, _under_, ~strike~, (dim). | ||
| 13 | +func show(spans []Span) string { | ||
| 14 | + var b strings.Builder | ||
| 15 | + for _, s := range spans { | ||
| 16 | + t := s.Text | ||
| 17 | + if s.Style == styleCode { | ||
| 18 | + t = "`" + t + "`" | ||
| 19 | + } | ||
| 20 | + if s.Attr&attrBold != 0 { | ||
| 21 | + t = "**" + t + "**" | ||
| 22 | + } | ||
| 23 | + if s.Attr&attrItalic != 0 { | ||
| 24 | + t = "*" + t + "*" | ||
| 25 | + } | ||
| 26 | + if s.Attr&attrUnderline != 0 { | ||
| 27 | + t = "_" + t + "_" | ||
| 28 | + } | ||
| 29 | + if s.Attr&attrStrike != 0 { | ||
| 30 | + t = "~" + t + "~" | ||
| 31 | + } | ||
| 32 | + if s.Attr&attrDim != 0 { | ||
| 33 | + t = "(" + t + ")" | ||
| 34 | + } | ||
| 35 | + b.WriteString(t) | ||
| 36 | + } | ||
| 37 | + return b.String() | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +func TestInline(t *testing.T) { | ||
| 41 | + cases := map[string]string{ | ||
| 42 | + "plain text": "plain text", | ||
| 43 | + "a **bold** word": "a **bold** word", | ||
| 44 | + "an *italic* and _also_": "an *italic* and *also*", | ||
| 45 | + "***both***": "***both***", | ||
| 46 | + "~~gone~~ now": "~gone~ now", | ||
| 47 | + "run `go test ./...` here": "run `go test ./...` here", | ||
| 48 | + "``a ` tick``": "`a ` tick`", | ||
| 49 | + "see [the docs](https://x.org/a)": "see _the docs_( (https://x.org/a))", | ||
| 50 | + "[https://x.org](https://x.org)": "_https://x.org_", | ||
| 51 | + "<https://x.org/b>": "_https://x.org/b_", | ||
| 52 | + "**bold with `code` inside**": "**bold with ****`code`**** inside**", | ||
| 53 | + "snake_case_name stays": "snake_case_name stays", | ||
| 54 | + "2 * 3 * 4": "2 * 3 * 4", | ||
| 55 | + "an **unclosed marker": "an **unclosed marker", | ||
| 56 | + `not \*italic\*`: "not *italic*", | ||
| 57 | + "a [label] without url": "a [label] without url", | ||
| 58 | + "`unclosed code": "`unclosed code", | ||
| 59 | + "**a** and **b**": "**a** and **b**", | ||
| 60 | + } | ||
| 61 | + for in, want := range cases { | ||
| 62 | + if got := show(inline(in, styleBody)); got != want { | ||
| 63 | + t.Errorf("inline(%q) = %q, want %q", in, got, want) | ||
| 64 | + } | ||
| 65 | + } | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +// Wrapping keeps each run's style across the break, and the hanging indent. | ||
| 69 | +func TestWrapSpans(t *testing.T) { | ||
| 70 | + spans := inline("one **two three** four", styleBody) | ||
| 71 | + lines := wrapSpans(spans, 10, []Span{{Text: "• "}}, []Span{{Text: " "}}) | ||
| 72 | + var got []string | ||
| 73 | + for _, l := range lines { | ||
| 74 | + got = append(got, show(l)) | ||
| 75 | + } | ||
| 76 | + want := []string{"• one **two**", " **three**", " four"} | ||
| 77 | + if strings.Join(got, "|") != strings.Join(want, "|") { | ||
| 78 | + t.Errorf("wrapSpans = %q, want %q", got, want) | ||
| 79 | + } | ||
| 80 | + if l := wrapSpans(nil, 10, nil, nil); len(l) != 1 || len(l[0]) != 0 { | ||
| 81 | + t.Errorf("empty: %+v", l) | ||
| 82 | + } | ||
| 83 | + long := wrapSpans(inline("abcdefghijklmnop", styleBody), 5, nil, nil) | ||
| 84 | + if len(long) != 4 || spansText(long[0]) != "abcde" || spansText(long[3]) != "p" { | ||
| 85 | + t.Errorf("a word longer than the line is cut: %+v", long) | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +func texts(lines []Line) []string { | ||
| 90 | + var out []string | ||
| 91 | + for _, l := range lines { | ||
| 92 | + out = append(out, l.Text) | ||
| 93 | + } | ||
| 94 | + return out | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +func TestMarkdownBlocks(t *testing.T) { | ||
| 98 | + text := strings.Join([]string{ | ||
| 99 | + "# Title", | ||
| 100 | + "Some **bold** text.", | ||
| 101 | + "", | ||
| 102 | + "", | ||
| 103 | + "## Steps", | ||
| 104 | + "1. first", | ||
| 105 | + "2. second", | ||
| 106 | + " - nested", | ||
| 107 | + "- [ ] todo", | ||
| 108 | + "- [x] done", | ||
| 109 | + "> a quote", | ||
| 110 | + "---", | ||
| 111 | + "```go", | ||
| 112 | + "fmt.Println(\"hi\")", | ||
| 113 | + "```", | ||
| 114 | + "End.", | ||
| 115 | + }, "\n") | ||
| 116 | + got := texts(markdown(text, 40)) | ||
| 117 | + want := []string{ | ||
| 118 | + " Title", | ||
| 119 | + " Some bold text.", | ||
| 120 | + "", | ||
| 121 | + " Steps", | ||
| 122 | + " 1. first", | ||
| 123 | + " 2. second", | ||
| 124 | + " • nested", | ||
| 125 | + " ☐ todo", | ||
| 126 | + " ☑ done", | ||
| 127 | + " │ a quote", | ||
| 128 | + " " + strings.Repeat("─", 38), | ||
| 129 | + " go", | ||
| 130 | + " fmt.Println(\"hi\")", | ||
| 131 | + " End.", | ||
| 132 | + } | ||
| 133 | + if strings.Join(got, "\n") != strings.Join(want, "\n") { | ||
| 134 | + t.Errorf("markdown =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) | ||
| 135 | + } | ||
| 136 | + lines := markdown(text, 40) | ||
| 137 | + if s := lines[0].Spans[1]; s.Style != styleHeading || s.Attr&attrBold == 0 || s.Attr&attrUnderline == 0 { | ||
| 138 | + t.Errorf("h1 span: %+v", s) | ||
| 139 | + } | ||
| 140 | + if s := lines[3].Spans[1]; s.Attr&attrUnderline != 0 { | ||
| 141 | + t.Errorf("h2 is not underlined: %+v", s) | ||
| 142 | + } | ||
| 143 | + if lines[12].Style != styleCode || lines[12].Spans != nil { | ||
| 144 | + t.Errorf("code line: %+v", lines[12]) | ||
| 145 | + } | ||
| 146 | + // A long list item wraps under its text, not under its bullet. | ||
| 147 | + item := texts(markdown("- one two three four five six", 16)) | ||
| 148 | + if strings.Join(item, "|") != " • one two| three four| five six" { | ||
| 149 | + t.Errorf("hanging indent: %q", item) | ||
| 150 | + } | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +func TestMarkdownTable(t *testing.T) { | ||
| 154 | + text := "| Name | Port |\n|---|--:|\n| llamacpp | 9931 |\n| ollama | 11434 |" | ||
| 155 | + got := texts(markdown(text, 40)) | ||
| 156 | + want := []string{ | ||
| 157 | + " Name │ Port ", | ||
| 158 | + " ─────────┼──────", | ||
| 159 | + " llamacpp │ 9931 ", | ||
| 160 | + " ollama │ 11434", | ||
| 161 | + } | ||
| 162 | + if strings.Join(got, "\n") != strings.Join(want, "\n") { | ||
| 163 | + t.Errorf("table =\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) | ||
| 164 | + } | ||
| 165 | + if s := markdown(text, 40)[0].Spans[1]; s.Attr&attrBold == 0 { | ||
| 166 | + t.Errorf("header not bold: %+v", s) | ||
| 167 | + } | ||
| 168 | + // Too wide: the widest column is narrowed and cut with "…". | ||
| 169 | + wide := "| Key | Description |\n|---|---|\n| model | the model identifier in the provider's naming |" | ||
| 170 | + for _, l := range texts(markdown(wide, 30)) { | ||
| 171 | + if n := len([]rune(l)); n > 30 { | ||
| 172 | + t.Errorf("line wider than the window (%d): %q", n, l) | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + if !strings.Contains(strings.Join(texts(markdown(wide, 30)), "\n"), "…") { | ||
| 176 | + t.Error("no cut mark in a narrowed table") | ||
| 177 | + } | ||
| 178 | + // A `|` line without its |---| line is a paragraph. | ||
| 179 | + if got := texts(markdown("| not a table", 40)); len(got) != 1 || got[0] != " | not a table" { | ||
| 180 | + t.Errorf("not a table: %q", got) | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +// The answer being written stays raw; once closed it is rendered. | ||
| 185 | +func TestLayoutRendersOnlyClosedAnswers(t *testing.T) { | ||
| 186 | + var c mdCache | ||
| 187 | + open := layoutWith([]Entry{{Kind: KindAgent, Text: "a **b**", Open: true}}, "mm", 40, 0, c.get) | ||
| 188 | + if open[1].Text != " a **b**" || open[1].Spans != nil { | ||
| 189 | + t.Errorf("open answer: %+v", open[1]) | ||
| 190 | + } | ||
| 191 | + closed := layoutWith([]Entry{{Kind: KindAgent, Text: "a **b**"}}, "mm", 40, 0, c.get) | ||
| 192 | + if closed[0].Text != "‣ mm" || closed[1].Text != " a b" || closed[1].Spans == nil { | ||
| 193 | + t.Errorf("closed answer: %+v", closed) | ||
| 194 | + } | ||
| 195 | + user := layoutWith([]Entry{{Kind: KindUser, Text: "a **b**"}}, "mm", 40, 0, c.get) | ||
| 196 | + if user[1].Text != " a **b**" { | ||
| 197 | + t.Errorf("a question is never rendered: %+v", user[1]) | ||
| 198 | + } | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +// The cache lays an answer out once per width. | ||
| 202 | +func TestMdCache(t *testing.T) { | ||
| 203 | + var c mdCache | ||
| 204 | + a := c.get("**x**", 40) | ||
| 205 | + b := c.get("**x**", 40) | ||
| 206 | + if &a[0] != &b[0] { | ||
| 207 | + t.Error("same text, same width: not taken from the cache") | ||
| 208 | + } | ||
| 209 | + if d := c.get("**x**", 20); &d[0] == &a[0] { | ||
| 210 | + t.Error("another width must lay it out again") | ||
| 211 | + } | ||
| 212 | +} | ||
| 213 | + | ||
| 214 | +// Transcript.Entries marks the answer being written, and only it. | ||
| 215 | +func TestEntriesMarksTheOpenAnswer(t *testing.T) { | ||
| 216 | + tr := &Transcript{} | ||
| 217 | + tr.Chunk("first") | ||
| 218 | + if e := tr.Entries(); !e[0].Open { | ||
| 219 | + t.Fatal("streaming answer not open") | ||
| 220 | + } | ||
| 221 | + tr.Close() | ||
| 222 | + if e := tr.Entries(); e[0].Open { | ||
| 223 | + t.Error("closed answer still open") | ||
| 224 | + } | ||
| 225 | + tr.Chunk("second") | ||
| 226 | + tr.ToolStart(ui.ToolEvent{ID: "1", Tool: "bash", Title: "bash: ls"}) | ||
| 227 | + if e := tr.Entries(); e[1].Open { | ||
| 228 | + t.Error("a tool call closes the answer before it") | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +// On screen: a closed answer is drawn without its markers, in its styles. | ||
| 233 | +func TestScreenDrawsRenderedAnswer(t *testing.T) { | ||
| 234 | + hs := newHarness(t, 60, 12) | ||
| 235 | + hs.v.t.Chunk("Use **yolo: false** and `mm -tui`.") | ||
| 236 | + if text := hs.screenText(); !strings.Contains(text, "Use **yolo: false** and `mm -tui`.") { | ||
| 237 | + t.Fatalf("while open, raw:\n%s", text) | ||
| 238 | + } | ||
| 239 | + hs.v.t.Close() | ||
| 240 | + text := hs.screenText() | ||
| 241 | + if !strings.Contains(text, "Use yolo: false and mm -tui.") || strings.Contains(text, "**") { | ||
| 242 | + t.Errorf("closed, rendered:\n%s", text) | ||
| 243 | + } | ||
| 244 | +} | ||
| 245 | + | ||
| 246 | +// renderMarkdown: false keeps every answer raw, closed or not (ticket 274); | ||
| 247 | +// it is on by default. | ||
| 248 | +func TestRenderMarkdownSwitch(t *testing.T) { | ||
| 249 | + saved := config.Cfg.RenderMarkdown | ||
| 250 | + t.Cleanup(func() { config.Cfg.RenderMarkdown = saved }) | ||
| 251 | + if !saved { | ||
| 252 | + t.Fatal("renderMarkdown must be on by default") | ||
| 253 | + } | ||
| 254 | + config.Cfg.RenderMarkdown = false | ||
| 255 | + hs := newHarness(t, 60, 12) | ||
| 256 | + hs.v.t.Chunk("Use **yolo: false**.") | ||
| 257 | + hs.v.t.Close() | ||
| 258 | + if text := hs.screenText(); !strings.Contains(text, "Use **yolo: false**.") { | ||
| 259 | + t.Errorf("off: the closed answer must stay raw:\n%s", text) | ||
| 260 | + } | ||
| 261 | +} | ||
modified
internal/tui/render.go +26 -1 | @@ -23,13 +23,22 @@ const ( | ||
| 23 | 23 | styleDiffDel |
| 24 | 24 | styleThinking |
| 25 | 25 | styleDisplay |
| 26 | + // Markdown (markdown.go): a heading, a list bullet, a quote and its bar, | |
| 27 | + // a rule or a table's lines. | |
| 28 | + styleHeading | |
| 29 | + styleBullet | |
| 30 | + styleQuote | |
| 31 | + styleRule | |
| 26 | 32 | ) |
| 27 | 33 | |
| 28 | 34 | // Line is one drawn line of the conversation: its text, wrapped to the width |
| 29 | -// asked for, and how to colour it. | |
| 35 | +// asked for, and how to colour it. A rendered answer (markdown.go) gives its | |
| 36 | +// lines Spans — runs of their own style —, Text then being their plain text; | |
| 37 | +// a line without Spans is drawn in Style, as every line was before. | |
| 30 | 38 | type Line struct { |
| 31 | 39 | Text string |
| 32 | 40 | Style styleKind |
| 41 | + Spans []Span | |
| 33 | 42 | } |
| 34 | 43 | |
| 35 | 44 | // indent is the margin content lines are drawn at, under their label. |
| @@ -43,11 +52,27 @@ var pad = strings.Repeat(" ", indent) | ||
| 43 | 52 | // a tool's output is folded to previewLines lines. agentName labels the |
| 44 | 53 | // answers; previewLines <= 0 shows every line of output. |
| 45 | 54 | func layout(entries []Entry, agentName string, width, previewLines int) []Line { |
| 55 | + return layoutWith(entries, agentName, width, previewLines, nil) | |
| 56 | +} | |
| 57 | + | |
| 58 | +// layoutWith is layout with a Markdown renderer for the closed answers | |
| 59 | +// (markdown.go): md(text, width) gives the lines of an answer whose entry is | |
| 60 | +// no longer open; nil, or the answer being written, keeps the raw body. | |
| 61 | +func layoutWith(entries []Entry, agentName string, width, previewLines int, md func(string, int) []Line) []Line { | |
| 46 | 62 | var out []Line |
| 47 | 63 | for i, e := range entries { |
| 48 | 64 | if i > 0 { |
| 49 | 65 | out = append(out, Line{}) |
| 50 | 66 | } |
| 67 | + if e.Kind == KindAgent && !e.Open && md != nil { | |
| 68 | + who := agentName | |
| 69 | + if e.Who != "" { | |
| 70 | + who = e.Who | |
| 71 | + } | |
| 72 | + out = append(out, label(who)...) | |
| 73 | + out = append(out, md(e.Text, width)...) | |
| 74 | + continue | |
| 75 | + } | |
| 51 | 76 | out = append(out, linesOf(e, agentName, width, previewLines)...) |
| 52 | 77 | } |
| 53 | 78 | return out |
| @@ -23,13 +23,22 @@ const ( | |||
| 23 | styleDiffDel | 23 | styleDiffDel |
| 24 | styleThinking | 24 | styleThinking |
| 25 | styleDisplay | 25 | styleDisplay |
| 26 | + // Markdown (markdown.go): a heading, a list bullet, a quote and its bar, | ||
| 27 | + // a rule or a table's lines. | ||
| 28 | + styleHeading | ||
| 29 | + styleBullet | ||
| 30 | + styleQuote | ||
| 31 | + styleRule | ||
| 26 | ) | 32 | ) |
| 27 | 33 | ||
| 28 | // Line is one drawn line of the conversation: its text, wrapped to the width | 34 | // Line is one drawn line of the conversation: its text, wrapped to the width |
| 29 | -// asked for, and how to colour it. | 35 | +// asked for, and how to colour it. A rendered answer (markdown.go) gives its |
| 36 | +// lines Spans — runs of their own style —, Text then being their plain text; | ||
| 37 | +// a line without Spans is drawn in Style, as every line was before. | ||
| 30 | type Line struct { | 38 | type Line struct { |
| 31 | Text string | 39 | Text string |
| 32 | Style styleKind | 40 | Style styleKind |
| 41 | + Spans []Span | ||
| 33 | } | 42 | } |
| 34 | 43 | ||
| 35 | // indent is the margin content lines are drawn at, under their label. | 44 | // indent is the margin content lines are drawn at, under their label. |
| @@ -43,11 +52,27 @@ var pad = strings.Repeat(" ", indent) | |||
| 43 | // a tool's output is folded to previewLines lines. agentName labels the | 52 | // a tool's output is folded to previewLines lines. agentName labels the |
| 44 | // answers; previewLines <= 0 shows every line of output. | 53 | // answers; previewLines <= 0 shows every line of output. |
| 45 | func layout(entries []Entry, agentName string, width, previewLines int) []Line { | 54 | func layout(entries []Entry, agentName string, width, previewLines int) []Line { |
| 55 | + return layoutWith(entries, agentName, width, previewLines, nil) | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +// layoutWith is layout with a Markdown renderer for the closed answers | ||
| 59 | +// (markdown.go): md(text, width) gives the lines of an answer whose entry is | ||
| 60 | +// no longer open; nil, or the answer being written, keeps the raw body. | ||
| 61 | +func layoutWith(entries []Entry, agentName string, width, previewLines int, md func(string, int) []Line) []Line { | ||
| 46 | var out []Line | 62 | var out []Line |
| 47 | for i, e := range entries { | 63 | for i, e := range entries { |
| 48 | if i > 0 { | 64 | if i > 0 { |
| 49 | out = append(out, Line{}) | 65 | out = append(out, Line{}) |
| 50 | } | 66 | } |
| 67 | + if e.Kind == KindAgent && !e.Open && md != nil { | ||
| 68 | + who := agentName | ||
| 69 | + if e.Who != "" { | ||
| 70 | + who = e.Who | ||
| 71 | + } | ||
| 72 | + out = append(out, label(who)...) | ||
| 73 | + out = append(out, md(e.Text, width)...) | ||
| 74 | + continue | ||
| 75 | + } | ||
| 51 | out = append(out, linesOf(e, agentName, width, previewLines)...) | 76 | out = append(out, linesOf(e, agentName, width, previewLines)...) |
| 52 | } | 77 | } |
| 53 | return out | 78 | return out |
modified
internal/tui/style.go +32 -0 | @@ -48,6 +48,38 @@ var styles = map[styleKind]tcell.Style{ | ||
| 48 | 48 | styleDiffDel: stDiffDel, |
| 49 | 49 | styleThinking: stThinking, |
| 50 | 50 | styleDisplay: stDisplay, |
| 51 | + styleHeading: stHeading, | |
| 52 | + styleBullet: stBullet, | |
| 53 | + styleQuote: stQuote, | |
| 54 | + styleRule: stRule, | |
| 55 | +} | |
| 56 | + | |
| 57 | +// The Markdown styles (markdown.go), on the terminal's own colours too. | |
| 58 | +var ( | |
| 59 | + stHeading = tcell.StyleDefault.Foreground(tcell.ColorTeal) | |
| 60 | + stBullet = tcell.StyleDefault.Foreground(tcell.ColorTeal) | |
| 61 | + stQuote = tcell.StyleDefault.Italic(true).Foreground(tcell.ColorGray) | |
| 62 | +) | |
| 63 | + | |
| 64 | +// spanStyle is a span's screen style: its kind's, plus its attributes. | |
| 65 | +func spanStyle(s Span) tcell.Style { | |
| 66 | + st := styleOf(s.Style) | |
| 67 | + if s.Attr&attrBold != 0 { | |
| 68 | + st = st.Bold(true) | |
| 69 | + } | |
| 70 | + if s.Attr&attrItalic != 0 { | |
| 71 | + st = st.Italic(true) | |
| 72 | + } | |
| 73 | + if s.Attr&attrStrike != 0 { | |
| 74 | + st = st.StrikeThrough(true) | |
| 75 | + } | |
| 76 | + if s.Attr&attrUnderline != 0 { | |
| 77 | + st = st.Underline(true) | |
| 78 | + } | |
| 79 | + if s.Attr&attrDim != 0 { | |
| 80 | + st = st.Dim(true) | |
| 81 | + } | |
| 82 | + return st | |
| 51 | 83 | } |
| 52 | 84 | |
| 53 | 85 | // styleOf returns the screen style of a laid-out line's kind. |
| @@ -48,6 +48,38 @@ var styles = map[styleKind]tcell.Style{ | |||
| 48 | styleDiffDel: stDiffDel, | 48 | styleDiffDel: stDiffDel, |
| 49 | styleThinking: stThinking, | 49 | styleThinking: stThinking, |
| 50 | styleDisplay: stDisplay, | 50 | styleDisplay: stDisplay, |
| 51 | + styleHeading: stHeading, | ||
| 52 | + styleBullet: stBullet, | ||
| 53 | + styleQuote: stQuote, | ||
| 54 | + styleRule: stRule, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +// The Markdown styles (markdown.go), on the terminal's own colours too. | ||
| 58 | +var ( | ||
| 59 | + stHeading = tcell.StyleDefault.Foreground(tcell.ColorTeal) | ||
| 60 | + stBullet = tcell.StyleDefault.Foreground(tcell.ColorTeal) | ||
| 61 | + stQuote = tcell.StyleDefault.Italic(true).Foreground(tcell.ColorGray) | ||
| 62 | +) | ||
| 63 | + | ||
| 64 | +// spanStyle is a span's screen style: its kind's, plus its attributes. | ||
| 65 | +func spanStyle(s Span) tcell.Style { | ||
| 66 | + st := styleOf(s.Style) | ||
| 67 | + if s.Attr&attrBold != 0 { | ||
| 68 | + st = st.Bold(true) | ||
| 69 | + } | ||
| 70 | + if s.Attr&attrItalic != 0 { | ||
| 71 | + st = st.Italic(true) | ||
| 72 | + } | ||
| 73 | + if s.Attr&attrStrike != 0 { | ||
| 74 | + st = st.StrikeThrough(true) | ||
| 75 | + } | ||
| 76 | + if s.Attr&attrUnderline != 0 { | ||
| 77 | + st = st.Underline(true) | ||
| 78 | + } | ||
| 79 | + if s.Attr&attrDim != 0 { | ||
| 80 | + st = st.Dim(true) | ||
| 81 | + } | ||
| 82 | + return st | ||
| 51 | } | 83 | } |
| 52 | 84 | ||
| 53 | // styleOf returns the screen style of a laid-out line's kind. | 85 | // styleOf returns the screen style of a laid-out line's kind. |
modified
internal/tui/transcript.go +9 -1 | @@ -64,6 +64,10 @@ type Entry struct { | ||
| 64 | 64 | Started time.Time |
| 65 | 65 | Elapsed time.Duration |
| 66 | 66 | Diff bool // the output is a file diff (edit tools): +/- lines get colour |
| 67 | + | |
| 68 | + // Open marks the answer still being written (KindAgent): set by Entries | |
| 69 | + // on a copy, never stored. A closed answer is drawn as Markdown. | |
| 70 | + Open bool | |
| 67 | 71 | } |
| 68 | 72 | |
| 69 | 73 | // Detail is what the tool was asked, without the tool's own name prefix: |
| @@ -93,7 +97,11 @@ type Transcript struct { | ||
| 93 | 97 | func (t *Transcript) Entries() []Entry { |
| 94 | 98 | t.mu.Lock() |
| 95 | 99 | defer t.mu.Unlock() |
| 96 | - return append([]Entry(nil), t.entries...) | |
| 100 | + out := append([]Entry(nil), t.entries...) | |
| 101 | + if last := len(out) - 1; t.open && last >= 0 && out[last].Kind == KindAgent { | |
| 102 | + out[last].Open = true | |
| 103 | + } | |
| 104 | + return out | |
| 97 | 105 | } |
| 98 | 106 | |
| 99 | 107 | // Len is how many entries the conversation holds. |
| @@ -64,6 +64,10 @@ type Entry struct { | |||
| 64 | Started time.Time | 64 | Started time.Time |
| 65 | Elapsed time.Duration | 65 | Elapsed time.Duration |
| 66 | Diff bool // the output is a file diff (edit tools): +/- lines get colour | 66 | Diff bool // the output is a file diff (edit tools): +/- lines get colour |
| 67 | + | ||
| 68 | + // Open marks the answer still being written (KindAgent): set by Entries | ||
| 69 | + // on a copy, never stored. A closed answer is drawn as Markdown. | ||
| 70 | + Open bool | ||
| 67 | } | 71 | } |
| 68 | 72 | ||
| 69 | // Detail is what the tool was asked, without the tool's own name prefix: | 73 | // Detail is what the tool was asked, without the tool's own name prefix: |
| @@ -93,7 +97,11 @@ type Transcript struct { | |||
| 93 | func (t *Transcript) Entries() []Entry { | 97 | func (t *Transcript) Entries() []Entry { |
| 94 | t.mu.Lock() | 98 | t.mu.Lock() |
| 95 | defer t.mu.Unlock() | 99 | defer t.mu.Unlock() |
| 96 | - return append([]Entry(nil), t.entries...) | 100 | + out := append([]Entry(nil), t.entries...) |
| 101 | + if last := len(out) - 1; t.open && last >= 0 && out[last].Kind == KindAgent { | ||
| 102 | + out[last].Open = true | ||
| 103 | + } | ||
| 104 | + return out | ||
| 97 | } | 105 | } |
| 98 | 106 | ||
| 99 | // Len is how many entries the conversation holds. | 107 | // Len is how many entries the conversation holds. |
modified
internal/tui/transcript_test.go +1 -1 | @@ -191,7 +191,7 @@ func TestDisplayIsDrawnVerbatimUnderItsLabel(t *testing.T) { | ||
| 191 | 191 | t.Fatalf("lines = %+v", lines) |
| 192 | 192 | } |
| 193 | 193 | for i := range want { |
| 194 | - if lines[i] != want[i] { | |
| 194 | + if lines[i].Text != want[i].Text || lines[i].Style != want[i].Style || lines[i].Spans != nil { | |
| 195 | 195 | t.Errorf("line %d = %+v, want %+v", i, lines[i], want[i]) |
| 196 | 196 | } |
| 197 | 197 | } |
| @@ -191,7 +191,7 @@ func TestDisplayIsDrawnVerbatimUnderItsLabel(t *testing.T) { | |||
| 191 | t.Fatalf("lines = %+v", lines) | 191 | t.Fatalf("lines = %+v", lines) |
| 192 | } | 192 | } |
| 193 | for i := range want { | 193 | for i := range want { |
| 194 | - if lines[i] != want[i] { | 194 | + if lines[i].Text != want[i].Text || lines[i].Style != want[i].Style || lines[i].Spans != nil { |
| 195 | t.Errorf("line %d = %+v, want %+v", i, lines[i], want[i]) | 195 | t.Errorf("line %d = %+v, want %+v", i, lines[i], want[i]) |
| 196 | } | 196 | } |
| 197 | } | 197 | } |
modified
internal/tui/view.go +9 -2 | @@ -1,6 +1,7 @@ | ||
| 1 | 1 | package tui |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | + "mm/internal/config" | |
| 4 | 5 | "mm/internal/elicit" |
| 5 | 6 | "strings" |
| 6 | 7 | "time" |
| @@ -84,7 +85,9 @@ type View struct { | ||
| 84 | 85 | skills []skills.Skill |
| 85 | 86 | // metas is what the `[` picker offers (ticket 272); nil = the built-ins. |
| 86 | 87 | metas []metaprompt.MetaPrompt |
| 87 | - cwd string | |
| 88 | + // md caches the Markdown layout of the closed answers (markdown.go). | |
| 89 | + md mdCache | |
| 90 | + cwd string | |
| 88 | 91 | |
| 89 | 92 | // What the runner reports for the chrome, refreshed before each frame. |
| 90 | 93 | header string // the header line |
| @@ -188,7 +191,11 @@ func (v *View) transcriptWidth() int { | ||
| 188 | 191 | |
| 189 | 192 | // lines lays the conversation out at the current width. |
| 190 | 193 | func (v *View) lines() []Line { |
| 191 | - return layout(v.t.Entries(), v.agentName, v.transcriptWidth(), v.previewLines) | |
| 194 | + var md func(string, int) []Line | |
| 195 | + if config.Cfg.RenderMarkdown { | |
| 196 | + md = v.md.get // closed answers as Markdown (ticket 274) | |
| 197 | + } | |
| 198 | + return layoutWith(v.t.Entries(), v.agentName, v.transcriptWidth(), v.previewLines, md) | |
| 192 | 199 | } |
| 193 | 200 | |
| 194 | 201 | // scrollBy moves through the conversation and stops following the end as |
| @@ -1,6 +1,7 @@ | |||
| 1 | package tui | 1 | package tui |
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | + "mm/internal/config" | ||
| 4 | "mm/internal/elicit" | 5 | "mm/internal/elicit" |
| 5 | "strings" | 6 | "strings" |
| 6 | "time" | 7 | "time" |
| @@ -84,7 +85,9 @@ type View struct { | |||
| 84 | skills []skills.Skill | 85 | skills []skills.Skill |
| 85 | // metas is what the `[` picker offers (ticket 272); nil = the built-ins. | 86 | // metas is what the `[` picker offers (ticket 272); nil = the built-ins. |
| 86 | metas []metaprompt.MetaPrompt | 87 | metas []metaprompt.MetaPrompt |
| 87 | - cwd string | 88 | + // md caches the Markdown layout of the closed answers (markdown.go). |
| 89 | + md mdCache | ||
| 90 | + cwd string | ||
| 88 | 91 | ||
| 89 | // What the runner reports for the chrome, refreshed before each frame. | 92 | // What the runner reports for the chrome, refreshed before each frame. |
| 90 | header string // the header line | 93 | header string // the header line |
| @@ -188,7 +191,11 @@ func (v *View) transcriptWidth() int { | |||
| 188 | 191 | ||
| 189 | // lines lays the conversation out at the current width. | 192 | // lines lays the conversation out at the current width. |
| 190 | func (v *View) lines() []Line { | 193 | func (v *View) lines() []Line { |
| 191 | - return layout(v.t.Entries(), v.agentName, v.transcriptWidth(), v.previewLines) | 194 | + var md func(string, int) []Line |
| 195 | + if config.Cfg.RenderMarkdown { | ||
| 196 | + md = v.md.get // closed answers as Markdown (ticket 274) | ||
| 197 | + } | ||
| 198 | + return layoutWith(v.t.Entries(), v.agentName, v.transcriptWidth(), v.previewLines, md) | ||
| 192 | } | 199 | } |
| 193 | 200 | ||
| 194 | // scrollBy moves through the conversation and stops following the end as | 201 | // scrollBy moves through the conversation and stops following the end as |