oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "log/slog"
10 "os"
11 "path/filepath"
12 "strings"
13 "sync"
14 "sync/atomic"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/equipo/assist"
19 "amadan.net/oficina/equipo/internal/wire"
20 "amadan.net/rastrillo/rastrillo/db"
21 "gorm.io/gorm"
22)
23
24// countingOps answers describe with a read and counts invocations.
25type countingOps struct{ invokes atomic.Int32 }
26
27func (o *countingOps) Look(context.Context, string, string) (string, error) { return "", nil }
28func (o *countingOps) Describe(_ context.Context, _, op string) (assist.Operation, error) {
29 return assist.Operation{Name: op, ReadOnly: true, Provider: "base"}, nil
30}
31func (o *countingOps) Invoke(context.Context, string, string, json.RawMessage, string) (json.RawMessage, error) {
32 o.invokes.Add(1)
33 return json.RawMessage(`{"apps":["Shop"]}`), nil
34}
35func (o *countingOps) Forget(string) {}
36
37type syncBuffer struct {
38 mu sync.Mutex
39 b bytes.Buffer
40}
41
42func (s *syncBuffer) Write(p []byte) (int, error) {
43 s.mu.Lock()
44 defer s.mu.Unlock()
45 return s.b.Write(p)
46}
47func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
48
49// TestRemoteResultStoredWithoutCallingAgain: when a call's result cannot
50// be stored, the failure is logged (call and operation only) and the
51// result kept, so the next pass stores it without calling the provider
52// again.
53func TestRemoteResultStoredWithoutCallingAgain(t *testing.T) {
54 const person = "owner@example.com"
55 src, err := hkTemplatePath()
56 if err != nil {
57 t.Fatal(err)
58 }
59 raw, err := os.ReadFile(src)
60 if err != nil {
61 t.Fatal(err)
62 }
63 path := filepath.Join(t.TempDir(), "calls.db")
64 if err := os.WriteFile(path, raw, 0o600); err != nil {
65 t.Fatal(err)
66 }
67 d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil)))
68 if err != nil {
69 t.Fatal(err)
70 }
71 t.Cleanup(func() { _ = d.Close() })
72 var fail atomic.Bool
73 fail.Store(true)
74 s := NewStore(d, Authority{
75 PrimaryRunner: func(*gorm.DB, string) (string, error) { return "RUNNER1", nil },
76 Audit: func(*gorm.DB, string, string, string) error {
77 if fail.Load() {
78 return errors.New("audit unavailable")
79 }
80 return nil
81 },
82 }, nil)
83 logs := &syncBuffer{}
84 s.SetLogger(slog.New(slog.NewTextHandler(logs, nil)))
85 ops := &countingOps{}
86 s.SetOperations(ops)
87 now := time.Now().UTC()
88 if err := d.G.Create(&turnRecord{ID: "t_1", Person: person, State: wire.TurnRunning, Attempt: 1, Revision: 1, CreatedAt: now, UpdatedAt: now, Lane: wire.LaneAssistant}).Error; err != nil {
89 t.Fatal(err)
90 }
91 call := toolCallRecord{CallID: "t_1/1/u1", Person: person, TurnID: "t_1", Attempt: 1, Name: wire.ToolUse, CreatedAt: now, Lane: wire.LaneAssistant, State: callPending, Operation: "base_apps", LedgerKey: "t_1\x00base_apps\x00h", Args: `{"operation":"base_apps","input":{"marker":"zebra-417"}}`}
92 if err := d.G.Create(&call).Error; err != nil {
93 t.Fatal(err)
94 }
95 state := func() (r toolCallRecord) {
96 if err := d.G.Where("call_id = ?", call.CallID).First(&r).Error; err != nil {
97 t.Fatal(err)
98 }
99 return r
100 }
101 until := func(what string, cond func() bool) {
102 t.Helper()
103 for deadline := time.Now().Add(10 * time.Second); !cond(); time.Sleep(10 * time.Millisecond) {
104 if time.Now().After(deadline) {
105 t.Fatalf("timed out waiting for %s; log:\n%s", what, logs.String())
106 }
107 }
108 }
109 ctx, cancel := context.WithCancel(context.Background())
110 done := make(chan struct{})
111 go func() { defer close(done); s.ServeRemoteCalls(ctx) }()
112 defer func() { cancel(); <-done }()
113
114 until("the failure logged", func() bool { return strings.Contains(logs.String(), "assistant call not stored") })
115 if r := state(); r.State != callPending || ops.invokes.Load() != 1 {
116 t.Fatalf("after a failed store: %s, %d invocations", r.State, ops.invokes.Load())
117 }
118 line := logs.String()
119 if !strings.Contains(line, call.CallID) || !strings.Contains(line, "base_apps") || strings.Contains(line, "zebra") || strings.Contains(line, "Shop") {
120 t.Fatalf("log %q", line)
121 }
122 // Later passes (a wake) store the kept result; the provider is not
123 // called again.
124 s.wakeRemote()
125 time.Sleep(100 * time.Millisecond)
126 fail.Store(false)
127 s.wakeRemote()
128 until("the result stored", func() bool { return state().State == callDone })
129 r := state()
130 if n := ops.invokes.Load(); n != 1 || !strings.Contains(r.Result, "Shop") || r.Args != "" {
131 t.Fatalf("%d invocations, result %q, args %q", n, r.Result, r.Args)
132 }
133}
134