fix(messaging): render a tool call as one line with its own icon

A tool call rendered as a label line plus a ```text fence. Telegram draws a
fenced block as a full code widget (language header bar, copy button, panel),
and the block parser inserts a spacer paragraph before every block, so one
call cost four rendered elements. Three calls filled the screen to show three
word counts.

Every toolPreview path already summarises to a single line, so the fence was
never wrapping more than one. Drop it and put the preview on the header line.
Tool lines now join with a hard break rather than a bare newline: a soft
break would space-join them into one run-on paragraph, and a blank line would
put the spacer back. Three calls are now three consecutive blocks.

Two hardcoded values go with it. The status word is printed only when the
outcome is not success, since every line otherwise read "done" and
distinguished nothing. The icon is no longer a literal in the renderer: each
builtin declares its own on tools.Tool (not on Schema, which is the model's
contract), the provider carries it into ToolEntry, and the turn snapshots the
registry's icons alongside its tool set. A tool that declares none renders
without one rather than borrowing a generic wrench.

Carries a dependency upgrade (go.mod, go.sum, tools/go.mod, tools/go.sum).
This commit is contained in:
sam committed 2026-09-22 21:36:02 +10:00
1 parent d1513af6f3
commit 5fa43b7e87
22 files changed
+340 -49

No files matched your search

+9 -6
View File
@@ -243,15 +243,15 @@ func chatRepoEnv(cfg config.Config, identity string) []gateway.RepoEnv {
// and records at its own adapter (curatorLLMRunner). Anything that reaches the
// runtime without recording leaves /status reporting a stale last-known
// outcome, which is a /status that lies about the provider.
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, outcomes *providerOutcomeRecorder) (string, error) {
text, err := runChatTurn(ctx, llm, chatModel, options, turn)
func sendChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, outcomes *providerOutcomeRecorder, icons map[string]string) (string, error) {
text, err := runChatTurn(ctx, llm, chatModel, options, turn, icons)
// record tolerates a nil recorder: a setup built without one (tests, a
// deployment whose health surface is unwired) still makes its calls.
outcomes.record(chatModel, err)
return text, err
}
func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream) (string, error) {
func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, options core.GenerateOptions, turn gateway.TurnStream, icons map[string]string) (string, error) {
if turn == nil {
result, err := llm.Chat(ctx, chatModel, options)
if err != nil {
@@ -263,7 +263,7 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
if err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
text := drainChatStream(stream.FullStream, turn)
text := drainChatStream(stream.FullStream, turn, icons)
if _, err := stream.FinishReason(); err != nil {
return "", fmt.Errorf("llm chat stream: %w", err)
}
@@ -280,7 +280,7 @@ func runChatTurn(ctx context.Context, llm *runtime.Runtime, chatModel string, op
// A tool is reported on its result, never on its call: the call part carries
// no outcome yet, so reporting both would show every tool twice, once with
// nothing to say.
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream) string {
func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream, icons map[string]string) string {
type pendingToolCall struct {
name string
parameters string
@@ -319,6 +319,7 @@ func drainChatStream(parts <-chan core.StreamPart, turn gateway.TurnStream) stri
turn.ToolCall(gateway.ToolCallEvent{
ID: part.ToolResult.ToolCallID,
Name: name,
Emoji: icons[name],
Parameters: call.parameters,
Output: part.ToolResult.Output,
Err: part.ToolResult.Error,
@@ -401,8 +402,10 @@ func (g *chatTitleGenerator) GenerateTitle(ctx context.Context, sessionID, first
// caller. Sharing the process-wide recorder let a title that merely timed
// out overwrite the chat-model health line with "failed", reporting a
// broken provider on the strength of a call no user was waiting for.
// No tool set and no stream, so no tool call can be reported: this turn
// needs no icons.
text, err := sendChatTurn(ctx, g.llm, g.chatModels.ActiveModel(),
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, nil)
core.GenerateOptions{Messages: messages, MaxSteps: 1}, nil, nil, nil)
if err != nil {
if g.log != nil {
g.log.Error("session title generation failed", "session", sessionID, "err", err)
+37 -3
View File
@@ -163,7 +163,7 @@ func TestDrainChatStream(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
sink := &recordingStream{}
text := drainChatStream(streamOf(tc.parts...), sink)
text := drainChatStream(streamOf(tc.parts...), sink, nil)
if text != tc.wantText {
t.Fatalf("text = %q, want %q", text, tc.wantText)
@@ -204,7 +204,7 @@ func TestDrainChatStreamCorrelatesBoundsAndRedactsToolParameters(t *testing.T) {
ToolName: "shell",
Output: "ok",
}},
), sink)
), sink, nil)
if len(sink.events) != 2 {
t.Fatalf("events = %v, want two completed calls", sink.events)
@@ -231,9 +231,43 @@ func TestDrainChatStreamWithoutASinkStillCollectsText(t *testing.T) {
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "a"},
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
core.StreamPart{Type: core.StreamPartTextDelta, TextDelta: "b"},
), nil)
), nil, nil)
if text != "ab" {
t.Fatalf("text = %q, want %q", text, "ab")
}
}
// TestDrainChatStreamCarriesTheToolsRegisteredIcon pins the seam between the
// tool registry and what a chat surface renders. The icon is looked up by
// tool name at report time, so a tool that registers one gets it and a tool
// that does not is reported without one rather than with a generic stand-in.
func TestDrainChatStreamCarriesTheToolsRegisteredIcon(t *testing.T) {
sink := &iconRecordingStream{}
drainChatStream(streamOf(
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "shell", Output: "ok"}},
core.StreamPart{Type: core.StreamPartToolResult, ToolResult: &core.ToolResult{ToolName: "mcp.github.search", Output: "ok"}},
), sink, map[string]string{"shell": "💻"})
want := []string{"shell:💻", "mcp.github.search:"}
if len(sink.icons) != len(want) {
t.Fatalf("icons = %v, want %v", sink.icons, want)
}
for i, w := range want {
if sink.icons[i] != w {
t.Errorf("icons[%d] = %q, want %q", i, sink.icons[i], w)
}
}
}
type iconRecordingStream struct {
icons []string
}
func (s *iconRecordingStream) Delta(string) {}
func (s *iconRecordingStream) ToolCall(event gateway.ToolCallEvent) {
s.icons = append(s.icons, event.Name+":"+event.Emoji)
}
func (s *iconRecordingStream) Media(gateway.MediaEvent) {}
+22 -1
View File
@@ -60,6 +60,7 @@ func (m *chatTurnModel) Prepare(
toolInfo: toolSummaries(options.Tools),
toolTokens: gateway.EstimateTokens(string(toolSchema)),
outcomes: m.outcomes,
icons: toolIcons(m.registry),
}, nil
}
@@ -70,6 +71,26 @@ type preparedChatTurnModel struct {
toolInfo []gateway.ToolSummary
toolTokens int
outcomes *providerOutcomeRecorder
// icons maps tool name to the icon that tool registered, for chat
// surfaces to render. A nil map yields "" for every lookup, which is
// the no-icon rendering.
icons map[string]string
}
// toolIcons snapshots the icon each registered tool declares. It is taken at
// prepare time alongside the tool set itself, so a turn renders the icons of
// the tools it was actually given.
func toolIcons(registry *tools.Registry) map[string]string {
if registry == nil {
return nil
}
icons := make(map[string]string)
for _, entry := range registry.All() {
if entry.Emoji != "" {
icons[entry.Name] = entry.Emoji
}
}
return icons
}
func (m *preparedChatTurnModel) ToolSummaries() []gateway.ToolSummary {
@@ -100,5 +121,5 @@ func (m *preparedChatTurnModel) Generate(
// This is one provider response's output allowance, not a turn-
// continuation budget. Tool loops remain free to continue.
options.MaxTokens = request.MaxOutputTokens
return sendChatTurn(ctx, m.llm, m.model, options, stream, m.outcomes)
return sendChatTurn(ctx, m.llm, m.model, options, stream, m.outcomes, m.icons)
}
+1 -1
View File
@@ -163,7 +163,7 @@ func TestSendChatTurnRecordsEachCallOutcome(t *testing.T) {
_, err := sendChatTurn(t.Context(), llm, "openai/gpt-5.6", core.GenerateOptions{
Messages: []chat.Message{{Role: chat.RoleUser, Content: "hi"}},
MaxSteps: 1,
}, nil, recorder)
}, nil, recorder, nil)
if tc.wantErr == "" && err != nil {
t.Fatalf("sendChatTurn = %v, want success (request path %q)", err, requestedPath)
+18 -5
View File
@@ -366,14 +366,27 @@ func (l *liveReply) ToolCall(event messaging.ToolCallEvent) {
l.requestRender()
}
// countedToolLine marks a collapsed entry with how many calls it stands for.
// The count belongs to the status, not to the preview, so it is inserted
// before the preview separator rather than appended: "grep — done ×14 · 2
// matches" counts calls, while "· 2 matches ×14" reads as counting matches.
// toolLineSeparator joins tool lines. It ends each one with CommonMark's
// hard-break marker rather than a blank line: a bare "\n" is a soft break,
// which the block parser space-joins into one run-on paragraph, while a blank
// line would insert a spacer block between every pair. A hard break gives
// each line its own block AND suppresses the spacer, so a turn's activity
// reads as consecutive lines instead of a double-spaced list.
const toolLineSeparator = " \n"
func countedToolLine(line string, count int) string {
if count <= 1 {
return line
}
if newline := strings.IndexByte(line, '\n'); newline >= 0 {
return line[:newline] + fmt.Sprintf(" ×%d", count) + line[newline:]
marker := fmt.Sprintf(" ×%d", count)
if cut := strings.Index(line, messaging.ToolPreviewSeparator); cut >= 0 {
return line[:cut] + marker + line[cut:]
}
return line + fmt.Sprintf(" ×%d", count)
return line + marker
}
// mediaSendTimeout bounds one Media delivery. It is independent of the
@@ -732,7 +745,7 @@ func (l *liveReply) toolBlockWith(start int) string {
if omitted := start; omitted > 0 {
prefix = fmt.Sprintf("+%d earlier\n\n", omitted)
}
return prefix + strings.Join(l.toolLines[start:], "\n")
return prefix + strings.Join(l.toolLines[start:], toolLineSeparator)
}
// clampToRunes cuts s to its last maxRunes runes, marking the cut with a
@@ -766,7 +779,7 @@ func (l *liveReply) finalText(reply string) string {
if len(l.toolLines) == 0 {
return reply
}
block := strings.Join(l.toolLines, "\n")
block := strings.Join(l.toolLines, toolLineSeparator)
if reply == "" {
return block + "\n\n_(no response)_"
}
+56 -16
View File
@@ -194,12 +194,12 @@ func TestLiveReplyCollapsesRepeatedSuccessfulEquivalentToolCalls(t *testing.T) {
live.finalize(context.Background(), "done")
got := (*calls)[len(*calls)-1].body()
want := "🔧 grep — done ×14\n\n2 matches\n\ndone"
want := "grep ×14 · 2 matches\n\ndone"
if got != want {
t.Fatalf("repeated successful grep calls rendered as:\n%s\nwant:\n%s", got, want)
}
if strings.Count(got, "🔧 grep") != 1 {
t.Fatalf("repeated successful grep calls should occupy one entry, got %d:\n%s", strings.Count(got, "🔧 grep"), got)
if strings.Count(got, "grep") != 1 {
t.Fatalf("repeated successful grep calls should occupy one entry, got %d:\n%s", strings.Count(got, "grep"), got)
}
}
@@ -213,10 +213,10 @@ func TestLiveReplyDoesNotCollapseSuccessfulCallsWithDifferentResults(t *testing.
live.finalize(context.Background(), "done")
got := (*calls)[len(*calls)-1].body()
if strings.Count(got, "🔧 ") != 3 {
if strings.Count(got, " · ") != 3 {
t.Fatalf("successful calls with different tools or summaries were collapsed:\n%s", got)
}
if !strings.Contains(got, "🔧 grep — done ×2") || strings.Contains(got, "×3") {
if !strings.Contains(got, "grep ×2") || strings.Contains(got, "×3") {
t.Fatalf("only equivalent successful calls should be counted together:\n%s", got)
}
}
@@ -229,7 +229,7 @@ func TestLiveReplySnapshotsToolCallVisibility(t *testing.T) {
live.finalize(context.Background(), "done")
last := (*calls)[len(*calls)-1]
if !strings.Contains(last.body(), "🔧 shell — done\n\nexit 0\n\ndone") {
if !strings.Contains(last.body(), "shell · exit 0\n\ndone") {
t.Fatalf("final reply = %q, want the visibility captured when the reply started", last.body())
}
}
@@ -269,10 +269,10 @@ func TestLiveReplyRendersNoisyToolTurnAsCompactTelegramText(t *testing.T) {
// A tool result is described, never quoted with an invented line count:
// "… 7 more lines" was the renderer counting its own truncated sample, and
// it cannot agree with the total the tool actually reported.
want := "🔧 read — done\n\npackage gateway\n\n" +
"🔧 find — done\n\n/home/sam/projects/unrelated/main.go\n\n" +
"🔧 shell — failed\n\ncommand_exit: exit status 2\n\n" +
"🔧 tools — stopped ×5\n\ntool-output limit reached (200000 chars); further results suppressed\n\n" +
want := "read · package gateway\n\n" +
"find · /home/sam/projects/unrelated/main.go\n\n" +
"shell — failed · command_exit: exit status 2\n\n" +
"tools — stopped ×5 · tool-output limit reached (200000 chars); further results suppressed\n\n" +
"I found the relevant renderer and stopped after the output-volume cap."
if got != want {
t.Fatalf("Telegram-visible text:\n%s\n\nwant:\n%s", got, want)
@@ -316,8 +316,8 @@ func TestLiveReplyToolCalls(t *testing.T) {
{
name: "shown",
showToolCalls: true,
wantLive: "🔧 shell — done\n\nexit 0\n\nchecking ▌",
wantFinal: "🔧 shell — done\n\nexit 0\n\nchecking",
wantLive: "shell · exit 0\n\nchecking ▌",
wantFinal: "shell · exit 0\n\nchecking",
},
{
name: "hidden",
@@ -694,7 +694,7 @@ func TestLiveReplyToolLinesSurviveTheLiveClamp(t *testing.T) {
live.flushRendering()
last := (*calls)[len(*calls)-1]
if !strings.HasPrefix(last.body(), "🔧 shell — done\n\nexit 0\n\n") {
if !strings.HasPrefix(last.body(), "shell · exit 0\n\n") {
t.Fatalf("live frame lost the tool line once the answer grew past the clamp: %.60q…", last.body())
}
if n := len([]rune(last.body())); n > 4096 {
@@ -712,10 +712,10 @@ func TestLiveReplyFinalizeWithToolsAndNoReplyMarksTheAbsence(t *testing.T) {
live.finalize(context.Background(), "")
last := (*calls)[len(*calls)-1]
if last.body() == "🔧 shell — done\n\nexit 0" {
if last.body() == "shell · exit 0" {
t.Fatalf("finalize sent the bare tool line as the finished answer: %q", last.body())
}
if !strings.Contains(last.body(), "🔧 shell — done\n\nexit 0") {
if !strings.Contains(last.body(), "shell · exit 0") {
t.Fatalf("finalize dropped the tool activity: %q", last.body())
}
if !strings.Contains(last.body(), "no response") {
@@ -1197,7 +1197,7 @@ func TestLiveReplyToolBlockKeepsEveryLineThatFits(t *testing.T) {
block := live.toolBlock()
for _, name := range []string{"read", "grep", "find"} {
if !strings.Contains(block, "🔧 "+name) {
if !strings.Contains(block, name+" · ") {
t.Errorf("tool block dropped %s while every line still fits the %d-rune budget:\n%s",
name, liveToolMaxRunes, block)
}
@@ -1236,3 +1236,43 @@ func TestLiveReplyClampAnswerAlwaysMarksTheCut(t *testing.T) {
})
}
}
// TestToolLinesRenderAsConsecutiveBlocksWithoutSpacers pins the vertical cost
// of a turn's tool activity, which is what the separator and the one-line
// render exist to control.
//
// Each call used to emit a header paragraph, a spacer, a fenced code block
// and another spacer: four rendered elements, the code block carrying a
// language header bar and a copy button, to show a word count. Each call now
// costs exactly one paragraph, and only the answer is set apart.
func TestToolLinesRenderAsConsecutiveBlocksWithoutSpacers(t *testing.T) {
live, calls := newTestLiveReply(t, true)
live.ToolCall(toolEvent("read", "package config", ""))
live.ToolCall(toolEvent("shell", "63", ""))
live.ToolCall(toolEvent("grep", "/src/a.go:12:match\n/src/b.go:40:match", ""))
live.finalize(context.Background(), "The answer.")
blocks := (*calls)[len(*calls)-1].richBlocks
want := []string{
"read · package config",
"shell · 63",
"grep · 2 matches",
"",
"The answer.",
}
if len(blocks) != len(want) {
got := make([]string, len(blocks))
for i, b := range blocks {
got[i] = blockText(b)
}
t.Fatalf("blocks = %d %q, want %d %q", len(blocks), got, len(want), want)
}
for i, w := range want {
if got := blockText(blocks[i]); got != w {
t.Errorf("block[%d] = %q, want %q", i, got, w)
}
if blocks[i].Type != models.RichBlockTypeParagraph {
t.Errorf("block[%d] type = %q, want paragraph -- a one-line preview needs no code widget", i, blocks[i].Type)
}
}
}
+4
View File
@@ -13,6 +13,10 @@ type ToolCallEvent struct {
// Parameters is a bounded, redacted JSON summary of the invocation input.
// It is safe for channel adapters to render directly.
Parameters string
// Emoji is the icon the tool registered for itself, empty when it
// declared none. Chat surfaces render it verbatim; they do not invent
// one, so an unrecognised tool simply shows no icon.
Emoji string
// Output is what the tool returned, verbatim.
Output string
// Err is non-empty when the tool failed, in which case Output is
+27 -6
View File
@@ -19,12 +19,15 @@ const (
// inputs are noisy, often contain secrets, and are not useful progress text.
func RenderToolCall(e ToolCallEvent) string {
if limit, ok := legacyTurnBudgetLimit(e.Err); ok {
return toolProgressBlock("tools", "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit))
return toolProgressBlock("tools", e.Emoji, "stopped", fmt.Sprintf("tool-output limit reached (%s chars); further results suppressed", limit))
}
if line := cleanToolError(e.Name, e.Err); line != "" {
return toolProgressBlock(e.Name, "failed", line)
return toolProgressBlock(e.Name, e.Emoji, "failed", line)
}
return toolProgressBlock(e.Name, "done", toolPreview(e.Name, e.Output))
// Success carries no status word. Every line would read "done", so it
// distinguishes nothing; a status is printed only when the outcome is
// not the one the preview already implies.
return toolProgressBlock(e.Name, e.Emoji, "", toolPreview(e.Name, e.Output))
}
// FailureKey identifies equivalent tool calls for channel adapters that
@@ -39,16 +42,34 @@ func FailureKey(e ToolCallEvent) string {
return "success\x00" + strings.TrimSpace(e.Name) + "\x00" + toolPreview(e.Name, e.Output)
}
func toolProgressBlock(name, status, preview string) string {
// ToolPreviewSeparator joins a tool's header to its preview. The preview is
// always one line (every toolPreview path summarises to one), so it belongs
// on the header line rather than in a block of its own: Telegram renders a
// fenced block as a full code widget, and the block parser puts a spacer
// paragraph before every block, so fencing one line cost four rendered
// elements to show a word count.
//
// Keeping the preview on the line also means a fence marker in the output can
// never reach column zero, which is why the preview is passed through
// verbatim instead of having its backticks substituted away.
const ToolPreviewSeparator = " · "
func toolProgressBlock(name, emoji, status, preview string) string {
name = strings.TrimSpace(name)
if name == "" {
name = "tool"
}
preview = strings.ReplaceAll(strings.TrimSpace(preview), "```", "''' ")
preview = strings.TrimSpace(preview)
if preview == "" {
preview = "completed"
}
return "🔧 " + name + " — " + status + "\n```text\n" + truncateRunes(preview, 180) + "\n```"
if status != "" {
name += " — " + status
}
if emoji = strings.TrimSpace(emoji); emoji != "" {
name = emoji + " " + name
}
return name + ToolPreviewSeparator + truncateRunes(preview, 180)
}
func toolPreview(name, output string) string {
+74 -2
View File
@@ -44,7 +44,7 @@ func TestToolCallEventRenderToolCallBoundsOutputAndPreservesFailure(t *testing.T
t.Fatalf("oversized contents were not bounded: %q", got)
}
failed := RenderToolCall(ToolCallEvent{Name: "shell", Output: "ignored", Err: "command_exit: exit status 2"})
if failed != "🔧 shell — failed\n```text\ncommand_exit: exit status 2\n```" {
if failed != "shell — failed · command_exit: exit status 2" {
t.Fatalf("failure render = %q", failed)
}
}
@@ -74,7 +74,79 @@ func TestToolCallEventFailureKeyCollapsesLegacyTurnBudget(t *testing.T) {
if FailureKey(first) == "" || FailureKey(first) != FailureKey(second) {
t.Fatalf("legacy output-limit failures should share one key: %q vs %q", FailureKey(first), FailureKey(second))
}
if RenderToolCall(first) != "🔧 tools — stopped\n```text\ntool-output limit reached (200000 chars); further results suppressed\n```" {
if RenderToolCall(first) != "tools — stopped · tool-output limit reached (200000 chars); further results suppressed" {
t.Fatalf("legacy output-limit render = %q", RenderToolCall(first))
}
}
// TestRenderToolCallKeepsAOneLinePreviewOnItsOwnLine pins the shape that
// decides how much vertical space a turn's tool activity costs.
//
// Telegram renders a fenced block as a full code widget: a language header
// bar, a copy button and a panel. The block parser also inserts a spacer
// paragraph before every block, so a fenced one-line preview cost four
// rendered elements (header, spacer, panel, spacer) to display a word count.
// A single-line preview belongs on the header line.
func TestRenderToolCallKeepsAOneLinePreviewOnItsOwnLine(t *testing.T) {
got := RenderToolCall(ToolCallEvent{Name: "shell", Output: "63"})
if want := "shell · 63"; got != want {
t.Fatalf("render = %q, want %q", got, want)
}
if strings.Contains(got, "```") {
t.Errorf("a one-line preview must not open a code block: %q", got)
}
}
// TestRenderToolCallCollapsesMultiLineOutputToOneLine pins that the preview
// is always a single line, whatever the tool printed. Every toolPreview path
// already summarises to one line, which is why the fence it used to sit in
// was never wrapping more than one.
func TestRenderToolCallCollapsesMultiLineOutputToOneLine(t *testing.T) {
got := RenderToolCall(ToolCallEvent{Name: "shell", Output: `{"content":"alpha\nbeta\ngamma"}`})
if strings.Contains(got, "\n") {
t.Fatalf("render spans several lines: %q", got)
}
if !strings.Contains(got, "alpha") {
t.Errorf("render dropped the informative line: %q", got)
}
}
// TestRenderToolCallNeverOpensACodeBlock pins that output carrying its own
// fence cannot start one. The preview follows the header on the same line, so
// a fence marker can never reach column zero -- which is what lets the render
// pass the output through verbatim instead of substituting the backticks away
// and corrupting it.
func TestRenderToolCallNeverOpensACodeBlock(t *testing.T) {
got := RenderToolCall(ToolCallEvent{Name: "read", Output: "```go\nx := 1\n```"})
if strings.HasPrefix(got, "```") || strings.Contains(got, "\n```") {
t.Fatalf("render opens a code block: %q", got)
}
if !strings.Contains(got, "```go") {
t.Errorf("backticks were corrupted rather than passed through: %q", got)
}
}
// TestRenderToolCallUsesTheToolsOwnIcon pins that the icon is data carried on
// the event, not a constant in the renderer. One icon for every tool
// distinguishes nothing, and a renderer that invents one cannot be corrected
// by registering a tool.
func TestRenderToolCallUsesTheToolsOwnIcon(t *testing.T) {
got := RenderToolCall(ToolCallEvent{Name: "shell", Emoji: "💻", Output: "63"})
if want := "💻 shell · 63"; got != want {
t.Fatalf("render = %q, want %q", got, want)
}
failed := RenderToolCall(ToolCallEvent{Name: "shell", Emoji: "💻", Err: "command_exit: exit status 2"})
if want := "💻 shell — failed · command_exit: exit status 2"; failed != want {
t.Fatalf("failure render = %q, want %q", failed, want)
}
}
// TestRenderToolCallOmitsTheIconWhenTheToolDeclaresNone pins the fallback: a
// tool with no icon costs no column, rather than borrowing a generic one that
// says nothing about which tool ran.
func TestRenderToolCallOmitsTheIconWhenTheToolDeclaresNone(t *testing.T) {
got := RenderToolCall(ToolCallEvent{Name: "mcp.github.search", Output: "63"})
if want := "mcp.github.search · 63"; got != want {
t.Fatalf("render = %q, want %q", got, want)
}
}
+1
View File
@@ -74,6 +74,7 @@ func NewEditTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool {
return Tool{
Schema: editSchema,
Source: "builtin",
Emoji: "✏️",
Execute: makeEditExecutor(cwd, mq, rt),
}
}
+1
View File
@@ -73,6 +73,7 @@ func NewFindTool(cwd string) Tool {
return Tool{
Schema: findSchema,
Source: "builtin",
Emoji: "📁",
Execute: makeFindExecutor(cwd),
}
}
+1
View File
@@ -126,6 +126,7 @@ func NewGrepTool(cwd string, indexes ...GrepIndex) Tool {
return Tool{
Schema: grepSchema,
Source: "builtin",
Emoji: "🔍",
Execute: makeGrepExecutor(cwd, workspaceIndex),
}
}
+1
View File
@@ -209,6 +209,7 @@ func NewReadTool(cwd string, rt *ReadTracker) Tool {
return Tool{
Schema: readSchema,
Source: "builtin",
Emoji: "📄",
Execute: makeReadExecutor(cwd, rt),
}
}
+4
View File
@@ -63,6 +63,10 @@ type Tool struct {
Schema Schema
Execute Executor
Source string // "builtin", "extension:<name>"
// Emoji is the icon chat surfaces show for this tool. It is deliberately
// not part of Schema: Schema is serialised to the model as the tool's
// contract, and an icon is presentation. Empty means no icon.
Emoji string
}
// Registry holds all registered tools and provides thread-safe access.
+1
View File
@@ -74,6 +74,7 @@ func NewShellTool(cwd string, mq *MutationQueue) Tool {
return Tool{
Schema: shellSchema,
Source: "builtin",
Emoji: "💻",
Execute: makeShellExecutor(cwd, mq),
}
}
+1
View File
@@ -53,6 +53,7 @@ func NewWriteTool(cwd string, mq *MutationQueue, rt *ReadTracker) Tool {
return Tool{
Schema: writeSchema,
Source: "builtin",
Emoji: "📝",
Execute: makeWriteExecutor(cwd, mq, rt),
}
}
@@ -139,6 +139,7 @@ func toEntry(tool toolsbuiltin.Tool) (tools.ToolEntry, error) {
Toolset: toolset,
Schema: schema,
Classification: classify(tool.Schema.Name),
Emoji: tool.Emoji,
Handler: handlerFor(tool),
}, nil
}
@@ -305,3 +305,28 @@ func TestGrepConsultsSuppliedWorkspaceIndex(t *testing.T) {
t.Errorf("index asked for pattern %q, want the caller's pattern %q", pattern, "Target")
}
}
// TestWorkspaceToolsCarryTheirOwnIcon pins that each builtin declares an icon
// and that the conversion carries it. A chat surface renders what the tool
// registered, so an icon missing here is an icon missing on screen.
func TestWorkspaceToolsCarryTheirOwnIcon(t *testing.T) {
p := startedProvider(t, t.TempDir())
entries, err := p.Discover(t.Context())
if err != nil {
t.Fatalf("Tools: %v", err)
}
if len(entries) == 0 {
t.Fatal("no workspace tools registered")
}
seen := make(map[string]bool)
for _, entry := range entries {
if entry.Emoji == "" {
t.Errorf("tool %q registered no icon", entry.Name)
continue
}
seen[entry.Emoji] = true
}
if len(seen) < 2 {
t.Errorf("icons = %v, want tools to be distinguishable by icon", seen)
}
}