diff --git a/ui-tui/src/__tests__/petPolling.test.ts b/ui-tui/src/__tests__/petPolling.test.ts new file mode 100644 index 0000000000..2cdfe096b8 --- /dev/null +++ b/ui-tui/src/__tests__/petPolling.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from 'vitest' + +import { createPetSingleFlight, requestPetUpdate } from '../lib/petPolling.js' + +const gateway = (request: ReturnType) => ({ request }) as never + +describe('requestPetUpdate', () => { + it('does not enqueue pet.cells while pets are disabled', async () => { + const request = vi.fn().mockResolvedValue({ enabled: false }) + const needsCells = vi.fn(() => true) + + const update = await requestPetUpdate(gateway(request), 'idle', false, needsCells) + + expect(update).toEqual({ cells: null, meta: { enabled: false } }) + expect(request).toHaveBeenCalledTimes(1) + expect(request).toHaveBeenCalledWith('pet.info.meta') + expect(needsCells).not.toHaveBeenCalled() + }) + + it('uses metadata only when the enabled state is already cached', async () => { + const request = vi.fn().mockResolvedValue({ + enabled: true, + scale: 0.33, + slug: 'boba', + spritesheetRevision: '1:2' + }) + + const update = await requestPetUpdate(gateway(request), 'idle', false, () => false) + + expect(update?.cells).toBeNull() + expect(request).toHaveBeenCalledTimes(1) + }) + + it('fetches cells only for an enabled uncached state', async () => { + const cells = { enabled: true, frames: [], slug: 'boba' } + const request = vi.fn().mockResolvedValueOnce({ enabled: true, slug: 'boba' }).mockResolvedValueOnce(cells) + + const update = await requestPetUpdate(gateway(request), 'review', false, () => true) + + expect(update?.cells).toEqual(cells) + expect(request).toHaveBeenNthCalledWith(1, 'pet.info.meta') + expect(request).toHaveBeenNthCalledWith(2, 'pet.cells', { + graphics: false, + state: 'review' + }) + }) + + it('silently drops cosmetic gateway failures', async () => { + const request = vi.fn().mockRejectedValue(new Error('timeout: pet.info.meta')) + + await expect(requestPetUpdate(gateway(request), 'idle', false, () => true)).resolves.toBeNull() + }) +}) + +describe('createPetSingleFlight', () => { + it('suppresses overlapping polls and permits the next completed poll', async () => { + let release = () => undefined + + const blocked = new Promise(resolve => { + release = resolve + }) + + const operation = vi.fn(() => blocked) + const run = createPetSingleFlight() + + const first = run(operation) + await expect(run(operation)).resolves.toBe(false) + expect(operation).toHaveBeenCalledTimes(1) + + release() + await expect(first).resolves.toBe(true) + await expect(run(async () => undefined)).resolves.toBe(true) + }) +}) diff --git a/ui-tui/src/app/usePet.ts b/ui-tui/src/app/usePet.ts index 01196821fc..595d9a37b1 100644 --- a/ui-tui/src/app/usePet.ts +++ b/ui-tui/src/app/usePet.ts @@ -2,6 +2,7 @@ import { useStdout } from '@hermes/ink' import { useCallback, useEffect, useRef, useState } from 'react' import type { PetGrid } from '../components/petSprite.js' +import { createPetSingleFlight, requestPetUpdate } from '../lib/petPolling.js' import { useGateway } from './gatewayContext.js' import { $overlayState, getOverlayState } from './overlayStore.js' @@ -104,10 +105,11 @@ export interface PetRender { * * A steady poll keeps it reactive to config changes made elsewhere (`/pet`, the * picker, `hermes pets select`) so adopting/switching/disabling takes effect - * live. The frame cache is keyed by `slug:state` so a switch re-pulls cleanly. + * live. Disabled/cached pets use the cheap inline `pet.info.meta` probe; only + * uncached enabled states request `pet.cells` from the long-handler pool. */ export function usePet(): PetRender { - const { rpc } = useGateway() + const { gw } = useGateway() const { write } = useStdout() const [enabled, setEnabled] = useState(false) const [grid, setGrid] = useState(null) @@ -116,9 +118,11 @@ export function usePet(): PetRender { const cache = useRef>(new Map()) const slugRef = useRef('') const scaleRef = useRef(0) + const revisionRef = useRef('') const imageIdRef = useRef(0) const stateRef = useRef('idle') const frameRef = useRef(0) + const runSingleFlight = useRef(createPetSingleFlight()).current const [petState, setPetState] = useState('idle') @@ -189,38 +193,76 @@ export function usePet(): PetRender { } }, [write]) - // Fetch + cache one (slug, state). `pet.cells` resolves the active pet from - // config, so its `slug`/`enabled` are the source of truth. + const disablePet = useCallback(() => { + releaseKitty() + slugRef.current = '' + scaleRef.current = 0 + revisionRef.current = '' + cache.current.clear() + setGrid(null) + setKitty(null) + setEnabled(false) + }, [releaseKitty]) + + // Probe the active selection cheaply, then fetch + cache one uncached state. const sync = useCallback( - async (state: PetState) => { - try { - const res = (await rpc('pet.cells', { graphics: IS_TTY, state })) as PetCellsResult | null + (state: PetState) => + runSingleFlight(async () => { + const update = await requestPetUpdate(gw, state, IS_TTY, meta => { + const slug = meta.slug ?? '' + const scale = meta.scale ?? 0 + const revision = meta.spritesheetRevision ?? '' + + const selectionChanged = + slug !== slugRef.current || scale !== scaleRef.current || revision !== revisionRef.current + + if (selectionChanged) { + releaseKitty() + slugRef.current = slug + scaleRef.current = scale + revisionRef.current = revision + cache.current.clear() + frameRef.current = 0 + } + + return !cache.current.has(`${slug}:${state}`) + }) + + if (!update) { + return + } + + if (!update.meta.enabled) { + disablePet() + + return + } + + const res = update.cells if (!res) { + setEnabled(true) + return } if (!res.enabled) { - releaseKitty() - slugRef.current = '' - cache.current.clear() - setGrid(null) - setKitty(null) - setEnabled(false) + disablePet() return } - const slug = res.slug ?? '' - const scale = res.scale ?? 0 + const slug = res.slug ?? update.meta.slug ?? '' + const scale = res.scale ?? update.meta.scale ?? 0 - // A switch OR a live `/pet scale` change invalidates the cached frames - // (they're rendered at the old size), so the steady poll repaints at the - // new scale without a restart. - if (slug !== slugRef.current || (scale > 0 && scale !== scaleRef.current)) { + // Config may change between the metadata and frame calls. Keep the + // frame response authoritative and force a fresh metadata revision on + // the next poll when the response moved to another selection. + if (slug !== slugRef.current || scale !== scaleRef.current) { releaseKitty() slugRef.current = slug scaleRef.current = scale + revisionRef.current = slug === update.meta.slug ? revisionRef.current : '' cache.current.clear() frameRef.current = 0 } @@ -243,11 +285,8 @@ export function usePet(): PetRender { } setEnabled(true) - } catch { - // cosmetic — ignore RPC failures - } - }, - [rpc, releaseKitty] + }), + [disablePet, gw, releaseKitty, runSingleFlight] ) // Pull frames whenever the state changes (if not already cached for the diff --git a/ui-tui/src/lib/petPolling.ts b/ui-tui/src/lib/petPolling.ts new file mode 100644 index 0000000000..afdc9d5152 --- /dev/null +++ b/ui-tui/src/lib/petPolling.ts @@ -0,0 +1,73 @@ +import type { GatewayClient } from '../gatewayClient.js' + +import { asRpcResult } from './rpc.js' + +export interface PetMetaResult { + enabled?: boolean + scale?: number + slug?: string + spritesheetRevision?: string +} + +interface PetUpdate { + cells: TCells | null + meta: PetMetaResult +} + +type PetGateway = Pick + +/** + * Suppress overlapping cosmetic polls so a slow gateway can never accumulate + * a queue of pet requests. Returning false tells callers that an existing + * probe is still in flight. + */ +export function createPetSingleFlight() { + let active = false + + return async (operation: () => Promise): Promise => { + if (active) { + return false + } + + active = true + + try { + await operation() + + return true + } finally { + active = false + } + } +} + +/** + * Probe cheap pet metadata on the gateway reader thread, then request the + * expensive frame payload only when the active selection/state is not cached. + * This deliberately bypasses the transcript-logging RPC wrapper: pet display + * is cosmetic, so an unavailable gateway must not print an error. + */ +export async function requestPetUpdate( + gateway: PetGateway, + state: string, + graphics: boolean, + needsCells: (meta: PetMetaResult) => boolean +): Promise | null> { + try { + const meta = asRpcResult(await gateway.request('pet.info.meta')) as PetMetaResult | null + + if (!meta) { + return null + } + + if (!meta.enabled || !needsCells(meta)) { + return { cells: null, meta } + } + + const cells = asRpcResult(await gateway.request('pet.cells', { graphics, state })) as TCells | null + + return { cells, meta } + } catch { + return null + } +}