Skip to content

Commit 35ff56e

Browse files
Merge pull request #3 from charlesnutter/turn-boundaries
Record each reply when it ends, and unfinished ones
2 parents 44d5d84 + c078338 commit 35ff56e

6 files changed

Lines changed: 190 additions & 15 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
## [Unreleased]
2+
### Fixed
3+
- A reply is recorded when it ends, not when OpenCode's execution does. A
4+
message sent while a reply is running is queued into the same execution,
5+
so the first reply was never shown: a 19m 53s reply left the previous
6+
turn in the sidebar.
7+
- A reply that was interrupted or failed is shown, marked `interrupted` or
8+
`failed`, with OpenCode's figures up to that point, instead of leaving the
9+
previous turn in place. The history panel marks it too.
10+
111
## [0.3.1] – 2026-09-24
212
### Changed
313
- The first turn after OpenCode starts can show engine figures on

‎history.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,8 @@ export interface TurnRecord {
7676
* parallel, so not a sum). Rates are never combined across them.
7777
*/
7878
subagents?: { count: number; tokens: number; spanS: number; cost?: number; steps?: number }
79+
/** Set when the reply did not finish: stopped by the user, or failed. */
80+
outcome?: "interrupted" | "failed"
7981
engine?: {
8082
prefillTokS?: number
8183
/** Tokens committed per verify pass (MTPLX's multi-token prediction). */
@@ -122,6 +124,11 @@ export interface Summary {
122124

123125
/** A turn's streaming time: recorded, or derived from an older row's rate. */
124126
export function streamOf(t: TurnRecord): number | undefined {
127+
// A reply that did not finish has no tokens recorded for its last step, so
128+
// its tokens over its streaming time would understate the speed (measured:
129+
// an interrupted turn, 0 tokens over 6s of streaming, halved a session's
130+
// average). It counts toward nothing that divides by streaming time.
131+
if (t.outcome) return undefined
125132
if (t.streamS !== undefined && t.streamS > 0) return t.streamS
126133
// Rows recorded before streamS existed carry a generation rate whose
127134
// window is tokens / rate. A whole-turn rate is not generation, so no.
@@ -180,6 +187,7 @@ export function formatRow(t: TurnRecord, modelWidth = 18): string {
180187
t.ttft !== undefined ? `ttft ${nn(t.ttft, 2)}s` : "",
181188
money(t.cost),
182189
t.cached !== undefined && t.cached > 0 ? `${ni(t.cached)} cached` : "",
190+
t.outcome ?? "",
183191
].filter(Boolean)
184192
// A leading marker rather than a column, so a row is readable at any width.
185193
const mark = t.source === "engine" ? "*" : " "

‎test/session.test.mjs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,4 +249,12 @@ test("the roll-up carries its sub-agents' steps -- one engine request each", ()
249249
assert.equal(rollupSubagents([child({ steps: undefined })], ["ses_child"], 0, 40_000).steps, 1)
250250
})
251251

252+
test("an unfinished reply counts toward no speed or time split", () => {
253+
// OpenCode records no tokens for an interrupted step: 0 tokens over 6s.
254+
const s = summariseSession([row({ outcome: "interrupted", tokens: 0, streamS: 6 }), row({ tokens: 100, streamS: 2 })], SID)
255+
assert.equal(s.genTokS, 50)
256+
assert.equal(s.trend.length, 1)
257+
assert.equal(s.turns, 2)
258+
})
259+
252260
console.log(`\n${passed} passed`)

‎test/universal.test.mjs‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
// counts never disagreed — only the rate's numerator did.
99
// Run with: bun test/universal.test.mjs
1010
import { strict as assert } from "node:assert"
11-
import { turnRate, universalLine, universalView, turnSteps, lastModel, aggregateTurn, DEFAULT_DISPLAY } from "../universal.ts"
11+
import { turnRate, universalLine, universalView, turnSteps, turnUserAt, lastModel, aggregateTurn, DEFAULT_DISPLAY } from "../universal.ts"
1212

1313
let passed = 0
1414
function test(name, fn) {
@@ -379,4 +379,37 @@ test("a session with no model named yet gives none, not a guess", () => {
379379
assert.equal(lastModel([]), undefined)
380380
})
381381

382+
// ---- a reply's boundaries, when one execution holds several -----------------
383+
// A message sent while a reply runs is queued into the same execution
384+
// (measured: a 9-step reply ended `stop`, and the queued message's step began
385+
// 2s later, in one execution that ended interrupted). Each reply is a turn.
386+
const queued = [
387+
{ type: "user", id: "u1", time: { created: 1_000 } },
388+
{ type: "assistant", id: "a1", time: { created: 2_000 } },
389+
{ type: "assistant", id: "a2", time: { created: 3_000 } },
390+
{ type: "user", id: "u2", time: { created: 2_500 } },
391+
{ type: "assistant", id: "b1", time: { created: 9_000 } },
392+
]
393+
394+
test("a reply ending at a given step excludes the queued message after it", () => {
395+
assert.deepEqual(turnSteps(queued, "a2").map((m) => m.id), ["a1", "a2"])
396+
assert.equal(turnUserAt(queued, "a2"), 1_000)
397+
})
398+
399+
test("without an end step, the turn is the latest reply", () => {
400+
assert.deepEqual(turnSteps(queued).map((m) => m.id), ["b1"])
401+
assert.equal(turnUserAt(queued), 2_500)
402+
})
403+
404+
test("an unknown end step falls back to the latest reply", () => {
405+
assert.deepEqual(turnSteps(queued, "gone").map((m) => m.id), ["b1"])
406+
})
407+
408+
test("an interrupted reply's total runs to when it stopped", () => {
409+
const partial = [{ type: "assistant", id: "x", time: { created: 5_000 }, tokens: { output: 10, reasoning: 0 } }]
410+
const { info } = aggregateTurn(partial, new Map(), { execStart: 4_000, endAt: 34_000 })
411+
assert.equal(info.time.completed, 34_000)
412+
assert.equal(info.time.created, 4_000)
413+
})
414+
382415
console.log(`\n${passed} passed`)

‎tui.tsx‎

Lines changed: 95 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import { appendFileSync } from "node:fs"
2929

3030
import { short } from "./format"
3131
import type { HttpOptions } from "./http"
32-
import { universalView, turnRate, turnSteps, lastModel, aggregateTurn, type Turn, type Display, DEFAULT_DISPLAY } from "./universal"
32+
import { universalView, turnRate, turnSteps, turnUserAt, lastModel, aggregateTurn, type Turn, type Display, DEFAULT_DISPLAY } from "./universal"
3333
import { record, historyLines, type History, type TurnRecord } from "./history"
3434
import { emptyPanels, lineFor, keyFor, setLine, LatestPerKey, PLACEHOLDER, type Panels } from "./panels"
3535
import { encodeView, decodeView, LABEL_WIDTH, type TurnView } from "./rows"
@@ -311,7 +311,9 @@ export default Plugin.define({
311311
const turns = new Map<string, Turn>()
312312
// When each session's current execution started: the start of what the
313313
// user waits for, which the turn's total runs from (retries included).
314-
const execStart = new Map<string, number>()
314+
// When each session's current reply started: the execution starting,
315+
// then each reply ending, since one execution can hold several replies.
316+
const replyStart = new Map<string, number>()
315317
// Per step: its provider and model (from session.step.started), and for
316318
// engines that report their latest request -- MTPLX, KoboldCpp, mlx-serve
317319
// -- a read taken at that step's end. A tool-using turn is one request
@@ -772,8 +774,19 @@ export default Plugin.define({
772774
// a turn in one tab suppress another tab's line (see panels.ts).
773775
const latest = new LatestPerKey()
774776

775-
async function report(sessionID: string): Promise<void> {
776-
const seq = latest.begin(sessionID)
777+
// Replies already reported, by their last step's id. A reply is reported
778+
// when its last step ends, and again asked for when the execution ends;
779+
// it must render once.
780+
const reported = new Set<string>()
781+
/**
782+
* One reply: the user message's steps, ending at `endID` (the step that
783+
* ended the reply) or at the latest step. `outcome` is set when the
784+
* execution was interrupted or failed before the reply finished.
785+
*/
786+
async function report(
787+
sessionID: string,
788+
opts: { endID?: string; outcome?: "interrupted" | "failed" } = {}
789+
): Promise<void> {
777790
// `message.list()` is a union of message kinds and its tail after a turn
778791
// is an "idle" marker, not the reply — measured, see audit P1. Scan
779792
// backwards for the assistant message.
@@ -782,12 +795,30 @@ export default Plugin.define({
782795
// The turn is every assistant message since the last user message: one
783796
// per step when it calls tools. Reading only the last one showed
784797
// `140 tok 10.20s` for a 316-token, 37s turn (measured, vllm-mlx).
785-
const steps = turnSteps(msgs)
786-
const agg = aggregateTurn(steps, turns, { execStart: execStart.get(sessionID) })
787-
execStart.delete(sessionID)
798+
const steps = turnSteps(msgs, opts.endID)
799+
const lastID = steps[steps.length - 1]?.id
800+
if (!lastID || reported.has(lastID)) return
801+
reported.add(lastID)
802+
if (reported.size > 64) {
803+
const oldest = reported.values().next().value
804+
if (oldest !== undefined) reported.delete(oldest)
805+
}
806+
const seq = latest.begin(sessionID)
807+
// The reply started when the execution did -- or, for a message queued
808+
// behind an earlier reply in the same execution, when that reply ended,
809+
// or when the message was sent if that is later.
810+
const userAt = turnUserAt(msgs, opts.endID)
811+
const since = replyStart.get(sessionID)
812+
const start = since !== undefined && userAt !== undefined ? Math.max(since, userAt) : (since ?? userAt)
813+
const agg = aggregateTurn(steps, turns, {
814+
execStart: start,
815+
endAt: opts.outcome ? Date.now() : undefined,
816+
})
817+
replyStart.set(sessionID, Date.now())
788818
const info = agg.info
789819
const turn = agg.turn
790820
if (!info) return
821+
dbg(`report: ${sessionID} ending ${lastID}${opts.outcome ? ` (${opts.outcome})` : ""}; ${steps.length} step(s)`)
791822
dbg(
792823
`turn: ${steps.length} assistant message(s) [${steps
793824
.map((m) => `${(m.tokens?.output ?? 0) + (m.tokens?.reasoning ?? 0)}${m.finish ? `/${m.finish}` : ""}`)
@@ -860,7 +891,9 @@ export default Plugin.define({
860891
}
861892
let line: TurnView | null = null
862893
try {
863-
line = await enrich(provider, model, info, turn, http, tier2, steps, sameEngine)
894+
// An unfinished reply's last step never completed, so the engine has
895+
// no reading of it to check against: OpenCode's figures only.
896+
if (!opts.outcome) line = await enrich(provider, model, info, turn, http, tier2, steps, sameEngine)
864897
// Recorded before the fallback overwrites it, so history knows which
865898
// tier the figures actually came from.
866899
} catch (e: unknown) {
@@ -884,7 +917,15 @@ export default Plugin.define({
884917
// above are measured and complete; only their SOURCE changes once a
885918
// baseline exists, and the rate in particular can move an order of
886919
// magnitude when it does. Split to fit the box's 32 cells.
887-
if (tier2.pendingBaseline) line.notes.push("engine telemetry", "from the next turn")
920+
if (opts.outcome) {
921+
// OpenCode records no tokens for a step it stopped mid-stream
922+
// (measured: an interrupted reply's step came back 0/error after 7s
923+
// of thinking), so a 0 here is unknown, not none.
924+
const out0 = (info.tokens?.output ?? 0) + (info.tokens?.reasoning ?? 0)
925+
if (out0 === 0) line.rows = line.rows.filter(([label]) => label !== "tokens" && label !== "speed")
926+
line.notes.push(opts.outcome)
927+
}
928+
else if (tier2.pendingBaseline) line.notes.push("engine telemetry", "from the next turn")
888929
else if (tier2.sharedWindow) line.notes.push("engine data skipped:", "overlapping requests")
889930
}
890931

@@ -919,6 +960,7 @@ export default Plugin.define({
919960
steps: turn?.steps,
920961
engine: enriched ? tier2.engine : undefined,
921962
subagents,
963+
outcome: opts.outcome,
922964
}
923965
setHistory((d) => {
924966
d.turns = record({ turns: d.turns }, rec).turns
@@ -992,7 +1034,7 @@ export default Plugin.define({
9921034
ctx.data.on("session.execution.started", (evt) => {
9931035
const sid = (evt as { data?: { sessionID?: string } }).data?.sessionID
9941036
if (typeof sid !== "string") return
995-
execStart.set(sid, Date.now())
1037+
replyStart.set(sid, Date.now())
9961038
// The engine this turn will use: the session's last model, or one
9971039
// just selected. A new session on the default model has neither,
9981040
// and its first turn goes unprimed, as before.
@@ -1131,6 +1173,49 @@ export default Plugin.define({
11311173
}
11321174
})
11331175
)
1176+
// A reply ends when a step ends with a final answer. That is
1177+
// its own turn even if the execution goes on: a message sent while it
1178+
// ran is queued into the same execution, which then only ends -- or is
1179+
// interrupted -- after the next reply (measured: a 19m 53s reply never
1180+
// reported, because its execution ended interrupted 20m in).
1181+
off.push(
1182+
ctx.data.on("session.step.ended", (evt) => {
1183+
const d = (evt as { data?: { sessionID?: string; assistantMessageID?: string; finish?: string } }).data
1184+
if (typeof d?.sessionID !== "string" || typeof d.assistantMessageID !== "string") return
1185+
// Not "error" or "unknown": OpenCode retries a step under the same
1186+
// message id, and a failed attempt must not end the reply before
1187+
// the retry does. The execution's own end catches those.
1188+
if (d.finish !== "stop" && d.finish !== "length" && d.finish !== "content-filter") return
1189+
const sid = d.sessionID
1190+
const id = d.assistantMessageID
1191+
// After the host has applied the step to the message it ends.
1192+
setTimeout(() => {
1193+
const m = ctx.data.session.message.get(sid, id) as SessionMessageAssistant | undefined
1194+
dbg(`reply ended ${id} (${d.finish}); completed ${m?.time?.completed !== undefined}, tokens ${m?.tokens?.output ?? "?"}`)
1195+
report(sid, { endID: id }).catch((e: unknown) => dbg(`report threw: ${String(e)}`))
1196+
}, 50)
1197+
})
1198+
)
1199+
// An execution stopped before its reply finished still used the engine;
1200+
// the reply is shown, marked, rather than leaving the previous turn up.
1201+
off.push(
1202+
ctx.data.on("session.execution.interrupted", (evt) => {
1203+
const sid = (evt as { data?: { sessionID?: string } }).data?.sessionID
1204+
if (typeof sid === "string") {
1205+
dbg(`event execution.interrupted ${sid}`)
1206+
report(sid, { outcome: "interrupted" }).catch((e: unknown) => dbg(`report threw: ${String(e)}`))
1207+
}
1208+
})
1209+
)
1210+
off.push(
1211+
ctx.data.on("session.execution.failed", (evt) => {
1212+
const sid = (evt as { data?: { sessionID?: string } }).data?.sessionID
1213+
if (typeof sid === "string") {
1214+
dbg(`event execution.failed ${sid}`)
1215+
report(sid, { outcome: "failed" }).catch((e: unknown) => dbg(`report threw: ${String(e)}`))
1216+
}
1217+
})
1218+
)
11341219
} catch (e: unknown) {
11351220
dbg(`subscribe failed: ${String(e)}`)
11361221
}

‎universal.ts‎

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,18 @@ export function turnRate(
112112
* Reading only the last one showed `140 tok 10.20s` for a 316-token, 37s turn.
113113
*/
114114
export function turnSteps(
115-
msgs: readonly ({ type?: string } | undefined)[]
115+
msgs: readonly ({ type?: string; id?: string } | undefined)[],
116+
/**
117+
* The reply's last step. Given, the turn ends there rather than at the end
118+
* of the list: a message sent while a reply is running is queued into the
119+
* same execution, so by the time the first reply ends the list can already
120+
* hold the next user message after it (measured: a 9-step reply ending in
121+
* `stop`, then a queued message's step 2s later, in one execution).
122+
*/
123+
endID?: string
116124
): SessionMessageAssistant[] {
117125
const steps: SessionMessageAssistant[] = []
118-
for (let i = msgs.length - 1; i >= 0; i--) {
126+
for (let i = lastIndex(msgs, endID); i >= 0; i--) {
119127
const m = msgs[i]
120128
if (!m) continue
121129
if (m.type === "user") break
@@ -124,6 +132,24 @@ export function turnSteps(
124132
return steps
125133
}
126134

135+
/** When the user message that opened the turn ending at `endID` was sent. */
136+
export function turnUserAt(
137+
msgs: readonly ({ type?: string; id?: string; time?: { created?: number } } | undefined)[],
138+
endID?: string
139+
): number | undefined {
140+
for (let i = lastIndex(msgs, endID); i >= 0; i--) {
141+
const m = msgs[i]
142+
if (m?.type === "user") return m.time?.created
143+
}
144+
return undefined
145+
}
146+
147+
function lastIndex(msgs: readonly ({ id?: string } | undefined)[], endID?: string): number {
148+
if (endID === undefined) return msgs.length - 1
149+
const i = msgs.findIndex((m) => m?.id === endID)
150+
return i >= 0 ? i : msgs.length - 1
151+
}
152+
127153
/**
128154
* The model a session last used or selected, newest first: an assistant
129155
* message's model, or a `model-switched` entry. Undefined for a session with
@@ -160,7 +186,12 @@ export function lastModel(
160186
export function aggregateTurn(
161187
steps: readonly SessionMessageAssistant[],
162188
marks: ReadonlyMap<string, Turn>,
163-
opts: { execStart?: number } = {}
189+
/**
190+
* `execStart`: when the reply started (the execution, or the previous reply
191+
* in it ending). `endAt`: when an interrupted reply stopped, since its last
192+
* step never completed.
193+
*/
194+
opts: { execStart?: number; endAt?: number } = {}
164195
): { info: SessionMessageAssistant | undefined; turn: Turn | undefined } {
165196
const first = steps[0]
166197
const last = steps[steps.length - 1]
@@ -198,7 +229,7 @@ export function aggregateTurn(
198229

199230
const info: SessionMessageAssistant = {
200231
...last,
201-
time: { created: opts.execStart ?? first.time.created, completed: last.time?.completed },
232+
time: { created: opts.execStart ?? first.time.created, completed: last.time?.completed ?? opts.endAt },
202233
tokens: {
203234
input: last.tokens?.input ?? 0,
204235
output,

0 commit comments

Comments
 (0)