diff --git a/packages/app/component-tests/timeline-pretext.fixture.tsx b/packages/app/component-tests/timeline-pretext.fixture.tsx new file mode 100644 index 00000000000..457d4678f15 --- /dev/null +++ b/packages/app/component-tests/timeline-pretext.fixture.tsx @@ -0,0 +1,158 @@ +import type { SessionDocument } from "@opencode/session-ui/document" +import { CurrentSessionProviders, STORY_MODEL, STORY_TIME } from "@opencode/session-ui/storybook" +import { createReactiveTimelineProjection, TimelineRow } from "@opencode/session-ui/timeline/projection" +import { createSessionTimelineRowRenderer } from "@opencode/session-ui/timeline/row" +import type { TimelineRowLayout } from "@opencode/session-ui/timeline/text-layout" +import { DialogProvider } from "@opencode/ui/context/dialog" +import { createStore } from "solid-js/store" +import { render } from "solid-js/web" +import { LanguageProvider } from "../src/runtime/i18n/language" +import { createTimelineVirtualizer } from "../src/session/timeline/virtualizer" + +let report = () => ({ + count: 0, + fallbacks: 0, + expected: 0, + extent: 0, + offset: 0, + viewport: 0, + mounted: 0, + mismatches: [] as string[], +}) +let reveal = (_id: string) => {} + +export function mountLongTimeline(count = 1800) { + const host = document.createElement("main") + host.dataset.testid = "pretext-long-timeline" + host.style.cssText = + "position:fixed;inset:24px;width:744px;height:640px;z-index:1000;background:var(--v2-background-bg-base)" + document.body.append(host) + const fixture: SessionDocument = { + sessionID: "pretext-long-session", + status: { type: "idle" }, + diffs: [], + messages: Array.from({ length: count }, (_, index) => index).flatMap((index) => [ + { + id: `long-user-${index}`, + type: "user" as const, + text: `Question ${index + 1}: ${"Explain how this part of the timeline works. ".repeat(1 + (index % 4))}`, + metadata: { agent: "build", model: STORY_MODEL }, + time: { created: STORY_TIME + index * 2 }, + }, + { + id: `long-assistant-${index}`, + type: "assistant" as const, + agent: "build", + model: STORY_MODEL, + content: [ + { + type: "text" as const, + text: + index % 3 === 0 + ? `## Result ${index + 1}\n\n${"The prepared text preserves **strong words** and `inline code`. ".repeat(1 + (index % 7))}` + : index % 3 === 1 + ? `A concrete implementation.\n\n\`\`\`ts\nconst result = ${index};\nconsole.log(result);\n\`\`\`\n\nThe source stays selectable.` + : `These are the steps.\n\n- Prepare the text once.\n- Reuse its measured advances when the viewport changes.\n- Paint the same revision.\n\nReady.`, + }, + ], + time: { created: STORY_TIME + index * 2, completed: STORY_TIME + index * 2 + 1 }, + }, + ]), + } + function Fixture() { + const [state, setState] = createStore({ pinned: true }) + const sizes = new Map() + let viewport: HTMLDivElement | undefined + const projection = createReactiveTimelineProjection({ + sessionMessages: () => fixture.messages, + status: () => fixture.status, + reasoningMode: () => "compact", + shellToolDefaultOpen: () => false, + editToolDefaultOpen: () => false, + }) + const timeline = createTimelineVirtualizer({ + sessionKey: () => fixture.sessionID, + projection, + showHeader: () => false, + layout: (row, environment) => { + const value = renderer.layout(row, environment) + sizes.set(TimelineRow.key(row), value) + return value + }, + pinned: () => state.pinned, + scroll: () => ({ overflow: true, jump: !state.pinned }), + setScrollRef: (element) => { + viewport = element + }, + setContentRef: () => {}, + onPin: () => setState("pinned", true), + onUnpin: () => setState("pinned", false), + onScheduleScrollState: () => {}, + onResumeScroll: () => {}, + onSelectionInteraction: () => {}, + onUserScroll: () => {}, + onHistoryScroll: () => {}, + canRenderImmediately: () => true, + setRevealMessage: (callback) => { + reveal = callback + }, + }) + const renderer = createSessionTimelineRowRenderer({ + sessionID: () => fixture.sessionID, + status: () => fixture.status, + projection, + presentation: () => undefined, + reasoningMode: () => "compact", + shellToolDefaultOpen: () => false, + editToolDefaultOpen: () => false, + disclosure: timeline.disclosure, + }) + report = () => { + const mounted = [...host.querySelectorAll("[data-timeline-key]")] + return { + count: projection.rows().length, + fallbacks: projection.rows().filter((row) => sizes.get(TimelineRow.key(row))?.source === "dom").length, + expected: [...sizes.values()].reduce((sum, value) => sum + (value.source === "dom" ? 0 : value.height), 80), + extent: viewport?.scrollHeight ?? 0, + offset: viewport?.scrollTop ?? 0, + viewport: viewport?.clientHeight ?? 0, + mounted: mounted.length, + mismatches: mounted.flatMap((element) => { + const key = element.dataset.timelineKey! + const size = sizes.get(key) + const natural = element.firstElementChild!.getBoundingClientRect().height + return size && size.source !== "dom" && Math.abs(natural - size.height) > 1 + ? [`${key}: ${natural} != ${size.height}`] + : [] + }), + } + } + return ( + false} + renderRow={(row, onSizeChange) => } + /> + ) + } + render( + () => ( + + + + + + + + ), + host, + ) +} + +export function longTimelineReport() { + return report() +} +export function jumpLongTimeline(index: number) { + reveal(`long-user-${index}`) + return report() +} diff --git a/packages/app/component-tests/timeline-virtualizer.fixture.tsx b/packages/app/component-tests/timeline-virtualizer.fixture.tsx index 2f9b2e91785..a2f4c05e13a 100644 --- a/packages/app/component-tests/timeline-virtualizer.fixture.tsx +++ b/packages/app/component-tests/timeline-virtualizer.fixture.tsx @@ -38,6 +38,7 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb messageLastRowIndex: () => indexes, }, showHeader: () => false, + layout: () => ({ source: "dom", reason: "deferred fixture content" }), pinned: () => state.pinned, scroll: () => ({ overflow: false, jump: false }), setScrollRef: (element) => { diff --git a/packages/app/component-tests/timeline-virtualizer.spec.ts b/packages/app/component-tests/timeline-virtualizer.spec.ts index 9497a32a9d1..6505a80cbe1 100644 --- a/packages/app/component-tests/timeline-virtualizer.spec.ts +++ b/packages/app/component-tests/timeline-virtualizer.spec.ts @@ -1,6 +1,36 @@ import { expect, sourceURL, story } from "../../stories/playwright/story" +import { writeFile } from "node:fs/promises" const fixture = sourceURL(new URL("./timeline-virtualizer.fixture.tsx", import.meta.url)) +const pretextFixture = sourceURL(new URL("./timeline-pretext.fixture.tsx", import.meta.url)) + +story("precomputes the full extent of 5000 rows before revealing or jumping", async ({ page }, testInfo) => { + await page.evaluate(async (url) => { + ;(await import(url)).mountLongTimeline() + }, pretextFixture) + const root = page.getByTestId("pretext-long-timeline") + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const initial = await page.evaluate(async (url) => (await import(url)).longTimelineReport(), pretextFixture) + await writeFile(testInfo.outputPath("long-initial.json"), JSON.stringify(initial, null, 2)) + expect(initial.count).toBeGreaterThan(5000) + expect(initial.fallbacks).toBe(0) + expect(Math.abs(initial.extent - initial.expected)).toBeLessThanOrEqual(1) + expect(Math.abs(initial.offset - (initial.extent - initial.viewport))).toBeLessThanOrEqual(1) + expect(initial.mounted).toBeLessThan(30) + expect(initial.mismatches).toEqual([]) + for (const index of [0, 900, 1799, 451]) { + const immediate = await page.evaluate(async ({ url, index }) => (await import(url)).jumpLongTimeline(index), { + url: pretextFixture, + index, + }) + await expect(root.locator(`[data-timeline-key="user-message:long-user-${index}"]`)).toBeVisible() + const painted = await page.evaluate(async (url) => (await import(url)).longTimelineReport(), pretextFixture) + await writeFile(testInfo.outputPath(`jump-${index}.json`), JSON.stringify({ immediate, painted }, null, 2)) + expect(Math.abs(painted.extent - initial.extent)).toBeLessThanOrEqual(1) + expect(Math.abs(painted.offset - immediate.offset)).toBeLessThanOrEqual(1) + expect(painted.mismatches).toEqual([]) + } +}) story.beforeEach(async ({ mount }) => { const component = await mount("opencode-composer-flow--mixed-attachments") diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx index a47693018b6..9b1553fa025 100644 --- a/packages/app/src/session/timeline/virtualizer.tsx +++ b/packages/app/src/session/timeline/virtualizer.tsx @@ -1431,16 +1431,8 @@ export function createTimelineVirtualizer(input: Input) { virtualizer.scrollToEnd() }) }} -<<<<<<< HEAD data-index={leaving() ? -1 : item().index} - style={{ "min-height": ready() ? undefined : `${initialItem.size}px` }} -||||||| parent of ba5527bd24 (feat(app): measure timeline rows with pretext) - data-index={item().index} - style={{ "min-height": ready() ? undefined : `${initialItem.size}px` }} -======= - data-index={item().index} style={{ "min-height": ready() || modeled() ? undefined : `${initialItem.size}px` }} ->>>>>>> ba5527bd24 (feat(app): measure timeline rows with pretext) > {props.renderRow(row, () => { setReady(true) diff --git a/packages/session-ui/component-tests/session-timeline.spec.ts b/packages/session-ui/component-tests/session-timeline.spec.ts index 962b7a1ae24..c90ef74e12d 100644 --- a/packages/session-ui/component-tests/session-timeline.spec.ts +++ b/packages/session-ui/component-tests/session-timeline.spec.ts @@ -1,4 +1,62 @@ -import { expect, story } from "../../stories/playwright/story" +import { expect, sourceURL, story } from "../../stories/playwright/story" +import { writeFile } from "node:fs/promises" + +const layoutFixture = sourceURL(new URL("./timeline-layout.fixture.tsx", import.meta.url)) + +story("models row heights before mounting and after width changes", async ({ mount, page }, testInfo) => { + page.on("pageerror", (error) => console.error(error.stack)) + page.on("console", (message) => { + if (message.type() === "error") console.error(message.text()) + }) + await mount("current-session-timeline-rows--agent-thinking") + await page.evaluate(async (url) => { + const fixture = await import(url) + await fixture.mountTimelineLayout(680) + }, layoutFixture) + const fixture = page.getByTestId("timeline-layout-fixture") + await expect(fixture.locator('[data-component="markdown"][data-markdown-ready]')).toHaveCount(6) + for (const width of [680, 370]) { + const report = await page.evaluate( + async ({ url, width }) => { + const fixture = await import(url) + return fixture.timelineLayoutReport(width) + }, + { url: layoutFixture, width }, + ) + await writeFile(testInfo.outputPath(`row-layout-${width}.json`), JSON.stringify(report, null, 2)) + expect(report.length).toBeGreaterThanOrEqual(8) + expect(report.filter((row: { source: string }) => row.source === "dom")).toEqual([]) + for (const row of report) expect(Math.abs(row.actual - row.expected), JSON.stringify(row)).toBeLessThanOrEqual(1) + } + const chunks = [ + "A streaming paragraph with **emphasis", + "A streaming paragraph with **emphasis** and additional words.\n\n```ts\nconst value = 1", + "A streaming paragraph with **emphasis** and additional words.\n\n```ts\nconst value = 1\nconsole.log(value)\n```\n\nDone.", + "A streaming paragraph with **emphasis** and additional words.\n\n```ts\nconst value = 1\nconsole.log(value)\n```\n\nDone.\n\n- First result\n- Second result", + ] + for (const [index, text] of [...chunks, chunks.at(-1)!].entries()) { + const report = await page.evaluate( + async ({ url, text, complete }) => { + const fixture = await import(url) + return fixture.streamTimelineLayout(text, complete) + }, + { url: layoutFixture, text, complete: index === chunks.length }, + ) + await writeFile(testInfo.outputPath(`row-stream-${index}.json`), JSON.stringify(report, null, 2)) + expect(report.filter((row: { source: string }) => row.source === "dom")).toEqual([]) + for (const row of report) expect(Math.abs(row.actual - row.expected), JSON.stringify(row)).toBeLessThanOrEqual(1) + } + const reasoning = await page.evaluate(async (url) => { + const fixture = await import(url) + return fixture.reasonTimelineLayout( + "Consider the constraints carefully. ".repeat(8) + + "\n\n**The next step**\n\nInspect the source and decide what needs to change.", + ) + }, layoutFixture) + await writeFile(testInfo.outputPath("row-reasoning.json"), JSON.stringify(reasoning, null, 2)) + expect(reasoning.filter((row: { source: string }) => row.source === "dom")).toEqual([]) + for (const row of reasoning) expect(Math.abs(row.actual - row.expected), JSON.stringify(row)).toBeLessThanOrEqual(1) +}) story("spaces an error between a shell result and expanded updates", async ({ mount }) => { const timeline = await mount("current-session-error-spacing--error-and-updates") diff --git a/packages/session-ui/component-tests/timeline-layout.fixture.tsx b/packages/session-ui/component-tests/timeline-layout.fixture.tsx new file mode 100644 index 00000000000..4713dd1bc7c --- /dev/null +++ b/packages/session-ui/component-tests/timeline-layout.fixture.tsx @@ -0,0 +1,225 @@ +import { For, batch, createMemo } from "solid-js" +import { createStore } from "solid-js/store" +import { render } from "solid-js/web" +import { DialogProvider } from "@opencode/ui/context/dialog" +import type { SessionDocument } from "../src/document" +import { CurrentSessionProviders } from "../src/storybook/current-session-story" +import { CURRENT_SESSION_ID, STORY_MODEL, STORY_TIME } from "../src/storybook/current-session-fixtures" +import { createReactiveTimelineProjection, TimelineRow } from "../src/timeline/projection" +import { createSessionTimelineRowRenderer } from "../src/timeline/session-timeline-row" +import { readTimelineTypography } from "../src/timeline/text-layout" + +const prompts = [ + "Short prompt.", + "A prompt whose wrapping must match the bubble width. ".repeat(12), + "Preserve these newlines.\n\nAnd this indented line:\n indentation is meaningful.", + "日本語の会話を読みながら English words and emoji 🦊🌿 move between lines. ".repeat(7), + "Show the implementation.", + "Explain the sequence.", +] +const replies = [ + "A short response.", + "Ordinary prose wraps at the same width before and after it is mounted. ".repeat(9), + "## A heading\n\nA **strong phrase** followed by `inline code` and more prose.\n\nAnother paragraph.", + "日本語の返答と English text share a paragraph. ".repeat(9), + "Here is the code.\n\n```ts\nconst long = 'a deliberately long non-wrapping source line that must not change the row height when the column narrows';\nconsole.log(long)\n```\n\nThe result stays selectable.", + "A list with nested items.\n\n- First item with **emphasis** and enough prose to wrap in the narrow column.\n- Second item\n - Nested item with more detail.\n - Another nested item.\n\n1. An ordered step.\n2. Another ordered step.\n\n> A quoted paragraph that should wrap and retain its ordinary paragraph height.\n\nA closing paragraph.", +] +const documentFixture: SessionDocument = { + sessionID: CURRENT_SESSION_ID, + status: { type: "idle" }, + diffs: [], + messages: prompts.flatMap((text, index) => [ + { + id: `layout-user-${index}`, + type: "user" as const, + text, + files: + index === 1 + ? Array.from({ length: 7 }, (_, image) => ({ + mime: "image/svg+xml", + name: `image-${image}.svg`, + data: "", + source: { + type: "uri" as const, + uri: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='200'%3E%3Crect width='400' height='200' fill='steelblue'/%3E%3C/svg%3E", + }, + })) + : undefined, + time: { created: STORY_TIME + index * 2 }, + metadata: { agent: "build", model: STORY_MODEL }, + }, + { + id: `layout-assistant-${index}`, + type: "assistant" as const, + agent: "build", + model: STORY_MODEL, + content: [ + ...(index === 0 + ? [ + { + type: "reasoning" as const, + text: "Inspect the existing implementation.", + time: { created: STORY_TIME, completed: STORY_TIME + 1 }, + }, + { + type: "tool" as const, + id: "layout-read", + name: "read", + state: { + status: "completed" as const, + input: { path: "packages/app/src/session/timeline/virtualizer.tsx" }, + content: [{ type: "text" as const, text: "Source content." }], + }, + time: { created: STORY_TIME, ran: STORY_TIME, completed: STORY_TIME + 1 }, + }, + ] + : []), + { type: "text" as const, text: replies[index]! }, + ], + time: { created: STORY_TIME + index * 2, completed: STORY_TIME + index * 2 + 1 }, + }, + ]), +} + +let inspect = () => [] as { key: string; source: string; expected?: number; actual: number }[] +let resize = (_width: number) => {} +let stream = (_text: string, _complete: boolean) => {} +let reasoning = (_text: string) => {} + +export async function mountTimelineLayout(width: number) { + const host = document.createElement("div") + host.dataset.testid = "timeline-layout-fixture" + document.body.append(host) + const typography = readTimelineTypography(host, 1) + const text = [...prompts, ...replies].join("") + await Promise.all([ + document.fonts.load(`${typography.weight} ${typography.size}px ${typography.family}`, text), + document.fonts.load(`${typography.medium} ${typography.size}px ${typography.family}`, text), + document.fonts.load(`${typography.weight} ${typography.size}px ${typography.codeFamily}`, text), + ]) + function Fixture() { + const [state, setState] = createStore({ width, open: false, document: structuredClone(documentFixture) }) + const projection = createReactiveTimelineProjection({ + sessionMessages: () => state.document.messages, + status: () => state.document.status, + reasoningMode: () => "compact", + shellToolDefaultOpen: () => false, + editToolDefaultOpen: () => false, + }) + const renderer = createSessionTimelineRowRenderer({ + sessionID: () => documentFixture.sessionID, + status: () => state.document.status, + projection, + presentation: () => undefined, + reasoningMode: () => "compact", + shellToolDefaultOpen: () => false, + editToolDefaultOpen: () => false, + disclosure: { value: () => (state.open ? true : undefined), set: () => {} }, + }) + // Calculate before constructing row DOM. The sample below never feeds a height back into the model. + const sizes = createMemo(() => + projection.rows().map((row) => + renderer.layout(row, { + width: state.width, + desktop: matchMedia("(min-width: 768px)").matches, + typography, + }), + ), + ) + resize = (width) => setState("width", width) + stream = (text, complete) => + batch(() => { + setState("document", "status", { type: complete ? "idle" : "busy" }) + setState("document", "messages", state.document.messages.length - 1, { + id: `layout-assistant-${replies.length - 1}`, + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "text", text }], + time: { created: STORY_TIME, completed: complete ? STORY_TIME + 1 : undefined }, + }) + }) + reasoning = (text) => + batch(() => { + setState("open", true) + setState("document", "status", { type: "busy" }) + // Keep the earlier context collapsed; only the live Thinking row is expanded. + setState("document", "messages", 1, (message) => + message.type === "assistant" ? { ...message, content: [{ type: "text", text: replies[0]! }] } : message, + ) + setState("document", "messages", state.document.messages.length - 1, { + id: `layout-assistant-${replies.length - 1}`, + type: "assistant", + agent: "build", + model: STORY_MODEL, + content: [{ type: "reasoning", text, time: { created: STORY_TIME } }], + time: { created: STORY_TIME, completed: undefined }, + }) + }) + inspect = () => + projection.rows().map((row, index) => { + const value = sizes()[index]! + const element = host.querySelector(`[data-layout-row="${index}"]`)! + return { + key: TimelineRow.key(row), + source: value.source, + fallbackBlocks: value.source === "dom" ? (value.blocks?.length ?? 1) : 0, + expected: value.source === "dom" ? undefined : value.height, + actual: element.getBoundingClientRect().height, + blocks: [ + ...element.querySelectorAll( + 'p,h1,h2,h3,pre,[data-slot="user-message-text"],[data-slot="collapsible-trigger"]', + ), + ].map((block) => { + const style = getComputedStyle(block) + return { + tag: block.tagName, + width: block.getBoundingClientRect().width, + height: block.getBoundingClientRect().height, + font: style.font, + leading: style.lineHeight, + before: style.marginTop, + after: style.marginBottom, + } + }), + } + }) + return ( +
+ + {(row, index) => ( +
+ row} /> +
+ )} +
+
+ ) + } + render( + () => ( + + + + + + ), + host, + ) +} + +export function timelineLayoutReport(width?: number) { + if (width !== undefined) resize(width) + return inspect() +} + +export function streamTimelineLayout(text: string, complete: boolean) { + stream(text, complete) + return inspect() +} + +export function reasonTimelineLayout(text: string) { + reasoning(text) + return inspect() +}