| 1 | package bot |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "log/slog" |
| 6 | "path/filepath" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/agent" |
| 10 | "reasonix/internal/control" |
| 11 | "reasonix/internal/event" |
| 12 | "reasonix/internal/provider" |
| 13 | "reasonix/internal/tool" |
| 14 | ) |
| 15 | |
| 16 | func TestGatewayIntentionalTransitionMovesLeaseAndMapping(t *testing.T) { |
| 17 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 18 | dir := t.TempDir() |
| 19 | originalPath := filepath.Join(dir, "original.jsonl") |
| 20 | sess := agent.NewSession("sys") |
| 21 | sess.Add(provider.Message{Role: provider.RoleUser, Content: "hello"}) |
| 22 | if err := sess.SaveIfAbsent(originalPath); err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | gw := NewGateway(GatewayConfig{}, nil, logger) |
| 26 | msg := InboundMessage{Platform: PlatformWeixin, ChatType: ChatDM, ChatID: "chat", UserID: "user"} |
| 27 | key := BuildSessionKey(msg.Session()) |
| 28 | state := &sessionState{ |
| 29 | leases: control.NewSessionLeaseKeeper(), |
| 30 | sessionPath: originalPath, |
| 31 | } |
| 32 | state.onSessionTransition = gw.botSessionTransitionHandler(key, msg, state) |
| 33 | exec := agent.New(nil, tool.NewRegistry(), sess, agent.Options{}, event.Discard) |
| 34 | ctrl := control.New(control.Options{ |
| 35 | Runner: exec, Executor: exec, SessionDir: dir, SessionPath: originalPath, |
| 36 | Sink: event.Discard, OnSessionTransition: state.onSessionTransition, |
| 37 | }) |
| 38 | state.ctrl = ctrl |
| 39 | t.Cleanup(ctrl.Close) |
| 40 | gw.controllers[key] = state |
| 41 | gw.sessionOverrides[key] = sessionRuntimeOverride{sessionPath: originalPath} |
| 42 | if err := rebindBotSessionWriteAuthority(state, originalPath); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | defer state.leases.Release() |
| 46 | |
| 47 | if err := ctrl.NewSession(); err != nil { |
| 48 | t.Fatalf("NewSession: %v", err) |
| 49 | } |
| 50 | targetPath := ctrl.SessionPath() |
| 51 | gw.mu.Lock() |
| 52 | statePath := state.sessionPath |
| 53 | overridePath := gw.sessionOverrides[key].sessionPath |
| 54 | gw.mu.Unlock() |
| 55 | if statePath != targetPath || overridePath != targetPath { |
| 56 | t.Fatalf("transition paths = state %q override %q, want %q", statePath, overridePath, targetPath) |
| 57 | } |
| 58 | if got := state.leases.HeldPath(); got != agent.CanonicalSessionPath(targetPath) { |
| 59 | t.Fatalf("lease path = %q, want %q", got, agent.CanonicalSessionPath(targetPath)) |
| 60 | } |
| 61 | if auth := exec.Session().WriteAuthority(); auth == nil || !auth.Covers(targetPath) { |
| 62 | t.Fatal("bot transition published an unowned Session") |
| 63 | } |
| 64 | } |
| 65 |