Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
44.8 KB
Raw Blame
package agent

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/multica-ai/multica/server/pkg/taskfailure"
)

// fakeGrokACPScript impersonates `grok agent --always-approve stdio` for unit
// tests. Wire format mirrors other Multica ACP fakes (traecli/kimi): method
// "session/update" with update.sessionUpdate discriminators, session/new
// returning sessionId + models, session/prompt returning stopReason=end_turn.
func fakeGrokACPScript() string {
	return `#!/bin/sh
seen_stdio=
for arg in "$@"; do
  if [ -n "$GROK_ARGS_FILE" ]; then
    printf '%s\n' "$arg" >> "$GROK_ARGS_FILE"
  fi
  if [ -n "$seen_stdio" ]; then
    printf 'unexpected argument after stdio: %s\n' "$arg" >&2
    exit 64
  fi
  if [ "$arg" = "stdio" ]; then
    seen_stdio=1
  fi
done
authenticated=
while IFS= read -r line; do
  if [ -n "$GROK_REQUESTS_FILE" ]; then
    printf '%s\n' "$line" >> "$GROK_REQUESTS_FILE"
  fi
  id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
  case "$line" in
    *'"method":"initialize"'*)
      case "$GROK_AUTH_METHODS" in
        none)
          printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[],"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id"
          ;;
        api)
          printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"xai.api_key","name":"API key"}],"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id"
          ;;
        unknown)
          printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"future_method","name":"Future"}],"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id"
          ;;
        *)
          printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"cached_token","name":"Cached login"},{"id":"xai.api_key","name":"API key"}],"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id"
          ;;
      esac
      ;;
    *'"method":"authenticate"'*)
      if [ -n "$GROK_AUTH_FAIL" ]; then
        printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"authentication required: run grok login"}}\n' "$id"
        exit 0
      fi
      printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
      authenticated=1
      ;;
    *'"method":"session/new"'*)
      if [ -z "$authenticated" ]; then
        printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"authenticate must complete first"}}\n' "$id"
        exit 0
      fi
      printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_new","models":{"availableModels":[{"modelId":"grok-4.6","name":"Grok 4.6","_meta":{"supportsReasoningEffort":true,"reasoningEfforts":[{"id":"xhigh","value":"xhigh","label":"Extra High Effort","default":false},{"id":"high","value":"high","label":"High Effort","default":true},{"id":"medium","value":"medium","label":"Medium Effort","default":false},{"id":"low","value":"low","label":"Low Effort","default":false}]}},{"modelId":"grok-4.5","name":"Grok 4.5","_meta":{"supportsReasoningEffort":true,"reasoningEfforts":[{"id":"high","value":"high","label":"High Effort","default":true},{"id":"medium","value":"medium","label":"Medium Effort","default":false},{"id":"low","value":"low","label":"Low Effort","default":false}]}},{"modelId":"grok-composer-2.5-fast","name":"Grok Composer 2.5 Fast"}],"currentModelId":"grok-4.6"}}}\n' "$id"
      ;;
    *'"method":"session/load"'*)
      if [ -z "$authenticated" ]; then
        printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32000,"message":"authenticate must complete first"}}\n' "$id"
        exit 0
      fi
      printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_loaded","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"history replay ignored"}}}}\n'
      printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
      ;;
    *'"method":"session/set_model"'*)
      case "$line" in
        *bogus-model*)
          printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32602,"message":"model not available: bogus-model"}}\n' "$id"
          exit 0
          ;;
        *)
          printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
          ;;
      esac
      ;;
    *'"method":"session/prompt"'*)
      if [ -n "$GROK_WAIT_FOR_INTERJECT" ]; then
        prompt_id=$id
        if [ -z "$GROK_NO_OUTPUT_BEFORE_INTERJECT" ]; then
          printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"working"}}}}\n'
        fi
        while IFS= read -r followup; do
          if [ -n "$GROK_REQUESTS_FILE" ]; then
            printf '%s\n' "$followup" >> "$GROK_REQUESTS_FILE"
          fi
          followup_id=$(printf '%s' "$followup" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
          case "$followup" in
            *'"method":"_x.ai/interject"'*)
              if [ -n "$GROK_INTERJECT_NO_FIRST_RESPONSE" ] && [ -z "$ignored_first_interject" ]; then
                ignored_first_interject=1
                continue
              fi
              if [ -n "$GROK_INTERJECT_UNSUPPORTED" ]; then
                printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$followup_id"
              elif [ -n "$GROK_INTERJECT_EXTENSION_ERROR" ]; then
                printf '{"jsonrpc":"2.0","id":%s,"result":{"result":null,"error":"delivery failed"}}\n' "$followup_id"
              else
                printf '{"jsonrpc":"2.0","id":%s,"result":{"result":{"status":"%s"}}}\n' "$followup_id" "${GROK_INTERJECT_NESTED_STATUS:-queued}"
              fi
              if [ -n "$GROK_NO_OUTPUT_BEFORE_INTERJECT" ]; then
                printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"111"}}}}\n'
              fi
              printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$prompt_id"
              break
              ;;
          esac
        done
        exit 0
      fi
      if [ -n "$GROK_HANG_PROMPT" ]; then
        while :; do sleep 1; done
      fi
      printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"thinking about it"}}}}\n'
      printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call","toolCallId":"tc-1","name":"Shell","status":"pending","parameters":{"command":"echo hi"}}}}\n'
      printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-1","status":"completed","name":"Shell","output":"hi\\n"}}}\n'
      printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"pong"}}}}\n'
      if [ -n "$GROK_USAGE" ]; then
        # Match live Grok Build ACP (0.2.x): metering lives under result._meta,
        # not a top-level usage field or sessionUpdate=usage_update.
        printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","_meta":{"sessionId":"ses_new","modelId":"grok-4.6","inputTokens":120,"outputTokens":30,"cachedReadTokens":20,"cachedWriteTokens":5,"usage":{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cachedReadTokens":20,"cachedWriteTokens":5,"modelCalls":1,"costUsdTicks":98765}}}}\n' "$id"
      else
        printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
      fi
      if [ -n "$GROK_LATE_CHUNK" ]; then
        sleep 0.05
        printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tail"}}}}\n'
      fi
      exit 0
      ;;
  esac
done
`
}

func TestGrokSupplementTargetsActivePrompt(t *testing.T) {
	t.Parallel()
	fakePath := filepath.Join(t.TempDir(), "grok")
	requestsPath := filepath.Join(t.TempDir(), "requests.jsonl")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Env: map[string]string{
			"GROK_WAIT_FOR_INTERJECT":         "1",
			"GROK_NO_OUTPUT_BEFORE_INTERJECT": "1",
			"GROK_REQUESTS_FILE":              requestsPath,
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()
	session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
	if err != nil {
		t.Fatal(err)
	}
	if session.Supplement == nil || session.SupplementReady == nil {
		t.Fatal("negotiated Grok session did not expose supplement callbacks")
	}
	if session.SupplementReady() {
		t.Fatal("supplement became ready before session/prompt started")
	}
	deadline := time.Now().Add(testFallbackTimeout)
	for !session.SupplementReady() && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if !session.SupplementReady() {
		t.Fatal("supplement never became ready during active prompt")
	}
	for len(session.Messages) > 0 {
		msg := <-session.Messages
		if msg.Type != MessageStatus {
			t.Fatalf("agent emitted output before interjection: %+v", msg)
		}
	}
	var messages []Message
	drained := make(chan struct{})
	go func() {
		defer close(drained)
		for msg := range session.Messages {
			messages = append(messages, msg)
		}
	}()
	if err := session.Supplement(ctx, "Reply with 111 instead of continuing the task."); err != nil {
		t.Fatalf("send interjection: %v", err)
	}
	result := <-session.Result
	<-drained
	if result.Status != "completed" {
		t.Fatalf("turn status=%q error=%q", result.Status, result.Error)
	}
	if result.Output != "111" {
		t.Fatalf("turn output=%q, want steering response 111", result.Output)
	}
	if len(messages) != 1 || messages[0].Type != MessageText || messages[0].Content != "111" {
		t.Fatalf("agent messages=%+v, want only steering response 111", messages)
	}
	if session.SupplementReady() {
		t.Fatal("supplement remained ready after session/prompt completed")
	}
	requests, err := os.ReadFile(requestsPath)
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{`"method":"_x.ai/interject"`, `"sessionId":"ses_new"`, `"text":"Reply with 111 instead of continuing the task."`} {
		if !strings.Contains(string(requests), want) {
			t.Errorf("ACP requests missing %s:\n%s", want, requests)
		}
	}
}

func TestGrokSupplementTimesOutIndependentlyAndAllowsNextMessage(t *testing.T) {
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Env: map[string]string{
			"GROK_WAIT_FOR_INTERJECT":          "1",
			"GROK_INTERJECT_NO_FIRST_RESPONSE": "1",
		},
	})
	if err != nil {
		t.Fatal(err)
	}

	previousTimeout := grokSupplementTimeout
	grokSupplementTimeout = 50 * time.Millisecond
	defer func() { grokSupplementTimeout = previousTimeout }()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: 10 * testFallbackTimeout, EnableTaskSupplement: true})
	if err != nil {
		t.Fatal(err)
	}
	deadline := time.Now().Add(testFallbackTimeout)
	for !session.SupplementReady() && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if !session.SupplementReady() {
		cancel()
		t.Fatal("supplement never became ready during active prompt")
	}

	// ctx has no deadline and the run timeout is far away, so a
	// DeadlineExceeded here can only come from grokSupplementTimeout.
	firstSupplement := make(chan error, 1)
	go func() {
		firstSupplement <- session.Supplement(ctx, "The first interjection will not be acknowledged.")
	}()
	select {
	case err = <-firstSupplement:
	case <-time.After(testFallbackTimeout):
		cancel()
		select {
		case <-session.Result:
		case <-time.After(testFallbackTimeout):
			t.Fatal("Grok run did not stop after its parent context was canceled")
		}
		t.Fatal("supplement did not return within its independent timeout")
	}
	if !errors.Is(err, context.DeadlineExceeded) {
		cancel()
		t.Fatalf("first supplement error=%v, want context deadline exceeded", err)
	}
	if !session.SupplementReady() {
		cancel()
		t.Fatal("an interject timeout ended the active Grok prompt")
	}

	if err := session.Supplement(ctx, "The next interjection should still be delivered."); err != nil {
		cancel()
		t.Fatalf("second supplement after timeout: %v", err)
	}
	select {
	case result := <-session.Result:
		if result.Status != "completed" {
			t.Fatalf("turn status=%q error=%q", result.Status, result.Error)
		}
	case <-time.After(testFallbackTimeout):
		cancel()
		t.Fatal("Grok prompt did not complete after the second interjection")
	}
}

func TestGrokSupplementReportsACPRejection(t *testing.T) {
	t.Parallel()
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Env: map[string]string{
			"GROK_WAIT_FOR_INTERJECT":    "1",
			"GROK_INTERJECT_UNSUPPORTED": "1",
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()
	session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
	if err != nil {
		t.Fatal(err)
	}
	drained := make(chan struct{})
	go func() {
		defer close(drained)
		for range session.Messages {
		}
	}()
	deadline := time.Now().Add(testFallbackTimeout)
	for !session.SupplementReady() && time.Now().Before(deadline) {
		time.Sleep(5 * time.Millisecond)
	}
	if !session.SupplementReady() {
		t.Fatal("supplement never became ready during active prompt")
	}
	err = session.Supplement(ctx, "A test message")
	if err == nil || !strings.Contains(err.Error(), "method not found") {
		t.Fatalf("supplement error=%v, want ACP method-not-found error", err)
	}
	result := <-session.Result
	<-drained
	if result.Status != "completed" {
		t.Fatalf("turn status=%q error=%q", result.Status, result.Error)
	}
}

func TestGrokSupplementHandlesObservedNestedResultStatus(t *testing.T) {
	for _, tc := range []struct {
		status  string
		wantErr string
	}{
		{status: "queued"},
		{status: "rejected", wantErr: "rejected"},
		{status: "in_band_error", wantErr: "delivery failed"},
	} {
		t.Run(tc.status, func(t *testing.T) {
			fakePath := filepath.Join(t.TempDir(), "grok")
			writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
			env := map[string]string{"GROK_WAIT_FOR_INTERJECT": "1"}
			if tc.status == "in_band_error" {
				env["GROK_INTERJECT_EXTENSION_ERROR"] = "1"
			} else {
				env["GROK_INTERJECT_NESTED_STATUS"] = tc.status
			}
			backend, err := New("grok", Config{
				ExecutablePath: fakePath,
				Env:            env,
			})
			if err != nil {
				t.Fatal(err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
			defer cancel()
			session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
			if err != nil {
				t.Fatal(err)
			}
			go func() {
				for range session.Messages {
				}
			}()
			deadline := time.Now().Add(testFallbackTimeout)
			for !session.SupplementReady() && time.Now().Before(deadline) {
				time.Sleep(5 * time.Millisecond)
			}
			if !session.SupplementReady() {
				t.Fatal("supplement never became ready during active prompt")
			}
			err = session.Supplement(ctx, "A test message")
			if tc.wantErr != "" {
				if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
					t.Fatalf("supplement error=%v, want %q", err, tc.wantErr)
				}
			} else if err != nil {
				t.Fatalf("nested queued status was rejected: %v", err)
			}
			if result := <-session.Result; result.Status != "completed" {
				t.Fatalf("turn status=%q error=%q", result.Status, result.Error)
			}
		})
	}
}

func TestGrokBackendStreamsAndCompletes(t *testing.T) {
	t.Parallel()
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{ExecutablePath: fakePath, Logger: slog.Default()})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()

	session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	var messages []Message
	done := make(chan struct{})
	go func() {
		defer close(done)
		for m := range session.Messages {
			messages = append(messages, m)
		}
	}()
	result := <-session.Result
	<-done

	if result.Status != "completed" {
		t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
	}
	if !strings.Contains(result.Output, "pong") {
		t.Fatalf("output = %q, want it to contain the assistant message 'pong'", result.Output)
	}
	if result.SessionID != "ses_new" {
		t.Fatalf("session id = %q, want ses_new", result.SessionID)
	}
	var sawText, sawToolUse bool
	for _, m := range messages {
		if m.Type == MessageText && strings.Contains(m.Content, "pong") {
			sawText = true
		}
		if m.Type == MessageToolUse && m.Tool == "terminal" {
			sawToolUse = true
		}
	}
	if !sawText {
		t.Error("expected a MessageText carrying the assistant 'pong'")
	}
	if !sawToolUse {
		t.Errorf("expected the Shell tool_call to normalize to 'terminal'; messages=%+v", messages)
	}
}

// Protocol limits end the RPC successfully, but do not mean the task completed.
func TestGrokPromptStopReasons(t *testing.T) {
	t.Parallel()
	for _, tc := range []struct {
		reason     string
		wantStatus string
		wantError  string
	}{
		{"end_turn", "completed", ""},
		{"max_tokens", "failed", "grok reached its maximum generated tokens (max_tokens)"},
		{"max_turn_requests", "failed", "grok reached its maximum turn requests (max_turn_requests)"},
		{"cancelled", "aborted", "grok cancelled the prompt"},
		{"refusal", "completed", ""},
	} {
		t.Run(tc.reason, func(t *testing.T) {
			t.Parallel()
			fakePath := filepath.Join(t.TempDir(), "grok")
			script := strings.ReplaceAll(fakeGrokACPScript(), `"stopReason":"end_turn"`, `"stopReason":"`+tc.reason+`"`)
			writeTestExecutable(t, fakePath, []byte(script))
			backend, err := New("grok", Config{
				ExecutablePath: fakePath,
				Env:            map[string]string{"GROK_USAGE": "1"},
			})
			if err != nil {
				t.Fatal(err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
			defer cancel()
			session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: testFallbackTimeout})
			if err != nil {
				t.Fatal(err)
			}
			drained := make(chan struct{})
			go func() {
				defer close(drained)
				for range session.Messages {
				}
			}()
			result := <-session.Result
			<-drained
			if result.Status != tc.wantStatus || result.Error != tc.wantError {
				t.Errorf("status=%q error=%q, want status=%q error=%q", result.Status, result.Error, tc.wantStatus, tc.wantError)
			}
			if tc.reason == "max_tokens" || tc.reason == "max_turn_requests" {
				// A turn budget is not evidence of a broken or oversized history.
				if reason := taskfailure.Classify(result.Error); reason != taskfailure.ReasonAgentUnknown {
					t.Errorf("failure reason=%q, want generic agent failure", reason)
				}
			}
			if result.Output != "pong" {
				t.Errorf("output=%q, want partial output preserved", result.Output)
			}
			if result.SessionID != "ses_new" || result.ResumeRejected {
				t.Errorf("session=%q resumeRejected=%v, want resumable session preserved", result.SessionID, result.ResumeRejected)
			}
			usage := result.Usage["grok-4.6"]
			if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 5 || usage.CostUSDTicks != 98765 {
				t.Errorf("usage not preserved: %+v", result.Usage)
			}
		})
	}
}

func TestGrokBlockedArgsFiltering(t *testing.T) {
	t.Parallel()
	tempDir := t.TempDir()
	argsFile := filepath.Join(tempDir, "argv.txt")
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env:            map[string]string{"GROK_ARGS_FILE": argsFile},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()

	session, err := backend.Execute(ctx, "task", ExecOptions{
		Timeout:       testFallbackTimeout,
		ThinkingLevel: "high",
		// Users must not strip ACP mode, disable auto-approve, or switch
		// into print/headless transports.
		CustomArgs: []string{"agent", "stdio", "--always-approve", "--yolo", "headless", "-p", "--output-format", "json", "--permission-mode", "default", "--model", "hijack", "--reasoning-effort", "low", "--effort", "low", "--cwd", "/tmp/hijack", "--worktree", "branch-dir", "--ref", "other", "--fork-session", "--rules", "extra"},
	})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	<-session.Result

	raw, err := os.ReadFile(argsFile)
	if err != nil {
		t.Fatalf("read args file: %v", err)
	}
	lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
	wantPrefix := []string{"--no-auto-update", "agent", "--always-approve", "--effort", "high", "--rules", "extra", "stdio"}
	if len(lines) < len(wantPrefix) {
		t.Fatalf("expected at least %d args, got %d: %q", len(wantPrefix), len(lines), lines)
	}
	for i, want := range wantPrefix {
		if lines[i] != want {
			t.Fatalf("arg[%d] = %q, want %q (full: %q)", i, lines[i], want, lines)
		}
	}
	joined := strings.Join(lines, " ")
	for _, once := range []string{"--no-auto-update", "agent", "--always-approve", "stdio"} {
		if c := countTokens(lines, once); c != 1 {
			t.Errorf("expected exactly one %q, got %d (full: %q)", once, c, joined)
		}
	}
	for _, blocked := range []string{"headless", "-p", "--output-format", "json", "--permission-mode", "default", "--yolo", "hijack", "--cwd", "/tmp/hijack", "--worktree", "branch-dir", "--ref", "other", "--fork-session"} {
		for _, got := range lines {
			if got == blocked {
				t.Errorf("blocked custom arg %q survived filtering: %q", blocked, lines)
			}
		}
	}
	// Daemon-owned thinking must win over custom --effort/--reasoning-effort low.
	if strings.Count(joined, "--effort") != 1 || !strings.Contains(joined, "--effort high") {
		t.Errorf("expected single --effort high, got %q", joined)
	}
	if strings.Contains(joined, "--reasoning-effort") {
		t.Errorf("legacy --reasoning-effort must be stripped, got %q", joined)
	}
	// An allowed custom arg must survive (after the fixed prefix).
	if !strings.Contains(joined, "--rules") || !strings.Contains(joined, "extra") {
		t.Errorf("expected allowed custom arg --rules to survive, got %q", joined)
	}
	if lines[len(lines)-1] != "stdio" {
		t.Errorf("stdio must be the final transport subcommand, got %q", lines)
	}
}

func TestGrokSetModelFailureFailsTask(t *testing.T) {
	t.Parallel()
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{ExecutablePath: fakePath, Logger: slog.Default()})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()

	session, err := backend.Execute(ctx, "task", ExecOptions{Model: "bogus-model", Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "failed" {
		t.Fatalf("expected failed on set_model error, got %q", result.Status)
	}
	if !strings.Contains(result.Error, `could not switch to model "bogus-model"`) {
		t.Errorf("expected error to name the model, got %q", result.Error)
	}
	if !strings.Contains(result.Error, "model not available") {
		t.Errorf("expected upstream message surfaced, got %q", result.Error)
	}
}

func TestGrokUsesSessionLoadForResume(t *testing.T) {
	t.Parallel()
	tempDir := t.TempDir()
	requestsFile := filepath.Join(tempDir, "requests.jsonl")
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env:            map[string]string{"GROK_REQUESTS_FILE": requestsFile},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()

	session, err := backend.Execute(ctx, "continue", ExecOptions{
		ResumeSessionID: "ses_existing",
		Timeout:         testFallbackTimeout,
	})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "completed" {
		t.Fatalf("expected completed, got %q (error=%q)", result.Status, result.Error)
	}
	if result.SessionID != "ses_existing" {
		t.Fatalf("session id = %q, want ses_existing", result.SessionID)
	}
	raw, err := os.ReadFile(requestsFile)
	if err != nil {
		t.Fatalf("read requests: %v", err)
	}
	requests := string(raw)
	if !strings.Contains(requests, `"method":"session/load"`) {
		t.Fatalf("expected session/load on resume, got:\n%s", requests)
	}
	if strings.Contains(requests, `"method":"session/resume"`) {
		t.Fatalf("grok must use session/load when resuming, not session/resume:\n%s", requests)
	}
}

// TestGrokAuthenticatesBeforeSession asserts the ACP auth handshake happens in
// the order the real Grok CLI requires: `authenticate` must be sent after
// `initialize` and before any session operation (session/new or session/load).
// A fake ACP that blindly accepts session/new (as ours does) would otherwise
// hide a missing handshake — the exact gap this guards against.
func TestGrokAuthenticatesBeforeSession(t *testing.T) {
	t.Parallel()
	for _, tc := range []struct {
		name        string
		resume      string
		wantSession string
	}{
		{name: "new session", resume: "", wantSession: `"method":"session/new"`},
		{name: "resume", resume: "ses_existing", wantSession: `"method":"session/load"`},
	} {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			t.Parallel()
			tempDir := t.TempDir()
			requestsFile := filepath.Join(tempDir, "requests.jsonl")
			fakePath := filepath.Join(tempDir, "grok")
			writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

			backend, err := New("grok", Config{
				ExecutablePath: fakePath,
				Logger:         slog.Default(),
				Env:            map[string]string{"GROK_REQUESTS_FILE": requestsFile},
			})
			if err != nil {
				t.Fatalf("new grok backend: %v", err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
			defer cancel()

			session, err := backend.Execute(ctx, "task", ExecOptions{
				ResumeSessionID: tc.resume,
				Timeout:         testFallbackTimeout,
			})
			if err != nil {
				t.Fatalf("execute: %v", err)
			}
			go func() {
				for range session.Messages {
				}
			}()
			<-session.Result

			raw, err := os.ReadFile(requestsFile)
			if err != nil {
				t.Fatalf("read requests: %v", err)
			}
			lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
			authIdx, sessionIdx, initIdx := -1, -1, -1
			for i, l := range lines {
				switch {
				case strings.Contains(l, `"method":"initialize"`):
					initIdx = i
				case strings.Contains(l, `"method":"authenticate"`):
					authIdx = i
				case strings.Contains(l, tc.wantSession):
					if sessionIdx == -1 {
						sessionIdx = i
					}
				}
			}
			if authIdx == -1 {
				t.Fatalf("expected an authenticate request, got:\n%s", raw)
			}
			if sessionIdx == -1 {
				t.Fatalf("expected a %s request, got:\n%s", tc.wantSession, raw)
			}
			if !(initIdx < authIdx && authIdx < sessionIdx) {
				t.Fatalf("expected order initialize(%d) < authenticate(%d) < session(%d):\n%s",
					initIdx, authIdx, sessionIdx, raw)
			}
			// The daemon has no XAI_API_KEY here, so it must fall back to the
			// cached-token method advertised by the fake.
			if !strings.Contains(lines[authIdx], `"methodId":"cached_token"`) {
				t.Errorf("expected cached_token auth method, got: %s", lines[authIdx])
			}
			if !strings.Contains(lines[authIdx], `"headless":true`) {
				t.Errorf("expected headless meta on authenticate, got: %s", lines[authIdx])
			}
		})
	}
}

// TestGrokAuthFailureFailsTask asserts a rejected authenticate handshake fails
// the task with a clear error instead of falling through to session/new.
func TestGrokAuthFailureFailsTask(t *testing.T) {
	t.Parallel()
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env:            map[string]string{"GROK_AUTH_FAIL": "1"},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
	defer cancel()

	session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "failed" {
		t.Fatalf("expected failed on authenticate error, got %q", result.Status)
	}
	if !strings.Contains(result.Error, "authenticate") {
		t.Errorf("expected error to mention authenticate, got %q", result.Error)
	}
}

func TestGrokNoUsableAuthMethodFailsBeforeSession(t *testing.T) {
	for _, methods := range []string{"none", "unknown", "api"} {
		t.Run(methods, func(t *testing.T) {
			tempDir := t.TempDir()
			requestsFile := filepath.Join(tempDir, "requests.jsonl")
			fakePath := filepath.Join(tempDir, "grok")
			writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

			backend, err := New("grok", Config{
				ExecutablePath: fakePath,
				Logger:         slog.Default(),
				Env: map[string]string{
					"GROK_AUTH_METHODS":  methods,
					"GROK_REQUESTS_FILE": requestsFile,
					"XAI_API_KEY":        "",
				},
			})
			if err != nil {
				t.Fatalf("new grok backend: %v", err)
			}
			session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
			if err != nil {
				t.Fatalf("execute: %v", err)
			}
			go func() {
				for range session.Messages {
				}
			}()
			result := <-session.Result
			if result.Status != "failed" || !strings.Contains(result.Error, "authentication setup") {
				t.Fatalf("expected auth setup failure, got status=%q error=%q", result.Status, result.Error)
			}
			raw, err := os.ReadFile(requestsFile)
			if err != nil {
				t.Fatalf("read requests: %v", err)
			}
			if strings.Contains(string(raw), `"method":"authenticate"`) || strings.Contains(string(raw), `"method":"session/`) {
				t.Fatalf("must stop before auth/session with unusable methods:\n%s", raw)
			}
		})
	}
}

func TestGrokUsesAdvertisedAPIKeyMethod(t *testing.T) {
	tempDir := t.TempDir()
	requestsFile := filepath.Join(tempDir, "requests.jsonl")
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))

	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env: map[string]string{
			"GROK_AUTH_METHODS":  "api",
			"GROK_REQUESTS_FILE": requestsFile,
			"XAI_API_KEY":        "test-only-key",
		},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "completed" {
		t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
	}
	raw, err := os.ReadFile(requestsFile)
	if err != nil {
		t.Fatalf("read requests: %v", err)
	}
	if !strings.Contains(string(raw), `"methodId":"xai.api_key"`) {
		t.Fatalf("expected advertised API-key method, got:\n%s", raw)
	}
}

func TestGrokDrainsNotificationsAfterPromptResponse(t *testing.T) {
	fakePath := filepath.Join(t.TempDir(), "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env:            map[string]string{"GROK_LATE_CHUNK": "1"},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "completed" {
		t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
	}
	if !strings.Contains(result.Output, "pong tail") {
		t.Fatalf("late output was truncated: %q", result.Output)
	}
}

func TestGrokPropagatesMCPAndUsage(t *testing.T) {
	tempDir := t.TempDir()
	requestsFile := filepath.Join(tempDir, "requests.jsonl")
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env: map[string]string{
			"GROK_REQUESTS_FILE": requestsFile,
			"GROK_USAGE":         "1",
		},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	session, err := backend.Execute(context.Background(), "task", ExecOptions{
		Timeout:   testFallbackTimeout,
		McpConfig: json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`),
	})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "completed" {
		t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
	}
	raw, err := os.ReadFile(requestsFile)
	if err != nil {
		t.Fatalf("read requests: %v", err)
	}
	requests := string(raw)
	if !strings.Contains(requests, `"name":"fetch"`) || !strings.Contains(requests, `"command":"uvx"`) {
		t.Fatalf("session/new did not receive MCP server:\n%s", raw)
	}
	usage, ok := result.Usage["grok-4.6"]
	if !ok {
		t.Fatalf("usage missing grok-4.6 key: %+v", result.Usage)
	}
	// The fixture's totalTokens (150) equals input + output, so its 20 cached
	// reads sit inside inputTokens and are billed once: input is stored as the
	// uncached remainder 120 - 20 = 100.
	if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 5 {
		t.Fatalf("unexpected usage: %+v", usage)
	}
	// xAI's own price for the turn has to survive the whole backend, not just
	// the parser: it is the only figure carrying the ≥200K prompt surcharge,
	// and everything downstream falls back to a rate-table guess without it.
	if usage.CostUSDTicks != 98765 {
		t.Fatalf("cost ticks = %d, want 98765", usage.CostUSDTicks)
	}
}

// TestGrokAttributesUsageOnResumeWithoutConfiguredModel pins the model
// attribution on the resume path. `session/load` reports no model id (only
// `session/new` does), so when neither the agent nor the runtime pins a model
// the turn's own `_meta.modelId` is the only source left. Without it the whole
// run buckets under "unknown", which matches no pricing row and reports $0
// spend for the task.
func TestGrokAttributesUsageOnResumeWithoutConfiguredModel(t *testing.T) {
	t.Parallel()
	tempDir := t.TempDir()
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env:            map[string]string{"GROK_USAGE": "1"},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	// No Model: the daemon leaves it empty whenever neither the agent nor
	// MULTICA_GROK_MODEL pins one (see daemon.go resolveModel).
	session, err := backend.Execute(context.Background(), "continue", ExecOptions{
		ResumeSessionID: "ses_existing",
		Timeout:         testFallbackTimeout,
	})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	result := <-session.Result
	if result.Status != "completed" {
		t.Fatalf("expected completed, got status=%q error=%q", result.Status, result.Error)
	}
	if _, unknown := result.Usage["unknown"]; unknown {
		t.Fatalf("resumed usage fell back to the unpriced \"unknown\" bucket: %+v", result.Usage)
	}
	usage, ok := result.Usage["grok-4.6"]
	if !ok {
		t.Fatalf("usage missing grok-4.6 key: %+v", result.Usage)
	}
	if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 5 {
		t.Fatalf("unexpected usage: %+v", usage)
	}
	if usage.CostUSDTicks != 98765 {
		t.Fatalf("cost ticks = %d, want 98765", usage.CostUSDTicks)
	}
}

func TestGrokCancellation(t *testing.T) {
	tempDir := t.TempDir()
	fakePath := filepath.Join(tempDir, "grok")
	requestsFile := filepath.Join(tempDir, "requests.jsonl")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	backend, err := New("grok", Config{
		ExecutablePath: fakePath,
		Logger:         slog.Default(),
		Env: map[string]string{
			"GROK_HANG_PROMPT":   "1",
			"GROK_REQUESTS_FILE": requestsFile,
		},
	})
	if err != nil {
		t.Fatalf("new grok backend: %v", err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: testFallbackTimeout})
	if err != nil {
		t.Fatalf("execute: %v", err)
	}
	go func() {
		for range session.Messages {
		}
	}()
	deadline := time.Now().Add(testFallbackTimeout)
	for {
		raw, _ := os.ReadFile(requestsFile)
		if strings.Contains(string(raw), `"method":"session/prompt"`) {
			cancel()
			break
		}
		if time.Now().After(deadline) {
			t.Fatal("fake never reached session/prompt before cancellation")
		}
		time.Sleep(10 * time.Millisecond)
	}
	select {
	case result := <-session.Result:
		if result.Status != "aborted" {
			t.Fatalf("status=%q error=%q, want aborted", result.Status, result.Error)
		}
	case <-time.After(testFallbackTimeout):
		t.Fatal("grok child was not terminated and reaped")
	}
}

func TestDiscoverGrokModelsWaitsForAdvertisedAuth(t *testing.T) {
	tempDir := t.TempDir()
	requestsFile := filepath.Join(tempDir, "requests.jsonl")
	fakePath := filepath.Join(tempDir, "grok")
	writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
	t.Setenv("GROK_REQUESTS_FILE", requestsFile)
	t.Setenv("GROK_AUTH_METHODS", "api")
	t.Setenv("XAI_API_KEY", "test-only-key")

	catalog, err := discoverGrokModels(context.Background(), Command{Path: fakePath})
	if err != nil {
		t.Fatalf("discover grok models: %v", err)
	}
	if len(catalog.Models) != 3 || catalog.Models[0].ID != "grok-4.6" {
		t.Fatalf("unexpected models: %+v", catalog.Models)
	}
	if catalog.Fallback {
		t.Error("a successful ACP discovery must not be marked Fallback")
	}
	byID := make(map[string]*ModelThinking, len(catalog.Models))
	for _, model := range catalog.Models {
		byID[model.ID] = model.Thinking
	}
	if got := thinkingValues(byID["grok-4.6"]); strings.Join(got, ",") != "xhigh,high,medium,low" || byID["grok-4.6"].DefaultLevel != "high" {
		t.Fatalf("grok-4.6 thinking = %+v, want advertised catalog with high default", byID["grok-4.6"])
	}
	if got := thinkingValues(byID["grok-4.5"]); strings.Join(got, ",") != "high,medium,low" || byID["grok-4.5"].DefaultLevel != "high" {
		t.Fatalf("grok-4.5 thinking = %+v, want advertised catalog with high default", byID["grok-4.5"])
	}
	if byID["grok-composer-2.5-fast"] != nil {
		t.Fatalf("model without vendor reasoning metadata got %+v", byID["grok-composer-2.5-fast"])
	}
	raw, err := os.ReadFile(requestsFile)
	if err != nil {
		t.Fatalf("read requests: %v", err)
	}
	requests := string(raw)
	initAt := strings.Index(requests, `"method":"initialize"`)
	authAt := strings.Index(requests, `"method":"authenticate"`)
	sessionAt := strings.Index(requests, `"method":"session/new"`)
	if !(initAt >= 0 && initAt < authAt && authAt < sessionAt) {
		t.Fatalf("expected response-driven initialize/auth/session order:\n%s", raw)
	}
	if !strings.Contains(requests, `"methodId":"xai.api_key"`) {
		t.Fatalf("expected API-key auth selected from initialize response:\n%s", raw)
	}
}

func TestDiscoverGrokModelsStopsOnAuthFailures(t *testing.T) {
	for _, tc := range []struct {
		name     string
		methods  string
		authFail string
		wantAuth bool
	}{
		{name: "no methods", methods: "none", wantAuth: false},
		{name: "authenticate rejected", authFail: "1", wantAuth: true},
	} {
		t.Run(tc.name, func(t *testing.T) {
			tempDir := t.TempDir()
			requestsFile := filepath.Join(tempDir, "requests.jsonl")
			fakePath := filepath.Join(tempDir, "grok")
			writeTestExecutable(t, fakePath, []byte(fakeGrokACPScript()))
			t.Setenv("GROK_REQUESTS_FILE", requestsFile)
			t.Setenv("GROK_AUTH_METHODS", tc.methods)
			t.Setenv("GROK_AUTH_FAIL", tc.authFail)
			t.Setenv("XAI_API_KEY", "")

			catalog, err := discoverGrokModels(context.Background(), Command{Path: fakePath})
			if err != nil {
				t.Fatalf("discover grok models: %v", err)
			}
			if len(catalog.Models) != 3 || catalog.Models[0].ID != "grok-4.6" {
				t.Fatalf("expected static fallback, got %+v", catalog.Models)
			}
			if !catalog.Fallback {
				t.Error("static fallback must be marked Fallback so it is never cached as the real catalog")
			}
			raw, err := os.ReadFile(requestsFile)
			if err != nil {
				t.Fatalf("read requests: %v", err)
			}
			requests := string(raw)
			if strings.Contains(requests, `"method":"session/new"`) {
				t.Fatalf("discovery must stop before session/new on auth failure:\n%s", raw)
			}
			if got := strings.Contains(requests, `"method":"authenticate"`); got != tc.wantAuth {
				t.Fatalf("authenticate present=%v, want %v:\n%s", got, tc.wantAuth, raw)
			}
		})
	}
}

func TestGrokThinkingCatalogIsPerModel(t *testing.T) {
	models := grokStaticModels()
	if len(models) != 3 || models[0].ID != "grok-4.6" || !models[0].Default {
		t.Fatalf("static fallback must default to grok-4.6: %+v", models)
	}
	want := map[string]string{
		"grok-4.6": "low,medium,high,xhigh",
		"grok-4.5": "low,medium,high",
	}
	for id, levels := range want {
		model := grokMustFindModel(t, models, id)
		if model.Thinking == nil {
			t.Fatalf("%s should advertise documented effort levels", id)
		}
		got := make([]string, 0, len(model.Thinking.SupportedLevels))
		for _, level := range model.Thinking.SupportedLevels {
			got = append(got, level.Value)
		}
		if strings.Join(got, ",") != levels {
			t.Fatalf("%s levels = %v, want %s", id, got, levels)
		}
	}
	composer := grokMustFindModel(t, models, "grok-composer-2.5-fast")
	if composer.Thinking != nil {
		t.Fatalf("unverified composer model must hide thinking controls: %+v", composer.Thinking)
	}
	unknown := []Model{{ID: "future-grok", Label: "Future"}}
	annotateGrokThinking(unknown)
	if unknown[0].Thinking != nil {
		t.Fatalf("unknown models must not inherit grok-4.5 effort levels: %+v", unknown[0].Thinking)
	}
}

// The static Grok list only shapes the fallback picker. A saved level is never
// judged against it — not even where it disagrees with the list — because a
// stand-in cannot say what the installed CLI accepts (MUL-7691).
func TestGrokFallbackCatalogPassesThinkingLevelThrough(t *testing.T) {
	for _, tc := range []struct{ model, level string }{
		{model: "grok-4.6", level: "high"},
		{model: "grok-4.5", level: "xhigh"},
		{model: "grok-composer-2.5-fast", level: "low"},
		{model: "future-grok", level: "high"},
		{model: "", level: "high"},
	} {
		got, err := ValidateThinkingLevel(context.Background(), "grok", Command{Path: "/nonexistent/grok"}, tc.model, tc.level)
		if got || !errors.Is(err, errUnverifiedCatalog) {
			t.Errorf("ValidateThinkingLevel(%q, %q) = (%v, %v), want errUnverifiedCatalog", tc.model, tc.level, got, err)
		}
	}
}

// TestGrokSelectAuthMethod covers the auth-method selection preference.
func TestGrokSelectAuthMethod(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name    string
		methods []string
		haveKey bool
		wantID  string
		wantErr bool
	}{
		{"none advertised", nil, false, "", true},
		{"cached only", []string{"cached_token"}, false, "cached_token", false},
		{"api key preferred when present", []string{"cached_token", "xai.api_key"}, true, "xai.api_key", false},
		{"api key ignored without env", []string{"cached_token", "xai.api_key"}, false, "cached_token", false},
		{"api only requires env", []string{"xai.api_key"}, false, "", true},
		{"unknown fails closed", []string{"future_method"}, true, "", true},
	}
	for _, tc := range cases {
		got, err := selectGrokAuthMethod(tc.methods, tc.haveKey)
		if got != tc.wantID || (err != nil) != tc.wantErr {
			t.Errorf("%s: selectGrokAuthMethod(%v, %v) = (%q, %v), want (%q, err=%v)",
				tc.name, tc.methods, tc.haveKey, got, err, tc.wantID, tc.wantErr)
		}
	}
}

func grokMustFindModel(t *testing.T, models []Model, id string) Model {
	t.Helper()
	for _, model := range models {
		if model.ID == id {
			return model
		}
	}
	t.Fatalf("model %q not in catalog: %+v", id, models)
	return Model{}
}