| 1 | package cliconversation |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "os" |
| 11 | "os/exec" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "sync/atomic" |
| 16 | "testing" |
| 17 | "time" |
| 18 | ) |
| 19 | |
| 20 | const testSessionID = "de3ac0b3-1bad-43da-88ab-d86b7af32210" |
| 21 | |
| 22 | func TestResultRequiresMatchingCompletedSession(t *testing.T) { |
| 23 | init := `{"type":"system","subtype":"init","session_id":"` + testSessionID + `"}` + "\n" |
| 24 | final := `{"type":"result","subtype":"success","session_id":"` + testSessionID + `","result":"done"}` |
| 25 | for _, events := range []string{ |
| 26 | `{"type":"assistant","message":{"content":[{"type":"text","text":"partial"}]}}`, |
| 27 | strings.Replace(final, testSessionID, "1d2f57e6-64f9-44df-b0b4-43381e33a317", 1), |
| 28 | init + final + "\n" + final, |
| 29 | `{"type":"result","session_id":"` + testSessionID + `","is_error":true,"result":"private upstream diagnostic"}`, |
| 30 | } { |
| 31 | _, err := readResult(strings.NewReader(events), testSessionID, nil, nil, nil) |
| 32 | if err == nil || strings.Contains(err.Error(), "private") { |
| 33 | t.Fatalf("expected a sanitized failure, got %v", err) |
| 34 | } |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestIdentityFailureExplainsFirstLaunch(t *testing.T) { |
| 39 | result, err := readResult(strings.NewReader(`{"type":"system","subtype":"cage_identity_unverified_start"}`), testSessionID, nil, nil, nil) |
| 40 | if result.Started || err == nil || !strings.Contains(err.Error(), "当前 Claude 账号") || strings.Contains(err.Error(), "新建会话") { |
| 41 | t.Fatalf("unexpected first-launch failure: %#v %v", result, err) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | func TestSupervisedInputKeepsConnectionOpenAfterPrompt(t *testing.T) { |
| 46 | const prompt = "a quoted \"argument\"\non another line" |
| 47 | if os.Getenv("CAGE_CLI_SUPERVISOR_FIXTURE") == "1" { |
| 48 | input := bufio.NewReader(os.Stdin) |
| 49 | line, err := input.ReadBytes('\n') |
| 50 | var received string |
| 51 | if err != nil || json.Unmarshal(line, &received) != nil || received != prompt { |
| 52 | os.Exit(2) |
| 53 | } |
| 54 | closed := make(chan struct{}) |
| 55 | go func() { _, _ = input.ReadByte(); close(closed) }() |
| 56 | select { |
| 57 | case <-closed: |
| 58 | os.Exit(3) |
| 59 | case <-time.After(70 * time.Millisecond): |
| 60 | } |
| 61 | fmt.Printf("{\"type\":\"system\",\"subtype\":\"init\",\"session_id\":%q}\n", testSessionID) |
| 62 | fmt.Printf("{\"type\":\"result\",\"subtype\":\"success\",\"session_id\":%q,\"result\":\"ok\"}\n", testSessionID) |
| 63 | os.Exit(0) |
| 64 | } |
| 65 | runner := Runner{SupervisedStdin: true, Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) { |
| 66 | cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestSupervisedInputKeepsConnectionOpenAfterPrompt$") |
| 67 | cmd.Env = append(os.Environ(), "CAGE_CLI_SUPERVISOR_FIXTURE=1") |
| 68 | return cmd, nil |
| 69 | }} |
| 70 | ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) |
| 71 | defer cancel() |
| 72 | result, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: prompt}, nil) |
| 73 | if err != nil || !result.Started || result.Text != "ok" { |
| 74 | t.Fatalf("supervised turn: %#v, %v", result, err) |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestCancelStopsRunningProcess(t *testing.T) { |
| 79 | if os.Getenv("CAGE_CLI_CANCEL_FIXTURE") == "1" { |
| 80 | fmt.Printf("{\"type\":\"stream_event\",\"session_id\":%q,\"event\":{\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"started\"}}}\n", testSessionID) |
| 81 | time.Sleep(30 * time.Second) |
| 82 | os.Exit(0) |
| 83 | } |
| 84 | ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) |
| 85 | defer cancel() |
| 86 | runner := Runner{Command: func(ctx context.Context, _ string, _ []string) (*exec.Cmd, error) { |
| 87 | cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCancelStopsRunningProcess$") |
| 88 | cmd.Env = append(os.Environ(), "CAGE_CLI_CANCEL_FIXTURE=1") |
| 89 | return cmd, nil |
| 90 | }} |
| 91 | _, err := runner.Run(ctx, Turn{Workspace: t.TempDir(), SessionID: testSessionID, Prompt: "synthetic"}, func(string) { cancel() }) |
| 92 | if err != context.Canceled { |
| 93 | t.Fatalf("cancelling a streaming turn returned %v", err) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | func TestRealClaudeCodeWithLocalUpstream(t *testing.T) { |
| 101 | binary := os.Getenv("CAGE_TEST_CLAUDE_CLI") |
| 102 | if binary == "" { |
| 103 | t.Skip("set CAGE_TEST_CLAUDE_CLI to an absolute official Claude Code executable") |
| 104 | } |
| 105 | if !filepath.IsAbs(binary) { |
| 106 | t.Fatal("use an absolute executable path") |
| 107 | } |
| 108 | home := t.TempDir() |
| 109 | project := t.TempDir() |
| 110 | forbidden := filepath.Join(project, "would-write.txt") |
| 111 | var resumed, denied atomic.Bool |
| 112 | upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 113 | if req.URL.Path == "/v1/messages/count_tokens" { |
| 114 | w.Header().Set("Content-Type", "application/json") |
| 115 | fmt.Fprint(w, `{"input_tokens":64}`) |
| 116 | return |
| 117 | } |
| 118 | if req.URL.Path != "/v1/messages" { |
| 119 | http.NotFound(w, req) |
| 120 | return |
| 121 | } |
| 122 | var payload struct { |
| 123 | Model string `json:"model"` |
| 124 | Messages json.RawMessage `json:"messages"` |
| 125 | Stream bool `json:"stream"` |
| 126 | } |
| 127 | if err := json.NewDecoder(req.Body).Decode(&payload); err != nil || !payload.Stream { |
| 128 | http.Error(w, "expected a streaming Messages API request", http.StatusBadRequest) |
| 129 | return |
| 130 | } |
| 131 | history := string(payload.Messages) |
| 132 | w.Header().Set("Content-Type", "text/event-stream") |
| 133 | event := func(kind string, data any) { |
| 134 | body, err := json.Marshal(data) |
| 135 | if err != nil { |
| 136 | t.Errorf("fixture event: %v", err) |
| 137 | return |
| 138 | } |
| 139 | fmt.Fprintf(w, "event: %s\ndata: %s\n\n", kind, body) |
| 140 | w.(http.Flusher).Flush() |
| 141 | } |
| 142 | event("message_start", map[string]any{"type": "message_start", "message": map[string]any{ |
| 143 | "id": "msg_synthetic_cage", "type": "message", "role": "assistant", "model": payload.Model, |
| 144 | "content": []any{}, "stop_reason": nil, "stop_sequence": nil, |
| 145 | "usage": map[string]int{"input_tokens": 64, "output_tokens": 1}, |
| 146 | }}) |
| 147 | stop := "end_turn" |
| 148 | if strings.Contains(history, "write-fixture") && !strings.Contains(history, `"tool_result"`) { |
| 149 | stop = "tool_use" |
| 150 | event("content_block_start", map[string]any{"type": "content_block_start", "index": 0, |
| 151 | "content_block": map[string]any{"type": "tool_use", "id": "toolu_cage", "name": "Bash", "input": map[string]any{}}}) |
| 152 | input, _ := json.Marshal(map[string]string{"command": "printf synthetic > would-write.txt", "description": "Create a synthetic test file"}) |
| 153 | event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, |
| 154 | "delta": map[string]string{"type": "input_json_delta", "partial_json": string(input)}}) |
| 155 | } else { |
| 156 | reply := "first simulated reply" |
| 157 | if strings.Contains(history, "resume-fixture") { |
| 158 | resumed.Store(strings.Contains(history, "first-fixture") && strings.Contains(history, "first simulated reply")) |
| 159 | reply = "second simulated reply" |
| 160 | } |
| 161 | if strings.Contains(history, "write-fixture") { |
| 162 | denied.Store(strings.Contains(history, `"is_error":true`)) |
| 163 | if denied.Load() { |
| 164 | reply = "simulated denial received" |
| 165 | } else { |
| 166 | reply = "simulated write completed" |
| 167 | } |
| 168 | } |
| 169 | event("content_block_start", map[string]any{"type": "content_block_start", "index": 0, |
| 170 | "content_block": map[string]string{"type": "text", "text": ""}}) |
| 171 | event("content_block_delta", map[string]any{"type": "content_block_delta", "index": 0, |
| 172 | "delta": map[string]string{"type": "text_delta", "text": reply}}) |
| 173 | } |
| 174 | event("content_block_stop", map[string]any{"type": "content_block_stop", "index": 0}) |
| 175 | event("message_delta", map[string]any{"type": "message_delta", "delta": map[string]any{"stop_reason": stop, "stop_sequence": nil}, |
| 176 | "usage": map[string]int{"output_tokens": 5}}) |
| 177 | event("message_stop", map[string]string{"type": "message_stop"}) |
| 178 | })) |
| 179 | defer upstream.Close() |
| 180 | supervisor := os.Getenv("CAGE_TEST_CLI_SUPERVISOR") |
| 181 | runner := Runner{SupervisedStdin: supervisor != "", Command: func(ctx context.Context, workspace string, args []string) (*exec.Cmd, error) { |
| 182 | command := append([]string{binary, "--bare"}, args...) |
| 183 | if supervisor != "" { |
| 184 | python, err := exec.LookPath("python3") |
| 185 | if err != nil { |
| 186 | return nil, err |
| 187 | } |
| 188 | command = append([]string{python, "-I", supervisor, workspace}, command...) |
| 189 | } |
| 190 | cmd := exec.CommandContext(ctx, command[0], command[1:]...) |
| 191 | if supervisor != "" { |
| 192 | |
| 193 | |
| 194 | cmd.Cancel = func() error { return nil } |
| 195 | } |
| 196 | cmd.Dir = workspace |
| 197 | cmd.Env = []string{ |
| 198 | "HOME=" + home, "USERPROFILE=" + home, "CLAUDE_CONFIG_DIR=" + filepath.Join(home, "config"), |
| 199 | "PATH=" + filepath.Dir(binary) + string(os.PathListSeparator) + "/usr/bin" + string(os.PathListSeparator) + "/bin", |
| 200 | "ANTHROPIC_BASE_URL=" + upstream.URL, "ANTHROPIC_API_KEY=sk-ant-fixture-only", |
| 201 | "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "DISABLE_AUTOUPDATER=1", |
| 202 | "HTTPS_PROXY=http://127.0.0.1:1", "HTTP_PROXY=http://127.0.0.1:1", "NO_PROXY=127.0.0.1,localhost", |
| 203 | } |
| 204 | if systemRoot := os.Getenv("SystemRoot"); systemRoot != "" { |
| 205 | cmd.Env = append(cmd.Env, "SystemRoot="+systemRoot) |
| 206 | } |
| 207 | return cmd, nil |
| 208 | }} |
| 209 | ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) |
| 210 | defer cancel() |
| 211 | run := func(id, prompt, want string, resume bool) Result { |
| 212 | t.Helper() |
| 213 | var live strings.Builder |
| 214 | result, err := runner.Run(ctx, Turn{project, id, prompt, resume}, func(delta string) { live.WriteString(delta) }) |
| 215 | if err != nil || !result.Started || result.Text != want || live.String() != want { |
| 216 | t.Fatalf("turn %s: result=%q live=%q err=%v", prompt, result.Text, live.String(), err) |
| 217 | } |
| 218 | return result |
| 219 | } |
| 220 | run(testSessionID, "first-fixture", "first simulated reply", false) |
| 221 | run(testSessionID, "resume-fixture", "second simulated reply", true) |
| 222 | if !resumed.Load() { |
| 223 | t.Fatal("resumed CLI did not send the first exchange to the local provider") |
| 224 | } |
| 225 | result := run("93b18ece-8eab-4c7e-b970-c3652252b7c4", "write-fixture", "simulated denial received", false) |
| 226 | if !denied.Load() || !slices.Contains(result.DeniedTools, "Bash") { |
| 227 | t.Fatalf("missing permission denial: upstream observed denial=%t, result=%#v", denied.Load(), result) |
| 228 | } |
| 229 | if _, err := os.Stat(forbidden); !os.IsNotExist(err) { |
| 230 | t.Fatalf("denied tool changed the workspace: %v", err) |
| 231 | } |
| 232 | var approvals atomic.Int32 |
| 233 | answer := func(allow bool) func(context.Context, PermissionRequest) bool { |
| 234 | return func(_ context.Context, request PermissionRequest) bool { |
| 235 | approvals.Add(1) |
| 236 | var proposed struct{ Command string } |
| 237 | if request.Tool != "Bash" || json.Unmarshal(request.Input, &proposed) != nil || proposed.Command != "printf synthetic > would-write.txt" { |
| 238 | t.Errorf("unexpected approval request: %s, %s", request.Tool, request.Input) |
| 239 | return false |
| 240 | } |
| 241 | if _, err := os.Stat(forbidden); !os.IsNotExist(err) { |
| 242 | t.Errorf("command ran before the decision: %v", err) |
| 243 | return false |
| 244 | } |
| 245 | |
| 246 | |
| 247 | clear(request.Input) |
| 248 | return allow |
| 249 | } |
| 250 | } |
| 251 | runner.Approve = answer(false) |
| 252 | run("24816c82-cf57-4ec3-b8c0-05dc70614440", "write-fixture", "simulated denial received", false) |
| 253 | pending, stop := context.WithCancel(ctx) |
| 254 | defer stop() |
| 255 | runner.Approve = func(approvalCtx context.Context, _ PermissionRequest) bool { |
| 256 | stop() |
| 257 | <-approvalCtx.Done() |
| 258 | return true |
| 259 | } |
| 260 | result, err := runner.Run(pending, Turn{project, "0ca69e7b-2661-4b81-b966-f2589547933c", "write-fixture", false}, nil) |
| 261 | if err != context.Canceled || !result.Started { |
| 262 | t.Fatalf("cancel during pending tool approval: %#v, %v", result, err) |
| 263 | } |
| 264 | runner.Approve = answer(true) |
| 265 | run("8c0d77d3-cb3e-43b2-9114-62cb05c5ebc4", "write-fixture", "simulated write completed", false) |
| 266 | bytes, err := os.ReadFile(forbidden) |
| 267 | if err != nil || string(bytes) != "synthetic" || approvals.Load() != 2 { |
| 268 | t.Fatalf("expected one approved write after exactly two decisions: %q, %v, decisions=%d", bytes, err, approvals.Load()) |
| 269 | } |
| 270 | } |