oficina / equipo Public

Conversation: clear stale thinking lines, one line while turns queue

Paul on staging (a069080): ten Coordinator lines stacked, timers 22 s
to 139 s, though every turn had replied. A specialist was working on a
task meanwhile. Its step activity events (resource "step", no turn_id)
reached the conversation's activity handler, and bubble(undefined)
made a new line for each one. Since 22f92a7, lineFor() finds no line
for a missing turn, so every event added a line, or took over a line
waiting since a send. Nothing removed them until the next refresh.

- The conversation applies delta and activity only for resource "turn"
  with a turn_id, and bubble() never makes a line without a turn.
- A refresh answer rendered before the newest turn, message or card
  event is stale. Another refresh follows, live lines for turns that
  started since stay, and a line for an ended turn never comes back.
- One line at a time. A message sent while a turn runs gets no line or
  timer. A quiet note goes under the latest waiting message ("Queued,
  answered next", COPY REVIEW REQUIRED), from the send, the turn
  events and the server render. When the queued turn starts, its line
  comes and the note goes.

TestBrowserThinkingLinesClear sends quickly, some messages while a turn
runs, one joining the queued turn, and one reply landing while a
refresh is in flight. The step reports activity throughout. It checks
one line and one note while turns queue, and no line plus each reply
once when all have replied, live and after a reload. It failed on
a069080 ("a step's activity drew a coordinator line"). Four mutations
fail it: the step filter, the send-time note, the queued-turn branch
and the stale-page keep. TestBrowserInstantThinkingQueued now expects
one line and the note.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev cf32916529e20cece4dd4c5b7488834608068384 parent a069080
6 files changed, +358 −27
  • internal/equipo/chat_page.go +25 −1
  • internal/equipo/copy.go +1 −0
  • internal/equipo/static/chat-stream.js +109 −12
  • internal/equipo/templates/chat.html +2 −1
  • internal/thintest/instant_browser_test.go +31 −13
  • internal/thintest/stale_thinking_browser_test.go +190 −0
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index cd60d43c..5b129774 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -43,7 +43,10 @@ type chatLine struct {
Switched string
// Waiting is the quiet status under a person's message whose turn
// waits for a connection (no thinking line, no timer).
- Waiting string
+ Waiting string
+ // Queued is the quiet note under the latest message of a turn queued
+ // behind the running one (no thinking line, no timer).
+ Queued string
ID, Text, TurnID string
// Files are what the person attached to their message.
Files []wire.MessageAttachment
@@ -241,6 +244,16 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
held = held || t.State == wire.TurnWaiting && t.Reason == wire.ReasonNoConnection
}
waitingTurns := map[string]bool{}
+ // The person's turns go one at a time: the oldest in flight has the
+ // thinking line, and one queued behind it a quiet note under its
+ // latest message instead of a line and timer of its own.
+ var ahead *wire.Turn
+ for i, t := range snap.Turns {
+ if t.Kind == wire.TurnPerson && !wire.Terminal(t.State) && (ahead == nil || t.CreatedAt.Before(ahead.CreatedAt) || t.CreatedAt.Equal(ahead.CreatedAt) && t.ID < ahead.ID) {
+ ahead = &snap.Turns[i]
+ }
+ }
+ queuedTurns := map[string]bool{}
var latest *wire.Turn
for i, t := range snap.Turns {
if !wire.Terminal(t.State) {
@@ -256,6 +269,10 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
}
continue
}
+ if t.Kind == wire.TurnPerson && t.State == wire.TurnQueued && ahead != nil && ahead.ID != t.ID {
+ queuedTurns[t.ID] = true
+ continue
+ }
view.Waiting = append(view.Waiting, t)
}
// Turns the coordinator takes on its own never end in a note.
@@ -268,6 +285,13 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
view.Messages[i].Waiting = copyText("chat.waiting_connection")
}
}
+ // One note at most: under the person's latest waiting message.
+ for i := len(view.Messages) - 1; i >= 0; i-- {
+ if m := &view.Messages[i]; m.Own && queuedTurns[m.TurnID] {
+ m.Queued = copyText("chat.queued")
+ break
+ }
+ }
if latest != nil && (latest.State == wire.TurnFailed || latest.State == wire.TurnCancelled) {
key := "chat." + latest.State
if latest.Reason == wire.ReasonStorageFull {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index 38f4da37..140ca98b 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -754,6 +754,7 @@ var pageCopy = map[string]string{
"chat.connections.reason.already_connected": "That account is already connected.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.offline": "Your runner is offline. Start it to add a connection.", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.waiting_connection": "Waiting for a connection", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
+ "chat.queued": "Queued, answered next", // COPY REVIEW REQUIRED (hotfix 2026-11-11: the note under a message queued behind the running turn)
"chat.connections.title_codex": "Connect Codex", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.title_claude": "Connect Claude", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
"chat.connections.open_openai": "Open OpenAI", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context)
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index d7baa8f1..dd24d6a4 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -332,7 +332,8 @@
}
// kind is a turn the coordinator takes on its own (move_in, explore):
// its line says so before any activity arrives.
- function bubble(turn, kind) {
+ function bubble(turn, kind, waited) {
+ if (!turn) return null;
var el = lineFor(turn);
if (!el && !kind && pending.length) {
// The line shown since the send becomes this turn's, in place.
@@ -350,8 +351,9 @@
el.dataset.kind = kind;
el.querySelector("[equipo-activity]").textContent = label;
}
- // The timer counts from the send that started this turn.
- el.dataset.started = String(!kind && Date.now() - lastSend < 60000 ? lastSend : Date.now());
+ // The timer counts from the send that started this turn (a turn
+ // that waited behind another, from now).
+ el.dataset.started = String(!kind && !waited && Date.now() - lastSend < 60000 ? lastSend : Date.now());
feed.append(el);
enliven(el);
tick();
@@ -369,6 +371,43 @@
function lineFor(turn) {
return turn ? feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(turn) + '"]') : null;
}
+ // ── One line at a time ─────────────────────────────────────────────
+ // The person's turns go one at a time. A turn queued behind the running
+ // one has no line or timer of its own: a quiet note under the person's
+ // latest message says it waits (queued holds those turns; revs the
+ // newest turn revision seen, so a late answer to a send never undoes
+ // its turn's event). Turns the coordinator takes on its own never hold
+ // a person's turn back here: they give way.
+ var queued = {}, revs = {};
+ feed.querySelectorAll("[data-queued]").forEach(function (n) {
+ var m = n.closest("[data-turn-id]");
+ if (m && m.dataset.turnId) queued[m.dataset.turnId] = true;
+ });
+ // behind: another person's turn holds the line (sending: or a line
+ // shown since a send that no turn has adopted yet).
+ function behind(turn, sending) {
+ if (thread) return false;
+ if (sending && pending.length) return true;
+ return Array.from(feed.querySelectorAll("[equipo-thinking]:not([data-kind]):not([data-optimistic])")).some(function (el) {
+ return el.dataset.turn && el.dataset.turn !== turn && !ended[el.dataset.turn];
+ });
+ }
+ function notes() {
+ if (thread) return;
+ var want = null;
+ feed.querySelectorAll('[equipo-message="own"]').forEach(function (m) {
+ var turn = m.dataset.turnId;
+ if (turn ? queued[turn] && !ended[turn] : m.queuedAtSend) want = m;
+ });
+ feed.querySelectorAll("[data-queued]").forEach(function (n) { if (n.parentElement !== want) n.remove(); });
+ if (want && !want.querySelector(":scope > [data-queued]")) {
+ var note = document.createElement("p");
+ note.setAttribute("equipo-card-note", "");
+ note.setAttribute("data-queued", "");
+ note.textContent = root.dataset.queuedNote || "";
+ want.append(note);
+ }
+ }
function optimistic(who) {
// Nothing can answer: the server's quiet status says so instead.
if (!thread && feed.querySelector("[data-no-connection]")) return null;
@@ -403,7 +442,7 @@
// already has one (the message joined an earlier queued turn) or is over.
function claim(el, turn) {
if (!el || !turn || !el.isConnected || !el.hasAttribute("data-optimistic")) return;
- if (lineFor(turn) || ended[turn]) drop(el);
+ if (lineFor(turn) || ended[turn] || queued[turn]) drop(el);
else adopt(el, turn);
}
// Who a thread question goes to, as ask-target.js shows it.
@@ -445,6 +484,7 @@
}, 250);
function showDraft(turn) {
var el = bubble(turn);
+ if (!el) return;
var text = drafts[turn] ? drafts[turn].text : "";
if (!text) return;
// The first words: the line fades where it sits, and the text
@@ -467,6 +507,7 @@
}
function showActivity(v) {
var el = bubble(v.turn_id);
+ if (!el) return;
if (drafts[v.turn_id] && drafts[v.turn_id].text) {
// A tool after text: show the line again under the draft.
delete el.dataset.streaming;
@@ -479,7 +520,10 @@
// drafts are put back. Refreshes run one at a time (a request during one
// runs once after it), and a page older than the one shown is dropped.
var inflight = null, again = false;
- var pageCursor = cursor;
+ // shape is the cursor of the newest event that changes what the page
+ // shows (a turn, a message, a card): a page rendered before it is
+ // stale, and is followed by another.
+ var pageCursor = cursor, shape = cursor;
function refresh() {
if (inflight) {
again = true;
@@ -511,6 +555,8 @@
var at = Number(page.dataset.cursor) || 0;
if (at < pageCursor) return;
pageCursor = at;
+ var stale = at < shape;
+ if (stale) again = true;
// Keep live timers and activity lines across the re-render.
// A newly committed reply settles into its draft's element; a turn
// may already have earlier messages on the page.
@@ -529,6 +575,9 @@
var fresh = el.matches('[equipo-message="incoming"][data-turn-id]') && !shown[el.dataset.message];
var turn = el.hasAttribute("equipo-thinking") ? el.dataset.turn : fresh ? el.dataset.turnId : "";
var old = turn && keep[turn];
+ // A page from before the turn ended never brings its line back.
+ if (!old && el.hasAttribute("equipo-thinking") && ended[turn]) return null;
+ if (el.hasAttribute("equipo-thinking") && !el.dataset.kind) delete queued[turn];
if (!old && el.hasAttribute("equipo-thinking") && !el.dataset.kind && pending.length && !ended[turn]) {
// The server shows the turn before its event came: the line
// shown since the send takes it, with the server's words.
@@ -547,12 +596,15 @@
if (!old) return el;
delete keep[turn];
return el.hasAttribute("equipo-thinking") ? old : settle(old, el);
- }));
+ }).filter(Boolean));
+ // A stale page lacks lines for turns that started since: they stay.
+ if (stale) Object.keys(keep).forEach(function (turn) { if (!ended[turn] && !queued[turn]) feed.append(keep[turn]); });
local.forEach(function (el) { place(el); });
pending.forEach(function (el) { feed.append(el); });
Object.keys(drafts).forEach(function (turn) {
if (feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(turn) + '"]')) showDraft(turn);
});
+ notes();
tick();
scroll();
});
@@ -562,6 +614,7 @@
if (e.cursor <= cursor) return;
cursor = e.cursor;
var v = e.data;
+ if (type === "turn" || type === "message" || type === "card" || type === "task" || type === "step") shape = cursor;
if (type === "thinking") {
root.dataset.thinkingSet = v.set;
return;
@@ -592,7 +645,9 @@
return;
}
if ((type !== "delta" && type !== "activity") || !question || !(v.turn_id in asked)) return;
- } else if (question || type === "question") {
+ } else if (question || type === "question" || (type === "delta" || type === "activity") && (e.resource !== "turn" || !v.turn_id)) {
+ // A specialist's step reports activity on the same stream: it is
+ // not the coordinator's, and draws no line here.
return;
}
if (type === "delta") {
@@ -608,18 +663,22 @@
if (v.role === "coordinator") {
delete drafts[v.turn_id];
ended[v.turn_id] = true;
+ notes();
refreshSoon();
return;
}
var own = template("equipo-own-template");
own.dataset.message = v.id;
+ own.dataset.turnId = v.turn_id || "";
own.querySelector("[equipo-message-body]").textContent = v.text;
sentFiles(own, served(v.attachments));
own.querySelector("time").textContent = new Date(v.created_at).toTimeString().slice(0, 5);
var waiting = feed.querySelector("[equipo-thinking]");
feed.insertBefore(own, waiting);
+ notes();
scroll();
} else if (type === "turn") {
+ revs[v.id] = Math.max(revs[v.id] || 0, v.revision || 0);
var heldNow = !!feed.querySelector("[data-no-connection]");
if (v.state === "waiting" && v.reason === "no_connection" || v.state === "queued" && heldNow) {
// Nothing can answer yet: no thinking line, no timer; the quiet
@@ -631,9 +690,18 @@
drop(thinking);
ended[v.id] = true;
refreshSoon();
+ } else if (v.state === "queued" && !v.kind && behind(v.id)) {
+ // Behind the running turn: the note, and no line or timer.
+ delete ended[v.id];
+ queued[v.id] = true;
+ drop(lineFor(v.id));
+ notes();
} else if (v.state === "queued" || v.state === "running" || v.state === "waiting") {
delete ended[v.id];
- var shownDraft = bubble(v.id, v.kind);
+ var waited = !!queued[v.id];
+ delete queued[v.id];
+ notes();
+ var shownDraft = bubble(v.id, v.kind, waited);
if (drafts[v.id] && drafts[v.id].attempt !== v.attempt) {
// The refused attempt's words go; the next attempt's follow.
delete drafts[v.id];
@@ -642,15 +710,23 @@
}
// Going again on a connection: the status and the card go.
if (heldNow || feed.querySelector('[data-message] [data-waiting-connection]')) refreshSoon();
+ } else if (v.state === "replied" && v.reply_id) {
+ ended[v.id] = true;
+ delete queued[v.id];
+ notes();
} else if (v.state === "replied" && !v.reply_id) {
// A turn that ended with nothing to say (an empty explore).
delete drafts[v.id];
ended[v.id] = true;
+ delete queued[v.id];
+ notes();
var quiet = feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(v.id) + '"]');
if (quiet) quiet.remove();
} else if (v.state === "failed" || v.state === "cancelled") {
delete drafts[v.id];
ended[v.id] = true;
+ delete queued[v.id];
+ notes();
var el = feed.querySelector('[equipo-thinking][data-turn="' + CSS.escape(v.id) + '"]');
if (el) el.remove();
// A move-in that gave way to the person, or stopped, is not the
@@ -747,6 +823,14 @@
});
box.hidden = false;
}
+ // The coordinator's line for a send, or, sent while a turn runs, the
+ // quiet note: the message waits its turn.
+ function lineOrNote(el, who) {
+ el.queuedAtSend = behind("", true);
+ if (!el.queuedAtSend) return optimistic(who);
+ notes();
+ return null;
+ }
function post(el, text, id, extra, files, line) {
el.dataset.pending = "";
delete el.dataset.sendFailed;
@@ -761,10 +845,20 @@
.then(function (sent) {
local.delete(el);
delete el.dataset.pending;
+ if (!thread && sent.turn) {
+ // The send's view of its turn, unless an event said more since.
+ if ((sent.turn.revision || 0) > (revs[sent.turn.id] || 0)) {
+ if (sent.turn.state === "queued" && behind(sent.turn.id)) queued[sent.turn.id] = true;
+ else delete queued[sent.turn.id];
+ }
+ el.dataset.turnId = sent.turn.id;
+ }
// A conversation send names its turn; a thread question is its own.
claim(line, thread ? sent.message.id : sent.turn && sent.turn.id);
+ notes();
if (feed.querySelector('[data-message="' + CSS.escape(sent.message.id) + '"]')) {
el.remove();
+ notes();
return;
}
el.dataset.message = sent.message.id;
@@ -778,8 +872,10 @@
}
})
.catch(function () {
- // Nothing was sent: no line waits for a reply.
+ // Nothing was sent: no line waits for a reply, nor a note.
drop(line);
+ el.queuedAtSend = false;
+ notes();
delete el.dataset.pending;
el.dataset.sendFailed = "";
var retry = document.createElement("button");
@@ -787,7 +883,7 @@
retry.setAttribute("rst-btn", "");
retry.dataset.retrySend = "";
retry.textContent = form.dataset.retry;
- retry.addEventListener("click", function () { post(el, text, id, extra, files, optimistic(extra.specialist)); });
+ retry.addEventListener("click", function () { post(el, text, id, extra, files, lineOrNote(el, extra.specialist)); });
el.querySelector("[equipo-bubble]").append(retry);
});
}
@@ -811,8 +907,9 @@
local.add(el);
lastSend = Date.now();
place(el);
- // The coordinator's line, now: nothing waits on the network.
- var line = optimistic(who);
+ // The coordinator's line, now: nothing waits on the network. Sent
+ // while a turn runs, the message waits its turn: the note instead.
+ var line = lineOrNote(el, who);
scroll(true);
// The form's other fields as they are now (who a question is for).
var extra = {};
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 40aa6c2d..e0c0ee54 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -12,7 +12,7 @@
{{define "work-task-receipt"}}{{with .Task}}<p equipo-card-line>{{icon "check-circle"}}<span><a href="/tasks/{{.ID}}">{{.Title}}</a></span><span equipo-stage data-stage="{{.Stage}}" data-needs="{{.NeedsYou}}">{{.StageLine}}</span></p>{{if and .Pushed (not .MergedLine)}}<p equipo-card-note data-pushed><span>{{.Pushed}}</span><a href="{{.URL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{if or .ChecksLine .ReviewLine}}<p equipo-card-note data-judged>{{with .ChecksLine}}<span data-checks>{{.}}</span>{{end}}{{with .ReviewLine}}<span data-verdict>{{.}}</span>{{end}}</p>{{end}}{{if .MergedLine}}<p equipo-card-note data-merged><span>{{.MergedLine}}</span><a href="{{.RepoURL}}" rel="noopener" target="_blank" data-open-amadan>{{copy "work.open"}}</a></p>{{end}}{{end}}{{if .Open}}<button type="button" equipo-receipt-more aria-expanded="false" aria-controls="acts-{{.ID}}" aria-label="{{copy "chat.card.more"}}">⋯</button><span equipo-receipt-actions id="acts-{{.ID}}">{{template "work-task-actions" .Task}}</span>{{end}}{{end}}
{{define "message-files"}}{{with .}}<div equipo-message-files>{{range .}}{{if eq .Kind "image"}}<a equipo-file-thumb href="/conversation/attachments/{{.ID}}" target="_blank" rel="noopener" data-attachment="{{.ID}}"><img src="/conversation/attachments/{{.ID}}/preview" alt="{{.Name}}"{{if .Width}} width="{{.Width}}" height="{{.Height}}"{{end}} loading="lazy" decoding="async"></a>{{else}}<a equipo-file-chip href="/conversation/attachments/{{.ID}}" target="_blank" rel="noopener" data-attachment="{{.ID}}">{{icon "file-text"}}<span equipo-file-name>{{.Name}}</span><span equipo-file-size>{{fileSize .Size}}</span></a>{{end}}{{end}}</div>{{end}}{{end}}
{{define "content"}}
-<div equipo-conversation data-chat-stream data-thinking-set="{{.ThinkingSet}}" data-thinking-words="{{.ThinkingWords}}" data-cursor="{{.Chat.Cursor}}" data-person="{{.Address}}" data-elapsed="{{copy "chat.elapsed"}}" data-moving-in="{{copy "chat.moving_in"}}" data-exploring="{{copy "chat.exploring"}}">
+<div equipo-conversation data-chat-stream data-thinking-set="{{.ThinkingSet}}" data-thinking-words="{{.ThinkingWords}}" data-cursor="{{.Chat.Cursor}}" data-person="{{.Address}}" data-elapsed="{{copy "chat.elapsed"}}" data-moving-in="{{copy "chat.moving_in"}}" data-exploring="{{copy "chat.exploring"}}" data-queued-note="{{copy "chat.queued"}}">
<header equipo-chat-header><h1>{{copy "conversation.title"}}</h1><a href="/conversation/settings/notebook" equipo-header-button aria-label="{{copy "chat.notebook.link"}}" title="{{copy "chat.notebook.link"}}">{{icon "notebook"}}</a><a href="/housekeeping" equipo-header-button aria-label="{{copy "chat.housekeeping.link"}}" title="{{copy "chat.housekeeping.link"}}" data-housekeeping-link>{{icon "list-checks"}}</a><a href="/conversation/settings/connections" equipo-header-button aria-label="{{copy "chat.connections.title"}}" title="{{copy "chat.connections.title"}}" data-connections-link>{{icon "plug"}}</a></header>
<p equipo-offline role="status"{{if not .Chat.Offline}} hidden{{end}}>{{copy "chat.offline"}}</p>
<div equipo-scroll tabindex="0" role="region" aria-label="{{copy "conversation.title"}}">
@@ -31,6 +31,7 @@
<div equipo-message-meta><strong{{if .Own}} equipo-visually-hidden{{end}}>{{if .Own}}{{$.Address}}{{else}}{{icon "message-circle"}}{{copy "conversation.coordinator"}}{{end}}</strong><time datetime="{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}">{{.CreatedAt.Format "15:04"}}</time></div>
{{if .Own}}{{template "message-files" .Files}}{{end}}<div equipo-bubble>{{if .Own}}<p equipo-message-body>{{.Text}}</p>{{else}}<div equipo-message-body equipo-markdown>{{chatMarkdown .Text}}</div>{{end}}</div>
{{with .Waiting}}<p equipo-card-note data-waiting-connection>{{.}}</p>{{end}}
+{{with .Queued}}<p equipo-card-note data-queued>{{.}}</p>{{end}}
{{with .Switched}}<p equipo-card-note data-switched>{{.}}</p>{{end}}
</li>
{{range .Cards}}{{template "chat-card" .}}{{end}}{{end}}
diff --git a/internal/thintest/instant_browser_test.go b/internal/thintest/instant_browser_test.go
index bffefc85..05cbf4c2 100644
--- a/internal/thintest/instant_browser_test.go
+++ b/internal/thintest/instant_browser_test.go
@@ -189,9 +189,11 @@ func messageFrame(t *testing.T, r *rig, runner *FakeRunner) wire.Frame {
// TestBrowserInstantThinkingQueued: while one turn runs, a second message
// queues a turn behind it and a third joins that queued turn (the server
-// says so in its answer). Every send shows a line at once; when the server
-// has answered, there is one line per turn, each the element shown at the
-// send, and nothing is orphaned.
+// says so in its answer). The first send shows its line at once; the
+// queued ones show no line or timer of their own, only a quiet note under
+// the latest (Paul, 2026-11-11: ten stacked lines, "Did I push it too
+// hard?"). When the server has answered there is one line, the element
+// shown at the first send, and nothing is orphaned.
func TestBrowserInstantThinkingQueued(t *testing.T) {
r, runner := instantRig(t)
p := instantPage(t, r)
@@ -203,18 +205,25 @@ func TestBrowserInstantThinkingQueued(t *testing.T) {
p.wait(`!window.__first.hasAttribute('data-optimistic')`, "the first turn adopted its line")
first := eval[string](p, `window.__first.dataset.turn`)
r.wait("first running", func(c *Conversation) bool { return c.Turns[first].State == wire.TurnRunning })
- p.check(sendNow+`('And a second.')`, "no line for the second send")
- p.check(`(()=>{window.__second=window.__line;return true})()`, "keep the second")
- p.check(sendNow+`('And a third.')`, "no line for the third send")
- p.check(`(()=>{window.__third=window.__line;return document.querySelectorAll('[equipo-thinking][data-optimistic]').length===2 && window.__held.length===2})()`, "two waiting lines, both sends held")
+ // queuedNow sends text and reports in the same task that the only line
+ // is still the first's and the note is under this message.
+ queuedNow := `(text=>{
+ const box=document.querySelector('#composer textarea');box.value=text;box.dispatchEvent(new Event('input'));
+ document.querySelector('#composer').requestSubmit();
+ const lines=[...document.querySelectorAll('[equipo-thinking]')], notes=[...document.querySelectorAll('[data-queued]')];
+ return lines.length===1 && lines[0]===window.__first && notes.length===1 && notes[0].closest('[equipo-message="own"]').querySelector('[equipo-message-body]').textContent===text;
+})`
+ p.check(queuedNow+`('And a second.')`, "a line of its own, or no note, for the second send")
+ p.check(queuedNow+`('And a third.')`, "a line of its own, or no note, for the third send")
+ p.check(`window.__held.length===2`, "both sends held")
p.check(`window.__release()`, "release the second")
- p.wait(`!window.__second.hasAttribute('data-optimistic') && window.__second.dataset.turn!==`+jsString(first), "the queued turn adopted the second line")
+ p.wait(`window.__answered===2`, "the second answered")
p.check(`window.__release()`, "release the third")
- p.wait(`window.__answered===3 && !document.querySelector('[equipo-thinking][data-optimistic]')`, "the third line gone")
- lines := `[...document.querySelectorAll('[equipo-thinking]')].map(l=>(l===window.__first?'first:':l===window.__second?'second:':l===window.__third?'third:':'')+l.dataset.turn).join(' ')`
- second := eval[string](p, `window.__second.dataset.turn`)
- if got := eval[string](p, lines); got != "first:"+first+" second:"+second {
- t.Fatalf("lines %q, want the first and second for turns %s and %s", got, first, second)
+ p.wait(`window.__answered===3`, "the third answered")
+ p.wait(`document.querySelectorAll('[data-queued]').length===1 && [...document.querySelectorAll('[equipo-message="own"]')].find(m=>m.querySelector('[data-queued]')).querySelector('[equipo-message-body]').textContent==='And a third.'`, "one note, under the third")
+ lines := `[...document.querySelectorAll('[equipo-thinking]')].map(l=>(l===window.__first?'first:':'')+l.dataset.turn).join(' ')`
+ if got := eval[string](p, lines); got != "first:"+first {
+ t.Fatalf("lines %q, want only the first's for turn %s", got, first)
}
snap, err := r.client.Snapshot(r.ctx)
if err != nil {
@@ -223,5 +232,14 @@ func TestBrowserInstantThinkingQueued(t *testing.T) {
if len(snap.Turns) != 2 {
t.Fatalf("the third message did not join the queued turn: %+v", snap.Turns)
}
+ var second string
+ for _, v := range snap.Turns {
+ if v.ID != first {
+ second = v.ID
+ }
+ }
+ // The first replies: the queued turn's line comes, the note goes.
+ runner.Send(r.ctx, "r-q1", wire.FrameReply, wire.Reply{TurnID: first, Attempt: 1, Text: "First done."})
+ p.wait(`document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-thinking]').dataset.turn===`+jsString(second)+` && !document.querySelector('[data-queued]')`, "the second turn's line, no note")
p.stayed("queued sends")
}
diff --git a/internal/thintest/stale_thinking_browser_test.go b/internal/thintest/stale_thinking_browser_test.go
new file mode 100644
index 00000000..51c216a3
--- /dev/null
+++ b/internal/thintest/stale_thinking_browser_test.go
@@ -0,0 +1,190 @@
+//go:build browser
+
+package thintest
+
+import (
+ "context"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+)
+
+// TestBrowserThinkingLinesClear: Paul on staging, 2026-11-11, "Did I push
+// it too hard?": ten Coordinator lines stacked, timers 22 s to 139 s, for
+// a conversation where every turn had replied. A specialist was at work
+// on a task meanwhile, and each of its step activity events (no turn)
+// drew a new thinking line that nothing took away.
+//
+// Messages go quickly, some while a turn runs (one joins the queued
+// turn), one reply lands while a refresh is in flight, and the task's
+// step reports activity throughout. While a turn runs there is one
+// thinking line (the running turn's) and the waiting message has a quiet
+// queued note instead of a line and timer of its own. Once every turn has
+// replied there is no thinking line, live and after a reload, and each
+// reply shows once.
+func TestBrowserThinkingLinesClear(t *testing.T) {
+ r := newToolRig(t)
+ // A task whose step keeps running: its activity reaches the stream.
+ task := taskID(t, r.call("k1", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Swipe back from the edge does nothing", "brief": "x"}))
+ r.call("k2", wire.ToolStartTask, map[string]string{"task": task, "brief": "go"})
+ _, body := r.expect(wire.FrameDispatch)
+ d := body.(*wire.DispatchCommand)
+ r.step("r-s1", wire.StepReport{TaskID: task, StepID: d.StepID, Attempt: 1, State: wire.StepRunning, BaseSHA: strings.Repeat("1", 40)})
+ acts := 0
+ activity := func() {
+ t.Helper()
+ acts++
+ r.activity("act-"+strconv.Itoa(acts), wire.StepActivityReport{TaskID: task, StepID: d.StepID, Attempt: 1, Kind: wire.ActivityRead, Subject: "panes/swipe.go"})
+ r.wait("step activity", func(c *Conversation) bool { return len(c.StepActivity[d.StepID]) == acts })
+ }
+ reply := func(turn, text string) {
+ t.Helper()
+ if err := r.runner.Send(r.ctx, "r-"+turn, wire.FrameReply, wire.Reply{TurnID: turn, Attempt: 1, Text: text}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("replied", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnReplied })
+ }
+ // next is the turn the instance dispatches next, acked: running.
+ next := func() string {
+ t.Helper()
+ _, body := r.expect(wire.FrameMessage)
+ turn := body.(*wire.MessageCommand).TurnID
+ r.wait("running", func(c *Conversation) bool { return c.Turns[turn].State == wire.TurnRunning })
+ return turn
+ }
+ reply(r.turn, "Started on the swipe.")
+
+ p := openInner(t, r.inst.URL, r.inst.Cookie(), 390, 844, true, "dark", "no-preference")
+ defer p.stop()
+ // Count the events the page has applied, and hold the page's refresh
+ // answers on demand (the request goes; its answer waits).
+ p.do(chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
+ _, err := cdp.Call(ctx, target, page.AddScriptToEvaluateOnNewDocument, page.AddScriptToEvaluateOnNewDocumentParams{Source: `(()=>{
+const ES=window.EventSource;window.__seen={};
+window.EventSource=function(u,o){const s=new ES(u,o);const add=s.addEventListener.bind(s);s.addEventListener=function(t,f,x){return add(t,function(e){f.call(this,e);window.__seen[t]=(window.__seen[t]||0)+1},x)};return s};
+window.EventSource.prototype=ES.prototype;
+const fetch0=window.fetch.bind(window);window.__hold=false;window.__held=[];
+window.fetch=(url,opts)=>{const f=fetch0(url,opts);if(!window.__hold||opts&&opts.method==='POST'||!String(url).endsWith('/conversation'))return f;return new Promise(go=>window.__held.push(()=>go(f)))};
+window.__release=()=>{window.__hold=false;const h=window.__held.splice(0);h.forEach(f=>f());return h.length};
+})()`})
+ return err
+ }))
+ p.open("/conversation")
+ p.wait(`document.querySelector('[data-chat-stream]') && window.__seen`, "the conversation")
+ turns := func() string {
+ var out []string
+ r.conv.Locked(func(c *Conversation) {
+ for id, v := range c.Turns {
+ out = append(out, id+" "+v.State+" "+strings.Join(v.MessageIDs, ","))
+ }
+ })
+ return strings.Join(out, "; ")
+ }
+ // What the feed shows, for a failure: lines by turn, messages by turn.
+ state := `[...document.querySelectorAll('[equipo-feed] > *')].map(l=>l.hasAttribute('equipo-thinking')?'line:'+l.dataset.turn+(l.hasAttribute('data-optimistic')?'(optimistic)':''):l.matches('[equipo-message]')?l.getAttribute('equipo-message')+':'+(l.dataset.turnId||'-')+':'+l.querySelector('[equipo-message-body]').textContent.slice(0,24)+(l.querySelector('[data-queued]')?' (queued)':''):l.tagName).join('\n')`
+ wait := func(expression, what string) {
+ t.Helper()
+ for deadline := time.Now().Add(8 * time.Second); !eval[bool](p, `!!(`+expression+`)`); time.Sleep(40 * time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatalf("waiting for %s; the feed:\n%s\nturns: %s", what, eval[string](p, state), turns())
+ }
+ }
+ }
+ check := func(expression, what string) {
+ t.Helper()
+ if !eval[bool](p, `!!(`+expression+`)`) {
+ t.Fatalf("%s; the feed:\n%s\nturns: %s", what, eval[string](p, state), turns())
+ }
+ }
+ // send types text and sends it; behind a running turn, nothing but
+ // that turn's line shows, from the moment of sending.
+ send := func(text string, behind bool) {
+ t.Helper()
+ check(`(()=>{const box=document.querySelector('#composer textarea');box.value=`+jsString(text)+`;box.dispatchEvent(new Event('input'));document.querySelector('#composer').requestSubmit();return `+strconv.FormatBool(!behind)+` || document.querySelectorAll('[equipo-thinking]').length===1})()`, "a second line at the send of "+text)
+ }
+ lines := `document.querySelectorAll('[equipo-thinking]').length`
+ lineFor := func(turn string) string {
+ return `document.querySelectorAll('[equipo-thinking]').length===1 && document.querySelector('[equipo-thinking]').dataset.turn===` + jsString(turn)
+ }
+ seen := func(n int) string { return `(window.__seen.activity||0)>=` + strconv.Itoa(n) }
+ own := func(text string) string {
+ return `[...document.querySelectorAll('[equipo-message="own"]')].find(m=>m.querySelector('[equipo-message-body]').textContent===` + jsString(text) + `)`
+ }
+ queued := func(text string) string { return `!!` + own(text) + `?.querySelector('[data-queued]')` }
+ notes := `document.querySelectorAll('[data-queued]').length`
+ count := func(text string) string {
+ return `[...document.querySelectorAll('[equipo-message="incoming"][data-message]')].filter(m=>m.textContent.includes(` + text + `)).length===1`
+ }
+ once := func(text string) string { return count(jsString(text)) }
+ wait(once("Started on the swipe.")+` && `+lines+`===0`, "the opening reply, no line")
+ activity()
+ wait(seen(1), "the first step activity")
+ check(lines+`===0`, "a step's activity drew a coordinator line")
+
+ // M1 runs; the specialist goes on meanwhile.
+ send("First thing.", false)
+ t1 := next()
+ wait(lineFor(t1), "one line, for the first turn")
+ activity()
+ wait(seen(2), "step activity while a turn runs")
+ check(lineFor(t1), "a second line beside the running turn's")
+
+ // M2 while T1 runs: queued, a quiet note and no line of its own; M3
+ // joins the queued turn.
+ send("And a second.", true)
+ wait(queued("And a second."), "the queued note under the second message")
+ check(lineFor(t1), "a line and timer for the queued turn")
+ wait(own("And a second.")+`?.dataset.message`, "the second message sent")
+ send("And a third.", true)
+ wait(queued("And a third.")+` && `+notes+`===1`, "one queued note, under the latest message")
+ check(lineFor(t1), "a line and timer for the joined turn")
+ wait(own("And a third.")+`?.dataset.turnId===`+own("And a second.")+`.dataset.turnId`, "the third message joined the queued turn")
+
+ // T1 replies: the queued turn runs, its note goes, its line comes.
+ reply(t1, "Done with the first.")
+ t2 := next()
+ wait(once("Done with the first.")+` && `+lineFor(t2)+` && `+notes+`===0`, "the first reply once, one line for the second turn, no note")
+ activity()
+ wait(seen(3), "step activity")
+ check(lineFor(t2), "a second line beside the running turn's")
+
+ // A refresh in flight (a task recorded during T2) when T2's reply
+ // lands and T3 starts running.
+ check(`(()=>{window.__hold=true;return true})()`, "hold refreshes")
+ r.turn = t2
+ r.call("k3", wire.ToolRecordTask, map[string]string{"repo": "oficina/sample", "title": "Pull to refresh stalls", "brief": "y"})
+ wait(`window.__held.length>=1`, "a refresh in flight")
+ send("A fourth.", true)
+ wait(queued("A fourth."), "the queued note under the fourth message")
+ reply(t2, "Second done.")
+ t3 := next()
+ activity()
+ wait(seen(4), "step activity during the refresh")
+ wait(`document.querySelector('[equipo-thinking][data-turn=`+jsString(t3)+`]')`, "the third turn's line")
+ // The answer from before T3 started never takes its line away.
+ check(`(()=>{window.__t3=document.querySelector('[equipo-thinking][data-turn=`+jsString(t3)+`]');return window.__release()>=1})()`, "release the refresh")
+ wait(once("Second done.")+` && `+lineFor(t3)+` && `+notes+`===0`, "the second reply once, one line for the third turn")
+ check(`document.querySelector('[equipo-thinking]')===window.__t3 && window.__t3.isConnected`, "the third turn's line went and came back")
+
+ reply(t3, "Fourth handled.")
+ wait(once("Fourth handled.")+` && `+lines+`===0`, "the last reply, no line")
+ // The specialist is still at work after the chat goes quiet.
+ activity()
+ activity()
+ wait(seen(6), "step activity after every turn replied")
+ check(lines+`===0`, "stale thinking lines once every turn replied")
+ replies := `["Started on the swipe.","Done with the first.","Second done.","Fourth handled."].every(t=>` + count("t") + `)`
+ check(replies, "a reply missing or shown twice")
+ p.stayed("quick sends")
+
+ p.open("/conversation")
+ wait(`document.querySelector('[data-chat-stream]')`, "the conversation again")
+ check(lines+`===0 && `+notes+`===0`, "a thinking line or queued note after a reload")
+ check(replies, "a reply missing or shown twice after a reload")
+}