package ai import ( "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "path/filepath" "strings" "sync/atomic" "testing" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" ) // fakeProvider answers every completion with the given tool call first, then // with a short text once a tool result is present in the history. func fakeProvider(t *testing.T, toolName string) (*httptest.Server, *int32) { t.Helper() var calls int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) var req struct { Messages []ChatMessage `json:"messages"` } _ = json.Unmarshal(raw, &req) hasToolResult := false for _, m := range req.Messages { if m.Role == "tool" { hasToolResult = true break } } w.Header().Set("Content-Type", "text/event-stream") if hasToolResult { fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"已完成\"}}]}\n\ndata: [DONE]\n\n") return } atomic.AddInt32(&calls, 1) chunk := map[string]any{ "choices": []any{map[string]any{ "delta": map[string]any{ "tool_calls": []any{map[string]any{ "index": 0, "id": "call_1", "type": "function", "function": map[string]any{"name": toolName, "arguments": "{}"}, }}, }, }}, } line, _ := json.Marshal(chunk) fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", line) })) t.Cleanup(srv.Close) return srv, &calls } func newTestService(t *testing.T, baseURL string) (*Service, *store.Store) { t.Helper() cfg := config.Default() cfg.DataDir = t.TempDir() db, err := store.Open(filepath.Join(cfg.DataDir, "test.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = db.Close() }) svc := New(cfg, db, nil, nil, nil, nil, nil, nil, nil, "test") if err := svc.SaveSettings(context.Background(), Settings{ Enabled: true, BaseURL: baseURL + "/v1", APIKey: "test-key", Model: "test-model", Temperature: 0.2, }); err != nil { t.Fatal(err) } svc.provider = &Provider{client: &http.Client{}} return svc, db } func noopEmit(string, any) error { return nil } func TestReadToolRunsWithoutApproval(t *testing.T) { srv, calls := fakeProvider(t, "test_ping") svc, db := newTestService(t, srv.URL) var executed int32 svc.Registry().Register(Tool{ Name: "test_ping", Description: "test", Parameters: objectSchema(map[string]any{}), Risk: RiskRead, Summary: func(map[string]any) string { return "ping" }, Run: func(context.Context, map[string]any) (string, error) { atomic.AddInt32(&executed, 1) return "pong", nil }, }) sessionID, err := svc.Chat(context.Background(), 1, "", "测试只读工具", noopEmit) if err != nil { t.Fatal(err) } if atomic.LoadInt32(&executed) != 1 { t.Fatalf("read tool executions = %d", executed) } if atomic.LoadInt32(calls) != 1 { t.Fatalf("provider tool-call rounds = %d", calls) } messages, err := db.ListAIMessages(context.Background(), sessionID, 0, 100) if err != nil { t.Fatal(err) } if len(messages) != 4 { t.Fatalf("messages = %d, want user/assistant/tool/assistant", len(messages)) } pending, err := db.PendingAIActions(context.Background(), sessionID) if err != nil { t.Fatal(err) } if len(pending) != 0 { t.Fatalf("read tool created %d pending actions", len(pending)) } } func TestWriteToolRequiresApprovalAndRunsOnce(t *testing.T) { srv, _ := fakeProvider(t, "test_restart") svc, db := newTestService(t, srv.URL) var executed int32 svc.Registry().Register(Tool{ Name: "test_restart", Description: "test write", Parameters: objectSchema(map[string]any{}), Risk: RiskWrite, Summary: func(map[string]any) string { return "重启测试服务" }, Run: func(context.Context, map[string]any) (string, error) { atomic.AddInt32(&executed, 1) return "restarted", nil }, }) sessionID, err := svc.Chat(context.Background(), 1, "", "重启测试服务", noopEmit) if err != nil { t.Fatal(err) } pending, err := db.PendingAIActions(context.Background(), sessionID) if err != nil { t.Fatal(err) } if len(pending) != 1 { t.Fatalf("pending actions = %d", len(pending)) } if atomic.LoadInt32(&executed) != 0 { t.Fatalf("write tool ran before approval") } if _, err := svc.Decide(context.Background(), 1, pending[0].ID, true, noopEmit); err != nil { t.Fatal(err) } if atomic.LoadInt32(&executed) != 1 { t.Fatalf("write tool executions = %d", executed) } action, err := db.AIActionByID(context.Background(), pending[0].ID) if err != nil { t.Fatal(err) } if action.Status != "done" || !strings.Contains(action.Result, "restarted") { t.Fatalf("action = %+v", action) } // A second decision on the same action must be refused. if _, err := svc.Decide(context.Background(), 1, pending[0].ID, true, noopEmit); err == nil { t.Fatal("second approval should fail") } } func TestOnlyOneApprovalPerAssistantTurn(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) var req struct { Messages []ChatMessage `json:"messages"` } _ = json.Unmarshal(raw, &req) hasTool := false for _, m := range req.Messages { if m.Role == "tool" { hasTool = true break } } w.Header().Set("Content-Type", "text/event-stream") if hasTool { fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"完成\"}}]}\n\ndata: [DONE]\n\n") return } chunk := map[string]any{ "choices": []any{map[string]any{ "delta": map[string]any{ "tool_calls": []any{ map[string]any{ "index": 0, "id": "call_a", "type": "function", "function": map[string]any{"name": "test_restart", "arguments": "{}"}, }, map[string]any{ "index": 1, "id": "call_b", "type": "function", "function": map[string]any{"name": "test_restart", "arguments": "{}"}, }, }, }, }}, } line, _ := json.Marshal(chunk) fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", line) })) t.Cleanup(srv.Close) svc, db := newTestService(t, srv.URL) svc.Registry().Register(Tool{ Name: "test_restart", Description: "test", Parameters: objectSchema(map[string]any{}), Risk: RiskWrite, Summary: func(map[string]any) string { return "重启测试服务" }, Run: func(context.Context, map[string]any) (string, error) { return "ok", nil }, }) sessionID, err := svc.Chat(context.Background(), 1, "", "重启测试服务", noopEmit) if err != nil { t.Fatal(err) } pending, err := db.PendingAIActions(context.Background(), sessionID) if err != nil { t.Fatal(err) } if len(pending) != 1 { t.Fatalf("pending actions = %d, want 1", len(pending)) } messages, err := db.ListAIMessages(context.Background(), sessionID, 0, 100) if err != nil { t.Fatal(err) } skipped := 0 for _, m := range messages { if m.Role == "tool" && m.Status == "skipped" { skipped++ } } if skipped != 1 { t.Fatalf("skipped messages = %d, want 1", skipped) } } func TestInterpretTerminalUsesCommandOutput(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/event-stream") fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"CPU 空闲 95.2%,负载很低。\"}}]}\n\ndata: [DONE]\n\n") })) t.Cleanup(srv.Close) svc, _ := newTestService(t, srv.URL) suggestion, err := svc.InterpretTerminal(context.Background(), "看看 CPU 占用率", "top -bn1", "%Cpu(s): 95.2 id") if err != nil { t.Fatal(err) } if !strings.Contains(suggestion.Reply, "95.2") { t.Fatalf("reply = %q", suggestion.Reply) } } func TestTerminalSuggestionSanitizesUnsafeCommands(t *testing.T) { s := parseTerminalSuggestion(`{"reply":"危险","commands":[{"command":"rm -rf /","note":"x"},{"command":"ls -al","note":"y"}]}`) sanitizeSuggestion(s) if len(s.Commands) != 1 || s.Commands[0].Risk != "danger" { t.Fatalf("risk = %+v", s.Commands) } s = parseTerminalSuggestion("```json\n{\"reply\":\"你好\",\"commands\":[]}\n```") if s.Reply != "你好" || len(s.Commands) != 0 { t.Fatalf("fenced parse = %+v", s) } }