feat(client): drag with prediction and rollback (#72)

Drag a controlled token (GM: any token) at <=20 Hz plus a final send on release;
the sprite follows the pointer while authoritative frames are ignored for drawing.
Uniform move nacks roll back with a short tween (on release if still dragging),
rate-limited acks drop quietly, and pending reqIds die with the connection.

- slices/move.ts: pure drag/pending/ack state machine at the reducer seam
- render/modules/drag.ts: canvas pointer input, capture-phase so token drag wins
  over pan/pinch (#69); sends via the new intents bridge
- tokens renderer draws the optimistic/confirmed position and tweens the rollback
- intents.ts + ws.send onReqId: one reqId-keyed sender for render modules
- e2e: drag persists after reload, wall refusal tween, GM move mid-drag,
  reconnect mid-drag dropping the pending map
This commit is contained in:
2026-11-21 09:41:03 +01:00
parent 4534ed6426
commit c7d5e2cc69
10 changed files with 1284 additions and 13 deletions
+331
View File
@@ -0,0 +1,331 @@
// Move prediction and rollback (T9, #72; DESIGN 7.5, 5.5, 6.4). The pure half of the drag: pointer
// input becomes `drag-*` events, each `token.move` intent is remembered by `reqId`, and the acks
// decide whether the optimistic position stands or slides back. No Pixi, no DOM, no socket.
//
// The contract is DESIGN 7.5:
// - while dragging, the sprite follows the pointer and authoritative positions for that token are
// ignored for drawing (they keep arriving in the tokens slice, unmodified);
// - `ack{ok:true}` confirms the requested position, which the server's `token` frame repeats;
// - the uniform move nack (`ok:false` with `pos`, no `code`) rolls back: at once when idle, on
// release when the finger is still down;
// - `ack{ok:false, code:"rate-limited"}` is dropped quietly: the optimistic position is discarded
// and the next authoritative frame reconciles the view (6.4);
// - pending requests die with the connection (6.3).
//
// Append-only registration: adding this file was enough; the reducer's glob picked it up and
// `hello` resets it with every other slice.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { isAck } from '../protocol.ts'
import type { TokenView } from './tokens.ts'
import { tokensOf } from './tokens.ts'
export interface DragState {
id: string
/** Where the token was when the drag began (the server's last position). */
origin: Vec2
/** The optimistic position under the pointer; the renderer draws here. */
pos: Vec2
}
export interface MovePending {
reqId: number
id: string
pos: Vec2
}
/** A refused move while the finger is still down: snap there on release, never under the finger. */
export interface MoveSnap {
id: string
pos: Vec2
}
export interface RollbackTween {
/** Monotonic id so the renderer can report the exact tween it finished. */
seq: number
id: string
from: Vec2
to: Vec2
}
export interface MoveState {
drag: DragState | null
/** `token.move` intents awaiting their ack, in send order (the server acks in order). */
pending: MovePending[]
snap: MoveSnap | null
/** Cosmetic rollbacks the renderer is sliding; keyed by token id, newest per token wins. */
rollbacks: Record<string, RollbackTween>
/** Confirmed positions kept until the matching `token` frame lands (ack precedes the frame). */
confirmed: Record<string, Vec2>
seq: number
/** Counters for the browser e2e's instrumentation and for the unit tests. */
accepted: number
refused: number
rateLimited: number
/** Pending intents thrown away because the connection closed (6.3). */
dropped: number
rollbackCount: number
}
const EMPTY: MoveState = {
drag: null,
pending: [],
snap: null,
rollbacks: {},
confirmed: {},
seq: 0,
accepted: 0,
refused: 0,
rateLimited: 0,
dropped: 0,
rollbackCount: 0,
}
export function initMove(): MoveState {
return { ...EMPTY, pending: [], rollbacks: {}, confirmed: {} }
}
function isVec2(value: unknown): value is Vec2 {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function copy(pos: Vec2): Vec2 {
return [pos[0], pos[1]]
}
/** The newest pending intent for one token, or null. */
function latestPending(state: MoveState, id: string): MovePending | null {
let found: MovePending | null = null
for (const entry of state.pending) {
if (entry.id === id && (found === null || entry.reqId > found.reqId)) found = entry
}
return found
}
function hasNewerPending(state: MoveState, id: string, reqId: number): boolean {
return state.pending.some(entry => entry.id === id && entry.reqId > reqId)
}
function startRollback(state: MoveState, id: string, from: Vec2, to: Vec2): void {
state.seq += 1
state.rollbackCount += 1
state.rollbacks = {
...state.rollbacks,
[id]: { seq: state.seq, id, from: copy(from), to: copy(to) },
}
}
export const slice: Slice<MoveState> = {
name: 'move',
init: initMove,
reduce(state: MoveState, event: ReducerEvent, root: RootState): void {
switch (event.type) {
case 'drag-start': {
// A new drag is a new prediction: any pending snap or tween for this token is obsolete.
state.drag = { id: event.id, origin: copy(event.pos), pos: copy(event.pos) }
state.snap = null
if (state.rollbacks[event.id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
}
delete state.confirmed[event.id]
return
}
case 'drag-move': {
if (state.drag?.id !== event.id) return
state.drag = { ...state.drag, pos: copy(event.pos) }
return
}
case 'drag-end': {
if (state.drag?.id !== event.id) return
state.drag = null
// A refusal seen during the drag is settled on release (7.5): its ack handler starts the
// tween from the released position. Nothing to do here but keep the snap for that ack.
return
}
case 'move-sent': {
state.pending = [
...state.pending.filter(entry => entry.reqId !== event.reqId),
{ reqId: event.reqId, id: event.id, pos: copy(event.pos) },
]
return
}
case 'rollback-done': {
const tween = state.rollbacks[event.id]
if (tween?.seq !== event.seq) return
const rollbacks = { ...state.rollbacks }
delete rollbacks[event.id]
state.rollbacks = rollbacks
return
}
case 'close': {
// 6.3: pending reqIds are dropped with the connection; no ack will ever arrive.
state.dropped += state.pending.length
state.pending = []
state.drag = null
state.snap = null
state.rollbacks = {}
state.confirmed = {}
return
}
case 'frame': {
const frame = event.frame
if (frame.t === 'token') {
// The server remains the judge (story 39): its frame wins for drawing once no drag or
// pending intent covers the token. Any frame settles a confirmed position.
const id = frame['id']
if (typeof id !== 'string') return
// A frame during a cosmetic rollback does not cancel the tween: the ack that produced it
// already gave the authoritative position, and the renderer only animates the sprite.
delete state.confirmed[id]
return
}
if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string') return
if (state.drag?.id === id) state.drag = null
if (state.snap?.id === id) state.snap = null
state.pending = state.pending.filter(entry => entry.id !== id)
delete state.confirmed[id]
if (state.rollbacks[id] !== undefined) {
const rollbacks = { ...state.rollbacks }
delete rollbacks[id]
state.rollbacks = rollbacks
}
return
}
if (isAck(frame)) {
applyAck(root, state, frame)
}
return
}
}
},
}
function applyAck(root: RootState, state: MoveState, frame: AckFrame): void {
const index = state.pending.findIndex(entry => entry.reqId === frame.reqId)
if (index < 0) return // an intent this slice does not own (admin, name, ...)
const entry = state.pending[index]!
// What the sprite shows right now, before the pending entry is removed (7.5 rollback tween).
const shown = drawPositionOf(root, entry.id) ?? entry.pos
const snap = state.snap?.id === entry.id ? state.snap : null
state.pending = state.pending.filter(item => item.reqId !== frame.reqId)
if (frame.ok) {
state.accepted += 1
if (state.snap?.id === entry.id) state.snap = null
// Ack then the token frame (settleLocked); hold the confirmed position for the frame so the
// sprite never blinks back to the pre-move position for one dispatch.
state.confirmed = {
...state.confirmed,
[entry.id]: isVec2(frame.pos) ? copy(frame.pos) : copy(entry.pos),
}
return
}
if (frame.code === 'rate-limited') {
// 6.4: refused by the bucket, never applied, no position to roll back to. Drop quietly and let
// the next frame (or the next drag sample) reconcile; dragging keeps its optimistic position.
state.rateLimited += 1
if (state.snap?.id === entry.id) state.snap = null
if (state.drag?.id !== entry.id) {
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
return
}
if (!isVec2(frame.pos)) return // a malformed nack cannot move the sprite
// A newer intent is already in flight; its ack decides. Acks arrive in order, so ignore this one.
if (hasNewerPending(state, entry.id, entry.reqId)) return
state.refused += 1
if (state.drag?.id === entry.id) {
// 7.5: do not teleport under the finger; snap on release.
state.snap = { id: entry.id, pos: copy(frame.pos) }
return
}
// Idle: slide back from the predicted position to the server's old position (story 40).
startRollback(state, entry.id, snap ? entry.pos : shown, frame.pos)
if (state.snap?.id === entry.id) state.snap = null
const confirmed = { ...state.confirmed }
delete confirmed[entry.id]
state.confirmed = confirmed
}
/** The move slice, or an empty one before the registry has run (unit helpers stay total). */
export function moveOf(state: RootState): MoveState {
return (state.slices['move'] as MoveState | undefined) ?? EMPTY
}
/**
* The position the token renderer must draw at, or null when the authoritative `token` frame is
* the truth. Precedence: under the finger, then the newest pending request, then a confirmed ack
* whose `token` frame has not arrived yet (DESIGN 7.2's `at` parameter, 7.5).
*/
export function drawPositionOf(state: RootState, id: string): Vec2 | null {
const move = moveOf(state)
if (move.drag?.id === id) return move.drag.pos
const pending = latestPending(move, id)
if (pending) return pending.pos
const confirmed = move.confirmed[id]
if (confirmed) return confirmed
return null
}
/** True while the pointer owns this token: its authoritative frames must not move the sprite. */
export function isDragging(state: RootState, id: string): boolean {
return moveOf(state).drag?.id === id
}
/** The rollbacks the renderer should be tweening, newest sequence first. */
export function rollbacksOf(state: RootState): RollbackTween[] {
return Object.values(moveOf(state).rollbacks)
}
/** The active drag (the module's own state machine), if any. */
export function dragOf(state: RootState): DragState | null {
return moveOf(state).drag
}
/**
* O(N) hit test on press only (DESIGN 7.2): the topmost token this recipient may move whose circle
* contains the world point. Players move only their own tokens; the GM moves any token (story 43).
* GM frames say `mine:false`, so the role check is what makes a GM drag work.
*/
export function draggableAt(
tokens: readonly TokenView[],
role: 'gm' | 'player' | null,
point: Vec2,
): TokenView | null {
if (role === null) return null
for (let index = tokens.length - 1; index >= 0; index -= 1) {
const token = tokens[index]
if (!token) continue
if (role !== 'gm' && !token.mine) continue
const dx = point[0] - token.pos[0]
const dy = point[1] - token.pos[1]
if (dx * dx + dy * dy <= token.radius * token.radius) return token
}
return null
}
/** The tokens a drag may start on, for the shell/e2e; not a secrecy filter (the server already is). */
export function draggableTokens(state: RootState): TokenView[] {
const role = state.session.role
if (role === null) return []
return tokensOf(state).filter(token => role === 'gm' || token.mine)
}