Merge branch 'assistant-warm' into main
Merge assistant-warm: warm Assistant sessions, tidy old questions The runner opens the Assistant's provider session before its first turn for recent users (no tokens; closed after 30 idle minutes), and a legacy hand-off's mirrored question is resolved once it is moot.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
14 files changed,
+908
−28
.rastrillo/budgets.txt+4 −4internal/equipo/chat/handoff.go+6 −0internal/equipo/chat/housekeeping_control.go+7 −1internal/equipo/chat/outcome.go+111 −0internal/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 −0internal/thintest/assistant_legacy_question_contract_test.go+221 −0
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e2e3e8f1..aecb6460 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 25314 17824 Runner state, connections and execution share private helpers: Copy validation, job lanes and the Assistant, its turn phases log included. Measured 25314 source, 17824 test lines. |
| +size internal/runner/thin 25506 18064 Runner state, connections and execution share private helpers: Copy validation, job lanes, the Assistant with its turn log and warm-up. Measured 25506 source, 18064 test lines. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 28488 - The transactional conversation store shares authority and dispatch helpers; Roster adds personal visibility and batched card-thread and project-context reads. Measured 28488 source lines. |
| +size internal/equipo/chat 28611 - Transactional conversation store shares authority and dispatch helpers; Roster visibility and batched reads; legacy mirrored questions resolve once moot. Measured 28611 source lines. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
| @@ -70,8 +70,8 @@ perf GET /api/v1/tasks/{id}/files/{file} skip Research kept images: bearer-only |
| perf GET /tasks/{id}/files/{file} skip Research kept images: the bytes of one image, shown on the task page; a file, not a screen. |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s TestReleaseRunnerHasNoFakeWorker builds the release runner and the thin package under testbuild (about 12s locally). |
| -size internal/headless - 10800 End-to-end scenarios through a real runner and instance: Copy setting, wording flag, the Assistant's job threads and streamed replies. Measured 10800 test lines. |
| -size internal/thintest - 28593 Contract and browser tests share one instance harness: Assistant hand-off, outcome and job contracts, Roster guards and captures. Measured 28469 test lines. |
| +size internal/headless - 10904 End-to-end scenarios through a real runner and instance: Copy setting, wording flag, the Assistant's job threads, streamed replies and warm start. Measured 10904 test lines. |
| +size internal/thintest - 28814 Contract and browser tests share one instance harness: Assistant hand-off, outcome, job and legacy question contracts, Roster guards and captures. Measured 28814 test lines. |
| perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}. |
| perf GET /api/v1/usage skip Thin v1 person API: bearer-only JSON for devices; the browser reads usage through /usage. |
| perf GET /api/v1/advice skip Thin v1 person API: bearer-only JSON for devices; the browser reads advice through /usage and /conversation. |
diff --git a/internal/equipo/chat/handoff.go b/internal/equipo/chat/handoff.go| index 4065fae4..ec379930 100644 |
| --- a/internal/equipo/chat/handoff.go |
| +++ b/internal/equipo/chat/handoff.go |
| @@ -641,6 +641,9 @@ func (t *txn) handoffChanged(h handoffRecord, needsPerson bool) error { |
| if err := t.tellAssistant(h, needsPerson); err != nil { |
| return err |
| } |
| + if err := t.settleLegacyQuestions(h); err != nil { |
| + return err |
| + } |
| return t.projectJob(h) |
| } |
| @@ -1362,6 +1365,9 @@ func (s *Store) teamCancel(ctx context.Context, call toolCallRecord, input json. |
| return err |
| } |
| h.State = state |
| + if err := t.settleLegacyQuestions(h); err != nil { |
| + return err |
| + } |
| return t.projectJob(h) |
| }) |
| if err != nil { |
diff --git a/internal/equipo/chat/housekeeping_control.go b/internal/equipo/chat/housekeeping_control.go| index ac73e471..ed8db0a6 100644 |
| --- a/internal/equipo/chat/housekeeping_control.go |
| +++ b/internal/equipo/chat/housekeeping_control.go |
| @@ -461,7 +461,9 @@ func (t *txn) subjectRevision(kind, id string) (int64, error) { |
| } |
| // HousekeepingTick is the loop's minute: receipts whose quiet hours ended |
| -// show; a job's preview that expired is offered no more; stale claims |
| +// show; a job's preview that expired is offered no more; a legacy |
| +// hand-off's mirrored question that needs no answer now is resolved; |
| +// stale claims |
| // are revalidated; the daily sweep runs once per day at 03:00 and held |
| // findings are looked at again; each person gets their digest once a |
| // day from 08:00 when something happened. |
| @@ -472,6 +474,10 @@ func (s *Store) HousekeepingTick(ctx context.Context) error { |
| if err := s.tx(ctx, func(t *txn) error { return t.expirePreviews() }); err != nil { |
| return err |
| } |
| + // A legacy hand-off's mirrored question nobody will answer now. |
| + if err := s.tx(ctx, func(t *txn) error { return t.settleStaleLegacyQuestions() }); err != nil { |
| + return err |
| + } |
| if _, _, err := s.RecoverHousekeeping(ctx, true); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/chat/outcome.go b/internal/equipo/chat/outcome.go| index f41f7a7a..f13d09be 100644 |
| --- a/internal/equipo/chat/outcome.go |
| +++ b/internal/equipo/chat/outcome.go |
| @@ -5,6 +5,7 @@ import ( |
| "errors" |
| "slices" |
| "strings" |
| + "time" |
| "amadan.net/oficina/equipo/internal/equipo/mergegate" |
| "amadan.net/oficina/equipo/internal/wire" |
| @@ -504,3 +505,113 @@ func (t *txn) answerOutcome(person string, c cardRecord, in wire.AnswerCard) (ou |
| out.Card, err = t.assistantCardView(c) |
| return out, current, err |
| } |
| + |
| +// Stale legacy questions (Paul's live check, 2026-11-14). A legacy |
| +// hand-off (lane "") mirrored its team question into the Assistant lane |
| +// as a question card (slice 1, kept by ruling P3j). The card follows its |
| +// source while the source changes (mirrorCard), but the person may |
| +// answer in the chat instead, and the source then stays open: the card |
| +// stayed open for ever. settleLegacyQuestions resolves it, with the |
| +// approved resolved line, once the hand-off is cancelled or its work has |
| +// settled or stopped (handoffSettled), or once its source has been open |
| +// for staleQuestion with no answer and none of the hand-off's work runs. |
| +// A source no longer open that the card missed is followed now. The team |
| +// card itself is never touched: it stays the Coordinator's. |
| + |
| +// staleQuestion is how long a legacy hand-off's question may wait |
| +// unanswered, its work not running, before its mirror is resolved. |
| +const staleQuestion = 24 * time.Hour |
| + |
| +// settleLegacyQuestions resolves the legacy hand-off's open mirrored |
| +// question cards that no longer need an answer, each with its event. |
| +func (t *txn) settleLegacyQuestions(h handoffRecord) error { |
| + if h.Lane != "" { |
| + return nil |
| + } |
| + var mirrors []cardRecord |
| + if err := t.db.Where("handoff_id = ? AND person = ? AND lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> ''", h.ID, h.Person, wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Order("created_at, id").Find(&mirrors).Error; err != nil || len(mirrors) == 0 { |
| + return err |
| + } |
| + ended := h.State == handoffCancelled || h.State == handoffStopping |
| + if !ended { |
| + settled, err := t.handoffSettled(h) |
| + if err != nil { |
| + return err |
| + } |
| + ended = settled |
| + } |
| + running, err := t.handoffRunning(h) |
| + if err != nil { |
| + return err |
| + } |
| + for _, m := range mirrors { |
| + var src cardRecord |
| + if err := t.db.Where("id = ? AND person = ?", m.SourceCard, m.Person).Limit(1).Find(&src).Error; err != nil { |
| + return err |
| + } |
| + switch { |
| + case src.ID == "" || ended: |
| + m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| + case src.State != wire.CardOpen: |
| + if err := t.fillMirror(&m, src); err != nil { |
| + return err |
| + } |
| + case !running && src.CreatedAt.Before(t.now().Add(-staleQuestion)): |
| + m.State, m.Result = wire.CardResolved, t.copy("assistant.outcome.resolved") |
| + default: |
| + continue |
| + } |
| + m.Revision++ |
| + m.UpdatedAt = t.now() |
| + if err := t.db.Model(&cardRecord{}).Where("id = ?", m.ID).Select("state", "question", "options", "links", "result", "revision", "updated_at").Updates(&m).Error; err != nil { |
| + return err |
| + } |
| + if err := t.cardEvent(m); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// handoffRunning: one of the hand-off's Coordinator turns has not ended, |
| +// or a step of a task it follows is under way. |
| +func (t *txn) handoffRunning(h handoffRecord) (bool, error) { |
| + var n int64 |
| + if err := t.handoffTurns(h).Where("state IN ?", wire.InFlight).Count(&n).Error; err != nil || n > 0 { |
| + return n > 0, err |
| + } |
| + tasks, err := t.handoffTasks(h) |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, k := range tasks { |
| + steps, err := t.steps(k.ID) |
| + if err != nil { |
| + return false, err |
| + } |
| + if slices.ContainsFunc(steps, func(s stepRecord) bool { return !wire.StepTerminal(s.State) }) { |
| + return true, nil |
| + } |
| + } |
| + return false, nil |
| +} |
| + |
| +// settleStaleLegacyQuestions is the minute's look at every legacy |
| +// hand-off with an open mirrored question: nothing else may move one |
| +// that waits for a day, or that settled before this rule. |
| +func (t *txn) settleStaleLegacyQuestions() error { |
| + var ids []string |
| + if err := t.db.Model(&cardRecord{}).Where("lane = ? AND kind = ? AND state = ? AND coalesce(source_card, '') <> '' AND coalesce(handoff_id, '') <> ''", wire.LaneAssistant, wire.CardQuestion, wire.CardOpen).Distinct().Order("handoff_id").Pluck("handoff_id", &ids).Error; err != nil || len(ids) == 0 { |
| + return err |
| + } |
| + var rows []handoffRecord |
| + if err := t.db.Where("id IN ? AND coalesce(lane, '') = ''", ids).Order("created_at, id").Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + for _, h := range rows { |
| + if err := t.settleLegacyQuestions(h); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
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) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/thintest/assistant_legacy_question_contract_test.go b/internal/thintest/assistant_legacy_question_contract_test.go| new file mode 100644 |
| index 00000000..0d1f759f |
| --- /dev/null |
| +++ b/internal/thintest/assistant_legacy_question_contract_test.go |
| @@ -0,0 +1,221 @@ |
| +package thintest |
| + |
| +import ( |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Stale legacy question cards (Paul's live check, 2026-11-14). A legacy |
| +// hand-off (lane "") mirrored its team question into the Assistant lane |
| +// as a question card (slice 1, kept by ruling P3j). Such a card follows |
| +// its source while the source changes; it is resolved, with the approved |
| +// resolved line, once the hand-off is cancelled or its work has settled |
| +// or stopped, or once its source has been open for a day with no answer |
| +// and none of the hand-off's work is running. Each time the card's |
| +// event in the Assistant lane carries the resolution. |
| + |
| +const legacyQuestion = "Which login page?" |
| + |
| +// legacyMirror is a legacy hand-off whose turn asked the person a |
| +// question, that turn ended, and the question mirrored into the |
| +// Assistant lane as slice 1 did: request, the turn, the team question |
| +// card and its Assistant mirror. With task, the turn records a task |
| +// first (its id is task's). |
| +func (o *teamRig) legacyMirror(key string, task *string) (request, turn, source, mirror string) { |
| + o.t.Helper() |
| + o.ask("Can we fix a bug in Tito? Login is broken") |
| + request, turn = o.legacyHandoff(key, "Login is broken") |
| + o.in(turn, func() { |
| + if task != nil { |
| + *task = o.record(key+"-rec", "Login page") |
| + } |
| + if res := o.call(key+"-ask", wire.ToolAskPerson, map[string]any{"question": legacyQuestion, "options": []string{"Web", "App"}}); res.Code != "asked" { |
| + o.t.Fatalf("ask %+v", res) |
| + } |
| + }) |
| + o.reply(turn) |
| + source = o.teamCard(wire.CardQuestion, turn, "").ID |
| + if source == "" { |
| + o.t.Fatal("no team question") |
| + } |
| + mirror = "c_mirror" + key |
| + o.exec("INSERT INTO chat_cards(id, person, kind, state, turn_id, question, options, revision, created_at, updated_at, lane, source_card, links, result, handoff_id) SELECT ?, person, kind, state, turn_id, question, '[{\"value\":\"Web\",\"label\":\"Web\"},{\"value\":\"App\",\"label\":\"App\"}]', 1, created_at, updated_at, ?, id, '[]', '', ? FROM chat_cards WHERE id = ?", mirror, wire.LaneAssistant, request, source) |
| + if c := o.mirrorCard(mirror); c.State != wire.CardOpen { |
| + o.t.Fatalf("the mirror %+v is not open", c) |
| + } |
| + return request, turn, source, mirror |
| +} |
| + |
| +// mirrorCard is the Assistant snapshot's card id (zero when absent). |
| +func (o *teamRig) mirrorCard(id string) wire.AssistantCard { |
| + o.t.Helper() |
| + for _, c := range o.assistantCards() { |
| + if c.ID == id { |
| + return c |
| + } |
| + } |
| + return wire.AssistantCard{} |
| +} |
| + |
| +// cardState is a card's state as stored. |
| +func (o *teamRig) cardState(id string) string { |
| + o.t.Helper() |
| + var st string |
| + if err := o.inst.DB.Writer().QueryRow("SELECT state FROM chat_cards WHERE id = ?", id).Scan(&st); err != nil { |
| + o.t.Fatal(err) |
| + } |
| + return st |
| +} |
| + |
| +// tick is the instance's housekeeping minute. |
| +func (o *teamRig) tick() { |
| + o.t.Helper() |
| + if err := o.inst.Store.Chat().HousekeepingTick(o.ctx); err != nil { |
| + o.t.Fatal(err) |
| + } |
| +} |
| + |
| +// resolvedMirror fails unless the mirror is resolved with the approved |
| +// line, gone from the open cards, and its newest event says so. |
| +func (o *teamRig) resolvedMirror(id string) { |
| + o.t.Helper() |
| + line := equipo.RunnerCopy("assistant.outcome.resolved") |
| + o.until("the mirror resolved", func() bool { return o.mirrorCard(id).State == wire.CardResolved }) |
| + if c := o.mirrorCard(id); c.Result != line || c.Options == nil || c.Links == nil { |
| + o.t.Fatalf("the resolved mirror %+v", c) |
| + } |
| + events := o.jobEvents(id) |
| + if len(events) == 0 { |
| + o.t.Fatal("no event for the mirror") |
| + } |
| + if last := events[len(events)-1]; last.State != wire.CardResolved || last.Result != line { |
| + o.t.Fatalf("the mirror's event %+v", last) |
| + } |
| +} |
| + |
| +// openMirror fails unless the mirror is still open and no event moved it. |
| +func (o *teamRig) openMirror(id string) { |
| + o.t.Helper() |
| + if c := o.mirrorCard(id); c.State != wire.CardOpen { |
| + o.t.Fatalf("the mirror %+v closed", c) |
| + } |
| + for _, e := range o.jobEvents(id) { |
| + if e.State != wire.CardOpen { |
| + o.t.Fatalf("an event closed the mirror: %+v", e) |
| + } |
| + } |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionCancelled: the person's request |
| +// cancelled, its mirrored question is resolved. |
| +func TestContractAssistantLegacyQuestionCancelled(t *testing.T) { |
| + o := newTeamRig(t) |
| + request, _, _, mirror := o.legacyMirror("qc", nil) |
| + o.in(o.turn, func() { |
| + if res := o.use("qc-cancel", "team_cancel", map[string]any{"request": request}); res.IsError { |
| + t.Fatalf("team_cancel %+v", res) |
| + } |
| + }) |
| + o.resolvedMirror(mirror) |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionSettled: the hand-off's work |
| +// settled (its task ended), its mirrored question is resolved. |
| +func TestContractAssistantLegacyQuestionSettled(t *testing.T) { |
| + o := newTeamRig(t) |
| + var id string |
| + request, _, _, mirror := o.legacyMirror("qs", &id) |
| + if !o.linked(request)[id] { |
| + t.Fatal("the task is not the hand-off's") |
| + } |
| + o.openMirror(mirror) |
| + o.exec("UPDATE chat_tasks SET stage = ? WHERE id = ?", wire.StageDone, id) |
| + o.tick() |
| + o.resolvedMirror(mirror) |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionStopped: the hand-off's work |
| +// stopped and needs someone (a step failed, its end proven), its |
| +// mirrored question is |
| +// resolved when the hand-off hears of it. |
| +func TestContractAssistantLegacyQuestionStopped(t *testing.T) { |
| + o := newTeamRig(t) |
| + var id string |
| + request, _, _, mirror := o.legacyMirror("qp", &id) |
| + if !o.linked(request)[id] { |
| + t.Fatal("the task is not the hand-off's") |
| + } |
| + o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, terminated, attempt, created_at, updated_at) VALUES ('s_qp', ?, ?, ?, 1, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepFailed) |
| + o.tick() |
| + o.resolvedMirror(mirror) |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionSourceAnswered: the source question |
| +// answered (here by team_reply), the mirror follows it out of the open |
| +// cards, and its event says so. |
| +func TestContractAssistantLegacyQuestionSourceAnswered(t *testing.T) { |
| + o := newTeamRig(t) |
| + request, _, source, mirror := o.legacyMirror("qa", nil) |
| + replied(t, o.teamReply("qa-reply", request, "App"), request) |
| + o.until("the source answered", func() bool { return o.cardState(source) == wire.CardAnswered }) |
| + o.until("the mirror closed", func() bool { return o.mirrorCard(mirror).State != wire.CardOpen }) |
| + if c := o.mirrorCard(mirror); c.State != wire.CardAnswered { |
| + t.Fatalf("the mirror %+v", c) |
| + } |
| + events := o.jobEvents(mirror) |
| + if len(events) == 0 || events[len(events)-1].State != wire.CardAnswered { |
| + t.Fatalf("the mirror's events %+v", events) |
| + } |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionSourceWithdrawn: a source question |
| +// no longer open but not answered (withdrawn) leaves its mirror |
| +// resolved, even when nothing moved the mirror at the time and the |
| +// hand-off's work still runs. |
| +func TestContractAssistantLegacyQuestionSourceWithdrawn(t *testing.T) { |
| + o := newTeamRig(t) |
| + var id string |
| + _, _, source, mirror := o.legacyMirror("qw", &id) |
| + o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, attempt, created_at, updated_at) VALUES ('s_qw', ?, ?, ?, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepRunning) |
| + o.exec("UPDATE chat_cards SET state = ? WHERE id = ?", wire.CardResolved, source) |
| + o.tick() |
| + o.resolvedMirror(mirror) |
| +} |
| + |
| +// TestContractAssistantLegacyQuestionStale: a source question open for |
| +// more than a day with no answer is resolved when none of the hand-off's |
| +// work runs; before the day is out, or while its work runs (a step under |
| +// way), it stays. |
| +func TestContractAssistantLegacyQuestionStale(t *testing.T) { |
| + o := newTeamRig(t) |
| + var id string |
| + request, _, source, mirror := o.legacyMirror("qx", &id) |
| + if !o.linked(request)[id] { |
| + t.Fatal("the task is not the hand-off's") |
| + } |
| + var asked time.Time |
| + if err := o.inst.DB.Writer().QueryRow("SELECT created_at FROM chat_cards WHERE id = ?", source).Scan(&asked); err != nil { |
| + t.Fatal(err) |
| + } |
| + // Its work does not run (a step done, the task not settled), but the |
| + // question is under a day old: it stays. |
| + o.exec("INSERT INTO chat_steps(id, task_id, specialist, state, attempt, created_at, updated_at) VALUES ('s_qx', ?, ?, ?, 1, datetime('now'), datetime('now'))", id, wire.SpecialistEngineering, wire.StepDone) |
| + o.exec("UPDATE chat_cards SET created_at = ? WHERE id = ?", asked.Add(-23*time.Hour), source) |
| + o.tick() |
| + o.openMirror(mirror) |
| + // A day old, but its work runs again: it stays. |
| + o.exec("UPDATE chat_steps SET state = ? WHERE id = 's_qx'", wire.StepRunning) |
| + o.exec("UPDATE chat_cards SET created_at = ? WHERE id = ?", asked.Add(-25*time.Hour), source) |
| + o.tick() |
| + o.openMirror(mirror) |
| + // The work no longer runs: resolved; the team's own question stays. |
| + o.exec("UPDATE chat_steps SET state = ? WHERE id = 's_qx'", wire.StepDone) |
| + o.tick() |
| + o.resolvedMirror(mirror) |
| + if st := o.cardState(source); st != wire.CardOpen { |
| + t.Fatalf("the team's own question moved to %s", st) |
| + } |
| +} |