From 15234950d68347844ea9f45652a8cb62a2e363fb Mon Sep 17 00:00:00 2001 From: Andrew Morgan Date: Tue, 1 Dec 2026 17:08:54 +0000 Subject: [PATCH] Audit today's merges: Safari-safe URL checks, one sign-in refresh at a time, shared MCP and host helpers Web: replace URL.parse/URL.canParse (missing on older Safari) with a webUrl helper, share one in-flight token renewal, catch a failed /compact, merge duplicate harness icon components, memoise the context reading. MCP server: encode tool icons once, reach() by value, one askSteer and one per-machine fan-out helper for sessions/folders. Host: one TurnEndedError for both runtimes, one withIntent helper. Co-Authored-By: Claude Opus 5.5 --- internal/host/harness/claudecode/runtime.go | 15 +- internal/host/harness/codex/runtime.go | 16 +- internal/host/session/adapter.go | 12 ++ internal/host/session/service.go | 24 +-- internal/mcpserver/agents.go | 9 +- internal/mcpserver/grant_requests.go | 7 + internal/mcpserver/icons.go | 48 ++--- internal/mcpserver/server.go | 198 +++++++++----------- internal/mcpserver/wake.go | 7 +- web/src/agents/AgentIcon.tsx | 5 +- web/src/auth.ts | 11 +- web/src/components/HarnessIcon.tsx | 17 +- web/src/lib.ts | 14 ++ web/src/pages/SessionPage.tsx | 5 +- web/src/session/SessionSheet.tsx | 2 + web/src/session/controls.tsx | 5 +- 16 files changed, 188 insertions(+), 207 deletions(-) diff --git a/internal/host/harness/claudecode/runtime.go b/internal/host/harness/claudecode/runtime.go index 6f8e419..95f4a83 100644 --- a/internal/host/harness/claudecode/runtime.go +++ b/internal/host/harness/claudecode/runtime.go @@ -502,12 +502,12 @@ func (rt *runtime) prompt(in session.TurnInput, priority string) error { // Nothing to steer into: the CLI would make the message a turn of its own, which the // service would not know was coming. The service queues it instead. rt.mu.Unlock() - return &TurnEndedError{Reason: "no turn is running"} + return &session.TurnEndedError{Reason: "no turn is running"} } else if rt.tr.Ended() != in.TurnsEnded { // The turn the service meant has ended here, and it has not heard yet: the message // would land in a turn it does not know of. rt.mu.Unlock() - return &TurnEndedError{Reason: "the turn it was meant for has ended"} + return &session.TurnEndedError{Reason: "the turn it was meant for has ended"} } else { rt.tr.Steered(id, in.MessageID) // the turn's result says if it was never taken in } @@ -516,17 +516,6 @@ func (rt *runtime) prompt(in session.TurnInput, priority string) error { return rt.write(UserLine(native, id, in.Text, images, priority)) } -// TurnEndedError is what Steer returns when there is no turn to add the message to. The message -// was not delivered; the service makes it a turn of its own. -type TurnEndedError struct{ Reason string } - -func (e *TurnEndedError) Error() string { - return "the turn had already ended, so the message was not added to it (" + e.Reason + ")" -} - -// TurnEnded marks the error for a caller that cannot name this package's types. -func (e *TurnEndedError) TurnEnded() bool { return true } - func (rt *runtime) StartTurn(in session.TurnInput) error { return rt.prompt(in, "") } // Steer adds a message to the turn in progress. A turn the CLI has just finished, whose result diff --git a/internal/host/harness/codex/runtime.go b/internal/host/harness/codex/runtime.go index 1ccf64e..f51bb8f 100644 --- a/internal/host/harness/codex/runtime.go +++ b/internal/host/harness/codex/runtime.go @@ -478,25 +478,13 @@ func (rt *runtime) awaitTurn(endedBefore string, limit time.Duration) string { } } -// TurnEndedError is what Steer returns when there is no turn to add the message to: it ended -// before the message got there. The message was not delivered, and was not made into a turn of -// its own; that is the caller's decision. -type TurnEndedError struct{ Reason string } - -func (e *TurnEndedError) Error() string { - return "the turn had already ended, so the message was not added to it (" + e.Reason + ")" -} - -// TurnEnded marks the error for a caller that cannot name this package's types. -func (e *TurnEndedError) TurnEnded() bool { return true } - // Steer adds a message to the turn in progress. func (rt *runtime) Steer(in session.TurnInput) error { rt.mu.Lock() thread, turn := rt.tr.ThreadID(), rt.tr.TurnID() rt.mu.Unlock() if turn == "" { - return &TurnEndedError{Reason: "no turn is running"} + return &session.TurnEndedError{Reason: "no turn is running"} } params := map[string]any{"threadId": thread, "expectedTurnId": turn, "input": input(in)} if in.MessageID != "" { @@ -509,7 +497,7 @@ func (rt *runtime) Steer(in session.TurnInput) error { strings.Contains(err.Error(), "cannot steer a compact turn")) { // Codex refused because the turn it was meant for is over (seen as "no active turn to // steer"), or a newer one has taken its place. - return &TurnEndedError{Reason: err.Error()} + return &session.TurnEndedError{Reason: err.Error()} } return err } diff --git a/internal/host/session/adapter.go b/internal/host/session/adapter.go index 9cf8813..abdbe6a 100644 --- a/internal/host/session/adapter.go +++ b/internal/host/session/adapter.go @@ -61,6 +61,18 @@ type TurnInput struct { TurnsEnded int } +// TurnEndedError is what Steer returns when there is no turn to add the message to: it ended +// before the message got there. The message was not delivered; the service makes it a turn of +// its own. +type TurnEndedError struct{ Reason string } + +func (e *TurnEndedError) Error() string { + return "the turn had already ended, so the message was not added to it (" + e.Reason + ")" +} + +// TurnEnded marks the error (steerFailed matches on this method). +func (e *TurnEndedError) TurnEnded() bool { return true } + type Answer struct { Decision string Answers map[string][]string diff --git a/internal/host/session/service.go b/internal/host/session/service.go index a004e6e..ad08e51 100644 --- a/internal/host/session/service.go +++ b/internal/host/session/service.go @@ -742,14 +742,9 @@ func (s *Service) planSendNow(ctx context.Context, l *live, sess *Session, w *Wr } now := time.Now().UTC() if s.canSteer(l, sess) { - var b map[string]any - if json.Unmarshal(item.Body, &b) != nil || b == nil { - b = map[string]any{} - } - b["intent"] = "steer" // It joins the running turn where it lands now, after what that turn has said so far. l.itemOrd++ - item.TurnID, item.Ordinal, item.StartedAt, item.EndedAt, item.Body = *sess.ActiveTurnID, l.itemOrd, now, &now, body(b) + item.TurnID, item.Ordinal, item.StartedAt, item.EndedAt, item.Body = *sess.ActiveTurnID, l.itemOrd, now, &now, withIntent(item.Body, "steer") w.Changes = append(w.Changes, TurnRemoved{SessionID: sess.ID, TurnID: turn.ID}, item, touch(sess)) return []func(){s.steerEffect(w, l, sess, in)}, nil } @@ -762,6 +757,16 @@ func (s *Service) planSendNow(ctx context.Context, l *live, sess *Session, w *Wr return []func(){s.startTurn(w, sess.ID, turn.ID, in)}, nil } +// withIntent is a user message's body with its delivery intent changed. +func withIntent(raw json.RawMessage, intent string) json.RawMessage { + var b map[string]any + if json.Unmarshal(raw, &b) != nil || b == nil { + b = map[string]any{} + } + b["intent"] = intent + return body(b) +} + // steerFailed deals with a message the harness did not add to the running turn, so it is never // lost without a word. A harness that found the turn already over has not delivered it: the // message becomes a queued turn of its own, started now if nothing else is running or else @@ -806,14 +811,9 @@ func (s *Service) steerFailed(sessionID string, in TurnInput, cause error) error } l.turnOrd++ turn := &Turn{ID: newID("trn"), SessionID: sessionID, Ordinal: l.turnOrd, Status: status, Trigger: "user", StartedAt: now} - var b map[string]any - if json.Unmarshal(item.Body, &b) != nil || b == nil { - b = map[string]any{} - } - b["intent"] = "queued" // It moves to the end, after what the turn it missed went on to say. l.itemOrd++ - item.TurnID, item.Ordinal, item.Body = turn.ID, l.itemOrd, body(b) + item.TurnID, item.Ordinal, item.Body = turn.ID, l.itemOrd, withIntent(item.Body, "queued") w.Changes = append(w.Changes, turn, item) if status == TurnStarting { sess.Status, sess.ActiveTurnID, sess.LastError = StatusStarting, &turn.ID, nil diff --git a/internal/mcpserver/agents.go b/internal/mcpserver/agents.go index 399dfae..ec8552d 100644 --- a/internal/mcpserver/agents.go +++ b/internal/mcpserver/agents.go @@ -53,11 +53,7 @@ func (s *Server) agentCreate(ctx context.Context, req *mcp.CallToolRequest, in A defer cancel() c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { - var out AgentCreated - if early != nil { - out = AgentCreated{MachineID: h.ID, Access: early.Access, ApproveURL: early.ApproveURL, Error: early.Error} - } - return ask, out, err + return ask, AgentCreated{MachineID: h.ID, Access: early.Access, ApproveURL: early.ApproveURL, Error: early.Error}, err } defer c.Close() // The MCP service handles the private prompt, then sends it over the encrypted channel. @@ -69,8 +65,7 @@ func (s *Server) agentCreate(ctx context.Context, req *mcp.CallToolRequest, in A if errors.As(err, &rpcErr) { switch { case needsSteer(err): - recordGrantRequest(ctx, c, u, peer.ScopeSteer) - ask, approval, err := s.machineApproval(u, req, h, peer.ScopeSteer) + ask, approval, err := s.askSteer(ctx, c, u, req, h) return ask, AgentCreated{MachineID: h.ID, Access: approval.Access, ApproveURL: approval.ApproveURL, Error: "Choose View and steer sessions for this machine to create an agent."}, err case rpcErr.Code == wire.CodeMethodNotFound || (rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"admin" scope`)): return nil, AgentCreated{}, fmt.Errorf("update Outpost on %s to a version that supports agent_create", h.Name) diff --git a/internal/mcpserver/grant_requests.go b/internal/mcpserver/grant_requests.go index cba7105..8fa486b 100644 --- a/internal/mcpserver/grant_requests.go +++ b/internal/mcpserver/grant_requests.go @@ -52,6 +52,13 @@ func needsSteer(err error) bool { return errors.As(err, &rpcErr) && rpcErr.Code == peer.CodeForbidden && strings.Contains(rpcErr.Message, `"steer" scope`) } +// askSteer answers a machine that refused a command for want of steer: it records the request +// on the machine and sends the person to approve steer there. +func (s *Server) askSteer(ctx context.Context, c *client.Conn, u user, req *mcp.CallToolRequest, h relayHost) (*mcp.CallToolResult, SessionRead, error) { + recordGrantRequest(ctx, c, u, peer.ScopeSteer) + return s.machineApproval(u, req, h, peer.ScopeSteer) +} + func (s *Server) machineApproval(u user, req *mcp.CallToolRequest, h relayHost, scope string) (*mcp.CallToolResult, SessionRead, error) { key, err := s.key(u) if err != nil { diff --git a/internal/mcpserver/icons.go b/internal/mcpserver/icons.go index 61547f1..33b7400 100644 --- a/internal/mcpserver/icons.go +++ b/internal/mcpserver/icons.go @@ -3,7 +3,6 @@ package mcpserver import ( "embed" "encoding/base64" - "strings" "github.com/modelcontextprotocol/go-sdk/mcp" ) @@ -39,30 +38,31 @@ func svgURI(svg []byte) string { return "data:image/svg+xml;base64," + base64.StdEncoding.EncodeToString(svg) } -// serverIcons is the brand mark for light and dark backgrounds; light first, for a client that -// takes the first it can show. -func serverIcons() []mcp.Icon { - light, _ := brand.ReadFile("icons/outpost-light.svg") - dark, _ := brand.ReadFile("icons/outpost-dark.svg") - return []mcp.Icon{ - {Source: svgURI(light), MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeLight}, - {Source: svgURI(dark), MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeDark}, - } -} +// The service is stateless, so every request builds a fresh MCP server; the icons are encoded +// once here rather than on each build. +var ( + brandIcons = func() []mcp.Icon { + light, _ := brand.ReadFile("icons/outpost-light.svg") + dark, _ := brand.ReadFile("icons/outpost-dark.svg") + return themed(svgURI(light), svgURI(dark)) + }() + glyphIcons = func() map[string][]mcp.Icon { + out := make(map[string][]mcp.Icon, len(toolGlyphs)) + for name, glyph := range toolGlyphs { + ink := func(color string) string { + return svgURI([]byte(`` + glyph + ``)) + } + out[name] = themed(ink(inkOnLight), ink(inkOnDark)) + } + return out + }() +) -// toolIcons is a tool's glyph inked for light and dark backgrounds; nil for a tool without one. -func toolIcons(name string) []mcp.Icon { - glyph, ok := toolGlyphs[name] - if !ok { - return nil - } - ink := func(color string) string { - return svgURI([]byte(strings.Join([]string{ - ``, glyph, ``}, ""))) - } +// themed is a light and a dark SVG; light first, for a client that takes the first it can show. +func themed(light, dark string) []mcp.Icon { return []mcp.Icon{ - {Source: ink(inkOnLight), MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeLight}, - {Source: ink(inkOnDark), MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeDark}, + {Source: light, MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeLight}, + {Source: dark, MIMEType: "image/svg+xml", Sizes: []string{"any"}, Theme: mcp.IconThemeDark}, } } diff --git a/internal/mcpserver/server.go b/internal/mcpserver/server.go index 7f630c3..1f74da7 100644 --- a/internal/mcpserver/server.go +++ b/internal/mcpserver/server.go @@ -324,7 +324,7 @@ func logged(next http.Handler) http.Handler { // withIcons gives a tool its picture. func withIcons(t *mcp.Tool) *mcp.Tool { - t.Icons = toolIcons(t.Name) + t.Icons = glyphIcons[t.Name] return t } @@ -341,7 +341,7 @@ func acts(destructive bool) *mcp.ToolAnnotations { } func (s *Server) mcp() *mcp.Server { - srv := mcp.NewServer(&mcp.Implementation{Name: "outpost", Title: "Outpost", Version: s.cfg.Version, WebsiteURL: s.cfg.WebURL, Icons: serverIcons()}, &mcp.ServerOptions{ + srv := mcp.NewServer(&mcp.Implementation{Name: "outpost", Title: "Outpost", Version: s.cfg.Version, WebsiteURL: s.cfg.WebURL, Icons: brandIcons}, &mcp.ServerOptions{ Instructions: "Outpost reaches coding sessions on the user's own machines. A machine answers only once the user " + "approves this connection in the Outpost web app. The user is normally sent there directly; when a tool's answer " + "carries needs_approval and an approveUrl instead, give the user that link. " + @@ -655,27 +655,27 @@ type hostSession struct { ArchivedAt *time.Time `json:"archivedAt"` } -func (s *Server) sessionsList(ctx context.Context, req *mcp.CallToolRequest, in SessionsInput) (*mcp.CallToolResult, Sessions, error) { - u, err := userOf(req) - if err != nil { - return nil, Sessions{}, err - } +// watched is one machine's session rows, or why it was not asked. +type watched struct { + h relayHost + sessions []hostSession + skipped *Machine +} + +// watchAll asks every machine (or the one named) for its session rows, concurrently. +func (s *Server) watchAll(ctx context.Context, u user, machine string) ([]watched, error) { hosts, err := s.hosts(ctx, u) if err != nil { - return nil, Sessions{}, err + return nil, err } - if in.Machine != "" { - h, err := pick(hosts, in.Machine) + if machine != "" { + h, err := pick(hosts, machine) if err != nil { - return nil, Sessions{}, err + return nil, err } hosts = []relayHost{h} } - type result struct { - sessions []Session - skipped *Machine - } - results := each(hosts, func(h relayHost) result { + return each(hosts, func(h relayHost) watched { ctx, cancel := context.WithTimeout(ctx, perHost) defer cancel() c, access, err := s.dial(ctx, u, h, peer.ScopeView) @@ -684,7 +684,7 @@ func (s *Server) sessionsList(ctx context.Context, req *mcp.CallToolRequest, in if err != nil { m.Error = err.Error() } - return result{skipped: m} + return watched{h: h, skipped: m} } defer c.Close() var res struct { @@ -692,34 +692,58 @@ func (s *Server) sessionsList(ctx context.Context, req *mcp.CallToolRequest, in Sessions []hostSession `json:"sessions"` } if err := c.Call(ctx, "sessions.watch", nil, &res); err != nil { - return result{skipped: &Machine{ID: h.ID, Name: h.Name, Online: true, Access: AccessError, Error: err.Error()}} + return watched{h: h, skipped: &Machine{ID: h.ID, Name: h.Name, Online: true, Access: AccessError, Error: err.Error()}} } _ = c.Call(ctx, "subscription.cancel", map[string]string{"sub": res.Sub}, nil) - var out []Session - for _, hs := range res.Sessions { - if hs.ArchivedAt != nil && !in.Archived { - continue - } - row := sessionRow(h, hs) - out = append(out, row) - } - return result{sessions: out} - }) - out := Sessions{Sessions: []Session{}} - // Every machine asked is waiting on approval, or none answered and one is: ask for it. - answered := slices.ContainsFunc(results, func(r result) bool { return r.skipped == nil }) - if !answered && slices.ContainsFunc(results, func(r result) bool { return r.skipped != nil && r.skipped.Access == AccessNeedsApproval }) { + return watched{h: h, sessions: res.Sessions} + }), nil +} + +// unanswered is what a list says about the machines that were not asked. Every machine asked is +// waiting on approval, or none answered and one is: the client is asked (ask or err set), and +// the caller returns that. Otherwise it is the skipped machines and, when one awaits approval, +// the link. +func (s *Server) unanswered(u user, req *mcp.CallToolRequest, results []watched) (ask *mcp.CallToolResult, skipped []Machine, approveURL string, err error) { + answered := slices.ContainsFunc(results, func(r watched) bool { return r.skipped == nil }) + waiting := slices.ContainsFunc(results, func(r watched) bool { return r.skipped != nil && r.skipped.Access == AccessNeedsApproval }) + if !answered && waiting { if ask, err := s.approval(u, req); ask != nil || err != nil { - return ask, Sessions{}, err + return ask, nil, "", err } } for _, r := range results { - out.Sessions = append(out.Sessions, r.sessions...) if r.skipped != nil { - out.Skipped = append(out.Skipped, *r.skipped) - if r.skipped.Access == AccessNeedsApproval && out.ApproveURL == "" { - key, _ := s.key(u) - out.ApproveURL = s.approveURL(u, key) + skipped = append(skipped, *r.skipped) + } + } + if waiting { + key, err := s.key(u) + if err != nil { + return nil, nil, "", err + } + approveURL = s.approveURL(u, key) + } + return nil, skipped, approveURL, nil +} + +func (s *Server) sessionsList(ctx context.Context, req *mcp.CallToolRequest, in SessionsInput) (*mcp.CallToolResult, Sessions, error) { + u, err := userOf(req) + if err != nil { + return nil, Sessions{}, err + } + results, err := s.watchAll(ctx, u, in.Machine) + if err != nil { + return nil, Sessions{}, err + } + ask, skipped, link, err := s.unanswered(u, req, results) + if ask != nil || err != nil { + return ask, Sessions{}, err + } + out := Sessions{Sessions: []Session{}, Skipped: skipped, ApproveURL: link} + for _, r := range results { + for _, hs := range r.sessions { + if hs.ArchivedAt == nil || in.Archived { + out.Sessions = append(out.Sessions, sessionRow(r.h, hs)) } } } @@ -800,24 +824,25 @@ func sessionRow(h relayHost, hs hostSession) Session { // reach opens a channel to the machine a session is on. When the machine does not answer, the // channel is nil and what to tell the client comes back instead: a question that sends the // person to approve, or an answer saying why. -func (s *Server) reach(ctx context.Context, req *mcp.CallToolRequest, u user, machine, scope string) (*client.Conn, relayHost, *mcp.CallToolResult, *SessionRead, error) { +func (s *Server) reach(ctx context.Context, req *mcp.CallToolRequest, u user, machine, scope string) (*client.Conn, relayHost, *mcp.CallToolResult, SessionRead, error) { hosts, err := s.hosts(ctx, u) if err != nil { - return nil, relayHost{}, nil, nil, err + return nil, relayHost{}, nil, SessionRead{}, err } h, err := pick(hosts, machine) if err != nil { - return nil, relayHost{}, nil, nil, err + return nil, relayHost{}, nil, SessionRead{}, err } c, access, err := s.dial(ctx, u, h, scope) if c != nil { - return c, h, nil, nil, nil + return c, h, nil, SessionRead{}, nil } - out := &SessionRead{Entries: []SessionEntry{}, Access: access} if access == AccessNeedsApproval { ask, result, err := s.machineApproval(u, req, h, scope) - return nil, h, ask, &result, err - } else if err != nil { + return nil, h, ask, result, err + } + out := SessionRead{Entries: []SessionEntry{}, Access: access} + if err != nil { out.Error = err.Error() } return nil, h, nil, out, nil @@ -865,10 +890,7 @@ func (s *Server) sessionRead(ctx context.Context, req *mcp.CallToolRequest, in S defer cancel() c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeView) if c == nil { - if early == nil { - early = &SessionRead{} - } - return ask, *early, err + return ask, early, err } defer c.Close() out, err := s.read(ctx, c, h, in.Session, in.Messages) @@ -891,17 +913,13 @@ func (s *Server) steer(ctx context.Context, req *mcp.CallToolRequest, machine, s defer cancel() c, h, ask, early, err := s.reach(ctx, req, u, machine, peer.ScopeSteer) if c == nil { - if early == nil { - early = &SessionRead{} - } - return ask, *early, err + return ask, early, err } defer c.Close() cmd := map[string]any{"id": "mcp-" + hex.EncodeToString(randomBytes(12)), "sessionId": session, "op": op, "args": args} if err := c.Call(ctx, "command", cmd, nil); err != nil { if needsSteer(err) { - recordGrantRequest(ctx, c, u, peer.ScopeSteer) - return s.machineApproval(u, req, h, peer.ScopeSteer) + return s.askSteer(ctx, c, u, req, h) } return nil, SessionRead{}, err } @@ -1000,50 +1018,25 @@ func (s *Server) foldersList(ctx context.Context, req *mcp.CallToolRequest, in F if err != nil { return nil, Folders{}, err } - hosts, err := s.hosts(ctx, u) + results, err := s.watchAll(ctx, u, in.Machine) if err != nil { return nil, Folders{}, err } - if in.Machine != "" { - h, err := pick(hosts, in.Machine) - if err != nil { - return nil, Folders{}, err - } - hosts = []relayHost{h} - } - type result struct { - folders []Folder - skipped *Machine + ask, skipped, link, err := s.unanswered(u, req, results) + if ask != nil || err != nil { + return ask, Folders{}, err } - results := each(hosts, func(h relayHost) result { - ctx, cancel := context.WithTimeout(ctx, perHost) - defer cancel() - c, access, err := s.dial(ctx, u, h, peer.ScopeView) - if c == nil { - m := &Machine{ID: h.ID, Name: h.Name, Online: h.Online, Access: access} - if err != nil { - m.Error = err.Error() - } - return result{skipped: m} - } - defer c.Close() - var res struct { - Sub string `json:"sub"` - Sessions []hostSession `json:"sessions"` - } - if err := c.Call(ctx, "sessions.watch", nil, &res); err != nil { - return result{skipped: &Machine{ID: h.ID, Name: h.Name, Online: true, Access: AccessError, Error: err.Error()}} - } - _ = c.Call(ctx, "subscription.cancel", map[string]string{"sub": res.Sub}, nil) + out := Folders{Folders: []Folder{}, Skipped: skipped, ApproveURL: link} + for _, r := range results { byPath := map[string]*Folder{} - for _, hs := range res.Sessions { + for _, hs := range r.sessions { path, git := hs.Cwd, false if hs.Git != nil && hs.Git.Repo != "" { path, git = hs.Git.Repo, true } f := byPath[path] if f == nil { - f = &Folder{Machine: h.Name, MachineID: h.ID, Folder: path, Agents: []string{}} + f = &Folder{Machine: r.h.Name, MachineID: r.h.ID, Folder: path, Agents: []string{}} byPath[path] = f } f.Git = f.Git || git @@ -1055,28 +1048,9 @@ func (s *Server) foldersList(ctx context.Context, req *mcp.CallToolRequest, in F f.LastUsed = hs.UpdatedAt } } - out := make([]Folder, 0, len(byPath)) for _, f := range byPath { slices.Sort(f.Agents) - out = append(out, *f) - } - return result{folders: out} - }) - out := Folders{Folders: []Folder{}} - answered := slices.ContainsFunc(results, func(r result) bool { return r.skipped == nil }) - if !answered && slices.ContainsFunc(results, func(r result) bool { return r.skipped != nil && r.skipped.Access == AccessNeedsApproval }) { - if ask, err := s.approval(u, req); ask != nil || err != nil { - return ask, Folders{}, err - } - } - for _, r := range results { - out.Folders = append(out.Folders, r.folders...) - if r.skipped != nil { - out.Skipped = append(out.Skipped, *r.skipped) - if r.skipped.Access == AccessNeedsApproval && out.ApproveURL == "" { - key, _ := s.key(u) - out.ApproveURL = s.approveURL(u, key) - } + out.Folders = append(out.Folders, *f) } } slices.SortFunc(out.Folders, func(a, b Folder) int { return b.LastUsed.Compare(a.LastUsed) }) @@ -1127,10 +1101,7 @@ func (s *Server) sessionStart(ctx context.Context, req *mcp.CallToolRequest, in defer cancel() c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { - if early == nil { - early = &SessionRead{} - } - return ask, *early, err + return ask, early, err } defer c.Close() id := "ses_mcp-" + hex.EncodeToString(randomBytes(12)) @@ -1151,8 +1122,7 @@ func (s *Server) sessionStart(ctx context.Context, req *mcp.CallToolRequest, in cmd := map[string]any{"id": "mcp-" + hex.EncodeToString(randomBytes(12)), "op": "session.start", "args": args} if err := c.Call(ctx, "command", cmd, nil); err != nil { if needsSteer(err) { - recordGrantRequest(ctx, c, u, peer.ScopeSteer) - return s.machineApproval(u, req, h, peer.ScopeSteer) + return s.askSteer(ctx, c, u, req, h) } return nil, SessionRead{}, err } diff --git a/internal/mcpserver/wake.go b/internal/mcpserver/wake.go index f61fcfe..cc6373a 100644 --- a/internal/mcpserver/wake.go +++ b/internal/mcpserver/wake.go @@ -49,9 +49,7 @@ func (s *Server) agentWake(ctx context.Context, req *mcp.CallToolRequest, in Age defer cancel() c, h, ask, early, err := s.reach(ctx, req, u, in.Machine, peer.ScopeSteer) if c == nil { - if early != nil { - result.Access, result.ApproveURL, result.Error = early.Access, early.ApproveURL, early.Error - } + result.Access, result.ApproveURL, result.Error = early.Access, early.ApproveURL, early.Error return ask, result, err } defer c.Close() @@ -59,8 +57,7 @@ func (s *Server) agentWake(ctx context.Context, req *mcp.CallToolRequest, in Age if err != nil { var rpcErr *wire.Error if needsSteer(err) { - recordGrantRequest(ctx, c, u, peer.ScopeSteer) - ask, approval, err := s.machineApproval(u, req, h, peer.ScopeSteer) + ask, approval, err := s.askSteer(ctx, c, u, req, h) return ask, AgentWakeResult{Access: approval.Access, ApproveURL: approval.ApproveURL, Error: "Choose View and steer sessions for this machine to schedule a wake."}, err } if errors.As(err, &rpcErr) && (rpcErr.Code == wire.CodeMethodNotFound || (rpcErr.Code == peer.CodeForbidden && (strings.Contains(rpcErr.Message, `"admin" scope`) || strings.Contains(rpcErr.Message, "may only reach sessions")))) { diff --git a/web/src/agents/AgentIcon.tsx b/web/src/agents/AgentIcon.tsx index 8f62ad5..e931470 100644 --- a/web/src/agents/AgentIcon.tsx +++ b/web/src/agents/AgentIcon.tsx @@ -1,12 +1,13 @@ import { useState } from 'react' +import { webUrl } from '../lib' const graphemes = new Intl.Segmenter() export function AgentIcon({ name, iconUrl, px = 18 }: { name: string; iconUrl: string; px?: number }) { const [failedUrl, setFailedUrl] = useState('') const style = { width: px, height: px, fontSize: Math.round(px * 0.68) } - const url = URL.canParse(iconUrl) ? new URL(iconUrl) : null - const allowed = url && (url.protocol === 'https:' || (url.protocol === 'http:' && url.origin === location.origin)) + const url = webUrl(iconUrl) + const allowed = url && (url.protocol === 'https:' || url.origin === location.origin) if (allowed && iconUrl !== failedUrl) { return setFailedUrl(iconUrl)} /> } diff --git a/web/src/auth.ts b/web/src/auth.ts index 3613e4a..7cc086d 100644 --- a/web/src/auth.ts +++ b/web/src/auth.ts @@ -157,7 +157,16 @@ export const refused = (e: unknown) => e instanceof ErrorResponse * look the same as an ended session. Those are tried again, and then reported as an error with * the sign-in kept. */ -async function renew(): Promise { +// One renewal at a time: callers that ask together share it, so a rotated refresh token is not +// spent twice (the second exchange would be refused and sign the browser out). +let renewing: Promise | undefined +function renew(): Promise { + return (renewing ??= renewOnce().finally(() => { + renewing = undefined + })) +} + +async function renewOnce(): Promise { for (let i = 0; ; i++) { try { return await manager!.signinSilent() diff --git a/web/src/components/HarnessIcon.tsx b/web/src/components/HarnessIcon.tsx index f359077..1b28f99 100644 --- a/web/src/components/HarnessIcon.tsx +++ b/web/src/components/HarnessIcon.tsx @@ -19,23 +19,18 @@ const MARK: Record = { const FRAME = { inline: 'h-7 w-5 bg-transparent', sm: 'size-6 rounded-md', xs: 'size-7 rounded-lg', md: 'size-9 rounded-xl', lg: 'size-10 rounded-xl' } const PX = { inline: 18, sm: 12, xs: 14, md: 18, lg: 24 } -function HarnessMark({ harness, px }: { harness: Harness; px: number }) { +/** An agent's own mark: sized in pixels, or by className (for drawing a step that runs that agent). */ +export function HarnessGlyph({ harness, px, className }: { harness: Harness; px?: number; className?: string }) { const mark = MARK[harness] - const img = (name: string, cls?: string) => - return mark.dark === mark.light ? img(mark.dark) : <>{img(mark.light, 'dark:hidden')}{img(mark.dark, 'hidden dark:block')} -} - -/** An agent's own mark, sized by className, for drawing a step that runs that agent. */ -export function HarnessGlyph({ harness, className }: { harness: Harness; className?: string }) { - const mark = MARK[harness] - const img = (name: string, cls = '') => + const size = px === undefined ? undefined : { width: px, height: px } + const img = (name: string, cls = '') => return mark.dark === mark.light ? img(mark.dark) : <>{img(mark.light, 'dark:hidden')}{img(mark.dark, 'hidden dark:block')} } export function HarnessLabel({ harness }: { harness: Harness }) { return ( - + {NAME[harness]} ) @@ -71,7 +66,7 @@ export function SessionIcon({ session, size = 'md', dim = false, working = false const label = agent ? session.title ?? '' : NAME[harness] return ( img]:opacity-60', dim && harness === 'codex' && size === 'inline' && 'dark:[&>img]:opacity-75', className)}> - {agent ? : } + {agent ? : } {count > 0 && ( {count} diff --git a/web/src/lib.ts b/web/src/lib.ts index a093392..878cf14 100644 --- a/web/src/lib.ts +++ b/web/src/lib.ts @@ -57,6 +57,20 @@ export function whileVisible(fn: () => void, ms: number): () => void { } } +/** + * An http(s) address, or null. Not URL.parse/URL.canParse: those are missing from the Safari + * versions still on older iPhones, where calling one throws. + */ +export function webUrl(s: unknown): URL | null { + if (typeof s !== 'string') return null + try { + const u = new URL(s) + return u.protocol === 'https:' || u.protocol === 'http:' ? u : null + } catch { + return null + } +} + /** Whether a media query matches, kept current. */ export function useMedia(query: string): boolean { return useSyncExternalStore( diff --git a/web/src/pages/SessionPage.tsx b/web/src/pages/SessionPage.tsx index d4e553d..b842d38 100644 --- a/web/src/pages/SessionPage.tsx +++ b/web/src/pages/SessionPage.tsx @@ -383,7 +383,10 @@ export function SessionPage() { } } const status = session ? SESSION_STATUS[session.status] : undefined - const usage = lastContext(sessionId, session?.contextUsage) + // Read from storage only when the reading changes, not on every streamed update. + const ctxUsed = session?.contextUsage?.used + const ctxWindow = session?.contextUsage?.window + const usage = useMemo(() => lastContext(sessionId, ctxUsed !== undefined && ctxWindow !== undefined ? { used: ctxUsed, window: ctxWindow } : null), [sessionId, ctxUsed, ctxWindow]) const context = usage ? Math.min(100, Math.round((100 * usage.used) / usage.window)) : null const tasks = session?.backgroundTasks ?? [] diff --git a/web/src/session/SessionSheet.tsx b/web/src/session/SessionSheet.tsx index 2bfe8a8..b053545 100644 --- a/web/src/session/SessionSheet.tsx +++ b/web/src/session/SessionSheet.tsx @@ -48,6 +48,8 @@ export function SessionSheet({ conn, session, onClose, onCompact }: { conn: Host try { await onCompact() onClose() + } catch { + // Already reported by the caller; the sheet stays open to try again. } finally { setCompacting(false) } diff --git a/web/src/session/controls.tsx b/web/src/session/controls.tsx index 2bb5980..2fbfa8e 100644 --- a/web/src/session/controls.tsx +++ b/web/src/session/controls.tsx @@ -36,7 +36,7 @@ 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' -import { cn } from '../lib' +import { cn, webUrl } from '../lib' import { PulseDots } from '../components/HarnessIcon' import type { Answer, Failure, Item, ItemStatus, Question, Request, Turn } from '../outpost/sessions' @@ -856,8 +856,7 @@ export function RequestControl({ }, [keys]) const known = (REQUEST_KINDS as readonly string[]).includes(r.kind) const isQuestion = r.kind === 'question' - const link = isURLRequest ? URL.parse(d.url) : null - const webLink = link && (link.protocol === 'https:' || link.protocol === 'http:') ? link : null + const webLink = isURLRequest ? webUrl(d.url) : null const Icon = requestIcon(r) if (r.status !== 'pending') {