mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
feat(tui): budget transcript mounting by rendered entries (#50936)
This commit is contained in:
committed by
GitHub
Unverified
parent
a117ebb408
commit
b3b030856b
@@ -120,6 +120,7 @@ import type { SessionEntry } from "./grouping/session"
|
||||
import { SessionGroupView } from "./group-view"
|
||||
import { useEntryAnchor } from "./anchor-view"
|
||||
import { containsAnchor, createTimelineAnchors } from "./anchors"
|
||||
import { rowsAfter, rowsBefore, rowWeight } from "./mount-budget"
|
||||
export { InlineToolRow } from "./message-parts"
|
||||
export { toolDisplay } from "./message-parts"
|
||||
|
||||
@@ -129,6 +130,7 @@ addDefaultParsers(parsers.parsers)
|
||||
const NAVIGATION_SLACK_ID = "session-navigation-slack"
|
||||
const BACKGROUND_TOOL_HINT_DELAY = 3_000
|
||||
|
||||
// Budgets count rendered entries (see mount-budget.ts); a collapsed group costs one.
|
||||
// The tail comfortably overfills a tall viewport; older rows mount as the reader approaches them.
|
||||
const TRANSCRIPT_TAIL_ROWS = 40
|
||||
const TRANSCRIPT_BACKFILL_CHUNK = 60
|
||||
@@ -390,7 +392,17 @@ export function Session(props: {
|
||||
// at the bottom the hidden span follows appends; leaving the bottom pins it to preserve the viewport.
|
||||
const [hiddenRows, setHiddenRows] = createSignal<number>()
|
||||
const [visibleRowsEnd, setVisibleRowsEnd] = createSignal<number>()
|
||||
const hidden = createMemo(() => Math.max(0, Math.min(hiddenRows() ?? Infinity, rows.length - TRANSCRIPT_TAIL_ROWS)))
|
||||
const weights = createMemo(() =>
|
||||
rows.map((row) =>
|
||||
rowWeight(row, {
|
||||
expanded: (groupID) => sessionTabs.groupExpanded(sessionID, groupID) ?? false,
|
||||
grouped: (kind) => (kind === "reasoning" ? thinkingMode() === "hide" : groupExploration()),
|
||||
}),
|
||||
),
|
||||
)
|
||||
const hidden = createMemo(() =>
|
||||
Math.min(hiddenRows() ?? Infinity, rowsBefore(weights(), rows.length, TRANSCRIPT_TAIL_ROWS)),
|
||||
)
|
||||
const visibleEnd = createMemo(() => Math.max(hidden(), Math.min(visibleRowsEnd() ?? rows.length, rows.length)))
|
||||
const visibleRows = createMemo(() => rows.slice(hidden(), visibleEnd()))
|
||||
const prependHistory = createHistoryPrepend({
|
||||
@@ -422,7 +434,7 @@ export function Session(props: {
|
||||
revealingOlderRows = true
|
||||
const before = scroll.scrollHeight
|
||||
scroll.stickyScroll = false
|
||||
setHiddenRows(Math.max(0, current - TRANSCRIPT_BACKFILL_CHUNK))
|
||||
setHiddenRows(rowsBefore(weights(), current, TRANSCRIPT_BACKFILL_CHUNK))
|
||||
afterLayout(() => {
|
||||
scroll.scrollBy(scroll.scrollHeight - before + scrollBy)
|
||||
scroll.stickyScroll = !navigationMessage()
|
||||
@@ -442,7 +454,7 @@ export function Session(props: {
|
||||
)
|
||||
return false
|
||||
revealingNewerRows = true
|
||||
const next = Math.min(rows.length, current + TRANSCRIPT_BACKFILL_CHUNK)
|
||||
const next = rowsAfter(weights(), current, TRANSCRIPT_BACKFILL_CHUNK)
|
||||
setVisibleRowsEnd(next === rows.length ? undefined : next)
|
||||
afterLayout(() => {
|
||||
revealingNewerRows = false
|
||||
@@ -537,8 +549,8 @@ export function Session(props: {
|
||||
setAwayFromBottom(false)
|
||||
return
|
||||
}
|
||||
setHiddenRows(Math.max(0, index - TRANSCRIPT_BACKFILL_CHUNK))
|
||||
const end = Math.min(rows.length, index + TRANSCRIPT_BACKFILL_CHUNK)
|
||||
setHiddenRows(rowsBefore(weights(), index, TRANSCRIPT_BACKFILL_CHUNK))
|
||||
const end = rowsAfter(weights(), index, TRANSCRIPT_BACKFILL_CHUNK)
|
||||
setVisibleRowsEnd(end === rows.length ? undefined : end)
|
||||
scroll.stickyScroll = false
|
||||
const restore = () =>
|
||||
@@ -555,7 +567,7 @@ export function Session(props: {
|
||||
const target = contentY - anchor.screenY
|
||||
const maximum = Math.max(0, scroll.scrollHeight - scroll.viewport.height)
|
||||
if (target > maximum && visibleEnd() < rows.length) {
|
||||
const next = Math.min(rows.length, visibleEnd() + TRANSCRIPT_BACKFILL_CHUNK)
|
||||
const next = rowsAfter(weights(), visibleEnd(), TRANSCRIPT_BACKFILL_CHUNK)
|
||||
setVisibleRowsEnd(next === rows.length ? undefined : next)
|
||||
restore()
|
||||
return
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { groupID } from "./anchors"
|
||||
import type { GroupKind, SessionNode, SessionRow } from "./grouping/session"
|
||||
|
||||
/**
|
||||
* Transcript mounting is budgeted by rendered entries, not rows. A collapsed group
|
||||
* renders one header however many parts it holds; an expanded or ungrouped one
|
||||
* renders its children. With every group collapsed each row costs one, which is
|
||||
* the former row-count budget.
|
||||
*/
|
||||
export function rowWeight(
|
||||
row: SessionRow,
|
||||
input: { expanded: (groupID: string) => boolean; grouped: (kind: GroupKind) => boolean },
|
||||
) {
|
||||
if (row.type !== "group") return 1
|
||||
const visit = (node: Extract<SessionNode, { type: "group" }>, level: number): number => {
|
||||
if (!input.grouped(node.kind)) return node.size
|
||||
const id = groupID(node, level)
|
||||
if (!id || !input.expanded(id)) return 1
|
||||
return node.children.reduce((total, child) => total + (child.type === "group" ? visit(child, level + 1) : 1), 1)
|
||||
}
|
||||
return visit(row, 0)
|
||||
}
|
||||
|
||||
/** First row index such that rows [index, end) spend at least `budget`. */
|
||||
export function rowsBefore(weights: readonly number[], end: number, budget: number) {
|
||||
let index = end
|
||||
let spent = 0
|
||||
while (index > 0 && spent < budget) spent += weights[--index]
|
||||
return index
|
||||
}
|
||||
|
||||
/** End row index such that rows [start, index) spend at least `budget`. */
|
||||
export function rowsAfter(weights: readonly number[], start: number, budget: number) {
|
||||
let index = start
|
||||
let spent = 0
|
||||
while (index < weights.length && spent < budget) spent += weights[index++]
|
||||
return index
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { groupID } from "../../../src/routes/session/anchors"
|
||||
import type { SessionEntry, SessionRow } from "../../../src/routes/session/grouping/session"
|
||||
import { groupEntries } from "../../../src/routes/session/grouping/tree"
|
||||
import { rowsAfter, rowsBefore, rowWeight } from "../../../src/routes/session/mount-budget"
|
||||
|
||||
const read = (index: number): SessionEntry => ({
|
||||
type: "part",
|
||||
ref: { messageID: `m${index}`, partID: `read-${index}` },
|
||||
})
|
||||
|
||||
function group(size: number, path: readonly ("exploration" | "reasoning")[] = ["exploration"]): SessionRow {
|
||||
const [node] = groupEntries(
|
||||
Array.from({ length: size }, (_, index) => read(index)),
|
||||
() => path,
|
||||
)
|
||||
if (node.type !== "group") throw new Error("Expected group")
|
||||
return node.kind === "reasoning"
|
||||
? { ...node, kind: "reasoning", completed: true }
|
||||
: { ...node, kind: "exploration", pending: [], completed: true }
|
||||
}
|
||||
|
||||
const collapsed = { expanded: () => false, grouped: () => true }
|
||||
|
||||
test("with every group collapsed each row costs one, matching the former row-count budget", () => {
|
||||
const rows: SessionRow[] = [
|
||||
{ type: "message", messageID: "u" },
|
||||
group(200),
|
||||
group(3, ["reasoning"]),
|
||||
read(1),
|
||||
{ type: "assistant-footer", messageID: "a" },
|
||||
]
|
||||
const weights = rows.map((row) => rowWeight(row, collapsed))
|
||||
expect(weights).toEqual([1, 1, 1, 1, 1])
|
||||
for (const length of [0, 1, 39, 40, 41, 150]) {
|
||||
const ones = Array.from({ length }, () => 1)
|
||||
expect(rowsBefore(ones, length, 40)).toBe(Math.max(0, length - 40))
|
||||
for (const index of [0, Math.floor(length / 2), length]) {
|
||||
expect(rowsBefore(ones, index, 60)).toBe(Math.max(0, index - 60))
|
||||
expect(rowsAfter(ones, index, 60)).toBe(Math.min(length, index + 60))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("an expanded group costs its header plus rendered children", () => {
|
||||
const row = group(200)
|
||||
if (row.type !== "group") throw new Error("Expected group")
|
||||
const id = groupID(row, 0)
|
||||
expect(rowWeight(row, { expanded: (key) => key === id, grouped: () => true })).toBe(201)
|
||||
})
|
||||
|
||||
test("a collapsed inner group costs one even when its parent is expanded", () => {
|
||||
const row = group(50, ["exploration", "exploration"])
|
||||
if (row.type !== "group" || row.children[0].type !== "group") throw new Error("Expected nested group")
|
||||
const outer = groupID(row, 0)
|
||||
const inner = groupID(row.children[0], 1)
|
||||
expect(rowWeight(row, { expanded: (key) => key === outer, grouped: () => true })).toBe(2)
|
||||
expect(rowWeight(row, { expanded: (key) => key === outer || key === inner, grouped: () => true })).toBe(52)
|
||||
// A saved expanded inner group under a collapsed parent mounts nothing.
|
||||
expect(rowWeight(row, { expanded: (key) => key === inner, grouped: () => true })).toBe(1)
|
||||
})
|
||||
|
||||
test("an ungrouped kind renders every leaf", () => {
|
||||
expect(rowWeight(group(12, ["reasoning"]), { expanded: () => false, grouped: (kind) => kind !== "reasoning" })).toBe(
|
||||
12,
|
||||
)
|
||||
})
|
||||
|
||||
test("a heavy tail group leaves fewer older rows mounted", () => {
|
||||
const weights = [...Array.from({ length: 100 }, () => 1), 201, 1, 1]
|
||||
// The expanded group alone exceeds the tail budget.
|
||||
expect(rowsBefore(weights, weights.length, 40)).toBe(100)
|
||||
expect(rowsAfter(weights, 90, 60)).toBe(101)
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import { expect, test } from "bun:test"
|
||||
import { createTestRenderer } from "@opentui/core/testing"
|
||||
import { ScrollBoxRenderable, type Renderable } from "@opentui/core"
|
||||
import { Effect, FileSystem } from "effect"
|
||||
import { Global } from "@opencode/util/global"
|
||||
import type { SessionMessageInfo } from "@opencode/client"
|
||||
import { createEventStream, createFetch, directory, json } from "./fixture/tui-client"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
|
||||
test("an expanded group spends the mounting budget that older rows used", async () => {
|
||||
await using state = await tmpdir()
|
||||
const setup = await createTestRenderer({ width: 100, height: 30, useThread: false, kittyKeyboard: true })
|
||||
setup.renderer.start()
|
||||
const session = {
|
||||
id: "ses_budget",
|
||||
title: "Budget",
|
||||
projectID: "proj_test",
|
||||
location: { directory },
|
||||
cost: 0,
|
||||
tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 0, updated: 0 },
|
||||
}
|
||||
const model = { providerID: "fixture", id: "fixture" }
|
||||
// 30 plain turns (3 rows each), then one turn whose single step makes 100 reads.
|
||||
const messages: SessionMessageInfo[] = [
|
||||
...Array.from({ length: 30 }, (_, index) => [
|
||||
{ type: "user" as const, id: `user-${index}`, text: `Turn ${index}`, time: { created: index * 10 } },
|
||||
{
|
||||
type: "assistant" as const,
|
||||
id: `answer-${index}`,
|
||||
agent: "build",
|
||||
model,
|
||||
finish: "stop" as const,
|
||||
time: { created: index * 10 + 1, completed: index * 10 + 2 },
|
||||
content: [{ type: "text" as const, text: `Answer ${index}` }],
|
||||
},
|
||||
]).flat(),
|
||||
{ type: "user", id: "user-explore", text: "Explore", time: { created: 1000 } },
|
||||
{
|
||||
type: "assistant",
|
||||
id: "answer-explore",
|
||||
agent: "build",
|
||||
model,
|
||||
finish: "stop",
|
||||
time: { created: 1001, completed: 1002 },
|
||||
content: Array.from({ length: 100 }, (_, index) => ({
|
||||
type: "tool" as const,
|
||||
id: `read-${index}`,
|
||||
name: "read",
|
||||
time: { created: 1001, completed: 1001 },
|
||||
state: {
|
||||
status: "completed" as const,
|
||||
input: { path: `${index}.ts` },
|
||||
content: [{ type: "text" as const, text: "ok" }] as [{ type: "text"; text: string }],
|
||||
metadata: {},
|
||||
},
|
||||
})),
|
||||
},
|
||||
]
|
||||
const calls = createFetch((url) => {
|
||||
if (url.pathname === "/api/session") return json({ data: [session], cursor: {} })
|
||||
if (url.pathname === `/api/session/${session.id}`) return json({ data: session })
|
||||
if (url.pathname === `/api/session/${session.id}/message`) return json({ data: messages.toReversed(), cursor: {} })
|
||||
if (url.pathname === `/api/session/${session.id}/inbox` || url.pathname === `/api/session/${session.id}/permission`)
|
||||
return json({ data: [] })
|
||||
}, createEventStream())
|
||||
const server = Bun.serve({ port: 0, idleTimeout: 0, fetch: (request) => calls.fetch(request) })
|
||||
const { run } = await import("../src/app")
|
||||
const task = Effect.runPromise(
|
||||
run({
|
||||
app: { name: "test", version: "test", channel: "test" },
|
||||
server: { endpoint: { url: server.url.toString() } },
|
||||
config: {
|
||||
get: async () => ({
|
||||
animations: false,
|
||||
tabs: { enabled: false },
|
||||
keybinds: { "session.messages_last_user": "ctrl+shift+u", "session.last": "ctrl+shift+l" },
|
||||
}),
|
||||
update: async () => ({}),
|
||||
},
|
||||
packages: { prepare: async () => ({ directory: "" }) },
|
||||
args: { sessionID: session.id },
|
||||
terminalHandoff: async () => ({ renderer: setup.renderer, mode: "dark", complete: () => {} }),
|
||||
log: () => {},
|
||||
}).pipe(Effect.provide(Global.layerWith({ state: state.path })), Effect.provide(FileSystem.layerNoop({}))),
|
||||
)
|
||||
const find = (node: Renderable): ScrollBoxRenderable | undefined =>
|
||||
node instanceof ScrollBoxRenderable && node.getRenderable("user-explore")
|
||||
? node
|
||||
: node.getChildren().map(find).find(Boolean)
|
||||
try {
|
||||
await setup.waitForFrame((frame) => frame.includes("Explored — 100 reads"))
|
||||
await setup.waitForVisualIdle({ quietFrames: 3 })
|
||||
const scroll = find(setup.renderer.root)
|
||||
if (!scroll) throw new Error("Missing transcript scrollbox")
|
||||
// Booleans keep a failure message from serializing the renderable graph.
|
||||
const mounted = (id: string) => scroll.getRenderable(id) !== undefined
|
||||
// Collapsed: 40 rows, the same as the former row budget. Turn 18 onward is mounted.
|
||||
expect(mounted("user-18")).toBe(true)
|
||||
expect(mounted("user-17")).toBe(false)
|
||||
|
||||
const header = setup
|
||||
.captureCharFrame()
|
||||
.split("\n")
|
||||
.findIndex((line) => line.includes("Explored — 100 reads"))
|
||||
await setup.mockMouse.click(6, header)
|
||||
await setup.waitForFrame((frame) => frame.includes("Read 99.ts"))
|
||||
await setup.waitForVisualIdle({ quietFrames: 3 })
|
||||
// Expanded: the group's 101 rendered entries exceed the 40-entry tail on their own.
|
||||
expect(mounted("user-29")).toBe(false)
|
||||
expect(mounted("user-explore")).toBe(false)
|
||||
|
||||
// Navigate back to the header (the view stayed pinned to the bottom), collapse, return.
|
||||
setup.mockInput.pressKey("u", { ctrl: true, shift: true })
|
||||
await setup.waitForFrame((frame) => frame.includes("Explored — 100 reads"))
|
||||
await setup.waitForVisualIdle({ quietFrames: 3 })
|
||||
await setup.mockMouse.click(
|
||||
6,
|
||||
setup
|
||||
.captureCharFrame()
|
||||
.split("\n")
|
||||
.findIndex((line) => line.includes("Explored — 100 reads")),
|
||||
)
|
||||
await setup.waitForVisualIdle({ quietFrames: 3 })
|
||||
setup.mockInput.pressKey("l", { ctrl: true, shift: true })
|
||||
await setup.waitForFrame((frame) => !frame.includes("Read 99.ts") && frame.includes("Explored — 100 reads"))
|
||||
await setup.waitForVisualIdle({ quietFrames: 3 })
|
||||
expect(mounted("user-18")).toBe(true)
|
||||
expect(mounted("user-17")).toBe(false)
|
||||
} finally {
|
||||
setup.renderer.destroy()
|
||||
await task
|
||||
await server.stop()
|
||||
}
|
||||
}, 20000)
|
||||
Reference in New Issue
Block a user