diff --git a/bun.lock b/bun.lock index c12184a35b64..a98f7ba0c74c 100644 --- a/bun.lock +++ b/bun.lock @@ -697,6 +697,7 @@ "name": "@opencode/session-ui", "version": "2.1.2", "dependencies": { + "@chenglou/pretext": "1.0.0", "@kobalte/core": "catalog:", "@opencode/client": "workspace:*", "@opencode/patchmark": "workspace:*", @@ -1583,6 +1584,8 @@ "@capsizecss/unpack": ["@capsizecss/unpack@4.0.1", "", { "dependencies": { "fontkitten": "^1.0.3" } }, "sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ=="], + "@chenglou/pretext": ["@chenglou/pretext@1.0.0", "", {}, "sha512-BxKiDMxWJhyzL8asvcgg3T9YnUU7OUFsKO8oRaR2SYAPX4Sh2wM9gqTBjrBaZ4fnl84cEQ8czC0Q1M83z3chsA=="], + "@clack/core": ["@clack/core@1.0.0-alpha.1", "", { "dependencies": { "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-rFbCU83JnN7l3W1nfgCqqme4ZZvTTgsiKQ6FM0l+r0P+o2eJpExcocBUWUIwnDzL76Aca9VhUdWmB2MbUv+Qyg=="], "@clack/prompts": ["@clack/prompts@1.0.0-alpha.1", "", { "dependencies": { "@clack/core": "1.0.0-alpha.1", "picocolors": "^1.0.0", "sisteransi": "^1.0.5" } }, "sha512-07MNT0OsxjKOcyVfX8KhXBhJiyUbDP1vuIAcHc+nx5v93MJO23pX3X/k3bWz6T3rpM9dgWPq90i4Jq7gZAyMbw=="], 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 000000000000..5e6008e3ed19 --- /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), 82), + 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 2f9b2e91785f..2b513baadcdd 100644 --- a/packages/app/component-tests/timeline-virtualizer.fixture.tsx +++ b/packages/app/component-tests/timeline-virtualizer.fixture.tsx @@ -1,11 +1,19 @@ import { TimelineRow } from "@opencode/session-ui/timeline/projection" -import { onCleanup } from "solid-js" +import { createMemo, onCleanup } from "solid-js" 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" -export function mountTimelineVirtualizer(input: { count: number; rowHeight: number; immediate?: boolean }) { +export function mountTimelineVirtualizer(input: { + count: number + rowHeight: number + immediate?: boolean + modeled?: number + growthRows?: number + viewportHeight?: number + insertedHeight?: number +}) { const host = document.createElement("main") host.dataset.testid = "timeline-virtualizer-fixture" host.dataset.scrolls = "0" @@ -14,15 +22,27 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb document.body.appendChild(host) function Fixture() { - const [state, setState] = createStore({ pinned: true, ready: false }) + const [state, setState] = createStore({ pinned: true, ready: false, growth: 0, inserted: false, removed: false }) - const rows = Array.from( + const initial = Array.from( { length: input.count }, (_, index) => new TimelineRow.UserMessage({ userMessageID: `message-${index}` }), ) - const rowByKey = new Map(rows.map((row) => [TimelineRow.key(row), row])) - const indexes = new Map(rows.map((row, index) => [row.userMessageID, index])) + const inserted = new TimelineRow.UserMessage({ userMessageID: "inserted" }) + const rows = createMemo(() => + (state.inserted ? [...initial.slice(0, -1), inserted, initial.at(-1)!] : initial).filter( + (row) => !state.removed || row.userMessageID !== `message-${input.count - 3}`, + ), + ) + const rowByKey = createMemo(() => new Map(rows().map((row) => [TimelineRow.key(row), row]))) + const indexes = new Map([...initial, inserted].map((row, index) => [row.userMessageID, index])) + const height = (id: string) => + (id === "inserted" ? (input.insertedHeight ?? input.rowHeight) : input.rowHeight) + + (indexes.get(id)! >= input.count - 1 - (input.growthRows ?? 1) && indexes.get(id)! < input.count - 1 + ? state.growth + : 0) + let scrollToEnd = (_behavior?: ScrollBehavior) => {} let viewport!: HTMLDivElement let content!: HTMLDivElement let container!: HTMLDivElement @@ -30,14 +50,18 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb const timeline = createTimelineVirtualizer({ sessionKey: () => "cold-reveal-fixture", projection: { - rows: () => rows, - rowByKey: () => rowByKey, + rows, + rowByKey, activeMessageID: () => undefined, messageByID: () => new Map(), messageRowIndex: () => indexes, messageLastRowIndex: () => indexes, }, showHeader: () => false, + layout: (row) => + row._tag === "UserMessage" && indexes.get(row.userMessageID)! < (input.modeled ?? 0) + ? { source: "fixed", height: height(row.userMessageID) } + : { source: "dom", reason: "deferred fixture content" }, pinned: () => state.pinned, scroll: () => ({ overflow: false, jump: false }), setScrollRef: (element) => { @@ -50,6 +74,7 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb reveal.observe(element, { attributes: true, attributeFilter: ["style"] }) }, onPin: () => setState("pinned", true), + setScrollToEnd: (scroll) => (scrollToEnd = scroll), onUnpin: () => setState("pinned", false), onScheduleScrollState: (element) => { host.dataset.scrolls = String(Number(host.dataset.scrolls) + 1) @@ -94,6 +119,35 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb + + + + + @@ -112,7 +166,7 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb > Reconnect ready rows -
+
false} @@ -120,7 +174,7 @@ export function mountTimelineVirtualizer(input: { count: number; rowHeight: numb
{row().userMessageID}
diff --git a/packages/app/component-tests/timeline-virtualizer.spec.ts b/packages/app/component-tests/timeline-virtualizer.spec.ts index 9497a32a9d11..7dc2255ad5c8 100644 --- a/packages/app/component-tests/timeline-virtualizer.spec.ts +++ b/packages/app/component-tests/timeline-virtualizer.spec.ts @@ -1,12 +1,202 @@ 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") - await expect(component.getByRole("textbox", { name: "Prompt", exact: true })).toBeVisible() + await mount("ui-button--playground") +}) + +story("reveals mixed modeled and measured rows without starving input", async ({ page }) => { + await page.evaluate(async (url) => { + const { mountTimelineVirtualizer } = await import(url) + mountTimelineVirtualizer({ count: 4, rowHeight: 44, modeled: 2, immediate: true }) + }, fixture) + const root = page.getByTestId("timeline-virtualizer-fixture") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + await root.getByRole("button", { name: "Hide viewport", exact: true }).click() + await expect(root.locator("[data-scrollable]")).toBeHidden() +}) + +story("animates only the final screen when resuming from deep history", async ({ page }) => { + await page.emulateMedia({ reducedMotion: "no-preference" }) + await page.evaluate(async (url) => { + const { mountTimelineVirtualizer } = await import(url) + mountTimelineVirtualizer({ count: 1000, rowHeight: 64, modeled: 1000, viewportHeight: 300, immediate: true }) + }, fixture) + const root = page.getByTestId("timeline-virtualizer-fixture") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const returnGap = await root.evaluate((host) => { + const viewport = host.querySelector("[data-scrollable]")! + viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -60000, bubbles: true })) + viewport.scrollTop = 0 + viewport.dispatchEvent(new Event("scroll")) + host.querySelector('[data-testid="resume"]')!.click() + return { gap: viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop, viewport: viewport.clientHeight } + }) + expect(returnGap.gap).toBeGreaterThan(0) + expect(returnGap.gap).toBeLessThanOrEqual(returnGap.viewport + 1) + await expect + .poll(() => + root + .locator("[data-scrollable]") + .evaluate((viewport) => viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop), + ) + .toBeLessThanOrEqual(1) }) +for (const action of ["wheel", "resume", "resume-removal", "follow", "backlog", "unpinned"] as const) { + story(`keeps in-flight row growth continuous during ${action}`, async ({ page }) => { + await page.emulateMedia({ reducedMotion: "no-preference" }) + await page.evaluate( + async ({ url, action }) => { + const { mountTimelineVirtualizer } = await import(url) + mountTimelineVirtualizer({ + count: 10, + rowHeight: 64, + viewportHeight: 300, + growthRows: action === "backlog" ? 3 : 1, + }) + }, + { url: fixture, action }, + ) + const root = page.getByTestId("timeline-virtualizer-fixture") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const growing = root.locator('[data-timeline-key="user-message:message-8"]') + await expect(growing).toHaveCSS("height", "64px") + const change = await root.evaluate(async (host, action) => { + const viewport = host.querySelector("[data-scrollable]")! + const row = host.querySelector('[data-timeline-key="user-message:message-8"]')! + const next = host.querySelector('[data-timeline-key="user-message:message-9"]')! + const content = host.querySelector("[data-timeline-virtual-content]")! + return new Promise<{ + before: { height: number; top: number; extent: number } + after: { height: number; top: number; extent: number } + rise: number + }>((resolve) => { + let change: + | { + before: { height: number; top: number; extent: number } + after: { height: number; top: number; extent: number } + rise: number + } + | undefined + const observer = new ResizeObserver(() => { + if (row.getBoundingClientRect().height <= 64) return + if (change) { + change.rise = Math.max(change.rise, next.getBoundingClientRect().top - change.after.top) + if (row.getBoundingClientRect().height < 184) return + observer.disconnect() + resolve(change) + return + } + if (action === "resume-removal" || action === "follow") { + viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -90, bubbles: true })) + viewport.scrollTop -= 90 + viewport.dispatchEvent(new Event("scroll")) + } + const before = { + height: row.getBoundingClientRect().height, + top: next.getBoundingClientRect().top, + extent: content.getBoundingClientRect().height, + } + if (action !== "backlog" && action !== "resume-removal" && action !== "follow") + viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -90, bubbles: true })) + if (action.startsWith("resume")) host.querySelector('[data-testid="resume"]')!.click() + if (action === "follow") host.querySelector('[data-testid="follow"]')!.click() + if (action === "resume-removal") host.querySelector('[data-testid="remove-row"]')!.click() + change = { + before, + after: { + height: row.getBoundingClientRect().height, + top: next.getBoundingClientRect().top, + extent: content.getBoundingClientRect().height, + }, + rise: 0, + } + if (action.startsWith("resume") && change.after.height < 184) return + observer.disconnect() + resolve(change) + }) + observer.observe(row) + if (action === "unpinned") viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -90, bubbles: true })) + host.querySelector('[data-testid="grow-row"]')!.click() + }) + }, action) + expect(change.before.height).toBeLessThan(184) + expect(Math.abs(change.after.height - change.before.height)).toBeLessThanOrEqual(1 / 64) + expect(Math.abs(change.after.top - change.before.top)).toBeLessThanOrEqual(1 / 64) + expect(Math.abs(change.after.extent - change.before.extent)).toBeLessThanOrEqual(1 / 64) + expect(change.rise).toBeLessThanOrEqual(1 / 64) + await expect(root.getByTestId("timeline-controls")).toHaveAttribute( + "data-pinned", + String(action !== "wheel" && action !== "unpinned"), + ) + await expect(growing).toHaveCSS("height", "184px") + }) +} + +for (const height of [64, 512]) { + story(`starts new unpinned ${height}px rows at zero height before their first measurement`, async ({ page }) => { + await page.emulateMedia({ reducedMotion: "no-preference" }) + await page.evaluate( + async ({ url, height }) => { + const { mountTimelineVirtualizer } = await import(url) + mountTimelineVirtualizer({ count: 10, rowHeight: 64, modeled: 11, viewportHeight: 300, insertedHeight: height }) + }, + { url: fixture, height }, + ) + const root = page.getByTestId("timeline-virtualizer-fixture") + await root.getByRole("button", { name: "Complete Markdown", exact: true }).click() + await expect(root.locator("[data-timeline-virtual-content]")).toHaveCSS("visibility", "visible") + const first = await root.evaluate((host) => { + const viewport = host.querySelector("[data-scrollable]")! + viewport.dispatchEvent(new WheelEvent("wheel", { deltaY: -1, bubbles: true })) + const next = host.querySelector('[data-timeline-key="user-message:message-9"]')! + const top = next.getBoundingClientRect().top + host.querySelector('[data-testid="insert-row"]')!.click() + const row = host.querySelector('[data-timeline-key="user-message:inserted"]')! + return { height: row.getBoundingClientRect().height, travel: next.getBoundingClientRect().top - top } + }) + expect(first.height).toBe(0) + expect(Math.abs(first.travel)).toBeLessThanOrEqual(1 / 64) + await expect(root.locator('[data-timeline-key="user-message:inserted"]')).toHaveCSS("height", `${height}px`) + await expect(root.locator('[data-timeline-key="user-message:inserted"]')).toHaveCSS("opacity", "1") + }) +} + story("spaces the first mobile message without changing desktop spacing", async ({ page }) => { await page.setViewportSize({ width: 390, height: 844 }) await page.evaluate(async (fixture) => { @@ -76,7 +266,7 @@ for (const input of [ await expect(content.locator("[data-timeline-key]")).toHaveCount(1) if (input.name === "offset-only") { - await expect(root).toHaveAttribute("data-last-scroll-top", "484") + await expect(root).toHaveAttribute("data-last-scroll-top", "502") await root.locator("[data-scrollable]").dispatchEvent("wheel", { deltaY: -1 }) await expect(root.getByTestId("timeline-controls")).toHaveAttribute("data-pinned", "false") } diff --git a/packages/app/e2e/regression/session-queue.spec.ts b/packages/app/e2e/regression/session-queue.spec.ts index 39f72c7a72fe..2a9df0dbed36 100644 --- a/packages/app/e2e/regression/session-queue.spec.ts +++ b/packages/app/e2e/regression/session-queue.spec.ts @@ -1008,7 +1008,42 @@ for (const [action, status] of [ }) } -test("waiting steers group under one Pending line, each keeping its own actions beside its bubble @quarantine", async ({ +test("a queued prompt flies from its row onto its bubble as it leaves for the timeline, like a sent message", async ({ + page, +}) => { + const mock = createQueueMock( + ["fly me into the timeline", "remove me quietly"], + [{ id: "msg_queue_delivered", type: "user", text: "First prompt", time: { created: 1 } }], + ) + const view = await openQueue(page, mock) + await expect(view.rows).toHaveCount(2) + // Records each flight copy that paints: the bubble copy carries the prompt's text. + await page.evaluate(() => { + const seen: string[] = [] + Object.assign(window, { flights: seen }) + new MutationObserver((records) => + records.forEach((record) => + record.addedNodes.forEach((node) => { + if (node instanceof HTMLElement && node.matches("[data-flight]")) seen.push(node.textContent ?? "") + }), + ), + ).observe(document.body, { childList: true, subtree: true }) + }) + const flights = () => page.evaluate(() => ("flights" in window ? (window.flights as string[]) : [])) + + await view.rows.nth(0).getByRole("button", { name: "Steer" }).click() + await expect(userRow(page, mock.rows[0].id)).toContainText("fly me into the timeline") + await expect.poll(flights).toEqual(["fly me into the timeline"]) + + // A removed prompt never reaches the timeline, so nothing flies. + await view.rows.nth(0).locator('[data-action="session-queue-remove"]').click() + await expect(view.rows).toHaveCount(0) + await page.waitForTimeout(800) + expect(await flights()).toEqual(["fly me into the timeline"]) + await expect(page.locator("[data-send-flight]")).toHaveCount(0) +}) + +test("waiting steers group under one Steering label, each keeping its own actions beside its bubble @quarantine", async ({ page, }) => { const mock = createQueueMock( @@ -1023,8 +1058,9 @@ test("waiting steers group under one Pending line, each keeping its own actions await expect(last).toContainText("U3: And rebase on beta first.") await expect(first.locator('[data-component="user-message"]')).toHaveAttribute("data-pending", "true") - // The run's last steer carries the one Pending line; the first folds its line away. - await expect(last.locator('[data-slot="user-message-meta"]')).toContainText("Pending") + // The run wears one Steering label above its first steer, and no meta line at rest. + await expect(first.locator('[data-slot="user-message-pending-label"]')).toHaveText("Steering") + await expect(last.locator('[data-slot="user-message-pending-label"]')).toHaveCount(0) await expect(first.locator('[data-slot="user-message-meta"]')).toBeHidden() await first.locator('[data-slot="user-message-text"]').hover() @@ -1162,12 +1198,12 @@ for (const delivery of ["steer", "queue"] as const) { : undefined if (colors) { - // A pending steer is grey, switches to it without a transition, and keeps its Pending row in view without hover. + // A pending steer is grey, switches to it without a transition, and wears a Steering label above it. await expect(bubble).toHaveCSS("background-color", colors.pending.background) await expect(bubble).toHaveCSS("color", colors.pending.text) await expect(bubble).toHaveCSS("transition-duration", "0s") - await expect(pending.locator('[data-slot="user-message-copy-wrapper"]')).toHaveCSS("opacity", "1") - await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText(/^Pending\s*·\s*Queue Model$/) + await expect(pending.locator('[data-slot="user-message-pending-label"]')).toHaveText("Steering") + await expect(pending.locator('[data-slot="user-message-meta"]')).toHaveText(/^Queue Model$/) await bubble.evaluate((element) => (element.dataset.deliveryMarker = "pending")) } diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index a42dcc59358e..14a22f35a90b 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -65,9 +65,11 @@ test("remeasures a recent explored context group before the next paint", async ( // Samples every painted frame after the click until the open group's row holds its measured content, so a // stale row height shows up as overlap before the virtualizer catches up. + type Sample = { frame: number; allocated: number; overlap: number; expanded: string | null; measured: boolean } + const samples = await page.evaluate( ({ contextSelector, following }) => - new Promise<{ frame: number; overlap: number; expanded: string | null; measured: boolean }[]>((resolve) => { + new Promise((resolve) => { const context = document.querySelector(contextSelector) const text = document.querySelector(following) const scroller = context?.closest(".scroll-view__viewport") @@ -78,18 +80,17 @@ test("remeasures a recent explored context group before the next paint", async ( if (!scroller || !trigger || !contextRow || !virtualRow || !textRow) throw new Error("missing regression nodes") scroller.scrollTop = scroller.scrollHeight - const samples: { frame: number; overlap: number; expanded: string | null; measured: boolean }[] = [] + const samples: Sample[] = [] const capture = (frame: number) => { const content = context!.querySelector('[data-slot="collapsible-content"]') const allocated = virtualRow.getBoundingClientRect().height const inner = virtualRow.firstElementChild?.getBoundingClientRect().height ?? Infinity + const shown = Math.min(contextRow.getBoundingClientRect().bottom, virtualRow.getBoundingClientRect().bottom) samples.push({ frame, - overlap: Math.max( - 0, - Math.round((contextRow.getBoundingClientRect().bottom - textRow.getBoundingClientRect().top) * 10) / 10, - ), + allocated, + overlap: Math.max(0, Math.round((shown - textRow.getBoundingClientRect().top) * 10) / 10), expanded: trigger.getAttribute("aria-expanded"), measured: !!content && @@ -118,6 +119,8 @@ test("remeasures a recent explored context group before the next paint", async ( expect(samples[0]?.overlap).toBe(0) expect(samples.filter((sample) => sample.frame >= 1 && sample.overlap > 0.5)).toEqual([]) + // The row opens steadily onto its measured height, never shrinking back on the way. + expect(samples.filter((sample, index) => sample.allocated < (samples[index - 1]?.allocated ?? 0) - 0.5)).toEqual([]) expect(samples.at(-1)).toMatchObject({ expanded: "true", measured: true }) }) @@ -250,6 +253,9 @@ test("keeps a file diff anchored while it expands and collapses", async ({ page await expect.poll(bottom).toBeLessThanOrEqual(1) } + // Following the end, the row eases onto its new height; let it land before scrolling away. + await expect.poll(measured).toBeLessThanOrEqual(1) + // Scrolled away from the tail, the header keeps its viewport position. await expect .poll(() => scroller.evaluate((element) => element.scrollHeight - element.clientHeight)) @@ -551,7 +557,10 @@ for (const failed of [false, true]) { expect(frames.some((frame) => frame.working && frame.prompt === undefined)).toBe(false) const positions = frames.flatMap((frame) => (frame.prompt === undefined ? [] : [frame.prompt])) expect(positions.length).toBeGreaterThan(0) - expect(new Set(positions).size).toBe(1) + // The prompt grows in at the followed end and rises into place: it never moves back down or jumps, including + // when Working shows. + const steps = positions.slice(1).map((position, index) => position - positions[index]!) + expect(steps.filter((step) => step > 0.5 || step < -40)).toEqual([]) } finally { release.resolve() await observation.dispose() diff --git a/packages/app/e2e/regression/timeline-stream.spec.ts b/packages/app/e2e/regression/timeline-stream.spec.ts index 03832f259b16..9197211ba98b 100644 --- a/packages/app/e2e/regression/timeline-stream.spec.ts +++ b/packages/app/e2e/regression/timeline-stream.spec.ts @@ -670,7 +670,7 @@ test.describe("Working", () => { await expect(working).toBeVisible() await timeline.send(partUpdated(reasoningPart("prt_working_reasoning", ""))) await expect(page.locator('[data-timeline-row="Thinking"]')).toBeVisible() - await expect(working).toHaveCount(0) + await expect(working).toBeVisible() await timeline.send(partUpdated(reasoningPart("prt_working_reasoning", "The inspection is complete."))) await expect(page.locator('[data-timeline-row="Thinking"]')).toHaveCount(0) @@ -727,7 +727,7 @@ test.describe("Working", () => { await timeline.send(partUpdated(toolPart(id, name, "streaming", input))) const tool = page.locator(`[data-timeline-part-id="${id}"]`) await expect(tool).toBeVisible() - await expect(working).toHaveCount(0) + await expect(working).toBeVisible() const metadata = name === "patch" @@ -738,7 +738,7 @@ test.describe("Working", () => { await expect(tool).toContainText( { shell: "printf ready", patch: "working.ts", subagent: "Inspect working indicator" }[name], ) - await expect(working).toHaveCount(0) + await expect(working).toBeVisible() await timeline.send(partUpdated(toolPart(id, name, "completed", input, { metadata }))) await expect(tool).toBeVisible() @@ -811,7 +811,7 @@ test.describe("Working", () => { if (!grouped) { await expect(page.locator('[data-timeline-part-id="prt_background_active"]')).toBeVisible() - await expect(working).toHaveCount(0) + await expect(working).toBeVisible() return } @@ -873,7 +873,7 @@ test.describe("Working", () => { await expect(page.locator(`[data-timeline-part-id="${assistantID}:text:0"]`)).toContainText( "The response is streaming.", ) - await expect(working).toHaveCount(0) + await expect(working).toBeVisible() }) }) diff --git a/packages/app/src/composer/editor/editor.tsx b/packages/app/src/composer/editor/editor.tsx index 8080d20a524e..75bea8e014d9 100644 --- a/packages/app/src/composer/editor/editor.tsx +++ b/packages/app/src/composer/editor/editor.tsx @@ -1,4 +1,5 @@ import { + createComputed, createEffect, createMemo, createResource, @@ -6,6 +7,7 @@ import { createUniqueId, For, onCleanup, + on, onMount, Show, Suspense, @@ -395,10 +397,12 @@ export function ComposerEditor(props: ComposerEditorProps) { classList={{ "font-mono! tracking-[-0.04px]": state.mode === "shell" }} style={{ "unicode-bidi": state.mode === "normal" ? "plaintext" : undefined, "text-align": "start" }} > - {view.placeholder?.() ?? - (state.mode === "shell" - ? i18n.t("ui.promptInput.placeholder.shell") - : i18n.t("ui.promptInput.placeholder.normal", { slash: "/", at: "@" }))} +
@@ -1406,9 +1410,23 @@ function ComposerEditorAlternateDelivery(props: { controller: ComposerEditorMode return queue.alternate() }) + // Sending marks the session busy a moment before the composer clears; a hint that would last only that moment + // stays hidden instead of flashing on every send. + const [settled, setSettled] = createSignal(action()) + createEffect( + on( + action, + (value) => { + if (!value) return setSettled(undefined) + const frame = requestAnimationFrame(() => setSettled(value)) + onCleanup(() => cancelAnimationFrame(frame)) + }, + { defer: true }, + ), + ) // Appears and leaves on the same frame as the placeholder, so typing never shows a fade. return ( - + {(delivery) => ( + ) +} + +function wait(ms: number, signal: AbortSignal) { + return new Promise((resolve) => { + const timer = setTimeout(done, ms) + signal.addEventListener("abort", done, { once: true }) + + function done() { + clearTimeout(timer) + signal.removeEventListener("abort", done) + resolve() + } + }) +} + +async function until(check: () => boolean, timeout: number, signal: AbortSignal) { + const deadline = Date.now() + timeout + + while (!signal.aborted && !check() && Date.now() < deadline) await wait(100, signal) +} diff --git a/packages/gui-extensions/src/debug/i18n/en.ts b/packages/gui-extensions/src/debug/i18n/en.ts index 1122a78321e4..2d6e1cad7ff4 100644 --- a/packages/gui-extensions/src/debug/i18n/en.ts +++ b/packages/gui-extensions/src/debug/i18n/en.ts @@ -35,6 +35,28 @@ export default { "motion.tip": "Tune live. Changes persist on this device.", "components.label": "COMPONENTS", "components.tip": "Open the components lab: every story, with live controls and its states", + "demo.label": "DEMO", + "demo.title": "Demo session", + "demo.tip": "Drive the open session through scripted states on OpenCode Drive's simulated model.", + "demo.unavailable": + "Open a session on OpenCode Drive's simulated model to use these controls. Start one with script/drive/demo-session.ts.", + "demo.hint": "Send a message or steer for a long reply. Type 'short', 'code' or 'random' for those replies.", + "demo.action.long": "Long reply", + "demo.speed": "Speed", + "demo.action.paragraph": "Paragraph", + "demo.action.code": "Code block", + "demo.action.shell": "Shell", + "demo.action.patch": "Patch", + "demo.action.turn": "Long turn", + "demo.action.finish": "Finish turn", + "demo.action.message": "Message", + "demo.action.steer": "Steer", + "demo.action.burst": "Burst", + "demo.action.queue": "Queue", + "demo.action.subagent": "Subagent", + "demo.action.background": "Bg shell", + "demo.autoplay.start": "Auto-play", + "demo.autoplay.stop": "Stop auto-play", "speed.label": "SPEED", "speed.tip": "Global animation speed. Click to step through 0.5× and 0.25× back to 1×.", "slow.label": "SLOW", diff --git a/packages/gui-extensions/src/debug/motion.tsx b/packages/gui-extensions/src/debug/motion.tsx index 126942d2dcb4..25364d7bd2b5 100644 --- a/packages/gui-extensions/src/debug/motion.tsx +++ b/packages/gui-extensions/src/debug/motion.tsx @@ -5,7 +5,7 @@ import { Portal } from "solid-js/web" const key = "opencode.motion.panel" // The Motion workspace, docked above the debug bar's right end until its header is dragged. knobs loads once it opens. -export default function Motion(props: { title: string; onClose: () => void }) { +export default function Motion(props: { title: string; section?: string; onClose: () => void }) { let container!: HTMLDivElement let unmount: (() => void) | undefined let disposed = false @@ -76,7 +76,7 @@ export default function Motion(props: { title: string; onClose: () => void }) { }) void import("@opencode/ui/motion-tuning-panel").then(({ mountMotionPanel }) => { - if (!disposed) unmount = mountMotionPanel(container, { title: props.title, onClose: props.onClose }) + if (!disposed) unmount = mountMotionPanel(container, { title: props.title, section: props.section, onClose: props.onClose }) }) return ( diff --git a/packages/gui-extensions/src/debug/renderer.tsx b/packages/gui-extensions/src/debug/renderer.tsx index 962af26f28ad..81e6c073dd21 100644 --- a/packages/gui-extensions/src/debug/renderer.tsx +++ b/packages/gui-extensions/src/debug/renderer.tsx @@ -1,6 +1,7 @@ -import { lazy, Show, Suspense } from "solid-js" -import { Command, Slot, type Setup } from "../sdk" +import { createSignal, lazy, Show, Suspense } from "solid-js" +import { Command, createKeyed, Slot, type Setup } from "../sdk" import type Debug from "./index" +import { simulated } from "./simulated" const setup: Setup = (ctx) => { const DebugBar = lazy(() => import("./bar")) @@ -11,6 +12,28 @@ const setup: Setup = (ctx) => { const bar = ctx.stores.bar const visible = () => bar.value.visible const motion = () => bar.value.motion + const Demo = motionTools ? lazy(() => import("./demo")) : undefined + const [demo, setDemo] = createSignal(false) + const [section, setSection] = createSignal() + + // Routing a session on Drive's simulated model opens the bar with its Demo panel and the Knobs on Experiments, where + // the Timeline card lives, so the controls are in view. + if (motionTools) + createKeyed( + () => { + const session = ctx.sessions.current() + + return session?.location && simulated({ ...session, location: session.location }) ? session.key : undefined + }, + () => { + void bar.update((draft) => { + draft.visible = true + draft.motion = true + }) + setSection("Experiments") + setDemo(true) + }, + ) const toggle = () => { bar.update((draft) => { @@ -24,6 +47,10 @@ const setup: Setup = (ctx) => { }) } + const toggleDemo = () => { + setDemo((value) => !value) + } + ctx.add( Command, (): Command => ({ @@ -45,6 +72,7 @@ const setup: Setup = (ctx) => { diagnostics={import.meta.env.DEV} onClose={toggle} motion={Motion ? { open: motion(), toggle: toggleMotion } : undefined} + demo={Demo ? { open: demo(), toggle: toggleDemo } : undefined} inline /> @@ -53,7 +81,14 @@ const setup: Setup = (ctx) => { // The Knobs workspace opens only from the debug bar's KNOBS cell, and shows while the bar does. - + + + + )} + {Demo && ( + + + )} diff --git a/packages/gui-extensions/src/debug/simulated.ts b/packages/gui-extensions/src/debug/simulated.ts new file mode 100644 index 000000000000..5b0d08887a07 --- /dev/null +++ b/packages/gui-extensions/src/debug/simulated.ts @@ -0,0 +1,13 @@ +import type { LocationRef } from "@opencode/client/promise" +import type { ServerRef } from "../sdk" + +// Drive's simulated provider (script/drive/demo-session.ts). Demo controls act only on a session that runs on it, so a +// demo prompt never reaches a real model or a real conversation. +const provider = "simulation" + +export function simulated(session: { id: string; location: LocationRef; server: ServerRef }) { + const model = session.server.data.session.get(session.id)?.model + const providers = session.server.data.location.provider.list(session.location) + + return (model === undefined || model.providerID === provider) && !!providers?.some((item) => item.id === provider) +} diff --git a/packages/session-ui/component-tests/markdown.fixture.tsx b/packages/session-ui/component-tests/markdown.fixture.tsx index 0b6a2c13e8ea..6bf9e94f4f79 100644 --- a/packages/session-ui/component-tests/markdown.fixture.tsx +++ b/packages/session-ui/component-tests/markdown.fixture.tsx @@ -6,6 +6,8 @@ import { preloadMarkdown } from "../src/components/markdown-cache" import { MarkdownProvider, type MarkdownLocalFileExists } from "../src/context/markdown" import { OpenCode } from "@opencode/client/promise" import { readLocalImage } from "../../app/src/runtime/server/image" +import { createTimelineMarkdownLayout } from "../src/timeline/markdown-layout" +import { createTimelineTextLayout } from "../src/timeline/text-layout" export { getCachedMarkdown, @@ -28,6 +30,7 @@ export async function mountMarkdown(options: { streaming?: boolean cached?: boolean images?: boolean + prepared?: boolean synchronousFiles?: boolean localFileExists?: MarkdownLocalFileExists }) { @@ -44,6 +47,8 @@ export async function mountMarkdown(options: { const [text, setText] = createSignal(options.text) const [streaming, setStreaming] = createSignal(options.streaming ?? false) const [visible, setVisible] = createSignal(true) + const [prepared, setPrepared] = createSignal(options.prepared ?? false) + const layout = createTimelineMarkdownLayout(createTimelineTextLayout()) return ( @@ -55,6 +60,7 @@ export async function mountMarkdown(options: { onChange={(event) => setStreaming(event.currentTarget.checked)} /> + options.images ? readLocalImage(api, "C:/project", path, signal) : Promise.resolve(undefined) @@ -69,6 +75,7 @@ export async function mountMarkdown(options: { text={text()} streaming={streaming()} cacheKey={options.cached ? "markdown-test" : undefined} + prepared={prepared() ? layout.prepare("markdown-test", text(), streaming()) : undefined} deferUntilReady /> diff --git a/packages/session-ui/component-tests/markdown.spec.ts b/packages/session-ui/component-tests/markdown.spec.ts index c1c1ab406094..ba860521e4cf 100644 --- a/packages/session-ui/component-tests/markdown.spec.ts +++ b/packages/session-ui/component-tests/markdown.spec.ts @@ -9,8 +9,7 @@ const png = Buffer.from( const fixture = sourceURL(new URL("./markdown.fixture.tsx", import.meta.url)) story.beforeEach(async ({ mount }) => { - const root = await mount("components-markdown--complete-response") - await expect(root.locator('[data-component="markdown"]')).toHaveAttribute("data-markdown-ready", "") + await mount("ui-button--playground") }) story("renders small completed Markdown immediately without skipping sanitization", async ({ page }) => { @@ -664,19 +663,41 @@ story("renders the trailing chunk while the stream is paused", async ({ page }) }) story("keeps live elements and selection when a stream completes and later changes", async ({ page }) => { - await page.evaluate(async (fixture) => { + const initial = await page.evaluate(async (fixture) => { const { mountMarkdown } = await import(fixture) - await mountMarkdown({ text: "Hello **world**", streaming: true, synchronousFiles: true }) + await mountMarkdown({ + text: "Hello **world**", + streaming: true, + cached: true, + prepared: true, + synchronousFiles: true, + }) + const markdown = document.querySelector('[data-testid="markdown-fixture"] [data-component="markdown"]')! + return { + words: markdown.querySelectorAll("[data-markdown-word]").length, + entering: markdown.querySelectorAll("[data-markdown-enter]").length, + } }, fixture) + expect(initial).toEqual({ words: 2, entering: 0 }) const harness = page.getByTestId("markdown-fixture") const markdown = harness.locator('[data-component="markdown"]') const paragraph = markdown.locator("p") await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2) await paragraph.evaluate((element) => element.setAttribute("data-retained", "true")) + await harness.getByRole("button", { name: "Toggle preparation", exact: true }).click() + await expect(markdown).toHaveAttribute("data-markdown-ready", "") + await expect(paragraph).toHaveAttribute("data-retained", "true") await harness.getByLabel("Markdown text").fill("Hello **world** again") await expect(markdown.locator("[data-markdown-word]")).toHaveCount(3) + await markdown + .locator("[data-markdown-word]") + .last() + .evaluate((element) => element.setAttribute("data-retained", "true")) await expect(paragraph).toHaveAttribute("data-retained", "true") await expect(markdown.locator("[data-markdown-enter]")).not.toHaveCount(0) + await harness.getByRole("button", { name: "Toggle preparation", exact: true }).click() + await expect(paragraph).toHaveAttribute("data-retained", "true") + await expect(markdown.locator('[data-markdown-word][data-retained="true"]')).toHaveText("again") await paragraph.evaluate((element) => { const range = document.createRange() range.selectNodeContents(element.querySelector("strong")!) @@ -691,6 +712,7 @@ story("keeps live elements and selection when a stream completes and later chang await expect(markdown).toHaveAttribute("data-markdown-ready", "") await expect(paragraph).toHaveAttribute("data-retained", "true") expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("world") + await expect(markdown.locator('[data-markdown-word][data-retained="true"]')).toHaveText("again") await harness.getByLabel("Markdown text").fill("Changed **content** in `new/file.ts` and `new/file.ts`") await expect(paragraph).toHaveText("Changed content in new/file.ts and new/file.ts") await expect(markdown.locator('code[data-inline-code-kind="path"]')).toHaveText(["new/file.ts", "new/file.ts"]) diff --git a/packages/session-ui/component-tests/session-message-projection.spec.ts b/packages/session-ui/component-tests/session-message-projection.spec.ts index 3f071ea5d252..8179e8b833d9 100644 --- a/packages/session-ui/component-tests/session-message-projection.spec.ts +++ b/packages/session-ui/component-tests/session-message-projection.spec.ts @@ -105,9 +105,10 @@ story("drops a pending footer at once on delivery with and without hover", async await expect(footer).toHaveCSS("opacity", "0") }) -story("marks pending metadata without badging delivered, starting, or queued prompts", async ({ mount, page }) => { +story("labels waiting prompts without badging delivered, starting, or queued prompts", async ({ mount, page }) => { const timeline = await mount("current-prompt-message--pending") - const indicator = timeline.locator('[data-slot="user-message-meta"] [data-slot="user-message-pending"]') + const label = timeline.locator('[data-slot="user-message-pending-label"]') + const indicator = label.locator('[data-slot="user-message-pending"]') const text = timeline.locator('[data-slot="user-message-text"]') for (const status of ["steering", "stranded", "starting", "queued", "delivered"]) { @@ -152,9 +153,9 @@ story("marks pending metadata without badging delivered, starting, or queued pro await expect(indicator.locator("use")).toHaveAttribute("href", "#opencode-v2-icon-outline-steer") const icon = await indicator.locator("svg").boundingBox() - const label = await timeline.locator('[data-slot="user-message-meta"]').boundingBox() - if (!icon || !label) throw new Error("Pending metadata geometry is unavailable") - expect(Math.abs(icon.y + icon.height / 2 - label.y - label.height / 2)).toBeLessThan(0.5) + const bounds = await label.boundingBox() + if (!icon || !bounds) throw new Error("Pending metadata geometry is unavailable") + expect(Math.abs(icon.y + icon.height / 2 - bounds.y - bounds.height / 2)).toBeLessThan(0.5) await expect(voice).toHaveCSS("width", "20px") await expect(voice).toHaveCSS("height", "20px") @@ -172,20 +173,22 @@ story("marks pending metadata without badging delivered, starting, or queued pro }) await expect(indicator).toHaveCSS("color", faint) - await expect(timeline.locator('[data-slot="user-message-meta"]')).toHaveText(/^Pending/) + await expect(label).toHaveText("Steering") await timeline.getByLabel("Grouped prompts", { exact: true }).check() await expect(timeline.locator('[data-run-folded] [data-slot="user-message-copy-wrapper"]')).toBeHidden() - await expect( - timeline.locator('[data-component="user-message"]:not([data-run-folded]) [data-slot="user-message-pending"]'), - ).toBeVisible() + await expect(label).toHaveCount(1) + await expect(timeline.locator('[data-run-folded] [data-slot="user-message-pending-label"]')).toBeVisible() await expect(timeline.getByRole("img", { name: "Pending", exact: true })).toHaveCount(0) await timeline.getByLabel("Grouped prompts", { exact: true }).uncheck() await page.setViewportSize({ width: 390, height: 844 }) await expect(indicator).toBeVisible() await expect(timeline.locator('[data-slot="user-message-meta-item"]')).toHaveCount(0) + await expect(label).toHaveText("Steering") await timeline.getByLabel("Prompt text", { exact: true }).uncheck() await expect(timeline.getByText("notes.json", { exact: true })).toBeVisible() await expect(indicator).toBeVisible() + // Like a delivered prompt's, a waiting prompt's actions show on hover. + await timeline.locator('[data-component="user-message"]').last().hover() await timeline.getByRole("button", { name: "Move to queue", exact: true }).click() await expect(indicator).toBeHidden() }) diff --git a/packages/session-ui/component-tests/session-timeline.spec.ts b/packages/session-ui/component-tests/session-timeline.spec.ts index 962b7a1ae249..6ab6a0e21615 100644 --- a/packages/session-ui/component-tests/session-timeline.spec.ts +++ b/packages/session-ui/component-tests/session-timeline.spec.ts @@ -1,4 +1,75 @@ -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)) + +// Windows draws the mixed Japanese and emoji prompt with fallback fonts that canvas measures slightly narrower, so it +// can wrap one line later there; its row corrects on mount. Every other row must match to the pixel. +const fallbackWrap = new Set(process.platform === "win32" ? ["user-message:layout-user-3"] : []) + +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( + fallbackWrap.has(row.key) ? 22 : 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( + fallbackWrap.has(row.key) ? 22 : 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( + fallbackWrap.has(row.key) ? 22 : 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 000000000000..a1fe096c059f --- /dev/null +++ b/packages/session-ui/component-tests/timeline-layout.fixture.tsx @@ -0,0 +1,226 @@ +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 { SessionMessageAssistantTool } from "@opencode/client/promise" +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 }, + } satisfies SessionMessageAssistantTool, + ] + : []), + { 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): SessionDocument["messages"][number] => + 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() +} diff --git a/packages/session-ui/package.json b/packages/session-ui/package.json index 7015afbf1aef..7fb702e8ef8b 100644 --- a/packages/session-ui/package.json +++ b/packages/session-ui/package.json @@ -11,6 +11,7 @@ "./timeline/projection": "./src/timeline/projection.ts", "./timeline/detail": "./src/timeline/detail.ts", "./timeline/row": "./src/timeline/session-timeline-row.tsx", + "./timeline/text-layout": "./src/timeline/text-layout.ts", "./timeline": "./src/timeline/session-timeline.tsx", "./basic-tool": "./src/components/basic-tool.tsx", "./dock-prompt": "./src/components/dock-prompt.tsx", @@ -61,6 +62,7 @@ "vite-plugin-solid": "catalog:" }, "dependencies": { + "@chenglou/pretext": "1.0.0", "@kobalte/core": "catalog:", "@opencode/client": "workspace:*", "@opencode/patchmark": "workspace:*", diff --git a/packages/session-ui/src/components/basic-tool.css b/packages/session-ui/src/components/basic-tool.css index 478c980e2ec4..e8f6ee3b7e15 100644 --- a/packages/session-ui/src/components/basic-tool.css +++ b/packages/session-ui/src/components/basic-tool.css @@ -481,3 +481,16 @@ } } } + +/* Closing, a tool's details fade out before they unmount, so they never vanish in one frame. */ +@media (prefers-reduced-motion: no-preference) { + [data-component="collapsible"].tool-collapsible > [data-slot="collapsible-content"][data-closed] { + animation: basic-tool-content-out 110ms cubic-bezier(0.4, 0, 1, 1) forwards; + } +} + +@keyframes basic-tool-content-out { + to { + opacity: 0; + } +} diff --git a/packages/session-ui/src/components/markdown-code-state.test.ts b/packages/session-ui/src/components/markdown-code-state.test.ts index 1be76d6f16c4..ed2cd03c47a9 100644 --- a/packages/session-ui/src/components/markdown-code-state.test.ts +++ b/packages/session-ui/src/components/markdown-code-state.test.ts @@ -1,10 +1,21 @@ import { expect, test } from "bun:test" -import { shouldResetCodeTokens } from "./markdown-code-state" +import { + diffCodeTokens, + projectHighlightedCode, + shouldResetCodeTokens, + type HighlightedCodeState, + type RenderedCodeState, +} from "./markdown-code-state" -const previous = { +const previous: RenderedCodeState = { language: "ts", generation: 1, stableCount: 3, + stable: [ + ["const", "color:#f00"], + [" ", ""], + ["x", "color:#0f0"], + ], unstable: [], raw: "```ts\nconst x = 1\n```", } @@ -30,3 +41,110 @@ test("retains tokens for an append-only streaming update", () => { }), ).toBe(false) }) + +test("projects highlighted prefix with an unstyled trailing suffix while worker catches up", () => { + const highlighted: HighlightedCodeState = { + requestedLanguage: "ts", + language: "ts", + source: "const x = 1\n", + complete: false, + generation: 1, + stable: [ + ["const", "color:#f00"], + [" ", ""], + ["x", "color:#0f0"], + ], + unstable: [[" = 1\n", "color:#00f"]], + } + + const interim = projectHighlightedCode(highlighted, "const x = 1\nconst y = 2\n", "ts") + expect(interim).toEqual({ + language: "ts", + generation: 1, + stable: highlighted.stable, + unstable: [ + [" = 1\n", "color:#00f"], + ["const y = 2\n", ""], + ], + }) + + const renderedBefore: RenderedCodeState = { + language: "ts", + generation: 1, + stableCount: highlighted.stable.length, + stable: highlighted.stable, + unstable: highlighted.unstable, + raw: "```ts\nconst x = 1\n", + } + + const diffInterim = diffCodeTokens(renderedBefore, { + ...interim, + raw: "```ts\nconst x = 1\nconst y = 2\n", + }) + expect(diffInterim).toEqual({ + keep: 4, + append: [["const y = 2\n", ""]], + }) + + const renderedInterim: RenderedCodeState = { + language: interim.language, + generation: interim.generation, + stableCount: interim.stable.length, + stable: interim.stable, + unstable: interim.unstable, + raw: "```ts\nconst x = 1\nconst y = 2\n", + } + + const diffCaughtUp = diffCodeTokens(renderedInterim, { + language: "ts", + generation: 1, + stable: [ + ...highlighted.stable, + [" = 1\n", "color:#00f"], + ["const", "color:#f00"], + ], + unstable: [[" y = 2\n", "color:#0f0"]], + raw: "```ts\nconst x = 1\nconst y = 2\n", + }) + expect(diffCaughtUp).toEqual({ + keep: 4, + append: [ + ["const", "color:#f00"], + [" y = 2\n", "color:#0f0"], + ], + }) +}) + +test("preserves matching token spans across completion generation bumps", () => { + const streamed: RenderedCodeState = { + language: "ts", + generation: 1, + stableCount: 2, + stable: [ + ["const", "color:#f00"], + [" ", ""], + ], + unstable: [ + ["x", "color:#0f0"], + [" = 1\n", "color:#00f"], + ], + raw: "```ts\nconst x = 1\n", + } + + const completed = diffCodeTokens(streamed, { + language: "ts", + generation: 2, + stable: [ + ["const", "color:#f00"], + [" ", ""], + ["x", "color:#0f0"], + [" = 1", "color:#00f"], + ], + unstable: [], + raw: "```ts\nconst x = 1\n```", + }) + expect(completed).toEqual({ + keep: 3, + append: [[" = 1", "color:#00f"]], + }) +}) diff --git a/packages/session-ui/src/components/markdown-code-state.ts b/packages/session-ui/src/components/markdown-code-state.ts index 502f3ecd3c27..80c6ad3b14f2 100644 --- a/packages/session-ui/src/components/markdown-code-state.ts +++ b/packages/session-ui/src/components/markdown-code-state.ts @@ -1,9 +1,20 @@ import type { MarkdownToken } from "./markdown-worker-protocol" +export type HighlightedCodeState = { + requestedLanguage: string + language: string + source: string + complete: boolean + generation: number + stable: MarkdownToken[] + unstable: MarkdownToken[] +} + export type RenderedCodeState = { language: string generation: number stableCount: number + stable?: MarkdownToken[] unstable: MarkdownToken[] raw: string } @@ -20,3 +31,71 @@ export function shouldResetCodeTokens( !next.raw.startsWith(previous.raw) ) } + +export function projectHighlightedCode( + previous: HighlightedCodeState | undefined, + source: string, + language: string | undefined, +) { + const requestedLanguage = language ?? "text" + if (previous && previous.requestedLanguage === requestedLanguage && source.startsWith(previous.source)) { + const suffix = source.slice(previous.source.length) + return { + language: previous.language, + generation: previous.generation, + stable: previous.stable, + unstable: suffix ? [...previous.unstable, [suffix, ""] satisfies MarkdownToken] : previous.unstable, + } + } + return { + language: requestedLanguage, + generation: -1, + stable: [] as MarkdownToken[], + unstable: source ? ([[source, ""]] satisfies MarkdownToken[]) : ([] as MarkdownToken[]), + } +} + +export function diffCodeTokens( + previous: RenderedCodeState | undefined, + next: { + language: string + generation: number + stable: MarkdownToken[] + unstable: MarkdownToken[] + raw: string + }, +) { + const reset = shouldResetCodeTokens(previous, { + language: next.language, + generation: next.generation, + stableCount: next.stable.length, + raw: next.raw, + }) + if (!reset && previous) { + const tail = [...next.stable.slice(previous.stableCount), ...next.unstable] + const prefix = previous.unstable.findIndex((token, index) => !sameToken(token, tail[index])) + const matched = prefix < 0 ? Math.min(previous.unstable.length, tail.length) : prefix + return { + keep: previous.stableCount + matched, + append: tail.slice(matched), + } + } + const all = [...next.stable, ...next.unstable] + if (!previous || previous.language !== next.language || !previous.stable) { + return { + keep: 0, + append: all, + } + } + const prior = [...previous.stable, ...previous.unstable] + const prefix = prior.findIndex((token, index) => !sameToken(token, all[index])) + const keep = prefix < 0 ? Math.min(prior.length, all.length) : prefix + return { + keep, + append: all.slice(keep), + } +} + +function sameToken(left: MarkdownToken, right: MarkdownToken | undefined) { + return !!right && left[0] === right[0] && left[1] === right[1] +} diff --git a/packages/session-ui/src/components/markdown-prepared.ts b/packages/session-ui/src/components/markdown-prepared.ts new file mode 100644 index 000000000000..d1d38f6bad51 --- /dev/null +++ b/packages/session-ui/src/components/markdown-prepared.ts @@ -0,0 +1,11 @@ +import type { MarkdownCacheEntry } from "./markdown-cache" + +/** A text revision whose blocks are shared by measure-ahead and painting. */ +export type PreparedMarkdown = { + text: string + blocks: PreparedMarkdownBlock[] +} + +export type PreparedMarkdownBlock = + | (MarkdownCacheEntry & { mode: "full" | "live" }) + | { mode: "code"; raw: string; source: string; language: string; complete: boolean } diff --git a/packages/session-ui/src/components/markdown-solid.tsx b/packages/session-ui/src/components/markdown-solid.tsx index a11b2e297737..854c5c810656 100644 --- a/packages/session-ui/src/components/markdown-solid.tsx +++ b/packages/session-ui/src/components/markdown-solid.tsx @@ -14,12 +14,38 @@ type MarkdownNode = | { key: string; type: "text"; text: string } | { key: string; type: "word"; text: string; animate?: true } -export function createMarkdownRenderer(root: HTMLDivElement, html: string, words: boolean) { - const [nodes, setNodes] = createStore(parseMarkdownNodes(html, words)) - let ready = false +export function createMarkdownRenderer(root: HTMLDivElement, html: string, words: boolean, animate = false) { + const visible = () => root.isConnected && document.visibilityState !== "hidden" + const [nodes, setNodes] = createStore( + parseMarkdownNodes(html, words, animate && document.visibilityState !== "hidden"), + ) + let ready = animate && document.visibilityState !== "hidden" + let frontier = 0 + + const settle = () => { + frontier = 0 + root.querySelectorAll("[data-markdown-enter]").forEach((element) => { + element.removeAttribute("data-markdown-enter") + element.style.removeProperty("--markdown-word-delay") + }) + } + document.addEventListener("visibilitychange", settle) + + const delay = () => { + const now = typeof performance === "object" ? performance.now() : 0 + const scale = + typeof document !== "undefined" + ? Number(document.documentElement?.style.getPropertyValue("--motion-time-scale")) || 1 + : 1 + const base = Math.max(now, frontier) + const lead = (base - now) / scale + const step = Math.max(5.5, Math.min(20, 20 - lead * 0.045)) * scale + frontier = base + step + return Math.max(0, Math.round(base - now)) + } const dispose = render( - () => {(node) => ready} />}, + () => {(node) => ready} delay={delay} />}, root, ) @@ -27,13 +53,17 @@ export function createMarkdownRenderer(root: HTMLDivElement, html: string, words return { update(next: string, nextWords: boolean, animate = true) { - setNodes(reconcile(parseMarkdownNodes(next, nextWords, animate), { key: "key" })) + if (!visible()) settle() + setNodes(reconcile(parseMarkdownNodes(next, nextWords, animate && visible()), { key: "key" })) + }, + dispose() { + document.removeEventListener("visibilitychange", settle) + dispose() }, - dispose, } } -function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean }) { +function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean; delay: () => number }) { const node = props.node if (node.type === "text") return node.text @@ -41,11 +71,22 @@ function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean }) if (node.type === "word") { let ref: HTMLSpanElement | undefined onMount(() => { - if (props.animate() && node.animate) ref?.setAttribute("data-markdown-enter", "") + if (props.animate() && node.animate && ref) { + const wait = props.delay() + if (wait > 0) ref.style.setProperty("--markdown-word-delay", `${wait}ms`) + ref.setAttribute("data-markdown-enter", "") + } }) return ( - + { + event.currentTarget.removeAttribute("data-markdown-enter") + event.currentTarget.style.removeProperty("--markdown-word-delay") + }} + > {node.text} ) @@ -58,7 +99,9 @@ function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean }) return ( - {(node) => } + + {(node) => } + ) } diff --git a/packages/session-ui/src/components/markdown-stream.ts b/packages/session-ui/src/components/markdown-stream.ts index 84d0c1d12872..447cce4ee552 100644 --- a/packages/session-ui/src/components/markdown-stream.ts +++ b/packages/session-ui/src/components/markdown-stream.ts @@ -72,6 +72,15 @@ export function stream(text: string, live: boolean): Block[] { return project(undefined, text, live).blocks } +/** Measure-ahead needs block boundaries even for the first completed message. */ +export function createBlockProjection() { + const instance = createStream() + return (text: string, live: boolean): Projection => ({ + text, + blocks: instance.update(text, { streaming: live }).blocks.map(toBlock), + }) +} + export function project(previous: Projection | undefined, text: string, live: boolean): Projection { if (!previous && !live) return completedProjection(text) diff --git a/packages/session-ui/src/components/markdown-worker-protocol.ts b/packages/session-ui/src/components/markdown-worker-protocol.ts index 03031009f091..be83465d4af8 100644 --- a/packages/session-ui/src/components/markdown-worker-protocol.ts +++ b/packages/session-ui/src/components/markdown-worker-protocol.ts @@ -36,7 +36,8 @@ export function shouldReleaseMarkdownWorkerState(complete: boolean, latestID: nu } export function markdownBlockKey(owner: string, cacheKey: string | undefined, index: number, mode: string) { - return `${owner}:${cacheKey ? `${cacheKey}:${index}:${mode}` : `block:${index}`}` + // Settling prose changes its parser mode, not its DOM identity. Code still owns a separate renderer lifetime. + return `${owner}:${cacheKey ? `${cacheKey}:${index}:${mode === "live" ? "full" : mode}` : `block:${index}`}` } export function applyMarkdownWorkerResponse( diff --git a/packages/session-ui/src/components/markdown.css b/packages/session-ui/src/components/markdown.css index c2bb351fd6fb..7ebb0d368c33 100644 --- a/packages/session-ui/src/components/markdown.css +++ b/packages/session-ui/src/components/markdown.css @@ -52,8 +52,9 @@ display: inline; } - :is([data-markdown-word], code)[data-markdown-enter] { - animation: markdown-word-enter 180ms ease-out both; + :is([data-markdown-word], code, [data-component="markdown-code"])[data-markdown-enter] { + animation: markdown-word-enter calc(180ms * var(--motion-time-scale, 1)) ease-out var(--markdown-word-delay, 0ms) + both; } /* Spacing for flow */ @@ -70,10 +71,8 @@ margin-bottom: 0; } - /* Pretty wrapping would move settled words as each token arrives, so the growing block stays greedy until it completes. */ - &[data-streaming] > [data-markdown-block]:last-child { - text-wrap-style: auto; - } + /* Pretty wrapping would rearrange words when a block finishes or a new paragraph starts, and diverge from pretext's greedy line measurement. */ + text-wrap-style: auto; /* Headings: Sized by level, distinguished by color and spacing */ h1 { @@ -469,8 +468,21 @@ } } +/* The streaming-edge experiment (Knobs, Experiments): No mask shows new words at once; Word fade fades them longer. */ +:root[data-streaming-edge="whole"] { + [data-component="markdown"] :is([data-markdown-word], code, [data-component="markdown-code"])[data-markdown-enter] { + animation: none; + } +} + +:root[data-streaming-edge="fade"] { + [data-component="markdown"] :is([data-markdown-word], code, [data-component="markdown-code"])[data-markdown-enter] { + animation-duration: calc(360ms * var(--motion-time-scale, 1)); + } +} + :root[data-motion="reduce"] { - [data-component="markdown"] :is([data-markdown-word], code)[data-markdown-enter] { + [data-component="markdown"] :is([data-markdown-word], code, [data-component="markdown-code"])[data-markdown-enter] { animation: none; } } diff --git a/packages/session-ui/src/components/markdown.tsx b/packages/session-ui/src/components/markdown.tsx index a348492697ba..e0b3f74a44f0 100644 --- a/packages/session-ui/src/components/markdown.tsx +++ b/packages/session-ui/src/components/markdown.tsx @@ -3,6 +3,7 @@ import { checksum } from "@opencode/util/encode" import { type ComponentProps, createEffect, + createMemo, createResource, createSignal, createUniqueId, @@ -26,7 +27,12 @@ import { projectMarkdown, } from "./markdown-worker" import { markdownBlockKey, type MarkdownToken } from "./markdown-worker-protocol" -import { shouldResetCodeTokens, type RenderedCodeState } from "./markdown-code-state" +import { + diffCodeTokens, + projectHighlightedCode, + type HighlightedCodeState, + type RenderedCodeState, +} from "./markdown-code-state" import { getCachedMarkdown, getReadyMarkdown, @@ -35,6 +41,7 @@ import { type MarkdownCacheEntry, } from "./markdown-cache" import { inlineCodeKind } from "./markdown-inline-code-kind" +import type { PreparedMarkdown, PreparedMarkdownBlock } from "./markdown-prepared" import { renderMermaidSvg } from "./markdown-mermaid" import { createMarkdownRenderer } from "./markdown-solid" import { @@ -91,30 +98,6 @@ function fallback(markdown: string) { return escape(markdown).replace(/\r\n?/g, "\n").replace(/\n/g, "
") } -async function code(text: string, language: string | undefined, key: string, complete = false) { - try { - const result = await highlightStreamingCode(key, text, language ?? "text", complete) - - return { - language: result.language, - generation: result.generation, - stable: result.stable, - unstable: result.unstable, - } - } catch (error) { - if ( - !(error instanceof MarkdownWorkerDisposedError) && - !(error instanceof MarkdownWorkerSupersededError) && - !(error instanceof MarkdownWorkerUnavailableError) - ) - console.error("Markdown highlighting worker failed", error) - - const fallbackToken: MarkdownToken = [text, ""] - - return { language: language ?? "text", generation: 0, stable: [], unstable: [fallbackToken] } - } -} - type CopyLabels = { copy: string copied: string @@ -575,7 +558,7 @@ function initialResult( if (block.mode !== "full") touchCachedMarkdown(cacheKey, cached) - return [{ key: `${owner}:${cacheKey}`, mode: block.mode, ...cached }] + return [{ key: markdownBlockKey(owner, key, index, block.mode), mode: block.mode, ...cached }] }) if (blocks.length === projection.blocks.length) return { text, blocks, ready: true } @@ -608,11 +591,20 @@ export function Markdown( cacheKey?: string streaming?: boolean deferUntilReady?: boolean + prepared?: PreparedMarkdown class?: string classList?: Record }, ) { - const [local, others] = splitProps(props, ["text", "cacheKey", "streaming", "deferUntilReady", "class", "classList"]) + const [local, others] = splitProps(props, [ + "text", + "cacheKey", + "streaming", + "deferUntilReady", + "prepared", + "class", + "classList", + ]) const i18n = useI18n() const markdown = useMarkdown() const previewImages = createImagePreview() @@ -620,17 +612,111 @@ export function Markdown( const owner = createUniqueId() const lifetime = new AbortController() const activeCodeKeys = new Set() + const highlightedCode = new Map() + const [highlightVersion, setHighlightVersion] = createSignal(0) const completedCode = new Map>() const settledMarkdown = new Map>() let renderedBlocks: RenderedBlock[] = [] let streamed = false + const painted = new WeakMap() + const paintedCode = new WeakMap< + PreparedMarkdownBlock, + { state: HighlightedCodeState | undefined; rendered: Extract } + >() + const highlighting = new WeakMap>() + + async function highlightCode(text: string, language: string | undefined, key: string, complete = false) { + const requestedLanguage = language ?? "text" + const existing = highlightedCode.get(key) + if ( + existing && + existing.requestedLanguage === requestedLanguage && + existing.source === text && + (!complete || existing.complete) + ) { + return existing + } + try { + const result = await highlightStreamingCode(key, text, requestedLanguage, complete) + const current = highlightedCode.get(key) + if ( + current && + current.requestedLanguage === requestedLanguage && + current.generation === result.generation && + (current.source.length > text.length || (current.complete && !complete)) && + current.source.startsWith(text) + ) { + return current + } + const next: HighlightedCodeState = { + requestedLanguage, + language: result.language, + source: text, + complete, + generation: result.generation, + stable: result.stable, + unstable: result.unstable, + } + highlightedCode.set(key, next) + if (!lifetime.signal.aborted) setHighlightVersion((version) => version + 1) + return next + } catch (error) { + if ( + !(error instanceof MarkdownWorkerDisposedError) && + !(error instanceof MarkdownWorkerSupersededError) && + !(error instanceof MarkdownWorkerUnavailableError) + ) + console.error("Markdown highlighting worker failed", error) + + return highlightedCode.get(key) + } + } + + const preparedResult = createMemo((): RenderResult | undefined => { + const prepared = local.prepared + if (!prepared || prepared.text !== local.text) return + highlightVersion() + return { + text: prepared.text, + ready: true, + blocks: prepared.blocks.map((block, index): RenderedBlock => { + const key = markdownBlockKey(owner, local.cacheKey, index, block.mode) + if (block.mode !== "code") { + const previous = painted.get(block) + if (previous) return previous + const result = { ...block, key } + painted.set(block, result) + return result + } + if (!highlighting.has(block)) { + highlighting.set(block, highlightCode(block.source, block.language, key, block.complete)) + } + const state = highlightedCode.get(key) + const cached = paintedCode.get(block) + if (cached && cached.state === state) return cached.rendered + const projected = projectHighlightedCode(state, block.source, block.language) + const rendered: Extract = { + key, + mode: "code", + raw: block.raw, + hash: String(block.raw.length), + complete: block.complete, + ...projected, + } + paintedCode.set(block, { state, rendered }) + return rendered + }), + } + }) + const [projection] = createResource( () => { if (isServer) return const live = local.streaming ?? false if (live) streamed = true + if (local.prepared) return if (!live && !streamed) return @@ -661,6 +747,7 @@ export function Markdown( const [html] = createResource( () => { + if (local.prepared) return if (isServer) return { text: local.text, @@ -708,7 +795,8 @@ export function Markdown( const cached = completedCode.get(blockKey) if (block.complete && cached?.raw === block.raw) return cached - const result = await code(block.src, block.language, blockKey, block.complete) + const state = await highlightCode(block.src, block.language, blockKey, block.complete) + const projected = projectHighlightedCode(state, block.src, block.language) const rendered = { key: blockKey, @@ -716,10 +804,10 @@ export function Markdown( raw: block.raw, hash: String(block.raw.length), complete: !!block.complete, - ...result, + ...projected, } - if (block.complete) completedCode.set(blockKey, rendered) + if (block.complete && state?.source === block.src && state.complete) completedCode.set(blockKey, rendered) return rendered } @@ -792,9 +880,17 @@ export function Markdown( createEffect(() => { const container = root() - const result = html.latest ?? html() - const projected = currentProjection() - const content = local.text ? pendingBlocks(result, projected, local.cacheKey, owner, local.deferUntilReady) : [] + const prepared = preparedResult() + const result = prepared ?? html.latest ?? html() + // Changing measurement paths can restart async preparation. Keep the revision already painted + // until the replacement renderer catches up, rather than painting its older cached response. + if (!prepared && local.text && renderedBlocks.length && (!result?.ready || result.text !== local.text)) return + const content = + prepared?.blocks ?? + (local.text + ? (highlightVersion(), + pendingBlocks(result, currentProjection(), local.cacheKey, owner, local.deferUntilReady, highlightedCode)) + : []) if (!container) return @@ -827,7 +923,10 @@ export function Markdown( const nextCodeKeys = new Set(content.filter((block) => block.mode === "code").map((block) => block.key)) activeCodeKeys.forEach((key) => { - if (!nextCodeKeys.has(key)) disposeCode(key) + if (!nextCodeKeys.has(key)) { + highlightedCode.delete(key) + disposeCode(key) + } }) activeCodeKeys.clear() nextCodeKeys.forEach((key) => activeCodeKeys.add(key)) @@ -840,7 +939,16 @@ export function Markdown( const check = renderedBlocks[index] === block && current instanceof HTMLDivElement ? inlineCodeChecks.get(current)?.pending - : updateBlock(container, index, block, labels, sessionLinks, lifetime.signal, localFileExists) + : updateBlock( + container, + index, + block, + renderedBlocks.length > 0 && container.isConnected, + labels, + sessionLinks, + lifetime.signal, + localFileExists, + ) return check ? [check] : [] }) @@ -913,6 +1021,7 @@ export function Markdown( if (streamed) disposeMarkdownProjection(owner) activeCodeKeys.forEach(disposeCode) + highlightedCode.clear() completedCode.clear() settledMarkdown.clear() renderedBlocks = [] @@ -939,6 +1048,7 @@ function pendingBlocks( cacheKey: string | undefined, owner: string, deferUntilReady: boolean | undefined, + highlightedCode: Map, ) { if (!result) return [] @@ -950,24 +1060,23 @@ function pendingBlocks( return projection.blocks.map((block, index) => { const current = initial ? undefined : result.blocks[index] - if (current && canReusePendingBlock(current, block)) return current - const key = markdownBlockKey(owner, cacheKey, index, block.mode) - - if (block.mode !== "code") + if (block.mode !== "code") { + if (current && canReusePendingBlock(current, block)) return current + const key = markdownBlockKey(owner, cacheKey, index, block.mode) return { key, mode: block.mode, raw: block.raw, hash: String(block.raw.length), html: fallback(block.src) } + } - const fallbackToken: MarkdownToken = [block.src, ""] + const key = markdownBlockKey(owner, cacheKey, index, block.mode) + if (current?.mode === "code" && current.raw === block.raw && current.complete === !!block.complete) return current + const projected = projectHighlightedCode(highlightedCode.get(key), block.src, block.language) return { key, mode: block.mode, raw: block.raw, hash: String(block.raw.length), - language: block.language ?? "text", complete: !!block.complete, - stable: [], - generation: 0, - unstable: [fallbackToken], + ...projected, } }) } @@ -980,6 +1089,7 @@ function updateBlock( container: HTMLDivElement, index: number, block: RenderedBlock, + animate: boolean, labels: CopyLabels, sessionLinks: ((id: string) => string | undefined) | undefined, signal: AbortSignal, @@ -1029,7 +1139,12 @@ function updateBlock( markExternalLinkFavicons(source) if (rendered) { - rendered.renderer.update(source.innerHTML, block.mode === "live", rendered.raw !== block.raw) + // Completion may decorate the same text; keep its words and their in-flight fades until the text actually changes. + rendered.renderer.update( + source.innerHTML, + block.mode === "live" || block.raw.startsWith(rendered.raw.trimEnd()), + animate && rendered.raw !== block.raw, + ) rendered.raw = block.raw return pending @@ -1038,7 +1153,7 @@ function updateBlock( if (block.mode === "live") { next.replaceChildren() renderedMarkdown.set(next, { - renderer: createMarkdownRenderer(next, source.innerHTML, true), + renderer: createMarkdownRenderer(next, source.innerHTML, true, animate), raw: block.raw, }) } @@ -1102,29 +1217,17 @@ function updateCodeBlock( if (wrapper instanceof HTMLElement) applyCodeMetadata(wrapper, block.language) code.className = `language-${block.language}` const previous = renderedCodeTokens.get(next) + const validPrevious = + previous && code.children.length === previous.stableCount + previous.unstable.length ? previous : undefined + const diff = diffCodeTokens(validPrevious, block) - const reset = shouldResetCodeTokens(previous, { - language: block.language, - generation: block.generation, - stableCount: block.stable.length, - raw: block.raw, - }) - - const stableCount = reset ? 0 : previous!.stableCount - const tail = [...block.stable.slice(stableCount), ...block.unstable] - const prior = reset ? [] : previous!.unstable - const prefix = prior.findIndex((token, index) => !sameToken(token, tail[index])) - const keep = stableCount + (prefix < 0 ? Math.min(prior.length, tail.length) : prefix) - - while (code.children.length > keep) code.lastElementChild?.remove() - tail - .slice(keep - stableCount) - .map(createTokenSpan) - .forEach((span) => code.appendChild(span)) + while (code.children.length > diff.keep) code.lastElementChild?.remove() + diff.append.map(createTokenSpan).forEach((span) => code.appendChild(span)) renderedCodeTokens.set(next, { language: block.language, generation: block.generation, stableCount: block.stable.length, + stable: block.stable, unstable: block.unstable, raw: block.raw, }) @@ -1136,6 +1239,7 @@ function updateCodeBlock( const wrapper = document.createElement("div") wrapper.setAttribute("data-component", "markdown-code") + if (!block.complete) wrapper.setAttribute("data-markdown-enter", "") applyCodeMetadata(wrapper, block.language) const pre = document.createElement("pre") pre.className = "highlights" @@ -1151,6 +1255,7 @@ function updateCodeBlock( language: block.language, generation: block.generation, stableCount: block.stable.length, + stable: block.stable, unstable: block.unstable, raw: block.raw, }) @@ -1166,10 +1271,6 @@ function updateCodeBlock( container.appendChild(next) } -function sameToken(left: MarkdownToken, right: MarkdownToken | undefined) { - return !!right && left[0] === right[0] && left[1] === right[1] -} - function createTokenSpan(token: MarkdownToken) { const span = document.createElement("span") span.setAttribute("style", token[1]) diff --git a/packages/session-ui/src/components/message-part.css b/packages/session-ui/src/components/message-part.css index 8a742d3b813d..6aa1dcab3473 100644 --- a/packages/session-ui/src/components/message-part.css +++ b/packages/session-ui/src/components/message-part.css @@ -379,12 +379,19 @@ &:focus-within [data-slot="user-message-meta-tail"] { opacity: 1; pointer-events: auto; + transition: opacity 0.15s ease; } - /* A pending steer keeps its Pending label and actions in view. */ - &[data-pending] [data-slot="user-message-copy-wrapper"] { - opacity: 1; - pointer-events: auto; + [data-slot="user-message-pending-label"] { + display: flex; + align-items: center; + justify-content: flex-end; + height: calc(20px * var(--user-run-label, 0)); + margin-bottom: calc(4px * var(--user-run-label, 0)); + overflow: hidden; + opacity: var(--user-run-label, 0); + user-select: none; + white-space: nowrap; } [data-slot="user-message-copy-wrapper"] > * { @@ -513,6 +520,18 @@ } } +/* Rows the timeline moves under a resting pointer stay quiet until the pointer moves. */ +[data-hover-stale] + [data-component="user-message"]:not([data-pending], :focus-within) + [data-slot="user-message-copy-wrapper"]:not(:has([data-expanded])), +[data-hover-stale] [data-component="text-part"]:not(:focus-within) [data-slot="text-part-copy-wrapper"] { + @media (hover: hover) { + opacity: 0; + pointer-events: none; + transition: none; + } +} + [data-timeline-row="AssistantPart"][data-timeline-spacing="content"] [data-component="text-part"] { margin-top: 0; } diff --git a/packages/session-ui/src/message/current-message.tsx b/packages/session-ui/src/message/current-message.tsx index 8592235c4fba..bf6ba6f46cd3 100644 --- a/packages/session-ui/src/message/current-message.tsx +++ b/packages/session-ui/src/message/current-message.tsx @@ -12,6 +12,7 @@ import { import { currentToolError, currentToolInput, currentToolMetadata, currentToolOutput } from "./current-tool-state" import { currentStreamingInput } from "./streaming-input" import type { UserRun } from "../timeline/user-runs" +import type { PreparedMarkdown } from "../components/markdown-prepared" // Registers the genui_render renderer with the tool registry. import "../genui/tool" @@ -60,6 +61,7 @@ export function SessionAssistantContent(props: { toolOpen?: boolean onToolOpenChange?: (open: boolean) => void onContentRendered?: () => void + preparedMarkdown?: PreparedMarkdown }) { return ( @@ -71,6 +73,7 @@ export function SessionAssistantContent(props: { message={props.message} showCopy={props.showAssistantCopyPartID === props.contentID} turnDurationMs={props.turnDurationMs} + preparedMarkdown={props.preparedMarkdown} /> )} @@ -84,6 +87,7 @@ export function SessionAssistantContent(props: { open={props.toolOpen} onOpenChange={props.onToolOpenChange} onContentRendered={props.onContentRendered} + preparedMarkdown={props.preparedMarkdown} /> )} diff --git a/packages/session-ui/src/message/message-content.tsx b/packages/session-ui/src/message/message-content.tsx index e46805434787..f06a38a13b2c 100644 --- a/packages/session-ui/src/message/message-content.tsx +++ b/packages/session-ui/src/message/message-content.tsx @@ -17,6 +17,7 @@ import { useData } from "../context" import { useDialog } from "@opencode/ui/context/dialog" import { useI18n } from "@opencode/ui/context/i18n" import { Markdown } from "../components/markdown" +import type { PreparedMarkdown } from "../components/markdown-prepared" import { linkSegments } from "../components/link-segments" import { sessionReferenceText, setupSessionLinks } from "../components/markdown-session-links" import { useMarkdown } from "../context/markdown" @@ -206,7 +207,7 @@ function createPacedValue(getValue: () => string, live?: () => boolean) { timeout = undefined const text = getValue() - if (!live?.()) { + if (!live?.() || document.visibilityState === "hidden") { sync(text) return @@ -233,7 +234,7 @@ function createPacedValue(getValue: () => string, live?: () => boolean) { createEffect(() => { const text = getValue() - if (!live?.()) { + if (!live?.() || document.visibilityState === "hidden") { clear() sync(text) @@ -258,22 +259,34 @@ function createPacedValue(getValue: () => string, live?: () => boolean) { timeout = setTimeout(run, TEXT_RENDER_PACE_MS) }) + const settle = () => { + clear() + sync(getValue()) + } + document.addEventListener("visibilitychange", settle) onCleanup(() => { + document.removeEventListener("visibilitychange", settle) clear() }) return value } -function PacedMarkdown(props: { text: string; cacheKey: string; streaming: boolean }) { +function PacedMarkdown(props: { text: string; cacheKey: string; streaming: boolean; prepared?: PreparedMarkdown }) { const value = createPacedValue( - () => props.text, + () => (props.prepared ? "" : props.text), () => props.streaming, ) return ( - - + + ) } @@ -349,6 +362,12 @@ export function CurrentUserMessageDisplay(props: { const stamp = createMemo(() => timefmt().format(props.message.time.created)) + const labelled = createMemo(() => waiting() && !props.run?.above) + const [label, setLabel] = createSignal("") + createEffect(() => { + if (labelled()) setLabel(i18n.t(status() === "stranded" ? "ui.message.pending" : "ui.message.steering")) + }) + const info = createMemo(() => [ waiting() ? i18n.t("ui.message.pending") : "", @@ -366,6 +385,7 @@ export function CurrentUserMessageDisplay(props: { ) const runPose = () => ({ + label: labelled() ? 1 : 0, meta: folded() ? 0 : 1, top: meetsAbove() ? 1 : 0, bottom: folded() ? 1 : 0, @@ -379,6 +399,8 @@ export function CurrentUserMessageDisplay(props: { () => root, runPose, (el, value) => { + el.style.setProperty("--user-run-label", `${value.label}`) + if (value.label === 0 && !labelled()) setLabel("") el.style.setProperty("--user-run-meta", `${value.meta}`) el.style.setProperty("--user-run-top", `${value.top}`) el.style.setProperty("--user-run-bottom", `${value.bottom}`) @@ -588,6 +610,7 @@ export function CurrentUserMessageDisplay(props: { data-run-folded={folded() ? "" : undefined} data-run-meta-hidden={restingPose.meta === 0 ? "" : undefined} style={{ + "--user-run-label": `${restingPose.label}`, "--user-run-meta": `${restingPose.meta}`, "--user-run-top": `${restingPose.top}`, "--user-run-bottom": `${restingPose.bottom}`, @@ -618,6 +641,14 @@ export function CurrentUserMessageDisplay(props: { {renderAttachments()} + +
+ + {label()} +
+
- - - {i18n.t("ui.message.pending")} - 0}> - - - 0}> @@ -897,6 +917,7 @@ export function AssistantTextContent(props: { message: SessionMessageAssistant showCopy: boolean turnDurationMs?: number | null + preparedMarkdown?: PreparedMarkdown }) { const data = useData() const i18n = useI18n() @@ -959,7 +980,12 @@ export function AssistantTextContent(props: {
- +
void onContentRendered?: () => void + preparedMarkdown?: PreparedMarkdown }) { const i18n = useI18n() const [state, setState] = createStore<{ open?: boolean }>({}) @@ -1075,7 +1102,12 @@ export function AssistantReasoningContent(props: {
} > - +
) diff --git a/packages/session-ui/src/timeline/markdown-layout.ts b/packages/session-ui/src/timeline/markdown-layout.ts new file mode 100644 index 000000000000..cc10bfe561d7 --- /dev/null +++ b/packages/session-ui/src/timeline/markdown-layout.ts @@ -0,0 +1,349 @@ +import type { RichInlineItem } from "@chenglou/pretext/rich-inline" +import { createMarkdownBase } from "@opencode/ui/context/marked-base" +import { checksum } from "@opencode/util/encode" +import { isServer } from "solid-js/web" +import { sanitizeMarkdown } from "../components/markdown-cache" +import { inlineCodeKind } from "../components/markdown-inline-code-kind" +import { createBlockProjection, type Block, type Projection } from "../components/markdown-stream" +import type { PreparedMarkdown, PreparedMarkdownBlock } from "../components/markdown-prepared" +import type { createTimelineTextLayout, TimelineTypography } from "./text-layout" + +/** Parse once per changed block. The exact same sanitized revision goes to the model and the renderer. */ +export function createTimelineMarkdownLayout(text: ReturnType) { + const parser = createMarkdownBase() + const compiled = new WeakMap() + const lists = new WeakMap() + const elementMeasurements = new WeakMap< + HTMLElement, + { + width: number + typography: TimelineTypography + reasoning: boolean + box: Box + } + >() + const measurements = new WeakMap< + PreparedMarkdown, + { + width: number + typography: TimelineTypography + height: number + streamHeight: number + trailingMargin: number + reasoning: boolean + } + >() + const documents = new Map< + string, + { + projection: Projection + streaming: boolean + prepared?: PreparedMarkdown + unsupported: number[] + elements: HTMLElement[][] + project: ReturnType + } + >() + + function prepare(key: string, raw: string, streaming: boolean) { + if (isServer) return + const cached = documents.get(key) + if (cached?.projection.text === raw && cached.streaming === streaming) return cached.prepared + const project = cached?.project ?? createBlockProjection() + const projection = project(raw, streaming) + const blocks = projection.blocks.map((block) => { + if (compiled.has(block)) return compiled.get(block) + const value = compile(block) + compiled.set(block, value ?? null) + return value + }) + const prepared = blocks.every((block) => block) + ? { text: raw, blocks: blocks.map((value) => value!.block) } + : undefined + documents.set(key, { + project, + projection, + streaming, + prepared, + unsupported: blocks.flatMap((value, index) => (value ? [] : [index])), + elements: blocks.map((value) => value?.elements ?? []), + }) + return prepared + } + + function compile(block: Block) { + if (block.mode === "code") { + if (block.language === "mermaid") return + return { + block: { + mode: "code", + raw: block.raw, + source: block.src, + language: block.language ?? "text", + complete: !!block.complete, + } satisfies PreparedMarkdownBlock, + elements: [], + } + } + // Keep math and raw HTML on their renderer-specific sizing path. + if (block.src.includes("<") || block.src.includes("\\(") || block.src.indexOf("$") !== block.src.lastIndexOf("$")) + return + const html = sanitizeMarkdown(parser.parse(block.src, { async: false })) + const template = document.createElement("template") + template.innerHTML = html + if ([...template.content.childNodes].some((node) => node instanceof Text && node.data.trim())) return + const elements = [...template.content.children].filter((node): node is HTMLElement => node instanceof HTMLElement) + if (elements.some((element) => !/^(P|H[1-6]|UL|OL|BLOCKQUOTE|HR)$/.test(element.tagName))) return + if ( + elements.some((element) => + [...element.querySelectorAll("*")].some( + (node) => + !/^(P|UL|OL|LI|BLOCKQUOTE|STRONG|B|EM|I|DEL|S|CODE)$/.test(node.tagName) || + (node.tagName === "CODE" && /^https?:\/\//.test(node.textContent ?? "")), + ), + ) + ) + return + return { + block: { + mode: block.mode, + raw: block.raw, + src: block.src, + html, + hash: checksum(html) ?? html, + } satisfies PreparedMarkdownBlock, + elements, + } + } + + return { + prepare, + layout( + key: string, + raw: string, + streaming: boolean, + width: number, + typography: TimelineTypography, + reasoning = false, + ) { + const prepared = prepare(key, raw, streaming) + if (!prepared) + return { + source: "dom" as const, + reason: "unsupported markdown block", + blocks: documents.get(key)?.unsupported ?? [], + } + const previous = measurements.get(prepared) + if (previous?.width === width && previous.typography === typography && previous.reasoning === reasoning) + return { + source: "pretext" as const, + height: previous.height, + streamHeight: previous.streamHeight, + trailingMargin: previous.trailingMargin, + } + const entry = documents.get(key)! + let lastSublineKey: string | undefined + const blocks = prepared.blocks.flatMap((block, blockIndex) => { + if (block.mode === "code") + return [ + { + height: + ((block.source ? block.source.split("\n").length - Number(block.source.endsWith("\n")) : 0) * + Math.round((reasoning ? 20 : typography.codeLineHeight) * 64)) / + 64 + + typography.codeInset, + before: 12, + after: 24, + edgeBefore: 12, + edgeAfter: 24, + }, + ] + return entry.elements[blockIndex]!.map((element, index) => { + const itemKey = `${key}:${blockIndex}:${index}` + lastSublineKey = itemKey + return measure(element, itemKey, width, typography, reasoning) + }) + }) + const baseHeight = flowHeight(blocks) + (blocks[0]?.edgeBefore ?? 0) + (blocks.at(-1)?.edgeAfter ?? 0) + const subline = streaming && lastSublineKey ? text.richSubline(lastSublineKey) : undefined + const lag = + subline && subline.lineCount >= 1 + ? (1 - Math.min(1, Math.max(0.14, subline.fill / 0.86))) * + subline.lineHeight * + (subline.lineCount === 1 ? 0.52 : 0.82) + : 0 + const measured = { + width, + typography, + reasoning, + height: baseHeight, + streamHeight: Math.max(0, Math.round((baseHeight - lag) * 64) / 64), + trailingMargin: blocks.at(-1)?.edgeAfter ?? 0, + } + measurements.set(prepared, measured) + return { + source: "pretext" as const, + height: measured.height, + streamHeight: measured.streamHeight, + trailingMargin: measured.trailingMargin, + } + }, + } + + function measure( + element: HTMLElement, + key: string, + width: number, + typography: TimelineTypography, + reasoning: boolean, + ): Box { + const cached = elementMeasurements.get(element) + if (cached?.width === width && cached.typography === typography && cached.reasoning === reasoning) return cached.box + const box = measureUncached(element, key, width, typography, reasoning) + elementMeasurements.set(element, { width, typography, reasoning, box }) + return box + } + + function measureUncached( + element: HTMLElement, + key: string, + width: number, + typography: TimelineTypography, + reasoning: boolean, + ): Box { + const tag = element.tagName + if (tag === "HR") return { height: 0, before: 32, after: 32 } + if (tag === "UL" || tag === "OL" || tag === "BLOCKQUOTE") { + const nested = element.parentElement?.tagName === "LI" + const inset = + tag === "BLOCKQUOTE" + ? typography.rem * 0.5 + (typography.codeInset - 24) / 2 + : tag === "OL" + ? typography.rem * (nested ? 1.75 : 2.25) + : nested + ? typography.rem + : 32 + const children = [...element.children].map((child, index) => + measure(child as HTMLElement, `${key}:${index}`, width - inset, typography, reasoning), + ) + return { + height: flowHeight(children), + edgeBefore: children[0]?.before ?? 0, + edgeAfter: children.at(-1)?.after ?? 0, + before: Math.max( + tag === "BLOCKQUOTE" ? typography.rem : nested ? typography.rem * 0.25 : 8, + children[0]?.before ?? 0, + ), + after: Math.max( + tag === "BLOCKQUOTE" ? typography.rem : nested ? typography.rem * 0.25 : 12, + children.at(-1)?.after ?? 0, + ), + } + } + if (tag === "LI") { + const children = lists.get(element) ?? listChildren(element) + lists.set(element, children) + const parts = children.map((child, index) => { + const box = measure(child, `${key}:${index}`, width, typography, reasoning) + if (child.tagName === "SPAN") return { ...box, before: 0, after: 0 } + return child.tagName === "P" ? { ...box, before: typography.rem * 0.5 } : box + }) + return { height: flowHeight(parts), before: parts[0]?.before ?? 0, after: Math.max(8, parts.at(-1)?.after ?? 0) } + } + const heading = /^H[1-6]$/.test(tag) + const size = reasoning ? 13 : tag === "H1" ? 17 : tag === "H2" ? 15 : heading ? 13 : typography.size + const style = { + ...typography, + size, + weight: !heading || reasoning ? typography.weight : tag === "H1" || tag === "H2" ? 600 : typography.medium, + } + return { + height: text.rich( + key, + inline(element, style), + width, + Math.round((heading ? size * 1.5 : reasoning ? 20 : size * 1.6) * 64) / 64, + typography.revision, + ), + before: + reasoning && tag === "P" && element.querySelector("strong") + ? element.previousElementSibling + ? 24 + : 0 + : !heading + ? 0 + : tag === "H1" + ? 28 + : tag === "H2" + ? 24 + : 20, + after: + reasoning && tag === "P" && element.querySelector("strong") + ? 0 + : !heading || tag === "H1" + ? 12 + : tag === "H2" + ? 10 + : 8, + } + } +} + +function listChildren(element: HTMLElement) { + const children: HTMLElement[] = [] + let line = document.createElement("span") + const flush = () => { + if (!line.textContent?.trim()) return + children.push(line) + line = document.createElement("span") + } + ;[...element.childNodes].forEach((child) => { + if (!(child instanceof HTMLElement) || !/^(P|UL|OL|BLOCKQUOTE)$/.test(child.tagName)) { + line.append(child.cloneNode(true)) + return + } + if (child.tagName === "P" && child === element.firstElementChild) { + line.append(...[...child.childNodes].map((node) => node.cloneNode(true))) + return + } + flush() + children.push(child) + }) + flush() + return children +} + +type Box = { height: number; before: number; after: number; edgeBefore?: number; edgeAfter?: number } + +function flowHeight(blocks: Box[]) { + return blocks.reduce( + (height, block, index) => height + block.height + (index ? Math.max(block.before, blocks[index - 1]!.after) : 0), + 0, + ) +} + +function inline(element: HTMLElement, style: TimelineTypography, italic = false): RichInlineItem[] { + return [...element.childNodes].flatMap((node): RichInlineItem[] => { + if (node instanceof Text) + return [ + { + text: node.data, + font: `${italic ? "italic " : ""}${style.weight} ${style.size}px ${style.family}`, + letterSpacing: style.letterSpacing, + }, + ] + if (!(node instanceof HTMLElement)) return [] + if (node.tagName === "STRONG" || node.tagName === "B") return inline(node, { ...style, weight: style.bold }, italic) + if (node.tagName === "EM" || node.tagName === "I") return inline(node, style, true) + if (node.tagName === "CODE") + return [ + { + text: node.textContent ?? "", + font: `${italic ? "italic " : ""}${style.medium} ${style.size}px ${style.codeFamily}`, + letterSpacing: style.letterSpacing, + extraWidth: inlineCodeKind(node.textContent ?? "") === "path" ? 4 : 8, + }, + ] + return inline(node, style, italic) + }) +} diff --git a/packages/session-ui/src/timeline/projection.test.ts b/packages/session-ui/src/timeline/projection.test.ts index d33515443e85..5dafb5c7e8a9 100644 --- a/packages/session-ui/src/timeline/projection.test.ts +++ b/packages/session-ui/src/timeline/projection.test.ts @@ -269,6 +269,50 @@ describe("createTimelineProjection", () => { expect(result.rowByKey.get("user-message:user-1")).toBe(result.rows[2]) }) + test("gives every steer of a delivered batch the context of the reply that answers it", () => { + const local = { id: "local", providerID: "local-provider" } + const answer = { id: "answer", providerID: "answer-provider" } + const steer = (id: string, created: number) => ({ + id, + type: "user" as const, + text: id, + time: { created }, + metadata: { model: { providerID: local.providerID, id: local.id } }, + }) + const messages = [ + steer("user-1", 1), + { + id: "assistant-1", + type: "assistant", + agent: "build", + model: answer, + content: [{ type: "text", text: "first" }], + time: { created: 2, completed: 3 }, + }, + steer("steer-1", 4), + steer("steer-2", 5), + steer("steer-3", 6), + { + id: "assistant-2", + type: "assistant", + agent: "build", + model: answer, + content: [{ type: "text", text: "second" }], + time: { created: 7 }, + }, + ] satisfies SessionMessageInfo[] + + const result = createTimelineProjection({ + sessionMessages: messages, + status: { type: "busy" }, + reasoningMode: "full", + }) + + expect(["user-1", "steer-1", "steer-2", "steer-3"].map((id) => result.userContextByID.get(id))).toEqual( + Array.from({ length: 4 }, () => ({ agent: "build", model: answer })), + ) + }) + test("reuses a stable projected row array", () => { const messages = [ { id: "user-1", type: "user", text: "first", time: { created: 1 } }, @@ -359,8 +403,8 @@ describe("reasoningHeading", () => { expect(reasoningHeading("## First step\n\nDetails.\n\n## Second step\n\nMore details.")).toBe("Second step") expect(reasoningHeading("

First step

\n

Body

\n

Second step

")).toBe("Second step") expect(reasoningHeading("First step\n===\n\nSecond step\n---")).toBe("Second step") - expect( - reasoningHeading("**Designing Interactive Experience**\n\n**Note** that this line ends with **bold**"), - ).toBe("Designing Interactive Experience") + expect(reasoningHeading("**Designing Interactive Experience**\n\n**Note** that this line ends with **bold**")).toBe( + "Designing Interactive Experience", + ) }) }) diff --git a/packages/session-ui/src/timeline/projection.ts b/packages/session-ui/src/timeline/projection.ts index a17d7e798a4b..6450cee90a04 100644 --- a/packages/session-ui/src/timeline/projection.ts +++ b/packages/session-ui/src/timeline/projection.ts @@ -794,7 +794,9 @@ function indexUserContext(messages: SessionMessageInfo[]) { const result = new Map() let agent = "" let model: ModelRef = { id: "", providerID: "" } - let userID: string | undefined + // The user messages the next assistant message answers: one, or a batch of steers delivered together. + let answering: string[] = [] + let answered = false messages.forEach((message) => { if (message.type === "agent-switched") agent = message.agent @@ -802,7 +804,9 @@ function indexUserContext(messages: SessionMessageInfo[]) { if (message.type === "model-switched") model = message.model if (message.type === "user") { - userID = message.id + if (answered) answering = [] + answered = false + answering.push(message.id) const localModel = Option.getOrUndefined(decodeLocalModel(message.metadata))?.model const localModelID = localModel?.id ?? localModel?.modelID @@ -818,13 +822,13 @@ function indexUserContext(messages: SessionMessageInfo[]) { }) } - if (message.type === "shell") userID = undefined + if (message.type === "shell") answering = [] if (message.type !== "assistant") return agent = message.agent model = message.model - - if (userID) result.set(userID, { agent, model }) + answered = true + answering.forEach((id) => result.set(id, { agent, model })) }) return result diff --git a/packages/session-ui/src/timeline/session-timeline-row.tsx b/packages/session-ui/src/timeline/session-timeline-row.tsx index e89b2da65b10..47d297b144ea 100644 --- a/packages/session-ui/src/timeline/session-timeline-row.tsx +++ b/packages/session-ui/src/timeline/session-timeline-row.tsx @@ -6,12 +6,25 @@ import type { } from "@opencode/client/promise" import { useI18n } from "@opencode/ui/context/i18n" import { Option, Predicate, Schema } from "effect" -import { For, Show, createEffect, createMemo, onCleanup, untrack, type Accessor, type JSX } from "solid-js" +import { + For, + Show, + createEffect, + createMemo, + createSignal, + onCleanup, + untrack, + type Accessor, + type JSX, +} from "solid-js" import { DiffChanges } from "@opencode/ui/diff-changes" import { Icon } from "@opencode/ui/icon" import { Spring, frameLoop, prefersReducedMotion } from "@opencode/ui/motion" import { springStyle } from "@opencode/ui/motion/solid" import { Dynamic } from "solid-js/web" +import { createTimelineTextLayout, type TimelineLayoutEnvironment, type TimelineRowLayout } from "./text-layout" +import { createTimelineMarkdownLayout } from "./markdown-layout" +import { attached } from "../components/message-file" import type { SessionUserActions, SessionUserAttachmentReference, SessionUserComment } from "../actions" import { useData } from "../context" import { useMessageMenu } from "../context/message-menu" @@ -37,7 +50,6 @@ import { SessionError } from "../components/session-error" import { timelineCategory, type TimelineDetail } from "./detail" import { currentToolFailed } from "../message/current-tool-state" import { userMessageRuns, userRunSpring } from "./user-runs" -import { attached } from "../components/message-file" import { createReactiveTimelineProjection, Timeline, @@ -60,6 +72,30 @@ type FramedTimelineRow = Exclude type Outcome = "completed" | "error" | "cancelled" +// A stream that pauses mid-line shows its held word once the text has sat still this long; the layout model reads the +// same release so its height agrees with the row. +const releasedTails = new Map() +const tailHoldMs = 300 + +// Hold an incomplete trailing word on an active prose line until its boundary arrives so it never +// measures short at the end of a line and wraps to the next line as its remaining letters stream in. +function settledStreamText(raw: string, live: boolean, partID?: string) { + if (!live || !raw || (partID !== undefined && releasedTails.get(partID) === raw)) return raw + if ((raw.match(/```/g)?.length ?? 0) % 2 === 1) return raw.replace(/\n[ \t]*`{1,2}$/, "") + const lastNewline = raw.lastIndexOf("\n") + const line = raw.slice(lastNewline + 1) + if (lastNewline > 0 && /^[A-Za-z0-9\u00C0-\u024F]{1,24}$/.test(line)) { + return raw.slice(0, lastNewline).replace(/\n+$/, "") + } + const edge = line.search(/[ \t]+\S{1,24}$/) + if (edge < 0) return raw + const prefix = line.slice(0, edge) + const tail = line.slice(edge).trimStart() + if (!/[A-Za-z0-9\u00C0-\u024F]/.test(prefix)) return raw + if (/^`|[.,!?;:)\]]$/.test(tail)) return raw + return raw.slice(0, raw.length - tail.length) +} + export type SessionUserPresentation = { displayText?: string comments?: SessionUserComment[] @@ -426,25 +462,65 @@ export function createSessionTimelineRowRenderer(input: { return item ? contentDefaultOpen(item) : undefined }) + const [released, setReleased] = createSignal(0) + const text = createMemo(() => { + const value = content() + const assistant = message() + const partID = ref()?.partID + released() + if (value?.type !== "text" && value?.type !== "reasoning") return "" + const live = + value.type === "text" && assistant?.time.completed === undefined && assistant?.content.at(-1) === value + if (!live && partID !== undefined) releasedTails.delete(partID) + const shown = settledStreamText(value.text, live, partID) + if (shown === value.text || partID === undefined) return shown + const raw = value.text + const timer = setTimeout(() => { + releasedTails.set(partID, raw) + setReleased((count) => count + 1) + }, tailHoldMs) + onCleanup(() => clearTimeout(timer)) + return shown + }) + + const prepared = createMemo(() => { + const value = content() + const assistant = message() + const reference = ref() + if ((value?.type !== "text" && value?.type !== "reasoning") || !assistant || !reference) return + return markdownLayout.prepare( + reference.partID, + text(), + value.type === "text" && assistant.time.completed === undefined, + ) + }) + const disclosureKey = () => (content()?.type === "reasoning" ? ref()!.partID : row().group.key) return ( {(message) => ( - {(content) => ( - input.disclosure.set(disclosureKey(), open)} - onContentRendered={onSizeChange} - /> - )} + {(content) => { + const item = () => { + const value = content() + return value.type === "text" ? { ...value, text: text() } : value + } + return ( + input.disclosure.set(disclosureKey(), open)} + onContentRendered={onSizeChange} + preparedMarkdown={prepared()} + /> + ) + }} )} @@ -1062,6 +1138,7 @@ export function createSessionTimelineRowRenderer(input: { } onOpenChange={(open) => input.disclosure.set(current().ref.partID, open)} onContentRendered={onSizeChange} + preparedMarkdown={markdownLayout.prepare(current().ref.partID, content().text, true)} /> )} @@ -1169,7 +1246,117 @@ export function createSessionTimelineRowRenderer(input: { ) } - return { Row } + const textLayout = createTimelineTextLayout() + const markdownLayout = createTimelineMarkdownLayout(textLayout) + + function layout(row: TimelineRow.TimelineRow, environment: TimelineLayoutEnvironment): TimelineRowLayout { + if (row._tag === "TurnGap") return { source: "fixed", height: runs().get(row.userMessageID)?.above ? 4 : menu() ? 24 : 16 } + if (row._tag === "Activity") return { source: "fixed", height: 36 } + const width = + (input.centered?.() && environment.desktop ? Math.min(744, environment.width) : environment.width) - + (environment.desktop ? 48 : 32) + if (row._tag === "Thinking") { + const open = + input.disclosure.value(row.ref.partID) ?? + (input.timelineDetail + ? input.timelineDetail().thinking.details === "expanded" + : input.reasoningMode() === "full") + if (!open) return { source: "fixed", height: 40 } + const content = Timeline.resolveContent(input.projection.messageByID().get(row.ref.messageID), row.ref.partID) + if (content?.type === "reasoning") { + if (!content.text.trim()) return { source: "fixed", height: 40 } + const measured = markdownLayout.layout( + row.ref.partID, + content.text, + true, + width - 12, + environment.typography, + true, + ) + return measured.source === "dom" ? measured : { source: "pretext", height: 44 + measured.height } + } + } + if (row._tag === "AssistantPart") { + const spacing = row.spacing === "tool" ? 8 : row.spacing === "content" ? 16 : 0 + if (row.group.type === "context" && input.disclosure.value(`context:${row.group.key}`) !== true) + return { source: "fixed", height: spacing + 28 } + if (row.group.type === "read" && input.disclosure.value(row.group.key) !== true) + return { source: "fixed", height: spacing + 32 } + if (row.group.type === "part") { + const content = Timeline.resolveContent( + input.projection.messageByID().get(row.group.ref.messageID), + row.group.ref.partID, + ) + if (content?.type === "reasoning") { + if (!content.text.trim() || !(input.disclosure.value(row.group.ref.partID) ?? contentDefaultOpen(content))) + return { source: "fixed", height: spacing + 28 } + const measured = markdownLayout.layout( + row.group.ref.partID, + content.text, + false, + width - 12, + environment.typography, + true, + ) + return measured.source === "dom" ? measured : { source: "pretext", height: spacing + 32 + measured.height } + } + } + } + if (row._tag === "AssistantPart" && row.group.type === "part") { + const message = input.projection.messageByID().get(row.group.ref.messageID) + const content = Timeline.resolveContent(message, row.group.ref.partID) + if (message?.type === "assistant" && content?.type === "text") { + const live = message.time.completed === undefined && message.content.at(-1) === content + const text = settledStreamText(content.text, live, row.group.ref.partID) + const measured = markdownLayout.layout( + row.group.ref.partID, + text, + message.time.completed === undefined, + width, + environment.typography, + ) + if (measured.source === "dom") return measured + const extra = + (row.spacing === "content" ? 16 : 24 + (row.spacing === "tool" ? 8 : 0)) + + (!menu() && copyContentID(row.userMessageID) === row.group.ref.partID ? 24 - Math.min(4, measured.trailingMargin) : 0) + return { + source: "pretext", + height: !text ? 0 : measured.height + extra, + streamHeight: !text ? 0 : (live ? measured.streamHeight : measured.height) + extra, + } + } + } + if (row._tag !== "UserMessage") return { source: "dom", reason: row._tag } + const message = input.projection.messageByID().get(row.userMessageID) + if (message?.type !== "user") return { source: "fixed", height: 0 } + const presentation = input.presentation?.(message) + if ( + message.files?.some((file) => file.mention || (attached(file) && !file.mime.startsWith("image/"))) || + message.agents?.length || + presentation?.comments?.length || + presentation?.references?.length + ) + return { source: "dom", reason: "user attachments or references" } + const text = presentation?.displayText ?? message.text + if (!text) return { source: "dom", reason: "empty user message" } + const contentWidth = Math.min(width * 0.82, 64 * textLayout.ch(environment.typography)) - 24 + const images = message.files?.filter(attached).length ?? 0 + const imageRows = Math.ceil(images / Math.max(1, Math.floor((contentWidth + 24 + 8) / (58 + 8)))) + const joined = runs().get(row.userMessageID) + const pending = input.actions?.pending?.status(message.id) + const labelled = (pending === "steering" || pending === "stranded") && !joined?.above + return { + source: "pretext", + height: + (labelled ? 24 : 0) + + (imageRows ? imageRows * (46 + 8) : presentation?.voice ? 8 : 0) + + 16 + + (joined?.below || (menu() && !labelled) ? 0 : 24) + + textLayout.text(TimelineRow.key(row), text, contentWidth, environment.typography, "pre-wrap"), + } + } + + return { Row, layout } } function capitalizeAgent(agent: string) { diff --git a/packages/session-ui/src/timeline/text-layout.ts b/packages/session-ui/src/timeline/text-layout.ts new file mode 100644 index 000000000000..a9c3b19f3e42 --- /dev/null +++ b/packages/session-ui/src/timeline/text-layout.ts @@ -0,0 +1,189 @@ +import { clearCache, layout, measureNaturalWidth, prepare, type PreparedText } from "@chenglou/pretext" +import { + prepareRichInline, + walkRichInlineLineRanges, + type PreparedRichInline, + type RichInlineItem, +} from "@chenglou/pretext/rich-inline" + +/** Resolved CSS values, read when the viewport's typography changes, never once per row. */ +export type TimelineTypography = { + family: string + codeFamily: string + codeInset: number + codeLineHeight: number + rem: number + size: number + weight: number + medium: number + bold: number + lineHeight: number + letterSpacing: number + revision: number +} + +export type TimelineRowLayout = + | { source: "pretext" | "fixed"; height: number; streamHeight?: number } + | { source: "dom"; reason: string; blocks?: number[] } + +export type TimelineLayoutEnvironment = { + width: number + desktop: boolean + typography: TimelineTypography +} + +export function readTimelineTypography(element: Element, revision: number): TimelineTypography { + const style = getComputedStyle(element) + const size = parseFloat(style.getPropertyValue("--font-size-base")) + const leading = style.getPropertyValue("--line-height-large").trim() + // Resolve CSS chrome once with typography. Browsers snap a .5px border differently; + // this empty style probe reads no content geometry and never measures a timeline row. + const probe = document.createElement("div") + probe.dataset.component = "markdown" + probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none" + const code = document.createElement("pre") + code.className = "highlights" + probe.append(code) + element.append(probe) + const chrome = getComputedStyle(code) + const codeInset = [chrome.paddingTop, chrome.paddingBottom, chrome.borderTopWidth, chrome.borderBottomWidth].reduce( + (sum, value) => sum + parseFloat(value), + 0, + ) + const codeLineHeight = parseFloat(chrome.lineHeight) || 20 + probe.remove() + return { + family: style.getPropertyValue("--font-family-sans").trim(), + codeFamily: style.getPropertyValue("--font-family-mono").trim(), + codeInset, + codeLineHeight, + rem: parseFloat(getComputedStyle(document.documentElement).fontSize), + size, + weight: parseFloat(style.getPropertyValue("--font-weight-regular")), + medium: parseFloat(style.getPropertyValue("--font-weight-medium")), + bold: parseFloat(style.getPropertyValue("--font-weight-bold")), + lineHeight: leading.endsWith("%") ? (size * parseFloat(leading)) / 100 : parseFloat(leading), + letterSpacing: parseFloat(style.getPropertyValue("--letter-spacing-normal")) || 0, + revision, + } +} + +/** The cache belongs to a session renderer. Width is deliberately absent from preparation keys. */ +export function createTimelineTextLayout() { + const text = new Map< + string, + { + value: string + font: string + letterSpacing: number + whiteSpace: "normal" | "pre-wrap" + prepared: PreparedText + width?: number + lineHeight?: number + height?: number + } + >() + const rich = new Map< + string, + { + signature: string + prepared: PreparedRichInline + width?: number + lineHeight?: number + height?: number + lineCount?: number + lastFill?: number + } + >() + let revision = -1 + + function refresh(next: number) { + if (next === revision) return + revision = next + clearCache() + text.clear() + rich.clear() + } + + return { + text(key: string, value: string, width: number, style: TimelineTypography, whiteSpace: "normal" | "pre-wrap") { + refresh(style.revision) + const font = `${style.weight} ${style.size}px ${style.family}` + const targetWidth = Math.max(1, width) + const previous = text.get(key) + const sameText = + previous?.value === value && + previous.font === font && + previous.letterSpacing === style.letterSpacing && + previous.whiteSpace === whiteSpace + if ( + sameText && + previous.width === targetWidth && + previous.lineHeight === style.lineHeight && + previous.height !== undefined + ) + return previous.height + const prepared = sameText + ? previous.prepared + : prepare(value, font, { whiteSpace, letterSpacing: style.letterSpacing }) + const height = layout(prepared, targetWidth, style.lineHeight).height + text.set(key, { + value, + font, + letterSpacing: style.letterSpacing, + whiteSpace, + prepared, + width: targetWidth, + lineHeight: style.lineHeight, + height, + }) + return height + }, + rich(key: string, items: RichInlineItem[], width: number, lineHeight: number, revision: number) { + refresh(revision) + const targetWidth = Math.max(1, width) + const signature = JSON.stringify(items) + const previous = rich.get(key) + if ( + previous?.signature === signature && + previous.width === targetWidth && + previous.lineHeight === lineHeight && + previous.height !== undefined + ) + return previous.height + const prepared = previous?.signature === signature ? previous.prepared : prepareRichInline(items) + let lastWidth = 0 + const lineCount = walkRichInlineLineRanges(prepared, targetWidth, (line) => { + lastWidth = line.width + }) + const height = lineCount * lineHeight + const lastFill = lineCount > 0 ? Math.min(1, Math.max(0, lastWidth / targetWidth)) : 0 + rich.set(key, { signature, prepared, width: targetWidth, lineHeight, height, lineCount, lastFill }) + return height + }, + richSubline(key: string) { + const entry = rich.get(key) + if (!entry || entry.lineCount === undefined || entry.lastFill === undefined || entry.lineHeight === undefined) + return undefined + return { lineCount: entry.lineCount, fill: entry.lastFill, lineHeight: entry.lineHeight } + }, + ch(style: TimelineTypography) { + refresh(style.revision) + const font = `${style.weight} ${style.size}px ${style.family}` + const key = `ch:${font}` + const previous = text.get(key) + if (previous) return previous.height ?? measureNaturalWidth(previous.prepared) + const prepared = prepare("0", font) + const chWidth = measureNaturalWidth(prepared) + text.set(key, { + value: "0", + font, + letterSpacing: 0, + whiteSpace: "normal", + prepared, + height: chWidth, + }) + return chWidth + }, + } +} diff --git a/packages/session-ui/src/timeline/user-runs.test.ts b/packages/session-ui/src/timeline/user-runs.test.ts index 7b3ee2efc7ee..1fcefef118c5 100644 --- a/packages/session-ui/src/timeline/user-runs.test.ts +++ b/packages/session-ui/src/timeline/user-runs.test.ts @@ -113,6 +113,15 @@ describe("userMessageRuns", () => { ).toEqual({ msg_1: alone, msg_2: alone, msg_3: alone }) }) + test("a message on the default variant joins one that names no variant", () => { + expect( + runs([user("msg_1", 1), user("msg_2", 2)], { + msg_1: { kind: "pending", model: { id: "model", providerID: "provider", variant: "default" } }, + msg_2: { kind: "pending" }, + }), + ).toEqual({ msg_1: { above: false, below: true }, msg_2: { above: true, below: false } }) + }) + test("a switch or compaction ends the run even when the timeline hides its notice", () => { const messages = [ user("msg_1", 1), diff --git a/packages/session-ui/src/timeline/user-runs.ts b/packages/session-ui/src/timeline/user-runs.ts index a7608ba80261..2ad69c57ad9f 100644 --- a/packages/session-ui/src/timeline/user-runs.ts +++ b/packages/session-ui/src/timeline/user-runs.ts @@ -48,7 +48,7 @@ export function userMessageRuns( upper.agent === lower.agent && upper.model.providerID === lower.model.providerID && upper.model.id === lower.model.id && - upper.model.variant === lower.model.variant && + variant(upper.model) === variant(lower.model) && segments.get(above.userMessageID) === segments.get(below.userMessageID) ) } @@ -85,3 +85,8 @@ function boundarySegments(messages: readonly SessionMessageInfo[]) { return segments } + +// A message sent without a local model takes its reply's, whose variant is "default"; one sent with it names none. +function variant(model: UserRunMember["model"]) { + return model.variant === "default" ? undefined : model.variant +} diff --git a/packages/session-ui/src/tools/tool-renderer.tsx b/packages/session-ui/src/tools/tool-renderer.tsx index 60aea25a11d8..68f5e61d6c7c 100644 --- a/packages/session-ui/src/tools/tool-renderer.tsx +++ b/packages/session-ui/src/tools/tool-renderer.tsx @@ -44,6 +44,7 @@ import { TextShimmer } from "@opencode/ui/text-shimmer" import { AnimatedNumber } from "@opencode/ui/animated-number" import { changedFileDiff, patchFileGroups } from "../components/apply-patch-file" import { animate } from "motion" +import { widthMorph } from "@opencode/ui/motion/solid" import { SessionProgressIndicatorV2 } from "../v2/components/session-progress-indicator-v2" import type { FileDiffInfo, @@ -1741,8 +1742,18 @@ ToolRegistry.register({ open() } + const [card, setCard] = createSignal() + // Backgrounding adds a suffix while the task stays on screen; its surface keeps one continuous width. + widthMorph({ + ref: card, + content: () => card()?.querySelector('[data-component="task-tool-surface"]') ?? undefined, + watch: () => [title(), subtitle(), running(), clickable()], + spring: () => ({ duration: 0.25, bounce: 0 }), + inset: 0, + }) + const trigger = () => ( -
+
diff --git a/packages/ui/src/components/scroll-view.tsx b/packages/ui/src/components/scroll-view.tsx index e46cec7af820..dfe8f300c828 100644 --- a/packages/ui/src/components/scroll-view.tsx +++ b/packages/ui/src/components/scroll-view.tsx @@ -6,6 +6,14 @@ import { useI18n } from "../context/i18n" export type ScrollViewThumbVisibility = "hover" | "scroll" +/** Geometry already owned by a virtual list; all dimensions are in CSS pixels. */ +export type ScrollViewGeometry = { + extent: number + viewport: number + offset: number + track: number +} + export interface ScrollViewProps extends ComponentProps<"div"> { viewportRef?: (el: HTMLDivElement) => void orientation?: "vertical" | "horizontal" | "both" @@ -24,6 +32,7 @@ export interface ScrollViewProps extends ComponentProps<"div"> { onBeforeScroll?: () => void /** Offset/extent correction for a virtualized vertical scrollbar. */ verticalScrollAdjustment?: number + verticalGeometry?: ScrollViewGeometry } export const scrollKey = (event: Pick) => { @@ -144,6 +153,7 @@ export function ScrollView(props: ScrollViewProps) { "thumbHoverTarget", "onBeforeScroll", "verticalScrollAdjustment", + "verticalGeometry", "style", ], [ @@ -214,20 +224,21 @@ export function ScrollView(props: ScrollViewProps) { if (vertical()) { const adjustment = local.verticalScrollAdjustment ?? 0 - const scrollHeight = viewportRef.scrollHeight + adjustment - const trackSize = Math.max(0, (thumbMount()?.clientHeight || viewportRef.clientHeight) - trackPadding * 2) + const geometry = local.verticalGeometry + const viewport = geometry?.viewport ?? viewportRef.clientHeight + const scrollHeight = (geometry?.extent ?? viewportRef.scrollHeight) + adjustment + const trackSize = Math.max(0, (geometry?.track ?? (thumbMount()?.clientHeight || viewport)) - trackPadding * 2) - const size = trackSize - ? Math.min(trackSize, Math.max((viewportRef.clientHeight / scrollHeight) * trackSize, minThumbSize)) - : 0 + const size = trackSize ? Math.min(trackSize, Math.max((viewport / scrollHeight) * trackSize, minThumbSize)) : 0 - const maxScroll = scrollHeight - viewportRef.clientHeight + const maxScroll = scrollHeight - viewport const maxStart = trackSize - size setState("showVerticalThumb", maxScroll > 0) setState("verticalThumbSize", size) setState( "verticalThumbStart", - trackPadding + (maxScroll > 0 ? ((viewportRef.scrollTop + adjustment) / maxScroll) * maxStart : 0), + trackPadding + + (maxScroll > 0 ? (((geometry?.offset ?? viewportRef.scrollTop) + adjustment) / maxScroll) * maxStart : 0), ) } else { setState("showVerticalThumb", false) @@ -262,7 +273,10 @@ export function ScrollView(props: ScrollViewProps) { // appears later), after layout. Measuring here as well would force a synchronous layout per // ScrollView while the page is still rendering. createResizeObserver( - () => [viewportRef, viewportRef.firstElementChild, thumbMount()].filter(Boolean) as HTMLElement[], + () => + local.verticalGeometry && !horizontal() + ? [] + : ([viewportRef, viewportRef.firstElementChild, thumbMount()].filter(Boolean) as HTMLElement[]), updateThumb, ) }) @@ -282,6 +296,10 @@ export function ScrollView(props: ScrollViewProps) { onCleanup(() => observer.disconnect()) }) + createEffect(() => { + if (local.verticalGeometry) updateThumb() + }) + createEffect(() => { const target = thumbHover() @@ -330,9 +348,11 @@ export function ScrollView(props: ScrollViewProps) { pointer: vertical ? e.clientY : e.clientX, viewportStart: vertical ? track.getBoundingClientRect().top : track.getBoundingClientRect().left, grabOffset, - clientSize: vertical ? track.clientHeight : track.clientWidth, - scrollClientSize: vertical ? viewportRef.clientHeight : viewportRef.clientWidth, - scrollSize: vertical ? viewportRef.scrollHeight : viewportRef.scrollWidth, + clientSize: vertical ? (local.verticalGeometry?.track ?? track.clientHeight) : track.clientWidth, + scrollClientSize: vertical + ? (local.verticalGeometry?.viewport ?? viewportRef.clientHeight) + : viewportRef.clientWidth, + scrollSize: vertical ? (local.verticalGeometry?.extent ?? viewportRef.scrollHeight) : viewportRef.scrollWidth, thumbSize: vertical ? state.verticalThumbSize : state.horizontalThumbSize, reverse: rtl, }) @@ -427,7 +447,7 @@ export function ScrollView(props: ScrollViewProps) { prepareScroll() if (!next) return - const scrollAmount = viewportRef.clientHeight * 0.8 + const scrollAmount = (local.verticalGeometry?.viewport ?? viewportRef.clientHeight) * 0.8 const lineAmount = 40 switch (next) { @@ -445,7 +465,7 @@ export function ScrollView(props: ScrollViewProps) { break case "end": e.preventDefault() - viewportRef.scrollTo({ top: viewportRef.scrollHeight }) + viewportRef.scrollTo({ top: local.verticalGeometry?.extent ?? viewportRef.scrollHeight }) break case "up": e.preventDefault() @@ -478,10 +498,9 @@ export function ScrollView(props: ScrollViewProps) { class="scroll-view__viewport" data-scrollable onScroll={(e) => { - updateThumb() - markScrolling() - if (typeof events.onScroll === "function") events.onScroll(e as any) + if (!local.verticalGeometry || horizontal()) updateThumb() + markScrolling() }} // Passive so the compositor never waits on the main thread to scroll; onWheel cannot cancel. on:wheel={{ diff --git a/packages/ui/src/i18n/en.ts b/packages/ui/src/i18n/en.ts index f9249b5a7750..7e76d8e8b725 100644 --- a/packages/ui/src/i18n/en.ts +++ b/packages/ui/src/i18n/en.ts @@ -284,6 +284,7 @@ const source = { "ui.message.revertMessage": "Revert message", "ui.message.moveToQueue": "Move to queue", "ui.message.pending": "Pending", + "ui.message.steering": "Steering", "ui.message.voice": "Voice", "ui.message.deletePending": "Delete", "ui.message.copyResponse": "Copy response", diff --git a/packages/ui/src/motion-tuning.ts b/packages/ui/src/motion-tuning.ts index 6b51d358f835..e4dfabb6a950 100644 --- a/packages/ui/src/motion-tuning.ts +++ b/packages/ui/src/motion-tuning.ts @@ -193,10 +193,12 @@ export const motionTuning = { }, list: () => [...knobs.values()], actions: () => [...actions.values()], + timeScale: () => timeScale(), /** Applies an edit and saves every knob that differs from its default. */ set(knob: K, value: K["value"]) { knob.value = value save() + syncScale() notify() }, subscribe(listener: () => void) { @@ -237,6 +239,13 @@ function timeScale() { return (slow.value ? 4 : 1) / speed.value } +function syncScale() { + if (typeof document !== "undefined") + document.documentElement?.style.setProperty("--motion-time-scale", `${timeScale()}`) +} + +syncScale() + function register(knob: K) { knobs.set(knob.id, knob) notify() diff --git a/packages/ui/src/motion/solid.ts b/packages/ui/src/motion/solid.ts index 668040613afd..faf43ece6560 100644 --- a/packages/ui/src/motion/solid.ts +++ b/packages/ui/src/motion/solid.ts @@ -1,4 +1,5 @@ import { createEffect, onCleanup } from "solid-js" +import { motionTuning } from "../motion-tuning" import { frameLoop } from "./loop" import { observeReducedMotion, prefersReducedMotion } from "./reduced" import { Spring } from "./spring" @@ -27,10 +28,11 @@ export function springStyle( let moving = false const snap = reduced || Boolean(options.snap?.()) + const scaledDt = dt / motionTuning.timeScale() for (let i = 0; i < keys.length; i++) { const spring = springs[i]! - values[keys[i]!] = snap ? spring.snap(spring.target).value : spring.step(dt) + values[keys[i]!] = snap ? spring.snap(spring.target).value : spring.step(scaledDt) moving = moving || spring.value !== spring.target || spring.velocity !== 0 } @@ -208,7 +210,8 @@ export function widthMorph(options: { spring?: () => DurationOptions inset?: number }): void { - let spring = Spring.fromDuration(0, { duration: 0.42, bounce: 0.18 }) + const spring = Spring.fromDuration(0, { duration: 0.42, bounce: 0.18 }) + let currentEl: HTMLElement | undefined let first = true createEffect(() => { options.watch?.() @@ -216,49 +219,54 @@ export function widthMorph(options: { const el = options.ref() const content = options.content() - if (!el || !content) return + if (!el || !content) { + currentEl = undefined + return + } - if (settings) { - const next = Spring.fromDuration(spring.value, settings) - next.velocity = spring.velocity - spring = next + if (el !== currentEl) { + currentEl = el + first = true } + if (settings) spring.tune(settings) + const originalContentWidth = content.style.width content.style.width = "100%" - // SAFETY: a deep clone of an HTMLElement is an HTMLElement. - const clone = content.cloneNode(true) as HTMLElement - clone.removeAttribute("id") - - for (const node of clone.querySelectorAll("[id]")) node.removeAttribute("id") - clone.setAttribute("aria-hidden", "true") - clone.inert = true - Object.assign(clone.style, { - position: "absolute", - visibility: "hidden", - pointerEvents: "none", - width: "max-content", - maxWidth: "none", - minWidth: "0", - top: "0", - left: "0", - }) - el.append(clone) let measured = false let remove: (() => void) | undefined let reduced = prefersReducedMotion() const read = () => { if (measured) return + // SAFETY: a deep clone of an HTMLElement is an HTMLElement. + const clone = content.cloneNode(true) as HTMLElement + clone.removeAttribute("id") + + for (const node of clone.querySelectorAll("[id]")) node.removeAttribute("id") + clone.setAttribute("aria-hidden", "true") + clone.inert = true + Object.assign(clone.style, { + position: "absolute", + visibility: "hidden", + pointerEvents: "none", + width: "max-content", + maxWidth: "none", + minWidth: "0", + top: "0", + left: "0", + }) + el.append(clone) spring.set(clone.getBoundingClientRect().width + 2 * (options.inset ?? 4)) + clone.remove() measured = true } const write = (dt: number) => { + if (options.spring) spring.tune(options.spring()) if (first || reduced) spring.snap(spring.target) first = false el.style.width = `${spring.step(dt)}px` - clone.remove() const moving = !spring.resting if (!moving) remove = undefined @@ -277,7 +285,6 @@ export function widthMorph(options: { onCleanup(() => { remove?.() unsubscribe() - clone.remove() content.style.width = originalContentWidth }) }) diff --git a/packages/ui/src/motion/spring.ts b/packages/ui/src/motion/spring.ts index 456907bfea8e..44f357e2422c 100644 --- a/packages/ui/src/motion/spring.ts +++ b/packages/ui/src/motion/spring.ts @@ -71,6 +71,25 @@ export class Spring { return new Spring(value, { omega: (2 * Math.PI) / duration, zeta: 1 - bounce }) } + tune({ duration, bounce }: DurationOptions): this { + if ( + !Number.isFinite(duration) || + duration < (2 * Math.PI) / 240 || + !Number.isFinite(bounce) || + bounce < 0 || + bounce >= 1 + ) { + throw new RangeError("duration must be >= 2π/240 seconds; bounce must be in [0, 1)") + } + + const nextOmega = (2 * Math.PI) / duration + if (this.omega > 0) this.velocity *= nextOmega / this.omega + this.omega = nextOmega + this.zeta = 1 - bounce + + return this + } + set(target: number, options?: { velocity?: number }): this { if (!Number.isFinite(target) || (options?.velocity !== undefined && !Number.isFinite(options.velocity))) throw new RangeError("Non-finite spring target or velocity") diff --git a/script/drive/demo-session.md b/script/drive/demo-session.md new file mode 100644 index 000000000000..2c6019fe5315 --- /dev/null +++ b/script/drive/demo-session.md @@ -0,0 +1,41 @@ +# Demo session + +`demo-session.ts` starts an isolated OpenCode server for the debug bar's Demo controls. Its simulated model answers +each `[demo: ×]` prompt with a scripted reply. Shell commands, patches, file reads and the background +subagent run for real inside the throwaway project, so the app renders them through the normal event path. + +## Run + +Use an `opencode-drive` installation on the module path and a dependency-installed checkout: + +```sh +DEMO_STATE=/tmp/demo-session.json opencode-drive run script/drive/demo-session.ts +``` + +The script prints the session it created. `DEMO_STATE` optionally receives the server URL, its password and that +session ID, for a proxy or a client that opens it directly. Connect a dev or Beta build of the app to that server, +open the session, toggle the debug bar and press DEMO. + +| Control | What the session does | +| ----------- | ------------------------------------------------------------------------ | +| Paragraph | Streams reasoning, then a paragraph | +| Code block | Streams a fenced TypeScript block line by line | +| Shell | Runs a real shell command whose output grows | +| Patch | Applies a real one-line patch, alternating between two values | +| Long turn | Thinks for a few seconds before answering | +| Finish turn | Interrupts the running turn | +| Message | Sends a user message that gets a short reply | +| Steer | Sends a prompt that steers a running turn | +| Burst | Reads five files in parallel, then streams one-character text deltas | +| Queue | Queues a prompt behind the running turn | +| Subagent | Starts a background subagent that reports back when it finishes | +| Bg shell | Starts a real background shell that keeps printing for about ten seconds | +| Auto-play | Loops a scripted mix of the above, including a steer and a queued prompt | + +Anything typed into the composer gets a random 5–10 second turn seeded by the conversation: reasoning, prose, +lists and code between one to three real shell builds, often a patch and parallel reads, sometimes a background +subagent or shell, then a summary. Typed text containing `short` or `code` gets those replies instead. Typed prompts +use the speed of the latest Demo control. Routing a session on the simulated model opens the debug bar and its +Demo panel. + +Speed scales the model's streaming delays and the shell scripts' pacing from 0.25× to 2×. diff --git a/script/drive/demo-session.ts b/script/drive/demo-session.ts new file mode 100644 index 000000000000..5cd1a476fcfc --- /dev/null +++ b/script/drive/demo-session.ts @@ -0,0 +1,510 @@ +import { readFileSync } from "node:fs" +import { Effect, Stream } from "effect" +import { Llm, OpenCodeDriver } from "opencode-drive" + +// Serves the debug bar's Demo controls: an isolated server whose simulated model answers each `[demo: ×]` +// prompt with a scripted reply. Shell, edit, read and subagent calls run for real inside the throwaway project. +// Run from the repository root with `opencode-drive run script/drive/demo-session.ts`; see demo-session.md. +const state = process.env.DEMO_STATE + +const tides = [ + "#!/bin/sh", + 'delay=$(awk "BEGIN { print 0.22 / ${1:-1} }")', + "for station in Breakwater 'North Mole' 'Lantern Quay' 'Saltmarsh Gate' 'Pilot Steps' 'Fishery Slip' 'East Buoy' 'Harbor Mouth'; do", + ' printf "✓ %-16s high water within 4 cm\\n" "$station"', + ' sleep "$delay"', + "done", + 'printf "\\n8 passed, 0 failed\\n"', +].join("\n") + +const preview = [ + "#!/bin/sh", + 'delay=$(awk "BEGIN { print 0.9 / ${1:-1} }")', + 'printf "Lantern preview starting on http://127.0.0.1:4173\\n"', + "for frame in 1 2 3 4 5 6 7 8 9 10 11 12; do", + ' sleep "$delay"', + ' printf "rebuilt beacon map (%s/12)\\n" "$frame"', + "done", + 'printf "preview idle\\n"', +].join("\n") + +const build = [ + "#!/bin/sh", + "count=${1:-8}", + 'delay=$(awk "BEGIN { print 0.07 / ${2:-1} }")', + "label=${3:-module}", + "i=1", + 'while [ "$i" -le "$count" ]; do', + ' printf " %s %02d/%02d compiled in %dms\\n" "$label" "$i" "$count" $((i * 37 % 90 + 8))', + ' sleep "$delay"', + " i=$((i+1))", + "done", + 'printf "\\n%s: %d built, 0 warnings\\n" "$label" "$count"', +].join("\n") + +const harbor = [ + "export const lantern = {", + ' name: "North Mole",', + " intervalMs: 4000,", + ' color: "amber",', + "}", + "", + "export function nextFlash(at: number) {", + " return at + lantern.intervalMs", + "}", + "", +].join("\n") + +const paragraph = + "The harbor wakes before the town does. Fishing boats slip their moorings while the lanterns along the North Mole " + + "are still turning, and the tide tables pinned inside the pilot's hut are already out of date by a few minutes. " + + "Most mornings the fog lifts in layers: first the masts, then the roofs of the net sheds, and finally the long " + + "breakwater, which always seems farther away than it is. By the time the bakery opens, the first catch is on ice." + +const code = [ + "Here is the scheduler that keeps the lanterns in phase:", + "", + "```ts", + "type Lantern = { name: string; intervalMs: number; offsetMs: number }", + "", + "export function schedule(lanterns: Lantern[], now: number) {", + " return lanterns", + " .map((lantern) => {", + " const elapsed = (now - lantern.offsetMs) % lantern.intervalMs", + " return { name: lantern.name, nextFlash: now + lantern.intervalMs - elapsed }", + " })", + " .toSorted((a, b) => a.nextFlash - b.nextFlash)", + "}", + "", + "export function inPhase(a: Lantern, b: Lantern) {", + " return a.intervalMs === b.intervalMs && a.offsetMs === b.offsetMs", + "}", + "```", + "", + "Each lantern keeps its own interval, so the sort decides which one flashes next.", +].join("\n") + +export default OpenCodeDriver.use( + { + opencode: { dev: process.env.OPENCODE_DEV ?? process.cwd() }, + tui: { viewport: { cols: 100, rows: 30 } }, + llm: { requestTimeout: 3_600_000, settlementTimeout: 5_000 }, + config: { + autoupdate: false, + username: "Demo", + agents: { surveyor: { mode: "subagent", description: "Surveys a part of the harbor" } }, + }, + project: { + git: true, + files: { + "README.md": "# Harbor\nLantern schedules and tide checks for a fictional harbor.\n", + "src/harbor.ts": harbor, + "src/tides.ts": "export const stations = ['Breakwater', 'North Mole', 'Lantern Quay']\n", + "src/fleet.ts": "export const boats = ['Gannet', 'Kittiwake', 'Shearwater']\n", + "docs/pilots.md": "# Pilot steps\nBoard at the pilot steps two hours before high water.\n", + "scripts/tides.sh": tides, + "scripts/preview.sh": preview, + "scripts/build.sh": build, + }, + }, + }, + ({ llm, artifacts, directory }) => + Effect.gen(function* () { + yield* llm.title(() => Effect.succeed("Timeline demo")) + yield* llm.serve((request) => { + const body = JSON.stringify(request.body) + if (body.includes("You are a subagent spawned")) return child(rate(body)) + const turn = demoTurn(request.body) + if (!turn) return reply("Noted. The harbor log is up to date.", 1) + if (turn.action === "random") return randomTurn(turn.seed, turn.step, turn.speed, directory) + return respond(turn.action, turn.step, turn.speed, directory) + }) + const session = yield* Effect.promise(() => createSession(artifacts, directory)) + console.log(`Demo session ${session.id} in ${directory}`) + if (state) + yield* Effect.promise(() => Bun.write(state, JSON.stringify({ ...session.server, session: session.id }))) + return yield* Effect.never + }), +) + +function respond(action: string, step: number, speed: number, directory: string) { + const call = (name: string, input: Record, index = 0) => + Llm.toolCall({ index, id: `call_${crypto.randomUUID().replaceAll("-", "")}`, name, input }) + const text = (value: string, chunk = 3) => Llm.text(value, { delay: 16 / speed, chunkSize: chunk }) + const think = (value: string) => Llm.reasoning(value, { delay: 24 / speed, chunkSize: 4 }) + const tools = (...outputs: Llm.Output[]) => Stream.make(...outputs, Llm.finish("tool-calls")) + + switch (action) { + case "paragraph": + return Stream.make(think("Describing the morning harbor."), text(paragraph)) + case "code": + return Stream.make(text(code, 6)) + case "shell": + if (step === 0) + return tools( + text("Running the tide checks."), + call("shell", { + command: `sh scripts/tides.sh ${speed}`, + description: "Run tide checks", + workdir: directory, + }), + ) + return Stream.make(text("All eight stations are within tolerance.")) + case "patch": + if (step === 0) + return tools(text("Retiming the North Mole lantern."), call("patch", { patchText: patch(directory) })) + return Stream.make(text("The lantern interval is updated.")) + case "turn": + return Stream.make( + think( + "Checking the tide tables against the lantern schedule. The North Mole runs on a four second interval, " + + "the Lantern Quay on six, so they line up every twelve seconds. High water is at 06:40, which means " + + "the pilot boat leaves at 04:40 and needs both lanterns in phase before then.", + ), + Llm.pause(1_500 / speed), + text("Both lanterns are in phase before the pilot boat leaves."), + ) + case "short": + return Stream.make(text("Sure. The harbor is quiet today.")) + case "long": + case "message": + case "steer": + return longReply(step, speed, directory) + case "burst": + if (step === 0) + return tools( + Llm.text("Reading the harbor files.", { delay: 4 / speed, chunkSize: 2 }), + ...["README.md", "src/harbor.ts", "src/tides.ts", "src/fleet.ts", "docs/pilots.md"].map((file, index) => + call("read", { path: `${directory}/${file}` }, index), + ), + ) + return Stream.make( + Llm.text( + "Five files: the lantern config, the tide stations, the fleet roster, the pilot notes and the readme.", + { delay: 4 / speed, chunkSize: 1 }, + ), + ) + case "queue": + return Stream.make(text("Next on the list: repaint the pilot steps before the spring tides.")) + case "subagent": + if (step === 0) + return tools( + text("Sending a surveyor to the breakwater."), + call("subagent", { + agent: "surveyor", + description: "Survey the breakwater", + prompt: `[demo:child ${speed}×] Walk the breakwater and report any loose stones.`, + background: true, + }), + ) + return Stream.make(text("The survey runs in the background. I'll report back when it lands.")) + case "notice": + return Stream.make(text("That finished. The results are in the harbor log.")) + case "background": + if (step === 0) + return tools( + text("Starting the lantern preview."), + call("shell", { + command: `sh scripts/preview.sh ${speed}`, + description: "Lantern preview", + workdir: directory, + background: true, + }), + ) + return Stream.make(text("The preview is starting in the background.")) + } + return reply("Noted.", speed) +} + +function child(speed: number) { + return Stream.make( + Llm.reasoning("Walking the breakwater from the harbor mouth.", { delay: 30 / speed, chunkSize: 3 }), + Llm.pause(1_200 / speed), + Llm.text( + "The breakwater is sound. Two capstones near the East Buoy have shifted a few centimetres and should be reset " + + "at the next low spring tide.", + { delay: 40 / speed, chunkSize: 3 }, + ), + ) +} + +// Tool boundaries let the real runner deliver steers before requesting the next section. +// A newly delivered steer starts another long continuation instead of ending with an acknowledgement. +function longReply(step: number, speed: number, directory: string) { + const text = (value: string) => Llm.text(value, { delay: 16 / speed, chunkSize: 3 }) + const sections = [ + `${paragraph}\n\n${sentences.slice(0, 6).join(" ")}\n\n${sentences.slice(6).join(" ")}`, + `${sentences.slice(4).join(" ")}\n\n${paragraph}\n\n${sentences.slice(0, 4).join(" ")}`, + `${paragraph}\n\n${sentences.slice(2, 9).join(" ")}\n\n${summaries.join(" ")}`, + ] + const output = text(sections[Math.min(step, sections.length - 1)]!) + if (step >= 2) return Stream.make(Llm.pause(600 / speed), output) + return Stream.make( + Llm.pause(600 / speed), + output, + Llm.toolCall({ + index: 0, + id: `call_${crypto.randomUUID().replaceAll("-", "")}`, + name: step === 0 ? "read" : "shell", + input: step === 0 + ? { path: `${directory}/docs/pilots.md` } + : { command: `sh scripts/tides.sh ${speed}`, description: "Check harbor tides", workdir: directory }, + }), + Llm.finish("tool-calls"), + ) +} + +function reply(value: string, speed: number) { + return Stream.make(Llm.text(value, { delay: 16 / speed, chunkSize: 3 })) +} + +// Toggles the lantern interval, so every press produces a real diff. +function patch(directory: string) { + const path = `${directory}/src/harbor.ts` + const [from, to] = readFileSync(path, "utf8").includes("intervalMs: 6000") ? [6000, 4000] : [4000, 6000] + return [ + "*** Begin Patch", + `*** Update File: ${path}`, + "@@", + `- intervalMs: ${from},`, + `+ intervalMs: ${to},`, + "*** End Patch", + ].join("\n") +} + +function rate(body: string) { + const match = body.match(/\[demo:[a-z]+ ([\d.]+)×\]/) + return match ? Number(match[1]) || 1 : 1 +} + +// Typed prompts carry no tag, so they stream at the speed of the latest Demo control. +let lastSpeed = 1 + +// The newest user message picks the action; assistant messages after it count the steps already taken this turn. +// A Demo control's tag names its action, a background notice gets a short acknowledgement, "short" and "code" in +// typed text pick those replies, and any other typed prompt gets a random turn seeded by the conversation so far. +function demoTurn(body: unknown) { + const messages = typeof body === "object" && body !== null && "messages" in body ? body.messages : undefined + if (!Array.isArray(messages)) return + const last = messages.findLastIndex((message) => message?.role === "user") + if (last < 0) return + const step = messages.slice(last + 1).filter((message) => message?.role === "assistant").length + const text = userText(messages[last]) + const match = text.match(/\[demo:([a-z]+) ([\d.]+)×\]/) + if (match) { + lastSpeed = Number(match[2]) || 1 + return { action: match[1], speed: lastSpeed, step, seed: 0 } + } + const pick = (action: string) => ({ action, speed: lastSpeed, step, seed: 0 }) + if (/<(subagent|shell) /.test(text)) return pick("notice") + if (/\bshort\b/i.test(text)) return pick("short") + if (/\bcode\b/i.test(text)) return pick("code") + if (/\brandom\b/i.test(text)) + return { action: "random", speed: lastSpeed, step, seed: hash(JSON.stringify(messages.slice(0, last + 1))) } + return pick("long") +} + +function userText(message: { content?: unknown }) { + if (typeof message.content === "string") return message.content + if (!Array.isArray(message.content)) return "" + return message.content.map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n") +} + +function hash(value: string) { + let result = 2166136261 + for (let index = 0; index < value.length; index++) result = Math.imul(result ^ value.charCodeAt(index), 16777619) + return result >>> 0 +} + +// A 5–10 s turn at 1×: reasoning, then three to five tool steps (one to three shells, often a patch and parallel +// reads, sometimes a background subagent or shell) with prose, lists and code between them, then a summary. The +// seed fixes the plan, so every request in the turn rebuilds the same one and plays its next step. +function randomTurn(seed: number, step: number, speed: number, directory: string) { + // The plan comes from the turn's seed; each step's text from its own, so steps never repeat each other. + const plan = mulberry(seed) + const random = mulberry(seed ^ Math.imul(step + 1, 0x9e3779b9)) + const int = (min: number, max: number, source = random) => min + Math.floor(source() * (max - min + 1)) + const one = (items: readonly T[]) => items[int(0, items.length - 1)] + const some = (items: readonly T[], count: number) => + items + .map((item) => ({ item, key: random() })) + .toSorted((a, b) => a.key - b.key) + .slice(0, count) + .map((entry) => entry.item) + const bursty = plan() < 0.5 + const stream = (value: string) => + bursty + ? Llm.text(value, { delay: int(25, 40) / speed, chunkSize: int(12, 28) }) + : Llm.text(value, { delay: 10 / speed, chunkSize: 10 }) + const pause = () => (bursty ? [Llm.pause(int(100, 300) / speed)] : []) + const call = (name: string, input: Record, index = 0) => + Llm.toolCall({ index, id: `call_${crypto.randomUUID().replaceAll("-", "")}`, name, input }) + const prose = () => `${some(sentences, int(3, 5)).join(" ")}\n\n` + const list = () => + `${one(headings)}\n\n${some(items, int(3, 6)) + .map((item, index) => `${index + 1}. ${item}`) + .join("\n")}\n\n` + const block = () => `${one(intros)}\n\n\`\`\`ts\n${one(snippets)}\n\`\`\`\n\n` + const piece = () => one([prose, prose, list, block])() + const lead = (first: boolean) => [ + ...(first ? [Llm.reasoning(one(thoughts), { delay: 14 / speed, chunkSize: 6 }), ...pause()] : []), + ...Array.from({ length: int(1, 2) }, () => [stream(piece()), ...pause()]).flat(), + ] + + const picked = [ + ...Array.from({ length: int(1, 3, plan) }, () => "shell"), + ...(plan() < 0.7 ? ["patch"] : []), + ...(plan() < 0.7 ? ["reads"] : []), + ...(plan() < 0.35 ? [plan() < 0.5 ? "subagent" : "background"] : []), + ] + // At least three tool steps, so even a short plan scrolls past a screen. + const kinds = [...picked, ...["patch", "reads"].filter((kind) => !picked.includes(kind))] + .slice(0, Math.max(3, picked.length)) + .toSorted(() => plan() - 0.5) + .slice(0, 5) + const kind = kinds[step] + if (kind === undefined) return Stream.make(stream(`${one(summaries)}\n\n${prose()}${random() < 0.5 ? list() : ""}`)) + const outputs = lead(step === 0) + const tools = (...calls: Llm.Output[]) => Stream.make(...outputs, ...calls, Llm.finish("tool-calls")) + if (kind === "shell") { + const label = one(["lanterns", "tides", "charts", "moorings", "beacons"]) + return tools( + stream(`Building the ${label}.`), + call("shell", { + command: `sh scripts/build.sh ${int(6, 12)} ${speed} ${label}`, + description: `Build ${label}`, + workdir: directory, + }), + ) + } + if (kind === "patch") + return tools(stream("Retiming the North Mole lantern."), call("patch", { patchText: patch(directory) })) + if (kind === "reads") + return tools( + stream("Reading the harbor files."), + ...files.slice(0, int(2, files.length)).map((file, at) => call("read", { path: `${directory}/${file}` }, at)), + ) + if (kind === "subagent") + return tools( + call("subagent", { + agent: "surveyor", + description: "Survey the breakwater", + prompt: `[demo:child ${speed}×] Walk the breakwater and report any loose stones.`, + background: true, + }), + ) + return tools( + call("shell", { + command: `sh scripts/preview.sh ${speed}`, + description: "Lantern preview", + workdir: directory, + background: true, + }), + ) +} + +function mulberry(seed: number) { + let state = seed + return () => { + state = (state + 0x6d2b79f5) | 0 + let value = Math.imul(state ^ (state >>> 15), 1 | state) + value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value + return ((value ^ (value >>> 14)) >>> 0) / 4294967296 + } +} + +const files = ["README.md", "src/harbor.ts", "src/tides.ts", "src/fleet.ts", "docs/pilots.md"] + +const thoughts = [ + "Working out which lanterns drift out of phase before the spring tide, and what to rebuild first.", + "The pilot boat leaves two hours before high water, so the beacon map has to be current by then.", + "Checking the mooring charts against last week's survey before touching the lantern config.", +] + +const sentences = [ + "The North Mole lantern runs on a four second interval, and the Lantern Quay on six.", + "Fog usually lifts in layers here: masts first, then the net sheds, then the breakwater.", + "The tide tables in the pilot's hut lag the gauges by a few minutes every morning.", + "Two capstones near the East Buoy shifted during the last storm and need resetting.", + "Fishing boats slip their moorings while the lanterns along the mole are still turning.", + "The harbor master wants every beacon in phase before the pilot boat leaves.", + "Spring tides bring the water within a hand's width of the quay steps.", + "The beacon map rebuilds whenever a lantern's interval or colour changes.", + "Gannet and Kittiwake share the inner berth, so their mooring lines cross at low water.", + "The saltmarsh gate only opens in the hour either side of high water.", + "Most of the fleet is back before noon, when the wind turns onshore.", + "The amber lanterns read better through fog than the old white ones did.", +] + +const headings = ["**Next steps**", "**What changed**", "**Before the spring tide**", "**Open questions**"] + +const items = [ + "Reset the two capstones by the East Buoy at the next low tide.", + "Bring the Lantern Quay into phase with the North Mole.", + "Repaint the pilot steps before the equinox.", + "Check the saltmarsh gate hinges after the storm.", + "Move Shearwater to the outer berth for the week.", + "Re-run the tide checks once the new gauge is fitted.", + "Swap the last white lantern for amber.", + "Add the breakwater survey to the harbor log.", +] + +const intros = ["The schedule helper now reads:", "Here is the phase check:", "The berth assignment looks like this:"] + +const snippets = [ + [ + "export function nextFlash(lantern: { intervalMs: number; offsetMs: number }, now: number) {", + " const elapsed = (now - lantern.offsetMs) % lantern.intervalMs", + " return now + lantern.intervalMs - elapsed", + "}", + ].join("\n"), + [ + "export const inPhase = (a: Lantern, b: Lantern) =>", + " a.intervalMs === b.intervalMs && a.offsetMs === b.offsetMs", + "", + "export function drift(lanterns: Lantern[]) {", + " return lanterns.filter((lantern) => !inPhase(lantern, lanterns[0]))", + "}", + ].join("\n"), + [ + "const berths = new Map([", + ' ["inner", ["Gannet", "Kittiwake"]],', + ' ["outer", ["Shearwater"]],', + "])", + "", + "export function berthOf(boat: string) {", + " return [...berths].find(([, boats]) => boats.includes(boat))?.[0]", + "}", + ].join("\n"), +] + +const summaries = [ + "All the lanterns are rebuilt and in phase, and the tide checks pass.", + "The beacon map is current, the patch is in, and the builds are clean.", + "Everything the pilot boat needs is ready ahead of high water.", +] + +// Drive's SDK client trails the server protocol, so the session is created over plain HTTP with the isolated +// server's own registration. +async function createSession(artifacts: string, directory: string) { + const registration: { url: string; password?: string } = await Bun.file( + `${artifacts}/home/.local/state/opencode/service-local.json`, + ).json() + const headers = { + "content-type": "application/json", + ...(registration.password ? { authorization: `Basic ${btoa(`opencode:${registration.password}`)}` } : {}), + } + const response = await fetch(`${registration.url}/api/session`, { + method: "POST", + headers, + // An explicit agent and model, so the composer can send before it has resolved the defaults. + body: JSON.stringify({ + title: "Timeline demo", + location: { directory }, + agent: "build", + model: { providerID: "simulation", id: "gpt-sim-model" }, + }), + }) + const created = (await response.json()) as { data: { id: string } } + return { id: created.data.id, server: registration } +}