fix: rename sidekick to pet (#1586)

This commit is contained in:
Jinjing
2026-05-08 13:04:09 -07:00
committed by GitHub
parent f5492c0043
commit 2dcff0687f
29 changed files with 678 additions and 382 deletions
@@ -97,7 +97,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
terminalMacOptionAsAltMigrated: true,
experimentalMobile: false,
mobileAutoRestoreFitMs: null,
experimentalSidekick: false,
experimentalPet: false,
experimentalWorktreeSymlinks: false,
terminalWindowsShell: 'powershell.exe',
terminalWindowsPowerShellImplementation: 'powershell.exe',
+1 -1
View File
@@ -91,7 +91,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
terminalMacOptionAsAltMigrated: true,
experimentalMobile: false,
mobileAutoRestoreFitMs: null,
experimentalSidekick: false,
experimentalPet: false,
experimentalWorktreeSymlinks: false,
terminalWindowsShell: 'powershell.exe',
terminalWindowsPowerShellImplementation: 'powershell.exe',
+108
View File
@@ -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()
})
})
+127
View File
@@ -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<string, SpriteAnimation>
}
export type ResolvedPetManifest<T extends PetManifestLike = PetManifestLike> = 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<string, SpriteAnimation> = {
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<T extends PetManifestLike>(
manifest: T
): ResolvedPetManifest<T> {
const shouldApplyCodexLayout =
isCodexPetSpritePath(manifest.spritesheetPath) &&
manifest.frame === undefined &&
manifest.animations === undefined
if (!shouldApplyCodexLayout) {
return {
...manifest,
spritesheetPath: manifest.spritesheetPath ?? CODEX_PET_SPRITESHEET_PATH
} as ResolvedPetManifest<T>
}
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
}
@@ -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 <img>, 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<string, string> = {
@@ -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/<id>/<fileName>. fileName is just the spritesheet
@@ -131,8 +126,8 @@ const PetManifestSchema = z
type PetManifest = z.infer<typeof PetManifestSchema> & 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<boolean> {
}
}
export function registerSidekickHandlers(): void {
ipcMain.handle('sidekick:import', async (event): Promise<CustomSidekick | null> => {
export function registerPetHandlers(): void {
ipcMain.handle('pet:import', async (event): Promise<CustomPet | null> => {
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<CustomSidekick | null> => {
ipcMain.handle('pet:importPetBundle', async (event): Promise<CustomPet | null> => {
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<CustomSidekick['sprite']> | undefined
let sprite: NonNullable<CustomPet['sprite']> | 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<ArrayBuffer | null> => {
// Why: validate IPC inputs before any path logic — renderer is not
// trusted to send strings of the right shape.
let parsed: z.infer<typeof SidekickFileRequestSchema>
let parsed: z.infer<typeof PetFileRequestSchema>
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<void> => {
// Why: validate IPC inputs before any path logic.
let parsed: z.infer<typeof SidekickFileRequestSchema>
let parsed: z.infer<typeof PetFileRequestSchema>
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)
}
}
)
+6 -6
View File
@@ -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)
+2 -2
View File
@@ -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)
+16
View File
@@ -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
+8
View File
@@ -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<typeof setTimeout> | 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: {
+4 -4
View File
@@ -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<string | null>
copyFile: (args: { srcPath: string; destPath: string }) => Promise<void>
}
sidekick: {
import: () => Promise<CustomSidekick | null>
importPetBundle: () => Promise<CustomSidekick | null>
pet: {
import: () => Promise<CustomPet | null>
importPetBundle: () => Promise<CustomPet | null>
read: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise<ArrayBuffer | null>
delete: (id: string, fileName: string, kind?: 'image' | 'bundle') => Promise<void>
}
+6 -7
View File
@@ -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<CustomSidekick | null> => ipcRenderer.invoke('sidekick:import'),
importPetBundle: (): Promise<CustomSidekick | null> =>
ipcRenderer.invoke('sidekick:importPetBundle'),
pet: {
import: (): Promise<CustomPet | null> => ipcRenderer.invoke('pet:import'),
importPetBundle: (): Promise<CustomPet | null> => ipcRenderer.invoke('pet:importPetBundle'),
read: (id: string, fileName: string, kind?: 'image' | 'bundle'): Promise<ArrayBuffer | null> =>
ipcRenderer.invoke('sidekick:read', id, fileName, kind),
ipcRenderer.invoke('pet:read', id, fileName, kind),
delete: (id: string, fileName: string, kind?: 'image' | 'bundle'): Promise<void> =>
ipcRenderer.invoke('sidekick:delete', id, fileName, kind)
ipcRenderer.invoke('pet:delete', id, fileName, kind)
},
browser: {
+18 -17
View File
@@ -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)
<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden>
<path
d="M2 0v2H0v8h8V8h2V0H2zm6 9H1V3h7v6zM9 7H8V2H3V1h6v6z"
fill="currentColor"
/>
<path d="M2 0v2H0v8h8V8h2V0H2zm6 9H1V3h7v6zM9 7H8V2H3V1h6v6z" fill="currentColor" />
</svg>
) : (
// Maximize icon (single square outline)
@@ -97,10 +101,7 @@ function WindowControls(): React.JSX.Element {
onClick={() => window.api.ui.requestClose()}
>
<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden>
<path
d="M1 0L0 1l4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4-1-1-4 4-4-4z"
fill="currentColor"
/>
<path d="M1 0L0 1l4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4-1-1-4 4-4-4z" fill="currentColor" />
</svg>
</button>
</div>
@@ -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<HTMLDivElement | null>(null)
@@ -1140,13 +1141,13 @@ function App(): React.JSX.Element {
{mountedLazyModalIds.has('quick-open') ? <QuickOpen /> : null}
{mountedLazyModalIds.has('worktree-palette') ? <WorktreeJumpPalette /> : null}
</Suspense>
{/* 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 ? (
<Suspense fallback={null}>
<SidekickOverlay />
<PetOverlay />
</Suspense>
) : null}
<UpdateCard />
@@ -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<CustomSidekick['sprite']>
type Sprite = NonNullable<CustomPet['sprite']>
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<Position>(() => {
// 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.
<div
aria-hidden
@@ -352,14 +352,14 @@ export function SidekickOverlay(): React.JSX.Element {
className="pointer-events-auto flex size-full select-none items-center justify-end"
style={{
cursor: dragging ? 'grabbing' : 'grab',
animation: 'sidekick-bob 1.2s ease-in-out infinite',
animation: 'pet-bob 1.2s ease-in-out infinite',
animationPlayState: animate ? 'running' : 'paused',
touchAction: 'none'
}}
>
<style>
{
'@keyframes sidekick-bob { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }'
'@keyframes pet-bob { 0%,100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }'
}
</style>
{sprite ? (
@@ -385,4 +385,4 @@ export function SidekickOverlay(): React.JSX.Element {
)
}
export default SidekickOverlay
export default PetOverlay
@@ -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<Parameters<typeof selectSidekickAnimationName>[0]> = {}
options: Partial<Parameters<typeof selectPetAnimationName>[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')
})
})
@@ -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'
}
@@ -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 <img> 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<HTMLImageElement> {
})
}
// 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)
@@ -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)
}
@@ -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.
@@ -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<CustomSidekick['sprite']>
sprite: NonNullable<CustomPet['sprite']>
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<string | null>(() =>
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<string | null>(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 }
}
@@ -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({
</SearchableSetting>
) : null}
{showSidekick ? (
{showPet ? (
<SearchableSetting
title="Sidekick"
description="Floating animated sidekick in the bottom-right corner."
keywords={EXPERIMENTAL_SEARCH_ENTRY.sidekick.keywords}
title="Pet"
description="Floating animated pet in the bottom-right corner."
keywords={EXPERIMENTAL_SEARCH_ENTRY.pet.keywords}
className="space-y-3 px-1 py-2"
id="experimental-sidekick"
id="experimental-pet"
>
<div className="flex items-start justify-between gap-4">
<div className="min-w-0 shrink space-y-1.5">
<Label>Sidekick</Label>
<Label>Pet</Label>
<p className="text-xs text-muted-foreground">
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.
</p>
</div>
<button
type="button"
role="switch"
aria-checked={settings.experimentalSidekick}
aria-checked={settings.experimentalPet}
onClick={() => {
updateSettings({ experimentalSidekick: !settings.experimentalSidekick })
updateSettings({ experimentalPet: !settings.experimentalPet })
}}
className={`relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors ${
settings.experimentalSidekick ? 'bg-foreground' : 'bg-muted-foreground/30'
settings.experimentalPet ? 'bg-foreground' : 'bg-muted-foreground/30'
}`}
>
<span
className={`inline-block h-3.5 w-3.5 transform rounded-full bg-background shadow-sm transition-transform ${
settings.experimentalSidekick ? 'translate-x-4' : 'translate-x-0.5'
settings.experimentalPet ? 'translate-x-4' : 'translate-x-0.5'
}`}
/>
</button>
@@ -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
@@ -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)
}
@@ -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<void> => {
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<void> => {
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 {
<button
type="button"
className="group inline-flex items-center cursor-pointer pl-1 pr-[6.5rem] py-0.5"
aria-label="Sidekick menu"
aria-label="Pet menu"
>
<span
className={`rounded px-1 py-0.5 text-[11px] font-medium text-muted-foreground group-hover:bg-accent/70 group-hover:text-foreground ${sidekickVisible ? '' : 'opacity-50'}`}
className={`rounded px-1 py-0.5 text-[11px] font-medium text-muted-foreground group-hover:bg-accent/70 group-hover:text-foreground ${petVisible ? '' : 'opacity-50'}`}
>
{label}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="end" sideOffset={8} className="min-w-[220px]">
<DropdownMenuLabel>Sidekick</DropdownMenuLabel>
<DropdownMenuLabel>Pet</DropdownMenuLabel>
<DropdownMenuItem
onSelect={(event) => {
event.preventDefault()
setSidekickVisible(!sidekickVisible)
setPetVisible(!petVisible)
}}
>
{sidekickVisible ? 'Hide sidekick' : 'Show sidekick'}
{petVisible ? 'Hide pet' : 'Show pet'}
</DropdownMenuItem>
{/* 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 {
>
<div className="mb-1 flex items-center justify-between text-[11px] text-muted-foreground">
<span>Size</span>
<span className="tabular-nums">{sidekickSize}px</span>
<span className="tabular-nums">{petSize}px</span>
</div>
<input
type="range"
min={SIDEKICK_SIZE_MIN}
max={SIDEKICK_SIZE_MAX}
min={PET_SIZE_MIN}
max={PET_SIZE_MAX}
step={10}
value={sidekickSize}
onChange={(e) => 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"
/>
</div>
<DropdownMenuSub>
<DropdownMenuSubTrigger>Choose sidekick</DropdownMenuSubTrigger>
<DropdownMenuSubTrigger>Choose pet</DropdownMenuSubTrigger>
{/* 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. */}
<DropdownMenuPortal>
<DropdownMenuSubContent className="min-w-[220px]">
{BUNDLED_SIDEKICKS.map((sidekick) => {
const selected = sidekick.id === sidekickId
{BUNDLED_PETS.map((pet) => {
const selected = pet.id === petId
return (
<DropdownMenuItem
key={sidekick.id}
key={pet.id}
onSelect={() => {
if (!sidekickVisible) {
setSidekickVisible(true)
if (!petVisible) {
setPetVisible(true)
}
setSidekickId(sidekick.id)
setPetId(pet.id)
}}
>
<span className="flex w-4 items-center justify-center">
{selected ? <Check className="size-3.5" aria-hidden /> : null}
</span>
{sidekick.label}
{pet.label}
</DropdownMenuItem>
)
})}
{customSidekicks.length > 0 ? <DropdownMenuSeparator /> : null}
{customSidekicks.map((model) => {
const selected = model.id === sidekickId
{customPets.length > 0 ? <DropdownMenuSeparator /> : null}
{customPets.map((model) => {
const selected = model.id === petId
return (
<DropdownMenuItem
key={model.id}
className="group"
onSelect={() => {
if (!sidekickVisible) {
setSidekickVisible(true)
if (!petVisible) {
setPetVisible(true)
}
setSidekickId(model.id)
setPetId(model.id)
}}
>
<span className="flex w-4 items-center justify-center">
@@ -193,7 +188,7 @@ function SidekickStatusSegmentInner(): React.JSX.Element {
onClick={(event) => {
event.stopPropagation()
event.preventDefault()
removeCustomSidekick(model.id)
removeCustomPet(model.id)
}}
>
<Trash2 className="size-3" aria-hidden />
@@ -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…
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)
}
export const SidekickStatusSegment = React.memo(SidekickStatusSegmentInner)
export const PetStatusSegment = React.memo(PetStatusSegmentInner)
@@ -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<HTMLDivElement>(null)
const [isRefreshing, setIsRefreshing] = useState(false)
@@ -839,7 +839,7 @@ function StatusBarInner(): React.JSX.Element | null {
<div className="flex items-center gap-3">
<UpdateStatusSegment compact={compact} iconOnly={iconOnly} />
{sidekickEnabled && <SidekickStatusSegment />}
{petEnabled && <PetStatusSegment />}
{showResourceUsage && <ResourceUsageStatusSegment compact={compact} iconOnly={iconOnly} />}
{showSsh && <SshStatusSegment compact={compact} iconOnly={iconOnly} />}
</div>
+38
View File
@@ -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()
+80 -77
View File
@@ -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<AppState, [], [], UISlice> = (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<UISlice> = { customSidekicks: next }
if (fallback !== s.sidekickId) {
partial.sidekickId = fallback
window.api.pet.delete(id, target.fileName, target.kind).catch(console.error)
const partial: Partial<UISlice> = { customPets: next }
if (fallback !== s.petId) {
partial.petId = fallback
}
return partial
}),
@@ -671,6 +667,14 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (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<AppState, [], [], UISlice> = (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,
+1 -1
View File
@@ -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
+1 -1
View File
@@ -158,7 +158,7 @@ export const SETTINGS_CHANGED_WHITELIST = [
'editorAutoSave',
'openLinksInApp',
'experimentalMobile',
'experimentalSidekick',
'experimentalPet',
'experimentalWorktreeSymlinks',
'geminiCliOAuthEnabled'
] as const satisfies readonly BooleanGlobalSettingsKey[]
+30 -21
View File
@@ -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