fix(tui): stop disabled pet cell polling

This commit is contained in:
Gabriel Atkinson
2026-07-23 14:18:33 -07:00
committed by Teknium
parent 1c23c2a50b
commit 868c400e54
3 changed files with 210 additions and 24 deletions
+74
View File
@@ -0,0 +1,74 @@
import { describe, expect, it, vi } from 'vitest'
import { createPetSingleFlight, requestPetUpdate } from '../lib/petPolling.js'
const gateway = (request: ReturnType<typeof vi.fn>) => ({ 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<void>(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)
})
})
+63 -24
View File
@@ -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<PetGrid | null>(null)
@@ -116,9 +118,11 @@ export function usePet(): PetRender {
const cache = useRef<Map<string, CacheEntry>>(new Map())
const slugRef = useRef('')
const scaleRef = useRef(0)
const revisionRef = useRef('')
const imageIdRef = useRef(0)
const stateRef = useRef<PetState>('idle')
const frameRef = useRef(0)
const runSingleFlight = useRef(createPetSingleFlight()).current
const [petState, setPetState] = useState<PetState>('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<PetCellsResult>(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
+73
View File
@@ -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<TCells> {
cells: TCells | null
meta: PetMetaResult
}
type PetGateway = Pick<GatewayClient, 'request'>
/**
* 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<void>): Promise<boolean> => {
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<TCells>(
gateway: PetGateway,
state: string,
graphics: boolean,
needsCells: (meta: PetMetaResult) => boolean
): Promise<PetUpdate<TCells> | 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
}
}