diff --git a/backend/internal/adapters/chatdriver/acp/conversation.go b/backend/internal/adapters/chatdriver/acp/conversation.go index 4030f98ed3d..d702afab9f2 100644 --- a/backend/internal/adapters/chatdriver/acp/conversation.go +++ b/backend/internal/adapters/chatdriver/acp/conversation.go @@ -124,6 +124,9 @@ type conversation struct { configOptions []ports.ChatConfigOption skills []ports.ChatSkill skillsKnown bool + // compactAdvertised is whether the agent's own list, before HideCommand, + // named compact; start derives compaction from it, not from the shown skills. + compactAdvertised bool closed bool // sessionLost records that the agent stopped holding this conversation's // session and the provider was stopped for it. See providerSessionLost. @@ -211,6 +214,7 @@ type conversation struct { sessionPromptResponseFailure func(string, acpsdk.PromptResponse, bool) error hibernationCheck func(context.Context, *acpsdk.ClientSideConnection, acpsdk.SessionId) (bool, error) historyNotice func(string) bool + hideCommand func(acpsdk.AvailableCommand) bool // promptErrorFailure: see Config.PromptErrorFailure. promptErrorFailure func(error, bool) error // historyUserChunkIsMessage: see Config.HistoryUserChunkIsMessage. @@ -417,7 +421,7 @@ func (c *conversation) start( } if c.skillsKnown { c.capabilities[ports.ChatCapabilitySkills] = true - c.capabilities[ports.ChatCapabilityCompaction] = hasCompactSkill(c.skills) + c.capabilities[ports.ChatCapabilityCompaction] = c.compactAdvertised } c.modeFor = modeFor c.optionsFor = optionsFor diff --git a/backend/internal/adapters/chatdriver/acp/driver.go b/backend/internal/adapters/chatdriver/acp/driver.go index 2952b93c69a..766810c9782 100644 --- a/backend/internal/adapters/chatdriver/acp/driver.go +++ b/backend/internal/adapters/chatdriver/acp/driver.go @@ -209,6 +209,15 @@ type Config struct { // session (claude-agent-acp's task list), re-sent into later turns, rather // than a plan for the turn it arrives in. PlansSpanTurns bool + // HideCommand reports an advertised command that AO keeps out of the `/` + // menu. AO sends a picked command as ordinary prompt text, so a built-in + // that drives the agent's own terminal UI, or changes a setting AO has its + // own control for (Claude's `/model` switches the model behind AO's + // picker), misleads there. Agents report no command kind over ACP, so each + // binding names its own built-ins; see HideCommands. A hidden command still + // counts for capability checks such as compaction, and typing it by hand + // still sends it. Nil keeps every command. + HideCommand func(acpsdk.AvailableCommand) bool // QuickStop marks a provider whose stop gains nothing from waiting (it never // reacts to stdin closing): a short session/close wait, then a quick signal. QuickStop bool @@ -936,6 +945,7 @@ func (d *Driver) initialize( conv.hibernationCheck = d.cfg.CanHibernate conv.decodeConversationID = d.cfg.DecodeProviderConversationID conv.historyNotice = d.cfg.HistoryNotice + conv.hideCommand = d.cfg.HideCommand conv.historyUserChunkIsMessage = d.cfg.HistoryUserChunkIsMessage conv.historyReconciler = d.cfg.HistoryReconciler conv.plansSpanTurns = d.cfg.PlansSpanTurns diff --git a/backend/internal/adapters/chatdriver/acp/driver_test.go b/backend/internal/adapters/chatdriver/acp/driver_test.go index bea90655faa..c338d66ffd5 100644 --- a/backend/internal/adapters/chatdriver/acp/driver_test.go +++ b/backend/internal/adapters/chatdriver/acp/driver_test.go @@ -6310,3 +6310,80 @@ func TestModelAliasAdmissionUsesTheBindingHarness(t *testing.T) { }) } } + +func TestACPDriverHidesCommandsTheBindingNames(t *testing.T) { + agent := &fakeAgent{} + driver := New(Config{ + Harness: domain.HarnessClaudeCode, + Capabilities: ports.ChatCapabilities{ports.ChatCapabilityStreaming: true}, + Probe: func(context.Context) error { return nil }, + Launch: func(context.Context, LaunchConfig) (Launch, error) { return Launch{Command: "fake"}, nil }, + HideCommand: HideCommands("model", "compact"), + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + driver.useTestProcess(fakeSpawn(agent)) + + conv, err := driver.Start(context.Background(), ports.ChatStartConfig{WorkspacePath: t.TempDir()}) + if err != nil { + t.Fatalf("Start: %v", err) + } + defer conv.Close() + + if err := agent.conn.SessionUpdate(context.Background(), acpsdk.SessionNotification{ + SessionId: acpsdk.SessionId(conv.ProviderConversationID()), + Update: acpsdk.SessionUpdate{AvailableCommandsUpdate: &acpsdk.SessionAvailableCommandsUpdate{ + AvailableCommands: []acpsdk.AvailableCommand{ + {Name: "goal", Description: "Keep working until a condition is met"}, + {Name: "model", Description: "Set the AI model"}, + {Name: "compact", Description: "Summarize the conversation"}, + }, + }}, + }); err != nil { + t.Fatalf("SessionUpdate: %v", err) + } + + skills := awaitSkillCount(t, conv.(ports.ChatSkillLister), 1) + if skills[0].Name != "goal" { + t.Fatalf("skills = %#v, want only goal", skills) + } + // Hiding is presentation only: the agent's compaction stays usable. + if !conv.Capabilities().Has(ports.ChatCapabilityCompaction) { + t.Fatal("hiding compact from the menu also disabled compaction") + } +} + +// Commands can arrive during session/new, before start() derives compaction. +// Hiding compact from the menu must not turn compaction off on that path either. +func TestACPEarlyHiddenCompactKeepsCompactionInStart(t *testing.T) { + agent := &fakeAgent{ + newSessionUpdates: []acpsdk.SessionUpdate{{ + AvailableCommandsUpdate: &acpsdk.SessionAvailableCommandsUpdate{ + AvailableCommands: []acpsdk.AvailableCommand{ + {Name: "compact", Description: "Compact history"}, + {Name: "goal", Description: "Keep working until a condition is met"}, + }, + }, + }}, + } + driver := New(Config{ + Harness: domain.HarnessClaudeCode, + Capabilities: ports.ChatCapabilities{ports.ChatCapabilityStreaming: true}, + Probe: func(context.Context) error { return nil }, + Launch: func(context.Context, LaunchConfig) (Launch, error) { return Launch{Command: "fake"}, nil }, + HideCommand: HideCommands("compact"), + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + driver.useTestProcess(fakeSpawn(agent)) + + opened, err := driver.Start(context.Background(), ports.ChatStartConfig{WorkspacePath: t.TempDir()}) + if err != nil { + t.Fatalf("Start: %v", err) + } + defer opened.Close() + + if !opened.Capabilities().Has(ports.ChatCapabilityCompaction) { + t.Fatal("a compact hidden from the menu before start() disabled compaction") + } + skills := awaitSkillCount(t, opened.(ports.ChatSkillLister), 1) + if skills[0].Name != "goal" { + t.Fatalf("skills = %#v, want only goal", skills) + } +} diff --git a/backend/internal/adapters/chatdriver/acp/skills.go b/backend/internal/adapters/chatdriver/acp/skills.go index dc31bf8ebb7..fdfcb09533d 100644 --- a/backend/internal/adapters/chatdriver/acp/skills.go +++ b/backend/internal/adapters/chatdriver/acp/skills.go @@ -31,6 +31,11 @@ func (c *conversation) replaceAvailableCommands(commands []acpsdk.AvailableComma if command.Name == "compact" { hasCompact = true } + // Hiding is presentation only, so it runs after the capability checks: + // an agent's compaction still works when its command stays off the menu. + if c.hideCommand != nil && c.hideCommand(command) { + continue + } inputHint := "" if command.Input != nil && command.Input.Unstructured != nil { inputHint = command.Input.Unstructured.Hint @@ -49,6 +54,7 @@ func (c *conversation) replaceAvailableCommands(commands []acpsdk.AvailableComma c.mu.Lock() c.skills = skills c.skillsKnown = true + c.compactAdvertised = hasCompact if c.capabilities != nil { c.capabilities[ports.ChatCapabilitySkills] = true c.capabilities[ports.ChatCapabilityCompaction] = hasCompact @@ -56,15 +62,23 @@ func (c *conversation) replaceAvailableCommands(commands []acpsdk.AvailableComma c.mu.Unlock() } -func cloneSkills(skills []ports.ChatSkill) []ports.ChatSkill { - return append([]ports.ChatSkill(nil), skills...) +// HideCommands returns a Config.HideCommand that hides the named built-ins. +// +// Matching is by name because ACP carries no command kind. That is safe only for +// an agent whose built-ins win over a same-named user command (the user's copy +// is unreachable anyway). An agent that lets a user command replace a built-in +// needs a HideCommand that also checks the agent's own provenance metadata. +func HideCommands(names ...string) func(acpsdk.AvailableCommand) bool { + hidden := make(map[string]struct{}, len(names)) + for _, name := range names { + hidden[name] = struct{}{} + } + return func(command acpsdk.AvailableCommand) bool { + _, ok := hidden[command.Name] + return ok + } } -func hasCompactSkill(skills []ports.ChatSkill) bool { - for _, skill := range skills { - if skill.Name == "compact" { - return true - } - } - return false +func cloneSkills(skills []ports.ChatSkill) []ports.ChatSkill { + return append([]ports.ChatSkill(nil), skills...) } diff --git a/backend/internal/adapters/chatdriver/agyacp/commands.go b/backend/internal/adapters/chatdriver/agyacp/commands.go new file mode 100644 index 00000000000..23696c3dc2e --- /dev/null +++ b/backend/internal/adapters/chatdriver/agyacp/commands.go @@ -0,0 +1,14 @@ +package agyacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Antigravity built-ins kept out of the `/` menu. +// +// agy_acp_server (agy before 1.5.4) advertises plan, logout and usage. `agy acp` +// in later CLIs lists its system commands and skills; its terminal-only commands +// are not known to reach ACP, but they are named here so they cannot appear. +// automation and generative_ui are documented as app-only. +var hiddenCommands = acpdriver.HideCommands( + "logout", "model", "effort", "rename", "resume", "config", "permissions", + "rewind", "automation", "generative_ui", +) diff --git a/backend/internal/adapters/chatdriver/agyacp/driver.go b/backend/internal/adapters/chatdriver/agyacp/driver.go index 962b0970f8b..550532b7085 100644 --- a/backend/internal/adapters/chatdriver/agyacp/driver.go +++ b/backend/internal/adapters/chatdriver/agyacp/driver.go @@ -60,7 +60,8 @@ func New(plugin Plugin, log *slog.Logger) ports.ChatDriver { func buildConfig(plugin Plugin, resolve resolver, log *slog.Logger) acpdriver.Config { return acpdriver.Config{ - Harness: domain.HarnessAgy, + Harness: domain.HarnessAgy, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ ports.ChatCapabilityStreaming: true, ports.ChatCapabilityTools: true, diff --git a/backend/internal/adapters/chatdriver/claudeacp/commands.go b/backend/internal/adapters/chatdriver/claudeacp/commands.go new file mode 100644 index 00000000000..2453ed464e3 --- /dev/null +++ b/backend/internal/adapters/chatdriver/claudeacp/commands.go @@ -0,0 +1,13 @@ +package claudeacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Claude Code built-ins kept out of the `/` menu. +// +// claude-agent-acp forwards the CLI's whole command list and strips only a few +// names, and Claude reports skills and built-ins together, so AO names the +// built-ins. Each of these changes a choice AO's own controls own, and AO's +// controls would not show the change: /model, /effort and /fast belong to the +// model menu (AO's /model opens it), and /auto-mode-setup to the approval mode. +// Sent as chat text, /model also only printed Claude's terminal usage. +var hiddenCommands = acpdriver.HideCommands("model", "effort", "fast", "auto-mode-setup") diff --git a/backend/internal/adapters/chatdriver/claudeacp/commands_test.go b/backend/internal/adapters/chatdriver/claudeacp/commands_test.go new file mode 100644 index 00000000000..144746d0b65 --- /dev/null +++ b/backend/internal/adapters/chatdriver/claudeacp/commands_test.go @@ -0,0 +1,22 @@ +package claudeacp + +import ( + "testing" + + acpsdk "github.com/coder/acp-go-sdk" +) + +func TestHiddenCommandsKeepWhatWorksInChat(t *testing.T) { + // /model printed its terminal usage text and could switch the model behind + // AO's picker; these others do real work when sent as prompt text. + for name, hidden := range map[string]bool{ + "model": true, "effort": true, "fast": true, "auto-mode-setup": true, + "goal": false, "init": false, "security-review": false, "context": false, + "usage": false, "compact": false, "code-review": false, + "autocompact": false, "rename": false, "config": false, "advisor": false, + } { + if got := hiddenCommands(acpsdk.AvailableCommand{Name: name}); got != hidden { + t.Errorf("/%s hidden = %v, want %v", name, got, hidden) + } + } +} diff --git a/backend/internal/adapters/chatdriver/claudeacp/driver.go b/backend/internal/adapters/chatdriver/claudeacp/driver.go index b44772eed8f..0be276d0e39 100644 --- a/backend/internal/adapters/chatdriver/claudeacp/driver.go +++ b/backend/internal/adapters/chatdriver/claudeacp/driver.go @@ -90,7 +90,8 @@ type claudeLaunchAuthenticator interface { // both Chat and TUI modes. func New(plugin claudePlugin, log *slog.Logger, onAuthRejected func()) ports.ChatDriver { return &checkpointDriver{plugin: plugin, ChatDriver: acpdriver.New(acpdriver.Config{ - Harness: domain.HarnessClaudeCode, + Harness: domain.HarnessClaudeCode, + HideCommand: hiddenCommands, // A live rejection is the ground truth that outranks any cached // verdict, so drop the cache the moment one arrives. This is also the // only auth correction that works for credential sources AO cannot diff --git a/backend/internal/adapters/chatdriver/copilotacp/commands.go b/backend/internal/adapters/chatdriver/copilotacp/commands.go new file mode 100644 index 00000000000..cfe0b5ccdf4 --- /dev/null +++ b/backend/internal/adapters/chatdriver/copilotacp/commands.go @@ -0,0 +1,13 @@ +package copilotacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Copilot CLI built-ins kept out of the `/` menu. +// +// Copilot runs a built-in before a same-named skill, so a name is enough. These +// change the model, the session name, the approval policy or the working +// directory, all of which AO controls. Read from @github/copilot 1.0.62, the +// last release that ships readable JavaScript. +var hiddenCommands = acpdriver.HideCommands( + "model", "rename", "allow-all", "reset-allowed-tools", "autopilot", "cwd", +) diff --git a/backend/internal/adapters/chatdriver/copilotacp/driver.go b/backend/internal/adapters/chatdriver/copilotacp/driver.go index 78e90b4474e..5e6247730ae 100644 --- a/backend/internal/adapters/chatdriver/copilotacp/driver.go +++ b/backend/internal/adapters/chatdriver/copilotacp/driver.go @@ -56,7 +56,8 @@ func New(plugin Plugin, log *slog.Logger) ports.ChatDriver { func config(plugin Plugin) nativeacp.Config { return nativeacp.Config{ - Harness: domain.HarnessCopilot, + Harness: domain.HarnessCopilot, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ // Copilot reports token usage on every prompt response. ports.ChatCapabilityUsage: true, diff --git a/backend/internal/adapters/chatdriver/cursoracp/commands.go b/backend/internal/adapters/chatdriver/cursoracp/commands.go new file mode 100644 index 00000000000..b296772e485 --- /dev/null +++ b/backend/internal/adapters/chatdriver/cursoracp/commands.go @@ -0,0 +1,10 @@ +package cursoracp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Cursor CLI built-ins kept out of the `/` menu. +// +// Cursor's only advertised built-in copies a request id to the clipboard of the +// machine the agent runs on. Everything else in its list is a user, team or +// project command, or a skill. +var hiddenCommands = acpdriver.HideCommands("copy-request-id") diff --git a/backend/internal/adapters/chatdriver/cursoracp/driver.go b/backend/internal/adapters/chatdriver/cursoracp/driver.go index a6708c87a5f..4f75e6bf5aa 100644 --- a/backend/internal/adapters/chatdriver/cursoracp/driver.go +++ b/backend/internal/adapters/chatdriver/cursoracp/driver.go @@ -27,6 +27,7 @@ import ( func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ Harness: domain.HarnessCursor, + HideCommand: hiddenCommands, Configure: configure, SessionOptions: sessionOptions, SessionPreamble: sessionPreamble, diff --git a/backend/internal/adapters/chatdriver/grokacp/commands.go b/backend/internal/adapters/chatdriver/grokacp/commands.go new file mode 100644 index 00000000000..7bef188ca93 --- /dev/null +++ b/backend/internal/adapters/chatdriver/grokacp/commands.go @@ -0,0 +1,9 @@ +package grokacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Grok CLI built-ins kept out of the `/` menu. +// +// always-approve changes the approval policy that AO's permission picker owns. +// Grok qualifies a skill whose name a built-in takes, so a name is enough. +var hiddenCommands = acpdriver.HideCommands("always-approve") diff --git a/backend/internal/adapters/chatdriver/grokacp/driver.go b/backend/internal/adapters/chatdriver/grokacp/driver.go index 80a54c39a73..736dbd2c02d 100644 --- a/backend/internal/adapters/chatdriver/grokacp/driver.go +++ b/backend/internal/adapters/chatdriver/grokacp/driver.go @@ -17,7 +17,8 @@ import ( // ownership of its cached login, model catalog, and native session history. func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ - Harness: domain.HarnessGrok, + Harness: domain.HarnessGrok, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ ports.ChatCapabilityHistory: true, }, diff --git a/backend/internal/adapters/chatdriver/hermesacp/commands.go b/backend/internal/adapters/chatdriver/hermesacp/commands.go new file mode 100644 index 00000000000..6652dbe1d0e --- /dev/null +++ b/backend/internal/adapters/chatdriver/hermesacp/commands.go @@ -0,0 +1,12 @@ +package hermesacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Hermes built-ins kept out of the `/` menu. +// +// /model and /title change what AO's model picker and thread name show. AO +// sends /steer itself, and /queue reorders the same mid-turn delivery. /undo +// and /retry rewind Hermes' history without AO's transcript following. /reset +// stays: AO handles it (see resetsConversation). /compress stays because it is +// Hermes' only compaction. +var hiddenCommands = acpdriver.HideCommands("model", "title", "steer", "queue", "undo", "retry") diff --git a/backend/internal/adapters/chatdriver/hermesacp/driver.go b/backend/internal/adapters/chatdriver/hermesacp/driver.go index dc9a24dbd9c..1ed4e4756a2 100644 --- a/backend/internal/adapters/chatdriver/hermesacp/driver.go +++ b/backend/internal/adapters/chatdriver/hermesacp/driver.go @@ -33,7 +33,8 @@ func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { func newDriver(plugin nativeacp.Plugin, probe nativeacp.VersionProbe, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ - Harness: domain.HarnessHermes, + Harness: domain.HarnessHermes, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ ports.ChatCapabilityDiffs: true, }, diff --git a/backend/internal/adapters/chatdriver/kimchiacp/commands.go b/backend/internal/adapters/chatdriver/kimchiacp/commands.go new file mode 100644 index 00000000000..ffb66e144ca --- /dev/null +++ b/backend/internal/adapters/chatdriver/kimchiacp/commands.go @@ -0,0 +1,10 @@ +package kimchiacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are Kimchi built-ins kept out of the `/` menu. +// +// /bug opens a browser on the agent's machine. /language writes a global +// setting and replies through a notification AO does not render, so it looks +// like nothing happened. Skills carry a `skill:` prefix and cannot collide. +var hiddenCommands = acpdriver.HideCommands("bug", "language") diff --git a/backend/internal/adapters/chatdriver/kimchiacp/driver.go b/backend/internal/adapters/chatdriver/kimchiacp/driver.go index efd88ef27f8..70588b88b3d 100644 --- a/backend/internal/adapters/chatdriver/kimchiacp/driver.go +++ b/backend/internal/adapters/chatdriver/kimchiacp/driver.go @@ -20,6 +20,7 @@ import ( func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ Harness: domain.HarnessKimchi, + HideCommand: hiddenCommands, Configure: configure, SessionOptions: sessionOptions, SteerRequest: steerRequest, diff --git a/backend/internal/adapters/chatdriver/nativeacp/driver.go b/backend/internal/adapters/chatdriver/nativeacp/driver.go index 9064e388a3f..9bbadd102ec 100644 --- a/backend/internal/adapters/chatdriver/nativeacp/driver.go +++ b/backend/internal/adapters/chatdriver/nativeacp/driver.go @@ -93,6 +93,8 @@ type Config struct { ValidateEnvironment func(context.Context, map[string]string) error // QuickStop: see acpdriver.Config.QuickStop. QuickStop bool + // HideCommand: see acpdriver.Config.HideCommand. + HideCommand func(acpsdk.AvailableCommand) bool } // New creates a Chat driver that launches the exact executable resolved by the @@ -205,5 +207,6 @@ func buildConfig(plugin Plugin, cfg Config, log *slog.Logger) acpdriver.Config { EncodeProviderConversationID: cfg.EncodeProviderConversationID, DecodeProviderConversationID: cfg.DecodeProviderConversationID, QuickStop: cfg.QuickStop, + HideCommand: cfg.HideCommand, } } diff --git a/backend/internal/adapters/chatdriver/ompacp/commands.go b/backend/internal/adapters/chatdriver/ompacp/commands.go new file mode 100644 index 00000000000..10d1c959717 --- /dev/null +++ b/backend/internal/adapters/chatdriver/ompacp/commands.go @@ -0,0 +1,16 @@ +package ompacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are oh-my-pi built-ins kept out of the `/` menu. +// +// OMP advertises only built-ins with a text handler and reserves their names +// before user commands, so a name is enough. These switch the model or effort +// AO's pickers show, rename the session, forget approvals, move the session's +// directory or worktree, open a dashboard on the agent's machine, or pin +// sessions in OMP's own resume list. +var hiddenCommands = acpdriver.HideCommands( + "model", "models", "switch", "effort", "modelpreset", "fast", "slow", + "extended-context", "rename", "forget-approvals", "move", "wt", "worktree", + "trace", "stats", "pin", "unpin", +) diff --git a/backend/internal/adapters/chatdriver/ompacp/driver.go b/backend/internal/adapters/chatdriver/ompacp/driver.go index 9ccaca02e20..53c47e28900 100644 --- a/backend/internal/adapters/chatdriver/ompacp/driver.go +++ b/backend/internal/adapters/chatdriver/ompacp/driver.go @@ -24,7 +24,8 @@ func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { func newDriver(plugin nativeacp.Plugin, probe nativeacp.VersionProbe, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ - Harness: domain.HarnessOMP, + Harness: domain.HarnessOMP, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ ports.ChatCapabilityUsage: true, ports.ChatCapabilityDiffs: true, diff --git a/backend/internal/adapters/chatdriver/piacp/commands.go b/backend/internal/adapters/chatdriver/piacp/commands.go new file mode 100644 index 00000000000..f8cae6db3a7 --- /dev/null +++ b/backend/internal/adapters/chatdriver/piacp/commands.go @@ -0,0 +1,11 @@ +package piacp + +import acpdriver "github.com/aoagents/agent-orchestrator/backend/internal/adapters/chatdriver/acp" + +// hiddenCommands are pi-acp built-ins kept out of the `/` menu. +// +// pi-acp runs its built-ins before a same-named prompt template, so a template +// with one of these names was never reachable. /name renames the session, and +// /steering and /follow-up change how mid-turn messages are delivered, both of +// which AO owns. /autocompact flips a pi setting AO does not show. +var hiddenCommands = acpdriver.HideCommands("name", "steering", "follow-up", "autocompact") diff --git a/backend/internal/adapters/chatdriver/piacp/driver.go b/backend/internal/adapters/chatdriver/piacp/driver.go index 6136b8eeb89..11e51ad0033 100644 --- a/backend/internal/adapters/chatdriver/piacp/driver.go +++ b/backend/internal/adapters/chatdriver/piacp/driver.go @@ -51,7 +51,8 @@ func buildConfig(plugin piPlugin, resolve binaryResolver, log *slog.Logger) acpd totals := &sessionTotals{totals: map[string]int{}} agentDirs := &piAgentDirs{} return acpdriver.Config{ - Harness: domain.HarnessPi, + Harness: domain.HarnessPi, + HideCommand: hiddenCommands, Capabilities: ports.ChatCapabilities{ ports.ChatCapabilityStreaming: true, ports.ChatCapabilityTools: true, diff --git a/backend/internal/adapters/chatdriver/qwenacp/commands.go b/backend/internal/adapters/chatdriver/qwenacp/commands.go new file mode 100644 index 00000000000..72ac013277e --- /dev/null +++ b/backend/internal/adapters/chatdriver/qwenacp/commands.go @@ -0,0 +1,25 @@ +package qwenacp + +import acpsdk "github.com/coder/acp-go-sdk" + +// qwenHiddenBuiltins are Qwen Code built-ins kept out of the `/` menu. They +// change the model, effort, language, output style, advisor or settings behind +// AO's back; start or delete sessions; handle auth or self-update; or open a +// browser or a terminal panel. /compress stays because it is Qwen's only +// compaction. +var qwenHiddenBuiltins = map[string]struct{}{ + "model": {}, "effort": {}, "language": {}, "output-style": {}, "advisor": {}, + "config": {}, "clear": {}, "delete": {}, "auth": {}, "update": {}, "docs": {}, + "bug": {}, "skills": {}, +} + +// hiddenCommand hides a Qwen built-in by name only when Qwen marks the entry as +// one. A user's file command may replace a built-in of the same name, and that +// command is the user's own, so it stays. +func hiddenCommand(command acpsdk.AvailableCommand) bool { + if source, _ := command.Meta["source"].(string); source != "builtin-command" { + return false + } + _, hidden := qwenHiddenBuiltins[command.Name] + return hidden +} diff --git a/backend/internal/adapters/chatdriver/qwenacp/commands_test.go b/backend/internal/adapters/chatdriver/qwenacp/commands_test.go new file mode 100644 index 00000000000..795f3f39842 --- /dev/null +++ b/backend/internal/adapters/chatdriver/qwenacp/commands_test.go @@ -0,0 +1,27 @@ +package qwenacp + +import ( + "testing" + + acpsdk "github.com/coder/acp-go-sdk" +) + +func TestHiddenCommandHidesOnlyQwenBuiltins(t *testing.T) { + builtin := map[string]any{"source": "builtin-command"} + for _, tc := range []struct { + name string + command acpsdk.AvailableCommand + hidden bool + }{ + {"built-in model", acpsdk.AvailableCommand{Name: "model", Meta: builtin}, true}, + {"built-in that works in chat", acpsdk.AvailableCommand{Name: "goal", Meta: builtin}, false}, + {"compaction stays", acpsdk.AvailableCommand{Name: "compress", Meta: builtin}, false}, + // A user's file command may take a built-in's name; it is theirs to run. + {"user command named model", acpsdk.AvailableCommand{Name: "model", Meta: map[string]any{"source": "file-command"}}, false}, + {"no provenance", acpsdk.AvailableCommand{Name: "model"}, false}, + } { + if got := hiddenCommand(tc.command); got != tc.hidden { + t.Errorf("%s: hidden = %v, want %v", tc.name, got, tc.hidden) + } + } +} diff --git a/backend/internal/adapters/chatdriver/qwenacp/driver.go b/backend/internal/adapters/chatdriver/qwenacp/driver.go index 05bb4e20ea5..0a8e3e87ab0 100644 --- a/backend/internal/adapters/chatdriver/qwenacp/driver.go +++ b/backend/internal/adapters/chatdriver/qwenacp/driver.go @@ -23,6 +23,7 @@ func New(plugin nativeacp.Plugin, log *slog.Logger) ports.ChatDriver { func newDriver(plugin nativeacp.Plugin, probe nativeacp.VersionProbe, log *slog.Logger) ports.ChatDriver { return nativeacp.New(plugin, nativeacp.Config{ Harness: domain.HarnessQwen, + HideCommand: hiddenCommand, Configure: configure, SessionMode: sessionMode, SessionOptions: sessionOptions, diff --git a/frontend/src/renderer/components/NewChatPage.tsx b/frontend/src/renderer/components/NewChatPage.tsx index 9f6a17395fd..bb322147f8a 100644 --- a/frontend/src/renderer/components/NewChatPage.tsx +++ b/frontend/src/renderer/components/NewChatPage.tsx @@ -71,7 +71,7 @@ export function NewChatPage({ projectId, hostId, report }: { projectId: string; const targetRef = useRef({ projectId, hostId }); targetRef.current = { projectId, hostId }; // The session's own composer shortcuts, before the session exists. - useSessionShortcut("model-picker", openComposerModelPicker); + useSessionShortcut("model-picker", () => { openComposerModelPicker(); }); useSessionShortcut("dictate", toggleComposerDictation); const mounted = useRef(true); useEffect(() => { diff --git a/frontend/src/renderer/components/SessionView.tsx b/frontend/src/renderer/components/SessionView.tsx index 5e831072b5d..44d7529e68c 100644 --- a/frontend/src/renderer/components/SessionView.tsx +++ b/frontend/src/renderer/components/SessionView.tsx @@ -2803,7 +2803,7 @@ export function SessionView({ sessionId, cloudOrgId, projectId, hostId }: Sessio }, hasInspector, ); - useSessionShortcut("model-picker", openComposerModelPicker, hasInspector); + useSessionShortcut("model-picker", () => { openComposerModelPicker(); }, hasInspector); useSessionShortcut("dictate", toggleComposerDictation, hasInspector); const inspectorMotionReadyRef = useRef(null); diff --git a/frontend/src/renderer/components/chat/ChatComposer.test.tsx b/frontend/src/renderer/components/chat/ChatComposer.test.tsx index 8f62d230460..a70d1512e0e 100644 --- a/frontend/src/renderer/components/chat/ChatComposer.test.tsx +++ b/frontend/src/renderer/components/chat/ChatComposer.test.tsx @@ -2332,6 +2332,115 @@ describe("slash commands", () => { await userEvent.click(screen.getByText("Ship")); expect(field.querySelector('[data-composer-token="skill"]')).toHaveTextContent("/ship"); }); + + describe("/model", () => { + // Stands in for the settings row's model menu: openComposerModelPicker + // opens it with an Enter keydown, which a Radix trigger answers. + function renderWithModelMenu(props: Partial[0]> = {}) { + const opened = vi.fn(); + const rendered = renderComposer({ + skills: SKILLS, + settings: ( + + ), + ...props, + }); + return { ...rendered, opened }; + } + + it("opens the model menu on Enter instead of sending", async () => { + const { field, onSend, opened } = renderWithModelMenu(); + await typeInComposer(field, "/model"); + // Typing the name only selects it; the menu waits for Enter. + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(opened).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Enter}"); + await waitFor(() => expect(opened).toHaveBeenCalledOnce()); + expect(onSend).not.toHaveBeenCalled(); + expect(composerWireText(field)).toBe(""); + }); + + it("still opens the menu when /model is sent with the suggestions dismissed", async () => { + const sessionId = "model-command-dismissed"; + const { field, onSend, opened } = renderWithModelMenu({ draftSessionId: sessionId }); + await typeInComposer(field, "/model"); + await waitFor(() => expect(readChatSessionDraft(sessionId).composer.text).toBe("/model")); + await userEvent.keyboard("{Escape}"); + await userEvent.keyboard("{Enter}"); + await waitFor(() => expect(opened).toHaveBeenCalledOnce()); + expect(onSend).not.toHaveBeenCalled(); + expect(composerWireText(field)).toBe(""); + // The saved draft is cleared too, so /model does not return on remount. + await waitFor(() => expect(readChatSessionDraft(sessionId).composer.text).toBe("")); + }); + + it("leaves /model as text in a queued message being edited", async () => { + const onSend = vi.fn(); + const opened = vi.fn(); + render( + { if (event.key === "Enter") opened(); }}>Opus 5.5} + />, + ); + fireEvent.submit(screen.getByLabelText("Message the agent").closest("form")!); + await waitFor(() => expect(onSend).toHaveBeenCalledWith("/model", undefined, undefined, [])); + expect(opened).not.toHaveBeenCalled(); + }); + + it.each(["Enter", "Tab"])("is not AO's while a queued message is edited (%s)", async (key) => { + const { field, onSend, opened } = renderWithModelMenu({ + editingQueuedTurnId: "queued-model-key", + draftSeed: { id: "queued-model-key", text: "" }, + }); + await typeInComposer(field, "/mod"); + expect(screen.queryAllByRole("option").some((option) => /^Model/.test(option.textContent ?? ""))).toBe(false); + await typeInComposer(field, "el"); + await userEvent.keyboard(`{${key}}`); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(opened).not.toHaveBeenCalled(); + if (key === "Enter") await waitFor(() => expect(onSend).toHaveBeenCalledWith("/model", undefined, undefined, [])); + else expect(composerWireText(field)).toBe("/model"); + }); + + const unusableMenus = { + "a settings row with no model menu": Context 12%, + "a disabled model menu": , + }; + it.each(Object.entries(unusableMenus))("keeps /model in the box with %s", async (_, settings) => { + const { field, onSend } = renderComposer({ skills: SKILLS, settings }); + await typeInComposer(field, "/mod"); + expect(screen.queryAllByRole("option").some((option) => /^Model/.test(option.textContent ?? ""))).toBe(false); + await typeInComposer(field, "el"); + await userEvent.keyboard("{Escape}"); + await userEvent.keyboard("{Enter}"); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(onSend).not.toHaveBeenCalled(); + expect(composerWireText(field)).toBe("/model"); + }); + + it("replaces an agent's own /model with AO's", async () => { + const { field } = renderWithModelMenu({ + skills: [...SKILLS, { name: "model", displayName: "model", description: "Set the AI model", source: "agent" }], + }); + await typeInComposer(field, "/mode"); + const options = screen.getAllByRole("option").filter((option) => /^Model/.test(option.textContent ?? "")); + expect(options).toHaveLength(1); + expect(options[0]?.textContent).toContain("Choose the agent, model and effort"); + }); + + it("is not offered where the composer has no model menu", async () => { + const { field } = renderComposer({ skills: SKILLS }); + await typeInComposer(field, "/"); + expect(screen.getAllByRole("option").some((option) => /^Model/.test(option.textContent ?? ""))).toBe(false); + }); + }); }); /* ---- file mentions ------------------------------------------------------- */ diff --git a/frontend/src/renderer/components/chat/ChatComposer.tsx b/frontend/src/renderer/components/chat/ChatComposer.tsx index 2e9b00e249c..c64b86a0561 100644 --- a/frontend/src/renderer/components/chat/ChatComposer.tsx +++ b/frontend/src/renderer/components/chat/ChatComposer.tsx @@ -72,6 +72,7 @@ import { apiErrorCode, apiErrorMessage, getApiBaseUrl } from "../../lib/api-clie import { ComposerSuggestMenu } from "./ComposerSuggestMenu"; import { ComposerEditor, + CONSUME_TRIGGER, type ComposerEditorHandle, type ComposerImage, type ComposerEditorSnapshot, @@ -79,6 +80,7 @@ import { type ComposerTrigger, } from "./ComposerEditor"; import { messageTokenScope, recordSentComposerTokens, sessionTokenScope } from "./sentComposerTokens"; +import { composerModelPicker, openComposerModelPicker } from "../../lib/composer-shortcuts"; import { moveHighlight, rankFiles, rankSkills, type Suggestion } from "./composerSuggest"; import { attachmentPayload, @@ -131,6 +133,13 @@ import { isCloudAttachmentReference } from "../../lib/cloud-attachment-reference import { setChatDraftBoundary } from "../../lib/chat-draft-boundary"; import { subscribeChatComposerReferences, subscribeChatComposerText } from "../../lib/chat-context-bus"; +/** + * AO's own `/model`: it opens the composer's agent and model menu instead of + * sending text. An agent's `/model` only printed usage over chat, or switched + * the model behind the menu, so AO's command takes its place. + */ +const MODEL_COMMAND = "model"; + // These responses precede AppendUserMessage. Provider/transport errors can // follow durable acceptance and must keep the original delivery ID for recovery. /** The agent switch that runs before a send failed, so the message never left. */ @@ -600,6 +609,7 @@ export const ChatComposer = memo(function ChatComposer({ */ const editor = useRef(null); + const formRef = useRef(null); const dictation = useDictation({ onText: (text) => editor.current?.dictate(text), onEnd: (keep) => editor.current?.endDictation(keep), @@ -797,28 +807,55 @@ export const ChatComposer = memo(function ChatComposer({ attachment.stagedPath ? [] : attachmentPayload(attachment)), fileAttachments.preparing); }, [fileAttachments.attachments, fileAttachments.preparing, holdAttachments, onHeldAttachmentsChange]); + // The model menu lives in the settings row, so /model is AO's where one is shown. + // A queued message being edited keeps `/model` as text, as it does /compact. + const offersModelCommand = Boolean(settings) && !editingQueuedTurnId; const slashCommands = useMemo(() => { - if (!onCompact || compactUnavailable === "This agent cannot compact its history") return skills; - return [ - { + const offersCompact = Boolean(onCompact) && compactUnavailable !== "This agent cannot compact its history"; + const own: ChatSkill[] = [ + ...(offersCompact ? [{ name: "compact", displayName: "compact", description: "Summarize earlier history to reclaim context", source: "AO", - }, - ...skills.filter((skill) => skill.name !== "compact"), + }] : []), + ...(offersModelCommand ? [{ + name: MODEL_COMMAND, + displayName: MODEL_COMMAND, + description: "Choose the agent, model and effort", + source: "AO", + }] : []), ]; - }, [compactUnavailable, onCompact, skills]); + if (own.length === 0) return skills; + return [...own, ...skills.filter((skill) => !own.some((command) => command.name === skill.name))]; + }, [compactUnavailable, offersModelCommand, onCompact, skills]); + + // After the key or click that chose /model has finished, so it cannot also + // act on the menu that opens. + const openModelMenu = useCallback(() => { + window.setTimeout(() => { + if (formRef.current) openComposerModelPicker(formRef.current); + }, 0); + }, []); + // Read when /model is listed or used, not at render: the settings row may hold + // no model menu yet, or show it disabled while the agent starts. + const modelMenuUsable = useCallback( + () => offersModelCommand && Boolean(formRef.current && composerModelPicker(formRef.current)), + [offersModelCommand], + ); const suggestionsFor = useCallback((currentTrigger?: ComposerTrigger): Suggestion[] => { if (!currentTrigger || currentTrigger.key === dismissedKeyRef.current) return []; // An empty candidate list is the whole reason the sigil stays ordinary: with // no commands or skills there is nothing to open, so `/` types a slash. if (currentTrigger.kind === "skill") { - return rankSkills(slashCommands, currentTrigger.query); + const commands = offersModelCommand && !modelMenuUsable() + ? slashCommands.filter((skill) => skill.name !== MODEL_COMMAND) + : slashCommands; + return rankSkills(commands, currentTrigger.query); } return rankFiles(filePaths, currentTrigger.query); - }, [slashCommands, filePaths]); + }, [slashCommands, filePaths, offersModelCommand, modelMenuUsable]); const suggestions: Suggestion[] = useMemo( () => suggestionsFor(trigger), @@ -1543,7 +1580,9 @@ export const ChatComposer = memo(function ChatComposer({ const pick = useCallback((value: string) => { const currentTrigger = triggerRef.current; if (!currentTrigger) return; - editor.current?.insertToken(currentTrigger, value); + const opensModelMenu = currentTrigger.kind === "skill" && value === MODEL_COMMAND && modelMenuUsable(); + if (opensModelMenu) editor.current?.removeTrigger(currentTrigger); + else editor.current?.insertToken(currentTrigger, value); triggerRef.current = undefined; previousTrigger.current = undefined; setTrigger(undefined); @@ -1551,7 +1590,8 @@ export const ChatComposer = memo(function ChatComposer({ setHighlighted(0); dismissedKeyRef.current = null; setDismissedKey(null); - }, []); + if (opensModelMenu) openModelMenu(); + }, [modelMenuUsable, openModelMenu]); useEffect(() => { if (isComposing || !trigger || trigger.kind !== "skill" || trigger.key === dismissedKey) return; @@ -1562,6 +1602,8 @@ export const ChatComposer = memo(function ChatComposer({ if (!query) return; const exact = slashCommands.find((skill) => skill.name.toLowerCase() === query); if (!exact) return; + // /model runs on Enter, like a sent command; typing its name only selects it. + if (offersModelCommand && exact.name === MODEL_COMMAND) return; // Do not eagerly accept a skill whose full name is also the start of another // skill. The user must still be able to type `/review-pr` when `/review` @@ -1571,7 +1613,7 @@ export const ChatComposer = memo(function ChatComposer({ return name.length > query.length && name.startsWith(query); }); if (!hasLongerPrefix) pick(exact.name); - }, [dismissedKey, isComposing, pick, slashCommands, trigger]); + }, [dismissedKey, isComposing, offersModelCommand, pick, slashCommands, trigger]); useLayoutEffect(() => { if (submitting || !restoreFocusAfterSubmission.current) return; @@ -1584,7 +1626,7 @@ export const ChatComposer = memo(function ChatComposer({ }, [submitting]); const completeFromEditor = useCallback( - (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab"): string | undefined => { + (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab"): string | typeof CONSUME_TRIGGER | undefined => { const currentTrigger = snapshot.trigger; if (!currentTrigger) return undefined; if (key === "Enter" && snapshot.text.trim() === "/compact" && onCompact) { @@ -1596,9 +1638,17 @@ export const ChatComposer = memo(function ChatComposer({ triggerRef.current = currentTrigger; highlightedRef.current = 0; dismissedKeyRef.current = null; + if (currentTrigger.kind === "skill" && chosen.value === MODEL_COMMAND && modelMenuUsable()) { + // The editor removes the typed `/mod…`; nothing is inserted or sent. + triggerRef.current = undefined; + setTrigger(undefined); + setHighlighted(0); + openModelMenu(); + return CONSUME_TRIGGER; + } return chosen.value; }, - [onCompact, skills, suggestionsFor], + [modelMenuUsable, onCompact, openModelMenu, skills, suggestionsFor], ); function submit(event?: FormEvent, forceSteer?: boolean): Promise { @@ -1620,6 +1670,19 @@ export const ChatComposer = memo(function ChatComposer({ return submitInFlight.current; } if (typingLocked) return Promise.resolve(); + // `/model` typed out with the menu dismissed still opens the model menu. With no + // usable menu it stays in the box: sent, the agent would only print its usage. + if (offersModelCommand && !forceSteer && textRef.current.trim() === `/${MODEL_COMMAND}`) { + if (!modelMenuUsable()) return Promise.resolve(); + // The editor's programmatic clear publishes no change, so the composer + // state and the saved draft are cleared here, or /model would come back. + clearEditorView(); + persistComposerText(""); + draftCaretRef.current = 0; + onDraftInput?.("", 0); + openModelMenu(); + return Promise.resolve(); + } setHeldSubmit(null); heldDuringSubmit.current = null; submitAccepted.current = false; @@ -2384,6 +2447,7 @@ export const ChatComposer = memo(function ChatComposer({ return withQueueStack(
void submit(event, steersDraft)} onDragOver={(event) => { diff --git a/frontend/src/renderer/components/chat/ComposerEditor.tsx b/frontend/src/renderer/components/chat/ComposerEditor.tsx index 2f4691cd86a..07b5176c30c 100644 --- a/frontend/src/renderer/components/chat/ComposerEditor.tsx +++ b/frontend/src/renderer/components/chat/ComposerEditor.tsx @@ -90,6 +90,8 @@ export type ComposerEditorHandle = { /** Where a collapsed caret sits relative to the whole text; undefined for a range. */ caretBoundary(): { atStart: boolean; atEnd: boolean } | undefined; insertToken(trigger: ComposerTrigger, value: string): void; + /** Removes the typed `/query` or `@query`, for a completion that runs instead of inserting. */ + removeTrigger(trigger: ComposerTrigger): void; /** * Shows a dictation transcript at the caret (or the end), replacing the one * shown before it, so the words appear as they are recognized. @@ -361,6 +363,26 @@ function $composerTokens(): ComposerSentToken[] { ); } +/** + * What onComplete returns for a choice that runs at once rather than becoming a + * chip, such as AO's `/model`: the typed trigger is removed and nothing inserted. + */ +export const CONSUME_TRIGGER = Symbol("consume-trigger"); + +function $removeComposerTrigger(trigger: ComposerTrigger): boolean { + const node = $getNodeByKey(trigger.nodeKey); + if (!$isTextNode(node)) return false; + const text = node.getTextContent(); + const expected = `${trigger.kind === "skill" ? "/" : "@"}${trigger.query}`; + if (text.slice(trigger.start, trigger.end) !== expected) return false; + const before = text.slice(0, trigger.start); + // Drop the space after the trigger too, so no gap is left where it was. + const after = text.slice(trigger.end).replace(/^ /, ""); + node.setTextContent(before + after); + node.select(before.length, before.length); + return true; +} + function $insertComposerToken(trigger: ComposerTrigger, value: string): boolean { const node = $getNodeByKey(trigger.nodeKey); if (!$isTextNode(node)) return false; @@ -624,7 +646,7 @@ const EditorBridge = forwardRef< /** Staged paths of the images attached right now. */ attachedImages: () => string[]; onChange: (snapshot: ComposerEditorSnapshot) => void; - onComplete: (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab") => string | undefined; + onComplete: (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab") => string | typeof CONSUME_TRIGGER | undefined; onEnter: (snapshot: ComposerEditorSnapshot, event: globalThis.KeyboardEvent) => boolean; } >(function EditorBridge({ disabled, enterSends, promptSuggestion, onDismissSuggestion, onEmptyChange, attachedImages, onChange, onComplete, onEnter }, ref) { @@ -673,6 +695,11 @@ const EditorBridge = forwardRef< $insertComposerToken(trigger, value); }, { discrete: true }); }, + removeTrigger: (trigger) => { + editor.update(() => { + $removeComposerTrigger(trigger); + }, { discrete: true }); + }, dictate: (text) => { const continuing = dictation.current !== null; editor.update(() => { @@ -803,7 +830,15 @@ const EditorBridge = forwardRef< return true; } const value = onComplete(snapshot, key); - if (snapshot.trigger && value) { + if (snapshot.trigger && value === CONSUME_TRIGGER) { + if (!$removeComposerTrigger(snapshot.trigger)) return false; + if (event) { + completionHandledEvents.add(event); + event.preventDefault(); + } + return true; + } + if (snapshot.trigger && typeof value === "string" && value) { if (!$insertComposerToken(snapshot.trigger, value)) return false; if (event) { completionHandledEvents.add(event); @@ -946,7 +981,7 @@ export const ComposerEditor = forwardRef< activeIndex: number; images?: ComposerImage[]; onChange: (snapshot: ComposerEditorSnapshot) => void; - onComplete: (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab") => string | undefined; + onComplete: (snapshot: ComposerEditorSnapshot, key: "Enter" | "Tab") => string | typeof CONSUME_TRIGGER | undefined; onEnter: (snapshot: ComposerEditorSnapshot, event: globalThis.KeyboardEvent) => boolean; onCompositionChange: (isComposing: boolean) => void; onKeyDown: (event: KeyboardEvent) => void; diff --git a/frontend/src/renderer/lib/composer-shortcuts.ts b/frontend/src/renderer/lib/composer-shortcuts.ts index ba51a14aacd..4fe21cba75c 100644 --- a/frontend/src/renderer/lib/composer-shortcuts.ts +++ b/frontend/src/renderer/lib/composer-shortcuts.ts @@ -1,17 +1,28 @@ import { queryAllShown, queryShown } from "./dom-selectors"; /** - * ⌘⇧M: opens the chat composer's model menu, on a session's chat and on the new - * chat page alike. Closing the menu hands focus back to the composer - * (TurnSettingsBar's restoreComposerFocus reads the mark set here). + * ⌘⇧M and `/model`: opens the chat composer's model menu, on a session's chat and + * on the new chat page alike. `scope` limits the search to one composer, for a + * surface that shows more than one. Reports whether a menu was found. Closing the + * menu hands focus back to the composer (TurnSettingsBar's restoreComposerFocus + * reads the mark set here). */ -export function openComposerModelPicker(): void { - const picker = queryShown("[data-shortcut-target='model-picker']:not([disabled])"); - if (!picker) return; +export function openComposerModelPicker(scope: ParentNode = document): boolean { + const picker = composerModelPicker(scope); + if (!picker) return false; // Radix menu triggers open on pointerdown or Enter, never on a synthetic click. picker.dataset.shortcutOpened = ""; picker.focus(); picker.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })); + return true; +} + +/** + * The enabled model menu in `scope`, if any: a chat still starting shows it + * disabled, and a chat kept mounted out of view is skipped. + */ +export function composerModelPicker(scope: ParentNode = document): HTMLElement | null { + return queryShown("[data-shortcut-target='model-picker']:not([disabled])", scope); } /** Dictate (⌥D on macOS): starts or finishes dictation in the focused chat composer, else the first one on screen. */