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
Trim PET PR to production files
JeffreyDeng-specd9ff277abd9c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d61e7e90f..3e409a0c6 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -54,7 +54,6 @@ 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@@ -70,7 +69,7 @@ jobs:- name: Start dev serversrun: |pnpm --filter @alook/email-worker dev &- pnpm --filter @alook/web exec next dev &+ pnpm --filter @alook/web 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.mddeleted file mode 100644index f411a51cb..000000000--- a/LOCAL_DEV.md+++ /dev/null@@ -1,53 +0,0 @@-# 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 66cbc3947..539c8cfeb 100644--- a/README.md+++ b/README.md@@ -96,9 +96,6 @@ 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 58dfb66ab..a40e3864b 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://127.0.0.1:3003 ALOOK_PROJECT_ROOT=$PWD ALOOK_HEALTH_PORT=19515 pnpm --filter @alook/cli dev",+ "dev:cli": "ALOOK_SERVER_URL=http://localhost:3000 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,7 +22,6 @@"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",@@ -51,4 +50,4 @@"workerd"]}-}+}\ No newline at end of filediff --git a/scripts/seed-homepage-stubs.mjs b/scripts/seed-homepage-stubs.mjsdeleted file mode 100644index bfaf6a80d..000000000--- a/scripts/seed-homepage-stubs.mjs+++ /dev/null@@ -1,102 +0,0 @@-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 2ac6b002b..292741cb4 100644--- a/src/shared/src/browser/chrome-finder.test.ts+++ b/src/shared/src/browser/chrome-finder.test.ts@@ -1,23 +1,20 @@import { describe, it, expect, vi, beforeEach } from "vitest"-import { existsSync, readdirSync } from "node:fs"+import { existsSync } 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", () => {@@ -60,32 +57,6 @@ 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 63f4daf17..b68449b42 100644--- a/src/shared/src/browser/chrome-finder.ts+++ b/src/shared/src/browser/chrome-finder.ts@@ -1,7 +1,5 @@-import { existsSync, readdirSync } from "node:fs"+import { existsSync } 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: [@@ -42,15 +40,17 @@ 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|Install location).*?:\s*(.+)/i)+ const match = result.match(/browser binaries.*?:\s*(.+)/i)if (match) {const dir = match[1].trim()- for (const p of getPlaywrightChromiumCandidates(dir)) {+ const chromePaths = [+ `${dir}/chrome-linux/chrome`,+ `${dir}/chrome-mac/Chromium.app/Contents/MacOS/Chromium`,+ `${dir}/chrome-win/chrome.exe`,+ ]+ for (const p of chromePaths) {if (existsSync(p)) return p}}@@ -58,39 +58,6 @@ 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 4d881cd43..7d2bd786d 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 | undefined+let server: Serverlet serverUrl: stringlet browser: Browser@@ -40,18 +40,10 @@ beforeAll(async () => {const port = typeof addr === "object" && addr ? addr.port : 0serverUrl = `http://localhost:${port}`- 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- }+ browser = await chromium.launch({+ executablePath: chromePath,+ headless: true,+ })}, 30_000)afterAll(async () => {diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex 10cb74bf1..bc482d72b 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://127.0.0.1:3003+BETTER_AUTH_URL=http://localhost:3000# 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 1f6e57ef9..e42a560f6 100644--- a/src/web/lighthouserc.json+++ b/src/web/lighthouserc.json@@ -2,7 +2,7 @@"ci": {"collect": {"url": ["http://localhost:3000/"],- "startServerCommand": "pnpm exec next dev",+ "startServerCommand": "pnpm dev","startServerReadyPattern": "Ready in","numberOfRuns": 1,"settings": {diff --git a/src/web/package.json b/src/web/package.jsonindex a18b4e75a..e31d2b54f 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 -H 127.0.0.1 -p 3003",+ "dev": "next dev","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.jsondeleted file mode 100644index 186a1cfd6..000000000--- a/src/web/public/pets/tater/pet.json+++ /dev/null@@ -1,6 +0,0 @@-{- "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.webpdeleted file mode 100644index b4d724393..000000000Binary files a/src/web/public/pets/tater/spritesheet.webp and /dev/null differdiff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 00cb80fba..19363cc30 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -1492,16 +1492,6 @@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;diff --git a/src/web/src/app/layout.tsx b/src/web/src/app/layout.tsxindex b81940685..555277fd1 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" suppressHydrationWarning>+ <body className="min-h-full flex flex-col"><scripttype="application/ld+json"dangerouslySetInnerHTML={{diff --git a/src/web/src/app/pet-preview/page.tsx b/src/web/src/app/pet-preview/page.tsxdeleted file mode 100644index 33950afc2..000000000--- a/src/web/src/app/pet-preview/page.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { PetPreviewPage } from "@/components/home-pet/pet-preview-page";--export default function Page() {- return <PetPreviewPage />;-}diff --git a/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts b/src/web/src/components/home-pet/cloud-code-monster-pet.test.tsnew file mode 100644index 000000000..7a91565d3--- /dev/null+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.test.ts@@ -0,0 +1,240 @@+import { readFileSync } from "node:fs";+import path from "node:path";+import { describe, expect, it } from "vitest";+import {+ calculateMonsterWalkIntensity,+ clampPetPosition,+ CLOUD_CODE_MONSTER_ACTIVITIES,+ CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS,+ CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS,+ CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS,+ CLOUD_CODE_MONSTER_FAINT_MS,+ CLOUD_CODE_MONSTER_PET_PRESETS,+ createCloudCodeMonsterHiddenState,+ createCloudCodeMonsterIdleState,+ createCloudCodeMonsterWalkVelocity,+ getCloudCodeMonsterExpression,+ getCloudCodeMonsterPreset,+ getMonsterFootstepIntervalMs,+ hasViolentMonsterDirectionChange,+ isViolentMonsterDrag,+ pickCloudCodeMonsterActivity,+ reflectCloudCodeMonsterWalk,+ resolveCloudCodeMonsterPeekPosition,+ resolveCloudCodeMonsterVisibleState,+ shouldCloudCodeMonsterAutoWalk,+ shouldFaintFromMonsterShake,+ shouldRefreshCloudCodeMonsterActivity,+} from "./cloud-code-monster-pet";++function webRoot() {+ return process.cwd().endsWith(`${path.sep}src${path.sep}web`)+ ? process.cwd()+ : path.join(process.cwd(), "src/web");+}++describe("Cloud Code monster PET helpers", () => {+ 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("keeps production presets selectable and validates fallback behavior", () => {+ const presetIds = new Set(CLOUD_CODE_MONSTER_PET_PRESETS.map((preset) => preset.id));++ expect(CLOUD_CODE_MONSTER_PET_PRESETS).toHaveLength(30);+ expect(presetIds.size).toBe(30);+ expect(getCloudCodeMonsterPreset("pet-12").id).toBe("pet-12");+ expect(getCloudCodeMonsterPreset("missing").id).toBe(+ CLOUD_CODE_MONSTER_PET_PRESETS[0]!.id+ );+ });++ it("refreshes visible activity only after the away threshold", () => {+ 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);++ const visible = resolveCloudCodeMonsterVisibleState(+ { activityId: "coding", updatedAt, hiddenAt: updatedAt },+ updatedAt + CLOUD_CODE_MONSTER_ACTIVITY_REFRESH_MS - 1,+ 0.99+ );++ expect(visible).toEqual({+ activityId: "coding",+ updatedAt,+ hiddenAt: null,+ });+ });++ it("tracks idle, hidden, and random activity states", () => {+ expect(createCloudCodeMonsterIdleState(8_000)).toEqual({+ activityId: null,+ updatedAt: 8_000,+ hiddenAt: null,+ });+ expect(+ createCloudCodeMonsterHiddenState(+ { activityId: null, updatedAt: 1_000, hiddenAt: null },+ 2_000+ )+ ).toEqual({+ activityId: null,+ updatedAt: 1_000,+ hiddenAt: 2_000,+ });+ expect(pickCloudCodeMonsterActivity(0).id).toBe(+ CLOUD_CODE_MONSTER_ACTIVITIES[0]!.id+ );+ expect(pickCloudCodeMonsterActivity(0.999).id).toBe(+ CLOUD_CODE_MONSTER_ACTIVITIES.at(-1)!.id+ );+ });++ it("limits autonomous walking to selected activities", () => {+ expect(CLOUD_CODE_MONSTER_AUTOWALK_ACTIVITY_IDS).toEqual([+ "reading",+ "phone",+ "snacking",+ ]);+ expect(shouldCloudCodeMonsterAutoWalk("reading")).toBe(true);+ expect(shouldCloudCodeMonsterAutoWalk("coding")).toBe(false);+ expect(shouldCloudCodeMonsterAutoWalk(null)).toBe(false);+ });++ it("calculates drag walking, shake, faint, and expression states", () => {+ const slowWalk = calculateMonsterWalkIntensity(4, 40);+ const fastWalk = calculateMonsterWalkIntensity(70, 16);++ expect(fastWalk).toBeGreaterThan(slowWalk);+ expect(getMonsterFootstepIntervalMs(fastWalk)).toBeLessThan(+ getMonsterFootstepIntervalMs(slowWalk)+ );+ expect(isViolentMonsterDrag(10, 40)).toBe(false);+ expect(isViolentMonsterDrag(58, 35)).toBe(true);+ expect(+ hasViolentMonsterDirectionChange({ x: 30, y: 1 }, { x: -28, y: 0 })+ ).toBe(true);+ expect(CLOUD_CODE_MONSTER_FAINT_MS).toBe(10_000);+ expect(+ shouldFaintFromMonsterShake(+ Array.from({ length: CLOUD_CODE_MONSTER_FAINT_MIN_EVENTS }, (_, index) => index * 100),+ 600+ )+ ).toBe(true);+ expect(getCloudCodeMonsterExpression("sleeping", false, false)).toBe(+ "sleeping"+ );+ expect(getCloudCodeMonsterExpression("sleeping", true, false)).toBe(+ "shocked"+ );+ expect(getCloudCodeMonsterExpression("phone", true, true, true)).toBe(+ "fainted"+ );+ });++ it("creates autonomous walk velocity and reflects from canvas bounds", () => {+ expect(createCloudCodeMonsterWalkVelocity(0, 3)).toEqual({ x: 3, y: 0 });++ const rightBounce = reflectCloudCodeMonsterWalk(+ { x: 202, y: 40 },+ { x: 4, y: 1 },+ { 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);+ });++ it("resolves peeking coordinates from a real agent node before 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;++ expect(+ resolveCloudCodeMonsterPeekPosition(+ { agentId: "ag_mandy", x: 1, y: 1 },+ boundary,+ { width: 900, height: 700 }+ )+ ).toEqual({ x: 309, y: 305.24 });+ });+});++describe("production workspace PET mounting", () => {+ it("mounts only production PET surfaces", () => {+ const root = webRoot();+ const workspaceHomePage = readFileSync(+ path.join(root, "src/app/(app)/w/[slug]/home/page.tsx"),+ "utf8"+ );+ const settingsPage = readFileSync(+ path.join(root, "src/app/(app)/w/[slug]/settings/page.tsx"),+ "utf8"+ );+ const petTab = readFileSync(+ path.join(root, "src/app/(app)/w/[slug]/settings/pet-tab.tsx"),+ "utf8"+ );+ const workspaceShell = readFileSync(+ path.join(root, "src/components/workspace-shell.tsx"),+ "utf8"+ );+ const workspacePetLayer = readFileSync(+ path.join(root, "src/components/home-pet/workspace-pet-layer.tsx"),+ "utf8"+ );+ const agentNode = readFileSync(+ path.join(root, "src/components/canvas/agent-node.tsx"),+ "utf8"+ );+ const globalCss = readFileSync(path.join(root, "src/app/globals.css"), "utf8");++ expect(workspaceHomePage).toContain("CloudCodeMonsterPet");+ expect(workspaceHomePage).toContain("useHomePetSettings");+ expect(settingsPage).toContain('{ id: "pet", label: "Pet" }');+ expect(petTab).toContain("Enable pet");+ expect(petTab).toContain("Homepage only");+ expect(petTab).toContain("Global Display");+ expect(petTab).toContain("CloudCodeMonsterPresetPreview");+ expect(workspaceShell).toContain("WorkspacePetLayer");+ expect(workspaceShell).toContain("RuntimeVersionGate");+ expect(workspacePetLayer).toContain('petSettings.displayScope !== "global"');+ expect(agentNode).toContain("data-agent-node-id={agent.id}");+ expect(agentNode).toContain('data-agent-working={activeTaskCount > 0 ? "true" : "false"}');+ expect(globalCss).toContain(".cloud-code-monster-pet");+ expect(globalCss).not.toContain(".pet-preview-flow");+ });+});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.tsxindex 274f0dcda..9128c0dde 100644--- a/src/web/src/components/home-pet/cloud-code-monster-pet.tsx+++ b/src/web/src/components/home-pet/cloud-code-monster-pet.tsx@@ -9,7 +9,6 @@ import {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";@@ -38,6 +37,21 @@ 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 PetPoint = {+ x: number;+ y: number;+};++export type PetBounds = {+ width: number;+ height: number;+};++type PetSize = {+ width: number;+ height: number;+};+export type CloudCodeMonsterPeekTarget = PetPoint & {agentId?: string;};@@ -171,6 +185,21 @@ type ReflectedMonsterWalk = {reflectedY: boolean;};+export function clampPetPosition(+ position: PetPoint,+ bounds: PetBounds,+ size: PetSize = CLOUD_CODE_MONSTER_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 const CLOUD_CODE_MONSTER_ACTIVITIES: CloudCodeMonsterActivity[] = [{ id: "coding", label: "写代码", caption: "在敲一段小 patch" },{ id: "sleeping", label: "睡觉", caption: "闭眼打盹" },diff --git a/src/web/src/components/home-pet/homepage-pet.test.ts b/src/web/src/components/home-pet/homepage-pet.test.tsdeleted file mode 100644index e196d4f30..000000000--- a/src/web/src/components/home-pet/homepage-pet.test.ts+++ /dev/null@@ -1,794 +0,0 @@-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.tsxdeleted file mode 100644index 52c489da1..000000000--- a/src/web/src/components/home-pet/homepage-pet.tsx+++ /dev/null@@ -1,320 +0,0 @@-"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.tsdeleted file mode 100644index c49710c37..000000000--- a/src/web/src/components/home-pet/pet-presets.ts+++ /dev/null@@ -1,295 +0,0 @@-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.tsxdeleted file mode 100644index 78f314b9c..000000000--- a/src/web/src/components/home-pet/pet-preview-page.tsx+++ /dev/null@@ -1,747 +0,0 @@-"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/workspace-shell.tsx b/src/web/src/components/workspace-shell.tsxindex 292428808..26edff995 100644--- a/src/web/src/components/workspace-shell.tsx+++ b/src/web/src/components/workspace-shell.tsx@@ -5,6 +5,7 @@ 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 { RuntimeVersionGate } from "@/components/runtime-version-gate";import { useWorkspace } from "@/contexts/workspace-context";import { useIsMobile } from "@/hooks/use-mobile";import {@@ -41,6 +42,7 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {</SheetContent></Sheet><WorkspacePetLayer boundaryRef={shellRef} slug={slug} />+ <RuntimeVersionGate /></div></SidebarTriggerContext.Provider>);@@ -56,6 +58,7 @@ export function WorkspaceShell({ children }: { children: ReactNode }) {</main></div><WorkspacePetLayer boundaryRef={shellRef} slug={slug} />+ <RuntimeVersionGate /></div>);}diff --git a/src/web/src/test/e2e/auth.test.ts b/src/web/src/test/e2e/auth.test.tsindex e2506ce64..5298a70ba 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://127.0.0.1:3003"+const APP_URL = process.env.APP_URL ?? "http://localhost:3000"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 6e748a9c2..b8ef76278 100644--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts+++ b/src/web/src/test/e2e/daemon-lifecycle.test.ts@@ -3,7 +3,6 @@ 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@@ -131,7 +130,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 fetchWithRetry(`${APP_URL}/api/daemon/tasks/poll`, {+ const res = await fetch(`${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 3aa0f45da..456540ce0 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, sqlBatch, sqlQuery } from "../helpers/db"+import { sql, 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", { timeout: 60_000 }, () => {+describe("whitelist bypass for same-workspace agents", () => {async function waitForEmail(agentId: string,fromEmail: string,@@ -41,9 +41,7 @@ describe("whitelist bypass for same-workspace agents", { timeout: 60_000 }, () =const siblingAgentId = `ag_${nanoid()}`const siblingHandle = `e2e-sib-${nanoid()}`const now = new Date().toISOString()- 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}')`,- ])+ 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}')`)try {const from = `${siblingHandle}@alook.ai`@@ -56,9 +54,7 @@ describe("whitelist bypass for same-workspace agents", { timeout: 60_000 }, () =expect(row).not.toBeNull()expect(row!.is_whitelisted).toBe(1)} finally {- sqlBatch([- `DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`,- ])+ sql(`DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`)}})@@ -124,10 +120,8 @@ describe("whitelist bypass for same-workspace agents", { timeout: 60_000 }, () =const siblingHandle = `e2e-both-${nanoid()}`const now = new Date().toISOString()const wlId = `wl_${nanoid()}`- 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}')`,- ])+ 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}')`)try {const from = `${siblingHandle}@alook.ai`@@ -140,10 +134,8 @@ describe("whitelist bypass for same-workspace agents", { timeout: 60_000 }, () =expect(row).not.toBeNull()expect(row!.is_whitelisted).toBe(1)} finally {- sqlBatch([- `DELETE FROM agent_whitelist WHERE id = '${wlId}'`,- `DELETE FROM agent WHERE id = '${siblingAgentId}' AND workspace_id = '${seed.workspaceId}'`,- ])+ sql(`DELETE FROM agent_whitelist WHERE id = '${wlId}'`)+ sql(`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 6346aa697..fd66a113b 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 { sqlBatch } from "../helpers/db"+import { sql } from "../helpers/db"const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`const testPassword = "TestPassword123!"@@ -14,13 +14,11 @@ beforeAll(async () => {afterAll(() => {try {- 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}'`,- ])+ 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}'`)} catch { /* ignore */ }})diff --git a/src/web/src/test/helpers/seed.ts b/src/web/src/test/helpers/seed.tsindex 102bf4db6..4f233f383 100644--- a/src/web/src/test/helpers/seed.ts+++ b/src/web/src/test/helpers/seed.ts@@ -38,16 +38,14 @@ export function seedTestData(): TestSeed {const now = new Date().toISOString()const slug = `test-${nanoid()}`- 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}')`,- ])+ 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}')`)return { userId, workspaceId, memberId, runtimeId, daemonId, agentId, agentEmailHandle: emailHandle, machineToken: rawToken, machineTokenId, whitelistId }}