From 83b3369ea5ceaee49d69c9afd11a24bde1442534 Mon Sep 17 00:00:00 2001 From: Cristian Lopez Date: Fri, 8 May 2026 08:50:20 +0200 Subject: [PATCH] fix: Support Codex pet sidekick animations (#1533) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Support Codex pet sidekick animations * Refine Codex pet defaults and drop unused failed animation state Always default spritesheetPath to spritesheet.webp when a manifest omits it, even when explicit frame/animation metadata is present, so non-Codex bundles still benefit from the standard sheet name. Drop the 'failed' animation entirely — Orca has no failure state, so mapping interrupted completions to 'failed' would conflate user cancellation with agent failure. Codex spritesheets can still expose a 'failed' row as an asset contract, but it's never selected at runtime. Co-authored-by: Orca --------- Co-authored-by: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Co-authored-by: Orca --- docs/sidekick-animation-state-mapping.md | 18 +++ src/main/ipc/sidekick-pet-bundle.test.ts | 108 +++++++++++++++ src/main/ipc/sidekick-pet-bundle.ts | 127 ++++++++++++++++++ src/main/ipc/sidekick.ts | 32 ++++- .../components/sidekick/SidekickOverlay.tsx | 44 +++++- .../sidekick/sidekick-agent-state.test.ts | 69 ++++++++++ .../sidekick/sidekick-agent-state.ts | 49 +++++++ 7 files changed, 433 insertions(+), 14 deletions(-) create mode 100644 docs/sidekick-animation-state-mapping.md create mode 100644 src/main/ipc/sidekick-pet-bundle.test.ts create mode 100644 src/main/ipc/sidekick-pet-bundle.ts create mode 100644 src/renderer/src/components/sidekick/sidekick-agent-state.test.ts create mode 100644 src/renderer/src/components/sidekick/sidekick-agent-state.ts diff --git a/docs/sidekick-animation-state-mapping.md b/docs/sidekick-animation-state-mapping.md new file mode 100644 index 000000000..a4ccd8afc --- /dev/null +++ b/docs/sidekick-animation-state-mapping.md @@ -0,0 +1,18 @@ +# Sidekick animation state mapping + +Orca's normalized agent status model has four hook-reported states: `working`, `blocked`, `waiting`, and `done`. `interrupted` is an optional flag on `done`, not a separate failure state. + +Codex pet spritesheets can expose more visual rows than Orca has agent states. Sidekick should treat those row names as an asset contract, not as proof that Codex or Orca reports matching runtime states. + +The current mapping is: + +| Orca condition | Sidekick animation | +| --- | --- | +| Sidekick is being dragged | `jumping` | +| Any fresh agent is `blocked` or `waiting` | `waiting` | +| Any fresh agent is `working` | `running` | +| Any fresh agent is `done` | `review` | +| Any retained completed agent exists | `review` | +| No fresh or retained agent state exists | `idle` | + +`SidekickAnimationName` deliberately omits `failed`. Orca distinguishes interrupted completions from normal completions, but interruption can mean user cancellation rather than agent failure, so mapping it to `failed` would overstate the status until Orca has a real failure/error signal. Codex spritesheets may still expose a `failed` row — that row stays as part of the asset contract but is never selected at runtime. diff --git a/src/main/ipc/sidekick-pet-bundle.test.ts b/src/main/ipc/sidekick-pet-bundle.test.ts new file mode 100644 index 000000000..0cafc2896 --- /dev/null +++ b/src/main/ipc/sidekick-pet-bundle.test.ts @@ -0,0 +1,108 @@ +import { describe, expect, it } from 'vitest' +import { + CODEX_PET_ANIMATIONS, + CODEX_PET_FRAME, + CODEX_PET_SPRITESHEET_PATH, + applyCodexPetDefaults, + readWebpDimensionsFromBuffer +} from './sidekick-pet-bundle' + +function u32(value: number): Buffer { + const buffer = Buffer.alloc(4) + buffer.writeUInt32LE(value, 0) + return buffer +} + +function u24(value: number): Buffer { + return Buffer.from([value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff]) +} + +function webpVp8x(width: number, height: number): Buffer { + const payload = Buffer.concat([Buffer.from([0, 0, 0, 0]), u24(width - 1), u24(height - 1)]) + return Buffer.concat([ + Buffer.from('RIFF'), + u32(4 + 8 + payload.byteLength), + Buffer.from('WEBP'), + Buffer.from('VP8X'), + u32(payload.byteLength), + payload + ]) +} + +describe('applyCodexPetDefaults', () => { + it('fills Codex pet manifests that omit Orca sprite metadata', () => { + const manifest = applyCodexPetDefaults({ id: 'apupepe', displayName: 'Pepe' }) + + expect(manifest.spritesheetPath).toBe(CODEX_PET_SPRITESHEET_PATH) + expect(manifest.frame).toEqual(CODEX_PET_FRAME) + expect(manifest.defaultAnimation).toBe('idle') + expect(manifest.animations).toEqual(CODEX_PET_ANIMATIONS) + expect(Object.keys(manifest.animations ?? [])).toEqual([ + 'idle', + 'running-right', + 'running-left', + 'waving', + 'jumping', + 'failed', + 'waiting', + 'running', + 'review' + ]) + }) + + it('fills Codex pet manifests that declare only spritesheetPath', () => { + const manifest = applyCodexPetDefaults({ + id: 'itachi', + displayName: 'Itachi', + spritesheetPath: 'spritesheet.webp' + }) + + expect(manifest.spritesheetPath).toBe(CODEX_PET_SPRITESHEET_PATH) + expect(manifest.frame).toEqual(CODEX_PET_FRAME) + expect(manifest.defaultAnimation).toBe('idle') + expect(manifest.animations).toEqual(CODEX_PET_ANIMATIONS) + }) + + it('does not override explicit Orca bundle sprite metadata', () => { + const manifest = applyCodexPetDefaults({ + spritesheetPath: 'custom.png', + frame: { width: 64, height: 64 }, + fps: 12, + defaultAnimation: 'blink', + animations: { blink: { row: 0, frames: 2 } } + }) + + expect(manifest).toEqual({ + spritesheetPath: 'custom.png', + frame: { width: 64, height: 64 }, + fps: 12, + defaultAnimation: 'blink', + animations: { blink: { row: 0, frames: 2 } } + }) + }) + + it('defaults only spritesheetPath when explicit sprite metadata is present', () => { + const manifest = applyCodexPetDefaults({ + frame: { width: 64, height: 64 }, + animations: { blink: { row: 0, frames: 2 } } + }) + + expect(manifest.spritesheetPath).toBe(CODEX_PET_SPRITESHEET_PATH) + expect(manifest.frame).toEqual({ width: 64, height: 64 }) + expect(manifest.animations).toEqual({ blink: { row: 0, frames: 2 } }) + expect(manifest.defaultAnimation).toBeUndefined() + }) +}) + +describe('readWebpDimensionsFromBuffer', () => { + it('reads VP8X WebP canvas dimensions without decoding pixels', () => { + expect(readWebpDimensionsFromBuffer(webpVp8x(1536, 1872))).toEqual({ + width: 1536, + height: 1872 + }) + }) + + it('returns null for non-WebP data', () => { + expect(readWebpDimensionsFromBuffer(Buffer.from('not an image'))).toBeNull() + }) +}) diff --git a/src/main/ipc/sidekick-pet-bundle.ts b/src/main/ipc/sidekick-pet-bundle.ts new file mode 100644 index 000000000..1d231ebaa --- /dev/null +++ b/src/main/ipc/sidekick-pet-bundle.ts @@ -0,0 +1,127 @@ +import type { SpriteAnimation } from '../../shared/types' + +export type PetManifestLike = { + id?: string + displayName?: string + description?: string + spritesheetPath?: string + frame?: { + width: number + height: number + } + fps?: number + defaultAnimation?: string + animations?: Record +} + +export type ResolvedPetManifest = T & + PetManifestLike & { + spritesheetPath: string + } + +export const CODEX_PET_SPRITESHEET_PATH = 'spritesheet.webp' +export const CODEX_PET_FRAME = { width: 192, height: 208 } as const +export const CODEX_PET_DEFAULT_ANIMATION = 'idle' +export const CODEX_PET_DEFAULT_FPS = 8 + +export const CODEX_PET_ANIMATIONS: Record = { + idle: { row: 0, frames: 6 }, + 'running-right': { row: 1, frames: 8 }, + 'running-left': { row: 2, frames: 8 }, + waving: { row: 3, frames: 4 }, + jumping: { row: 4, frames: 5 }, + failed: { row: 5, frames: 8 }, + waiting: { row: 6, frames: 6 }, + running: { row: 7, frames: 6 }, + review: { row: 8, frames: 6 } +} + +function isCodexPetSpritePath(spritesheetPath: string | undefined): boolean { + return spritesheetPath === undefined || /(^|[/\\])spritesheet\.webp$/i.test(spritesheetPath) +} + +export function applyCodexPetDefaults( + manifest: T +): ResolvedPetManifest { + const shouldApplyCodexLayout = + isCodexPetSpritePath(manifest.spritesheetPath) && + manifest.frame === undefined && + manifest.animations === undefined + + if (!shouldApplyCodexLayout) { + return { + ...manifest, + spritesheetPath: manifest.spritesheetPath ?? CODEX_PET_SPRITESHEET_PATH + } as ResolvedPetManifest + } + + return { + ...manifest, + spritesheetPath: manifest.spritesheetPath ?? CODEX_PET_SPRITESHEET_PATH, + frame: manifest.frame ?? CODEX_PET_FRAME, + fps: manifest.fps ?? CODEX_PET_DEFAULT_FPS, + defaultAnimation: manifest.defaultAnimation ?? CODEX_PET_DEFAULT_ANIMATION, + animations: manifest.animations ?? CODEX_PET_ANIMATIONS + } +} + +function readUInt24LE(buffer: Buffer, offset: number): number { + return buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) +} + +export function readWebpDimensionsFromBuffer( + buffer: Buffer +): { width: number; height: number } | null { + if ( + buffer.byteLength < 20 || + buffer.toString('ascii', 0, 4) !== 'RIFF' || + buffer.toString('ascii', 8, 12) !== 'WEBP' + ) { + return null + } + + let offset = 12 + while (offset + 8 <= buffer.byteLength) { + const chunkType = buffer.toString('ascii', offset, offset + 4) + const chunkSize = buffer.readUInt32LE(offset + 4) + const dataOffset = offset + 8 + const dataEnd = dataOffset + chunkSize + if (dataEnd > buffer.byteLength) { + return null + } + + if (chunkType === 'VP8X' && chunkSize >= 10) { + return { + width: readUInt24LE(buffer, dataOffset + 4) + 1, + height: readUInt24LE(buffer, dataOffset + 7) + 1 + } + } + + if (chunkType === 'VP8L' && chunkSize >= 5 && buffer[dataOffset] === 0x2f) { + const b0 = buffer[dataOffset + 1] + const b1 = buffer[dataOffset + 2] + const b2 = buffer[dataOffset + 3] + const b3 = buffer[dataOffset + 4] + return { + width: 1 + (((b1 & 0x3f) << 8) | b0), + height: 1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)) + } + } + + if ( + chunkType === 'VP8 ' && + chunkSize >= 10 && + buffer[dataOffset + 3] === 0x9d && + buffer[dataOffset + 4] === 0x01 && + buffer[dataOffset + 5] === 0x2a + ) { + const width = buffer.readUInt16LE(dataOffset + 6) & 0x3fff + const height = buffer.readUInt16LE(dataOffset + 8) & 0x3fff + return width > 0 && height > 0 ? { width, height } : null + } + + offset = dataEnd + (chunkSize % 2) + } + + return null +} diff --git a/src/main/ipc/sidekick.ts b/src/main/ipc/sidekick.ts index 9faead1ad..f8fee2a91 100644 --- a/src/main/ipc/sidekick.ts +++ b/src/main/ipc/sidekick.ts @@ -7,6 +7,12 @@ import { randomUUID } from 'node:crypto' import { basename, dirname, extname, isAbsolute, join, normalize, resolve, sep } from 'node:path' import { z } from 'zod' import type { CustomSidekick } from '../../shared/types' +import { + applyCodexPetDefaults, + readWebpDimensionsFromBuffer, + type PetManifestLike, + type ResolvedPetManifest +} from './sidekick-pet-bundle' // Why: image-only sidekick uploads. Static + animated variants render natively // via , so no 3D engine is needed. Main owns the accepted-format table as @@ -96,7 +102,8 @@ const PetManifestSchema = z .refine( (p) => !p.includes('\0') && !p.startsWith('/') && !p.startsWith('\\') && !p.includes('..'), 'invalid spritesheetPath' - ), + ) + .optional(), frame: z .object({ width: z.number().int().positive().max(1024), @@ -121,7 +128,7 @@ const PetManifestSchema = z // key" error instead of just ignoring the extras. .loose() -type PetManifest = z.infer +type PetManifest = z.infer & PetManifestLike // Why: renderer-supplied IPC inputs are untrusted — validate shape before any // path resolution. resolveSidekickFile still gates the actual filesystem path. @@ -134,6 +141,15 @@ const SidekickFileRequestSchema = z.object({ async function readSheetDimensions( buffer: Buffer ): Promise<{ width: number; height: number } | null> { + // Why: Electron's nativeImage can fail to decode some valid WebP variants + // even though Chromium can render them. Sprite sheets only need the canvas + // size, so read WebP dimensions from the container header before falling + // back to native decoding. + const webpDims = readWebpDimensionsFromBuffer(buffer) + if (webpDims) { + return webpDims + } + // Why: nativeImage decodes PNG/JPEG/GIF/WebP/BMP. SVG isn't supported here // (vector → no integer pixel grid), so pet bundles must use a raster sheet. const image = nativeImage.createFromBuffer(buffer) @@ -286,7 +302,7 @@ export function registerSidekickHandlers(): void { throw new Error('pet.json must not be a symlink.') } - let manifest: PetManifest + let manifest: ResolvedPetManifest try { const raw = await readFile(manifestPath, 'utf8') // Why: defend against TOCTOU between stat and read — the file could have @@ -294,14 +310,16 @@ export function registerSidekickHandlers(): void { if (Buffer.byteLength(raw, 'utf8') > MAX_MANIFEST_BYTES) { throw new Error('pet.json exceeded the manifest size limit.') } - manifest = PetManifestSchema.parse(JSON.parse(raw)) + manifest = applyCodexPetDefaults(PetManifestSchema.parse(JSON.parse(raw))) } catch (error) { throw new Error(`Invalid pet.json: ${error instanceof Error ? error.message : 'parse error'}`) } - // Why: spritesheetPath is bundle-relative. Reject absolute paths and any - // resolved path that escapes the bundle directory. Also reject symlinks so - // a malicious bundle can't reach outside via a sibling link. + // Why: spritesheetPath is bundle-relative. Codex pet.json files omit this + // path and use a fixed `spritesheet.webp`; applyCodexPetDefaults fills + // that shape before path validation. Reject absolute paths and any resolved + // path that escapes the bundle directory. Also reject symlinks so a + // malicious bundle can't reach outside via a sibling link. if (isAbsolute(manifest.spritesheetPath)) { throw new Error('spritesheetPath must be relative to the bundle.') } diff --git a/src/renderer/src/components/sidekick/SidekickOverlay.tsx b/src/renderer/src/components/sidekick/SidekickOverlay.tsx index 7baf8b870..d59d038e7 100644 --- a/src/renderer/src/components/sidekick/SidekickOverlay.tsx +++ b/src/renderer/src/components/sidekick/SidekickOverlay.tsx @@ -3,27 +3,50 @@ import { useSidekickUrl } from './useSidekickUrl' import type { DetectedSpriteCacheEntry } from './sidekick-blob-cache' import type { CustomSidekick } from '../../../../shared/types' import { useAppStore } from '../../store' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types' +import { selectSidekickAnimationName, type SidekickAnimationName } from './sidekick-agent-state' type Sprite = NonNullable +function useSidekickAnimationName(dragging: boolean): SidekickAnimationName { + const agentStatusByPaneKey = useAppStore((s) => s.agentStatusByPaneKey) + const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) + const retainedAgentsByPaneKey = useAppStore((s) => s.retainedAgentsByPaneKey) + + // Re-render when the freshness scheduler ticks so stale live states stop + // driving sidekick animations even if no other store value changes. + void agentStatusEpoch + + return selectSidekickAnimationName({ + entries: Object.values(agentStatusByPaneKey), + retainedCount: Object.keys(retainedAgentsByPaneKey).length, + dragging, + now: Date.now(), + staleAfterMs: AGENT_STATUS_STALE_AFTER_MS + }) +} + // Why: pet bundles ship a sprite sheet — animate by stepping a CSS background -// across the cells of one row. We pick which row + how many frames from the -// manifest's defaultAnimation, falling back to the first row if the manifest -// only declared frame size. imageRendering: 'pixelated' keeps edges crisp even -// when scale is fractional (needed when frames exceed maxSize). +// across the cells of one row. We pick the row from the live sidekick state +// when the manifest provides that animation, then fall back to the bundle's +// default animation. imageRendering: 'pixelated' keeps edges crisp even when +// scale is fractional (needed when frames exceed maxSize). function SpriteFrame({ url, sprite, animate, - maxSize + maxSize, + animationName }: { url: string sprite: Sprite animate: boolean maxSize: number + animationName: SidekickAnimationName }): React.JSX.Element { const animKeyframesId = useId().replace(/[^a-zA-Z0-9_-]/g, '') const anim = + sprite.animations?.[animationName] || (sprite.defaultAnimation && sprite.animations?.[sprite.defaultAnimation]) || (sprite.animations ? Object.values(sprite.animations)[0] : undefined) const row = anim?.row ?? 0 @@ -129,7 +152,7 @@ function DetectedSpriteFrame({ cancelAnimationFrame(raf) } } - }, [detected, animate, maxSize]) + }, [detected, animate, maxSize, fps]) return ( {sprite ? ( - + ) : detected ? ( ) : ( diff --git a/src/renderer/src/components/sidekick/sidekick-agent-state.test.ts b/src/renderer/src/components/sidekick/sidekick-agent-state.test.ts new file mode 100644 index 000000000..1e0c434d3 --- /dev/null +++ b/src/renderer/src/components/sidekick/sidekick-agent-state.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest' +import type { AgentStatusEntry, AgentStatusState } from '../../../../shared/agent-status-types' +import { selectSidekickAnimationName } from './sidekick-agent-state' + +const NOW = 1_000 +const STALE_AFTER_MS = 500 + +function entry( + state: AgentStatusState, + overrides: Partial = {} +): AgentStatusEntry { + return { + state, + prompt: '', + updatedAt: NOW, + stateStartedAt: NOW, + paneKey: `tab:${state}`, + stateHistory: [], + ...overrides + } +} + +function select( + entries: AgentStatusEntry[], + options: Partial[0]> = {} +) { + return selectSidekickAnimationName({ + entries, + retainedCount: 0, + dragging: false, + now: NOW, + staleAfterMs: STALE_AFTER_MS, + ...options + }) +} + +describe('selectSidekickAnimationName', () => { + it('uses idle when no fresh agent state exists', () => { + expect(select([])).toBe('idle') + expect(select([entry('working', { updatedAt: NOW - STALE_AFTER_MS - 1 })])).toBe('idle') + }) + + it('maps live work to running', () => { + expect(select([entry('working')])).toBe('running') + }) + + it('maps blocked and waiting states to waiting', () => { + expect(select([entry('blocked')])).toBe('waiting') + expect(select([entry('waiting')])).toBe('waiting') + }) + + it('prioritizes attention-needed states over running work', () => { + expect(select([entry('working'), entry('blocked')])).toBe('waiting') + }) + + it('maps completed live or retained work to review', () => { + expect(select([entry('done')])).toBe('review') + expect(select([], { retainedCount: 1 })).toBe('review') + }) + + it('maps interrupted completion to review because Orca does not expose failure as a state', () => { + expect(select([entry('done', { interrupted: true })])).toBe('review') + expect(select([entry('working'), entry('done', { interrupted: true })])).toBe('running') + }) + + it('uses jumping while the sidekick is being dragged', () => { + expect(select([entry('blocked')], { dragging: true })).toBe('jumping') + }) +}) diff --git a/src/renderer/src/components/sidekick/sidekick-agent-state.ts b/src/renderer/src/components/sidekick/sidekick-agent-state.ts new file mode 100644 index 000000000..96430ddbc --- /dev/null +++ b/src/renderer/src/components/sidekick/sidekick-agent-state.ts @@ -0,0 +1,49 @@ +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { isExplicitAgentStatusFresh } from '@/lib/agent-status' + +export type SidekickAnimationName = 'idle' | 'running' | 'waiting' | 'review' | 'jumping' + +export type SidekickAnimationInput = { + entries: AgentStatusEntry[] + retainedCount: number + dragging: boolean + now: number + staleAfterMs: number +} + +export function selectSidekickAnimationName({ + entries, + retainedCount, + dragging, + now, + staleAfterMs +}: SidekickAnimationInput): SidekickAnimationName { + if (dragging) { + return 'jumping' + } + + let hasWorking = false + let hasDone = false + + for (const entry of entries) { + if (!isExplicitAgentStatusFresh(entry, now, staleAfterMs)) { + continue + } + if (entry.state === 'blocked' || entry.state === 'waiting') { + return 'waiting' + } + if (entry.state === 'working') { + hasWorking = true + } else if (entry.state === 'done') { + hasDone = true + } + } + + if (hasWorking) { + return 'running' + } + if (hasDone || retainedCount > 0) { + return 'review' + } + return 'idle' +}