返回 DeepSeek-Reasonix
bot_runtime_app_test.go
根目录 / desktop / bot_runtime_app_test.go
1 package main
2
3 import (
4 "errors"
5 "io"
6 "log/slog"
7 "os"
8 "path/filepath"
9 "strings"
10 "testing"
11
12 "reasonix/internal/bot"
13 "reasonix/internal/botruntime"
14 "reasonix/internal/config"
15 )
16
17 func TestDesktopBotRuntimePlanStartsSavedConnections(t *testing.T) {
18 cfg := config.Default()
19 cfg.Bot.Enabled = true
20 cfg.Bot.Allowlist.Enabled = true
21 cfg.Bot.Allowlist.FeishuUsers = []string{"ou-installer"}
22 cfg.Bot.Allowlist.WeixinUsers = []string{"wx-user"}
23 cfg.Bot.Connections = []config.BotConnectionConfig{
24 {ID: "feishu-feishu", Provider: "feishu", Domain: "feishu", Enabled: true},
25 {ID: "feishu-lark", Provider: "feishu", Domain: "lark", Enabled: true},
26 {ID: "weixin-weixin", Provider: "weixin", Domain: "weixin", Enabled: true},
27 }
28
29 plan := desktopBotRuntimePlan(cfg)
30 if !plan.Start {
31 t.Fatalf("plan = %+v, want start", plan)
32 }
33 if !plan.Enabled[bot.PlatformFeishu] || !plan.Enabled[bot.PlatformWeixin] {
34 t.Fatalf("enabled = %+v, want feishu/lark and weixin platforms", plan.Enabled)
35 }
36 }
37
38 func TestDesktopBotRuntimePlanBlocksWithoutAllowlist(t *testing.T) {
39 cfg := config.Default()
40 cfg.Bot.Enabled = true
41 cfg.Bot.Allowlist.Enabled = true
42 cfg.Bot.Pairing.Enabled = false
43 cfg.Bot.Connections = []config.BotConnectionConfig{
44 {ID: "feishu-lark", Provider: "feishu", Domain: "lark", Enabled: true},
45 }
46
47 plan := desktopBotRuntimePlan(cfg)
48 if plan.Start || plan.Status != "blocked" {
49 t.Fatalf("plan = %+v, want blocked without allowlist", plan)
50 }
51 }
52
53 func TestDesktopBotRuntimePlanStartsWithPairing(t *testing.T) {
54 cfg := config.Default()
55 cfg.Bot.Enabled = true
56 cfg.Bot.Allowlist.Enabled = true
57 cfg.Bot.Pairing.Enabled = true
58 cfg.Bot.Connections = []config.BotConnectionConfig{
59 {ID: "feishu-lark", Provider: "feishu", Domain: "lark", Enabled: true},
60 }
61
62 plan := desktopBotRuntimePlan(cfg)
63 if !plan.Start {
64 t.Fatalf("plan = %+v, want start with pairing enabled", plan)
65 }
66 }
67
68 func TestDesktopBotChannelsWithLegacyQQConfig(t *testing.T) {
69 channels, connectionChannels := desktopBotChannelsWithLegacyQQ(config.QQBotConfig{
70 Model: "qq-model",
71 ToolApprovalMode: "auto",
72 WorkspaceRoot: "/tmp/qq-project",
73 }, nil, nil)
74
75 channel, ok := channels[bot.PlatformQQ]
76 if !ok {
77 t.Fatalf("platform QQ channel missing: %+v", channels)
78 }
79 if channel.Model != "qq-model" || channel.ToolApprovalMode != "workspace-write" || channel.WorkspaceRoot != "/tmp/qq-project" {
80 t.Fatalf("platform channel = %+v, want QQ-specific runtime fields", channel)
81 }
82 connectionChannel, ok := connectionChannels["qq"]
83 if !ok {
84 t.Fatalf("connection QQ channel missing: %+v", connectionChannels)
85 }
86 if connectionChannel.Model != "qq-model" || connectionChannel.ToolApprovalMode != "workspace-write" || connectionChannel.WorkspaceRoot != "/tmp/qq-project" {
87 t.Fatalf("connection channel = %+v, want QQ-specific runtime fields", connectionChannel)
88 }
89 }
90
91 func TestDesktopBotRuntimePlanStopsWhenBotDisabled(t *testing.T) {
92 cfg := config.Default()
93 cfg.Bot.Enabled = false
94 cfg.Bot.Allowlist.FeishuUsers = []string{"ou-installer"}
95 cfg.Bot.Connections = []config.BotConnectionConfig{
96 {ID: "feishu-lark", Provider: "feishu", Domain: "lark", Enabled: true},
97 }
98
99 plan := desktopBotRuntimePlan(cfg)
100 if plan.Start || plan.Status != "stopped" {
101 t.Fatalf("plan = %+v, want stopped when disabled", plan)
102 }
103 }
104
105 func TestDesktopBotRuntimeForwardTargetsDeduplicatesMappedChats(t *testing.T) {
106 cfg := config.Default()
107 cfg.Bot.Connections = []config.BotConnectionConfig{{
108 ID: "feishu-lark",
109 Provider: "feishu",
110 Domain: "lark",
111 Enabled: true,
112 SessionMappings: []config.BotConnectionSessionMapping{
113 {RemoteID: "oc-group-1", ChatType: string(bot.ChatGroup), UserID: "ou-user-1"},
114 {RemoteID: "oc-group-1", ChatType: string(bot.ChatGroup), UserID: "ou-user-2"},
115 {RemoteID: "oc-dm-1", ChatType: string(bot.ChatDM), UserID: "ou-user-1"},
116 },
117 }}
118
119 targets := newDesktopBotRuntime().ForwardTargets(cfg)
120 if len(targets) != 2 {
121 t.Fatalf("targets = %+v, want one group target plus one dm target", targets)
122 }
123 seen := map[string]bool{}
124 for _, target := range targets {
125 key := target.ConnID + "|" + target.Domain + "|" + target.ChatID + "|" + string(target.ChatType)
126 if seen[key] {
127 t.Fatalf("duplicate target %q in %+v", key, targets)
128 }
129 seen[key] = true
130 }
131 if !seen["feishu-lark|lark|oc-group-1|group"] || !seen["feishu-lark|lark|oc-dm-1|dm"] {
132 t.Fatalf("targets = %+v, want group and dm targets", targets)
133 }
134 }
135
136 func TestDesktopBotRuntimeConfigUsesUserBotSettings(t *testing.T) {
137 isolateDesktopUserDirs(t)
138
139 userCfg := config.LoadForEdit(config.UserConfigPath())
140 userCfg.Bot.Enabled = true
141 userCfg.Bot.Allowlist.Enabled = true
142 userCfg.Bot.Allowlist.FeishuUsers = []string{"ou-installer"}
143 userCfg.Bot.Connections = []config.BotConnectionConfig{
144 {ID: "feishu-lark", Provider: "feishu", Domain: "lark", Enabled: true, Status: "connected"},
145 }
146 if err := userCfg.SaveTo(config.UserConfigPath()); err != nil {
147 t.Fatalf("save user config: %v", err)
148 }
149
150 project := robustTempDir(t)
151 if err := os.WriteFile(filepath.Join(project, "reasonix.toml"), []byte(`
152 [bot]
153 enabled = false
154 `), 0o644); err != nil {
155 t.Fatalf("write project config: %v", err)
156 }
157
158 orig, _ := os.Getwd()
159 defer func() { _ = os.Chdir(orig) }()
160 if err := os.Chdir(project); err != nil {
161 t.Fatalf("chdir project: %v", err)
162 }
163
164 got, err := NewApp().loadDesktopBotConfig()
165 if err != nil {
166 t.Fatalf("load desktop bot config: %v", err)
167 }
168 plan := desktopBotRuntimePlan(got)
169 if !plan.Start || !plan.Enabled[bot.PlatformFeishu] {
170 t.Fatalf("desktop runtime plan = %+v, want user-level Lark connection to start", plan)
171 }
172 }
173
174 func TestDesktopBotRuntimeConfigLoadsAllSavedCredentialsAfterRestart(t *testing.T) {
175 isolateDesktopUserDirs(t)
176 t.Cleanup(func() {
177 _ = os.Unsetenv("FEISHU_BOT_APP_SECRET")
178 _ = os.Unsetenv("LARK_BOT_APP_SECRET")
179 })
180
181 userCfg := config.Default()
182 userCfg.Bot.Enabled = true
183 userCfg.Bot.Allowlist.Enabled = true
184 userCfg.Bot.Allowlist.FeishuUsers = []string{"ou-feishu-installer", "ou-lark-installer"}
185 userCfg.Bot.Allowlist.WeixinUsers = []string{"wx-installer"}
186 userCfg.Bot.Feishu.Enabled = true
187 userCfg.Bot.Weixin.Enabled = true
188 userCfg.Bot.Weixin.AccountID = "weixin-account"
189 userCfg.Bot.Weixin.TokenEnv = "WEIXIN_BOT_TOKEN"
190 userCfg.Bot.Connections = []config.BotConnectionConfig{
191 {
192 ID: "feishu-feishu",
193 Provider: "feishu",
194 Domain: "feishu",
195 Enabled: true,
196 Status: "connected",
197 Credential: config.BotConnectionCredential{
198 AppID: "cli-feishu",
199 AppSecretEnv: "FEISHU_BOT_APP_SECRET",
200 },
201 },
202 {
203 ID: "feishu-lark",
204 Provider: "feishu",
205 Domain: "lark",
206 Enabled: true,
207 Status: "connected",
208 Credential: config.BotConnectionCredential{
209 AppID: "cli-lark",
210 AppSecretEnv: "LARK_BOT_APP_SECRET",
211 },
212 },
213 {
214 ID: "weixin-weixin",
215 Provider: "weixin",
216 Domain: "weixin",
217 Enabled: true,
218 Status: "connected",
219 Credential: config.BotConnectionCredential{
220 AccountID: "weixin-account",
221 TokenEnv: "WEIXIN_BOT_TOKEN",
222 },
223 },
224 }
225 if err := userCfg.SaveTo(config.UserConfigPath()); err != nil {
226 t.Fatalf("save user config: %v", err)
227 }
228 if err := os.MkdirAll(filepath.Dir(config.UserCredentialsPath()), 0o755); err != nil {
229 t.Fatalf("create credentials dir: %v", err)
230 }
231 if err := os.WriteFile(config.UserCredentialsPath(), []byte("FEISHU_BOT_APP_SECRET=feishu-secret\nLARK_BOT_APP_SECRET=lark-secret\n"), 0o600); err != nil {
232 t.Fatalf("write credentials: %v", err)
233 }
234 weixinAccountPath := filepath.Join(config.MemoryUserDir(), "weixin", "accounts", "weixin-account.json")
235 if err := os.MkdirAll(filepath.Dir(weixinAccountPath), 0o700); err != nil {
236 t.Fatalf("create weixin account dir: %v", err)
237 }
238 if err := os.WriteFile(weixinAccountPath, []byte(`{"token":"weixin-token","base_url":"https://ilinkai.weixin.qq.com","user_id":"wx-installer"}`), 0o600); err != nil {
239 t.Fatalf("write weixin account: %v", err)
240 }
241 _ = os.Unsetenv("FEISHU_BOT_APP_SECRET")
242 _ = os.Unsetenv("LARK_BOT_APP_SECRET")
243
244 got, err := NewApp().loadDesktopBotConfig()
245 if err != nil {
246 t.Fatalf("load desktop bot config: %v", err)
247 }
248 views := botConnectionViews(got.Bot.Connections)
249 if len(views) != 3 {
250 t.Fatalf("connection views = %+v, want Feishu, Lark, and Weixin", views)
251 }
252 for _, view := range views {
253 if !view.Credential.SecretSet {
254 t.Fatalf("connection %s credential = %+v, want saved credential loaded after restart", view.ID, view.Credential)
255 }
256 }
257 plan := desktopBotRuntimePlan(got)
258 if !plan.Start || !plan.Enabled[bot.PlatformFeishu] || !plan.Enabled[bot.PlatformWeixin] {
259 t.Fatalf("desktop runtime plan = %+v, want saved Feishu/Lark/Weixin connections to start", plan)
260 }
261 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
262 bindings := botruntime.AdapterBindings(got, plan.Enabled, nil, logger)
263 if len(bindings) != 3 {
264 t.Fatalf("adapter bindings = %+v, want one per saved connection", bindings)
265 }
266 }
267
268 // A checkout's [bot] never reaches the bot runtime or the user's config, with
269 // or without a user config of its own.
270 func TestDesktopBotRuntimeIgnoresProjectBotSettings(t *testing.T) {
271 for _, withUser := range []bool{false, true} {
272 isolateDesktopUserDirs(t)
273 if withUser {
274 if err := config.Default().SaveTo(config.UserConfigPath()); err != nil {
275 t.Fatalf("save user config: %v", err)
276 }
277 }
278 project := robustTempDir(t)
279 if err := os.WriteFile(filepath.Join(project, "reasonix.toml"), []byte(`
280 [bot]
281 enabled = true
282
283 [bot.allowlist]
284 enabled = true
285 feishu_users = ["ou-legacy"]
286
287 [[bot.connections]]
288 id = "feishu-lark"
289 provider = "feishu"
290 domain = "lark"
291 enabled = true
292 status = "connected"
293 `), 0o644); err != nil {
294 t.Fatalf("write project config: %v", err)
295 }
296 t.Chdir(project)
297 app := NewApp()
298 got, err := app.loadDesktopBotConfig()
299 if err != nil {
300 t.Fatalf("load desktop bot config: %v", err)
301 }
302 if got.Bot.Enabled || len(got.Bot.Connections) != 0 {
303 t.Fatalf("desktop bot config = %+v, want the checkout's [bot] ignored", got.Bot)
304 }
305 if err := app.applyConfigOnly(func(*config.Config) error { return nil }); err != nil {
306 t.Fatalf("applyConfigOnly: %v", err)
307 }
308 if persisted := config.LoadForEdit(config.UserConfigPath()); persisted.Bot.Enabled || len(persisted.Bot.Connections) != 0 {
309 t.Fatalf("user config took the checkout's [bot]: %+v", persisted.Bot)
310 }
311 }
312 }
313
314 func TestDesktopBotRuntimeKeepsUserBotSettingsBesideAProjectBot(t *testing.T) {
315 isolateDesktopUserDirs(t)
316
317 userCfg := config.Default()
318 userCfg.Bot.Enabled = true
319 userCfg.Bot.Allowlist.Enabled = true
320 userCfg.Bot.Allowlist.WeixinUsers = []string{"wx-user"}
321 userCfg.Bot.Connections = []config.BotConnectionConfig{
322 {ID: "weixin-weixin", Provider: "weixin", Domain: "weixin", Enabled: true, Status: "connected"},
323 }
324 if err := userCfg.SaveTo(config.UserConfigPath()); err != nil {
325 t.Fatalf("save user config: %v", err)
326 }
327
328 project := robustTempDir(t)
329 if err := os.WriteFile(filepath.Join(project, "reasonix.toml"), []byte(`
330 [bot]
331 enabled = true
332
333 [bot.allowlist]
334 enabled = true
335 feishu_users = ["ou-legacy"]
336
337 [[bot.connections]]
338 id = "feishu-lark"
339 provider = "feishu"
340 domain = "lark"
341 enabled = true
342 status = "connected"
343 `), 0o644); err != nil {
344 t.Fatalf("write project config: %v", err)
345 }
346
347 orig, _ := os.Getwd()
348 defer func() { _ = os.Chdir(orig) }()
349 if err := os.Chdir(project); err != nil {
350 t.Fatalf("chdir project: %v", err)
351 }
352
353 got, err := NewApp().loadDesktopBotConfig()
354 if err != nil {
355 t.Fatalf("load desktop bot config: %v", err)
356 }
357 if len(got.Bot.Connections) != 1 || got.Bot.Connections[0].ID != "weixin-weixin" {
358 t.Fatalf("desktop bot config = %+v, want existing user WeChat connection", got.Bot)
359 }
360 }
361
362 func TestSummarizeBotRuntimeErrorsCapsOutput(t *testing.T) {
363 got := summarizeBotRuntimeErrors([]error{
364 errors.New("first"),
365 nil,
366 errors.New("second"),
367 errors.New("third"),
368 errors.New("fourth"),
369 })
370
371 for _, want := range []string{"first", "second", "third", "1 more"} {
372 if !strings.Contains(got, want) {
373 t.Fatalf("summary = %q, want %q", got, want)
374 }
375 }
376 if strings.Contains(got, "fourth") {
377 t.Fatalf("summary = %q, should cap extra errors", got)
378 }
379 }
380
380 lines GO