oficina / equipo Public

Keep glances live-only, first, fresh and free of machinery

Review fix round 1 (Astra) of 1ab53c35, four findings:

1. Never stored. The instance no longer writes a glance to chat_events:
   it publishes it after commit to the person's streams open in this
   process (Hub.Live/publish), written with no id line and cursor 0, so
   a reconnect never replays it. Live events published before a batch
   was read go out before that batch. Backstop: a glance for a turn
   that already has a delta is dropped. Docs say so (still marked for
   copy review).
2. Never after its delta. The link takes glances, activity and deltas
   under one lock (takeQueued). TestLinkGlanceAndDeltaQueuedMidFlush
   queues a glance and its delta mid-flush through a test seam
   (afterTake) and needs the glance first.
3. Newest message only. A Claude process answers one glance and is then
   spent (not up); the engine warms a fresh one after the turn. A Codex
   glance after the first starts its own thread on the warm app-server.
   The fakes answer "again" when the conversation held earlier turns;
   headless glance checks two consecutive glances on both providers.
4. Leak rules. wire.GlanceText also refuses repositor, deploy and
   specialist anywhere; check(s), repo(s) and review(s) as whole words
   ("Checking your calendar" stays); links and paths (://, www., /, \);
   hex runs of 7 or more with a digit, or 16 or more.

Each fix was broken once and a test failed; the Claude turns==0 check
stays as a harness backstop behind the spent flag, which masks it.
Budgets re-measured for wire, thin, chat, headless and thintest.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 7bb50d431adf955a7920f0200009b6cd0fca2d50 parent 1ab53c3
18 files changed, +316 −47
  • .rastrillo/budgets.txt +5 −5
  • docs/api/equipo-v1.md +1 −1
  • internal/equipo/chat/assistant_http.go +1 −1
  • internal/equipo/chat/http.go +32 −2
  • internal/equipo/chat/hub.go +44 −2
  • internal/equipo/chat/runner.go +22 −5
  • internal/equipo/chat/store.go +12 −0
  • internal/fakeclaude/fake.go +1 −1
  • internal/fakeclaude/glance.go +9 −4
  • internal/fakecodex/fake.go +6 −1
  • internal/headless/assistant_test.go +41 −0
  • internal/runner/thin/claude.go +5 −0
  • internal/runner/thin/glance.go +24 −6
  • internal/runner/thin/glance_test.go +28 −1
  • internal/runner/thin/link.go +15 −14
  • internal/thintest/assistant_glance_contract_test.go +26 −1
  • internal/wire/glance.go +40 −2
  • internal/wire/glance_test.go +4 −1

CI cancelled — superseded by a newer push — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 1c7d2c10..6e84e7af 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re
time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage.
size internal/equipo 20392 - The web view models and templates share rendering; Roster adds bylines, fact details, sub-chat views, Stop and compact reports. Measured 20392 source lines.
-size internal/wire 6309 - Runner and person API types share Encode. 21 adds Copy fields, 22 job lanes and cards, 23 the glance frame and its guard. Measured 6309 source lines.
+size internal/wire 6347 - Runner and person API types share Encode. 21 adds Copy fields, 22 job lanes and cards, 23 the glance frame and its guard. Measured 6347 source lines.
size internal/equipotest - 13400 Task 21 repairs historical migration and conversation fixtures after Plan 3. Measured 13024 test lines; the 300s time ceiling is unchanged.
time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded);
time internal/runner 330s Plan 3 CI repair measured 292.120s for the full package (controller CI 472.184s).
@@ -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 26205 18448 Runner state, connections and execution share private helpers: Copy, job lanes, the Assistant's warm-up and glance. Measured 26205 source, 18448 test lines.
+size internal/runner/thin 26229 18538 Runner state, connections and execution share private helpers: Copy, job lanes, the Assistant's warm-up and glance. Measured 26229 source, 18538 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 28677 - Transactional conversation store shares authority and dispatch helpers; roster reads; legacy mirrors; the glance relay. Measured 28677 source lines.
+size internal/equipo/chat 28778 - Transactional conversation store shares authority and dispatch helpers; roster reads; legacy mirrors; the glance relay. Measured 28778 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 - 11017 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11017 test lines.
-size internal/thintest - 29125 Contract and browser tests share one instance harness: Assistant hand-off, outcome, job, legacy question and glance contracts, Roster guards. Measured 29125 test lines.
+size internal/headless - 11058 End-to-end scenarios through a real runner and instance: Copy setting, the Assistant's job threads, streamed replies, warm start, glance. Measured 11058 test lines.
+size internal/thintest - 29150 Contract and browser tests share one instance harness: Assistant hand-off, outcome, job, legacy question and glance contracts, Roster guards. Measured 29150 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/docs/api/equipo-v1.md b/docs/api/equipo-v1.md
index bd25bcfe..be51d82f 100644
--- a/docs/api/equipo-v1.md
+++ b/docs/api/equipo-v1.md
@@ -91,7 +91,7 @@ A new message is `201`, with the message and its turn. The same key and text aga
Follow the conversation with `GET /api/v1/assistant/events?after=<cursor>`, a stream of Server-Sent Events. `after` wins over `Last-Event-ID`. With neither, the stream starts at the newest event. The stream opens with `retry: 2000`, then sends each event as `id: <cursor>`, `event: <type>` and `data:` with the event as JSON, whose own `data` field holds the message, turn, delta, glance, card or activity. The types are `message`, `turn`, `delta`, `glance`, `card` and `activity`, and a `ping` comes every 20 seconds. A cursor that is too old is `410 cursor_expired`. Read the snapshot again and follow from its cursor.
<!-- COPY REVIEW REQUIRED -->
-When a turn that answers you starts, a `glance` event may come first: one short line to show while the Assistant works on its answer, such as "Looking into your invoices". Its `data` has `turn_id` and `text`. The text is one line of at most 8 words and 60 characters, with no markdown. Show it for the turn until the turn's first `delta` or its message arrives. A glance is never a message: no snapshot or message list holds it. Not every turn has one, none comes after the turn's first `delta` or once the turn has ended, and a `team_update` turn never has one. Glances need your runner on protocol 23 or later.
+When a turn that answers you starts, a `glance` event may come first: one short line to show while the Assistant works on its answer, such as "Looking into your invoices". Its `data` has `turn_id` and `text`. The text is one line of at most 8 words and 60 characters, with no markdown. Show it for the turn until the turn's first `delta` or its message arrives. A glance is never a message, and nothing keeps it: only a stream open at the time gets it, with no `id:` line and a `cursor` of 0, and reading the events again does not bring it back. Not every turn has one, none comes after the turn's first `delta` or once the turn has ended, and a `team_update` turn never has one. Glances need your runner on protocol 23 or later.
A message has `role` `person` or `assistant`. A turn's `kind` is empty when it answers you, and `team_update` when the Assistant tells you, on its own, what the team did with something you asked for. A `team_update` turn may end with no message: its state is `replied` and its `reply_id` is empty. Cancel a turn in flight with `POST /api/v1/assistant/turns/{id}/cancel` and an empty JSON object. The answer is `202` with the turn's `attempt`, or `409 turn_ended` once the turn has ended.
diff --git a/internal/equipo/chat/assistant_http.go b/internal/equipo/chat/assistant_http.go
index 6fb38158..b74258c4 100644
--- a/internal/equipo/chat/assistant_http.go
+++ b/internal/equipo/chat/assistant_http.go
@@ -38,7 +38,7 @@ func (h *HTTP) MountAssistant(r chi.Router) {
h.assistantAnswer(w, r, p, lane)
}))
r.Get("/events", h.bearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
- h.stream(w, r, p, lane.Events)
+ h.stream(w, r, p, lane.lane, lane.Events)
}))
r.Put("/host", h.bearer(func(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) {
h.assistantHost(w, r, p, lane)
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go
index 1e5873a9..68f10178 100644
--- a/internal/equipo/chat/http.go
+++ b/internal/equipo/chat/http.go
@@ -605,13 +605,16 @@ func (h *HTTP) events(w http.ResponseWriter, r *http.Request) {
h.Failure(w, r, err)
return
}
- h.stream(w, r, p, h.Store.Events)
+ h.stream(w, r, p, wire.LaneCoordinator, h.Store.Events)
}
// stream serves a lane's events as Server-Sent Events from the request's
// cursor, rechecking the person before each batch and ping.
-func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, read func(context.Context, string, int64, int) ([]wire.Event, error)) {
+func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, lane string, read func(context.Context, string, int64, int) ([]wire.Event, error)) {
ctx := personapi.WithVerifiedPrincipal(r.Context(), p)
+ // Live-only events (a glance) come from the moment the stream opens.
+ live, stop := h.Store.Hub().Live(p.Address, lane)
+ defer stop()
after, err := h.cursor(ctx, r)
if err != nil {
h.fail(w, r, err)
@@ -634,9 +637,32 @@ func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.Person
defer ping.Stop()
poll := time.NewTicker(streamPoll)
defer poll.Stop()
+ // writeLive sends one live-only event: no id line, so a client's
+ // cursor never moves to it.
+ writeLive := func(e wire.Event) bool {
+ if _, err := h.Authenticate(r); err != nil {
+ return false
+ }
+ _ = rc.SetWriteDeadline(time.Now().Add(30 * time.Second))
+ raw, _ := json.Marshal(e)
+ _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.Type, raw)
+ return err == nil && rc.Flush() == nil
+ }
batch := first
for {
wake := h.Store.Hub().Wait(p.Address)
+ // What went live before this batch was read goes before it: a
+ // glance before its turn's first delta.
+ for drained := false; !drained; {
+ select {
+ case e := <-live:
+ if !writeLive(e) {
+ return
+ }
+ default:
+ drained = true
+ }
+ }
if len(batch) > 0 {
// Roster removal or device revocation closes the stream here.
if _, err := h.Authenticate(r); err != nil {
@@ -667,6 +693,10 @@ func (h *HTTP) stream(w http.ResponseWriter, r *http.Request, p personapi.Person
if _, err := io.WriteString(w, "event: ping\ndata: {\"type\":\"ping\"}\n\n"); err != nil || rc.Flush() != nil {
return
}
+ case e := <-live:
+ if !writeLive(e) {
+ return
+ }
case <-wake:
case <-poll.C:
}
diff --git a/internal/equipo/chat/hub.go b/internal/equipo/chat/hub.go
index 71ec7b15..de56ed80 100644
--- a/internal/equipo/chat/hub.go
+++ b/internal/equipo/chat/hub.go
@@ -1,6 +1,10 @@
package chat
-import "sync"
+import (
+ "sync"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
// Hub wakes streams in this process after a commit. Other processes (an
// overlapping deploy) are covered by each stream's one-second poll.
@@ -11,10 +15,48 @@ type Hub struct {
next int64
closing chan struct{}
closed bool
+ // live are the streams open in this process, for events that are
+ // never stored (a glance): sent to whoever is following now, and
+ // missed by anyone who is not.
+ live map[*liveSub]bool
+}
+
+type liveSub struct {
+ person, lane string
+ ch chan wire.Event
}
func NewHub() *Hub {
- return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{})}
+ return &Hub{waiters: map[string]chan struct{}{}, runners: map[string]registration{}, closing: make(chan struct{}), live: map[*liveSub]bool{}}
+}
+
+// Live follows the person's live-only events in one lane, until stop.
+// A stream that falls behind loses them; they are never replayed.
+func (h *Hub) Live(person, lane string) (events <-chan wire.Event, stop func()) {
+ sub := &liveSub{person: person, lane: lane, ch: make(chan wire.Event, 16)}
+ h.mu.Lock()
+ h.live[sub] = true
+ h.mu.Unlock()
+ return sub.ch, func() {
+ h.mu.Lock()
+ delete(h.live, sub)
+ h.mu.Unlock()
+ }
+}
+
+// publish hands a live-only event to the person's streams in its lane
+// in this process, without waiting for any.
+func (h *Hub) publish(person, lane string, e wire.Event) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ for sub := range h.live {
+ if sub.person == person && sub.lane == lane {
+ select {
+ case sub.ch <- e:
+ default:
+ }
+ }
+ }
}
// Wait returns a channel closed at the person's next wake.
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index d44b3bd1..4369b165 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -443,12 +443,14 @@ func (t *txn) delta(l Lease, d *wire.DeltaReport) error {
return t.event(r.Lane, r.Person, wire.EventDelta, "turn", r.ID, 0, r.ID, "", r.Attempt, wire.Delta{TurnID: r.ID, Offset: d.Offset, Text: d.Text})
}
-// glance publishes an Assistant turn's instant first line on the
-// Assistant's stream: a glance event, revision 0 like a delta, never a
-// message, so no snapshot holds it. It goes only for a live Assistant
+// glance publishes an Assistant turn's instant first line to the
+// Assistant's streams following now: a glance event, revision 0 and no
+// cursor, never stored as a message or an event, so no snapshot or
+// replay holds it. It goes only for a live Assistant
// person turn at its attempt, from the person's primary runner speaking
// protocol 23, and only when its text is already one clean line
-// (wire.GlanceText). Anything else is dropped, quietly: a glance is a
+// (wire.GlanceText), and before the turn's first delta. Anything else is
+// dropped, quietly: a glance is a
// nicety, never worth the runner's stream.
func (t *txn) glance(l Lease, g *wire.GlanceReport) error {
if l.Protocol < wire.ProtocolGlance {
@@ -468,7 +470,22 @@ func (t *txn) glance(l Lease, g *wire.GlanceReport) error {
if r.Lane != wire.LaneAssistant || r.Kind != wire.TurnPerson || wire.Terminal(r.State) || g.Attempt != r.Attempt {
return nil
}
- return t.event(r.Lane, r.Person, wire.EventGlance, "turn", r.ID, 0, r.ID, "", r.Attempt, wire.Glance{TurnID: r.ID, Text: text})
+ // The reply began: its words already replace the glance.
+ var streamed int64
+ if err := t.db.Model(&eventRecord{}).Where("person = ? AND lane = ? AND type = ? AND body LIKE ?", r.Person, r.Lane, wire.EventDelta, `%"turn_id":"`+r.ID+`"%`).Count(&streamed).Error; err != nil {
+ return err
+ }
+ if streamed > 0 {
+ return nil
+ }
+ data, err := json.Marshal(wire.Glance{TurnID: r.ID, Text: text})
+ if err != nil {
+ return err
+ }
+ // Live only: it goes to the streams following now and nowhere else,
+ // with no cursor, so nothing stores or replays it.
+ t.live = append(t.live, liveEvent{person: r.Person, lane: r.Lane, event: wire.Event{Type: wire.EventGlance, Resource: "turn", ID: r.ID, TurnID: r.ID, Attempt: r.Attempt, Data: data}})
+ return nil
}
// reply commits the coordinator's message, ends the turn and starts the
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index 9991b1d0..cda18f97 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -153,6 +153,9 @@ func (s *Store) tx(ctx context.Context, fn func(*txn) error) error {
if err != nil {
return err
}
+ for _, l := range t.live {
+ s.hub.publish(l.person, l.lane, l.event)
+ }
for person := range t.touched {
s.hub.Wake(person)
}
@@ -182,6 +185,9 @@ type txn struct {
failures []hkFailureRecord
// pending: the transaction stored a call for ServeRemoteCalls.
pending bool
+ // live are events for the streams following now, never stored,
+ // published once the transaction commits.
+ live []liveEvent
}
func (t *txn) now() time.Time { return t.s.now() }
@@ -200,6 +206,12 @@ func (t *txn) event(lane, person, kind, resource, id string, revision int64, tur
return t.db.Create(&eventRecord{Person: person, Type: kind, Body: string(body), CreatedAt: t.now(), Lane: lane}).Error
}
+// liveEvent is one live-only event (Hub.publish).
+type liveEvent struct {
+ person, lane string
+ event wire.Event
+}
+
func (t *txn) turnEvent(r turnRecord) error {
v, err := t.turnView(r)
if err != nil {
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index 3cc98ad7..59a5b540 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -1034,7 +1034,7 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int {
continue
}
// A glance: one short line from the small model, no tools.
- if line, pause, fail, ok := Glance(prompt); ok {
+ if line, pause, fail, ok := Glance(prompt, f.resume || turn > 1); ok {
time.Sleep(pause)
f.record(prompt, line)
emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_glance_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": line}}}, "uuid": fmt.Sprintf("assistant-%d", turn)})
diff --git a/internal/fakeclaude/glance.go b/internal/fakeclaude/glance.go
index 0b3a8fab..e32da3d2 100644
--- a/internal/fakeclaude/glance.go
+++ b/internal/fakeclaude/glance.go
@@ -11,10 +11,12 @@ import (
const GlancePrefix = "Write the line a person sees while their assistant starts on their message."
// Glance answers a glance prompt: "Looking into that now", or "Hi
-// <name>" for a greeting when the prompt names the person. In the
-// message, glanceslow takes five seconds, glancefail fails and
-// glanceteam names the team. ok is false for any other prompt.
-func Glance(prompt string) (line string, pause time.Duration, fail, ok bool) {
+// <name>" for a greeting when the prompt names the person, and "Looking
+// into that again" when the conversation already held earlier turns (a
+// glance must see the newest message alone). In the message, glanceslow
+// takes five seconds, glancefail fails and glanceteam names the team. ok
+// is false for any other prompt.
+func Glance(prompt string, earlier bool) (line string, pause time.Duration, fail, ok bool) {
if !strings.HasPrefix(prompt, GlancePrefix) {
return "", 0, false, false
}
@@ -25,6 +27,9 @@ func Glance(prompt string) (line string, pause time.Duration, fail, ok bool) {
name, _, _ = strings.Cut(name, ".")
line = "Hi " + name
}
+ if earlier {
+ line = "Looking into that again"
+ }
switch {
case strings.Contains(message, "glanceslow"):
pause = 5 * time.Second
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go
index 67f2913e..68cb982f 100644
--- a/internal/fakecodex/fake.go
+++ b/internal/fakecodex/fake.go
@@ -442,7 +442,12 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) {
return
}
// A glance: one short line from the small model, no tools.
- if line, pause, fail, ok := fakeclaude.Glance(prompt); ok {
+ earlier := false
+ if path := s.rollout(thread); path != "" {
+ raw, _ := os.ReadFile(path)
+ earlier = strings.Contains(string(raw), `"type":"agent"`)
+ }
+ if line, pause, fail, ok := fakeclaude.Glance(prompt, earlier); ok {
select {
case <-stop:
case <-time.After(pause):
diff --git a/internal/headless/assistant_test.go b/internal/headless/assistant_test.go
index eaa3f9d0..e85d6bb0 100644
--- a/internal/headless/assistant_test.go
+++ b/internal/headless/assistant_test.go
@@ -596,6 +596,35 @@ func TestHeadlessAssistant(t *testing.T) {
if line := phaseLine(t, logs, sent.Turn.ID); !strings.Contains(line, "glance=sent") {
t.Fatalf("phase line %s", line)
}
+ // The next glance sees the newest message alone, not the
+ // last one nor its line: a fresh conversation, still warm.
+ waitGlanceWarm(t, logs, map[string]int{"claude": 2, "codex": 1}[provider])
+ next, err := a.Send(ctx, "Now the invoices please. pause:1000", key())
+ if err != nil {
+ t.Fatal(err)
+ }
+ var second wire.Glance
+ for second.TurnID == "" {
+ select {
+ case e, ok := <-s.Events:
+ if !ok {
+ t.Fatal("the Assistant's stream ended")
+ }
+ if e.Type == wire.EventGlance && e.TurnID == next.Turn.ID {
+ json.Unmarshal(e.Data, &second)
+ }
+ if e.Type == wire.EventDelta && e.TurnID == next.Turn.ID && second.TurnID == "" {
+ t.Fatalf("on %s the second glance did not come first: %s", provider, phaseLine(t, logs, next.Turn.ID))
+ }
+ case <-ctx.Done():
+ t.Fatal("no second glance")
+ }
+ }
+ if second.Text != "Looking into that now" {
+ t.Fatalf("on %s the second glance saw earlier turns: %q", provider, second.Text)
+ }
+ assistantReply(t, ctx, a, next.Turn.ID)
+ waitGlanceWarm(t, logs, map[string]int{"claude": 3, "codex": 1}[provider])
var stored int
if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_messages WHERE text = ?", glance.Text).Scan(&stored); err != nil || stored != 0 {
t.Fatalf("%d stored glances %v", stored, err)
@@ -620,6 +649,18 @@ func TestHeadlessAssistant(t *testing.T) {
})
}
+// waitGlanceWarm waits for the runner's n-th glance warm-up.
+func waitGlanceWarm(t *testing.T, logs *lockedBuffer, n int) {
+ t.Helper()
+ deadline := time.Now().Add(60 * time.Second)
+ for strings.Count(logs.String(), `msg="assistant glance warm" outcome=warm`) < n {
+ if time.Now().After(deadline) {
+ t.Fatalf("no glance warm-up %d:\n%s", n, logs.String())
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
// drain reads what the stream has now, without waiting.
func drain(s *thintest.Stream) []wire.Event {
var out []wire.Event
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index c1a8f5bf..90c64b79 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -543,6 +543,11 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st
func (c *claudeCoordinator) Warm(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
+ if c.proc != nil && c.profile.ephemeral && !c.up.Load() {
+ // A glance's spent process: a fresh one takes its place.
+ c.stopTimers()
+ c.stop(true)
+ }
if c.proc != nil {
return nil
}
diff --git a/internal/runner/thin/glance.go b/internal/runner/thin/glance.go
index e8f99b69..c60e1d0d 100644
--- a/internal/runner/thin/glance.go
+++ b/internal/runner/thin/glance.go
@@ -55,8 +55,9 @@ const (
DefaultGlanceSlots = 2
// glanceMessage bounds the newest message a glance reads, in bytes.
glanceMessage = 500
- // glanceTurns is how many glances one process answers before it
- // closes, so its context stays small; the next is warmed afresh.
+ // glanceTurns is how many glances one Codex process answers, each on
+ // a thread of its own, before it closes; the next is warmed afresh.
+ // A Claude process answers one: its session is its only conversation.
glanceTurns = 20
// glanceFresh is what a glance needs of its copy beyond the margin.
glanceFresh = 30 * time.Second
@@ -374,16 +375,17 @@ func (c *coordBase) workspace() string {
// Up reports whether the harness's process is up.
func (c *coordBase) Up() bool { return c.up.Load() }
-// glanceReady is the check before a glance on a warm process: up, not
-// exited, its copy fresh for the glance and the stop after it, and not
-// past its turns. Otherwise the process stops and the glance is cold.
+// glanceReady is the check before a glance on a warm Claude process: up,
+// not exited, its copy fresh for the glance and the stop after it, and
+// unused, so the glance's conversation holds nothing before it.
+// Otherwise the process stops and the glance is cold.
func glanceReady(p *claudeProcess, margin time.Duration) bool {
select {
case <-p.exited:
return false
default:
}
- return time.Until(p.lease.FreshUntil()) > margin+glanceFresh && p.turns < glanceTurns
+ return time.Until(p.lease.FreshUntil()) > margin+glanceFresh && p.turns == 0
}
// Glance writes one glance prompt to the warm Claude process and returns
@@ -450,6 +452,10 @@ func (c *claudeCoordinator) Glance(ctx context.Context, prompt string) (string,
return "", errGlanceFailed
}
p.turns++
+ // Spent: the next glance needs a fresh session, so the
+ // harness is no longer up; the engine warms a new one
+ // after the turn (Warm replaces this process).
+ c.up.Store(false)
c.idle, c.idleAt = time.AfterFunc(c.o.WarmIdle, c.idleExit), time.Now().Add(c.o.WarmIdle)
return res.Text, nil
}
@@ -486,6 +492,18 @@ func (c *codexCoordinator) Glance(ctx context.Context, prompt string) (string, e
c.stop(false)
return "", err
}
+ // Each glance on a thread of its own: the newest message alone, never
+ // an earlier glance's. The warm-up's thread serves the first.
+ if p.turns > 0 {
+ raw, _, err := p.rpc.Call(ctx, "thread/start", codex.ThreadParams(p.policy, ""))
+ if err == nil {
+ p.thread, err = codex.CheckThread(raw, c.threadModel(), "")
+ }
+ if err != nil {
+ c.stop(false)
+ return "", errors.Join(errGlanceFailed, err)
+ }
+ }
raw, _, err := p.rpc.Call(ctx, "turn/start", codex.TurnParams(p.policy, p.thread, prompt))
var started struct {
Turn struct{ ID string } `json:"turn"`
diff --git a/internal/runner/thin/glance_test.go b/internal/runner/thin/glance_test.go
index cabd658e..f81fad22 100644
--- a/internal/runner/thin/glance_test.go
+++ b/internal/runner/thin/glance_test.go
@@ -8,6 +8,7 @@ import (
"strconv"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -429,7 +430,7 @@ func order(t *testing.T, c *websocket.Conn, protocol int) {
if err != nil {
t.Fatal(err)
}
- if g, ok := body.(*wire.GlanceReport); ok && (g.TurnID != "t_1" || g.Attempt != 1 || g.Text != "Looking now") {
+ if g, ok := body.(*wire.GlanceReport); ok && (g.Attempt != 1 || g.Text != "Looking now") {
t.Fatalf("glance %+v", g)
}
if f.Type == wire.FrameGlance || f.Type == wire.FrameDelta {
@@ -445,3 +446,29 @@ func order(t *testing.T, c *websocket.Conn, protocol int) {
}
}
}
+
+// A glance and its delta queued while a flush is under way (after it
+// took the queue) both go in the next flush, glance first: never the
+// delta in this flush and the glance after it.
+func TestLinkGlanceAndDeltaQueuedMidFlush(t *testing.T) {
+ inst := newFakeInstance(t)
+ var once sync.Once
+ var armed atomic.Pointer[Link]
+ afterTake = func() {
+ if link := armed.Load(); link != nil {
+ once.Do(func() {
+ link.Glance(wire.GlanceReport{TurnID: "t_mid", Attempt: 1, Text: "Looking now"})
+ link.Delta(wire.DeltaReport{TurnID: "t_mid", Attempt: 1, Text: "Hi"})
+ })
+ }
+ }
+ t.Cleanup(func() { afterTake = nil })
+ link, _, _, _ := startLink(t, inst.url, &stubCoordinator{})
+ c := <-inst.conns
+ read(t, c, wire.FrameHello)
+ write(t, c, []byte(`{"id":"i-welcome","type":"welcome","data":{"generation":3,"runner_id":"RUNNER1","protocol":23,"role":"primary"}}`))
+ read(t, c, wire.FrameSync)
+ armed.Store(link)
+ link.Notify()
+ order(t, c, wire.ProtocolGlance)
+}
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go
index 115088d0..6fe45c9c 100644
--- a/internal/runner/thin/link.go
+++ b/internal/runner/thin/link.go
@@ -402,20 +402,15 @@ func (l *Link) Glances() bool {
return p >= wire.ProtocolGlance
}
-func (l *Link) takeGlances() []wire.GlanceReport {
+// takeQueued takes the glances, activity, deltas and a hello request
+// under one lock: a glance and the delta queued after it are taken
+// together or not at all, so the glance is sent first.
+func (l *Link) takeQueued() ([]wire.GlanceReport, []wire.ActivityReport, []wire.DeltaReport, bool) {
l.mu.Lock()
defer l.mu.Unlock()
- out := l.glances
- l.glances = nil
- return out
-}
-
-func (l *Link) takeDeltas() ([]wire.ActivityReport, []wire.DeltaReport, bool) {
- l.mu.Lock()
- defer l.mu.Unlock()
- acts, out, hello := l.activity, l.pending, l.helloSoon
- l.activity, l.pending, l.helloSoon = nil, nil, false
- return acts, out, hello
+ glances, acts, out, hello := l.glances, l.activity, l.pending, l.helloSoon
+ l.glances, l.activity, l.pending, l.helloSoon = nil, nil, nil, false
+ return glances, acts, out, hello
}
// Run connects and reconnects until ctx ends or the lease is lost.
@@ -986,6 +981,10 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro
}
}
+// afterTake, set only by tests, runs in a flush right after it takes
+// what is queued.
+var afterTake func()
+
// write sends unacked outbox frames, then new ones, deltas and heartbeats.
func (l *Link) write(ctx context.Context, c *websocket.Conn) error {
var sent int64
@@ -1004,8 +1003,10 @@ func (l *Link) write(ctx context.Context, c *websocket.Conn) error {
}
flush := func() error {
// Glances first: a delta queued after one goes after it.
- glances := l.takeGlances()
- acts, deltas, hello := l.takeDeltas()
+ glances, acts, deltas, hello := l.takeQueued()
+ if afterTake != nil {
+ afterTake()
+ }
if hello {
if err := sendHello(); err != nil {
return err
diff --git a/internal/thintest/assistant_glance_contract_test.go b/internal/thintest/assistant_glance_contract_test.go
index 5279ae2a..f6e78fee 100644
--- a/internal/thintest/assistant_glance_contract_test.go
+++ b/internal/thintest/assistant_glance_contract_test.go
@@ -74,9 +74,29 @@ func TestContractAssistantGlance(t *testing.T) {
if json.Unmarshal(e.Data, &data) != nil || len(data) != 2 || data["turn_id"] != cmd.TurnID || data["text"] != "Starting on your website" {
t.Fatalf("glance data %s", e.Data)
}
- if e.Resource != "turn" || e.ID != cmd.TurnID || e.TurnID != cmd.TurnID || e.Revision != 0 || e.Attempt != 1 || e.MessageID != "" {
+ if e.Resource != "turn" || e.ID != cmd.TurnID || e.TurnID != cmd.TurnID || e.Revision != 0 || e.Attempt != 1 || e.MessageID != "" || e.Cursor != 0 {
t.Fatalf("glance event %+v", e)
}
+ // Live only: no event row holds it, and a stream that follows from
+ // before it (a reconnect) never sees it, though it sees the delta.
+ var rows int
+ if err := r.inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_events WHERE body LIKE ? OR type = ?", "%Starting on your website%", wire.EventGlance).Scan(&rows); err != nil || rows != 0 {
+ t.Fatalf("%d stored glance events %v", rows, err)
+ }
+ again, err := a.Open(r.ctx, snap.Cursor)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer again.Close()
+ var replay []wire.Event
+ assistEvents(t, again, "the replayed reply", &replay, func(es []wire.Event) bool {
+ return slices.ContainsFunc(es, func(e wire.Event) bool {
+ return e.Type == wire.EventMessage && e.TurnID == cmd.TurnID && bytes.Contains(e.Data, []byte(`"role":"assistant"`))
+ })
+ })
+ if g := glanceEvents(replay); len(g) != 0 || !slices.ContainsFunc(replay, func(e wire.Event) bool { return e.Type == wire.EventDelta }) {
+ t.Fatalf("replay %+v", replay)
+ }
snap, err = a.Snapshot(r.ctx)
if err != nil || len(snap.Messages) != 2 {
t.Fatalf("snapshot %+v %v", snap, err)
@@ -157,6 +177,11 @@ func TestContractAssistantGlanceDropped(t *testing.T) {
// The turn ends; a glance after that is late.
runner.Send(r.ctx, "d-reply", wire.FrameReply, wire.Reply{TurnID: cmd.TurnID, Attempt: 1, Text: "Hi."})
runner.Send(r.ctx, "d-late", wire.FrameGlance, wire.GlanceReport{TurnID: cmd.TurnID, Attempt: 1, Text: "After the reply"})
+ // Its reply began: a glance after the turn's first delta is late.
+ streamed := r.assistantTurn(runner, a, "and the calendar", "d-3")
+ runner.Send(r.ctx, "s-delta", wire.FrameDelta, wire.DeltaReport{TurnID: streamed.TurnID, Attempt: 1, Text: "Sure"})
+ runner.Send(r.ctx, "s-glance", wire.FrameGlance, wire.GlanceReport{TurnID: streamed.TurnID, Attempt: 1, Text: "Checking your calendar"})
+ runner.Send(r.ctx, "s-reply", wire.FrameReply, wire.Reply{TurnID: streamed.TurnID, Attempt: 1, Text: "Sure."})
next := r.assistantTurn(runner, a, "and the invoices", "d-2")
// A worker of the same person, speaking 23, is not the primary: its
// glance for the live turn is dropped (the lease check after it is
diff --git a/internal/wire/glance.go b/internal/wire/glance.go
index 905dc95d..a43295f4 100644
--- a/internal/wire/glance.go
+++ b/internal/wire/glance.go
@@ -16,8 +16,36 @@ const (
)
// glanceRefused are the words a glance never carries, in any case and
-// anywhere in a word: the machinery behind Base.
-var glanceRefused = []string{"equipo", "team", "runner", "task", "branch", "merge", "coordinator"}
+// anywhere in a word: the machinery behind Base (the Assistant lane's
+// leak rules).
+var glanceRefused = []string{"equipo", "team", "runner", "task", "branch", "merge", "coordinator", "repositor", "deploy", "specialist"}
+
+// glanceRefusedWords are refused as whole words only, so "Checking your
+// calendar" and "Reviewing your draft" stay plain speech.
+var glanceRefusedWords = map[string]bool{"check": true, "checks": true, "repo": true, "repos": true, "review": true, "reviews": true}
+
+// glanceRefusedMarks are a link or a path: never in a glance.
+var glanceRefusedMarks = []string{"://", "www.", "/", "\\"}
+
+// glanceHex says whether a word holds an identifier: a run of at least
+// seven hex digits with a digit in it (a short or full SHA), or of
+// sixteen with or without one.
+func glanceHex(word string) bool {
+ run, digit := 0, false
+ for _, r := range word + " " {
+ hex := r >= '0' && r <= '9' || r >= 'a' && r <= 'f'
+ if hex {
+ run++
+ digit = digit || r <= '9'
+ continue
+ }
+ if run >= 16 || run >= 7 && digit {
+ return true
+ }
+ run, digit = 0, false
+ }
+ return false
+}
// glanceMarkup is markdown punctuation, dropped from a glance.
const glanceMarkup = "*_`#>~[]|\"“”"
@@ -73,5 +101,15 @@ func GlanceText(raw string) (string, bool) {
return "", false
}
}
+ for _, m := range glanceRefusedMarks {
+ if strings.Contains(lower, m) {
+ return "", false
+ }
+ }
+ for _, w := range strings.Fields(lower) {
+ if glanceRefusedWords[strings.TrimFunc(w, func(r rune) bool { return !unicode.IsLetter(r) })] || glanceHex(w) {
+ return "", false
+ }
+ }
return line, true
}
diff --git a/internal/wire/glance_test.go b/internal/wire/glance_test.go
index e1a1d327..fd1dd997 100644
--- a/internal/wire/glance_test.go
+++ b/internal/wire/glance_test.go
@@ -56,6 +56,9 @@ func TestGlanceText(t *testing.T) {
{"one two three four five six seven eight nine ten", "one two three four five six seven eight"},
{"Considering extraordinarily comprehensive internationalisation requirements thoroughly", "Considering extraordinarily comprehensive"},
{"Checking\tyour\x00 invoices", "Checking your invoices"},
+ {"Reviewing your draft for Tito", "Reviewing your draft for Tito"},
+ {"Checking your calendar for Friday", "Checking your calendar for Friday"},
+ {"Looking at the defaced page", "Looking at the defaced page"},
} {
got, ok := wire.GlanceText(c.in)
if !ok || got != c.want {
@@ -68,7 +71,7 @@ func TestGlanceText(t *testing.T) {
t.Fatalf("a clean line changed: %q -> %q", got, again)
}
}
- for _, in := range []string{"", " \n ", "**", "Asking the team now", "Starting a TASK for you", "Creating a branch", "Merge coming up", "Handing it to the coordinator", "Your runner is busy", "Equipo is on it", "Supercalifragilisticexpialidociousandmoreandmoreandmoreandmorewords"} {
+ for _, in := range []string{"", " \n ", "**", "Asking the team now", "Starting a TASK for you", "Creating a branch", "Merge coming up", "Handing it to the coordinator", "Your runner is busy", "Equipo is on it", "Checking repository abc", "Opening the repo now", "Opening your repos", "Running the checks", "One check left", "Sending it for review", "Deploying your site", "Asking a specialist", "Looking at 1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b", "Looking at abc1234 now", "Opening deadbeefcafe0", "Opening https://tito.io/admin", "Reading src/main.go", "Opening www.tito.io", "Looking at C:\\work", "Supercalifragilisticexpialidociousandmoreandmoreandmoreandmorewords"} {
if got, ok := wire.GlanceText(in); ok {
t.Fatalf("GlanceText(%q) kept %q", in, got)
}