Warm the Assistant's provider session before its first turn
Paul measured about 4.2 s before the first Assistant message after a release even reached the model: the rule version changed, so the old session could not resume and the turn waited for a fresh process. On every sync with the instance (runner start, reconnect, and so the first start under a new rule) the engine now asks the Assistant worker of each person who used it in the last 7 days (a sessions_lane row or an Assistant run in that time) to start its harness. The warm-up runs on the worker's own goroutine and slot, takes the connection a turn would (Conns.Choose, stickiness, stale-session rule via the new seat helper shared with converse) and runs only with the lease confirmed. Nothing goes to the model: Claude starts on its session and waits for a user frame; Codex runs initialize, account/read, config/read and thread/start or thread/resume, which are app-server requests, not turns. An unused warm process closes after WarmIdle (30 min default). Tests: TestAssistantWarmsOnlyUsedLanes, TestAssistantWarmNeedsConnection AndLease, and headless TestHeadlessAssistant/warm_start on the fake Claude and Codex (warm after a rule change; first turn cold=false and its prompt is the process's first; unused warm process closes).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+559
−23
internal/headless/assistant_test.go+104 −0internal/runner/thin/claude.go+30 −4internal/runner/thin/codex.go+20 −0internal/runner/thin/engine.go+19 −1internal/runner/thin/failover.go+27 −17internal/runner/thin/run.go+8 −1internal/runner/thin/state.go+22 −0internal/runner/thin/warm.go+89 −0internal/runner/thin/warm_test.go+240 −0
Intent
diff --git a/internal/headless/assistant_test.go b/internal/headless/assistant_test.go| index 424d6af6..8a2811c5 100644 |
| --- a/internal/headless/assistant_test.go |
| +++ b/internal/headless/assistant_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "database/sql" |
| "encoding/json" |
| "errors" |
| + "log/slog" |
| "net/http" |
| "os" |
| "path/filepath" |
| @@ -446,6 +447,109 @@ func TestHeadlessAssistant(t *testing.T) { |
| } |
| asJob(t, ctx, env, inst, r, request, thread, title) |
| }) |
| + |
| + // warm_start: after a restart under a new Assistant rule (its old |
| + // session cannot resume), the runner starts the person's Assistant |
| + // process and session before their first message, on either |
| + // provider, sending the model nothing: the first turn finds it up |
| + // (cold=false) and its first prompt is the process's first. A person |
| + // whose Assistant was never used is not warmed, and a warm process no |
| + // turn uses closes after WarmIdle. |
| + t.Run("warm_start", func(t *testing.T) { |
| + for _, provider := range []string{"claude", "codex"} { |
| + t.Run(provider, func(t *testing.T) { |
| + env, _, r := localEnv(t) |
| + r.opts.NoMoveIn = true |
| + if provider == "codex" { |
| + r.addAccount(t, "codex", "codex-1", thintest.Owner) |
| + r.only(t, "codex-1") |
| + } |
| + logs := &lockedBuffer{} |
| + r.opts.Logger = slog.New(slog.NewTextHandler(logs, &slog.HandlerOptions{Level: slog.LevelDebug})) |
| + r.start(t) |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) |
| + defer cancel() |
| + a := env.Client.Assistant() |
| + first, err := a.Send(ctx, "Hello.", key()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + assistantReply(t, ctx, a, first.Turn.ID) |
| + if line := phaseLine(t, logs, first.Turn.ID); !strings.Contains(line, "cold=true") { |
| + t.Fatalf("the first turn ever was warm: %s", line) |
| + } |
| + if strings.Contains(logs.String(), `msg="assistant warm"`) { |
| + t.Fatalf("warmed an Assistant nobody had used:\n%s", logs.String()) |
| + } |
| + r.stop(t) |
| + state, err := sql.Open("sqlite", filepath.Join(r.cfg.StateDir, "thin.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err = state.Exec("UPDATE sessions_lane SET account = account || '-old' WHERE lane = ?", wire.LaneAssistant); err != nil { |
| + t.Fatal(err) |
| + } |
| + state.Close() |
| + r.start(t) |
| + warmed(t, logs, 1) |
| + second, err := a.Send(ctx, "And again.", key()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reply := assistantReply(t, ctx, a, second.Turn.ID) |
| + if line := phaseLine(t, logs, second.Turn.ID); !strings.Contains(line, "cold=false") { |
| + t.Fatalf("the first turn after the warm-up started cold: %s", line) |
| + } |
| + want := map[string]string{"claude": "Turn 1, fresh session, process turn 1.", "codex": "Turn 1, fresh thread."}[provider] |
| + if !strings.Contains(reply.Text, want) { |
| + t.Fatalf("the warm process was not the turn's, fresh and unprompted: %q", reply.Text) |
| + } |
| + |
| + r.stop(t) |
| + r.opts.Claude.WarmIdle = 2 * time.Second |
| + r.start(t) |
| + warmed(t, logs, 2) |
| + time.Sleep(4 * time.Second) |
| + third, err := a.Send(ctx, "Still there?", key()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + assistantReply(t, ctx, a, third.Turn.ID) |
| + if line := phaseLine(t, logs, third.Turn.ID); !strings.Contains(line, "cold=true") { |
| + t.Fatalf("an unused warm process outlived WarmIdle: %s", line) |
| + } |
| + }) |
| + } |
| + }) |
| +} |
| + |
| +// phaseLine waits for the runner's debug phase line of an Assistant turn. |
| +func phaseLine(t *testing.T, logs *lockedBuffer, turn string) string { |
| + t.Helper() |
| + deadline := time.Now().Add(30 * time.Second) |
| + for { |
| + for _, l := range strings.Split(logs.String(), "\n") { |
| + if strings.Contains(l, `msg="assistant turn"`) && strings.Contains(l, "turn="+turn+" ") { |
| + return l |
| + } |
| + } |
| + if time.Now().After(deadline) { |
| + t.Fatalf("no phase line for %s", turn) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| +} |
| + |
| +// warmed waits for the runner's n-th successful Assistant warm-up. |
| +func warmed(t *testing.T, logs *lockedBuffer, n int) { |
| + t.Helper() |
| + deadline := time.Now().Add(60 * time.Second) |
| + for strings.Count(logs.String(), `msg="assistant warm" outcome=warm`) < n { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("no warm-up %d:\n%s", n, logs.String()) |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + } |
| } |
| // rot13 hides tool words from the fake that reads them first. |
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go| index d988daae..4dfb9089 100644 |
| --- a/internal/runner/thin/claude.go |
| +++ b/internal/runner/thin/claude.go |
| @@ -32,9 +32,11 @@ import ( |
| // Turn timing. A turn starts only if the credential copy stays valid for |
| // the turn cap plus the margin; otherwise the process is rotated first. |
| const ( |
| - DefaultMaxTurn = 20 * time.Minute |
| - DefaultMargin = 2 * time.Minute |
| - DefaultIdle = 10 * time.Minute |
| + DefaultMaxTurn = 20 * time.Minute |
| + DefaultMargin = 2 * time.Minute |
| + DefaultIdle = 10 * time.Minute |
| + // DefaultWarmIdle closes a warmed process no turn used. |
| + DefaultWarmIdle = 30 * time.Minute |
| DefaultLockWait = 90 * time.Second |
| minTurn = time.Minute |
| transcriptLimit = 64 << 20 |
| @@ -52,7 +54,10 @@ type ClaudeOptions struct { |
| // Refresh runs the official CLI in the source home under its lock. |
| Refresh func(context.Context, provider.Binding) (provider.Identity, error) |
| MaxTurn, Margin, Idle, LockWait time.Duration |
| - Logger *slog.Logger |
| + // WarmIdle is how long a process started ahead of a turn (Warm) |
| + // waits for one before it closes. |
| + WarmIdle time.Duration |
| + Logger *slog.Logger |
| // Tools runs the coordinator's Equipo tools for a turn. Nil serves no |
| // tools (the permission callback still denies everything else). |
| Tools ToolCaller |
| @@ -83,6 +88,9 @@ func (o *ClaudeOptions) defaults() { |
| if o.LockWait == 0 { |
| o.LockWait = DefaultLockWait |
| } |
| + if o.WarmIdle == 0 { |
| + o.WarmIdle = DefaultWarmIdle |
| + } |
| if o.Digest == "" { |
| o.Digest = claude.ExecutableSHA256 |
| } |
| @@ -516,6 +524,24 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st |
| } |
| } |
| +// Warm starts the process ahead of the first turn: the CLI starts on |
| +// its session (resumed or fresh) and waits for a user frame, so the |
| +// model is sent nothing. Unused, it closes after WarmIdle. |
| +func (c *claudeCoordinator) Warm(ctx context.Context) error { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.proc != nil { |
| + return nil |
| + } |
| + if err := c.start(ctx); err != nil { |
| + return err |
| + } |
| + c.stopTimers() |
| + c.idle, c.idleAt = time.AfterFunc(c.o.WarmIdle, c.idleExit), time.Now().Add(c.o.WarmIdle) |
| + c.scheduleWarm() |
| + return nil |
| +} |
| + |
| func (c *claudeCoordinator) ended(ctx, tctx context.Context) TurnResult { |
| if ctx.Err() != nil { |
| return TurnResult{Reason: "cancelled"} |
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go| index 97732e63..020d82da 100644 |
| --- a/internal/runner/thin/codex.go |
| +++ b/internal/runner/thin/codex.go |
| @@ -100,6 +100,26 @@ func (c *codexCoordinator) idleExit() { |
| c.stop(true) |
| } |
| +// Warm starts the app-server ahead of the first turn: initialize, the |
| +// account and configuration checks, and thread/start or thread/resume, |
| +// none of which is a turn, so the model is sent nothing. Unused, it |
| +// closes after WarmIdle. |
| +func (c *codexCoordinator) Warm(ctx context.Context) error { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if c.proc != nil { |
| + return nil |
| + } |
| + if err := c.start(ctx); err != nil { |
| + return err |
| + } |
| + if c.idle != nil { |
| + c.idle.Stop() |
| + } |
| + c.idle, c.idleAt = time.AfterFunc(c.o.WarmIdle, c.idleExit), time.Now().Add(c.o.WarmIdle) |
| + return nil |
| +} |
| + |
| // codexItem is the part of an item notification the coordinator reads. |
| type codexItem struct { |
| ID string `json:"id"` |
diff --git a/internal/runner/thin/engine.go b/internal/runner/thin/engine.go| index 70514b47..a53b6043 100644 |
| --- a/internal/runner/thin/engine.go |
| +++ b/internal/runner/thin/engine.go |
| @@ -87,6 +87,13 @@ type Coordinator interface { |
| Close() |
| } |
| +// Warmer is a harness that can start its process and session ahead of |
| +// the first turn, sending the model nothing: the first turn then finds |
| +// it up. A warm process no turn uses closes after a while on its own. |
| +type Warmer interface { |
| + Warm(ctx context.Context) error |
| +} |
| + |
| // Engine runs each person's turns one at a time per lane from the |
| // durable runs table: the coordinator's, the Assistant's and each job's |
| // run at once. |
| @@ -122,6 +129,8 @@ type workerKey struct{ Person, Lane string } |
| type worker struct { |
| wake chan struct{} |
| + // warm asks the worker to start its harness ahead of a turn. |
| + warm chan struct{} |
| // conn wakes a turn held for a connection. |
| conn chan struct{} |
| coord Coordinator |
| @@ -165,7 +174,7 @@ func (e *Engine) Wait() { e.wg.Wait() } |
| func (e *Engine) worker(k workerKey) *worker { |
| w := e.workers[k] |
| if w == nil { |
| - w = &worker{wake: make(chan struct{}, 1), conn: make(chan struct{}, 1)} |
| + w = &worker{wake: make(chan struct{}, 1), warm: make(chan struct{}, 1), conn: make(chan struct{}, 1)} |
| e.workers[k] = w |
| e.wg.Add(1) |
| go e.loop(k, w) |
| @@ -255,11 +264,15 @@ func (e *Engine) loop(k workerKey, w *worker) { |
| } |
| }() |
| for { |
| + warm := false |
| select { |
| case <-e.ctx.Done(): |
| return |
| case <-w.wake: |
| + case <-w.warm: |
| + warm = true |
| } |
| + ran := false |
| for e.ctx.Err() == nil { |
| // A reset is the person's own conversation's: the |
| // Assistant's lane and job threads go on. |
| @@ -275,6 +288,11 @@ func (e *Engine) loop(k workerKey, w *worker) { |
| break |
| } |
| e.runOne(k.Person, w, r) |
| + ran = true |
| + } |
| + // A turn that ran started the harness anyway. |
| + if warm && !ran && e.ctx.Err() == nil { |
| + e.warmOne(k, w) |
| } |
| } |
| } |
diff --git a/internal/runner/thin/failover.go b/internal/runner/thin/failover.go| index 48235fdc..74a595b8 100644 |
| --- a/internal/runner/thin/failover.go |
| +++ b/internal/runner/thin/failover.go |
| @@ -53,23 +53,9 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| e.log("runner hold", e.State.Hold(e.ctx, *r, "")) |
| e.Notify() |
| } |
| - if w.coord == nil || w.connID != b.ID { |
| - if w.coord != nil { |
| - w.coord.Close() |
| - w.coord = nil |
| - } |
| - // A session the conversation went on without is stale: coming |
| - // back to a connection starts afresh from the notebook and the |
| - // tail, never resumes a session that missed turns. |
| - if last, _ := e.State.meta(ctx, conn); last != "" && last != b.ID { |
| - e.log("runner session", e.State.deleteSession(ctx, person, r.Lane)) |
| - } |
| - c, err := e.Open(person, r.Lane, b) |
| - if err != nil { |
| - e.log("coordinator open", err) |
| - return TurnResult{Reason: "account_unavailable"} |
| - } |
| - w.coord, w.connID = c, b.ID |
| + if err := e.seat(ctx, person, r.Lane, conn, w, b); err != nil { |
| + e.log("coordinator open", err) |
| + return TurnResult{Reason: "account_unavailable"} |
| } |
| _ = choice |
| var offset int64 |
| @@ -128,6 +114,30 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run, |
| } |
| } |
| +// seat makes the worker's harness the one on connection b, closing one |
| +// on another connection; conn is the lane's connKey. |
| +func (e *Engine) seat(ctx context.Context, person, lane, conn string, w *worker, b runner.AccountBinding) error { |
| + if w.coord != nil && w.connID == b.ID { |
| + return nil |
| + } |
| + if w.coord != nil { |
| + w.coord.Close() |
| + w.coord = nil |
| + } |
| + // A session the conversation went on without is stale: coming back |
| + // to a connection starts afresh from the notebook and the tail, never |
| + // resumes a session that missed turns. |
| + if last, _ := e.State.meta(ctx, conn); last != "" && last != b.ID { |
| + e.log("runner session", e.State.deleteSession(ctx, person, lane)) |
| + } |
| + c, err := e.Open(person, lane, b) |
| + if err != nil { |
| + return err |
| + } |
| + w.coord, w.connID = c, b.ID |
| + return nil |
| +} |
| + |
| // usageRows fills an attempt's rows with what ran it: one row with no |
| // figures (complete false) when the harness reported nothing, so the |
| // attempt is recorded all the same. |
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go| index b2a8a217..8582d05f 100644 |
| --- a/internal/runner/thin/run.go |
| +++ b/internal/runner/thin/run.go |
| @@ -340,7 +340,14 @@ func Run(ctx context.Context, c runner.Config, o Options) error { |
| if merges.Every <= 0 { |
| merges.Every = reachEvery + 5*time.Second |
| } |
| - link.Synced = merges.Kick |
| + link.Synced = func() { |
| + merges.Kick() |
| + // Each sync (start, reconnect, and so a new rule's first start) |
| + // warms the Assistant lanes in use, where the instance has them. |
| + if proto, _ := link.Spoken(); proto >= wire.ProtocolAssistant { |
| + engine.WarmAssistants() |
| + } |
| + } |
| go merges.Loop(ctx) |
| if engineer.MaxStep == 0 { |
| engineer.MaxStep = DefaultMaxStep |
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go| index 280bab0f..0e0b08a5 100644 |
| --- a/internal/runner/thin/state.go |
| +++ b/internal/runner/thin/state.go |
| @@ -11,6 +11,7 @@ import ( |
| "errors" |
| "fmt" |
| "path/filepath" |
| + "slices" |
| "strings" |
| "time" |
| @@ -716,3 +717,24 @@ func (s *State) anyRefused(ctx context.Context, refs []wire.AttachmentRef) bool |
| } |
| return false |
| } |
| + |
| +// assistantUsers are the persons whose Assistant lane saved a session or |
| +// took a turn since then. |
| +func (s *State) assistantUsers(ctx context.Context, since time.Time) ([]string, error) { |
| + rows, err := s.db.QueryContext(ctx, "SELECT person, updated_at FROM sessions_lane WHERE lane=? UNION ALL SELECT person, created_at FROM runs WHERE lane=?", wire.LaneAssistant, wire.LaneAssistant) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var p, at string |
| + if err = rows.Scan(&p, &at); err != nil { |
| + return nil, err |
| + } |
| + if t, err := time.Parse(time.RFC3339Nano, at); err == nil && t.After(since) && !slices.Contains(out, p) { |
| + out = append(out, p) |
| + } |
| + } |
| + return out, rows.Err() |
| +} |
diff --git a/internal/runner/thin/warm.go b/internal/runner/thin/warm.go| new file mode 100644 |
| index 00000000..82ddf03d |
| --- /dev/null |
| +++ b/internal/runner/thin/warm.go |
| @@ -0,0 +1,89 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Warming the Assistant (Paul's live check, 2026-11-14): after a release |
| +// the Assistant's rule changes, so its old session cannot resume, and |
| +// the first message waited for a fresh provider process and session |
| +// before the model saw a word. On every sync with the instance (the |
| +// runner's start, a reconnect, and so the first start under a new rule) |
| +// the runner now starts that process and session ahead of the turn, for |
| +// each person who used their Assistant lately. Nothing is sent to the |
| +// model: Claude starts and waits for its first user frame; Codex |
| +// initializes and starts or resumes its thread, which are app-server |
| +// requests, not turns. |
| + |
| +// warmWithin is how recent an Assistant's use must be to warm it: its |
| +// session saved, or a turn of its run, in that time. |
| +const warmWithin = 7 * 24 * time.Hour |
| + |
| +// warmLimit bounds one warm-up (the lease check and the start). |
| +const warmLimit = time.Minute |
| + |
| +// WarmAssistants asks the Assistant worker of each person who used it |
| +// within warmWithin to start its harness, if it is not up already. |
| +func (e *Engine) WarmAssistants() { |
| + if e == nil { |
| + return |
| + } |
| + e.mu.Lock() |
| + ctx := e.ctx |
| + e.mu.Unlock() |
| + if ctx == nil || ctx.Err() != nil { |
| + return |
| + } |
| + persons, err := e.State.assistantUsers(ctx, time.Now().Add(-warmWithin)) |
| + if err != nil { |
| + e.log("runner warm", err) |
| + return |
| + } |
| + e.mu.Lock() |
| + defer e.mu.Unlock() |
| + for _, p := range persons { |
| + w := e.worker(workerKey{p, wire.LaneAssistant}) |
| + select { |
| + case w.warm <- struct{}{}: |
| + default: |
| + } |
| + } |
| +} |
| + |
| +// warmOne starts the lane's harness on the connection a turn would take |
| +// now, with the execution lease confirmed, as a turn would. No |
| +// connection, no lease or a harness that cannot warm: nothing happens, |
| +// and the first turn starts it as before. |
| +func (e *Engine) warmOne(k workerKey, w *worker) { |
| + ctx, cancel := context.WithTimeout(e.ctx, warmLimit) |
| + defer cancel() |
| + conn := connKey(k.Person, k.Lane) |
| + b, _, err := e.choose(ctx, k.Person, conn, w.connID) |
| + if err != nil { |
| + return |
| + } |
| + if e.Authorize != nil && e.Authorize(ctx) != nil { |
| + return |
| + } |
| + if err := e.seat(ctx, k.Person, k.Lane, conn, w, b); err != nil { |
| + e.log("coordinator open", err) |
| + return |
| + } |
| + h, ok := w.coord.(Warmer) |
| + if !ok { |
| + return |
| + } |
| + start := time.Now() |
| + err = h.Warm(ctx) |
| + e.log("runner warm", err) |
| + if e.Logger != nil { |
| + outcome := "warm" |
| + if err != nil { |
| + outcome = "failed" |
| + } |
| + e.Logger.Debug("assistant warm", "outcome", outcome, "ms", time.Since(start).Milliseconds()) |
| + } |
| +} |
diff --git a/internal/runner/thin/warm_test.go b/internal/runner/thin/warm_test.go| new file mode 100644 |
| index 00000000..a9e211fe |
| --- /dev/null |
| +++ b/internal/runner/thin/warm_test.go |
| @@ -0,0 +1,240 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "slices" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/connect" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// warmCoordinator records its warm-ups and turns. |
| +type warmCoordinator struct { |
| + person string |
| + mu sync.Mutex |
| + warmed int |
| + turns []string |
| + done chan string |
| +} |
| + |
| +func (c *warmCoordinator) Warm(context.Context) error { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.warmed++ |
| + return nil |
| +} |
| + |
| +func (c *warmCoordinator) Turn(_ context.Context, in TurnInput, _ func(string)) TurnResult { |
| + c.mu.Lock() |
| + c.turns = append(c.turns, in.TurnID) |
| + c.mu.Unlock() |
| + if c.done != nil { |
| + c.done <- in.TurnID |
| + } |
| + return TurnResult{Text: "ok"} |
| +} |
| +func (c *warmCoordinator) Close() {} |
| + |
| +func (c *warmCoordinator) counts() (int, int) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.warmed, len(c.turns) |
| +} |
| + |
| +// warmOpens is an Engine.Open that hands out warmCoordinators and |
| +// remembers each one by person and lane. |
| +type warmOpens struct { |
| + mu sync.Mutex |
| + opened map[workerKey][]*warmCoordinator |
| + done chan string |
| +} |
| + |
| +func (o *warmOpens) open(person, lane string, _ runner.AccountBinding) (Coordinator, error) { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + c := &warmCoordinator{person: person, done: o.done} |
| + if o.opened == nil { |
| + o.opened = map[workerKey][]*warmCoordinator{} |
| + } |
| + k := workerKey{person, lane} |
| + o.opened[k] = append(o.opened[k], c) |
| + return c, nil |
| +} |
| + |
| +func (o *warmOpens) get(person, lane string) []*warmCoordinator { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + return append([]*warmCoordinator(nil), o.opened[workerKey{person, lane}]...) |
| +} |
| + |
| +func (o *warmOpens) keys() []workerKey { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + var out []workerKey |
| + for k := range o.opened { |
| + out = append(out, k) |
| + } |
| + return out |
| +} |
| + |
| +func waitWarm(t *testing.T, what string, ok func() bool) { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for !ok() { |
| + if time.Now().After(deadline) { |
| + t.Fatalf("timed out waiting for %s", what) |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| +} |
| + |
| +// The runner warms the Assistant lane of each person who used it lately |
| +// (a session or a run in the last week), and only theirs: never a |
| +// person who only talks to the Coordinator, nor one whose Assistant was |
| +// last used long ago. The first turn after runs on the warmed harness: |
| +// no new open, no new process. |
| +func TestAssistantWarmsOnlyUsedLanes(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + state, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer state.Close() |
| + ana, bob, cy, dee := "ana@example.com", "bob@example.com", "cy@example.com", "dee@example.com" |
| + if err := state.saveSession(ctx, ana, wire.LaneAssistant, "claude", "c1#rule-old", "s-ana", "t0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := state.saveSession(ctx, bob, wire.LaneCoordinator, "claude", "c1#rule-x", "s-bob", "t0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := state.saveSession(ctx, cy, wire.LaneAssistant, "claude", "c1#rule-old", "s-cy", "t0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + old := time.Now().Add(-30 * 24 * time.Hour).UTC().Format(time.RFC3339Nano) |
| + if _, err := state.db.ExecContext(ctx, "UPDATE sessions_lane SET updated_at=? WHERE person=?", old, cy); err != nil { |
| + t.Fatal(err) |
| + } |
| + // dee's Assistant ran a turn yesterday but has no session row (it |
| + // was forgotten); a finished run counts as use. |
| + if _, err := state.db.ExecContext(ctx, "INSERT INTO runs(turn_id, person, attempt, state, text, tail, lane, created_at) VALUES('td', ?, 1, ?, '', '[]', ?, ?)", dee, runDone, wire.LaneAssistant, time.Now().Add(-24*time.Hour).UTC().Format(time.RFC3339Nano)); err != nil { |
| + t.Fatal(err) |
| + } |
| + opens := &warmOpens{done: make(chan string, 4)} |
| + e := &Engine{State: state, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: opens.open} |
| + if err := e.Start(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer e.Wait() |
| + defer cancel() |
| + e.WarmAssistants() |
| + waitWarm(t, "two warm-ups", func() bool { |
| + a, d := opens.get(ana, wire.LaneAssistant), opens.get(dee, wire.LaneAssistant) |
| + if len(a) != 1 || len(d) != 1 { |
| + return false |
| + } |
| + wa, _ := a[0].counts() |
| + wd, _ := d[0].counts() |
| + return wa == 1 && wd == 1 |
| + }) |
| + time.Sleep(100 * time.Millisecond) |
| + keys := opens.keys() |
| + if len(keys) != 2 || !slices.Contains(keys, workerKey{ana, wire.LaneAssistant}) || !slices.Contains(keys, workerKey{dee, wire.LaneAssistant}) { |
| + t.Fatalf("opened %v, want only ana's and dee's Assistant", keys) |
| + } |
| + |
| + // Warming again (a reconnect) while the harness is up opens nothing new. |
| + e.WarmAssistants() |
| + if err := state.Accept(ctx, "f1", wire.MessageCommand{Person: ana, TurnID: "ta", Attempt: 1, Text: "hello", Lane: wire.LaneAssistant}); err != nil { |
| + t.Fatal(err) |
| + } |
| + e.Wake(ana, wire.LaneAssistant) |
| + select { |
| + case got := <-opens.done: |
| + if got != "ta" { |
| + t.Fatalf("ran %s", got) |
| + } |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("the Assistant's turn did not run") |
| + } |
| + a := opens.get(ana, wire.LaneAssistant) |
| + if len(a) != 1 { |
| + t.Fatalf("the first turn after the warm-up opened %d harnesses", len(a)) |
| + } |
| + if _, turns := a[0].counts(); turns != 1 { |
| + t.Fatalf("the warmed harness ran %d turns", turns) |
| + } |
| +} |
| + |
| +// chooser is a ConnChooser that gives one binding, or none. |
| +type chooser struct { |
| + b runner.AccountBinding |
| + err error |
| +} |
| + |
| +func (c *chooser) Choose(context.Context, string, string, string, []string) (runner.AccountBinding, connect.Choice, error) { |
| + return c.b, connect.Choice{}, c.err |
| +} |
| +func (c *chooser) Limit(string, connect.Limit) time.Time { return time.Time{} } |
| +func (c *chooser) Observe(string, connect.Limit, string) {} |
| +func (c *chooser) LimitedFrom(string) *wire.Switched { return nil } |
| +func (c *chooser) SignInAgain(string) {} |
| +func (c *chooser) Answered(string) {} |
| +func (c *chooser) NextCheck(string) time.Time { return time.Time{} } |
| + |
| +// A warm-up takes the connection a turn would (Conns) and runs only with |
| +// the execution lease confirmed: no connection, or no lease, warms |
| +// nothing and opens nothing. |
| +func TestAssistantWarmNeedsConnectionAndLease(t *testing.T) { |
| + for _, c := range []struct { |
| + name string |
| + conns *chooser |
| + authorize func(context.Context) error |
| + want int |
| + }{ |
| + {"no_connection", &chooser{err: ErrNoConnection}, nil, 0}, |
| + {"no_lease", &chooser{b: runner.AccountBinding{ID: "c1", Provider: "claude"}}, func(context.Context) error { return ErrNoAuthority }, 0}, |
| + {"chosen", &chooser{b: runner.AccountBinding{ID: "c1", Provider: "claude"}}, func(context.Context) error { return nil }, 1}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + state, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer state.Close() |
| + p := "ana@example.com" |
| + if err := state.saveSession(ctx, p, wire.LaneAssistant, "claude", "c1#rule-old", "s", "t0"); err != nil { |
| + t.Fatal(err) |
| + } |
| + opens := &warmOpens{} |
| + e := &Engine{State: state, Conns: c.conns, Authorize: c.authorize, Emit: func(wire.DeltaReport) {}, Notify: func() {}, Open: opens.open} |
| + if err := e.Start(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + defer e.Wait() |
| + defer cancel() |
| + e.WarmAssistants() |
| + if c.want > 0 { |
| + waitWarm(t, "a warm-up", func() bool { |
| + a := opens.get(p, wire.LaneAssistant) |
| + if len(a) != 1 { |
| + return false |
| + } |
| + w, _ := a[0].counts() |
| + return w == 1 |
| + }) |
| + return |
| + } |
| + time.Sleep(300 * time.Millisecond) |
| + if got := opens.keys(); len(got) != 0 { |
| + t.Fatalf("opened %v", got) |
| + } |
| + }) |
| + } |
| +} |