Skip to content
19 changes: 16 additions & 3 deletions packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ interface ProcessorContext extends Input {
needsCompaction: boolean
currentText: SessionV1.TextPart | undefined
reasoningMap: Record<string, SessionV1.ReasoningPart>
// Time of the last reasoning delta per part, so a thought ends when the model stopped thinking, not when the next chunk arrived.
reasoningLast: Record<string, number>
}

type StreamEvent = LLMEvent
Expand Down Expand Up @@ -114,6 +116,7 @@ const layer = Layer.effect(
needsCompaction: false,
currentText: undefined,
reasoningMap: {},
reasoningLast: {},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: ctx.reasoningLast is not cleared where ctx.reasoningMap is cleared

ctx.reasoningMap is reset in two places that leave the new ctx.reasoningLast map populated: the abort cleanup (ctx.reasoningMap = {}, processor.ts:638) and the start of every process iteration (ctx.reasoningMap = {}, processor.ts:712). The two maps are meant to stay parallel: finishReasoning reads ctx.reasoningLast[id] and deletes it only after the early return for an unknown id, so a reasoning-end for an id that is no longer in the map leaves the entry behind.

No wrong value is computed today (every reasoning-start overwrites the entry), but the drift is a trap for the next change here. Clear ctx.reasoningLast in the same two places, and delete the entry in finishReasoning before the early return.

}
let aborted = false
const clock = createGenerationClock()
Expand Down Expand Up @@ -261,9 +264,13 @@ const layer = Layer.effect(
if (!(reasoningID in ctx.reasoningMap)) return
// oxlint-disable-next-line no-self-assign -- reactivity trigger
ctx.reasoningMap[reasoningID].text = ctx.reasoningMap[reasoningID].text
ctx.reasoningMap[reasoningID].time = { ...ctx.reasoningMap[reasoningID].time, end: Date.now() }
ctx.reasoningMap[reasoningID].time = {
...ctx.reasoningMap[reasoningID].time,
end: ctx.reasoningLast[reasoningID] ?? Date.now(),
}
yield* session.updatePart(ctx.reasoningMap[reasoningID])
delete ctx.reasoningMap[reasoningID]
delete ctx.reasoningLast[reasoningID]
})

const ensureToolCall = Effect.fn("SessionProcessor.ensureToolCall")(function* (input: {
Expand Down Expand Up @@ -342,13 +349,15 @@ const layer = Layer.effect(
time: { start: Date.now() },
metadata: value.providerMetadata,
}
ctx.reasoningLast[value.id] = Date.now()
yield* session.updatePart(ctx.reasoningMap[value.id])
return

case "reasoning-delta":
// Match dev: silently drop orphan deltas (no preceding reasoning-start).
if (!(value.id in ctx.reasoningMap)) return
ctx.reasoningMap[value.id].text += value.text
ctx.reasoningLast[value.id] = Date.now()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: The new end-time semantics are not pinned down by a test

This line defines the behaviour the whole feature rests on: the reasoning part's persisted time.end is now the time of the last delta instead of the time the reasoning-end event was handled, and the TUI measures the pause from that value. Nothing asserts it, so a later change to the delta handling - or a provider that closes the reasoning block before its last delta - would silently change every marker.

packages/opencode/test/session/processor-effect.test.ts already drives the processor with a synthetic event stream (the test LLM server supports reasoning deltas). Assert there that a reasoning part's time.end equals its last delta timestamp and not the time reasoning-end was processed.

if (value.providerMetadata) ctx.reasoningMap[value.id].metadata = value.providerMetadata
yield* session.updatePartDelta({
sessionID: ctx.reasoningMap[value.id].sessionID,
Expand Down Expand Up @@ -622,14 +631,15 @@ const layer = Layer.effect(
ctx.currentText = undefined
}

for (const part of Object.values(ctx.reasoningMap)) {
const end = Date.now()
for (const [id, part] of Object.entries(ctx.reasoningMap)) {
const end = ctx.reasoningLast[id] ?? Date.now()
yield* session.updatePart({
...part,
time: { start: part.time.start ?? end, end },
})
}
ctx.reasoningMap = {}
ctx.reasoningLast = {}

yield* Effect.forEach(
Object.values(ctx.toolcalls),
Expand Down Expand Up @@ -703,7 +713,10 @@ const layer = Layer.effect(
return yield* Effect.gen(function* () {
yield* Effect.gen(function* () {
ctx.currentText = undefined
// A retry after a stalled or failed stream must not leave the previous attempt's thought open.
yield* Effect.forEach(Object.keys(ctx.reasoningMap), finishReasoning)
ctx.reasoningMap = {}
ctx.reasoningLast = {}
yield* status.set(ctx.sessionID, { type: "busy" })
const stream = llm.stream(streamInput)
clock.startRequest(Date.now())
Expand Down
15 changes: 15 additions & 0 deletions packages/tui/src/routes/session/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ import { PermissionPrompt } from "./permission"
import { QuestionPrompt } from "./question"
import { DialogExportOptions } from "../../ui/dialog-export-options"
import * as Model from "../../util/model"
import { pauseMarker } from "../../util/pause"
import { elapsed, useClock } from "../../util/clock"
import { formatTranscript } from "../../util/transcript"
import { formatGenerationMetrics } from "../../util/generation-metrics"
Expand Down Expand Up @@ -1718,7 +1719,20 @@ export function AssistantMessageRow(props: { message: AssistantMessage; parts: P
return { groupID, owner: info.parts[0]?.part.id === part.id }
})
const component = createMemo(() => PART_MAPPING[part.type as keyof typeof PART_MAPPING])
const pause = createMemo(() => (group() && !group()!.owner ? undefined : pauseMarker(props.parts, index())))
return (
<>
<Show when={pause()}>
{(text) => (
<box
marginTop={1}
border={["top"]}
title={` ↻ ${text()} `}
titleAlignment="center"
borderColor={theme.border}
/>
)}
</Show>
<Switch>
<Match when={group()?.owner === true}>
<ActivityGroup groupID={group()!.groupID} />
Expand All @@ -1737,6 +1751,7 @@ export function AssistantMessageRow(props: { message: AssistantMessage; parts: P
</Show>
</Match>
</Switch>
</>
)
}}
</For>
Expand Down
43 changes: 43 additions & 0 deletions packages/tui/src/util/pause.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Part } from "@opencode-ai/sdk/v2"

// Only a real stall gets a marker: a minute with no token arriving. Normal streaming never gets near this.
export const PAUSE_MIN_MS = 60_000

function startOf(part: Part | undefined): number | undefined {
if (!part) return undefined
// A tool part is only timed once its arguments finished streaming, so it cannot tell a silent model from one that is still sending tokens.
if (part.type === "text" || part.type === "reasoning") return part.time?.start
return undefined
}

/**
* Milliseconds with no token between the last thinking token and the next text or
* thinking part, when long enough to be a stall.
*/
export function pauseBefore(parts: readonly Part[], index: number): number | undefined {
// A retry opens a new step, so look past the step marker to the previous visible part.
let before = index - 1
while (before >= 0 && parts[before]?.type === "step-start") before--
const prev = parts[before]
if (!prev || prev.type !== "reasoning") return undefined
const end = prev.time.end
const start = startOf(parts[index])
if (end === undefined || start === undefined) return undefined
const gap = start - end
// The stream watchdog fires a minute after the last token, so allow a second of timer jitter.
return gap >= PAUSE_MIN_MS - 1000 ? gap : undefined
}

export function pauseLabel(ms: number): string {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: pauseLabel duplicates Locale.duration in a second format

Locale.duration (packages/tui/src/util/locale.ts:38) already formats a millisecond duration for this TUI and is what the reasoning header uses for Thought · 1.2s. The new helper renders the same kind of value differently (8s vs 8.0s), so the pause marker and the thought duration drawn right next to it disagree, and it has no hour/day branch - an hour-long pause renders as 60m 0s.

Reuse Locale.duration for the marker (the session route already imports it) and drop pauseLabel, unless the compact form is deliberate - in which case the divergence needs a reason and a test.

const seconds = Math.round(ms / 1000)
if (seconds < 60) return `${seconds}s`
return `${Math.floor(seconds / 60)}m ${seconds % 60}s`
}

// The marker text. A stall that ends in a new thought is a retried stream.
export function pauseMarker(parts: readonly Part[], index: number): string | undefined {
const ms = pauseBefore(parts, index)
if (ms === undefined) return undefined
const retried = parts[index]?.type === "reasoning"
return `Stalled for ${pauseLabel(ms)}${retried ? ", retrying..." : ""}`
}
48 changes: 48 additions & 0 deletions packages/tui/test/pause.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { describe, expect, test } from "bun:test"
import type { Part } from "@opencode-ai/sdk/v2"
import { pauseBefore, pauseLabel, pauseMarker } from "../src/util/pause"

const reasoning = (start: number, end?: number) => ({ type: "reasoning", time: { start, end } }) as unknown as Part
const text = (start: number) => ({ type: "text", time: { start } }) as unknown as Part
const tool = (start?: number) =>
({ type: "tool", state: start === undefined ? { status: "pending" } : { status: "running", time: { start } } }) as unknown as Part

describe("pauseBefore", () => {
test("marks a stall of a minute or more before the next text or thought", () => {
expect(pauseBefore([reasoning(0, 1000), text(61000)], 1)).toBe(60000)
expect(pauseBefore([reasoning(0, 1000), reasoning(121000, 122000)], 1)).toBe(120000)
})
test("a retry's step marker does not hide the stall", () => {
const step = { type: "step-start" } as unknown as Part
expect(pauseBefore([reasoning(0, 1000), step, reasoning(63000, 64000)], 2)).toBe(62000)
})
test("normal streaming latency never gets a marker", () => {
expect(pauseBefore([reasoning(0, 1000), text(3000)], 1)).toBeUndefined()
expect(pauseBefore([reasoning(0, 1000), text(30000)], 1)).toBeUndefined()
expect(pauseBefore([reasoning(0, 1000), text(58000)], 1)).toBeUndefined()
expect(pauseBefore([reasoning(0, 1000), text(60000)], 1)).toBe(59000)
})
test("tool calls are never marked, since their time includes streamed arguments", () => {
expect(pauseBefore([reasoning(0, 1000), tool(300000)], 1)).toBeUndefined()
})
test("ignores the first part and parts that do not follow reasoning or lack timing", () => {
expect(pauseBefore([reasoning(0, 1000)], 0)).toBeUndefined()
expect(pauseBefore([text(0), text(300000)], 1)).toBeUndefined()
expect(pauseBefore([reasoning(0), text(300000)], 1)).toBeUndefined()
})
test("labels seconds and minutes", () => {
expect(pauseLabel(60000)).toBe("1m 0s")
expect(pauseLabel(75000)).toBe("1m 15s")
})
})

describe("pauseMarker", () => {
test("says retrying when the stall ended in a new thought", () => {
const step = { type: "step-start" } as unknown as Part
expect(pauseMarker([reasoning(0, 1000), step, reasoning(63000, 64000)], 2)).toBe("Stalled for 1m 2s, retrying...")
})
test("plain stall before text", () => {
expect(pauseMarker([reasoning(0, 1000), text(91000)], 1)).toBe("Stalled for 1m 30s")
expect(pauseMarker([reasoning(0, 1000), text(3000)], 1)).toBeUndefined()
})
})
Loading