diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index 7d26bfba6..aa905cadb 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -97,7 +97,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings terminalMacOptionAsAltMigrated: true, experimentalMobile: false, mobileAutoRestoreFitMs: null, - experimentalSidekick: false, + experimentalPet: false, experimentalWorktreeSymlinks: false, terminalWindowsShell: 'powershell.exe', terminalWindowsPowerShellImplementation: 'powershell.exe', diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index 55747297d..0f66249ed 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -91,7 +91,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings terminalMacOptionAsAltMigrated: true, experimentalMobile: false, mobileAutoRestoreFitMs: null, - experimentalSidekick: false, + experimentalPet: false, experimentalWorktreeSymlinks: false, terminalWindowsShell: 'powershell.exe', terminalWindowsPowerShellImplementation: 'powershell.exe', diff --git a/src/main/ipc/pet-bundle.test.ts b/src/main/ipc/pet-bundle.test.ts new file mode 100644 index 000000000..f8d4f880f --- /dev/null +++ b/src/main/ipc/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 './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/pet-bundle.ts b/src/main/ipc/pet-bundle.ts new file mode 100644 index 000000000..1d231ebaa --- /dev/null +++ b/src/main/ipc/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/pet.ts similarity index 87% rename from src/main/ipc/sidekick.ts rename to src/main/ipc/pet.ts index f8fee2a91..de3d11b59 100644 --- a/src/main/ipc/sidekick.ts +++ b/src/main/ipc/pet.ts @@ -6,15 +6,15 @@ import { pipeline } from 'node:stream/promises' 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 type { CustomPet } from '../../shared/types' import { applyCodexPetDefaults, readWebpDimensionsFromBuffer, type PetManifestLike, type ResolvedPetManifest -} from './sidekick-pet-bundle' +} from './pet-bundle' -// Why: image-only sidekick uploads. Static + animated variants render natively +// Why: image-only pet uploads. Static + animated variants render natively // via , so no 3D engine is needed. Main owns the accepted-format table as // the single source of truth for what the renderer will try to display. const IMAGE_FORMATS: Record = { @@ -36,11 +36,10 @@ function classifyFile(src: string): { mimeType: string; ext: string } | null { return { mimeType: mime, ext } } -// Why: custom user-uploaded images live in a dedicated folder under userData -// so they persist across updates but are scoped to the Orca install. We never -// trust paths the renderer hands us — the renderer only ever knows the opaque -// CustomSidekick.id; main resolves it to an absolute path inside this folder. -function getSidekicksDir(): string { +// Why: keep using the legacy sidekicks folder so existing user-uploaded pets +// keep rendering after the product rename. The renderer only knows CustomPet.id; +// main resolves it to an absolute path inside this folder. +function getPetsDir(): string { return join(app.getPath('userData'), 'sidekicks', 'custom') } @@ -54,16 +53,12 @@ function isSafeId(id: string): boolean { return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) } -function resolveSidekickFile( - id: string, - fileName: string, - kind: 'image' | 'bundle' -): string | null { +function resolvePetFile(id: string, fileName: string, kind: 'image' | 'bundle'): string | null { if (!isSafeId(id)) { return null } const safeName = basename(fileName) - const root = normalize(getSidekicksDir()) + const root = normalize(getPetsDir()) let filePath: string if (kind === 'bundle') { // Bundle layout: custom//. fileName is just the spritesheet @@ -131,8 +126,8 @@ const PetManifestSchema = z 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. -const SidekickFileRequestSchema = z.object({ +// path resolution. resolvePetFile still gates the actual filesystem path. +const PetFileRequestSchema = z.object({ id: z.string(), fileName: z.string(), kind: z.enum(['image', 'bundle']).optional() @@ -192,12 +187,12 @@ async function isSymlink(path: string): Promise { } } -export function registerSidekickHandlers(): void { - ipcMain.handle('sidekick:import', async (event): Promise => { +export function registerPetHandlers(): void { + ipcMain.handle('pet:import', async (event): Promise => { const senderWindow = BrowserWindow.fromWebContents(event.sender) ?? BrowserWindow.getFocusedWindow() const options: Electron.OpenDialogOptions = { - title: 'Pick sidekick', + title: 'Pick pet', properties: ['openFile'], // Why: single filter and no `apng` extension. macOS file dialogs map // filter extensions to UTIs; `apng` has no registered UTI, so including @@ -206,7 +201,7 @@ export function registerSidekickHandlers(): void { // bytes by the browser. filters: [ { - name: 'Sidekick image', + name: 'Pet image', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'] } ] @@ -237,11 +232,11 @@ export function registerSidekickHandlers(): void { ) } - const dir = getSidekicksDir() + const dir = getPetsDir() await mkdir(dir, { recursive: true }) const id = randomUUID() - // Why: preserve original extension in the on-disk name so sidekick:read can - // rebuild the right Blob MIME via resolveSidekickFile without a separate + // Why: preserve original extension in the on-disk name so pet:read can + // rebuild the right Blob MIME via resolvePetFile without a separate // lookup. The extension is only ever written by main (never the renderer). const fileName = `${id}${classified.ext}` const dest = join(dir, fileName) @@ -249,11 +244,11 @@ export function registerSidekickHandlers(): void { await copyFile(src, dest) } catch { await rm(dest, { force: true }).catch(() => {}) - throw new Error('Could not save the sidekick.') + throw new Error('Could not save the pet.') } const rawLabel = basename(src, extname(src)).trim() - const label = rawLabel.length > 0 ? rawLabel.slice(0, 40) : 'Custom sidekick' + const label = rawLabel.length > 0 ? rawLabel.slice(0, 40) : 'Custom pet' return { id, label, @@ -263,7 +258,7 @@ export function registerSidekickHandlers(): void { } }) - ipcMain.handle('sidekick:importPetBundle', async (event): Promise => { + ipcMain.handle('pet:importPetBundle', async (event): Promise => { const senderWindow = BrowserWindow.fromWebContents(event.sender) ?? BrowserWindow.getFocusedWindow() // Why: the bundle is a folder. macOS users may also pick `pet.json` itself @@ -359,7 +354,7 @@ export function registerSidekickHandlers(): void { ) } - let sprite: NonNullable | undefined + let sprite: NonNullable | undefined if (manifest.frame) { // Why: only decode the sheet when we need to validate frame layout. // nativeImage may fail on some WebP variants in headless contexts, and @@ -412,10 +407,10 @@ export function registerSidekickHandlers(): void { // Why: storage id is always a fresh UUID — the manifest's `id` is purely // a display hint. This guards against (a) collisions with bundled - // sidekick ids, (b) failing isSafeId, and (c) re-import clobbering an + // pet ids, (b) failing isSafeId, and (c) re-import clobbering an // earlier copy of the same bundle. const id = randomUUID() - const root = getSidekicksDir() + const root = getPetsDir() await mkdir(root, { recursive: true }) const destDir = join(root, id) const sheetExt = sheetClass.ext @@ -451,7 +446,7 @@ export function registerSidekickHandlers(): void { }) ipcMain.handle( - 'sidekick:read', + 'pet:read', async ( _event, id: string, @@ -460,15 +455,15 @@ export function registerSidekickHandlers(): void { ): Promise => { // Why: validate IPC inputs before any path logic — renderer is not // trusted to send strings of the right shape. - let parsed: z.infer + let parsed: z.infer try { - parsed = SidekickFileRequestSchema.parse({ id, fileName, kind }) + parsed = PetFileRequestSchema.parse({ id, fileName, kind }) } catch { - throw new Error('Invalid sidekick:read arguments') + throw new Error('Invalid pet:read arguments') } // Why: missing kind defaults to 'image' for backwards compatibility with // pre-bundle persisted state. - const filePath = resolveSidekickFile(parsed.id, parsed.fileName, parsed.kind ?? 'image') + const filePath = resolvePetFile(parsed.id, parsed.fileName, parsed.kind ?? 'image') if (!filePath) { return null } @@ -476,30 +471,30 @@ export function registerSidekickHandlers(): void { const buf = await readFile(filePath) return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) } catch (error) { - console.warn('[sidekick-overlay] sidekick:read failed', error) + console.warn('[pet-overlay] pet:read failed', error) return null } } ) ipcMain.handle( - 'sidekick:delete', + 'pet:delete', async (_event, id: string, fileName: string, kind?: 'image' | 'bundle'): Promise => { // Why: validate IPC inputs before any path logic. - let parsed: z.infer + let parsed: z.infer try { - parsed = SidekickFileRequestSchema.parse({ id, fileName, kind }) + parsed = PetFileRequestSchema.parse({ id, fileName, kind }) } catch { - throw new Error('Invalid sidekick:delete arguments') + throw new Error('Invalid pet:delete arguments') } if (!isSafeId(parsed.id)) { return } if ((parsed.kind ?? 'image') === 'bundle') { // Why: bundle imports own a whole directory. isSafeId already gates id; - // we still build the path under the sidekicks root and verify the + // we still build the path under the pets root and verify the // prefix before recursive removal as defense in depth. - const root = normalize(getSidekicksDir()) + const root = normalize(getPetsDir()) const target = normalize(join(root, parsed.id)) if (!target.startsWith(root + sep)) { return @@ -507,18 +502,18 @@ export function registerSidekickHandlers(): void { try { await rm(target, { recursive: true, force: true }) } catch (error) { - console.warn('[sidekick-overlay] sidekick:delete (bundle) failed', error) + console.warn('[pet-overlay] pet:delete (bundle) failed', error) } return } - const filePath = resolveSidekickFile(parsed.id, parsed.fileName, 'image') + const filePath = resolvePetFile(parsed.id, parsed.fileName, 'image') if (!filePath) { return } try { await rm(filePath, { force: true }) } catch (error) { - console.warn('[sidekick-overlay] sidekick:delete failed', error) + console.warn('[pet-overlay] pet:delete failed', error) } } ) diff --git a/src/main/ipc/register-core-handlers.test.ts b/src/main/ipc/register-core-handlers.test.ts index e43f3de60..3002d53d5 100644 --- a/src/main/ipc/register-core-handlers.test.ts +++ b/src/main/ipc/register-core-handlers.test.ts @@ -14,7 +14,7 @@ const { registerSettingsHandlersMock, registerTelemetryHandlersMock, registerShellHandlersMock, - registerSidekickHandlersMock, + registerPetHandlersMock, registerSessionHandlersMock, registerUIHandlersMock, registerFilesystemHandlersMock, @@ -47,7 +47,7 @@ const { registerSettingsHandlersMock: vi.fn(), registerTelemetryHandlersMock: vi.fn(), registerShellHandlersMock: vi.fn(), - registerSidekickHandlersMock: vi.fn(), + registerPetHandlersMock: vi.fn(), registerSessionHandlersMock: vi.fn(), registerUIHandlersMock: vi.fn(), registerFilesystemHandlersMock: vi.fn(), @@ -124,8 +124,8 @@ vi.mock('./shell', () => ({ registerShellHandlers: registerShellHandlersMock })) -vi.mock('./sidekick', () => ({ - registerSidekickHandlers: registerSidekickHandlersMock +vi.mock('./pet', () => ({ + registerPetHandlers: registerPetHandlersMock })) vi.mock('./session', () => ({ @@ -204,7 +204,7 @@ describe('registerCoreHandlers', () => { registerSettingsHandlersMock.mockReset() registerTelemetryHandlersMock.mockReset() registerShellHandlersMock.mockReset() - registerSidekickHandlersMock.mockReset() + registerPetHandlersMock.mockReset() registerSessionHandlersMock.mockReset() registerUIHandlersMock.mockReset() registerFilesystemHandlersMock.mockReset() @@ -250,7 +250,7 @@ describe('registerCoreHandlers', () => { expect(registerCodexUsageHandlersMock).toHaveBeenCalledWith(codexUsage) expect(registerCodexAccountHandlersMock).toHaveBeenCalledWith(codexAccounts) expect(registerAgentHookHandlersMock).toHaveBeenCalled() - expect(registerSidekickHandlersMock).toHaveBeenCalled() + expect(registerPetHandlersMock).toHaveBeenCalled() expect(registerClaudeAccountHandlersMock).toHaveBeenCalledWith(claudeAccounts) expect(registerRateLimitHandlersMock).toHaveBeenCalledWith(rateLimits) expect(registerGitHubHandlersMock).toHaveBeenCalledWith(store, stats) diff --git a/src/main/ipc/register-core-handlers.ts b/src/main/ipc/register-core-handlers.ts index 2213476ca..4fa4d2237 100644 --- a/src/main/ipc/register-core-handlers.ts +++ b/src/main/ipc/register-core-handlers.ts @@ -25,7 +25,7 @@ import { registerTelemetryHandlers } from './telemetry' import { registerBrowserHandlers } from './browser' import { browserSessionRegistry } from '../browser/browser-session-registry' import { registerShellHandlers } from './shell' -import { registerSidekickHandlers } from './sidekick' +import { registerPetHandlers } from './pet' import { registerUIHandlers } from './ui' import { registerCodexAccountHandlers } from './codex-accounts' import { registerAgentHookHandlers } from './agent-hooks' @@ -94,7 +94,7 @@ export function registerCoreHandlers( browserSessionRegistry.applyPendingCookieImport() browserSessionRegistry.restorePersistedUserAgent() registerShellHandlers() - registerSidekickHandlers() + registerPetHandlers() registerSessionHandlers(store) registerUIHandlers(store) registerFilesystemHandlers(store) diff --git a/src/main/persistence.test.ts b/src/main/persistence.test.ts index 9acdff75f..0339bdecb 100644 --- a/src/main/persistence.test.ts +++ b/src/main/persistence.test.ts @@ -650,6 +650,22 @@ describe('Store', () => { expect(store.getSettings().terminalMacOptionAsAltMigrated).toBe(true) }) + it('migrates the legacy experimentalSidekick setting to experimentalPet', async () => { + writeDataFile({ + schemaVersion: 1, + repos: [], + worktreeMeta: {}, + settings: { experimentalSidekick: true }, + ui: {}, + githubCache: { pr: {}, issue: {} }, + workspaceSession: {} + }) + + const store = await createStore() + + expect(store.getSettings().experimentalPet).toBe(true) + }) + // ── inline-agents card-property migration ────────────────────────── // // Why: 'inline-agents' was added to DEFAULT_WORKTREE_CARD_PROPERTIES after diff --git a/src/main/persistence.ts b/src/main/persistence.ts index c8166b85e..3cd7dc81b 100644 --- a/src/main/persistence.ts +++ b/src/main/persistence.ts @@ -115,6 +115,10 @@ function readDeprecatedExperimentFlag(parsed: PersistedState | undefined): boole ) } +function readLegacySidekickFlag(parsed: PersistedState | undefined): boolean | undefined { + return (parsed?.settings as { experimentalSidekick?: boolean } | undefined)?.experimentalSidekick +} + export class Store { private state: PersistedState private writeTimer: ReturnType | null = null @@ -180,6 +184,10 @@ export class Store { settings: { ...defaults.settings, ...parsed.settings, + // Why: v1.3.42 renamed the cosmetic sidekick setting to pet. Carry + // the old persisted flag forward once so enabled users don't lose it. + experimentalPet: + parsed.settings?.experimentalPet ?? readLegacySidekickFlag(parsed) ?? false, terminalMacOptionAsAlt: migratedOptionAsAlt, terminalMacOptionAsAltMigrated: true, notifications: { diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index a8458795b..9e623d1ca 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -11,7 +11,7 @@ import type { CodexRateLimitAccountsState, CreateWorktreeArgs, CreateWorktreeResult, - CustomSidekick, + CustomPet, DirEntry, FsChangedPayload, GhosttyImportPreview, @@ -769,9 +769,9 @@ export type PreloadApi = { pickDirectory: (args: { defaultPath?: string }) => Promise copyFile: (args: { srcPath: string; destPath: string }) => Promise } - sidekick: { - import: () => Promise - importPetBundle: () => Promise + pet: { + import: () => Promise + importPetBundle: () => Promise read: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise delete: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise } diff --git a/src/preload/index.ts b/src/preload/index.ts index 8d3eb0306..03d61ebe3 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -10,7 +10,7 @@ import type { BaseRefDefaultResult, BrowserViewportOverride, CreateWorktreeArgs, - CustomSidekick, + CustomPet, FsChangedPayload, GetRateLimitResult, GitHubAssignableUser, @@ -1003,14 +1003,13 @@ const api = { ipcRenderer.invoke('shell:copyFile', args) }, - sidekick: { - import: (): Promise => ipcRenderer.invoke('sidekick:import'), - importPetBundle: (): Promise => - ipcRenderer.invoke('sidekick:importPetBundle'), + pet: { + import: (): Promise => ipcRenderer.invoke('pet:import'), + importPetBundle: (): Promise => ipcRenderer.invoke('pet:importPetBundle'), read: (id: string, fileName: string, kind?: 'image' | 'bundle'): Promise => - ipcRenderer.invoke('sidekick:read', id, fileName, kind), + ipcRenderer.invoke('pet:read', id, fileName, kind), delete: (id: string, fileName: string, kind?: 'image' | 'bundle'): Promise => - ipcRenderer.invoke('sidekick:delete', id, fileName, kind) + ipcRenderer.invoke('pet:delete', id, fileName, kind) }, browser: { diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 88b1f659d..b18483f74 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -2,7 +2,14 @@ import { lazy, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { getDefaultUIState } from '../../shared/constants' -import { ArrowLeft, ArrowRight, Minimize2, MoreHorizontal, PanelLeft, PanelRight } from 'lucide-react' +import { + ArrowLeft, + ArrowRight, + Minimize2, + MoreHorizontal, + PanelLeft, + PanelRight +} from 'lucide-react' import logo from '../../../resources/logo.svg' import { SYNC_FIT_PANES_EVENT, TOGGLE_TERMINAL_PANE_EXPAND_EVENT } from '@/constants/terminal' import { syncZoomCSSVar } from '@/lib/ui-zoom' @@ -75,10 +82,7 @@ function WindowControls(): React.JSX.Element { {maximized ? ( // Restore icon (two overlapping squares) - + ) : ( // Maximize icon (single square outline) @@ -97,10 +101,7 @@ function WindowControls(): React.JSX.Element { onClick={() => window.api.ui.requestClose()} > - + @@ -115,7 +116,7 @@ const WorktreeJumpPalette = lazy(() => import('./components/WorktreeJumpPalette' const NewWorkspaceComposerModal = lazy(() => import('./components/NewWorkspaceComposerModal')) // Why: lazy-loaded so the WebP asset + overlay module aren't fetched unless // the user opts into the experimental flag. -const SidekickOverlay = lazy(() => import('./components/sidekick/SidekickOverlay')) +const PetOverlay = lazy(() => import('./components/pet/PetOverlay')) function isEditableTarget(target: EventTarget | null): boolean { if (!(target instanceof HTMLElement)) { @@ -205,8 +206,8 @@ function App(): React.JSX.Element { const rightSidebarOpen = useAppStore((s) => s.rightSidebarOpen) const isFullScreen = useAppStore((s) => s.isFullScreen) const settings = useAppStore((s) => s.settings) - const sidekickEnabled = useAppStore((s) => s.settings?.experimentalSidekick === true) - const sidekickVisible = useAppStore((s) => s.sidekickVisible) + const petEnabled = useAppStore((s) => s.settings?.experimentalPet === true) + const petVisible = useAppStore((s) => s.petVisible) const canGoBackWorktree = useAppStore(canGoBackWorktreeHistory) const canGoForwardWorktree = useAppStore(canGoForwardWorktreeHistory) const titlebarLeftControlsRef = useRef(null) @@ -1140,13 +1141,13 @@ function App(): React.JSX.Element { {mountedLazyModalIds.has('quick-open') ? : null} {mountedLazyModalIds.has('worktree-palette') ? : null} - {/* Why: mount SidekickOverlay only when the experimental flag is on AND - the user hasn't hit "Hide sidekick" in the status-bar menu. Both - conditions must be true — see design doc (sidekick-overlay.md) on why + {/* Why: mount PetOverlay only when the experimental flag is on AND + the user hasn't hit "Hide pet" in the status-bar menu. Both + conditions must be true — see design doc (pet-overlay.md) on why the two toggles are kept independent. */} - {sidekickEnabled && sidekickVisible ? ( + {petEnabled && petVisible ? ( - + ) : null} diff --git a/src/renderer/src/components/sidekick/SidekickOverlay.tsx b/src/renderer/src/components/pet/PetOverlay.tsx similarity index 89% rename from src/renderer/src/components/sidekick/SidekickOverlay.tsx rename to src/renderer/src/components/pet/PetOverlay.tsx index d59d038e7..06812a4a5 100644 --- a/src/renderer/src/components/sidekick/SidekickOverlay.tsx +++ b/src/renderer/src/components/pet/PetOverlay.tsx @@ -1,23 +1,23 @@ import { useEffect, useId, useRef, useState } from 'react' -import { useSidekickUrl } from './useSidekickUrl' -import type { DetectedSpriteCacheEntry } from './sidekick-blob-cache' -import type { CustomSidekick } from '../../../../shared/types' +import { usePetUrl } from './usePetUrl' +import type { DetectedSpriteCacheEntry } from './pet-blob-cache' +import type { CustomPet } 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' +import { selectPetAnimationName, type PetAnimationName } from './pet-agent-state' -type Sprite = NonNullable +type Sprite = NonNullable -function useSidekickAnimationName(dragging: boolean): SidekickAnimationName { +function usePetAnimationName(dragging: boolean): PetAnimationName { 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. + // driving pet animations even if no other store value changes. void agentStatusEpoch - return selectSidekickAnimationName({ + return selectPetAnimationName({ entries: Object.values(agentStatusByPaneKey), retainedCount: Object.keys(retainedAgentsByPaneKey).length, dragging, @@ -27,7 +27,7 @@ function useSidekickAnimationName(dragging: boolean): SidekickAnimationName { } // Why: pet bundles ship a sprite sheet — animate by stepping a CSS background -// across the cells of one row. We pick the row from the live sidekick state +// across the cells of one row. We pick the row from the live pet 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). @@ -42,7 +42,7 @@ function SpriteFrame({ sprite: Sprite animate: boolean maxSize: number - animationName: SidekickAnimationName + animationName: PetAnimationName }): React.JSX.Element { const animKeyframesId = useId().replace(/[^a-zA-Z0-9_-]/g, '') const anim = @@ -198,7 +198,7 @@ function usePrefersReducedMotion(): boolean { // Why: keep a default for the cached helpers below; the live size now comes // from the store so the user can resize from the status-bar menu. const SIZE = 180 -const POSITION_STORAGE_KEY = 'sidekick-overlay-position' +const POSITION_STORAGE_KEY = 'pet-overlay-position' type Position = { x: number; y: number } @@ -249,18 +249,18 @@ function defaultPosition(size: number = SIZE): Position { ) } -export function SidekickOverlay(): React.JSX.Element { +export function PetOverlay(): React.JSX.Element { const documentVisible = useDocumentVisible() const reducedMotion = usePrefersReducedMotion() - const { url, sprite, detected } = useSidekickUrl() - const size = useAppStore((s) => s.sidekickSize) + const { url, sprite, detected } = usePetUrl() + const size = useAppStore((s) => s.petSize) const [position, setPosition] = useState(() => { // Why: read the persisted size eagerly via getState so the initial clamp - // uses the user's last sidekick size — useState's lazy initializer runs + // uses the user's last pet size — useState's lazy initializer runs // before the `size` prop binding settles, and `loadStoredPosition` would // otherwise default to SIZE and clip a previously-saved position. - const currentSize = useAppStore.getState().sidekickSize ?? SIZE + const currentSize = useAppStore.getState().petSize ?? SIZE return loadStoredPosition(currentSize) ?? defaultPosition(currentSize) }) const [dragging, setDragging] = useState(false) @@ -290,7 +290,7 @@ export function SidekickOverlay(): React.JSX.Element { }, [dragging, position]) const animate = documentVisible && !reducedMotion && !dragging - const animationName = useSidekickAnimationName(dragging) + const animationName = usePetAnimationName(dragging) // Why: setPointerCapture routes subsequent pointer events to this element // even when the cursor leaves the OS window, so dragging can't get stuck in @@ -332,7 +332,7 @@ export function SidekickOverlay(): React.JSX.Element { return ( // Why: the wrapper is fixed-positioned and pointer-events-none so app - // chrome stays interactive; only the sidekick itself opts back in to + // chrome stays interactive; only the pet itself opts back in to // pointer events so the user can press and drag it around.
{sprite ? ( @@ -385,4 +385,4 @@ export function SidekickOverlay(): React.JSX.Element { ) } -export default SidekickOverlay +export default PetOverlay diff --git a/src/renderer/src/components/sidekick/sidekick-agent-state.test.ts b/src/renderer/src/components/pet/pet-agent-state.test.ts similarity index 85% rename from src/renderer/src/components/sidekick/sidekick-agent-state.test.ts rename to src/renderer/src/components/pet/pet-agent-state.test.ts index 1e0c434d3..4c6d28b71 100644 --- a/src/renderer/src/components/sidekick/sidekick-agent-state.test.ts +++ b/src/renderer/src/components/pet/pet-agent-state.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { AgentStatusEntry, AgentStatusState } from '../../../../shared/agent-status-types' -import { selectSidekickAnimationName } from './sidekick-agent-state' +import { selectPetAnimationName } from './pet-agent-state' const NOW = 1_000 const STALE_AFTER_MS = 500 @@ -22,9 +22,9 @@ function entry( function select( entries: AgentStatusEntry[], - options: Partial[0]> = {} + options: Partial[0]> = {} ) { - return selectSidekickAnimationName({ + return selectPetAnimationName({ entries, retainedCount: 0, dragging: false, @@ -34,7 +34,7 @@ function select( }) } -describe('selectSidekickAnimationName', () => { +describe('selectPetAnimationName', () => { 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') @@ -63,7 +63,7 @@ describe('selectSidekickAnimationName', () => { expect(select([entry('working'), entry('done', { interrupted: true })])).toBe('running') }) - it('uses jumping while the sidekick is being dragged', () => { + it('uses jumping while the pet 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/pet/pet-agent-state.ts similarity index 79% rename from src/renderer/src/components/sidekick/sidekick-agent-state.ts rename to src/renderer/src/components/pet/pet-agent-state.ts index 96430ddbc..f45d54bad 100644 --- a/src/renderer/src/components/sidekick/sidekick-agent-state.ts +++ b/src/renderer/src/components/pet/pet-agent-state.ts @@ -1,9 +1,9 @@ import type { AgentStatusEntry } from '../../../../shared/agent-status-types' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' -export type SidekickAnimationName = 'idle' | 'running' | 'waiting' | 'review' | 'jumping' +export type PetAnimationName = 'idle' | 'running' | 'waiting' | 'review' | 'jumping' -export type SidekickAnimationInput = { +export type PetAnimationInput = { entries: AgentStatusEntry[] retainedCount: number dragging: boolean @@ -11,13 +11,13 @@ export type SidekickAnimationInput = { staleAfterMs: number } -export function selectSidekickAnimationName({ +export function selectPetAnimationName({ entries, retainedCount, dragging, now, staleAfterMs -}: SidekickAnimationInput): SidekickAnimationName { +}: PetAnimationInput): PetAnimationName { if (dragging) { return 'jumping' } diff --git a/src/renderer/src/components/sidekick/sidekick-blob-cache.ts b/src/renderer/src/components/pet/pet-blob-cache.ts similarity index 92% rename from src/renderer/src/components/sidekick/sidekick-blob-cache.ts rename to src/renderer/src/components/pet/pet-blob-cache.ts index 8de75255e..67495cbd6 100644 --- a/src/renderer/src/components/sidekick/sidekick-blob-cache.ts +++ b/src/renderer/src/components/pet/pet-blob-cache.ts @@ -1,11 +1,11 @@ -// Why: isolated module so the store slice can call revokeCustomSidekickBlobUrl -// without importing useSidekickUrl (which itself imports the store). Keeps +// Why: isolated module so the store slice can call revokeCustomPetBlobUrl +// without importing usePetUrl (which itself imports the store). Keeps // the dependency graph acyclic. import { detectFramesFromImageData, type DetectedFrame } from './sprite-frame-detection' // Why: sandbox=true + webSecurity=true block the renderer from reading user -// files directly. For custom sidekick images we fetch the bytes over IPC and +// files directly. For custom pet images we fetch the bytes over IPC and // turn them into a `blob:` URL that an tag can load. A small in-memory // cache means switching back and forth between images in the same session // doesn't re-fetch from main. @@ -37,12 +37,12 @@ export async function loadCustomBlobUrl( } // Why: defensively clear any stale entry so we don't leak a prior blob URL // or ImageBitmap[] when re-populating after a cache miss. - revokeCustomSidekickBlobUrl(id) - const buffer = await window.api.sidekick.read(id, fileName, kind) + revokeCustomPetBlobUrl(id) + const buffer = await window.api.pet.read(id, fileName, kind) if (!buffer) { return null } - // Why: MIME comes from CustomSidekick.mimeType — required especially for + // Why: MIME comes from CustomPet.mimeType — required especially for // SVG, which browsers refuse to render from a blob URL with the wrong // Content-Type. const blob = new Blob([buffer], { type: mimeType }) @@ -53,7 +53,7 @@ export async function loadCustomBlobUrl( // so the overlay just sees a normal blob URL. if (kind === 'bundle' && mimeType !== 'image/svg+xml') { // Why: when the manifest already provides a valid sprite layout, the - // renderer reads the `sprite` branch of useSidekickUrl and never touches + // renderer reads the `sprite` branch of usePetUrl and never touches // detectedSpriteCache — so skipping detection (and the per-frame // ImageBitmap allocations) avoids a per-bundle memory leak. const processed = await processBundleSheet(url, spriteFps, hasManifestSprite === true) @@ -167,10 +167,10 @@ function loadImage(url: string): Promise { }) } -// Why: the store invokes this on removeCustomSidekick so the underlying Blob +// Why: the store invokes this on removeCustomPet so the underlying Blob // is released; otherwise the blob: URL keeps it alive for the rest of the // session, wasting memory per imported image. -export function revokeCustomSidekickBlobUrl(id: string): void { +export function revokeCustomPetBlobUrl(id: string): void { const url = blobUrlCache.get(id) if (url) { URL.revokeObjectURL(url) diff --git a/src/renderer/src/components/pet/pet-models.ts b/src/renderer/src/components/pet/pet-models.ts new file mode 100644 index 000000000..28cc16f3f --- /dev/null +++ b/src/renderer/src/components/pet/pet-models.ts @@ -0,0 +1,46 @@ +import claudeUrl from '../../../../../resources/claude.webp?url' +import opencodeUrl from '../../../../../resources/opencode.webp?url' +import gremlinUrl from '../../../../../resources/gremlin.webp?url' + +// Why: bundled defaults so the overlay always has something to render when the +// user hasn't uploaded a custom image. Vite's `?url` import hashes each asset +// at build time so they participate in the normal caching pipeline. +export const DEFAULT_PET_ID = 'claude-the-mage' +export const OPENCODE_PET_ID = 'opencode-the-rogue' +export const GREMLIN_PET_ID = 'gremlin-the-trickster' + +export type BundledPetId = typeof DEFAULT_PET_ID | typeof OPENCODE_PET_ID | typeof GREMLIN_PET_ID + +export type BundledPet = { + id: BundledPetId + label: string + url: string +} + +export const BUNDLED_PETS: readonly BundledPet[] = [ + { + id: DEFAULT_PET_ID, + label: 'Claudino', + url: claudeUrl + }, + { + id: OPENCODE_PET_ID, + label: 'OpenCode', + url: opencodeUrl + }, + { + id: GREMLIN_PET_ID, + label: 'Gremlin', + url: gremlinUrl + } +] as const + +export const BUNDLED_PET: BundledPet = BUNDLED_PETS[0] + +export function isBundledPetId(id: string | undefined): boolean { + return BUNDLED_PETS.some((s) => s.id === id) +} + +export function findBundledPet(id: string | undefined): BundledPet | undefined { + return BUNDLED_PETS.find((s) => s.id === id) +} diff --git a/src/renderer/src/components/sidekick/sprite-frame-detection.ts b/src/renderer/src/components/pet/sprite-frame-detection.ts similarity index 97% rename from src/renderer/src/components/sidekick/sprite-frame-detection.ts rename to src/renderer/src/components/pet/sprite-frame-detection.ts index 45a73fa04..d622634ea 100644 --- a/src/renderer/src/components/sidekick/sprite-frame-detection.ts +++ b/src/renderer/src/components/pet/sprite-frame-detection.ts @@ -1,6 +1,6 @@ // Why: pet bundles often ship a sprite sheet without manifest frame data, so // we can't grid-step it. The sheets we see in the wild leave magenta (chroma -// keyed in sidekick-blob-cache) or transparent gutters between sprites. +// keyed in pet-blob-cache) or transparent gutters between sprites. // After keying, find connected non-empty rows → bands; within the best band, // split on empty columns to get one frame per sprite. The result drives the // canvas-based animation in the overlay. diff --git a/src/renderer/src/components/sidekick/useSidekickUrl.ts b/src/renderer/src/components/pet/usePetUrl.ts similarity index 75% rename from src/renderer/src/components/sidekick/useSidekickUrl.ts rename to src/renderer/src/components/pet/usePetUrl.ts index 3bec626a7..f61f2d484 100644 --- a/src/renderer/src/components/sidekick/useSidekickUrl.ts +++ b/src/renderer/src/components/pet/usePetUrl.ts @@ -1,45 +1,45 @@ import { useEffect, useRef, useState } from 'react' -import type { CustomSidekick } from '../../../../shared/types' +import type { CustomPet } from '../../../../shared/types' import { useAppStore } from '../../store' -import { BUNDLED_SIDEKICK, findBundledSidekick, isBundledSidekickId } from './sidekick-models' +import { BUNDLED_PET, findBundledPet, isBundledPetId } from './pet-models' import { blobUrlCache, detectedSpriteCache, loadCustomBlobUrl, type DetectedSpriteCacheEntry -} from './sidekick-blob-cache' +} from './pet-blob-cache' // Re-export so existing callers (the store slice) that point at this module // keep working without knowing about the cache module split. -export { revokeCustomSidekickBlobUrl } from './sidekick-blob-cache' +export { revokeCustomPetBlobUrl } from './pet-blob-cache' -export type ResolvedSidekick = +export type ResolvedPet = | { url: string; ready: boolean; sprite: null; detected: null } | { url: string ready: boolean - sprite: NonNullable + sprite: NonNullable detected: null } | { url: string; ready: boolean; sprite: null; detected: DetectedSpriteCacheEntry } -/** Resolve the active sidekick to a URL the overlay can render. +/** Resolve the active pet to a URL the overlay can render. * - * For bundled sidekicks this is synchronous. For custom ones we issue an + * For bundled pets this is synchronous. For custom ones we issue an * IPC read and build a blob: URL with the correct MIME; until that resolves, * we fall back to the bundled default so the overlay is never empty. */ -export function useSidekickUrl(): ResolvedSidekick { - const sidekickId = useAppStore((s) => s.sidekickId) - const customSidekicks = useAppStore((s) => s.customSidekicks) - const bundled = isBundledSidekickId(sidekickId) - const customMeta = bundled ? null : customSidekicks.find((m) => m.id === sidekickId) +export function usePetUrl(): ResolvedPet { + const petId = useAppStore((s) => s.petId) + const customPets = useAppStore((s) => s.customPets) + const bundled = isBundledPetId(petId) + const customMeta = bundled ? null : customPets.find((m) => m.id === petId) const [customUrl, setCustomUrl] = useState(() => customMeta ? (blobUrlCache.get(customMeta.id) ?? null) : null ) // Why: track the last id we started loading so a rapid switch between - // custom sidekicks doesn't let a slower earlier response clobber the newer + // custom pets doesn't let a slower earlier response clobber the newer // state. const pendingRef = useRef(null) @@ -92,8 +92,8 @@ export function useSidekickUrl(): ResolvedSidekick { }, [customId, customFileName, customMime, customKind, customSpriteFps, customHasManifestSprite]) if (bundled) { - const sidekick = findBundledSidekick(sidekickId) ?? BUNDLED_SIDEKICK - return { url: sidekick.url, ready: true, sprite: null, detected: null } + const pet = findBundledPet(petId) ?? BUNDLED_PET + return { url: pet.url, ready: true, sprite: null, detected: null } } if (customMeta && customUrl) { // Why: guard against manifest entries with zero/negative dims or fps — @@ -112,5 +112,5 @@ export function useSidekickUrl(): ResolvedSidekick { } return { url: customUrl, ready: true, sprite: null, detected: null } } - return { url: BUNDLED_SIDEKICK.url, ready: false, sprite: null, detected: null } + return { url: BUNDLED_PET.url, ready: false, sprite: null, detected: null } } diff --git a/src/renderer/src/components/settings/ExperimentalPane.tsx b/src/renderer/src/components/settings/ExperimentalPane.tsx index 093e314ef..5b0655e9a 100644 --- a/src/renderer/src/components/settings/ExperimentalPane.tsx +++ b/src/renderer/src/components/settings/ExperimentalPane.tsx @@ -32,7 +32,7 @@ export function ExperimentalPane({ }: ExperimentalPaneProps): React.JSX.Element { const searchQuery = useAppStore((s) => s.settingsSearchQuery) const showMobile = matchesSettingsSearch(searchQuery, [EXPERIMENTAL_SEARCH_ENTRY.mobile]) - const showSidekick = matchesSettingsSearch(searchQuery, [EXPERIMENTAL_SEARCH_ENTRY.sidekick]) + const showPet = matchesSettingsSearch(searchQuery, [EXPERIMENTAL_SEARCH_ENTRY.pet]) const showOrchestration = matchesSettingsSearch(searchQuery, [ EXPERIMENTAL_SEARCH_ENTRY.orchestration ]) @@ -129,38 +129,38 @@ export function ExperimentalPane({ ) : null} - {showSidekick ? ( + {showPet ? (
- +

- Shows a small animated sidekick pinned to the bottom-right corner. Pick a character + Shows a small animated pet pinned to the bottom-right corner. Pick a character (Claudino, OpenCode, Gremlin) or upload your own PNG, APNG, GIF, WebP, JPG, or SVG - from the status-bar sidekick menu. Hide it any time from the same menu without - disabling this setting. + from the status-bar pet menu. Hide it any time from the same menu without disabling + this setting.

diff --git a/src/renderer/src/components/settings/experimental-search.ts b/src/renderer/src/components/settings/experimental-search.ts index d27cadac3..b6f6b5205 100644 --- a/src/renderer/src/components/settings/experimental-search.ts +++ b/src/renderer/src/components/settings/experimental-search.ts @@ -19,12 +19,12 @@ export const EXPERIMENTAL_PANE_SEARCH_ENTRIES: SettingsSearchEntry[] = [ ] }, { - title: 'Sidekick', - description: 'Floating animated sidekick in the bottom-right corner.', + title: 'Pet', + description: 'Floating animated pet in the bottom-right corner.', keywords: [ 'experimental', - 'sidekick', 'pet', + 'sidekick', 'mascot', 'overlay', 'animated', @@ -82,7 +82,7 @@ function findEntry(title: string): SettingsSearchEntry { export const EXPERIMENTAL_SEARCH_ENTRY = { mobile: findEntry('Mobile Pairing'), - sidekick: findEntry('Sidekick'), + pet: findEntry('Pet'), orchestration: findEntry('Agent Orchestration'), symlinks: findEntry('Symlinks on worktrees') } as const diff --git a/src/renderer/src/components/sidekick/sidekick-models.ts b/src/renderer/src/components/sidekick/sidekick-models.ts deleted file mode 100644 index 5234b88ba..000000000 --- a/src/renderer/src/components/sidekick/sidekick-models.ts +++ /dev/null @@ -1,49 +0,0 @@ -import claudeUrl from '../../../../../resources/claude.webp?url' -import opencodeUrl from '../../../../../resources/opencode.webp?url' -import gremlinUrl from '../../../../../resources/gremlin.webp?url' - -// Why: bundled defaults so the overlay always has something to render when the -// user hasn't uploaded a custom image. Vite's `?url` import hashes each asset -// at build time so they participate in the normal caching pipeline. -export const DEFAULT_SIDEKICK_ID = 'claude-the-mage' -export const OPENCODE_SIDEKICK_ID = 'opencode-the-rogue' -export const GREMLIN_SIDEKICK_ID = 'gremlin-the-trickster' - -export type BundledSidekickId = - | typeof DEFAULT_SIDEKICK_ID - | typeof OPENCODE_SIDEKICK_ID - | typeof GREMLIN_SIDEKICK_ID - -export type BundledSidekick = { - id: BundledSidekickId - label: string - url: string -} - -export const BUNDLED_SIDEKICKS: readonly BundledSidekick[] = [ - { - id: DEFAULT_SIDEKICK_ID, - label: 'Claudino', - url: claudeUrl - }, - { - id: OPENCODE_SIDEKICK_ID, - label: 'OpenCode', - url: opencodeUrl - }, - { - id: GREMLIN_SIDEKICK_ID, - label: 'Gremlin', - url: gremlinUrl - } -] as const - -export const BUNDLED_SIDEKICK: BundledSidekick = BUNDLED_SIDEKICKS[0] - -export function isBundledSidekickId(id: string | undefined): boolean { - return BUNDLED_SIDEKICKS.some((s) => s.id === id) -} - -export function findBundledSidekick(id: string | undefined): BundledSidekick | undefined { - return BUNDLED_SIDEKICKS.find((s) => s.id === id) -} diff --git a/src/renderer/src/components/status-bar/SidekickStatusSegment.tsx b/src/renderer/src/components/status-bar/PetStatusSegment.tsx similarity index 62% rename from src/renderer/src/components/status-bar/SidekickStatusSegment.tsx rename to src/renderer/src/components/status-bar/PetStatusSegment.tsx index 692533ce4..29682dd61 100644 --- a/src/renderer/src/components/status-bar/SidekickStatusSegment.tsx +++ b/src/renderer/src/components/status-bar/PetStatusSegment.tsx @@ -14,79 +14,74 @@ import { DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { useAppStore } from '../../store' -import { - BUNDLED_SIDEKICK, - BUNDLED_SIDEKICKS, - findBundledSidekick, - isBundledSidekickId -} from '../sidekick/sidekick-models' -import { SIDEKICK_SIZE_MAX, SIDEKICK_SIZE_MIN } from '../../../../shared/types' +import { BUNDLED_PET, BUNDLED_PETS, findBundledPet, isBundledPetId } from '../pet/pet-models' +import { PET_SIZE_MAX, PET_SIZE_MIN } from '../../../../shared/types' -// Why: cluster sidekick-related controls (show/hide, character picker, custom +// Why: cluster pet-related controls (show/hide, character picker, custom // upload + removal, jump-to-settings) behind a single status-bar segment. Only -// rendered when experimentalSidekick is on (gated by the caller). Sidekick +// rendered when experimentalPet is on (gated by the caller). Pet // visibility is independently tracked so users can dismiss without having to // find the experimental flag again. -function SidekickStatusSegmentInner(): React.JSX.Element { - const sidekickVisible = useAppStore((s) => s.sidekickVisible) - const setSidekickVisible = useAppStore((s) => s.setSidekickVisible) - const sidekickId = useAppStore((s) => s.sidekickId) - const setSidekickId = useAppStore((s) => s.setSidekickId) - const customSidekicks = useAppStore((s) => s.customSidekicks) - const addCustomSidekick = useAppStore((s) => s.addCustomSidekick) - const removeCustomSidekick = useAppStore((s) => s.removeCustomSidekick) - const sidekickSize = useAppStore((s) => s.sidekickSize) - const setSidekickSize = useAppStore((s) => s.setSidekickSize) +function PetStatusSegmentInner(): React.JSX.Element { + const petVisible = useAppStore((s) => s.petVisible) + const setPetVisible = useAppStore((s) => s.setPetVisible) + const petId = useAppStore((s) => s.petId) + const setPetId = useAppStore((s) => s.setPetId) + const customPets = useAppStore((s) => s.customPets) + const addCustomPet = useAppStore((s) => s.addCustomPet) + const removeCustomPet = useAppStore((s) => s.removeCustomPet) + const petSize = useAppStore((s) => s.petSize) + const setPetSize = useAppStore((s) => s.setPetSize) const openSettingsPage = useAppStore((s) => s.openSettingsPage) const openSettingsTarget = useAppStore((s) => s.openSettingsTarget) - const bundled = isBundledSidekickId(sidekickId) - const activeBundled = bundled ? (findBundledSidekick(sidekickId) ?? BUNDLED_SIDEKICK) : null - const activeCustom = bundled ? null : customSidekicks.find((m) => m.id === sidekickId) - const activeLabel = activeBundled ? activeBundled.label : (activeCustom?.label ?? 'Sidekick') - const label = sidekickVisible ? activeLabel : `${activeLabel} hidden` + const bundled = isBundledPetId(petId) + const activeBundled = bundled ? (findBundledPet(petId) ?? BUNDLED_PET) : null + const activeCustom = bundled ? null : customPets.find((m) => m.id === petId) + const activeLabel = activeBundled ? activeBundled.label : (activeCustom?.label ?? 'Pet') + const label = petVisible ? activeLabel : `${activeLabel} hidden` const handleImport = async (): Promise => { - console.log('[sidekick-overlay] upload: click') - if (!window.api?.sidekick?.import) { - console.warn('[sidekick-overlay] upload: window.api.sidekick.import missing — restart Orca') - toast.error('Custom sidekick upload needs a full app restart (not just reload).') + console.log('[pet-overlay] upload: click') + if (!window.api?.pet?.import) { + console.warn('[pet-overlay] upload: window.api.pet.import missing — restart Orca') + toast.error('Custom pet upload needs a full app restart (not just reload).') return } try { - const model = await window.api.sidekick.import() - console.log('[sidekick-overlay] upload: result', model) + const model = await window.api.pet.import() + console.log('[pet-overlay] upload: result', model) if (!model) { return } - addCustomSidekick(model) - if (!sidekickVisible) { - setSidekickVisible(true) + addCustomPet(model) + if (!petVisible) { + setPetVisible(true) } - setSidekickId(model.id) + setPetId(model.id) } catch (error) { - console.error('[sidekick-overlay] upload: error', error) + console.error('[pet-overlay] upload: error', error) toast.error(error instanceof Error ? error.message : 'Failed to import file') } } const handleImportPetBundle = async (): Promise => { - if (!window.api?.sidekick?.importPetBundle) { + if (!window.api?.pet?.importPetBundle) { toast.error('Pet bundle import needs a full app restart (not just reload).') return } try { - const model = await window.api.sidekick.importPetBundle() + const model = await window.api.pet.importPetBundle() if (!model) { return } - addCustomSidekick(model) - if (!sidekickVisible) { - setSidekickVisible(true) + addCustomPet(model) + if (!petVisible) { + setPetVisible(true) } - setSidekickId(model.id) + setPetId(model.id) } catch (error) { - console.error('[sidekick-overlay] pet bundle: error', error) + console.error('[pet-overlay] pet bundle: error', error) toast.error(error instanceof Error ? error.message : 'Failed to import pet bundle') } } @@ -97,24 +92,24 @@ function SidekickStatusSegmentInner(): React.JSX.Element { - Sidekick + Pet { event.preventDefault() - setSidekickVisible(!sidekickVisible) + setPetVisible(!petVisible) }} > - {sidekickVisible ? 'Hide sidekick' : 'Show sidekick'} + {petVisible ? 'Hide pet' : 'Show pet'} {/* Why: in-menu range so users can resize the overlay without leaving the dropdown — pet sprites can import larger than the default 180px @@ -128,58 +123,58 @@ function SidekickStatusSegmentInner(): React.JSX.Element { >
Size - {sidekickSize}px + {petSize}px
setSidekickSize(Number(e.target.value))} + value={petSize} + onChange={(e) => setPetSize(Number(e.target.value))} className="w-full" - aria-label="Sidekick size" + aria-label="Pet size" />
- Choose sidekick + Choose pet {/* Why: portal so the submenu escapes the parent Content's overflow clipping — without this, the submenu opens inside the scroll container and gets clipped. Matches the convention used in BrowserToolbarMenu/BrowserProfileRow. */} - {BUNDLED_SIDEKICKS.map((sidekick) => { - const selected = sidekick.id === sidekickId + {BUNDLED_PETS.map((pet) => { + const selected = pet.id === petId return ( { - if (!sidekickVisible) { - setSidekickVisible(true) + if (!petVisible) { + setPetVisible(true) } - setSidekickId(sidekick.id) + setPetId(pet.id) }} > {selected ? : null} - {sidekick.label} + {pet.label} ) })} - {customSidekicks.length > 0 ? : null} - {customSidekicks.map((model) => { - const selected = model.id === sidekickId + {customPets.length > 0 ? : null} + {customPets.map((model) => { + const selected = model.id === petId return ( { - if (!sidekickVisible) { - setSidekickVisible(true) + if (!petVisible) { + setPetVisible(true) } - setSidekickId(model.id) + setPetId(model.id) }} > @@ -193,7 +188,7 @@ function SidekickStatusSegmentInner(): React.JSX.Element { onClick={(event) => { event.stopPropagation() event.preventDefault() - removeCustomSidekick(model.id) + removeCustomPet(model.id) }} > @@ -231,16 +226,16 @@ function SidekickStatusSegmentInner(): React.JSX.Element { openSettingsTarget({ pane: 'experimental', repoId: null, - sectionId: 'experimental-sidekick' + sectionId: 'experimental-pet' }) openSettingsPage() }} > - Sidekick settings… + Pet settings… ) } -export const SidekickStatusSegment = React.memo(SidekickStatusSegmentInner) +export const PetStatusSegment = React.memo(PetStatusSegmentInner) diff --git a/src/renderer/src/components/status-bar/StatusBar.tsx b/src/renderer/src/components/status-bar/StatusBar.tsx index 609473a86..ff8032ec2 100644 --- a/src/renderer/src/components/status-bar/StatusBar.tsx +++ b/src/renderer/src/components/status-bar/StatusBar.tsx @@ -26,7 +26,7 @@ import { markLiveCodexSessionsForRestart } from '@/lib/codex-session-restart' import { SshStatusSegment } from './SshStatusSegment' import { UpdateStatusSegment } from './UpdateStatusSegment' import { ResourceUsageStatusSegment } from './ResourceUsageStatusSegment' -import { SidekickStatusSegment } from './SidekickStatusSegment' +import { PetStatusSegment } from './PetStatusSegment' function getCodexAccountLabel( state: CodexRateLimitAccountsState, @@ -697,11 +697,11 @@ function StatusBarInner(): React.JSX.Element | null { const refreshRateLimits = useAppStore((s) => s.refreshRateLimits) const statusBarVisible = useAppStore((s) => s.statusBarVisible) const statusBarItems = useAppStore((s) => s.statusBarItems) - // Why: sidekick segment intentionally does NOT participate in statusBarItems + // Why: pet segment intentionally does NOT participate in statusBarItems // (see design doc — gating with both the experimental flag and a // statusBarItems checkbox would double-toggle the surface). It is driven - // purely by the experimentalSidekick settings flag. - const sidekickEnabled = useAppStore((s) => s.settings?.experimentalSidekick === true) + // purely by the experimentalPet settings flag. + const petEnabled = useAppStore((s) => s.settings?.experimentalPet === true) const toggleStatusBarItem = useAppStore((s) => s.toggleStatusBarItem) const containerRef = useRef(null) const [isRefreshing, setIsRefreshing] = useState(false) @@ -839,7 +839,7 @@ function StatusBarInner(): React.JSX.Element | null {
- {sidekickEnabled && } + {petEnabled && } {showResourceUsage && } {showSsh && }
diff --git a/src/renderer/src/store/slices/ui.test.ts b/src/renderer/src/store/slices/ui.test.ts index 3b2d9fcbe..cdd786024 100644 --- a/src/renderer/src/store/slices/ui.test.ts +++ b/src/renderer/src/store/slices/ui.test.ts @@ -139,6 +139,44 @@ describe('createUISlice hydratePersistedUI', () => { expect(store.getState().browserKagiSessionLink).toBeNull() }) + it('hydrates legacy sidekick persisted keys into pet state', () => { + const store = createUIStore() + + store.getState().hydratePersistedUI( + makePersistedUI({ + petVisible: undefined, + petId: undefined, + petSize: undefined, + customPets: undefined, + sidekickVisible: false, + sidekickId: 'custom-pet', + sidekickSize: 240, + customSidekicks: [ + { + id: 'custom-pet', + label: 'Legacy pet', + fileName: 'custom-pet.webp', + mimeType: 'image/webp', + kind: 'image' + } + ] + }) + ) + + expect(store.getState().petVisible).toBe(false) + expect(store.getState().petId).toBe('custom-pet') + expect(store.getState().petSize).toBe(240) + expect(store.getState().customPets).toEqual([ + { + id: 'custom-pet', + label: 'Legacy pet', + fileName: 'custom-pet.webp', + mimeType: 'image/webp', + kind: 'image' + } + ]) + }) + it('sanitizes task resume state field-by-field during hydration', () => { const store = createUIStore() diff --git a/src/renderer/src/store/slices/ui.ts b/src/renderer/src/store/slices/ui.ts index 76c578498..27511703f 100644 --- a/src/renderer/src/store/slices/ui.ts +++ b/src/renderer/src/store/slices/ui.ts @@ -4,7 +4,7 @@ import type { AppState } from '../types' import { findPrevLiveWorktreeHistoryIndex } from './worktree-nav-history' import type { ChangelogData, - CustomSidekick, + CustomPet, PersistedTrustedOrcaHooks, PersistedUIState, StatusBarItem, @@ -14,11 +14,7 @@ import type { UpdateStatus, WorktreeCardProperty } from '../../../../shared/types' -import { - SIDEKICK_SIZE_DEFAULT, - SIDEKICK_SIZE_MAX, - SIDEKICK_SIZE_MIN -} from '../../../../shared/types' +import { PET_SIZE_DEFAULT, PET_SIZE_MAX, PET_SIZE_MIN } from '../../../../shared/types' import { PER_REPO_FETCH_LIMIT } from '../../../../shared/work-items' import { DEFAULT_STATUS_BAR_ITEMS, @@ -26,15 +22,15 @@ import { } from '../../../../shared/constants' import { normalizeKagiSessionLink } from '../../../../shared/browser-url' import type { OrcaHookScriptKind } from '../../lib/orca-hook-trust' -import { DEFAULT_SIDEKICK_ID, isBundledSidekickId } from '../../components/sidekick/sidekick-models' -import { revokeCustomSidekickBlobUrl } from '../../components/sidekick/sidekick-blob-cache' +import { DEFAULT_PET_ID, isBundledPetId } from '../../components/pet/pet-models' +import { revokeCustomPetBlobUrl } from '../../components/pet/pet-blob-cache' import { isGitRepoKind } from '../../../../shared/repo-kind' -function clampSidekickSize(size: number): number { +function clampPetSize(size: number): number { if (!Number.isFinite(size)) { - return SIDEKICK_SIZE_DEFAULT + return PET_SIZE_DEFAULT } - return Math.max(SIDEKICK_SIZE_MIN, Math.min(SIDEKICK_SIZE_MAX, Math.round(size))) + return Math.max(PET_SIZE_MIN, Math.min(PET_SIZE_MAX, Math.round(size))) } // Why: mirrors the preset→query mapping used by TaskPage's preset buttons. @@ -264,25 +260,25 @@ export type UISlice = { toggleStatusBarItem: (item: StatusBarItem) => void statusBarVisible: boolean setStatusBarVisible: (v: boolean) => void - /** Whether the experimental sidekick overlay is currently visible. Persisted - * so "Hide sidekick" from the status-bar menu survives reload. Independent - * of the experimentalSidekick settings flag — the feature flag gates + /** Whether the experimental pet overlay is currently visible. Persisted + * so "Hide pet" from the status-bar menu survives reload. Independent + * of the experimentalPet settings flag — the feature flag gates * whether the overlay can ever render; this controls whether it does now. */ - sidekickVisible: boolean - setSidekickVisible: (v: boolean) => void - /** Which sidekick is active — either a bundled id or a custom UUID. - * Persisted alongside sidekickVisible via the PersistedUIState pipeline. */ - sidekickId: string - setSidekickId: (id: string) => void - /** User-uploaded sidekick images. Metadata only — bytes live in main's userData. */ - customSidekicks: CustomSidekick[] - addCustomSidekick: (model: CustomSidekick) => void - removeCustomSidekick: (id: string) => void - /** Sidekick overlay size in CSS pixels (square). User-adjustable from the + petVisible: boolean + setPetVisible: (v: boolean) => void + /** Which pet is active — either a bundled id or a custom UUID. + * Persisted alongside petVisible via the PersistedUIState pipeline. */ + petId: string + setPetId: (id: string) => void + /** User-uploaded pet images. Metadata only — bytes live in main's userData. */ + customPets: CustomPet[] + addCustomPet: (model: CustomPet) => void + removeCustomPet: (id: string) => void + /** Pet overlay size in CSS pixels (square). User-adjustable from the * status-bar menu so a too-big imported sprite isn't a stuck-on-screen * problem. */ - sidekickSize: number - setSidekickSize: (size: number) => void + petSize: number + setPetSize: (size: number) => void pendingRevealWorktreeId: string | null revealWorktreeInSidebar: (worktreeId: string) => void clearPendingRevealWorktreeId: () => void @@ -594,65 +590,65 @@ export const createUISlice: StateCreator = (set, get) set({ statusBarVisible: v }) }, - // Why: default true so a user who enables experimentalSidekick sees the - // sidekick immediately. Hide sidekick from the status-bar menu flips this + // Why: default true so a user who enables experimentalPet sees the + // pet immediately. Hide pet from the status-bar menu flips this // to false; the value is persisted via the standard PersistedUIState pipeline. - sidekickVisible: true, - setSidekickVisible: (v) => { - window.api.ui.set({ sidekickVisible: v }).catch(console.error) - set({ sidekickVisible: v }) + petVisible: true, + setPetVisible: (v) => { + window.api.ui.set({ petVisible: v }).catch(console.error) + set({ petVisible: v }) }, - sidekickId: DEFAULT_SIDEKICK_ID, - setSidekickId: (id) => { - window.api.ui.set({ sidekickId: id }).catch(console.error) - set({ sidekickId: id }) + petId: DEFAULT_PET_ID, + setPetId: (id) => { + window.api.ui.set({ petId: id }).catch(console.error) + set({ petId: id }) }, - sidekickSize: SIDEKICK_SIZE_DEFAULT, - setSidekickSize: (size) => { - const clamped = clampSidekickSize(size) - window.api.ui.set({ sidekickSize: clamped }).catch(console.error) - set({ sidekickSize: clamped }) + petSize: PET_SIZE_DEFAULT, + setPetSize: (size) => { + const clamped = clampPetSize(size) + window.api.ui.set({ petSize: clamped }).catch(console.error) + set({ petSize: clamped }) }, - customSidekicks: [], - addCustomSidekick: (model) => + customPets: [], + addCustomPet: (model) => set((s) => { - const next = [...s.customSidekicks.filter((m) => m.id !== model.id), model] - window.api.ui.set({ customSidekicks: next }).catch(console.error) - return { customSidekicks: next } + const next = [...s.customPets.filter((m) => m.id !== model.id), model] + window.api.ui.set({ customPets: next }).catch(console.error) + return { customPets: next } }), - removeCustomSidekick: (id) => + removeCustomPet: (id) => set((s) => { - const target = s.customSidekicks.find((m) => m.id === id) + const target = s.customPets.find((m) => m.id === id) if (!target) { return s } - const next = s.customSidekicks.filter((m) => m.id !== id) - // Why: if the user removes the currently-active custom sidekick, fall + const next = s.customPets.filter((m) => m.id !== id) + // Why: if the user removes the currently-active custom pet, fall // back to the bundled default so the overlay doesn't render nothing. - const fallback = s.sidekickId === id ? DEFAULT_SIDEKICK_ID : s.sidekickId - // Why: send a single combined IPC update so customSidekicks and - // sidekickId persist atomically when both change. - const ipcPayload: { customSidekicks: CustomSidekick[]; sidekickId?: string } = { - customSidekicks: next + const fallback = s.petId === id ? DEFAULT_PET_ID : s.petId + // Why: send a single combined IPC update so customPets and + // petId persist atomically when both change. + const ipcPayload: { customPets: CustomPet[]; petId?: string } = { + customPets: next } - if (fallback !== s.sidekickId) { - ipcPayload.sidekickId = fallback + if (fallback !== s.petId) { + ipcPayload.petId = fallback } window.api.ui.set(ipcPayload).catch(console.error) // Why: revoke the cached blob: URL so the underlying Blob is released; // otherwise it stays in memory for the rest of the session. - revokeCustomSidekickBlobUrl(id) + revokeCustomPetBlobUrl(id) // Why: best-effort — the bytes are owned by main. If the disk delete // fails, the orphaned image stays in userData; each import uses a fresh // UUID so the file won't be hit again, and the renderer's metadata // index no longer references it. - window.api.sidekick.delete(id, target.fileName, target.kind).catch(console.error) - const partial: Partial = { customSidekicks: next } - if (fallback !== s.sidekickId) { - partial.sidekickId = fallback + window.api.pet.delete(id, target.fileName, target.kind).catch(console.error) + const partial: Partial = { customPets: next } + if (fallback !== s.petId) { + partial.petId = fallback } return partial }), @@ -671,6 +667,14 @@ export const createUISlice: StateCreator = (set, get) hydratePersistedUI: (ui) => set((s) => { const validRepoIds = new Set(s.repos.map((repo) => repo.id)) + // Why: persisted UI from pre-rename builds used sidekick* keys. Read + // those only as fallbacks so new pet* writes win immediately after upgrade. + const customPets = Array.isArray(ui.customPets) + ? ui.customPets + : Array.isArray(ui.customSidekicks) + ? ui.customSidekicks + : [] + const petId = ui.petId ?? ui.sidekickId // Migration history: // v1: sort was called 'smart' internally // v2: renamed 'smart' → 'recent' (same weighted-score behavior) @@ -710,28 +714,27 @@ export const createUISlice: StateCreator = (set, get) worktreeCardProperties: ui.worktreeCardProperties ?? [...DEFAULT_WORKTREE_CARD_PROPERTIES], statusBarItems: migrateStatusBarItems(ui.statusBarItems), statusBarVisible: ui.statusBarVisible ?? true, - // Why: absent → true so existing users see the sidekick the first time - // they enable the experimental flag. Only an explicit Hide sidekick + // Why: absent → true so existing users see the pet the first time + // they enable the experimental flag. Only an explicit Hide pet // dismissal persists a `false` value. - sidekickVisible: ui.sidekickVisible ?? true, - sidekickSize: clampSidekickSize(ui.sidekickSize ?? SIDEKICK_SIZE_DEFAULT), - customSidekicks: Array.isArray(ui.customSidekicks) ? ui.customSidekicks : [], - // Why: accept the persisted id if it matches a bundled sidekick or a + petVisible: ui.petVisible ?? ui.sidekickVisible ?? true, + petSize: clampPetSize(ui.petSize ?? ui.sidekickSize ?? PET_SIZE_DEFAULT), + customPets, + // Why: accept the persisted id if it matches a bundled pet or a // known custom one; otherwise fall back so the overlay never renders - // nothing (e.g. custom sidekick was removed by another session). - sidekickId: ((): string => { - const id = ui.sidekickId + // nothing (e.g. custom pet was removed by another session). + petId: ((): string => { + const id = petId if (typeof id !== 'string') { - return DEFAULT_SIDEKICK_ID + return DEFAULT_PET_ID } - if (isBundledSidekickId(id)) { + if (isBundledPetId(id)) { return id } - const custom = Array.isArray(ui.customSidekicks) ? ui.customSidekicks : [] - if (custom.some((m) => m.id === id)) { + if (customPets.some((m) => m.id === id)) { return id } - return DEFAULT_SIDEKICK_ID + return DEFAULT_PET_ID })(), dismissedUpdateVersion: ui.dismissedUpdateVersion ?? null, updateReassuranceSeen: ui.updateReassuranceSeen ?? false, diff --git a/src/shared/constants.ts b/src/shared/constants.ts index 4033fd1d0..f6b7e64b4 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -204,7 +204,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings { mobileAutoRestoreFitMs: null, // Why: off by default — opt-in cosmetic joke feature. Leaving the default // false keeps the overlay unmounted for users who never enable it. - experimentalSidekick: false, + experimentalPet: false, experimentalWorktreeSymlinks: false, // Why: hydrate an empty default so the renderer's optional-chained reads // (`settings?.githubProjects?.activeProject`) land on a stable shape diff --git a/src/shared/telemetry-events.ts b/src/shared/telemetry-events.ts index fcfadd7c5..75665e30d 100644 --- a/src/shared/telemetry-events.ts +++ b/src/shared/telemetry-events.ts @@ -158,7 +158,7 @@ export const SETTINGS_CHANGED_WHITELIST = [ 'editorAutoSave', 'openLinksInApp', 'experimentalMobile', - 'experimentalSidekick', + 'experimentalPet', 'experimentalWorktreeSymlinks', 'geminiCliOAuthEnabled' ] as const satisfies readonly BooleanGlobalSettingsKey[] diff --git a/src/shared/types.ts b/src/shared/types.ts index 1618b3d7a..602281f74 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1216,11 +1216,14 @@ export type GlobalSettings = { * on read into [5_000ms, 60min] to defend against bad config. * See docs/mobile-fit-hold.md. */ mobileAutoRestoreFitMs: number | null - /** Experimental: floating animated sidekick (claude.webp) in the bottom-right + /** Experimental: floating animated pet (claude.webp) in the bottom-right * corner. Opt-in because it's a cosmetic joke feature; users who leave it * off never mount the overlay. Toggling takes effect immediately in the * current session (no relaunch) because it is purely renderer-side. */ - experimentalSidekick: boolean + experimentalPet: boolean + /** Legacy persisted key from before the sidekick -> pet rename. Read only + * during migration; new writes use experimentalPet. */ + experimentalSidekick?: boolean /** Experimental: when creating a worktree, automatically symlink a * user-configured set of files/folders from the primary checkout (e.g. * `.env`, `node_modules`) into the new worktree. Opt-in while the @@ -1421,23 +1424,29 @@ export type PersistedUIState = { * suppress the nag — no further thresholds, no notifications. */ starNagCompleted?: boolean trustedOrcaHooks?: PersistedTrustedOrcaHooks - /** Whether the experimental sidekick overlay is currently visible. Separate - * from the experimentalSidekick settings flag so "Hide sidekick" from the + /** Whether the experimental pet overlay is currently visible. Separate + * from the experimentalPet settings flag so "Hide pet" from the * status-bar menu is a reversible dismiss (re-show without re-enabling the - * feature). Absent = treated as true so existing users see the sidekick + * feature). Absent = treated as true so existing users see the pet * the first time they enable the experimental flag. */ - sidekickVisible?: boolean - /** Active sidekick id: one of the bundled ids or a custom UUID from - * customSidekicks. Unknown ids fall back to the default at read time so - * removing a custom sidekick the user had selected doesn't leave the + petVisible?: boolean + /** Active pet id: one of the bundled ids or a custom UUID from + * customPets. Unknown ids fall back to the default at read time so + * removing a custom pet the user had selected doesn't leave the * overlay rendering nothing. */ + petId?: string + /** User-uploaded pet images. Bytes live under the legacy + * userData/sidekicks/custom/ folder; this field is the metadata index so + * custom pets ride the existing PersistedUIState save pipeline. */ + customPets?: CustomPet[] + /** On-screen size of the pet overlay in CSS pixels (square box). + * Clamped to [PET_SIZE_MIN, PET_SIZE_MAX] when read. */ + petSize?: number + /** Legacy persisted keys from before the sidekick -> pet rename. Read only + * during migration; new writes use the pet* names above. */ + sidekickVisible?: boolean sidekickId?: string - /** User-uploaded sidekick images. Bytes live under userData/sidekicks/custom/; - * this field is the metadata index so custom sidekicks ride the existing - * PersistedUIState save pipeline. */ - customSidekicks?: CustomSidekick[] - /** On-screen size of the sidekick overlay in CSS pixels (square box). - * Clamped to [SIDEKICK_SIZE_MIN, SIDEKICK_SIZE_MAX] when read. */ + customSidekicks?: CustomPet[] sidekickSize?: number /** Page-position state for Tasks. Source/repo/team/project selections keep * using their existing settings paths; this only restores transient tabs @@ -1445,15 +1454,15 @@ export type PersistedUIState = { taskResumeState?: TaskResumeState } -export const SIDEKICK_SIZE_MIN = 60 -export const SIDEKICK_SIZE_MAX = 360 -export const SIDEKICK_SIZE_DEFAULT = 180 +export const PET_SIZE_MIN = 60 +export const PET_SIZE_MAX = 360 +export const PET_SIZE_DEFAULT = 180 -/** Metadata for a user-uploaded sidekick image. `id` is the stable identifier; +/** Metadata for a user-uploaded pet image. `id` is the stable identifier; * the on-disk filename (preserving the original extension) lives in `fileName`. * The renderer never learns the absolute path — it asks main for the bytes - * via sidekick:read using (id, fileName). */ -export type CustomSidekick = { + * via pet:read using (id, fileName). */ +export type CustomPet = { id: string label: string fileName: string