mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(session-ui): drive markdown readiness, steer grow-in and tool status titles through state machines (#61977)
This commit is contained in:
committed by
GitHub
Unverified
parent
af5d3b531d
commit
883249d729
@@ -0,0 +1,95 @@
|
||||
import type { Page } from "@playwright/test"
|
||||
import { expect, sourceURL, story } from "../../stories/playwright/story"
|
||||
|
||||
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", "")
|
||||
})
|
||||
|
||||
// The timeline observes data-markdown-ready, so each change of the attribute is a record here.
|
||||
function recordReadiness(page: Page) {
|
||||
return page.evaluateHandle(() => {
|
||||
const markdown = document.querySelector('[data-testid="markdown-fixture"] [data-component="markdown"]')!
|
||||
const changes: boolean[] = []
|
||||
|
||||
const observer = new MutationObserver((records) =>
|
||||
records.forEach((record) => changes.push(record.oldValue === null)),
|
||||
)
|
||||
|
||||
observer.observe(markdown, { attributes: true, attributeFilter: ["data-markdown-ready"], attributeOldValue: true })
|
||||
|
||||
// `true` adds the attribute, `false` removes it.
|
||||
return () => {
|
||||
observer.takeRecords().forEach((record) => changes.push(record.oldValue === null))
|
||||
|
||||
return changes
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
story("keeps completed Markdown ready when an unrelated input reruns its render", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "```sh\necho hello\n```" })
|
||||
}, fixture)
|
||||
const harness = page.getByTestId("markdown-fixture")
|
||||
const markdown = harness.locator('[data-component="markdown"]')
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
const readiness = await recordReadiness(page)
|
||||
|
||||
await harness.getByLabel("German").check()
|
||||
await expect(markdown.getByRole("button", { name: "Kopieren" })).toHaveCount(1)
|
||||
// Before the machine, every rerun removed the attribute and added it again.
|
||||
expect(await readiness.evaluate((changes) => changes())).toEqual([])
|
||||
await readiness.dispose()
|
||||
})
|
||||
|
||||
story("does not report a finished stream ready before its settled render checks paths", async ({ page }) => {
|
||||
const check = await page.evaluateHandle(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
const exists = Promise.withResolvers<boolean>()
|
||||
const requested: string[] = []
|
||||
await mountMarkdown({
|
||||
text: "Edit `src/file.ts`",
|
||||
streaming: true,
|
||||
localFileExists: (path: string) => {
|
||||
requested.push(path)
|
||||
|
||||
return exists.promise
|
||||
},
|
||||
})
|
||||
|
||||
return { requested, resolve: () => exists.resolve(true) }
|
||||
}, fixture)
|
||||
|
||||
const harness = page.getByTestId("markdown-fixture")
|
||||
const markdown = harness.locator('[data-component="markdown"]')
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
const readiness = await recordReadiness(page)
|
||||
|
||||
await harness.getByLabel("Streaming").uncheck()
|
||||
await expect.poll(() => check.evaluate((state) => state.requested)).toEqual(["src/file.ts"])
|
||||
await expect(markdown).not.toHaveAttribute("data-markdown-ready")
|
||||
await check.evaluate((state) => state.resolve())
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(markdown.locator('code[data-inline-code-kind="path"]')).toHaveText("src/file.ts")
|
||||
// Before the machine, the last live render reported ready again before the settled render started its check.
|
||||
expect(await readiness.evaluate((changes) => changes())).toEqual([false, true])
|
||||
await readiness.dispose()
|
||||
await check.dispose()
|
||||
})
|
||||
|
||||
story("reports completed Markdown ready when an inline path check never settles", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "Edit `src/file.ts`", localFileExists: () => new Promise<boolean>(() => {}) })
|
||||
}, fixture)
|
||||
const markdown = page.getByTestId("markdown-fixture").locator('[data-component="markdown"]')
|
||||
await expect(markdown.locator("code")).toHaveText("src/file.ts")
|
||||
await expect(markdown).not.toHaveAttribute("data-markdown-ready")
|
||||
// The check gives up after 2 s and leaves the path as plain code.
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(markdown.locator("code")).not.toHaveAttribute("data-inline-code-kind")
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import { render } from "solid-js/web"
|
||||
import { ToolStatusTitle } from "../src/components/tool-status-title"
|
||||
|
||||
export function mountToolStatusTitle() {
|
||||
const host = document.createElement("div")
|
||||
host.dataset.testid = "tool-status-title-fixture"
|
||||
document.body.appendChild(host)
|
||||
const [active, setActive] = createSignal(true)
|
||||
const [hidden, setHidden] = createSignal(false)
|
||||
|
||||
render(
|
||||
() => (
|
||||
<div style={{ display: hidden() ? "none" : "block" }}>
|
||||
<ToolStatusTitle active={active()} activeText="Exploring" doneText="Explored" split={false} />
|
||||
</div>
|
||||
),
|
||||
host,
|
||||
)
|
||||
|
||||
return { setActive, setHidden }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { expect, sourceURL, story } from "../../stories/playwright/story"
|
||||
|
||||
const fixture = sourceURL(new URL("./tool-status-title.fixture.tsx", import.meta.url))
|
||||
|
||||
story("shows a title that finished in a hidden tab at once when the tab shows again", async ({ mount, page }) => {
|
||||
await mount("components-animated-count-list--completed")
|
||||
|
||||
const width = await page.evaluate(async (fixture) => {
|
||||
const { mountToolStatusTitle } = await import(fixture)
|
||||
const title = mountToolStatusTitle()
|
||||
title.setHidden(true)
|
||||
title.setActive(false)
|
||||
// The title measures its new width on the next frame.
|
||||
await new Promise(requestAnimationFrame)
|
||||
await new Promise(requestAnimationFrame)
|
||||
title.setHidden(false)
|
||||
|
||||
return document.querySelector<HTMLElement>(
|
||||
'[data-testid="tool-status-title-fixture"] [data-slot="tool-status-swap"]',
|
||||
)!.style.width
|
||||
}, fixture)
|
||||
|
||||
// Before the machine, the hidden title measured 0px and kept that width, clipping "Explored" for 600 ms.
|
||||
expect(width).toBe("")
|
||||
const title = page.getByTestId("tool-status-title-fixture").locator('[data-component="tool-status-title"]')
|
||||
await expect(title).toHaveAttribute("data-ready", "false")
|
||||
await expect(title).toHaveAttribute("aria-label", "Explored")
|
||||
await expect(title.locator('[data-slot="tool-status-done"]')).toBeVisible()
|
||||
await expect(title.locator('[data-slot="tool-status-active"]')).toHaveCount(0)
|
||||
})
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createMarkdownPhaseState,
|
||||
DISPOSED_MARKDOWN_PHASE_EVENT,
|
||||
DISPOSED_MARKDOWN_PHASE_STATE,
|
||||
markdownMode,
|
||||
markdownReady,
|
||||
transitionMarkdownPhase,
|
||||
type MarkdownPhaseEvent,
|
||||
type MarkdownPhaseState,
|
||||
} from "./markdown-phase-machine"
|
||||
|
||||
function replay(events: MarkdownPhaseEvent[], state: MarkdownPhaseState) {
|
||||
return events.reduce(transitionMarkdownPhase, state)
|
||||
}
|
||||
|
||||
const rendered = (pendingChecks = 0, reused = false): MarkdownPhaseEvent => ({
|
||||
type: "dom.rendered",
|
||||
rendered: true,
|
||||
pendingChecks,
|
||||
reused,
|
||||
})
|
||||
|
||||
const stale: MarkdownPhaseEvent = { type: "dom.rendered", rendered: false, pendingChecks: 0, reused: false }
|
||||
|
||||
describe("transitionMarkdownPhase", () => {
|
||||
test("keeps a completed render ready through unrelated effect runs", () => {
|
||||
const ready = transitionMarkdownPhase(createMarkdownPhaseState(false), rendered())
|
||||
|
||||
expect(markdownReady(ready)).toBe(true)
|
||||
// Before the machine, every rerun (a language, plugin or session title change) removed and re-added the attribute.
|
||||
expect(transitionMarkdownPhase(ready, rendered(0, true))).toBe(ready)
|
||||
expect(transitionMarkdownPhase(ready, rendered(1, true))).toBe(ready)
|
||||
})
|
||||
|
||||
test("waits for the settled render after a stream ends instead of reporting the last live render", () => {
|
||||
const streaming = transitionMarkdownPhase(createMarkdownPhaseState(true), rendered())
|
||||
|
||||
expect(streaming).toEqual({ status: "ready", mode: "streaming", attempts: 0 })
|
||||
|
||||
const ended = transitionMarkdownPhase(streaming, { type: "props.sync", streaming: false })
|
||||
|
||||
expect(ended).toEqual({ status: "pending", mode: "settled", attempts: 0 })
|
||||
expect(markdownReady(ended)).toBe(false)
|
||||
// The live render still matches the text, but the driver reports it as not rendered for the settled mode.
|
||||
expect(transitionMarkdownPhase(ended, stale)).toBe(ended)
|
||||
|
||||
const checking = transitionMarkdownPhase(ended, rendered(1))
|
||||
|
||||
expect(checking).toEqual({ status: "checking", mode: "settled", attempt: 1 })
|
||||
expect(transitionMarkdownPhase(checking, { type: "checks.settled", attempt: 1 })).toEqual({
|
||||
status: "ready",
|
||||
mode: "settled",
|
||||
attempts: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("reports ready when an inline path check never settles", () => {
|
||||
const checking = transitionMarkdownPhase(createMarkdownPhaseState(false), rendered(1))
|
||||
|
||||
expect(checking).toEqual({ status: "checking", mode: "static", attempt: 1 })
|
||||
expect(markdownReady(transitionMarkdownPhase(checking, { type: "checks.timed-out", attempt: 1 }))).toBe(true)
|
||||
})
|
||||
|
||||
test("ignores checks of a replaced render and keeps a running check through unrelated reruns", () => {
|
||||
const first = transitionMarkdownPhase(createMarkdownPhaseState(false), rendered(1))
|
||||
|
||||
expect(transitionMarkdownPhase(first, rendered(1, true))).toBe(first)
|
||||
|
||||
const second = transitionMarkdownPhase(first, rendered(1))
|
||||
|
||||
expect(second).toEqual({ status: "checking", mode: "static", attempt: 2 })
|
||||
expect(transitionMarkdownPhase(second, { type: "checks.settled", attempt: 1 })).toBe(second)
|
||||
expect(transitionMarkdownPhase(second, { type: "checks.timed-out", attempt: 1 })).toBe(second)
|
||||
expect(transitionMarkdownPhase(second, { type: "checks.settled", attempt: 2 })).toEqual({
|
||||
status: "ready",
|
||||
mode: "static",
|
||||
attempts: 2,
|
||||
})
|
||||
})
|
||||
|
||||
test("leaves a check when the render goes stale or the text starts streaming", () => {
|
||||
const checking = transitionMarkdownPhase(createMarkdownPhaseState(false), rendered(1))
|
||||
const pending = transitionMarkdownPhase(checking, stale)
|
||||
|
||||
expect(pending).toEqual({ status: "pending", mode: "static", attempts: 1 })
|
||||
expect(transitionMarkdownPhase(pending, { type: "checks.settled", attempt: 1 })).toBe(pending)
|
||||
// The next check gets a new attempt, so the first one cannot settle it.
|
||||
expect(transitionMarkdownPhase(pending, rendered(1, true))).toEqual({
|
||||
status: "checking",
|
||||
mode: "static",
|
||||
attempt: 2,
|
||||
})
|
||||
|
||||
const streaming = transitionMarkdownPhase(checking, { type: "props.sync", streaming: true })
|
||||
|
||||
expect(streaming).toEqual({ status: "pending", mode: "streaming", attempts: 1 })
|
||||
expect(transitionMarkdownPhase(streaming, { type: "checks.settled", attempt: 1 })).toBe(streaming)
|
||||
})
|
||||
|
||||
test("never waits for path checks while streaming", () => {
|
||||
expect(transitionMarkdownPhase(createMarkdownPhaseState(true), rendered(2))).toEqual({
|
||||
status: "ready",
|
||||
mode: "streaming",
|
||||
attempts: 0,
|
||||
})
|
||||
})
|
||||
|
||||
test("returns the same frozen states on every streamed delta", () => {
|
||||
const streaming = createMarkdownPhaseState(true)
|
||||
const ready = transitionMarkdownPhase(streaming, rendered())
|
||||
const sync: MarkdownPhaseEvent = { type: "props.sync", streaming: true }
|
||||
|
||||
const states = Array.from({ length: 100 }, () => [
|
||||
transitionMarkdownPhase(ready, stale),
|
||||
transitionMarkdownPhase(streaming, rendered()),
|
||||
transitionMarkdownPhase(ready, sync),
|
||||
]).flat()
|
||||
|
||||
expect(Object.isFrozen(streaming) && Object.isFrozen(ready)).toBe(true)
|
||||
expect(states.every((state, index) => state === [streaming, ready, ready][index % 3])).toBe(true)
|
||||
})
|
||||
|
||||
test("names the mode the driver disposes the worker projection by, and ignores events after disposal", () => {
|
||||
const fixed = transitionMarkdownPhase(createMarkdownPhaseState(false), rendered())
|
||||
const streamed = replay([rendered(), { type: "props.sync", streaming: false }], createMarkdownPhaseState(true))
|
||||
|
||||
expect(markdownMode(fixed)).toBe("static")
|
||||
expect(markdownMode(streamed)).toBe("settled")
|
||||
expect(transitionMarkdownPhase(streamed, DISPOSED_MARKDOWN_PHASE_EVENT)).toBe(DISPOSED_MARKDOWN_PHASE_STATE)
|
||||
expect(transitionMarkdownPhase(DISPOSED_MARKDOWN_PHASE_STATE, rendered())).toBe(DISPOSED_MARKDOWN_PHASE_STATE)
|
||||
expect(transitionMarkdownPhase(DISPOSED_MARKDOWN_PHASE_STATE, { type: "props.sync", streaming: true })).toBe(
|
||||
DISPOSED_MARKDOWN_PHASE_STATE,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,102 @@
|
||||
/** A completed render waits this long for inline path checks before it reports ready anyway. */
|
||||
export const INLINE_PATH_CHECK_TIMEOUT_MS = 2_000
|
||||
|
||||
/**
|
||||
* `static` never streamed and renders its text in one pass. `streaming` projects each delta through the worker as live
|
||||
* blocks. `settled` streamed earlier and now projects the final text once more as completed blocks, so the streamed DOM
|
||||
* and the user's selection survive.
|
||||
*/
|
||||
export type MarkdownMode = "static" | "streaming" | "settled"
|
||||
|
||||
/**
|
||||
* Whether one Markdown component can report `data-markdown-ready`. `pending` waits for a render of the current text in
|
||||
* the current mode. `checking` has rendered a completed text and waits for its inline path checks, numbered `attempt`.
|
||||
* `ready` has rendered the current text and every check it needs. `attempts` counts started checks, so a check that
|
||||
* settles after another started is stale. Every streamed delta dispatches here, so an event that changes nothing returns
|
||||
* the same state, and every state with no started check is a frozen singleton.
|
||||
*/
|
||||
export type MarkdownPhaseState =
|
||||
| { readonly status: "pending"; readonly mode: MarkdownMode; readonly attempts: number }
|
||||
| { readonly status: "checking"; readonly mode: Exclude<MarkdownMode, "streaming">; readonly attempt: number }
|
||||
| { readonly status: "ready"; readonly mode: MarkdownMode; readonly attempts: number }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type MarkdownPhaseEvent =
|
||||
| { readonly type: "props.sync"; readonly streaming: boolean }
|
||||
| {
|
||||
readonly type: "dom.rendered"
|
||||
/** The DOM shows a finished render of the current text, made for the current mode. */
|
||||
readonly rendered: boolean
|
||||
/** Inline path checks the rendered blocks still wait for. */
|
||||
readonly pendingChecks: number
|
||||
/** Every block is the one the previous DOM pass rendered, so no new check started. */
|
||||
readonly reused: boolean
|
||||
}
|
||||
| { readonly type: "checks.settled"; readonly attempt: number }
|
||||
| { readonly type: "checks.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
const PENDING = {
|
||||
static: Object.freeze({ status: "pending", mode: "static", attempts: 0 }),
|
||||
streaming: Object.freeze({ status: "pending", mode: "streaming", attempts: 0 }),
|
||||
settled: Object.freeze({ status: "pending", mode: "settled", attempts: 0 }),
|
||||
} as const satisfies Record<MarkdownMode, MarkdownPhaseState>
|
||||
|
||||
const READY = {
|
||||
static: Object.freeze({ status: "ready", mode: "static", attempts: 0 }),
|
||||
streaming: Object.freeze({ status: "ready", mode: "streaming", attempts: 0 }),
|
||||
settled: Object.freeze({ status: "ready", mode: "settled", attempts: 0 }),
|
||||
} as const satisfies Record<MarkdownMode, MarkdownPhaseState>
|
||||
|
||||
export const DISPOSED_MARKDOWN_PHASE_STATE: MarkdownPhaseState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export const DISPOSED_MARKDOWN_PHASE_EVENT: MarkdownPhaseEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
export function createMarkdownPhaseState(streaming: boolean): MarkdownPhaseState {
|
||||
return streaming ? PENDING.streaming : PENDING.static
|
||||
}
|
||||
|
||||
export function transitionMarkdownPhase(state: MarkdownPhaseState, event: MarkdownPhaseEvent): MarkdownPhaseState {
|
||||
if (state.status === "disposed") return state
|
||||
|
||||
if (event.type === "disposed") return DISPOSED_MARKDOWN_PHASE_STATE
|
||||
const attempts = state.status === "checking" ? state.attempt : state.attempts
|
||||
|
||||
if (event.type === "props.sync") {
|
||||
if (event.streaming) return state.mode === "streaming" ? state : phase("pending", "streaming", attempts)
|
||||
|
||||
// The last live render is not the settled one: completed blocks still need their path checks.
|
||||
return state.mode === "streaming" ? phase("pending", "settled", attempts) : state
|
||||
}
|
||||
|
||||
if (event.type === "checks.settled" || event.type === "checks.timed-out") {
|
||||
if (state.status !== "checking" || event.attempt !== state.attempt) return state
|
||||
|
||||
return phase("ready", state.mode, state.attempt)
|
||||
}
|
||||
|
||||
if (!event.rendered) return state.status === "pending" ? state : phase("pending", state.mode, attempts)
|
||||
|
||||
// A streaming answer renders again on the next delta, so it never waits for path checks.
|
||||
if (state.mode === "streaming" || event.pendingChecks === 0)
|
||||
return state.status === "ready" ? state : phase("ready", state.mode, attempts)
|
||||
|
||||
// A pass that kept every block started no check, so the running check or a reached `ready` still holds.
|
||||
if (event.reused && state.status !== "pending") return state
|
||||
|
||||
return { status: "checking", mode: state.mode, attempt: attempts + 1 }
|
||||
}
|
||||
|
||||
export function markdownMode(state: MarkdownPhaseState): MarkdownMode {
|
||||
return state.status === "disposed" ? "static" : state.mode
|
||||
}
|
||||
|
||||
export function markdownReady(state: MarkdownPhaseState) {
|
||||
return state.status === "ready"
|
||||
}
|
||||
|
||||
function phase(status: "pending" | "ready", mode: MarkdownMode, attempts: number): MarkdownPhaseState {
|
||||
if (attempts === 0) return status === "pending" ? PENDING[mode] : READY[mode]
|
||||
|
||||
return { status, mode, attempts }
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { abort } from "@opencode/util/abort"
|
||||
import { checksum } from "@opencode/util/encode"
|
||||
import {
|
||||
type ComponentProps,
|
||||
createComputed,
|
||||
createEffect,
|
||||
createMemo,
|
||||
createResource,
|
||||
createSignal,
|
||||
createUniqueId,
|
||||
@@ -11,6 +13,7 @@ import {
|
||||
onCleanup,
|
||||
type Setter,
|
||||
splitProps,
|
||||
untrack,
|
||||
} from "solid-js"
|
||||
import { isServer, render } from "solid-js/web"
|
||||
import { Icon } from "@opencode/ui/icon"
|
||||
@@ -44,6 +47,15 @@ import {
|
||||
type CodeDecorationEffect,
|
||||
type CodeDecorationEvent,
|
||||
} from "./markdown-code-machine"
|
||||
import {
|
||||
createMarkdownPhaseState,
|
||||
DISPOSED_MARKDOWN_PHASE_EVENT,
|
||||
INLINE_PATH_CHECK_TIMEOUT_MS,
|
||||
markdownMode,
|
||||
markdownReady,
|
||||
transitionMarkdownPhase,
|
||||
type MarkdownPhaseEvent,
|
||||
} from "./markdown-phase-machine"
|
||||
import { renderMermaidSvg } from "./markdown-mermaid"
|
||||
import { createMarkdownRenderer } from "./markdown-solid"
|
||||
import {
|
||||
@@ -80,6 +92,8 @@ type RenderResult = {
|
||||
text: string
|
||||
blocks: RenderedBlock[]
|
||||
ready: boolean
|
||||
/** Rendered from a live projection, so a stream that ends still waits for its settled render. */
|
||||
live?: boolean
|
||||
}
|
||||
|
||||
const renderedCodeTokens = new WeakMap<HTMLDivElement, RenderedCodeState>()
|
||||
@@ -728,36 +742,75 @@ export function Markdown(
|
||||
let appliedLabels: CopyLabels | undefined
|
||||
// The code block languages the blocks were decorated for; false before the first run.
|
||||
let decoratedMatch: MarkdownCodeBlockMatch | undefined | false = false
|
||||
let streamed = false
|
||||
// Every streamed delta dispatches a rendered event, so the driver reuses its events and the machine returns the same
|
||||
// state when nothing changed.
|
||||
const [phase, setPhase] = createSignal(createMarkdownPhaseState(!!local.streaming))
|
||||
const mode = createMemo(() => markdownMode(phase()))
|
||||
const syncEvent = { type: "props.sync" as const, streaming: false }
|
||||
const renderedEvent = { type: "dom.rendered" as const, rendered: false, pendingChecks: 0, reused: false }
|
||||
let checkTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const dispatchPhase = (event: MarkdownPhaseEvent, checks?: Promise<void>[]) => {
|
||||
const previous = untrack(phase)
|
||||
const next = transitionMarkdownPhase(previous, event)
|
||||
|
||||
if (next === previous) return
|
||||
const started = next.status === "checking" && (previous.status !== "checking" || previous.attempt !== next.attempt)
|
||||
|
||||
if (previous.status === "checking" && (next.status !== "checking" || started)) {
|
||||
clearTimeout(checkTimer)
|
||||
checkTimer = undefined
|
||||
}
|
||||
|
||||
if (next.status === "disposed") {
|
||||
if (markdownMode(previous) !== "static") disposeMarkdownProjection(owner)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setPhase(next)
|
||||
// The timeline observes this attribute, and toggling it to its current value records no mutation.
|
||||
untrack(root)?.toggleAttribute("data-markdown-ready", markdownReady(next))
|
||||
|
||||
if (!started) return
|
||||
const attempt = next.attempt
|
||||
checkTimer = setTimeout(() => dispatchPhase({ type: "checks.timed-out", attempt }), INLINE_PATH_CHECK_TIMEOUT_MS)
|
||||
// Each check catches its own failure, so this always settles.
|
||||
void Promise.all(checks ?? []).then(() => dispatchPhase({ type: "checks.settled", attempt }))
|
||||
}
|
||||
|
||||
// Runs before the resources below read the mode, so a stream that ends never projects with the old mode.
|
||||
createComputed(() => {
|
||||
syncEvent.streaming = !!local.streaming
|
||||
dispatchPhase(syncEvent)
|
||||
})
|
||||
|
||||
const [projection] = createResource(
|
||||
() => {
|
||||
if (isServer) return
|
||||
const live = local.streaming ?? false
|
||||
if (isServer || mode() === "static") return
|
||||
|
||||
if (live) streamed = true
|
||||
|
||||
if (!live && !streamed) return
|
||||
|
||||
return { key: owner, text: local.text, live }
|
||||
return { key: owner, text: local.text, live: mode() === "streaming" }
|
||||
},
|
||||
// A failed projection renders the text unprojected, so the block still settles and the next delta projects again.
|
||||
// The result names the mode it was projected for, so a settled render never uses the last live projection.
|
||||
(src) =>
|
||||
projectMarkdown(src.key, src.text, src.live).catch((error) => {
|
||||
if (
|
||||
!(error instanceof MarkdownWorkerDisposedError) &&
|
||||
!(error instanceof MarkdownWorkerSupersededError) &&
|
||||
!(error instanceof MarkdownWorkerUnavailableError)
|
||||
)
|
||||
console.error("Markdown projection worker failed", error)
|
||||
projectMarkdown(src.key, src.text, src.live)
|
||||
.catch((error) => {
|
||||
if (
|
||||
!(error instanceof MarkdownWorkerDisposedError) &&
|
||||
!(error instanceof MarkdownWorkerSupersededError) &&
|
||||
!(error instanceof MarkdownWorkerUnavailableError)
|
||||
)
|
||||
console.error("Markdown projection worker failed", error)
|
||||
|
||||
return src.live ? pendingProjection(src.text) : completedProjection(src.text)
|
||||
}),
|
||||
{ initialValue: pendingProjection("") },
|
||||
return src.live ? pendingProjection(src.text) : completedProjection(src.text)
|
||||
})
|
||||
.then((value) => ({ text: value.text, blocks: value.blocks, live: src.live })),
|
||||
{ initialValue: { text: "", blocks: [], live: true } },
|
||||
)
|
||||
|
||||
const currentProjection = () => {
|
||||
if (!(local.streaming ?? false) && !streamed) return completedProjection(local.text)
|
||||
if (mode() === "static") return completedProjection(local.text)
|
||||
const value = projection.latest
|
||||
|
||||
if (value?.text === local.text) return value
|
||||
@@ -767,13 +820,16 @@ export function Markdown(
|
||||
return pendingProjection(local.text)
|
||||
}
|
||||
|
||||
const initial = initialResult(
|
||||
local.text,
|
||||
local.cacheKey,
|
||||
local.streaming ? pendingProjection(local.text) : completedProjection(local.text),
|
||||
owner,
|
||||
local.deferUntilReady,
|
||||
)
|
||||
const initial = {
|
||||
...initialResult(
|
||||
local.text,
|
||||
local.cacheKey,
|
||||
local.streaming ? pendingProjection(local.text) : completedProjection(local.text),
|
||||
owner,
|
||||
local.deferUntilReady,
|
||||
),
|
||||
live: !!local.streaming,
|
||||
}
|
||||
|
||||
const [html] = createResource(
|
||||
() => {
|
||||
@@ -781,23 +837,31 @@ export function Markdown(
|
||||
return {
|
||||
text: local.text,
|
||||
key: local.cacheKey,
|
||||
mode: "static" as const,
|
||||
projection: pendingProjection(local.text),
|
||||
}
|
||||
const value = !(local.streaming ?? false) && !streamed ? completedProjection(local.text) : projection.latest
|
||||
|
||||
if (!value || value.text !== local.text) return
|
||||
if (mode() === "static")
|
||||
return { text: local.text, key: local.cacheKey, mode: mode(), projection: completedProjection(local.text) }
|
||||
const value = projection.latest
|
||||
|
||||
if (value.text !== local.text || value.live !== (mode() === "streaming")) return
|
||||
|
||||
return {
|
||||
text: local.text,
|
||||
key: local.cacheKey,
|
||||
mode: mode(),
|
||||
projection: value,
|
||||
}
|
||||
},
|
||||
(src): RenderResult | Promise<RenderResult> => {
|
||||
const live = src.mode === "streaming"
|
||||
|
||||
if (isServer)
|
||||
return {
|
||||
text: src.text,
|
||||
ready: true,
|
||||
live,
|
||||
blocks: [
|
||||
{
|
||||
key: "server",
|
||||
@@ -809,11 +873,11 @@ export function Markdown(
|
||||
],
|
||||
} satisfies RenderResult
|
||||
|
||||
if (!src.text) return { text: src.text, blocks: [], ready: true } satisfies RenderResult
|
||||
if (!src.text) return { text: src.text, blocks: [], ready: true, live } satisfies RenderResult
|
||||
|
||||
if (!streamed && initial.ready && initial.text === src.text) return initial
|
||||
if (src.mode === "static" && initial.ready && initial.text === src.text) return initial
|
||||
|
||||
const base = src.key ?? (!streamed ? checksum(src.text) : undefined)
|
||||
const base = src.key ?? (src.mode === "static" ? checksum(src.text) : undefined)
|
||||
|
||||
const render = async (block: Block, index: number): Promise<RenderedBlock> => {
|
||||
const key = base ? `${base}:${index}:${block.mode}` : undefined
|
||||
@@ -893,15 +957,16 @@ export function Markdown(
|
||||
const blocks = queued.map((item, index) => (item instanceof Promise ? resolved.get(index)! : item))
|
||||
lastRender = { base, blocks: src.projection.blocks, rendered: blocks }
|
||||
|
||||
return { text: src.text, blocks, ready: true } satisfies RenderResult
|
||||
return { text: src.text, blocks, ready: true, live } satisfies RenderResult
|
||||
})
|
||||
.catch(
|
||||
() =>
|
||||
(lifetime.signal.aborted
|
||||
? { text: src.text, blocks: [], ready: false }
|
||||
? { text: src.text, blocks: [], ready: false, live }
|
||||
: {
|
||||
text: src.text,
|
||||
ready: true,
|
||||
live,
|
||||
blocks: [
|
||||
{
|
||||
key: base ?? "fallback",
|
||||
@@ -941,7 +1006,6 @@ export function Markdown(
|
||||
images = readImage ? createMarkdownImages(readImage) : undefined
|
||||
}
|
||||
|
||||
delete container.dataset.markdownReady
|
||||
const codeBlocks = markdown?.codeBlocks
|
||||
const match = codeBlocks?.current()
|
||||
|
||||
@@ -952,15 +1016,17 @@ export function Markdown(
|
||||
|
||||
const redecorate = decoratedMatch !== false && decoratedMatch !== match
|
||||
decoratedMatch = match
|
||||
renderedEvent.rendered = !!result?.ready && result.text === local.text && !!result.live === (mode() === "streaming")
|
||||
|
||||
if (content.length === 0) {
|
||||
renderedEvent.reused = renderedBlocks.length === 0
|
||||
renderedBlocks = []
|
||||
disposeCodeHosts(container)
|
||||
disposeRenderedMarkdown(container)
|
||||
container.innerHTML = ""
|
||||
images?.update(container)
|
||||
|
||||
if (result?.ready && result.text === local.text) container.dataset.markdownReady = ""
|
||||
renderedEvent.pendingChecks = 0
|
||||
dispatchPhase(renderedEvent)
|
||||
|
||||
return
|
||||
}
|
||||
@@ -979,13 +1045,17 @@ export function Markdown(
|
||||
const sessionLinks = markdown?.sessionTitle
|
||||
const localFileExists = markdown?.localFileExists
|
||||
|
||||
renderedEvent.reused = content.length === renderedBlocks.length
|
||||
|
||||
const pending = content.flatMap((block, index) => {
|
||||
const current = container.children[index]
|
||||
const kept = renderedBlocks[index] === block && current instanceof HTMLDivElement
|
||||
|
||||
const check =
|
||||
renderedBlocks[index] === block && current instanceof HTMLDivElement
|
||||
? inlineCodeChecks.get(current)?.pending
|
||||
: updateBlock(container, index, block, labels, plugins, sessionLinks, lifetime.signal, localFileExists)
|
||||
if (!kept) renderedEvent.reused = false
|
||||
|
||||
const check = kept
|
||||
? inlineCodeChecks.get(current)?.pending
|
||||
: updateBlock(container, index, block, labels, plugins, sessionLinks, lifetime.signal, localFileExists)
|
||||
|
||||
return check ? [check] : []
|
||||
})
|
||||
@@ -1036,21 +1106,10 @@ export function Markdown(
|
||||
|
||||
if (!faviconCleanup) faviconCleanup = setupExternalLinkFavicons(container)
|
||||
container.toggleAttribute("data-local-links", !!markdown?.openLocalFile)
|
||||
|
||||
if (!result?.ready || result.text !== local.text) return
|
||||
|
||||
if (local.streaming || pending.length === 0) {
|
||||
container.dataset.markdownReady = ""
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Cold timelines already wait for Markdown readiness before measuring and revealing their content. Include
|
||||
// path classification so the first visible frame uses the final blue-link styling and padding.
|
||||
void Promise.all(pending).then(() => {
|
||||
if (lifetime.signal.aborted || renderedBlocks !== content || result.text !== local.text) return
|
||||
container.dataset.markdownReady = ""
|
||||
})
|
||||
renderedEvent.pendingChecks = pending.length
|
||||
dispatchPhase(renderedEvent, pending)
|
||||
})
|
||||
|
||||
onCleanup(() => {
|
||||
@@ -1070,7 +1129,7 @@ export function Markdown(
|
||||
|
||||
if (container) disposeRenderedMarkdown(container)
|
||||
|
||||
if (streamed) disposeMarkdownProjection(owner)
|
||||
dispatchPhase(DISPOSED_MARKDOWN_PHASE_EVENT)
|
||||
activeCodeKeys.forEach(disposeCode)
|
||||
completedCode.clear()
|
||||
settledMarkdown.clear()
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createToolStatusTitleState,
|
||||
DISPOSED_TOOL_STATUS_TITLE_EVENT,
|
||||
DISPOSED_TOOL_STATUS_TITLE_STATE,
|
||||
transitionToolStatusTitle,
|
||||
viewToolStatusTitle,
|
||||
type ToolStatusMode,
|
||||
type ToolStatusTitleState,
|
||||
} from "./tool-status-title-machine"
|
||||
|
||||
const idle = createToolStatusTitleState({ active: true, mode: "swap", text: "Exploring" })
|
||||
|
||||
const sync = (
|
||||
state: ToolStatusTitleState,
|
||||
input: { active: boolean; text: string; width: string | undefined; mode?: ToolStatusMode; reducedMotion?: boolean },
|
||||
) =>
|
||||
transitionToolStatusTitle(state, {
|
||||
type: "sync",
|
||||
active: input.active,
|
||||
mode: input.mode ?? "swap",
|
||||
text: input.text,
|
||||
width: input.width,
|
||||
reducedMotion: input.reducedMotion ?? false,
|
||||
})
|
||||
|
||||
describe("transitionToolStatusTitle", () => {
|
||||
test("animates from the current width to the measured one, then settles", () => {
|
||||
const measuring = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
|
||||
expect(measuring).toMatchObject({ status: "measuring", attempt: 1, from: "72px", crossfade: true })
|
||||
expect(viewToolStatusTitle(measuring)).toEqual({
|
||||
active: false,
|
||||
animating: true,
|
||||
width: "72px",
|
||||
showActive: true,
|
||||
showDone: true,
|
||||
})
|
||||
|
||||
const animating = transitionToolStatusTitle(measuring, { type: "measured", attempt: 1, width: "64px" })
|
||||
|
||||
expect(animating).toMatchObject({ status: "animating", attempt: 1, width: "64px" })
|
||||
expect(transitionToolStatusTitle(animating, { type: "settled", attempt: 1 })).toEqual({
|
||||
status: "idle",
|
||||
active: false,
|
||||
mode: "swap",
|
||||
text: "Explored",
|
||||
attempts: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("does not pin a 0px width in a hidden tab", () => {
|
||||
// Before the machine, a hidden title measured "0px" and kept that width, clipping the title for 600 ms.
|
||||
const hidden = sync(idle, { active: false, text: "Explored", width: undefined })
|
||||
|
||||
expect(hidden).toMatchObject({ status: "idle", active: false })
|
||||
expect(viewToolStatusTitle(hidden).width).toBeUndefined()
|
||||
|
||||
const measuring = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
|
||||
expect(transitionToolStatusTitle(measuring, { type: "measured", attempt: 1, width: undefined })).toMatchObject({
|
||||
status: "idle",
|
||||
attempts: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("ignores a change to the hidden text", () => {
|
||||
// Before the machine, a new done text while active mounted both texts and pinned the width for 600 ms.
|
||||
expect(sync(idle, { active: true, text: "Exploring", width: "72px" })).toBe(idle)
|
||||
})
|
||||
|
||||
test("snaps when the title switches between suffix and swap", () => {
|
||||
const measuring = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
const switched = sync(measuring, { active: false, text: "ed", width: "72px", mode: "suffix" })
|
||||
|
||||
expect(switched).toEqual({ status: "idle", active: false, mode: "suffix", text: "ed", attempts: 1 })
|
||||
expect(transitionToolStatusTitle(switched, { type: "measured", attempt: 1, width: "20px" })).toBe(switched)
|
||||
})
|
||||
|
||||
test("snaps under reduced motion", () => {
|
||||
expect(sync(idle, { active: false, text: "Explored", width: "72px", reducedMotion: true })).toMatchObject({
|
||||
status: "idle",
|
||||
active: false,
|
||||
})
|
||||
})
|
||||
|
||||
test("crossfades an active change at the same width but settles a same-width text change at once", () => {
|
||||
const flipped = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
|
||||
expect(transitionToolStatusTitle(flipped, { type: "measured", attempt: 1, width: "72px" })).toMatchObject({
|
||||
status: "animating",
|
||||
})
|
||||
|
||||
const renamed = sync(idle, { active: true, text: "Searching", width: "72px" })
|
||||
|
||||
expect(renamed).toMatchObject({ status: "measuring", crossfade: false })
|
||||
expect(transitionToolStatusTitle(renamed, { type: "measured", attempt: 1, width: "72px" })).toMatchObject({
|
||||
status: "idle",
|
||||
text: "Searching",
|
||||
})
|
||||
})
|
||||
|
||||
test("restarts on a reversal and ignores the earlier frame and timer", () => {
|
||||
const first = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
const second = sync(first, { active: true, text: "Exploring", width: "70px" })
|
||||
|
||||
expect(second).toMatchObject({ status: "measuring", attempt: 2, crossfade: true })
|
||||
expect(transitionToolStatusTitle(second, { type: "measured", attempt: 1, width: "64px" })).toBe(second)
|
||||
|
||||
const animating = transitionToolStatusTitle(second, { type: "measured", attempt: 2, width: "72px" })
|
||||
|
||||
expect(transitionToolStatusTitle(animating, { type: "settled", attempt: 1 })).toBe(animating)
|
||||
expect(transitionToolStatusTitle(idle, { type: "settled", attempt: 0 })).toBe(idle)
|
||||
})
|
||||
|
||||
test("stops after disposal", () => {
|
||||
const measuring = sync(idle, { active: false, text: "Explored", width: "72px" })
|
||||
const disposed = transitionToolStatusTitle(measuring, DISPOSED_TOOL_STATUS_TITLE_EVENT)
|
||||
|
||||
expect(disposed).toBe(DISPOSED_TOOL_STATUS_TITLE_STATE)
|
||||
expect(transitionToolStatusTitle(disposed, { type: "measured", attempt: 1, width: "64px" })).toBe(disposed)
|
||||
expect(sync(disposed, { active: true, text: "Exploring", width: "72px" })).toBe(disposed)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
/** How long the width and crossfade transitions keep both titles mounted. */
|
||||
export const TOOL_STATUS_ANIMATION_MS = 600
|
||||
|
||||
/** `suffix` animates only the differing tail after a shared prefix; `swap` animates the whole title. */
|
||||
export type ToolStatusMode = "suffix" | "swap"
|
||||
|
||||
type Shared = {
|
||||
readonly active: boolean
|
||||
readonly mode: ToolStatusMode
|
||||
/** The tail the user sees: the active text while active, the done text after. */
|
||||
readonly text: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A title that animates between its active and done text. `idle` shows one text at its natural width. `measuring` pins
|
||||
* the previous width for one frame with both texts mounted, `animating` transitions to the measured width until the
|
||||
* transition ends. `crossfade` keeps the animation even at an unchanged width, so the two texts still fade. `attempts`
|
||||
* counts started animations, so a frame or timer of an earlier one is stale.
|
||||
*/
|
||||
export type ToolStatusTitleState =
|
||||
| (Shared & { readonly status: "idle"; readonly attempts: number })
|
||||
| (Shared & {
|
||||
readonly status: "measuring"
|
||||
readonly attempt: number
|
||||
readonly from: string
|
||||
readonly crossfade: boolean
|
||||
})
|
||||
| (Shared & { readonly status: "animating"; readonly attempt: number; readonly width: string })
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type ToolStatusTitleEvent =
|
||||
| {
|
||||
readonly type: "sync"
|
||||
readonly active: boolean
|
||||
readonly mode: ToolStatusMode
|
||||
readonly text: string
|
||||
/** The current width, or `undefined` while the title is hidden, detached or has no width. */
|
||||
readonly width: string | undefined
|
||||
readonly reducedMotion: boolean
|
||||
}
|
||||
| {
|
||||
readonly type: "measured"
|
||||
readonly attempt: number
|
||||
/** The new text's width, or `undefined` while the title is hidden, detached or has no width. */
|
||||
readonly width: string | undefined
|
||||
}
|
||||
| { readonly type: "settled"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export const DISPOSED_TOOL_STATUS_TITLE_STATE: ToolStatusTitleState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export const DISPOSED_TOOL_STATUS_TITLE_EVENT: ToolStatusTitleEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
export function createToolStatusTitleState(input: Shared): ToolStatusTitleState {
|
||||
return { status: "idle", active: input.active, mode: input.mode, text: input.text, attempts: 0 }
|
||||
}
|
||||
|
||||
export function transitionToolStatusTitle(
|
||||
state: ToolStatusTitleState,
|
||||
event: ToolStatusTitleEvent,
|
||||
): ToolStatusTitleState {
|
||||
if (state.status === "disposed") return state
|
||||
|
||||
if (event.type === "disposed") return DISPOSED_TOOL_STATUS_TITLE_STATE
|
||||
const attempts = state.status === "idle" ? state.attempts : state.attempt
|
||||
|
||||
if (event.type === "sync") {
|
||||
// A change to the hidden text shows nothing new.
|
||||
if (event.active === state.active && event.mode === state.mode && event.text === state.text) return state
|
||||
|
||||
// A hidden title has no width to animate from, and a width from the other mode's container would jump the layout.
|
||||
if (!event.width || event.reducedMotion || event.mode !== state.mode)
|
||||
return { status: "idle", active: event.active, mode: event.mode, text: event.text, attempts }
|
||||
|
||||
return {
|
||||
status: "measuring",
|
||||
active: event.active,
|
||||
mode: event.mode,
|
||||
text: event.text,
|
||||
attempt: attempts + 1,
|
||||
from: event.width,
|
||||
crossfade: event.active !== state.active || state.status !== "idle",
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "measured") {
|
||||
if (state.status !== "measuring" || event.attempt !== state.attempt) return state
|
||||
|
||||
if (!event.width || (!state.crossfade && event.width === state.from))
|
||||
return { status: "idle", active: state.active, mode: state.mode, text: state.text, attempts: state.attempt }
|
||||
|
||||
return {
|
||||
status: "animating",
|
||||
active: state.active,
|
||||
mode: state.mode,
|
||||
text: state.text,
|
||||
attempt: state.attempt,
|
||||
width: event.width,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "animating" || event.attempt !== state.attempt) return state
|
||||
|
||||
return { status: "idle", active: state.active, mode: state.mode, text: state.text, attempts: state.attempt }
|
||||
}
|
||||
|
||||
export function viewToolStatusTitle(state: ToolStatusTitleState) {
|
||||
if (state.status === "disposed")
|
||||
return { active: false, animating: false, width: undefined, showActive: false, showDone: true }
|
||||
|
||||
if (state.status === "idle")
|
||||
return {
|
||||
active: state.active,
|
||||
animating: false,
|
||||
width: undefined,
|
||||
showActive: state.active,
|
||||
showDone: !state.active,
|
||||
}
|
||||
|
||||
// Both texts stay mounted so one fades out while the other fades in.
|
||||
return {
|
||||
active: state.active,
|
||||
animating: true,
|
||||
width: state.status === "measuring" ? state.from : state.width,
|
||||
showActive: true,
|
||||
showDone: true,
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,15 @@
|
||||
import { Show, createEffect, createMemo, on, onCleanup } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Show, createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js"
|
||||
import { TextShimmer } from "@opencode/ui/text-shimmer"
|
||||
import { prefersReducedMotion } from "@opencode/ui/motion"
|
||||
import {
|
||||
createToolStatusTitleState,
|
||||
DISPOSED_TOOL_STATUS_TITLE_EVENT,
|
||||
TOOL_STATUS_ANIMATION_MS,
|
||||
transitionToolStatusTitle,
|
||||
viewToolStatusTitle,
|
||||
type ToolStatusMode,
|
||||
type ToolStatusTitleEvent,
|
||||
} from "./tool-status-title-machine"
|
||||
|
||||
function common(active: string, done: string) {
|
||||
const a = Array.from(active)
|
||||
@@ -16,10 +25,12 @@ function common(active: string, done: string) {
|
||||
}
|
||||
}
|
||||
|
||||
// A title in a hidden tab or a detached row measures 0px; pinning that width would clip it until the animation ends.
|
||||
function contentWidth(el: HTMLSpanElement | undefined) {
|
||||
if (!el) return
|
||||
if (!el?.isConnected) return
|
||||
const width = Math.ceil(el.getBoundingClientRect().width)
|
||||
|
||||
return `${Math.ceil(el.getBoundingClientRect().width)}px`
|
||||
return width > 0 ? `${width}px` : undefined
|
||||
}
|
||||
|
||||
export function ToolStatusTitle(props: {
|
||||
@@ -38,82 +49,90 @@ export function ToolStatusTitle(props: {
|
||||
const prefixLen = createMemo(() => Array.from(split().prefix).length)
|
||||
const activeTail = createMemo(() => (suffix() ? split().active : props.activeText))
|
||||
const doneTail = createMemo(() => (suffix() ? split().done : props.doneText))
|
||||
const mode = createMemo<ToolStatusMode>(() => (suffix() ? "suffix" : "swap"))
|
||||
const text = createMemo(() => (props.active ? activeTail() : doneTail()))
|
||||
|
||||
const [state, setState] = createStore({
|
||||
active: props.active,
|
||||
animating: false,
|
||||
width: undefined as string | undefined,
|
||||
})
|
||||
const [machine, setMachine] = createSignal(
|
||||
createToolStatusTitleState({ active: props.active, mode: untrack(mode), text: untrack(text) }),
|
||||
)
|
||||
|
||||
const width = () => state.width
|
||||
const active = () => state.active
|
||||
const animating = () => state.animating
|
||||
const view = createMemo(() => viewToolStatusTitle(machine()))
|
||||
let activeRef: HTMLSpanElement | undefined
|
||||
let doneRef: HTMLSpanElement | undefined
|
||||
let widthRef: HTMLSpanElement | undefined
|
||||
let frame: number | undefined
|
||||
let finishTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const dispatch = (event: ToolStatusTitleEvent) => {
|
||||
const previous = untrack(machine)
|
||||
const next = transitionToolStatusTitle(previous, event)
|
||||
|
||||
if (next === previous) return
|
||||
|
||||
const finish = () => {
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
|
||||
if (finishTimer !== undefined) clearTimeout(finishTimer)
|
||||
clearTimeout(timer)
|
||||
frame = undefined
|
||||
finishTimer = undefined
|
||||
setState("animating", false)
|
||||
setState("width", undefined)
|
||||
timer = undefined
|
||||
|
||||
if (next.status === "disposed") return
|
||||
setMachine(next)
|
||||
|
||||
if (next.status === "measuring") {
|
||||
const attempt = next.attempt
|
||||
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
dispatch({ type: "measured", attempt, width: contentWidth(next.active ? activeRef : doneRef) })
|
||||
})
|
||||
}
|
||||
|
||||
if (next.status === "animating") {
|
||||
const attempt = next.attempt
|
||||
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined
|
||||
dispatch({ type: "settled", attempt })
|
||||
}, TOOL_STATUS_ANIMATION_MS)
|
||||
}
|
||||
}
|
||||
|
||||
const animate = () => {
|
||||
const first = contentWidth(widthRef)
|
||||
const next = props.active
|
||||
finish()
|
||||
setState("active", next)
|
||||
createEffect(
|
||||
on(
|
||||
[() => props.active, mode, text],
|
||||
() =>
|
||||
dispatch({
|
||||
type: "sync",
|
||||
active: props.active,
|
||||
mode: mode(),
|
||||
text: text(),
|
||||
width: contentWidth(widthRef),
|
||||
reducedMotion: prefersReducedMotion(),
|
||||
}),
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
|
||||
if (!first) return
|
||||
|
||||
setState("animating", true)
|
||||
setState("width", first)
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
const last = contentWidth(next ? activeRef : doneRef)
|
||||
|
||||
if (!last) {
|
||||
finish()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (first !== last) setState("width", last)
|
||||
finishTimer = setTimeout(finish, 600)
|
||||
})
|
||||
}
|
||||
|
||||
createEffect(on([() => props.active, activeTail, doneTail], () => animate(), { defer: true }))
|
||||
|
||||
onCleanup(() => {
|
||||
finish()
|
||||
})
|
||||
onCleanup(() => dispatch(DISPOSED_TOOL_STATUS_TITLE_EVENT))
|
||||
|
||||
return (
|
||||
<span
|
||||
data-component="tool-status-title"
|
||||
data-active={active() ? "true" : "false"}
|
||||
data-ready={animating() ? "true" : "false"}
|
||||
data-mode={suffix() ? "suffix" : "swap"}
|
||||
data-active={view().active ? "true" : "false"}
|
||||
data-ready={view().animating ? "true" : "false"}
|
||||
data-mode={mode()}
|
||||
class={props.class}
|
||||
aria-label={active() ? props.activeText : props.doneText}
|
||||
aria-label={view().active ? props.activeText : props.doneText}
|
||||
>
|
||||
<Show
|
||||
when={suffix()}
|
||||
fallback={
|
||||
<span data-slot="tool-status-swap" ref={widthRef} style={{ width: width() }}>
|
||||
<Show when={animating() || active()}>
|
||||
<span data-slot="tool-status-swap" ref={widthRef} style={{ width: view().width }}>
|
||||
<Show when={view().showActive}>
|
||||
<span data-slot="tool-status-active" ref={activeRef}>
|
||||
<TextShimmer text={activeTail()} active={active()} offset={0} />
|
||||
<TextShimmer text={activeTail()} active={view().active} offset={0} />
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={animating() || !active()}>
|
||||
<Show when={view().showDone}>
|
||||
<span data-slot="tool-status-done" ref={doneRef}>
|
||||
<TextShimmer text={doneTail()} active={false} offset={0} />
|
||||
</span>
|
||||
@@ -123,15 +142,15 @@ export function ToolStatusTitle(props: {
|
||||
>
|
||||
<span data-slot="tool-status-suffix">
|
||||
<span data-slot="tool-status-prefix">
|
||||
<TextShimmer text={split().prefix} active={active()} offset={0} />
|
||||
<TextShimmer text={split().prefix} active={view().active} offset={0} />
|
||||
</span>
|
||||
<span data-slot="tool-status-tail" ref={widthRef} style={{ width: width() }}>
|
||||
<Show when={animating() || active()}>
|
||||
<span data-slot="tool-status-tail" ref={widthRef} style={{ width: view().width }}>
|
||||
<Show when={view().showActive}>
|
||||
<span data-slot="tool-status-active" ref={activeRef}>
|
||||
<TextShimmer text={activeTail()} active={active()} offset={prefixLen()} />
|
||||
<TextShimmer text={activeTail()} active={view().active} offset={prefixLen()} />
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={animating() || !active()}>
|
||||
<Show when={view().showDone}>
|
||||
<span data-slot="tool-status-done" ref={doneRef}>
|
||||
<TextShimmer text={doneTail()} active={false} offset={prefixLen()} />
|
||||
</span>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Match,
|
||||
Show,
|
||||
Switch,
|
||||
createComputed,
|
||||
createEffect,
|
||||
createMemo,
|
||||
onCleanup,
|
||||
@@ -60,6 +61,12 @@ import {
|
||||
type ReasoningMode,
|
||||
} from "./projection"
|
||||
import { IDLE_TURN_PHASE, sameRef, viewTurnPhase } from "./turn-phase-machine"
|
||||
import {
|
||||
DISPOSED_STEER_ARRIVAL_EVENT,
|
||||
INITIAL_STEER_ARRIVAL_STATE,
|
||||
shouldGrowUserMessage,
|
||||
transitionSteerArrival,
|
||||
} from "./steer-arrival-machine"
|
||||
|
||||
const emptyAssistantMessages: SessionMessageAssistant[] = []
|
||||
|
||||
@@ -169,29 +176,44 @@ export function createSessionTimelineRowRenderer(input: {
|
||||
})
|
||||
})
|
||||
|
||||
// A steer sent while the timeline is open grows in. Messages already there when a session loads, and rows the
|
||||
// virtualizer remounts, appear as they are.
|
||||
const seen = { sessionID: "", ids: new Set<string>() }
|
||||
// A steer sent while the timeline is open grows in. Messages already there when a session loads, history loaded
|
||||
// above them, and rows the virtualizer remounts appear as they are. Every row change syncs here, so the driver reuses
|
||||
// its events and skips a sync whose inputs did not change.
|
||||
let arrivals = INITIAL_STEER_ARRIVAL_STATE
|
||||
const arrivalRendered = { type: "rendered" as const, messageID: "" }
|
||||
|
||||
const arrivals = createMemo(() => {
|
||||
const noRows: readonly TimelineRow.TimelineRow[] = []
|
||||
const arrivalSync = { type: "sync" as const, sessionID: "", rows: noRows, busy: false }
|
||||
|
||||
const syncArrivals = () => {
|
||||
const sessionID = input.sessionID()
|
||||
const loaded = seen.sessionID === sessionID && seen.ids.size > 0
|
||||
const arrived = new Set<string>()
|
||||
const rows = input.projection.rows()
|
||||
// The input's pending status lands after its row, so a message sent while the session works counts as a steer.
|
||||
const busy = input.status().type !== "idle"
|
||||
|
||||
if (seen.sessionID !== sessionID) seen.ids.clear()
|
||||
seen.sessionID = sessionID
|
||||
input.projection.rows().forEach((row) => {
|
||||
if (!Predicate.isTagged(row, "UserMessage") || seen.ids.has(row.userMessageID)) return
|
||||
seen.ids.add(row.userMessageID)
|
||||
if (sessionID === arrivalSync.sessionID && rows === arrivalSync.rows && busy === arrivalSync.busy) return
|
||||
arrivalSync.sessionID = sessionID
|
||||
arrivalSync.rows = rows
|
||||
arrivalSync.busy = busy
|
||||
arrivals = transitionSteerArrival(arrivals, arrivalSync)
|
||||
}
|
||||
|
||||
if (loaded) arrived.add(row.userMessageID)
|
||||
})
|
||||
|
||||
return arrived
|
||||
createComputed(syncArrivals)
|
||||
onCleanup(() => {
|
||||
arrivals = transitionSteerArrival(arrivals, DISPOSED_STEER_ARRIVAL_EVENT)
|
||||
})
|
||||
|
||||
// The input's pending status lands after its row, so a message sent while the session works counts as a steer.
|
||||
const arriving = (messageID: string) => untrack(() => arrivals().delete(messageID) && input.status().type !== "idle")
|
||||
// A row can render before the sync for the rows that hold it, so it syncs first.
|
||||
const arriving = (messageID: string) =>
|
||||
untrack(() => {
|
||||
syncArrivals()
|
||||
|
||||
if (!shouldGrowUserMessage(arrivals, messageID)) return false
|
||||
arrivalRendered.messageID = messageID
|
||||
arrivals = transitionSteerArrival(arrivals, arrivalRendered)
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
const run = (messageID: string) =>
|
||||
createMemo(() => runs().get(messageID), undefined, {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
DISPOSED_STEER_ARRIVAL_EVENT,
|
||||
DISPOSED_STEER_ARRIVAL_STATE,
|
||||
INITIAL_STEER_ARRIVAL_STATE,
|
||||
shouldGrowUserMessage,
|
||||
transitionSteerArrival,
|
||||
type SteerArrivalState,
|
||||
} from "./steer-arrival-machine"
|
||||
import { TimelineRow } from "./timeline-row"
|
||||
|
||||
const user = (id: string) => new TimelineRow.UserMessage({ userMessageID: id })
|
||||
|
||||
const assistant = (userMessageID: string, messageID: string) =>
|
||||
new TimelineRow.AssistantPart({
|
||||
userMessageID,
|
||||
group: { key: `${messageID}:text`, type: "part", ref: { messageID, partID: "text" } },
|
||||
previousAssistantPart: false,
|
||||
})
|
||||
|
||||
const sync = (state: SteerArrivalState, rows: TimelineRow.TimelineRow[], busy = true, sessionID = "ses_1") =>
|
||||
transitionSteerArrival(state, { type: "sync", sessionID, rows, busy })
|
||||
|
||||
const rendered = (state: SteerArrivalState, messageID: string) =>
|
||||
transitionSteerArrival(state, { type: "rendered", messageID })
|
||||
|
||||
const page = [user("m50"), assistant("m50", "a50")]
|
||||
|
||||
describe("transitionSteerArrival", () => {
|
||||
test("does not grow history loaded above the first page", () => {
|
||||
const loaded = sync(INITIAL_STEER_ARRIVAL_STATE, page)
|
||||
const paged = sync(loaded, [user("m10"), assistant("m10", "a10"), ...page])
|
||||
|
||||
// Before the machine, every prepended user message counted as a steer once the first page loaded.
|
||||
expect(shouldGrowUserMessage(paged, "m10")).toBe(false)
|
||||
expect(shouldGrowUserMessage(sync(paged, [...page, user("m51")]), "m51")).toBe(true)
|
||||
})
|
||||
|
||||
test("does not grow the user message of a truncated first turn when its history loads", () => {
|
||||
const loaded = sync(INITIAL_STEER_ARRIVAL_STATE, [assistant("m50", "a50")])
|
||||
const paged = sync(loaded, page)
|
||||
|
||||
expect(shouldGrowUserMessage(paged, "m50")).toBe(false)
|
||||
expect(shouldGrowUserMessage(sync(paged, [...page, user("m51")]), "m51")).toBe(true)
|
||||
})
|
||||
|
||||
test("keeps a steer through row updates until its row renders", () => {
|
||||
const steered = sync(sync(INITIAL_STEER_ARRIVAL_STATE, page), [...page, user("m51")])
|
||||
const updated = [1, 2, 3].reduce((state) => sync(state, [...page, user("m51"), assistant("m51", "a51")]), steered)
|
||||
|
||||
// Before the machine, the next row update recomputed the arrivals and dropped the unrendered steer.
|
||||
expect(shouldGrowUserMessage(updated, "m51")).toBe(true)
|
||||
|
||||
const shown = rendered(updated, "m51")
|
||||
|
||||
expect(shouldGrowUserMessage(shown, "m51")).toBe(false)
|
||||
expect(rendered(shown, "m51")).toBe(shown)
|
||||
})
|
||||
|
||||
test("never grows a prompt sent while idle or a steer left unrendered when the session went idle", () => {
|
||||
const loaded = sync(INITIAL_STEER_ARRIVAL_STATE, page)
|
||||
const prompted = sync(loaded, [...page, user("m51")], false)
|
||||
|
||||
expect(shouldGrowUserMessage(sync(prompted, [...page, user("m51")], true), "m51")).toBe(false)
|
||||
|
||||
const steered = sync(loaded, [...page, user("m51")])
|
||||
const idle = sync(steered, [...page, user("m51")], false)
|
||||
|
||||
// Before the machine, an offscreen prompt still grew in when the user scrolled to it during a later turn.
|
||||
expect(shouldGrowUserMessage(sync(idle, [...page, user("m51")], true), "m51")).toBe(false)
|
||||
})
|
||||
|
||||
test("does not grow the opener after a leading notice", () => {
|
||||
const notice = new TimelineRow.Notice({ userMessageID: "", messageID: "n1" })
|
||||
const empty = sync(INITIAL_STEER_ARRIVAL_STATE, [notice])
|
||||
|
||||
expect(shouldGrowUserMessage(sync(empty, [notice, user("m1")]), "m1")).toBe(false)
|
||||
})
|
||||
|
||||
test("returns the same state for row updates that add nothing", () => {
|
||||
const loaded = sync(INITIAL_STEER_ARRIVAL_STATE, page)
|
||||
const steered = sync(loaded, [...page, user("m51")])
|
||||
|
||||
expect(sync(loaded, [...page])).toBe(loaded)
|
||||
expect(sync(loaded, [...page], false)).toBe(loaded)
|
||||
expect(sync(steered, [...page, user("m51")])).toBe(steered)
|
||||
})
|
||||
|
||||
test("starts over on another session and stops after disposal", () => {
|
||||
const steered = sync(sync(INITIAL_STEER_ARRIVAL_STATE, page), [...page, user("m51")])
|
||||
const other = sync(steered, [user("m1"), user("m51")], true, "ses_2")
|
||||
|
||||
expect(shouldGrowUserMessage(other, "m51")).toBe(false)
|
||||
expect(shouldGrowUserMessage(other, "m1")).toBe(false)
|
||||
|
||||
const disposed = transitionSteerArrival(steered, DISPOSED_STEER_ARRIVAL_EVENT)
|
||||
|
||||
expect(disposed).toBe(DISPOSED_STEER_ARRIVAL_STATE)
|
||||
expect(sync(disposed, [...page, user("m52")])).toBe(disposed)
|
||||
expect(shouldGrowUserMessage(disposed, "m51")).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Predicate } from "effect"
|
||||
import type { TimelineRow } from "./timeline-row"
|
||||
|
||||
/**
|
||||
* Which user messages grow in as they render. `seen` holds the message IDs of the session's rows so far: user messages,
|
||||
* shells and assistant messages. A user message counts as a steer only when it lands below a seen row while the session
|
||||
* works, so the first page and history loaded above it appear as they are. `arriving` holds steers whose rows have not
|
||||
* rendered yet; rendering one, or the session going idle, removes it.
|
||||
*/
|
||||
export type SteerArrivalState =
|
||||
| {
|
||||
readonly status: "tracking"
|
||||
readonly sessionID: string
|
||||
readonly seen: ReadonlySet<string>
|
||||
readonly arriving: ReadonlySet<string>
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type SteerArrivalEvent =
|
||||
| {
|
||||
readonly type: "sync"
|
||||
readonly sessionID: string
|
||||
readonly rows: readonly TimelineRow.TimelineRow[]
|
||||
readonly busy: boolean
|
||||
}
|
||||
| { readonly type: "rendered"; readonly messageID: string }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
const EMPTY: ReadonlySet<string> = new Set()
|
||||
|
||||
export const INITIAL_STEER_ARRIVAL_STATE: SteerArrivalState = Object.freeze({
|
||||
status: "tracking",
|
||||
sessionID: "",
|
||||
seen: EMPTY,
|
||||
arriving: EMPTY,
|
||||
})
|
||||
|
||||
export const DISPOSED_STEER_ARRIVAL_STATE: SteerArrivalState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export const DISPOSED_STEER_ARRIVAL_EVENT: SteerArrivalEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
// Row projections run on every streamed change, so a sync that adds no row and keeps the steers returns the same state.
|
||||
export function transitionSteerArrival(state: SteerArrivalState, event: SteerArrivalEvent): SteerArrivalState {
|
||||
if (state.status === "disposed") return state
|
||||
|
||||
if (event.type === "disposed") return DISPOSED_STEER_ARRIVAL_STATE
|
||||
|
||||
if (event.type === "rendered") {
|
||||
if (!state.arriving.has(event.messageID)) return state
|
||||
const arriving = new Set(state.arriving)
|
||||
arriving.delete(event.messageID)
|
||||
|
||||
return { ...state, arriving }
|
||||
}
|
||||
|
||||
const rows = event.rows
|
||||
|
||||
if (event.sessionID !== state.sessionID)
|
||||
return {
|
||||
status: "tracking",
|
||||
sessionID: event.sessionID,
|
||||
seen: new Set(rows.flatMap((row) => rowAnchor(row) ?? [])),
|
||||
arriving: EMPTY,
|
||||
}
|
||||
|
||||
const unseen = rows.some((row) => {
|
||||
const anchor = rowAnchor(row)
|
||||
|
||||
return anchor !== undefined && !state.seen.has(anchor)
|
||||
})
|
||||
|
||||
if (!unseen && (event.busy || state.arriving.size === 0)) return state
|
||||
|
||||
const last = rows.findLastIndex((row) => {
|
||||
const anchor = rowAnchor(row)
|
||||
|
||||
return anchor !== undefined && state.seen.has(anchor)
|
||||
})
|
||||
|
||||
// With no seen row left to land below (a first page, or rows replaced wholesale), every row is history.
|
||||
const steers =
|
||||
event.busy && last >= 0
|
||||
? rows
|
||||
.slice(last + 1)
|
||||
.filter((row) => Predicate.isTagged(row, "UserMessage") && !state.seen.has(row.userMessageID))
|
||||
.map((row) => row.userMessageID)
|
||||
: []
|
||||
|
||||
return {
|
||||
status: "tracking",
|
||||
sessionID: state.sessionID,
|
||||
seen: unseen ? new Set([...state.seen, ...rows.flatMap((row) => rowAnchor(row) ?? [])]) : state.seen,
|
||||
arriving: !event.busy ? EMPTY : steers.length > 0 ? new Set([...state.arriving, ...steers]) : state.arriving,
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldGrowUserMessage(state: SteerArrivalState, messageID: string) {
|
||||
return state.status === "tracking" && state.arriving.has(messageID)
|
||||
}
|
||||
|
||||
// Each row stands for the message that produced it; message IDs are unique across user, shell and assistant messages.
|
||||
function rowAnchor(row: TimelineRow.TimelineRow) {
|
||||
if (Predicate.isTagged(row, "UserMessage")) return row.userMessageID
|
||||
|
||||
if (Predicate.isTagged(row, "Shell")) return row.messageID
|
||||
|
||||
if (Predicate.isTagged(row, "Thinking")) return row.ref.messageID
|
||||
|
||||
if (!Predicate.isTagged(row, "AssistantPart")) return
|
||||
|
||||
return row.group.type === "part" ? row.group.ref.messageID : row.group.refs[0]?.messageID
|
||||
}
|
||||
Reference in New Issue
Block a user