miaopanel
1package ai
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "path/filepath"
11 "strings"
12 "sync/atomic"
13 "testing"
14
15 "github.com/miaopanel/miaopanel/internal/config"
16 "github.com/miaopanel/miaopanel/internal/store"
17)
18
19// fakeProvider answers every completion with the given tool call first, then
20// with a short text once a tool result is present in the history.
21func fakeProvider(t *testing.T, toolName string) (*httptest.Server, *int32) {
22 t.Helper()
23 var calls int32
24 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
25 raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
26 var req struct {
27 Messages []ChatMessage `json:"messages"`
28 }
29 _ = json.Unmarshal(raw, &req)
30 hasToolResult := false
31 for _, m := range req.Messages {
32 if m.Role == "tool" {
33 hasToolResult = true
34 break
35 }
36 }
37 w.Header().Set("Content-Type", "text/event-stream")
38 if hasToolResult {
39 fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"已完成\"}}]}\n\ndata: [DONE]\n\n")
40 return
41 }
42 atomic.AddInt32(&calls, 1)
43 chunk := map[string]any{
44 "choices": []any{map[string]any{
45 "delta": map[string]any{
46 "tool_calls": []any{map[string]any{
47 "index": 0, "id": "call_1", "type": "function",
48 "function": map[string]any{"name": toolName, "arguments": "{}"},
49 }},
50 },
51 }},
52 }
53 line, _ := json.Marshal(chunk)
54 fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", line)
55 }))
56 t.Cleanup(srv.Close)
57 return srv, &calls
58}
59
60func newTestService(t *testing.T, baseURL string) (*Service, *store.Store) {
61 t.Helper()
62 cfg := config.Default()
63 cfg.DataDir = t.TempDir()
64 db, err := store.Open(filepath.Join(cfg.DataDir, "test.db"))
65 if err != nil {
66 t.Fatal(err)
67 }
68 t.Cleanup(func() { _ = db.Close() })
69 svc := New(cfg, db, nil, nil, nil, nil, nil, nil, nil, "test")
70 if err := svc.SaveSettings(context.Background(), Settings{
71 Enabled: true, BaseURL: baseURL + "/v1", APIKey: "test-key",
72 Model: "test-model", Temperature: 0.2,
73 }); err != nil {
74 t.Fatal(err)
75 }
76 svc.provider = &Provider{client: &http.Client{}}
77 return svc, db
78}
79
80func noopEmit(string, any) error { return nil }
81
82func TestReadToolRunsWithoutApproval(t *testing.T) {
83 srv, calls := fakeProvider(t, "test_ping")
84 svc, db := newTestService(t, srv.URL)
85 var executed int32
86 svc.Registry().Register(Tool{
87 Name: "test_ping", Description: "test", Parameters: objectSchema(map[string]any{}),
88 Risk: RiskRead, Summary: func(map[string]any) string { return "ping" },
89 Run: func(context.Context, map[string]any) (string, error) {
90 atomic.AddInt32(&executed, 1)
91 return "pong", nil
92 },
93 })
94
95 sessionID, err := svc.Chat(context.Background(), 1, "", "测试只读工具", noopEmit)
96 if err != nil {
97 t.Fatal(err)
98 }
99 if atomic.LoadInt32(&executed) != 1 {
100 t.Fatalf("read tool executions = %d", executed)
101 }
102 if atomic.LoadInt32(calls) != 1 {
103 t.Fatalf("provider tool-call rounds = %d", calls)
104 }
105 messages, err := db.ListAIMessages(context.Background(), sessionID, 0, 100)
106 if err != nil {
107 t.Fatal(err)
108 }
109 if len(messages) != 4 {
110 t.Fatalf("messages = %d, want user/assistant/tool/assistant", len(messages))
111 }
112 pending, err := db.PendingAIActions(context.Background(), sessionID)
113 if err != nil {
114 t.Fatal(err)
115 }
116 if len(pending) != 0 {
117 t.Fatalf("read tool created %d pending actions", len(pending))
118 }
119}
120
121func TestWriteToolRequiresApprovalAndRunsOnce(t *testing.T) {
122 srv, _ := fakeProvider(t, "test_restart")
123 svc, db := newTestService(t, srv.URL)
124 var executed int32
125 svc.Registry().Register(Tool{
126 Name: "test_restart", Description: "test write", Parameters: objectSchema(map[string]any{}),
127 Risk: RiskWrite, Summary: func(map[string]any) string { return "重启测试服务" },
128 Run: func(context.Context, map[string]any) (string, error) {
129 atomic.AddInt32(&executed, 1)
130 return "restarted", nil
131 },
132 })
133
134 sessionID, err := svc.Chat(context.Background(), 1, "", "重启测试服务", noopEmit)
135 if err != nil {
136 t.Fatal(err)
137 }
138 pending, err := db.PendingAIActions(context.Background(), sessionID)
139 if err != nil {
140 t.Fatal(err)
141 }
142 if len(pending) != 1 {
143 t.Fatalf("pending actions = %d", len(pending))
144 }
145 if atomic.LoadInt32(&executed) != 0 {
146 t.Fatalf("write tool ran before approval")
147 }
148
149 if _, err := svc.Decide(context.Background(), 1, pending[0].ID, true, noopEmit); err != nil {
150 t.Fatal(err)
151 }
152 if atomic.LoadInt32(&executed) != 1 {
153 t.Fatalf("write tool executions = %d", executed)
154 }
155 action, err := db.AIActionByID(context.Background(), pending[0].ID)
156 if err != nil {
157 t.Fatal(err)
158 }
159 if action.Status != "done" || !strings.Contains(action.Result, "restarted") {
160 t.Fatalf("action = %+v", action)
161 }
162 // A second decision on the same action must be refused.
163 if _, err := svc.Decide(context.Background(), 1, pending[0].ID, true, noopEmit); err == nil {
164 t.Fatal("second approval should fail")
165 }
166}
167
168func TestOnlyOneApprovalPerAssistantTurn(t *testing.T) {
169 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
170 raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
171 var req struct {
172 Messages []ChatMessage `json:"messages"`
173 }
174 _ = json.Unmarshal(raw, &req)
175 hasTool := false
176 for _, m := range req.Messages {
177 if m.Role == "tool" {
178 hasTool = true
179 break
180 }
181 }
182 w.Header().Set("Content-Type", "text/event-stream")
183 if hasTool {
184 fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"完成\"}}]}\n\ndata: [DONE]\n\n")
185 return
186 }
187 chunk := map[string]any{
188 "choices": []any{map[string]any{
189 "delta": map[string]any{
190 "tool_calls": []any{
191 map[string]any{
192 "index": 0, "id": "call_a", "type": "function",
193 "function": map[string]any{"name": "test_restart", "arguments": "{}"},
194 },
195 map[string]any{
196 "index": 1, "id": "call_b", "type": "function",
197 "function": map[string]any{"name": "test_restart", "arguments": "{}"},
198 },
199 },
200 },
201 }},
202 }
203 line, _ := json.Marshal(chunk)
204 fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", line)
205 }))
206 t.Cleanup(srv.Close)
207 svc, db := newTestService(t, srv.URL)
208 svc.Registry().Register(Tool{
209 Name: "test_restart", Description: "test", Parameters: objectSchema(map[string]any{}),
210 Risk: RiskWrite, Summary: func(map[string]any) string { return "重启测试服务" },
211 Run: func(context.Context, map[string]any) (string, error) { return "ok", nil },
212 })
213
214 sessionID, err := svc.Chat(context.Background(), 1, "", "重启测试服务", noopEmit)
215 if err != nil {
216 t.Fatal(err)
217 }
218 pending, err := db.PendingAIActions(context.Background(), sessionID)
219 if err != nil {
220 t.Fatal(err)
221 }
222 if len(pending) != 1 {
223 t.Fatalf("pending actions = %d, want 1", len(pending))
224 }
225 messages, err := db.ListAIMessages(context.Background(), sessionID, 0, 100)
226 if err != nil {
227 t.Fatal(err)
228 }
229 skipped := 0
230 for _, m := range messages {
231 if m.Role == "tool" && m.Status == "skipped" {
232 skipped++
233 }
234 }
235 if skipped != 1 {
236 t.Fatalf("skipped messages = %d, want 1", skipped)
237 }
238}
239
240func TestInterpretTerminalUsesCommandOutput(t *testing.T) {
241 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
242 w.Header().Set("Content-Type", "text/event-stream")
243 fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"CPU 空闲 95.2%,负载很低。\"}}]}\n\ndata: [DONE]\n\n")
244 }))
245 t.Cleanup(srv.Close)
246 svc, _ := newTestService(t, srv.URL)
247 suggestion, err := svc.InterpretTerminal(context.Background(), "看看 CPU 占用率", "top -bn1", "%Cpu(s): 95.2 id")
248 if err != nil {
249 t.Fatal(err)
250 }
251 if !strings.Contains(suggestion.Reply, "95.2") {
252 t.Fatalf("reply = %q", suggestion.Reply)
253 }
254}
255
256func TestTerminalSuggestionSanitizesUnsafeCommands(t *testing.T) {
257 s := parseTerminalSuggestion(`{"reply":"危险","commands":[{"command":"rm -rf /","note":"x"},{"command":"ls -al","note":"y"}]}`)
258 sanitizeSuggestion(s)
259 if len(s.Commands) != 1 || s.Commands[0].Risk != "danger" {
260 t.Fatalf("risk = %+v", s.Commands)
261 }
262
263 s = parseTerminalSuggestion("```json\n{\"reply\":\"你好\",\"commands\":[]}\n```")
264 if s.Reply != "你好" || len(s.Commands) != 0 {
265 t.Fatalf("fenced parse = %+v", s)
266 }
267}