diff --git a/docs/contract.md b/docs/contract.md index b544d45..067594e 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -101,7 +101,7 @@ type: 'user_message' { text, images: Ref[], intent: 'start' | 'queued' | 'stee | 'command' { command, cwd, exitCode, output, outputTruncated, background: boolean } | 'file_change' { changes: { path, kind: 'add' | 'update' | 'delete' | 'move', diff }[] } | 'web_search' { query, results: { url, title }[] } - | 'tool' { name, server: string | null, input, output, isError } // anything else + | 'tool' { name, server: string | null, input, output, isError, icon? } // anything else; icon: the MCP server's own icon as a data: URI, fetched once by the host from the serverInfo icons its results carry | 'plan' { steps: { text, status }[] } | 'subagent' { title, agentType, prompt, result, childSessionId: string | null } | 'request' { requestId } // the card diff --git a/docs/ux.md b/docs/ux.md index 60f63f8..7fcad2d 100644 --- a/docs/ux.md +++ b/docs/ux.md @@ -42,7 +42,9 @@ A user preference (`quiet`, default on). T3 hides the mechanics of a turn until first; thinking, plans and approvals do not count). A new tool flies in and knocks the stack, a change of rank shuffles them like lotto balls, another call to a tool hops its icon, and a tool whose call failed turns red. That red replaces a "1 failed" count. A finished run in the history - sits still. + sits still. A command is drawn by its program (Python, Git, GitHub, Go, text search, packages, + containers, network; a terminal otherwise), and an MCP tool by its server's own icon when the + server sends one (Obsidian and Telegram do), else a wrench. Steps that look alike count together. - **A cheeky line beneath a working run** ("Hoarding GPUs…"): typed out, held 20 seconds, struck through and faded for the next; struck out when the run ends. The list is in web/src/session/phrases.ts. The `workPhrases` preference turns it off. diff --git a/internal/host/harness/claudecode/runtime.go b/internal/host/harness/claudecode/runtime.go index 7471ac5..3c2cba6 100644 --- a/internal/host/harness/claudecode/runtime.go +++ b/internal/host/harness/claudecode/runtime.go @@ -22,6 +22,7 @@ import ( "context" "github.com/andyjmorgan/outpost/internal/host/harness/feed" + "github.com/andyjmorgan/outpost/internal/host/harness/mcpicon" "github.com/andyjmorgan/outpost/internal/host/session" ) @@ -228,6 +229,7 @@ func (a *Adapter) Open(_ context.Context, s session.Session) (session.Runtime, e out: feed.New(), waiters: map[string]chan *ControlResponse{}, done: make(chan struct{})} rt.tr.OnUnknown = a.OnUnknown rt.tr.OnRateLimit = a.OnRateLimit + rt.tr.Icons.Fetch = mcpicon.Fetch cmd.Stderr = &rt.stderr started := func(int) {} if a.Spawn != nil { diff --git a/internal/host/harness/claudecode/translate.go b/internal/host/harness/claudecode/translate.go index 85be8fd..22a08da 100644 --- a/internal/host/harness/claudecode/translate.go +++ b/internal/host/harness/claudecode/translate.go @@ -13,6 +13,7 @@ import ( "strings" "time" + "github.com/andyjmorgan/outpost/internal/host/harness/mcpicon" "github.com/andyjmorgan/outpost/internal/host/session" ) @@ -26,6 +27,8 @@ type Translator struct { OnUnknown func(where string, raw json.RawMessage) // OnRateLimit is given each rate_limit_event line (the account's limits, during a turn). OnRateLimit func(raw json.RawMessage) + // Icons are the MCP servers' icons, passed on with their tool steps once Icons.Fetch is set. + Icons mcpicon.Servers inTurn bool interrupting bool @@ -836,6 +839,9 @@ func (t *Translator) toolUse(id, name string, input json.RawMessage, parent stri server = parts[1] } tl.body = map[string]any{"name": name, "server": server, "input": in, "output": "", "isError": false} + if s, ok := server.(string); ok { + mcpicon.Attach(tl.body, t.Icons.Known(s)) + } } t.tools[id] = tl return tl.event(session.ItemRunning) @@ -918,6 +924,7 @@ func (t *Translator) toolResult(id string, content json.RawMessage, isError bool tl.body["output"], tl.body["outputTruncated"] = text, cut case "tool": tl.body["output"] = text + t.reicon(tl, structured) } return tl.event(session.ItemRunning), true } @@ -960,6 +967,7 @@ func (t *Translator) toolResult(id string, content json.RawMessage, isError bool tl.body["result"] = text case "tool": tl.body["output"], tl.body["isError"] = text, isError + t.reicon(tl, structured) } return tl.event(status), true } @@ -1151,3 +1159,23 @@ func compaction(key, status string, before, after int64) session.AdapterEvent { raw, _ := json.Marshal(body) return session.AdapterEvent{Kind: session.EventItem, Item: &session.ItemUpdate{Key: key, Type: "compaction", Status: status, Body: raw}} } + +// reicon puts the server's icon on a tool step whose output has just come in: learnt from the +// result if it offers one, and checked again against the body limit now the output is there. +func (t *Translator) reicon(tl *tool, structured json.RawMessage) { + server, _ := tl.body["server"].(string) + icon, _ := tl.body["icon"].(string) + delete(tl.body, "icon") + var r struct { + Meta json.RawMessage `json:"_meta"` + } + _ = json.Unmarshal(structured, &r) + if r.Meta != nil { + if learnt := t.Icons.Learn(server, r.Meta); learnt != "" { + icon = learnt + } + } else if icon == "" { + icon = t.Icons.Known(server) + } + mcpicon.Attach(tl.body, icon) +} diff --git a/internal/host/harness/claudecode/translate_test.go b/internal/host/harness/claudecode/translate_test.go index ddf647d..9eab03f 100644 --- a/internal/host/harness/claudecode/translate_test.go +++ b/internal/host/harness/claudecode/translate_test.go @@ -3,6 +3,7 @@ package claudecode import ( "bufio" "encoding/json" + "fmt" "os" "path/filepath" "reflect" @@ -782,3 +783,29 @@ func TestAnInterruptedTurnsSteersAreNotRestarted(t *testing.T) { t.Fatal("the steer's own turn was not stopped") } } + +func TestMCPServerIconRidesOnItsSteps(t *testing.T) { + tr := NewTranslator() + tr.Icons.Fetch = func(src string) string { return "data:image/svg+xml;base64,PHN2Zy8+" } + tool := func(res Result) map[string]any { + var body map[string]any + for _, e := range res.Events { + if e.Kind == session.EventItem && e.Item.Type == "tool" { + _ = json.Unmarshal(e.Item.Body, &body) + } + } + return body + } + start := `{"type":"assistant","message":{"id":"m%d","content":[{"type":"tool_use","id":"toolu_%d","name":"mcp__obsidian__list_vaults","input":{}}]}}` + result := `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_%d","content":"{}"}]},"tool_use_result":{"content":"{}","_meta":{"io.modelcontextprotocol/serverInfo":{"name":"obsidian","icons":[{"src":"https://x/obsidian.svg","mimeType":"image/svg+xml","sizes":["any"]}]}}}}` + if b := tool(tr.Line(fmt.Appendf(nil, start, 1, 1))); b["icon"] != nil { + t.Fatalf("icon before the server showed one: %v", b["icon"]) + } + tool(tr.Line(fmt.Appendf(nil, result, 1))) + for tr.Icons.Known("obsidian") == "" { + time.Sleep(time.Millisecond) + } + if b := tool(tr.Line(fmt.Appendf(nil, start, 2, 2))); b["icon"] != "data:image/svg+xml;base64,PHN2Zy8+" { + t.Fatalf("a later step of the same server: %v", b) + } +} diff --git a/internal/host/harness/codex/runtime.go b/internal/host/harness/codex/runtime.go index 1893f09..1893623 100644 --- a/internal/host/harness/codex/runtime.go +++ b/internal/host/harness/codex/runtime.go @@ -17,6 +17,7 @@ import ( "time" "github.com/andyjmorgan/outpost/internal/host/harness/feed" + "github.com/andyjmorgan/outpost/internal/host/harness/mcpicon" "github.com/andyjmorgan/outpost/internal/host/session" ) @@ -123,6 +124,7 @@ func (a *Adapter) start(dir string, s session.Session) (*runtime, error) { rt := &runtime{a: a, cmd: cmd, stdin: stdin, tr: NewTranslator(), conf: s, out: feed.New(), waiters: map[string]chan *Response{}, done: make(chan struct{})} rt.tr.OnUnknown, rt.tr.OnRateLimits = a.OnUnknown, a.OnRateLimits + rt.tr.Icons.Fetch = mcpicon.Fetch cmd.Stderr = &rt.stderr started := func(int) {} if a.Spawn != nil && s.ID != "" { diff --git a/internal/host/harness/codex/translate.go b/internal/host/harness/codex/translate.go index c14fbda..b75f66f 100644 --- a/internal/host/harness/codex/translate.go +++ b/internal/host/harness/codex/translate.go @@ -12,6 +12,7 @@ import ( "strings" "time" + "github.com/andyjmorgan/outpost/internal/host/harness/mcpicon" "github.com/andyjmorgan/outpost/internal/host/session" ) @@ -22,6 +23,8 @@ type Translator struct { OnUnknown func(where string, raw json.RawMessage) // OnRateLimits is given the account's limits whenever the app-server reports them. OnRateLimits func(raw json.RawMessage) + // Icons are the MCP servers' icons, passed on with their tool steps once Icons.Fetch is set. + Icons mcpicon.Servers threadID string turnID string @@ -701,6 +704,7 @@ func (t *Translator) item(raw json.RawMessage, completed bool) (session.AdapterE Result *struct { Content []json.RawMessage `json:"content"` Structured json.RawMessage `json:"structuredContent"` + Meta json.RawMessage `json:"_meta"` } `json:"result"` Error *struct { Message string `json:"message"` @@ -843,7 +847,15 @@ func (t *Translator) item(raw json.RawMessage, completed bool) (session.AdapterE if completed && isError { status = session.ItemFailed } - return emit("tool", status, map[string]any{"name": name, "server": server, "input": input, "output": output, "isError": isError}) + body := map[string]any{"name": name, "server": server, "input": input, "output": output, "isError": isError} + if it.Type == "mcpToolCall" { + icon := t.Icons.Known(it.Server) + if it.Result != nil && it.Result.Meta != nil { + icon = t.Icons.Learn(it.Server, it.Result.Meta) + } + mcpicon.Attach(body, icon) + } + return emit("tool", status, body) case "webSearch": return emit("web_search", done, map[string]any{"query": it.Query, "results": []any{}}) case "subAgentActivity": diff --git a/internal/host/harness/mcpicon/mcpicon.go b/internal/host/harness/mcpicon/mcpicon.go new file mode 100644 index 0000000..e3b3b96 --- /dev/null +++ b/internal/host/harness/mcpicon/mcpicon.go @@ -0,0 +1,199 @@ +// Package mcpicon passes on what an MCP server looks like. +// +// A server can say so: its tool results carry its info, icons included, under +// _meta["io.modelcontextprotocol/serverInfo"]. The web client only shows images it is handed, +// never ones it would fetch from elsewhere, so the host fetches a server's icon once and passes +// it on as a data URI on that server's tool steps. Claude Code and Codex both pass _meta through. +package mcpicon + +import ( + "encoding/base64" + "encoding/json" + "errors" + "io" + "mime" + "net" + "net/http" + "strconv" + "strings" + "sync" + "syscall" + "time" + + "github.com/andyjmorgan/outpost/internal/host/session" +) + +const iconMax = 24 << 10 + +var ( + // The address comes from a tool server, so the host only goes to public addresses, over + // https all the way: never to itself or its own network, not even by a redirect. + iconClient = &http.Client{ + Timeout: 5 * time.Second, + Transport: &http.Transport{ + Proxy: nil, + DialContext: (&net.Dialer{Timeout: 3 * time.Second, Control: publicOnly}).DialContext, + TLSHandshakeTimeout: 3 * time.Second, + }, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 3 || req.URL.Scheme != "https" { + return errors.New("not followed") + } + return nil + }, + } + iconCache sync.Map // src -> data URI, or "" when it could not be had + // Shared address space (100.64.0.0/10): carrier NAT and Tailscale, never the public internet. + cgnat = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)} + // public says whether an address may be fetched from; tests widen it to their own server. + public = func(ip net.IP) bool { + return !(cgnat.Contains(ip) || ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsUnspecified() || ip.IsMulticast() || ip.IsInterfaceLocalMulticast()) + } +) + +// publicOnly refuses a connection to anything but a public address, checked on the address +// actually dialled so a name that resolves somewhere private is refused too. +func publicOnly(_, address string, _ syscall.RawConn) error { + host, _, err := net.SplitHostPort(address) + if err != nil { + return err + } + if ip := net.ParseIP(host); ip == nil || !public(ip) { + return errors.New("icon address is not public") + } + return nil +} + +// Pick is the icon a tool result's _meta offers for its server: a vector, else the bitmap +// nearest 32 pixels. "" when it offers none. +func Pick(meta json.RawMessage) string { + var r struct { + Server struct { + Icons []struct { + Src string `json:"src"` + MimeType string `json:"mimeType"` + Sizes []string `json:"sizes"` + } `json:"icons"` + } `json:"io.modelcontextprotocol/serverInfo"` + } + if json.Unmarshal(meta, &r) != nil { + return "" + } + best, score := "", -1 + for _, ic := range r.Server.Icons { + if !strings.HasPrefix(ic.Src, "https://") && !strings.HasPrefix(ic.Src, "data:image/") { + continue + } + s := 0 + switch { + case ic.MimeType == "image/svg+xml" || strings.HasSuffix(ic.Src, ".svg"): + s = 1000 + default: + for _, size := range ic.Sizes { + ws, _, _ := strings.Cut(size, "x") + if w, err := strconv.Atoi(ws); err == nil { + d := w - 32 + if d < 0 { + d = -d * 3 // smaller than 32 looks worse than larger + } + s = max(s, 500-d) + } + } + } + if s > score { + best, score = ic.Src, s + } + } + return best +} + +// Fetch turns an icon's address into a data URI, once per address for the life of the host. +// Only https, only images, and only small ones; anything else is remembered as missing. +func Fetch(src string) string { + if strings.HasPrefix(src, "data:image/") { + if len(src) > iconMax*2 { + return "" + } + return src + } + if v, ok := iconCache.Load(src); ok { + return v.(string) + } + uri := "" + defer func() { iconCache.Store(src, uri) }() + if !strings.HasPrefix(src, "https://") { + return "" + } + res, err := iconClient.Get(src) + if err != nil { + return "" + } + defer res.Body.Close() + ct, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")) + if res.StatusCode != http.StatusOK || (ct != "image/svg+xml" && ct != "image/png" && ct != "image/webp" && ct != "image/jpeg") { + return "" + } + b, err := io.ReadAll(io.LimitReader(res.Body, iconMax+1)) + if err != nil || len(b) > iconMax || len(b) == 0 { + return "" + } + uri = "data:" + ct + ";base64," + base64.StdEncoding.EncodeToString(b) + return uri +} + +// Attach puts the icon on a tool step's body unless that would make the body too big to keep: +// a picture is never worth losing the step's input and output for. +func Attach(body map[string]any, icon string) { + if icon == "" { + return + } + body["icon"] = icon + if b, err := json.Marshal(body); err != nil || len(b) > session.MaxItemBody { + delete(body, "icon") + } +} + +// Servers remembers each server's icon for one session, so a server's later steps show it. The +// icon is fetched in the background, so a slow or missing picture never holds up the session: +// the step that first offers it goes on without, and the steps after it carry it. The zero value +// passes nothing on until Fetch is set. +type Servers struct { + Fetch func(src string) string + mu sync.Mutex + icons map[string]string // server -> data URI, "" while fetching or once known to have none +} + +// Known is the server's icon if it has been fetched. +func (s *Servers) Known(server string) string { + s.mu.Lock() + defer s.mu.Unlock() + return s.icons[server] +} + +// Learn takes the icon a result's _meta offers for its server and fetches it once, in the +// background. It says the icon if it is already to hand. +func (s *Servers) Learn(server string, meta json.RawMessage) string { + if server == "" || s.Fetch == nil { + return "" + } + s.mu.Lock() + defer s.mu.Unlock() + if icon, ok := s.icons[server]; ok { + return icon + } + src := Pick(meta) + if src == "" { + return "" + } + if s.icons == nil { + s.icons = map[string]string{} + } + s.icons[server] = "" + go func() { + icon := s.Fetch(src) + s.mu.Lock() + s.icons[server] = icon + s.mu.Unlock() + }() + return "" +} diff --git a/internal/host/harness/mcpicon/mcpicon_test.go b/internal/host/harness/mcpicon/mcpicon_test.go new file mode 100644 index 0000000..5ed4b13 --- /dev/null +++ b/internal/host/harness/mcpicon/mcpicon_test.go @@ -0,0 +1,106 @@ +package mcpicon + +import ( + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/andyjmorgan/outpost/internal/host/session" +) + +func TestPickPrefersAVectorThenTheBitmapNearest32(t *testing.T) { + meta := `{"io.modelcontextprotocol/serverInfo":{"icons":[ + {"src":"https://x/16.png","mimeType":"image/png","sizes":["16x16"]}, + {"src":"https://x/64.png","mimeType":"image/png","sizes":["64x64"]}, + {"src":"http://x/plain.svg","mimeType":"image/svg+xml"}]}}` + if got := Pick(json.RawMessage(meta)); got != "https://x/64.png" { + t.Fatalf("without https vector: %q", got) + } + meta = strings.Replace(meta, "http://x/plain.svg", "https://x/icon.svg", 1) + if got := Pick(json.RawMessage(meta)); got != "https://x/icon.svg" { + t.Fatalf("with vector: %q", got) + } + if got := Pick(json.RawMessage(`{"other":1}`)); got != "" { + t.Fatalf("no icons: %q", got) + } +} + +func TestFetchKeepsSmallImagesOnly(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/ok.svg": + w.Header().Set("Content-Type", "image/svg+xml; charset=utf-8") + _, _ = w.Write([]byte("")) + case "/page": + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte("")) + case "/huge.png": + w.Header().Set("Content-Type", "image/png") + _, _ = w.Write(make([]byte, iconMax+1)) + } + })) + defer srv.Close() + tr := iconClient.Transport.(*http.Transport) + was, wasPublic := tr.TLSClientConfig, public + t.Cleanup(func() { tr.TLSClientConfig, public, iconCache = was, wasPublic, sync.Map{} }) + iconCache = sync.Map{} + tr.TLSClientConfig = srv.Client().Transport.(*http.Transport).TLSClientConfig + if got := Fetch(srv.URL + "/ok.svg"); got != "" { + t.Fatalf("a loopback address was fetched: %q", got) + } + iconCache = sync.Map{} + public = func(net.IP) bool { return true } + if got := Fetch(srv.URL + "/ok.svg"); got != "data:image/svg+xml;base64,PHN2Zy8+" { + t.Fatalf("svg: %q", got) + } + for _, p := range []string{"/page", "/huge.png", "/missing.png"} { + if got := Fetch(srv.URL + p); got != "" { + t.Fatalf("%s: %q", p, got) + } + } + if got := Fetch(strings.Replace(srv.URL, "https", "http", 1) + "/ok.svg"); got != "" { + t.Fatalf("plain http: %q", got) + } +} + +func TestServersFetchOncePerServer(t *testing.T) { + var calls atomic.Int32 + s := Servers{Fetch: func(src string) string { calls.Add(1); return "data:image/png;base64,AA==" }} + meta := json.RawMessage(`{"io.modelcontextprotocol/serverInfo":{"icons":[{"src":"https://x/a.svg","mimeType":"image/svg+xml"}]}}`) + if s.Known("obsidian") != "" { + t.Fatal("known before any result") + } + if got := s.Learn("obsidian", meta); got != "" { + t.Fatalf("the first sight waited for the fetch: %q", got) + } + for s.Known("obsidian") == "" { + time.Sleep(time.Millisecond) + } + for range 3 { + if got := s.Learn("obsidian", meta); got != "data:image/png;base64,AA==" { + t.Fatalf("learn: %q", got) + } + } + if calls.Load() != 1 { + t.Fatalf("fetched %d times", calls.Load()) + } +} + +func TestAttachLeavesTheIconOffABodyTooBigToKeep(t *testing.T) { + small := map[string]any{"output": "ok"} + Attach(small, "data:image/png;base64,AA==") + if small["icon"] == nil { + t.Fatal("a small body lost its icon") + } + big := map[string]any{"output": strings.Repeat("x", session.MaxItemBody-10)} + Attach(big, "data:image/png;base64,"+strings.Repeat("A", 100)) + if big["icon"] != nil { + t.Fatal("an icon pushed the body over the limit") + } +} diff --git a/web/package-lock.json b/web/package-lock.json index 74d0103..c8bcece 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -29,6 +29,7 @@ "react-markdown": "^10.1.0", "react-router-dom": "^7.18.7", "remark-gfm": "^4.0.1", + "simple-icons": "^16.39.0", "sonner": "^2.0.8", "tailwind-merge": "^3.7.1" }, @@ -5121,6 +5122,25 @@ "integrity": "sha512-irZHtTqurLna57KQG/s+fzOwv/J6XSH4cs8M/vsrY3uCaQ3S6+QJguAH0WdN47SXlk82voMZ4naWMQf8fdEoIg==", "license": "MIT" }, + "node_modules/simple-icons": { + "version": "16.39.0", + "resolved": "https://registry.npmjs.org/simple-icons/-/simple-icons-16.39.0.tgz", + "integrity": "sha512-LHSABBcOUtTnBTclT0cNigYQkcYrJQONMD3E3FTIfkg3i2BOH7y8U8dYJapwxODMLgK5QRNlmKGzLZF1gLE6mQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/simple-icons" + }, + { + "type": "github", + "url": "https://github.com/sponsors/simple-icons" + } + ], + "license": "CC0-1.0", + "engines": { + "node": ">=0.12.18" + } + }, "node_modules/sonner": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.8.tgz", diff --git a/web/package.json b/web/package.json index c4f19df..0b4855f 100644 --- a/web/package.json +++ b/web/package.json @@ -31,6 +31,7 @@ "react-markdown": "^10.1.0", "react-router-dom": "^7.18.7", "remark-gfm": "^4.0.1", + "simple-icons": "^16.39.0", "sonner": "^2.0.8", "tailwind-merge": "^3.7.1" }, diff --git a/web/src/pages/GalleryPage.tsx b/web/src/pages/GalleryPage.tsx index 9dbf109..bbceca1 100644 --- a/web/src/pages/GalleryPage.tsx +++ b/web/src/pages/GalleryPage.tsx @@ -9,6 +9,7 @@ import { StatusPill } from '../components/StatusPill' import type { Answer, Item, ItemStatus, Request, Turn } from '../outpost/sessions' import { Agents } from '../session/Agents' import { Conversation } from '../session/Conversation' +import { toolIcon } from '../session/toolIcons' import { FailureNote, ItemControl, RequestControl, TurnNote, Unknown, type Ctx } from '../session/controls' import { LimitMeters } from '../session/Limits' import recordedClaude from '../session/recorded.json' @@ -271,18 +272,40 @@ const TURNS = [ turn('failed', { class: 'unknown', message: '' }), ] +// A stand-in for a tool server's own icon, as the host hands it over. +const GEM = 'data:image/svg+xml;base64,' + btoa('') + +const sample = (type: string, body: Record) => ({ id: 'icon-' + JSON.stringify(body), type, status: 'completed', body, parentItemId: null }) as unknown as Item +const ICON_SAMPLES: [string, Item][] = [ + ['python3 · pip · uv', sample('command', { command: 'python3 x.py' })], + ['git', sample('command', { command: 'git status' })], + ['gh', sample('command', { command: 'gh pr view' })], + ['go', sample('command', { command: 'go test ./...' })], + ['Grep · rg · grep · sed · awk', sample('command', { command: 'rg foo' })], + ['npm · node · pnpm', sample('command', { command: 'npm test' })], + ['docker · kubectl', sample('command', { command: 'kubectl get pods' })], + ['WebFetch · curl · wget · web search', sample('command', { command: 'curl -s x' })], + ['Read · cat · head · tail', sample('command', { command: 'cat x' })], + ['Glob · ls · find · tree', sample('command', { command: 'ls -la' })], + ['sleep · until · while', sample('command', { command: 'sleep 5' })], + ['other commands', sample('command', { command: 'make' })], + ['file change', sample('file_change', { changes: [] })], + ['MCP server icon', sample('tool', { name: 'mcp__obsidian__list', server: 'obsidian', icon: GEM })], + ['other tools', sample('tool', { name: 'Read', server: null })], +] + // A run that plays itself, so the tool icons can be watched arriving, shuffling, hopping and failing. const SCRIPT: [string, string, boolean?][] = [ - ['command', 'npm run build'], - ['command', 'rg -n harness'], + ['command', 'python3 scripts/check.py'], + ['command', 'python3 -m pytest'], ['file_change', 'src/Conversation.tsx'], - ['tool', 'Read'], - ['tool', 'Read'], - ['command', 'ls -l /tmp/nope', true], - ['web_search', 'prefers-reduced-motion'], - ['web_search', 'lotto ball animation'], - ['web_search', 'WAAPI composite'], - ['web_search', 'spring easing'], + ['tool', 'mcp__obsidian__search_notes'], + ['tool', 'mcp__obsidian__read_note'], + ['command', 'python3 scripts/nope.py', true], + ['command', 'git status'], + ['command', 'git diff --stat'], + ['command', 'git log -1'], + ['command', 'gh pr checks'], ['file_change', 'src/ToolStack.tsx'], ] function LiveRun() { @@ -302,7 +325,7 @@ function LiveRun() { ? { changes: [{ path: what, kind: 'update', diff: '' }] } : type === 'web_search' ? { query: what } - : { name: what, server: null, input: {}, output: '', isError: false } + : { name: what, server: what.split('__')[1] ?? null, icon: what.startsWith('mcp__') ? GEM : undefined, input: {}, output: '', isError: false } return { id: `live-${k}`, type, status, body, parentItemId: null, ordinal: k, turnId: 'live', startedAt: new Date(started + k * 1400).toISOString(), endedAt: status === 'running' ? null : new Date(started + (k + 1) * 1400).toISOString() } as Item }) if (!items.length) return
@@ -423,6 +446,20 @@ export function GalleryPage() { /> +
+
+ {ICON_SAMPLES.map(([label, sample]) => { + const Icon = toolIcon(sample)?.Icon + return ( + + {Icon && } + {label} + + ) + })} +
+
+
diff --git a/web/src/pages/SessionPage.tsx b/web/src/pages/SessionPage.tsx index 9c44f98..cb23b84 100644 --- a/web/src/pages/SessionPage.tsx +++ b/web/src/pages/SessionPage.tsx @@ -15,7 +15,7 @@ import { listModels } from '../outpost/catalog' import { connect } from '../outpost/hosts' import { imagesIn, upload, type Attachment } from '../session/attachments' import { WorktreePreparation } from '../session/WorktreePreparation' -import { Conversation } from '../session/Conversation' +import { Conversation, endsInLiveRun } from '../session/Conversation' import { Agents } from '../session/Agents' import { ChangesPanel } from '../session/ChangesPanel' import { useGit } from '../session/git' @@ -500,7 +500,7 @@ export function SessionPage() { {/* Only when the failed turn's own note is not already on screen. */} {session?.status === 'failed' && session.lastError && snap.turns.get(items.at(-1)?.turnId ?? '')?.status !== 'failed' && } - {working && !items.some((i) => i.status === 'running') && ( + {working && !items.some((i) => i.status === 'running') && !(prefs.quiet !== false && endsInLiveRun(items, snap.turns, snap.requests)) && (

{session?.status === 'starting' ? 'Starting…' : 'Working…'} diff --git a/web/src/session/Conversation.tsx b/web/src/session/Conversation.tsx index 23de716..aa04dd7 100644 --- a/web/src/session/Conversation.tsx +++ b/web/src/session/Conversation.tsx @@ -5,6 +5,7 @@ import { usePreferences } from '../preferences' import type { Item, Request, Turn } from '../outpost/sessions' import { ItemControl, MachineImages, sameRow, TurnNote, type Ctx } from './controls' import { ToolStack, WorkPhrase } from './ToolStack' +import { serverIconsOf } from './toolIcons' // The mechanics of a turn: what the agent did between the things it said. They are drawn as one // run down a rule, and in quiet mode each run is a single line until it is opened. @@ -18,6 +19,23 @@ const isWork = (i: Item, requests: Map) => type Block = { kind: 'item'; item: Item } | { kind: 'work'; items: Item[] } +/** A reply with nothing in it (the agent often sends one between two tool calls): not drawn, and it does not split a run. */ +const blank = (i: Item) => i.type === 'assistant_message' && !String(i.body?.text ?? '').trim() + +const turnRunning = (turn?: Turn) => turn?.status === 'running' || turn?.status === 'starting' + +/** + * Whether the conversation already ends in a folded run that says it is working, so the session + * needs no "Working…" line of its own under it. + */ +export function endsInLiveRun(items: Item[], turns: Map, requests: Map): boolean { + // A turn's latest step, as Conversation draws it: a queued message after it does not count. + const ids = new Set(items.map((i) => i.id)) + const latest = new Map() + for (const i of items) if (i.turnId && !blank(i) && !(i.parentItemId && ids.has(i.parentItemId))) latest.set(i.turnId, i) + return [...latest].some(([turn, last]) => isWork(last, requests) && turnRunning(turns.get(turn))) +} + function clock(ms: number): string { const s = Math.max(0, Math.round(ms / 1000)) if (s < 60) return `${s}s` @@ -25,20 +43,21 @@ function clock(ms: number): string { return m < 60 ? `${m}m ${s % 60}s` : `${Math.floor(m / 60)}h ${m % 60}m` } -type WorkProps = { items: Item[]; quiet: boolean; ctx: Ctx } +/** working: its turn is running and this is the turn's latest block. turnRunning: its turn is running. */ +type WorkProps = { items: Item[]; quiet: boolean; ctx: Ctx; working: boolean; turnRunning: boolean } // A run is regrouped on every update, so its list is new each time; it draws again only when a // step in it is a different object or reads something from ctx that changed. const sameWork = (a: WorkProps, b: WorkProps) => - a.quiet === b.quiet && a.items.length === b.items.length && a.items.every((item, n) => sameRow({ item, ctx: a.ctx }, { item: b.items[n], ctx: b.ctx })) + a.quiet === b.quiet && a.working === b.working && a.turnRunning === b.turnRunning && a.items.length === b.items.length && a.items.every((item, n) => sameRow({ item, ctx: a.ctx }, { item: b.items[n], ctx: b.ctx })) /** * A run of steps. Quiet: one line, "Working for 1m 12s · 9 steps" or "Worked for 48s · 15 steps", * with its most used tools as icons at the end and, while it works, a cheeky line beneath. */ -const Work = memo(function Work({ items, quiet, ctx }: WorkProps) { - const doing = items.findLast((i) => i.status === 'running') - const live = doing !== undefined +const Work = memo(function Work({ items, quiet, ctx, working, turnRunning }: WorkProps) { + // Working while a step runs, and between steps while the turn goes on with nothing after this run yet. + const live = working || items.some((i) => i.status === 'running') const phrases = usePreferences().workPhrases !== false const [open, setOpen] = useState(false) const [now, setNow] = useState(() => Date.now()) @@ -78,10 +97,10 @@ const Work = memo(function Work({ items, quiet, ctx }: WorkProps) { {`${steps} ${steps === 1 ? 'step' : 'steps'}`} {failed > 0 && {`, ${failed} failed`}} - + - {phrases && } + {phrases && } {open &&

{renderRows()}
}
) @@ -123,6 +142,7 @@ export function Conversation({ const kids = new Map() const blocks: Block[] = [] for (const i of items) { + if (blank(i)) continue // A step whose parent has not been read yet (it is on an older page) stands on its own. if (i.parentItemId && ids.has(i.parentItemId)) { const siblings = kids.get(i.parentItemId) @@ -137,6 +157,11 @@ export function Conversation({ } return { blocks, kids } }, [items, requests]) + // Rebuilt only when an icon arrives or changes, so rows do not redraw on every update. + const found = serverIconsOf(items) + const iconSig = [...found].map(([s, i]) => s + '=' + i).join(',') + // eslint-disable-next-line react-hooks/exhaustive-deps + const serverIcons = useMemo(() => found, [iconSig]) const ctx = useMemo( () => ({ children: (id) => kids.get(id) ?? [], @@ -149,20 +174,29 @@ export function Conversation({ pinned, queued: (item) => !!item.turnId && turns.get(item.turnId)?.status === 'queued', onQueued, + serverIcons, }), - [kids, requests, canSteer, onAnswer, image, loopback, fork, pinned, turns, onQueued], + [kids, requests, canSteer, onAnswer, image, loopback, fork, pinned, turns, onQueued, serverIcons], ) const turnOf = (b?: Block) => (b?.kind === 'item' ? b.item.turnId : b?.items[0].turnId) + // Each turn's latest block: a queued message can sit between two runs of the same turn. + const latest = new Map() + blocks.forEach((b, n) => latest.set(turnOf(b), n)) return ( {blocks.map((b, n) => { const id = turnOf(b) const turn = id ? turns.get(id) : undefined const closes = turnOf(blocks[n + 1]) !== id + const running = turnRunning(turn) return (
- {b.kind === 'item' ? : } + {b.kind === 'item' ? ( + + ) : ( + + )} {turn && closes && }
) diff --git a/web/src/session/ToolStack.tsx b/web/src/session/ToolStack.tsx index faf5cb4..2dfc0f2 100644 --- a/web/src/session/ToolStack.tsx +++ b/web/src/session/ToolStack.tsx @@ -1,11 +1,9 @@ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { FilePen, Globe, SquareTerminal, Wrench, type LucideIcon } from 'lucide-react' import { cn } from '../lib' import type { Item } from '../outpost/sessions' import { PHRASES } from './phrases' -import { rankTools, type ToolKind } from './rankTools' - -const ICON: Record = { command: SquareTerminal, file_change: FilePen, web_search: Globe, tool: Wrench } +import { rankTools } from './rankTools' +import { toolIcon } from './toolIcons' /** How far apart the overlapping chips sit; a chip is 18px across. */ const STEP = 11 @@ -15,7 +13,7 @@ const still = () => typeof matchMedia === 'function' && matchMedia('(prefers-red const T = (x: number, y = 0, r = 0, sx = 1, sy = sx) => `translate(${x}px, ${y}px) rotate(${r}deg) scale(${sx}, ${sy})` -type Seen = { order: ToolKind[]; counts: Map; failed: Set; at: Map } +type Seen = { order: string[]; counts: Map; failed: Set; at: Map } /** * The three tools a run used most, as overlapping icons, most used in front. They move as the run @@ -23,37 +21,37 @@ type Seen = { order: ToolKind[]; counts: Map; failed: Set rankTools(items), [items]) +export function ToolStack({ items, serverIcons }: { items: Item[]; serverIcons?: Map }) { + const ranked = useMemo(() => rankTools(items, (i) => toolIcon(i, serverIcons)?.key ?? null), [items, serverIcons]) const box = useRef(null) - const chips = useRef(new Map()) + const chips = useRef(new Map()) const seen = useRef(null) - const key = ranked.map((t) => `${t.kind}:${t.count}:${t.failed ? 1 : 0}`).join(',') + const key = ranked.map((t) => `${t.key}:${t.count}:${t.failed ? 1 : 0}`).join(',') useLayoutEffect(() => { const right = box.current?.getBoundingClientRect().right ?? 0 // Where each chip sits, measured from the stack's right edge so scrolling does not read as movement. - const at = new Map() + const at = new Map() for (const t of ranked) { - const el = chips.current.get(t.kind) - if (el) at.set(t.kind, el.getBoundingClientRect().left - right) + const el = chips.current.get(t.key) + if (el) at.set(t.key, el.getBoundingClientRect().left - right) } const prev = seen.current - seen.current = { order: ranked.map((t) => t.kind), counts: new Map(ranked.map((t) => [t.kind, t.count])), failed: new Set(ranked.filter((t) => t.failed).map((t) => t.kind)), at } + seen.current = { order: ranked.map((t) => t.key), counts: new Map(ranked.map((t) => [t.key, t.count])), failed: new Set(ranked.filter((t) => t.failed).map((t) => t.key)), at } if (!prev || still()) return - const order = ranked.map((t) => t.kind) + const order = ranked.map((t) => t.key) const entered = order.filter((k) => !prev.order.includes(k)) const shuffled = order.some((k, i) => prev.order.includes(k) && prev.order.indexOf(k) !== i) const timers: number[] = [] const restacks: (() => void)[] = [] ranked.forEach((t, i) => { - const el = chips.current.get(t.kind) + const el = chips.current.get(t.key) if (!el) return - const was = prev.order.indexOf(t.kind) - const dx = (prev.at.get(t.kind) ?? 0) - (at.get(t.kind) ?? 0) - const newlyFailed = t.failed && !prev.failed.has(t.kind) && was >= 0 + const was = prev.order.indexOf(t.key) + const dx = (prev.at.get(t.key) ?? 0) - (at.get(t.key) ?? 0) + const newlyFailed = t.failed && !prev.failed.has(t.key) && was >= 0 if (was < 0) { // A new tool flies in from the right, overshoots into the stack, and settles. @@ -118,7 +116,7 @@ export function ToolStack({ items }: { items: Item[] }) { el.animate([{ transform: T(0) }, { transform: T(-2) }, { transform: T(2) }, { transform: T(-2) }, { transform: T(0) }], { duration: 300 }) return } - if (t.count > (prev.counts.get(t.kind) ?? 0)) { + if (t.count > (prev.counts.get(t.key) ?? 0)) { // Called again with no change of rank: a little hop. el.animate( [ @@ -145,15 +143,15 @@ export function ToolStack({ items }: { items: Item[] }) { return ( {ranked.map((t, i) => { - const Icon = ICON[t.kind] + const Icon = toolIcon(t.item, serverIcons)?.Icon ?? (() => null) return ( { - if (el) chips.current.set(t.kind, el) - else chips.current.delete(t.kind) + if (el) chips.current.set(t.key, el) + else chips.current.delete(t.key) }} - data-tool={t.kind} + data-tool={t.key} data-failed={t.failed || undefined} className={cn( 'absolute top-0 grid size-[18px] place-items-center rounded-full border ring-2 ring-background transition-colors duration-200', @@ -179,11 +177,17 @@ function nextPhrase() { const HOLD = 20_000 +// The line a turn is showing, so a run split by a message sent mid-turn carries it on instead +// of starting another. +const carried = new Map() + /** * A cheeky line under a working run: typed out, held for 20 seconds, struck through, faded, and - * replaced. When the run ends the last one is struck out and goes. A finished run shows none. + * replaced. When the turn ends the last one is struck out and goes. When the run stops being the + * turn's latest (a message was sent into it) the line moves on to the next run unbroken. A + * finished run shows none. */ -export function WorkPhrase({ live }: { live: boolean }) { +export function WorkPhrase({ live, turn = '', turnRunning }: { live: boolean; turn?: string; turnRunning: boolean }) { const [text, setText] = useState('') const [typing, setTyping] = useState(false) const [struck, setStruck] = useState(false) @@ -194,6 +198,10 @@ export function WorkPhrase({ live }: { live: boolean }) { let stop = false const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)) const calm = still() + const show = (phrase: string) => { + shown.current = phrase + setText(phrase) + } const leave = async () => { setStruck(true) await wait(calm ? 0 : 700) @@ -204,25 +212,37 @@ export function WorkPhrase({ live }: { live: boolean }) { const type = async (phrase: string) => { setStruck(false) setGone(false) - if (calm) { - shown.current = phrase - setText(phrase) - return - } - setTyping(true) - for (let n = 1; n <= phrase.length && !stop; n++) { - shown.current = phrase.slice(0, n) - setText(shown.current) - await wait(30 + Math.random() * 45) + if (calm) show(phrase) + else { + setTyping(true) + for (let n = 1; n <= phrase.length && !stop; n++) { + show(phrase.slice(0, n)) + await wait(30 + Math.random() * 45) + } + setTyping(false) } - setTyping(false) + if (!stop) carried.set(turn, { text: phrase, at: Date.now() }) } void (async () => { if (!live) { + // Handed on to a later run of the same turn: go quietly, the line lives on there. + if (turnRunning) { + if (!stop) show('') + return + } + carried.delete(turn) if (shown.current) await leave() - if (!stop) setText((shown.current = '')) + if (!stop) show('') return } + const before = carried.get(turn) + if (!shown.current && before && Date.now() - before.at < HOLD) { + // Picked up from the run before: shown whole, for what is left of its time. + setStruck(false) + setGone(false) + show(before.text) + await wait(HOLD - (Date.now() - before.at)) + } while (!stop) { if (shown.current) await leave() if (stop) return @@ -233,7 +253,7 @@ export function WorkPhrase({ live }: { live: boolean }) { return () => { stop = true } - }, [live]) + }, [live, turn, turnRunning]) if (!text) return null return ( diff --git a/web/src/session/controls.tsx b/web/src/session/controls.tsx index bb8aaee..93d2bb4 100644 --- a/web/src/session/controls.tsx +++ b/web/src/session/controls.tsx @@ -31,8 +31,8 @@ import { SquareTerminal, TriangleAlert, Wrench, - type LucideIcon, } from 'lucide-react' +import { toolIcon, type IconComponent } from './toolIcons' import { Button } from '../ui/components/button' import { Input } from '../ui/components/input' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '../ui/components/dropdown-menu' @@ -58,6 +58,8 @@ export interface Ctx { fork?: (item: Item) => (() => void) | undefined /** The request held above the composer; where it was asked, it is only marked. */ pinned?: string + /** Each tool server's icon in this conversation, for its steps that did not carry it. */ + serverIcons?: Map /** Whether a message is still waiting in a queued turn of its own. */ queued?: (item: Item) => boolean /** Sends a queued message now (into the running turn), or takes it back. */ @@ -354,7 +356,7 @@ function Step({ }: { shape: string status: ItemStatus - icon: LucideIcon + icon: IconComponent label: string summary?: string mono?: boolean @@ -433,6 +435,10 @@ export function sameRow(a: { item: Item; ctx: Ctx }, b: { item: Item; ctx: Ctx } if (a.ctx === b.ctx) return true if (a.ctx.canSteer !== b.ctx.canSteer || a.ctx.onAnswer !== b.ctx.onAnswer || a.ctx.image !== b.ctx.image || a.ctx.loopback !== b.ctx.loopback) return false switch (a.item.type) { + case 'tool': { + const server = str(a.item.body?.server) + return a.ctx.serverIcons?.get(server) === b.ctx.serverIcons?.get(server) + } case 'request': { const id = str(a.item.body?.requestId) return a.ctx.request(id) === b.ctx.request(id) && (a.ctx.pinned === id) === (b.ctx.pinned === id) @@ -493,7 +499,7 @@ export const ItemControl = memo(function ItemControl({ item, ctx }: { item: Item ) case 'command': return ( - + $ {str(b.command)} @@ -552,7 +558,7 @@ export const ItemControl = memo(function ItemControl({ item, ctx }: { item: Item const input = b.input && typeof b.input === 'object' ? b.input : {} const hint = input.file_path ?? input.path ?? input.pattern ?? input.url ?? input.query ?? input.description return ( - + {Object.keys(input).length > 0 && {str(input)}} {str(b.output) ? {str(b.output)} : item.status !== 'running' &&

No output.

}
diff --git a/web/src/session/phrases.ts b/web/src/session/phrases.ts index e58742f..7f937a9 100644 --- a/web/src/session/phrases.ts +++ b/web/src/session/phrases.ts @@ -127,4 +127,7 @@ export const PHRASES: readonly string[] = [ "Writing superior bash commands", "Manufacturing sharp edges", "Widening the blast radius", + "Inflating GPU prices", + "Performing circular finance options", + "Stealing RAM from gamers", ] diff --git a/web/src/session/rankTools.test.ts b/web/src/session/rankTools.test.ts index f4d4da9..d734026 100644 --- a/web/src/session/rankTools.test.ts +++ b/web/src/session/rankTools.test.ts @@ -2,12 +2,15 @@ import { describe, expect, it } from 'vitest' import type { Item } from '../outpost/sessions' import { rankTools } from './rankTools' +const KINDS = ['command', 'file_change', 'web_search', 'tool'] +const keyOf = (i: Item) => (KINDS.includes(i.type) ? i.type : null) + const step = (type: string, status = 'completed') => ({ id: Math.random().toString(36), type, status }) as unknown as Item describe('rankTools', () => { it('orders tools by use, most used first, and keeps three', () => { const items = [step('tool'), step('command'), step('command'), step('file_change'), step('web_search'), step('web_search'), step('web_search')] - expect(rankTools(items).map((t) => [t.kind, t.count])).toEqual([ + expect(rankTools(items, keyOf).map((t) => [t.key, t.count])).toEqual([ ['web_search', 3], ['command', 2], ['tool', 1], @@ -15,15 +18,15 @@ describe('rankTools', () => { }) it('breaks a tie in favour of the tool used first', () => { - expect(rankTools([step('file_change'), step('command'), step('command'), step('file_change')]).map((t) => t.kind)).toEqual(['file_change', 'command']) + expect(rankTools([step('file_change'), step('command'), step('command'), step('file_change')], keyOf).map((t) => t.key)).toEqual(['file_change', 'command']) }) it('ignores thinking, plans and approvals', () => { - expect(rankTools([step('reasoning'), step('plan'), step('request')])).toEqual([]) + expect(rankTools([step('reasoning'), step('plan'), step('request')], keyOf)).toEqual([]) }) it('marks a tool failed once any of its calls failed', () => { - const [command] = rankTools([step('command', 'failed'), step('command')]) - expect(command).toEqual({ kind: 'command', count: 2, failed: true }) + const [command] = rankTools([step('command', 'failed'), step('command')], keyOf) + expect(command).toMatchObject({ key: 'command', count: 2, failed: true }) }) }) diff --git a/web/src/session/rankTools.ts b/web/src/session/rankTools.ts index 737c113..cfd3481 100644 --- a/web/src/session/rankTools.ts +++ b/web/src/session/rankTools.ts @@ -1,29 +1,26 @@ import type { Item } from '../outpost/sessions' -/** The kinds of step that count as using a tool. Thinking, plans and approvals do not. */ -export const TOOL_KINDS = ['command', 'file_change', 'web_search', 'tool'] as const -export type ToolKind = (typeof TOOL_KINDS)[number] - -export type RankedTool = { kind: ToolKind; count: number; failed: boolean } - -const isTool = (type: string): type is ToolKind => (TOOL_KINDS as readonly string[]).includes(type) +export type RankedTool = { key: string; count: number; failed: boolean; item: Item } /** - * The three tools a run used most, most used first. A tie goes to the tool used first, so the - * order only changes when one tool really overtakes another. A tool is failed once any of its - * calls failed. + * The three tools a run used most, most used first. keyOf names what a step looks like (null for + * a step that is not a tool use: thinking, plans, approvals), so steps that look alike count + * together. A tie goes to the tool used first, so the order only changes when one tool really + * overtakes another. A tool is failed once any of its calls failed; item is its latest call. */ -export function rankTools(items: Item[]): RankedTool[] { - const seen = new Map() +export function rankTools(items: Item[], keyOf: (item: Item) => string | null): RankedTool[] { + const seen = new Map() items.forEach((item, n) => { - if (!isTool(item.type)) return - const entry = seen.get(item.type) ?? { kind: item.type, count: 0, failed: false, first: n } + const key = keyOf(item) + if (key === null) return + const entry = seen.get(key) ?? { key, count: 0, failed: false, item, first: n } entry.count++ + entry.item = item if (item.status === 'failed') entry.failed = true - seen.set(item.type, entry) + seen.set(key, entry) }) return [...seen.values()] .sort((a, b) => b.count - a.count || a.first - b.first) .slice(0, 3) - .map(({ kind, count, failed }) => ({ kind, count, failed })) + .map(({ key, count, failed, item }) => ({ key, count, failed, item })) } diff --git a/web/src/session/toolIcons.test.ts b/web/src/session/toolIcons.test.ts new file mode 100644 index 0000000..da9d184 --- /dev/null +++ b/web/src/session/toolIcons.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest' +import type { Item } from '../outpost/sessions' +import { program, toolIcon } from './toolIcons' + +const command = (c: string) => ({ id: 'x', type: 'command', status: 'completed', body: { command: c } }) as unknown as Item + +describe('program', () => { + it('finds the program past the scene-setting', () => { + expect(program('python3 -m pytest')).toBe('python3') + expect(program('cd web && npm run build')).toBe('npm') + expect(program('FOO=1 sudo timeout 30 /usr/bin/git status')).toBe('git') + expect(program('export X=1; gh pr list')).toBe('gh') + expect(program('')).toBe('') + }) +}) + +describe('toolIcon', () => { + it('draws a command by its program, and a terminal for the rest', () => { + expect(['python3.12 x.py', 'uv run t', 'git diff', 'gh pr view', 'rg -n foo | head', 'kubectl get pods', 'cat x', 'find . -name y', 'until gh pr checks 35; do sleep 5; done', 'make'].map((c) => toolIcon(command(c))?.key)).toEqual([ + 'python', + 'python', + 'git', + 'github', + 'text-search', + 'container', + 'read', + 'find', + 'wait', + 'terminal', + ]) + }) + + it("uses a tool server's own icon only when the host handed it over", () => { + const tool = (icon: unknown) => ({ id: 't', type: 'tool', status: 'completed', body: { name: 'mcp__obsidian__list', server: 'obsidian', icon } }) as unknown as Item + expect(toolIcon(tool('data:image/svg+xml;base64,PHN2Zy8+'))?.key).toBe('mcp:obsidian') + expect(toolIcon(tool('https://example.com/icon.svg'))?.key).toBe('tool') + expect(toolIcon({ id: 'g', type: 'tool', status: 'completed', body: { name: 'Read', server: null } } as unknown as Item)?.key).toBe('read') + expect(toolIcon({ id: 'r', type: 'reasoning', status: 'completed', body: {} } as unknown as Item)).toBeNull() + }) +}) diff --git a/web/src/session/toolIcons.tsx b/web/src/session/toolIcons.tsx new file mode 100644 index 0000000..3249ba4 --- /dev/null +++ b/web/src/session/toolIcons.tsx @@ -0,0 +1,118 @@ +import type { ComponentType } from 'react' +import { Clock, Container, Eye, FilePen, FolderSearch, Globe, Package, SquareTerminal, TextSearch, Wrench } from 'lucide-react' +import { siGit, siGithub, siGo, siPython } from 'simple-icons' +import type { Item } from '../outpost/sessions' + +export type IconComponent = ComponentType<{ className?: string }> + +/** What a step looks like: key names the picture, so steps that look the same count together. */ +export type ToolIcon = { key: string; Icon: IconComponent } + +const brand = (si: { title: string; path: string }): IconComponent => + function Brand({ className }) { + return ( + + + + ) + } + +const Python = brand(siPython) +const Git = brand(siGit) +const GitHub = brand(siGithub) +const Go = brand(siGo) + +const READ: ToolIcon = { key: 'read', Icon: Eye } +const FIND: ToolIcon = { key: 'find', Icon: FolderSearch } +const SEARCH: ToolIcon = { key: 'text-search', Icon: TextSearch } +const WEB: ToolIcon = { key: 'globe', Icon: Globe } +// What a command is, by the program it runs. Anything not listed is a terminal. +const PROGRAMS: [RegExp, ToolIcon][] = [ + [/^(python\d*(\.\d+)?|pip\d*|uv|uvx|pytest|poetry)$/, { key: 'python', Icon: Python }], + [/^git$/, { key: 'git', Icon: Git }], + [/^gh$/, { key: 'github', Icon: GitHub }], + [/^(grep|egrep|fgrep|rg|ag|sed|awk)$/, SEARCH], + [/^(cat|head|tail|less|more|bat|wc|nl)$/, READ], + [/^(ls|find|fd|tree|du)$/, FIND], + [/^(npm|npx|node|pnpm|yarn|bun|bunx)$/, { key: 'package', Icon: Package }], + [/^(docker|kubectl|helm|podman)$/, { key: 'container', Icon: Container }], + [/^(curl|wget)$/, WEB], + [/^(sleep|until|while|wait|watch)$/, { key: 'wait', Icon: Clock }], + [/^go$/, { key: 'go', Icon: Go }], +] +const TERMINAL: ToolIcon = { key: 'terminal', Icon: SquareTerminal } + +// The agents' own tools, by name. Reading a file looks the same whether a tool or cat did it. +const BUILTIN: Record = { Read: READ, NotebookRead: READ, Grep: SEARCH, Glob: FIND, LS: FIND, WebFetch: WEB } + +// Words in front of the program that are not the program. +const WRAPPERS = new Set(['sudo', 'env', 'time', 'nohup', 'nice', 'exec', 'command']) +// Leading steps that only set the scene; the program after them is the one that counts. +const SETUP = new Set(['cd', 'pushd', 'export', 'set', 'source', '.', 'unset']) + +/** The program a shell command runs: past `cd x &&`, variables, `sudo` and the like, and a path. */ +export function program(command: string): string { + for (const part of command.split(/&&|\|\||;|\||\n/)) { + const words = part.trim().split(/\s+/).filter(Boolean) + let n = 0 + while (n < words.length) { + const w = words[n] + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(w) || WRAPPERS.has(w)) n++ + else if (w === 'timeout') n += /^\d/.test(words[n + 1] ?? '') ? 2 : 1 + else break + } + const word = words[n] + if (!word || SETUP.has(word)) continue + return word.replace(/^["']|["']$/g, '').split('/').pop() ?? '' + } + return '' +} + +// One component per MCP icon, so a stack or a row does not remount it on every update. +const pictures = new Map() +function picture(src: string): IconComponent { + let p = pictures.get(src) + if (!p) { + p = function McpIcon({ className }) { + return + } + pictures.set(src, p) + } + return p +} + +/** + * Each tool server's icon in one conversation, from any step that carried it. The host passes a + * server's icon on only once it has fetched it, so the server's earlier steps learn it from here. + */ +export function serverIconsOf(items: Item[]): Map { + const icons = new Map() + for (const i of items) { + const b = i.body ?? {} + if (i.type === 'tool' && typeof b.server === 'string' && typeof b.icon === 'string' && b.icon.startsWith('data:image/')) icons.set(b.server, b.icon) + } + return icons +} + +/** The picture for a step that uses a tool, or null for a step that does not. */ +export function toolIcon(item: Item, serverIcons?: Map): ToolIcon | null { + const b = item.body ?? {} + switch (item.type) { + case 'command': { + const prog = program(typeof b.command === 'string' ? b.command : '') + return PROGRAMS.find(([re]) => re.test(prog))?.[1] ?? TERMINAL + } + case 'file_change': + return { key: 'file_change', Icon: FilePen } + case 'web_search': + return WEB + case 'tool': { + // A tool server's own icon, passed on by the host as a data URI; never fetched from elsewhere. + const icon = typeof b.icon === 'string' && b.icon.startsWith('data:image/') ? b.icon : typeof b.server === 'string' ? serverIcons?.get(b.server) : undefined + if (icon) return { key: 'mcp:' + (b.server ?? icon), Icon: picture(icon) } + return BUILTIN[typeof b.name === 'string' ? b.name : ''] ?? { key: 'tool', Icon: Wrench } + } + default: + return null + } +} diff --git a/web/tests/e2e.mjs b/web/tests/e2e.mjs index 1de2948..b80d195 100644 --- a/web/tests/e2e.mjs +++ b/web/tests/e2e.mjs @@ -986,11 +986,13 @@ for (const engine of engines) { await confirmReturn.click() ok('returning and confirming explicitly accepts the elicitation', (await page.getByTestId('gallery-answer').innerText()).includes('"decision":"accept"')) // A folded run ends with its most used tools as icons; one whose call failed is red. - ok('a run shows its most used tools, a failed one in red', (await page.locator('[data-shape="work"] [data-tool="command"][data-failed]').count()) >= 1) + ok('a run shows its most used tools, a failed one in red', (await page.locator('[data-shape="work"] [data-tool="go"][data-failed]').count()) >= 1) await page.waitForFunction(() => (document.querySelector('[data-shape-part="work-phrase"]')?.textContent ?? '').endsWith('…'), null, { timeout: 10000 }) ok('a working run types a cheeky line beneath itself', true) await page.locator('[data-shape-part="work-phrase"]').first().evaluate((el) => el.scrollIntoView({ block: 'center' })) await shot('5g-tool-stack') + await page.getByTestId('tool-icons').evaluate((el) => el.scrollIntoView({ block: 'center' })) + await shot('5h-tool-icons') await page.locator('[data-shape-part="diagram"] svg').first().waitFor({ timeout: 20000 }) ok('a mermaid block in a reply is drawn as a diagram', (await page.locator('[data-shape-part="diagram"] svg').first().innerHTML()).includes('IK handshake')) ok('a diagram still being written waits instead of drawing half of itself', (await page.locator('[data-shape-part="drawing-pending"]').count()) === 1 && (await page.locator('[data-shape-part="diagram"]').count()) === 1)