modified
.tickets/issues/0254-measure-and-show-the-token-generation-speed-tokens-s.yaml +47 -7 | @@ -1,15 +1,16 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 254 |
| 3 | 3 | title: Measure and show the token generation speed (tokens/s) |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T06:32:51.000Z |
| 9 | -updatedAt: 2026-11-24T06:32:51.000Z | |
| 9 | +updatedAt: 2026-11-24T18:26:51.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - enhancement |
| 12 | 12 | - kind::feature |
| 13 | +milestone: v2.0.1 | |
| 13 | 14 | epic: Providers (LLM Engine) |
| 14 | 15 | body: | |
| 15 | 16 | Compute the model's generation speed and show it to the user, e.g. |
| @@ -59,34 +60,73 @@ body: | | ||
| 59 | 60 | tasks: |
| 60 | 61 | - id: 1 |
| 61 | 62 | title: List which servers send timings (llama-server, llmman, DMR, Kronk, Ollama, MLX-Serve) |
| 62 | - state: open | |
| 63 | + state: closed | |
| 63 | 64 | priority: high |
| 64 | 65 | author: |
| 65 | 66 | name: k33g |
| 66 | 67 | email: ph.charriere@gmail.com |
| 67 | 68 | createdAt: 2026-11-24T06:32:51.000Z |
| 69 | + updatedAt: 2026-11-24T18:07:30.000Z | |
| 70 | + closedAt: 2026-11-24T18:07:30.000Z | |
| 68 | 71 | - id: 2 |
| 69 | 72 | title: Read timings in the SSE tap; measure first-to-last token time as fallback |
| 70 | - state: open | |
| 73 | + state: closed | |
| 71 | 74 | priority: none |
| 72 | 75 | author: |
| 73 | 76 | name: k33g |
| 74 | 77 | email: ph.charriere@gmail.com |
| 75 | 78 | createdAt: 2026-11-24T06:32:51.000Z |
| 79 | + updatedAt: 2026-11-24T18:07:30.000Z | |
| 80 | + closedAt: 2026-11-24T18:07:30.000Z | |
| 76 | 81 | - id: 3 |
| 77 | 82 | title: Show the speed in the terminal, the window and (maybe) ACP |
| 78 | - state: open | |
| 83 | + state: closed | |
| 79 | 84 | priority: none |
| 80 | 85 | author: |
| 81 | 86 | name: k33g |
| 82 | 87 | email: ph.charriere@gmail.com |
| 83 | 88 | createdAt: 2026-11-24T06:32:51.000Z |
| 89 | + updatedAt: 2026-11-24T18:07:30.000Z | |
| 90 | + closedAt: 2026-11-24T18:07:30.000Z | |
| 84 | 91 | - id: 4 |
| 85 | 92 | title: Tests and EN+FR docs |
| 86 | - state: open | |
| 93 | + state: closed | |
| 87 | 94 | priority: none |
| 88 | 95 | author: |
| 89 | 96 | name: k33g |
| 90 | 97 | email: ph.charriere@gmail.com |
| 91 | 98 | createdAt: 2026-11-24T06:32:51.000Z |
| 92 | -comments: [] | |
| 99 | + updatedAt: 2026-11-24T18:07:30.000Z | |
| 100 | + closedAt: 2026-11-24T18:07:30.000Z | |
| 101 | +comments: | |
| 102 | + - id: 1 | |
| 103 | + author: | |
| 104 | + name: k33g | |
| 105 | + email: ph.charriere@gmail.com | |
| 106 | + createdAt: 2026-11-24T18:07:30.000Z | |
| 107 | + body: | | |
| 108 | + Decisions (user, 2026-11-24): milestone v2.0.1; the window's status bar | |
| 109 | + shows the call in progress while it streams (live estimate), then the | |
| 110 | + turn's average (tokens / decode time, tools left out); on by default | |
| 111 | + (`showSpeed`); ACP reports it. | |
| 112 | + Implemented on branch `feature/token-speed` (not committed): | |
| 113 | + - `internal/engine/speed.go`: a meter per Generate fed by the SSE tap | |
| 114 | + (first/last chunk that carries text, reasoning or a tool call; the | |
| 115 | + server's `timings`), settled per call with `usage.completion_tokens`, | |
| 116 | + live estimate every 0.5 s, turn average at the end; | |
| 117 | + - `ui.Speed` / `ui.SpeedSink` / `ui.ReportSpeed`; the window's sink keeps | |
| 118 | + it for `status()` (`⚡ ~58 tok/s` live, `⚡ 59.9 tok/s` after); | |
| 119 | + - ACP: finished call/turn in a `usage_update` `_meta.mm` | |
| 120 | + {tokensPerSecond, scope, source} — ACP has no field for it. | |
| 121 | + Servers: llama-server 12359 and MLX-Serve 26.11.3 send `timings`; | |
| 122 | + the others (llmman, DMR, Kronk, Ollama) not checked → measured. | |
| 123 | + Live: window on llama-server (gemma-3-1b): `⚡~58 tok/s` while | |
| 124 | + streaming, `⚡59.9 tok/s` after. The line mode shows nothing (not asked). | |
| 125 | + Not tested: the ACP `_meta` (no harness capturing session updates). | |
| 126 | + - id: 2 | |
| 127 | + author: | |
| 128 | + name: k33g | |
| 129 | + email: ph.charriere@gmail.com | |
| 130 | + createdAt: 2026-11-24T18:26:51.000Z | |
| 131 | + body: | | |
| 132 | + Tested by the user; merged into `main`. | |
| @@ -1,15 +1,16 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 254 | 2 | id: 254 |
| 3 | title: Measure and show the token generation speed (tokens/s) | 3 | title: Measure and show the token generation speed (tokens/s) |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T06:32:51.000Z | 8 | createdAt: 2026-11-24T06:32:51.000Z |
| 9 | -updatedAt: 2026-11-24T06:32:51.000Z | 9 | +updatedAt: 2026-11-24T18:26:51.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - enhancement | 11 | - enhancement |
| 12 | - kind::feature | 12 | - kind::feature |
| 13 | +milestone: v2.0.1 | ||
| 13 | epic: Providers (LLM Engine) | 14 | epic: Providers (LLM Engine) |
| 14 | body: | | 15 | body: | |
| 15 | Compute the model's generation speed and show it to the user, e.g. | 16 | Compute the model's generation speed and show it to the user, e.g. |
| @@ -59,34 +60,73 @@ body: | | |||
| 59 | tasks: | 60 | tasks: |
| 60 | - id: 1 | 61 | - id: 1 |
| 61 | title: List which servers send timings (llama-server, llmman, DMR, Kronk, Ollama, MLX-Serve) | 62 | title: List which servers send timings (llama-server, llmman, DMR, Kronk, Ollama, MLX-Serve) |
| 62 | - state: open | 63 | + state: closed |
| 63 | priority: high | 64 | priority: high |
| 64 | author: | 65 | author: |
| 65 | name: k33g | 66 | name: k33g |
| 66 | email: ph.charriere@gmail.com | 67 | email: ph.charriere@gmail.com |
| 67 | createdAt: 2026-11-24T06:32:51.000Z | 68 | createdAt: 2026-11-24T06:32:51.000Z |
| 69 | + updatedAt: 2026-11-24T18:07:30.000Z | ||
| 70 | + closedAt: 2026-11-24T18:07:30.000Z | ||
| 68 | - id: 2 | 71 | - id: 2 |
| 69 | title: Read timings in the SSE tap; measure first-to-last token time as fallback | 72 | title: Read timings in the SSE tap; measure first-to-last token time as fallback |
| 70 | - state: open | 73 | + state: closed |
| 71 | priority: none | 74 | priority: none |
| 72 | author: | 75 | author: |
| 73 | name: k33g | 76 | name: k33g |
| 74 | email: ph.charriere@gmail.com | 77 | email: ph.charriere@gmail.com |
| 75 | createdAt: 2026-11-24T06:32:51.000Z | 78 | createdAt: 2026-11-24T06:32:51.000Z |
| 79 | + updatedAt: 2026-11-24T18:07:30.000Z | ||
| 80 | + closedAt: 2026-11-24T18:07:30.000Z | ||
| 76 | - id: 3 | 81 | - id: 3 |
| 77 | title: Show the speed in the terminal, the window and (maybe) ACP | 82 | title: Show the speed in the terminal, the window and (maybe) ACP |
| 78 | - state: open | 83 | + state: closed |
| 79 | priority: none | 84 | priority: none |
| 80 | author: | 85 | author: |
| 81 | name: k33g | 86 | name: k33g |
| 82 | email: ph.charriere@gmail.com | 87 | email: ph.charriere@gmail.com |
| 83 | createdAt: 2026-11-24T06:32:51.000Z | 88 | createdAt: 2026-11-24T06:32:51.000Z |
| 89 | + updatedAt: 2026-11-24T18:07:30.000Z | ||
| 90 | + closedAt: 2026-11-24T18:07:30.000Z | ||
| 84 | - id: 4 | 91 | - id: 4 |
| 85 | title: Tests and EN+FR docs | 92 | title: Tests and EN+FR docs |
| 86 | - state: open | 93 | + state: closed |
| 87 | priority: none | 94 | priority: none |
| 88 | author: | 95 | author: |
| 89 | name: k33g | 96 | name: k33g |
| 90 | email: ph.charriere@gmail.com | 97 | email: ph.charriere@gmail.com |
| 91 | createdAt: 2026-11-24T06:32:51.000Z | 98 | createdAt: 2026-11-24T06:32:51.000Z |
| 92 | -comments: [] | 99 | + updatedAt: 2026-11-24T18:07:30.000Z |
| 100 | + closedAt: 2026-11-24T18:07:30.000Z | ||
| 101 | +comments: | ||
| 102 | + - id: 1 | ||
| 103 | + author: | ||
| 104 | + name: k33g | ||
| 105 | + email: ph.charriere@gmail.com | ||
| 106 | + createdAt: 2026-11-24T18:07:30.000Z | ||
| 107 | + body: | | ||
| 108 | + Decisions (user, 2026-11-24): milestone v2.0.1; the window's status bar | ||
| 109 | + shows the call in progress while it streams (live estimate), then the | ||
| 110 | + turn's average (tokens / decode time, tools left out); on by default | ||
| 111 | + (`showSpeed`); ACP reports it. | ||
| 112 | + Implemented on branch `feature/token-speed` (not committed): | ||
| 113 | + - `internal/engine/speed.go`: a meter per Generate fed by the SSE tap | ||
| 114 | + (first/last chunk that carries text, reasoning or a tool call; the | ||
| 115 | + server's `timings`), settled per call with `usage.completion_tokens`, | ||
| 116 | + live estimate every 0.5 s, turn average at the end; | ||
| 117 | + - `ui.Speed` / `ui.SpeedSink` / `ui.ReportSpeed`; the window's sink keeps | ||
| 118 | + it for `status()` (`⚡ ~58 tok/s` live, `⚡ 59.9 tok/s` after); | ||
| 119 | + - ACP: finished call/turn in a `usage_update` `_meta.mm` | ||
| 120 | + {tokensPerSecond, scope, source} — ACP has no field for it. | ||
| 121 | + Servers: llama-server 12359 and MLX-Serve 26.11.3 send `timings`; | ||
| 122 | + the others (llmman, DMR, Kronk, Ollama) not checked → measured. | ||
| 123 | + Live: window on llama-server (gemma-3-1b): `⚡~58 tok/s` while | ||
| 124 | + streaming, `⚡59.9 tok/s` after. The line mode shows nothing (not asked). | ||
| 125 | + Not tested: the ACP `_meta` (no harness capturing session updates). | ||
| 126 | + - id: 2 | ||
| 127 | + author: | ||
| 128 | + name: k33g | ||
| 129 | + email: ph.charriere@gmail.com | ||
| 130 | + createdAt: 2026-11-24T18:26:51.000Z | ||
| 131 | + body: | | ||
| 132 | + Tested by the user; merged into `main`. | ||
modified
docs/en/reference/cli.md +1 -0 | @@ -146,6 +146,7 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | ||
| 146 | 146 | | Keys | See [Slash commands — window keys](slash-commands.md#window-mode-keys). | |
| 147 | 147 | | Struggles | A badge on the right of the status bar until the next question — see [Struggle signals](#struggle-signals). | |
| 148 | 148 | | Completion duration | `⏱ <duration>` in the status bar, absent until the first question. During a turn or an `/ask` it counts up from the moment the question is sent, tools and hooks included, in tenths of a second (`⏱ 4.2s`) under a minute and in minutes and seconds beyond (`⏱ 2m05s`). When the turn ends — answered, failed or cancelled — it stops and keeps that duration until the next question. `/compact` is not timed. Hidden with `showCompletionTime: false` ([configuration](configuration.md)). | |
| 149 | +| Generation speed | `⚡ ~58 tok/s` after the duration while the model streams (an estimate), then `⚡ 59.9 tok/s`, the turn's average without the tools' time, until the next answer starts. The server's `timings` when it sends them, otherwise measured. `showSpeed: false` removes it | | |
| 149 | 150 | | Mouse | Not captured at start-up, so the terminal's click-and-drag selection works. `F2` captures it (wheel scrolling; `Shift`+drag selects) and releases it again. | |
| 150 | 151 | |
| 151 | 152 | ## Prompt mode specifics |
| @@ -146,6 +146,7 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | |||
| 146 | | Keys | See [Slash commands — window keys](slash-commands.md#window-mode-keys). | | 146 | | Keys | See [Slash commands — window keys](slash-commands.md#window-mode-keys). | |
| 147 | | Struggles | A badge on the right of the status bar until the next question — see [Struggle signals](#struggle-signals). | | 147 | | Struggles | A badge on the right of the status bar until the next question — see [Struggle signals](#struggle-signals). | |
| 148 | | Completion duration | `⏱ <duration>` in the status bar, absent until the first question. During a turn or an `/ask` it counts up from the moment the question is sent, tools and hooks included, in tenths of a second (`⏱ 4.2s`) under a minute and in minutes and seconds beyond (`⏱ 2m05s`). When the turn ends — answered, failed or cancelled — it stops and keeps that duration until the next question. `/compact` is not timed. Hidden with `showCompletionTime: false` ([configuration](configuration.md)). | | 148 | | Completion duration | `⏱ <duration>` in the status bar, absent until the first question. During a turn or an `/ask` it counts up from the moment the question is sent, tools and hooks included, in tenths of a second (`⏱ 4.2s`) under a minute and in minutes and seconds beyond (`⏱ 2m05s`). When the turn ends — answered, failed or cancelled — it stops and keeps that duration until the next question. `/compact` is not timed. Hidden with `showCompletionTime: false` ([configuration](configuration.md)). | |
| 149 | +| Generation speed | `⚡ ~58 tok/s` after the duration while the model streams (an estimate), then `⚡ 59.9 tok/s`, the turn's average without the tools' time, until the next answer starts. The server's `timings` when it sends them, otherwise measured. `showSpeed: false` removes it | | ||
| 149 | | Mouse | Not captured at start-up, so the terminal's click-and-drag selection works. `F2` captures it (wheel scrolling; `Shift`+drag selects) and releases it again. | | 150 | | Mouse | Not captured at start-up, so the terminal's click-and-drag selection works. `F2` captures it (wheel scrolling; `Shift`+drag selects) and releases it again. | |
| 150 | 151 | ||
| 151 | ## Prompt mode specifics | 152 | ## Prompt mode specifics |
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 | +| `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. | | |
| 25 | 26 | | `system` | string | built-in prompt | The system prompt, first message of every history. | |
| 26 | 27 | | `turnReminder` | string | `""` | A text appended to every question the model reads, under a `[reminder]` line, after the `preGeneration` hooks, in every front end (line mode, window, `-p`, editor). Kept in the history, like a hook's context; a question recalled with ↑ comes back without it. For a small model, a rule placed next to the question is followed more often than the same rule in the system prompt: measured in `demos/lfm-coder`, a rule asking it to call `ask_user` when a decision is missing was followed 0 times out of 5 from the system prompt, and 3 out of 3 next to the question with the exact call shape. Empty = none. | |
| 27 | 28 | | `structuredOutput` | string (Go declarations) | `""` | The shape every answer must follow, as JSON: Go `type` declarations and one `var` naming the root of the answer. See [`structuredOutput`](#structuredoutput) below. Empty = free-text answers. Incompatible with any declared tool. | |
| @@ -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 | +| `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. | | ||
| 25 | | `system` | string | built-in prompt | The system prompt, first message of every history. | | 26 | | `system` | string | built-in prompt | The system prompt, first message of every history. | |
| 26 | | `turnReminder` | string | `""` | A text appended to every question the model reads, under a `[reminder]` line, after the `preGeneration` hooks, in every front end (line mode, window, `-p`, editor). Kept in the history, like a hook's context; a question recalled with ↑ comes back without it. For a small model, a rule placed next to the question is followed more often than the same rule in the system prompt: measured in `demos/lfm-coder`, a rule asking it to call `ask_user` when a decision is missing was followed 0 times out of 5 from the system prompt, and 3 out of 3 next to the question with the exact call shape. Empty = none. | | 27 | | `turnReminder` | string | `""` | A text appended to every question the model reads, under a `[reminder]` line, after the `preGeneration` hooks, in every front end (line mode, window, `-p`, editor). Kept in the history, like a hook's context; a question recalled with ↑ comes back without it. For a small model, a rule placed next to the question is followed more often than the same rule in the system prompt: measured in `demos/lfm-coder`, a rule asking it to call `ask_user` when a decision is missing was followed 0 times out of 5 from the system prompt, and 3 out of 3 next to the question with the exact call shape. Empty = none. | |
| 27 | | `structuredOutput` | string (Go declarations) | `""` | The shape every answer must follow, as JSON: Go `type` declarations and one `var` naming the root of the answer. See [`structuredOutput`](#structuredoutput) below. Empty = free-text answers. Incompatible with any declared tool. | | 28 | | `structuredOutput` | string (Go declarations) | `""` | The shape every answer must follow, as JSON: Go `type` declarations and one `var` naming the root of the answer. See [`structuredOutput`](#structuredoutput) below. Empty = free-text answers. Incompatible with any declared tool. | |
modified
docs/fr/reference/cli.md +1 -0 | @@ -146,6 +146,7 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | ||
| 146 | 146 | | Touches | Voir [Commandes slash — touches du mode fenêtre](slash-commands.md#touches-du-mode-fenêtre). | |
| 147 | 147 | | Difficultés | Un badge à droite de la barre d'état jusqu'à la question suivante — voir [Signaux de difficulté](#signaux-de-difficulté). | |
| 148 | 148 | | Durée de la complétion | `⏱ <durée>` dans la barre d'état, absent avant la première question. Pendant un tour ou un `/ask`, le compteur défile depuis l'envoi de la question, outils et hooks compris, au dixième de seconde (`⏱ 4.2s`) sous la minute, en minutes et secondes au-delà (`⏱ 2m05s`). À la fin du tour — réponse, échec ou annulation — il s'arrête et garde cette durée jusqu'à la question suivante. `/compact` n'est pas chronométré. Masqué avec `showCompletionTime: false` ([configuration](configuration.md)). | |
| 149 | +| Vitesse de génération | `⚡ ~58 tok/s` après la durée pendant que le modèle génère (une estimation), puis `⚡ 59.9 tok/s`, la moyenne du tour sans le temps des outils, jusqu'au début de la réponse suivante. Les `timings` du serveur quand il en envoie, sinon une mesure de mm. `showSpeed: false` l'enlève | | |
| 149 | 150 | | Souris | Non capturée au démarrage, donc le cliquer-glisser du terminal sélectionne du texte. `F2` la capture (défilement à la molette ; `Maj`+glisser sélectionne) puis la rend. | |
| 150 | 151 | |
| 151 | 152 | ## Spécificités du mode invite |
| @@ -146,6 +146,7 @@ mm v0.1.7 | config: agent.llamacpp.yaml | provider: llamacpp | model: jetbrains/ | |||
| 146 | | Touches | Voir [Commandes slash — touches du mode fenêtre](slash-commands.md#touches-du-mode-fenêtre). | | 146 | | Touches | Voir [Commandes slash — touches du mode fenêtre](slash-commands.md#touches-du-mode-fenêtre). | |
| 147 | | Difficultés | Un badge à droite de la barre d'état jusqu'à la question suivante — voir [Signaux de difficulté](#signaux-de-difficulté). | | 147 | | Difficultés | Un badge à droite de la barre d'état jusqu'à la question suivante — voir [Signaux de difficulté](#signaux-de-difficulté). | |
| 148 | | Durée de la complétion | `⏱ <durée>` dans la barre d'état, absent avant la première question. Pendant un tour ou un `/ask`, le compteur défile depuis l'envoi de la question, outils et hooks compris, au dixième de seconde (`⏱ 4.2s`) sous la minute, en minutes et secondes au-delà (`⏱ 2m05s`). À la fin du tour — réponse, échec ou annulation — il s'arrête et garde cette durée jusqu'à la question suivante. `/compact` n'est pas chronométré. Masqué avec `showCompletionTime: false` ([configuration](configuration.md)). | | 148 | | Durée de la complétion | `⏱ <durée>` dans la barre d'état, absent avant la première question. Pendant un tour ou un `/ask`, le compteur défile depuis l'envoi de la question, outils et hooks compris, au dixième de seconde (`⏱ 4.2s`) sous la minute, en minutes et secondes au-delà (`⏱ 2m05s`). À la fin du tour — réponse, échec ou annulation — il s'arrête et garde cette durée jusqu'à la question suivante. `/compact` n'est pas chronométré. Masqué avec `showCompletionTime: false` ([configuration](configuration.md)). | |
| 149 | +| Vitesse de génération | `⚡ ~58 tok/s` après la durée pendant que le modèle génère (une estimation), puis `⚡ 59.9 tok/s`, la moyenne du tour sans le temps des outils, jusqu'au début de la réponse suivante. Les `timings` du serveur quand il en envoie, sinon une mesure de mm. `showSpeed: false` l'enlève | | ||
| 149 | | Souris | Non capturée au démarrage, donc le cliquer-glisser du terminal sélectionne du texte. `F2` la capture (défilement à la molette ; `Maj`+glisser sélectionne) puis la rend. | | 150 | | Souris | Non capturée au démarrage, donc le cliquer-glisser du terminal sélectionne du texte. `F2` la capture (défilement à la molette ; `Maj`+glisser sélectionne) puis la rend. | |
| 150 | 151 | ||
| 151 | ## Spécificités du mode invite | 152 | ## Spécificités du mode invite |
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 | +| `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. | | |
| 25 | 26 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. | |
| 26 | 27 | | `turnReminder` | chaîne | `""` | Un texte ajouté à chaque question que lit le modèle, sous une ligne `[reminder]`, après les hooks `preGeneration`, dans toutes les interfaces (mode ligne, fenêtre, `-p`, éditeur). Gardé dans l'historique, comme le contexte d'un hook ; une question rappelée avec ↑ revient sans lui. Pour un petit modèle, une règle placée à côté de la question est mieux suivie que la même règle dans le prompt système : mesuré dans `demos/lfm-coder`, une règle lui demandant d'appeler `ask_user` quand une décision manque a été suivie 0 fois sur 5 depuis le prompt système, et 3 fois sur 3 à côté de la question avec la forme exacte de l'appel. Vide = aucun. | |
| 27 | 28 | | `structuredOutput` | chaîne (déclarations Go) | `""` | La forme que doit suivre chaque réponse, en JSON : des déclarations `type` Go et une `var` qui nomme la racine de la réponse. Voir [`structuredOutput`](#structuredoutput) ci-dessous. Vide = réponses en texte libre. Incompatible avec tout outil déclaré. | |
| @@ -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 | +| `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. | | ||
| 25 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. | | 26 | | `system` | chaîne | prompt intégré | Le prompt système, premier message de chaque historique. | |
| 26 | | `turnReminder` | chaîne | `""` | Un texte ajouté à chaque question que lit le modèle, sous une ligne `[reminder]`, après les hooks `preGeneration`, dans toutes les interfaces (mode ligne, fenêtre, `-p`, éditeur). Gardé dans l'historique, comme le contexte d'un hook ; une question rappelée avec ↑ revient sans lui. Pour un petit modèle, une règle placée à côté de la question est mieux suivie que la même règle dans le prompt système : mesuré dans `demos/lfm-coder`, une règle lui demandant d'appeler `ask_user` quand une décision manque a été suivie 0 fois sur 5 depuis le prompt système, et 3 fois sur 3 à côté de la question avec la forme exacte de l'appel. Vide = aucun. | | 27 | | `turnReminder` | chaîne | `""` | Un texte ajouté à chaque question que lit le modèle, sous une ligne `[reminder]`, après les hooks `preGeneration`, dans toutes les interfaces (mode ligne, fenêtre, `-p`, éditeur). Gardé dans l'historique, comme le contexte d'un hook ; une question rappelée avec ↑ revient sans lui. Pour un petit modèle, une règle placée à côté de la question est mieux suivie que la même règle dans le prompt système : mesuré dans `demos/lfm-coder`, une règle lui demandant d'appeler `ask_user` quand une décision manque a été suivie 0 fois sur 5 depuis le prompt système, et 3 fois sur 3 à côté de la question avec la forme exacte de l'appel. Vide = aucun. | |
| 27 | | `structuredOutput` | chaîne (déclarations Go) | `""` | La forme que doit suivre chaque réponse, en JSON : des déclarations `type` Go et une `var` qui nomme la racine de la réponse. Voir [`structuredOutput`](#structuredoutput) ci-dessous. Vide = réponses en texte libre. Incompatible avec tout outil déclaré. | | 28 | | `structuredOutput` | chaîne (déclarations Go) | `""` | La forme que doit suivre chaque réponse, en JSON : des déclarations `type` Go et une `var` qui nomme la racine de la réponse. Voir [`structuredOutput`](#structuredoutput) ci-dessous. Vide = réponses en texte libre. Incompatible avec tout outil déclaré. | |
modified
internal/acp/usage.go +34 -0 | @@ -2,6 +2,7 @@ package acp | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | + "math" | |
| 5 | 6 | |
| 6 | 7 | "mm/internal/compact" |
| 7 | 8 | "mm/internal/ui" |
| @@ -76,6 +77,39 @@ func (k *sink) Usage(r ui.Usage) { | ||
| 76 | 77 | |
| 77 | 78 | var _ ui.UsageSink = (*sink)(nil) |
| 78 | 79 | |
| 80 | +// Speed sends the generation speed (ticket 254) to the editor in a | |
| 81 | +// usage_update's _meta — ACP has no field for it; a client that does not | |
| 82 | +// know the key ignores it. Only the measures of a finished call or turn: the | |
| 83 | +// live estimates would be a notification every half second. | |
| 84 | +// | |
| 85 | +// "_meta": {"mm": {"tokensPerSecond": 48.2, "scope": "call", "source": "server"}} | |
| 86 | +func (k *sink) Speed(r ui.Speed) { | |
| 87 | + if r.Live { | |
| 88 | + return | |
| 89 | + } | |
| 90 | + scope, source := "call", "measured" | |
| 91 | + if r.Turn { | |
| 92 | + scope = "turn" | |
| 93 | + } | |
| 94 | + if r.FromServer { | |
| 95 | + source = "server" | |
| 96 | + } | |
| 97 | + _ = k.f.conn.SessionUpdate(k.ctx, sdk.SessionNotification{ | |
| 98 | + SessionId: k.sid, | |
| 99 | + Update: sdk.SessionUpdate{UsageUpdate: &sdk.SessionUsageUpdate{ | |
| 100 | + Used: contextUsed(k.s), | |
| 101 | + Size: k.f.e.ContextWindow, | |
| 102 | + Meta: map[string]any{"mm": map[string]any{ | |
| 103 | + "tokensPerSecond": math.Round(r.TokensPerSecond*10) / 10, | |
| 104 | + "scope": scope, | |
| 105 | + "source": source, | |
| 106 | + }}, | |
| 107 | + }}, | |
| 108 | + }) | |
| 109 | +} | |
| 110 | + | |
| 111 | +var _ ui.SpeedSink = (*sink)(nil) | |
| 112 | + | |
| 79 | 113 | // contextUsed is how full the session's context is: the server's measure of |
| 80 | 114 | // the last call when there is one, the character estimate of the history |
| 81 | 115 | // when it is larger — the same rule as the terminal UI's header, and for the |
| @@ -2,6 +2,7 @@ package acp | |||
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | "context" | 4 | "context" |
| 5 | + "math" | ||
| 5 | 6 | ||
| 6 | "mm/internal/compact" | 7 | "mm/internal/compact" |
| 7 | "mm/internal/ui" | 8 | "mm/internal/ui" |
| @@ -76,6 +77,39 @@ func (k *sink) Usage(r ui.Usage) { | |||
| 76 | 77 | ||
| 77 | var _ ui.UsageSink = (*sink)(nil) | 78 | var _ ui.UsageSink = (*sink)(nil) |
| 78 | 79 | ||
| 80 | +// Speed sends the generation speed (ticket 254) to the editor in a | ||
| 81 | +// usage_update's _meta — ACP has no field for it; a client that does not | ||
| 82 | +// know the key ignores it. Only the measures of a finished call or turn: the | ||
| 83 | +// live estimates would be a notification every half second. | ||
| 84 | +// | ||
| 85 | +// "_meta": {"mm": {"tokensPerSecond": 48.2, "scope": "call", "source": "server"}} | ||
| 86 | +func (k *sink) Speed(r ui.Speed) { | ||
| 87 | + if r.Live { | ||
| 88 | + return | ||
| 89 | + } | ||
| 90 | + scope, source := "call", "measured" | ||
| 91 | + if r.Turn { | ||
| 92 | + scope = "turn" | ||
| 93 | + } | ||
| 94 | + if r.FromServer { | ||
| 95 | + source = "server" | ||
| 96 | + } | ||
| 97 | + _ = k.f.conn.SessionUpdate(k.ctx, sdk.SessionNotification{ | ||
| 98 | + SessionId: k.sid, | ||
| 99 | + Update: sdk.SessionUpdate{UsageUpdate: &sdk.SessionUsageUpdate{ | ||
| 100 | + Used: contextUsed(k.s), | ||
| 101 | + Size: k.f.e.ContextWindow, | ||
| 102 | + Meta: map[string]any{"mm": map[string]any{ | ||
| 103 | + "tokensPerSecond": math.Round(r.TokensPerSecond*10) / 10, | ||
| 104 | + "scope": scope, | ||
| 105 | + "source": source, | ||
| 106 | + }}, | ||
| 107 | + }}, | ||
| 108 | + }) | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +var _ ui.SpeedSink = (*sink)(nil) | ||
| 112 | + | ||
| 79 | // contextUsed is how full the session's context is: the server's measure of | 113 | // contextUsed is how full the session's context is: the server's measure of |
| 80 | // the last call when there is one, the character estimate of the history | 114 | // the last call when there is one, the character estimate of the history |
| 81 | // when it is larger — the same rule as the terminal UI's header, and for the | 115 | // when it is larger — the same rule as the terminal UI's header, and for the |
modified
internal/config/config.go +8 -0 | @@ -199,6 +199,13 @@ type Config struct { | ||
| 199 | 199 | // nothing. Override: AGENT_UNLOAD_ON_EXIT. |
| 200 | 200 | UnloadOnExit bool `yaml:"unloadOnExit"` |
| 201 | 201 | |
| 202 | + // ShowSpeed: the model's generation speed in tokens per second (ticket | |
| 203 | + // 254) — in the window's status bar (the call in progress while it | |
| 204 | + // streams, then the turn's average) and in ACP's usage updates. The | |
| 205 | + // server's own timings when it sends them, else measured from the first | |
| 206 | + // streamed token to the last. On by default. | |
| 207 | + ShowSpeed bool `yaml:"showSpeed"` | |
| 208 | + | |
| 202 | 209 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself |
| 203 | 210 | // when nothing answers (ticket 223). See LlamaCppConfig. |
| 204 | 211 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` |
| @@ -842,6 +849,7 @@ var Cfg = Config{ | ||
| 842 | 849 | AskUserTool: true, |
| 843 | 850 | UnloadModels: true, |
| 844 | 851 | UnloadOnExit: true, |
| 852 | + ShowSpeed: true, | |
| 845 | 853 | // FetchContentTool stays false (the zero value): see its field comment. |
| 846 | 854 | System: `You are a coding agent working in a terminal. |
| 847 | 855 | You have a "bash" tool to run shell commands. |
| @@ -199,6 +199,13 @@ type Config struct { | |||
| 199 | // nothing. Override: AGENT_UNLOAD_ON_EXIT. | 199 | // nothing. Override: AGENT_UNLOAD_ON_EXIT. |
| 200 | UnloadOnExit bool `yaml:"unloadOnExit"` | 200 | UnloadOnExit bool `yaml:"unloadOnExit"` |
| 201 | 201 | ||
| 202 | + // ShowSpeed: the model's generation speed in tokens per second (ticket | ||
| 203 | + // 254) — in the window's status bar (the call in progress while it | ||
| 204 | + // streams, then the turn's average) and in ACP's usage updates. The | ||
| 205 | + // server's own timings when it sends them, else measured from the first | ||
| 206 | + // streamed token to the last. On by default. | ||
| 207 | + ShowSpeed bool `yaml:"showSpeed"` | ||
| 208 | + | ||
| 202 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself | 209 | // LlamaCpp: provider llamacpp only — mm starts llama-server itself |
| 203 | // when nothing answers (ticket 223). See LlamaCppConfig. | 210 | // when nothing answers (ticket 223). See LlamaCppConfig. |
| 204 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` | 211 | LlamaCpp LlamaCppConfig `yaml:"llamacpp"` |
| @@ -842,6 +849,7 @@ var Cfg = Config{ | |||
| 842 | AskUserTool: true, | 849 | AskUserTool: true, |
| 843 | UnloadModels: true, | 850 | UnloadModels: true, |
| 844 | UnloadOnExit: true, | 851 | UnloadOnExit: true, |
| 852 | + ShowSpeed: true, | ||
| 845 | // FetchContentTool stays false (the zero value): see its field comment. | 853 | // FetchContentTool stays false (the zero value): see its field comment. |
| 846 | System: `You are a coding agent working in a terminal. | 854 | System: `You are a coding agent working in a terminal. |
| 847 | You have a "bash" tool to run shell commands. | 855 | You have a "bash" tool to run shell commands. |
modified
internal/engine/engine.go +16 -0 | @@ -333,6 +333,14 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 333 | 333 | // `New` is called once per `Generate`, which keeps `full` captured at the |
| 334 | 334 | // right level. |
| 335 | 335 | var full []*ai.Message |
| 336 | + // speed measures the generation speed of each call and of the turn | |
| 337 | + // (speed.go, ticket 254); nil with showSpeed off. | |
| 338 | + speed := turnSpeedMeter() | |
| 339 | + defer func() { | |
| 340 | + if speed != nil { | |
| 341 | + speed.finish() | |
| 342 | + } | |
| 343 | + }() | |
| 336 | 344 | // reply is the model's latest message — for a tool, the one that called |
| 337 | 345 | // it (reply.go). |
| 338 | 346 | var reply *ai.Message |
| @@ -488,6 +496,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 488 | 496 | // An event-consuming front end (ACP) wants the counts of |
| 489 | 497 | // every call, not just the last input: the client shows the |
| 490 | 498 | // context meter and the tokens a turn cost. |
| 499 | + if speed != nil && resp != nil { | |
| 500 | + out := 0 | |
| 501 | + if resp.Usage != nil { | |
| 502 | + out = resp.Usage.OutputTokens | |
| 503 | + } | |
| 504 | + speed.settle(out) | |
| 505 | + } | |
| 491 | 506 | if resp != nil && resp.Usage != nil { |
| 492 | 507 | if s, ok := ui.ActiveSink().(ui.UsageSink); ok { |
| 493 | 508 | s.Usage(ui.Usage{ |
| @@ -614,6 +629,7 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | ||
| 614 | 629 | genCtx, _ = withServerErrors(genCtx) |
| 615 | 630 | // While the server reads the prompt it says how far it got: proof of life |
| 616 | 631 | // for the watchdog, and something to show instead of "Thinking". |
| 632 | + genCtx = withSpeed(genCtx, speed) | |
| 617 | 633 | genCtx = withPromptProgress(genCtx, func(pp promptProgress) { |
| 618 | 634 | pl.alive() |
| 619 | 635 | if pl.waiting.Load() { |
| @@ -333,6 +333,14 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 333 | // `New` is called once per `Generate`, which keeps `full` captured at the | 333 | // `New` is called once per `Generate`, which keeps `full` captured at the |
| 334 | // right level. | 334 | // right level. |
| 335 | var full []*ai.Message | 335 | var full []*ai.Message |
| 336 | + // speed measures the generation speed of each call and of the turn | ||
| 337 | + // (speed.go, ticket 254); nil with showSpeed off. | ||
| 338 | + speed := turnSpeedMeter() | ||
| 339 | + defer func() { | ||
| 340 | + if speed != nil { | ||
| 341 | + speed.finish() | ||
| 342 | + } | ||
| 343 | + }() | ||
| 336 | // reply is the model's latest message — for a tool, the one that called | 344 | // reply is the model's latest message — for a tool, the one that called |
| 337 | // it (reply.go). | 345 | // it (reply.go). |
| 338 | var reply *ai.Message | 346 | var reply *ai.Message |
| @@ -488,6 +496,13 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 488 | // An event-consuming front end (ACP) wants the counts of | 496 | // An event-consuming front end (ACP) wants the counts of |
| 489 | // every call, not just the last input: the client shows the | 497 | // every call, not just the last input: the client shows the |
| 490 | // context meter and the tokens a turn cost. | 498 | // context meter and the tokens a turn cost. |
| 499 | + if speed != nil && resp != nil { | ||
| 500 | + out := 0 | ||
| 501 | + if resp.Usage != nil { | ||
| 502 | + out = resp.Usage.OutputTokens | ||
| 503 | + } | ||
| 504 | + speed.settle(out) | ||
| 505 | + } | ||
| 491 | if resp != nil && resp.Usage != nil { | 506 | if resp != nil && resp.Usage != nil { |
| 492 | if s, ok := ui.ActiveSink().(ui.UsageSink); ok { | 507 | if s, ok := ui.ActiveSink().(ui.UsageSink); ok { |
| 493 | s.Usage(ui.Usage{ | 508 | s.Usage(ui.Usage{ |
| @@ -614,6 +629,7 @@ func (e *Engine) generate(ctx context.Context, messages []*ai.Message, tools []a | |||
| 614 | genCtx, _ = withServerErrors(genCtx) | 629 | genCtx, _ = withServerErrors(genCtx) |
| 615 | // While the server reads the prompt it says how far it got: proof of life | 630 | // While the server reads the prompt it says how far it got: proof of life |
| 616 | // for the watchdog, and something to show instead of "Thinking". | 631 | // for the watchdog, and something to show instead of "Thinking". |
| 632 | + genCtx = withSpeed(genCtx, speed) | ||
| 617 | genCtx = withPromptProgress(genCtx, func(pp promptProgress) { | 633 | genCtx = withPromptProgress(genCtx, func(pp promptProgress) { |
| 618 | pl.alive() | 634 | pl.alive() |
| 619 | if pl.waiting.Load() { | 635 | if pl.waiting.Load() { |
modified
internal/engine/reasoning.go +13 -3 | @@ -7,6 +7,7 @@ import ( | ||
| 7 | 7 | "net/http" |
| 8 | 8 | "slices" |
| 9 | 9 | "strings" |
| 10 | + "time" | |
| 10 | 11 | |
| 11 | 12 | "github.com/firebase/genkit/go/ai" |
| 12 | 13 | "github.com/openai/openai-go/option" |
| @@ -98,14 +99,18 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | ||
| 98 | 99 | on := reasoningFrom(req.Context()) |
| 99 | 100 | errs := serverErrorsFrom(req.Context()) |
| 100 | 101 | progress := promptProgressFrom(req.Context()) |
| 102 | + speed := speedFrom(req.Context()) | |
| 101 | 103 | resp, err := next(req) |
| 102 | - if (on == nil && errs == nil && progress == nil) || err != nil || resp == nil || resp.Body == nil { | |
| 104 | + if (on == nil && errs == nil && progress == nil && speed == nil) || err != nil || resp == nil || resp.Body == nil { | |
| 103 | 105 | return resp, err |
| 104 | 106 | } |
| 105 | 107 | if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { |
| 106 | 108 | return resp, nil |
| 107 | 109 | } |
| 108 | - tap := &sseTap{rc: resp.Body, on: on, onProgress: progress} | |
| 110 | + tap := &sseTap{rc: resp.Body, on: on, onProgress: progress, speed: speed} | |
| 111 | + if speed != nil { | |
| 112 | + speed.begin() | |
| 113 | + } | |
| 109 | 114 | if errs != nil { |
| 110 | 115 | tap.onErr = errs.record |
| 111 | 116 | } |
| @@ -127,7 +132,9 @@ type sseTap struct { | ||
| 127 | 132 | onErr func(string) // a server error event; nil = not listened to |
| 128 | 133 | // onProgress: a prompt_progress chunk (progress.go); nil = not listened to |
| 129 | 134 | onProgress func(promptProgress) |
| 130 | - buf []byte | |
| 135 | + // speed: the generation speed meter (speed.go); nil = not measured | |
| 136 | + speed *speedMeter | |
| 137 | + buf []byte | |
| 131 | 138 | } |
| 132 | 139 | |
| 133 | 140 | func (t *sseTap) Read(p []byte) (int, error) { |
| @@ -153,6 +160,9 @@ func (t *sseTap) scan(b []byte) { | ||
| 153 | 160 | } |
| 154 | 161 | line := string(t.buf[:i]) |
| 155 | 162 | t.buf = t.buf[i+1:] |
| 163 | + if t.speed != nil { | |
| 164 | + t.speed.line(line, time.Now()) | |
| 165 | + } | |
| 156 | 166 | if msg := serverErrorOf(line); msg != "" { |
| 157 | 167 | if t.onErr != nil { |
| 158 | 168 | t.onErr(msg) |
| @@ -7,6 +7,7 @@ import ( | |||
| 7 | "net/http" | 7 | "net/http" |
| 8 | "slices" | 8 | "slices" |
| 9 | "strings" | 9 | "strings" |
| 10 | + "time" | ||
| 10 | 11 | ||
| 11 | "github.com/firebase/genkit/go/ai" | 12 | "github.com/firebase/genkit/go/ai" |
| 12 | "github.com/openai/openai-go/option" | 13 | "github.com/openai/openai-go/option" |
| @@ -98,14 +99,18 @@ func reasoningTap(req *http.Request, next option.MiddlewareNext) (*http.Response | |||
| 98 | on := reasoningFrom(req.Context()) | 99 | on := reasoningFrom(req.Context()) |
| 99 | errs := serverErrorsFrom(req.Context()) | 100 | errs := serverErrorsFrom(req.Context()) |
| 100 | progress := promptProgressFrom(req.Context()) | 101 | progress := promptProgressFrom(req.Context()) |
| 102 | + speed := speedFrom(req.Context()) | ||
| 101 | resp, err := next(req) | 103 | resp, err := next(req) |
| 102 | - if (on == nil && errs == nil && progress == nil) || err != nil || resp == nil || resp.Body == nil { | 104 | + if (on == nil && errs == nil && progress == nil && speed == nil) || err != nil || resp == nil || resp.Body == nil { |
| 103 | return resp, err | 105 | return resp, err |
| 104 | } | 106 | } |
| 105 | if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { | 107 | if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { |
| 106 | return resp, nil | 108 | return resp, nil |
| 107 | } | 109 | } |
| 108 | - tap := &sseTap{rc: resp.Body, on: on, onProgress: progress} | 110 | + tap := &sseTap{rc: resp.Body, on: on, onProgress: progress, speed: speed} |
| 111 | + if speed != nil { | ||
| 112 | + speed.begin() | ||
| 113 | + } | ||
| 109 | if errs != nil { | 114 | if errs != nil { |
| 110 | tap.onErr = errs.record | 115 | tap.onErr = errs.record |
| 111 | } | 116 | } |
| @@ -127,7 +132,9 @@ type sseTap struct { | |||
| 127 | onErr func(string) // a server error event; nil = not listened to | 132 | onErr func(string) // a server error event; nil = not listened to |
| 128 | // onProgress: a prompt_progress chunk (progress.go); nil = not listened to | 133 | // onProgress: a prompt_progress chunk (progress.go); nil = not listened to |
| 129 | onProgress func(promptProgress) | 134 | onProgress func(promptProgress) |
| 130 | - buf []byte | 135 | + // speed: the generation speed meter (speed.go); nil = not measured |
| 136 | + speed *speedMeter | ||
| 137 | + buf []byte | ||
| 131 | } | 138 | } |
| 132 | 139 | ||
| 133 | func (t *sseTap) Read(p []byte) (int, error) { | 140 | func (t *sseTap) Read(p []byte) (int, error) { |
| @@ -153,6 +160,9 @@ func (t *sseTap) scan(b []byte) { | |||
| 153 | } | 160 | } |
| 154 | line := string(t.buf[:i]) | 161 | line := string(t.buf[:i]) |
| 155 | t.buf = t.buf[i+1:] | 162 | t.buf = t.buf[i+1:] |
| 163 | + if t.speed != nil { | ||
| 164 | + t.speed.line(line, time.Now()) | ||
| 165 | + } | ||
| 156 | if msg := serverErrorOf(line); msg != "" { | 166 | if msg := serverErrorOf(line); msg != "" { |
| 157 | if t.onErr != nil { | 167 | if t.onErr != nil { |
| 158 | t.onErr(msg) | 168 | t.onErr(msg) |
added
internal/engine/speed.go +188 -0 | new file mode 100644 | ||
| @@ -0,0 +1,188 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "encoding/json" | |
| 6 | + "strings" | |
| 7 | + "sync" | |
| 8 | + "time" | |
| 9 | + | |
| 10 | + "mm/internal/config" | |
| 11 | + "mm/internal/ui" | |
| 12 | +) | |
| 13 | + | |
| 14 | +// The generation speed (ticket 254), in tokens per second, from two sources | |
| 15 | +// in this order: | |
| 16 | +// | |
| 17 | +// 1. the server's own `timings`, beside `usage` in the last streamed chunk | |
| 18 | +// (llama.cpp style: predicted_n, predicted_ms, predicted_per_second) — | |
| 19 | +// exact, and the prompt reading is not in it. Measured on MLX-Serve | |
| 20 | +// 26.11.3 and llama-server build 12359 (2026-11-24); | |
| 21 | +// 2. otherwise measured by mm: the call's output tokens (`usage`) over the | |
| 22 | +// time from the FIRST streamed chunk to the last — not from the request, | |
| 23 | +// which would count the prompt reading. With no `usage`, the streamed | |
| 24 | +// chunks are counted instead (about one token each). | |
| 25 | +// | |
| 26 | +// While a call streams, an estimate is reported every half second (chunks | |
| 27 | +// over time); when the call ends, its measure; when the turn ends, the | |
| 28 | +// turn's tokens over its decode time — the tools' run time left out. | |
| 29 | + | |
| 30 | +// speedMeter measures one Generate. The stream tap feeds it (begin, line); | |
| 31 | +// the engine settles each call and the turn. | |
| 32 | +type speedMeter struct { | |
| 33 | + mu sync.Mutex | |
| 34 | + // the call in flight | |
| 35 | + first, last time.Time | |
| 36 | + chunks int | |
| 37 | + timings *serverTimings | |
| 38 | + lastLive time.Time | |
| 39 | + // the turn so far | |
| 40 | + turnTokens int | |
| 41 | + turnDecode time.Duration | |
| 42 | + report func(ui.Speed) | |
| 43 | +} | |
| 44 | + | |
| 45 | +// serverTimings is the `timings` object of a llama.cpp-style server. | |
| 46 | +type serverTimings struct { | |
| 47 | + PredictedN int `json:"predicted_n"` | |
| 48 | + PredictedMS float64 `json:"predicted_ms"` | |
| 49 | + PredictedPS float64 `json:"predicted_per_second"` | |
| 50 | +} | |
| 51 | + | |
| 52 | +// liveEvery spaces the live estimates. | |
| 53 | +const liveEvery = 500 * time.Millisecond | |
| 54 | + | |
| 55 | +func newSpeedMeter(report func(ui.Speed)) *speedMeter { | |
| 56 | + return &speedMeter{report: report} | |
| 57 | +} | |
| 58 | + | |
| 59 | +type speedKey struct{} | |
| 60 | + | |
| 61 | +// withSpeed returns a context whose streamed requests feed m; nil when the | |
| 62 | +// speed is not shown (showSpeed: false). | |
| 63 | +func withSpeed(ctx context.Context, m *speedMeter) context.Context { | |
| 64 | + if m == nil { | |
| 65 | + return ctx | |
| 66 | + } | |
| 67 | + return context.WithValue(ctx, speedKey{}, m) | |
| 68 | +} | |
| 69 | + | |
| 70 | +func speedFrom(ctx context.Context) *speedMeter { | |
| 71 | + m, _ := ctx.Value(speedKey{}).(*speedMeter) | |
| 72 | + return m | |
| 73 | +} | |
| 74 | + | |
| 75 | +// begin starts a new call: one streamed request. | |
| 76 | +func (m *speedMeter) begin() { | |
| 77 | + m.mu.Lock() | |
| 78 | + defer m.mu.Unlock() | |
| 79 | + m.first, m.last, m.chunks, m.timings, m.lastLive = time.Time{}, time.Time{}, 0, nil, time.Time{} | |
| 80 | +} | |
| 81 | + | |
| 82 | +// speedChunk is the little of a chunk the meter reads. | |
| 83 | +type speedChunk struct { | |
| 84 | + Choices []struct { | |
| 85 | + Delta map[string]any `json:"delta"` | |
| 86 | + } `json:"choices"` | |
| 87 | + Timings *serverTimings `json:"timings"` | |
| 88 | +} | |
| 89 | + | |
| 90 | +// line reads one SSE line of the call in flight: a chunk that carries | |
| 91 | +// something (text, reasoning, a tool call) moves the clock, a `timings` | |
| 92 | +// object is kept. | |
| 93 | +func (m *speedMeter) line(line string, now time.Time) { | |
| 94 | + if !strings.Contains(line, `"delta"`) && !strings.Contains(line, `"timings"`) { | |
| 95 | + return | |
| 96 | + } | |
| 97 | + data, ok := strings.CutPrefix(strings.TrimSpace(line), "data:") | |
| 98 | + if !ok { | |
| 99 | + return | |
| 100 | + } | |
| 101 | + var c speedChunk | |
| 102 | + if json.Unmarshal([]byte(strings.TrimSpace(data)), &c) != nil { | |
| 103 | + return | |
| 104 | + } | |
| 105 | + m.mu.Lock() | |
| 106 | + defer m.mu.Unlock() | |
| 107 | + if c.Timings != nil && c.Timings.PredictedN > 0 { | |
| 108 | + m.timings = c.Timings | |
| 109 | + } | |
| 110 | + if len(c.Choices) == 0 || !carries(c.Choices[0].Delta) { | |
| 111 | + return | |
| 112 | + } | |
| 113 | + if m.first.IsZero() { | |
| 114 | + // The first estimate waits liveEvery: two chunks are too few to say. | |
| 115 | + m.first, m.lastLive = now, now | |
| 116 | + } | |
| 117 | + m.last = now | |
| 118 | + m.chunks++ | |
| 119 | + if m.report != nil && m.chunks > 1 && now.Sub(m.lastLive) >= liveEvery { | |
| 120 | + if d := m.last.Sub(m.first); d > 0 { | |
| 121 | + m.lastLive = now | |
| 122 | + m.report(ui.Speed{TokensPerSecond: float64(m.chunks-1) / d.Seconds(), Live: true}) | |
| 123 | + } | |
| 124 | + } | |
| 125 | +} | |
| 126 | + | |
| 127 | +// carries says a delta holds generated text, reasoning or a tool call — not | |
| 128 | +// the role-only first chunk nor the empty last one. | |
| 129 | +func carries(delta map[string]any) bool { | |
| 130 | + for k, v := range delta { | |
| 131 | + if k == "role" || v == nil { | |
| 132 | + continue | |
| 133 | + } | |
| 134 | + if s, ok := v.(string); ok && s == "" { | |
| 135 | + continue | |
| 136 | + } | |
| 137 | + return true | |
| 138 | + } | |
| 139 | + return false | |
| 140 | +} | |
| 141 | + | |
| 142 | +// settle ends the call in flight with the server's count of its output | |
| 143 | +// tokens (0 = not reported): its speed is reported and added to the turn's. | |
| 144 | +func (m *speedMeter) settle(outputTokens int) { | |
| 145 | + m.mu.Lock() | |
| 146 | + defer m.mu.Unlock() | |
| 147 | + tokens, decode, fromServer := 0, time.Duration(0), false | |
| 148 | + switch { | |
| 149 | + case m.timings != nil && m.timings.PredictedMS > 0: | |
| 150 | + tokens, fromServer = m.timings.PredictedN, true | |
| 151 | + decode = time.Duration(m.timings.PredictedMS * float64(time.Millisecond)) | |
| 152 | + case !m.first.IsZero() && m.last.After(m.first): | |
| 153 | + // From the first chunk to the last: the first token is already out | |
| 154 | + // at `first`, so the time covers the tokens after it. | |
| 155 | + decode = m.last.Sub(m.first) | |
| 156 | + tokens = outputTokens - 1 | |
| 157 | + if outputTokens <= 0 { | |
| 158 | + tokens = m.chunks - 1 | |
| 159 | + } | |
| 160 | + } | |
| 161 | + m.first, m.last, m.chunks, m.timings = time.Time{}, time.Time{}, 0, nil | |
| 162 | + if tokens <= 0 || decode <= 0 { | |
| 163 | + return | |
| 164 | + } | |
| 165 | + m.turnTokens += tokens | |
| 166 | + m.turnDecode += decode | |
| 167 | + if m.report != nil { | |
| 168 | + m.report(ui.Speed{TokensPerSecond: float64(tokens) / decode.Seconds(), FromServer: fromServer}) | |
| 169 | + } | |
| 170 | +} | |
| 171 | + | |
| 172 | +// finish reports the turn's average, when anything was measured. | |
| 173 | +func (m *speedMeter) finish() { | |
| 174 | + m.mu.Lock() | |
| 175 | + defer m.mu.Unlock() | |
| 176 | + if m.report == nil || m.turnTokens <= 0 || m.turnDecode <= 0 { | |
| 177 | + return | |
| 178 | + } | |
| 179 | + m.report(ui.Speed{TokensPerSecond: float64(m.turnTokens) / m.turnDecode.Seconds(), Turn: true}) | |
| 180 | +} | |
| 181 | + | |
| 182 | +// turnSpeedMeter is the meter of one Generate, nil with showSpeed off. | |
| 183 | +func turnSpeedMeter() *speedMeter { | |
| 184 | + if !config.Cfg.ShowSpeed { | |
| 185 | + return nil | |
| 186 | + } | |
| 187 | + return newSpeedMeter(ui.ReportSpeed) | |
| 188 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,188 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "encoding/json" | ||
| 6 | + "strings" | ||
| 7 | + "sync" | ||
| 8 | + "time" | ||
| 9 | + | ||
| 10 | + "mm/internal/config" | ||
| 11 | + "mm/internal/ui" | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | +// The generation speed (ticket 254), in tokens per second, from two sources | ||
| 15 | +// in this order: | ||
| 16 | +// | ||
| 17 | +// 1. the server's own `timings`, beside `usage` in the last streamed chunk | ||
| 18 | +// (llama.cpp style: predicted_n, predicted_ms, predicted_per_second) — | ||
| 19 | +// exact, and the prompt reading is not in it. Measured on MLX-Serve | ||
| 20 | +// 26.11.3 and llama-server build 12359 (2026-11-24); | ||
| 21 | +// 2. otherwise measured by mm: the call's output tokens (`usage`) over the | ||
| 22 | +// time from the FIRST streamed chunk to the last — not from the request, | ||
| 23 | +// which would count the prompt reading. With no `usage`, the streamed | ||
| 24 | +// chunks are counted instead (about one token each). | ||
| 25 | +// | ||
| 26 | +// While a call streams, an estimate is reported every half second (chunks | ||
| 27 | +// over time); when the call ends, its measure; when the turn ends, the | ||
| 28 | +// turn's tokens over its decode time — the tools' run time left out. | ||
| 29 | + | ||
| 30 | +// speedMeter measures one Generate. The stream tap feeds it (begin, line); | ||
| 31 | +// the engine settles each call and the turn. | ||
| 32 | +type speedMeter struct { | ||
| 33 | + mu sync.Mutex | ||
| 34 | + // the call in flight | ||
| 35 | + first, last time.Time | ||
| 36 | + chunks int | ||
| 37 | + timings *serverTimings | ||
| 38 | + lastLive time.Time | ||
| 39 | + // the turn so far | ||
| 40 | + turnTokens int | ||
| 41 | + turnDecode time.Duration | ||
| 42 | + report func(ui.Speed) | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +// serverTimings is the `timings` object of a llama.cpp-style server. | ||
| 46 | +type serverTimings struct { | ||
| 47 | + PredictedN int `json:"predicted_n"` | ||
| 48 | + PredictedMS float64 `json:"predicted_ms"` | ||
| 49 | + PredictedPS float64 `json:"predicted_per_second"` | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +// liveEvery spaces the live estimates. | ||
| 53 | +const liveEvery = 500 * time.Millisecond | ||
| 54 | + | ||
| 55 | +func newSpeedMeter(report func(ui.Speed)) *speedMeter { | ||
| 56 | + return &speedMeter{report: report} | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +type speedKey struct{} | ||
| 60 | + | ||
| 61 | +// withSpeed returns a context whose streamed requests feed m; nil when the | ||
| 62 | +// speed is not shown (showSpeed: false). | ||
| 63 | +func withSpeed(ctx context.Context, m *speedMeter) context.Context { | ||
| 64 | + if m == nil { | ||
| 65 | + return ctx | ||
| 66 | + } | ||
| 67 | + return context.WithValue(ctx, speedKey{}, m) | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +func speedFrom(ctx context.Context) *speedMeter { | ||
| 71 | + m, _ := ctx.Value(speedKey{}).(*speedMeter) | ||
| 72 | + return m | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +// begin starts a new call: one streamed request. | ||
| 76 | +func (m *speedMeter) begin() { | ||
| 77 | + m.mu.Lock() | ||
| 78 | + defer m.mu.Unlock() | ||
| 79 | + m.first, m.last, m.chunks, m.timings, m.lastLive = time.Time{}, time.Time{}, 0, nil, time.Time{} | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +// speedChunk is the little of a chunk the meter reads. | ||
| 83 | +type speedChunk struct { | ||
| 84 | + Choices []struct { | ||
| 85 | + Delta map[string]any `json:"delta"` | ||
| 86 | + } `json:"choices"` | ||
| 87 | + Timings *serverTimings `json:"timings"` | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +// line reads one SSE line of the call in flight: a chunk that carries | ||
| 91 | +// something (text, reasoning, a tool call) moves the clock, a `timings` | ||
| 92 | +// object is kept. | ||
| 93 | +func (m *speedMeter) line(line string, now time.Time) { | ||
| 94 | + if !strings.Contains(line, `"delta"`) && !strings.Contains(line, `"timings"`) { | ||
| 95 | + return | ||
| 96 | + } | ||
| 97 | + data, ok := strings.CutPrefix(strings.TrimSpace(line), "data:") | ||
| 98 | + if !ok { | ||
| 99 | + return | ||
| 100 | + } | ||
| 101 | + var c speedChunk | ||
| 102 | + if json.Unmarshal([]byte(strings.TrimSpace(data)), &c) != nil { | ||
| 103 | + return | ||
| 104 | + } | ||
| 105 | + m.mu.Lock() | ||
| 106 | + defer m.mu.Unlock() | ||
| 107 | + if c.Timings != nil && c.Timings.PredictedN > 0 { | ||
| 108 | + m.timings = c.Timings | ||
| 109 | + } | ||
| 110 | + if len(c.Choices) == 0 || !carries(c.Choices[0].Delta) { | ||
| 111 | + return | ||
| 112 | + } | ||
| 113 | + if m.first.IsZero() { | ||
| 114 | + // The first estimate waits liveEvery: two chunks are too few to say. | ||
| 115 | + m.first, m.lastLive = now, now | ||
| 116 | + } | ||
| 117 | + m.last = now | ||
| 118 | + m.chunks++ | ||
| 119 | + if m.report != nil && m.chunks > 1 && now.Sub(m.lastLive) >= liveEvery { | ||
| 120 | + if d := m.last.Sub(m.first); d > 0 { | ||
| 121 | + m.lastLive = now | ||
| 122 | + m.report(ui.Speed{TokensPerSecond: float64(m.chunks-1) / d.Seconds(), Live: true}) | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// carries says a delta holds generated text, reasoning or a tool call — not | ||
| 128 | +// the role-only first chunk nor the empty last one. | ||
| 129 | +func carries(delta map[string]any) bool { | ||
| 130 | + for k, v := range delta { | ||
| 131 | + if k == "role" || v == nil { | ||
| 132 | + continue | ||
| 133 | + } | ||
| 134 | + if s, ok := v.(string); ok && s == "" { | ||
| 135 | + continue | ||
| 136 | + } | ||
| 137 | + return true | ||
| 138 | + } | ||
| 139 | + return false | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +// settle ends the call in flight with the server's count of its output | ||
| 143 | +// tokens (0 = not reported): its speed is reported and added to the turn's. | ||
| 144 | +func (m *speedMeter) settle(outputTokens int) { | ||
| 145 | + m.mu.Lock() | ||
| 146 | + defer m.mu.Unlock() | ||
| 147 | + tokens, decode, fromServer := 0, time.Duration(0), false | ||
| 148 | + switch { | ||
| 149 | + case m.timings != nil && m.timings.PredictedMS > 0: | ||
| 150 | + tokens, fromServer = m.timings.PredictedN, true | ||
| 151 | + decode = time.Duration(m.timings.PredictedMS * float64(time.Millisecond)) | ||
| 152 | + case !m.first.IsZero() && m.last.After(m.first): | ||
| 153 | + // From the first chunk to the last: the first token is already out | ||
| 154 | + // at `first`, so the time covers the tokens after it. | ||
| 155 | + decode = m.last.Sub(m.first) | ||
| 156 | + tokens = outputTokens - 1 | ||
| 157 | + if outputTokens <= 0 { | ||
| 158 | + tokens = m.chunks - 1 | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + m.first, m.last, m.chunks, m.timings = time.Time{}, time.Time{}, 0, nil | ||
| 162 | + if tokens <= 0 || decode <= 0 { | ||
| 163 | + return | ||
| 164 | + } | ||
| 165 | + m.turnTokens += tokens | ||
| 166 | + m.turnDecode += decode | ||
| 167 | + if m.report != nil { | ||
| 168 | + m.report(ui.Speed{TokensPerSecond: float64(tokens) / decode.Seconds(), FromServer: fromServer}) | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +// finish reports the turn's average, when anything was measured. | ||
| 173 | +func (m *speedMeter) finish() { | ||
| 174 | + m.mu.Lock() | ||
| 175 | + defer m.mu.Unlock() | ||
| 176 | + if m.report == nil || m.turnTokens <= 0 || m.turnDecode <= 0 { | ||
| 177 | + return | ||
| 178 | + } | ||
| 179 | + m.report(ui.Speed{TokensPerSecond: float64(m.turnTokens) / m.turnDecode.Seconds(), Turn: true}) | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +// turnSpeedMeter is the meter of one Generate, nil with showSpeed off. | ||
| 183 | +func turnSpeedMeter() *speedMeter { | ||
| 184 | + if !config.Cfg.ShowSpeed { | ||
| 185 | + return nil | ||
| 186 | + } | ||
| 187 | + return newSpeedMeter(ui.ReportSpeed) | ||
| 188 | +} | ||
added
internal/engine/speed_test.go +125 -0 | new file mode 100644 | ||
| @@ -0,0 +1,125 @@ | ||
| 1 | +package engine | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "math" | |
| 5 | + "strings" | |
| 6 | + "testing" | |
| 7 | + "time" | |
| 8 | + | |
| 9 | + "mm/internal/ui" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// Lines as llama-server build 12359 streams them (2026-11-24): a role-only | |
| 13 | +// first chunk, content chunks, and the timings in the last chunk. | |
| 14 | +const ( | |
| 15 | + roleLine = `data: {"choices":[{"finish_reason":null,"index":0,"delta":{"role":"assistant","content":null}}],"object":"chat.completion.chunk"}` | |
| 16 | + contentLine = `data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":"Hi"}}],"object":"chat.completion.chunk"}` | |
| 17 | + toolLine = `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"cmd"}}]}}]}` | |
| 18 | + timingsLine = `data: {"choices":[],"usage":{"completion_tokens":6},"timings":{"prompt_n":5,"prompt_ms":40.52,"predicted_n":6,"predicted_ms":64.819,"predicted_per_second":77.13787623999136}}` | |
| 19 | +) | |
| 20 | + | |
| 21 | +func collect() (*speedMeter, *[]ui.Speed) { | |
| 22 | + var got []ui.Speed | |
| 23 | + return newSpeedMeter(func(s ui.Speed) { got = append(got, s) }), &got | |
| 24 | +} | |
| 25 | + | |
| 26 | +func near(a, b float64) bool { return math.Abs(a-b) < 0.01 } | |
| 27 | + | |
| 28 | +// The server's timings win: exact, and the prompt reading is not in them. | |
| 29 | +func TestSpeedFromTheServersTimings(t *testing.T) { | |
| 30 | + m, got := collect() | |
| 31 | + t0 := time.Now() | |
| 32 | + m.begin() | |
| 33 | + m.line(roleLine, t0) | |
| 34 | + m.line(contentLine, t0.Add(10*time.Millisecond)) | |
| 35 | + m.line(contentLine, t0.Add(20*time.Millisecond)) | |
| 36 | + m.line(timingsLine, t0.Add(30*time.Millisecond)) | |
| 37 | + m.line("data: [DONE]", t0.Add(31*time.Millisecond)) | |
| 38 | + m.settle(6) | |
| 39 | + if len(*got) != 1 || !(*got)[0].FromServer || !near((*got)[0].TokensPerSecond, 6/0.064819) { | |
| 40 | + t.Fatalf("got %+v, want one call speed of 6 tokens / 64.819 ms from the server", *got) | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +// Without timings, mm measures: the output tokens after the first one over | |
| 45 | +// the time from the first chunk that carries something to the last — the | |
| 46 | +// role-only chunk and the prompt reading before it are not counted. | |
| 47 | +func TestSpeedMeasuredFromFirstToLastChunk(t *testing.T) { | |
| 48 | + m, got := collect() | |
| 49 | + t0 := time.Now() | |
| 50 | + m.begin() | |
| 51 | + m.line(roleLine, t0) // not a token | |
| 52 | + m.line(contentLine, t0.Add(2*time.Second)) | |
| 53 | + m.line(toolLine, t0.Add(2100*time.Millisecond)) | |
| 54 | + m.line(contentLine, t0.Add(2200*time.Millisecond)) | |
| 55 | + m.settle(21) // 20 tokens after the first, in 200 ms | |
| 56 | + if len(*got) != 1 || (*got)[0].FromServer || !near((*got)[0].TokensPerSecond, 100) { | |
| 57 | + t.Fatalf("got %+v, want 100 tok/s measured", *got) | |
| 58 | + } | |
| 59 | +} | |
| 60 | + | |
| 61 | +// No usage either: the streamed chunks are counted. | |
| 62 | +func TestSpeedCountsChunksWithoutUsage(t *testing.T) { | |
| 63 | + m, got := collect() | |
| 64 | + t0 := time.Now() | |
| 65 | + m.begin() | |
| 66 | + for i := range 11 { | |
| 67 | + m.line(contentLine, t0.Add(time.Duration(i)*10*time.Millisecond)) | |
| 68 | + } | |
| 69 | + m.settle(0) | |
| 70 | + if len(*got) != 1 || !near((*got)[0].TokensPerSecond, 100) { | |
| 71 | + t.Fatalf("got %+v, want 10 chunks / 100 ms", *got) | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 75 | +// While a call streams, an estimate every half second; the turn's average | |
| 76 | +// is its tokens over its decode time, whatever the tools took in between. | |
| 77 | +func TestSpeedLiveAndTurnAverage(t *testing.T) { | |
| 78 | + m, got := collect() | |
| 79 | + t0 := time.Now() | |
| 80 | + m.begin() | |
| 81 | + for i := range 21 { // 20 tokens in 1 s: two live estimates | |
| 82 | + m.line(contentLine, t0.Add(time.Duration(i)*50*time.Millisecond)) | |
| 83 | + } | |
| 84 | + m.settle(21) // 20 tok/s | |
| 85 | + live := 0 | |
| 86 | + for _, s := range *got { | |
| 87 | + if s.Live { | |
| 88 | + live++ | |
| 89 | + } | |
| 90 | + } | |
| 91 | + if live != 2 { | |
| 92 | + t.Errorf("%d live estimates in 1 s, want 2: %+v", live, *got) | |
| 93 | + } | |
| 94 | + // A tool runs for a minute: not counted. | |
| 95 | + t1 := t0.Add(time.Minute) | |
| 96 | + m.begin() | |
| 97 | + m.line(contentLine, t1) | |
| 98 | + m.line(contentLine, t1.Add(100*time.Millisecond)) | |
| 99 | + m.settle(41) // 40 tokens in 100 ms: 400 tok/s | |
| 100 | + m.finish() | |
| 101 | + last := (*got)[len(*got)-1] | |
| 102 | + if !last.Turn || !near(last.TokensPerSecond, 60/1.1) { | |
| 103 | + t.Errorf("turn: %+v, want 60 tokens / 1.1 s", last) | |
| 104 | + } | |
| 105 | +} | |
| 106 | + | |
| 107 | +// Nothing measured — a call with no streamed chunk — reports nothing. | |
| 108 | +func TestSpeedReportsNothingWithoutMeasure(t *testing.T) { | |
| 109 | + m, got := collect() | |
| 110 | + m.begin() | |
| 111 | + m.settle(10) | |
| 112 | + m.finish() | |
| 113 | + if len(*got) != 0 { | |
| 114 | + t.Errorf("got %+v, want nothing", *got) | |
| 115 | + } | |
| 116 | +} | |
| 117 | + | |
| 118 | +func TestSpeedLabel(t *testing.T) { | |
| 119 | + if s := (ui.Speed{TokensPerSecond: 48.24}).String(); s != "⚡ 48.2 tok/s" { | |
| 120 | + t.Errorf("%q", s) | |
| 121 | + } | |
| 122 | + if s := (ui.Speed{TokensPerSecond: 44.6, Live: true}).String(); !strings.HasPrefix(s, "⚡ ~45") { | |
| 123 | + t.Errorf("%q", s) | |
| 124 | + } | |
| 125 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,125 @@ | |||
| 1 | +package engine | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "math" | ||
| 5 | + "strings" | ||
| 6 | + "testing" | ||
| 7 | + "time" | ||
| 8 | + | ||
| 9 | + "mm/internal/ui" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// Lines as llama-server build 12359 streams them (2026-11-24): a role-only | ||
| 13 | +// first chunk, content chunks, and the timings in the last chunk. | ||
| 14 | +const ( | ||
| 15 | + roleLine = `data: {"choices":[{"finish_reason":null,"index":0,"delta":{"role":"assistant","content":null}}],"object":"chat.completion.chunk"}` | ||
| 16 | + contentLine = `data: {"choices":[{"finish_reason":null,"index":0,"delta":{"content":"Hi"}}],"object":"chat.completion.chunk"}` | ||
| 17 | + toolLine = `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"cmd"}}]}}]}` | ||
| 18 | + timingsLine = `data: {"choices":[],"usage":{"completion_tokens":6},"timings":{"prompt_n":5,"prompt_ms":40.52,"predicted_n":6,"predicted_ms":64.819,"predicted_per_second":77.13787623999136}}` | ||
| 19 | +) | ||
| 20 | + | ||
| 21 | +func collect() (*speedMeter, *[]ui.Speed) { | ||
| 22 | + var got []ui.Speed | ||
| 23 | + return newSpeedMeter(func(s ui.Speed) { got = append(got, s) }), &got | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +func near(a, b float64) bool { return math.Abs(a-b) < 0.01 } | ||
| 27 | + | ||
| 28 | +// The server's timings win: exact, and the prompt reading is not in them. | ||
| 29 | +func TestSpeedFromTheServersTimings(t *testing.T) { | ||
| 30 | + m, got := collect() | ||
| 31 | + t0 := time.Now() | ||
| 32 | + m.begin() | ||
| 33 | + m.line(roleLine, t0) | ||
| 34 | + m.line(contentLine, t0.Add(10*time.Millisecond)) | ||
| 35 | + m.line(contentLine, t0.Add(20*time.Millisecond)) | ||
| 36 | + m.line(timingsLine, t0.Add(30*time.Millisecond)) | ||
| 37 | + m.line("data: [DONE]", t0.Add(31*time.Millisecond)) | ||
| 38 | + m.settle(6) | ||
| 39 | + if len(*got) != 1 || !(*got)[0].FromServer || !near((*got)[0].TokensPerSecond, 6/0.064819) { | ||
| 40 | + t.Fatalf("got %+v, want one call speed of 6 tokens / 64.819 ms from the server", *got) | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// Without timings, mm measures: the output tokens after the first one over | ||
| 45 | +// the time from the first chunk that carries something to the last — the | ||
| 46 | +// role-only chunk and the prompt reading before it are not counted. | ||
| 47 | +func TestSpeedMeasuredFromFirstToLastChunk(t *testing.T) { | ||
| 48 | + m, got := collect() | ||
| 49 | + t0 := time.Now() | ||
| 50 | + m.begin() | ||
| 51 | + m.line(roleLine, t0) // not a token | ||
| 52 | + m.line(contentLine, t0.Add(2*time.Second)) | ||
| 53 | + m.line(toolLine, t0.Add(2100*time.Millisecond)) | ||
| 54 | + m.line(contentLine, t0.Add(2200*time.Millisecond)) | ||
| 55 | + m.settle(21) // 20 tokens after the first, in 200 ms | ||
| 56 | + if len(*got) != 1 || (*got)[0].FromServer || !near((*got)[0].TokensPerSecond, 100) { | ||
| 57 | + t.Fatalf("got %+v, want 100 tok/s measured", *got) | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +// No usage either: the streamed chunks are counted. | ||
| 62 | +func TestSpeedCountsChunksWithoutUsage(t *testing.T) { | ||
| 63 | + m, got := collect() | ||
| 64 | + t0 := time.Now() | ||
| 65 | + m.begin() | ||
| 66 | + for i := range 11 { | ||
| 67 | + m.line(contentLine, t0.Add(time.Duration(i)*10*time.Millisecond)) | ||
| 68 | + } | ||
| 69 | + m.settle(0) | ||
| 70 | + if len(*got) != 1 || !near((*got)[0].TokensPerSecond, 100) { | ||
| 71 | + t.Fatalf("got %+v, want 10 chunks / 100 ms", *got) | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +// While a call streams, an estimate every half second; the turn's average | ||
| 76 | +// is its tokens over its decode time, whatever the tools took in between. | ||
| 77 | +func TestSpeedLiveAndTurnAverage(t *testing.T) { | ||
| 78 | + m, got := collect() | ||
| 79 | + t0 := time.Now() | ||
| 80 | + m.begin() | ||
| 81 | + for i := range 21 { // 20 tokens in 1 s: two live estimates | ||
| 82 | + m.line(contentLine, t0.Add(time.Duration(i)*50*time.Millisecond)) | ||
| 83 | + } | ||
| 84 | + m.settle(21) // 20 tok/s | ||
| 85 | + live := 0 | ||
| 86 | + for _, s := range *got { | ||
| 87 | + if s.Live { | ||
| 88 | + live++ | ||
| 89 | + } | ||
| 90 | + } | ||
| 91 | + if live != 2 { | ||
| 92 | + t.Errorf("%d live estimates in 1 s, want 2: %+v", live, *got) | ||
| 93 | + } | ||
| 94 | + // A tool runs for a minute: not counted. | ||
| 95 | + t1 := t0.Add(time.Minute) | ||
| 96 | + m.begin() | ||
| 97 | + m.line(contentLine, t1) | ||
| 98 | + m.line(contentLine, t1.Add(100*time.Millisecond)) | ||
| 99 | + m.settle(41) // 40 tokens in 100 ms: 400 tok/s | ||
| 100 | + m.finish() | ||
| 101 | + last := (*got)[len(*got)-1] | ||
| 102 | + if !last.Turn || !near(last.TokensPerSecond, 60/1.1) { | ||
| 103 | + t.Errorf("turn: %+v, want 60 tokens / 1.1 s", last) | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +// Nothing measured — a call with no streamed chunk — reports nothing. | ||
| 108 | +func TestSpeedReportsNothingWithoutMeasure(t *testing.T) { | ||
| 109 | + m, got := collect() | ||
| 110 | + m.begin() | ||
| 111 | + m.settle(10) | ||
| 112 | + m.finish() | ||
| 113 | + if len(*got) != 0 { | ||
| 114 | + t.Errorf("got %+v, want nothing", *got) | ||
| 115 | + } | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +func TestSpeedLabel(t *testing.T) { | ||
| 119 | + if s := (ui.Speed{TokensPerSecond: 48.24}).String(); s != "⚡ 48.2 tok/s" { | ||
| 120 | + t.Errorf("%q", s) | ||
| 121 | + } | ||
| 122 | + if s := (ui.Speed{TokensPerSecond: 44.6, Live: true}).String(); !strings.HasPrefix(s, "⚡ ~45") { | ||
| 123 | + t.Errorf("%q", s) | ||
| 124 | + } | ||
| 125 | +} | ||
modified
internal/tui/sink.go +11 -3 | @@ -18,9 +18,10 @@ import ( | ||
| 18 | 18 | type sink struct{ r *runner } |
| 19 | 19 | |
| 20 | 20 | var ( |
| 21 | - _ ui.Sink = (*sink)(nil) | |
| 22 | - _ ui.Speaker = (*sink)(nil) | |
| 23 | - _ ui.Noticer = (*sink)(nil) | |
| 21 | + _ ui.Sink = (*sink)(nil) | |
| 22 | + _ ui.Speaker = (*sink)(nil) | |
| 23 | + _ ui.Noticer = (*sink)(nil) | |
| 24 | + _ ui.SpeedSink = (*sink)(nil) | |
| 24 | 25 | ) |
| 25 | 26 | |
| 26 | 27 | // Speaking switches the header and the answers' label to the agent now |
| @@ -92,6 +93,13 @@ func (k *sink) ToolEnd(id string, res ui.ToolResult) { | ||
| 92 | 93 | k.r.wake() |
| 93 | 94 | } |
| 94 | 95 | |
| 96 | +// Speed keeps the generation speed for the status bar (ticket 254). Called | |
| 97 | +// from the stream's goroutine: the pointer swap is the whole update. | |
| 98 | +func (k *sink) Speed(s ui.Speed) { | |
| 99 | + k.r.speed.Store(&s) | |
| 100 | + k.r.wake() | |
| 101 | +} | |
| 102 | + | |
| 95 | 103 | // Struggle keeps a sign that the model is struggling for the status bar's |
| 96 | 104 | // badge (ticket 153), where it stays until the next question. |
| 97 | 105 | func (k *sink) Struggle(s ui.Struggle) { |
| @@ -18,9 +18,10 @@ import ( | |||
| 18 | type sink struct{ r *runner } | 18 | type sink struct{ r *runner } |
| 19 | 19 | ||
| 20 | var ( | 20 | var ( |
| 21 | - _ ui.Sink = (*sink)(nil) | 21 | + _ ui.Sink = (*sink)(nil) |
| 22 | - _ ui.Speaker = (*sink)(nil) | 22 | + _ ui.Speaker = (*sink)(nil) |
| 23 | - _ ui.Noticer = (*sink)(nil) | 23 | + _ ui.Noticer = (*sink)(nil) |
| 24 | + _ ui.SpeedSink = (*sink)(nil) | ||
| 24 | ) | 25 | ) |
| 25 | 26 | ||
| 26 | // Speaking switches the header and the answers' label to the agent now | 27 | // Speaking switches the header and the answers' label to the agent now |
| @@ -92,6 +93,13 @@ func (k *sink) ToolEnd(id string, res ui.ToolResult) { | |||
| 92 | k.r.wake() | 93 | k.r.wake() |
| 93 | } | 94 | } |
| 94 | 95 | ||
| 96 | +// Speed keeps the generation speed for the status bar (ticket 254). Called | ||
| 97 | +// from the stream's goroutine: the pointer swap is the whole update. | ||
| 98 | +func (k *sink) Speed(s ui.Speed) { | ||
| 99 | + k.r.speed.Store(&s) | ||
| 100 | + k.r.wake() | ||
| 101 | +} | ||
| 102 | + | ||
| 95 | // Struggle keeps a sign that the model is struggling for the status bar's | 103 | // Struggle keeps a sign that the model is struggling for the status bar's |
| 96 | // badge (ticket 153), where it stays until the next question. | 104 | // badge (ticket 153), where it stays until the next question. |
| 97 | func (k *sink) Struggle(s ui.Struggle) { | 105 | func (k *sink) Struggle(s ui.Struggle) { |
modified
internal/tui/turn.go +8 -0 | @@ -150,6 +150,11 @@ type runner struct { | ||
| 150 | 150 | |
| 151 | 151 | // watch times the completion in progress for the status bar (ticket 158). |
| 152 | 152 | watch stopwatch |
| 153 | + | |
| 154 | + // speed is the generation speed for the status bar (ticket 254): the | |
| 155 | + // call in progress while it streams, then the turn's average, which | |
| 156 | + // stays until the next answer starts. nil = nothing measured yet. | |
| 157 | + speed atomic.Pointer[ui.Speed] | |
| 153 | 158 | } |
| 154 | 159 | |
| 155 | 160 | func newRunner(opts Options, t *Transcript, wake func()) *runner { |
| @@ -467,6 +472,9 @@ func (r *runner) header() string { | ||
| 467 | 472 | // since only it knows how wide the window is. |
| 468 | 473 | func (r *runner) status() string { |
| 469 | 474 | counters := fmt.Sprintf("%d msgs · %d tools", session.Forgotten(r.messages), r.t.Tools()) |
| 475 | + if s := r.speed.Load(); s != nil && config.Cfg.ShowSpeed { | |
| 476 | + counters = s.String() + " · " + counters | |
| 477 | + } | |
| 470 | 478 | if d := r.watch.label(); d != "" && config.Cfg.ShowCompletionTime { |
| 471 | 479 | return d + " · " + counters |
| 472 | 480 | } |
| @@ -150,6 +150,11 @@ type runner struct { | |||
| 150 | 150 | ||
| 151 | // watch times the completion in progress for the status bar (ticket 158). | 151 | // watch times the completion in progress for the status bar (ticket 158). |
| 152 | watch stopwatch | 152 | watch stopwatch |
| 153 | + | ||
| 154 | + // speed is the generation speed for the status bar (ticket 254): the | ||
| 155 | + // call in progress while it streams, then the turn's average, which | ||
| 156 | + // stays until the next answer starts. nil = nothing measured yet. | ||
| 157 | + speed atomic.Pointer[ui.Speed] | ||
| 153 | } | 158 | } |
| 154 | 159 | ||
| 155 | func newRunner(opts Options, t *Transcript, wake func()) *runner { | 160 | func newRunner(opts Options, t *Transcript, wake func()) *runner { |
| @@ -467,6 +472,9 @@ func (r *runner) header() string { | |||
| 467 | // since only it knows how wide the window is. | 472 | // since only it knows how wide the window is. |
| 468 | func (r *runner) status() string { | 473 | func (r *runner) status() string { |
| 469 | counters := fmt.Sprintf("%d msgs · %d tools", session.Forgotten(r.messages), r.t.Tools()) | 474 | counters := fmt.Sprintf("%d msgs · %d tools", session.Forgotten(r.messages), r.t.Tools()) |
| 475 | + if s := r.speed.Load(); s != nil && config.Cfg.ShowSpeed { | ||
| 476 | + counters = s.String() + " · " + counters | ||
| 477 | + } | ||
| 470 | if d := r.watch.label(); d != "" && config.Cfg.ShowCompletionTime { | 478 | if d := r.watch.label(); d != "" && config.Cfg.ShowCompletionTime { |
| 471 | return d + " · " + counters | 479 | return d + " · " + counters |
| 472 | } | 480 | } |
modified
internal/ui/ui.go +34 -0 | @@ -104,6 +104,40 @@ type UsageSink interface { | ||
| 104 | 104 | Usage(u Usage) |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | +// Speed is the model's generation speed (ticket 254), in tokens per second. | |
| 108 | +// Reported while a call streams (Live: counted from the streamed chunks), when | |
| 109 | +// a call ends (the server's timings, or mm's measure from the first token to | |
| 110 | +// the last), and once a turn is over (Turn: the turn's tokens over its decode | |
| 111 | +// time — the tools' time left out). | |
| 112 | +type Speed struct { | |
| 113 | + TokensPerSecond float64 | |
| 114 | + Live bool // an estimate while the call streams | |
| 115 | + Turn bool // the average of the turn just over | |
| 116 | + FromServer bool // the server measured it (its `timings`) | |
| 117 | +} | |
| 118 | + | |
| 119 | +// String is the footer's label: "⚡ 48.2 tok/s", "⚡ ~45 tok/s" live. | |
| 120 | +func (s Speed) String() string { | |
| 121 | + if s.Live { | |
| 122 | + return fmt.Sprintf("⚡ ~%.0f tok/s", s.TokensPerSecond) | |
| 123 | + } | |
| 124 | + return fmt.Sprintf("⚡ %.1f tok/s", s.TokensPerSecond) | |
| 125 | +} | |
| 126 | + | |
| 127 | +// SpeedSink is the optional side of a Sink that shows the generation speed | |
| 128 | +// (the window's status bar, an editor through ACP). | |
| 129 | +type SpeedSink interface { | |
| 130 | + Speed(s Speed) | |
| 131 | +} | |
| 132 | + | |
| 133 | +// ReportSpeed hands s to the active sink when it shows speeds; the line mode | |
| 134 | +// does not. | |
| 135 | +func ReportSpeed(s Speed) { | |
| 136 | + if k, ok := ActiveSink().(SpeedSink); ok { | |
| 137 | + k.Speed(s) | |
| 138 | + } | |
| 139 | +} | |
| 140 | + | |
| 107 | 141 | // Elicitor is the optional side of a Sink that can put questions to its user |
| 108 | 142 | // — the ask_user tool's way through: a box in the window, a form or a dialog |
| 109 | 143 | // in an editor, the asker's own front end for an agent asked by another. A |
| @@ -104,6 +104,40 @@ type UsageSink interface { | |||
| 104 | Usage(u Usage) | 104 | Usage(u Usage) |
| 105 | } | 105 | } |
| 106 | 106 | ||
| 107 | +// Speed is the model's generation speed (ticket 254), in tokens per second. | ||
| 108 | +// Reported while a call streams (Live: counted from the streamed chunks), when | ||
| 109 | +// a call ends (the server's timings, or mm's measure from the first token to | ||
| 110 | +// the last), and once a turn is over (Turn: the turn's tokens over its decode | ||
| 111 | +// time — the tools' time left out). | ||
| 112 | +type Speed struct { | ||
| 113 | + TokensPerSecond float64 | ||
| 114 | + Live bool // an estimate while the call streams | ||
| 115 | + Turn bool // the average of the turn just over | ||
| 116 | + FromServer bool // the server measured it (its `timings`) | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +// String is the footer's label: "⚡ 48.2 tok/s", "⚡ ~45 tok/s" live. | ||
| 120 | +func (s Speed) String() string { | ||
| 121 | + if s.Live { | ||
| 122 | + return fmt.Sprintf("⚡ ~%.0f tok/s", s.TokensPerSecond) | ||
| 123 | + } | ||
| 124 | + return fmt.Sprintf("⚡ %.1f tok/s", s.TokensPerSecond) | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// SpeedSink is the optional side of a Sink that shows the generation speed | ||
| 128 | +// (the window's status bar, an editor through ACP). | ||
| 129 | +type SpeedSink interface { | ||
| 130 | + Speed(s Speed) | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +// ReportSpeed hands s to the active sink when it shows speeds; the line mode | ||
| 134 | +// does not. | ||
| 135 | +func ReportSpeed(s Speed) { | ||
| 136 | + if k, ok := ActiveSink().(SpeedSink); ok { | ||
| 137 | + k.Speed(s) | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 107 | // Elicitor is the optional side of a Sink that can put questions to its user | 141 | // Elicitor is the optional side of a Sink that can put questions to its user |
| 108 | // — the ask_user tool's way through: a box in the window, a form or a dialog | 142 | // — the ask_user tool's way through: a box in the window, a form or a dialog |
| 109 | // in an editor, the asker's own front end for an agent asked by another. A | 143 | // in an editor, the asker's own front end for an agent asked by another. A |