mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(app): explicit state machines for timeline sync, quote toolbar, queue panel and scroll reconnect (#62008)
This commit is contained in:
committed by
GitHub
Unverified
parent
418f862b4b
commit
ae3de411ae
@@ -3317,6 +3317,16 @@ test("reaches the quote action from the keyboard and blocks a selection over the
|
||||
await expect(more).not.toBeFocused()
|
||||
expect(await page.evaluate(() => !!document.activeElement?.closest('[data-component="timeline-quote"]'))).toBe(false)
|
||||
await expect(composer).toHaveCount(1)
|
||||
|
||||
// A press that turns into a native drag of the selection ends with dragend, and no pointerup follows.
|
||||
await page.evaluate(() => window.getSelection()?.removeAllRanges())
|
||||
await expect(toolbar).toHaveCount(0)
|
||||
await short.hover()
|
||||
await page.mouse.down()
|
||||
await page.evaluate(() => document.dispatchEvent(new Event("dragend")))
|
||||
await short.evaluate((element) => window.getSelection()?.selectAllChildren(element))
|
||||
await expect(toolbar).toBeVisible()
|
||||
await page.mouse.up()
|
||||
})
|
||||
|
||||
function pauseExitAnimations(locator: Locator) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
|
||||
import type { Prompt } from "@/composer/state"
|
||||
import {
|
||||
createQueueState,
|
||||
movedTarget,
|
||||
selectQueueRows,
|
||||
transitionQueue,
|
||||
viewQueue,
|
||||
@@ -169,6 +170,55 @@ describe("queue changes run one at a time", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("replaced inbox IDs", () => {
|
||||
const moved = (state: QueueState) => viewQueue(state, { working: true, behavior: "queue" }).moved
|
||||
|
||||
// Edits `id` as a queued prompt; its replacement and the prompts after it take `next`.
|
||||
function edit(state: QueueState, id: string, next: string[]) {
|
||||
const confirmed = replay(state, [
|
||||
{ type: "edit.start", id, reverted: false, draft: draft("") },
|
||||
{ type: "edit.confirm", delivery: "queue", reverted: false, prompt: prompt(`${id} edited`), ids: next },
|
||||
])
|
||||
|
||||
return { state: confirmed.state, attempt: runs(confirmed.effects)[0].attempt }
|
||||
}
|
||||
|
||||
test("an edit's replacements chain across later edits until their prompts leave the queue", () => {
|
||||
const first = edit(createQueueState([one]), "inb_1", ["msg_1"])
|
||||
// In flight, the panel already sees the replacement it may swap in.
|
||||
expect(moved(first.state)).toEqual({ inb_1: "msg_1" })
|
||||
|
||||
const settled = replay(first.state, [
|
||||
{ type: "inbox.synced", items: [item("msg_1")] },
|
||||
{ type: "mutation.succeeded", attempt: first.attempt },
|
||||
]).state
|
||||
|
||||
expect(settled.status).toBe("idle")
|
||||
expect(moved(settled)).toEqual({ inb_1: "msg_1" })
|
||||
|
||||
const second = edit(settled, "msg_1", ["msg_2"])
|
||||
|
||||
const chained = replay(second.state, [
|
||||
{ type: "inbox.synced", items: [item("msg_2")] },
|
||||
{ type: "mutation.succeeded", attempt: second.attempt },
|
||||
]).state
|
||||
|
||||
expect(movedTarget(moved(chained), "inb_1", new Set(["msg_2"]))).toBe("msg_2")
|
||||
expect(movedTarget(moved(chained), "inb_1", new Set(["msg_1", "msg_2"]))).toBe("msg_1")
|
||||
|
||||
// Once the last replacement is delivered, nothing it maps is queued.
|
||||
expect(moved(transitionQueue(chained, { type: "inbox.synced", items: [] }).state)).toEqual({})
|
||||
})
|
||||
|
||||
test("a failed edit leaves no replacement behind", () => {
|
||||
const sent = edit(createQueueState([one, two]), "inb_1", ["msg_1", "msg_2"])
|
||||
expect(moved(sent.state)).toEqual({ inb_1: "msg_1", inb_2: "msg_2" })
|
||||
|
||||
const failed = transitionQueue(sent.state, { type: "mutation.failed", attempt: sent.attempt, hidden: [] })
|
||||
expect(moved(failed.state)).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe("optimistic rows", () => {
|
||||
test("a steer hides its row until the server confirms or refuses it", () => {
|
||||
const requested = transitionQueue(createQueueState([one, two]), { type: "steer.requested", id: "inb_1" })
|
||||
|
||||
@@ -80,8 +80,13 @@ type QueueBase = {
|
||||
readonly seq: number
|
||||
readonly items: readonly QueuedPrompt[]
|
||||
readonly gone: readonly GoneEntry[]
|
||||
// Each inbox ID a finished edit or reorder replaced, mapped to the ID admitted in its place, so the strip can swap
|
||||
// the row in place. An entry is dropped once no ID along its chain is queued.
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
const NO_MOVES: Readonly<Record<string, string>> = Object.freeze({})
|
||||
|
||||
// Operations run one at a time in the order they were requested: `active` is in flight and `pending` waits for it.
|
||||
export type QueueState =
|
||||
| (QueueBase & { readonly status: "idle" })
|
||||
@@ -157,10 +162,12 @@ export type QueueView = {
|
||||
readonly undoing: boolean
|
||||
readonly delivery: ComposerDelivery
|
||||
readonly alternate: ComposerDelivery | undefined
|
||||
/** Inbox IDs replaced by an edit or reorder, finished or in flight, mapped to their replacements. */
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
export function createQueueState(items: readonly QueuedPrompt[]): QueueState {
|
||||
return { status: "idle", seq: 0, items, gone: [] }
|
||||
return { status: "idle", seq: 0, items, gone: [], moved: NO_MOVES }
|
||||
}
|
||||
|
||||
export function transitionQueue(state: QueueState, event: QueueEvent): QueueTransition {
|
||||
@@ -200,7 +207,10 @@ export function transitionQueue(state: QueueState, event: QueueEvent): QueueTran
|
||||
const closed = state.status === "editing" || state.status === "editing-while-mutating" ? closeEdit(state) : state
|
||||
|
||||
// Operations in flight still finish: the server may already hold half of an edit.
|
||||
return changed({ ...closed, gone: [] }, [...(edit ? [restore(edit, false)] : []), { type: "timer.clearAll" }])
|
||||
return changed({ ...closed, gone: [], moved: NO_MOVES }, [
|
||||
...(edit ? [restore(edit, false)] : []),
|
||||
{ type: "timer.clearAll" },
|
||||
])
|
||||
}
|
||||
|
||||
return settle(state, event)
|
||||
@@ -256,9 +266,30 @@ export function viewQueue(
|
||||
undoing: state.status === "mutating" && state.active.type === "undo",
|
||||
delivery: context.working ? context.behavior : "steer",
|
||||
alternate: editing ? "steer" : context.working ? (context.behavior === "queue" ? "steer" : "queue") : undefined,
|
||||
moved: selectQueueMoved(state),
|
||||
}
|
||||
}
|
||||
|
||||
export function selectQueueMoved(state: QueueState) {
|
||||
const active = state.status === "mutating" || state.status === "editing-while-mutating" ? state.active : undefined
|
||||
|
||||
if ((active?.type !== "edit" && active?.type !== "reorder") || !Object.keys(active.moved).length) return state.moved
|
||||
|
||||
return { ...state.moved, ...active.moved }
|
||||
}
|
||||
|
||||
/** The first ID along `id`'s chain of replacements that `listed` holds. */
|
||||
export function movedTarget(moved: Readonly<Record<string, string>>, id: string, listed: ReadonlySet<string>) {
|
||||
// Every replacement is a freshly minted ID, so a chain cannot loop; the bound only guards malformed input.
|
||||
const hops = Object.keys(moved).length
|
||||
|
||||
for (let next = moved[id], step = 0; next !== undefined && step < hops; next = moved[next], step++) {
|
||||
if (listed.has(next)) return next
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function editingID(state: QueueState) {
|
||||
return editOf(state)?.id
|
||||
}
|
||||
@@ -272,7 +303,15 @@ function synced(state: QueueState, items: readonly QueuedPrompt[]): QueueTransit
|
||||
gone.some((entry) => entry.expiry === expiry) ? [] : [{ type: "timer.clear", expiry }],
|
||||
)
|
||||
|
||||
const next = { ...state, items, gone }
|
||||
// A replacement in flight can continue a finished one's chain.
|
||||
const chains = selectQueueMoved(state)
|
||||
|
||||
const kept = Object.entries(state.moved).filter(
|
||||
([, id]) => listed.has(id) || movedTarget(chains, id, listed) !== undefined,
|
||||
)
|
||||
|
||||
const moved = kept.length === Object.keys(state.moved).length ? state.moved : Object.fromEntries(kept)
|
||||
const next = { ...state, items, gone, moved }
|
||||
|
||||
if (next.status !== "editing" && next.status !== "editing-while-mutating") return changed(next, cleared)
|
||||
|
||||
@@ -312,7 +351,7 @@ function startEdit(state: QueueState, event: Extract<QueueEvent, { type: "edit.s
|
||||
...(attachments.length ? [{ type: "media.pin" as const, attempt: edit.pin, attachments }] : []),
|
||||
]
|
||||
|
||||
const base = { seq: edit.pin, items: state.items, gone: state.gone }
|
||||
const base = { seq: edit.pin, items: state.items, gone: state.gone, moved: state.moved }
|
||||
|
||||
if (state.status === "idle" || state.status === "editing")
|
||||
return changed({ ...base, status: "editing", edit }, effects)
|
||||
@@ -377,7 +416,15 @@ function reorder(state: QueueState, event: Extract<QueueEvent, { type: "reorder.
|
||||
|
||||
// The rewrite can replace the row being edited, so the edit closes first and keeps what was typed into it.
|
||||
return changed(
|
||||
{ seq: active.attempt, items: state.items, gone: state.gone, status: "mutating", active, pending: [] },
|
||||
{
|
||||
seq: active.attempt,
|
||||
items: state.items,
|
||||
gone: state.gone,
|
||||
moved: state.moved,
|
||||
status: "mutating",
|
||||
active,
|
||||
pending: [],
|
||||
},
|
||||
[
|
||||
...(state.status === "editing" ? [restore(state.edit, true, state.edit.item)] : []),
|
||||
{ type: "mutation.run", operation: active },
|
||||
@@ -407,7 +454,15 @@ function undo(state: QueueState, event: Extract<QueueEvent, { type: "undo.reques
|
||||
const active = { type: "undo" as const, attempt: state.seq + 1, item }
|
||||
|
||||
return changed(
|
||||
{ seq: active.attempt, items: state.items, gone: state.gone, status: "mutating", active, pending: [] },
|
||||
{
|
||||
seq: active.attempt,
|
||||
items: state.items,
|
||||
gone: state.gone,
|
||||
moved: state.moved,
|
||||
status: "mutating",
|
||||
active,
|
||||
pending: [],
|
||||
},
|
||||
[{ type: "mutation.run", operation: active }],
|
||||
)
|
||||
}
|
||||
@@ -458,7 +513,12 @@ function settle(
|
||||
: Object.keys(active.moved)
|
||||
|
||||
const hidden = hide(state, confirmed)
|
||||
const next = advance(hidden.state, active.type === "edit" || active.type === "reorder" ? active.moved : {})
|
||||
const moved = active.type === "edit" || active.type === "reorder" ? active.moved : NO_MOVES
|
||||
|
||||
const next = advance(
|
||||
moved === NO_MOVES ? hidden.state : { ...hidden.state, moved: { ...hidden.state.moved, ...moved } },
|
||||
moved,
|
||||
)
|
||||
|
||||
return changed(next.state, [...hidden.effects, ...next.effects])
|
||||
}
|
||||
@@ -523,7 +583,7 @@ function advance(state: Mutating, moved: Readonly<Record<string, string>>): Queu
|
||||
: { ...operation, id: remap(operation.id) },
|
||||
)
|
||||
|
||||
const base = { seq: state.seq, items: state.items, gone: state.gone }
|
||||
const base = { seq: state.seq, items: state.items, gone: state.gone, moved: state.moved }
|
||||
|
||||
if (!head)
|
||||
return changed(
|
||||
@@ -546,7 +606,7 @@ function enqueue(state: QueueState, operation: QueuedOperation, effects: QueueEf
|
||||
if (state.status === "mutating" || state.status === "editing-while-mutating")
|
||||
return changed({ ...state, pending: [...state.pending, operation] }, effects)
|
||||
const active = activate(operation, state.seq + 1)
|
||||
const base = { seq: active.attempt, items: state.items, gone: state.gone, active, pending: [] }
|
||||
const base = { seq: active.attempt, items: state.items, gone: state.gone, moved: state.moved, active, pending: [] }
|
||||
const run: QueueEffect = { type: "mutation.run", operation: active }
|
||||
|
||||
if (state.status === "editing")
|
||||
@@ -568,7 +628,7 @@ function withActive(state: Mutating, active: ActiveOperation): QueueState {
|
||||
}
|
||||
|
||||
function closeEdit(state: Extract<QueueState, { edit: ActiveEdit }>): QueueState {
|
||||
const base = { seq: state.seq, items: state.items, gone: state.gone }
|
||||
const base = { seq: state.seq, items: state.items, gone: state.gone, moved: state.moved }
|
||||
|
||||
if (state.status === "editing") return { ...base, status: "idle" }
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { QueueRow } from "./queue-machine"
|
||||
import {
|
||||
createQueuePanelState,
|
||||
DISPOSED_QUEUE_PANEL_EVENT,
|
||||
isQueuePanelOpen,
|
||||
PANEL_CLOSED_EVENT,
|
||||
queuePanelCount,
|
||||
transitionQueuePanel,
|
||||
type QueuePanelEvent,
|
||||
type QueuePanelState,
|
||||
} from "./queue-panel-machine"
|
||||
|
||||
const row = (id: string): QueueRow => ({ id, text: `${id} text`, attachments: 0 })
|
||||
|
||||
const sync = (
|
||||
ids: string[],
|
||||
options: { moved?: Record<string, string>; hidden?: boolean; stagger?: number } = {},
|
||||
): Extract<QueuePanelEvent, { type: "sync" }> => ({
|
||||
type: "sync",
|
||||
rows: ids.map(row),
|
||||
moved: options.moved ?? {},
|
||||
hidden: options.hidden ?? false,
|
||||
stagger: options.stagger ?? 0,
|
||||
reducedMotion: false,
|
||||
})
|
||||
|
||||
const phases = (state: QueuePanelState) =>
|
||||
state.status === "disposed" ? [] : state.entries.map((entry) => `${entry.id}:${entry.phase}`)
|
||||
|
||||
function play(state: QueuePanelState, events: QueuePanelEvent[]) {
|
||||
return events.reduce((current, event) => transitionQueuePanel(current, event).state, state)
|
||||
}
|
||||
|
||||
const open = (ids: string[]) => createQueuePanelState(ids.map(row), false)
|
||||
|
||||
describe("queue panel", () => {
|
||||
test("a prompt delivered as another is queued closes while the new one grows in", () => {
|
||||
const next = transitionQueuePanel(open(["A", "B"]), sync(["B", "C"]))
|
||||
|
||||
expect(phases(next.state)).toEqual(["A:leaving", "B:present", "C:entering"])
|
||||
expect(queuePanelCount(next.state)).toBe(2)
|
||||
|
||||
const closed = transitionQueuePanel(next.state, { type: "row.closed", id: "A" })
|
||||
expect(phases(closed.state)).toEqual(["B:present", "C:entering"])
|
||||
})
|
||||
|
||||
test("an edited prompt swaps in place under its new ID, even as another prompt is queued", () => {
|
||||
expect(phases(play(open(["id_1", "B"]), [sync(["id_2", "B"], { moved: { id_1: "id_2" } })]))).toEqual([
|
||||
"id_2:present",
|
||||
"B:present",
|
||||
])
|
||||
|
||||
expect(phases(play(open(["id_1", "B"]), [sync(["id_2", "B", "D"], { moved: { id_1: "id_2" } })]))).toEqual([
|
||||
"id_2:present",
|
||||
"B:present",
|
||||
"D:entering",
|
||||
])
|
||||
})
|
||||
|
||||
test("a reorder swaps every row in place", () => {
|
||||
const moved = { A: "A2", B: "B2" }
|
||||
|
||||
expect(phases(play(open(["A", "B"]), [sync(["B2", "A2"], { moved })]))).toEqual(["B2:present", "A2:present"])
|
||||
})
|
||||
|
||||
test("prompts delivered while a dock hides the panel leave no ghost rows", () => {
|
||||
const state = play(open(["A", "B"]), [
|
||||
sync(["A", "B"], { hidden: true }),
|
||||
PANEL_CLOSED_EVENT,
|
||||
sync([], { hidden: true }),
|
||||
sync(["C"], { hidden: true }),
|
||||
])
|
||||
|
||||
expect(state.status).toBe("closed")
|
||||
|
||||
const shown = transitionQueuePanel(state, sync(["C"]))
|
||||
expect(isQueuePanelOpen(shown.state)).toBe(true)
|
||||
expect(phases(shown.state)).toEqual(["C:present"])
|
||||
})
|
||||
|
||||
test("the last prompts stay drawn while the emptied panel closes", () => {
|
||||
const closing = transitionQueuePanel(open(["A", "B"]), sync([])).state
|
||||
|
||||
expect(closing.status).toBe("closing")
|
||||
expect(phases(closing)).toEqual(["A:leaving", "B:leaving"])
|
||||
expect(queuePanelCount(closing)).toBe(2)
|
||||
expect(phases(transitionQueuePanel(closing, PANEL_CLOSED_EVENT).state)).toEqual([])
|
||||
})
|
||||
|
||||
test.each([
|
||||
["unmounts", DISPOSED_QUEUE_PANEL_EVENT],
|
||||
["closes", sync(["A"], { hidden: true })],
|
||||
])("a cascade queued before the panel %s never starts", (_name, event) => {
|
||||
const closed = createQueuePanelState([row("A")], true)
|
||||
const opened = transitionQueuePanel(closed, sync(["A"], { stagger: 0.04 }))
|
||||
const attempt = opened.state.status === "open" ? opened.state.attempt : -1
|
||||
|
||||
expect(opened.effects).toEqual([{ type: "cascade.schedule", attempt }])
|
||||
expect(transitionQueuePanel(opened.state, { type: "cascade.ready", attempt }).effects).toEqual([
|
||||
{ type: "cascade.paint", step: 0.04 },
|
||||
])
|
||||
|
||||
const left = transitionQueuePanel(opened.state, event)
|
||||
expect(left.effects).toEqual([{ type: "cascade.cancel" }])
|
||||
|
||||
const late = transitionQueuePanel(left.state, { type: "cascade.ready", attempt })
|
||||
expect(late.state).toBe(left.state)
|
||||
expect(late.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a panel open from the start does not cascade, and an unchanged row keeps its entry", () => {
|
||||
const rows = [row("A")]
|
||||
const state = createQueuePanelState(rows, false)
|
||||
const next = transitionQueuePanel(state, { ...sync([]), rows })
|
||||
const entries = (value: QueuePanelState) => (value.status === "disposed" ? [] : value.entries)
|
||||
|
||||
expect(next.effects).toEqual([])
|
||||
expect(entries(next.state)[0]).toBe(entries(state)[0]!)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,229 @@
|
||||
import { movedTarget, type QueueRow } from "./queue-machine"
|
||||
|
||||
/**
|
||||
* `entering`: a prompt queued into an open panel, which grows in when it mounts. `leaving`: a prompt gone from the queue,
|
||||
* drawn in its slot while it closes.
|
||||
*/
|
||||
export type QueuePanelRowPhase = "entering" | "present" | "leaving"
|
||||
|
||||
export type QueuePanelEntry = {
|
||||
readonly id: string
|
||||
readonly row: QueueRow
|
||||
readonly phase: QueuePanelRowPhase
|
||||
}
|
||||
|
||||
/**
|
||||
* The pullout above the composer. `closing` keeps drawing its last prompts while it closes; `closed` draws nothing, so
|
||||
* it holds only the current prompts. `cascade` is the stagger of the rows fading in as the panel opens, set until the
|
||||
* panel leaves `open`; `attempt` advances on every change of phase, so a cascade for an earlier opening never starts.
|
||||
*/
|
||||
export type QueuePanelState =
|
||||
| { readonly status: "closed"; readonly attempt: number; readonly entries: readonly QueuePanelEntry[] }
|
||||
| {
|
||||
readonly status: "open"
|
||||
readonly attempt: number
|
||||
readonly entries: readonly QueuePanelEntry[]
|
||||
readonly cascade?: number
|
||||
}
|
||||
| { readonly status: "closing"; readonly attempt: number; readonly entries: readonly QueuePanelEntry[] }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type QueuePanelEvent =
|
||||
| {
|
||||
readonly type: "sync"
|
||||
readonly rows: readonly QueueRow[]
|
||||
/** Inbox IDs an edit or reorder replaced, mapped to their replacements. */
|
||||
readonly moved: Readonly<Record<string, string>>
|
||||
readonly hidden: boolean
|
||||
readonly stagger: number
|
||||
readonly reducedMotion: boolean
|
||||
}
|
||||
| { readonly type: "cascade.ready"; readonly attempt: number }
|
||||
| { readonly type: "row.closed"; readonly id: string }
|
||||
| { readonly type: "panel.closed" }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type QueuePanelEffect =
|
||||
| { readonly type: "cascade.schedule"; readonly attempt: number }
|
||||
| { readonly type: "cascade.paint"; readonly step: number }
|
||||
| { readonly type: "cascade.cancel" }
|
||||
|
||||
export type QueuePanelTransition = {
|
||||
readonly state: QueuePanelState
|
||||
readonly effects: readonly QueuePanelEffect[]
|
||||
}
|
||||
|
||||
export const PANEL_CLOSED_EVENT: QueuePanelEvent = Object.freeze({ type: "panel.closed" })
|
||||
|
||||
export const DISPOSED_QUEUE_PANEL_EVENT: QueuePanelEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
const NO_EFFECTS: readonly QueuePanelEffect[] = Object.freeze([])
|
||||
|
||||
const CASCADE_CANCEL: readonly QueuePanelEffect[] = Object.freeze([{ type: "cascade.cancel" }])
|
||||
|
||||
const DISPOSED_STATE: QueuePanelState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export function createQueuePanelState(rows: readonly QueueRow[], hidden: boolean): QueuePanelState {
|
||||
return { status: !hidden && rows.length > 0 ? "open" : "closed", attempt: 0, entries: present(rows) }
|
||||
}
|
||||
|
||||
export function transitionQueuePanel(state: QueuePanelState, event: QueuePanelEvent): QueuePanelTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (event.type === "disposed")
|
||||
return {
|
||||
state: DISPOSED_STATE,
|
||||
effects: state.status === "open" && state.cascade !== undefined ? CASCADE_CANCEL : NO_EFFECTS,
|
||||
}
|
||||
|
||||
if (event.type === "sync") {
|
||||
const open = !event.hidden && event.rows.length > 0
|
||||
|
||||
// Nothing is drawn, so prompts that left meanwhile leave no rows behind.
|
||||
if (state.status === "closed" && !open)
|
||||
return { state: { ...state, entries: present(event.rows) }, effects: NO_EFFECTS }
|
||||
|
||||
if (state.status === "open" && open)
|
||||
return {
|
||||
state: { ...state, entries: reconcile(state.entries, event.rows, event.moved, event.hidden) },
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
// The last prompts stay drawn while the emptied panel closes.
|
||||
const entries =
|
||||
event.rows.length === 0
|
||||
? state.status === "open"
|
||||
? state.entries.map((entry) =>
|
||||
entry.phase === "leaving" ? entry : { ...entry, phase: "leaving" as const },
|
||||
)
|
||||
: state.entries
|
||||
: reconcile(state.entries, event.rows, event.moved, event.hidden)
|
||||
|
||||
if (state.status === "closing") return { state: { ...state, entries }, effects: NO_EFFECTS }
|
||||
|
||||
return {
|
||||
state: { status: "closing", attempt: state.attempt + 1, entries },
|
||||
effects: state.status === "open" && state.cascade !== undefined ? CASCADE_CANCEL : NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
// The panel opens with prompts already queued, such as after a dock closes, so its rows can cascade in.
|
||||
const attempt = state.attempt + 1
|
||||
const cascade = event.stagger > 0 && !event.reducedMotion ? event.stagger : undefined
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "open",
|
||||
attempt,
|
||||
entries:
|
||||
state.status === "closed"
|
||||
? present(event.rows)
|
||||
: reconcile(state.entries, event.rows, event.moved, event.hidden),
|
||||
cascade,
|
||||
},
|
||||
effects: cascade === undefined ? NO_EFFECTS : [{ type: "cascade.schedule", attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "cascade.ready") {
|
||||
if (state.status !== "open" || state.attempt !== event.attempt || state.cascade === undefined)
|
||||
return unchanged(state)
|
||||
|
||||
return { state, effects: [{ type: "cascade.paint", step: state.cascade }] }
|
||||
}
|
||||
|
||||
if (event.type === "row.closed") {
|
||||
if (state.status !== "open" || !state.entries.some((entry) => entry.id === event.id && entry.phase === "leaving"))
|
||||
return unchanged(state)
|
||||
|
||||
return { state: { ...state, entries: state.entries.filter((entry) => entry.id !== event.id) }, effects: NO_EFFECTS }
|
||||
}
|
||||
|
||||
if (state.status !== "closing") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "closed",
|
||||
attempt: state.attempt + 1,
|
||||
entries: state.entries.flatMap((entry) =>
|
||||
entry.phase === "leaving" ? [] : [entry.phase === "present" ? entry : { ...entry, phase: "present" as const }],
|
||||
),
|
||||
},
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
export function isQueuePanelOpen(state: QueuePanelState) {
|
||||
return state.status === "open"
|
||||
}
|
||||
|
||||
/** The prompts the header counts: the queued ones while open, every drawn one while closing. */
|
||||
export function queuePanelCount(state: QueuePanelState) {
|
||||
if (state.status === "disposed") return 0
|
||||
|
||||
if (state.status !== "open") return state.entries.length
|
||||
|
||||
return state.entries.filter((entry) => entry.phase !== "leaving").length
|
||||
}
|
||||
|
||||
export function selectQueuePanelIDs(state: QueuePanelState) {
|
||||
return state.status === "disposed" ? [] : state.entries.map((entry) => entry.id)
|
||||
}
|
||||
|
||||
export function selectQueuePanelLiveIDs(state: QueuePanelState) {
|
||||
return state.status === "disposed"
|
||||
? []
|
||||
: state.entries.flatMap((entry) => (entry.phase === "leaving" ? [] : [entry.id]))
|
||||
}
|
||||
|
||||
export function queuePanelEntry(state: QueuePanelState, id: string) {
|
||||
return state.status === "disposed" ? undefined : state.entries.find((entry) => entry.id === id)
|
||||
}
|
||||
|
||||
function present(rows: readonly QueueRow[]): QueuePanelEntry[] {
|
||||
return rows.map((row) => ({ id: row.id, row, phase: "present" }))
|
||||
}
|
||||
|
||||
// A prompt whose inbox ID an edit or reorder replaced swaps in place under its new ID; any other prompt that left
|
||||
// closes in its slot, and a new one grows in unless the panel is opening around it.
|
||||
function reconcile(
|
||||
previous: readonly QueuePanelEntry[],
|
||||
rows: readonly QueueRow[],
|
||||
moved: Readonly<Record<string, string>>,
|
||||
hidden: boolean,
|
||||
): QueuePanelEntry[] {
|
||||
const listed = new Set(rows.map((row) => row.id))
|
||||
const live = previous.filter((entry) => entry.phase !== "leaving")
|
||||
|
||||
const swapped = new Set(
|
||||
live.flatMap((entry) => {
|
||||
if (listed.has(entry.id)) return []
|
||||
const target = movedTarget(moved, entry.id, listed)
|
||||
|
||||
return target === undefined ? [] : [entry.id, target]
|
||||
}),
|
||||
)
|
||||
|
||||
const next = rows.map((row): QueuePanelEntry => {
|
||||
const before = previous.find((entry) => entry.id === row.id)
|
||||
const phase = before || swapped.has(row.id) || live.length === 0 || hidden ? "present" : "entering"
|
||||
const kept = before?.phase === "entering" ? "entering" : phase
|
||||
|
||||
return before && before.row === row && before.phase === kept ? before : { id: row.id, row, phase: kept }
|
||||
})
|
||||
|
||||
// A closing row keeps its place after the prompt it followed.
|
||||
previous.forEach((entry, index) => {
|
||||
if (listed.has(entry.id) || swapped.has(entry.id)) return
|
||||
const anchor = previous.slice(0, index).findLast((item) => next.some((placed) => placed.id === item.id))
|
||||
const at = anchor ? next.findIndex((placed) => placed.id === anchor.id) + 1 : 0
|
||||
next.splice(at, 0, entry.phase === "leaving" ? entry : { ...entry, phase: "leaving" })
|
||||
})
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
function unchanged(state: QueuePanelState): QueuePanelTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -13,77 +13,80 @@ import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { prefersReducedMotion } from "@opencode/ui/motion"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { SessionQueueView } from "./queue"
|
||||
import type { QueueRow } from "./queue-machine"
|
||||
import {
|
||||
createQueuePanelState,
|
||||
DISPOSED_QUEUE_PANEL_EVENT,
|
||||
isQueuePanelOpen,
|
||||
PANEL_CLOSED_EVENT,
|
||||
queuePanelCount,
|
||||
queuePanelEntry,
|
||||
selectQueuePanelIDs,
|
||||
selectQueuePanelLiveIDs,
|
||||
transitionQueuePanel,
|
||||
type QueuePanelEffect,
|
||||
type QueuePanelEvent,
|
||||
} from "./queue-panel-machine"
|
||||
import { cascade, Grow, queueStagger } from "./spring-height"
|
||||
import "./queue-panel.css"
|
||||
|
||||
type QueueRow = ReturnType<SessionQueueView["rows"]>[number]
|
||||
|
||||
// Pullout above the composer listing the prompts queued behind the current
|
||||
// turn. The panel slides under the composer card (negative margin, opaque
|
||||
// composer background) so the two read as one attached surface.
|
||||
export function SessionQueuePanel(props: { queue: SessionQueueView; hidden?: boolean }) {
|
||||
const language = useLanguage()
|
||||
// A removed prompt stays drawn in its slot while it closes; the last prompts stay while the emptied panel closes.
|
||||
const [shown, setShown] = createSignal(props.queue.rows())
|
||||
const live = createMemo(() => props.queue.rows().map((row) => row.id))
|
||||
const appearing = new Set<string>()
|
||||
let lastLive = props.queue.rows()
|
||||
const open = () => !props.hidden && live().length > 0
|
||||
const count = () => (open() ? live().length : shown().length)
|
||||
|
||||
let current = createQueuePanelState(
|
||||
untrack(() => props.queue.rows()),
|
||||
untrack(() => !!props.hidden),
|
||||
)
|
||||
|
||||
const [panelState, setPanelState] = createSignal(current)
|
||||
const open = createMemo(() => isQueuePanelOpen(panelState()))
|
||||
const count = createMemo(() => queuePanelCount(panelState()))
|
||||
const ids = createMemo(() => selectQueuePanelIDs(panelState()), undefined, { equals: sameIDs })
|
||||
const live = createMemo(() => selectQueuePanelLiveIDs(panelState()), undefined, { equals: sameIDs })
|
||||
let stopCascade: (() => void) | undefined
|
||||
let listRef!: HTMLDivElement
|
||||
|
||||
const dispatch = (event: QueuePanelEvent) =>
|
||||
untrack(() => {
|
||||
const next = transitionQueuePanel(current, event)
|
||||
|
||||
if (next.state !== current) {
|
||||
current = next.state
|
||||
setPanelState(current)
|
||||
}
|
||||
|
||||
next.effects.forEach(run)
|
||||
})
|
||||
|
||||
const run = (effect: QueuePanelEffect) => {
|
||||
// The rows the opening panel mounted are in the list once the render settles.
|
||||
if (effect.type === "cascade.schedule")
|
||||
return queueMicrotask(() => dispatch({ type: "cascade.ready", attempt: effect.attempt }))
|
||||
stopCascade?.()
|
||||
stopCascade = undefined
|
||||
|
||||
if (effect.type === "cascade.cancel") return
|
||||
stopCascade = cascade(
|
||||
[...listRef.querySelectorAll<HTMLElement>('[data-component="session-queue-row"]')],
|
||||
effect.step,
|
||||
)
|
||||
}
|
||||
|
||||
createEffect(
|
||||
on(
|
||||
() => props.queue.rows(),
|
||||
(next) => {
|
||||
const prevLive = lastLive
|
||||
lastLive = next
|
||||
|
||||
if (next.length === 0) return
|
||||
|
||||
// An in-place edit or reorder keeps the row count: a row whose ID it replaced swaps in place rather than closing,
|
||||
// while a row that was already closing keeps closing until its exit completes.
|
||||
const swap = next.length === prevLive.length && prevLive.length > 0
|
||||
|
||||
if (!swap && prevLive.length > 0 && !props.hidden)
|
||||
next.forEach((row) => !prevLive.some((item) => item.id === row.id) && appearing.add(row.id))
|
||||
|
||||
const kept = untrack(shown).filter(
|
||||
(row) => !swap || next.some((item) => item.id === row.id) || !prevLive.some((item) => item.id === row.id),
|
||||
)
|
||||
|
||||
setShown(keepLeaving(kept, next))
|
||||
},
|
||||
() => [props.queue.rows(), props.queue.moved?.() ?? NO_MOVES, !!props.hidden] as const,
|
||||
([rows, moved, hidden]) =>
|
||||
dispatch({ type: "sync", rows, moved, hidden, stagger: queueStagger(), reducedMotion: prefersReducedMotion() }),
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
|
||||
// When the panel opens with prompts already queued, such as after a dock closes, its rows can cascade in.
|
||||
let stopCascade: (() => void) | undefined
|
||||
createEffect(
|
||||
on(
|
||||
open,
|
||||
(now, was) => {
|
||||
stopCascade?.()
|
||||
stopCascade = undefined
|
||||
const step = queueStagger()
|
||||
|
||||
if (!now || was !== false || step <= 0 || prefersReducedMotion()) return
|
||||
queueMicrotask(() => {
|
||||
if (!open()) return
|
||||
stopCascade = cascade(
|
||||
[...listRef.querySelectorAll<HTMLElement>('[data-component="session-queue-row"]')],
|
||||
step,
|
||||
)
|
||||
})
|
||||
},
|
||||
{ defer: true },
|
||||
),
|
||||
)
|
||||
onCleanup(() => stopCascade?.())
|
||||
onCleanup(() => dispatch(DISPOSED_QUEUE_PANEL_EVENT))
|
||||
|
||||
return (
|
||||
<Grow when={open()} fade class="relative z-0" onClosed={() => setShown(props.queue.rows())}>
|
||||
<Grow when={open()} fade class="relative z-0" onClosed={() => dispatch(PANEL_CLOSED_EVENT)}>
|
||||
<div
|
||||
data-component="session-queue-panel"
|
||||
inert={!open()}
|
||||
@@ -133,17 +136,21 @@ export function SessionQueuePanel(props: { queue: SessionQueueView; hidden?: boo
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
<For each={shown().map((row) => row.id)}>
|
||||
{(id) => (
|
||||
<Grow
|
||||
when={!open() || live().includes(id)}
|
||||
appear={appearing.delete(id)}
|
||||
fade
|
||||
onClosed={() => setShown((rows) => rows.filter((row) => row.id !== id))}
|
||||
>
|
||||
<SessionQueueRow queue={props.queue} id={id} index={live().indexOf(id)} />
|
||||
</Grow>
|
||||
)}
|
||||
<For each={ids()}>
|
||||
{(id) => {
|
||||
const entry = createMemo(() => queuePanelEntry(panelState(), id))
|
||||
|
||||
return (
|
||||
<Grow
|
||||
when={!open() || entry()?.phase !== "leaving"}
|
||||
appear={entry()?.phase === "entering"}
|
||||
fade
|
||||
onClosed={() => dispatch({ type: "row.closed", id })}
|
||||
>
|
||||
<SessionQueueRow queue={props.queue} id={id} row={entry()?.row} index={live().indexOf(id)} />
|
||||
</Grow>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
</DragDropProvider>
|
||||
@@ -152,22 +159,14 @@ export function SessionQueuePanel(props: { queue: SessionQueueView; hidden?: boo
|
||||
)
|
||||
}
|
||||
|
||||
function keepLeaving<T extends { id: string }>(previous: T[], next: T[]) {
|
||||
const rows = [...next]
|
||||
const NO_MOVES: Readonly<Record<string, string>> = Object.freeze({})
|
||||
|
||||
previous.forEach((row, index) => {
|
||||
if (rows.some((item) => item.id === row.id)) return
|
||||
const before = previous.slice(0, index).findLast((item) => rows.some((entry) => entry.id === item.id))
|
||||
const at = before ? rows.findIndex((item) => item.id === before.id) + 1 : 0
|
||||
rows.splice(at, 0, row)
|
||||
})
|
||||
|
||||
return rows
|
||||
function sameIDs(a: readonly string[], b: readonly string[]) {
|
||||
return a.length === b.length && a.every((id, index) => id === b[index])
|
||||
}
|
||||
|
||||
function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: number }) {
|
||||
function SessionQueueRow(props: { queue: SessionQueueView; id: string; row: QueueRow | undefined; index: number }) {
|
||||
const language = useLanguage()
|
||||
const row = createMemo((last?: QueueRow) => props.queue.rows().find((entry) => entry.id === props.id) ?? last)
|
||||
const leaving = () => props.index < 0
|
||||
const editing = () => props.queue.editing() === props.id
|
||||
// While the turn is stopped the queue stays parked, so the first prompt
|
||||
@@ -190,7 +189,7 @@ function SessionQueueRow(props: { queue: SessionQueueView; id: string; index: nu
|
||||
// Not keyed: the queue rebuilds every row object whenever it changes, and a keyed row would remount, tooltips and
|
||||
// all, each time a prompt is added or the server confirms one.
|
||||
return (
|
||||
<Show when={row()}>
|
||||
<Show when={props.row}>
|
||||
{(entry) => (
|
||||
<div
|
||||
ref={sortable.ref}
|
||||
|
||||
@@ -398,6 +398,7 @@ export function createSessionQueue(input: {
|
||||
return edit(first.id)
|
||||
},
|
||||
rows: () => view().rows,
|
||||
moved: () => view().moved,
|
||||
busy: () => view().busy,
|
||||
undoing: () => view().undoing,
|
||||
working: input.working,
|
||||
@@ -411,11 +412,12 @@ export function createSessionQueue(input: {
|
||||
|
||||
export type SessionQueue = ReturnType<typeof createSessionQueue>
|
||||
|
||||
// The slice of the queue the panel renders and drives.
|
||||
// The slice of the queue the panel renders and drives. Without `moved`, a replaced row closes and its replacement opens.
|
||||
export type SessionQueueView = Pick<
|
||||
SessionQueue,
|
||||
"rows" | "editing" | "working" | "busy" | "steer" | "remove" | "undo" | "edit" | "reorder"
|
||||
>
|
||||
> &
|
||||
Partial<Pick<SessionQueue, "moved">>
|
||||
|
||||
// Pin `media:<hash>` attachments before cancelling: the cancel releases the item's blob refs and sweeps blobs
|
||||
// nothing else references, so a pin that fails leaves the item queued.
|
||||
|
||||
@@ -354,7 +354,7 @@ export function Grow<T>(props: {
|
||||
onClosed?: () => void
|
||||
children: JSX.Element | ((item: NonNullable<T>) => JSX.Element)
|
||||
}) {
|
||||
// Read once, on mount, as a caller may compute it with a side effect (the queue's `appearing.delete(id)`).
|
||||
// Read once, on mount: a row that grows in when it is added does not grow again when it changes.
|
||||
const appear = !!props.when && !!props.appear
|
||||
let current = createGrowState(!!props.when)
|
||||
const [state, setState] = createSignal(current)
|
||||
|
||||
@@ -1,6 +1,19 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { SessionMessageAssistant, SessionMessageInfo, SessionMessageUser } from "@opencode/client/promise"
|
||||
import { enrichLeadingTurn } from "./model"
|
||||
import {
|
||||
createTimelineSyncState,
|
||||
DISPOSED_TIMELINE_SYNC_EVENT,
|
||||
isTimelineReady,
|
||||
isTimelineSyncing,
|
||||
LEADING_TURN_BUSY_LIMIT,
|
||||
leadingTurnNeedsParent,
|
||||
resolveLeadingAssistant,
|
||||
timelineSyncError,
|
||||
transitionTimelineSync,
|
||||
type TimelineSyncEffect,
|
||||
type TimelineSyncEvent,
|
||||
type TimelineSyncState,
|
||||
} from "./sync-machine"
|
||||
|
||||
const user = (id: string): SessionMessageUser => ({ id, type: "user", text: id, time: { created: 1 } })
|
||||
|
||||
@@ -13,146 +26,344 @@ const assistant = (id: string): SessionMessageAssistant => ({
|
||||
time: { created: 1 },
|
||||
})
|
||||
|
||||
describe("timeline model", () => {
|
||||
test("does not enrich a different leading turn after prepending to a retained transcript", async () => {
|
||||
const messages: SessionMessageInfo[] = [user("msg_user"), assistant("msg_latest")]
|
||||
let loads = 0
|
||||
const target = { sessionKey: "dir/ses_1", sessionID: "ses_1" }
|
||||
|
||||
const input = {
|
||||
current: () => true,
|
||||
messages: () => messages,
|
||||
more: () => true,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loads += 1
|
||||
},
|
||||
pause: async () => undefined,
|
||||
maxPages: 3,
|
||||
const other = { sessionKey: "dir/ses_2", sessionID: "ses_2" }
|
||||
|
||||
function syncing(state = createTimelineSyncState()) {
|
||||
return transitionTimelineSync(state, { type: "target.changed", target }).state
|
||||
}
|
||||
|
||||
// Plays the machine against an in-memory transcript the way the model's driver does: every pause and page reads the
|
||||
// transcript as it is when the timer or request settles.
|
||||
function enrich(input: {
|
||||
memo: WeakMap<SessionMessageInfo[], string>
|
||||
messages: () => SessionMessageInfo[]
|
||||
more: () => boolean
|
||||
loadMore: () => boolean
|
||||
state?: TimelineSyncState
|
||||
// Stops after this many effects, as a tab switch would.
|
||||
interrupt?: (effect: TimelineSyncEffect) => boolean
|
||||
}) {
|
||||
const calls: string[] = []
|
||||
let state = syncing(input.state)
|
||||
const messages = input.messages()
|
||||
const assistantID = resolveLeadingAssistant(input.memo, messages)
|
||||
|
||||
let effects = dispatch({
|
||||
type: "sync.succeeded",
|
||||
attempt: state.attempt,
|
||||
assistantID,
|
||||
needsParent: !!assistantID && leadingTurnNeedsParent(messages, assistantID),
|
||||
more: input.more(),
|
||||
})
|
||||
|
||||
function dispatch(event: TimelineSyncEvent) {
|
||||
const next = transitionTimelineSync(state, event)
|
||||
state = next.state
|
||||
|
||||
return next.effects
|
||||
}
|
||||
|
||||
const needsParent = (id: string) => leadingTurnNeedsParent(input.messages(), id)
|
||||
|
||||
while (effects.length) {
|
||||
const effect = effects[0]!
|
||||
|
||||
if (input.interrupt?.(effect)) return { calls, state }
|
||||
|
||||
if (effect.type === "pause.start") {
|
||||
calls.push("pause")
|
||||
effects = dispatch({
|
||||
type: "enrich.paused",
|
||||
attempt: effect.attempt,
|
||||
needsParent: needsParent(effect.assistantID),
|
||||
more: input.more(),
|
||||
loading: false,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
await enrichLeadingTurn(input)
|
||||
if (effect.type !== "page.load") throw new Error(`Unexpected effect ${effect.type}`)
|
||||
calls.push("load")
|
||||
const succeeded = input.loadMore()
|
||||
effects = dispatch({
|
||||
type: "enrich.page-settled",
|
||||
attempt: effect.attempt,
|
||||
succeeded,
|
||||
needsParent: needsParent(effect.assistantID),
|
||||
more: input.more(),
|
||||
})
|
||||
}
|
||||
|
||||
return { calls, state }
|
||||
}
|
||||
|
||||
const loads = (calls: string[]) => calls.filter((call) => call === "load").length
|
||||
|
||||
describe("timeline sync", () => {
|
||||
test("bounds the wait for another history load instead of polling forever", () => {
|
||||
const loading = syncing()
|
||||
|
||||
let { state, effects } = transitionTimelineSync(loading, {
|
||||
type: "sync.succeeded",
|
||||
attempt: loading.attempt,
|
||||
assistantID: "msg_latest",
|
||||
needsParent: true,
|
||||
more: true,
|
||||
})
|
||||
|
||||
let pauses = 0
|
||||
|
||||
// Another caller's page load never settles, so every pause finds history still loading.
|
||||
while (effects[0]?.type === "pause.start" && pauses < LEADING_TURN_BUSY_LIMIT * 2) {
|
||||
pauses += 1
|
||||
|
||||
const next = transitionTimelineSync(state, {
|
||||
type: "enrich.paused",
|
||||
attempt: state.attempt,
|
||||
needsParent: true,
|
||||
more: true,
|
||||
loading: true,
|
||||
})
|
||||
|
||||
state = next.state
|
||||
effects = next.effects
|
||||
}
|
||||
|
||||
expect(pauses).toBe(LEADING_TURN_BUSY_LIMIT)
|
||||
expect(state.status).toBe("ready")
|
||||
expect(effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a failed first sync reports its error without throwing, and only for that session", () => {
|
||||
const error = new Error("sync failed")
|
||||
const loading = syncing()
|
||||
const failed = transitionTimelineSync(loading, { type: "sync.failed", attempt: loading.attempt, error }).state
|
||||
|
||||
expect(timelineSyncError(failed, target)).toBe(error)
|
||||
expect(isTimelineSyncing(failed, target)).toBe(false)
|
||||
expect(isTimelineReady(failed, target, () => false)).toBe(false)
|
||||
|
||||
// A new-session draft has no session.
|
||||
const draft = transitionTimelineSync(failed, { type: "target.changed", target: undefined })
|
||||
expect(draft.state.status).toBe("idle")
|
||||
expect(timelineSyncError(draft.state, undefined)).toBeUndefined()
|
||||
expect(isTimelineSyncing(draft.state, undefined)).toBe(false)
|
||||
expect(isTimelineReady(draft.state, undefined, () => false)).toBe(true)
|
||||
|
||||
const switched = transitionTimelineSync(failed, { type: "target.changed", target: other })
|
||||
expect(timelineSyncError(switched.state, other)).toBeUndefined()
|
||||
expect(isTimelineSyncing(switched.state, other)).toBe(true)
|
||||
expect(switched.effects).toEqual([{ type: "sync.start", target: other, attempt: switched.state.attempt }])
|
||||
})
|
||||
|
||||
test("a first sync that never settles reveals the timeline and ignores its late result", () => {
|
||||
const loading = syncing()
|
||||
expect(isTimelineReady(loading, target, () => false)).toBe(false)
|
||||
|
||||
const timedOut = transitionTimelineSync(loading, { type: "sync.timed-out", attempt: loading.attempt })
|
||||
expect(timedOut.state.status).toBe("ready")
|
||||
expect(timedOut.effects).toEqual([{ type: "sync.cancel" }])
|
||||
expect(isTimelineReady(timedOut.state, target, () => false)).toBe(true)
|
||||
|
||||
const late: TimelineSyncEvent[] = [
|
||||
{ type: "sync.succeeded", attempt: loading.attempt, assistantID: "msg_1", needsParent: true, more: true },
|
||||
{ type: "sync.failed", attempt: loading.attempt, error: new Error("late") },
|
||||
]
|
||||
|
||||
late.forEach((event) => expect(transitionTimelineSync(timedOut.state, event).state).toBe(timedOut.state))
|
||||
})
|
||||
|
||||
test("background enrichment does not count as syncing", () => {
|
||||
const loading = syncing()
|
||||
expect(isTimelineSyncing(loading, target)).toBe(true)
|
||||
|
||||
const pausing = transitionTimelineSync(loading, {
|
||||
type: "sync.succeeded",
|
||||
attempt: loading.attempt,
|
||||
assistantID: "msg_latest",
|
||||
needsParent: true,
|
||||
more: true,
|
||||
}).state
|
||||
|
||||
expect(pausing).toMatchObject({ status: "enriching", step: "pausing" })
|
||||
expect(isTimelineSyncing(pausing, target)).toBe(false)
|
||||
|
||||
const paging = transitionTimelineSync(pausing, {
|
||||
type: "enrich.paused",
|
||||
attempt: pausing.attempt,
|
||||
needsParent: true,
|
||||
more: true,
|
||||
loading: false,
|
||||
}).state
|
||||
|
||||
expect(paging).toMatchObject({ status: "enriching", step: "loading" })
|
||||
expect(isTimelineSyncing(paging, target)).toBe(false)
|
||||
expect(isTimelineReady(paging, target, () => false)).toBe(true)
|
||||
})
|
||||
|
||||
test("leaving the session cancels the step in flight, and disposal stops it", () => {
|
||||
const loading = syncing()
|
||||
expect(transitionTimelineSync(loading, DISPOSED_TIMELINE_SYNC_EVENT).effects).toEqual([{ type: "sync.cancel" }])
|
||||
|
||||
const pausing = transitionTimelineSync(loading, {
|
||||
type: "sync.succeeded",
|
||||
attempt: loading.attempt,
|
||||
assistantID: "msg_latest",
|
||||
needsParent: true,
|
||||
more: true,
|
||||
}).state
|
||||
|
||||
expect(transitionTimelineSync(pausing, { type: "target.changed", target: other }).effects).toEqual([
|
||||
{ type: "pause.cancel" },
|
||||
{ type: "sync.start", target: other, attempt: pausing.attempt + 1 },
|
||||
])
|
||||
|
||||
const paging = transitionTimelineSync(pausing, {
|
||||
type: "enrich.paused",
|
||||
attempt: pausing.attempt,
|
||||
needsParent: true,
|
||||
more: true,
|
||||
loading: false,
|
||||
}).state
|
||||
|
||||
const disposed = transitionTimelineSync(paging, DISPOSED_TIMELINE_SYNC_EVENT)
|
||||
expect(disposed.state.status).toBe("idle")
|
||||
expect(disposed.effects).toEqual([{ type: "page.abort" }])
|
||||
|
||||
const stale = transitionTimelineSync(disposed.state, {
|
||||
type: "enrich.page-settled",
|
||||
attempt: paging.attempt,
|
||||
succeeded: true,
|
||||
needsParent: true,
|
||||
more: true,
|
||||
})
|
||||
|
||||
expect(stale.state).toBe(disposed.state)
|
||||
expect(transitionTimelineSync(disposed.state, DISPOSED_TIMELINE_SYNC_EVENT).state).toBe(disposed.state)
|
||||
})
|
||||
|
||||
test("the same session keeps its sync", () => {
|
||||
const loading = syncing()
|
||||
const next = transitionTimelineSync(loading, { type: "target.changed", target: { ...target } })
|
||||
|
||||
expect(next.state).toBe(loading)
|
||||
expect(next.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("does not enrich a different leading turn after prepending to a retained transcript", () => {
|
||||
const memo = new WeakMap<SessionMessageInfo[], string>()
|
||||
const messages: SessionMessageInfo[] = [user("msg_user"), assistant("msg_latest")]
|
||||
const input = { memo, messages: () => messages, more: () => true, loadMore: () => true }
|
||||
|
||||
expect(loads(enrich(input).calls)).toBe(0)
|
||||
messages.unshift(assistant("msg_older"))
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads).toBe(0)
|
||||
expect(loads(enrich(input).calls)).toBe(0)
|
||||
|
||||
// An evicted/reloaded transcript gets its own initial enrichment budget.
|
||||
const reloaded = [...messages]
|
||||
await enrichLeadingTurn({ ...input, messages: () => reloaded })
|
||||
expect(loads).toBe(3)
|
||||
expect(loads(enrich({ ...input, messages: () => reloaded }).calls)).toBe(3)
|
||||
})
|
||||
|
||||
const resumed = ["msg_previous_turn", "msg_parent", "msg_latest"]
|
||||
|
||||
test("resumes the original leading turn after switching away", async () => {
|
||||
test("resumes the original leading turn after switching away", () => {
|
||||
const memo = new WeakMap<SessionMessageInfo[], string>()
|
||||
const messages: SessionMessageInfo[] = [assistant("msg_latest")]
|
||||
let current = true
|
||||
let loads = 0
|
||||
|
||||
const input = {
|
||||
current: () => current,
|
||||
memo,
|
||||
messages: () => messages,
|
||||
more: () => true,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loads += 1
|
||||
loadMore: () => {
|
||||
messages.unshift(assistant("msg_previous_turn"), user("msg_parent"))
|
||||
|
||||
return true
|
||||
},
|
||||
pause: async () => {
|
||||
current = false
|
||||
},
|
||||
maxPages: 3,
|
||||
}
|
||||
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads).toBe(0)
|
||||
// The tab switches away during the first pause.
|
||||
const away = enrich({ ...input, interrupt: (effect) => effect.type === "pause.start" })
|
||||
expect(loads(away.calls)).toBe(0)
|
||||
const left = transitionTimelineSync(away.state, { type: "target.changed", target: other }).state
|
||||
|
||||
current = true
|
||||
await enrichLeadingTurn({ ...input, pause: async () => undefined })
|
||||
const back = enrich({ ...input, state: left })
|
||||
expect(messages.map((message) => message.id)).toEqual(resumed)
|
||||
expect(loads).toBe(1)
|
||||
expect(loads(back.calls)).toBe(1)
|
||||
expect(back.state.status).toBe("ready")
|
||||
|
||||
await enrichLeadingTurn({ ...input, pause: async () => undefined })
|
||||
expect(loads).toBe(1)
|
||||
expect(loads(enrich(input).calls)).toBe(0)
|
||||
})
|
||||
|
||||
test("resumes the original leading turn after a failed page", async () => {
|
||||
test("resumes the original leading turn after a failed page", () => {
|
||||
const memo = new WeakMap<SessionMessageInfo[], string>()
|
||||
const messages: SessionMessageInfo[] = [assistant("msg_latest")]
|
||||
let loads = 0
|
||||
let attempts = 0
|
||||
|
||||
const input = {
|
||||
current: () => true,
|
||||
memo,
|
||||
messages: () => messages,
|
||||
more: () => true,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loads += 1
|
||||
loadMore: () => {
|
||||
attempts += 1
|
||||
|
||||
if (loads === 1) throw new Error("history failed")
|
||||
if (attempts === 1) return false
|
||||
messages.unshift(assistant("msg_previous_turn"), user("msg_parent"))
|
||||
|
||||
return true
|
||||
},
|
||||
pause: async () => undefined,
|
||||
maxPages: 3,
|
||||
}
|
||||
|
||||
await expect(enrichLeadingTurn(input)).rejects.toThrow("history failed")
|
||||
await enrichLeadingTurn(input)
|
||||
expect(messages.map((message) => message.id)).toEqual(resumed)
|
||||
expect(loads).toBe(2)
|
||||
const failed = enrich(input)
|
||||
expect(failed.state.status).toBe("ready")
|
||||
expect(loads(failed.calls)).toBe(1)
|
||||
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads).toBe(2)
|
||||
const retried = enrich(input)
|
||||
expect(messages.map((message) => message.id)).toEqual(resumed)
|
||||
expect(loads(retried.calls)).toBe(1)
|
||||
expect(loads(enrich(input).calls)).toBe(0)
|
||||
})
|
||||
|
||||
test("resumes the original leading turn after the transcript reconnects", async () => {
|
||||
test("resumes the original leading turn after the transcript reconnects", () => {
|
||||
const memo = new WeakMap<SessionMessageInfo[], string>()
|
||||
const messages: SessionMessageInfo[] = [assistant("msg_latest")]
|
||||
let loads = 0
|
||||
|
||||
const input = {
|
||||
current: () => true,
|
||||
memo,
|
||||
messages: () => messages,
|
||||
more: () => true,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loads += 1
|
||||
loadMore: () => {
|
||||
messages.unshift(assistant("msg_previous_turn"), user("msg_parent"))
|
||||
|
||||
return true
|
||||
},
|
||||
pause: async () => undefined,
|
||||
maxPages: 3,
|
||||
}
|
||||
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads(enrich(input).calls)).toBe(1)
|
||||
messages.splice(0, messages.length, assistant("msg_latest"))
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads(enrich(input).calls)).toBe(1)
|
||||
expect(messages.map((message) => message.id)).toEqual(resumed)
|
||||
expect(loads).toBe(2)
|
||||
|
||||
await enrichLeadingTurn(input)
|
||||
expect(loads).toBe(2)
|
||||
expect(loads(enrich(input).calls)).toBe(0)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["caps background pages when the parent remains outside the window", [assistant("msg_latest")], 3],
|
||||
["does not load before a leading user turn", [user("msg_user"), assistant("msg_latest")], 0],
|
||||
["does not load without an assistant turn", [user("msg_user")], 0],
|
||||
])("%s", async (_name, messages: SessionMessageInfo[], expected) => {
|
||||
let loads = 0
|
||||
|
||||
await enrichLeadingTurn({
|
||||
current: () => true,
|
||||
])("%s", (_name, messages: SessionMessageInfo[], expected) => {
|
||||
const result = enrich({
|
||||
memo: new WeakMap(),
|
||||
messages: () => messages,
|
||||
more: () => true,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loads += 1
|
||||
},
|
||||
pause: async () => undefined,
|
||||
maxPages: 3,
|
||||
loadMore: () => true,
|
||||
})
|
||||
|
||||
expect(loads).toBe(expected)
|
||||
expect(loads(result.calls)).toBe(expected)
|
||||
expect(result.state.status).toBe("ready")
|
||||
})
|
||||
|
||||
test("pauses between history pages and stops once the leading turn has its parent", async () => {
|
||||
test("pauses between history pages and stops once the leading turn has its parent", () => {
|
||||
const pages: SessionMessageInfo[][] = [
|
||||
[assistant("msg_older")],
|
||||
[assistant("msg_previous_turn"), user("msg_parent")],
|
||||
@@ -162,23 +373,21 @@ describe("timeline model", () => {
|
||||
const messages: SessionMessageInfo[] = [assistant("msg_latest"), user("msg_next")]
|
||||
const calls: string[] = []
|
||||
|
||||
await enrichLeadingTurn({
|
||||
current: () => true,
|
||||
const result = enrich({
|
||||
memo: new WeakMap(),
|
||||
messages: () => messages,
|
||||
more: () => pages.length > 0,
|
||||
loading: () => false,
|
||||
loadMore: async () => {
|
||||
loadMore: () => {
|
||||
const page = pages.shift()!
|
||||
messages.unshift(...page)
|
||||
calls.push(`load:${page[0]!.id}`)
|
||||
|
||||
return true
|
||||
},
|
||||
pause: async () => {
|
||||
calls.push("pause")
|
||||
},
|
||||
maxPages: 3,
|
||||
})
|
||||
|
||||
expect(calls).toEqual(["pause", "load:msg_older", "pause", "load:msg_previous_turn"])
|
||||
expect(result.calls).toEqual(["pause", "load", "pause", "load"])
|
||||
expect(calls).toEqual(["load:msg_older", "load:msg_previous_turn"])
|
||||
expect(pages).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,52 +1,177 @@
|
||||
import { createMemo, createResource, type Accessor } from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js"
|
||||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
import { useServer } from "@/runtime/server/current"
|
||||
import type { SessionModel } from "../model"
|
||||
import {
|
||||
createTimelineSyncState,
|
||||
DISPOSED_TIMELINE_SYNC_EVENT,
|
||||
isTimelineReady,
|
||||
isTimelineSyncing,
|
||||
LEADING_TURN_LOAD_TIMEOUT_MS,
|
||||
LEADING_TURN_PAGE_DELAY_MS,
|
||||
leadingTurnNeedsParent,
|
||||
resolveLeadingAssistant,
|
||||
sameTarget,
|
||||
TIMELINE_SYNC_TIMEOUT_MS,
|
||||
timelineSyncError,
|
||||
transitionTimelineSync,
|
||||
type TimelineSyncEffect,
|
||||
type TimelineSyncEvent,
|
||||
type TimelineSyncTarget,
|
||||
} from "./sync-machine"
|
||||
|
||||
const leadingTurnPageDelay = 200
|
||||
// The leading turn first seen in each transcript, kept across route remounts.
|
||||
const leadingAssistants = new WeakMap<SessionMessageInfo[], string>()
|
||||
|
||||
const leadingTurnPageLimit = 3
|
||||
|
||||
// The store preserves the transcript array across prepends and tab switches, and replaces it on eviction.
|
||||
// Remember the original turn so interrupted enrichment can resume without chasing newly prepended turns.
|
||||
const enrichmentTurns = new WeakMap<SessionMessageInfo[], string>()
|
||||
|
||||
export function createTimelineModel(input: { session: Pick<SessionModel, "identity" | "history" | "ownership"> }) {
|
||||
export function createTimelineModel(input: { session: Pick<SessionModel, "identity" | "history"> }) {
|
||||
const server = useServer()
|
||||
const data = server.ctx.data
|
||||
const [syncState, setSyncState] = createSignal(createTimelineSyncState())
|
||||
let syncTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let pauseTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let pageLoad: { controller: AbortController; timer: ReturnType<typeof setTimeout> } | undefined
|
||||
|
||||
const [resource] = createResource(
|
||||
() => input.session.identity.sessionID(),
|
||||
async (id) => {
|
||||
if (!id) return
|
||||
const owner = input.session.ownership.capture()
|
||||
await Promise.all([data.session.message.sync(id), data.session.pending.sync(id)])
|
||||
await enrichLeadingTurn({
|
||||
current: owner.current,
|
||||
messages: () => data.session.message.list(id),
|
||||
more: () => data.session.message.more(id),
|
||||
loading: () => data.session.message.loading(id),
|
||||
loadMore: () => data.session.message.loadMore(id),
|
||||
pause: () => new Promise((resolve) => setTimeout(resolve, leadingTurnPageDelay)),
|
||||
maxPages: leadingTurnPageLimit,
|
||||
}).catch(() => undefined)
|
||||
const target = createMemo(
|
||||
(): TimelineSyncTarget | undefined => {
|
||||
const sessionID = input.session.identity.sessionID()
|
||||
|
||||
return id
|
||||
return sessionID ? { sessionKey: input.session.identity.sessionKey(), sessionID } : undefined
|
||||
},
|
||||
undefined,
|
||||
{ equals: sameTarget },
|
||||
)
|
||||
|
||||
const ready = createMemo(() => {
|
||||
const id = input.session.identity.sessionID()
|
||||
const dispatch = (event: TimelineSyncEvent) =>
|
||||
untrack(() => {
|
||||
const current = syncState()
|
||||
const next = transitionTimelineSync(current, event)
|
||||
|
||||
if (!id || (!resource.loading && resource.latest === id)) return true
|
||||
if (next.state !== current) setSyncState(next.state)
|
||||
next.effects.forEach(run)
|
||||
})
|
||||
|
||||
// Enrich the partial leading group without withholding the already loaded tail. Undelivered inbox rows
|
||||
// load with the inbox, not the transcript, so alone they are no tail; a first prompt shows through its handoff.
|
||||
return (
|
||||
data.session.message.list(id).some((message) => !data.session.input.has(id, message.id)) ||
|
||||
!!server.ctx.handoff.get(id)
|
||||
const run = (effect: TimelineSyncEffect) => {
|
||||
if (effect.type === "sync.start") {
|
||||
clearTimeout(syncTimer)
|
||||
const id = effect.target.sessionID
|
||||
const attempt = effect.attempt
|
||||
const timer = setTimeout(() => dispatch({ type: "sync.timed-out", attempt }), TIMELINE_SYNC_TIMEOUT_MS)
|
||||
|
||||
const settle = (event: TimelineSyncEvent) => {
|
||||
clearTimeout(timer)
|
||||
|
||||
if (syncTimer === timer) syncTimer = undefined
|
||||
dispatch(event)
|
||||
}
|
||||
|
||||
syncTimer = timer
|
||||
Promise.all([data.session.message.sync(id), data.session.pending.sync(id)]).then(
|
||||
() => {
|
||||
const messages = data.session.message.list(id)
|
||||
const assistantID = resolveLeadingAssistant(leadingAssistants, messages)
|
||||
|
||||
settle({
|
||||
type: "sync.succeeded",
|
||||
attempt,
|
||||
assistantID,
|
||||
needsParent: !!assistantID && leadingTurnNeedsParent(messages, assistantID),
|
||||
more: data.session.message.more(id),
|
||||
})
|
||||
},
|
||||
// The error boundary rethrows it, so a rejection without a value still needs one.
|
||||
(error) =>
|
||||
settle({ type: "sync.failed", attempt, error: error instanceof Object ? error : new Error(String(error)) }),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "sync.cancel") {
|
||||
clearTimeout(syncTimer)
|
||||
syncTimer = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "pause.start") {
|
||||
clearTimeout(pauseTimer)
|
||||
pauseTimer = setTimeout(() => {
|
||||
pauseTimer = undefined
|
||||
dispatch({
|
||||
type: "enrich.paused",
|
||||
attempt: effect.attempt,
|
||||
needsParent: leadingTurnNeedsParent(data.session.message.list(effect.sessionID), effect.assistantID),
|
||||
more: data.session.message.more(effect.sessionID),
|
||||
loading: data.session.message.loading(effect.sessionID),
|
||||
})
|
||||
}, LEADING_TURN_PAGE_DELAY_MS)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "pause.cancel") {
|
||||
clearTimeout(pauseTimer)
|
||||
pauseTimer = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
abortPage()
|
||||
|
||||
if (effect.type === "page.abort") return
|
||||
|
||||
const load = {
|
||||
controller: new AbortController(),
|
||||
timer: setTimeout(() => {
|
||||
load.controller.abort()
|
||||
settle(false)
|
||||
}, LEADING_TURN_LOAD_TIMEOUT_MS),
|
||||
}
|
||||
|
||||
// Settles once: the timeout aborts the request, whose rejection then finds the load already gone.
|
||||
const settle = (succeeded: boolean) => {
|
||||
if (pageLoad !== load) return
|
||||
clearTimeout(load.timer)
|
||||
pageLoad = undefined
|
||||
dispatch({
|
||||
type: "enrich.page-settled",
|
||||
attempt: effect.attempt,
|
||||
succeeded,
|
||||
needsParent: leadingTurnNeedsParent(data.session.message.list(effect.sessionID), effect.assistantID),
|
||||
more: data.session.message.more(effect.sessionID),
|
||||
})
|
||||
}
|
||||
|
||||
pageLoad = load
|
||||
data.session.message.loadMore(effect.sessionID, { signal: load.controller.signal }).then(
|
||||
() => settle(true),
|
||||
() => settle(false),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const abortPage = () => {
|
||||
if (!pageLoad) return
|
||||
clearTimeout(pageLoad.timer)
|
||||
pageLoad.controller.abort()
|
||||
pageLoad = undefined
|
||||
}
|
||||
|
||||
createEffect(() => dispatch({ type: "target.changed", target: target() }))
|
||||
onCleanup(() => dispatch(DISPOSED_TIMELINE_SYNC_EVENT))
|
||||
|
||||
// Enrich the partial leading group without withholding the already loaded tail. Undelivered inbox rows
|
||||
// load with the inbox, not the transcript, so alone they are no tail; a first prompt shows through its handoff.
|
||||
const ready = createMemo(() =>
|
||||
isTimelineReady(syncState(), target(), () => {
|
||||
const id = target()?.sessionID
|
||||
|
||||
return (
|
||||
!!id &&
|
||||
(data.session.message.list(id).some((message) => !data.session.input.has(id, message.id)) ||
|
||||
!!server.ctx.handoff.get(id))
|
||||
)
|
||||
}),
|
||||
)
|
||||
|
||||
const more = () => {
|
||||
const id = input.session.identity.sessionID()
|
||||
@@ -62,55 +187,15 @@ export function createTimelineModel(input: { session: Pick<SessionModel, "identi
|
||||
lastUserMessage: input.session.history.lastUserMessage,
|
||||
messages: input.session.history.messages,
|
||||
ready,
|
||||
resource,
|
||||
// Never suspends or throws: `loading` covers only the newest page, and `error` belongs to the current session.
|
||||
resource: {
|
||||
get loading() {
|
||||
return isTimelineSyncing(syncState(), target())
|
||||
},
|
||||
get error() {
|
||||
return timelineSyncError(syncState(), target())
|
||||
},
|
||||
},
|
||||
visibleUserMessages: input.session.history.visibleUserMessages,
|
||||
}
|
||||
}
|
||||
|
||||
export async function enrichLeadingTurn(input: {
|
||||
current: Accessor<boolean>
|
||||
messages: Accessor<SessionMessageInfo[]>
|
||||
more: Accessor<boolean>
|
||||
loading: Accessor<boolean>
|
||||
loadMore: () => Promise<void>
|
||||
pause: () => Promise<void>
|
||||
maxPages: number
|
||||
}) {
|
||||
const messages = input.messages()
|
||||
|
||||
if (!input.current()) return
|
||||
const assistant = enrichmentTurns.get(messages) ?? messages.find((message) => message.type === "assistant")?.id
|
||||
|
||||
if (!assistant) return
|
||||
enrichmentTurns.set(messages, assistant)
|
||||
|
||||
const load = async (pages: number): Promise<void> => {
|
||||
if (
|
||||
!input.current() ||
|
||||
pages >= input.maxPages ||
|
||||
!leadingTurnNeedsParent(input.messages(), assistant) ||
|
||||
!input.more()
|
||||
)
|
||||
return
|
||||
await input.pause()
|
||||
|
||||
if (!input.current() || !leadingTurnNeedsParent(input.messages(), assistant) || !input.more()) return
|
||||
|
||||
if (input.loading()) return load(pages)
|
||||
await input.loadMore()
|
||||
|
||||
return load(pages + 1)
|
||||
}
|
||||
|
||||
return load(0)
|
||||
}
|
||||
|
||||
function leadingTurnNeedsParent(messages: SessionMessageInfo[], id: string) {
|
||||
// Older pages can start mid-turn too; only complete the turn that was visible on entry.
|
||||
const assistant = messages.findIndex((message) => message.id === id)
|
||||
|
||||
if (assistant === -1) return false
|
||||
const boundary = messages.findIndex((message) => message.type === "user" || message.type === "shell")
|
||||
|
||||
return boundary === -1 || assistant < boundary
|
||||
}
|
||||
|
||||
@@ -69,6 +69,59 @@ test("reports a divergent native offset once and ignores equal offsets and unrel
|
||||
}
|
||||
})
|
||||
|
||||
test.each([
|
||||
[
|
||||
"in a later batch",
|
||||
(main: Node, wrap: ChildNode, viewport: Node, mutations: ReturnType<typeof controlledMutations>) => {
|
||||
const staging = viewport.ownerDocument!.createElement("div")
|
||||
mutations.batch(() => {
|
||||
wrap.remove()
|
||||
staging.append(viewport)
|
||||
})
|
||||
mutations.batch(() => main.appendChild(staging))
|
||||
},
|
||||
],
|
||||
[
|
||||
"in the same batch",
|
||||
(main: Node, wrap: ChildNode, viewport: Node, mutations: ReturnType<typeof controlledMutations>) =>
|
||||
mutations.batch(() => {
|
||||
wrap.remove()
|
||||
main.appendChild(viewport)
|
||||
}),
|
||||
],
|
||||
])("restores a view reparented after its ancestor was removed %s", async (_name, move) => {
|
||||
const frame = openFrame()
|
||||
const targetWindow = frame.targetWindow
|
||||
const mutations = controlledMutations(targetWindow)
|
||||
const main = targetWindow.document.createElement("main")
|
||||
const wrap = targetWindow.document.createElement("div")
|
||||
const viewport = targetWindow.document.createElement("div")
|
||||
wrap.append(viewport)
|
||||
main.append(wrap)
|
||||
targetWindow.document.body.append(main)
|
||||
|
||||
const instance = attachedVirtualizer(viewport, { scrollOffset: 79_400, isScrollingResetDelay: 0 })
|
||||
const connections: boolean[] = []
|
||||
|
||||
const cleanup = observeElementOffsetReconnectAware(
|
||||
instance,
|
||||
(offset) => {
|
||||
instance.scrollOffset = offset
|
||||
},
|
||||
() => connections.push(viewport.isConnected),
|
||||
)
|
||||
|
||||
try {
|
||||
move(main, wrap, viewport, mutations)
|
||||
await frames(2, targetWindow)
|
||||
expect(connections).toEqual([true])
|
||||
expect(instance.scrollOffset).toBe(0)
|
||||
} finally {
|
||||
cleanup()
|
||||
frame.close()
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps checking until stale reset-delay callbacks can no longer win", async () => {
|
||||
const frame = openFrame()
|
||||
const targetWindow = frame.targetWindow
|
||||
@@ -223,6 +276,10 @@ function controlledMutations(targetWindow: Window & typeof globalThis) {
|
||||
Object.defineProperty(targetWindow, "MutationObserver", { value: ControlledMutationObserver })
|
||||
|
||||
return {
|
||||
batch(change: () => void) {
|
||||
change()
|
||||
flush()
|
||||
},
|
||||
append(parent: Node, node: Node) {
|
||||
parent.appendChild(node)
|
||||
flush()
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { observeElementOffset, type Virtualizer } from "@tanstack/solid-virtual"
|
||||
import {
|
||||
createReconnectState,
|
||||
DISPOSED_RECONNECT_EVENT,
|
||||
isReconnectObserverActive,
|
||||
transitionReconnect,
|
||||
type ReconnectEffect,
|
||||
type ReconnectEvent,
|
||||
} from "./reconnect-machine"
|
||||
|
||||
export function observeElementOffsetReconnectAware<TScrollElement extends Element, TItemElement extends Element>(
|
||||
instance: Virtualizer<TScrollElement, TItemElement>,
|
||||
callback: (offset: number, isScrolling: boolean) => void,
|
||||
onReconnect?: () => void,
|
||||
) {
|
||||
let active = true
|
||||
const element = instance.scrollElement
|
||||
let state = createReconnectState(!!element?.isConnected)
|
||||
let frame: number | undefined
|
||||
|
||||
// TanStack resets isScrolling on a timer that reports the offset of the last scroll event. A virtualizer
|
||||
// write since then (prepend anchoring, size compensation) may not have dispatched its scroll event yet, and
|
||||
// compensating from that stale offset would undo the write, so a settled scroll reads the live scrollTop
|
||||
// (vertical only, like the reconnect check below).
|
||||
const deliver = (offset: number, isScrolling: boolean) => {
|
||||
if (!active) return
|
||||
if (!isReconnectObserverActive(state)) return
|
||||
callback(isScrolling || !element?.isConnected ? offset : element.scrollTop, isScrolling)
|
||||
}
|
||||
|
||||
@@ -23,57 +32,53 @@ export function observeElementOffsetReconnectAware<TScrollElement extends Elemen
|
||||
|
||||
if (!element || !targetWindow || !root)
|
||||
return () => {
|
||||
active = false
|
||||
state = transitionReconnect(state, DISPOSED_RECONNECT_EVENT).state
|
||||
cleanupOffset?.()
|
||||
}
|
||||
|
||||
// Cached views can be constructed before their first attachment to the page.
|
||||
let removed = !element.isConnected
|
||||
let frame: number | undefined
|
||||
|
||||
const clearCheck = () => {
|
||||
if (frame === undefined) return
|
||||
targetWindow.cancelAnimationFrame(frame)
|
||||
frame = undefined
|
||||
const dispatch = (event: ReconnectEvent) => {
|
||||
const next = transitionReconnect(state, event)
|
||||
state = next.state
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
const startCheck = () => {
|
||||
clearCheck()
|
||||
const deadline = targetWindow.performance.now() + instance.options.isScrollingResetDelay
|
||||
let framesAfterDeadline = 0
|
||||
const run = (effect: ReconnectEffect) => {
|
||||
if (effect.type === "reconnected") return onReconnect?.()
|
||||
|
||||
const check = (time: number) => {
|
||||
if (effect.type === "offset.deliver") return deliver(effect.offset, false)
|
||||
|
||||
if (frame !== undefined) targetWindow.cancelAnimationFrame(frame)
|
||||
frame = undefined
|
||||
|
||||
if (effect.type === "frame.cancel") return
|
||||
const attempt = effect.attempt
|
||||
frame = targetWindow.requestAnimationFrame((time) => {
|
||||
frame = undefined
|
||||
|
||||
if (
|
||||
element.isConnected &&
|
||||
(instance.scrollOffset === null || Math.abs(element.scrollTop - instance.scrollOffset) > 1)
|
||||
)
|
||||
deliver(element.scrollTop, false)
|
||||
|
||||
if (time >= deadline) framesAfterDeadline += 1
|
||||
|
||||
if (framesAfterDeadline >= 2) return
|
||||
frame = targetWindow.requestAnimationFrame(check)
|
||||
}
|
||||
|
||||
frame = targetWindow.requestAnimationFrame(check)
|
||||
dispatch({
|
||||
type: "frame",
|
||||
attempt,
|
||||
time,
|
||||
connected: element.isConnected,
|
||||
nativeTop: element.scrollTop,
|
||||
virtualOffset: instance.scrollOffset,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const observer = new targetWindow.MutationObserver((records) => {
|
||||
if (!active) return
|
||||
records.forEach((record) => {
|
||||
if (record.target === element || element.contains(record.target)) return
|
||||
if (!isReconnectObserverActive(state)) return
|
||||
const connected = element.isConnected
|
||||
|
||||
if (mutationNodesContainElement(record.removedNodes, element)) {
|
||||
removed = true
|
||||
clearCheck()
|
||||
}
|
||||
// A detached view stays detached until it is back in the document, whatever else the page changes.
|
||||
if (!connected && state.status === "detached") return
|
||||
const added = connected && state.status !== "detached" && reattached(records, element)
|
||||
|
||||
if (!removed || !element.isConnected || !mutationNodesContainElement(record.addedNodes, element)) return
|
||||
removed = false
|
||||
onReconnect?.()
|
||||
startCheck()
|
||||
if (connected && state.status !== "detached" && !added) return
|
||||
dispatch({
|
||||
type: "mutated",
|
||||
connected,
|
||||
added,
|
||||
deadline: targetWindow.performance.now() + instance.options.isScrollingResetDelay,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -81,13 +86,21 @@ export function observeElementOffsetReconnectAware<TScrollElement extends Elemen
|
||||
observer.observe(root, { childList: true, subtree: true })
|
||||
|
||||
return () => {
|
||||
active = false
|
||||
observer.disconnect()
|
||||
clearCheck()
|
||||
dispatch(DISPOSED_RECONNECT_EVENT)
|
||||
cleanupOffset?.()
|
||||
}
|
||||
}
|
||||
|
||||
function mutationNodesContainElement(nodes: Iterable<Node>, element: Element) {
|
||||
return [...nodes].some((node) => node === element || node.contains(element))
|
||||
// Whether a record outside the element inserted it or one of its ancestors: a move within the page.
|
||||
function reattached(records: MutationRecord[], element: Element) {
|
||||
for (const record of records) {
|
||||
if (record.target === element || element.contains(record.target)) continue
|
||||
|
||||
for (const node of record.addedNodes) {
|
||||
if (node === element || node.contains(element)) return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
activeQuote,
|
||||
createQuoteState,
|
||||
DISPOSED_QUOTE_EVENT,
|
||||
isQuotePressing,
|
||||
quoteToolbarView,
|
||||
RESET_QUOTE_EVENT,
|
||||
ROOT_RESIZED_QUOTE_EVENT,
|
||||
SELECTION_CHANGED_QUOTE_EVENT,
|
||||
SELECTION_CLEARED_QUOTE_EVENT,
|
||||
transitionQuote,
|
||||
VIEWPORT_MOVED_QUOTE_EVENT,
|
||||
type ActiveQuote,
|
||||
type QuoteEffect,
|
||||
type QuoteEvent,
|
||||
type QuoteState,
|
||||
} from "./quote-machine"
|
||||
import type { TimelineSelection } from "./quote-text"
|
||||
|
||||
const node = document.createTextNode("selected text")
|
||||
|
||||
const selected: TimelineSelection = {
|
||||
range: document.createRange(),
|
||||
start: { node, offset: 0 },
|
||||
end: { node, offset: 13 },
|
||||
backward: false,
|
||||
}
|
||||
|
||||
const bounds = { top: 0, bottom: 600, left: 0, right: 800 }
|
||||
|
||||
const extent = { top: 100, bottom: 120, left: 10, right: 200, short: true, backward: false }
|
||||
|
||||
const quote = (text = "selected text", inView = true): ActiveQuote => ({
|
||||
text,
|
||||
truncated: false,
|
||||
selected,
|
||||
horizontal: undefined,
|
||||
placement: { bounds, extent: inView ? extent : undefined },
|
||||
})
|
||||
|
||||
const escape: QuoteEvent = { type: "escape", range: selected.range, toolbarFocused: false }
|
||||
|
||||
function play(events: QuoteEvent[], state: QuoteState = createQuoteState()) {
|
||||
const effects: QuoteEffect[] = []
|
||||
|
||||
const final = events.reduce((current, event) => {
|
||||
const next = transitionQuote(current, event)
|
||||
effects.push(...next.effects)
|
||||
|
||||
return next.state
|
||||
}, state)
|
||||
|
||||
return { state: final, effects }
|
||||
}
|
||||
|
||||
const settleOf = (state: QuoteState) => state.settle ?? -1
|
||||
|
||||
// A keyboard selection settles and reads as `text`.
|
||||
function select(state: QuoteState, text = "selected text") {
|
||||
const changed = transitionQuote(state, SELECTION_CHANGED_QUOTE_EVENT).state
|
||||
|
||||
return play(
|
||||
[
|
||||
{ type: "settle.ready", attempt: settleOf(changed) },
|
||||
{ type: "quote.measured", quote: quote(text) },
|
||||
],
|
||||
changed,
|
||||
).state
|
||||
}
|
||||
|
||||
function shown() {
|
||||
return select(createQuoteState())
|
||||
}
|
||||
|
||||
describe("quote machine", () => {
|
||||
test("a press that never sees its release no longer blocks the toolbar after a session switch", () => {
|
||||
const pressed = transitionQuote(createQuoteState(), { type: "pointer.down" })
|
||||
expect(pressed.effects).toEqual([{ type: "press.watch" }])
|
||||
expect(isQuotePressing(pressed.state)).toBe(true)
|
||||
|
||||
// The session changes mid-press and the pointerup never reaches the document.
|
||||
const reset = transitionQuote(pressed.state, RESET_QUOTE_EVENT)
|
||||
expect(reset.effects).toEqual([{ type: "press.unwatch" }])
|
||||
expect(isQuotePressing(reset.state)).toBe(false)
|
||||
|
||||
// Shift+Arrow then selects text from the keyboard.
|
||||
const changed = transitionQuote(reset.state, SELECTION_CHANGED_QUOTE_EVENT)
|
||||
expect(changed.effects).toEqual([{ type: "settle.schedule", attempt: settleOf(changed.state) }])
|
||||
const read = transitionQuote(changed.state, { type: "settle.ready", attempt: settleOf(changed.state) })
|
||||
expect(read.effects).toEqual([{ type: "quote.read" }])
|
||||
expect(quoteToolbarView(transitionQuote(read.state, { type: "quote.measured", quote: quote() }).state)).toEqual({
|
||||
text: "selected text",
|
||||
truncated: false,
|
||||
bounds,
|
||||
extent,
|
||||
})
|
||||
})
|
||||
|
||||
test("a release seen as a primary-button-up move reads the drag selection", () => {
|
||||
const result = play([{ type: "pointer.down" }, SELECTION_CHANGED_QUOTE_EVENT, SELECTION_CHANGED_QUOTE_EVENT])
|
||||
// The selection waits for the release.
|
||||
expect(result.effects).toEqual([{ type: "press.watch" }])
|
||||
|
||||
const released = transitionQuote(result.state, { type: "pointer.up", collapsed: false })
|
||||
expect(released.effects).toEqual([
|
||||
{ type: "press.unwatch" },
|
||||
{ type: "settle.schedule", attempt: settleOf(released.state) },
|
||||
])
|
||||
|
||||
const read = play(
|
||||
[
|
||||
{ type: "settle.ready", attempt: settleOf(released.state) },
|
||||
{ type: "quote.measured", quote: quote() },
|
||||
],
|
||||
released.state,
|
||||
)
|
||||
|
||||
expect(read.effects).toEqual([{ type: "quote.read" }])
|
||||
expect(activeQuote(read.state)?.text).toBe("selected text")
|
||||
})
|
||||
|
||||
test("a settle timer from before a press is ignored", () => {
|
||||
const changed = transitionQuote(createQuoteState(), SELECTION_CHANGED_QUOTE_EVENT).state
|
||||
const pressed = transitionQuote(changed, { type: "pointer.down" })
|
||||
expect(pressed.effects).toEqual([{ type: "settle.cancel" }, { type: "press.watch" }])
|
||||
expect(transitionQuote(pressed.state, { type: "settle.ready", attempt: settleOf(changed) }).state).toBe(
|
||||
pressed.state,
|
||||
)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["a reset", RESET_QUOTE_EVENT],
|
||||
["a new selection", SELECTION_CHANGED_QUOTE_EVENT],
|
||||
["a cleared selection", SELECTION_CLEARED_QUOTE_EVENT],
|
||||
])("the unselectable-press clear is cancelled by %s", (_name, event) => {
|
||||
const pressed = transitionQuote(shown(), { type: "pointer.down", clearRange: selected.range })
|
||||
const clear = pressed.state.status === "shown" ? pressed.state.clear : undefined
|
||||
expect(clear).toBeDefined()
|
||||
expect(pressed.effects).toContainEqual({ type: "clear.schedule", attempt: clear!.attempt })
|
||||
|
||||
const next = transitionQuote(pressed.state, event)
|
||||
expect(next.effects).toContainEqual({ type: "clear.cancel" })
|
||||
|
||||
const late = transitionQuote(next.state, { type: "clear.ready", attempt: clear!.attempt })
|
||||
expect(late.state).toBe(next.state)
|
||||
expect(late.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("the unselectable-press clear runs while its press is current", () => {
|
||||
const pressed = transitionQuote(shown(), { type: "pointer.down", clearRange: selected.range }).state
|
||||
const clear = pressed.status === "shown" ? pressed.clear! : undefined
|
||||
|
||||
expect(transitionQuote(pressed, { type: "clear.ready", attempt: clear!.attempt }).effects).toEqual([
|
||||
{ type: "selection.clearIfSame", range: clear!.range },
|
||||
])
|
||||
})
|
||||
|
||||
test.each([
|
||||
["a cleared selection", SELECTION_CLEARED_QUOTE_EVENT],
|
||||
["Escape", escape],
|
||||
["a reset", RESET_QUOTE_EVENT],
|
||||
["disposal", DISPOSED_QUOTE_EVENT],
|
||||
])("%s cancels pending place and reflow frames", (_name, event) => {
|
||||
const pending = play([VIEWPORT_MOVED_QUOTE_EVENT, ROOT_RESIZED_QUOTE_EVENT], shown()).state
|
||||
const next = transitionQuote(pending, event)
|
||||
|
||||
expect(next.effects).toContainEqual({ type: "place.cancel" })
|
||||
expect(next.effects).toContainEqual({ type: "reflow.cancel" })
|
||||
expect(quoteToolbarView(next.state)).toBeUndefined()
|
||||
})
|
||||
|
||||
test("scrolling the selection out of view hides the toolbar and scrolling back restores it", () => {
|
||||
const state = shown()
|
||||
const moved = transitionQuote(state, VIEWPORT_MOVED_QUOTE_EVENT)
|
||||
expect(moved.effects).toEqual([{ type: "place.schedule", attempt: state.attempt }])
|
||||
// Further scrolls share the pending frame.
|
||||
expect(transitionQuote(moved.state, VIEWPORT_MOVED_QUOTE_EVENT).state).toBe(moved.state)
|
||||
|
||||
const measure = transitionQuote(moved.state, { type: "place.ready", attempt: state.attempt })
|
||||
expect(measure.effects).toEqual([{ type: "place.measure", quote: activeQuote(state)! }])
|
||||
|
||||
const away = transitionQuote(measure.state, {
|
||||
type: "place.measured",
|
||||
collapsed: false,
|
||||
placement: { bounds, extent: undefined },
|
||||
}).state
|
||||
|
||||
expect(quoteToolbarView(away)).toBeUndefined()
|
||||
expect(activeQuote(away)?.text).toBe("selected text")
|
||||
|
||||
const back = transitionQuote(away, { type: "place.measured", collapsed: false, placement: { bounds, extent } })
|
||||
expect(quoteToolbarView(back.state)?.extent).toEqual(extent)
|
||||
|
||||
// The virtualizer removed the selected rows.
|
||||
expect(transitionQuote(away, { type: "place.measured", collapsed: true, placement: undefined }).state.status).toBe(
|
||||
"idle",
|
||||
)
|
||||
})
|
||||
|
||||
test("Escape keeps the same selection dismissed until it changes or clears", () => {
|
||||
const dismissed = transitionQuote(shown(), { type: "escape", range: selected.range, toolbarFocused: true })
|
||||
expect(dismissed.state.status).toBe("dismissed")
|
||||
expect(dismissed.effects).toEqual([{ type: "focus.root" }])
|
||||
|
||||
const changed = transitionQuote(dismissed.state, SELECTION_CHANGED_QUOTE_EVENT).state
|
||||
const read = transitionQuote(changed, { type: "settle.ready", attempt: settleOf(changed) })
|
||||
expect(read.effects).toEqual([{ type: "quote.read", dismissed: selected.range }])
|
||||
|
||||
// The browser still holds the dismissed range.
|
||||
expect(transitionQuote(read.state, { type: "quote.measured", quote: undefined, dismissed: true }).state).toBe(
|
||||
read.state,
|
||||
)
|
||||
|
||||
// A different range shows again.
|
||||
expect(transitionQuote(read.state, { type: "quote.measured", quote: quote("other text") }).state.status).toBe(
|
||||
"shown",
|
||||
)
|
||||
expect(transitionQuote(dismissed.state, SELECTION_CLEARED_QUOTE_EVENT).state.status).toBe("idle")
|
||||
})
|
||||
|
||||
test("a resize reads the quote again only once the press is released", () => {
|
||||
const state = shown()
|
||||
const pressed = transitionQuote(state, { type: "pointer.down" }).state
|
||||
expect(transitionQuote(pressed, ROOT_RESIZED_QUOTE_EVENT).state).toBe(pressed)
|
||||
|
||||
const resized = transitionQuote(state, ROOT_RESIZED_QUOTE_EVENT)
|
||||
expect(resized.effects).toEqual([{ type: "reflow.schedule", attempt: state.attempt }])
|
||||
expect(transitionQuote(resized.state, { type: "reflow.ready", attempt: state.attempt }).effects).toEqual([
|
||||
{ type: "quote.read" },
|
||||
])
|
||||
})
|
||||
|
||||
test("the toolbar stays up while a changed selection settles", () => {
|
||||
const changed = transitionQuote(shown(), SELECTION_CHANGED_QUOTE_EVENT).state
|
||||
expect(quoteToolbarView(changed)?.text).toBe("selected text")
|
||||
expect(activeQuote(select(changed, "longer selected text"))?.text).toBe("longer selected text")
|
||||
})
|
||||
|
||||
test("reset from a quiet idle state writes nothing", () => {
|
||||
const state = createQuoteState()
|
||||
expect(transitionQuote(state, RESET_QUOTE_EVENT).state).toBe(state)
|
||||
expect(transitionQuote(state, DISPOSED_QUOTE_EVENT).state).toBe(state)
|
||||
expect(transitionQuote(state, SELECTION_CLEARED_QUOTE_EVENT).state).toBe(state)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,355 @@
|
||||
import type { TimelineSelection } from "./quote-text"
|
||||
|
||||
// A new selection waits this long without changing before the toolbar reads it.
|
||||
export const QUOTE_SETTLE_MS = 150
|
||||
|
||||
export type QuoteRect = {
|
||||
readonly top: number
|
||||
readonly bottom: number
|
||||
readonly left: number
|
||||
readonly right: number
|
||||
}
|
||||
|
||||
export type QuoteExtent = QuoteRect & {
|
||||
readonly short: boolean
|
||||
readonly backward: boolean
|
||||
}
|
||||
|
||||
export type QuoteHorizontal = {
|
||||
readonly left: number
|
||||
readonly right: number
|
||||
readonly origin: number
|
||||
}
|
||||
|
||||
/** Where the toolbar can sit. `extent` is unset while the selection is scrolled out of `bounds`. */
|
||||
export type QuotePlacement = {
|
||||
readonly bounds: QuoteRect
|
||||
readonly extent: QuoteExtent | undefined
|
||||
}
|
||||
|
||||
export type ActiveQuote = {
|
||||
readonly text: string
|
||||
readonly truncated: boolean
|
||||
readonly selected: TimelineSelection
|
||||
readonly horizontal: QuoteHorizontal | undefined
|
||||
readonly placement: QuotePlacement | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* The quote toolbar for text selected in the timeline. `pressing` is a primary press outside the toolbar that has not
|
||||
* been released: a selection made with the pointer is read only after the release. Each pending timer or frame keeps
|
||||
* the attempt it was scheduled with, and its result applies only while the state still holds that attempt.
|
||||
*
|
||||
* - `idle`: no toolbar.
|
||||
* - `shown`: the toolbar for `quote`, which stays up while a changed selection settles.
|
||||
* - `dismissed`: Escape closed the toolbar for `range`, which stays dismissed until the selection changes or clears.
|
||||
*/
|
||||
export type QuoteState =
|
||||
| {
|
||||
readonly status: "idle"
|
||||
readonly attempt: number
|
||||
readonly pressing: boolean
|
||||
readonly settle?: number
|
||||
}
|
||||
| {
|
||||
readonly status: "shown"
|
||||
readonly attempt: number
|
||||
readonly pressing: boolean
|
||||
readonly settle?: number
|
||||
readonly place?: number
|
||||
readonly reflow?: number
|
||||
/** A press on unselectable chrome clears `range` once the press is handled, if it is still selected. */
|
||||
readonly clear?: { readonly attempt: number; readonly range: Range }
|
||||
readonly quote: ActiveQuote
|
||||
}
|
||||
| {
|
||||
readonly status: "dismissed"
|
||||
readonly attempt: number
|
||||
readonly pressing: boolean
|
||||
readonly settle?: number
|
||||
readonly range: Range
|
||||
}
|
||||
|
||||
export type QuoteEvent =
|
||||
| { readonly type: "pointer.down"; readonly clearRange?: Range }
|
||||
| { readonly type: "pointer.up"; readonly collapsed: boolean }
|
||||
| { readonly type: "selection.changed"; readonly collapsed: boolean }
|
||||
| { readonly type: "settle.ready"; readonly attempt: number }
|
||||
/** The selection as read now. `dismissed`: it is still the range Escape dismissed. */
|
||||
| { readonly type: "quote.measured"; readonly quote: ActiveQuote | undefined; readonly dismissed?: boolean }
|
||||
| { readonly type: "viewport.moved" }
|
||||
| { readonly type: "place.ready"; readonly attempt: number }
|
||||
/** `collapsed`: the virtualizer removed the selected rows. */
|
||||
| { readonly type: "place.measured"; readonly collapsed: boolean; readonly placement: QuotePlacement | undefined }
|
||||
| { readonly type: "root.resized" }
|
||||
| { readonly type: "reflow.ready"; readonly attempt: number }
|
||||
| { readonly type: "clear.ready"; readonly attempt: number }
|
||||
| { readonly type: "escape"; readonly range: Range | undefined; readonly toolbarFocused: boolean }
|
||||
| { readonly type: "reset" }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type QuoteEffect =
|
||||
| { readonly type: "press.watch" }
|
||||
| { readonly type: "press.unwatch" }
|
||||
| { readonly type: "settle.schedule"; readonly attempt: number }
|
||||
| { readonly type: "settle.cancel" }
|
||||
| { readonly type: "quote.read"; readonly dismissed?: Range }
|
||||
| { readonly type: "place.schedule"; readonly attempt: number }
|
||||
| { readonly type: "place.cancel" }
|
||||
| { readonly type: "place.measure"; readonly quote: ActiveQuote }
|
||||
| { readonly type: "reflow.schedule"; readonly attempt: number }
|
||||
| { readonly type: "reflow.cancel" }
|
||||
| { readonly type: "clear.schedule"; readonly attempt: number }
|
||||
| { readonly type: "clear.cancel" }
|
||||
| { readonly type: "selection.clearIfSame"; readonly range: Range }
|
||||
| { readonly type: "focus.root" }
|
||||
|
||||
export type QuoteTransition = {
|
||||
readonly state: QuoteState
|
||||
readonly effects: readonly QuoteEffect[]
|
||||
}
|
||||
|
||||
// Shared events for the frequent dispatches, so scrolling and resizing allocate nothing.
|
||||
export const VIEWPORT_MOVED_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "viewport.moved" })
|
||||
|
||||
export const ROOT_RESIZED_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "root.resized" })
|
||||
|
||||
export const SELECTION_CHANGED_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "selection.changed", collapsed: false })
|
||||
|
||||
export const SELECTION_CLEARED_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "selection.changed", collapsed: true })
|
||||
|
||||
export const RESET_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "reset" })
|
||||
|
||||
export const DISPOSED_QUOTE_EVENT: QuoteEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
const NO_EFFECTS: readonly QuoteEffect[] = Object.freeze([])
|
||||
|
||||
const PRESS_WATCH: QuoteEffect = Object.freeze({ type: "press.watch" })
|
||||
|
||||
const PRESS_UNWATCH: QuoteEffect = Object.freeze({ type: "press.unwatch" })
|
||||
|
||||
const SETTLE_CANCEL: QuoteEffect = Object.freeze({ type: "settle.cancel" })
|
||||
|
||||
const PLACE_CANCEL: QuoteEffect = Object.freeze({ type: "place.cancel" })
|
||||
|
||||
const REFLOW_CANCEL: QuoteEffect = Object.freeze({ type: "reflow.cancel" })
|
||||
|
||||
const CLEAR_CANCEL: QuoteEffect = Object.freeze({ type: "clear.cancel" })
|
||||
|
||||
const QUOTE_READ: QuoteEffect = Object.freeze({ type: "quote.read" })
|
||||
|
||||
const FOCUS_ROOT: QuoteEffect = Object.freeze({ type: "focus.root" })
|
||||
|
||||
export function createQuoteState(): QuoteState {
|
||||
return { status: "idle", attempt: 0, pressing: false }
|
||||
}
|
||||
|
||||
export function transitionQuote(state: QuoteState, event: QuoteEvent): QuoteTransition {
|
||||
if (event.type === "reset" || event.type === "disposed") {
|
||||
if (state.status === "idle" && !state.pressing && state.settle === undefined) return unchanged(state)
|
||||
|
||||
return idle(state, false)
|
||||
}
|
||||
|
||||
if (event.type === "pointer.down") {
|
||||
const attempt = state.attempt + 1
|
||||
const clear = state.status === "shown" && event.clearRange ? { attempt, range: event.clearRange } : undefined
|
||||
|
||||
// A press ends any settling selection: the release reads it again.
|
||||
return {
|
||||
state:
|
||||
state.status === "shown"
|
||||
? { ...state, attempt, pressing: true, settle: undefined, clear }
|
||||
: { ...state, attempt, pressing: true, settle: undefined },
|
||||
effects: [
|
||||
...(state.settle !== undefined ? [SETTLE_CANCEL] : NO_EFFECTS),
|
||||
...(state.status === "shown" && state.clear ? [CLEAR_CANCEL] : NO_EFFECTS),
|
||||
...(state.pressing ? NO_EFFECTS : [PRESS_WATCH]),
|
||||
...(clear ? [{ type: "clear.schedule" as const, attempt }] : NO_EFFECTS),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "pointer.up") {
|
||||
if (!state.pressing) return unchanged(state)
|
||||
|
||||
if (event.collapsed) return idle(state, false)
|
||||
|
||||
return settle({ ...state, pressing: false }, [PRESS_UNWATCH])
|
||||
}
|
||||
|
||||
if (event.type === "selection.changed") {
|
||||
// A cleared selection closes at once, even mid-press.
|
||||
if (event.collapsed) {
|
||||
if (state.status === "idle" && state.settle === undefined) return unchanged(state)
|
||||
|
||||
return idle(state, true)
|
||||
}
|
||||
|
||||
// A selection still being made with the pointer is read once it is released.
|
||||
if (state.pressing) {
|
||||
if (state.status !== "shown" || !state.clear) return unchanged(state)
|
||||
|
||||
return { state: { ...state, clear: undefined }, effects: [CLEAR_CANCEL] }
|
||||
}
|
||||
|
||||
return settle(state, NO_EFFECTS)
|
||||
}
|
||||
|
||||
if (event.type === "settle.ready") {
|
||||
if (state.settle !== event.attempt || state.pressing) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, settle: undefined },
|
||||
effects: [state.status === "dismissed" ? { type: "quote.read", dismissed: state.range } : QUOTE_READ],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "quote.measured") {
|
||||
if (event.dismissed && state.status === "dismissed") return unchanged(state)
|
||||
|
||||
if (!event.quote) return idle(state, true)
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "shown",
|
||||
attempt: state.attempt + 1,
|
||||
pressing: state.pressing,
|
||||
settle: state.settle,
|
||||
quote: event.quote,
|
||||
},
|
||||
effects: state.status === "shown" ? handles(state, { place: true, reflow: true, clear: true }) : NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "escape") {
|
||||
if (state.status !== "shown") return unchanged(state)
|
||||
|
||||
const effects = [
|
||||
...handles(state, { settle: true, place: true, reflow: true, clear: true }),
|
||||
...(event.toolbarFocused ? [FOCUS_ROOT] : NO_EFFECTS),
|
||||
]
|
||||
|
||||
if (!event.range)
|
||||
return { state: { status: "idle", attempt: state.attempt + 1, pressing: state.pressing }, effects }
|
||||
|
||||
return {
|
||||
state: { status: "dismissed", attempt: state.attempt + 1, pressing: state.pressing, range: event.range },
|
||||
effects,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "shown") return unchanged(state)
|
||||
|
||||
if (event.type === "viewport.moved") {
|
||||
if (state.place !== undefined) return unchanged(state)
|
||||
|
||||
return { state: { ...state, place: state.attempt }, effects: [{ type: "place.schedule", attempt: state.attempt }] }
|
||||
}
|
||||
|
||||
if (event.type === "place.ready") {
|
||||
if (state.place !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, place: undefined }, effects: [{ type: "place.measure", quote: state.quote }] }
|
||||
}
|
||||
|
||||
if (event.type === "place.measured") {
|
||||
if (event.collapsed) return idle(state, true)
|
||||
|
||||
return { state: { ...state, quote: { ...state.quote, placement: event.placement } }, effects: NO_EFFECTS }
|
||||
}
|
||||
|
||||
// A resize reflows the selected text, so the quote is read again once the press, if any, is released.
|
||||
if (event.type === "root.resized") {
|
||||
if (state.reflow !== undefined || state.pressing) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, reflow: state.attempt },
|
||||
effects: [{ type: "reflow.schedule", attempt: state.attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "reflow.ready") {
|
||||
if (state.reflow !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, reflow: undefined }, effects: state.pressing ? NO_EFFECTS : [QUOTE_READ] }
|
||||
}
|
||||
|
||||
if (state.clear?.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, clear: undefined },
|
||||
effects: [{ type: "selection.clearIfSame", range: state.clear.range }],
|
||||
}
|
||||
}
|
||||
|
||||
export function activeQuote(state: QuoteState) {
|
||||
return state.status === "shown" ? state.quote : undefined
|
||||
}
|
||||
|
||||
/** The toolbar's content and placement, while the selection is in view. */
|
||||
export function quoteToolbarView(state: QuoteState) {
|
||||
if (state.status !== "shown" || !state.quote.placement?.extent) return undefined
|
||||
|
||||
return {
|
||||
text: state.quote.text,
|
||||
truncated: state.quote.truncated,
|
||||
bounds: state.quote.placement.bounds,
|
||||
extent: state.quote.placement.extent,
|
||||
}
|
||||
}
|
||||
|
||||
export function isQuotePressing(state: QuoteState) {
|
||||
return state.pressing
|
||||
}
|
||||
|
||||
export function canScheduleQuotePlace(state: QuoteState) {
|
||||
return state.status === "shown" && state.place === undefined
|
||||
}
|
||||
|
||||
export function canScheduleQuoteReflow(state: QuoteState) {
|
||||
return state.status === "shown" && state.reflow === undefined && !state.pressing
|
||||
}
|
||||
|
||||
// Leaving the toolbar cancels every timer and frame it scheduled; `keepPress` keeps watching a press in progress.
|
||||
function idle(state: QuoteState, keepPress: boolean): QuoteTransition {
|
||||
const pressing = keepPress && state.pressing
|
||||
|
||||
return {
|
||||
state: { status: "idle", attempt: state.attempt + 1, pressing },
|
||||
effects: [
|
||||
...handles(state, { settle: true, place: true, reflow: true, clear: true }),
|
||||
...(state.pressing && !pressing ? [PRESS_UNWATCH] : NO_EFFECTS),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
// A selection that changed waits to settle before it is read again; an open toolbar stays meanwhile.
|
||||
function settle(state: QuoteState, effects: readonly QuoteEffect[]): QuoteTransition {
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { ...state, attempt, settle: attempt },
|
||||
effects: [
|
||||
...effects,
|
||||
...(state.settle !== undefined ? [SETTLE_CANCEL] : NO_EFFECTS),
|
||||
{ type: "settle.schedule", attempt },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function handles(
|
||||
state: QuoteState,
|
||||
which: { settle?: boolean; place?: boolean; reflow?: boolean; clear?: boolean },
|
||||
): QuoteEffect[] {
|
||||
return [
|
||||
...(which.settle && state.settle !== undefined ? [SETTLE_CANCEL] : NO_EFFECTS),
|
||||
...(which.place && state.status === "shown" && state.place !== undefined ? [PLACE_CANCEL] : NO_EFFECTS),
|
||||
...(which.reflow && state.status === "shown" && state.reflow !== undefined ? [REFLOW_CANCEL] : NO_EFFECTS),
|
||||
...(which.clear && state.status === "shown" && state.clear ? [CLEAR_CANCEL] : NO_EFFECTS),
|
||||
]
|
||||
}
|
||||
|
||||
function unchanged(state: QuoteState): QuoteTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createEffect, on, onCleanup, Show } from "solid-js"
|
||||
import { createEffect, createMemo, createSignal, on, onCleanup, Show, untrack } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { Portal } from "solid-js/web"
|
||||
import { makeEventListener } from "@solid-primitives/event-listener"
|
||||
@@ -12,6 +12,26 @@ import { useLanguage } from "@/runtime/i18n/language"
|
||||
import type { QuoteSource } from "@/composer/quote-source"
|
||||
import { quotePosition } from "@/composer/quote-position"
|
||||
import { captureQuoteSource } from "./quote-highlight"
|
||||
import {
|
||||
activeQuote,
|
||||
canScheduleQuotePlace,
|
||||
canScheduleQuoteReflow,
|
||||
createQuoteState,
|
||||
DISPOSED_QUOTE_EVENT,
|
||||
isQuotePressing,
|
||||
QUOTE_SETTLE_MS,
|
||||
quoteToolbarView,
|
||||
RESET_QUOTE_EVENT,
|
||||
ROOT_RESIZED_QUOTE_EVENT,
|
||||
SELECTION_CHANGED_QUOTE_EVENT,
|
||||
SELECTION_CLEARED_QUOTE_EVENT,
|
||||
transitionQuote,
|
||||
VIEWPORT_MOVED_QUOTE_EVENT,
|
||||
type QuoteEffect,
|
||||
type QuoteEvent,
|
||||
type QuoteHorizontal,
|
||||
type QuotePlacement,
|
||||
} from "./quote-machine"
|
||||
import {
|
||||
characterRect,
|
||||
narrowSelection,
|
||||
@@ -23,14 +43,8 @@ import {
|
||||
|
||||
const IS_MAC = /(Mac|iPod|iPhone|iPad)/.test(navigator.platform)
|
||||
|
||||
const SETTLE_MS = 150
|
||||
|
||||
const SHORT_LINES = 3
|
||||
|
||||
type Rect = { top: number; bottom: number; left: number; right: number }
|
||||
|
||||
type Extent = Rect & { short: boolean; backward: boolean }
|
||||
|
||||
/** Offers to quote text selected in the session timeline into the composer. */
|
||||
export function createTimelineQuote(input: {
|
||||
root: () => HTMLElement | undefined
|
||||
@@ -38,98 +52,167 @@ export function createTimelineQuote(input: {
|
||||
enabled: () => boolean
|
||||
add: (text: string, source: QuoteSource, anchor?: ComposerQuoteAnchor) => void
|
||||
}) {
|
||||
const [state, setState] = createStore<{
|
||||
text: string | undefined
|
||||
truncated: boolean
|
||||
extent: Extent | undefined
|
||||
bounds: Rect | undefined
|
||||
layout: number
|
||||
}>({ text: undefined, truncated: false, extent: undefined, bounds: undefined, layout: 0 })
|
||||
|
||||
let selected: TimelineSelection | undefined
|
||||
let horizontal: { left: number; right: number; origin: number } | undefined
|
||||
let current = createQuoteState()
|
||||
const [quoteState, setQuoteState] = createSignal(current)
|
||||
// Counts timeline resizes, so a quote anchor in the composer follows a reflow after the toolbar closed.
|
||||
const [layout, setLayout] = createSignal(0)
|
||||
let element: HTMLElement | undefined
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let frame: number | undefined
|
||||
let pointer = false
|
||||
let reflow: number | undefined
|
||||
// The selection Escape dismissed, which stays dismissed until it changes or clears.
|
||||
let dismissed: Range | undefined
|
||||
let settleTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let clearTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let placeFrame: number | undefined
|
||||
let reflowFrame: number | undefined
|
||||
let unwatchPress: (() => void) | undefined
|
||||
|
||||
const close = () => {
|
||||
selected = undefined
|
||||
horizontal = undefined
|
||||
dismissed = undefined
|
||||
clearTimeout(timer)
|
||||
const dispatch = (event: QuoteEvent) =>
|
||||
untrack(() => {
|
||||
const next = transitionQuote(current, event)
|
||||
|
||||
if (reflow !== undefined) cancelAnimationFrame(reflow)
|
||||
reflow = undefined
|
||||
setState({ text: undefined, truncated: false, extent: undefined, bounds: undefined })
|
||||
}
|
||||
if (next.state !== current) {
|
||||
current = next.state
|
||||
setQuoteState(current)
|
||||
}
|
||||
|
||||
const dismiss = () => {
|
||||
const focused = document.activeElement instanceof Node && !!element?.contains(document.activeElement)
|
||||
const selection = window.getSelection()
|
||||
close()
|
||||
dismissed = selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined
|
||||
|
||||
if (focused) input.root()?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
const place = () => {
|
||||
const root = input.root()
|
||||
|
||||
if (!root || !selected) return
|
||||
|
||||
// The virtualizer removed the selected rows.
|
||||
if (selected.range.collapsed) return close()
|
||||
const measured = measureQuote(root, selected, horizontal)
|
||||
setState({
|
||||
bounds: measured?.bounds,
|
||||
extent:
|
||||
measured && measured.extent.bottom > measured.bounds.top && measured.extent.top < measured.bounds.bottom
|
||||
? measured.extent
|
||||
: undefined,
|
||||
next.effects.forEach(run)
|
||||
})
|
||||
|
||||
const run = (effect: QuoteEffect) => {
|
||||
if (effect.type === "press.watch") return watchPress()
|
||||
|
||||
if (effect.type === "press.unwatch") {
|
||||
unwatchPress?.()
|
||||
unwatchPress = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "settle.schedule" || effect.type === "settle.cancel") {
|
||||
clearTimeout(settleTimer)
|
||||
settleTimer = undefined
|
||||
|
||||
if (effect.type === "settle.cancel") return
|
||||
settleTimer = setTimeout(() => {
|
||||
settleTimer = undefined
|
||||
dispatch({ type: "settle.ready", attempt: effect.attempt })
|
||||
}, QUOTE_SETTLE_MS)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "clear.schedule" || effect.type === "clear.cancel") {
|
||||
clearTimeout(clearTimer)
|
||||
clearTimer = undefined
|
||||
|
||||
if (effect.type === "clear.cancel") return
|
||||
// Runs once the press is handled.
|
||||
clearTimer = setTimeout(() => {
|
||||
clearTimer = undefined
|
||||
dispatch({ type: "clear.ready", attempt: effect.attempt })
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "place.schedule" || effect.type === "place.cancel") {
|
||||
if (placeFrame !== undefined) cancelAnimationFrame(placeFrame)
|
||||
placeFrame = undefined
|
||||
|
||||
if (effect.type === "place.cancel") return
|
||||
placeFrame = requestAnimationFrame(() => {
|
||||
placeFrame = undefined
|
||||
dispatch({ type: "place.ready", attempt: effect.attempt })
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "reflow.schedule" || effect.type === "reflow.cancel") {
|
||||
if (reflowFrame !== undefined) cancelAnimationFrame(reflowFrame)
|
||||
reflowFrame = undefined
|
||||
|
||||
if (effect.type === "reflow.cancel") return
|
||||
reflowFrame = requestAnimationFrame(() => {
|
||||
reflowFrame = undefined
|
||||
dispatch({ type: "reflow.ready", attempt: effect.attempt })
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "quote.read") return read(effect.dismissed)
|
||||
|
||||
if (effect.type === "place.measure") {
|
||||
const root = input.root()
|
||||
|
||||
if (!root) return
|
||||
const selected = effect.quote.selected
|
||||
// The virtualizer removed the selected rows.
|
||||
const collapsed = selected.range.collapsed
|
||||
|
||||
return dispatch({
|
||||
type: "place.measured",
|
||||
collapsed,
|
||||
placement: collapsed ? undefined : placeQuote(root, selected, effect.quote.horizontal),
|
||||
})
|
||||
}
|
||||
|
||||
if (effect.type === "selection.clearIfSame") {
|
||||
const selection = window.getSelection()
|
||||
|
||||
if (selection?.rangeCount && sameRange(selection.getRangeAt(0), effect.range)) selection.removeAllRanges()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
input.root()?.focus({ preventScroll: true })
|
||||
}
|
||||
|
||||
const read = () => {
|
||||
if (pointer) return
|
||||
const read = (dismissed: Range | undefined) => {
|
||||
const root = input.root()
|
||||
const selection = window.getSelection()
|
||||
|
||||
if (dismissed && selection?.rangeCount && sameRange(selection.getRangeAt(0), dismissed)) return
|
||||
dismissed = undefined
|
||||
if (dismissed && selection?.rangeCount && sameRange(selection.getRangeAt(0), dismissed))
|
||||
return dispatch({ type: "quote.measured", quote: undefined, dismissed: true })
|
||||
const next = root && input.enabled() && selection ? timelineSelection(selection, root) : undefined
|
||||
const quote = next ? quoteText(next) : undefined
|
||||
|
||||
if (!root || !next || !quote?.text) return close()
|
||||
horizontal = quote.horizontal && { ...quote.horizontal, origin: root.getBoundingClientRect().left }
|
||||
if (!root || !next || !quote?.text) return dispatch({ type: "quote.measured", quote: undefined })
|
||||
const horizontal = quote.horizontal && { ...quote.horizontal, origin: root.getBoundingClientRect().left }
|
||||
|
||||
// Selecting a whole paragraph ends the selection at the start of the next block.
|
||||
selected = quote.first
|
||||
const selected = quote.first
|
||||
? narrowSelection(next, quote.first, quote.truncated ? next.end : (quote.last ?? next.end))
|
||||
: next
|
||||
setState({ text: quote.text, truncated: quote.truncated })
|
||||
place()
|
||||
}
|
||||
|
||||
const schedule = () => {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(read, SETTLE_MS)
|
||||
}
|
||||
|
||||
const schedulePlace = () => {
|
||||
if (frame !== undefined || !selected) return
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = undefined
|
||||
place()
|
||||
dispatch({
|
||||
type: "quote.measured",
|
||||
quote: {
|
||||
text: quote.text,
|
||||
truncated: quote.truncated,
|
||||
selected,
|
||||
horizontal,
|
||||
placement: placeQuote(root, selected, horizontal),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const release = () => {
|
||||
if (!pointer) return
|
||||
pointer = false
|
||||
schedule()
|
||||
// A press can end without a pointerup reaching the document (a native drag of the selection, a capture on a removed
|
||||
// node), so a move with the primary button up also releases it. The listeners exist only while a press is held.
|
||||
const watchPress = () => {
|
||||
unwatchPress?.()
|
||||
const release = () => dispatch({ type: "pointer.up", collapsed: window.getSelection()?.isCollapsed ?? true })
|
||||
const controller = new AbortController()
|
||||
const options = { signal: controller.signal }
|
||||
document.addEventListener("pointerup", release, options)
|
||||
document.addEventListener("pointercancel", release, options)
|
||||
document.addEventListener("contextmenu", release, options)
|
||||
document.addEventListener("dragend", release, options)
|
||||
window.addEventListener("blur", release, options)
|
||||
document.addEventListener("visibilitychange", () => document.hidden && release(), options)
|
||||
document.addEventListener("pointermove", (event) => (event.buttons & 1) === 0 && release(), {
|
||||
signal: controller.signal,
|
||||
passive: true,
|
||||
})
|
||||
unwatchPress = () => controller.abort()
|
||||
}
|
||||
|
||||
const inside = (target: EventTarget | null) => target instanceof Node && !!element?.contains(target)
|
||||
@@ -140,7 +223,7 @@ export function createTimelineQuote(input: {
|
||||
const selection = window.getSelection()
|
||||
const active = document.activeElement
|
||||
|
||||
if (pointer || !root || !input.enabled() || !selection || selection.rangeCount === 0) return
|
||||
if (isQuotePressing(current) || !root || !input.enabled() || !selection || selection.rangeCount === 0) return
|
||||
|
||||
if (active !== document.body && !(active instanceof Node && root.contains(active) && !editable(active))) return
|
||||
const range = selection.getRangeAt(0)
|
||||
@@ -156,23 +239,25 @@ export function createTimelineQuote(input: {
|
||||
|
||||
makeEventListener(document, "selectionchange", () => {
|
||||
containSelectAll()
|
||||
|
||||
// Only a new selection waits to settle; a cleared one closes at once.
|
||||
if (window.getSelection()?.isCollapsed ?? true) return close()
|
||||
schedule()
|
||||
dispatch(
|
||||
(window.getSelection()?.isCollapsed ?? true) ? SELECTION_CLEARED_QUOTE_EVENT : SELECTION_CHANGED_QUOTE_EVENT,
|
||||
)
|
||||
})
|
||||
makeEventListener(document, "pointerdown", (event) => {
|
||||
if (inside(event.target) || event.button !== 0) return
|
||||
pointer = true
|
||||
const selection = window.getSelection()
|
||||
const target = event.target instanceof Element ? event.target : undefined
|
||||
|
||||
if (state.text === undefined || event.shiftKey || !selection?.rangeCount || target?.closest(".scroll-view__thumb"))
|
||||
return
|
||||
const range = selection.getRangeAt(0).cloneRange()
|
||||
const range =
|
||||
activeQuote(current) && !event.shiftKey && selection?.rangeCount && !target?.closest(".scroll-view__thumb")
|
||||
? selection.getRangeAt(0).cloneRange()
|
||||
: undefined
|
||||
|
||||
// A press on the selection itself may start dragging it; the page clears it on release otherwise.
|
||||
if (
|
||||
// A press on the selection itself may start dragging it; the page clears it on release otherwise. A press on
|
||||
// content the shell makes unselectable leaves the selection as it was, so it clears once the press is handled.
|
||||
const onSelection =
|
||||
!!range &&
|
||||
[...range.getClientRects()].some(
|
||||
(rect) =>
|
||||
event.clientX >= rect.left &&
|
||||
@@ -180,25 +265,24 @@ export function createTimelineQuote(input: {
|
||||
event.clientY >= rect.top &&
|
||||
event.clientY <= rect.bottom,
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
// A press on content the shell makes unselectable leaves the selection as it was, so clear it once the press is
|
||||
// handled.
|
||||
setTimeout(() => {
|
||||
if (selection.rangeCount && sameRange(selection.getRangeAt(0), range)) selection.removeAllRanges()
|
||||
})
|
||||
dispatch({ type: "pointer.down", clearRange: onSelection ? undefined : range })
|
||||
})
|
||||
makeEventListener(document, "pointerup", release)
|
||||
makeEventListener(document, "pointercancel", release)
|
||||
makeEventListener(document, "contextmenu", release)
|
||||
makeEventListener(window, "blur", release)
|
||||
makeEventListener(document, "keydown", (event) => {
|
||||
if (event.defaultPrevented || event.isComposing) return
|
||||
const root = input.root()
|
||||
const active = document.activeElement
|
||||
|
||||
if (event.key === "Escape" && state.text !== undefined) return dismiss()
|
||||
if (event.key === "Escape" && activeQuote(current)) {
|
||||
const selection = window.getSelection()
|
||||
|
||||
return dispatch({
|
||||
type: "escape",
|
||||
range: selection?.rangeCount ? selection.getRangeAt(0).cloneRange() : undefined,
|
||||
toolbarFocused: active instanceof Node && !!element?.contains(active),
|
||||
})
|
||||
}
|
||||
|
||||
const action = element?.querySelector<HTMLButtonElement>("button:not(:disabled)")
|
||||
|
||||
if (
|
||||
@@ -232,56 +316,48 @@ export function createTimelineQuote(input: {
|
||||
window.getSelection()?.selectAllChildren(root)
|
||||
}
|
||||
})
|
||||
makeEventListener(document, "scroll", schedulePlace, { capture: true, passive: true })
|
||||
makeEventListener(window, "resize", schedulePlace)
|
||||
|
||||
const moved = () => canScheduleQuotePlace(current) && dispatch(VIEWPORT_MOVED_QUOTE_EVENT)
|
||||
makeEventListener(document, "scroll", moved, { capture: true, passive: true })
|
||||
makeEventListener(window, "resize", moved)
|
||||
|
||||
// A resized timeline, such as when a side panel opens, reflows the selected text.
|
||||
createResizeObserver(input.root, () => {
|
||||
setState("layout", (value) => value + 1)
|
||||
setLayout((value) => value + 1)
|
||||
|
||||
if (!selected || reflow !== undefined) return
|
||||
reflow = requestAnimationFrame(() => {
|
||||
reflow = undefined
|
||||
read()
|
||||
})
|
||||
if (canScheduleQuoteReflow(current)) dispatch(ROOT_RESIZED_QUOTE_EVENT)
|
||||
})
|
||||
|
||||
createEffect(on(input.sessionKey, close, { defer: true }))
|
||||
createEffect(on(input.sessionKey, () => dispatch(RESET_QUOTE_EVENT), { defer: true }))
|
||||
createEffect(() => {
|
||||
if (!input.enabled()) close()
|
||||
})
|
||||
onCleanup(() => {
|
||||
clearTimeout(timer)
|
||||
|
||||
if (frame !== undefined) cancelAnimationFrame(frame)
|
||||
|
||||
if (reflow !== undefined) cancelAnimationFrame(reflow)
|
||||
if (!input.enabled()) dispatch(RESET_QUOTE_EVENT)
|
||||
})
|
||||
onCleanup(() => dispatch(DISPOSED_QUOTE_EVENT))
|
||||
|
||||
return {
|
||||
state,
|
||||
toolbar: createMemo(() => quoteToolbarView(quoteState())),
|
||||
// Alt skips the optional comment. Otherwise the editor replaces the selection toolbar.
|
||||
add: (skip: boolean) => {
|
||||
const text = state.text
|
||||
const quote = activeQuote(current)
|
||||
|
||||
if (!text || state.truncated) return
|
||||
const ranges = selected ? quoteText(selected).ranges : []
|
||||
if (!quote?.text || quote.truncated) return
|
||||
const ranges = quoteText(quote.selected).ranges
|
||||
const source = captureQuoteSource(ranges)
|
||||
const selection = selected
|
||||
const selection = quote.selected
|
||||
const root = input.root()
|
||||
const sessionKey = input.sessionKey()
|
||||
let horizontalBounds = horizontal
|
||||
let layout = state.layout
|
||||
const initial = root && selection ? measureQuote(root, selection, horizontalBounds) : undefined
|
||||
let horizontalBounds = quote.horizontal
|
||||
let measuredLayout = layout()
|
||||
const initial = root ? measureQuote(root, selection, horizontalBounds) : undefined
|
||||
let last = initial
|
||||
|
||||
const anchor: ComposerQuoteAnchor = (size) => {
|
||||
// Keep the source anchor reactive when a divider resizes the timeline after selection is cleared.
|
||||
void state.layout
|
||||
const revision = layout()
|
||||
|
||||
if (!root?.isConnected || input.sessionKey() !== sessionKey || !input.enabled()) return
|
||||
|
||||
if (layout !== state.layout) {
|
||||
if (measuredLayout !== revision) {
|
||||
// Only quoted glyphs determine the width; the enclosing selection also includes block boxes and chrome.
|
||||
const rects = ranges
|
||||
.flatMap((range) => (range.startContainer.isConnected ? [...range.getClientRects()] : []))
|
||||
@@ -294,10 +370,10 @@ export function createTimelineQuote(input: {
|
||||
origin: root.getBoundingClientRect().left,
|
||||
}
|
||||
: undefined
|
||||
layout = state.layout
|
||||
measuredLayout = revision
|
||||
}
|
||||
|
||||
const measured = selection && measureQuote(root, selection, horizontalBounds)
|
||||
const measured = measureQuote(root, selection, horizontalBounds)
|
||||
last = measured ?? last
|
||||
|
||||
if (!last) return
|
||||
@@ -310,8 +386,8 @@ export function createTimelineQuote(input: {
|
||||
}
|
||||
|
||||
window.getSelection()?.removeAllRanges()
|
||||
close()
|
||||
input.add(text, source, skip ? undefined : anchor)
|
||||
dispatch(RESET_QUOTE_EVENT)
|
||||
input.add(quote.text, source, skip ? undefined : anchor)
|
||||
},
|
||||
setElement: (value: HTMLElement | undefined) => {
|
||||
element = value
|
||||
@@ -329,16 +405,15 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
const [size, setSize] = createStore({ width: 0, height: 0 })
|
||||
|
||||
const position = () => {
|
||||
const bounds = quote.state.bounds
|
||||
const extent = quote.state.extent
|
||||
const view = quote.toolbar()
|
||||
|
||||
if (!bounds || !extent) return
|
||||
if (!view) return
|
||||
|
||||
return quotePosition(bounds, extent, size, docked())
|
||||
return quotePosition(view.bounds, view.extent, size, docked())
|
||||
}
|
||||
|
||||
return (
|
||||
<Show when={quote.state.text !== undefined && position()}>
|
||||
<Show when={position()}>
|
||||
{(place) => (
|
||||
<Portal>
|
||||
<div
|
||||
@@ -359,7 +434,7 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
}}
|
||||
onMouseDown={(event) => event.preventDefault()}
|
||||
>
|
||||
<Show when={quote.state.truncated}>
|
||||
<Show when={quote.toolbar()?.truncated}>
|
||||
<span class="px-2 text-[12px] leading-[var(--line-height-compact)] text-v2-text-text-muted [font-weight:440]">
|
||||
{language.t("session.quote.tooLong")}
|
||||
</span>
|
||||
@@ -378,7 +453,7 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
size="small"
|
||||
variant="ghost"
|
||||
icon="outline-quote"
|
||||
disabled={quote.state.truncated}
|
||||
disabled={quote.toolbar()?.truncated}
|
||||
onClick={(event: MouseEvent) => quote.add(event.altKey)}
|
||||
>
|
||||
{language.t("session.quote.add")}
|
||||
@@ -391,11 +466,26 @@ export function TimelineQuote(props: { controller: TimelineQuoteController }) {
|
||||
)
|
||||
}
|
||||
|
||||
function measureQuote(
|
||||
function placeQuote(
|
||||
root: HTMLElement,
|
||||
selected: TimelineSelection,
|
||||
horizontal?: { left: number; right: number; origin: number },
|
||||
) {
|
||||
horizontal: QuoteHorizontal | undefined,
|
||||
): QuotePlacement | undefined {
|
||||
const measured = measureQuote(root, selected, horizontal)
|
||||
|
||||
if (!measured) return undefined
|
||||
|
||||
return {
|
||||
bounds: measured.bounds,
|
||||
// A selection scrolled out of view keeps its quote but hides the toolbar.
|
||||
extent:
|
||||
measured.extent.bottom > measured.bounds.top && measured.extent.top < measured.bounds.bottom
|
||||
? measured.extent
|
||||
: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
function measureQuote(root: HTMLElement, selected: TimelineSelection, horizontal?: QuoteHorizontal) {
|
||||
if (selected.range.collapsed || !selected.start.node.isConnected || !selected.end.node.isConnected) return
|
||||
const view = root.getBoundingClientRect()
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createReconnectState,
|
||||
DISPOSED_RECONNECT_EVENT,
|
||||
isReconnectObserverActive,
|
||||
transitionReconnect,
|
||||
type ReconnectEvent,
|
||||
type ReconnectState,
|
||||
} from "./reconnect-machine"
|
||||
|
||||
const mutated = (connected: boolean, added: boolean, deadline = 100): ReconnectEvent => ({
|
||||
type: "mutated",
|
||||
connected,
|
||||
added,
|
||||
deadline,
|
||||
})
|
||||
|
||||
const frame = (
|
||||
state: ReconnectState,
|
||||
time: number,
|
||||
nativeTop = 0,
|
||||
virtualOffset: number | null = 0,
|
||||
): Extract<ReconnectEvent, { type: "frame" }> => ({
|
||||
type: "frame",
|
||||
attempt: attemptOf(state),
|
||||
time,
|
||||
connected: true,
|
||||
nativeTop,
|
||||
virtualOffset,
|
||||
})
|
||||
|
||||
function attemptOf(state: ReconnectState) {
|
||||
return state.status === "disposed" ? -1 : state.attempt
|
||||
}
|
||||
|
||||
function checking() {
|
||||
return transitionReconnect(createReconnectState(false), mutated(true, false)).state
|
||||
}
|
||||
|
||||
describe("reconnect machine", () => {
|
||||
test("detects an ancestor removed, then the element reparented in a later batch", () => {
|
||||
// `wrap.remove(); staging.append(scroller)`: the removal record no longer contains the element.
|
||||
const detached = transitionReconnect(createReconnectState(true), mutated(false, false))
|
||||
expect(detached.state.status).toBe("detached")
|
||||
expect(detached.effects).toEqual([])
|
||||
|
||||
// `main.append(staging)`
|
||||
const back = transitionReconnect(detached.state, mutated(true, true))
|
||||
expect(back.state).toMatchObject({ status: "checking", deadline: 100, framesAfterDeadline: 0 })
|
||||
expect(back.effects).toEqual([{ type: "reconnected" }, { type: "frame.schedule", attempt: attemptOf(back.state) }])
|
||||
})
|
||||
|
||||
test("detects a detach and reattach within one batch", () => {
|
||||
// `wrap.remove(); main.append(scroller)`
|
||||
const next = transitionReconnect(createReconnectState(true), mutated(true, true))
|
||||
expect(next.state.status).toBe("checking")
|
||||
expect(next.effects.filter((effect) => effect.type === "reconnected")).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("ignores unrelated mutations without a new state", () => {
|
||||
const attached = createReconnectState(true)
|
||||
expect(transitionReconnect(attached, mutated(true, false)).state).toBe(attached)
|
||||
|
||||
const state = checking()
|
||||
expect(transitionReconnect(state, mutated(true, false)).state).toBe(state)
|
||||
|
||||
const detached = createReconnectState(false)
|
||||
expect(transitionReconnect(detached, mutated(false, false)).state).toBe(detached)
|
||||
})
|
||||
|
||||
test("a detach mid-check cancels the frame", () => {
|
||||
const next = transitionReconnect(checking(), mutated(false, false))
|
||||
expect(next.state.status).toBe("detached")
|
||||
expect(next.effects).toEqual([{ type: "frame.cancel" }])
|
||||
})
|
||||
|
||||
test("a second reattach mid-check restarts the window", () => {
|
||||
const state = checking()
|
||||
const next = transitionReconnect(state, mutated(true, true, 500))
|
||||
expect(next.state).toMatchObject({ status: "checking", deadline: 500 })
|
||||
expect(next.effects.map((effect) => effect.type)).toEqual(["frame.cancel", "reconnected", "frame.schedule"])
|
||||
expect(transitionReconnect(next.state, frame(state, 600)).state).toBe(next.state)
|
||||
})
|
||||
|
||||
test("delivers a divergent offset and settles two frames after the deadline", () => {
|
||||
const state = checking()
|
||||
const first = transitionReconnect(state, frame(state, 50, 0, 79_400))
|
||||
expect(first.state).toBe(state)
|
||||
expect(first.effects).toEqual([
|
||||
{ type: "offset.deliver", offset: 0 },
|
||||
{ type: "frame.schedule", attempt: attemptOf(state) },
|
||||
])
|
||||
|
||||
const second = transitionReconnect(first.state, frame(state, 100))
|
||||
expect(second.state).toMatchObject({ status: "checking", framesAfterDeadline: 1 })
|
||||
expect(second.effects).toEqual([{ type: "frame.schedule", attempt: attemptOf(state) }])
|
||||
|
||||
const third = transitionReconnect(second.state, frame(state, 116))
|
||||
expect(third.state.status).toBe("attached")
|
||||
expect(third.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a disconnected frame delivers nothing", () => {
|
||||
const state = checking()
|
||||
const next = transitionReconnect(state, { ...frame(state, 50, 0, 79_400), connected: false })
|
||||
expect(next.effects.map((effect) => effect.type)).toEqual(["frame.schedule"])
|
||||
})
|
||||
|
||||
test("disposal cancels a pending frame and deactivates the observer", () => {
|
||||
const next = transitionReconnect(checking(), DISPOSED_RECONNECT_EVENT)
|
||||
expect(next.effects).toEqual([{ type: "frame.cancel" }])
|
||||
expect(isReconnectObserverActive(next.state)).toBe(false)
|
||||
expect(transitionReconnect(next.state, mutated(true, true)).state).toBe(next.state)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
// TanStack's reset timer can still report a stale offset in the frame after its deadline, so the check outlives it.
|
||||
export const RECONNECT_POST_DEADLINE_FRAMES = 2
|
||||
|
||||
export const RECONNECT_OFFSET_EPSILON = 1
|
||||
|
||||
/**
|
||||
* Whether the scroll element is in the document. A reattached element resets its native `scrollTop`, so `checking`
|
||||
* compares it with the virtualizer's offset every frame until the reset delay has passed.
|
||||
*/
|
||||
export type ReconnectState =
|
||||
| { readonly status: "attached"; readonly attempt: number }
|
||||
| { readonly status: "detached"; readonly attempt: number }
|
||||
| {
|
||||
readonly status: "checking"
|
||||
readonly attempt: number
|
||||
readonly deadline: number
|
||||
readonly framesAfterDeadline: number
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type ReconnectEvent =
|
||||
/**
|
||||
* One MutationObserver batch. `connected` is the element's final connection; `added` means an external record
|
||||
* inserted the element or one of its ancestors.
|
||||
*/
|
||||
| {
|
||||
readonly type: "mutated"
|
||||
readonly connected: boolean
|
||||
readonly added: boolean
|
||||
readonly deadline: number
|
||||
}
|
||||
| {
|
||||
readonly type: "frame"
|
||||
readonly attempt: number
|
||||
readonly time: number
|
||||
readonly connected: boolean
|
||||
readonly nativeTop: number
|
||||
readonly virtualOffset: number | null
|
||||
}
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type ReconnectEffect =
|
||||
| { readonly type: "reconnected" }
|
||||
| { readonly type: "frame.schedule"; readonly attempt: number }
|
||||
| { readonly type: "frame.cancel" }
|
||||
| { readonly type: "offset.deliver"; readonly offset: number }
|
||||
|
||||
export type ReconnectTransition = {
|
||||
readonly state: ReconnectState
|
||||
readonly effects: readonly ReconnectEffect[]
|
||||
}
|
||||
|
||||
export const DISPOSED_RECONNECT_EVENT: ReconnectEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
const DISPOSED_STATE: ReconnectState = Object.freeze({ status: "disposed" })
|
||||
|
||||
const NO_EFFECTS: readonly ReconnectEffect[] = Object.freeze([])
|
||||
|
||||
const FRAME_CANCEL: readonly ReconnectEffect[] = Object.freeze([{ type: "frame.cancel" }])
|
||||
|
||||
const RECONNECTED: ReconnectEffect = Object.freeze({ type: "reconnected" })
|
||||
|
||||
const FRAME_CANCEL_EFFECT: ReconnectEffect = Object.freeze({ type: "frame.cancel" })
|
||||
|
||||
// Cached views can be constructed before their first attachment to the page.
|
||||
export function createReconnectState(connected: boolean): ReconnectState {
|
||||
return connected ? { status: "attached", attempt: 0 } : { status: "detached", attempt: 0 }
|
||||
}
|
||||
|
||||
export function transitionReconnect(state: ReconnectState, event: ReconnectEvent): ReconnectTransition {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (event.type === "disposed")
|
||||
return { state: DISPOSED_STATE, effects: state.status === "checking" ? FRAME_CANCEL : NO_EFFECTS }
|
||||
|
||||
if (event.type === "mutated") {
|
||||
// A removed ancestor detaches the element whether or not the removal record still contains it.
|
||||
if (!event.connected) {
|
||||
if (state.status === "detached") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "detached", attempt: state.attempt + 1 },
|
||||
effects: state.status === "checking" ? FRAME_CANCEL : NO_EFFECTS,
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "detached" && !event.added) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { status: "checking", attempt, deadline: event.deadline, framesAfterDeadline: 0 },
|
||||
effects: [
|
||||
...(state.status === "checking" ? [FRAME_CANCEL_EFFECT] : NO_EFFECTS),
|
||||
RECONNECTED,
|
||||
{ type: "frame.schedule", attempt },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "checking" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
const divergent =
|
||||
event.connected &&
|
||||
(event.virtualOffset === null || Math.abs(event.nativeTop - event.virtualOffset) > RECONNECT_OFFSET_EPSILON)
|
||||
|
||||
const after = state.framesAfterDeadline + (event.time >= state.deadline ? 1 : 0)
|
||||
const done = after >= RECONNECT_POST_DEADLINE_FRAMES
|
||||
|
||||
const next: ReconnectState = done
|
||||
? { status: "attached", attempt: state.attempt + 1 }
|
||||
: after === state.framesAfterDeadline
|
||||
? state
|
||||
: { ...state, framesAfterDeadline: after }
|
||||
|
||||
return {
|
||||
state: next,
|
||||
effects: [
|
||||
...(divergent ? [{ type: "offset.deliver" as const, offset: event.nativeTop }] : NO_EFFECTS),
|
||||
...(done ? NO_EFFECTS : [{ type: "frame.schedule" as const, attempt: state.attempt }]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export function isReconnectObserverActive(state: ReconnectState) {
|
||||
return state.status !== "disposed"
|
||||
}
|
||||
|
||||
function unchanged(state: ReconnectState): ReconnectTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import type { SessionMessageInfo } from "@opencode/client/promise"
|
||||
|
||||
// A first sync that never settles reveals the timeline instead of hiding it forever.
|
||||
export const TIMELINE_SYNC_TIMEOUT_MS = 30_000
|
||||
|
||||
export const LEADING_TURN_PAGE_DELAY_MS = 200
|
||||
|
||||
export const LEADING_TURN_PAGE_LIMIT = 3
|
||||
|
||||
// Pauses spent waiting for another history load, so a page that hangs elsewhere cannot keep enrichment polling.
|
||||
export const LEADING_TURN_BUSY_LIMIT = 15
|
||||
|
||||
export const LEADING_TURN_LOAD_TIMEOUT_MS = 30_000
|
||||
|
||||
export type TimelineSyncTarget = {
|
||||
readonly sessionKey: string
|
||||
readonly sessionID: string
|
||||
}
|
||||
|
||||
/**
|
||||
* The first sync of a session's newest messages, then the background pages that complete a leading turn the newest
|
||||
* page cut mid-turn. `attempt` advances on every change of phase, so a sync, pause or page from an earlier one is
|
||||
* ignored.
|
||||
*/
|
||||
export type TimelineSyncState =
|
||||
| { readonly status: "idle"; readonly attempt: number }
|
||||
| { readonly status: "syncing"; readonly target: TimelineSyncTarget; readonly attempt: number }
|
||||
| {
|
||||
readonly status: "enriching"
|
||||
readonly target: TimelineSyncTarget
|
||||
readonly attempt: number
|
||||
readonly assistantID: string
|
||||
readonly step: "pausing" | "loading"
|
||||
readonly pages: number
|
||||
readonly waits: number
|
||||
}
|
||||
| { readonly status: "ready"; readonly target: TimelineSyncTarget; readonly attempt: number }
|
||||
| { readonly status: "failed"; readonly target: TimelineSyncTarget; readonly attempt: number; readonly error: object }
|
||||
|
||||
export type TimelineSyncEvent =
|
||||
| { readonly type: "target.changed"; readonly target: TimelineSyncTarget | undefined }
|
||||
| {
|
||||
readonly type: "sync.succeeded"
|
||||
readonly attempt: number
|
||||
/** The leading assistant message first seen in this transcript. */
|
||||
readonly assistantID: string | undefined
|
||||
readonly needsParent: boolean
|
||||
readonly more: boolean
|
||||
}
|
||||
| { readonly type: "sync.failed"; readonly attempt: number; readonly error: object }
|
||||
| { readonly type: "sync.timed-out"; readonly attempt: number }
|
||||
| {
|
||||
readonly type: "enrich.paused"
|
||||
readonly attempt: number
|
||||
readonly needsParent: boolean
|
||||
readonly more: boolean
|
||||
/** Another history load is in flight. */
|
||||
readonly loading: boolean
|
||||
}
|
||||
| {
|
||||
readonly type: "enrich.page-settled"
|
||||
readonly attempt: number
|
||||
readonly succeeded: boolean
|
||||
readonly needsParent: boolean
|
||||
readonly more: boolean
|
||||
}
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type TimelineSyncEffect =
|
||||
| { readonly type: "sync.start"; readonly target: TimelineSyncTarget; readonly attempt: number }
|
||||
| { readonly type: "sync.cancel" }
|
||||
| {
|
||||
readonly type: "pause.start"
|
||||
readonly sessionID: string
|
||||
readonly assistantID: string
|
||||
readonly attempt: number
|
||||
}
|
||||
| { readonly type: "pause.cancel" }
|
||||
| {
|
||||
readonly type: "page.load"
|
||||
readonly sessionID: string
|
||||
readonly assistantID: string
|
||||
readonly attempt: number
|
||||
}
|
||||
| { readonly type: "page.abort" }
|
||||
|
||||
export type TimelineSyncTransition = {
|
||||
readonly state: TimelineSyncState
|
||||
readonly effects: readonly TimelineSyncEffect[]
|
||||
}
|
||||
|
||||
export const DISPOSED_TIMELINE_SYNC_EVENT: TimelineSyncEvent = Object.freeze({ type: "disposed" })
|
||||
|
||||
const NO_EFFECTS: readonly TimelineSyncEffect[] = Object.freeze([])
|
||||
|
||||
const SYNC_CANCEL: readonly TimelineSyncEffect[] = Object.freeze([{ type: "sync.cancel" }])
|
||||
|
||||
const PAUSE_CANCEL: readonly TimelineSyncEffect[] = Object.freeze([{ type: "pause.cancel" }])
|
||||
|
||||
const PAGE_ABORT: readonly TimelineSyncEffect[] = Object.freeze([{ type: "page.abort" }])
|
||||
|
||||
export function createTimelineSyncState(): TimelineSyncState {
|
||||
return { status: "idle", attempt: 0 }
|
||||
}
|
||||
|
||||
export function transitionTimelineSync(state: TimelineSyncState, event: TimelineSyncEvent): TimelineSyncTransition {
|
||||
if (event.type === "disposed") return stop(state)
|
||||
|
||||
if (event.type === "target.changed") {
|
||||
const target = event.target
|
||||
|
||||
// A new-session draft has no session to sync.
|
||||
if (!target) return stop(state)
|
||||
|
||||
if (state.status !== "idle" && sameTarget(state.target, target)) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { status: "syncing", target, attempt },
|
||||
effects: [...cancel(state), { type: "sync.start", target, attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status === "idle" || state.attempt !== event.attempt) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
if (state.status === "syncing") {
|
||||
if (event.type === "sync.failed")
|
||||
return {
|
||||
state: { status: "failed", target: state.target, attempt, error: event.error },
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
|
||||
if (event.type === "sync.timed-out") return ready(state.target, attempt, SYNC_CANCEL)
|
||||
|
||||
if (event.type !== "sync.succeeded") return unchanged(state)
|
||||
|
||||
if (!event.assistantID || !event.needsParent || !event.more) return ready(state.target, attempt)
|
||||
|
||||
return pause({
|
||||
status: "enriching",
|
||||
target: state.target,
|
||||
attempt,
|
||||
assistantID: event.assistantID,
|
||||
step: "pausing",
|
||||
pages: 0,
|
||||
waits: 0,
|
||||
})
|
||||
}
|
||||
|
||||
if (state.status !== "enriching") return unchanged(state)
|
||||
|
||||
if (event.type === "enrich.paused" && state.step === "pausing") {
|
||||
if (!event.needsParent || !event.more) return ready(state.target, attempt)
|
||||
|
||||
if (event.loading)
|
||||
return state.waits + 1 >= LEADING_TURN_BUSY_LIMIT
|
||||
? ready(state.target, attempt)
|
||||
: pause({ ...state, attempt, waits: state.waits + 1 })
|
||||
|
||||
return {
|
||||
state: { ...state, attempt, step: "loading", waits: 0 },
|
||||
effects: [{ type: "page.load", sessionID: state.target.sessionID, assistantID: state.assistantID, attempt }],
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "enrich.page-settled" && state.step === "loading") {
|
||||
// A failed page leaves the leading turn as it is; a later visit to the session resumes it.
|
||||
if (!event.succeeded || state.pages + 1 >= LEADING_TURN_PAGE_LIMIT || !event.needsParent || !event.more)
|
||||
return ready(state.target, attempt)
|
||||
|
||||
return pause({ ...state, attempt, step: "pausing", pages: state.pages + 1, waits: 0 })
|
||||
}
|
||||
|
||||
return unchanged(state)
|
||||
}
|
||||
|
||||
/** Whether the newest page of `target` is still loading. Background enrichment does not count. */
|
||||
export function isTimelineSyncing(state: TimelineSyncState, target: TimelineSyncTarget | undefined) {
|
||||
if (!target) return false
|
||||
|
||||
return state.status === "idle" || state.status === "syncing" || !sameTarget(state.target, target)
|
||||
}
|
||||
|
||||
export function timelineSyncError(state: TimelineSyncState, target: TimelineSyncTarget | undefined) {
|
||||
if (!target || state.status !== "failed" || !sameTarget(state.target, target)) return undefined
|
||||
|
||||
return state.error
|
||||
}
|
||||
|
||||
/** Whether the timeline can show. A loaded tail shows at once; enrichment never withholds it. */
|
||||
export function isTimelineReady(
|
||||
state: TimelineSyncState,
|
||||
target: TimelineSyncTarget | undefined,
|
||||
hasTail: () => boolean,
|
||||
) {
|
||||
if (!target) return true
|
||||
|
||||
if ((state.status === "enriching" || state.status === "ready") && sameTarget(state.target, target)) return true
|
||||
|
||||
return hasTail()
|
||||
}
|
||||
|
||||
export function sameTarget(a: TimelineSyncTarget | undefined, b: TimelineSyncTarget | undefined) {
|
||||
return a?.sessionKey === b?.sessionKey && a?.sessionID === b?.sessionID
|
||||
}
|
||||
|
||||
/**
|
||||
* The leading assistant message to complete, remembered per transcript. The store keeps the transcript array across
|
||||
* prepends and tab switches and replaces it on eviction, so an interrupted enrichment resumes the turn that was
|
||||
* visible on entry rather than one that older pages prepended since.
|
||||
*/
|
||||
export function resolveLeadingAssistant(memo: WeakMap<SessionMessageInfo[], string>, messages: SessionMessageInfo[]) {
|
||||
const assistant = memo.get(messages) ?? messages.find((message) => message.type === "assistant")?.id
|
||||
|
||||
if (assistant) memo.set(messages, assistant)
|
||||
|
||||
return assistant
|
||||
}
|
||||
|
||||
export function leadingTurnNeedsParent(messages: SessionMessageInfo[], id: string) {
|
||||
// Older pages can start mid-turn too; only complete the turn that was visible on entry.
|
||||
const assistant = messages.findIndex((message) => message.id === id)
|
||||
|
||||
if (assistant === -1) return false
|
||||
const boundary = messages.findIndex((message) => message.type === "user" || message.type === "shell")
|
||||
|
||||
return boundary === -1 || assistant < boundary
|
||||
}
|
||||
|
||||
function stop(state: TimelineSyncState): TimelineSyncTransition {
|
||||
if (state.status === "idle") return unchanged(state)
|
||||
|
||||
return { state: { status: "idle", attempt: state.attempt + 1 }, effects: cancel(state) }
|
||||
}
|
||||
|
||||
function ready(target: TimelineSyncTarget, attempt: number, effects = NO_EFFECTS): TimelineSyncTransition {
|
||||
return { state: { status: "ready", target, attempt }, effects }
|
||||
}
|
||||
|
||||
function pause(state: Extract<TimelineSyncState, { status: "enriching" }>): TimelineSyncTransition {
|
||||
return {
|
||||
state,
|
||||
effects: [
|
||||
{
|
||||
type: "pause.start",
|
||||
sessionID: state.target.sessionID,
|
||||
assistantID: state.assistantID,
|
||||
attempt: state.attempt,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function cancel(state: TimelineSyncState) {
|
||||
if (state.status === "syncing") return SYNC_CANCEL
|
||||
|
||||
if (state.status !== "enriching") return NO_EFFECTS
|
||||
|
||||
return state.step === "pausing" ? PAUSE_CANCEL : PAGE_ABORT
|
||||
}
|
||||
|
||||
function unchanged(state: TimelineSyncState): TimelineSyncTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
Reference in New Issue
Block a user