Merge branch 'worktree-agent-af57ebcee7c17abd6'
This commit is contained in:
@@ -121,6 +121,9 @@ type Chat struct {
|
||||
// so a listed row names its levels without starting a CLI.
|
||||
catalogMu sync.Mutex
|
||||
catalog []protocol.ChatModel
|
||||
// commandCatalog is the latest slash-command list per directory
|
||||
// (commands.go), guarded by catalogMu.
|
||||
commandCatalog map[string][]protocol.ChatCommand
|
||||
}
|
||||
|
||||
func New(ctx context.Context) *Chat {
|
||||
@@ -369,6 +372,10 @@ type session struct {
|
||||
account accountIdentity
|
||||
prompts []promptRecord
|
||||
models []protocol.ChatModel
|
||||
// commands are the slash commands the live CLI's initialize listed;
|
||||
// terminalCommands are those its init line marks terminal-only (commands.go).
|
||||
commands []protocol.ChatCommand
|
||||
terminalCommands map[string]bool
|
||||
|
||||
// model is the requested selection; modelActual is the model the CLI last
|
||||
// reported for a message. appliedModel is what the live process was told.
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// parseInitializeCommands reads the slash commands Claude Code's initialize
|
||||
// response lists: bundled skills (code-review), ~/.claude and project skills,
|
||||
// plugin and claude.ai-synced skills, and the CLI's own commands, each with its
|
||||
// description and argument hint. The operator sends "/<name> args" as an
|
||||
// ordinary prompt and the CLI expands it. Internal entries ("__…") and
|
||||
// duplicates are dropped; a response without commands yields none.
|
||||
func parseInitializeCommands(raw json.RawMessage) []protocol.ChatCommand {
|
||||
var reply struct {
|
||||
Commands []struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
ArgumentHint string `json:"argumentHint"`
|
||||
} `json:"commands"`
|
||||
}
|
||||
if len(raw) == 0 || json.Unmarshal(raw, &reply) != nil {
|
||||
return nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
commands := make([]protocol.ChatCommand, 0, len(reply.Commands))
|
||||
for _, c := range reply.Commands {
|
||||
name := strings.TrimPrefix(strings.TrimSpace(c.Name), "/")
|
||||
if name == "" || strings.HasPrefix(name, "_") || strings.ContainsAny(name, " \t\r\n") || seen[name] {
|
||||
continue
|
||||
}
|
||||
seen[name] = true
|
||||
commands = append(commands, protocol.ChatCommand{
|
||||
Name: name,
|
||||
Description: strings.TrimSpace(c.Description),
|
||||
ArgumentHint: strings.TrimSpace(c.ArgumentHint),
|
||||
})
|
||||
}
|
||||
return commands
|
||||
}
|
||||
|
||||
// noteTerminalCommands records the commands the CLI's init line reports as
|
||||
// terminal-only (terminal_slash_commands): they do nothing in a stream-json
|
||||
// session, so the chat does not offer them.
|
||||
func (s *session) noteTerminalCommands(names []string) {
|
||||
if len(names) == 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.terminalCommands = map[string]bool{}
|
||||
for _, name := range names {
|
||||
s.terminalCommands[strings.TrimPrefix(name, "/")] = true
|
||||
}
|
||||
directory, commands := s.directory, s.commandsLocked()
|
||||
s.mu.Unlock()
|
||||
s.chat.rememberCommands(directory, commands)
|
||||
}
|
||||
|
||||
// rememberCommands keeps the newest command list a CLI in directory reported,
|
||||
// so a chat there lists commands before its own CLI has started.
|
||||
func (c *Chat) rememberCommands(directory string, commands []protocol.ChatCommand) {
|
||||
if commands == nil {
|
||||
return
|
||||
}
|
||||
c.catalogMu.Lock()
|
||||
defer c.catalogMu.Unlock()
|
||||
if c.commandCatalog == nil {
|
||||
c.commandCatalog = map[string][]protocol.ChatCommand{}
|
||||
}
|
||||
c.commandCatalog[directory] = append([]protocol.ChatCommand(nil), commands...)
|
||||
}
|
||||
|
||||
func (c *Chat) cachedCommands(directory string) []protocol.ChatCommand {
|
||||
c.catalogMu.Lock()
|
||||
defer c.catalogMu.Unlock()
|
||||
return append([]protocol.ChatCommand(nil), c.commandCatalog[directory]...)
|
||||
}
|
||||
|
||||
// commandsLocked is the session's offered commands. Callers hold s.mu.
|
||||
func (s *session) commandsLocked() []protocol.ChatCommand {
|
||||
commands := make([]protocol.ChatCommand, 0, len(s.commands))
|
||||
for _, c := range s.commands {
|
||||
if !s.terminalCommands[c.Name] {
|
||||
commands = append(commands, c)
|
||||
}
|
||||
}
|
||||
return commands
|
||||
}
|
||||
|
||||
// Commands lists the slash commands and skills the session's CLI loaded at the
|
||||
// initialize handshake. It never waits for a CLI to start: requests on a
|
||||
// connection are answered in order, and a cold start would stall them. With no
|
||||
// live CLI it starts one in the background (the next prompt needs it anyway)
|
||||
// and answers from the list a CLI in the same directory last reported, empty
|
||||
// when none has; the client asks again later.
|
||||
func (c *Chat) Commands(_ context.Context, id string) ([]protocol.ChatCommand, error) {
|
||||
s := c.session(id)
|
||||
if s == nil {
|
||||
return nil, errors.New("unknown Claude session " + id)
|
||||
}
|
||||
s.mu.Lock()
|
||||
live := s.proc != nil
|
||||
commands := s.commandsLocked()
|
||||
directory := s.directory
|
||||
s.mu.Unlock()
|
||||
if live {
|
||||
return commands, nil
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(c.ctx, initializeTimeout+5*time.Second)
|
||||
defer cancel()
|
||||
_, _ = s.ensureProcess(ctx)
|
||||
}()
|
||||
return c.cachedCommands(directory), nil
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package claude
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestInitializeCommandsKeepNamesDescriptionsAndHints(t *testing.T) {
|
||||
commands := parseInitializeCommands(json.RawMessage(`{"commands":[
|
||||
{"name":"code-review","description":"Review the current diff","argumentHint":"[low|high]"},
|
||||
{"name":" /docs ","description":" Docs (claude.ai sync) ","argumentHint":""},
|
||||
{"name":"","description":"nameless"},
|
||||
{"name":"two words","description":"bad"},
|
||||
{"name":"__remote-workflow","description":"internal"},
|
||||
{"name":"code-review","description":"duplicate"}]}`))
|
||||
want := []protocol.ChatCommand{
|
||||
{Name: "code-review", Description: "Review the current diff", ArgumentHint: "[low|high]"},
|
||||
{Name: "docs", Description: "Docs (claude.ai sync)"},
|
||||
}
|
||||
if len(commands) != len(want) {
|
||||
t.Fatalf("commands = %+v", commands)
|
||||
}
|
||||
for i := range want {
|
||||
if commands[i] != want[i] {
|
||||
t.Fatalf("command %d = %+v, want %+v", i, commands[i], want[i])
|
||||
}
|
||||
}
|
||||
if got := parseInitializeCommands(json.RawMessage(`{"models":[]}`)); len(got) != 0 {
|
||||
t.Fatalf("no commands field = %+v", got)
|
||||
}
|
||||
if got := parseInitializeCommands(nil); got != nil {
|
||||
t.Fatalf("empty init = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The chat lists the CLI's initialize commands and, once the init line names
|
||||
// terminal-only commands, stops offering them. A slash prompt reaches the CLI
|
||||
// verbatim, so the CLI expands the skill.
|
||||
func TestClaudeCommandsComeFromInitializeAndSkipTerminalOnly(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
session := newCreatedChat(t, chat)
|
||||
ctx := context.Background()
|
||||
names := func(commands []protocol.ChatCommand) []string {
|
||||
out := []string{}
|
||||
for _, c := range commands {
|
||||
out = append(out, c.Name)
|
||||
}
|
||||
return out
|
||||
}
|
||||
// No CLI runs yet: the list is empty at once and the CLI starts in the
|
||||
// background, so a later ask has its commands.
|
||||
commands, err := chat.Commands(ctx, session.ID)
|
||||
if err != nil || len(commands) != 0 {
|
||||
t.Fatalf("commands before any CLI = %v, %v", names(commands), err)
|
||||
}
|
||||
eventually(t, "commands after the background start", func() bool {
|
||||
commands, err = chat.Commands(ctx, session.ID)
|
||||
return err == nil && len(commands) > 0
|
||||
})
|
||||
if got := names(commands); len(got) != 3 || got[0] != "code-review" || got[1] != "probe-skill" || got[2] != "color" {
|
||||
t.Fatalf("commands before init = %v", got)
|
||||
}
|
||||
if commands[0].ArgumentHint != "[low|high] [<pr#>]" || commands[0].Description != "Review the current diff" {
|
||||
t.Fatalf("code-review = %+v", commands[0])
|
||||
}
|
||||
frames := subscribe(t, chat, session.ID)
|
||||
if err := chat.Prompt(ctx, session.ID, "/probe-skill banana"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitStepEnded(t, frames)
|
||||
commands, err = chat.Commands(ctx, session.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := names(commands); len(got) != 2 || got[0] != "code-review" || got[1] != "probe-skill" {
|
||||
t.Fatalf("commands after init = %v", got)
|
||||
}
|
||||
// Another chat in the same directory lists them before its CLI starts.
|
||||
other, err := chat.Create(ctx, "other", session.Directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, _ := chat.Commands(ctx, other.ID); len(got) != 2 {
|
||||
t.Fatalf("same-directory cached commands = %v", names(got))
|
||||
}
|
||||
eventually(t, "other chat's CLI", func() bool {
|
||||
s := chat.session(other.ID)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.proc != nil
|
||||
})
|
||||
eventually(t, "transcript", func() bool { return sessionTranscriptPath(session.ID) != "" })
|
||||
page, err := chat.Messages(ctx, session.ID, 50, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Messages) == 0 || len(page.Messages[0].Parts) != 1 || page.Messages[0].Parts[0].Text != "/probe-skill banana" {
|
||||
t.Fatalf("slash prompt did not reach the CLI verbatim: %+v", page.Messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaudeCommandsRejectUnknownSession(t *testing.T) {
|
||||
chat := testChat(t)
|
||||
if _, err := chat.Commands(context.Background(), "missing"); err == nil {
|
||||
t.Fatal("unknown session listed commands")
|
||||
}
|
||||
}
|
||||
@@ -249,6 +249,7 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
|
||||
p.link.tasksIncomplete.Store(status.Tasks == nil && status.Base > 0)
|
||||
p.stderr.WriteString(status.Stderr)
|
||||
p.models, p.account, p.appliedModel = models, account, status.Model
|
||||
p.commands = parseInitializeCommands(status.Init)
|
||||
p.automations = status.Automations
|
||||
plan := replayPlan{base: status.Base, silentUntil: status.Acked, catchUpEnd: status.End, pending: map[string]bool{}, busyAtAcked: status.BusyAtAcked, restore: true, tasks: status.Tasks}
|
||||
for _, pending := range status.Pending {
|
||||
@@ -267,6 +268,8 @@ func (c *Chat) connectHostContext(ctx context.Context, record claudehost.Record)
|
||||
// Callers hold s.mu.
|
||||
func (s *session) adoptLocked(p *process) {
|
||||
s.models, s.account = p.models, p.account
|
||||
s.commands = p.commands
|
||||
s.chat.rememberCommands(s.directory, s.commandsLocked())
|
||||
s.chat.rememberCatalog(p.models)
|
||||
s.appliedModel = p.appliedModel
|
||||
if p.automations != nil {
|
||||
|
||||
@@ -63,6 +63,7 @@ type process struct {
|
||||
// models, account and appliedModel carry an attached host's
|
||||
// initialize state until the session adopts it.
|
||||
models []protocol.ChatModel
|
||||
commands []protocol.ChatCommand
|
||||
account accountIdentity
|
||||
appliedModel string
|
||||
automations *claudehost.AutomationSnapshot
|
||||
@@ -167,13 +168,15 @@ func (s *session) spawnOnce(ctx context.Context) (*process, error) {
|
||||
// before any user turn so an approval is never silently denied.
|
||||
initCtx, cancel := context.WithTimeout(ctx, initializeTimeout)
|
||||
defer cancel()
|
||||
models, account, err := p.initialize(initCtx)
|
||||
models, account, commands, err := p.initialize(initCtx)
|
||||
if err != nil {
|
||||
p.close()
|
||||
return nil, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.models = models
|
||||
s.commands = commands
|
||||
s.chat.rememberCommands(s.directory, s.commandsLocked())
|
||||
s.account = account
|
||||
s.chat.rememberCatalog(models)
|
||||
s.lastErr = ""
|
||||
@@ -211,7 +214,7 @@ func (s *session) startDirect(args []string, mode string, env []string) (*proces
|
||||
return p, nil
|
||||
}
|
||||
|
||||
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, error) {
|
||||
func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, accountIdentity, []protocol.ChatCommand, error) {
|
||||
raw, err := p.request(ctx, "initialize", map[string]any{
|
||||
"hooks": map[string]any{"Stop": []any{map[string]any{
|
||||
"hookCallbackIds": []string{claudehost.NativeAutomationCallbackID},
|
||||
@@ -219,9 +222,10 @@ func (p *process) initialize(ctx context.Context) ([]protocol.ChatModel, account
|
||||
}}},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, accountIdentity{}, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
|
||||
return nil, accountIdentity{}, nil, fmt.Errorf("initialize Claude Code: %w%s", err, p.diagnostic())
|
||||
}
|
||||
return parseInitialize(raw)
|
||||
models, account, err := parseInitialize(raw)
|
||||
return models, account, parseInitializeCommands(raw), err
|
||||
}
|
||||
|
||||
// parseInitialize reads the CLI's initialize response: its model catalog and
|
||||
|
||||
+9
-2
@@ -70,7 +70,8 @@ def user_message(text):
|
||||
append({"type": "user", "uuid": "user-%d" % state["turn"], "timestamp": stamp(),
|
||||
"message": {"role": "user", "content": [{"type": "text", "text": text}]}})
|
||||
send({"type": "system", "subtype": "init", "session_id": state["session"],
|
||||
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd()})
|
||||
"model": "claude-test", "permissionMode": "default", "cwd": os.getcwd(),
|
||||
"terminal_slash_commands": ["color"]})
|
||||
message_id = "msg_fake_%d" % state["turn"]
|
||||
if "gate" in text:
|
||||
gated(message_id)
|
||||
@@ -218,7 +219,13 @@ def handle(line):
|
||||
"supportsEffort": True, "supportedEffortLevels": ["low", "medium", "high", "max"]},
|
||||
{"value": "haiku", "displayName": "Haiku", "description": "Haiku model"},
|
||||
],
|
||||
"commands": [], "agents": [],
|
||||
"commands": [
|
||||
{"name": "code-review", "description": "Review the current diff", "argumentHint": "[low|high] [<pr#>]"},
|
||||
{"name": "probe-skill", "description": "Probe skill (user)", "argumentHint": ""},
|
||||
{"name": "color", "description": "Set the prompt bar color", "argumentHint": "[red|blue]"},
|
||||
{"name": "__remote-workflow", "description": "internal", "argumentHint": ""},
|
||||
{"name": "code-review", "description": "duplicate", "argumentHint": ""},
|
||||
], "agents": [],
|
||||
"account": {"email": "fixture@example.invalid", "organization": "Fixture Org",
|
||||
"subscriptionType": "max", "apiProvider": "firstParty"},
|
||||
})
|
||||
|
||||
@@ -42,6 +42,9 @@ type lineEnvelope struct {
|
||||
IsMeta bool `json:"isMeta"`
|
||||
// RateLimitInfo is the payload of a rate_limit_event line (see quota.go).
|
||||
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
|
||||
// TerminalSlashCommands, on a system init line, names the commands that
|
||||
// only work in the interactive terminal (see commands.go).
|
||||
TerminalSlashCommands []string `json:"terminal_slash_commands"`
|
||||
}
|
||||
|
||||
type contentBlock struct {
|
||||
@@ -648,6 +651,7 @@ func (s *session) handleSystem(envelope lineEnvelope) {
|
||||
case "init":
|
||||
// The CLI re-emits init at each turn; keep only the authoritative identity.
|
||||
s.adoptFollowUpTurn()
|
||||
s.noteTerminalCommands(envelope.TerminalSlashCommands)
|
||||
if envelope.SessionID != "" && envelope.SessionID != s.id {
|
||||
s.mu.Lock()
|
||||
s.lastErr = "Claude Code opened unexpected session " + envelope.SessionID
|
||||
|
||||
@@ -67,6 +67,10 @@ const (
|
||||
// ChatModels lists the models the chat's harness can switch to; its request
|
||||
// body is ChatQuery (the session id).
|
||||
ChatModels = "chat_models"
|
||||
// ChatCommands lists the slash commands and skills the chat's harness
|
||||
// session offers; its request body is ChatQuery (the session id). A harness
|
||||
// that reports none replies with an empty list.
|
||||
ChatCommands = "chat_commands"
|
||||
// ChatModelSelect switches one session's model for subsequent turns.
|
||||
ChatModelSelect = "chat_model"
|
||||
// ChatModes lists the permission modes the chat's harness offers (Claude
|
||||
@@ -267,6 +271,16 @@ const (
|
||||
ChatMessageKindNotice = "notice"
|
||||
)
|
||||
|
||||
// ChatCommand is one slash command or skill the chat's harness session offers.
|
||||
// Name is the word after the slash; the operator sends "/<Name> <args>" as an
|
||||
// ordinary prompt and the harness expands it. ArgumentHint is the harness's
|
||||
// usage hint for the arguments, if any.
|
||||
type ChatCommand struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
ArgumentHint string `json:"argument_hint,omitempty"`
|
||||
}
|
||||
|
||||
// ChatModel is one model the current chat harness can switch to. ID is the
|
||||
// provider's model id, Provider its provider id, Name the harness's display name.
|
||||
type ChatModel struct {
|
||||
|
||||
@@ -248,6 +248,8 @@ type Message struct {
|
||||
ChatBackends []string `json:"chat_backends,omitempty"`
|
||||
// ChatModels is the chat_models reply: models the session's harness offers.
|
||||
ChatModels []ChatModel `json:"chat_models,omitempty"`
|
||||
// ChatCommands is the chat_commands reply: the session's slash commands.
|
||||
ChatCommands []ChatCommand `json:"chat_commands,omitempty"`
|
||||
// ModelRequest is the chat_model body and echoed selection.
|
||||
ModelRequest *ChatModelRequest `json:"chat_model,omitempty"`
|
||||
// ChatModes is the chat_modes reply: the permission modes the session's
|
||||
|
||||
@@ -250,6 +250,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatModels:
|
||||
handleChatModels(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatCommands:
|
||||
handleChatCommands(ctx, request, broker, write)
|
||||
return true
|
||||
case protocol.ChatModelSelect:
|
||||
handleChatModelSwitch(ctx, request, broker, write)
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// chatCommander is the optional slash-command surface of a chat harness:
|
||||
// the skills and commands its session loaded, which the operator invokes by
|
||||
// sending "/<name> args" as an ordinary prompt. Claude Code implements it; a
|
||||
// harness without one offers an empty list rather than an error.
|
||||
type chatCommander interface {
|
||||
Commands(ctx context.Context, sessionID string) ([]protocol.ChatCommand, error)
|
||||
}
|
||||
|
||||
// Commands lists the slash commands the session's harness offers.
|
||||
func (m *chatManager) Commands(ctx context.Context, sessionID string) ([]protocol.ChatCommand, error) {
|
||||
adapter, err := m.brokerFor(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
commander, ok := adapter.(chatCommander)
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return commander.Commands(ctx, sessionID)
|
||||
}
|
||||
|
||||
// handleChatCommands answers chat_commands with the session's slash commands.
|
||||
func handleChatCommands(ctx context.Context, request protocol.Message, broker chatBroker, write func(protocol.Message) error) {
|
||||
query := request.ChatQuery
|
||||
if query == nil || !validChatSessionID(query.SessionID) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"})
|
||||
return
|
||||
}
|
||||
var commands []protocol.ChatCommand
|
||||
if commander, ok := broker.(chatCommander); ok {
|
||||
var err error
|
||||
if commands, err = commander.Commands(ctx, query.SessionID); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = write(protocol.Message{Type: protocol.ChatCommands, ID: request.ID, ChatCommands: commands})
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/pipeline"
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// commandChat is a harness that reports its session's slash commands.
|
||||
type commandChat struct {
|
||||
*fakeChat
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (c *commandChat) Commands(_ context.Context, id string) ([]protocol.ChatCommand, error) {
|
||||
c.asked = append(c.asked, id)
|
||||
return []protocol.ChatCommand{{Name: "code-review", Description: "Review the diff", ArgumentHint: "[low|high]"}, {Name: "probe-skill"}}, nil
|
||||
}
|
||||
|
||||
func TestChatCommandsRouteToTheSessionHarness(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
claudeID := "01900000-0000-7000-8000-000000000011"
|
||||
codexID := "01900000-0000-7000-8000-000000000012"
|
||||
for id, backend := range map[string]string{claudeID: "claude", codexID: "codex"} {
|
||||
if err := store.RecordOperatorSession(ctx, id, "/fixture", "chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.SetOperatorSessionBackend(ctx, id, backend); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
claude := &commandChat{fakeChat: scriptedChat()}
|
||||
manager := &chatManager{claude: claude, codex: scriptedChat(), registry: store, cache: map[string]string{}}
|
||||
var reply protocol.Message
|
||||
capture := func(msg protocol.Message) error { reply = msg; return nil }
|
||||
|
||||
handleChatCommands(ctx, protocol.Message{ID: "c1", ChatQuery: &protocol.ChatQuery{SessionID: claudeID}}, manager, capture)
|
||||
if reply.Type != protocol.ChatCommands || reply.ID != "c1" || len(reply.ChatCommands) != 2 || len(claude.asked) != 1 || claude.asked[0] != claudeID {
|
||||
t.Fatalf("claude reply = %+v, asked %v", reply, claude.asked)
|
||||
}
|
||||
wire, err := json.Marshal(reply)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(string(wire), `"chat_commands":[{"name":"code-review","description":"Review the diff","argument_hint":"[low|high]"},{"name":"probe-skill"}]`) {
|
||||
t.Fatalf("wire = %s", wire)
|
||||
}
|
||||
|
||||
// A harness without commands answers with an empty list, not an error.
|
||||
handleChatCommands(ctx, protocol.Message{ID: "c2", ChatQuery: &protocol.ChatQuery{SessionID: codexID}}, manager, capture)
|
||||
if reply.Type != protocol.ChatCommands || reply.ID != "c2" || len(reply.ChatCommands) != 0 {
|
||||
t.Fatalf("codex reply = %+v", reply)
|
||||
}
|
||||
handleChatCommands(ctx, protocol.Message{ID: "c3", ChatQuery: &protocol.ChatQuery{SessionID: "not a session"}}, manager, capture)
|
||||
if reply.Type != protocol.Error {
|
||||
t.Fatalf("invalid id reply = %+v", reply)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user