Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
Add Alook PET preview and settings
JeffreyDeng-spec1325588eda18
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3e409a0c6..d61e7e90f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -54,6 +54,7 @@ jobs:env:BETTER_AUTH_SECRET: ci-e2e-secretBETTER_AUTH_URL: http://localhost:3000+ APP_URL: http://localhost:3000steps:- uses: actions/checkout@v6- uses: pnpm/action-setup@v6@@ -69,7 +70,7 @@ jobs:- name: Start dev serversrun: |pnpm --filter @alook/email-worker dev &- pnpm --filter @alook/web dev &+ pnpm --filter @alook/web exec next dev &until curl -sf http://localhost:3000/api/health; do sleep 2; done- run: pnpm test:e2ediff --git a/LOCAL_DEV.md b/LOCAL_DEV.mdnew file mode 100644index 000000000..f411a51cb--- /dev/null+++ b/LOCAL_DEV.md@@ -0,0 +1,53 @@+# Alook Local Dev++Use one browser entry for local development: `http://127.0.0.1:3003`.++## Setup++```bash+pnpm install --frozen-lockfile++cp src/web/.dev.vars.example src/web/.dev.vars+WEB_SECRET="$(openssl rand -base64 32)"+ENC_KEY="$(openssl rand -base64 32)"+node - <<'NODE' "$WEB_SECRET" "$ENC_KEY"+const fs = require("fs")+const [secret, enc] = process.argv.slice(2)+let text = fs.readFileSync("src/web/.dev.vars", "utf8")+for (const [key, value] of Object.entries({+ BETTER_AUTH_SECRET: secret,+ BETTER_AUTH_URL: "http://127.0.0.1:3003",+ ENCRYPTION_KEY: enc,+})) {+ text = text.replace(new RegExp(`^${key}=.*$`, "m"), `${key}=${value}`)+}+fs.writeFileSync("src/web/.dev.vars", text)++let email = fs.readFileSync("src/email-worker/.dev.vars.example", "utf8")+email = email.replace(/^ENCRYPTION_KEY=.*$/m, `ENCRYPTION_KEY=${enc}`)+fs.writeFileSync("src/email-worker/.dev.vars", email)+NODE++pnpm db:migrate+pnpm db:seed:homepage-stubs+pnpm dev+```++`GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `GOOGLE_CLIENT_ID`, and `GOOGLE_CLIENT_SECRET` can stay empty; social login is unavailable until they are configured.++## Verification++Open `http://127.0.0.1:3003/sign-in`, enter `[email protected]`, and use the development email flow. In `next dev`, the app signs in or creates the user with the fixed internal dev password.++After login, `http://127.0.0.1:3003/workspaces?auto` creates a personal workspace from the email local-part when none exists. For `[email protected]`, the expected workspace slug is `d1183898546`.++`pnpm db:seed:homepage-stubs` adds 5 local-only agents, 2 local-only machines/runtimes, and one running stub task for Homepage/PET interaction testing. It is safe to rerun after the workspace exists.++Check:++```bash+curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/api/health+curl -sS -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3003/pet-preview+```++Both should return `200`.diff --git a/README.md b/README.mdindex 539c8cfeb..66cbc3947 100644--- a/README.md+++ b/README.md@@ -96,6 +96,9 @@ pnpm test # run all testspnpm typecheck # typecheck all packages```+Local browser entry is `http://127.0.0.1:3003`; keep `src/web/.dev.vars` `BETTER_AUTH_URL` exactly the same.+Use `pnpm dev` for daily development; `@alook/web` listens on `127.0.0.1:3003`.+### Individual services```bashdiff --git a/package.json b/package.jsonindex a40e3864b..58dfb66ab 100644--- a/package.json+++ b/package.json@@ -12,7 +12,7 @@"reinstall": "pnpm run clean && pnpm install","typecheck": "turbo run typecheck","dev:web": "pnpm --filter @alook/web dev",- "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev",+ "dev:cli": "ALOOK_SERVER_URL=http://127.0.0.1:3003 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev","dev:email": "pnpm --filter @alook/email-worker dev","dev:ws": "pnpm --filter @alook/ws-do dev","dev:meeting": "node scripts/dev-meeting.mjs",@@ -22,6 +22,7 @@"test:web": "pnpm --filter @alook/web test","test:e2e": "pnpm --filter @alook/web test:e2e","db:migrate": "pnpm --filter @alook/web exec wrangler d1 migrations apply alook-app --local",+ "db:seed:homepage-stubs": "node scripts/seed-homepage-stubs.mjs","db:reset": "rm -rf src/web/.wrangler/state && pnpm run db:migrate","test:all": "vitest run","deploy:web": "pnpm db:migrate:remote && cd src/web && npx opennextjs-cloudflare build && npx opennextjs-cloudflare deploy",@@ -50,4 +51,4 @@"workerd"]}-}\ No newline at end of file+}diff --git a/scripts/seed-homepage-stubs.mjs b/scripts/seed-homepage-stubs.mjsnew file mode 100644index 000000000..bfaf6a80d--- /dev/null+++ b/scripts/seed-homepage-stubs.mjs@@ -0,0 +1,102 @@+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { spawnSync } from "node:child_process";++const workspaceSlug = process.env.ALOOK_STUB_WORKSPACE_SLUG || "d1183898546";+const ownerEmail = process.env.ALOOK_STUB_OWNER_EMAIL || "[email protected]";+const now = "strftime('%Y-%m-%dT%H:%M:%fZ','now')";+const stubOnlineUntil = "strftime('%Y-%m-%dT%H:%M:%SZ','now','+1 hour')";++const workspaceId = `(select id from workspace where slug = '${workspaceSlug.replaceAll("'", "''")}')`;+const ownerId = `(select id from user where email = '${ownerEmail.replaceAll("'", "''")}')`;++const sql = `+PRAGMA foreign_keys=ON;++insert into machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at)+values+ ('daemon_stub_studio', ${workspaceId}, 'MacBook Studio Stub', ${stubOnlineUntil}, ${now}, ${now}),+ ('daemon_stub_lab', ${workspaceId}, 'Alook Lab Stub', ${stubOnlineUntil}, ${now}, ${now})+on conflict(workspace_id, daemon_id) do update set+ device_info = excluded.device_info,+ last_seen_at = excluded.last_seen_at,+ updated_at = excluded.updated_at;++insert into agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, device_info, metadata, created_at, updated_at)+values+ ('rt_stub_codex_studio', ${workspaceId}, 'daemon_stub_studio', 'local', 'codex', 'MacBook Studio Stub', json('{"version":"stub-codex","stub":true}'), ${now}, ${now}),+ ('rt_stub_claude_lab', ${workspaceId}, 'daemon_stub_lab', 'local', 'claude', 'Alook Lab Stub', json('{"version":"stub-claude","stub":true}'), ${now}, ${now})+on conflict(id) do update set+ daemon_id = excluded.daemon_id,+ runtime_mode = excluded.runtime_mode,+ provider = excluded.provider,+ device_info = excluded.device_info,+ metadata = excluded.metadata,+ updated_at = excluded.updated_at;++insert into agent (id, workspace_id, name, description, instructions, avatar_url, runtime_id, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, tools, triggers, email_handle, created_at, updated_at)+values+ ('ag_stub_mandy', ${workspaceId}, 'Mandy', 'General manager stub for local Homepage testing.', 'Coordinate, summarize, and keep the work moving.', null, 'rt_stub_claude_lab', 'local', json('{"model":"claude-sonnet-4-6","stub":true}'), 'private', 'idle', 6, ${ownerId}, null, null, 'stub-mandy', ${now}, ${now}),+ ('ag_stub_tony', ${workspaceId}, 'Tony', 'Implementation engineer stub.', 'Implement scoped product and infrastructure changes.', null, 'rt_stub_codex_studio', 'local', json('{"model":"gpt-5.3-codex","stub":true}'), 'private', 'idle', 6, ${ownerId}, null, null, 'stub-tony', ${now}, ${now}),+ ('ag_stub_jesse', ${workspaceId}, 'Jesse', 'Adversarial reviewer stub.', 'Challenge assumptions, review edge cases, and verify implementation quality.', null, 'rt_stub_codex_studio', 'local', json('{"model":"gpt-5.3-codex","stub":true}'), 'private', 'idle', 6, ${ownerId}, null, null, 'stub-jesse', ${now}, ${now}),+ ('ag_stub_huzi', ${workspaceId}, 'Huzi', 'MacBook and local execution stub.', 'Handle local MacBook checks, tunnels, and filesystem execution.', null, 'rt_stub_claude_lab', 'local', json('{"model":"claude-sonnet-4-6","stub":true}'), 'private', 'idle', 6, ${ownerId}, null, null, 'stub-huzi', ${now}, ${now}),+ ('ag_stub_fenge', ${workspaceId}, 'Fenge', 'Email operations stub.', 'Handle outbound email drafts, replies, and outreach workflows.', null, 'rt_stub_claude_lab', 'local', json('{"model":"claude-sonnet-4-6","stub":true}'), 'private', 'idle', 6, ${ownerId}, null, null, 'stub-fenge', ${now}, ${now})+on conflict(id, workspace_id) do update set+ name = excluded.name,+ description = excluded.description,+ instructions = excluded.instructions,+ runtime_id = excluded.runtime_id,+ runtime_mode = excluded.runtime_mode,+ runtime_config = excluded.runtime_config,+ owner_id = excluded.owner_id,+ email_handle = excluded.email_handle,+ updated_at = excluded.updated_at;++insert into agent_link (id, workspace_id, source_agent_id, target_agent_id, instruction, created_at, updated_at)+values+ ('al_stub_mandy_tony', ${workspaceId}, 'ag_stub_mandy', 'ag_stub_tony', 'Mandy assigns implementation work to Tony.', ${now}, ${now}),+ ('al_stub_tony_jesse', ${workspaceId}, 'ag_stub_tony', 'ag_stub_jesse', 'Tony sends changes to Jesse for adversarial review.', ${now}, ${now}),+ ('al_stub_jesse_mandy', ${workspaceId}, 'ag_stub_jesse', 'ag_stub_mandy', 'Jesse reports risks back to Mandy for acceptance.', ${now}, ${now}),+ ('al_stub_mandy_huzi', ${workspaceId}, 'ag_stub_mandy', 'ag_stub_huzi', 'Mandy asks Huzi to validate local MacBook workflows.', ${now}, ${now}),+ ('al_stub_fenge_mandy', ${workspaceId}, 'ag_stub_fenge', 'ag_stub_mandy', 'Fenge reports email delivery status to Mandy.', ${now}, ${now})+on conflict(workspace_id, source_agent_id, target_agent_id) do update set+ instruction = excluded.instruction,+ updated_at = excluded.updated_at;++insert into conversation (id, workspace_id, agent_id, user_id, title, type, channel, created_at)+values+ ('conv_stub_tony_working', ${workspaceId}, 'ag_stub_tony', ${ownerId}, 'Stub active task for Homepage PET testing', 'user_dm_message', 'default', ${now})+on conflict(id) do update set+ title = excluded.title,+ channel = excluded.channel;++insert into agent_task_queue (id, agent_id, runtime_id, workspace_id, conversation_id, prompt, type, context_key, status, priority, result, context, session_id, created_at, dispatched_at, started_at, completed_at, error, trace_id, parent_task_id)+values+ ('task_stub_tony_running', 'ag_stub_tony', 'rt_stub_codex_studio', ${workspaceId}, 'conv_stub_tony_working', 'Stub running task so PET can react to a working agent on Homepage.', 'user_dm_message', 'stub-homepage-pet', 'running', 0, null, json('{"stub":true}'), 'stub-session', ${now}, ${now}, ${now}, null, null, 'trace_stub_homepage_pet', null)+on conflict(id) do update set+ status = excluded.status,+ prompt = excluded.prompt,+ context = excluded.context,+ dispatched_at = excluded.dispatched_at,+ started_at = excluded.started_at;++select 'workspace' as kind, id, slug as label from workspace where slug = '${workspaceSlug.replaceAll("'", "''")}';+select 'machine_count' as kind, count(*) as id, '' as label from machine where workspace_id = ${workspaceId} and daemon_id like 'daemon_stub_%';+select 'runtime_count' as kind, count(*) as id, '' as label from agent_runtime where workspace_id = ${workspaceId} and id like 'rt_stub_%';+select 'agent_count' as kind, count(*) as id, '' as label from agent where workspace_id = ${workspaceId} and id like 'ag_stub_%';+select 'active_stub_tasks' as kind, count(*) as id, '' as label from agent_task_queue where workspace_id = ${workspaceId} and id = 'task_stub_tony_running' and status = 'running';+`;++const dir = mkdtempSync(join(tmpdir(), "alook-homepage-stubs-"));+const file = join(dir, "seed.sql");+writeFileSync(file, sql);++const result = spawnSync(+ "pnpm",+ ["--filter", "@alook/web", "exec", "wrangler", "d1", "execute", "alook-app", "--local", "--file", file],+ { stdio: "inherit" },+);++rmSync(dir, { recursive: true, force: true });+process.exit(result.status ?? 1);diff --git a/src/shared/src/browser/chrome-finder.test.ts b/src/shared/src/browser/chrome-finder.test.tsindex 292741cb4..2ac6b002b 100644--- a/src/shared/src/browser/chrome-finder.test.ts+++ b/src/shared/src/browser/chrome-finder.test.ts@@ -1,20 +1,23 @@import { describe, it, expect, vi, beforeEach } from "vitest"-import { existsSync } from "node:fs"+import { existsSync, readdirSync } from "node:fs"import { execSync } from "node:child_process"import { findChrome, hasChromeInstalled, ensureChrome } from "./chrome-finder"vi.mock("node:fs", () => ({existsSync: vi.fn(),+ readdirSync: vi.fn(),}))vi.mock("node:child_process", () => ({execSync: vi.fn(),}))const mockExistsSync = vi.mocked(existsSync)+const mockReaddirSync = vi.mocked(readdirSync)const mockExecSync = vi.mocked(execSync) as unknown as ReturnType<typeof vi.fn>beforeEach(() => {vi.clearAllMocks()+ mockReaddirSync.mockReturnValue([])})describe("findChrome", () => {@@ -57,6 +60,32 @@ describe("findChrome", () => {Object.defineProperty(process, "platform", { value: originalPlatform })})++ it("returns cached Playwright Chromium without running dry-run", () => {+ const originalPlatform = process.platform+ const originalHome = process.env.HOME+ Object.defineProperty(process, "platform", { value: "linux" })+ process.env.HOME = "/home/tester"++ mockExistsSync.mockImplementation((p) =>+ p === "/home/tester/.cache/ms-playwright/chromium-1217/chrome-linux64/chrome"+ )+ mockReaddirSync.mockReturnValue(["chromium-1217"] as unknown as ReturnType<typeof readdirSync>)++ expect(findChrome()).toBe(+ "/home/tester/.cache/ms-playwright/chromium-1217/chrome-linux64/chrome"+ )+ expect(mockExecSync).toHaveBeenCalledWith("which google-chrome || which chromium", {+ encoding: "utf8",+ })+ expect(mockExecSync).not.toHaveBeenCalledWith(+ expect.stringContaining("playwright install --dry-run"),+ expect.anything()+ )++ process.env.HOME = originalHome+ Object.defineProperty(process, "platform", { value: originalPlatform })+ })})describe("hasChromeInstalled", () => {diff --git a/src/shared/src/browser/chrome-finder.ts b/src/shared/src/browser/chrome-finder.tsindex b68449b42..63f4daf17 100644--- a/src/shared/src/browser/chrome-finder.ts+++ b/src/shared/src/browser/chrome-finder.ts@@ -1,5 +1,7 @@-import { existsSync } from "node:fs"+import { existsSync, readdirSync } from "node:fs"import { execSync } from "node:child_process"+import { homedir } from "node:os"+import { join } from "node:path"const CHROME_PATHS: Record<string, string[]> = {darwin: [@@ -40,17 +42,15 @@ export function findChrome(): string | null {}function findPlaywrightChromium(): string | null {+ const cached = findCachedPlaywrightChromium()+ if (cached) return cached+try {const result = execSync("npx playwright install --dry-run chromium 2>&1", { encoding: "utf8" })- const match = result.match(/browser binaries.*?:\s*(.+)/i)+ const match = result.match(/(?:browser binaries|Install location).*?:\s*(.+)/i)if (match) {const dir = match[1].trim()- const chromePaths = [- `${dir}/chrome-linux/chrome`,- `${dir}/chrome-mac/Chromium.app/Contents/MacOS/Chromium`,- `${dir}/chrome-win/chrome.exe`,- ]- for (const p of chromePaths) {+ for (const p of getPlaywrightChromiumCandidates(dir)) {if (existsSync(p)) return p}}@@ -58,6 +58,39 @@ function findPlaywrightChromium(): string | null {return null}+function findCachedPlaywrightChromium(): string | null {+ const roots = [+ process.env.PLAYWRIGHT_BROWSERS_PATH,+ join(homedir(), ".cache", "ms-playwright"),+ ].filter(Boolean) as string[]++ for (const root of roots) {+ let entries: string[]+ try {+ entries = readdirSync(root, { encoding: "utf8" })+ } catch {+ continue+ }++ for (const entry of entries.filter((item) => item.startsWith("chromium-")).sort().reverse()) {+ for (const p of getPlaywrightChromiumCandidates(join(root, entry))) {+ if (existsSync(p)) return p+ }+ }+ }++ return null+}++function getPlaywrightChromiumCandidates(dir: string): string[] {+ return [+ join(dir, "chrome-linux64", "chrome"),+ join(dir, "chrome-linux", "chrome"),+ join(dir, "chrome-mac", "Chromium.app", "Contents", "MacOS", "Chromium"),+ join(dir, "chrome-win", "chrome.exe"),+ ]+}+export function ensureChrome(): string {const existing = findChrome()if (existing) return existingdiff --git a/src/shared/test/browser/meet-browser.test.ts b/src/shared/test/browser/meet-browser.test.tsindex 7d2bd786d..4d881cd43 100644--- a/src/shared/test/browser/meet-browser.test.ts+++ b/src/shared/test/browser/meet-browser.test.ts@@ -20,7 +20,7 @@ import type { BrowserPage } from "../../src/browser/index"const _dir = dirname(fileURLToPath(import.meta.url))const mockHtml = readFileSync(join(_dir, "mock-meet.html"), "utf-8")-let server: Server+let server: Server | undefinedlet serverUrl: stringlet browser: Browser@@ -40,10 +40,18 @@ beforeAll(async () => {const port = typeof addr === "object" && addr ? addr.port : 0serverUrl = `http://localhost:${port}`- browser = await chromium.launch({- executablePath: chromePath,- headless: true,- })+ try {+ browser = await chromium.launch({+ executablePath: chromePath,+ headless: true,+ })+ } catch (error) {+ console.warn(+ `SKIP: Chrome could not launch — browser integration tests require browser system dependencies (${error instanceof Error ? error.message : String(error)})`+ )+ server.close()+ server = undefined+ }}, 30_000)afterAll(async () => {diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex bc482d72b..10cb74bf1 100644--- a/src/web/.dev.vars.example+++ b/src/web/.dev.vars.example@@ -8,7 +8,7 @@# Session signing secret (generate with: openssl rand -base64 32)BETTER_AUTH_SECRET=-BETTER_AUTH_URL=http://localhost:3000+BETTER_AUTH_URL=http://127.0.0.1:3003# Encryption key for IMAP/SMTP credentials (generate with: openssl rand -base64 32)ENCRYPTION_KEY=diff --git a/src/web/lighthouserc.json b/src/web/lighthouserc.jsonindex e42a560f6..1f6e57ef9 100644--- a/src/web/lighthouserc.json+++ b/src/web/lighthouserc.json@@ -2,7 +2,7 @@"ci": {"collect": {"url": ["http://localhost:3000/"],- "startServerCommand": "pnpm dev",+ "startServerCommand": "pnpm exec next dev","startServerReadyPattern": "Ready in","numberOfRuns": 1,"settings": {diff --git a/src/web/package.json b/src/web/package.jsonindex e31d2b54f..a18b4e75a 100644--- a/src/web/package.json+++ b/src/web/package.json@@ -3,7 +3,7 @@"version": "0.0.59","private": true,"scripts": {- "dev": "next dev",+ "dev": "next dev -H 127.0.0.1 -p 3003","build": "next build","start": "next start","lint": "next lint",diff --git a/src/web/public/pets/tater/pet.json b/src/web/public/pets/tater/pet.jsonnew file mode 100644index 000000000..186a1cfd6--- /dev/null+++ b/src/web/public/pets/tater/pet.json@@ -0,0 +1,6 @@+{+ "id": "tater",+ "displayName": "Tater",+ "description": "A cheerful potato mascot with oversized translucent visor goggles, a glowing red stylus in one hand, soft pale limbs, and chunky futuristic sneakers, simplified into the Codex digital pet style.",+ "spritesheetPath": "spritesheet.webp"+}diff --git a/src/web/public/pets/tater/spritesheet.webp b/src/web/public/pets/tater/spritesheet.webpnew file mode 100644index 000000000..b4d724393Binary files /dev/null and b/src/web/public/pets/tater/spritesheet.webp differdiff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex ae4894297..55998e226 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -46,6 +46,8 @@ import { LinkSidecar } from "@/components/canvas/link-sidecar";import { ActiveTasksFloat } from "@/components/canvas/active-tasks-float";import { UpcomingEventsFloat } from "@/components/canvas/upcoming-events-float";import { getAutoLayout } from "@/components/canvas/auto-layout";+import { CloudCodeMonsterPet } from "@/components/home-pet/cloud-code-monster-pet";+import { useHomePetSettings } from "@/lib/home-pet-settings";const nodeTypes = { agent: AgentNode };const edgeTypes = { link: LinkEdge };@@ -78,6 +80,8 @@ function AgentCanvas() {const { agents, runtimes, loading, activeTaskCounts } = useAgentContext();const { slug, workspaceId } = useWorkspace();const { zoomIn, zoomOut, fitView } = useReactFlow();+ const canvasRef = useRef<HTMLDivElement>(null);+ const petSettings = useHomePetSettings();const [nodes, setNodes] = useState<Node[]>([]);const [edges, setEdges] = useState<Edge[]>([]);@@ -342,7 +346,7 @@ function AgentCanvas() {);return (- <div className="flex-1 relative">+ <div ref={canvasRef} className="flex-1 relative"><ReactFlownodes={nodes}edges={edges}@@ -365,9 +369,18 @@ function AgentCanvas() {<Background variant={BackgroundVariant.Dots} gap={24} size={1.5} color="var(--color-border)" /></ReactFlow>+ {petSettings.enabled ? (+ <CloudCodeMonsterPet+ boundaryRef={canvasRef}+ activityTriggerMode={+ petSettings.displayScope === "global" ? "global" : "home"+ }+ />+ ) : null}+{/* Custom floating toolbar */}<div- className="absolute bottom-4 left-4 bg-background/80 backdrop-blur-sm rounded-lg ring-1 ring-foreground/5 p-1 flex gap-0.5 animate-[fade-up_300ms_ease-out_both]"+ className="absolute bottom-4 left-4 z-40 bg-background/80 backdrop-blur-sm rounded-lg ring-1 ring-foreground/5 p-1 flex gap-0.5 animate-[fade-up_300ms_ease-out_both]"style={{ animationDelay: "200ms" }}><button@@ -402,7 +415,7 @@ function AgentCanvas() {{/* No-links hint */}{showHint && (- <div className="absolute bottom-14 left-4 text-xs text-muted-foreground bg-background/80 backdrop-blur-sm rounded-md px-3 py-1.5 ring-1 ring-foreground/5">+ <div className="absolute bottom-14 left-4 z-40 text-xs text-muted-foreground bg-background/80 backdrop-blur-sm rounded-md px-3 py-1.5 ring-1 ring-foreground/5">Drag between agent handles to create relationships.</div>)}@@ -424,7 +437,7 @@ function AgentCanvas() {{/* Create agent button */}<buttontype="button"- className="absolute top-4 right-4 size-8 rounded-lg bg-background/80 backdrop-blur-sm ring-1 ring-foreground/5 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors animate-[fade-up_300ms_ease-out_both]"+ className="absolute top-4 right-4 z-40 size-8 rounded-lg bg-background/80 backdrop-blur-sm ring-1 ring-foreground/5 flex items-center justify-center text-muted-foreground hover:text-foreground hover:bg-accent transition-colors animate-[fade-up_300ms_ease-out_both]"style={{ animationDelay: "200ms" }}onClick={() => router.push(`/w/${slug}/agents/new`)}title="Create new agent"diff --git a/src/web/src/app/(app)/w/[slug]/settings/page.tsx b/src/web/src/app/(app)/w/[slug]/settings/page.tsxindex fbca66d4a..73b318e50 100644--- a/src/web/src/app/(app)/w/[slug]/settings/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/settings/page.tsx@@ -8,10 +8,12 @@ import { GeneralTab } from "./general-tab";import { InstructionTab } from "./instruction-tab";import { MembersTab } from "./members-tab";import { NotificationTab } from "./notification-tab";+import { PetTab } from "./pet-tab";import { UsagesTab } from "./usages-tab";const TABS = [{ id: "general", label: "General" },+ { id: "pet", label: "Pet" },{ id: "instruction", label: "Global Instruction" },{ id: "notifications", label: "Notifications" },{ id: "members", label: "Members" },@@ -73,6 +75,7 @@ export default function SettingsPage() {) : (<div className="mx-auto max-w-md">{activeTab === "general" && <GeneralTab />}+ {activeTab === "pet" && <PetTab />}{activeTab === "notifications" && <NotificationTab />}{activeTab === "members" && <MembersTab />}</div>diff --git a/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx b/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsxnew file mode 100644index 000000000..c7232b9bb--- /dev/null+++ b/src/web/src/app/(app)/w/[slug]/settings/pet-tab.tsx@@ -0,0 +1,215 @@+"use client";++import { useEffect, useState } from "react";+import { Monitor, PanelTop, Sparkles } from "lucide-react";++import {+ CloudCodeMonsterPresetPreview,+ CLOUD_CODE_MONSTER_PET_PRESETS,+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ getCloudCodeMonsterPreset,+ readCloudCodeMonsterPetPresetId,+ writeCloudCodeMonsterPetPresetId,+} from "@/components/home-pet/cloud-code-monster-pet";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import {+ readHomePetSettings,+ writeHomePetSettings,+ type HomePetDisplayScope,+} from "@/lib/home-pet-settings";+import { cn } from "@/lib/utils";++const DISPLAY_SCOPE_OPTIONS: Array<{+ id: HomePetDisplayScope;+ label: string;+ description: string;+ icon: typeof PanelTop;+}> = [+ {+ id: "home",+ label: "Homepage only",+ description: "Show inside the relationship canvas",+ icon: PanelTop,+ },+ {+ id: "global",+ label: "Global Display",+ description: "Show across workspace pages",+ icon: Monitor,+ },+];++export function PetTab() {+ const [enabled, setEnabled] = useState(true);+ const [displayScope, setDisplayScope] = useState<HomePetDisplayScope>("home");+ const [selectedPresetId, setSelectedPresetId] = useState(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ const selectedPreset = getCloudCodeMonsterPreset(selectedPresetId);++ useEffect(() => {+ const settings = readHomePetSettings();+ setEnabled(settings.enabled);+ setDisplayScope(settings.displayScope);+ setSelectedPresetId(readCloudCodeMonsterPetPresetId());++ const handlePresetChange = (event: Event) => {+ const nextPresetId = (event as CustomEvent<{ presetId?: string }>).detail+ ?.presetId;+ setSelectedPresetId(+ nextPresetId+ ? getCloudCodeMonsterPreset(nextPresetId).id+ : readCloudCodeMonsterPetPresetId()+ );+ };++ window.addEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );++ return () => {+ window.removeEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );+ };+ }, []);++ const handleEnabledChange = (checked: boolean) => {+ setEnabled(checked);+ writeHomePetSettings({ enabled: checked });+ };++ const handleDisplayScopeChange = (scope: HomePetDisplayScope) => {+ setDisplayScope(scope);+ writeHomePetSettings({ displayScope: scope });+ };++ return (+ <div className="space-y-8">+ <section className="space-y-4">+ <h2 className="text-sm font-medium">Pet</h2>+ <div className="space-y-4">+ <div className="flex items-center justify-between gap-4">+ <div className="space-y-0.5">+ <Label htmlFor="pet-enabled" className="text-sm">+ Enable pet+ </Label>+ <p className="text-xs text-muted-foreground">+ Keep the workspace companion visible when enabled+ </p>+ </div>+ <Switch+ id="pet-enabled"+ checked={enabled}+ onCheckedChange={handleEnabledChange}+ />+ </div>++ {enabled ? (+ <div className="space-y-2">+ <p className="text-xs text-muted-foreground">Display range</p>+ <div className="grid gap-2">+ {DISPLAY_SCOPE_OPTIONS.map((option) => {+ const Icon = option.icon;+ const isSelected = displayScope === option.id;++ return (+ <button+ key={option.id}+ type="button"+ aria-pressed={isSelected}+ onClick={() => handleDisplayScopeChange(option.id)}+ className={cn(+ "flex items-center gap-3 rounded-md border px-3 py-2 text-left transition-colors",+ isSelected+ ? "border-primary/50 bg-accent text-foreground"+ : "border-border/60 bg-background/60 text-muted-foreground hover:bg-accent/50 hover:text-foreground"+ )}+ >+ <Icon className="size-4 shrink-0" />+ <span className="min-w-0">+ <span className="block text-sm font-medium">+ {option.label}+ </span>+ <span className="block text-xs text-muted-foreground">+ {option.description}+ </span>+ </span>+ </button>+ );+ })}+ </div>+ </div>+ ) : null}+ </div>+ </section>++ {enabled ? (+ <section className="space-y-4">+ <div className="flex items-center justify-between gap-3">+ <div>+ <h2 className="text-sm font-medium">Preset</h2>+ <p className="mt-1 text-xs text-muted-foreground">+ {selectedPreset.name}+ </p>+ </div>+ <div className="grid size-14 place-items-center rounded-md bg-card ring-1 ring-border/60">+ <CloudCodeMonsterPresetPreview+ preset={selectedPreset}+ className="size-11"+ />+ </div>+ </div>++ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3">+ {CLOUD_CODE_MONSTER_PET_PRESETS.map((preset) => {+ const isSelected = preset.id === selectedPreset.id;++ return (+ <button+ key={preset.id}+ type="button"+ aria-pressed={isSelected}+ onClick={() => {+ const nextPresetId = writeCloudCodeMonsterPetPresetId(+ preset.id+ );+ setSelectedPresetId(nextPresetId);+ }}+ className={cn(+ "group grid h-28 min-w-0 grid-rows-[1fr_auto] rounded-md border bg-card/60 p-2 text-left transition-all hover:border-foreground/20 hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70",+ isSelected+ ? "border-primary/50 bg-accent text-foreground"+ : "border-border/50 text-muted-foreground"+ )}+ >+ <div className="grid place-items-center rounded bg-background/70 ring-1 ring-border/35">+ <CloudCodeMonsterPresetPreview+ preset={preset}+ className="size-14 transition-transform duration-200 group-hover:scale-105"+ />+ </div>+ <div className="mt-1.5 flex min-w-0 items-center justify-between gap-1 text-[10px] leading-none">+ <span className="truncate font-medium text-foreground">+ {preset.name}+ </span>+ {isSelected ? (+ <Sparkles className="size-3 shrink-0 text-primary" />+ ) : (+ <span className="shrink-0 text-muted-foreground">+ {preset.id.replace("pet-", "#")}+ </span>+ )}+ </div>+ </button>+ );+ })}+ </div>+ </section>+ ) : null}+ </div>+ );+}diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex eb874bd08..00cb80fba 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -1361,8 +1361,500 @@animation: sidebar-agent-pop 500ms cubic-bezier(0.34, 1.56, 0.64, 1) both;}+/* ── Workspace canvas PET ── */+.home-pet {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 10;+ width: 72px;+ transform: translate3d(var(--home-pet-x), var(--home-pet-y), 0);+ pointer-events: none;+ user-select: none;+ touch-action: none;+}++.home-pet-status {+ position: absolute;+ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++.home-pet-status::after {+ display: none;+}++.home-pet-status-kicker {+ display: block;+ margin-bottom: 0.18rem;+ color: var(--muted-foreground);+ font-size: 0.58rem;+ font-weight: 700;+ letter-spacing: 0;+ text-transform: uppercase;+}++.home-pet-button {+ position: relative;+ display: grid;+ place-items: center;+ padding: 0;+ border: 0;+ background: transparent;+ cursor: grab;+ filter: drop-shadow(0 10px 16px color-mix(in oklch, var(--foreground) 15%, transparent));+ pointer-events: auto;+ transform-origin: 50% 86%;+}++.home-pet-button:active,+.home-pet-button[data-dragging="true"] {+ cursor: grabbing;+}++.home-pet-button:focus-visible {+ outline: 2px solid color-mix(in oklch, var(--primary) 55%, transparent);+ outline-offset: 5px;+ border-radius: 8px;+}++.home-pet-sprite {+ display: block;+ width: 100%;+ height: 100%;+ background-image: var(--home-pet-sprite-url);+ background-repeat: no-repeat;+ background-size: var(--home-pet-bg-width) var(--home-pet-bg-height);+ background-position: var(--home-pet-bg-x) var(--home-pet-bg-y);+ image-rendering: auto;+ -webkit-user-drag: none;+ pointer-events: none;+}++.home-pet-motion-idle {+ animation: none;+}++.home-pet-motion-watch {+ animation: home-pet-watch 780ms ease-out both;+}++.home-pet-motion-scroll {+ animation: home-pet-scroll 820ms ease-out both;+}++.home-pet-motion-nap {+ animation: home-pet-nap 900ms ease-out both;+}++.home-pet-motion-think {+ animation: home-pet-think 840ms ease-out both;+}++.home-pet-motion-startled {+ animation: home-pet-startled 900ms cubic-bezier(0.34, 1.56, 0.64, 1) both;+}++@keyframes home-pet-watch {+ 0%, 100% { transform: rotate(0deg) translateY(0); }+ 38% { transform: rotate(-3deg) translateY(-2px); }+ 72% { transform: rotate(2deg) translateY(-1px); }+}++@keyframes home-pet-scroll {+ 0%, 100% { transform: translateX(0) translateY(0); }+ 30% { transform: translateX(-3px) translateY(-2px); }+ 65% { transform: translateX(2px) translateY(1px); }+}++@keyframes home-pet-nap {+ 0%, 100% { transform: rotate(-2deg) scale(1); }+ 50% { transform: rotate(-3deg) scale(0.99, 1.005); }+}++@keyframes home-pet-think {+ 0%, 100% { transform: translateY(0) rotate(0deg); }+ 25% { transform: translateY(-3px) rotate(-1.5deg); }+ 75% { transform: translateY(-1px) rotate(1.5deg); }+}++@keyframes home-pet-startled {+ 0% { transform: translateY(0) rotate(0deg) scale(1); }+ 18% { transform: translateY(-12px) rotate(-7deg) scale(1.07); }+ 36% { transform: translateY(3px) rotate(6deg) scale(0.98, 1.03); }+ 58% { transform: translateY(-5px) rotate(-3deg) scale(1.02); }+ 100% { transform: translateY(0) rotate(0deg) scale(1); }+}++/* ── Preview PET: Claude Code pixel monster ── */+.pet-preview-flow {+ position: relative;+ z-index: 10;+}++.pet-preview-flow .react-flow__node {+ z-index: 30 !important;+}++.cloud-code-monster-pet {+ position: absolute;+ top: 0;+ left: 0;+ z-index: 12;+ width: 82px;+ transform: translate3d(var(--cloud-code-monster-pet-x), var(--cloud-code-monster-pet-y), 0);+ pointer-events: none;+ user-select: none;+ touch-action: none;+}++.cloud-code-monster-pet-footsteps {+ position: absolute;+ inset: 0;+ z-index: 11;+ overflow: hidden;+ pointer-events: none;+}++.cloud-code-monster-pet-footprint {+ position: absolute;+ left: 0;+ top: 0;+ width: 11px;+ height: 6px;+ border-radius: 3px;+ background: color-mix(in oklch, var(--foreground) 26%, transparent);+ opacity: 0;+ transform: translate3d(var(--monster-footprint-x), var(--monster-footprint-y), 0)+ rotate(var(--monster-footprint-rotate, -8deg))+ scale(var(--monster-footprint-scale, 1));+ animation: cloud-code-monster-footprint 980ms ease-out both;+}++.cloud-code-monster-pet-footprint[data-side="right"] {+ --monster-footprint-rotate: 8deg;+}++.cloud-code-monster-pet-button {+ position: relative;+ display: grid;+ width: 82px;+ height: 82px;+ place-items: center;+ padding: 0;+ border: 0;+ background: transparent;+ cursor: grab;+ filter: drop-shadow(0 12px 18px color-mix(in oklch, var(--foreground) 16%, transparent));+ pointer-events: auto;+ transform-origin: 50% 88%;+}++.cloud-code-monster-pet-button:active,+.cloud-code-monster-pet-button[data-dragging="true"] {+ cursor: grabbing;+}++.cloud-code-monster-pet-button[data-fainted="true"] {+ cursor: pointer;+}++.cloud-code-monster-pet-button:focus-visible {+ outline: 2px solid color-mix(in oklch, var(--primary) 55%, transparent);+ outline-offset: 5px;+ border-radius: 8px;+}++.cloud-code-monster-pet-svg {+ display: block;+ width: 100%;+ height: 100%;+ overflow: visible;+ pointer-events: none;+ transform-origin: 50% 50%;+}++.cloud-code-monster-pet[data-direction="left"] .cloud-code-monster-pet-svg {+ transform: scaleX(-1);+}++.cloud-code-monster-pet-character {+ animation: cloud-code-monster-breathe 4.6s ease-in-out infinite;+ transform-box: fill-box;+ transform-origin: 50% 80%;+}++.cloud-code-monster-pet-left-foot,+.cloud-code-monster-pet-right-foot {+ transform-box: fill-box;+}++.cloud-code-monster-pet-accessory {+ transform-box: fill-box;+ transform-origin: 50% 80%;+}++.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-character {+ animation: cloud-code-monster-walk var(--monster-walk-duration, 260ms) steps(2, end) infinite;+}++.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-left-foot {+ animation: cloud-code-monster-left-foot var(--monster-walk-duration, 260ms) steps(2, end) infinite;+ transform-origin: 50% 50%;+}++.cloud-code-monster-pet[data-walking="true"] .cloud-code-monster-pet-right-foot {+ animation: cloud-code-monster-right-foot var(--monster-walk-duration, 260ms) steps(2, end) infinite;+ transform-origin: 50% 50%;+}++.cloud-code-monster-pet[data-reacting="true"] .cloud-code-monster-pet-button {+ animation: cloud-code-monster-startled 900ms cubic-bezier(0.34, 1.56, 0.64, 1) both;+}++.cloud-code-monster-pet[data-shaken="true"] .cloud-code-monster-pet-button {+ animation: cloud-code-monster-shaken 180ms steps(2, end) infinite;+}++.cloud-code-monster-pet[data-fainted="true"] .cloud-code-monster-pet-button {+ animation: cloud-code-monster-faint 10s ease-in-out both;+ filter: drop-shadow(0 6px 9px color-mix(in oklch, var(--foreground) 12%, transparent));+ transform-origin: 50% 92%;+}++.cloud-code-monster-pet[data-fainted="true"] .cloud-code-monster-pet-character {+ animation: none;+}++.cloud-code-monster-pet[data-peeking="true"] {+ z-index: 2;+}++.cloud-code-monster-pet[data-peeking="true"] .cloud-code-monster-pet-button {+ animation: cloud-code-monster-peek 4.2s ease-in-out both;+}++.cloud-code-monster-pet-notification-bell {+ position: absolute;+ left: 50%;+ top: -18px;+ z-index: 3;+ display: grid;+ width: 28px;+ height: 28px;+ place-items: center;+ background: transparent;+ filter: drop-shadow(0 7px 10px color-mix(in oklch, var(--foreground) 20%, transparent));+ image-rendering: pixelated;+ transform: translateX(-50%);+ animation: cloud-code-monster-bell-alert 980ms cubic-bezier(0.34, 1.56, 0.64, 1) infinite;+ pointer-events: none;+}++.cloud-code-monster-pet-shock rect {+ animation: cloud-code-monster-shock-pixels 360ms steps(2, end) infinite;+ transform-box: fill-box;+ transform-origin: center;+}++.cloud-code-monster-pet-shock rect:nth-child(2),+.cloud-code-monster-pet-shock rect:nth-child(4) {+ animation-delay: 80ms;+}++.cloud-code-monster-pet-shock rect:nth-child(3),+.cloud-code-monster-pet-shock rect:nth-child(5) {+ animation-delay: 140ms;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-character {+ animation: cloud-code-monster-sleep 5.2s steps(2, end) infinite;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep rect {+ animation: cloud-code-monster-sleep-pixels 2.6s ease-in-out infinite;+ transform-box: fill-box;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z {+ animation: cloud-code-monster-sleep-pixels 2.6s ease-in-out infinite;+ transform-box: fill-box;+ transform-origin: center;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z rect {+ animation: none;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z:nth-child(2) {+ animation-delay: 320ms;+}++.cloud-code-monster-pet[data-activity="sleeping"] .cloud-code-monster-pet-sleep-z:nth-child(3) {+ animation-delay: 640ms;+}++.cloud-code-monster-pet[data-activity="reading"] .cloud-code-monster-pet-book {+ animation: cloud-code-monster-read 3.2s steps(2, end) infinite;+}++.cloud-code-monster-pet[data-activity="phone"] .cloud-code-monster-pet-phone {+ animation: cloud-code-monster-phone 2.4s steps(2, end) infinite;+}++.cloud-code-monster-pet-phone-glow {+ opacity: 0.18;+ animation: cloud-code-monster-phone-glow 1.4s ease-in-out infinite;+}++.cloud-code-monster-pet[data-activity="coding"] .cloud-code-monster-pet-laptop {+ animation: cloud-code-monster-keytap 1s steps(2, end) infinite;+}++.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect {+ animation: cloud-code-monster-thought 2.8s ease-in-out infinite;+ transform-box: fill-box;+}++.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect:nth-child(2) {+ animation-delay: 240ms;+}++.cloud-code-monster-pet[data-activity="thinking"] .cloud-code-monster-pet-thought rect:nth-child(3) {+ animation-delay: 480ms;+}++.cloud-code-monster-pet[data-activity="snacking"] .cloud-code-monster-pet-snack {+ animation: cloud-code-monster-snack 2.2s steps(2, end) infinite;+}++@keyframes cloud-code-monster-breathe {+ 0%, 100% { transform: translateY(0) rotate(0deg) scale(1); }+ 50% { transform: translateY(-2px) scale(1.015, 0.985); }+}++@keyframes cloud-code-monster-sleep {+ 0%, 100% { transform: translateY(1px) rotate(0deg) scale(1.02, 0.98); }+ 50% { transform: translateY(3px) rotate(0deg) scale(1.04, 0.96); }+}++@keyframes cloud-code-monster-sleep-pixels {+ 0%, 100% { opacity: 0.18; transform: translateY(5px) scale(0.7); }+ 50% { opacity: 0.85; transform: translateY(-3px) scale(1); }+}++@keyframes cloud-code-monster-walk {+ 0% { transform: translateY(0) rotate(-2deg) scale(1); }+ 50% { transform: translateY(var(--monster-walk-lift, -2px)) rotate(2deg) scale(1.03, 0.97); }+ 100% { transform: translateY(0) rotate(-2deg) scale(1); }+}++@keyframes cloud-code-monster-left-foot {+ 0%, 100% { transform: translateX(-4px) translateY(0); }+ 50% { transform: translateX(3px) translateY(2px); }+}++@keyframes cloud-code-monster-right-foot {+ 0%, 100% { transform: translateX(4px) translateY(2px); }+ 50% { transform: translateX(-3px) translateY(0); }+}++@keyframes cloud-code-monster-footprint {+ 0% { opacity: 0.42; }+ 65% { opacity: 0.25; }+ 100% { opacity: 0; transform: translate3d(var(--monster-footprint-x), calc(var(--monster-footprint-y) + 4px), 0) rotate(var(--monster-footprint-rotate, -8deg)) scale(0.72); }+}++@keyframes cloud-code-monster-startled {+ 0% { transform: translateY(0) rotate(0deg) scale(1); }+ 16% { transform: translateY(-13px) rotate(-8deg) scale(1.08); }+ 34% { transform: translateY(3px) rotate(8deg) scale(0.96, 1.05); }+ 58% { transform: translateY(-4px) rotate(-4deg) scale(1.02); }+ 100% { transform: translateY(0) rotate(0deg) scale(1); }+}++@keyframes cloud-code-monster-shaken {+ 0%, 100% { transform: translateX(-3px) rotate(-8deg) scale(1.05); }+ 50% { transform: translateX(3px) rotate(8deg) scale(0.98, 1.08); }+}++@keyframes cloud-code-monster-faint {+ 0% { transform: translateY(0) rotate(0deg) scale(1); }+ 4% { transform: translateY(-4px) rotate(-10deg) scale(1.03); }+ 8% { transform: translateY(11px) rotate(78deg) scale(0.98, 1.05); }+ 92% { transform: translateY(11px) rotate(78deg) scale(0.98, 1.05); }+ 100% { transform: translateY(0) rotate(0deg) scale(1); }+}++@keyframes cloud-code-monster-peek {+ 0% { transform: translateY(18px) scale(0.98); }+ 16%, 82% { transform: translateY(0) scale(1); }+ 100% { transform: translateY(16px) scale(0.98); }+}++@keyframes cloud-code-monster-shock-pixels {+ 0%, 100% { opacity: 0.35; transform: scale(0.78); }+ 50% { opacity: 1; transform: scale(1.18); }+}++@keyframes cloud-code-monster-bell-alert {+ 0%, 100% { transform: translateX(-50%) translateY(0) rotate(-8deg) scale(1); }+ 35% { transform: translateX(-50%) translateY(-5px) rotate(10deg) scale(1.08); }+ 70% { transform: translateX(-50%) translateY(-1px) rotate(-12deg) scale(1.02); }+}++@keyframes cloud-code-monster-read {+ 0%, 100% { transform: translateY(0) skewY(0deg); }+ 50% { transform: translateY(-1px) skewY(-2deg); }+}++@keyframes cloud-code-monster-phone {+ 0%, 100% { transform: translateX(0) translateY(0); }+ 50% { transform: translateX(1px) translateY(-1px); }+}++@keyframes cloud-code-monster-phone-glow {+ 0%, 100% { opacity: 0.12; }+ 50% { opacity: 0.42; }+}++@keyframes cloud-code-monster-keytap {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(2px); }+}++@keyframes cloud-code-monster-thought {+ 0%, 100% { opacity: 0.22; transform: translateY(3px) scale(0.82); }+ 50% { opacity: 0.78; transform: translateY(-2px) scale(1); }+}++@keyframes cloud-code-monster-snack {+ 0%, 100% { transform: translateY(0); }+ 50% { transform: translateY(-3px); }+}+@media (prefers-reduced-motion: reduce) {.sidebar-agent-pop { animation: none !important; }+ .home-pet-button,+ .cloud-code-monster-pet-button,+ .cloud-code-monster-pet-character,+ .cloud-code-monster-pet-left-foot,+ .cloud-code-monster-pet-right-foot,+ .cloud-code-monster-pet-accessory,+ .cloud-code-monster-pet-sleep-z,+ .cloud-code-monster-pet-accessory rect,+ .cloud-code-monster-pet-shock rect,+ .cloud-code-monster-pet-phone-glow,+ .cloud-code-monster-pet-notification-bell,+ .cloud-code-monster-pet-footprint {+ animation: none !important;+ }.avatar-anim-shape-bounce [data-avatar-shape],.avatar-anim-head-tilt [data-avatar-shape],.avatar-anim-head-tilt [data-avatar-eyes],diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsxindex 555277fd1..b81940685 100644--- a/src/web/src/app/layout.tsx+++ b/src/web/src/app/layout.tsx@@ -123,7 +123,7 @@ export default function RootLayout({<link rel="preconnect" href="https://fonts.googleapis.com" /><link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="anonymous" /></head>- <body className="min-h-full flex flex-col">+ <body className="min-h-full flex flex-col" suppressHydrationWarning><scripttype="application/ld+json"dangerouslySetInnerHTML={{diff --git a/src/web/src/app/pet-preview/page.tsx b/src/web/src/app/pet-preview/page.tsxnew file mode 100644index 000000000..33950afc2--- /dev/null+++ b/src/web/src/app/pet-preview/page.tsx@@ -0,0 +1,5 @@+import { PetPreviewPage } from "@/components/home-pet/pet-preview-page";++export default function Page() {+ return <PetPreviewPage />;+}diff --git a/src/web/src/components/canvas/agent-node.tsx b/src/web/src/components/canvas/agent-node.tsxindex 0ffb497a3..58d5195ca 100644--- a/src/web/src/components/canvas/agent-node.tsx+++ b/src/web/src/components/canvas/agent-node.tsx@@ -27,6 +27,8 @@ function AgentNodeInner({ data, selected, dragging }: NodeProps) {return (<div+ data-agent-node-id={agent.id}+ data-agent-working={activeTaskCount > 0 ? "true" : "false"}onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}className={cn(diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx b/src/web/src/components/home-pet/cloud-code-monster-pet.tsxnew file mode 100644index 000000000..274f0dcda--- /dev/null+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx@@ -0,0 +1,3282 @@+"use client";++import {+ type CSSProperties,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import { clampPetPosition, type PetBounds, type PetPoint } from "./pet-presets";++export const CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS = 3 * 60 * 1000;+const CLOUD_CODE_MONSTER_STORAGE_KEY = "alook-cloud-code-monster-pet-activity-v1";+export const CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY =+ "alook-cloud-code-monster-pet-preset-v1";+export const CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT =+ "alook-cloud-code-monster-pet-preset-changed";+const CLOUD_CODE_MONSTER_REACTION_MS = 900;+const CLOUD_CODE_MONSTER_SHAKE_REACTION_MS = 680;+export const CLOUD_CODE_MONSTER_FAINT_MS = 10_000;+const CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_DISTANCE = 24;+const CLOUD_CODE_MONSTER_VIOLENT_DRAG_STRONG_DISTANCE = 56;+const CLOUD_CODE_MONSTER_VIOLENT_DRAG_MAX_ELAPSED_MS = 70;+const CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_SPEED = 1.2;+const CLOUD_CODE_MONSTER_VIOLENT_REVERSAL_MIN_SPEED = 1.5;+const CLOUD_CODE_MONSTER_FAINT_DRAG_MIN_DISTANCE = 72;+const CLOUD_CODE_MONSTER_FAINT_DRAG_MAX_ELAPSED_MS = 55;+const CLOUD_CODE_MONSTER_FAINT_DRAG_MIN_SPEED = 2.2;+const CLOUD_CODE_MONSTER_FAINT_REVERSAL_MIN_SPEED = 2.75;+export const CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS = 1_300;+export const CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS = 6;+export const CLOUD_CODE_MONSTER_FAINT_MIN_SPAN_MS = 450;+const CLOUD_CODE_MONSTER_AUTO_WALK_STEP_MS = 80;+const CLOUD_CODE_MONSTER_AUTO_WALK_SPEED = 2.7;+const CLOUD_CODE_MONSTER_PEEK_MS = 4_200;+const CLOUD_CODE_MONSTER_PEEK_INTERVAL_MS = 11_000;+const CLOUD_CODE_MONSTER_SIZE = { width: 82, height: 82 };++export type CloudCodeMonsterPeekTarget = PetPoint & {+ agentId?: string;+};++export type CloudCodeMonsterActivityTriggerMode = "home" | "global";++export type CloudCodeMonsterActivityId =+ | "coding"+ | "sleeping"+ | "reading"+ | "phone"+ | "thinking"+ | "snacking";++type CloudCodeMonsterActivity = {+ id: CloudCodeMonsterActivityId;+ label: string;+ caption: string;+};++type CloudCodeMonsterPresetFeature =+ | "square"+ | "horns"+ | "ears"+ | "visor"+ | "antenna"+ | "crown"+ | "bell"+ | "bolt"+ | "star"+ | "leaf"+ | "flame"+ | "fins"+ | "moon"+ | "mushroom"+ | "spin"+ | "chomp"+ | "ghost"+ | "cap"+ | "bow"+ | "hood"+ | "mask"+ | "soot"+ | "straw"+ | "ninja"+ | "pearl"+ | "wand"+ | "mecha"+ | "slime"+ | "ink"+ | "drum"+ | "sprout";++type CloudCodeMonsterPresetShape =+ | "monster"+ | "doraemon"+ | "pikachu"+ | "kirby"+ | "bulbasaur"+ | "charmander"+ | "squirtle"+ | "minecraft-steve"+ | "minecraft-creeper"+ | "minecraft-zombie"+ | "toad"+ | "sonic"+ | "pacman"+ | "boo"+ | "mario"+ | "pooh"+ | "hello-kitty"+ | "my-melody"+ | "kuromi"+ | "totoro"+ | "soot-sprite"+ | "luffy"+ | "naruto"+ | "goku"+ | "sailor-moon"+ | "gundam"+ | "dragon-quest-slime"+ | "inkling"+ | "snoopy"+ | "chopper";++export type CloudCodeMonsterPetPreset = {+ id: string;+ name: string;+ group: string;+ feature: CloudCodeMonsterPresetFeature;+ shape?: CloudCodeMonsterPresetShape;+ bodyTop: string;+ body: string;+ bodyDark: string;+ bodyLight: string;+ bodySideLight: string;+ bodySideDark: string;+ accent: string;+ accessory: string;+ eye: string;+ highlight: string;+ facePatch?: string;+ cheek?: string;+};++export type StoredCloudCodeMonsterActivity = {+ activityId: CloudCodeMonsterActivityId | null;+ updatedAt: number;+ hiddenAt: number | null;+};++export type CloudCodeMonsterExpression =+ | "idle"+ | "sleeping"+ | "shocked"+ | "shaken"+ | "fainted";++type Footprint = {+ id: number;+ x: number;+ y: number;+ side: "left" | "right";+ intensity: number;+};++type ReflectedMonsterWalk = {+ position: PetPoint;+ velocity: PetPoint;+ reflectedX: boolean;+ reflectedY: boolean;+};++export const CLOUD_CODE_MONSTER_ACTIVITIES: CloudCodeMonsterActivity[] = [+ { id: "coding", label: "写代码", caption: "在敲一段小 patch" },+ { id: "sleeping", label: "睡觉", caption: "闭眼打盹" },+ { id: "reading", label: "看书", caption: "翻一本很厚的 docs" },+ { id: "phone", label: "玩手机", caption: "盯着小屏幕发光" },+ { id: "thinking", label: "发呆", caption: "处理一点后台思考" },+ { id: "snacking", label: "吃零食", caption: "嚼一点能量块" },+];++export const CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS: readonly CloudCodeMonsterActivityId[] = [+ "reading",+ "phone",+ "snacking",+];++const CLOUD_CODE_MONSTER_PET_PRESET_BASES: CloudCodeMonsterPetPreset[] = [+ {+ id: "pet-01",+ name: "Claude Pixel",+ group: "Codex",+ feature: "square",+ bodyTop: "#e0845f",+ body: "#d87352",+ bodyDark: "#cf684a",+ bodyLight: "#e88d68",+ bodySideLight: "#df7d5a",+ bodySideDark: "#c86347",+ accent: "#d7654a",+ accessory: "#f1bc62",+ eye: "#12100f",+ highlight: "#f6e7d7",+ },+ {+ id: "pet-02",+ name: "Blue Pocket Bot",+ group: "Gadget Buddy",+ feature: "bell",+ bodyTop: "#4aa8d8",+ body: "#2f8fc4",+ bodyDark: "#2674a4",+ bodyLight: "#68bce5",+ bodySideLight: "#48a8d5",+ bodySideDark: "#1f6591",+ accent: "#d84e4a",+ accessory: "#f4c94f",+ eye: "#10141a",+ highlight: "#f7fbff",+ facePatch: "#f6fbff",+ cheek: "#d84e4a",+ },+ {+ id: "pet-03",+ name: "Spark Arcade Pal",+ group: "Electric Mascot",+ feature: "bolt",+ bodyTop: "#f2d45a",+ body: "#e6bd37",+ bodyDark: "#c89a2a",+ bodyLight: "#ffe37a",+ bodySideLight: "#f0cc4c",+ bodySideDark: "#b58724",+ accent: "#2f2520",+ accessory: "#df5145",+ eye: "#17120e",+ highlight: "#fff7c7",+ cheek: "#e94d43",+ },+ {+ id: "pet-04",+ name: "Pink Star Puff",+ group: "Star Puff",+ feature: "star",+ bodyTop: "#eba0b7",+ body: "#df7fa0",+ bodyDark: "#c76589",+ bodyLight: "#f2b6c8",+ bodySideLight: "#e993ac",+ bodySideDark: "#b95778",+ accent: "#c84d64",+ accessory: "#f0d862",+ eye: "#171016",+ highlight: "#fff0f6",+ cheek: "#e75c7a",+ },+ {+ id: "pet-05",+ name: "Leaf Sprite",+ group: "Forest Starter",+ feature: "leaf",+ bodyTop: "#76aa7b",+ body: "#5f9666",+ bodyDark: "#4d7c54",+ bodyLight: "#91bd8f",+ bodySideLight: "#72a875",+ bodySideDark: "#426d49",+ accent: "#2f6f46",+ accessory: "#d6e78a",+ eye: "#11160f",+ highlight: "#f0f8e4",+ facePatch: "#dceec2",+ },+ {+ id: "pet-06",+ name: "Ember Starter",+ group: "Fire Buddy",+ feature: "flame",+ bodyTop: "#df8755",+ body: "#ce6b3f",+ bodyDark: "#af5333",+ bodyLight: "#ee9d6b",+ bodySideLight: "#dd7b4c",+ bodySideDark: "#9a482c",+ accent: "#8d3d2f",+ accessory: "#f3c34b",+ eye: "#17100c",+ highlight: "#ffe8d4",+ cheek: "#e45842",+ },+ {+ id: "pet-07",+ name: "Ripple Buddy",+ group: "Water Buddy",+ feature: "fins",+ bodyTop: "#82b5d6",+ body: "#629dcc",+ bodyDark: "#4f82ad",+ bodyLight: "#9bc8e5",+ bodySideLight: "#73add6",+ bodySideDark: "#44749b",+ accent: "#5f6f8d",+ accessory: "#ead59a",+ eye: "#10151b",+ highlight: "#eff8ff",+ facePatch: "#d9eef8",+ },+ {+ id: "pet-08",+ name: "Moon Alley Cat",+ group: "Moon Cat",+ feature: "moon",+ bodyTop: "#4f4b69",+ body: "#3f3a59",+ bodyDark: "#332f49",+ bodyLight: "#67607e",+ bodySideLight: "#554f6d",+ bodySideDark: "#2b283e",+ accent: "#e5c85c",+ accessory: "#d66f91",+ eye: "#f5e8a7",+ highlight: "#fff6c8",+ cheek: "#cf6d8f",+ },+ {+ id: "pet-09",+ name: "Spore Runner",+ group: "Mushroom Runner",+ feature: "mushroom",+ bodyTop: "#e0524f",+ body: "#f0dcc6",+ bodyDark: "#d7c0aa",+ bodyLight: "#f7ead9",+ bodySideLight: "#f1dfcb",+ bodySideDark: "#c7aa95",+ accent: "#b83736",+ accessory: "#ffffff",+ eye: "#17120f",+ highlight: "#fff8ea",+ },+ {+ id: "pet-10",+ name: "Dash Quill",+ group: "Speed Mascot",+ feature: "spin",+ bodyTop: "#4e83d0",+ body: "#356dbd",+ bodyDark: "#2a579b",+ bodyLight: "#6896de",+ bodySideLight: "#477dd0",+ bodySideDark: "#244c88",+ accent: "#f2c45b",+ accessory: "#f2ece1",+ eye: "#10131a",+ highlight: "#eef4ff",+ facePatch: "#ead3b9",+ },+ {+ id: "pet-11",+ name: "Lemon Chomper",+ group: "Arcade Chomper",+ feature: "chomp",+ bodyTop: "#f0ce45",+ body: "#e5ba2f",+ bodyDark: "#c89924",+ bodyLight: "#ffe26c",+ bodySideLight: "#efc73f",+ bodySideDark: "#b18520",+ accent: "#1f1b18",+ accessory: "#f2845f",+ eye: "#15110d",+ highlight: "#fff2b6",+ },+ {+ id: "pet-12",+ name: "Lantern Ghost",+ group: "Round Ghost",+ feature: "ghost",+ bodyTop: "#d9dff0",+ body: "#c4cee6",+ bodyDark: "#aab6d2",+ bodyLight: "#edf2ff",+ bodySideLight: "#d3dced",+ bodySideDark: "#9aa8c6",+ accent: "#6d7da8",+ accessory: "#e77c9c",+ eye: "#151926",+ highlight: "#ffffff",+ },+ {+ id: "pet-13",+ name: "Red Cap Jumper",+ group: "Platform Pal",+ feature: "cap",+ bodyTop: "#d84f45",+ body: "#c5a17d",+ bodyDark: "#a98263",+ bodyLight: "#e0ba94",+ bodySideLight: "#d3ad86",+ bodySideDark: "#936f54",+ accent: "#2c4f99",+ accessory: "#f6e9d1",+ eye: "#16110d",+ highlight: "#fff2df",+ },+ {+ id: "pet-14",+ name: "Honey Cub",+ group: "Classic Toy",+ feature: "ears",+ bodyTop: "#e4b25a",+ body: "#d0993e",+ bodyDark: "#ad7d30",+ bodyLight: "#efc46d",+ bodySideLight: "#dba84d",+ bodySideDark: "#996d2a",+ accent: "#b54d3f",+ accessory: "#f4d991",+ eye: "#17110d",+ highlight: "#fff0c8",+ facePatch: "#f2d083",+ },+ {+ id: "pet-15",+ name: "Ribbon Puff",+ group: "Bow Buddy",+ feature: "bow",+ bodyTop: "#f2f0e8",+ body: "#e3ded4",+ bodyDark: "#c9c2b7",+ bodyLight: "#ffffff",+ bodySideLight: "#eee9df",+ bodySideDark: "#bab2a7",+ accent: "#d84b5b",+ accessory: "#f3cc56",+ eye: "#15110f",+ highlight: "#ffffff",+ cheek: "#df6d80",+ },+ {+ id: "pet-16",+ name: "Cozy Hood Cub",+ group: "Hooded Mascot",+ feature: "hood",+ bodyTop: "#ef9eba",+ body: "#e681a4",+ bodyDark: "#c96789",+ bodyLight: "#f5b6ca",+ bodySideLight: "#ee94b2",+ bodySideDark: "#b85878",+ accent: "#f0d6de",+ accessory: "#f3d66b",+ eye: "#171017",+ highlight: "#fff0f6",+ facePatch: "#fff6f2",+ },+ {+ id: "pet-17",+ name: "Masked Beetle",+ group: "Bug Hero",+ feature: "mask",+ bodyTop: "#6e617d",+ body: "#554761",+ bodyDark: "#41374b",+ bodyLight: "#837491",+ bodySideLight: "#655570",+ bodySideDark: "#382f41",+ accent: "#cf6f8e",+ accessory: "#f0d46a",+ eye: "#f7edf4",+ highlight: "#fff7ff",+ facePatch: "#ece0ea",+ },+ {+ id: "pet-18",+ name: "Round Forest Pal",+ group: "Forest Neighbor",+ feature: "ears",+ bodyTop: "#8c8d7d",+ body: "#74766a",+ bodyDark: "#606257",+ bodyLight: "#a0a293",+ bodySideLight: "#838578",+ bodySideDark: "#55574d",+ accent: "#d9d3b8",+ accessory: "#c6d68c",+ eye: "#121411",+ highlight: "#efead8",+ facePatch: "#dad4ba",+ },+ {+ id: "pet-19",+ name: "Soot Sprite",+ group: "Tiny Soot",+ feature: "soot",+ bodyTop: "#34343a",+ body: "#25262c",+ bodyDark: "#1d1e24",+ bodyLight: "#4a4b52",+ bodySideLight: "#383941",+ bodySideDark: "#171820",+ accent: "#6c6f7a",+ accessory: "#f0f0d8",+ eye: "#f7f7e8",+ highlight: "#ffffff",+ },+ {+ id: "pet-20",+ name: "Straw Field Pal",+ group: "Harvest Buddy",+ feature: "straw",+ bodyTop: "#d96a50",+ body: "#c65342",+ bodyDark: "#a74336",+ bodyLight: "#e47d64",+ bodySideLight: "#d0614d",+ bodySideDark: "#933a30",+ accent: "#2f5f93",+ accessory: "#e8c866",+ eye: "#15100d",+ highlight: "#ffe6d9",+ },+ {+ id: "pet-21",+ name: "Shadow Ninja Bean",+ group: "Ninja Mascot",+ feature: "ninja",+ bodyTop: "#e7a04d",+ body: "#d88432",+ bodyDark: "#b96c27",+ bodyLight: "#efb464",+ bodySideLight: "#df943e",+ bodySideDark: "#a25d22",+ accent: "#2d415c",+ accessory: "#ded5c6",+ eye: "#15100c",+ highlight: "#ffe7c8",+ facePatch: "#f3c78d",+ },+ {+ id: "pet-22",+ name: "Pearl Quest Cub",+ group: "Pearl Hero",+ feature: "pearl",+ bodyTop: "#e3a54e",+ body: "#ce8438",+ bodyDark: "#ac682e",+ bodyLight: "#efbc68",+ bodySideLight: "#db9345",+ bodySideDark: "#985a28",+ accent: "#476ca6",+ accessory: "#f0d464",+ eye: "#15100c",+ highlight: "#ffe8c4",+ },+ {+ id: "pet-23",+ name: "Wand Starling",+ group: "Magic Mascot",+ feature: "wand",+ bodyTop: "#f0a6c4",+ body: "#df87ad",+ bodyDark: "#c26b92",+ bodyLight: "#f5bad2",+ bodySideLight: "#e99ab9",+ bodySideDark: "#ad5d82",+ accent: "#d8b34a",+ accessory: "#e9d7ff",+ eye: "#171017",+ highlight: "#fff0f7",+ cheek: "#e76791",+ },+ {+ id: "pet-24",+ name: "Mecha Bean",+ group: "Tiny Mecha",+ feature: "mecha",+ bodyTop: "#d7dbe2",+ body: "#bdc3ce",+ bodyDark: "#9ea6b3",+ bodyLight: "#edf0f5",+ bodySideLight: "#cbd1da",+ bodySideDark: "#8d96a5",+ accent: "#d44d4a",+ accessory: "#f0c748",+ eye: "#151923",+ highlight: "#ffffff",+ },+ {+ id: "pet-25",+ name: "Bubble Slimelet",+ group: "Slime Buddy",+ feature: "slime",+ bodyTop: "#79b8e8",+ body: "#5aa0d8",+ bodyDark: "#4384ba",+ bodyLight: "#96cdf0",+ bodySideLight: "#70b3e3",+ bodySideDark: "#3975a6",+ accent: "#2a658f",+ accessory: "#f3f7ff",+ eye: "#101722",+ highlight: "#f5fbff",+ },+ {+ id: "pet-26",+ name: "Ink Courier",+ group: "Ink Runner",+ feature: "ink",+ bodyTop: "#75c8bb",+ body: "#54afa2",+ bodyDark: "#3f9188",+ bodyLight: "#90d9ce",+ bodySideLight: "#67c1b5",+ bodySideDark: "#377f77",+ accent: "#d7668f",+ accessory: "#e4f2ef",+ eye: "#101716",+ highlight: "#effffb",+ },+ {+ id: "pet-27",+ name: "Drum Marcher",+ group: "Rhythm Pal",+ feature: "drum",+ bodyTop: "#ef7f5f",+ body: "#df6349",+ bodyDark: "#bd4d3b",+ bodyLight: "#f39a7b",+ bodySideLight: "#e77358",+ bodySideDark: "#a84434",+ accent: "#4f78b6",+ accessory: "#f3e4c6",+ eye: "#15100d",+ highlight: "#fff0e4",+ },+ {+ id: "pet-28",+ name: "Sprout Forestling",+ group: "Sprout Buddy",+ feature: "sprout",+ bodyTop: "#a58f5d",+ body: "#8f7548",+ bodyDark: "#755f3a",+ bodyLight: "#b9a26e",+ bodySideLight: "#9b8354",+ bodySideDark: "#655233",+ accent: "#5d8b56",+ accessory: "#dfc86e",+ eye: "#15110c",+ highlight: "#f8ecc0",+ facePatch: "#d8be71",+ },+ {+ id: "pet-29",+ name: "Frost Star Pup",+ group: "Ice Pal",+ feature: "star",+ bodyTop: "#8aa7d8",+ body: "#6e91c8",+ bodyDark: "#5877aa",+ bodyLight: "#a1bce5",+ bodySideLight: "#7f9fd3",+ bodySideDark: "#4e6898",+ accent: "#f0cf5b",+ accessory: "#f3edf5",+ eye: "#10151c",+ highlight: "#eff5ff",+ cheek: "#d66d86",+ },+ {+ id: "pet-30",+ name: "Tiny Quest Cub",+ group: "Quest Mascot",+ feature: "bow",+ bodyTop: "#efa2c8",+ body: "#df84b2",+ bodyDark: "#c46999",+ bodyLight: "#f5b9d5",+ bodySideLight: "#eb96c2",+ bodySideDark: "#ad5a86",+ accent: "#cf4d78",+ accessory: "#f0d66a",+ eye: "#171016",+ highlight: "#fff0f8",+ cheek: "#df688f",+ },+];++const LICENSED_IP_PRESET_OVERRIDES = [+ { id: "pet-02", name: "Doraemon", group: "Licensed IP", feature: "bell", shape: "doraemon" },+ { id: "pet-03", name: "Pikachu", group: "Licensed IP", feature: "bolt", shape: "pikachu" },+ { id: "pet-04", name: "Kirby", group: "Licensed IP", feature: "star", shape: "kirby" },+ { id: "pet-05", name: "Bulbasaur", group: "Licensed IP", feature: "leaf", shape: "bulbasaur" },+ { id: "pet-06", name: "Charmander", group: "Licensed IP", feature: "flame", shape: "charmander" },+ { id: "pet-07", name: "Squirtle", group: "Licensed IP", feature: "fins", shape: "squirtle" },+ { id: "pet-08", name: "Minecraft Steve", group: "Licensed IP", feature: "visor", shape: "minecraft-steve" },+ { id: "pet-09", name: "Minecraft Creeper", group: "Licensed IP", feature: "mask", shape: "minecraft-creeper" },+ { id: "pet-10", name: "Minecraft Zombie", group: "Licensed IP", feature: "visor", shape: "minecraft-zombie" },+ { id: "pet-11", name: "Toad", group: "Licensed IP", feature: "mushroom", shape: "toad" },+ { id: "pet-12", name: "Sonic", group: "Licensed IP", feature: "spin", shape: "sonic" },+ { id: "pet-13", name: "Pac-Man", group: "Licensed IP", feature: "chomp", shape: "pacman" },+ { id: "pet-14", name: "Boo", group: "Licensed IP", feature: "ghost", shape: "boo" },+ { id: "pet-15", name: "Mario", group: "Licensed IP", feature: "cap", shape: "mario" },+ { id: "pet-16", name: "Winnie the Pooh", group: "Licensed IP", feature: "ears", shape: "pooh" },+ { id: "pet-17", name: "Hello Kitty", group: "Licensed IP", feature: "bow", shape: "hello-kitty" },+ { id: "pet-18", name: "My Melody", group: "Licensed IP", feature: "hood", shape: "my-melody" },+ { id: "pet-19", name: "Kuromi", group: "Licensed IP", feature: "mask", shape: "kuromi" },+ { id: "pet-20", name: "Totoro", group: "Licensed IP", feature: "ears", shape: "totoro" },+ { id: "pet-21", name: "Soot Sprite", group: "Licensed IP", feature: "soot", shape: "soot-sprite" },+ { id: "pet-22", name: "Luffy", group: "Licensed IP", feature: "straw", shape: "luffy" },+ { id: "pet-23", name: "Naruto", group: "Licensed IP", feature: "ninja", shape: "naruto" },+ { id: "pet-24", name: "Goku", group: "Licensed IP", feature: "pearl", shape: "goku" },+ { id: "pet-25", name: "Sailor Moon", group: "Licensed IP", feature: "wand", shape: "sailor-moon" },+ { id: "pet-26", name: "Gundam", group: "Licensed IP", feature: "mecha", shape: "gundam" },+ { id: "pet-27", name: "Dragon Quest Slime", group: "Licensed IP", feature: "slime", shape: "dragon-quest-slime" },+ { id: "pet-28", name: "Inkling", group: "Licensed IP", feature: "ink", shape: "inkling" },+ { id: "pet-29", name: "Snoopy", group: "Licensed IP", feature: "ears", shape: "snoopy" },+ { id: "pet-30", name: "Chopper", group: "Licensed IP", feature: "horns", shape: "chopper" },+] satisfies Array<+ Pick<CloudCodeMonsterPetPreset, "id" | "name" | "group" | "feature" | "shape">+>;++const LICENSED_IP_PRESET_OVERRIDE_BY_ID = new Map(+ LICENSED_IP_PRESET_OVERRIDES.map((preset) => [preset.id, preset])+);++export const CLOUD_CODE_MONSTER_PET_PRESETS: CloudCodeMonsterPetPreset[] =+ CLOUD_CODE_MONSTER_PET_PRESET_BASES.map((preset) => ({+ ...preset,+ ...LICENSED_IP_PRESET_OVERRIDE_BY_ID.get(preset.id),+ }));++export function getCloudCodeMonsterPreset(presetId?: string | null) {+ return (+ CLOUD_CODE_MONSTER_PET_PRESETS.find((preset) => preset.id === presetId) ??+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!+ );+}++export function readCloudCodeMonsterPetPresetId() {+ if (typeof localStorage === "undefined") {+ return CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id;+ }++ try {+ return getCloudCodeMonsterPreset(+ localStorage.getItem(CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY)+ ).id;+ } catch {+ return CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id;+ }+}++export function writeCloudCodeMonsterPetPresetId(presetId: string) {+ const nextPreset = getCloudCodeMonsterPreset(presetId);++ if (typeof localStorage !== "undefined") {+ try {+ localStorage.setItem(CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY, nextPreset.id);+ } catch {}+ }++ if (typeof window !== "undefined") {+ window.dispatchEvent(+ new CustomEvent(CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT, {+ detail: { presetId: nextPreset.id },+ })+ );+ }++ return nextPreset.id;+}++function isCloudCodeMonsterActivityId(+ value: string+): value is CloudCodeMonsterActivityId {+ return CLOUD_CODE_MONSTER_ACTIVITIES.some(+ (activity) => activity.id === value+ );+}++export function shouldRefreshCloudCodeMonsterActivity(+ updatedAt: number,+ now: number,+ refreshMs = CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS+) {+ return !Number.isFinite(updatedAt) || now - updatedAt >= refreshMs;+}++export function pickCloudCodeMonsterActivity(randomValue = Math.random()) {+ const safeRandom = Number.isFinite(randomValue) ? randomValue : 0;+ const index = Math.min(+ CLOUD_CODE_MONSTER_ACTIVITIES.length - 1,+ Math.max(0, Math.floor(safeRandom * CLOUD_CODE_MONSTER_ACTIVITIES.length))+ );++ return CLOUD_CODE_MONSTER_ACTIVITIES[index]!;+}++export function shouldCloudCodeMonsterAutoWalk(+ activityId: CloudCodeMonsterActivityId | null+) {+ return (+ activityId !== null &&+ CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS.includes(activityId)+ );+}++export function createCloudCodeMonsterWalkVelocity(+ randomValue = Math.random(),+ speed = CLOUD_CODE_MONSTER_AUTO_WALK_SPEED+): PetPoint {+ const safeRandom = Number.isFinite(randomValue) ? randomValue : 0;+ const angle = safeRandom * Math.PI * 2;+ const x = Math.cos(angle) * speed;+ const y = Math.sin(angle) * speed;++ if (Math.abs(x) < 0.2 && Math.abs(y) < 0.2) {+ return { x: speed, y: 0 };+ }++ return { x, y };+}++export function reflectCloudCodeMonsterWalk(+ position: PetPoint,+ velocity: PetPoint,+ bounds: PetBounds,+ size = CLOUD_CODE_MONSTER_SIZE,+ padding = 16+): ReflectedMonsterWalk {+ const minX = padding;+ const minY = padding;+ const maxX = Math.max(padding, bounds.width - size.width - padding);+ const maxY = Math.max(padding, bounds.height - size.height - padding);+ let nextX = position.x + velocity.x;+ let nextY = position.y + velocity.y;+ let nextVelocityX = velocity.x;+ let nextVelocityY = velocity.y;+ let reflectedX = false;+ let reflectedY = false;++ if (nextX < minX) {+ nextX = minX + (minX - nextX);+ nextVelocityX = Math.abs(nextVelocityX);+ reflectedX = true;+ } else if (nextX > maxX) {+ nextX = maxX - (nextX - maxX);+ nextVelocityX = -Math.abs(nextVelocityX);+ reflectedX = true;+ }++ if (nextY < minY) {+ nextY = minY + (minY - nextY);+ nextVelocityY = Math.abs(nextVelocityY);+ reflectedY = true;+ } else if (nextY > maxY) {+ nextY = maxY - (nextY - maxY);+ nextVelocityY = -Math.abs(nextVelocityY);+ reflectedY = true;+ }++ return {+ position: clampPetPosition(+ { x: nextX, y: nextY },+ bounds,+ size,+ padding+ ),+ velocity: { x: nextVelocityX, y: nextVelocityY },+ reflectedX,+ reflectedY,+ };+}++export function resolveCloudCodeMonsterActivityState(+ stored: StoredCloudCodeMonsterActivity | null,+ now = Date.now(),+ randomValue = Math.random()+): StoredCloudCodeMonsterActivity {+ if (+ stored &&+ stored.activityId &&+ isCloudCodeMonsterActivityId(stored.activityId) &&+ !shouldRefreshCloudCodeMonsterActivity(stored.updatedAt, now)+ ) {+ return stored;+ }++ return {+ activityId: pickCloudCodeMonsterActivity(randomValue).id,+ updatedAt: now,+ hiddenAt: null,+ };+}++export function createCloudCodeMonsterIdleState(+ now = Date.now()+): StoredCloudCodeMonsterActivity {+ return {+ activityId: null,+ updatedAt: now,+ hiddenAt: null,+ };+}++export function createCloudCodeMonsterHiddenState(+ current: StoredCloudCodeMonsterActivity | null,+ now = Date.now()+): StoredCloudCodeMonsterActivity {+ return {+ activityId: current?.activityId ?? null,+ updatedAt: current?.updatedAt ?? now,+ hiddenAt: now,+ };+}++export function createCloudCodeMonsterPreviewAwayState(+ now = Date.now()+): StoredCloudCodeMonsterActivity {+ const hiddenAt = now - CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS;++ return {+ activityId: null,+ updatedAt: hiddenAt,+ hiddenAt,+ };+}++export function simulateCloudCodeMonsterPreviewAway(now = Date.now()) {+ writeStoredActivity(createCloudCodeMonsterPreviewAwayState(now));+}++export function resolveCloudCodeMonsterPreviewComebackState(+ now = Date.now(),+ randomValue = Math.random()+) {+ return resolveCloudCodeMonsterVisibleState(+ createCloudCodeMonsterPreviewAwayState(now),+ now,+ randomValue+ );+}++export function resolveCloudCodeMonsterVisibleState(+ stored: StoredCloudCodeMonsterActivity | null,+ now = Date.now(),+ randomValue = Math.random()+): StoredCloudCodeMonsterActivity {+ if (stored?.hiddenAt) {+ if (shouldRefreshCloudCodeMonsterActivity(stored.hiddenAt, now)) {+ return {+ activityId: pickCloudCodeMonsterActivity(randomValue).id,+ updatedAt: now,+ hiddenAt: null,+ };+ }++ return {+ activityId: stored.activityId,+ updatedAt: stored.updatedAt,+ hiddenAt: null,+ };+ }++ if (!stored) {+ return resolveCloudCodeMonsterActivityState(stored, now, randomValue);+ }++ return {+ activityId: stored.activityId,+ updatedAt: stored.updatedAt,+ hiddenAt: null,+ };+}++export function calculateMonsterWalkIntensity(+ distancePx: number,+ elapsedMs: number+) {+ if (+ !Number.isFinite(distancePx) ||+ !Number.isFinite(elapsedMs) ||+ distancePx <= 0 ||+ elapsedMs <= 0+ ) {+ return 1;+ }++ const speedPxPerMs = distancePx / elapsedMs;+ return Math.min(2.8, Math.max(0.75, 0.75 + speedPxPerMs * 2.8));+}++export function hasViolentMonsterDirectionChange(+ previousDelta: PetPoint | null,+ nextDelta: PetPoint+) {+ if (!previousDelta) {+ return false;+ }++ const previousDistance = Math.hypot(previousDelta.x, previousDelta.y);+ const nextDistance = Math.hypot(nextDelta.x, nextDelta.y);++ if (+ previousDistance < CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_DISTANCE ||+ nextDistance < CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_DISTANCE+ ) {+ return false;+ }++ const dotProduct =+ previousDelta.x * nextDelta.x + previousDelta.y * nextDelta.y;+ return dotProduct / (previousDistance * nextDistance) <= -0.55;+}++export function isViolentMonsterDrag(+ distancePx: number,+ elapsedMs: number,+ sharpDirectionChange = false+) {+ if (+ !Number.isFinite(distancePx) ||+ !Number.isFinite(elapsedMs) ||+ distancePx < CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_DISTANCE ||+ elapsedMs <= 0 ||+ elapsedMs > CLOUD_CODE_MONSTER_VIOLENT_DRAG_MAX_ELAPSED_MS+ ) {+ return false;+ }++ const speedPxPerMs = distancePx / elapsedMs;+ if (sharpDirectionChange) {+ return speedPxPerMs >= CLOUD_CODE_MONSTER_VIOLENT_REVERSAL_MIN_SPEED;+ }++ return (+ distancePx >= CLOUD_CODE_MONSTER_VIOLENT_DRAG_STRONG_DISTANCE &&+ speedPxPerMs >= CLOUD_CODE_MONSTER_VIOLENT_DRAG_MIN_SPEED+ );+}++export function isMonsterFaintShakeEvent(+ distancePx: number,+ elapsedMs: number,+ sharpDirectionChange = false+) {+ if (+ !Number.isFinite(distancePx) ||+ !Number.isFinite(elapsedMs) ||+ distancePx < CLOUD_CODE_MONSTER_FAINT_DRAG_MIN_DISTANCE ||+ elapsedMs <= 0 ||+ elapsedMs > CLOUD_CODE_MONSTER_FAINT_DRAG_MAX_ELAPSED_MS+ ) {+ return false;+ }++ const speedPxPerMs = distancePx / elapsedMs;+ return sharpDirectionChange+ ? speedPxPerMs >= CLOUD_CODE_MONSTER_FAINT_REVERSAL_MIN_SPEED+ : speedPxPerMs >= CLOUD_CODE_MONSTER_FAINT_DRAG_MIN_SPEED;+}++export function shouldFaintFromMonsterShake(+ eventTimes: number[],+ now: number+) {+ const recentEvents = eventTimes.filter(+ (eventTime) => now - eventTime <= CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS+ );+ const firstEvent = recentEvents[0];++ return (+ recentEvents.length >= CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS &&+ typeof firstEvent === "number" &&+ now - firstEvent >= CLOUD_CODE_MONSTER_FAINT_MIN_SPAN_MS+ );+}++export function getMonsterFootstepIntervalMs(walkIntensity: number) {+ const safeIntensity = Number.isFinite(walkIntensity)+ ? Math.min(2.8, Math.max(0.75, walkIntensity))+ : 1;++ return Math.round(260 / safeIntensity);+}++export function getCloudCodeMonsterExpression(+ activityId: CloudCodeMonsterActivityId | null,+ reacting: boolean,+ shaken: boolean,+ fainted = false+): CloudCodeMonsterExpression {+ if (fainted) {+ return "fainted";+ }++ if (shaken) {+ return "shaken";+ }++ if (reacting) {+ return "shocked";+ }++ if (activityId === "sleeping") {+ return "sleeping";+ }++ return "idle";+}++function readStoredActivity(): StoredCloudCodeMonsterActivity | null {+ try {+ const raw = localStorage.getItem(CLOUD_CODE_MONSTER_STORAGE_KEY);+ if (!raw) return null;+ const parsed = JSON.parse(raw) as Partial<StoredCloudCodeMonsterActivity>;+ if (+ typeof parsed.activityId === "string" &&+ isCloudCodeMonsterActivityId(parsed.activityId) &&+ typeof parsed.updatedAt === "number"+ ) {+ return {+ activityId: parsed.activityId,+ updatedAt: parsed.updatedAt,+ hiddenAt:+ typeof parsed.hiddenAt === "number" && Number.isFinite(parsed.hiddenAt)+ ? parsed.hiddenAt+ : null,+ };+ }+ if (parsed.activityId === null && typeof parsed.updatedAt === "number") {+ return {+ activityId: null,+ updatedAt: parsed.updatedAt,+ hiddenAt:+ typeof parsed.hiddenAt === "number" && Number.isFinite(parsed.hiddenAt)+ ? parsed.hiddenAt+ : null,+ };+ }+ } catch {}++ return null;+}++function writeStoredActivity(activityState: StoredCloudCodeMonsterActivity) {+ try {+ localStorage.setItem(+ CLOUD_CODE_MONSTER_STORAGE_KEY,+ JSON.stringify(activityState)+ );+ } catch {}+}++function getBounds(boundary: HTMLElement | null): PetBounds {+ return {+ width: boundary?.clientWidth ?? window.innerWidth,+ height: boundary?.clientHeight ?? window.innerHeight,+ };+}++function findAgentPeekNode(+ boundary: HTMLElement | null,+ agentId: string+): HTMLElement | null {+ if (!boundary) {+ return null;+ }++ return (+ Array.from(+ boundary.querySelectorAll<HTMLElement>("[data-agent-node-id]")+ ).find((node) => node.dataset.agentNodeId === agentId) ?? null+ );+}++export function resolveCloudCodeMonsterPeekPosition(+ target: CloudCodeMonsterPeekTarget,+ boundary: HTMLElement | null,+ bounds: PetBounds+): PetPoint {+ if (target.agentId) {+ const agentNode = findAgentPeekNode(boundary, target.agentId);+ const boundaryRect = boundary?.getBoundingClientRect();+ const agentRect = agentNode?.getBoundingClientRect();++ if (agentRect && boundaryRect) {+ return clampPetPosition(+ {+ x:+ agentRect.left -+ boundaryRect.left ++ agentRect.width / 2 -+ CLOUD_CODE_MONSTER_SIZE.width / 2,+ y:+ agentRect.top -+ boundaryRect.top -+ CLOUD_CODE_MONSTER_SIZE.height * 0.18,+ },+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ );+ }+ }++ return clampPetPosition(+ {+ x: target.x - CLOUD_CODE_MONSTER_SIZE.width / 2,+ y: target.y - CLOUD_CODE_MONSTER_SIZE.height + 20,+ },+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ );+}++function getPointerPoint(+ event: ReactPointerEvent<HTMLButtonElement>,+ boundary: HTMLElement | null+): PetPoint {+ const boundaryRect = boundary?.getBoundingClientRect();++ return {+ x: event.clientX - (boundaryRect?.left ?? 0),+ y: event.clientY - (boundaryRect?.top ?? 0),+ };+}++function MonsterEyes({+ activityId,+ preset,+ reacting,+ shaken,+ fainted = false,+}: {+ activityId: CloudCodeMonsterActivityId | null;+ preset: CloudCodeMonsterPetPreset;+ reacting: boolean;+ shaken: boolean;+ fainted?: boolean;+}) {+ const expression = getCloudCodeMonsterExpression(+ activityId,+ reacting,+ shaken,+ fainted+ );++ if (expression === "fainted") {+ return (+ <>+ <rect x="43" y="39" width="5" height="5" fill={preset.eye} />+ <rect x="49" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="43" y="51" width="5" height="5" fill={preset.eye} />+ <rect x="49" y="39" width="5" height="5" fill={preset.eye} />+ <rect x="43" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="76" y="39" width="5" height="5" fill={preset.eye} />+ <rect x="82" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="76" y="51" width="5" height="5" fill={preset.eye} />+ <rect x="82" y="39" width="5" height="5" fill={preset.eye} />+ <rect x="76" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="58" y="64" width="14" height="4" fill={preset.eye} />+ </>+ );+ }++ if (expression === "shaken") {+ return (+ <>+ <rect x="45" y="40" width="5" height="5" fill={preset.eye} />+ <rect x="50" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="45" y="50" width="5" height="5" fill={preset.eye} />+ <rect x="82" y="40" width="5" height="5" fill={preset.eye} />+ <rect x="77" y="45" width="5" height="5" fill={preset.eye} />+ <rect x="82" y="50" width="5" height="5" fill={preset.eye} />+ <rect x="62" y="61" width="6" height="4" fill={preset.eye} />+ </>+ );+ }++ if (expression === "shocked") {+ return (+ <>+ <rect x="44" y="39" width="12" height="13" fill={preset.eye} />+ <rect x="76" y="39" width="12" height="13" fill={preset.eye} />+ <rect x="47" y="42" width="4" height="4" fill={preset.highlight} />+ <rect x="79" y="42" width="4" height="4" fill={preset.highlight} />+ <rect x="60" y="60" width="10" height="12" fill={preset.eye} />+ <rect x="62" y="62" width="6" height="3" fill="#332520" />+ </>+ );+ }++ if (expression === "sleeping") {+ return (+ <>+ <rect x="45" y="46" width="11" height="4" fill={preset.eye} />+ <rect x="76" y="46" width="11" height="4" fill={preset.eye} />+ </>+ );+ }++ return (+ <>+ <rect x="47" y="43" width="8" height="9" fill={preset.eye} />+ <rect x="78" y="43" width="8" height="9" fill={preset.eye} />+ <rect x="48" y="44" width="3" height="3" fill="#2c2521" />+ <rect x="79" y="44" width="3" height="3" fill="#2c2521" />+ </>+ );+}++function MonsterActivityAccessory({+ activityId,+ preset,+}: {+ activityId: CloudCodeMonsterActivityId | null;+ preset: CloudCodeMonsterPetPreset;+}) {+ if (!activityId) {+ return null;+ }++ if (activityId === "sleeping") {+ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-sleep">+ <g className="cloud-code-monster-pet-sleep-z">+ <rect x="88" y="20" width="11" height="3" fill={preset.accent} />+ <rect x="94" y="23" width="4" height="3" fill={preset.accent} />+ <rect x="91" y="26" width="4" height="3" fill={preset.accent} />+ <rect x="88" y="29" width="11" height="3" fill={preset.accent} />+ </g>+ <g className="cloud-code-monster-pet-sleep-z">+ <rect x="99" y="12" width="14" height="3" fill={preset.accent} />+ <rect x="108" y="15" width="4" height="3" fill={preset.accent} />+ <rect x="104" y="18" width="4" height="3" fill={preset.accent} />+ <rect x="100" y="21" width="4" height="3" fill={preset.accent} />+ <rect x="99" y="24" width="14" height="3" fill={preset.accent} />+ </g>+ <g className="cloud-code-monster-pet-sleep-z">+ <rect x="114" y="2" width="17" height="4" fill={preset.accent} />+ <rect x="126" y="6" width="4" height="4" fill={preset.accent} />+ <rect x="122" y="10" width="4" height="4" fill={preset.accent} />+ <rect x="118" y="14" width="4" height="4" fill={preset.accent} />+ <rect x="114" y="18" width="17" height="4" fill={preset.accent} />+ </g>+ </g>+ );+ }++ if (activityId === "reading") {+ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-book">+ <rect x="39" y="70" width="24" height="24" fill="#f5e6b8" />+ <rect x="65" y="70" width="24" height="24" fill="#ead394" />+ <rect x="63" y="70" width="4" height="26" fill="#6e4e2a" />+ <rect x="45" y="77" width="12" height="3" fill="#9a733d" />+ <rect x="71" y="77" width="12" height="3" fill="#9a733d" />+ <rect x="45" y="84" width="9" height="3" fill="#9a733d" />+ </g>+ );+ }++ if (activityId === "phone") {+ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-phone">+ <rect x="76" y="62" width="18" height="29" fill="#2b2724" />+ <rect x="80" y="66" width="10" height="17" fill="#9ed7d4" />+ <rect x="83" y="86" width="4" height="3" fill="#f4e7d2" />+ <rect className="cloud-code-monster-pet-phone-glow" x="80" y="66" width="10" height="17" fill="#d5fff6" />+ </g>+ );+ }++ if (activityId === "coding") {+ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-laptop">+ <rect x="35" y="68" width="58" height="25" fill="#2b2724" />+ <rect x="39" y="72" width="50" height="16" fill="#37322d" />+ <rect x="31" y="93" width="66" height="8" fill="#d8d0c6" />+ <rect x="47" y="77" width="10" height="3" fill={preset.accessory} />+ <rect x="58" y="80" width="4" height="3" fill={preset.accessory} />+ <rect x="66" y="83" width="13" height="3" fill={preset.accessory} />+ </g>+ );+ }++ if (activityId === "snacking") {+ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-snack">+ <rect x="77" y="65" width="17" height="21" fill="#efc06d" />+ <rect x="81" y="71" width="9" height="3" fill="#7d5723" />+ <rect x="81" y="78" width="7" height="3" fill="#7d5723" />+ <rect x="67" y="59" width="8" height="8" fill={preset.accent} />+ </g>+ );+ }++ return (+ <g className="cloud-code-monster-pet-accessory cloud-code-monster-pet-thought">+ <rect x="92" y="25" width="8" height="8" fill={preset.accent} />+ <rect x="104" y="17" width="6" height="6" fill={preset.bodyLight} />+ <rect x="113" y="9" width="5" height="5" fill={preset.highlight} />+ </g>+ );+}++function MonsterPresetFeature({+ preset,+}: {+ preset: CloudCodeMonsterPetPreset;+}) {+ const { feature } = preset;++ if (feature === "horns") {+ return (+ <>+ <rect x="29" y="20" width="10" height="8" fill={preset.accent} />+ <rect x="91" y="20" width="10" height="8" fill={preset.accent} />+ <rect x="34" y="16" width="7" height="7" fill={preset.accessory} />+ <rect x="88" y="16" width="7" height="7" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "ears") {+ return (+ <>+ <rect x="18" y="38" width="10" height="18" fill={preset.bodyDark} />+ <rect x="100" y="38" width="10" height="18" fill={preset.bodyDark} />+ <rect x="21" y="42" width="5" height="8" fill={preset.bodyLight} />+ <rect x="102" y="42" width="5" height="8" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "visor") {+ return (+ <>+ <rect x="41" y="36" width="47" height="5" fill={preset.accent} />+ <rect x="45" y="38" width="39" height="3" fill={preset.highlight} />+ </>+ );+ }++ if (feature === "antenna") {+ return (+ <>+ <rect x="62" y="15" width="5" height="13" fill={preset.accent} />+ <rect x="58" y="10" width="13" height="6" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "crown") {+ return (+ <>+ <rect x="43" y="18" width="8" height="10" fill={preset.accessory} />+ <rect x="60" y="14" width="8" height="14" fill={preset.accessory} />+ <rect x="77" y="18" width="8" height="10" fill={preset.accessory} />+ <rect x="42" y="26" width="44" height="5" fill={preset.accent} />+ </>+ );+ }++ if (feature === "bell") {+ return (+ <>+ <rect x="22" y="42" width="8" height="14" fill={preset.bodyDark} />+ <rect x="98" y="42" width="8" height="14" fill={preset.bodyDark} />+ <rect x="59" y="21" width="11" height="7" fill={preset.accent} />+ </>+ );+ }++ if (feature === "bolt") {+ return (+ <>+ <rect x="29" y="20" width="8" height="17" fill={preset.accent} />+ <rect x="91" y="20" width="8" height="17" fill={preset.accent} />+ <rect x="33" y="32" width="8" height="9" fill={preset.bodyTop} />+ <rect x="87" y="32" width="8" height="9" fill={preset.bodyTop} />+ </>+ );+ }++ if (feature === "star") {+ return (+ <>+ <rect x="60" y="13" width="8" height="24" fill={preset.accessory} />+ <rect x="52" y="21" width="24" height="8" fill={preset.accessory} />+ <rect x="56" y="17" width="16" height="16" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "leaf" || feature === "sprout") {+ return (+ <>+ <rect x="61" y="15" width="6" height="18" fill={preset.accent} />+ <rect x="49" y="18" width="16" height="10" fill={preset.accent} />+ <rect x="66" y="18" width="16" height="10" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "flame") {+ return (+ <>+ <rect x="58" y="9" width="12" height="20" fill={preset.accessory} />+ <rect x="52" y="18" width="9" height="14" fill={preset.accent} />+ <rect x="69" y="17" width="8" height="15" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "fins") {+ return (+ <>+ <rect x="18" y="45" width="10" height="18" fill={preset.accent} />+ <rect x="100" y="45" width="10" height="18" fill={preset.accent} />+ <rect x="55" y="18" width="18" height="10" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "moon") {+ return (+ <>+ <rect x="57" y="14" width="18" height="18" fill={preset.accessory} />+ <rect x="64" y="12" width="15" height="19" fill={preset.bodyTop} />+ <rect x="24" y="37" width="7" height="18" fill={preset.bodyDark} />+ <rect x="97" y="37" width="7" height="18" fill={preset.bodyDark} />+ </>+ );+ }++ if (feature === "mushroom") {+ return (+ <>+ <rect x="31" y="18" width="66" height="22" fill={preset.bodyTop} />+ <rect x="42" y="13" width="44" height="11" fill={preset.bodyTop} />+ <rect x="45" y="22" width="9" height="8" fill={preset.accessory} />+ <rect x="73" y="20" width="10" height="8" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "spin") {+ return (+ <>+ <rect x="47" y="17" width="34" height="9" fill={preset.bodyLight} />+ <rect x="37" y="24" width="14" height="8" fill={preset.bodyLight} />+ <rect x="78" y="24" width="13" height="8" fill={preset.bodyLight} />+ <rect x="29" y="31" width="11" height="7" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "chomp") {+ return (+ <>+ <rect x="88" y="48" width="14" height="8" fill={preset.highlight} />+ <rect x="88" y="60" width="14" height="8" fill={preset.highlight} />+ </>+ );+ }++ if (feature === "ghost" || feature === "slime") {+ return (+ <>+ <rect x="44" y="19" width="40" height="12" fill={preset.bodyLight} />+ <rect x="36" y="27" width="56" height="10" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "cap" || feature === "straw") {+ return (+ <>+ <rect x="34" y="18" width="58" height="12" fill={feature === "straw" ? preset.accessory : preset.bodyTop} />+ <rect x="45" y="12" width="36" height="10" fill={feature === "straw" ? preset.accessory : preset.bodyTop} />+ <rect x="58" y="22" width="14" height="5" fill={feature === "straw" ? preset.accent : preset.accessory} />+ </>+ );+ }++ if (feature === "bow" || feature === "hood") {+ return (+ <>+ <rect x="76" y="17" width="13" height="13" fill={preset.accent} />+ <rect x="91" y="17" width="13" height="13" fill={preset.accent} />+ <rect x="88" y="21" width="7" height="7" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "mask" || feature === "ninja") {+ return (+ <>+ <rect x="35" y="25" width="58" height="8" fill={preset.accent} />+ <rect x="48" y="18" width="12" height="10" fill={preset.accent} />+ <rect x="69" y="18" width="12" height="10" fill={preset.accent} />+ </>+ );+ }++ if (feature === "soot") {+ return (+ <>+ <rect x="27" y="25" width="8" height="8" fill={preset.bodyLight} />+ <rect x="92" y="23" width="9" height="9" fill={preset.bodyLight} />+ <rect x="61" y="12" width="7" height="7" fill={preset.bodyLight} />+ </>+ );+ }++ if (feature === "pearl" || feature === "wand") {+ return (+ <>+ <rect x="58" y="12" width="13" height="13" fill={preset.accessory} />+ <rect x="61" y="7" width="7" height="7" fill={preset.accent} />+ <rect x="73" y="17" width="9" height="9" fill={preset.accent} />+ </>+ );+ }++ if (feature === "mecha") {+ return (+ <>+ <rect x="29" y="24" width="12" height="13" fill={preset.accent} />+ <rect x="87" y="24" width="12" height="13" fill={preset.accent} />+ <rect x="51" y="18" width="27" height="9" fill={preset.accessory} />+ </>+ );+ }++ if (feature === "ink") {+ return (+ <>+ <rect x="35" y="19" width="12" height="16" fill={preset.accent} />+ <rect x="56" y="14" width="14" height="20" fill={preset.accent} />+ <rect x="80" y="19" width="12" height="16" fill={preset.accent} />+ </>+ );+ }++ if (feature === "drum") {+ return (+ <>+ <rect x="31" y="27" width="66" height="7" fill={preset.accent} />+ <rect x="41" y="18" width="46" height="10" fill={preset.accessory} />+ </>+ );+ }++ return (+ <>+ <rect x="38" y="30" width="10" height="4" fill={preset.bodyLight} />+ <rect x="80" y="30" width="10" height="4" fill={preset.bodyDark} />+ </>+ );+}++function MonsterPresetBodyMarks({+ preset,+}: {+ preset: CloudCodeMonsterPetPreset;+}) {+ const feature = preset.feature as string;++ return (+ <>+ {preset.facePatch ? (+ <>+ <rect x="40" y="39" width="48" height="34" fill={preset.facePatch} />+ <rect x="46" y="73" width="36" height="10" fill={preset.facePatch} />+ </>+ ) : null}+ {feature === "bell" ? (+ <>+ <rect x="50" y="74" width="28" height="6" fill={preset.accent} />+ <rect x="58" y="80" width="13" height="11" fill={preset.accessory} />+ <rect x="61" y="84" width="7" height="3" fill={preset.eye} />+ </>+ ) : null}+ {feature === "bolt" ? (+ <rect x="89" y="76" width="13" height="8" fill={preset.accent} />+ ) : null}+ {feature === "chomp" ? (+ <rect x="72" y="56" width="22" height="16" fill={preset.highlight} />+ ) : null}+ {feature === "ghost" ? (+ <>+ <rect x="28" y="91" width="12" height="8" fill={preset.bodyLight} />+ <rect x="52" y="91" width="12" height="8" fill={preset.bodyLight} />+ <rect x="76" y="91" width="12" height="8" fill={preset.bodyLight} />+ </>+ ) : null}+ {feature === "drum" ? (+ <rect x="31" y="55" width="66" height="8" fill={preset.accessory} />+ ) : null}+ {feature === "mecha" ? (+ <>+ <rect x="41" y="35" width="45" height="6" fill={preset.accent} />+ <rect x="57" y="58" width="14" height="9" fill={preset.accessory} />+ </>+ ) : null}+ {preset.cheek ? (+ <>+ <rect x="36" y="58" width="8" height="7" fill={preset.cheek} />+ <rect x="86" y="58" width="8" height="7" fill={preset.cheek} />+ </>+ ) : null}+ </>+ );+}++function DirectPixelEyes({+ activityId,+ preset,+ reacting,+ shaken,+ fainted = false,+ leftX = 47,+ rightX = 78,+ y = 43,+ color,+ highlightColor,+ singleEye = false,+ mouthX = 61,+ mouthY,+ mouthWidth = 10,+ mouthHeight = 4,+ mouthColor,+ mouthStyle = "flat",+}: {+ activityId: CloudCodeMonsterActivityId | null;+ preset: CloudCodeMonsterPetPreset;+ reacting: boolean;+ shaken: boolean;+ fainted?: boolean;+ leftX?: number;+ rightX?: number;+ y?: number;+ color?: string;+ highlightColor?: string;+ singleEye?: boolean;+ mouthX?: number;+ mouthY?: number;+ mouthWidth?: number;+ mouthHeight?: number;+ mouthColor?: string;+ mouthStyle?: "flat" | "open" | "smile" | "none";+}) {+ const expression = getCloudCodeMonsterExpression(+ activityId,+ reacting,+ shaken,+ fainted+ );+ const eye = color ?? preset.eye;+ const highlight = highlightColor ?? preset.highlight;+ const faceMouthY = mouthY ?? y + 21;+ const faceMouthColor = mouthColor ?? eye;+ const secondEyeX = singleEye ? null : rightX;+ const renderEyeBlock = (+ eyeX: number,+ eyeY: number,+ width = 8,+ height = 9,+ includeHighlight = true+ ) => (+ <>+ <rect x={eyeX} y={eyeY} width={width} height={height} fill={eye} />+ {includeHighlight ? (+ <rect x={eyeX + 1} y={eyeY + 1} width="3" height="3" fill={highlight} />+ ) : null}+ </>+ );+ const renderMouth = (+ style = mouthStyle,+ x = mouthX,+ mouthTop = faceMouthY,+ width = mouthWidth,+ height = mouthHeight+ ) => {+ if (style === "none") {+ return null;+ }++ if (style === "open") {+ return (+ <>+ <rect x={x} y={mouthTop} width={width} height={height + 7} fill={faceMouthColor} />+ <rect x={x + 2} y={mouthTop + 2} width={Math.max(3, width - 4)} height="3" fill="#332520" />+ </>+ );+ }++ if (style === "smile") {+ return (+ <>+ <rect x={x} y={mouthTop} width={width} height={height} fill={faceMouthColor} />+ <rect x={x - 3} y={mouthTop - 3} width="4" height={height} fill={faceMouthColor} />+ <rect x={x + width - 1} y={mouthTop - 3} width="4" height={height} fill={faceMouthColor} />+ </>+ );+ }++ return <rect x={x} y={mouthTop} width={width} height={height} fill={faceMouthColor} />;+ };++ if (expression === "fainted") {+ return (+ <>+ <rect x={leftX - 3} y={y - 3} width="5" height="5" fill={eye} />+ <rect x={leftX + 3} y={y + 3} width="5" height="5" fill={eye} />+ <rect x={leftX + 3} y={y - 3} width="5" height="5" fill={eye} />+ <rect x={leftX - 3} y={y + 3} width="5" height="5" fill={eye} />+ {secondEyeX === null ? null : (+ <>+ <rect x={secondEyeX - 3} y={y - 3} width="5" height="5" fill={eye} />+ <rect x={secondEyeX + 3} y={y + 3} width="5" height="5" fill={eye} />+ <rect x={secondEyeX + 3} y={y - 3} width="5" height="5" fill={eye} />+ <rect x={secondEyeX - 3} y={y + 3} width="5" height="5" fill={eye} />+ </>+ )}+ {renderMouth("flat", mouthX - 2, faceMouthY + 1, mouthWidth + 5, mouthHeight)}+ </>+ );+ }++ if (expression === "shaken") {+ return (+ <>+ <rect x={leftX - 2} y={y - 2} width="5" height="5" fill={eye} />+ <rect x={leftX + 3} y={y + 3} width="5" height="5" fill={eye} />+ <rect x={leftX - 2} y={y + 8} width="5" height="5" fill={eye} />+ {secondEyeX === null ? null : (+ <>+ <rect x={secondEyeX + 3} y={y - 2} width="5" height="5" fill={eye} />+ <rect x={secondEyeX - 2} y={y + 3} width="5" height="5" fill={eye} />+ <rect x={secondEyeX + 3} y={y + 8} width="5" height="5" fill={eye} />+ </>+ )}+ {renderMouth("open", mouthX, faceMouthY, Math.max(6, mouthWidth - 1), mouthHeight)}+ </>+ );+ }++ if (expression === "shocked") {+ return (+ <>+ <rect x={leftX - 3} y={y - 3} width="12" height="13" fill={eye} />+ {secondEyeX === null ? null : (+ <rect x={secondEyeX - 3} y={y - 3} width="12" height="13" fill={eye} />+ )}+ <rect x={leftX} y={y} width="4" height="4" fill={highlight} />+ {secondEyeX === null ? null : (+ <rect x={secondEyeX} y={y} width="4" height="4" fill={highlight} />+ )}+ {renderMouth("open", mouthX, faceMouthY - 3, mouthWidth, mouthHeight + 1)}+ </>+ );+ }++ if (expression === "sleeping") {+ return (+ <>+ <rect x={leftX - 2} y={y + 3} width="12" height="4" fill={eye} />+ {secondEyeX === null ? null : (+ <rect x={secondEyeX - 2} y={y + 3} width="12" height="4" fill={eye} />+ )}+ {renderMouth("flat", mouthX, faceMouthY, mouthWidth, mouthHeight)}+ </>+ );+ }++ return (+ <>+ {renderEyeBlock(leftX, y)}+ {secondEyeX === null ? null : renderEyeBlock(secondEyeX, y)}+ {renderMouth()}+ </>+ );+}++function MonsterDirectPixelCharacter({+ preset,+ activityId,+ reacting,+ shaken,+ fainted,+}: {+ preset: CloudCodeMonsterPetPreset;+ activityId: CloudCodeMonsterActivityId | null;+ reacting: boolean;+ shaken: boolean;+ fainted: boolean;+}) {+ const shape = preset.shape;++ switch (shape) {+ case "doraemon":+ return (+ <>+ <rect x="36" y="23" width="56" height="13" fill="#2d9bd3" />+ <rect x="28" y="36" width="72" height="45" fill="#2d9bd3" />+ <rect x="37" y="43" width="54" height="36" fill="#f8fbff" />+ <rect x="44" y="80" width="40" height="22" fill="#2d9bd3" />+ <rect x="34" y="81" width="60" height="6" fill="#d9403f" />+ <rect x="58" y="87" width="13" height="12" fill="#f0bf36" />+ <rect className="cloud-code-monster-pet-left-foot" x="36" y="103" width="21" height="11" fill="#f8fbff" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="103" width="21" height="11" fill="#f8fbff" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={45} rightX={76} y={44} mouthX={56} mouthY={71} mouthWidth={18} mouthHeight={3} mouthColor="#111318" mouthStyle="smile" />+ <rect x="62" y="55" width="6" height="6" fill="#d9403f" />+ <rect x="62" y="61" width="3" height="12" fill="#111318" />+ <rect x="54" y="73" width="20" height="3" fill="#111318" />+ </>+ );+ case "pikachu":+ return (+ <>+ <rect x="31" y="15" width="10" height="31" fill="#2b2319" />+ <rect x="87" y="15" width="10" height="31" fill="#2b2319" />+ <rect x="36" y="25" width="10" height="27" fill="#f1ce43" />+ <rect x="82" y="25" width="10" height="27" fill="#f1ce43" />+ <rect x="37" y="39" width="54" height="14" fill="#f4d64f" />+ <rect x="29" y="53" width="70" height="44" fill="#f1c93b" />+ <rect x="93" y="59" width="19" height="10" fill="#8d5d28" />+ <rect x="105" y="49" width="10" height="20" fill="#f1c93b" />+ <rect className="cloud-code-monster-pet-left-foot" x="37" y="96" width="18" height="15" fill="#d7a72e" />+ <rect className="cloud-code-monster-pet-right-foot" x="74" y="96" width="18" height="15" fill="#d7a72e" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={45} rightX={77} y={54} />+ <rect x="34" y="68" width="11" height="10" fill="#e84b43" />+ <rect x="84" y="68" width="11" height="10" fill="#e84b43" />+ </>+ );+ case "kirby":+ return (+ <>+ <rect x="42" y="29" width="44" height="9" fill="#f2a8bd" />+ <rect x="29" y="38" width="70" height="52" fill="#ee86a7" />+ <rect x="40" y="90" width="48" height="13" fill="#d96c91" />+ <rect x="18" y="57" width="17" height="18" fill="#ee86a7" />+ <rect x="93" y="57" width="17" height="18" fill="#ee86a7" />+ <rect className="cloud-code-monster-pet-left-foot" x="35" y="100" width="22" height="12" fill="#c94d62" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="100" width="22" height="12" fill="#c94d62" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={75} y={51} color="#24335b" mouthX={61} mouthY={66} mouthWidth={10} mouthHeight={5} mouthColor="#7c2448" mouthStyle="smile" />+ <rect x="43" y="69" width="9" height="8" fill="#e95d77" />+ <rect x="83" y="69" width="9" height="8" fill="#e95d77" />+ </>+ );+ case "bulbasaur":+ return (+ <>+ <rect x="45" y="20" width="38" height="18" fill="#5e9f5b" />+ <rect x="38" y="31" width="52" height="22" fill="#74b86b" />+ <rect x="30" y="50" width="68" height="38" fill="#69b8a6" />+ <rect x="20" y="64" width="22" height="23" fill="#69b8a6" />+ <rect x="86" y="64" width="22" height="23" fill="#4c9f92" />+ <rect className="cloud-code-monster-pet-left-foot" x="29" y="88" width="16" height="16" fill="#4c9f92" />+ <rect className="cloud-code-monster-pet-right-foot" x="82" y="88" width="16" height="16" fill="#408b80" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={44} rightX={74} y={56} color="#b33b42" />+ <rect x="53" y="75" width="7" height="4" fill="#2d5d56" />+ <rect x="67" y="75" width="7" height="4" fill="#2d5d56" />+ </>+ );+ case "charmander":+ return (+ <>+ <rect x="38" y="29" width="50" height="13" fill="#e88743" />+ <rect x="30" y="42" width="66" height="45" fill="#d76d35" />+ <rect x="41" y="70" width="39" height="28" fill="#f2c878" />+ <rect x="88" y="70" width="17" height="10" fill="#d76d35" />+ <rect x="101" y="58" width="9" height="15" fill="#f0b540" />+ <rect x="103" y="51" width="7" height="9" fill="#e24c38" />+ <rect className="cloud-code-monster-pet-left-foot" x="36" y="98" width="17" height="14" fill="#b9542c" />+ <rect className="cloud-code-monster-pet-right-foot" x="75" y="98" width="17" height="14" fill="#b9542c" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={77} y={50} />+ </>+ );+ case "squirtle":+ return (+ <>+ <rect x="39" y="27" width="50" height="13" fill="#83b7d8" />+ <rect x="31" y="40" width="66" height="39" fill="#6aa4cf" />+ <rect x="37" y="76" width="55" height="25" fill="#b9854a" />+ <rect x="45" y="80" width="39" height="17" fill="#ecd59a" />+ <rect x="16" y="62" width="20" height="16" fill="#6aa4cf" />+ <rect x="92" y="62" width="20" height="16" fill="#6aa4cf" />+ <rect className="cloud-code-monster-pet-left-foot" x="35" y="101" width="18" height="12" fill="#5c92bd" />+ <rect className="cloud-code-monster-pet-right-foot" x="76" y="101" width="18" height="12" fill="#5c92bd" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={46} rightX={76} y={48} />+ </>+ );+ case "minecraft-steve":+ return (+ <>+ <rect x="42" y="18" width="44" height="14" fill="#5b3625" />+ <rect x="36" y="32" width="56" height="42" fill="#b98363" />+ <rect x="36" y="74" width="56" height="28" fill="#2b9aa0" />+ <rect x="28" y="78" width="11" height="28" fill="#b98363" />+ <rect x="89" y="78" width="11" height="28" fill="#b98363" />+ <rect className="cloud-code-monster-pet-left-foot" x="42" y="102" width="18" height="16" fill="#31549a" />+ <rect className="cloud-code-monster-pet-right-foot" x="68" y="102" width="18" height="16" fill="#31549a" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={73} y={46} color="#2b2018" mouthX={57} mouthY={59} mouthWidth={14} mouthHeight={4} mouthColor="#6c3f2b" />+ <rect x="57" y="59" width="14" height="4" fill="#6c3f2b" />+ </>+ );+ case "minecraft-creeper":+ return (+ <>+ <rect x="37" y="20" width="54" height="54" fill="#5aaa4c" />+ <rect x="44" y="27" width="10" height="10" fill="#78c763" />+ <rect x="72" y="34" width="11" height="11" fill="#458d3d" />+ <rect x="42" y="74" width="44" height="32" fill="#4b963f" />+ <rect className="cloud-code-monster-pet-left-foot" x="34" y="101" width="18" height="15" fill="#397b35" />+ <rect className="cloud-code-monster-pet-left-foot" x="54" y="101" width="18" height="15" fill="#397b35" />+ <rect className="cloud-code-monster-pet-right-foot" x="76" y="101" width="18" height="15" fill="#397b35" />+ <rect x="47" y="40" width="11" height="13" fill="#151711" />+ <rect x="70" y="40" width="11" height="13" fill="#151711" />+ <rect x="59" y="54" width="10" height="18" fill="#151711" />+ <rect x="51" y="64" width="10" height="8" fill="#151711" />+ <rect x="67" y="64" width="10" height="8" fill="#151711" />+ </>+ );+ case "minecraft-zombie":+ return (+ <>+ <rect x="38" y="22" width="52" height="49" fill="#77a86c" />+ <rect x="37" y="71" width="54" height="31" fill="#248f9e" />+ <rect x="25" y="74" width="14" height="30" fill="#77a86c" />+ <rect x="89" y="74" width="14" height="30" fill="#77a86c" />+ <rect className="cloud-code-monster-pet-left-foot" x="41" y="102" width="18" height="16" fill="#5d4aa1" />+ <rect className="cloud-code-monster-pet-right-foot" x="69" y="102" width="18" height="16" fill="#5d4aa1" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={73} y={43} color="#2b221d" mouthX={57} mouthY={58} mouthWidth={14} mouthHeight={4} mouthColor="#2b221d" />+ <rect x="57" y="58" width="14" height="4" fill="#2b221d" />+ </>+ );+ case "toad":+ return (+ <>+ <rect x="29" y="19" width="70" height="22" fill="#fff3e4" />+ <rect x="38" y="8" width="52" height="18" fill="#fff3e4" />+ <rect x="42" y="20" width="16" height="13" fill="#d84741" />+ <rect x="70" y="16" width="15" height="13" fill="#d84741" />+ <rect x="39" y="43" width="50" height="40" fill="#f0c89c" />+ <rect x="36" y="78" width="56" height="24" fill="#f7f1dc" />+ <rect x="31" y="80" width="11" height="20" fill="#2d5ca8" />+ <rect x="86" y="80" width="11" height="20" fill="#2d5ca8" />+ <rect className="cloud-code-monster-pet-left-foot" x="38" y="102" width="17" height="12" fill="#7a5735" />+ <rect className="cloud-code-monster-pet-right-foot" x="73" y="102" width="17" height="12" fill="#7a5735" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={74} y={54} />+ </>+ );+ case "sonic":+ return (+ <>+ <rect x="33" y="22" width="17" height="13" fill="#2d62b3" />+ <rect x="43" y="13" width="22" height="14" fill="#2d62b3" />+ <rect x="61" y="17" width="23" height="12" fill="#2d62b3" />+ <rect x="36" y="31" width="55" height="42" fill="#356fc1" />+ <rect x="42" y="48" width="40" height="25" fill="#e4c19b" />+ <rect x="44" y="74" width="39" height="26" fill="#356fc1" />+ <rect className="cloud-code-monster-pet-left-foot" x="31" y="99" width="26" height="12" fill="#d9463f" />+ <rect className="cloud-code-monster-pet-right-foot" x="71" y="99" width="26" height="12" fill="#d9463f" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={74} y={42} />+ </>+ );+ case "pacman":+ return (+ <>+ <rect x="43" y="28" width="45" height="11" fill="#f1d34a" />+ <rect x="31" y="39" width="56" height="49" fill="#edc738" />+ <rect x="42" y="88" width="44" height="11" fill="#cfa62a" />+ <rect x="82" y="52" width="20" height="11" fill="#fff8de" />+ <rect x="82" y="65" width="15" height="11" fill="#fff8de" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={58} rightX={58} y={43} singleEye mouthX={84} mouthY={62} mouthWidth={15} mouthHeight={7} mouthColor="#15110d" mouthStyle="open" />+ </>+ );+ case "boo":+ return (+ <>+ <rect x="39" y="26" width="50" height="12" fill="#f0f2fb" />+ <rect x="29" y="38" width="70" height="48" fill="#e0e5f3" />+ <rect x="23" y="55" width="13" height="18" fill="#e0e5f3" />+ <rect x="92" y="55" width="13" height="18" fill="#d0d8ea" />+ <rect x="31" y="86" width="13" height="12" fill="#e0e5f3" />+ <rect x="56" y="86" width="13" height="12" fill="#e0e5f3" />+ <rect x="81" y="86" width="13" height="12" fill="#e0e5f3" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={45} rightX={77} y={47} mouthX={56} mouthY={63} mouthWidth={19} mouthHeight={10} mouthColor="#df7198" mouthStyle="open" />+ <rect x="57" y="63" width="18" height="13" fill="#df7198" />+ </>+ );+ case "mario":+ return (+ <>+ <rect x="35" y="18" width="58" height="12" fill="#d34437" />+ <rect x="46" y="9" width="35" height="12" fill="#d34437" />+ <rect x="39" y="31" width="50" height="38" fill="#c8916b" />+ <rect x="52" y="55" width="28" height="8" fill="#4c2d20" />+ <rect x="36" y="69" width="56" height="32" fill="#2f5aa8" />+ <rect x="30" y="71" width="14" height="28" fill="#d34437" />+ <rect x="84" y="71" width="14" height="28" fill="#d34437" />+ <rect className="cloud-code-monster-pet-left-foot" x="35" y="101" width="21" height="13" fill="#6c3e27" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="101" width="21" height="13" fill="#6c3e27" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={74} y={41} />+ </>+ );+ case "pooh":+ return (+ <>+ <rect x="31" y="30" width="13" height="14" fill="#d99b39" />+ <rect x="84" y="30" width="13" height="14" fill="#c88730" />+ <rect x="38" y="26" width="52" height="46" fill="#e0a33f" />+ <rect x="32" y="72" width="64" height="29" fill="#c9473c" />+ <rect className="cloud-code-monster-pet-left-foot" x="37" y="101" width="18" height="14" fill="#b87a2e" />+ <rect className="cloud-code-monster-pet-right-foot" x="74" y="101" width="18" height="14" fill="#b87a2e" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={75} y={47} />+ <rect x="61" y="59" width="7" height="5" fill="#4a2c1e" />+ </>+ );+ case "hello-kitty":+ return (+ <>+ <rect x="28" y="25" width="16" height="18" fill="#f6f3ea" />+ <rect x="84" y="25" width="16" height="18" fill="#f6f3ea" />+ <rect x="33" y="31" width="62" height="45" fill="#f6f3ea" />+ <rect x="76" y="24" width="13" height="13" fill="#d94c5e" />+ <rect x="91" y="24" width="13" height="13" fill="#d94c5e" />+ <rect x="87" y="28" width="8" height="8" fill="#e8c94a" />+ <rect x="39" y="76" width="50" height="26" fill="#d94c5e" />+ <rect className="cloud-code-monster-pet-left-foot" x="38" y="102" width="18" height="11" fill="#f6f3ea" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="102" width="18" height="11" fill="#f6f3ea" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={46} rightX={78} y={49} color="#25201f" highlightColor="#fffdfa" mouthX={61} mouthY={64} mouthWidth={7} mouthHeight={2} mouthColor="#7b4542" mouthStyle="smile" />+ <rect x="61" y="58" width="8" height="6" fill="#e0ad31" />+ <rect x="63" y="59" width="4" height="3" fill="#f6d75b" />+ <rect x="39" y="58" width="7" height="2" fill="#25201f" opacity="0.72" />+ <rect x="82" y="58" width="7" height="2" fill="#25201f" opacity="0.72" />+ </>+ );+ case "my-melody":+ case "kuromi": {+ const isKuromi = shape === "kuromi";+ const hood = isKuromi ? "#51425c" : "#e78eaa";+ const accent = isKuromi ? "#dd6d99" : "#d84c64";+ return (+ <>+ <rect x="27" y="12" width="13" height="42" fill={hood} />+ <rect x="88" y="12" width="13" height="42" fill={hood} />+ <rect x="35" y="25" width="58" height="54" fill={hood} />+ <rect x="42" y="39" width="44" height="34" fill="#fff5ee" />+ {isKuromi ? (+ <>+ <rect x="57" y="28" width="14" height="10" fill="#f2e9e1" />+ <rect x="60" y="31" width="3" height="3" fill="#51425c" />+ <rect x="66" y="31" width="3" height="3" fill="#51425c" />+ <rect x="63" y="35" width="3" height="2" fill="#51425c" />+ </>+ ) : null}+ <rect x="48" y="57" width="7" height="6" fill={isKuromi ? "#f2dfe8" : "#f3d6dc"} />+ <rect x="76" y="57" width="7" height="6" fill={isKuromi ? "#f2dfe8" : "#f3d6dc"} />+ <rect x="38" y="79" width="52" height="25" fill={accent} />+ <rect className="cloud-code-monster-pet-left-foot" x="39" y="104" width="17" height="10" fill={hood} />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="104" width="17" height="10" fill={hood} />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={50} rightX={75} y={49} color="#31232f" highlightColor="#fff5ee" mouthX={60} mouthY={64} mouthWidth={9} mouthHeight={3} mouthColor="#7a3c55" mouthStyle="smile" />+ </>+ );+ }+ case "totoro":+ return (+ <>+ <rect x="38" y="16" width="10" height="22" fill="#74766a" />+ <rect x="80" y="16" width="10" height="22" fill="#74766a" />+ <rect x="36" y="30" width="56" height="17" fill="#85877a" />+ <rect x="24" y="47" width="80" height="54" fill="#74766a" />+ <rect x="38" y="65" width="52" height="33" fill="#dad3b8" />+ <rect x="46" y="72" width="8" height="5" fill="#74766a" />+ <rect x="61" y="72" width="8" height="5" fill="#74766a" />+ <rect x="76" y="72" width="8" height="5" fill="#74766a" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={47} rightX={76} y={47} />+ </>+ );+ case "soot-sprite":+ return (+ <>+ <rect x="38" y="29" width="52" height="9" fill="#2b2c31" />+ <rect x="27" y="38" width="74" height="45" fill="#1f2026" />+ <rect x="36" y="83" width="56" height="12" fill="#17181e" />+ <rect x="22" y="45" width="9" height="9" fill="#1f2026" />+ <rect x="97" y="48" width="9" height="9" fill="#1f2026" />+ <rect x="48" y="52" width="14" height="14" fill="#f5f2dc" />+ <rect x="69" y="52" width="14" height="14" fill="#f5f2dc" />+ <rect x="53" y="56" width="5" height="6" fill="#17181e" />+ <rect x="74" y="56" width="5" height="6" fill="#17181e" />+ </>+ );+ case "luffy":+ return (+ <>+ <rect x="31" y="18" width="66" height="9" fill="#e7c65d" />+ <rect x="40" y="8" width="48" height="15" fill="#e7c65d" />+ <rect x="43" y="22" width="42" height="6" fill="#c84f3e" />+ <rect x="38" y="31" width="52" height="39" fill="#d89064" />+ <rect x="36" y="70" width="56" height="31" fill="#cf4d3f" />+ <rect x="45" y="82" width="38" height="20" fill="#2c5ca0" />+ <rect className="cloud-code-monster-pet-left-foot" x="39" y="102" width="18" height="13" fill="#d89064" />+ <rect className="cloud-code-monster-pet-right-foot" x="71" y="102" width="18" height="13" fill="#d89064" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={75} y={44} />+ </>+ );+ case "naruto":+ return (+ <>+ <rect x="34" y="18" width="11" height="16" fill="#e0a641" />+ <rect x="48" y="12" width="10" height="22" fill="#e0a641" />+ <rect x="61" y="14" width="10" height="20" fill="#e0a641" />+ <rect x="75" y="18" width="11" height="16" fill="#e0a641" />+ <rect x="36" y="32" width="56" height="9" fill="#2f4560" />+ <rect x="55" y="34" width="18" height="6" fill="#c9ccd2" />+ <rect x="38" y="41" width="52" height="34" fill="#dfa06c" />+ <rect x="34" y="75" width="60" height="31" fill="#e27a31" />+ <rect className="cloud-code-monster-pet-left-foot" x="39" y="106" width="18" height="10" fill="#2f4560" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="106" width="18" height="10" fill="#2f4560" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={75} y={50} />+ </>+ );+ case "goku":+ return (+ <>+ <rect x="35" y="14" width="13" height="23" fill="#191817" />+ <rect x="50" y="6" width="13" height="31" fill="#191817" />+ <rect x="66" y="9" width="13" height="28" fill="#191817" />+ <rect x="80" y="18" width="12" height="19" fill="#191817" />+ <rect x="38" y="35" width="52" height="38" fill="#dc9864" />+ <rect x="33" y="73" width="62" height="31" fill="#df7a30" />+ <rect x="52" y="77" width="24" height="29" fill="#244f91" />+ <rect className="cloud-code-monster-pet-left-foot" x="39" y="104" width="19" height="12" fill="#244f91" />+ <rect className="cloud-code-monster-pet-right-foot" x="71" y="104" width="19" height="12" fill="#244f91" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={75} y={47} />+ </>+ );+ case "sailor-moon":+ return (+ <>+ <rect x="29" y="24" width="14" height="14" fill="#e6c44e" />+ <rect x="85" y="24" width="14" height="14" fill="#e6c44e" />+ <rect x="40" y="12" width="48" height="31" fill="#e6c44e" />+ <rect x="38" y="38" width="52" height="35" fill="#e6a96b" />+ <rect x="34" y="73" width="60" height="31" fill="#f3eee9" />+ <rect x="42" y="72" width="44" height="8" fill="#2f5ca9" />+ <rect x="58" y="80" width="12" height="19" fill="#d9495d" />+ <rect className="cloud-code-monster-pet-left-foot" x="38" y="104" width="18" height="10" fill="#d9495d" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="104" width="18" height="10" fill="#d9495d" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={75} y={48} />+ </>+ );+ case "gundam":+ return (+ <>+ <rect x="38" y="25" width="52" height="39" fill="#d7dbe2" />+ <rect x="31" y="28" width="10" height="18" fill="#d94b43" />+ <rect x="87" y="28" width="10" height="18" fill="#d94b43" />+ <rect x="54" y="17" width="7" height="17" fill="#e8c64c" />+ <rect x="68" y="17" width="7" height="17" fill="#e8c64c" />+ <rect x="45" y="44" width="38" height="8" fill="#26344f" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={50} rightX={70} y={44} color="#edf6ff" highlightColor="#7fd7ff" mouthX={58} mouthY={57} mouthWidth={13} mouthHeight={3} mouthColor="#d94b43" />+ <rect x="34" y="64" width="60" height="39" fill="#eef1f5" />+ <rect x="48" y="68" width="32" height="19" fill="#315aa8" />+ <rect x="56" y="70" width="16" height="12" fill="#d94b43" />+ <rect className="cloud-code-monster-pet-left-foot" x="38" y="103" width="20" height="12" fill="#26344f" />+ <rect className="cloud-code-monster-pet-right-foot" x="70" y="103" width="20" height="12" fill="#26344f" />+ </>+ );+ case "dragon-quest-slime":+ return (+ <>+ <rect x="56" y="16" width="16" height="15" fill="#80c4ef" />+ <rect x="42" y="31" width="44" height="13" fill="#69aee2" />+ <rect x="29" y="44" width="70" height="43" fill="#5aa0d8" />+ <rect x="39" y="87" width="50" height="12" fill="#4384ba" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={47} rightX={76} y={55} mouthX={58} mouthY={72} mouthWidth={14} mouthHeight={5} mouthColor="#c4444a" mouthStyle="smile" />+ <rect x="58" y="72" width="14" height="5" fill="#c4444a" />+ </>+ );+ case "inkling":+ return (+ <>+ <rect x="50" y="13" width="11" height="28" fill="#61c3b8" />+ <rect x="67" y="13" width="11" height="28" fill="#61c3b8" />+ <rect x="38" y="31" width="52" height="43" fill="#54afa2" />+ <rect x="32" y="72" width="15" height="29" fill="#54afa2" />+ <rect x="56" y="72" width="15" height="29" fill="#3f9188" />+ <rect x="81" y="72" width="15" height="29" fill="#3f9188" />+ <rect x="41" y="78" width="46" height="17" fill="#25292f" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={48} rightX={74} y={45} />+ </>+ );+ case "snoopy":+ return (+ <>+ <rect x="42" y="23" width="36" height="9" fill="#fffaf0" />+ <rect x="34" y="32" width="55" height="14" fill="#fffaf0" />+ <rect x="32" y="46" width="61" height="18" fill="#f4f1e8" />+ <rect x="43" y="64" width="43" height="10" fill="#e6dfd2" />+ <rect x="82" y="39" width="20" height="10" fill="#fffaf0" />+ <rect x="92" y="49" width="17" height="12" fill="#fffaf0" />+ <rect x="101" y="43" width="11" height="10" fill="#1f1f22" />+ <rect x="106" y="48" width="7" height="8" fill="#1f1f22" />+ <rect x="23" y="31" width="18" height="14" fill="#1f1f22" />+ <rect x="19" y="45" width="23" height="30" fill="#1f1f22" />+ <rect x="23" y="75" width="16" height="12" fill="#1f1f22" />+ <rect x="28" y="36" width="7" height="31" fill="#373234" />+ <rect x="39" y="74" width="50" height="7" fill="#d84c43" />+ <rect x="42" y="81" width="51" height="22" fill="#fffaf0" />+ <rect x="35" y="88" width="12" height="18" fill="#fffaf0" />+ <rect x="88" y="82" width="13" height="13" fill="#fffaf0" />+ <rect x="98" y="79" width="8" height="8" fill="#fffaf0" />+ <rect x="48" y="101" width="11" height="6" fill="#e6dfd2" />+ <rect x="75" y="101" width="11" height="6" fill="#e6dfd2" />+ <rect className="cloud-code-monster-pet-left-foot" x="36" y="104" width="24" height="10" fill="#fffaf0" />+ <rect className="cloud-code-monster-pet-right-foot" x="70" y="104" width="24" height="10" fill="#fffaf0" />+ <rect x="36" y="112" width="24" height="4" fill="#e6dfd2" />+ <rect x="70" y="112" width="24" height="4" fill="#e6dfd2" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={61} rightX={61} y={43} color="#1f1f22" highlightColor="#fffaf0" singleEye mouthX={86} mouthY={59} mouthWidth={11} mouthHeight={3} mouthColor="#1f1f22" mouthStyle="flat" />+ </>+ );+ case "chopper":+ return (+ <>+ <rect x="32" y="19" width="14" height="8" fill="#b07d55" />+ <rect x="82" y="19" width="14" height="8" fill="#b07d55" />+ <rect x="27" y="25" width="13" height="30" fill="#b07d55" />+ <rect x="88" y="25" width="13" height="30" fill="#b07d55" />+ <rect x="38" y="19" width="52" height="19" fill="#df84b2" />+ <rect x="48" y="10" width="32" height="15" fill="#df84b2" />+ <rect x="38" y="38" width="52" height="39" fill="#bd7d55" />+ <rect x="45" y="54" width="38" height="22" fill="#f0cba6" />+ <rect x="36" y="77" width="56" height="27" fill="#c95b70" />+ <rect className="cloud-code-monster-pet-left-foot" x="39" y="104" width="18" height="10" fill="#bd7d55" />+ <rect className="cloud-code-monster-pet-right-foot" x="72" y="104" width="18" height="10" fill="#bd7d55" />+ <DirectPixelEyes activityId={activityId} preset={preset} reacting={reacting} shaken={shaken} fainted={fainted} leftX={49} rightX={75} y={49} />+ </>+ );+ default:+ return null;+ }+}++function MonsterStaticBody({+ preset,+ activityId,+ animated = false,+ reacting = false,+ shaken = false,+ fainted = false,+}: {+ preset: CloudCodeMonsterPetPreset;+ activityId: CloudCodeMonsterActivityId | null;+ animated?: boolean;+ reacting?: boolean;+ shaken?: boolean;+ fainted?: boolean;+}) {+ const shape = preset.shape ?? "monster";++ if (shape !== "monster") {+ return (+ <g className={animated ? "cloud-code-monster-pet-character" : undefined}>+ <MonsterDirectPixelCharacter+ activityId={activityId}+ preset={preset}+ reacting={reacting}+ shaken={shaken}+ fainted={fainted}+ />+ </g>+ );+ }++ return (+ <g className={animated ? "cloud-code-monster-pet-character" : undefined}>+ <MonsterPresetFeature preset={preset} />+ <rect x="36" y="27" width="56" height="10" fill={preset.bodyTop} />+ <rect x="28" y="37" width="72" height="14" fill={preset.bodyTop} />+ <rect x="16" y="51" width="12" height="24" fill={preset.body} />+ <rect x="28" y="51" width="72" height="45" fill={preset.body} />+ <rect x="100" y="51" width="12" height="24" fill={preset.body} />+ <rect x="16" y="63" width="12" height="12" fill={preset.bodyDark} />+ <rect x="28" y="84" width="72" height="12" fill={preset.bodyDark} />+ <rect x="36" y="37" width="56" height="5" fill={preset.bodyLight} />+ <rect x="28" y="51" width="8" height="33" fill={preset.bodySideLight} />+ <rect x="92" y="51" width="8" height="33" fill={preset.bodySideDark} />+ <MonsterPresetBodyMarks preset={preset} />+ <MonsterEyes+ activityId={activityId}+ preset={preset}+ reacting={reacting}+ shaken={shaken}+ fainted={fainted}+ />+ <rect x="36" y="69" width="8" height="8" fill={preset.bodyLight} />+ <rect x="84" y="69" width="8" height="8" fill={preset.bodySideDark} />+ <rect+ className="cloud-code-monster-pet-left-foot"+ x="29"+ y="96"+ width="12"+ height="22"+ fill={preset.body}+ />+ <rect+ className="cloud-code-monster-pet-left-foot"+ x="52"+ y="96"+ width="12"+ height="22"+ fill={preset.body}+ />+ <rect+ className="cloud-code-monster-pet-right-foot"+ x="76"+ y="96"+ width="12"+ height="22"+ fill={preset.bodyDark}+ />+ <rect+ className="cloud-code-monster-pet-right-foot"+ x="96"+ y="96"+ width="12"+ height="22"+ fill={preset.bodyDark}+ />+ </g>+ );+}++export function CloudCodeMonsterPresetPreview({+ preset,+ className,+}: {+ preset: CloudCodeMonsterPetPreset;+ className?: string;+}) {+ return (+ <svg+ className={className}+ viewBox="0 0 128 128"+ role="img"+ aria-label={`${preset.name} pixel PET preset`}+ shapeRendering="crispEdges"+ >+ <rect x="31" y="116" width="66" height="5" fill="rgba(45,40,36,.12)" />+ <rect x="40" y="121" width="48" height="3" fill="rgba(45,40,36,.07)" />+ <MonsterStaticBody preset={preset} activityId={null} />+ </svg>+ );+}++function MonsterSvg({+ activityId,+ preset,+ reacting,+ shaken,+ fainted,+}: {+ activityId: CloudCodeMonsterActivityId | null;+ preset: CloudCodeMonsterPetPreset;+ reacting: boolean;+ shaken: boolean;+ fainted: boolean;+}) {+ const expression = getCloudCodeMonsterExpression(+ activityId,+ reacting,+ shaken,+ fainted+ );+ const isShocked = expression === "shocked" || expression === "shaken";++ return (+ <svg+ className="cloud-code-monster-pet-svg"+ viewBox="0 0 128 128"+ role="img"+ aria-label={`Claude Code style pixel monster ${activityId ?? "idle"}`}+ shapeRendering="crispEdges"+ >+ <rect x="31" y="116" width="66" height="5" fill="rgba(45,40,36,.14)" />+ <rect x="40" y="121" width="48" height="3" fill="rgba(45,40,36,.08)" />+ {isShocked ? (+ <g className="cloud-code-monster-pet-shock" aria-hidden="true">+ <rect x="17" y="15" width="7" height="17" fill={preset.accent} />+ <rect x="103" y="13" width="7" height="17" fill={preset.accent} />+ <rect x="61" y="4" width="7" height="16" fill={preset.accent} />+ <rect x="19" y="91" width="16" height="6" fill={preset.accessory} />+ <rect x="94" y="91" width="16" height="6" fill={preset.accessory} />+ </g>+ ) : null}+ <MonsterStaticBody+ preset={preset}+ activityId={activityId}+ animated+ reacting={reacting}+ shaken={shaken}+ fainted={fainted}+ />+ <MonsterActivityAccessory+ activityId={fainted ? null : activityId}+ preset={preset}+ />+ </svg>+ );+}++type CloudCodeMonsterPetProps = {+ boundaryRef: RefObject<HTMLElement | null>;+ initialPosition?: PetPoint;+ activityTriggerMode?: CloudCodeMonsterActivityTriggerMode;+ previewComebackToken?: number;+ notificationToken?: number;+ peekTargets?: CloudCodeMonsterPeekTarget[];+};++export function CloudCodeMonsterPet({+ boundaryRef,+ initialPosition,+ activityTriggerMode = "global",+ previewComebackToken = 0,+ notificationToken = 0,+ peekTargets = [],+}: CloudCodeMonsterPetProps) {+ const [activityState, setActivityState] =+ useState<StoredCloudCodeMonsterActivity | null>(null);+ const [position, setPosition] = useState<PetPoint | null>(null);+ const [isDragging, setIsDragging] = useState(false);+ const [isAutoWalking, setIsAutoWalking] = useState(false);+ const [isPeeking, setIsPeeking] = useState(false);+ const [notificationActive, setNotificationActive] = useState(false);+ const [reacting, setReacting] = useState(false);+ const [shaken, setShaken] = useState(false);+ const [fainted, setFainted] = useState(false);+ const [presetId, setPresetId] = useState(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ const [walkIntensity, setWalkIntensity] = useState(1);+ const [walkDirection, setWalkDirection] = useState<"left" | "right">("right");+ const [footprints, setFootprints] = useState<Footprint[]>([]);+ const dragOffsetRef = useRef<PetPoint>({ x: 0, y: 0 });+ const dragStartPointRef = useRef<PetPoint | null>(null);+ const lastPointerRef = useRef<{ point: PetPoint; time: number } | null>(null);+ const lastDragDeltaRef = useRef<PetPoint | null>(null);+ const lastFootstepAtRef = useRef(0);+ const autoWalkVelocityRef = useRef<PetPoint | null>(null);+ const nextFootprintIdRef = useRef(1);+ const nextFootSideRef = useRef<"left" | "right">("left");+ const didDragRef = useRef(false);+ const reactionTimerRef = useRef<number | null>(null);+ const shakeTimerRef = useRef<number | null>(null);+ const faintTimerRef = useRef<number | null>(null);+ const autonomousWalkTimerRef = useRef<number | null>(null);+ const autonomousWalkStopTimerRef = useRef<number | null>(null);+ const peekTimerRef = useRef<number | null>(null);+ const peekStopTimerRef = useRef<number | null>(null);+ const notificationTimerRef = useRef<number | null>(null);+ const walkSettleTimerRef = useRef<number | null>(null);+ const resizeObserverRef = useRef<ResizeObserver | null>(null);+ const violentDragEventsRef = useRef<number[]>([]);++ useEffect(() => {+ const syncPreset = (nextPresetId?: string | null) => {+ setPresetId(+ nextPresetId+ ? getCloudCodeMonsterPreset(nextPresetId).id+ : readCloudCodeMonsterPetPresetId()+ );+ };+ const handlePresetChange = (event: Event) => {+ syncPreset(+ (event as CustomEvent<{ presetId?: string }>).detail?.presetId+ );+ };+ const handleStorageChange = (event: StorageEvent) => {+ if (event.key === CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY) {+ syncPreset(event.newValue);+ }+ };++ syncPreset();+ window.addEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );+ window.addEventListener("storage", handleStorageChange);++ return () => {+ window.removeEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );+ window.removeEventListener("storage", handleStorageChange);+ };+ }, []);++ useEffect(() => {+ const nextState = resolveCloudCodeMonsterVisibleState(readStoredActivity());+ writeStoredActivity(nextState);+ setActivityState(nextState);++ const handleVisibility = () => {+ const now = Date.now();++ setActivityState((current) => {+ const nextState =+ document.visibilityState === "hidden"+ ? createCloudCodeMonsterHiddenState(current, now)+ : resolveCloudCodeMonsterVisibleState(+ current ?? readStoredActivity(),+ now+ );+ writeStoredActivity(nextState);+ return nextState;+ });+ };++ document.addEventListener("visibilitychange", handleVisibility);++ return () => {+ document.removeEventListener("visibilitychange", handleVisibility);+ if (activityTriggerMode === "home" && document.visibilityState === "visible") {+ writeStoredActivity(+ createCloudCodeMonsterHiddenState(readStoredActivity(), Date.now())+ );+ }+ };+ }, [activityTriggerMode]);++ useEffect(() => {+ if (previewComebackToken <= 0) {+ return;+ }++ const nextState = resolveCloudCodeMonsterPreviewComebackState();+ writeStoredActivity(nextState);+ setActivityState(nextState);+ }, [previewComebackToken]);++ useEffect(() => {+ const syncPosition = () => {+ const bounds = getBounds(boundaryRef.current);++ setPosition((currentPosition) =>+ currentPosition+ ? clampPetPosition(currentPosition, bounds, CLOUD_CODE_MONSTER_SIZE)+ : clampPetPosition(+ initialPosition ?? {+ x: bounds.width - CLOUD_CODE_MONSTER_SIZE.width - 112,+ y: Math.min(+ bounds.height * 0.48,+ bounds.height - CLOUD_CODE_MONSTER_SIZE.height - 120+ ),+ },+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ )+ );+ };++ syncPosition();+ window.addEventListener("resize", syncPosition);+ if (typeof ResizeObserver !== "undefined" && boundaryRef.current) {+ resizeObserverRef.current = new ResizeObserver(syncPosition);+ resizeObserverRef.current.observe(boundaryRef.current);+ }++ return () => {+ window.removeEventListener("resize", syncPosition);+ resizeObserverRef.current?.disconnect();+ resizeObserverRef.current = null;+ };+ }, [boundaryRef, initialPosition]);++ useEffect(() => {+ return () => {+ if (reactionTimerRef.current) {+ window.clearTimeout(reactionTimerRef.current);+ }+ if (shakeTimerRef.current) {+ window.clearTimeout(shakeTimerRef.current);+ }+ if (faintTimerRef.current) {+ window.clearTimeout(faintTimerRef.current);+ }+ if (autonomousWalkTimerRef.current) {+ window.clearTimeout(autonomousWalkTimerRef.current);+ autonomousWalkTimerRef.current = null;+ }+ if (autonomousWalkStopTimerRef.current) {+ window.clearTimeout(autonomousWalkStopTimerRef.current);+ }+ if (peekTimerRef.current) {+ window.clearTimeout(peekTimerRef.current);+ }+ if (peekStopTimerRef.current) {+ window.clearTimeout(peekStopTimerRef.current);+ }+ if (notificationTimerRef.current) {+ window.clearTimeout(notificationTimerRef.current);+ }+ if (walkSettleTimerRef.current) {+ window.clearTimeout(walkSettleTimerRef.current);+ }+ };+ }, []);++ const activity = useMemo(() => {+ if (!activityState?.activityId) {+ return null;+ }++ return CLOUD_CODE_MONSTER_ACTIVITIES.find(+ (item) => item.id === activityState.activityId+ );+ }, [activityState]);+ const preset = useMemo(() => getCloudCodeMonsterPreset(presetId), [presetId]);+ const isWalking = isDragging || isAutoWalking;+ const hasPosition = position !== null;+ const shouldAutoWalk = shouldCloudCodeMonsterAutoWalk(+ activityState?.activityId ?? null+ );++ useEffect(() => {+ if (+ !hasPosition ||+ !activityState?.activityId ||+ !shouldAutoWalk ||+ isDragging ||+ reacting ||+ shaken ||+ fainted ||+ isPeeking+ ) {+ setIsAutoWalking(false);+ setWalkIntensity(1);+ autoWalkVelocityRef.current = null;+ return;+ }++ setIsAutoWalking(true);+ autoWalkVelocityRef.current ??= createCloudCodeMonsterWalkVelocity();++ const scheduleNextWalkStep = () => {+ autonomousWalkTimerRef.current = window.setTimeout(() => {+ const bounds = getBounds(boundaryRef.current);+ const intensity = 1.45;++ setWalkIntensity(intensity);+ setPosition((currentPosition) => {+ const velocity = autoWalkVelocityRef.current;++ if (!currentPosition || !velocity) {+ return currentPosition;+ }++ const nextWalk = reflectCloudCodeMonsterWalk(+ currentPosition,+ velocity,+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ );+ autoWalkVelocityRef.current = nextWalk.velocity;+ setWalkDirection(nextWalk.velocity.x >= 0 ? "right" : "left");++ const now = performance.now();+ if (+ now - lastFootstepAtRef.current >=+ getMonsterFootstepIntervalMs(intensity)+ ) {+ pushFootprint(nextWalk.position, intensity);+ lastFootstepAtRef.current = now;+ }++ return nextWalk.position;+ });+ scheduleNextWalkStep();+ }, CLOUD_CODE_MONSTER_AUTO_WALK_STEP_MS);+ };++ autonomousWalkTimerRef.current = window.setTimeout(+ scheduleNextWalkStep,+ CLOUD_CODE_MONSTER_AUTO_WALK_STEP_MS+ );++ return () => {+ if (autonomousWalkTimerRef.current) {+ window.clearTimeout(autonomousWalkTimerRef.current);+ autonomousWalkTimerRef.current = null;+ }+ };+ }, [+ activityState?.activityId,+ boundaryRef,+ fainted,+ hasPosition,+ isDragging,+ isPeeking,+ reacting,+ shaken,+ shouldAutoWalk,+ ]);++ useEffect(() => {+ if (+ !position ||+ peekTargets.length === 0 ||+ isDragging ||+ reacting ||+ shaken ||+ fainted+ ) {+ return;+ }++ peekTimerRef.current = window.setTimeout(() => {+ const target =+ peekTargets[Math.floor(Math.random() * peekTargets.length)] ??+ peekTargets[0];++ if (!target) {+ return;+ }++ const bounds = getBounds(boundaryRef.current);+ const nextPosition = resolveCloudCodeMonsterPeekPosition(+ target,+ boundaryRef.current,+ bounds+ );++ setIsAutoWalking(false);+ autoWalkVelocityRef.current = null;+ setIsPeeking(true);+ setWalkIntensity(1);+ setPosition(nextPosition);++ peekStopTimerRef.current = window.setTimeout(() => {+ setIsPeeking(false);+ peekStopTimerRef.current = null;+ }, CLOUD_CODE_MONSTER_PEEK_MS);+ }, CLOUD_CODE_MONSTER_PEEK_INTERVAL_MS + Math.random() * 4_000);++ return () => {+ if (peekTimerRef.current) {+ window.clearTimeout(peekTimerRef.current);+ peekTimerRef.current = null;+ }+ };+ }, [+ boundaryRef,+ fainted,+ isDragging,+ peekTargets,+ position,+ reacting,+ shaken,+ ]);++ const pushFootprint = (nextPosition: PetPoint, intensity: number) => {+ const side = nextFootSideRef.current;+ nextFootSideRef.current = side === "left" ? "right" : "left";+ const sideOffset = side === "left" ? 25 : 52;++ setFootprints((current) => [+ ...current.slice(-13),+ {+ id: nextFootprintIdRef.current++,+ x: nextPosition.x + sideOffset,+ y: nextPosition.y + CLOUD_CODE_MONSTER_SIZE.height - 7,+ side,+ intensity,+ },+ ]);+ };++ const wakeMonsterToDefault = () => {+ setActivityState((current) => {+ if (current && !current.activityId && current.hiddenAt === null) {+ return current;+ }++ const nextState = createCloudCodeMonsterIdleState();+ writeStoredActivity(nextState);+ return nextState;+ });+ };++ const stopTemporaryMotion = () => {+ setIsAutoWalking(false);+ setIsPeeking(false);+ violentDragEventsRef.current = [];+ autoWalkVelocityRef.current = null;++ if (autonomousWalkStopTimerRef.current) {+ window.clearTimeout(autonomousWalkStopTimerRef.current);+ autonomousWalkStopTimerRef.current = null;+ }+ if (peekStopTimerRef.current) {+ window.clearTimeout(peekStopTimerRef.current);+ peekStopTimerRef.current = null;+ }+ };++ const startShockReaction = () => {+ if (reactionTimerRef.current) {+ window.clearTimeout(reactionTimerRef.current);+ }++ setReacting(true);+ reactionTimerRef.current = window.setTimeout(() => {+ setReacting(false);+ reactionTimerRef.current = null;+ }, CLOUD_CODE_MONSTER_REACTION_MS);+ };++ useEffect(() => {+ if (notificationToken <= 0) {+ return;+ }++ stopTemporaryMotion();+ if (activityState?.activityId) {+ wakeMonsterToDefault();+ }+ startShockReaction();+ setNotificationActive(true);++ if (notificationTimerRef.current) {+ window.clearTimeout(notificationTimerRef.current);+ }+ notificationTimerRef.current = window.setTimeout(() => {+ setNotificationActive(false);+ notificationTimerRef.current = null;+ }, CLOUD_CODE_MONSTER_REACTION_MS + 1_500);+ }, [notificationToken]);++ const startShakeReaction = () => {+ if (fainted) {+ return;+ }++ if (activityState?.activityId) {+ wakeMonsterToDefault();+ }++ if (shakeTimerRef.current) {+ window.clearTimeout(shakeTimerRef.current);+ }++ setShaken(true);+ shakeTimerRef.current = window.setTimeout(() => {+ setShaken(false);+ shakeTimerRef.current = null;+ }, CLOUD_CODE_MONSTER_SHAKE_REACTION_MS);+ };++ const startFaintReaction = () => {+ if (faintTimerRef.current) {+ window.clearTimeout(faintTimerRef.current);+ }+ if (reactionTimerRef.current) {+ window.clearTimeout(reactionTimerRef.current);+ reactionTimerRef.current = null;+ }+ if (shakeTimerRef.current) {+ window.clearTimeout(shakeTimerRef.current);+ shakeTimerRef.current = null;+ }++ wakeMonsterToDefault();+ stopTemporaryMotion();+ setReacting(false);+ setShaken(false);+ setFainted(true);+ setWalkIntensity(1);++ faintTimerRef.current = window.setTimeout(() => {+ setFainted(false);+ faintTimerRef.current = null;+ }, CLOUD_CODE_MONSTER_FAINT_MS);+ };++ const handlePetClick = () => {+ stopTemporaryMotion();+ setNotificationActive(false);+ if (notificationTimerRef.current) {+ window.clearTimeout(notificationTimerRef.current);+ notificationTimerRef.current = null;+ }++ if (didDragRef.current) {+ didDragRef.current = false;+ return;+ }++ if (isDragging) {+ return;+ }++ if (activityState?.activityId) {+ wakeMonsterToDefault();+ }++ if (fainted) {+ setFainted(false);+ if (faintTimerRef.current) {+ window.clearTimeout(faintTimerRef.current);+ faintTimerRef.current = null;+ }+ }++ startShockReaction();+ };++ const handlePointerDown = (event: ReactPointerEvent<HTMLButtonElement>) => {+ if (event.button !== 0) {+ return;+ }++ const bounds = getBounds(boundaryRef.current);+ const currentPosition =+ position ??+ clampPetPosition(+ initialPosition ?? {+ x: bounds.width - CLOUD_CODE_MONSTER_SIZE.width - 112,+ y: bounds.height * 0.48,+ },+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ );+ const pointerPoint = getPointerPoint(event, boundaryRef.current);+ const now = performance.now();++ dragOffsetRef.current = {+ x: pointerPoint.x - currentPosition.x,+ y: pointerPoint.y - currentPosition.y,+ };+ dragStartPointRef.current = pointerPoint;+ lastPointerRef.current = { point: pointerPoint, time: now };+ lastDragDeltaRef.current = null;+ lastFootstepAtRef.current = now;+ didDragRef.current = false;+ stopTemporaryMotion();+ setIsDragging(true);+ setWalkIntensity(1.1);+ event.currentTarget.setPointerCapture(event.pointerId);+ };++ const handlePointerMove = (event: ReactPointerEvent<HTMLButtonElement>) => {+ if (!isDragging) {+ return;+ }++ const bounds = getBounds(boundaryRef.current);+ const pointerPoint = getPointerPoint(event, boundaryRef.current);+ const now = performance.now();+ const lastPointer = lastPointerRef.current ?? {+ point: pointerPoint,+ time: now,+ };+ const deltaX = pointerPoint.x - lastPointer.point.x;+ const deltaY = pointerPoint.y - lastPointer.point.y;+ const nextDelta = { x: deltaX, y: deltaY };+ const distance = Math.hypot(deltaX, deltaY);+ const elapsed = Math.max(1, now - lastPointer.time);+ const intensity = calculateMonsterWalkIntensity(distance, elapsed);+ const nextPosition = clampPetPosition(+ {+ x: pointerPoint.x - dragOffsetRef.current.x,+ y: pointerPoint.y - dragOffsetRef.current.y,+ },+ bounds,+ CLOUD_CODE_MONSTER_SIZE+ );+ const dragStartPoint = dragStartPointRef.current ?? pointerPoint;+ const movementX = Math.abs(pointerPoint.x - dragStartPoint.x);+ const movementY = Math.abs(pointerPoint.y - dragStartPoint.y);++ if (movementX > 3 || movementY > 3) {+ didDragRef.current = true;+ }+ if (Math.abs(deltaX) > 0.5) {+ setWalkDirection(deltaX >= 0 ? "right" : "left");+ }+ const hasSharpDirectionChange = hasViolentMonsterDirectionChange(+ lastDragDeltaRef.current,+ nextDelta+ );++ if (+ !fainted &&+ isViolentMonsterDrag(distance, elapsed, hasSharpDirectionChange)+ ) {+ startShakeReaction();+ }++ if (+ !fainted &&+ isMonsterFaintShakeEvent(distance, elapsed, hasSharpDirectionChange)+ ) {+ violentDragEventsRef.current = [+ ...violentDragEventsRef.current.filter(+ (eventTime) =>+ now - eventTime <= CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS+ ),+ now,+ ];++ if (shouldFaintFromMonsterShake(violentDragEventsRef.current, now)) {+ startFaintReaction();+ return;+ }+ }++ setWalkIntensity(intensity);+ setPosition(nextPosition);+ lastPointerRef.current = { point: pointerPoint, time: now };+ if (distance > 0.5) {+ lastDragDeltaRef.current = nextDelta;+ }++ if (+ distance > 1 &&+ now - lastFootstepAtRef.current >= getMonsterFootstepIntervalMs(intensity)+ ) {+ pushFootprint(nextPosition, intensity);+ lastFootstepAtRef.current = now;+ }+ };++ const stopDragging = (event: ReactPointerEvent<HTMLButtonElement>) => {+ if (!isDragging) {+ return;+ }++ setIsDragging(false);+ violentDragEventsRef.current = [];+ dragStartPointRef.current = null;+ lastPointerRef.current = null;+ lastDragDeltaRef.current = null;++ if (walkSettleTimerRef.current) {+ window.clearTimeout(walkSettleTimerRef.current);+ }+ walkSettleTimerRef.current = window.setTimeout(() => {+ setWalkIntensity(1);+ walkSettleTimerRef.current = null;+ }, 180);++ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ };++ if (!position || !activityState) {+ return null;+ }++ const displayedActivity = isPeeking || fainted ? null : activity;++ return (+ <>+ <div className="cloud-code-monster-pet-footsteps" aria-hidden="true">+ {footprints.map((footprint) => (+ <span+ key={footprint.id}+ className="cloud-code-monster-pet-footprint"+ data-side={footprint.side}+ style={+ {+ "--monster-footprint-x": `${footprint.x}px`,+ "--monster-footprint-y": `${footprint.y}px`,+ "--monster-footprint-scale": String(+ Math.min(1.35, Math.max(0.75, footprint.intensity / 1.45))+ ),+ } as CSSProperties+ }+ />+ ))}+ </div>+ <aside+ aria-label={`${preset.name} pixel PET: ${+ fainted+ ? "晕倒"+ : isPeeking+ ? "偷看工作"+ : displayedActivity?.label ?? "默认状态"+ }`}+ className="cloud-code-monster-pet"+ data-activity={displayedActivity?.id ?? "idle"}+ data-dragging={isDragging}+ data-walking={isWalking}+ data-direction={walkDirection}+ data-reaction={shaken ? "shake" : reacting ? "shock" : "none"}+ data-reacting={reacting}+ data-shaken={shaken}+ data-fainted={fainted}+ data-peeking={isPeeking}+ data-notifying={notificationActive}+ style={+ {+ "--cloud-code-monster-pet-x": `${position.x}px`,+ "--cloud-code-monster-pet-y": `${position.y}px`,+ "--monster-walk-duration": `${Math.round(+ 360 / Math.max(0.75, walkIntensity)+ )}ms`,+ "--monster-walk-lift": `-${Math.round(+ 2 * Math.max(0.75, walkIntensity)+ )}px`,+ "--monster-walk-intensity": String(walkIntensity),+ } as CSSProperties+ }+ >+ {notificationActive ? (+ <span className="cloud-code-monster-pet-notification-bell" aria-hidden="true">+ <svg+ viewBox="0 0 24 24"+ className="cloud-code-monster-pet-notification-bell-pixel size-6"+ role="img"+ shapeRendering="crispEdges"+ >+ <rect x="10" y="2" width="4" height="3" fill="#2b2112" />+ <rect x="8" y="5" width="8" height="3" fill="#2b2112" />+ <rect x="6" y="8" width="12" height="8" fill="#2b2112" />+ <rect x="4" y="16" width="16" height="4" fill="#2b2112" />+ <rect x="9" y="20" width="6" height="2" fill="#2b2112" />+ <rect x="10" y="5" width="4" height="2" fill="#ffe37a" />+ <rect x="8" y="8" width="8" height="8" fill="#f4c84f" />+ <rect x="6" y="16" width="12" height="2" fill="#f4c84f" />+ <rect x="9" y="9" width="3" height="7" fill="#ffe37a" />+ <rect x="13" y="18" width="3" height="2" fill="#c8922f" />+ </svg>+ </span>+ ) : null}+ <button+ type="button"+ className="cloud-code-monster-pet-button"+ data-dragging={isDragging}+ data-fainted={fainted}+ onClick={handlePetClick}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={stopDragging}+ onPointerCancel={stopDragging}+ onLostPointerCapture={stopDragging}+ aria-label={`Claude Code pixel monster is ${+ fainted+ ? "晕倒"+ : isPeeking+ ? "偷看工作"+ : displayedActivity?.label ?? "默认状态"+ }. Click to ${+ displayedActivity || fainted || isPeeking ? "interrupt it" : "notice it"+ }, drag to make it walk.`}+ >+ <MonsterSvg+ activityId={displayedActivity?.id ?? null}+ preset={preset}+ reacting={reacting}+ shaken={shaken}+ fainted={fainted}+ />+ </button>+ </aside>+ </>+ );+}diff --git a/src/web/src/components/home-pet/homepage-pet.test.ts b/src/web/src/components/home-pet/homepage-pet.test.tsnew file mode 100644index 000000000..e196d4f30--- /dev/null+++ b/src/web/src/components/home-pet/homepage-pet.test.ts@@ -0,0 +1,794 @@+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import {+ calculateMonsterWalkIntensity,+ CLOUD_CODE_MONSTER_ACTIVITIES,+ CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS,+ CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS,+ CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS,+ CLOUD_CODE_MONSTER_FAINT_MS,+ CLOUD_CODE_MONSTER_PET_PRESETS,+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY,+ createCloudCodeMonsterWalkVelocity,+ createCloudCodeMonsterHiddenState,+ createCloudCodeMonsterIdleState,+ createCloudCodeMonsterPreviewAwayState,+ getCloudCodeMonsterExpression,+ getCloudCodeMonsterPreset,+ getMonsterFootstepIntervalMs,+ hasViolentMonsterDirectionChange,+ isMonsterFaintShakeEvent,+ isViolentMonsterDrag,+ pickCloudCodeMonsterActivity,+ reflectCloudCodeMonsterWalk,+ resolveCloudCodeMonsterPeekPosition,+ resolveCloudCodeMonsterPreviewComebackState,+ resolveCloudCodeMonsterActivityState,+ resolveCloudCodeMonsterVisibleState,+ shouldCloudCodeMonsterAutoWalk,+ shouldFaintFromMonsterShake,+ shouldRefreshCloudCodeMonsterActivity,+} from "./cloud-code-monster-pet";+import {+ clampPetPosition,+ getAmbientScenes,+ getPetPreset,+ getReactionScene,+ getReactionReturnScene,+ getSpriteFrameDelay,+ HOME_PET_SIZE,+ type PetPreset,+ selectAmbientScene,+ selectNextAmbientScene,+} from "./pet-presets";++function webRoot() {+ return process.cwd().endsWith(`${path.sep}src${path.sep}web`)+ ? process.cwd()+ : path.join(process.cwd(), "src/web");+}++describe("workspace home PET helpers", () => {+ const preset = getPetPreset("tater");++ it("keeps the PET small enough for the relationship canvas", () => {+ expect(HOME_PET_SIZE.width).toBeLessThanOrEqual(72);+ expect(HOME_PET_SIZE.height).toBeLessThanOrEqual(78);+ });++ it("selects only valid ambient preset scene names", () => {+ const ambientSceneNames = new Set(+ getAmbientScenes(preset).map((scene) => scene.name)+ );++ expect(ambientSceneNames.size).toBeGreaterThan(0);+ expect(selectAmbientScene(preset, 0).kind).toBe("ambient");+ expect(selectAmbientScene(preset, 0.42).kind).toBe("ambient");+ expect(selectAmbientScene(preset, 0.999).kind).toBe("ambient");+ expect(ambientSceneNames.has(selectAmbientScene(preset, 0.999).name)).toBe(+ true+ );+ });++ it("keeps the PET inside the provided bounds", () => {+ expect(+ clampPetPosition(+ { x: -40, y: 900 },+ { width: 500, height: 400 },+ { width: 120, height: 140 },+ 12+ )+ ).toEqual({ x: 12, y: 248 });+ });++ it("allows bounds taller than the first viewport", () => {+ expect(+ clampPetPosition(+ { x: 420, y: 1200 },+ { width: 500, height: 1600 },+ { width: 120, height: 140 },+ 12+ )+ ).toEqual({ x: 368, y: 1200 });+ });++ it("keeps scene metadata ready for action-specific assets", () => {+ for (const scene of Object.values(preset.scenes)) {+ expect(scene.animationClass).toMatch(/^home-pet-motion-/);+ expect(scene.spriteAnimation.row).toBeGreaterThanOrEqual(0);+ expect(scene.spriteAnimation.frames).toBeGreaterThan(0);+ expect(scene.spriteAnimation.frameDurations.length).toBeGreaterThan(0);+ if (scene.kind === "ambient") {+ expect(scene.spriteAnimation.restDurationMs?.[0]).toBeGreaterThanOrEqual(3000);+ }+ expect(scene.asset?.src ?? preset.sprite.src).toBeTruthy();+ expect(scene.asset?.alt ?? preset.sprite.alt).toBeTruthy();+ }+ });++ it("adds a quiet rest after ambient sprite bursts but keeps reactions immediate", () => {+ const idle = preset.scenes.idle;+ const startled = preset.scenes.startled;++ expect(getSpriteFrameDelay(idle, 0, 0)).toBe(+ idle.spriteAnimation.restDurationMs?.[0]+ );+ expect(getSpriteFrameDelay(idle, 0, 1)).toBe(+ idle.spriteAnimation.restDurationMs?.[1]+ );+ expect(getSpriteFrameDelay(idle, 1, 0)).toBe(idle.spriteAnimation.frameDurations[1]);+ expect(+ getSpriteFrameDelay(startled, startled.spriteAnimation.frames - 1, 1)+ ).toBe(+ startled.spriteAnimation.frameDurations[startled.spriteAnimation.frames - 1]+ );+ });++ it("usually returns to idle between occasional ambient bursts", () => {+ expect(selectNextAmbientScene(preset, "thinking", 0.99).name).toBe("idle");+ expect(selectNextAmbientScene(preset, "idle", 0.2).name).toBe("idle");+ expect(selectNextAmbientScene(preset, "idle", 0.99).name).not.toBe("idle");+ });++ it("maps any ambient click reaction back to the previous normal scene", () => {+ const ambientScenes = getAmbientScenes(preset);++ for (const scene of ambientScenes) {+ expect(getReactionReturnScene(preset, scene.name)).toBe(scene);+ }++ expect(getReactionReturnScene(preset, "startled").name).toBe("idle");+ });++ it("does not require future presets to use the Tater scene names", () => {+ const customPreset: PetPreset = {+ id: "quiet",+ displayName: "Quiet",+ description: "A quiet PET preset.",+ sprite: {+ src: "/pets/quiet/spritesheet.webp",+ alt: "Quiet workspace PET",+ },+ homeScene: "rest",+ reactionScene: "blink",+ scenes: {+ rest: {+ name: "rest",+ label: "Rest",+ kind: "ambient",+ statusText: "resting",+ animationClass: "home-pet-motion-idle",+ spriteAnimation: {+ row: 0,+ frames: 1,+ frameDurations: [1000],+ },+ },+ blink: {+ name: "blink",+ label: "Blink",+ kind: "reaction",+ statusText: "blinked",+ animationClass: "home-pet-motion-startled",+ spriteAnimation: {+ row: 1,+ frames: 2,+ frameDurations: [120, 180],+ },+ returnTo: "rest",+ },+ },+ };++ expect(selectAmbientScene(customPreset, 0).name).toBe("rest");+ expect(getReactionScene(customPreset)?.name).toBe("blink");+ expect(getReactionReturnScene(customPreset, "blink").name).toBe("rest");+ });+});++describe("preview Claude Code monster PET activity state", () => {+ it("offers 30 unique configurable monster presets", () => {+ const presetIds = new Set(CLOUD_CODE_MONSTER_PET_PRESETS.map((preset) => preset.id));+ const colorPattern = /^#[0-9a-f]{6}$/i;+ const licensedIpTemplates = [+ { id: "pet-02", name: "Doraemon", feature: "bell", shape: "doraemon" },+ { id: "pet-03", name: "Pikachu", feature: "bolt", shape: "pikachu" },+ { id: "pet-04", name: "Kirby", feature: "star", shape: "kirby" },+ { id: "pet-05", name: "Bulbasaur", feature: "leaf", shape: "bulbasaur" },+ { id: "pet-06", name: "Charmander", feature: "flame", shape: "charmander" },+ { id: "pet-07", name: "Squirtle", feature: "fins", shape: "squirtle" },+ { id: "pet-08", name: "Minecraft Steve", feature: "visor", shape: "minecraft-steve" },+ { id: "pet-09", name: "Minecraft Creeper", feature: "mask", shape: "minecraft-creeper" },+ { id: "pet-10", name: "Minecraft Zombie", feature: "visor", shape: "minecraft-zombie" },+ { id: "pet-11", name: "Toad", feature: "mushroom", shape: "toad" },+ { id: "pet-12", name: "Sonic", feature: "spin", shape: "sonic" },+ { id: "pet-13", name: "Pac-Man", feature: "chomp", shape: "pacman" },+ { id: "pet-14", name: "Boo", feature: "ghost", shape: "boo" },+ { id: "pet-15", name: "Mario", feature: "cap", shape: "mario" },+ { id: "pet-16", name: "Winnie the Pooh", feature: "ears", shape: "pooh" },+ { id: "pet-17", name: "Hello Kitty", feature: "bow", shape: "hello-kitty" },+ { id: "pet-18", name: "My Melody", feature: "hood", shape: "my-melody" },+ { id: "pet-19", name: "Kuromi", feature: "mask", shape: "kuromi" },+ { id: "pet-20", name: "Totoro", feature: "ears", shape: "totoro" },+ { id: "pet-21", name: "Soot Sprite", feature: "soot", shape: "soot-sprite" },+ { id: "pet-22", name: "Luffy", feature: "straw", shape: "luffy" },+ { id: "pet-23", name: "Naruto", feature: "ninja", shape: "naruto" },+ { id: "pet-24", name: "Goku", feature: "pearl", shape: "goku" },+ { id: "pet-25", name: "Sailor Moon", feature: "wand", shape: "sailor-moon" },+ { id: "pet-26", name: "Gundam", feature: "mecha", shape: "gundam" },+ { id: "pet-27", name: "Dragon Quest Slime", feature: "slime", shape: "dragon-quest-slime" },+ { id: "pet-28", name: "Inkling", feature: "ink", shape: "inkling" },+ { id: "pet-29", name: "Snoopy", feature: "ears", shape: "snoopy" },+ { id: "pet-30", name: "Chopper", feature: "horns", shape: "chopper" },+ ];+ const licensedPresets = CLOUD_CODE_MONSTER_PET_PRESETS.slice(1);++ expect(CLOUD_CODE_MONSTER_PET_PRESETS).toHaveLength(30);+ expect(presetIds.size).toBe(30);+ expect(CLOUD_CODE_MONSTER_PET_PRESETS[0]).toMatchObject({+ id: "pet-01",+ name: "Claude Pixel",+ group: "Codex",+ body: "#d87352",+ feature: "square",+ });+ expect(+ licensedPresets.map(({ id, name, feature, shape }) => ({+ id,+ name,+ feature,+ shape,+ }))+ ).toEqual(licensedIpTemplates);+ expect(+ new Set(licensedPresets.map((preset) => preset.shape)).size+ ).toBe(29);+ expect(+ new Set(licensedPresets.map((preset) => preset.feature)).size+ ).toBeGreaterThanOrEqual(22);+ expect(+ licensedPresets.map((preset) => preset.shape)+ ).not.toEqual(+ licensedPresets.map(() => "monster")+ );+ expect(+ licensedPresets.some((preset) =>+ [+ "bot",+ "mouse",+ "round",+ "quad",+ "cat",+ "human",+ "mecha",+ "slime",+ "squid",+ "dog",+ ].includes(preset.shape ?? "")+ )+ ).toBe(false);+ expect(licensedPresets.map((preset) => preset.name)).toEqual(+ expect.arrayContaining([+ "Minecraft Steve",+ "Minecraft Creeper",+ "Minecraft Zombie",+ ])+ );++ for (const preset of CLOUD_CODE_MONSTER_PET_PRESETS) {+ if (preset.id !== "pet-01") {+ expect(preset.group).toBe("Licensed IP");+ }+ expect(preset.id).toMatch(/^pet-\d{2}$/);+ expect(preset.name.length).toBeGreaterThan(2);+ expect(preset.group.length).toBeGreaterThan(2);+ expect(preset.bodyTop).toMatch(colorPattern);+ expect(preset.body).toMatch(colorPattern);+ expect(preset.bodyDark).toMatch(colorPattern);+ expect(preset.bodyLight).toMatch(colorPattern);+ expect(preset.bodySideLight).toMatch(colorPattern);+ expect(preset.bodySideDark).toMatch(colorPattern);+ expect(preset.accent).toMatch(colorPattern);+ expect(preset.accessory).toMatch(colorPattern);+ expect(preset.eye).toMatch(colorPattern);+ expect(preset.highlight).toMatch(colorPattern);+ }+ });++ it("falls back to the default monster preset for invalid ids", () => {+ expect(getCloudCodeMonsterPreset("pet-12").id).toBe("pet-12");+ expect(getCloudCodeMonsterPreset("missing").id).toBe(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ expect(getCloudCodeMonsterPreset(null).id).toBe(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ });++ it("keeps a monster activity stable until the 3 minute refresh window elapses", () => {+ const updatedAt = 1_000;++ expect(CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS).toBe(3 * 60 * 1000);+ expect(+ shouldRefreshCloudCodeMonsterActivity(+ updatedAt,+ updatedAt + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS - 1+ )+ ).toBe(false);+ expect(+ shouldRefreshCloudCodeMonsterActivity(+ updatedAt,+ updatedAt + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS+ )+ ).toBe(true);+ });++ it("starts the monster in an activity when the page is first opened", () => {+ const initialState = resolveCloudCodeMonsterVisibleState(null, 5_000, 0.99);++ expect(CLOUD_CODE_MONSTER_ACTIVITIES.map((activity) => activity.id)).toContain(+ initialState.activityId+ );+ expect(initialState).toEqual({+ activityId: CLOUD_CODE_MONSTER_ACTIVITIES.at(-1)!.id,+ updatedAt: 5_000,+ hiddenAt: null,+ });+ });++ it("reuses the current monster state during frequent page switching", () => {+ const stored = {+ activityId: "coding" as const,+ updatedAt: 1_000,+ hiddenAt: 1_000,+ };++ expect(+ resolveCloudCodeMonsterVisibleState(+ stored,+ stored.hiddenAt + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS - 1,+ 0.99+ )+ ).toEqual({+ activityId: "coding",+ updatedAt: 1_000,+ hiddenAt: null,+ });+ });++ it("picks a valid new monster activity after being away for the refresh window", () => {+ const now = 1_000 + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS;+ const next = resolveCloudCodeMonsterVisibleState(+ { activityId: null, updatedAt: 1_000, hiddenAt: 1_000 },+ now,+ 0.99+ );++ expect(next.updatedAt).toBe(now);+ expect(next.hiddenAt).toBeNull();+ expect(CLOUD_CODE_MONSTER_ACTIVITIES.map((activity) => activity.id)).toContain(+ next.activityId+ );+ });++ it("does not refresh a stale idle state without an away marker", () => {+ const idleState = {+ activityId: null,+ updatedAt: 1_000,+ hiddenAt: null,+ };++ expect(+ resolveCloudCodeMonsterVisibleState(+ idleState,+ 1_000 + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ 0.99+ )+ ).toEqual(idleState);+ });++ it("can interrupt an active monster activity back to the default state", () => {+ const active = resolveCloudCodeMonsterActivityState(+ { activityId: null, updatedAt: 1_000, hiddenAt: 1_000 },+ 1_000 + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ 0+ );++ expect(active.activityId).not.toBeNull();+ expect(createCloudCodeMonsterIdleState(8_000)).toEqual({+ activityId: null,+ updatedAt: 8_000,+ hiddenAt: null,+ });+ });++ it("records when the page is hidden before comeback activity selection", () => {+ expect(+ createCloudCodeMonsterHiddenState(+ { activityId: null, updatedAt: 1_000, hiddenAt: null },+ 2_000+ )+ ).toEqual({+ activityId: null,+ updatedAt: 1_000,+ hiddenAt: 2_000,+ });+ });++ it("supports preview-only Other Page switching as a 3 minute away state", () => {+ const now = 20_000;+ const awayState = createCloudCodeMonsterPreviewAwayState(now);++ expect(awayState).toEqual({+ activityId: null,+ updatedAt: now - CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ hiddenAt: now - CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ });+ expect(+ resolveCloudCodeMonsterVisibleState(awayState, now, 0.42).activityId+ ).not.toBeNull();+ expect(resolveCloudCodeMonsterPreviewComebackState(now, 0.42)).toEqual(+ resolveCloudCodeMonsterVisibleState(awayState, now, 0.42)+ );+ });++ it("selects deterministic monster activity boundaries", () => {+ expect(pickCloudCodeMonsterActivity(0).id).toBe(+ CLOUD_CODE_MONSTER_ACTIVITIES[0]!.id+ );+ expect(pickCloudCodeMonsterActivity(0.999).id).toBe(+ CLOUD_CODE_MONSTER_ACTIVITIES[+ CLOUD_CODE_MONSTER_ACTIVITIES.length - 1+ ]!.id+ );+ });++ it("keeps all random activities but only lets reading, phone, and snacking auto-walk", () => {+ expect(CLOUD_CODE_MONSTER_ACTIVITIES.map((activity) => activity.id)).toEqual(+ ["coding", "sleeping", "reading", "phone", "thinking", "snacking"]+ );+ expect(CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS).toEqual([+ "reading",+ "phone",+ "snacking",+ ]);+ expect(+ CLOUD_CODE_MONSTER_ACTIVITIES.filter((activity) =>+ shouldCloudCodeMonsterAutoWalk(activity.id)+ ).map((activity) => activity.id)+ ).toEqual(+ CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS+ );+ expect(shouldCloudCodeMonsterAutoWalk("coding")).toBe(false);+ expect(shouldCloudCodeMonsterAutoWalk("sleeping")).toBe(false);+ expect(shouldCloudCodeMonsterAutoWalk("thinking")).toBe(false);+ expect(shouldCloudCodeMonsterAutoWalk(null)).toBe(false);+ });++ it("increases walking intensity and footstep cadence as drag speed rises", () => {+ const slowWalk = calculateMonsterWalkIntensity(4, 40);+ const fastWalk = calculateMonsterWalkIntensity(70, 16);++ expect(fastWalk).toBeGreaterThan(slowWalk);+ expect(getMonsterFootstepIntervalMs(fastWalk)).toBeLessThan(+ getMonsterFootstepIntervalMs(slowWalk)+ );+ });++ it("creates real autonomous walk velocity and reflects from canvas bounds", () => {+ expect(createCloudCodeMonsterWalkVelocity(0, 3)).toEqual({+ x: 3,+ y: 0,+ });+ expect(createCloudCodeMonsterWalkVelocity(0.25, 3).x).toBeCloseTo(0, 6);+ expect(createCloudCodeMonsterWalkVelocity(0.25, 3).y).toBeCloseTo(3, 6);++ const rightBounce = reflectCloudCodeMonsterWalk(+ { x: 202, y: 40 },+ { x: 4, y: 1 },+ { width: 300, height: 240 },+ { width: 82, height: 82 },+ 16+ );+ const topBounce = reflectCloudCodeMonsterWalk(+ { x: 44, y: 17 },+ { x: -2, y: -5 },+ { width: 300, height: 240 },+ { width: 82, height: 82 },+ 16+ );++ expect(rightBounce.reflectedX).toBe(true);+ expect(rightBounce.velocity.x).toBeLessThan(0);+ expect(rightBounce.position.x).toBeLessThanOrEqual(202);+ expect(topBounce.reflectedY).toBe(true);+ expect(topBounce.velocity.y).toBeGreaterThan(0);+ expect(topBounce.position.y).toBeGreaterThanOrEqual(16);+ });++ it("keeps click shock distinct from violent shake and sleeping eyes", () => {+ expect(getCloudCodeMonsterExpression(null, false, false)).toBe("idle");+ expect(getCloudCodeMonsterExpression("sleeping", false, false)).toBe(+ "sleeping"+ );+ expect(getCloudCodeMonsterExpression("sleeping", true, false)).toBe(+ "shocked"+ );+ expect(getCloudCodeMonsterExpression(null, true, true)).toBe("shaken");+ expect(getCloudCodeMonsterExpression("phone", true, true, true)).toBe(+ "fainted"+ );+ });++ it("only treats fast drag or sharp fast reversal as a violent shake", () => {+ expect(isViolentMonsterDrag(10, 40)).toBe(false);+ expect(isViolentMonsterDrag(28, 120)).toBe(false);+ expect(isViolentMonsterDrag(28, 70, true)).toBe(false);+ expect(isViolentMonsterDrag(48, 50)).toBe(false);+ expect(isViolentMonsterDrag(58, 35)).toBe(true);+ expect(isViolentMonsterDrag(36, 20, true)).toBe(true);+ });++ it("detects sharp back-and-forth shake direction changes", () => {+ expect(+ hasViolentMonsterDirectionChange({ x: 30, y: 1 }, { x: -28, y: 0 })+ ).toBe(true);+ expect(+ hasViolentMonsterDirectionChange({ x: 30, y: 1 }, { x: 24, y: 2 })+ ).toBe(false);+ expect(+ hasViolentMonsterDirectionChange({ x: 12, y: 0 }, { x: -28, y: 0 })+ ).toBe(false);+ });++ it("requires sustained severe dragging before the monster faints", () => {+ expect(CLOUD_CODE_MONSTER_FAINT_MS).toBe(10_000);+ expect(isMonsterFaintShakeEvent(62, 42, true)).toBe(false);+ expect(isMonsterFaintShakeEvent(78, 52, false)).toBe(false);+ expect(isMonsterFaintShakeEvent(118, 38, false)).toBe(true);+ expect(isMonsterFaintShakeEvent(112, 40, true)).toBe(true);++ const sparseEvents = [0, CLOUD_CODE_MONSTER_FAINT_EVENT_WINDOW_MS + 1];+ const sustainedEvents = Array.from(+ { length: CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS },+ (_, index) => index * 100+ );++ expect(shouldFaintFromMonsterShake(sparseEvents, 1_500)).toBe(false);+ expect(shouldFaintFromMonsterShake(sustainedEvents, 300)).toBe(false);+ expect(shouldFaintFromMonsterShake(sustainedEvents, 600)).toBe(true);+ });++ it("uses shape-specific pixel face expression configuration", () => {+ const monsterPet = readFileSync(+ path.join(webRoot(), "src/components/home-pet/cloud-code-monster-pet.tsx"),+ "utf8"+ );++ expect(monsterPet).toContain("singleEye");+ expect(monsterPet).toContain('mouthStyle?: "flat" | "open" | "smile" | "none"');+ expect(monsterPet).toContain('case "pacman"');+ expect(monsterPet).toContain("leftX={58} rightX={58} y={43} singleEye");+ expect(monsterPet).toContain('case "snoopy"');+ expect(monsterPet).toContain("leftX={61} rightX={61} y={43}");+ expect(monsterPet).toContain('case "my-melody"');+ expect(monsterPet).toContain('shape === "kuromi"');+ expect(monsterPet).toContain('mouthStyle="smile"');+ expect(monsterPet).toContain('highlightColor="#fff5ee"');+ expect(monsterPet).toContain('mouthColor="#7a3c55"');+ expect(monsterPet).toContain('leftX={50} rightX={70} y={44} color="#edf6ff"');+ expect(monsterPet).toContain('case "hello-kitty"');+ expect(monsterPet).toContain('color="#25201f" highlightColor="#fffdfa"');+ expect(monsterPet).toContain('mouthColor="#7b4542" mouthStyle="smile"');+ });+});++describe("workspace PET mounting", () => {+ it("does not mount the PET on the public landing page", () => {+ const landingPage = readFileSync(+ path.join(webRoot(), "src/app/page.tsx"),+ "utf8"+ );++ expect(landingPage).not.toContain("HomepagePet");+ expect(landingPage).not.toContain("home-pet");+ });++ it("mounts the PET inside the authenticated workspace home canvas", () => {+ const workspaceHomePage = readFileSync(+ path.join(webRoot(), "src/app/(app)/w/[slug]/home/page.tsx"),+ "utf8"+ );++ expect(workspaceHomePage).toContain(+ 'import { CloudCodeMonsterPet } from "@/components/home-pet/cloud-code-monster-pet"'+ );+ expect(workspaceHomePage).toContain("activityTriggerMode={");+ expect(workspaceHomePage).toContain('petSettings.displayScope === "global" ? "global" : "home"');+ expect(workspaceHomePage).toContain("useHomePetSettings");+ expect(workspaceHomePage.indexOf("function AgentCanvas")).toBeLessThan(+ workspaceHomePage.indexOf("<CloudCodeMonsterPet")+ );+ });++ it("moves PET controls into workspace settings", () => {+ const settingsPage = readFileSync(+ path.join(webRoot(), "src/app/(app)/w/[slug]/settings/page.tsx"),+ "utf8"+ );+ const petTab = readFileSync(+ path.join(webRoot(), "src/app/(app)/w/[slug]/settings/pet-tab.tsx"),+ "utf8"+ );++ expect(settingsPage).toContain('{ id: "pet", label: "Pet" }');+ expect(settingsPage).toContain('import { PetTab } from "./pet-tab"');+ expect(settingsPage).toContain('activeTab === "pet" && <PetTab />');+ expect(petTab).toContain("Enable pet");+ expect(petTab).toContain("Homepage only");+ expect(petTab).toContain("Global Display");+ expect(petTab).toContain("CloudCodeMonsterPresetPreview");+ expect(petTab).toContain("writeCloudCodeMonsterPetPresetId");+ expect(petTab).not.toContain("selectedPreset.group");+ expect(petTab).not.toContain("preset.group");+ });++ it("mounts the global PET layer only for global non-home workspace pages", () => {+ const workspaceShell = readFileSync(+ path.join(webRoot(), "src/components/workspace-shell.tsx"),+ "utf8"+ );+ const workspacePetLayer = readFileSync(+ path.join(webRoot(), "src/components/home-pet/workspace-pet-layer.tsx"),+ "utf8"+ );++ expect(workspaceShell).toContain("WorkspacePetLayer");+ expect(workspaceShell).toContain("boundaryRef={shellRef}");+ expect(workspacePetLayer).toContain('petSettings.displayScope !== "global"');+ expect(workspacePetLayer).toContain('activityTriggerMode="global"');+ expect(workspacePetLayer).toContain("isHome");+ expect(workspacePetLayer).toContain("<CloudCodeMonsterPet");+ });++ it("exposes a public PET preview page without the authenticated app shell", () => {+ const previewRoute = readFileSync(+ path.join(webRoot(), "src/app/pet-preview/page.tsx"),+ "utf8"+ );+ const previewPage = readFileSync(+ path.join(webRoot(), "src/components/home-pet/pet-preview-page.tsx"),+ "utf8"+ );+ const monsterPet = readFileSync(+ path.join(webRoot(), "src/components/home-pet/cloud-code-monster-pet.tsx"),+ "utf8"+ );+ const globalCss = readFileSync(+ path.join(webRoot(), "src/app/globals.css"),+ "utf8"+ );+ const agentNode = readFileSync(+ path.join(webRoot(), "src/components/canvas/agent-node.tsx"),+ "utf8"+ );++ expect(previewRoute).toContain("PetPreviewPage");+ expect(previewPage).toContain("Home Page");+ expect(previewPage).toContain("Other Page");+ expect(previewPage).toContain("previewPetInitialPosition");+ expect(previewPage).toContain("CloudCodeMonsterPet");+ expect(previewPage).toContain("CloudCodeMonsterPresetPreview");+ expect(previewPage).toContain("CLOUD_CODE_MONSTER_PET_PRESETS");+ expect(previewPage).toContain("writeCloudCodeMonsterPetPresetId");+ expect(previewPage).toContain("Preset Library");+ expect(previewPage).not.toContain("selectedPreset.group");+ expect(previewPage).not.toContain("preset.group");+ expect(previewPage).toContain("thin-scrollbar");+ expect(previewPage).toContain("previewComebackToken");+ expect(previewPage).toContain("inboxCount");+ expect(previewPage).toContain("handleInboxClick");+ expect(previewPage).toContain("Inbox");+ expect(previewPage).toContain("notificationToken={inboxNotificationToken}");+ expect(monsterPet).toContain("cloud-code-monster-pet-shock");+ expect(monsterPet).toContain("notificationToken?: number");+ expect(monsterPet).toContain("notificationActive");+ expect(monsterPet).toContain("cloud-code-monster-pet-notification-bell");+ expect(monsterPet).toContain("cloud-code-monster-pet-notification-bell-pixel");+ expect(monsterPet).toContain('shapeRendering="crispEdges"');+ expect(monsterPet).not.toContain('d="M6.5 10.5');+ expect(monsterPet).toContain("data-notifying={notificationActive}");+ expect(monsterPet).toContain(CLOUD_CODE_MONSTER_PRESET_STORAGE_KEY);+ expect(monsterPet).toContain(CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT);+ expect(monsterPet).toContain("CloudCodeMonsterPresetPreview");+ expect(monsterPet).toContain("getCloudCodeMonsterPreset");+ expect(monsterPet).toContain('activityTriggerMode = "global"');+ expect(monsterPet).toContain('activityTriggerMode === "home"');+ expect(monsterPet).toContain("MonsterDirectPixelCharacter");+ expect(monsterPet).toContain('case "doraemon"');+ expect(monsterPet).toContain('case "minecraft-steve"');+ expect(monsterPet).toContain('case "minecraft-creeper"');+ expect(monsterPet).toContain('case "minecraft-zombie"');+ expect(monsterPet).not.toContain("MonsterLicensedShapeBase");+ expect(monsterPet).not.toContain("MonsterLicensedShapeFeet");+ expect(monsterPet).toContain('feature === "bolt"');+ expect(monsterPet).toContain('feature === "mushroom"');+ expect(monsterPet).toContain("MonsterPresetBodyMarks");+ expect(monsterPet).toContain(+ 'data-reaction={shaken ? "shake" : reacting ? "shock" : "none"}'+ );+ expect(monsterPet).toContain('expression === "shocked"');+ expect(monsterPet).toContain('expression === "shaken"');+ expect(monsterPet).toContain('expression === "fainted"');+ expect(monsterPet).toContain("data-shaken");+ expect(monsterPet).toContain("data-fainted");+ expect(monsterPet).toContain("data-peeking");+ expect(monsterPet).toContain("cloud-code-monster-pet-sleep-z");+ expect(monsterPet).not.toContain('<rect x="88" y="19" width="6" height="6"');+ expect(monsterPet).toContain("isViolentMonsterDrag");+ expect(monsterPet).toContain("hasViolentMonsterDirectionChange");+ expect(monsterPet).toContain("isMonsterFaintShakeEvent");+ expect(monsterPet).toContain("shouldFaintFromMonsterShake");+ expect(monsterPet).toContain("reflectCloudCodeMonsterWalk");+ expect(monsterPet).toContain("createCloudCodeMonsterWalkVelocity");+ expect(monsterPet).toContain("autoWalkVelocityRef");+ expect(monsterPet).toContain("wakeMonsterToDefault");+ expect(monsterPet).not.toContain("event.button !== 0 || fainted");+ expect(monsterPet).not.toContain("!isDragging || fainted");+ expect(previewPage).not.toContain("previewWorkingAgentPeekTargets");+ expect(previewPage).not.toContain("peekTargets=");+ expect(previewPage).not.toContain('agentId: "ag_mandy"');+ expect(previewPage).not.toContain('agentId: "ag_fenge"');+ expect(previewPage).toContain('className="pet-preview-flow"');+ expect(globalCss).toContain(".pet-preview-flow .react-flow__node");+ expect(globalCss).toContain("z-index: 30 !important");+ expect(globalCss).toContain('.cloud-code-monster-pet[data-peeking="true"]');+ expect(globalCss).toContain("z-index: 2;");+ expect(monsterPet).toContain("resolveCloudCodeMonsterPeekPosition");+ expect(monsterPet).toContain("[data-agent-node-id]");+ expect(monsterPet).not.toContain("cloud-code-monster-pet-peek-cover");+ expect(agentNode).toContain("data-agent-node-id={agent.id}");+ expect(agentNode).toContain(+ 'data-agent-working={activeTaskCount > 0 ? "true" : "false"}'+ );+ expect(previewPage).not.toContain("<HomepagePet");+ expect(monsterPet).not.toContain("cloud-code-monster-pet-bubble");+ expect(previewPage).not.toContain("sign-in");+ expect(previewPage).not.toContain("WorkspaceShell");+ });++ it("resolves peeking coordinates from a real agent node before using fallback coordinates", () => {+ const agentNode = {+ dataset: { agentNodeId: "ag_mandy" },+ getBoundingClientRect: () => ({+ left: 260,+ top: 360,+ width: 220,+ height: 96,+ }),+ };+ const boundary = {+ querySelectorAll: () => [agentNode],+ getBoundingClientRect: () => ({ left: 20, top: 40 }),+ } as unknown as HTMLElement;++ const resolved = resolveCloudCodeMonsterPeekPosition(+ { agentId: "ag_mandy", x: 1, y: 1 },+ boundary,+ { width: 1000, height: 720 }+ );++ expect(resolved.x).toBeCloseTo(309);+ expect(resolved.y).toBeCloseTo(305.24);+ expect(+ resolveCloudCodeMonsterPeekPosition(+ { agentId: "missing", x: 245, y: 345 },+ boundary,+ { width: 1000, height: 720 }+ )+ ).toEqual({ x: 204, y: 283 });+ });+});diff --git a/src/web/src/components/home-pet/homepage-pet.tsx b/src/web/src/components/home-pet/homepage-pet.tsxnew file mode 100644index 000000000..52c489da1--- /dev/null+++ b/src/web/src/components/home-pet/homepage-pet.tsx@@ -0,0 +1,320 @@+"use client";++import {+ type CSSProperties,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+ useEffect,+ useMemo,+ useRef,+ useState,+} from "react";+import {+ getDefaultPetPosition,+ getPetPreset,+ getReactionScene,+ getReactionReturnScene,+ getSpriteFrameDelay,+ HOME_PET_ATLAS,+ HOME_PET_REACTION_MS,+ HOME_PET_SIZE,+ selectAmbientScene,+ selectNextAmbientScene,+ type PetBounds,+ type PetPoint,+ type PetScene,+} from "./pet-presets";+import { clampPetPosition } from "./pet-presets";++type HomepagePetProps = {+ boundaryRef: RefObject<HTMLElement | null>;+ presetId?: string;+ initialPosition?: PetPoint;+};++function getHomepageBounds(boundary: HTMLElement | null): PetBounds {+ const width = boundary?.clientWidth ?? window.innerWidth;+ const height = boundary?.clientHeight ?? window.innerHeight;++ return {+ width,+ height,+ };+}++function getPointerPointInBoundary(+ event: ReactPointerEvent<HTMLButtonElement>,+ boundary: HTMLElement | null+): PetPoint {+ const boundaryRect = boundary?.getBoundingClientRect();++ return {+ x: event.clientX - (boundaryRect?.left ?? 0),+ y: event.clientY - (boundaryRect?.top ?? 0),+ };+}++export function HomepagePet({ boundaryRef, presetId, initialPosition }: HomepagePetProps) {+ const preset = getPetPreset(presetId);+ const [{ scene, lastAmbientScene }, setSceneState] = useState<{+ scene: PetScene;+ lastAmbientScene: PetScene;+ }>(() => {+ const initialScene = preset.scenes[preset.homeScene];++ return {+ scene: initialScene,+ lastAmbientScene: initialScene,+ };+ });+ const [position, setPosition] = useState<PetPoint | null>(null);+ const [isDragging, setIsDragging] = useState(false);+ const [spriteFrame, setSpriteFrame] = useState(0);+ const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);+ const dragOffsetRef = useRef<PetPoint>({ x: 0, y: 0 });+ const dragStartPointRef = useRef<PetPoint | null>(null);+ const didDragRef = useRef(false);+ const reactionTimerRef = useRef<number | null>(null);+ const resizeObserverRef = useRef<ResizeObserver | null>(null);+ const sceneAsset = scene.asset ?? preset.sprite;+ const spriteStyle = useMemo(+ () =>+ ({+ "--home-pet-sprite-url": `url("${sceneAsset.src}")`,+ "--home-pet-bg-width": `${HOME_PET_ATLAS.columns * HOME_PET_SIZE.width}px`,+ "--home-pet-bg-height": `${HOME_PET_ATLAS.rows * HOME_PET_SIZE.height}px`,+ "--home-pet-bg-x": `${-spriteFrame * HOME_PET_SIZE.width}px`,+ "--home-pet-bg-y": `${-scene.spriteAnimation.row * HOME_PET_SIZE.height}px`,+ }) as CSSProperties,+ [scene.spriteAnimation.row, sceneAsset.src, spriteFrame]+ );++ useEffect(() => {+ const initialScene = selectAmbientScene(preset);++ setSceneState({+ scene: initialScene,+ lastAmbientScene: initialScene,+ });+ }, [preset]);++ useEffect(() => {+ const mediaQuery = window.matchMedia("(prefers-reduced-motion: reduce)");+ const updateReducedMotion = () =>+ setPrefersReducedMotion(mediaQuery.matches);++ updateReducedMotion();+ mediaQuery.addEventListener("change", updateReducedMotion);++ return () => mediaQuery.removeEventListener("change", updateReducedMotion);+ }, []);++ useEffect(() => {+ const syncPosition = () => {+ const bounds = getHomepageBounds(boundaryRef.current);++ setPosition((currentPosition) =>+ currentPosition+ ? clampPetPosition(currentPosition, bounds)+ : clampPetPosition(initialPosition ?? getDefaultPetPosition(bounds), bounds)+ );+ };++ syncPosition();+ window.addEventListener("resize", syncPosition);+ if (typeof ResizeObserver !== "undefined" && boundaryRef.current) {+ resizeObserverRef.current = new ResizeObserver(syncPosition);+ resizeObserverRef.current.observe(boundaryRef.current);+ }++ return () => {+ window.removeEventListener("resize", syncPosition);+ resizeObserverRef.current?.disconnect();+ resizeObserverRef.current = null;+ };+ }, [boundaryRef, initialPosition]);++ useEffect(() => {+ return () => {+ if (reactionTimerRef.current) {+ window.clearTimeout(reactionTimerRef.current);+ }+ };+ }, []);++ useEffect(() => {+ setSpriteFrame(0);+ }, [scene.name]);++ useEffect(() => {+ if (prefersReducedMotion) {+ return;+ }++ const animation = scene.spriteAnimation;+ const isLastFrame = spriteFrame >= animation.frames - 1;++ if (scene.kind === "reaction" && isLastFrame) {+ return;+ }++ const duration = getSpriteFrameDelay(scene, spriteFrame);+ const timeout = window.setTimeout(() => {+ if (!isLastFrame) {+ setSpriteFrame(spriteFrame + 1);+ return;+ }++ setSpriteFrame(0);++ if (scene.kind === "ambient") {+ const nextScene = selectNextAmbientScene(preset, scene.name);+ setSceneState({+ scene: nextScene,+ lastAmbientScene: nextScene,+ });+ }+ }, duration);++ return () => window.clearTimeout(timeout);+ }, [preset, prefersReducedMotion, scene, spriteFrame]);++ const startReaction = () => {+ if (didDragRef.current) {+ didDragRef.current = false;+ return;+ }++ if (isDragging) {+ return;+ }++ if (reactionTimerRef.current) {+ window.clearTimeout(reactionTimerRef.current);+ }++ const returnScene = getReactionReturnScene(preset, lastAmbientScene.name);+ const reactionScene = getReactionScene(preset);++ if (!reactionScene) {+ return;+ }++ setSceneState({+ scene: reactionScene,+ lastAmbientScene: returnScene,+ });++ reactionTimerRef.current = window.setTimeout(() => {+ setSceneState({+ scene: returnScene,+ lastAmbientScene: returnScene,+ });+ reactionTimerRef.current = null;+ }, HOME_PET_REACTION_MS);+ };++ const handlePointerDown = (+ event: ReactPointerEvent<HTMLButtonElement>+ ) => {+ if (event.button !== 0) {+ return;+ }++ const bounds = getHomepageBounds(boundaryRef.current);+ const currentPosition = position ?? getDefaultPetPosition(bounds);+ const pointerPoint = getPointerPointInBoundary(event, boundaryRef.current);++ dragOffsetRef.current = {+ x: pointerPoint.x - currentPosition.x,+ y: pointerPoint.y - currentPosition.y,+ };+ dragStartPointRef.current = pointerPoint;+ didDragRef.current = false;+ setIsDragging(true);+ event.currentTarget.setPointerCapture(event.pointerId);+ };++ const handlePointerMove = (+ event: ReactPointerEvent<HTMLButtonElement>+ ) => {+ if (!isDragging) {+ return;+ }++ const bounds = getHomepageBounds(boundaryRef.current);+ const pointerPoint = getPointerPointInBoundary(event, boundaryRef.current);+ const nextPosition = {+ x: pointerPoint.x - dragOffsetRef.current.x,+ y: pointerPoint.y - dragOffsetRef.current.y,+ };+ const dragStartPoint = dragStartPointRef.current ?? pointerPoint;+ const movementX = Math.abs(pointerPoint.x - dragStartPoint.x);+ const movementY = Math.abs(pointerPoint.y - dragStartPoint.y);++ if (movementX > 3 || movementY > 3) {+ didDragRef.current = true;+ }++ setPosition(+ clampPetPosition(nextPosition, bounds)+ );+ };++ const stopDragging = (event: ReactPointerEvent<HTMLButtonElement>) => {+ if (!isDragging) {+ return;+ }++ setIsDragging(false);+ dragStartPointRef.current = null;++ if (event.currentTarget.hasPointerCapture(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId);+ }+ };++ if (!position) {+ return null;+ }++ return (+ <aside+ aria-label={`${preset.displayName} workspace PET status`}+ className="home-pet"+ data-scene-kind={scene.kind}+ style={{+ "--home-pet-x": `${position.x}px`,+ "--home-pet-y": `${position.y}px`,+ } as CSSProperties}+ >+ <div className="home-pet-status" aria-live="polite">+ <span className="home-pet-status-kicker">{preset.displayName}</span>+ <span>{scene.statusText}</span>+ </div>+ <button+ type="button"+ className={`home-pet-button ${scene.animationClass}`}+ data-dragging={isDragging}+ onClick={startReaction}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={stopDragging}+ onPointerCancel={stopDragging}+ onLostPointerCapture={stopDragging}+ aria-label={`${preset.displayName}: ${scene.statusText}. Click to greet, drag to move.`}+ style={{+ width: HOME_PET_SIZE.width,+ height: HOME_PET_SIZE.height,+ }}+ >+ <span+ aria-label={sceneAsset.alt}+ className="home-pet-sprite"+ role="img"+ style={spriteStyle}+ />+ </button>+ </aside>+ );+}diff --git a/src/web/src/components/home-pet/pet-presets.ts b/src/web/src/components/home-pet/pet-presets.tsnew file mode 100644index 000000000..c49710c37--- /dev/null+++ b/src/web/src/components/home-pet/pet-presets.ts@@ -0,0 +1,295 @@+export type PetSceneKind = "ambient" | "reaction";++export type PetSceneName = string;++export type PetScene = {+ name: PetSceneName;+ label: string;+ kind: PetSceneKind;+ statusText: string;+ animationClass: string;+ spriteAnimation: PetSpriteAnimation;+ asset?: PetSpriteAsset;+ returnTo?: PetSceneName;+};++export type PetSpriteAnimation = {+ row: number;+ frames: number;+ frameDurations: readonly number[];+ restDurationMs?: readonly [number, number];+};++export type PetSpriteAsset = {+ src: string;+ alt: string;+};++export type PetPreset = {+ id: string;+ displayName: string;+ description: string;+ sprite: PetSpriteAsset;+ homeScene: PetSceneName;+ reactionScene?: PetSceneName;+ scenes: Record<PetSceneName, PetScene>;+};++export type PetPoint = {+ x: number;+ y: number;+};++export type PetBounds = {+ width: number;+ height: number;+};++export type PetSize = {+ width: number;+ height: number;+};++export const HOME_PET_SIZE: PetSize = {+ width: 72,+ height: 78,+};++export const HOME_PET_ATLAS = {+ columns: 8,+ rows: 9,+ cellWidth: 192,+ cellHeight: 208,+} as const;++export const HOME_PET_REACTION_MS = 900;+export const HOME_PET_FRAME_REST_MS = [5600, 12800] as const;++export const HOME_PET_PRESETS: PetPreset[] = [+ {+ id: "tater",+ displayName: "Tater",+ description:+ "A cheerful potato mascot with visor goggles and chunky futuristic sneakers.",+ sprite: {+ src: "/pets/tater/spritesheet.webp",+ alt: "Tater, the Alook workspace PET",+ },+ homeScene: "idle",+ reactionScene: "startled",+ scenes: {+ idle: {+ name: "idle",+ label: "Idle",+ kind: "ambient",+ statusText: "keeping the workspace warm",+ animationClass: "home-pet-motion-idle",+ spriteAnimation: {+ row: 0,+ frames: 6,+ frameDurations: [520, 120, 110, 130, 120, 180],+ restDurationMs: HOME_PET_FRAME_REST_MS,+ },+ },+ watching: {+ name: "watching",+ label: "Watching",+ kind: "ambient",+ statusText: "watching the agents wake up",+ animationClass: "home-pet-motion-watch",+ spriteAnimation: {+ row: 8,+ frames: 6,+ frameDurations: [220, 120, 120, 130, 130, 180],+ restDurationMs: HOME_PET_FRAME_REST_MS,+ },+ },+ scrolling: {+ name: "scrolling",+ label: "Scrolling",+ kind: "ambient",+ statusText: "checking the latest task cards",+ animationClass: "home-pet-motion-scroll",+ spriteAnimation: {+ row: 6,+ frames: 6,+ frameDurations: [240, 120, 120, 125, 125, 180],+ restDurationMs: HOME_PET_FRAME_REST_MS,+ },+ },+ napping: {+ name: "napping",+ label: "Napping",+ kind: "ambient",+ statusText: "taking a tiny systems nap",+ animationClass: "home-pet-motion-nap",+ spriteAnimation: {+ row: 5,+ frames: 8,+ frameDurations: [420, 130, 130, 130, 130, 130, 130, 220],+ restDurationMs: [7200, 14800],+ },+ },+ thinking: {+ name: "thinking",+ label: "Thinking",+ kind: "ambient",+ statusText: "thinking through a handoff",+ animationClass: "home-pet-motion-think",+ spriteAnimation: {+ row: 3,+ frames: 4,+ frameDurations: [260, 130, 130, 220],+ restDurationMs: [6200, 13200],+ },+ },+ startled: {+ name: "startled",+ label: "Noticed",+ kind: "reaction",+ statusText: "noticed you",+ animationClass: "home-pet-motion-startled",+ spriteAnimation: {+ row: 4,+ frames: 5,+ frameDurations: [140, 140, 140, 140, 280],+ },+ returnTo: "idle",+ },+ },+ },+];++export function getPetPreset(presetId = "tater") {+ return (+ HOME_PET_PRESETS.find((preset) => preset.id === presetId) ??+ HOME_PET_PRESETS[0]+ );+}++export function getAmbientScenes(preset: PetPreset) {+ return Object.values(preset.scenes).filter(+ (scene) => scene.kind === "ambient"+ );+}++export function selectAmbientScene(+ preset: PetPreset,+ randomValue = Math.random()+) {+ const ambientScenes = getAmbientScenes(preset);+ const safeRandomValue = Number.isFinite(randomValue) ? randomValue : 0;+ const index = Math.min(+ ambientScenes.length - 1,+ Math.max(0, Math.floor(safeRandomValue * ambientScenes.length))+ );++ return ambientScenes[index] ?? preset.scenes[preset.homeScene];+}++export function selectNextAmbientScene(+ preset: PetPreset,+ previousSceneName: PetSceneName,+ randomValue = Math.random()+) {+ const homeScene = preset.scenes[preset.homeScene];++ if (previousSceneName !== preset.homeScene) {+ return homeScene;+ }++ const burstScenes = getAmbientScenes(preset).filter(+ (scene) => scene.name !== preset.homeScene+ );++ if (burstScenes.length === 0) {+ return homeScene;+ }++ const safeRandomValue = Number.isFinite(randomValue) ? randomValue : 0;++ if (safeRandomValue < 0.68) {+ return homeScene;+ }++ const burstRandom = (safeRandomValue - 0.68) / 0.32;+ const index = Math.min(+ burstScenes.length - 1,+ Math.max(0, Math.floor(burstRandom * burstScenes.length))+ );++ return burstScenes[index] ?? homeScene;+}++export function getReactionReturnScene(+ preset: PetPreset,+ previousSceneName: PetSceneName+) {+ const previousScene = preset.scenes[previousSceneName];++ if (previousScene?.kind === "ambient") {+ return previousScene;+ }++ return preset.scenes[previousScene?.returnTo ?? preset.homeScene];+}++export function getReactionScene(preset: PetPreset) {+ const configuredScene = preset.reactionScene+ ? preset.scenes[preset.reactionScene]+ : undefined;++ if (configuredScene?.kind === "reaction") {+ return configuredScene;+ }++ return Object.values(preset.scenes).find(+ (scene) => scene.kind === "reaction"+ );+}++export function clampPetPosition(+ position: PetPoint,+ bounds: PetBounds,+ size: PetSize = HOME_PET_SIZE,+ padding = 16+) {+ const maxX = Math.max(padding, bounds.width - size.width - padding);+ const maxY = Math.max(padding, bounds.height - size.height - padding);++ return {+ x: Math.min(maxX, Math.max(padding, position.x)),+ y: Math.min(maxY, Math.max(padding, position.y)),+ };+}++export function getDefaultPetPosition(bounds: PetBounds) {+ return clampPetPosition(+ {+ x: bounds.width - HOME_PET_SIZE.width - 64,+ y: Math.min(bounds.height * 0.44, bounds.height - HOME_PET_SIZE.height - 112),+ },+ bounds+ );+}++export function getSpriteFrameDelay(+ scene: PetScene,+ spriteFrame: number,+ randomValue = Math.random()+) {+ const animation = scene.spriteAnimation;+ const isRestingFrame = spriteFrame === 0;++ if (scene.kind === "ambient" && isRestingFrame && animation.restDurationMs) {+ const [minRest, maxRest] = animation.restDurationMs;+ const safeRandomValue = Number.isFinite(randomValue) ? randomValue : 0;+ return minRest + Math.round((maxRest - minRest) * safeRandomValue);+ }++ return (+ animation.frameDurations[spriteFrame] ??+ animation.frameDurations[animation.frameDurations.length - 1] ??+ 150+ );+}diff --git a/src/web/src/components/home-pet/pet-preview-page.tsx b/src/web/src/components/home-pet/pet-preview-page.tsxnew file mode 100644index 000000000..78f314b9c--- /dev/null+++ b/src/web/src/components/home-pet/pet-preview-page.tsx@@ -0,0 +1,747 @@+"use client";++import { useEffect, useMemo, useRef, useState } from "react";+import {+ Background,+ BackgroundVariant,+ ReactFlow,+ ReactFlowProvider,+ type Edge,+ type Node,+} from "@xyflow/react";+import "@xyflow/react/dist/style.css";+import type { Agent, AgentRuntime } from "@alook/shared";+import {+ ArrowLeftRight,+ CalendarDays,+ CircleDot,+ GitBranch,+ Home,+ Inbox,+ Maximize2,+ Minus,+ Monitor,+ Plus,+ RotateCcw,+ Search,+ Settings,+ SunMoon,+ ZoomIn,+ ZoomOut,+} from "lucide-react";+import { GradientBackground } from "@/components/gradient-background";+import { Logo } from "@/components/logo";+import { AgentNode, type AgentNodeData } from "@/components/canvas/agent-node";+import { LinkEdge } from "@/components/canvas/link-edge";+import { AnimatedAvatar, parseAvatarUrl, serializeAvatarConfig } from "@/components/avatar";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import {+ CloudCodeMonsterPet,+ CloudCodeMonsterPresetPreview,+ CLOUD_CODE_MONSTER_PET_PRESETS,+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ getCloudCodeMonsterPreset,+ readCloudCodeMonsterPetPresetId,+ writeCloudCodeMonsterPetPresetId,+} from "@/components/home-pet/cloud-code-monster-pet";+import { WorkspaceProvider } from "@/contexts/workspace-context";+import { cn } from "@/lib/utils";++type PreviewPage = "home" | "other";++const nodeTypes = { agent: AgentNode };+const edgeTypes = { link: LinkEdge };+const now = "2026-05-07T00:00:00.000Z";+const previewPetInitialPosition = { x: 640, y: 330 };++function avatar(shape: string, eye: string, nose: string, bg: number) {+ return serializeAvatarConfig({ shape, eye, nose, bg });+}++const previewRuntime: AgentRuntime = {+ id: "rt_preview",+ workspace_id: "ws_preview",+ daemon_id: "daemon_preview",+ runtime_mode: "local",+ provider: "codex",+ status: "online",+ device_info: "MacBook Preview",+ metadata: {},+ last_seen_at: now,+ created_at: now,+ updated_at: now,+};++const previewAgents: Agent[] = [+ {+ id: "ag_huzi",+ workspace_id: "ws_preview",+ runtime_id: previewRuntime.id,+ name: "户子",+ description: "MacBook / local execution",+ instructions: "",+ runtime_mode: "local",+ runtime_config: {},+ status: "idle",+ max_concurrent_tasks: 6,+ email_handle: "huzi",+ avatar_url: avatar("task", "dots", "dot", 1),+ visibility: "private",+ owner_id: null,+ created_at: now,+ updated_at: now,+ },+ {+ id: "ag_jesse",+ workspace_id: "ws_preview",+ runtime_id: previewRuntime.id,+ name: "杰西",+ description: "Implementation / technical check",+ instructions: "",+ runtime_mode: "local",+ runtime_config: {},+ status: "idle",+ max_concurrent_tasks: 6,+ email_handle: "jesse",+ avatar_url: avatar("book", "happy", "dash", 9),+ visibility: "private",+ owner_id: null,+ created_at: now,+ updated_at: now,+ },+ {+ id: "ag_mandy",+ workspace_id: "ws_preview",+ runtime_id: previewRuntime.id,+ name: "曼迪",+ description: "Coordination / acceptance",+ instructions: "",+ runtime_mode: "local",+ runtime_config: {},+ status: "idle",+ max_concurrent_tasks: 6,+ email_handle: "mandy",+ avatar_url: avatar("task", "dots", "dot", 5),+ visibility: "private",+ owner_id: null,+ created_at: now,+ updated_at: now,+ },+ {+ id: "ag_tony",+ workspace_id: "ws_preview",+ runtime_id: previewRuntime.id,+ name: "托尼",+ description: "Engineering execution",+ instructions: "",+ runtime_mode: "local",+ runtime_config: {},+ status: "idle",+ max_concurrent_tasks: 6,+ email_handle: "tony",+ avatar_url: avatar("book", "happy", "dash", 11),+ visibility: "private",+ owner_id: null,+ created_at: now,+ updated_at: now,+ },+ {+ id: "ag_fenge",+ workspace_id: "ws_preview",+ runtime_id: previewRuntime.id,+ name: "峰哥",+ description: "Email owner",+ instructions: "",+ runtime_mode: "local",+ runtime_config: {},+ status: "idle",+ max_concurrent_tasks: 6,+ email_handle: "fenge",+ avatar_url: avatar("mail", "dots", "smile", 3),+ visibility: "private",+ owner_id: null,+ created_at: now,+ updated_at: now,+ },+];++const taskCounts: Record<string, number> = {+ ag_mandy: 1,+ ag_fenge: 1,+};++const previewNodes: Node<AgentNodeData>[] = [+ { id: "ag_huzi", type: "agent", position: { x: 0, y: 0 }, data: { agent: previewAgents[0]!, runtimes: [previewRuntime], activeTaskCount: 0, slug: "preview", index: 0 } },+ { id: "ag_jesse", type: "agent", position: { x: 360, y: 0 }, data: { agent: previewAgents[1]!, runtimes: [previewRuntime], activeTaskCount: 0, slug: "preview", index: 1 } },+ { id: "ag_mandy", type: "agent", position: { x: 0, y: 220 }, data: { agent: previewAgents[2]!, runtimes: [previewRuntime], activeTaskCount: 1, slug: "preview", index: 2 } },+ { id: "ag_tony", type: "agent", position: { x: 360, y: 220 }, data: { agent: previewAgents[3]!, runtimes: [previewRuntime], activeTaskCount: 0, slug: "preview", index: 3 } },+ { id: "ag_fenge", type: "agent", position: { x: 720, y: 220 }, data: { agent: previewAgents[4]!, runtimes: [previewRuntime], activeTaskCount: 1, slug: "preview", index: 4 } },+];++const previewEdges: Edge[] = [+ {+ id: "edge-huzi-jesse",+ source: "ag_huzi",+ target: "ag_jesse",+ sourceHandle: "right",+ targetHandle: "target-left",+ type: "link",+ data: { instruction: "" },+ },+ {+ id: "edge-huzi-mandy",+ source: "ag_huzi",+ target: "ag_mandy",+ sourceHandle: "bottom",+ targetHandle: "target-top",+ type: "link",+ data: { instruction: "<p>preview</p>" },+ },+ {+ id: "edge-mandy-tony",+ source: "ag_mandy",+ target: "ag_tony",+ sourceHandle: "right",+ targetHandle: "target-left",+ type: "link",+ data: { instruction: "<p>preview</p>" },+ },+ {+ id: "edge-jesse-tony",+ source: "ag_jesse",+ target: "ag_tony",+ sourceHandle: "bottom",+ targetHandle: "target-top",+ type: "link",+ data: { instruction: "<p>preview</p>" },+ },+ {+ id: "edge-jesse-fenge",+ source: "ag_jesse",+ target: "ag_fenge",+ sourceHandle: "right",+ targetHandle: "target-top",+ type: "link",+ data: { instruction: "<p>preview</p>" },+ },+ {+ id: "edge-tony-fenge",+ source: "ag_tony",+ target: "ag_fenge",+ sourceHandle: "right",+ targetHandle: "target-left",+ type: "link",+ data: { instruction: "<p>preview</p>" },+ },+];++function PageSwitch({+ activePage,+ onPageChange,+}: {+ activePage: PreviewPage;+ onPageChange: (page: PreviewPage) => void;+}) {+ return (+ <div className="absolute left-4 top-4 z-50 inline-flex rounded-lg bg-background/80 p-1 ring-1 ring-foreground/5 shadow-sm backdrop-blur-sm">+ {[+ ["home", "Home Page"],+ ["other", "Other Page"],+ ].map(([id, label]) => (+ <button+ key={id}+ type="button"+ aria-pressed={activePage === id}+ onClick={() => onPageChange(id as PreviewPage)}+ className="h-7 min-w-22 rounded-md px-2.5 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-foreground data-[active=true]:bg-accent data-[active=true]:text-foreground"+ data-active={activePage === id}+ >+ {label}+ </button>+ ))}+ </div>+ );+}++function PreviewSidebarAgent({ agent, isActive }: { agent: Agent; isActive?: boolean }) {+ const [hovered, setHovered] = useState(false);+ const avatarConfig = parseAvatarUrl(agent.avatar_url);++ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ onClick={(event) => event.preventDefault()}+ className={cn(+ "relative flex shrink-0 items-center justify-center size-10 rounded-xl text-sm font-medium transition-all duration-200 cursor-pointer",+ isActive+ ? "ring-2 ring-primary shadow-sm"+ : "ring-0 bg-secondary text-secondary-foreground hover:bg-accent"+ )}+ />+ }+ >+ {avatarConfig ? (+ <AnimatedAvatar+ config={avatarConfig}+ size={40}+ className="rounded-xl"+ isHovered={hovered}+ isWorking={(taskCounts[agent.id] ?? 0) > 0}+ />+ ) : (+ agent.name.charAt(0).toUpperCase()+ )}+ <span className="absolute bottom-0 right-0 size-2 rounded-full bg-status-online ring-2 ring-background" />+ </TooltipTrigger>+ <TooltipContent side="right">{agent.name}</TooltipContent>+ </Tooltip>+ );+}++function PreviewSidebarButton({+ label,+ active,+ onClick,+ children,+}: {+ label: string;+ active?: boolean;+ onClick?: () => void;+ children: React.ReactNode;+}) {+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={(event) => {+ event.preventDefault();+ onClick?.();+ }}+ className={cn(+ "flex items-center justify-center size-10 rounded-xl transition-colors duration-200 cursor-pointer",+ "text-muted-foreground hover:text-foreground hover:bg-accent",+ active && "bg-accent text-foreground"+ )}+ />+ }+ >+ {children}+ </TooltipTrigger>+ <TooltipContent side="right">{label}</TooltipContent>+ </Tooltip>+ );+}++function PreviewSidebar({+ inboxCount,+ onInboxClick,+}: {+ inboxCount: number;+ onInboxClick: () => void;+}) {+ return (+ <nav className="flex h-full w-14 flex-col items-center gap-0.5 pt-1 pb-2">+ <div className="mb-1 pb-1.5">+ <div className="flex size-8 shrink-0 cursor-pointer items-center justify-center transition-transform active:scale-90 [&>button]:pointer-events-none">+ <Logo size="sm" iconOnly />+ </div>+ </div>++ <div className="mb-1 flex flex-col items-center gap-1.5 border-b border-border/50 pb-1.5">+ <PreviewSidebarButton label="Home" active>+ <Home className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Threads">+ <GitBranch className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Issues">+ <CircleDot className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label={`Inbox (${inboxCount})`} onClick={onInboxClick} active={inboxCount > 0}>+ <span className="relative grid size-4 place-items-center">+ <Inbox className="size-4" />+ {inboxCount > 0 ? (+ <span className="absolute -right-2 -top-2 grid min-w-3.5 place-items-center rounded-full bg-primary px-1 text-[9px] font-semibold leading-3 text-primary-foreground">+ {Math.min(inboxCount, 9)}+ </span>+ ) : null}+ </span>+ </PreviewSidebarButton>+ </div>++ <div className="scrollbar-none flex w-full flex-1 flex-col items-center gap-1.5 overflow-y-auto py-1">+ {previewAgents.map((agent, index) => (+ <PreviewSidebarAgent key={agent.id} agent={agent} isActive={index === 2} />+ ))}+ <button+ type="button"+ title="New agent"+ onClick={(event) => event.preventDefault()}+ className="flex size-10 shrink-0 cursor-pointer items-center justify-center rounded-xl border border-dashed border-foreground/15 text-muted-foreground transition-colors duration-200 hover:border-foreground/30 hover:bg-accent hover:text-foreground"+ >+ <Plus className="size-4" />+ </button>+ </div>++ <div className="mt-1 flex flex-col items-center gap-1 border-t border-border/50 pt-2">+ <PreviewSidebarButton label="Calendar">+ <CalendarDays className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Runtimes">+ <Monitor className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Toggle theme">+ <SunMoon className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Settings">+ <Settings className="size-4" />+ </PreviewSidebarButton>+ <PreviewSidebarButton label="Switch workspace">+ <ArrowLeftRight className="size-4" />+ </PreviewSidebarButton>+ <button+ type="button"+ aria-label="Preview user"+ onClick={(event) => event.preventDefault()}+ className="grid size-8 place-items-center rounded-full bg-secondary text-xs font-medium text-secondary-foreground transition-colors hover:bg-accent"+ >+ T+ </button>+ </div>+ </nav>+ );+}++function PreviewToolbar() {+ const buttons = [+ ["Zoom in", ZoomIn],+ ["Zoom out", ZoomOut],+ ["Fit canvas", Maximize2],+ ["Reset layout", RotateCcw],+ ] as const;++ return (+ <div+ className="absolute bottom-4 left-4 z-40 flex animate-[fade-up_300ms_ease-out_both] gap-0.5 rounded-lg bg-background/80 p-1 ring-1 ring-foreground/5 backdrop-blur-sm"+ style={{ animationDelay: "200ms" }}+ >+ {buttons.map(([label, Icon]) => (+ <button+ key={label}+ type="button"+ aria-label={label}+ onClick={(event) => event.preventDefault()}+ className="flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"+ >+ <Icon className="size-4" />+ </button>+ ))}+ </div>+ );+}++function PreviewCreateButton() {+ return (+ <button+ type="button"+ title="Create new agent"+ onClick={(event) => event.preventDefault()}+ className="absolute top-4 right-4 z-40 flex size-8 animate-[fade-up_300ms_ease-out_both] items-center justify-center rounded-lg bg-background/80 text-muted-foreground ring-1 ring-foreground/5 backdrop-blur-sm transition-colors hover:bg-accent hover:text-foreground"+ style={{ animationDelay: "200ms" }}+ >+ <Plus className="size-4" />+ </button>+ );+}++function PreviewTasksFloat() {+ return (+ <div+ role="region"+ aria-label="Active tasks preview"+ className="absolute right-4 bottom-4 z-10 w-80 animate-[fade-up_300ms_ease-out_both] rounded-lg bg-background/90 shadow-sm ring-1 ring-foreground/8 backdrop-blur-sm"+ >+ <div className="flex items-center justify-between border-b border-border/50 px-3 py-2">+ <div className="flex items-center gap-2 text-sm font-medium">+ <span className="size-1.5 animate-pulse rounded-full bg-primary" />+ <span>2 tasks active</span>+ </div>+ <div className="flex items-center gap-0.5 text-muted-foreground">+ <button type="button" aria-label="Minimize tasks" className="flex size-6 items-center justify-center rounded-md transition-colors hover:bg-accent hover:text-foreground">+ <Minus className="size-3.5" />+ </button>+ <button type="button" aria-label="Close tasks panel" className="flex size-6 items-center justify-center rounded-md transition-colors hover:bg-accent hover:text-foreground">+ <span className="text-sm leading-none">×</span>+ </button>+ </div>+ </div>+ <div className="py-1">+ {[+ ["曼迪", "#alook_pet", "嗯,你再给我启动一下这个程序,我...", "just now", previewAgents[2]!],+ ["峰哥", "#default", "职位发布更新-错过跳过", "2m ago", previewAgents[4]!],+ ].map(([name, channel, prompt, time, agent]) => {+ const avatarConfig = parseAvatarUrl((agent as Agent).avatar_url);++ return (+ <div+ key={`${name}-${time}`}+ className="flex cursor-default items-center gap-2.5 rounded-md px-3 py-2 transition-colors hover:bg-accent/50"+ >+ <div className="relative shrink-0">+ {avatarConfig ? (+ <AnimatedAvatar config={avatarConfig} size={24} className="rounded-full" isHovered={false} isWorking />+ ) : (+ <span className="flex size-6 items-center justify-center rounded-full bg-secondary text-[7px] font-medium">+ {String(name).charAt(0)}+ </span>+ )}+ <span className="absolute -right-0.5 -bottom-0.5 size-2 animate-pulse rounded-full bg-primary ring-2 ring-background" />+ </div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5 leading-tight">+ <span className="truncate text-sm font-medium">{String(name)}</span>+ <span className="shrink-0 text-xs text-muted-foreground">{String(channel)}</span>+ </div>+ <p className="truncate text-xs leading-tight text-muted-foreground">{String(prompt)}</p>+ </div>+ <span className="shrink-0 whitespace-nowrap text-xs text-muted-foreground">{String(time)}</span>+ </div>+ );+ })}+ </div>+ </div>+ );+}++function PreviewHint() {+ return (+ <div className="absolute bottom-14 left-4 z-40 rounded-md bg-background/80 px-3 py-1.5 text-xs text-muted-foreground ring-1 ring-foreground/5 backdrop-blur-sm">+ Hover agents and relationship labels to preview the live home-page behavior.+ </div>+ );+}++function PreviewHomeCanvas({+ previewComebackToken,+ inboxNotificationToken,+}: {+ previewComebackToken: number;+ inboxNotificationToken: number;+}) {+ const canvasRef = useRef<HTMLDivElement>(null);+ const nodes = useMemo(() => previewNodes, []);+ const edges = useMemo(() => previewEdges, []);++ return (+ <div ref={canvasRef} className="relative isolate flex-1">+ <ReactFlow+ className="pet-preview-flow"+ nodes={nodes}+ edges={edges}+ nodeTypes={nodeTypes}+ edgeTypes={edgeTypes}+ fitView+ fitViewOptions={{ padding: 0.42, maxZoom: 1 }}+ minZoom={0.25}+ maxZoom={2.5}+ nodesDraggable={false}+ nodesConnectable={false}+ elementsSelectable={false}+ panOnDrag={false}+ zoomOnScroll={false}+ panOnScroll={false}+ proOptions={{ hideAttribution: true }}+ >+ <Background variant={BackgroundVariant.Dots} gap={24} size={1.5} color="var(--color-border)" />+ </ReactFlow>++ <CloudCodeMonsterPet+ boundaryRef={canvasRef}+ initialPosition={previewPetInitialPosition}+ previewComebackToken={previewComebackToken}+ notificationToken={inboxNotificationToken}+ />+ <PreviewToolbar />+ <PreviewHint />+ <PreviewTasksFloat />+ <PreviewCreateButton />+ </div>+ );+}++function OtherPage() {+ const [selectedPresetId, setSelectedPresetId] = useState(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ const selectedPreset = getCloudCodeMonsterPreset(selectedPresetId);++ useEffect(() => {+ const syncPreset = (nextPresetId?: string | null) => {+ setSelectedPresetId(+ nextPresetId+ ? getCloudCodeMonsterPreset(nextPresetId).id+ : readCloudCodeMonsterPetPresetId()+ );+ };+ const handlePresetChange = (event: Event) => {+ syncPreset(+ (event as CustomEvent<{ presetId?: string }>).detail?.presetId+ );+ };++ syncPreset();+ window.addEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );++ return () => {+ window.removeEventListener(+ CLOUD_CODE_MONSTER_PRESET_CHANGED_EVENT,+ handlePresetChange+ );+ };+ }, []);++ return (+ <div className="flex min-h-0 flex-1 px-4 pb-4 pt-14">+ <div className="grid min-h-0 w-full grid-cols-[minmax(210px,280px)_1fr] gap-4 max-lg:grid-cols-1">+ <section className="flex min-h-0 flex-col justify-between rounded-lg border border-border/60 bg-background/70 p-4 shadow-sm">+ <div>+ <div className="text-xs font-medium uppercase tracking-normal text-muted-foreground">+ Other Page+ </div>+ <h1 className="mt-3 text-xl font-semibold tracking-normal">+ PET Presets+ </h1>+ <div className="mt-1 text-sm text-muted-foreground">+ {CLOUD_CODE_MONSTER_PET_PRESETS.length} presets+ </div>+ </div>++ <div className="mt-8 grid place-items-center rounded-lg bg-card/80 px-4 py-5 ring-1 ring-border/50">+ <CloudCodeMonsterPresetPreview+ preset={selectedPreset}+ className="size-32"+ />+ <div className="mt-3 text-center">+ <div className="text-sm font-medium">{selectedPreset.name}</div>+ <div className="mt-0.5 text-xs text-muted-foreground">+ {selectedPreset.id.replace("pet-", "#")}+ </div>+ </div>+ </div>++ <div className="mt-6 grid grid-cols-2 gap-2 text-xs text-muted-foreground">+ <div className="rounded-md bg-muted/60 px-2.5 py-2">+ <div className="font-medium text-foreground">Stored</div>+ <div className="mt-0.5">local preview</div>+ </div>+ <div className="rounded-md bg-muted/60 px-2.5 py-2">+ <div className="font-medium text-foreground">Home PET</div>+ <div className="mt-0.5">synced</div>+ </div>+ </div>+ </section>++ <section className="flex min-h-0 flex-col rounded-lg border border-border/60 bg-background/70 shadow-sm">+ <div className="flex items-center justify-between border-b border-border/50 px-4 py-3">+ <div className="text-sm font-medium">Preset Library</div>+ <div className="text-xs text-muted-foreground">+ {selectedPreset.id}+ </div>+ </div>+ <div className="thin-scrollbar grid min-h-0 flex-1 grid-cols-2 content-start gap-2 overflow-y-auto p-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">+ {CLOUD_CODE_MONSTER_PET_PRESETS.map((preset) => {+ const isSelected = preset.id === selectedPreset.id;++ return (+ <button+ key={preset.id}+ type="button"+ aria-pressed={isSelected}+ onClick={() => {+ const nextPresetId = writeCloudCodeMonsterPetPresetId(+ preset.id+ );+ setSelectedPresetId(nextPresetId);+ }}+ className={cn(+ "group grid h-36 min-w-0 grid-rows-[1fr_auto] rounded-lg border bg-card/70 p-2.5 text-left transition-all duration-200 hover:-translate-y-0.5 hover:border-foreground/20 hover:bg-accent/55 hover:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/70",+ isSelected+ ? "border-primary/50 bg-accent text-foreground shadow-sm"+ : "border-border/50 text-muted-foreground"+ )}+ >+ <div className="grid place-items-center rounded-md bg-background/65 ring-1 ring-border/35">+ <CloudCodeMonsterPresetPreview+ preset={preset}+ className="size-20 transition-transform duration-200 group-hover:scale-105"+ />+ </div>+ <div className="mt-2 min-w-0">+ <div className="truncate text-xs font-medium text-foreground">+ {preset.name}+ </div>+ <div className="mt-0.5 text-[10px] leading-none text-muted-foreground">+ {preset.id.replace("pet-", "#")}+ </div>+ </div>+ </button>+ );+ })}+ </div>+ </section>+ </div>+ </div>+ );+}++export function PetPreviewPage() {+ const [activePage, setActivePage] = useState<PreviewPage>("home");+ const [previewComebackToken, setPreviewComebackToken] = useState(0);+ const [inboxCount, setInboxCount] = useState(0);+ const [inboxNotificationToken, setInboxNotificationToken] = useState(0);+ const handlePageChange = (page: PreviewPage) => {+ if (page === "home" && activePage === "other") {+ setPreviewComebackToken((token) => token + 1);+ }++ setActivePage(page);+ };+ const handleInboxClick = () => {+ setInboxCount((count) => count + 1);+ setInboxNotificationToken((token) => token + 1);+ };++ return (+ <div className="relative flex h-dvh overflow-hidden">+ <GradientBackground />+ <PreviewSidebar inboxCount={inboxCount} onInboxClick={handleInboxClick} />+ <div className="flex min-w-0 flex-1 flex-col pt-1 pr-2 pb-2">+ <main className="relative flex min-h-0 flex-1 overflow-hidden rounded-xl bg-card/80 shadow-lg ring-1 ring-border/40 backdrop-blur-xl">+ <PageSwitch activePage={activePage} onPageChange={handlePageChange} />+ {activePage === "home" ? (+ <WorkspaceProvider workspaceId="ws_preview" slug="preview">+ <ReactFlowProvider>+ <PreviewHomeCanvas+ previewComebackToken={previewComebackToken}+ inboxNotificationToken={inboxNotificationToken}+ />+ </ReactFlowProvider>+ </WorkspaceProvider>+ ) : (+ <OtherPage />+ )}+ </main>+ </div>+ </div>+ );+}diff --git a/src/web/src/components/home-pet/workspace-pet-layer.tsx b/src/web/src/components/home-pet/workspace-pet-layer.tsxnew file mode 100644index 000000000..8f10eaba4--- /dev/null+++ b/src/web/src/components/home-pet/workspace-pet-layer.tsx@@ -0,0 +1,28 @@+"use client";++import { type RefObject } from "react";+import { usePathname } from "next/navigation";++import { useHomePetSettings } from "@/lib/home-pet-settings";+import { CloudCodeMonsterPet } from "./cloud-code-monster-pet";++type WorkspacePetLayerProps = {+ boundaryRef: RefObject<HTMLElement | null>;+ slug: string;+};++export function WorkspacePetLayer({ boundaryRef, slug }: WorkspacePetLayerProps) {+ const pathname = usePathname();+ const petSettings = useHomePetSettings();+ const isHome = pathname === `/w/${slug}/home`;++ if (+ !petSettings.enabled ||+ petSettings.displayScope !== "global" ||+ isHome+ ) {+ return null;+ }++ return <CloudCodeMonsterPet boundaryRef={boundaryRef} activityTriggerMode="global" />;+}diff --git a/src/web/src/components/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsxindex 4e7a92697..292428808 100644--- a/src/web/src/components/workspace-shell.tsx+++ b/src/web/src/components/workspace-shell.tsx@@ -1,15 +1,16 @@"use client";-import { createContext, useContext, type ReactNode, useState } from "react";+import { createContext, useContext, type ReactNode, useRef, useState } from "react";import { AppSidebar } from "@/components/app-sidebar";import { MobileTopBar } from "@/components/mobile-top-bar";import { GradientBackground } from "@/components/gradient-background";+import { WorkspacePetLayer } from "@/components/home-pet/workspace-pet-layer";+import { useWorkspace } from "@/contexts/workspace-context";import { useIsMobile } from "@/hooks/use-mobile";import {Sheet,SheetContent,} from "@/components/ui/sheet";-import { RuntimeVersionGate } from "@/components/runtime-version-gate";const SidebarTriggerContext = createContext<(() => void) | null>(null);@@ -19,12 +20,14 @@ export function useSidebarTrigger() {export function WorkspaceShell({ children }: { children: ReactNode }) {const isMobile = useIsMobile();+ const { slug } = useWorkspace();const [sidebarOpen, setSidebarOpen] = useState(false);+ const shellRef = useRef<HTMLDivElement>(null);if (isMobile) {return (<SidebarTriggerContext.Provider value={() => setSidebarOpen(true)}>- <div className="flex flex-col h-dvh overflow-hidden relative">+ <div ref={shellRef} className="flex flex-col h-dvh overflow-hidden relative"><GradientBackground /><div className="flex-1 min-h-0 px-2 pb-2 pt-2 flex flex-col"><MobileTopBar />@@ -37,14 +40,14 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {<AppSidebar onNavigate={() => setSidebarOpen(false)} /></SheetContent></Sheet>- <RuntimeVersionGate />+ <WorkspacePetLayer boundaryRef={shellRef} slug={slug} /></div></SidebarTriggerContext.Provider>);}return (- <div className="flex h-dvh overflow-hidden relative">+ <div ref={shellRef} className="flex h-dvh overflow-hidden relative"><GradientBackground /><AppSidebar /><div className="flex-1 flex flex-col min-w-0 pt-2 pr-2 pb-2">@@ -52,7 +55,7 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {{children}</main></div>- <RuntimeVersionGate />+ <WorkspacePetLayer boundaryRef={shellRef} slug={slug} /></div>);}diff --git a/src/web/src/lib/home-pet-settings.ts b/src/web/src/lib/home-pet-settings.tsnew file mode 100644index 000000000..59cf4fbfd--- /dev/null+++ b/src/web/src/lib/home-pet-settings.ts@@ -0,0 +1,93 @@+"use client";++import { useEffect, useState } from "react";++export const HOME_PET_SETTINGS_CHANGED_EVENT = "alook-home-pet-settings-changed";+export const HOME_PET_ENABLED_STORAGE_KEY = "alook-home-pet-enabled-v1";+export const HOME_PET_DISPLAY_SCOPE_STORAGE_KEY = "alook-home-pet-display-scope-v1";++export type HomePetDisplayScope = "home" | "global";++export type HomePetSettings = {+ enabled: boolean;+ displayScope: HomePetDisplayScope;+};++const DEFAULT_HOME_PET_SETTINGS: HomePetSettings = {+ enabled: true,+ displayScope: "home",+};++export function isHomePetDisplayScope(value: string | null): value is HomePetDisplayScope {+ return value === "home" || value === "global";+}++export function readHomePetSettings(): HomePetSettings {+ if (typeof window === "undefined") {+ return DEFAULT_HOME_PET_SETTINGS;+ }++ const enabled = window.localStorage.getItem(HOME_PET_ENABLED_STORAGE_KEY);+ const displayScope = window.localStorage.getItem(HOME_PET_DISPLAY_SCOPE_STORAGE_KEY);++ return {+ enabled: enabled === null ? DEFAULT_HOME_PET_SETTINGS.enabled : enabled === "true",+ displayScope: isHomePetDisplayScope(displayScope)+ ? displayScope+ : DEFAULT_HOME_PET_SETTINGS.displayScope,+ };+}++export function writeHomePetSettings(settings: Partial<HomePetSettings>) {+ const next = {+ ...readHomePetSettings(),+ ...settings,+ };++ window.localStorage.setItem(HOME_PET_ENABLED_STORAGE_KEY, String(next.enabled));+ window.localStorage.setItem(HOME_PET_DISPLAY_SCOPE_STORAGE_KEY, next.displayScope);+ window.dispatchEvent(+ new CustomEvent<HomePetSettings>(HOME_PET_SETTINGS_CHANGED_EVENT, {+ detail: next,+ })+ );++ return next;+}++export function useHomePetSettings() {+ const [settings, setSettings] = useState<HomePetSettings>(+ DEFAULT_HOME_PET_SETTINGS+ );++ useEffect(() => {+ setSettings(readHomePetSettings());++ const handleSettingsChanged = (event: Event) => {+ setSettings(+ (event as CustomEvent<HomePetSettings>).detail ?? readHomePetSettings()+ );+ };+ const handleStorageChanged = (event: StorageEvent) => {+ if (+ event.key === HOME_PET_ENABLED_STORAGE_KEY ||+ event.key === HOME_PET_DISPLAY_SCOPE_STORAGE_KEY+ ) {+ setSettings(readHomePetSettings());+ }+ };++ window.addEventListener(HOME_PET_SETTINGS_CHANGED_EVENT, handleSettingsChanged);+ window.addEventListener("storage", handleStorageChanged);++ return () => {+ window.removeEventListener(+ HOME_PET_SETTINGS_CHANGED_EVENT,+ handleSettingsChanged+ );+ window.removeEventListener("storage", handleStorageChanged);+ };+ }, []);++ return settings;+}diff --git a/src/web/src/test/e2e/auth.test.ts b/src/web/src/test/e2e/auth.test.tsindex 5298a70ba..e2506ce64 100644--- a/src/web/src/test/e2e/auth.test.ts+++ b/src/web/src/test/e2e/auth.test.ts@@ -3,7 +3,7 @@ import { randomUUID } from "crypto"import { signUp, signIn, sessionRequest } from "../helpers/auth"import { sql } from "../helpers/db"-const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+const APP_URL = process.env.APP_URL ?? "http://127.0.0.1:3003"const testEmail = `e2e_auth_${randomUUID().slice(0, 8)}@test.local`const testPassword = "TestPassword123!"diff --git a/src/web/src/test/e2e/daemon-lifecycle.test.ts b/src/web/src/test/e2e/daemon-lifecycle.test.tsindex b8ef76278..6e748a9c2 100644--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts+++ b/src/web/src/test/e2e/daemon-lifecycle.test.ts@@ -3,6 +3,7 @@ import { randomUUID } from "crypto"import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed"import { tokenRequest } from "../helpers/auth"import { sqlQuery, sqlBatch } from "../helpers/db"+import { fetchWithRetry } from "../helpers/fetch"let seed: TestSeed@@ -130,7 +131,7 @@ describe("daemon lifecycle", () => {it("POST /api/daemon/tasks/poll rejects without machine token", async () => {const APP_URL = process.env.APP_URL ?? "http://localhost:3000"- const res = await fetch(`${APP_URL}/api/daemon/tasks/poll`, {+ const res = await fetchWithRetry(`${APP_URL}/api/daemon/tasks/poll`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ daemon_id: daemonId }),diff --git a/src/web/src/test/e2e/whitelist-bypass.test.ts b/src/web/src/test/e2e/whitelist-bypass.test.tsindex 456540ce0..3aa0f45da 100644--- a/src/web/src/test/e2e/whitelist-bypass.test.ts+++ b/src/web/src/test/e2e/whitelist-bypass.test.ts@@ -1,6 +1,6 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed"-import { sql, sqlQuery } from "../helpers/db"+import { sql, sqlBatch, sqlQuery } from "../helpers/db"import { postEmail } from "../helpers/email"import { randomUUID } from "crypto"@@ -20,7 +20,7 @@ afterAll(() => {cleanupTestData(seedOther)})-describe("whitelist bypass for same-workspace agents", () => {+describe("whitelist bypass for same-workspace agents", { timeout: 60_000 }, () => {async function waitForEmail(agentId: string,fromEmail: string,@@ -41,7 +41,9 @@ describe("whitelist bypass for same-workspace agents", () => {const siblingAgentId = `ag_${nanoid()}`const siblingHandle = `e2e-sib-${nanoid()}`const now = new Date().toISOString()- sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${siblingAgentId}', '${seed.workspaceId}', 'Sibling Agent', '${seed.runtimeId}', '${siblingHandle}', '${seed.userId}', '${now}', '${now}')`)+ sqlBatch([+ `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${siblingAgentId}', '${seed.workspaceId}', 'Sibling Agent', '${seed.runtimeId}', '${siblingHandle}', '${seed.userId}', '${now}', '${now}')`,+ ])try {const from = `${siblingHandle}@alook.ai`@@ -54,7 +56,9 @@ describe("whitelist bypass for same-workspace agents", () => {expect(row).not.toBeNull()expect(row!.is_whitelisted).toBe(1)} finally {- sql(`DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`)+ sqlBatch([+ `DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`,+ ])}})@@ -120,8 +124,10 @@ describe("whitelist bypass for same-workspace agents", () => {const siblingHandle = `e2e-both-${nanoid()}`const now = new Date().toISOString()const wlId = `wl_${nanoid()}`- sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${siblingAgentId}', '${seed.workspaceId}', 'Both Agent', '${seed.runtimeId}', '${siblingHandle}', '${seed.userId}', '${now}', '${now}')`)- sql(`INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES ('${wlId}', '${seed.agentId}', '${seed.workspaceId}', '${siblingHandle}@alook.ai', '${now}')`)+ sqlBatch([+ `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${siblingAgentId}', '${seed.workspaceId}', 'Both Agent', '${seed.runtimeId}', '${siblingHandle}', '${seed.userId}', '${now}', '${now}')`,+ `INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES ('${wlId}', '${seed.agentId}', '${seed.workspaceId}', '${siblingHandle}@alook.ai', '${now}')`,+ ])try {const from = `${siblingHandle}@alook.ai`@@ -134,8 +140,10 @@ describe("whitelist bypass for same-workspace agents", () => {expect(row).not.toBeNull()expect(row!.is_whitelisted).toBe(1)} finally {- sql(`DELETE FROM agent_whitelist WHERE id = '${wlId}'`)- sql(`DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`)+ sqlBatch([+ `DELETE FROM agent_whitelist WHERE id = '${wlId}'`,+ `DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`,+ ])}})})diff --git a/src/web/src/test/e2e/workspace.test.ts b/src/web/src/test/e2e/workspace.test.tsindex fd66a113b..6346aa697 100644--- a/src/web/src/test/e2e/workspace.test.ts+++ b/src/web/src/test/e2e/workspace.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"import { randomUUID } from "crypto"import { signUp, signIn, sessionRequest } from "../helpers/auth"-import { sql } from "../helpers/db"+import { sqlBatch } from "../helpers/db"const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`const testPassword = "TestPassword123!"@@ -14,11 +14,13 @@ beforeAll(async () => {afterAll(() => {try {- sql(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)- sql(`DELETE FROM workspace WHERE id IN (SELECT workspace_id FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = '${testEmail}'))`)- sql(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)- sql(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)- sql(`DELETE FROM "user" WHERE email = '${testEmail}'`)+ sqlBatch([+ `DELETE FROM workspace WHERE id IN (SELECT workspace_id FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = '${testEmail}'))`,+ `DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = '${testEmail}')`,+ `DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`,+ `DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`,+ `DELETE FROM "user" WHERE email = '${testEmail}'`,+ ])} catch { /* ignore */ }})diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex 4f233f383..102bf4db6 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -38,14 +38,16 @@ export function seedTestData(): TestSeed {const now = new Date().toISOString()const slug = `test-${nanoid()}`- sql(`INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES ('${userId}', 'Test User', '${userId}@test.local', 1, '${now}', '${now}')`)- sql(`INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES ('${workspaceId}', 'Test Workspace', '${slug}', '${now}', '${now}')`)- sql(`INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('${memberId}', '${workspaceId}', '${userId}', 'owner', '${now}')`)- sql(`INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at) VALUES ('${daemonId}', '${workspaceId}', 'test-device', '${now}', '${now}', '${now}')`)- sql(`INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', '${daemonId}', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`)- sql(`INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${emailHandle}', '${userId}', '${now}', '${now}')`)- sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${rawToken}', 'test-token', 'active', '${now}')`)- sql(`INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES ('${whitelistId}', '${agentId}', '${workspaceId}', '${userId}@test.local', '${now}')`)+ sqlBatch([+ `INSERT INTO "user" (id, name, email, emailVerified, createdAt, updatedAt) VALUES ('${userId}', 'Test User', '${userId}@test.local', 1, '${now}', '${now}')`,+ `INSERT INTO workspace (id, name, slug, created_at, updated_at) VALUES ('${workspaceId}', 'Test Workspace', '${slug}', '${now}', '${now}')`,+ `INSERT INTO member (id, workspace_id, user_id, role, created_at) VALUES ('${memberId}', '${workspaceId}', '${userId}', 'owner', '${now}')`,+ `INSERT INTO machine (daemon_id, workspace_id, device_info, last_seen_at, created_at, updated_at) VALUES ('${daemonId}', '${workspaceId}', 'test-device', '${now}', '${now}', '${now}')`,+ `INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES ('${runtimeId}', '${workspaceId}', '${daemonId}', 'local', 'claude', 'online', 'test-device', '${now}', '${now}')`,+ `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES ('${agentId}', '${workspaceId}', 'Test Agent', '${runtimeId}', '${emailHandle}', '${userId}', '${now}', '${now}')`,+ `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${machineTokenId}', '${userId}', '${workspaceId}', '${rawToken}', 'test-token', 'active', '${now}')`,+ `INSERT INTO agent_whitelist (id, agent_id, workspace_id, email, created_at) VALUES ('${whitelistId}', '${agentId}', '${workspaceId}', '${userId}@test.local', '${now}')`,+ ])return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, agentEmailHandle: emailHandle, machineToken: rawToken, machineTokenId, whitelistId }}