๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
feat(cli): generic agent-testing skill + lh verify install (#17280)
Innei66a2bb54ff55
diff --git a/.agents/skills/agent-testing-bot/SKILL.md b/.agents/skills/agent-testing-bot/SKILL.mdnew file mode 100644index 00000000000..68d816ecfa5--- /dev/null+++ b/.agents/skills/agent-testing-bot/SKILL.md@@ -0,0 +1,88 @@+---+name: agent-testing-bot+description: >+ Bot-channel end-to-end verification for LobeHub โ drives the real native chat+ apps (Discord / Slack / Telegram / WeChat / Lark / QQ / iMessage) via osascript+ or the iMessage bridge, on macOS. Extends the generic agent-testing skill for+ bot surfaces. Triggers on 'test bot', 'bot test', 'test in discord',+ 'test in telegram', 'test in slack', 'test in wechat', 'test in weixin',+ 'test in lark', 'test in feishu', 'test in qq'.+---++# Agent Testing โ Bot Channels (LobeHub project skill)++This skill **extends** the generic `agent-testing` skill (installed alongside at+`../agent-testing/`) to the bot-channel surfaces. It does NOT replace the core+process: the same three phases apply โ++```text+PLAN (Steps 0โ2) โ EXECUTE (Steps 3โ6) โ FINISH (Step 7)+```++โ and the same report + publish pipeline (`result.json` โ `report-init.sh` โ+`lh verify ingest-report โฆ --source agent-testing`). Read the generic skill's+`SKILL.md` for target grounding, the living logs, the Phase-1 approval gate, the+report format, and teardown. This file only adds the bot-channel surface.++For LobeHub environment/auth/probe specifics (dev server, seeded account, ports),+the adapter is `.agents/verify/PROJECT.md`.++## When this surface applies++| Change scope | Surface | Why |+| ---------------------------------------------- | --------------------------------- | ------------------------------------------------ |+| **Bot channels** (Discord / WeChat / Lark / โฆ) | Native app via osascript / bridge | Only way to exercise the real channel end-to-end |++Route here only when the behavior under test is a bot channel. For CLI / Web /+Electron changes, use the generic skill's surfaces.++## Platforms++Each platform folder has an `index.md` (activation, navigation, send-message,+verification snippets) and a `test-<platform>-bot.sh` driver.++| Platform | Guide | Quick switcher |+| ------------- | ---------------------------------------- | --------------------- |+| Discord | [discord/index.md](./discord/index.md) | `Cmd+K` |+| Slack | [slack/index.md](./slack/index.md) | `Cmd+K` |+| Telegram | [telegram/index.md](./telegram/index.md) | `Cmd+F` |+| WeChat / ๅพฎไฟก | [wechat/index.md](./wechat/index.md) | `Cmd+F` |+| Lark / ้ฃไนฆ | [lark/index.md](./lark/index.md) | `Cmd+K` |+| QQ | [qq/index.md](./qq/index.md) | `Cmd+F` |+| iMessage | [imessage/index.md](./imessage/index.md) | bridge (no osascript) |++## Shared driver contract++Every osascript platform script shares one interface:++```bash+./$PLATFORM/test-$PLATFORM-bot.sh $CHANNEL_OR_CONTACT $MESSAGE [$WAIT_SECONDS] [$SCREENSHOT_PATH]+```++The script activates the app, navigates to the channel/contact, sends the+message, waits, and screenshots the result window (via the generic skill's+`../agent-testing/scripts/capture-app-window.sh`). iMessage is the exception: it+uses a BlueBubbles bridge, not osascript โ see [imessage/index.md](./imessage/index.md).++## osascript prerequisites++The osascript platforms drive real macOS apps (activate, keystroke, click, read+accessibility, screenshot). Read the generic skill's general macOS-automation+reference before a first bot run:+[../agent-testing/references/osascript.md](../agent-testing/references/osascript.md).+The target native app must already be running and logged in.++## Screen-recording gate (macOS-only)++Bot evidence is captured with OS-level `screencapture` (through+`capture-app-window.sh`), NOT CDP โ so it comes out **entirely black** when macOS+Screen Recording (TCC) permission is missing OR the display is asleep / locked /+on a screensaver. Gate BEFORE any bot capture:++```bash+./.agents/skills/agent-testing/scripts/check-screen-recording.sh # exit 0 = OS capture will work+```++Keep the display awake for the whole capture session (`caffeinate -dimsu &`, kill+when done). Because this surface depends on OS capture and native macOS apps,+**bot channels are macOS-only โ they do not run headless / in cloud.**diff --git a/.agents/skills/agent-testing/bot/discord/index.md b/.agents/skills/agent-testing-bot/discord/index.mdsimilarity index 90%rename from .agents/skills/agent-testing/bot/discord/index.mdrename to .agents/skills/agent-testing-bot/discord/index.mdindex 00b9096f104..9ef5d5fc88e 100644--- a/.agents/skills/agent-testing/bot/discord/index.md+++ b/.agents/skills/agent-testing-bot/discord/index.md@@ -2,7 +2,7 @@**App name:** `Discord` | **Process name:** `Discord`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -92,6 +92,6 @@ echo "Screenshot saved to /tmp/discord-test-result.png"## Script```bash-./.agents/skills/agent-testing/bot/discord/test-discord-bot.sh "bot-testing" "!ping"-./.agents/skills/agent-testing/bot/discord/test-discord-bot.sh "bot-testing" "/ask Tell me a joke" 30+./.agents/skills/agent-testing-bot/discord/test-discord-bot.sh "bot-testing" "!ping"+./.agents/skills/agent-testing-bot/discord/test-discord-bot.sh "bot-testing" "/ask Tell me a joke" 30```diff --git a/.agents/skills/agent-testing/bot/discord/test-discord-bot.sh b/.agents/skills/agent-testing-bot/discord/test-discord-bot.shsimilarity index 95%rename from .agents/skills/agent-testing/bot/discord/test-discord-bot.shrename to .agents/skills/agent-testing-bot/discord/test-discord-bot.shindex be71ec1df9b..00b2060e934 100755--- a/.agents/skills/agent-testing/bot/discord/test-discord-bot.sh+++ b/.agents/skills/agent-testing-bot/discord/test-discord-bot.sh@@ -60,5 +60,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/bot/imessage/index.md b/.agents/skills/agent-testing-bot/imessage/index.mdsimilarity index 97%rename from .agents/skills/agent-testing/bot/imessage/index.mdrename to .agents/skills/agent-testing-bot/imessage/index.mdindex f966f16d4fc..fcf969ef438 100644--- a/.agents/skills/agent-testing/bot/imessage/index.md+++ b/.agents/skills/agent-testing-bot/imessage/index.md@@ -21,7 +21,7 @@ So the test surface is three layers:curl -sS -m4 -o /dev/null -w '%{http_code}\n' \"http://127.0.0.1:1234/api/v1/server/info?password=<PW>" # expect 200```-- **Electron dev running with CDP**: `./.agents/skills/agent-testing/scripts/electron-dev.sh start`+- **Electron dev running with CDP**: `.agents/verify/scripts/electron-dev.sh start`- The **iMessage Desktop branch** checked out (the `imessageBridge` IPC groupand `@lobechat/chat-adapter-imessage` must be compiled into the main bundle).Run `pnpm install --ignore-scripts` at the repo root **and** in `apps/desktop/`@@ -31,7 +31,7 @@ So the test surface is three layers:## Fast path: automated script```bash-./.agents/skills/agent-testing/bot/imessage/test-imessage-bridge.sh '<bluebubbles_password>' [bb_url] [cdp_port]+./.agents/skills/agent-testing-bot/imessage/test-imessage-bridge.sh '<bluebubbles_password>' [bb_url] [cdp_port]```Asserts the whole flow and self-cleans (unique `applicationId` per run, removes@@ -136,7 +136,7 @@ Verifies the leg the bridge uses to _reply_: `BlueBubblesApiClient.sendText`โ `POST /api/v1/message/text`. Run the helper against your own number:```bash-./.agents/skills/agent-testing/bot/imessage/send-imessage-test.sh '<bb_password>' '+<E164>' # e.g. +15551234567+./.agents/skills/agent-testing-bot/imessage/send-imessage-test.sh '<bb_password>' '+<E164>' # e.g. +15551234567```**Gotcha that bites everyone:** with `method=apple-script` and a _new_diff --git a/.agents/skills/agent-testing/bot/imessage/send-imessage-test.sh b/.agents/skills/agent-testing-bot/imessage/send-imessage-test.shsimilarity index 100%rename from .agents/skills/agent-testing/bot/imessage/send-imessage-test.shrename to .agents/skills/agent-testing-bot/imessage/send-imessage-test.shdiff --git a/.agents/skills/agent-testing/bot/imessage/test-imessage-bridge.sh b/.agents/skills/agent-testing-bot/imessage/test-imessage-bridge.shsimilarity index 100%rename from .agents/skills/agent-testing/bot/imessage/test-imessage-bridge.shrename to .agents/skills/agent-testing-bot/imessage/test-imessage-bridge.shdiff --git a/.agents/skills/agent-testing/bot/lark/index.md b/.agents/skills/agent-testing-bot/lark/index.mdsimilarity index 85%rename from .agents/skills/agent-testing/bot/lark/index.mdrename to .agents/skills/agent-testing-bot/lark/index.mdindex 9fbbc01e5bf..a71309d9ab6 100644--- a/.agents/skills/agent-testing/bot/lark/index.md+++ b/.agents/skills/agent-testing-bot/lark/index.md@@ -2,7 +2,7 @@**App name:** `Lark` or `้ฃไนฆ` | **Process name:** `Lark` or `้ฃไนฆ`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -56,6 +56,6 @@ screencapture /tmp/lark-bot-response.png## Script```bash-./.agents/skills/agent-testing/bot/lark/test-lark-bot.sh "bot-testing" "@MyBot hello"-./.agents/skills/agent-testing/bot/lark/test-lark-bot.sh "bot-testing" "Help me with this" 30+./.agents/skills/agent-testing-bot/lark/test-lark-bot.sh "bot-testing" "@MyBot hello"+./.agents/skills/agent-testing-bot/lark/test-lark-bot.sh "bot-testing" "Help me with this" 30```diff --git a/.agents/skills/agent-testing/bot/lark/test-lark-bot.sh b/.agents/skills/agent-testing-bot/lark/test-lark-bot.shsimilarity index 96%rename from .agents/skills/agent-testing/bot/lark/test-lark-bot.shrename to .agents/skills/agent-testing-bot/lark/test-lark-bot.shindex daa0dd89d06..a41b2d2cf5b 100755--- a/.agents/skills/agent-testing/bot/lark/test-lark-bot.sh+++ b/.agents/skills/agent-testing-bot/lark/test-lark-bot.sh@@ -80,5 +80,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/bot/qq/index.md b/.agents/skills/agent-testing-bot/qq/index.mdsimilarity index 81%rename from .agents/skills/agent-testing/bot/qq/index.mdrename to .agents/skills/agent-testing-bot/qq/index.mdindex afc0fb02974..94eaea40e43 100644--- a/.agents/skills/agent-testing/bot/qq/index.md+++ b/.agents/skills/agent-testing-bot/qq/index.md@@ -2,7 +2,7 @@**App name:** `QQ` | **Process name:** `QQ`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -57,6 +57,6 @@ screencapture /tmp/qq-bot-response.png## Script```bash-./.agents/skills/agent-testing/bot/qq/test-qq-bot.sh "bot-testing" "Hello bot" 15-./.agents/skills/agent-testing/bot/qq/test-qq-bot.sh "MyBot" "/help" 10+./.agents/skills/agent-testing-bot/qq/test-qq-bot.sh "bot-testing" "Hello bot" 15+./.agents/skills/agent-testing-bot/qq/test-qq-bot.sh "MyBot" "/help" 10```diff --git a/.agents/skills/agent-testing/bot/qq/test-qq-bot.sh b/.agents/skills/agent-testing-bot/qq/test-qq-bot.shsimilarity index 96%rename from .agents/skills/agent-testing/bot/qq/test-qq-bot.shrename to .agents/skills/agent-testing-bot/qq/test-qq-bot.shindex 763bae8752c..68b303c6907 100755--- a/.agents/skills/agent-testing/bot/qq/test-qq-bot.sh+++ b/.agents/skills/agent-testing-bot/qq/test-qq-bot.sh@@ -72,5 +72,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/bot/slack/index.md b/.agents/skills/agent-testing-bot/slack/index.mdsimilarity index 85%rename from .agents/skills/agent-testing/bot/slack/index.mdrename to .agents/skills/agent-testing-bot/slack/index.mdindex b5c591d4ab5..4cd7498f9ab 100644--- a/.agents/skills/agent-testing/bot/slack/index.md+++ b/.agents/skills/agent-testing-bot/slack/index.md@@ -2,7 +2,7 @@**App name:** `Slack` | **Process name:** `Slack`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -68,6 +68,6 @@ screencapture /tmp/slack-bot-response.png## Script```bash-./.agents/skills/agent-testing/bot/slack/test-slack-bot.sh "bot-testing" "@mybot hello"-./.agents/skills/agent-testing/bot/slack/test-slack-bot.sh "bot-testing" "/ask What is 2+2?" 20+./.agents/skills/agent-testing-bot/slack/test-slack-bot.sh "bot-testing" "@mybot hello"+./.agents/skills/agent-testing-bot/slack/test-slack-bot.sh "bot-testing" "/ask What is 2+2?" 20```diff --git a/.agents/skills/agent-testing/bot/slack/test-slack-bot.sh b/.agents/skills/agent-testing-bot/slack/test-slack-bot.shsimilarity index 95%rename from .agents/skills/agent-testing/bot/slack/test-slack-bot.shrename to .agents/skills/agent-testing-bot/slack/test-slack-bot.shindex 2906d2dfe8d..651c2715f97 100755--- a/.agents/skills/agent-testing/bot/slack/test-slack-bot.sh+++ b/.agents/skills/agent-testing-bot/slack/test-slack-bot.sh@@ -60,5 +60,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/bot/telegram/index.md b/.agents/skills/agent-testing-bot/telegram/index.mdsimilarity index 86%rename from .agents/skills/agent-testing/bot/telegram/index.mdrename to .agents/skills/agent-testing-bot/telegram/index.mdindex df094a374ae..48e377344a1 100644--- a/.agents/skills/agent-testing/bot/telegram/index.md+++ b/.agents/skills/agent-testing-bot/telegram/index.md@@ -2,7 +2,7 @@**App name:** `Telegram` | **Process name:** `Telegram`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -75,6 +75,6 @@ curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/getUpdates?limit=5" | j## Script```bash-./.agents/skills/agent-testing/bot/telegram/test-telegram-bot.sh "MyTestBot" "/start"-./.agents/skills/agent-testing/bot/telegram/test-telegram-bot.sh "GPTBot" "Hello" 60+./.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh "MyTestBot" "/start"+./.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh "GPTBot" "Hello" 60```diff --git a/.agents/skills/agent-testing/bot/telegram/test-telegram-bot.sh b/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.shsimilarity index 96%rename from .agents/skills/agent-testing/bot/telegram/test-telegram-bot.shrename to .agents/skills/agent-testing-bot/telegram/test-telegram-bot.shindex 3d18f0291c0..5a2657d8898 100755--- a/.agents/skills/agent-testing/bot/telegram/test-telegram-bot.sh+++ b/.agents/skills/agent-testing-bot/telegram/test-telegram-bot.sh@@ -75,5 +75,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/bot/wechat/index.md b/.agents/skills/agent-testing-bot/wechat/index.mdsimilarity index 88%rename from .agents/skills/agent-testing/bot/wechat/index.mdrename to .agents/skills/agent-testing-bot/wechat/index.mdindex 53afdef8cad..fa9290cdf50 100644--- a/.agents/skills/agent-testing/bot/wechat/index.md+++ b/.agents/skills/agent-testing-bot/wechat/index.md@@ -2,7 +2,7 @@**App name:** `ๅพฎไฟก` or `WeChat` | **Process name:** `WeChat`-See [references/osascript.md](../../references/osascript.md) for shared patterns.+See [references/osascript.md](../../agent-testing/references/osascript.md) for shared patterns.## Activate & Navigate@@ -76,6 +76,6 @@ screencapture /tmp/wechat-bot-response.png## Script```bash-./.agents/skills/agent-testing/bot/wechat/test-wechat-bot.sh "ๆไปถไผ ่พๅฉๆ" "test message" 5-./.agents/skills/agent-testing/bot/wechat/test-wechat-bot.sh "MyBot" "Tell me a joke" 30+./.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh "ๆไปถไผ ่พๅฉๆ" "test message" 5+./.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh "MyBot" "Tell me a joke" 30```diff --git a/.agents/skills/agent-testing/bot/wechat/test-wechat-bot.sh b/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.shsimilarity index 96%rename from .agents/skills/agent-testing/bot/wechat/test-wechat-bot.shrename to .agents/skills/agent-testing-bot/wechat/test-wechat-bot.shindex 4f76f28fc38..de47db74ecc 100755--- a/.agents/skills/agent-testing/bot/wechat/test-wechat-bot.sh+++ b/.agents/skills/agent-testing-bot/wechat/test-wechat-bot.sh@@ -81,5 +81,5 @@ echo "[$APP] Waiting ${WAIT}s for bot response..."sleep "$WAIT"echo "[$APP] Capturing screenshot..."-"$SCRIPT_DIR/../../scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"+"$SCRIPT_DIR/../../agent-testing/scripts/capture-app-window.sh" "$APP" "$SCREENSHOT"echo "[$APP] Done! Screenshot saved to $SCREENSHOT"diff --git a/.agents/skills/agent-testing/.skill-meta.json b/.agents/skills/agent-testing/.skill-meta.jsonnew file mode 100644index 00000000000..2d878452ee0--- /dev/null+++ b/.agents/skills/agent-testing/.skill-meta.json@@ -0,0 +1,5 @@+{+ "cliRoot": "../../../apps/cli",+ "name": "agent-testing",+ "version": "0.0.44"+}diff --git a/.agents/skills/agent-testing/SKILL.md b/.agents/skills/agent-testing/SKILL.mdindex 54bd3cbf931..e8f3efa7c84 100644--- a/.agents/skills/agent-testing/SKILL.md+++ b/.agents/skills/agent-testing/SKILL.md@@ -1,21 +1,20 @@---name: agent-testingdescription: >- Agentic end-to-end testing for LobeHub: backend verification via the CLI,- frontend verification via agent-browser (Electron), full-stack verification in- the browser, and bot-channel verification via osascript. Local-first today,- designed to extend to cloud automation. Triggers on 'cli test', 'test with cli',- 'verify with cli', 'backend test with cli', 'local test', 'test in electron',- 'test desktop', 'test bot', 'bot test', 'test in discord', 'test in telegram',- 'test in slack', 'test in wechat', 'test in weixin', 'test in lark', 'test in feishu',- 'test in qq', 'manual test', 'osascript', 'test report', or any local- end-to-end verification task.+ Agentic end-to-end testing for any project: backend verification via the+ project CLI, frontend verification via agent-browser (web), and desktop+ verification via CDP (Electron). Drives the real surface, captures visually+ confirmed evidence, and publishes a structured report to the LobeHub verify+ platform. Triggers on 'cli test', 'test with cli', 'verify with cli',+ 'backend test with cli', 'local test', 'test in electron', 'test desktop',+ 'manual test', 'test report', or any local end-to-end verification task.---# Agent Testing (Agentic End-to-End Verification)-One skill for all agentic end-to-end testing โ local-first today, designed to-also run as full cloud automation. Every test session follows three phases:+One skill for agentic end-to-end testing of any project โ backend through the+project CLI, web through a browser, desktop through Electron/CDP. Every session+follows three phases:```textPLAN (Steps 0โ2) โ EXECUTE (Steps 3โ6) โ FINISH (Step 7)@@ -26,341 +25,180 @@ execution plan. Treat Steps 3โ6 as one continuous execution phase: select thesurface, run the cases, produce the report, and publish it. Always end withFinish unless the user explicitly asks to keep the environment running.+**Everything project-specific comes from an adapter, not from this skill.** The+concrete start/stop commands, ports, auth, surfaces, and probes for the project+under test live in `.agents/verify/PROJECT.md`. This skill supplies the process,+the evidence discipline, and the surface methodology; `PROJECT.md` supplies the+commands. When a step below says "from `PROJECT.md`", read that file for the+actual command instead of guessing. See+[references/project-adapter.md](./references/project-adapter.md).+## Phase 1 โ PlanConfirm what will run and whether the environment is ready before changing orstarting anything.-Skill-internal setup โ loading this skill, reading the living logs and-reference files โ is silent preparation: never narrate it to the user ("I'll-load the mandatory living logs firstโฆ" is noise). The first user-visible-message of a session is about the user's test โ the target confirmation-(Step 0) or the Phase 1 approval gate โ in one message, not a setup-announcement followed by the same question again.+Skill-internal setup โ loading this skill, reading the living logs and reference+files โ is silent preparation: never narrate it to the user ("I'll load the+mandatory living logs firstโฆ" is noise). The first user-visible message of a+session is about the user's test โ the target confirmation (Step 0) or the+Phase 1 approval gate โ in one message, not a setup announcement followed by the+same question again.-### Step 0 โ Ground the target, then read the two living logs (mandatory)+### Step 0 โ Ground the target, then read the two living-log layers (mandatory)**A test target must exist before anything else happens.** When the invocation-carries none (bare skill invocation, no pending ask in the conversation),-ground it first โ do NOT read the living logs or touch the environment yet:+carries none (bare skill invocation, no pending ask in the conversation), ground+it first โ do NOT read the living logs or touch the environment yet:-1. Take the target from the user's words in this conversation when they- exist โ the task lives in their words, not in git (common-mistakes Case 3).+1. Take the target from the user's words in this conversation when they exist โ+ the task lives in their words, not in git (common-mistakes: task from the ask,+ not the branch).2. Otherwise, infer the most likely candidate from observable context (currentbranch, recent commits, working-tree changes) and confirm it with one- structured question โ the candidate as the recommended option, clearly- labeled as a guess. Never start executing against an unconfirmed guess.+ structured question โ the candidate as the recommended option, clearly labeled+ as a guess. Never start executing against an unconfirmed guess.3. Only when nothing is inferable, ask one direct open question. Asking "what- should I verify" is the one legitimate opening question (common-mistakes- Case 8) โ but asking it open-ended when a candidate was inferable wastes- the user's turn.--**Once the target is known**, read both of these in full and hold them in mind-for this run. Reading them before a target exists wastes context that may be-compacted away before Execute โ they inform execution, not target selection:--- [references/common-mistakes.md](./references/common-mistakes.md) โ mistakes the- user has called out. Two that keep biting:- - **Never declare a case `passed` from grep/skeleton-count heuristics โ open- the actual screenshot with Read and confirm it rendered the expected- content.** A blank/white page also has 0 skeletons and still matches- persistent nav text.- - **If the task's goal is verifying error/failure states, do NOT stop at- happy-path when injection is hard.** Escalate (see the pattern library) until- you have real failure-state evidence.-- [references/probe-mock-patterns.md](./references/probe-mock-patterns.md) โ the- verified recipes for forcing failures, beating the SWR cache/retry, and probing- runtime state. Read it before any run that must force an error state or inspect- store/SWR values, so you don't rediscover the dead ends.--**Both files are living logs โ append to them during the run**, in English:--- User gives negative feedback โ new case in `common-mistakes.md`+ should I verify" is the one legitimate opening question โ but asking it+ open-ended when a candidate was inferable wastes the user's turn.++**Once the target is known**, read both layers of both living logs in full and+hold them in mind for this run. Reading them before a target exists wastes+context that may be compacted away before Execute โ they inform execution, not+target selection.++- **Generic layer** (ships with this skill, read-only here):+ [references/common-mistakes.md](./references/common-mistakes.md) and+ [references/probe-mock-patterns.md](./references/probe-mock-patterns.md).+ Two mistakes that keep biting:+ - **Never declare a case `passed` from grep/skeleton-count heuristics โ open the+ actual screenshot with Read and confirm it rendered the expected content.** A+ blank/white page also has 0 skeletons and still matches persistent nav text.+ - **If the goal is verifying error/failure states, do NOT stop at happy-path+ when injection is hard.** Escalate (see the pattern library) until you have+ real failure-state evidence.+- **Project layer** (writable, owned by the project): `.agents/verify/common-mistakes.md`+ and `.agents/verify/probe-mock-patterns.md`, when they exist. These carry what+ earlier runs learned about THIS project.++**The project layer is a living log โ append to it during the run**, in English:++- User gives negative feedback โ new case in `.agents/verify/common-mistakes.md`(Wrong approach / Why / What it breaks / Correct approach).- You hit any probe/mock that is blocked, bypassed, or needs a workaround โ new- item in `probe-mock-patterns.md` (Situation / Doesn't work / Works).-- **Confidentiality โ this skill ships in the open-source repository.** Keep- appended entries product-generic: never include details that only exist in a- private/commercial superproject (its packages, routes, DB schemas, env vars,- service names, or business logic). Record those learnings in the- superproject's own skills/notes instead, and genericize anything worth- keeping here.+ item in `.agents/verify/probe-mock-patterns.md` (Situation / Doesn't work /+ Works).++Write project-specific learnings to the **project layer only**. Never edit the+generic layer from a consumer repo โ it is read-only and updated by PR to the CLI+repo. **Confidentiality of the generic layer:** its entries must be+product-independent. If a learning turns out to be product-independent and worth+sharing, genericize it and open a PR upstream; keep anything naming a project's+packages, routes, schemas, env vars, service names, or business logic in the+project layer.++### Step 0.5 โ Adapter check (mandatory when `PROJECT.md` is missing)++If `.agents/verify/PROJECT.md` does not exist, run the first-run bootstrap in+[references/project-adapter.md](./references/project-adapter.md) BEFORE anything+else: explore the repo (package.json / README / CI workflows / Makefile / compose+files), draft a `PROJECT.md` from the fixed section skeleton, present it to the+user for confirmation, and write it only after approval. Do not start a dev+server or write test steps against an unconfirmed adapter.++When `PROJECT.md` exists, read it now โ every concrete command in Steps 1โ7 comes+from it. When observed reality diverges from it during the run, fix the adapter in+place (adapter drift is a living-log entry: amend the file during the run).### Step 1 โ Prepare the execution plan-Skip directly to Step 2 if: the test is a single re-run after a fix, the plan-was already agreed on, or the user gave exact commands.+Skip directly to Step 2 if: the test is a single re-run after a fix, the plan was+already agreed on, or the user gave exact commands.Prepare the proposed surface, cases, expected evidence, assumptions, and reportdeliverable. Do not ask for approval yet: Step 2 must establish the real-environment state first so the user can approve one complete, evidence-backed-plan instead of separate plan and environment prompts.+environment state first so the user can approve one complete, evidence-backed plan+instead of separate plan and environment prompts.### Step 2 โ Confirm environment state and auth (mandatory)-Step 2 is about getting the environment ready: **dependencies are healthy**-and **auth is green**. A test run that dies halfway on a missing dependency or-a login wall wastes the whole session โ clear both gates BEFORE writing a-single test step.+Step 2 is about getting the environment ready: **dependencies are healthy** and+**auth is green**. A test run that dies halfway on a missing dependency or a login+wall wastes the whole session โ clear both gates BEFORE writing a single test+step. The concrete commands for each check come from `PROJECT.md`; the rules below+are the ones that hold for every project.#### 2.0 Resolve the current test environmentBefore starting a dev server, checking auth, opening agent-browser, or writing-test steps, print and confirm the current local test environment:--```bash-./.agents/skills/agent-testing/scripts/test-env.sh-```--This command is the source of truth for local test ports. It reads the current-shell plus `.env` files using the same precedence as `scripts/runWithEnv.mts`,-then prints:--- `APP_URL`-- `PORT`-- `SERVER_URL`-- `AUTH_TRUSTED_ORIGINS`-- `SPA_PORT`-- `MOBILE_SPA_PORT`-- `DESKTOP_PORT`--For commands that need these values, export them from the same resolver:--```bash-eval "$(./.agents/skills/agent-testing/scripts/test-env.sh --exports)"-```--Do not rely on hard-coded port tables. If the printed values do not match the-running dev server, fix/export the env first, then continue.--#### 2.1 Dependencies are installed โ root AND standalone apps--The root pnpm workspace does **NOT** cover every app: `pnpm-workspace.yaml`-lists `packages/**`, `e2e`, `apps/server`, and only `apps/desktop/src/main` โ-**`apps/desktop` and `apps/cli` are standalone**, each keeping its own-`node_modules` with its own links into `packages/`. A root install does not-refresh them, so install in every app the test will touch:--```bash-pnpm install # root workspace-cd apps/desktop && pnpm install # Electron surface-cd apps/cli && pnpm install # CLI surface-```--Symptom of a stale standalone install: the build/launch fails to resolve a-recently added workspace package โ `Rolldown failed to resolve import-"@lobechat/<pkg>"` (Electron) or `Cannot find module '@lobechat/<pkg>'` (CLI).--#### 2.2 Run scripts from the repo root--All paths in this skill (`./.agents/skills/agent-testing/...`) are-repo-root-relative, and background commands inherit the current working-directory โ a script launched while `cwd` is `apps/desktop` fails with-`No such file or directory`. Verify `pwd` is the repo root before launching-long-running scripts.--#### 2.3 Init local dev env without `.env`--For Web smoke against local code, start a **normal local dev environment**.-First check the repo root for `.env`:--- If `.env` exists, use the existing local configuration and start the dev- server normally.-- If `.env` does not exist, use the agent-testing env bootstrap.+test steps, resolve and confirm the environment `PROJECT.md` describes โ the base+URLs, ports, and required services. Do not rely on a hard-coded port table: read+the values from the project's own env resolver (per `PROJECT.md` ยง2). If the+resolved values do not match a running dev server, fix/export the env first, then+continue.-Do not start the standalone e2e server as the product under test.+#### 2.1 Dependencies are installed-Use `scripts/init-dev-env.sh`. It follows the e2e setup pattern โ Postgres,-Redis, migrations, auth/key-vault/S3 test env, seed user โ but it is owned by this-skill and starts the repo's dev server (`pnpm run dev:next` / `bun run dev`),-not `e2e/scripts/setup.ts --start`. The script hard-blocks when root `.env`-exists, so it cannot accidentally override a user's local config. When `.env`-exists, do not call any `init-dev-env.sh` subcommand.+Install per `PROJECT.md` ยง2. **Universal rule: a monorepo root install does not+always cover every app.** If the project has standalone sub-packages with their+own `node_modules` (the adapter says which), install in each one the test will+touch โ a stale standalone install typically fails at build/launch with an+unresolved workspace import.-Decision flow:+#### 2.2 Run long-lived scripts from the repo root-```bash-if [[ -f .env ]]; then- bun run dev-else- ./.agents/skills/agent-testing/scripts/init-dev-env.sh setup-db- ./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user- ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-fi-```--Bootstrap flow when no `.env` exists:--```bash-# From repo root. Managed Postgres/Redis flow requires Docker Desktop.-./.agents/skills/agent-testing/scripts/init-dev-env.sh setup-db-./.agents/skills/agent-testing/scripts/init-dev-env.sh s3 # terminal B โ keep running-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user-./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-```--If using an existing Postgres instead of the managed Docker DB, set-`DATABASE_URL` and `REDIS_URL`, then skip `setup-db`:--```bash-DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh migrate-DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user-DATABASE_URL=postgresql://... REDIS_URL=redis://... ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-```--For backend-only checks, `dev-next` is available, but Web smoke needs the-full-stack `dev` command so Next can proxy the SPA HTML from Vite:+Background commands inherit the current working directory. Relative paths in this+skill and in `PROJECT.md` are repo-root-relative, so a script launched while `cwd`+is a sub-package can fail with `No such file or directory`. Verify `pwd` is the+repo root before launching long-running scripts.-```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-next-```--Useful subcommands:--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh env # print exports-./.agents/skills/agent-testing/scripts/init-dev-env.sh write # write .records/env/agent-testing-dev.env-./.agents/skills/agent-testing/scripts/init-dev-env.sh migrate # migrations only-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user # seed user + CLI API key-./.agents/skills/agent-testing/scripts/init-dev-env.sh qstash # local QStash for workflow paths-./.agents/skills/agent-testing/scripts/init-dev-env.sh s3 # local S3-compatible file storage-./.agents/skills/agent-testing/scripts/init-dev-env.sh preflight # gate agent-runtime tests (QStash + S3)-./.agents/skills/agent-testing/scripts/init-dev-env.sh clean-db # remove managed DB container-./.agents/skills/agent-testing/scripts/init-dev-env.sh clean-s3 # remove persisted local S3 objects-```--#### Local file storage: s3rver MUST be up--The no-`.env` bootstrap points the app at a local `s3rver` instance so browser-uploads, presigned URLs, attachments, and generated files exercise a real S3-HTTP round trip instead of a placeholder endpoint. Start it in a separate-terminal before the dev server:--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh s3-```+#### 2.3 Start the dev environment-The command creates `agent-testing-bucket`, configures CORS for the allocated-local app/SPA origins, and persists objects under-`.records/data/agent-testing-s3`. The fixed `S3RVER` credentials are required by-the emulator's presigned-URL validation. `preflight` performs HeadBucket plus a-real Put/Get/Delete round trip; a listening port alone is not considered ready.+Start the environment per `PROJECT.md` ยง2 (dev server, plus any required services+such as a database, cache, queue, or object store). **Universal rules:**-Keep this storage local to the product-under-test. Step 4 report publishing-still runs in a clean production CLI environment and uploads evidence to-production storage.--#### Agent-runtime prerequisite: QStash MUST be up (queue mode)--Any test that runs an **agent** (`lh agent run`, durable ops, `/api/agent/run`,-the server agent runtime) goes through `AGENT_RUNTIME_MODE=queue` โ the default-here and in production. Creating an agent operation **POSTs to local QStash-(`127.0.0.1:8080`)**, so if QStash is not running the run dies at operation-creation with `TypeError: fetch failed` / `ECONNREFUSED 127.0.0.1:8080`-**before any LLM call** โ no trace is recorded and the failure reads as-unrelated to the env. `FEATURE_FLAGS=-agent_self_iteration` only drops the-self-iteration workflow; it does **not** remove this dispatch dependency. Treat-QStash as a hard prerequisite for agent-runtime tests, not an "only when-workflow" nicety.--So before the first `agent run`, start QStash in a separate terminal and gate on-the preflight:--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh qstash # terminal B โ keep running-./.agents/skills/agent-testing/scripts/init-dev-env.sh preflight # exits non-zero if QStash (or Redis) is down-```--Default script env:--- `APP_URL=http://localhost:3010`-- `DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres`-- `DATABASE_DRIVER=node`-- `AGENT_RUNTIME_MODE=queue` so backend-only agent runtime checks use the- same queued execution path as production-- `REDIS_URL=redis://localhost:6380` for queue-mode agent runtime state-- `FEATURE_FLAGS=-agent_self_iteration` drops the self-iteration workflow (so a- simple chat doesn't fan out), but this does **not** remove QStash from the- agent-runtime path โ queue-mode operation creation still POSTs to QStash.-- Local QStash defaults (`QSTASH_URL`, `QSTASH_TOKEN`, signing keys) are exported,- but the QStash server itself is not auto-started. Run `init-dev-env.sh qstash`- in a separate terminal for **any agent-runtime test** (see the agent-runtime- prerequisite above), not only workflow paths.-- `KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off-- Local S3-compatible storage vars (`s3rver`; start with the `s3` subcommand)-- Managed DB container: `lobehub-agent-testing-postgres`-- Managed Redis container: `lobehub-agent-testing-redis`--`seed-user` creates `[email protected]` / `TestPassword123!` with-onboarding already completed, plus a local API key in-`.records/env/agent-testing-cli.env` for CLI automation. When running Cucumber-against this dev server, pass the same script env into the test process too;-Cucumber has its own `BeforeAll` seed path and it must see `DATABASE_URL`-instead of silently skipping setup:--```bash-cd e2e-# Only in the no-.env branch.-eval "$(../.agents/skills/agent-testing/scripts/init-dev-env.sh env)"-BASE_URL=http://localhost:3010 HEADLESS=true bun run test:smoke-```+- Prefer the project's own already-configured local environment when one exists;+ do not clobber a user's running config.+- Any service the feature under test depends on is a **hard prerequisite**, not an+ "only when needed" nicety. If a run touches a code path that dispatches to a+ queue/worker/object store, that service must be up first or the run dies before+ reaching the code under test โ and the failure often reads as unrelated to the+ env. `PROJECT.md` ยง6 lists these constraints; gate on them.#### 2.4 Auth is green for the selected surface-**Auth is the gate for automated testing, but the gate is surface-scoped.**-Pick the intended surface first when it is already clear from the task, then-check only that surface. Do not block a Web test on CLI device-code auth or an-Electron login state unless the test spans those surfaces.--```bash-./.agents/skills/agent-testing/scripts/setup-auth.sh status --surface web-```--Use `status` with no `--surface` only for cross-surface test plans.--| Surface | Mechanism | One-key path | Standard check |-| -------- | --------------------------------------------- | ------------------------ | ----------------------------------------- |-| CLI | Seeded API key, device-code fallback | `setup-auth.sh cli-seed` | `setup-auth.sh status --surface cli` |-| Web | Seeded better-auth login into `agent-browser` | `setup-auth.sh web-seed` | `setup-auth.sh status --surface web` |-| Electron | App's own persistent login state | Log in once in the app | `setup-auth.sh status --surface electron` |-| Bot | Native apps already logged in | โ | per-platform screenshot |--Login-state checks are standardized โ do NOT hand-roll `window.__LOBE_STORES`-eval snippets; use `scripts/app-probe.sh auth` (returns `{ isSignedIn, userId }`,-works for Electron CDP and web sessions via `AB_TARGET`).--For Web tests, the test surface is always `agent-browser --session lobehub-dev`.-Use `setup-auth.sh web-seed` first in the seeded local env. The user's normal-Chrome is only a source for copying the Cookie header when seed auth is not-available or `status --surface web` still fails. If Chrome is already logged in,-do not open a login page; verify agent-browser first, then request the Network-`Cookie:` header only if that verification fails. Full background and failure modes:-[references/auth.md](./references/auth.md).+**Auth is the gate for automated testing, but the gate is surface-scoped.** Pick+the intended surface first when it is already clear from the task, then check only+that surface. Do not block a web test on CLI auth or a desktop login state unless+the test spans those surfaces. Run the per-surface status check from `PROJECT.md`+ยง3. If a surface is signed out, **drive the sign-in yourself** โ auth is+environment mechanics the skill owns; never hand the user the sign-in click unless+a step genuinely needs something only they can supply (a 2FA push), and then name+the exact blocking step.-#### 2.5 โ Screen-recording preflight (OS-capture surfaces only)+#### 2.5 Screen-recording preflight (OS-capture surfaces only)-macOS `screencapture` / osascript / bot-channel captures come out **entirely-black** when Screen Recording (TCC) permission is missing OR โ just as often โ-the **display is asleep / locked / on a screensaver** (permission is fine, but-there is nothing lit to capture; this bites after a long idle test run). A black-PNG is easy to mistake for a real capture, so gate BEFORE any OS-capture step:+macOS `screencapture` / osascript captures come out **entirely black** when Screen+Recording (TCC) permission is missing OR โ just as often โ the **display is+asleep / locked / on a screensaver** (permission is fine, but there is nothing lit+to capture; this bites after a long idle run). A black PNG is easy to mistake for+a real capture, so gate BEFORE any OS-capture step:```bash-./.agents/skills/agent-testing/scripts/check-screen-recording.sh # exit 0 = OS capture will work+# $SKILL_DIR = wherever this skill is installed+"$SKILL_DIR/scripts/check-screen-recording.sh" # exit 0 = OS capture will work```-It checks both layers โ `CGPreflightScreenCaptureAccess` for permission and a-real one-frame capture for blackness โ and prints the exact fix (which `.app` to-grant, or wake/unlock the display). `capture-app-window.sh` runs it automatically-and refuses to write a black artifact (bypass with `SKIP_SCREEN_CHECK=1`).--This gate is **only** for OS-capture surfaces (bot tests, `capture-app-window.sh`,-osascript screenshots). CDP-based evidence (`agent-browser screenshot`,-`record-app-screen.sh`) renders from the browser engine and is unaffected. Because-the display can sleep mid-run, keep it awake for the whole capture session:+It checks both layers โ permission and a real one-frame blackness probe โ and+prints the exact fix. `capture-app-window.sh` runs it automatically and refuses to+write a black artifact (bypass with `SKIP_SCREEN_CHECK=1`). This gate is **only**+for OS-capture surfaces. CDP-based evidence (`agent-browser screenshot`,+`cdp-screenshot.sh`, `record-app-screen.sh`) renders from the browser engine and+is unaffected. Because the display can sleep mid-run, keep it awake for the whole+capture session:```bash-caffeinate -dimsu & # prevent display/idle sleep for the test run; kill when done+caffeinate -dimsu & # prevent display/idle sleep for the run; kill when done```#### Phase 1 approval gate โ report environment + plan to the user@@ -372,7 +210,7 @@ Execute. Read and follow [references/plan.md](./references/plan.md). It requires- emoji-prefixed status markers in the verdict and every table row(`โ Ready`, `โ ๏ธ Warning`, `โ Blocked`, `โณ Pending`);- the proposed execution plan, cases, and expected evidence;-- every unresolved prerequisite, clearly assigned to Codex or the user;+- every unresolved prerequisite, clearly assigned to the agent or the user;- an explicit statement that nothing is needed from the user when that is true;- one structured confirmation question after the feedback.@@ -389,187 +227,137 @@ invalidates the plan.### Step 3 โ Pick the surface by change scope-| Change scope | Default surface | Why | Guide |-| ------------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------- | ---------------------------------- |-| **Backend** (TRPC router / service / model / migration) | **CLI** | Fastest loop, text-assertable output, zero UI flakiness | [cli/index.md](./cli/index.md) |-| **Pure frontend** (components, store, styles, UX) | **Electron** (agent-browser + CDP) | Primary product shape; `__LOBE_STORES` state introspection | [ui/electron.md](./ui/electron.md) |-| **Full-stack** (new API + UI consuming it) | **Web** (browser + local dev server) | One surface where network requests and UI are observable together | [ui/web.md](./ui/web.md) |-| **Bot channels** (Discord / WeChat / Lark / โฆ) | Native app via osascript / bridge | Only way to exercise the real channel end-to-end | `bot/<platform>/index.md` |+| Change scope | Default surface | Why | Guide |+| -------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------- |+| **Backend** (router / service / model / migration) | **CLI** | Fastest loop, text-assertable output, zero UI flakiness | [surfaces/cli.md](./surfaces/cli.md) |+| **Pure frontend** (components, store, styles, UX) | **Electron** (agent-browser + CDP) if the project ships a desktop shell, else **Web** | Primary product shape; live state introspection | [surfaces/electron.md](./surfaces/electron.md) |+| **Full-stack** (new API + UI consuming it) | **Web** (browser + local dev server) | One surface where network requests and UI are observable together | [surfaces/web.md](./surfaces/web.md) |-Escalate, don't duplicate: verify a backend change with the CLI first; only add-a UI pass when the change actually affects the UI.+Which of these surfaces the project actually has, and how each one launches, comes+from `PROJECT.md` ยง4. Escalate, don't duplicate: verify a backend change with the+CLI first; only add a UI pass when the change actually affects the UI.**Verify the change runs where you think it does โ confirm runtime, don't assume.**-Some features have two execution paths and the UI silently picks one (e.g. group-orchestration: the chat UI defaults to the **client** runtime, while the fix may-live in the **server** runtime / `AGENT_RUNTIME_MODE=queue` durable-op path). A-test that exercises the wrong path can pass green without ever touching the code-under test. Before trusting a result, **prove which runtime ran** โ e.g. check for-a server `agent_operations` row, the QStash `/api/agent/run` steps, or server-only-log lines. If the UI won't take the server path, drive it directly (call the-server TRPC mutation / endpoint) so the server runtime actually executes.+Some features have two execution paths and the UI silently picks one (e.g. a client+runtime vs a server/queue runtime). A test that exercises the wrong path can pass+green without ever touching the code under test. Before trusting a result, **prove+which runtime ran** โ a server-side operation row, a queue step, a server-only log+line. If the UI won't take the intended path, drive it directly (call the server+endpoint) so that runtime actually executes.#### Environment support (local macOS vs cloud Linux)-The decisive constraint per surface is **how evidence (screenshots) is-captured**: CDP-based capture (`agent-browser screenshot`) renders from the-browser engine and needs no real display; OS-level capture (`screencapture`,-osascript) is macOS-only.+The decisive constraint per surface is **how evidence (screenshots) is captured**:+CDP-based capture (`agent-browser screenshot`) renders from the browser engine and+needs no real display; OS-level capture (`screencapture`, osascript) is macOS-only.| Surface | macOS (local) | Linux / cloud (headless) | Screenshot mechanism || -------- | ------------- | --------------------------------------------------------- | ------------------------------------------------------ || CLI | โ | โ | n/a โ text output || Web | โ | โ headless Chromium works natively | CDP โ no display needed || Electron | โ | โ ๏ธ runs, but needs a display server: wrap with `xvfb-run` | CDP works under Xvfb; `capture-app-window.sh` does NOT |-| Bot | โ | โ osascript + native apps are macOS-only | macOS `screencapture` only |--When a test must stay cloud-portable, prefer CDP-based evidence over-OS-level capture wherever both exist.--#### Bot platforms-| Platform | Guide | Quick switcher |-| ------------- | ------------------------------------------------ | --------------------- |-| Discord | [bot/discord/index.md](./bot/discord/index.md) | `Cmd+K` |-| Slack | [bot/slack/index.md](./bot/slack/index.md) | `Cmd+K` |-| Telegram | [bot/telegram/index.md](./bot/telegram/index.md) | `Cmd+F` |-| WeChat / ๅพฎไฟก | [bot/wechat/index.md](./bot/wechat/index.md) | `Cmd+F` |-| Lark / ้ฃไนฆ | [bot/lark/index.md](./bot/lark/index.md) | `Cmd+K` |-| QQ | [bot/qq/index.md](./bot/qq/index.md) | `Cmd+F` |-| iMessage | [bot/imessage/index.md](./bot/imessage/index.md) | bridge (no osascript) |--Each platform folder contains an `index.md` (activation, navigation,-send-message, verification snippets) and a `test-<platform>-bot.sh` script-sharing the interface:--```bash-./.agents/skills/agent-testing/bot/<platform>/test-<platform>-bot.sh <channel_or_contact> <message> [wait_seconds] [screenshot_path]-```--New to osascript automation? Read-[references/osascript.md](./references/osascript.md) first โ it is a general-macOS-automation asset (activate, type, paste, screenshot, accessibility reads,-gotchas), not bot-specific.+When a test must stay cloud-portable, prefer CDP-based evidence over OS-level+capture wherever both exist.### Step 4 โ RunSurface guides above carry the detailed workflows. Shared infrastructure:-| Need | Where |-| ------------------------------------ | -------------------------------------------------------------------- |-| Start / restart the local dev server | [references/dev-server.md](./references/dev-server.md) |-| `agent-browser` command reference | [references/agent-browser.md](./references/agent-browser.md) |-| osascript patterns (general macOS) | [references/osascript.md](./references/osascript.md) |-| Local gateway closed loop + probing | [references/agent-gateway.md](./references/agent-gateway.md) |-| Screen recording | [references/record-app-screen.md](./references/record-app-screen.md) |+| Need | Where |+| ---------------------------------- | -------------------------------------------------------------------- |+| `agent-browser` command reference | [references/agent-browser.md](./references/agent-browser.md) |+| osascript patterns (general macOS) | [references/osascript.md](./references/osascript.md) |+| Screen recording | [references/record-app-screen.md](./references/record-app-screen.md) |#### Scripts-All under `.agents/skills/agent-testing/scripts/`:--| Script | Usage |-| ------------------------------- | ------------------------------------------------------------------------------------------- |-| `test-env.sh` | Print/export the resolved local test env and ports |-| `setup-auth.sh` | One-stop auth setup & status check (`status` / `cli` / `web`) |-| `init-dev-env.sh` | Self-contained local dev env (`setup-db` / `s3` / `seed-user` / `dev-next` / `dev`) |-| `app-probe.sh` | LobeHub app probes: `auth` / `route` / `ops` / `goto <path>` / `errors` |-| `agent-browser-klm.mjs` | Wrap `agent-browser`, run the real action, and append a GOMS-KLM interaction atom JSONL |-| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` / markdown cost output |-| `record-gif.sh` | Frame-sequence โ GIF for time-based behavior (streaming, timers, animations) |-| `report-init.sh` | Scaffold a structured test report, grouped by acceptance subject (Step 5) |-| `fixture.mjs` | Per-check fixture assets: `init-check` / `list` / `compose` an ingest-ready round (Step 5) |-| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |-| `electron-dev.sh` | Manage Electron dev env (start/stop/status/restart, CDP 9222) |-| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses agent-browser daemon); `--check` preflight |-| `capture-app-window.sh` | Screenshot a specific app window (general; used by bot tests) |-| `record-app-screen.sh` | Record app screen (video + periodic screenshots) |-| `record-electron-demo.sh` | Record Electron app demo with ffmpeg |-| `agent-gateway/` | Gateway probe / dump / analyze tools |--`app-probe.sh` is the LobeHub-specific fast path into app state โ auth check,-current route, running operations, and `goto <path>` quick navigation-(`/agent/<agentId>/<topicId>`, `/task/<taskId>`, `/settings`, โฆ) so a test can-jump straight to the state under test instead of clicking through the UI. See-[ui/electron.md](./ui/electron.md#lobehub-probes--quick-navigation) for usage.--#### Agent-browser interaction-cost tracing+All under `<skill-dir>/scripts/` (resolve `<skill-dir>` to wherever this skill is+installed; `chmod +x` is applied on install):++| Script | Usage |+| ------------------------------- | ----------------------------------------------------------------------------------------------- |+| `report-init.sh` | Scaffold a structured report grouped by acceptance subject (Step 5) |+| `fixture.mjs` | Per-check fixtures: `init-check`, `list`, and `compose` an ingest-ready round (Step 5) |+| `record-gif.sh` | Frame-sequence โ GIF for time-based behavior (streaming, timers, animations) |+| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |+| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses the agent-browser daemon); `--check` preflight |+| `capture-app-window.sh` | Screenshot a specific app window (general; macOS OS capture) |+| `record-app-screen.sh` | Record app screen (CDP screenshots โ video + gallery) |+| `agent-browser-klm.mjs` | Wrap `agent-browser`, run the real action, append a GOMS-KLM interaction atom JSONL |+| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` |++Project-specific probes and env scripts (the "jump straight to app state" fast+paths) live in the project's own `.agents/verify/scripts/` and are described in+`PROJECT.md` ยง5 โ not here.++#### Agent-browser interaction-cost tracing (optional, UI runs)For UI verification runs, drive cost-bearing browser actions through the KLMwrapper so the same action also records a user-equivalent interaction atom:```bashTRACE="$DIR/interaction-trace.jsonl"+SESSION=your-session # from PROJECT.md-./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs \+"$SKILL_DIR/scripts/agent-browser-klm.mjs" \--klm-trace "$TRACE" --klm-phase login --klm-check case-1 \- --session lobehub-dev click @e3+ --session "$SESSION" click @e3-./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs mental \+"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \--klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \- --confidence 0.75 --reason "First view requires understanding run status and next action"+ --confidence 0.75 --reason "First view requires understanding state and next action"```The wrapper forwards every non-`--klm-*` argument to `agent-browser`. Physicalactions are inferred from the browser command (`click โ P+K`, `fill/type โP+T(n)`, `press โ K`, `wait โ R`). Mental operators (`M`) are explicit agent-estimates recorded with the `mental` subcommand after the first meaningful page-view or a decision-heavy inspection step.--Analyze the trace before publishing:+estimates recorded with the `mental` subcommand. Analyze before publishing:```bash-./.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs \+"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \--trace "$TRACE" --result "$DIR/result.json" --write```-This writes `result.json.interactionCost`; `verify ingest-report` stores it on-the verify run metadata so the report can render a separate interaction-cost-section.+This writes `result.json.interactionCost`; `verify ingest-report` stores it on the+run metadata so the report can render a separate interaction-cost section.### Step 5 โ Structured report (mandatory deliverable)-Every automated test session ends with a structured, evidence-backed report โ-not a chat-only summary. Scaffold it up front and fill it as you test:+Every automated test session ends with a structured, evidence-backed report โ not+a chat-only summary. Scaffold it up front and fill it as you test:```bash-# --subject = the acceptance this run belongs to (Step 6) โ pass it up front-DIR=$(./.agents/skills/agent-testing/scripts/report-init.sh --subject topic:tpc_xxx my-feature "Verify my feature")+# Pass the acceptance subject up front so every round is grouped correctly.+DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-feature "Verify my feature")# ... test, saving screenshots / CLI transcripts into $DIR/assets/ ...-# fill $DIR/result.json (scenario, context, cases[], summary.conclusion) โ the report;+# fill $DIR/result.json (scenario, context, plan[], cases[], summary.conclusion) โ the report;# $DIR/report.md holds only the narrative tail (follow-ups / notes / score)```-Reports live in `.records/reports/<subject-key>/<timestamp>-<slug>/` (gitignored),-**grouped by acceptance**: one dir per subject (`topic-tpc_xxx`, with an-`acceptance.json` marker), one subdir per verification run. Each run dir holds-`result.json` (the structured report โ scenario/context/cases/summary),-`report.md` (narrative tail), `assets/` (evidence). `--subject` also pre-fills-`result.json.subject` so ingest attaches the run automatically. Format spec and-evidence rules: [references/report.md](./references/report.md).--#### Fixtures: reusable per-check assets--When a run needs seeded/constructed data (fixture rounds, seed files, probe-steps), keep those assets per CHECK ITEM โ the business check that recurs-across rounds โ under `.records/fixtures/<subject-key>/<check-id>/`-(`check.json` = plan fragment + case template + future replay `steps`;-`seed/` = reusable INPUT assets only). The reusability line is inputs vs-outputs: what a run consumes (files to upload, DB seed fragments, stand-in-evidence for synthetic ingest rounds) belongs in `seed/`; what a run produces-(screenshots, transcripts) is tied to that one execution and stays in the round-dir's `assets/` โ never copy it back into the fixture. Compose an ingest-ready-round from checks instead of hand-writing result.json each time:+Reports live in `.records/reports/<subject-key>/<timestamp>-<slug>/` (instruct+the project to gitignore `.records/`), grouped by acceptance. The subject+directory contains an `acceptance.json` marker and one subdirectory per+immutable round. Passing `--subject` also pre-fills `result.json.subject`.+Format and evidence rules: [references/report.md](./references/report.md).++#### Fixtures: reusable per-check inputs++When a check needs reusable seed data or replay steps, keep it under+`.records/fixtures/<subject-key>/<check-id>/`: `check.json` stores the plan and+case template; `seed/` stores reusable inputs. Execution outputs such as+screenshots and transcripts remain in the round's `assets/` and must never be+copied back into a fixture.```bash-F=./.agents/skills/agent-testing/scripts/fixture.mjs-$F init-check --subject topic:tpc_xxx palette-long-list # scaffold, then fill check.json+F="$SKILL_DIR/scripts/fixture.mjs"+$F init-check --subject topic:tpc_xxx palette-long-list$F list --subject topic:tpc_xxx-DIR=$($F compose --subject topic:tpc_xxx --slug round4 --title "็ฌฌๅ่ฝฎๅ จ้ๅๅฝ" \- palette-open palette-long-list) # โ report group round dir-lh verify ingest-report "$DIR" ... # fixture rounds are normal reports+DIR=$($F compose --subject topic:tpc_xxx --slug round4 --title "Full regression" \+ palette-open palette-long-list)```-Two hard rules worth front-loading:+Hard rules worth front-loading:- **Report language = the user's conversation language.** Write `report.md` andevery human-facing string in `result.json` (case `name`/`observation`,@@ -577,207 +365,154 @@ Two hard rules worth front-loading:conversing in. `result.json` keys/status values stay English.- **`result.json` is the report; the verify page renders it.** Each testedbehavior is one entry in `cases[]` (`{ name, result, observation, evidence }`);- the published `/verify/<id>` page builds the scope header from- `scenario`+`context`, the check list from `cases[]`, and the headline verdict- from `summary.conclusion`. So do NOT hand-build a case table or a scope block in- `report.md` โ they double up on the page. `report.md` is the narrative tail- only (follow-ups / this-round notes / score).+ the page builds the scope header from `scenario`+`context`, the check list from+ `plan[]`+`cases[]`, and the verdict from `summary.conclusion`. Do NOT hand-build+ a case table or a scope block in `report.md` โ they double up on the page.- **Visual evidence lives in `result.json`, NOT in `report.md`.** Attach each- screenshot/GIF to the relevant case via `cases[].evidence` (path or array of- paths under `$DIR`); the verify page renders it next to that check. Do NOT- embed images/GIFs in `report.md` (no ``) โ they would just- double up with the per-case evidence the page already shows. `report.md` stays- prose-only (follow-ups / notes / reproduction).-- **Final replies: the ONLY visual deliverable is the published `/verify/<id>`- link โ put NO images and NO local-file links in the chat reply at all.** The- chat UI cannot load a local-path image: a ``- embed renders as a broken-image placeholder (empty grey box), and a- `[Image #1 โฆ](<report-dir>/assets/foo.png)` link renders as blue text that- can't be opened โ both are dead. Local report paths only resolve on the- machine, not in the message. So the primary (and only) evidence pointer in the- reply is the `https://app.lobehub.com/verify/<id>` URL, where every screenshot- is already rendered inline; you may also mention the local report dir as a- plain string for reference (not a markdown link). Describe key visual outcomes- in prose if useful, but never attempt to show a screenshot inline in chat.-- **Time-based behavior needs a GIF, not a screenshot.** If a case asserts- change over time (streaming output, a ticking timer, loading states,- animations), record it with `scripts/record-gif.sh` and attach the GIF as that- case's `evidence` โ a static screenshot cannot prove the behavior.--### Step 6 โ Publish to LobeHub (mandatory)+ screenshot/GIF to its case via `cases[].evidence`; the page renders it next to+ the check. Do NOT embed images/GIFs in `report.md`.+- **Final replies lead with the published `/acceptance/<id>` link; the round's+ `/verify/<id>` link may follow as the immutable record. Put no images or local+ file links in the chat reply.** The acceptance page is the stable cross-round+ decision surface; the verify page renders that round's evidence inline. You+ may mention the local report directory as plain text.+- **Time-based behavior needs a GIF, not a screenshot.** Streaming output, a+ ticking timer, loading states, animations โ record with `scripts/record-gif.sh`+ and attach the GIF as that case's evidence; a static screenshot cannot prove it.++### Step 6 โ Publish to the LobeHub verify platform (mandatory)The local report under `.records/reports/` is the working artifact; the-**deliverable is the report opened in LobeHub**. Do not stop at local files โ-push the session up with the CLI so the user (and later reviewers) can open it-at a stable URL with the evidence rendered inline.--**Publish targets PRODUCTION (`https://app.lobehub.com`), not the local dev-server.** The product-under-test usually runs against a local env whose seeded-CLI profile (`.records/env/agent-testing-cli.env`) points the CLI at-`http://localhost:3010` via `LOBEHUB_SERVER` / `LOBE_API_KEY` /-`LOBEHUB_CLI_HOME=.lobehub-dev`. Those overrides are for _running_ the backend-test โ they are wrong for _publishing_: a localhost run yields a URL nobody else-can open, and a local env's stub S3 makes file-evidence uploads fail-(`fetch failed`). The deliverable must live on production, with the user's real-login (`~/.lobehub`) and real storage.--So run the publish in a CLEAN environment that strips the local dev overrides,-which falls back to the CLI defaults (`https://app.lobehub.com` + `~/.lobehub`):+**deliverable is the report opened on the verify platform**. Do not stop at local+files โ push the session up with the CLI so the user (and later reviewers) can open+it at a stable URL with the evidence rendered inline.++**Publish targets PRODUCTION defaults (`https://app.lobehub.com`), not a local-dev+override profile.** When the product-under-test runs against a local env, the CLI+may be pointed at that local server through override env vars โ those overrides are+for _running_ the test, and they are wrong for _publishing_: a localhost run yields+a URL nobody else can open, and a local env's stub storage makes file-evidence+uploads fail. Publish in a CLEAN environment that strips those overrides so `lh`+falls back to its production defaults and the user's real login. Clear whatever+override vars the project uses; for reference, clearing a local-server override+profile looks like:```bash-# Publish to PRODUCTION โ strip the local dev CLI overrides so `lh` uses its-# production defaults (app.lobehub.com + the user's real ~/.lobehub login).+# Strip local-dev CLI overrides so `lh` uses production defaults + the user's real login.env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \lh verify ingest-report "$DIR" --source agent-testing --open --json```-Production auth is the user's own device-code login, not the seeded local key.-Verify it first in the same clean env; if it returns "No authentication found",-have the user log in (the flow prints a URL + code to authorize in the browser),-then re-run the publish:+Production auth is the user's own device-code login. Verify it first in the same+clean env; if it returns "No authentication found", have the user log in+(`lh login` prints a URL + code), then re-run the publish.-```bash-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME lh verify run list --json # [] = authed-env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME lh login # only if not authed-```+**Check the CLI version before publishing.** The publish flags this step relies on+(`--subject`, `--source agent-testing`) require `lh` >= the version recorded in+this skill's `.skill-meta.json`. The `lh` on PATH in a consumer repo is often+older and fails only at this final step (`unknown option '--subject'`). Run+`lh --version` first; when it is older than the marker version, publish through+`npx @lobehub/cli@latest` instead of the PATH binary.`verify ingest-report` reads `$DIR` and, in one call, creates a new immutableverification run, attaches it to the subject acceptance, and uploads everything:-- `result.json.plan[]` โ the frozen check plan (what this round set out to verify),- with a business-scenario `category` on every item; categories name requirements- or features, never execution surfaces such as Desktop / CLI / Backend-- `result.json.cases[]` โ one check result each (verdict + key observation),- paired back to its plan item by `id`; a planned item with no case renders as- **ๆชๆง่ก** instead of silently disappearing-- each case's `evidence` file(s) โ uploaded to storage and attached to that result-- `report.md` โ the session's full report body, plus the `summary` stats--Two links are attached for you, no flags needed: the branch's **pull request**-(asked of `gh`) and โ when the harness is running inside a LobeHub-spawned agent-โ the **conversation that produced the report**, read from the `LOBEHUB_TOPIC_ID`-/ `LOBEHUB_AGENT_ID` / `LOBEHUB_OPERATION_ID` the runtime echoes into the child-env. The origin conversation is shown to the report's author only, never to-someone holding the shared link.--It prints the `verifyRunId` and, with `--open`, the in-app path-`/verify/<verifyRunId>` โ the report viewer (verdict, stats, every check, and the-inline screenshot/text evidence). On production that resolves to-`https://app.lobehub.com/verify/<verifyRunId>`.--**The final chat reply leads with the ACCEPTANCE link, not the verify link.**-`https://app.lobehub.com/acceptance/<acceptanceId>` is the stable cross-round-page where the user reviews the LATEST merged state and closes the loop; a-`/verify/<id>` report is one round's immutable snapshot โ supporting detail.-Phrase the deliverable as "ๅจ acceptance ้กตๆฅ็ๆๆฐ้ชๆถ็ถๆ" with the acceptance-URL first; the round's verify link may follow as the per-round record.+- `result.json.plan[]` โ the frozen check plan, with a business-scenario+ `category` on every item (categories name requirements or features, never+ execution surfaces such as Desktop / CLI / Backend);+- `result.json.cases[]` โ one check result each, paired to its plan item by `id`;+ a planned item with no case renders as **ๆชๆง่ก** instead of silently vanishing;+- each case's `evidence` file(s) โ uploaded and attached to that result;+- `report.md` โ the report body, plus the `summary` stats.++It prints the `verifyRunId`, `acceptanceId`, and their in-app paths. The final+reply leads with `https://app.lobehub.com/acceptance/<acceptanceId>` as the+latest cross-round state; the round-specific+`https://app.lobehub.com/verify/<verifyRunId>` may follow as supporting detail.#### Every run belongs to a subject acceptance (mandatory)-Every agent-testing run MUST be chained onto a task, topic, or document-**acceptance aggregate**, so every round lands on one auditable decision page.-When the harness runs inside a LobeHub topic, `ingest-report` automatically uses-`LOBEHUB_TOPIC_ID` as `topic:<id>`; do not ask the user to supply it and do not-omit the acceptance. An explicit `--subject` or `result.json.subject` overrides-that default for task/document verification:+Every run MUST be chained onto a task, topic, or document **acceptance aggregate**,+so every round lands on one auditable decision page. When the harness runs inside a+LobeHub topic, `ingest-report` automatically uses `LOBEHUB_TOPIC_ID` as+`topic:<id>` โ do not ask the user for it and do not omit the acceptance. Outside a+LobeHub topic, an explicit subject is required and publishing without one fails:```bash# SUBJECT is task:$TASK_ID, topic:$TOPIC_ID, or document:$DOC_IDenv -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \- lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" --open --json+ lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" \+ --requirement "$REQUIREMENT" --open --json```-`--subject` accepts `task:<id> | topic:<id> | document:<id>` (or put-`"subject": "task:<id>"` / `{ "type", "id", "requirement" }` in `result.json`).-Outside a LobeHub topic, one of those explicit forms is required; publishing-without a resolvable subject fails instead of creating an orphan verify report.--**Always supply the acceptance `requirement` (้ชๆถ็ฎๆ ) with the subject** โ-the object form `{ "type", "id", "requirement": "<one-sentence goal>" }` or-`--requirement`. It is NOT auto-generated: an aggregate created without one-renders "ๅฐๆช่ฎฐๅฝ่ฏฅๅฏน่ฑก็้ชๆถ็ฎๆ " at the top of the decision page. Write it as-the one-sentence business goal the whole acceptance is judged against (not this-round's scope). A recorded requirement is immutable; an empty one is backfilled-by the first later round that supplies it.+`--subject` accepts `task:<id> | topic:<id> | document:<id>`; `result.json` may+instead use the string form or+`{ "type": "task", "id": "<id>", "requirement": "<goal>" }`.++**Always supply the acceptance requirement on the first ingest.** It is not+generated automatically. Write the one-sentence business goal against which the+whole acceptance is judged, not the current round's narrower scope. A recorded+requirement is immutable; an initially empty value may be backfilled by the first+later round that supplies one.+The first ingest creates the acceptance and every ingest creates its next-immutable round. The user closes the loop on `/acceptance/<acceptanceId>` (also-printed by `--open`) โ accept / reject with a comment; inspect or decide from the-terminal via `lh verify acceptance view|accept|reject <id | type:id>`.+immutable round. The user closes the loop on `/acceptance/<acceptanceId>`; the+same state is available through+`lh verify acceptance view|accept|reject <id | type:id>`.++When no subject exists yet (first verification in a repo, no tracked task),+create one with the CLI instead of asking the user for an id โ a dedicated task+is the natural acceptance subject for the run:++```bash+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh task create -n "<project>: <what this run verifies>" -i "<one-line goal>"+# prints: Task created: T-<n> <name> โ the T-<n> identifier works directly:+SUBJECT="task:T-<n>"+```-#### Before the next round: read the acceptance state and the user's feedback (mandatory)+Tell the user which task was created. Reuse the same subject for every follow-up+round in that repo so all rounds land on one acceptance page.-When a follow-up round starts on a subject that already has an acceptance-(repair after a reject, another iteration on the same PR/topic), the FIRST step-of planning is reading the prior state โ never re-derive it from memory:+#### Before a follow-up round: read user feedback++When the subject already has an acceptance, planning starts from its current+state rather than memory:```bashenv -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \- lh verify acceptance view "$SUBJECT" --json # or the acceptance uuid+ lh verify acceptance view "$SUBJECT" --json```-Read three things from the bundle:--- `checks[].state` + `checks[].id` โ which checks passed / failed / never ran,- and the stable ids the next plan MUST reuse (or `supersedes`).-- `checks[].userReview` โ the user's own verdict on each check:- - `action: "accept"` โ the user has signed this check off. It stays settled- across rounds; keep its stable id in the plan (carry it forward or re-run- it cheaply), but it needs no repair work.- - `action: "reject", stale: false` โ **actionable feedback**: this check is- what the next round exists to fix. Read `comment` and every- `annotations[].comment` (region notes circled on the evidence screenshots)- and address them explicitly; the round's fix summary should reference them.- - `stale: true` โ feedback already consumed by a newer round; it is history.-- `checks[].reviews` โ the full feedback trail (for context on how a check- evolved).--The human-readable `view` (without `--json`) prints the same signal: a `C#`-label and a USER column per check, plus a `user feedback` section with-`โถ actionable` / `ยท addressed` markers. After the new round is ingested, the-addressed feedback automatically moves into the check's iteration history on-the acceptance page โ do not delete or restate it anywhere.--**The next round touches ONLY what is not user-settled.** Rounds are immutable-snapshots, but the union view is where "overwriting" happens โ through ids:--- `userReview.action == "accept"` โ user-settled. Do NOT re-run it, do NOT- restate it in the new plan; the union carries it forward untouched.-- a check being fixed or re-verified โ reuse its EXACT stable id, so the new- result lands on the same union row (same `C#`) as a new timeline step.-- a check whose semantics changed โ new id with `supersedes: ['old-id']`.-- NEVER give the same semantic assertion a fresh id without `supersedes`: the- union has no fuzzy matching, so it renders as a pile of new parallel rows- next to the old ones instead of an iteration.+- `checks[].userReview.action === "accept"`: user-settled; omit it from the new+ plan and do not re-run it.+- `action === "reject"` with `stale: false`: address its comment and annotations,+ and reuse the exact stable check id so the next result lands on the same row.+- For a semantic replacement, create a new id with `supersedes: ['old-id']`.+ A fresh id without `supersedes` creates an unrelated parallel check.+- Treat `stale: true` feedback as history already consumed by a newer round.#### Every verification run is an immutable snapshotOne call to `ingest-report` creates one immutable `/verify/<id>` snapshot. Neveroverwrite, replace, prune, or re-ingest into an earlier run. A fix followed byre-verification MUST create another run on the same acceptance, preserving the-earlier plan, results, evidence, and verdict exactly as observed at that time.--Use a fresh report directory for every execution round. The acceptance page is-the stable cross-round URL; individual `/verify/<id>` URLs are permanent-historical records. There is no `--run` update path and no same-directory-sidecar reuse in the agent-testing workflow.+earlier plan, results, evidence, and verdict exactly as observed. Use a fresh+report directory for every execution round.Notes:- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;- `evidence` is a path (or array of paths) relative to `$DIR`. `result`/`verdict`- map onto `passed | failed | uncertain` (pass/okโpassed, fail/errorโfailed,- elseโuncertain).-- Need finer control? The same data is reachable through the atomic commands โ- `verify run create`, `verify result ingest`, `verify evidence upload`- (`--file` or `--content`), `verify report upsert` โ so a session can be built- incrementally instead of from a report dir.-- File evidence uploads through the app's storage (S3/R2). Against a stub or- unreachable bucket (common in local dev) the file PUT fails; `ingest-report`- logs a warning, **skips that one artifact**, and still finishes the session,- results, and report. So the published session is real and openable โ but it is- **missing the skipped evidence**, which is easy to mistake for a complete- report. If the evidence must appear, publish against an env with real storage- (e.g. production) or attach it inline with `verify evidence upload --content`.+ `evidence` is a path (or array) relative to `$DIR`. `result`/`verdict` map onto+ `passed | failed | uncertain`.+- Finer control is available through the atomic commands โ `verify run create`,+ `verify result ingest`, `verify evidence upload` (`--file` or `--content`),+ `verify report upsert`.+- File evidence uploads through the platform's storage. Against a stub or+ unreachable bucket (common in local dev) the PUT fails; `ingest-report` warns,+ **skips that one artifact**, and still finishes โ so the published session is+ real and openable but **missing the skipped evidence**. Publish against real+ storage (production defaults) if the evidence must appear.## Phase 3 โ Finish@@ -787,32 +522,25 @@ Close the run cleanly and leave behind only intentional, auditable artifacts.A test run leaves processes and code edits behind. Clean them up by default oncethe report is published โ a dev server left listening or an injection left in a-service file silently corrupts the next run (and the next agent's mental model).--- **Stop the dev server you started.** If you launched it via `init-dev-env.sh dev`- (the no-`.env` path), tear it down with:-- ```bash- ./.agents/skills/agent-testing/scripts/init-dev-env.sh clean # stop dev server; keep DB/Redis- ```-- `clean` stops only the recorded dev-server PID tree after verifying its PID- start time, command, and working directory. It never uses a global process-name- match and never kills an arbitrary listener merely because it owns a persisted- port. It **leaves the managed Postgres/Redis- containers running** (they are idempotently reused across runs โ `setup-db` is a- no-op when they're up). Use `clean-db` only when you deliberately want the- containers gone, or `stop-dev` for just the server with no note. If the user- started their own `.env` dev server, leave it โ you didn't start it.--- **Revert every code injection.** Any HMR fault-injection (A4/A6/A8 in- `probe-mock-patterns.md`) must be undone and verified: `git checkout -- <files>`- then `grep -rn AGENT-TEST src/` returns nothing. Never leave an injection or a- debug global (`__DBG`, `__loadMoreCalls`) behind.--- **Keep the report + evidence.** `.records/reports/**` is the deliverable โ do- NOT delete it in teardown; it's gitignored and the published verify run points at+source file silently corrupts the next run (and the next agent's mental model).++- **Stop what you started.** Stop the dev server and any services you started,+ using the stop commands from `PROJECT.md` ยง2. Stop only what THIS run started โ+ never a global process-name kill, and never a listener you didn't launch. If the+ user started their own dev server, leave it.+- **Revert every code injection.** Any fault-injection or debug global you added+ (see [references/probe-mock-patterns.md](./references/probe-mock-patterns.md))+ must be undone and verified: restore the file, then `grep -rn AGENT-TEST` returns+ nothing. Never leave an injection or a debug global behind. Note: when you+ injected into a file that already had uncommitted changes, `git checkout --` is+ the WRONG revert โ it wipes the branch's edits too; snapshot the file first and+ restore from the snapshot (probe-mock-patterns covers this).+- **Keep the report + evidence.** `.records/reports/**` is the deliverable โ do NOT+ delete it in teardown; it is gitignored and the published verify run points atit.+- **Check `git status` before reporting the tree clean.** Some dev servers write+ managed files on start; reverting them can make them look like per-start churn.+ Confirm what is dirty rather than assuming.Skip teardown only when the user explicitly wants the environment left up (e.g."leave the dev server running, I'll keep poking at it").@@ -821,17 +549,25 @@ Skip teardown only when the user explicitly wants the environment left up (e.g.```textagent-testing/-โโโ SKILL.md # this router-โโโ cli/index.md # backend verification via the LobeHub CLI-โโโ ui/electron.md # pure-frontend verification in the desktop app-โโโ ui/web.md # full-stack verification in the browser-โโโ bot/<platform>/ # bot-channel verification (osascript / bridge)-โโโ references/ # shared knowledge: auth, dev-server, agent-browser, osascript, report-โโโ scripts/ # setup-auth, report-init, electron-dev, capture, recording, gateway+โโโ SKILL.md # this router+โโโ surfaces/+โ โโโ cli.md # backend verification via the project CLI+โ โโโ web.md # full-stack verification in the browser+โ โโโ electron.md # desktop verification over CDP+โโโ references/ # shared knowledge (generic, read-only in consumers)+โ โโโ plan.md # Phase 1 approval-gate format+โ โโโ report.md # result.json / report.md / evidence spec+โ โโโ agent-browser.md # agent-browser CLI reference+โ โโโ osascript.md # general macOS automation+โ โโโ record-app-screen.md # screen recording+โ โโโ project-adapter.md # PROJECT.md template + first-run bootstrap+โ โโโ common-mistakes.md # GENERIC living log โ read-only, PR upstream+โ โโโ probe-mock-patterns.md # GENERIC living log โ read-only, PR upstream+โโโ scripts/ # generic scripts```## Gotchas- agent-browser: see [references/agent-browser.md](./references/agent-browser.md#gotchas)-- Electron: see [ui/electron.md](./ui/electron.md#electron-gotchas)+- Electron: see [surfaces/electron.md](./surfaces/electron.md#electron-gotchas)- osascript: see [references/osascript.md](./references/osascript.md#gotchas)diff --git a/.agents/skills/agent-testing/cli/index.md b/.agents/skills/agent-testing/cli/index.mddeleted file mode 100644index 88ccfdf092e..00000000000--- a/.agents/skills/agent-testing/cli/index.md+++ /dev/null@@ -1,164 +0,0 @@-# CLI Backend Verification--Default surface for verifying **backend changes** (TRPC routers, services,-models, migrations) end-to-end: fastest loop, text-assertable output, zero UI-flakiness.--## When to use--- Verifying TRPC router / service / model changes end-to-end-- Testing new API fields or response structure changes-- Validating CLI command output after backend modifications-- Debugging data flow issues between server and CLI--## Prerequisites--| Requirement | Details |-| ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |-| Dev server | `localhost:3010` โ see [../references/dev-server.md](../references/dev-server.md) |-| CLI source | `apps/cli/` โ runs from source, no rebuild; standalone `node_modules` โ run `pnpm install` inside `apps/cli/` (root install does not cover it) |-| CLI dev mode | `LOBEHUB_CLI_HOME=.lobehub-dev` for isolated settings |-| Auth | Seeded API key first; Device Code Flow only as fallback โ see [../references/auth.md](../references/auth.md) |-| QStash | **Required for `agent run`** (queue mode). Start `init-dev-env.sh qstash` and verify with `init-dev-env.sh preflight` โ see below |--All CLI dev commands run from `apps/cli/`. Subsequent examples use `$CLI`:--```bash-source ../../.records/env/agent-testing-cli.env-CLI="bun src/index.ts"-```--## Workflow--### Step 1 โ Server up?--See [../references/dev-server.md](../references/dev-server.md) for the health-check, start, and restart commands. Server-side code changes require a restart.--### Step 2 โ Auth ready?--```bash-./.agents/skills/agent-testing/scripts/setup-auth.sh status-```--If the CLI is not ready in the seeded local environment:--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user-source .records/env/agent-testing-cli.env-./.agents/skills/agent-testing/scripts/setup-auth.sh cli-seed-```--If the target environment is not seeded, use the interactive fallback:--```bash-cd apps/cli && LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts login --server http://localhost:3010-```--Seeded API-key auth does not store credentials. It writes local settings under-`$HOME/.lobehub-dev` and requires the generated env file to be sourced before-CLI commands. Details:-[../references/auth.md](../references/auth.md).--### Step 3 โ Test with CLI commands--CLI runs from source, so CLI-side code changes take effect immediately without-rebuilding:--```bash-cd apps/cli-$CLI <command>-```--Capture output for the report as you go (e.g. `$CLI task list | tee "$DIR/assets/task-list.txt"`).--### Step 4 โ Clean up test data--```bash-$CLI task delete < id > -y-$CLI agent delete < id > -y-```--### Step 5 โ Report--Finish with a structured report โ-[../references/report.md](../references/report.md). CLI evidence = exact-command + trimmed output.--## Common testing patterns--### Task system--```bash-$CLI task list-$CLI task create -n "Root Task" -i "Test instruction"-$CLI task create -n "Child Task" -i "Sub instruction" --parent T-1-$CLI task view T-1-$CLI task tree T-1-$CLI task edit T-1 --status running-$CLI task comment T-1 -m "Test comment"-$CLI task delete T-1 -y-```--### Agent system--`agent run` executes through the **server agent runtime in queue mode**, which-POSTs the operation to local QStash (`127.0.0.1:8080`). If QStash is not-running, the run fails at operation creation with `fetch failed` /-`ECONNREFUSED 127.0.0.1:8080` **before any LLM call** โ and no trace is-recorded. So before running an agent, start QStash and gate on the preflight:--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh qstash # separate terminal โ keep running-./.agents/skills/agent-testing/scripts/init-dev-env.sh preflight # non-zero exit if QStash/Redis is down-```--```bash-$CLI agent list-$CLI agent view <agent-id>-$CLI agent run <agent-id> -m "Test prompt" # requires QStash (see preflight above)-```--### Document & knowledge base--```bash-$CLI doc list-$CLI doc create -t "Test Doc" -c "Content here"-$CLI doc view <doc-id>-$CLI kb list-$CLI kb tree <kb-id>-```--### Model & provider--```bash-$CLI model list-$CLI provider list-$CLI provider test <provider-id>-```--## Dev-test cycle--```-1. Make code changes (service/model/router/type)- |-2. Run unit tests (fast feedback)- bunx vitest run --silent='passed-only' '<test-file>'- |-3. Restart dev server (if server-side changes โ see dev-server.md)- |-4. CLI verification (end-to-end)- $CLI <command>- |-5. Clean up test data + write the report-```--## Troubleshooting--| Issue | Solution |-| --------------------------- | ------------------------------------------------------------------------------------------------------ |-| `No authentication found` | Source `.records/env/agent-testing-cli.env`, or run device-code `login --server http://localhost:3010` |-| `UNAUTHORIZED` on API calls | Re-run `init-dev-env.sh seed-user` and re-source the env file; for device-code fallback, re-run login |-| `ECONNREFUSED` | Dev server not running โ see dev-server.md |-| CLI shows old data/behavior | Server needs restart to pick up code changes |-| Login opens wrong server | Must use `--server` flag (env var doesn't work) |diff --git a/.agents/skills/agent-testing/references/agent-browser.md b/.agents/skills/agent-testing/references/agent-browser.mdindex fa5550ff29d..3f0f4a3c501 100644--- a/.agents/skills/agent-testing/references/agent-browser.md+++ b/.agents/skills/agent-testing/references/agent-browser.md@@ -1,10 +1,14 @@# agent-browser CLI Reference-Generic reference for the `agent-browser` CLI โ automate Chromium-based apps (Electron, Chrome, web) via Chrome DevTools Protocol. LobeHub-specific patterns live in [../ui/electron.md](../ui/electron.md) and [../ui/web.md](../ui/web.md); authentication recipes live in [auth.md](./auth.md).+Generic reference for the `agent-browser` CLI โ automate Chromium-based apps+(Electron, Chrome, web) via Chrome DevTools Protocol. Surface-specific patterns+live in [../surfaces/web.md](../surfaces/web.md) and+[../surfaces/electron.md](../surfaces/electron.md); project auth recipes live in+`.agents/verify/PROJECT.md`.-Use `agent-browser` to automate Chromium-based apps via Chrome DevTools Protocol.--Install via `npm i -g agent-browser`, `brew install agent-browser`, or `cargo install agent-browser`. Run `agent-browser install` to download Chrome. Run `agent-browser upgrade` to update.+Install via `npm i -g agent-browser`, `brew install agent-browser`, or+`cargo install agent-browser`. Run `agent-browser install` to download Chrome. Run+`agent-browser upgrade` to update.## Core Workflow@@ -34,10 +38,11 @@ When a UI verification should report user-side interaction cost, run```bashTRACE="$DIR/interaction-trace.jsonl"+SESSION=your-session # from PROJECT.md; $SKILL_DIR = the skill's install dir-./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs \+"$SKILL_DIR/scripts/agent-browser-klm.mjs" \--klm-trace "$TRACE" --klm-phase settings --klm-check case-1 \- --session lobehub-dev click @e4+ --session "$SESSION" click @e4```The wrapper forwards the real command to `agent-browser` and appends one JSONL@@ -50,7 +55,7 @@ Mental effort is intentionally not guessed from DOM shape. After the firstmeaningful page view, add an explicit agent estimate:```bash-./.agents/skills/agent-testing/scripts/agent-browser-klm.mjs mental \+"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \--klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \--confidence 0.75 --reason "Need to understand current page state and choose the verify path"```@@ -58,12 +63,12 @@ meaningful page view, add an explicit agent estimate:Before publish, summarize the trace into the structured report:```bash-./.agents/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs \+"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \--trace "$TRACE" --result "$DIR/result.json" --write```-This populates `result.json.interactionCost` with the `goms-klm@lobe-v1`-summary. The raw trace stays in the local report directory for audit/debug.+This populates `result.json.interactionCost` with the `goms-klm@lobe-v1` summary.+The raw trace stays in the local report directory for audit/debug.## Command Chaining@@ -72,7 +77,8 @@ summary. The raw trace stays in the local report directory for audit/debug.agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i```-Use `&&` when you don't need to read intermediate output. Run commands separately when you need to parse output first (e.g., snapshot to discover refs, then interact).+Use `&&` when you don't need to read intermediate output. Run commands separately+when you need to parse output first (e.g. snapshot to discover refs, then interact).## Essential Commands@@ -130,6 +136,7 @@ agent-browser network har stop ./capture.har # Stop and save HAR fileagent-browser set viewport 1920 1080 # Set viewport size (default: 1280x720)agent-browser set viewport 1920 1080 2 # 2x retinaagent-browser set device "iPhone 14" # Emulate device (viewport + user agent)+agent-browser set offline on|off # Toggle offline (under `set`, not a top-level cmd)# Captureagent-browser screenshot # Screenshot to temp dir@@ -137,27 +144,10 @@ agent-browser screenshot --full # Full page screenshotagent-browser screenshot --annotate # Annotated screenshot with numbered element labelsagent-browser pdf output.pdf # Save as PDF-# Clipboard-agent-browser clipboard read # Read text from clipboard-agent-browser clipboard write "text" # Write text to clipboard-agent-browser clipboard copy # Copy current selection-agent-browser clipboard paste # Paste from clipboard--# Dialogs (alert, confirm, prompt, beforeunload)-agent-browser dialog accept # Accept dialog-agent-browser dialog accept "input" # Accept prompt dialog with text-agent-browser dialog dismiss # Dismiss/cancel dialog-agent-browser dialog status # Check if dialog is open-# Diff (compare page states)-agent-browser diff snapshot # Compare current vs last snapshot+agent-browser diff snapshot # Compare current vs last snapshotagent-browser diff screenshot --baseline before.png # Visual pixel diff-agent-browser diff url <url1> <url2> # Compare two pages--# Streaming-agent-browser stream enable # Start WebSocket streaming-agent-browser stream status # Inspect streaming state-agent-browser stream disable # Stop streaming+agent-browser diff url <url1> <url2> # Compare two pages```## Batch Execution@@ -191,9 +181,10 @@ agent-browser state save auth.jsonagent-browser state load auth.json```-### LobeHub dev server โ inject better-auth cookie--`agent-browser --headed` on macOS can create an off-screen Chromium window, blocking manual login. For a local LobeHub dev server (e.g. `localhost:3010`), copy the `better-auth.session_token` cookie out of a **Network request** in the user's own Chrome DevTools and load it via `state load`. See [auth.md](./auth.md) for the full recipe.+For a local dev server where a headed login is awkward, copy the session cookie out+of a **Network request** in your own browser's DevTools and load it via+`state load`. The exact cookie name and origin for the project under test come from+`PROJECT.md` ยง3.## Semantic Locators (Alternative to Refs)@@ -226,17 +217,9 @@ agent-browser eval -b "$(echo -n 'document.title' | base64)"## Ref Lifecycle-Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot after clicking links/buttons that navigate, form submissions, or dynamic content loading.--## Annotated Screenshots (Vision Mode)--```bash-agent-browser screenshot --annotate-# Output includes the image path and a legend:-# [1] @e1 button "Submit"-# [2] @e2 link "Home"-agent-browser click @e2 # Click using ref from annotated screenshot-```+Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot+after clicking links/buttons that navigate, form submissions, or dynamic content+loading.## Parallel Sessions@@ -246,50 +229,48 @@ agent-browser --session site2 open https://site-b.comagent-browser session list```-## Connect to Existing Chrome--```bash-agent-browser --auto-connect snapshot # Auto-discover running Chrome-agent-browser --cdp 9222 snapshot # Explicit CDP port-```--## iOS Simulator (Mobile Safari)--```bash-agent-browser device list-agent-browser -p ios --device "iPhone 16 Pro" open https://example.com-agent-browser -p ios snapshot -i-agent-browser -p ios tap @e1-agent-browser -p ios swipe up-agent-browser -p ios screenshot mobile.png-agent-browser -p ios close-```--## Observability Dashboard+Each session is a separate daemon socket, so a wedge in one session is scoped to+that session, not the whole tool. Use distinct session names per target when driving+more than one page.-```bash-agent-browser dashboard install-agent-browser dashboard start # Background server on port 4848-agent-browser dashboard stop-```--## Cloud Providers--Use `-p <provider>` to run against cloud browsers: `agentcore`, `browserbase`, `browserless`, `browseruse`, `kernel`.--## Browser Engine Selection+## Connect to Existing Chrome / Electron```bash-agent-browser --engine lightpanda open example.com # 10x faster, 10x less memory+agent-browser --auto-connect snapshot # Auto-discover running Chrome+agent-browser --cdp 9222 snapshot # Explicit CDP port (Electron dev, remote-debugging Chrome)```## Gotchas-- **Daemon can get stuck** โ if commands hang, `agent-browser close --all` or `pkill -f agent-browser` to reset-- **HMR invalidates everything** โ after code changes, refs break. Re-snapshot or restart-- **`snapshot -i` doesn't find contenteditable** โ use `snapshot -i -C` for rich text editors-- **`fill` doesn't work on contenteditable** โ use `type` for chat inputs-- **Screenshots go to `~/.agent-browser/tmp/screenshots/`** โ read them with the `Read` tool-- **Dialogs block all commands** โ if commands time out, check `agent-browser dialog status`-- **Default timeout is 25s** โ override with `AGENT_BROWSER_DEFAULT_TIMEOUT` (ms) or use explicit waits-- **Shell quoting corrupts eval** โ use `eval --stdin <<'EVALEOF'` for complex JS+- **Daemon can get stuck** โ if commands hang, `agent-browser close --all` or+ `pkill -f agent-browser` to reset. A screenshot RPC that is interrupted can leave+ the session's socket half-consumed, after which every later `screenshot` fails+ (`CDP response channel closed` / `Resource temporarily unavailable`) while+ `eval` / `get url` keep working โ reset with `close --all`, or bypass the daemon+ with `scripts/cdp-screenshot.sh` (raw CDP).+- **HMR invalidates everything** โ after code changes, refs break. Re-snapshot or+ restart.+- **`snapshot -i` doesn't find contenteditable** โ use `snapshot -i -C` for rich+ text editors.+- **`fill` doesn't work on contenteditable** โ use `type` for rich-text inputs.+- **Screenshots go to `~/.agent-browser/tmp/screenshots/`** unless you pass a path โ+ a relative path saves to the caller's cwd; pass an absolute path in longer scripts+ so a lost cwd doesn't misplace the file. Read them with the `Read` tool.+- **`network requests` under-reports** โ it is not ground truth for "did the request+ happen". To judge whether a fault landed, wrap `window.fetch` and record each+ request's own outcome (see probe-mock-patterns).+- **`set offline` trips Chrome's own offline interstitial**, not the app's error+ state โ its "Reconnect" copy also false-matches error-copy greps. Use it to break+ connectivity, not to assert an app-level error.+- **`wait --load networkidle` HANGS during a retry loop** (the network never idles)+ and can blow the command timeout โ use a fixed `wait <ms>` when a fetch is stuck+ retrying. (macOS has no `timeout(1)` to bound it.)+- **Dialogs block all commands** โ if commands time out, check+ `agent-browser dialog status`.+- **Default timeout is 25s** โ override with `AGENT_BROWSER_DEFAULT_TIMEOUT` (ms) or+ use explicit waits.+- **Shell quoting corrupts eval** โ use `eval --stdin <<'EVALEOF'` for complex JS.+- **A blank page at `about:blank` with a 1280px viewport usually means the previous+ `open` failed** (exited non-zero without navigating). The session still answers+ every later probe โ against the fresh page it was born with. Read the `open` exit+ code and stderr rather than assuming the page went blank.diff --git a/.agents/skills/agent-testing/references/common-mistakes.md b/.agents/skills/agent-testing/references/common-mistakes.mdindex d2289c12b85..8e395a1e983 100644--- a/.agents/skills/agent-testing/references/common-mistakes.md+++ b/.agents/skills/agent-testing/references/common-mistakes.md@@ -1,776 +1,540 @@-# Common Mistakes--> **Mandatory**: read this file in full before every agent-testing run and-> self-check against each case.-> When the user gives any negative feedback, append it here as a new case โ-> each with: Wrong approach / Why it's wrong / What it breaks / Correct approach.+# Common Mistakes (generic layer)++> **This is the GENERIC layer of the living log.** It is read-only in a consumer+> repo and updated only by PR to the CLI repo that ships this skill. Every entry+> here must be **product-independent** โ no project's packages, routes, schemas,+> env vars, service names, or business logic. Project-specific learnings go to+> `.agents/verify/common-mistakes.md` (the writable project layer).+>+> **Mandatory:** read this file in full before every agent-testing run and+> self-check against each case. When the user gives negative feedback that is+> product-independent, genericize it and PR it here; otherwise record it in the+> project layer. Each case: Wrong approach / Why it's wrong / What it breaks /+> Correct approach.----## Case 25 โ Building a surface's "twin" without walking the sibling implementation feature-by-feature--**Wrong approach**: when asked to make surface B "consistent with" an existing surface A (a list-panel, an evidence renderer, a link chip), skimming A for its visual language (colors, spacing,-component choices) and rebuilding B from that impression โ instead of walking A's implementation-feature-by-feature and porting each one deliberately. In one round this dropped: A's search box,-A's before/after comparison rendering, and A's authored-report field conventions (title / verdict /-comparison labels), while a hover state contradicted the intended text-emphasis semantics.--**Why it's wrong**: "consistency" is a checklist over the sibling's FEATURES, not a style match.-Every capability the sibling has that the twin lacks is a bug the user will find one screenshot-later. The ux skill's own line โ "compose the canonical surface component, don't re-derive it" โ-covers exactly this, but it only bites if the sibling is actually enumerated before building.--**What it breaks**: the user gets a surface that looks 90% right and is missing load-bearing-features; a round of "ไธบไปไน่ฟ้็ผบ X / ไธขไบ Y" feedback that a 10-minute sibling walk would have-prevented; trust that "ๅฏน้ฝ" means aligned.--**Correct approach**: before building a twin surface, enumerate the sibling's implementation โ-grep its component for every rendered affordance (search, empty states, comparison views, hover-behaviors, drawer wiring) and its data conventions (which fields the author must supply) โ and-turn that list into the build checklist. After building, diff the two surfaces side by side in-screenshots before publishing. For authored artifacts (result.json), re-read the field spec in-references/report.md instead of writing from memory: `title` and `summary.verdict` are identity-fields, and comparison pairs need per-side `label`s.+## M1 โ Judging `passed` from heuristics instead of looking at the screenshot-## Case 20 โ Publishing a replacement as a second Acceptance row and passing UI from text-only evidence+**Wrong approach**: after navigating to a surface, deciding "renders fine / passed"+from only `innerText` keyword greps + a skeleton/element count, without ever opening+the screenshot.-**Wrong approach**: giving a refined check a new id without declaring `supersedes`, then marking-visual UI checks passed from unit-test output or computed-style text without capturing and opening a-screenshot of each claimed surface. A layout probe also accepted an absolutely positioned sidebar-because it was right-aligned, without checking whether it covered the report.+**Why it's wrong**: the persistent nav / layout-shell text is always in the DOM, so+an `innerText` grep almost always false-positives. A blank/white page also has 0+skeletons, so `skeletons === 0` cannot tell "rendered successfully" from "rendered+blank".-**Why it's wrong**: the Acceptance union intentionally does no fuzzy title matching; without an explicit-replacement edge, both ids are valid independent requirements. Program output proves logic, not the-rendered Markdown entity or the absence of visual overlap. A single CSS property is not the layout-contract.+**What it breaks**: publishes a **false `passed`** โ a blank or watermark-only page+reported as working, hiding a real regression.-**What it breaks**: superseded wording remains as a duplicate row, UI changes have no inspectable proof,-and a green report can visibly cover its own content.+**Correct approach**: every screenshot destined for a report `evidence` **must first+be opened with the Read tool and visually confirmed to render the expected content**+before pass/fail. Greps/counts are supporting signals only, never the verdict. A+blank page / watermark / layout-shell-only = fail or uncertain โ go find the root+cause.-**Correct approach**: when a new check replaces an older semantic requirement, put the prior stable id in-the new plan item's `supersedes` array. Every user-visible UI case must require its own screenshot, open-that image before passing, and assert the complete spatial outcome (right attachment plus zero overlap),-not an isolated computed-style value. Never reuse one screenshot as evidence for unrelated UI cases.+----## Case 19 โ Stopping after a fix without publishing the next Acceptance round+## M2 โ Goal is verifying error states, but stopping at happy-path because injection is hard-**Wrong approach**: implementing and locally validating a user-requested second iteration, then-ending the task without committing, pushing, or publishing a fresh immutable verify run to the-existing Acceptance.+**Wrong approach**: after the first batch of fault-injection methods fails to force+an error, giving up on the error-state screenshots and shipping only happy-path ++unit tests, marking the core goal uncertain/blocked.-**Why it's wrong**: an Acceptance is the cross-round audit trail. A local-only fix leaves the PR-stale and makes the Acceptance claim that the previous round is still the latest result. Local-tests are preparation, not the delivery.+**Why it's wrong**: the **entire point** of the task was verifying the error states.+Abandoning that = task not done โ especially when other viable methods exist+unattempted.-**What it breaks**: reviewers cannot inspect the updated code, the Acceptance timeline misses the-iteration, and the user has to ask whether anything was actually shipped.+**What it breaks**: the deliverable doesn't cover what the user asked for โ a wasted+round that needs redoing.-**Correct approach**: after every requested iteration, complete the whole delivery loop unless the-user explicitly says not to: validate the new state, commit and push the PR branch, create a fresh-report directory, ingest exactly once as the next immutable run on the same subject Acceptance,-verify the new round appears, then return both the commit and production links.+**Correct approach**: **do not stop until the core goal is met.** When the first+batch of methods fails, immediately switch to the next known-working one โ see+[probe-mock-patterns.md](./probe-mock-patterns.md) for the escalation ladder (code+injection via HMR, CDP `Network.setBlockedURLs`, server-side fault injection). Get+the **real failure-state evidence** before writing the report.----## Case 18 โ Treating a status badge as proof that the error message rendered+## M3 โ Deriving the task from commit messages / branch name instead of the actual ask-**Wrong approach**: marking an error-state UI case as passed because the platform page showed-the `Failed` badge, while the screenshot only contained an unrelated configuration reminder-and did not show the error alert or its translated message.+**Wrong approach**: on a resumed session with lost prior context, reading the branch+name and top commits and concluding _that_ is the thing to verify โ then building a+whole test run around it โ when the user's real task was a different feature.-**Why it's wrong**: the badge proves only that a failed runtime state reached the page. It does-not prove that `errorCode` was translated and presented to the user, which is the core assertion-of an error-message verification.+**Why it's wrong**: a branch's committed work is not necessarily the current ask.+When context was summarized/lost, the commit history is a _hypothesis_, not the task.+The task lives in the user's words.-**What it breaks**: a report can claim that users receive an actionable explanation while its-visual evidence shows no explanation at all.+**What it breaks**: burns a full test run and clarifying rounds on the wrong feature+before course-correcting.-**Correct approach**: for an error-presentation case, visually require all three signals in the-same screenshot: the target platform, the failed status, and the error alert containing the-expected user-facing message. Any unrelated warning or setup reminder does not satisfy the-error-message assertion.+**Correct approach**: when the user references a task you don't have in context, say+so plainly and RECOVER it before acting โ check `.records/reports/` for prior+sessions on this branch, read the live conversation's own messages (the first user+turn is usually the task), or ask for a pointer. Only translate the ask into+code/commits after it's grounded.-## Case 1 โ Judging `passed` from heuristics instead of looking at the screenshot+----**Wrong approach**: after navigating to a surface, deciding "renders fine /-passed" from only `document.body.innerText` keyword greps +-`document.querySelectorAll('[class*=Skeleton]').length === 0`, without ever-opening the screenshot.+## M4 โ Asserting a capture/tooling root cause from plausibility instead of measuring it-**Why it's wrong**:+**Wrong approach**: when a screenshot came out black or a capture failed, declaring a+root cause from what "sounds right" (missing permission, display sleep, tool bug) and+publishing it โ before running the experiment.-- The persistent left nav / layout-shell text is always in the DOM, so an- innerText grep almost always false-positives.-- A blank / white page also has 0 skeletons, so `skeletons === 0` cannot tell- "rendered successfully" from "rendered blank".+**Why it's wrong**: each of these is falsifiable in seconds and often wrong. A black+frame can be display sleep OR a wedged capture daemon OR a real blank page; guessing+sends the next reader to fix the wrong thing.-**What it breaks**: publishes a **false `passed`**. This run's `/page`-screenshot was actually a blank page (just the LobeHub watermark +-`Debug ID: Desktop > Main > Layout`), yet was reported as "renders fine, proves-removing the dead Suspense didn't break rendering" โ hiding a possible real-regression and misleading the reviewer/user.+**What it breaks**: a published report with a wrong root cause, plus wasted+round-trips retracting each claim.-**Correct approach**: every screenshot destined for a report `evidence` **must-first be opened with the Read tool and visually confirmed to render the expected-content** before pass/fail. grep / counts are supporting signals only, never the-verdict. A blank page / watermark / layout-shell-only = fail or uncertain โ go-find the root cause.+**Correct approach**: for any capture / permission / timing / "environment" failure,+**reproduce and measure before asserting or publishing** โ pixel brightness for+blackness, the permission bit for TCC, an A/B with the variable toggled to isolate+the cause. State "confirmed by X" vs "suspected", and never ship a root cause a+one-line probe could have checked.----## Case 2 โ Goal is verifying error states, but stopping at happy-path because injection is hard+## M5 โ Attaching a stale "before" screenshot as a passed case's evidence (unlabeled)-**Wrong approach**: after `network route --abort`, `window.fetch` override, and-`set offline` all failed to force a fetch failure, giving up on the error-state-screenshots and shipping only happy-path + unit tests, marking the core goal-uncertain/blocked.+**Wrong approach**: putting BOTH the "after" and a stale "before" screenshot into the+same `cases[].evidence` array, unlabeled. The verify page renders every evidence+image with its filename as a heading, so the user opens the stale shots and concludes+the fix didn't land.-**Why it's wrong**: the **entire point** of the task was verifying every error-state. Abandoning that core goal = task not done. Worse, I had already written-down viable alternatives (CDP `Network.setBlockedURLs`, server-side fault-injection) but stopped without executing them.+**Why it's wrong**: a passed case's evidence must show the PASSING (after) state. An+unlabeled before-shot next to it reads as "the current result", making a correct fix+look broken. Filenames are not captions.-**What it breaks**: the deliverable doesn't cover what the user actually asked-for โ a wasted round that needs redoing.+**What it breaks**: the user reads a green report as a failure, loses trust, and it+takes another round to re-explain.-**Correct approach**: **do not stop until the core goal is met**. When the first-batch of methods fails, immediately switch to the next known-working one. For-this app's TRPC the working method is **client-service fetcher instrumentation-via HMR** (throw an error with `data.httpStatus`) or server-side fault-injection โ get the **real failure-state screenshot** before writing the report.-See `probe-mock-patterns.md` for the full working recipes.+**Correct approach**: never ship a raw stale/before screenshot as standalone+evidence. When a contrast helps, use the report format's **native comparison+pairing** โ attach both raw screenshots tagged with a shared `comparison` id and the+page renders them under Before / After bands (see+[report.md](./report.md)). **Do NOT hand-compose the two shots into one image** โ the+page owns the labeling. Two more traps: one evidence item per case (don't reuse the+same pair across cases), and a group needs **exactly one `before` and one `after`**+or it silently degrades to unlabeled evidence.----## Case 3 โ Deriving the task from commit messages / branch name instead of the actual ask+## M6 โ Verifying against a stale build, not your working-tree code-**Wrong approach**: on a resumed session with lost prior context, reading the-branch name (`fix/hetero-callback-signal-metadata`) and top commits (signal-metadata + Monitor re-enable) and concluding _that_ was the thing to verify โ-then spinning up a whole Monitor E2E โ when the user's real task (" ๅผๆ Agent-ๆถๆฏๅ่ฝฌๅๅ่ฝ็ผบๅคฑ ") was an entirely different feature (message multi-select /-forward not exposed on hetero agents). Made the user say "ไฝ ๆฏไธขๅคฑไธไธๆไบๅ๏ผ"-and "ไฝ ็่งฃ้ไบ" twice.+**Wrong approach**: driving an already-running app instance to verify a working-tree+change, and eyeballing the first screenshot as "looks changed".-**Why it's wrong**: a branch's committed work is not necessarily the current-ask. When context was summarized/lost, the commit history is a _hypothesis_, not-the task. The task lives in the user's words.+**Why it's wrong**: a resident or packaged app serves a BUILT snapshot โ it does not+reflect uncommitted / HMR src changes. The change under test may not be running at+all, so the screenshot proves nothing about your code.-**What it breaks**: burned a full Monitor test run + two rounds of clarifying-questions on the wrong feature before course-correcting.+**What it breaks**: verifying against code that isn't your change โ a false pass (or+false fail) on the wrong bundle entirely.-**Correct approach**: when the user references a task you don't have in context,-say so plainly and RECOVER it before acting โ check `.records/reports/` for-prior sessions on this branch, read the live conversation's own messages (the-desktop app persists them; the very first user turn is usually the task), or ask-for a pointer. Only translate the ask into code/commits after it's grounded.-Note: the LobeHub desktop app conversation you're driving may BE the host session-running you โ its message list is the source of truth for what was asked.+**Correct approach**: verify working-tree code in an instance that actually loads it+(a dev instance with HMR/live reload), and **prove it's live by MEASURING a+known-changed value** (a computed style, a new string) before trusting any+screenshot. Don't disturb the user's resident instance โ use a separate+instance/port. Remember main-process / server / adapter code often does not+hot-reload; restart the process and prove which code it runs before concluding a+logic bug.----## Case 4 โ Asserting a capture/tooling root cause from plausibility instead of measuring it+## M7 โ Embedding a local-path screenshot in the chat reply-**Wrong approach**: when a screenshot came out black and CDP capture failed, I-declared root causes from what "sounded right" and published them: first-"terminal lacks Screen Recording permission" (put it in the shipped report), then-"CDP is immune to display sleep", then the opposite "headful CDP stalls when the-display sleeps". Each was stated before running the experiment.+**Wrong approach**: ending the final reply with an inline image embed or link+pointing at the local report dir, believing it will render as a picture in chat.-**Why it's wrong**: every one was falsifiable in seconds and most were wrong.-`CGPreflightScreenCaptureAccess` returned _granted_; a pixel probe showed the black-frame was **display sleep**, not permission; a raw-CDP A/B (display asleep, window-minimized) showed CDP capture works fine in both โ so the real cause was the-agent-browser daemon wedging (D5), not sleep at all.+**Why it's wrong**: the chat UI cannot load a local filesystem path. An image embed+of a local path renders as an empty broken-image box, and a markdown link to a local+path is an un-openable dead link. Local report paths only resolve on the machine,+never inside the message.-**What it breaks**: a **published report with a wrong root cause**, plus wasted-round-trips flip-flopping and having to retract each claim.+**What it breaks**: the reply looks like it has evidence but shows nothing โ the user+gets a broken box and has to go find the verify link anyway.-**Correct approach**: for any capture / permission / timing / "environment"-failure, **reproduce and measure before asserting or publishing** โ pixel-brightness (mean/max) for blackness, `CGPreflightScreenCaptureAccess` for the TCC-bit, an A/B with the variable toggled (display asleep vs awake; window normal vs-minimized) to isolate the cause. State "confirmed by X" vs "suspected", and never-ship a root cause into a report that a one-line probe could have checked.+**Correct approach**: put NO images and NO local-file links in the chat reply. The+published `/verify/<id>` page already renders every screenshot inline โ that URL is+the only visual deliverable. Describe key visual outcomes in prose; mention the local+report dir as a plain string (not a markdown link) if a reference is useful.----## Case 5 โ Attaching the stale "before" screenshot as a passed case's evidence (unlabeled)--**Wrong approach**: after verifying a UI change on the live-code instance, I put-BOTH the "after" (live) and the "before" (stale-build) screenshots into the same-`cases[].evidence` array, unlabeled. The verify page renders every evidence image-with its filename as a heading, so the user opened `01-drag-overlay.png` /-`02-switcher-popover.png` (the STALE shots) and saw the old 28px gap + Apple logo โ-concluding "่ฟๆฏๆฒก่ดด่พน / ่ฟๆฏ Apple logo, ไฝ ๆฒกๆนๅ".+## M8 โ Asking the user "how should I run this?" instead of defaulting to a full isolated run-**Why it's wrong**: a passed case's evidence must show the PASSING (after) state.-An unlabeled before-shot sitting next to it reads as "the current result", making a-correct fix look broken. Filenames are not captions โ the viewer can't tell-before from after.+**Wrong approach**: when a visual/screenshot request needs a non-trivial environment+(the app must run a specific branch, a fixture must be built, an isolated instance is+needed), stopping to ask the user which approach to take โ full isolated run vs a+lighter shot vs a static prototype.-**What it breaks**: the user reads a green/passed report as a failure, loses trust,-and it takes another round to re-explain.--**Correct approach**: never ship a raw stale/before screenshot as standalone-evidence. When a contrast helps, use the report format's **native comparison pairing**-โ attach both raw screenshots and tag them with a shared `comparison` id, and the-verify page renders them side by side under Before / After headings-([report.md](./report.md#L64-78)):--```json-"evidence": [- { "path": "assets/before.png", "comparison": { "id": "layout", "role": "before" } },- { "path": "assets/after.png", "comparison": { "id": "layout", "role": "after" } }-]-```--**Do NOT hand-compose the two shots into one image with sharp** (an earlier version of-this note told you to, and an agent duly shipped stacked red/green banner images โ the-user asked why the report ignored the spec). The page owns the labeling; a composite-also bakes in a fixed layout, can't be zoomed per side, and duplicates the heading the-page already draws. Evidence for a passed case = the after state, or a `comparison`-pair, full stop.--Two more traps in the same area:--- **One evidence item per case, not the same image reused across cases.** Attaching the- same before/after pair to two different cases makes the report look padded and leaves- the second case with no evidence of its own claim.-- A group needs **exactly one `before` and one `after`** โ an incomplete group silently- degrades to ordinary (unlabeled) evidence, i.e. straight back into this bug.--## Case 6 โ `app://renderer` desktop instance runs the STALE built bundle, not working-tree code--**Wrong approach**: driving the already-running desktop app on CDP 9222 (URL-`app://renderer/โฆ`) to verify a working-tree UI change, and eyeballing the first-screenshot as "looks changed".--**Why it's wrong**: the resident desktop app serves a BUILT renderer snapshot โ it-does not reflect uncommitted/HMR src changes. The measured `::before` inset was-still 28px (old) even though the code said 10px. Eyeballing nearly passed it.--**What it breaks**: verifying against code that isn't your change โ a false pass (or-false fail), on the wrong bundle entirely.--**Correct approach**: to verify working-tree UI in the desktop shape, start an-isolated dev instance that loads live code โ `electron-dev.sh start <id>` runs-the dev orchestrator `scripts/dev.mjs` (its own CDP/Vite, copied login), which DOES bundle your src-changes. Prove it's live by MEASURING a known-changed value (e.g. computed-`::before` inset 10px vs old 28px) before trusting any screenshot. Don't kill the-user's resident 9222 app โ use a pool id. Also: `agent-browser open` mangles-`app://` โ `https://app//โฆ` (ERR\_CONNECTION\_CLOSED); navigate inside the SPA by-clicking its own `<a href>` links, not `open`.--## Case 7 โ Embedding a local-path screenshot in the chat reply (broken-image placeholder)--**Wrong approach**: ending the final reply with an inline image embed pointing at-the report dir โ `` โ-believing a leading `!` makes it render as a picture in chat.--**Why it's wrong**: the chat UI can't load a local filesystem path. The embed-renders as an empty grey broken-image box (the user sees a placeholder + " ๅฎๅ จ-็ไธไบๅพๅ ๅฎน "), and the plain-link form `[Image](โฆlocalโฆpng)` is an un-openable-dead link. Local report paths only resolve on the machine, never inside the-message. The earlier guidance that said "if a visual helps, embed it as an image,-not a link" was itself wrong and has been removed.--**What it breaks**: the reply looks like it has evidence but shows nothing โ-the user gets a broken box instead of the screenshot, and has to go find the-verify link anyway.--**Correct approach**: put NO images and NO local-file links in the chat reply.-The published `https://app.lobehub.com/verify/<id>` page already renders every-screenshot inline โ that URL is the only visual deliverable. Describe key visual-outcomes in prose; mention the local report dir as a plain string (not a-markdown link) if a reference is useful.--## Case 8 โ Asking the user "how should I run this?" instead of defaulting to an isolated full run--**Wrong approach**: when a visual/screenshot request needs an isolated env (app-must run the feature branch, not the working dir's current branch; a background-process owns the shared checkout; the surface needs fixture data like a git repo-with 2 worktrees), stopping to ask the user which approach to take โ full-isolated run vs a lighter HMR shot vs a static prototype โ via a plan-approval-question.--**Why it's wrong**: the user's standing preference is that **agent-testing-DEFAULTS to a full isolated-environment screenshot/recording run that ends in a-published verify report** โ "time is not a concern; solve the env problems-yourself." Presenting environment difficulty as a menu of shortcuts pushes setup-decisions back onto the user that the skill is supposed to own.--**What it breaks**: wastes a round on a question the user doesn't want, and+**Why it's wrong**: environment mechanics are the skill's job to own. Presenting env+difficulty as a menu of shortcuts pushes setup decisions back onto the user andsignals the agent will cut corners on fidelity when the env is inconvenient.-**Correct approach**: for any "run it and show me" request, go straight to the-**isolated full run** by default โ spin up a dedicated worktree + dev instance on-the feature branch (never disturb the user's running app or the branch a-background process holds), build whatever fixture data the surface needs (create a-throwaway git repo, `git worktree add` a second tree, point a fresh conversation's-working directory at it, etc.), capture the real rendered screenshot/GIF, verify-it by opening the PNG, and publish the `/verify` report. Only surface a-plan-approval question when the _product decision_ is ambiguous (what to test),-never for _environment mechanics_ (how to render it). Env obstacles are the-skill's job to solve and then iterate back into these logs.+**What it breaks**: wastes a round on a question the user doesn't want.----+**Correct approach**: for any "run it and show me" request, default to the **full+isolated run** that ends in a published verify report โ spin up whatever dedicated+instance and fixture data the surface needs (a throwaway repo, an isolated dev+instance, seeded data), capture the real rendered evidence, verify it by opening the+image, and publish. Only surface a plan-approval question when the _product decision_+is ambiguous (what to test), never for _environment mechanics_ (how to render it).-## Case 8b โ Handing the user the sign-in click when the app under test is signed out--**Wrong approach**: an isolated Electron instance came up signed out (its userData had been wiped by an-earlier `electron-dev.sh stop`, and the golden profile's refresh token was rejected โ `invalid_grant`), so-the run stopped and offered the user a choice: "I click Sign in and you authorize in the browser" vs-"skip the screenshot".+----**Why it's wrong**: this is Case 8 wearing a different hat. `auth.md` says "Electron: log in once manually-in the app" โ that line is addressed to the **agent**, not the user. Auth is environment mechanics, and the-standing rule is that the skill owns those end to end. The user's words: " ไฝ ไปฅๅ้ฝ่ชๅทฑ็น sign in ๆๆ๏ผไธๅบ-่ฏฅ่ฎฉๆๆไฝ ".+## M9 โ Handing the user the sign-in click when the app under test is signed out-**What it breaks**: burns a round on a question the user doesn't want, and stalls a UI-touching change-(Case 9 / Case 10) one click short of its screenshot.+**Wrong approach**: an isolated instance came up signed out, so the run stopped and+offered the user a choice: "I click Sign in and you authorize" vs "skip the+screenshot".-**Correct approach**: drive the sign-in yourself โ click the app's own "Sign in" entry, follow the OAuth-flow in the browser it opens, and get back into the app. Only escalate when a step genuinely needs-something you cannot supply (a 2FA push on their phone), and then name the exact blocking step instead of-offering to drop the evidence.+**Why it's wrong**: auth is environment mechanics, and the skill owns those end to+end. "Log in once in the app" is addressed to the **agent**, not the user.-**What this run changed**: `electron-dev.sh stop <id>` used to delete the instance's userData and its login-with it, so every run re-entered the sign-in flow. It now snapshots the login into-`~/.lobehub/agent-testing/electron-login` first, and `start` seeds new instances from that snapshot-(`login-status` shows the source + expiry; `save-login <id>` captures a live instance before anything-risky, since a _killed_ instance loses its rotated refresh token).+**What it breaks**: burns a round on a question the user doesn't want, and stalls a+UI-touching change one click short of its screenshot.-**Corollary**: never assume a profile is signed in because it exists โ probe for a real signed-in state-(`user().user?.id`, or a cheap authed mutation) before building a fixture on top of it. A rendered sidebar-is not proof: the signed-out onboarding screen has text too, so `innerText.length > 50` passes while-`createAgent` returns `UNAUTHORIZED`.+**Correct approach**: drive the sign-in yourself โ click the app's own "Sign in"+entry, follow the OAuth flow in the browser it opens, and get back into the app. Only+escalate when a step genuinely needs something you cannot supply (a 2FA push on their+phone), and then name the exact blocking step instead of offering to drop the+evidence. Corollary: never assume a profile is signed in because it exists โ probe+for a real signed-in state (a cheap authed call) before building a fixture on top of+it; a rendered shell is not proof (a signed-out onboarding screen has text too).----## Case 9 โ Self-judging a screenshot as "too costly" and asking the user to picture the result+## M10 โ Self-judging a screenshot as "too costly" and asking the user to picture the result-**Wrong approach**: after a small user-facing UI change (a padding tweak), skipping-the rendered screenshot with "it's a trivial style change; restarting Electron to-screenshot costs more than the change is worth โ tell me if you want one." I decided-the cost/benefit for the user and shipped a diff they had to picture in their head.+**Wrong approach**: after a small user-facing UI change, skipping the rendered+screenshot with "it's a trivial style change; restarting to screenshot costs more+than it's worth โ tell me if you want one." Deciding the cost/benefit for the user and+shipping a diff they had to picture.-**Why it's wrong**: whether a verification artifact is "worth it" is **not mine to-decide**. The measuring stick is _whether the user can conveniently inspect the-product_, not how much effort _I_ spend rendering it. Making the user guess the visual-effect from a code diff is the actually-expensive outcome.+**Why it's wrong**: whether a verification artifact is "worth it" is not the agent's+to decide. The measuring stick is _whether the user can conveniently inspect the+product_, not how much effort the agent spends rendering it. Making the user guess the+visual effect from a diff is the actually-expensive outcome.**What it breaks**: the user can't check the deliverable, loses trust, and has to push-back (" ๆๆฌ้ซไธ้ซไธๆฏไฝ ่ชๅทฑ่ฏดไบ็ฎ๏ผ่ๆฏ็จๆทๆฏๅฆๆนไพฟๆฃๆฅไบง็ฉไฝไธบ่กก้ๆ ๅใไฝ ่ฎฉ็จๆท็ๆๆ-่ฟไธชๆๆฌๆ้ซ๏ผๅซ็ๆฃๆตๅๅทๆ ") โ burning a round to get the screenshot I should have-produced up front.+back โ burning a round to get the screenshot that should have been produced up front.**Correct approach**: for ANY user-facing change (even one line of padding/color),-default to rendering it and attaching the screenshot to the verify report as a record-point โ open the PNG to confirm, publish. Never offer the screenshot as an opt-in-("want me to screenshot?"); just produce it. Env/restart cost is the skill's job to-absorb, not a reason to shift the checking burden onto the user.+default to rendering it and attaching the screenshot as a record point โ open the+image to confirm, publish. Never offer the screenshot as an opt-in.----## Case 10 โ Reporting a UI-touching change with only CLI transcripts and no screenshot+## M11 โ Reporting a UI-touching change with only CLI transcripts and no screenshot-**Wrong approach**: when a change includes visible UI copy/badges/alerts, treating-the run as purely backend/service validation and publishing only command-output-evidence, then calling it a complete agent-testing report.+**Wrong approach**: when a change includes visible UI (copy, badges, alerts, a+rejection state), treating the run as purely backend/service validation and+publishing only command-output evidence.-**Why it's wrong**: CLI transcripts prove code paths and tests passed, but they do-not let the reviewer inspect the actual rendered UI. If the feature changed a-channel page alert or badge, the report needs at least one screenshot evidence item-for that visible state.+**Why it's wrong**: CLI transcripts prove code paths and tests passed, but they do not+let the reviewer inspect the rendered UI. "The diff touches no UI file" does not mean+"no UI surface" โ a permission tightening, for instance, IS a UI-visible state (the+blocked user still sees the affordance and now gets a rejection).-**What it breaks**: the user opens the report expecting visual proof and asks-"ๆฒกๆชๅพๅ๏ผ", because the report cannot show whether the UI looks correct.+**What it breaks**: the user opens the report expecting visual proof and finds none.**Correct approach**: if any UI surface changed, include a visual case in the same-verify run. Either drive the real app UI with agent-browser/Electron/Web and attach-a screenshot, or explicitly mark the UI screenshot case blocked with the measured-environment blocker. Do not present a UI-touching report as complete with only CLI-evidence.--## Case 11 โ Skipping the agent-testing entry point for a UI E2E check--**Wrong approach**: after implementing a user-facing Markdown/chat interaction,-running generic local checks and an ad-hoc browser probe without first reading and-following the repo's `agent-testing` skill. The user had to ask why the test plan-did not use the dedicated skill.+run. Drive the real UI and attach a screenshot of the changed/blocked state (and the+success state where relevant), or explicitly mark the UI screenshot case blocked with+the measured environment blocker. Do not present a UI-touching report as complete with+only CLI evidence.-**Why it's wrong**: `agent-testing` encodes LobeHub-specific surface choice, auth,-isolated Electron dev instances, screenshot evidence rules, reporting, and known-tooling traps. Bypassing it makes the validation weaker even when individual unit-tests pass.--**What it breaks**: the run can stop at DOM/text heuristics, use the wrong app-surface, miss required screenshot/report evidence, or fail to publish a verify-report that the user can inspect.--**Correct approach**: for any local end-to-end or manual verification task,-especially UI-facing changes, start with `agent-testing`: read this file and-`probe-mock-patterns.md`, resolve the test env, choose the correct surface, run-the app-specific probes, capture visually confirmed evidence, publish the verify-report, and tear down processes started by the run.+----## Case 12 โ Verifying the selection chip but not the final model payload+## M12 โ Verifying the UI state but not the final effect / payload-**Wrong approach**: after adding a chat text-selection action, marking the feature-verified because the floating toolbar appeared, the selected-text chip rendered,-and the UI store contained a `contextSelections` entry โ without checking the-final message payload that the model receives.+**Wrong approach**: marking a "inject context / apply setting / send data" feature+verified because the UI showed the expected chip/badge/state โ without checking the+actual payload or side effect the feature is supposed to produce.**Why it's wrong**: UI metadata can be saved and displayed while a later-context-engine/runtime gate drops it before request construction. In this case,-the user bubble showed the selected text, but the Anthropic request only carried-the raw user question because generic `contextSelections` were gated behind page-editor context injection.+runtime/transport gate drops it before the real effect. The UI looks successful while+the underlying behavior never happened.-**What it breaks**: ships a feature that looks successful in the chat UI but has-no effect on model behavior; the user must inspect DevTools to discover the-selected context never reached the assistant.+**What it breaks**: ships a feature that looks right in the UI but has no effect;+the user must inspect the network/DB to discover it.-**Correct approach**: for any feature that claims to "inject" context, verify the-last mile: add or run an integration-level assertion against the transformed-messages/request body (e.g. `MessagesEngine` output or transport payload), and-only treat the UI chip/store as supporting evidence.+**Correct approach**: for any feature that claims to change what the system _does_,+verify the last mile โ assert against the transformed request/payload or the observed+side effect (a network body, a DB row, a downstream call), and treat the UI state as+supporting evidence only.----## Case 13 โ GIF evidence ending on an expected-failure frame reads as "the page failed to load"+## M13 โ GIF evidence ending on an expected-failure frame reads as "the page failed"-**Wrong approach**: for a loading-skeleton case, attaching a GIF that records the-full timeline โ skeleton (the asserted state) followed by the error page that the-test data inevitably produces (fake ids / dummy provider keys mean the route can-only end in its error state). The GIF loops and rests on its final frames, so the-viewer opens the report and sees the error card, not the skeleton.+**Wrong approach**: for a loading/streaming case, attaching a GIF that records the+full timeline through to a terminal error state that the test data inevitably+produces. The GIF loops and rests on its final frames, so the viewer opens the report+and sees the error, not the asserted state.-**Why it's wrong**: same trap as Case 5 (unlabeled before-shot) in time-based-form โ the LAST frame of a GIF is its de-facto headline. An expected-failure-terminal state without explanation reads as the case failing (" ่ฟ้ๆไนๅ ่ฝฝๅคฑ่ดฅ-ไบ "), even when the asserted behavior (the skeleton) passed.+**Why it's wrong**: the LAST frame of a GIF is its de-facto headline. An+expected-failure terminal state without explanation reads as the case failing, even+when the asserted behavior passed.-**What it breaks**: the user reads a passed case as a load failure and a round is-burned re-explaining the evidence.+**What it breaks**: the user reads a passed case as a failure and a round is burned+re-explaining.-**Correct approach**: trim evidence to the asserted state โ end the GIF on the-skeleton/loading phase (cut the frames after the terminal state appears), or-attach the static shot of the asserted state as the primary evidence. If the-expected-failure terminal state is worth showing, say so explicitly in the-case's `observation` ("ends in the error page because the test session id is-fake โ expected, not the assertion") so the viewer is told before they see it.+**Correct approach**: trim evidence to the asserted state โ end the GIF on the phase+you're asserting (cut frames after the terminal state), or attach a static shot of the+asserted state as primary evidence. If the terminal state is worth showing, say so in+the case's `observation` so the viewer is told before they see it.----## Case 14 โ Verifying only the entry compose surface when a shared component also appears in deeper pages+## M14 โ Verifying only the entry surface when a shared component also renders deeper-**Wrong approach**: after changing a shared chat input component, publishing a-passing UI report from the home compose surface only, even though the same-component also renders after entering an agent/conversation page.+**Wrong approach**: after changing a shared UI component, publishing a passing report+from one surface only, even though the same component also renders on other pages.-**Why it's wrong**: shared components can be composed with different wrappers,-slots, and responsive containers across surfaces. A fix that looks correct on the-home input can still be misplaced on an inner conversation page.+**Why it's wrong**: shared components are composed with different wrappers, slots, and+responsive containers across surfaces. A fix that looks correct in one place can still+be misplaced elsewhere.-**What it breaks**: the verify report goes green while a deeper product path-still shows the old or awkward warning placement, and the user has to point out-that the page after entry was never checked.+**What it breaks**: the report goes green while a deeper product path still shows the+old or awkward behavior, and the user has to point out the surface that was never+checked.-**Correct approach**: enumerate all product surfaces where the changed shared UI-renders before publishing. For ChatInput placement changes, verify both the home-input and an inner agent/conversation page, attach separate screenshot evidence-for each, and mark any skipped surface explicitly blocked or untested.+**Correct approach**: enumerate every product surface where the changed shared UI+renders before publishing, attach separate screenshot evidence for each, and mark any+skipped surface explicitly blocked or untested.----## Case 15 โ Verifying action-bar placement without covering collapsed toolbar state+## M15 โ Verifying a UI change only in its default state, not its collapsed/overflow state-**Wrong approach**: after moving a warning into a chat input action bar, checking-only the normal expanded toolbar state and publishing the layout as passed,-without forcing the toolbar into its persisted collapsed / auto-collapsed state.+**Wrong approach**: after changing something inside an action bar / toolbar / list+row, checking only the normal expanded state and publishing, without forcing the+collapsed / auto-collapsed / overflow state.-**Why it's wrong**: action bars often have their own overflow behavior and saved-user preference. Adding a warning beside the toolbar can shrink the measured-available width enough to trigger a popup collapse, or a previously saved-collapsed preference can hide the exact action the change is supposed to sit-beside.+**Why it's wrong**: bars and rows often have their own overflow behavior and saved+user preference. A change can shrink the available width enough to trigger a collapse,+or a previously saved collapsed preference can hide the exact affordance the change+sits beside.-**What it breaks**: the screenshot can look acceptable for a fresh profile while-real users who have collapsed the toolbar, or narrower input containers, see the-primary left action replaced by a chevron/popup icon.+**What it breaks**: the screenshot looks fine for a fresh profile while real users+with a collapsed toolbar or narrower container see something different.-**Correct approach**: for any UI change inside an action/toolbar row, verify both-the default state and the collapsed/overflow state. If the design requires a-specific action to stay visible, disable or bypass the toolbar collapse logic for-that surface and include evidence that no collapse chevron is rendered.+**Correct approach**: for any UI change inside a bar/row with overflow behavior,+verify both the default and the collapsed/overflow state, with evidence for each.----## Case 16 โ Publishing a component harness when the user asked for full product verification+## M16 โ Publishing a component harness when the user asked for full product verification-**Wrong approach**: when the isolated Electron instance failed once and local Docker-was unavailable, declaring the product-surface verification blocked and publishing a-component harness report as the main answer, even though another live Electron dev-pool / CDP route was already running and previous runs had used it successfully.+**Wrong approach**: when the product surface hit friction once, declaring it blocked+and publishing a narrow component harness as the main answer โ even though another+live path (a running dev instance, a sibling worktree) was available.-**Why it's wrong**: a component harness proves a narrow render contract, but it does-not prove the full product composition, message list layout, app theme tokens,-store plumbing, or that the evidence is inspectable in the actual desktop surface.-Environment friction is the agent-testing job to solve, not a reason to downgrade-without exhausting known running surfaces.+**Why it's wrong**: a component harness proves a narrow render contract; it does not+prove the full product composition, layout, theming, or that the evidence is+inspectable in the real surface. Environment friction is the skill's job to solve, not+a reason to downgrade before exhausting known-working paths.-**What it breaks**: the user opens a report expecting complete product evidence and-gets a partial proof instead, then has to push back that the full verification used-to run normally.+**What it breaks**: the user opens a report expecting full product evidence and gets a+partial proof.-**Correct approach**: before marking Electron/Web blocked, inventory existing dev-instances and CDP ports, check whether a sibling worktree already runs the needed-live branch, measure the target URL/bundle, and use that path if it renders current-code. Only keep a harness as supporting evidence; the primary UI evidence must come-from the product surface, or the report must clearly fail/block after every known-path is measured.+**Correct approach**: before marking a product surface blocked, inventory existing dev+instances and running surfaces, measure the target to confirm it renders current code,+and use that path if it does. Keep a harness only as supporting evidence; the primary+UI evidence must come from the product surface, or the report must clearly fail/block+after every known path is measured.----## Case 17 โ Using a fixed timeout to arbitrate competing nested popovers+## M17 โ Turning a feature verification into an unbounded environment repair-**Wrong approach**: when a row-level hover popover competes with a nested action-popover, closing the hover surface and suppressing it for an arbitrary number of-milliseconds.+**Wrong approach**: after the normal surface fails to boot, repeatedly modifying+shared dev configuration, reinstalling the whole workspace, and chasing unrelated+dependency problems before running any assertion for the feature under test.-**Why it's wrong**: pointer travel time varies. After the timeout expires, the hover-surface can reopen while the action menu is still active and consume the interaction.+**Why it's wrong**: environment readiness is a gate, not the test goal. A workaround+that changes shared configuration can also make the verification less representative,+while an open-ended repair loop produces no feature evidence.-**What it breaks**: menu actions become intermittently unclickable; destructive-actions can disappear before their confirmation surface opens.+**What it breaks**: the user waits through a long sequence of setup experiments, the+tree gains unrelated edits, and the run still has no reportable result.-**Correct approach**: coordinate both surfaces through explicit shared state. Keep-the hover surface disabled for the complete lifetime of the nested action popover,-then restore it only after that popover closes.+**Correct approach**: follow only recovery paths documented by this skill or the+project adapter. If the failure mode is not covered, stop, revert any experimental+changes, summarize the exact checks and evidence collected, and ask the user before+continuing. Do not repair the environment, switch surfaces, or invent a fallback+without direction.----## Case 19 โ Coordinator hand-driving a broken UI flow instead of re-delegating+## M18 โ Probing the wrong layer: asserting a fixture landed because the write succeeded-**Wrong approach**: after a delegated UI-verification subagent is killed mid-case,-the coordinator takes over and drives the remaining flow inline โ dozens of small-browser commands (probe, reload, sign-in retries, dialog step-through), plus a deep-root-cause dig into a flapping shared dependency, all in the main loop.+**Wrong approach**: writing a fixture directly to the database, reloading the page, and+reading what the UI shows โ then treating a stale value as a product bug.-**Why it's wrong**: the coordinator's per-step latency and context cost are far-higher than a subagent's, and inline grinding turns one recoverable failure into a-long visible stall. Root-causing an env flake (a shared cache/DB rejecting-connections) is also not the goal of the test run โ a disposable local replacement-gets the case unblocked in one step.+**Why it's wrong**: a persisted client cache (SWR / IndexedDB / localStorage) can keep+serving the old value. A successful DB write proves the row changed; it proves nothing+about what the app is _running on_. A fixture bug wearing a product-bug costume is the+most expensive kind.-**What it breaks**: the user watches minutes of micro-steps with no case progress-and loses confidence; total wall-clock and token spend balloon for zero extra-evidence value.+**What it breaks**: you nearly file your own fixture as a regression.-**Correct approach**: when a delegated case dies, repackage the _remaining_ steps-into a fresh, tightly-scoped subagent prompt (include everything already learned:-working recipes, seeded fixtures, exact remaining assertions). Timebox any-environment rabbit hole to a couple of probes, then switch to a disposable local-substitute (e.g. spin up a local instance and override the connection env var for-the test server) instead of diagnosing shared infrastructure.+**Correct approach**: after any direct-DB fixture write, cold-load (clear client+storage/caches, re-seed auth, reopen) and then **assert the fixture in the store+before asserting anything downstream of it**. The DB is where you _wrote_ it; the store+is where the behavior _reads_ it โ verify at the layer the behavior reads. See+[probe-mock-patterns.md](./probe-mock-patterns.md) B.----## Case 20 โ Calling a server-side permission change "no UI surface" and shipping an API-transcript-only report+## M19 โ Building an elaborate mock before checking whether the env already has the real thing-**Wrong approach**: for a change that only edits TRPC routers (tightening who may-mutate a shared resource), classifying the run as backend-only and publishing a-verify report whose evidence is exclusively curl/API probe transcripts. The user-opened the report and asked "ๅฎๅ จๆฒกๆๆชๅพๅ๏ผ".+**Wrong approach**: needing a capability (a working provider key, a service) and,+finding none in the shell env, building a mock server and seeding it โ then watching+the mock receive **zero** requests while the run produces real output.-**Why it's wrong**: a permission tightening IS a UI-visible state โ the blocked-user still sees the edit/delete affordances and now gets a rejection (error toast /-failed action) when clicking them. "The diff touches no .tsx file" does not mean-"no UI surface"; the UI surface is the product behavior the change alters, not the-files it edits.+**Why it's wrong**: the capability may already exist somewhere the runtime actually+reads (a different config store than the one you checked). Two unmeasured assumptions+stack: that no capability existed, and that you knew where it comes from.-**What it breaks**: the report cannot show what a real blocked user experiences-(is the rejection surfaced comprehensibly? silently swallowed? a raw error?), and-it misses UX follow-ups the screenshot would expose (e.g. affordances that should-be hidden/disabled for users who will always be rejected).+**What it breaks**: a chunk of the run spent building an apparatus the test didn't+need, plus a fixture to tear down. Worse, had the mock _partially_ worked, the run+would have silently verified a fake path.-**Correct approach**: for any authorization/permission change, drive the REAL UI-as the blocked role and screenshot the rejection state (and the allowed role's-success state) in addition to API probes. If the rejection renders as a raw or-missing error message, report that as a finding instead of leaving it undiscovered.+**Correct approach**: before constructing any mock, **probe the env for the real+capability** โ query the config the runtime reads, or fire one cheap real call and see+whether it completes. Only mock what is provably absent. And when a mock records+nothing while the feature clearly works, that is the signal the mock is _not in the+path_ โ everything "verified" through it is unverified.----## Case 21 โ Turning a feature verification into an unbounded dev-environment repair+## M20 โ Bare invocation: narrating skill setup, then asking an open "what should I test?"-**Wrong approach**: after the normal product surface fails to boot, repeatedly modify-shared dev configuration, reinstall the entire workspace, and investigate unrelated-dependency/context problems before running any assertion for the feature under test.+**Wrong approach**: invoked with no test target, the agent announces "I'm loading the+mandatory living logs first", reads both logs in full, then asks an open "what should I+verify?" that ignores the visible candidate (the current branch and its commits).-**Why it's wrong**: environment readiness is a gate, not the test goal. A workaround-that changes shared configuration can also make the verification less representative,-while an open-ended repair loop produces no feature evidence.+**Why it's wrong**: the living logs inform execution, not target selection โ reading+them before a target exists burns context that may be compacted away before the run.+Narrating internal setup is compliance-reporting the user never asked for. And an open+question pushes work onto the user that observable context could have pre-filled.-**What it breaks**: the user waits through a long sequence of setup experiments, the-working tree gains unrelated edits, and the run still has no reportable test result.+**What it breaks**: two user-visible turns whose combined value is one clarifying+question, asked twice.-**Correct approach**: follow only recovery paths already documented by this skill. If the-observed failure mode is not covered, stop the test immediately, revert any experimental-changes, summarize the exact checks and evidence collected, and ask the user for help before-continuing. Do not repair the environment, switch surfaces, or invent a fallback without user-direction.+**Correct approach**: ground the target first (SKILL.md Step 0): the user's words > an+inferred candidate from branch/commits/working tree, confirmed via one structured+question and labeled as a guess (never executed on unconfirmed) > an open question only+as last resort. Read the living logs once the target is known, and never narrate+skill-internal setup.----## Case 22 โ Bare invocation: narrating skill setup, then asking an open "what should I test?"+## M21 โ A status badge is not proof the error message rendered-**Wrong approach**: invoked with no test target, the agent sent "I'm using the-agent-testing skill; I'll load its mandatory living logs first", read both-living logs in full (\~1.9k lines), then sent a second message โ "Agent-testing-is loaded, including both mandatory living logs. What feature, change, PR, or-user flow should I verify?" โ an open question that ignored the visible-candidate (the current feature branch and its recent commits).+**Wrong approach**: marking an error-state UI case passed because the page showed a+`Failed` badge, while the screenshot did not actually contain the error alert or its+translated message.-**Why it's wrong**: the living logs inform execution, not target selection โ-reading them before a target exists burns context that may be compacted away-before the run starts. Narrating internal setup ("mandatory living logs") is-compliance-reporting the user never asked for. And an open question pushes work-onto the user that observable context could have pre-filled as a candidate.+**Why it's wrong**: the badge proves only that a failed state reached the page. It does+not prove the error was translated and presented to the user, which is the core+assertion of an error-message verification.-**What it breaks**: two user-visible turns whose combined value is one-clarifying question, asked twice; the user must type the target from scratch.+**What it breaks**: a report claims users receive an actionable explanation while its+evidence shows none.-**Correct approach**: ground the target first (SKILL.md Step 0): the user's-words in the conversation > an inferred candidate from branch/commits/working-tree, confirmed via one structured question and labeled as a guess (never-executed on unconfirmed โ Case 3) > an open question only as last resort. Read-the living logs once the target is known, and never narrate skill-internal-setup โ the first visible message is about the user's test.+**Correct approach**: for an error-presentation case, visually require all the signals+in the same screenshot: the failed status AND the error alert containing the expected+user-facing message. An unrelated warning or setup reminder does not satisfy the+assertion.----## Case 23 โ Building an elaborate mock before checking whether the env already has the real thing+## M22 โ Coordinator hand-driving a broken flow instead of re-delegating-**Wrong approach**: needing a working LLM for an agent-runtime test and finding no provider key in-the shell env, I built an OpenAI-compatible mock server, wrote a key-vault encryption script, and-seeded `user_settings.key_vaults` to point `deepseek` at it โ then ran the agent and watched the-mock receive **zero** requests while the run produced real, rich LLM output.+**Wrong approach**: after a delegated verification subagent dies mid-case, the+coordinator takes over and drives the remaining flow inline โ dozens of small steps+plus a deep root-cause dig into a flapping shared dependency, all in the main loop.-**Why it's wrong**: the seeded test user _already had a real DeepSeek key_ configured โ in-`ai_providers`, which is what the runtime actually reads (not `user_settings.keyVaults`). Two-wasted assumptions stacked: that no credential existed, and that I knew which table supplies it.-Neither was measured; both were inferred from an `env | grep`.+**Why it's wrong**: the coordinator's per-step latency and context cost are far higher+than a subagent's, and inline grinding turns one recoverable failure into a long+visible stall. Root-causing an env flake is also not the test's goal.-**What it breaks**: a chunk of the run spent building an apparatus the test didn't need, plus a-fixture (mock server + an encrypted row) that had to be torn down afterwards. Worse, had the mock-_partially_ worked, the run would have silently verified a fake path.+**What it breaks**: the user watches minutes of micro-steps with no case progress;+total wall-clock and token spend balloon for zero extra evidence value.-**Correct approach**: before constructing any mock, **probe the env for the real capability** โ-query the provider tables (`select id, key_vaults is not null from ai_providers where user_id=โฆ`),-or just fire one cheap real turn and see whether it completes. Only mock what is provably absent.-And when a mock records nothing while the feature clearly works, do not shrug โ that is the signal-that the mock is _not in the path_, and everything you "verified" through it is unverified.+**Correct approach**: when a delegated case dies, repackage the _remaining_ steps into+a fresh, tightly-scoped subagent prompt (include everything already learned: working+recipes, seeded fixtures, exact remaining assertions). Timebox any environment rabbit+hole to a couple of probes, then switch to a disposable local substitute instead of+diagnosing shared infrastructure.----## Case 24 โ Asserting a fixture landed because the DB write succeeded--**Wrong approach**: writing `agents.agency_config = NULL` directly in Postgres, reloading the page,-and reading the "sub-agent model" the UI displayed โ then treating the stale value it showed as a-product bug in the fallback logic.--**Why it's wrong**: the client's persisted SWR cache (IndexedDB + localStorage) kept serving the old-`agencyConfig`, and even `internal_refreshAgentConfig` did not dislodge it. `UPDATE 1` in psql proves-the row changed; it proves nothing about what the app _is running on_. A fixture bug in-product-bug costume is the most expensive kind โ I nearly filed my own fixture as a regression.+## M23 โ Stopping after a fix without publishing the next verification round-**Correct approach**: after any direct-DB fixture write, cold-load (clear localStorage /-sessionStorage / IndexedDB / caches, re-seed auth, reopen) and then **assert the fixture in the store-before asserting anything downstream of it** (`__LOBE_STORES.agent().agentMap[id]`). See-probe-mock-patterns C11. Rule of thumb: the DB is where you _wrote_ it; the store is where the-behavior _reads_ it โ verify at the layer the behavior reads.-----+**Wrong approach**: implementing and locally validating a requested iteration, then+ending the task without committing, pushing, or publishing a fresh immutable verify run+to the existing acceptance.-## Case 26 โ Applying dual scope to only one action in a bulk-maintenance menu+**Why it's wrong**: an acceptance is the cross-round audit trail. A local-only fix+leaves the PR stale and makes the acceptance claim the previous round is still the+latest result. Local tests are preparation, not delivery.-**Wrong approach**: after introducing own-scope and workspace-scope variants for one-bulk action, leave sibling maintenance actions owner-own-only because the review focused-on restricting what regular members can do.+**What it breaks**: reviewers can't inspect the updated code, the acceptance timeline+misses the iteration, and the user has to ask whether anything shipped.-**Why it's wrong**: the capability matrix was evaluated per menu entry instead of across-role ร action ร scope. An owner can retain safe personal actions while also receiving-explicit workspace-wide variants for every applicable maintenance action.+**Correct approach**: after every requested iteration, complete the whole delivery loop+unless told not to: validate the new state, commit and push the branch, create a fresh+report directory, ingest exactly once as the next immutable run on the same subject+acceptance, verify the new round appears, then return both the commit and the+production link.-**What it breaks**: owners must manually process other members' records for the omitted-actions, and the menu presents an inconsistent authority model where only one bulk action-can operate at workspace scope.--**Correct approach**: enumerate the full role ร bulk-action matrix before implementation-and verification. Give members own-only actions; give owners both own and workspace-variants for every applicable action; use elevated confirmation for destructive-workspace-wide variants; and assert every matrix cell in UI tests and screenshots.+----## Case 27 โ Labeling two steps of a flow as a before/after `comparison` pair+## M24 โ Labeling sequential flow steps as a before/after comparison-**Wrong approach**: for a case whose evidence is two SEQUENTIAL steps of one flow (the reject-dialog being filled in, then the feedback card rendered after submitting), attaching them as a-`comparison` pair with `role: before` / `role: after`.+**Wrong approach**: attaching two sequential steps of one flow as a `comparison`+pair with `before` and `after` roles.-**Why it's wrong**: the comparison rendering's semantics are "the SAME view in two states" โ the-red band reads as "defective old state", the green band as "the fix". Flow steps are neither: the-first shot is not a defect and the second is not a remediation. The user immediately asked " ่ฟ็งๆๆ-ๆฏๆญฅ้ชค๏ผไธบไปไนๆฏไผๅๅๅไผๅๅ๏ผ".+**Why it is wrong**: comparison rendering means the same surface before and after+a change. Sequential steps are neither a defect nor its remediation.-**What it breaks**: the report claims an optimization happened where none did; the red/green framing-misleads reviewers about what they are looking at.+**Correct approach**: reserve `comparison` for one view in two states. Attach+flow steps as ordinary ordered evidence with a caption naming each step.-**Correct approach**: `comparison` is ONLY for the same surface before vs after a change. For flow-steps, attach plain ordered evidence items (the array preserves order) and give each a caption-naming its step ("step 1 โ dialog with region circled", "step 2 โ feedback card after submit").+----## Case 28 โ Publishing the report to the LOCAL instance because the subject "only exists locally"+## M25 โ Publishing locally because the acceptance subject exists only locally-**Wrong approach**: the run's subject (the task under test) lived only in the local dev DB, so I-ingested the report into the local instance (`--subject task:<local id>` against `localhost`) and-delivered `localhost` URLs as the final links โ reasoning that a production subject didn't exist and-that attaching to the actual local task was "semantically perfect".+**Wrong approach**: ingesting the primary report into a local instance because+its task or topic is absent from production.-**Why it's wrong**: the user immediately asked why the report wasn't on production. The publish-target rule (SKILL Step 6) is not conditional on subject convenience: the deliverable must live on-`app.lobehub.com`, where links survive teardown and are shareable. A missing production subject is a-solvable prerequisite, not a reason to downgrade the publish target โ the CLI can create one in-seconds (`lh task create -n "<verification anchor>" -i "..."` โ `--subject task:T-<seq>`). A local-ingest is fine as an _additional_ demo of the acceptance chaining, but never as the primary-deliverable.+**Why it is wrong**: localhost links disappear with the environment and cannot+serve as shared deliverables. Subject convenience does not change the production+publication requirement.-**Correct approach**: when no production subject exists, create a production anchor entity first-(task via `lh task create`, or a topic), then run the clean-env production publish-(`env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME` + the branch's-own CLI for the canary `--subject` contract). Gotcha hit on the way: bare `--json` on `task create`-crashes (`fields.split is not a function`) โ omit it or pass explicit fields.+**Correct approach**: create a production task or topic as the acceptance anchor,+then publish in a clean environment against `app.lobehub.com`. A local ingest may+supplement the run, but never replace the production deliverable.----## Case 29 โ Publishing an acceptance without its `requirement` (้ชๆถ็ฎๆ ), assuming it is auto-generated--**Wrong approach**: authoring `result.json` with the bare-string subject form-(`"subject": "topic:<id>"`) and no `--requirement`, assuming the system derives the acceptance-goal on its own.+## M26 โ Creating an acceptance without its requirement-**Why it's wrong**: `acceptances.requirement` is author-supplied only โ the CLI passes it to-`acceptance.ensure` solely from the subject OBJECT form (`{ type, id, requirement }`) or the-`--requirement` flag. Nothing generates it. Worse, it is set at aggregate creation: a first-ingest that omits it leaves the decision page reading "ๅฐๆช่ฎฐๅฝ่ฏฅๅฏน่ฑก็้ชๆถ็ฎๆ " (a model-side-backfill for the empty case ships later; a recorded value stays immutable either way).+**Wrong approach**: using a bare subject string on the first ingest and assuming+the acceptance goal is inferred automatically.-**What it breaks**: the decision page's headline card โ the one thing the whole acceptance is-judged against โ renders a placeholder, and the user has to ask why.+**Why it is wrong**: the requirement is author-supplied. Omitting it leaves the+decision page without the business goal against which all rounds are judged.-**Correct approach**: every FIRST ingest for a subject uses the object subject form with a-one-sentence business goal: `"subject": { "type": "topic", "id": "<id>", "requirement": "<่ฏฅไธปไฝ-ๆดไฝ่ฆ่พพๆไปไน>" }`. Phrase it as the cross-round goal, not the current round's scope.+**Correct approach**: supply `--requirement` or the object subject form on the+first ingest. State the cross-round business goal, not the current round's scope.diff --git a/.agents/skills/agent-testing/references/osascript.md b/.agents/skills/agent-testing/references/osascript.mdindex 3aaecf39d2b..9d80a426f16 100644--- a/.agents/skills/agent-testing/references/osascript.md+++ b/.agents/skills/agent-testing/references/osascript.md@@ -1,13 +1,20 @@# osascript Common Patterns-Shared AppleScript / `osascript` patterns used by all platform bot tests. Read this first, then refer to the per-platform file for app-specific quirks.+General macOS automation via AppleScript / `osascript` โ activating apps, typing,+pasting, keyboard shortcuts, clicking, screenshots, and accessibility reads. This is+a general macOS-automation asset, not tied to any one app or surface. Use it when a+test needs to drive a native macOS app that is not reachable over CDP.++macOS only. See also [record-app-screen.md](./record-app-screen.md) for capture and+the screen-recording preflight (`scripts/check-screen-recording.sh`) before any+OS-level capture.## Core Patterns### Activate an App```bash-osascript -e 'tell application "Discord" to activate'+osascript -e 'tell application "AppName" to activate'```### Type Text@@ -46,23 +53,15 @@ tell application "System Events" to keystroke "v" using command down### Keyboard Shortcuts```bash-# Cmd+K (quick switcher in Discord/Slack)-osascript -e 'tell application "System Events" to keystroke "k" using command down'--# Cmd+F (search)-osascript -e 'tell application "System Events" to keystroke "f" using command down'--# Cmd+N (new message/chat)-osascript -e 'tell application "System Events" to keystroke "n" using command down'--# Cmd+Shift+K (example: multi-modifier)-osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}'+osascript -e 'tell application "System Events" to keystroke "k" using command down' # Cmd+K+osascript -e 'tell application "System Events" to keystroke "f" using command down' # Cmd+F+osascript -e 'tell application "System Events" to keystroke "n" using command down' # Cmd+N+osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}' # multi-modifier```### Click at Position```bash-# Click at absolute screen coordinatesosascript -e 'tell application "System Events"click at {500, 300}@@ -73,10 +72,9 @@ end tell### Get Window Info```bash-# Get window position and sizeosascript -e 'tell application "System Events"- tell process "Discord"+ tell process "AppName"get {position, size} of window 1end tellend tell@@ -86,22 +84,17 @@ end tell### Screenshot```bash-# Full screen-screencapture /tmp/screenshot.png--# Interactive region select-screencapture -i /tmp/screenshot.png--# Specific window (by window ID from CGWindowList)-screencapture -l < WINDOW_ID > /tmp/screenshot.png+screencapture /tmp/screenshot.png # Full screen+screencapture -i /tmp/screenshot.png # Interactive region select+screencapture -l "$WINDOW_ID" /tmp/shot.png # Specific window (id from CGWindowList)```-To get window ID for a specific app:+To get the window id for a specific app:```bashosascript -e 'tell application "System Events"- tell process "Discord"+ tell process "AppName"get id of window 1end tellend tell@@ -114,7 +107,7 @@ end tell# Get all UI elements of the frontmost window (can be slow/large)osascript -e 'tell application "System Events"- tell process "Discord"+ tell process "AppName"entire contents of window 1end tellend tell@@ -123,21 +116,19 @@ end tell# Get a specific element's valueosascript -e 'tell application "System Events"- tell process "Discord"+ tell process "AppName"get value of text field 1 of window 1end tellend tell'```-> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer screenshots + `Read` tool for visual verification.+> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer+> screenshots + the `Read` tool for visual verification.### Read Screen Text via Clipboard-For reading the latest message or response from an app:-```bash-# Select all text in the focused area and copyosascript -e 'tell application "System Events"keystroke "a" using command down@@ -145,35 +136,30 @@ tell application "System Events"end tell'sleep 0.5-# Read clipboardpbpaste```------## Common Bot Testing Workflow--Regardless of platform, the pattern is:+## General App-Automation Workflow```bash-APP_NAME="Discord" # or "Slack", "Telegram", "ๅพฎไฟก"-CHANNEL="bot-testing"-MESSAGE="Hello bot!"+APP_NAME="AppName"+TARGET="some-target"+MESSAGE="Hello!"WAIT_SECONDS=10# 1. Activateosascript -e "tell application \"$APP_NAME\" to activate"sleep 1-# 2. Navigate to channel/chat (via Quick Switcher or Search)+# 2. Navigate (via the app's own quick switcher / search shortcut)osascript -e 'tell application "System Events" to keystroke "k" using command down'sleep 0.5-osascript -e "tell application \"System Events\" to keystroke \"$CHANNEL\""+osascript -e "tell application \"System Events\" to keystroke \"$TARGET\""sleep 1osascript -e 'tell application "System Events" to key code 36'sleep 2-# 3. Send message+# 3. Input (clipboard paste for long/non-ASCII text)osascript -e "set the clipboard to \"$MESSAGE\""osascript -e 'tell application "System Events"@@ -183,35 +169,34 @@ tell application "System Events"end tell'-# 4. Wait for bot response+# 4. Wait for the app to reactsleep "$WAIT_SECONDS"# 5. Screenshot for verification-screencapture /tmp/"${APP_NAME,,}"-bot-test.png-echo "Result saved to /tmp/${APP_NAME,,}-bot-test.png"+screencapture /tmp/app-test.png```### Tips-- **Use clipboard paste** (`Cmd+V`) for messages containing special characters or long text โ `keystroke` can mangle non-ASCII-- **Add `delay`** between actions โ apps need time to process UI events-- **Screenshot for verification** โ use `screencapture` + `Read` tool for visual checks-- **Use a dedicated test channel/chat** โ avoid polluting real conversations-- **Check app name** โ some apps have different names in different locales (e.g., `ๅพฎไฟก` vs `WeChat`)-- **Accessibility permissions required** โ System Events automation requires granting Accessibility access in System Preferences > Privacy & Security > Accessibility-----+- **Use clipboard paste** (`Cmd+V`) for messages with special characters or long+ text โ `keystroke` can mangle non-ASCII.+- **Add `delay`** between actions โ apps need time to process UI events.+- **Screenshot for verification** โ `screencapture` + the `Read` tool.+- **Accessibility permission required** โ System Events automation requires+ Accessibility access for the driving app (Terminal / iTerm / the agent host) in+ System Settings > Privacy & Security > Accessibility.## Gotchas-- **Accessibility permission required** โ first run will prompt for access; grant it in System Preferences > Privacy & Security > Accessibility for Terminal / iTerm / Claude Code-- **`keystroke` is slow for long text** โ always use clipboard paste (`Cmd+V`) for messages over \~20 characters-- **`keystroke` can mangle non-ASCII** โ use clipboard paste for Chinese, emoji, or special characters-- **`key code 36` is Enter** โ this is the hardware key code, works regardless of keyboard layout-- **`entire contents` is extremely slow** โ avoid for complex UIs; use screenshots instead-- **App name varies by locale** โ `ๅพฎไฟก` vs `WeChat`, `ไผไธๅพฎไฟก` vs `WeCom`; handle both-- **WeChat Enter sends immediately** โ use `Shift+Enter` for newlines within a message-- **Rate limiting** โ don't send messages too fast; platforms may throttle or flag automated input-- **Lark / ้ฃไนฆ app name varies** โ `Lark` (international) vs `้ฃไนฆ` (China mainland); scripts auto-detect-- **QQ uses `Cmd+F` for search** โ not `Cmd+K` like Discord/Slack/Lark-- **Bot response times vary** โ AI-powered bots may take 10-60s; use generous sleep values+- **Accessibility permission required** โ first run prompts for access; grant it in+ System Settings > Privacy & Security > Accessibility.+- **`keystroke` is slow for long text** โ use clipboard paste (`Cmd+V`) for anything+ over \~20 characters.+- **`keystroke` can mangle non-ASCII** โ use clipboard paste for CJK, emoji, or+ special characters.+- **`key code 36` is Enter** โ hardware key code, works regardless of keyboard+ layout.+- **`entire contents` is extremely slow** โ avoid for complex UIs; use screenshots.+- **OS screenshots go BLACK when the display is asleep/locked/screensaver** โ gate+ with `scripts/check-screen-recording.sh` and keep the display awake with+ `caffeinate -dimsu &` for the whole capture run.diff --git a/.agents/skills/agent-testing/references/plan.md b/.agents/skills/agent-testing/references/plan.mdindex 7249482a963..5e268238bf4 100644--- a/.agents/skills/agent-testing/references/plan.md+++ b/.agents/skills/agent-testing/references/plan.md@@ -6,28 +6,29 @@ Keep it concrete and compact: report observed state, not generic readiness claim## Readiness verdicts- **โ Ready**: every prerequisite for the proposed run is verified.-- **โ ๏ธ Ready with warnings**: execution can proceed; list non-blocking limitations and- their effect on evidence or scope.-- **โ Blocked**: execution cannot start until one or more prerequisites are resolved.-- **โณ Pending**: an agent-owned check is actively being resolved and has not reached a- final readiness verdict yet.+- **โ ๏ธ Ready with warnings**: execution can proceed; list non-blocking limitations+ and their effect on evidence or scope.+- **โ Blocked**: execution cannot start until one or more prerequisites are+ resolved.+- **โณ Pending**: an agent-owned check is actively being resolved and has not+ reached a final readiness verdict yet.Always prefix the overall verdict and every Status cell with its emoji marker:`โ Ready`, `โ ๏ธ Warning`, `โ Blocked`, or `โณ Pending`. Do not use color words orbare status text without the marker; the table must remain scannable in clientsthat do not render semantic colors.-Fix safe environment mechanics yourself before reporting. Separate remaining-items by owner:+Fix safe environment mechanics yourself before reporting. Separate remaining items+by owner:-- **Codex-owned**: dependencies, processes, ports, generated local env, seeded+- **Agent-owned**: dependencies, processes, ports, generated local env, seededfixtures, navigation, retries, and other work possible within the task's scope.- **User-owned**: secrets the user must supply, device/2FA approval, permissionsonly the user can grant, destructive authorization, or an unresolved productchoice that materially changes the plan.-Never put a Codex-owned item under โNeeded from you.โ If none remain, write-`None` explicitly.+Never put an agent-owned item under "Needed from you." If none remain, write `None`+explicitly.## Template@@ -41,7 +42,7 @@ Environment| Workspace / branch | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <path, branch/worktree, relevant dirty-state note> || Dependencies | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <root and selected standalone app status> || Runtime / ports | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <resolved URLs/ports and ownership or availability> |-| Required services | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <DB, Redis, QStash, dev serverโonly those in scope> |+| Required services | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <DB, cache, queue, dev serverโonly those in scope> || Auth | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <selected surface and verified signed-in state> || Evidence capture | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <CDP or OS capture readiness> |@@ -60,34 +61,29 @@ Scope and assumptionsNeeded before execution-- Codex will resolve: <remaining non-blocking or in-progress agent-owned work, or None>+- Agent will resolve: <remaining non-blocking or in-progress agent-owned work, or None>- Needed from you: <exact user-owned prerequisite and why it is required, or None>```-Do not include irrelevant environment rows. Add a row when the run has another-hard prerequisite, such as a native bot app, gateway, fixture repository, or-specific external account.--When a check refines or replaces a requirement from an earlier Acceptance round, keep the-old stable id if it is the same assertion. If the semantic assertion needs a new id, declare-the replacement explicitly with `supersedes: ['old-check-id']`; title similarity is never a-merge signal. For every user-visible UI case, plan a dedicated screenshot or recording for-that exact claimโprogram output may supplement it but cannot replace visual evidence.--On a follow-up round, seed the plan from `lh verify acceptance view <subject> --json`-before writing any case (see SKILL.md "Before the next round"). Per-check policy:--- `userReview.action == "accept"` โ user-settled. OMIT it from the new plan- entirely: no re-run, no restating. The union carries it forward untouched;- a settled check is not yours to touch again.-- `userReview.action == "reject"` with `stale: false` โ the round's primary work- items. Quote the user's `comment` / `annotations[].comment` in the plan case's- expected outcome so the fix is verified against the actual feedback, and reuse- the EXACT stable id so the re-run lands on the same union row (same `C#`).-- everything else โ plan by the check's own `state` (failed / uncertain first),- again reusing stable ids; only a semantic change warrants a new id, and then- ONLY with `supersedes: ['old-id']` โ a fresh id without it renders as a new- parallel row, not an iteration.+Do not include irrelevant environment rows. Add a row when the run has another hard+prerequisite, such as a native app, gateway, fixture repository, or specific+external account.++When a check refines or replaces a requirement from an earlier Acceptance round,+keep the old stable id if it is the same assertion. If the semantic assertion needs+a new id, declare the replacement explicitly with `supersedes: ['old-check-id']`;+title similarity is never a merge signal. For every user-visible UI case, plan a+dedicated screenshot or recording for that exact claim โ program output may+supplement it but cannot replace visual evidence.++On a follow-up round, seed the plan from+`lh verify acceptance view <subject> --json` before writing any case:++- Accepted checks are user-settled; omit them from the new plan.+- Rejected, non-stale checks are the primary repair items. Carry their comments+ and annotations into the expected outcome, and reuse their exact stable ids.+- Plan all remaining checks from their current state, again reusing stable ids.+ A semantic replacement requires a new id plus `supersedes: ['old-id']`.## Confirmation behaviordiff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex 8a0c85b362a..67c1d716348 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -1,59 +1,31 @@-# Probe / Mock Pattern Library+# Probe / Mock Pattern Library (generic layer)-> **Purpose**: the accumulated, verified recipes for probing app/runtime state-> and mocking / faulting network in agent-testing. Every time a probe or a mock-> is **blocked, bypassed, or needs a workaround** during a run, add an item here-> recording what does NOT work and what DOES.-> **Read this before any run that needs to force an error state or inspect-> runtime state.** Each item: Situation / Doesn't work / Works.+> **This is the GENERIC layer of the living log.** It is read-only in a consumer+> repo and updated only by PR to the CLI repo that ships this skill. Every recipe+> here must be **product-independent** โ framework-level or tool-level, no project's+> stores, routes, tables, env vars, or file paths. Project-specific probes and mocks+> go to `.agents/verify/probe-mock-patterns.md` (the writable project layer).>-> **Separate the observation from the explanation.** A full audit of this file (source read +-> live re-run against `agent-browser 0.26.0` and the dev server) found that several items'-> observations were real but their stated mechanism was invented after the fact โ a symbol-> that never existed (`getRetryScopeId`), an error code the code rejects (`interrupted`), a-> `PATH` clobber the script cannot perform. Two "doesn't work" items (A1, A2) turned out to-> work fine; the original runs had measured the wrong signal. A wrong mechanism is worse than-> none: it sends the next reader to fix the wrong thing. When you add an item, cite-> `file:line` for any mechanism claim, and if you only saw a symptom, write-> "cause not established" instead of guessing.+> **Read this before any run that must force an error state or inspect runtime+> state.** Each item: Situation / Doesn't work / Works.+>+> **Separate the observation from the explanation.** When you add an item, cite the+> exact mechanism (a `file:line`, a measured A/B) โ and if you only saw a symptom,+> write "cause not established" instead of guessing. A wrong mechanism is worse than+> none: it sends the next reader to fix the wrong thing.---## A. Forcing a fetch to FAIL (error-state testing)-### A1. โ `network route --abort` DOES intercept this app's TRPC โ the old note measured the wrong thing--Re-tested end-to-end against the running dev server. The previous claim ("blocks nothing โ-815 requests still returned 200") was wrong three times over:--- **The glob never matched.** `**/trpc/**` matches nothing. Only an absolute-URL prefix with- a trailing `*` matched reliably; `**/x`, `**/*` and `*/trpc/*` all failed on a nested path.- Use `route "<origin><path-prefix>*" --abort` โ the trailing `*` is required to cover TRPC's- `?input=โฆ` query string.-- **The app swallows the failure, so a working abort still "looks like" a 200.** With- `route "http://localhost:<port>/trpc/lambda/user.getUserState*" --abort` installed, the- fetch really is killed โ yet the store action still resolves:- ```text- with route: fetchOutcomes ["REJECTED_Failed to fetch"] storeActionOk 1 storeActionErr null- no route: fetchOutcomes ["resolved_200","resolved_200"] storeActionOk 1- ```- Never judge interception by the action's promise or by the UI. Wrap `window.fetch` and- record each request's own outcome (snippet in A2).-- **`network requests` under-reports.** In a window where the page-realm wrapper counted- thousands of fetches (one of them TRPC), `agent-browser network requests` listed **1 request- and 0 TRPC**. It is not ground truth for "did the request happen".+### A1. Judge interception by the fetch's own outcome, not by the UI or the promise-### A2. โ A post-load `window.fetch` override DOES see this app's TRPC--- The old note claimed the TRPC client "captures the `fetch` reference at client-creation".- It does not: `packages/trpc/src/client/lambda.ts:104-108` passes a wrapper that calls the- **ambient** `fetch` per request (consumed by `httpBatchLink`/`httpLink`, lines 148-149), so- a later `window.fetch = โฆ` reassigns exactly the binding it resolves.-- Measured on the running app: install the override post-load, force a real call with- `window.__LOBE_STORES.user().refreshUserState()`, and the override sees the TRPC request.- `agent-browser eval` shares the page realm โ confirmed separately on a static page whose own- script calls ambient `fetch` (`REAL_FETCH_200` before the override, `THREW_OVERRIDDEN` after).-- **Use this shape**; it records the _fetch's_ outcome, the only trustworthy signal:+- Apps commonly **swallow** a failed fetch: a store action can resolve successfully+ even when its underlying request was aborted, so the UI and the action's promise+ both "look like" a 200. Never judge whether your fault landed by the action or the+ UI.+- **Works**: wrap `window.fetch` post-load and record each request's own resolve /+ reject. Use a guard so a second `eval` doesn't wrap the wrapper (stack overflow):```jsif (!window.__W) {window.__W = 1;@@ -61,7 +33,7 @@ Re-tested end-to-end against the running dev server. The previous claim ("blocksconst of = window.fetch;window.fetch = function (...a) {const p = of.apply(this, a);- if (String(a[0]).includes('/trpc/'))+ if (String(a[0]).includes('<url-fragment>'))p.then((r) => window.__R.push('resolved_' + r.status),(e) => window.__R.push('REJECTED_' + e.message),@@ -70,253 +42,81 @@ Re-tested end-to-end against the running dev server. The previous claim ("blocks};}```- The `__W` guard matters: re-running the snippet in a second `eval` wraps the wrapper and- the next call dies with `Maximum call stack size exceeded`.-- If you point `agent-browser` at the **Debug Proxy** URL instead of the local origin, the SPA- runs in an iframe and a top-frame override lands in a different realm. That โ not the client- โ is what a genuine bypass would look like.+- **`agent-browser network route --abort` glob matching is finicky.** A bare `**/x`+ or `*/path/*` can match nothing on a nested path; an absolute-URL prefix with a+ trailing `*` matches reliably (the trailing `*` also covers a `?query` string). And+ `agent-browser network requests` **under-reports** โ it is not ground truth for+ "did the request happen"; trust the `window.fetch` wrapper instead.-### A3. `set offline` shows Chrome's page, not the component error+### A2. `set offline` shows the browser's page, not the component error-- **Doesn't work for component errors**: `agent-browser set offline on` trips- Chrome's document-level offline interstitial ("Reconnect to Wi-Fi"), not the- app's `AsyncError`. Its "Reload" button also false-matches error-copy greps.- (Offline also breaks lazy route-chunk loading โ hard-nav fallback โ Chrome page.)-- **Re-confirmed** (`set offline on` + `reload`): `document.body.innerText` comes back as- `ๆ็ฉบๆ ผ้ฎๅณๅฏๅผๅงๆธธๆ โฆ ้ๆฐ่ฟๆฅๅฐ Wi-Fi ็ฝ็ป โฆ ERR_INTERNET_DISCONNECTED`. The dino-game- and Wi-Fi copy are exactly the kind of text a naive error-copy grep matches.+- `agent-browser set offline on` trips Chrome's document-level offline interstitial+ ("Reconnect to Wi-Fi"), not the app's own error component. Its copy (and the dino+ game) also false-matches naive error-copy greps, and offline breaks lazy+ route-chunk loading โ a hard-nav fallback to the browser page. Use it to break+ connectivity, not to assert an app-level error state.-### A4. โ WORKS โ client-service fetcher instrumentation via HMR+### A3. WORKS โ force an error by injecting a throw into the code path via HMR-- Add a throw at the top of the client service method the SWR fetcher calls,- then let Vite HMR apply it, screenshot, and `git checkout --` to revert:+- Add a throw at the top of the client method the data fetcher / mutation calls, let+ the dev server hot-apply it, capture, then revert:```ts- // src/services/task.ts (the method useFetchTaskList's fetcher calls)+ // <the service method the fetcher calls> โ [AGENT-TEST] REMOVElist = async (params) => {- // [AGENT-TEST] REMOVEif (true) throw Object.assign(new Error('injected'), { data: { httpStatus: 500 } });- return lambdaClient.task.list.query(params);- };- ```-- `data.httpStatus: 500` โ the error is retryable, so `AsyncError` shows the- Retry button AND the status-specific copy (`response.500`). Use a status the- UI treats as retryable if you want the Retry button visible.-- Revert with `git checkout -- <service files>`; grep `AGENT-TEST` to confirm no- residue.--### A5. โ ALTERNATIVES (valid, use if HMR isn't available)--- CDP `Network.setBlockedURLs` โ blocks at the network stack (below fetch, so it- DOES catch TRPC). Needs a raw CDP ws (see C2 for getting the endpoint).-- Server-side: temporarily make the one endpoint return 500.--### A6. โ WORKS โ WRITE-side (mutation) fault injection, same HMR technique--- To test the write-side save-state UI (`AutoSaveHint` failed tag + `saveToast`),- inject the throw into the client service **mutation** method, not a fetcher:- ```ts- // src/services/task.ts โ the method the store action calls (updateTask โ taskService.update)- update = async (id, data) => {- // [AGENT-TEST] REMOVE- if (true)- throw Object.assign(new Error('injected save failure'), { data: { httpStatus: 500 } });- return lambdaClient.task.update.mutate({ id, ...data });+ return realClient.list(params);};```- Then trigger a save in the UI (edit the title / change the model). `runMutation`- (`src/store/utils/runMutation.ts:82-88`) calls `setStatus('failed')` then `onError`; the task- detail action supplies `internal_setTaskSaveStatus`, so the state lands in- **`taskSaveStatusMap[id]`** (a per-task map, not a scalar `taskSaveStatus`) and `saveToast`- fires. Retryability comes from `normalizeAsyncError`, whose only non-retryable statuses are- **401 and 403** (`src/libs/swr/normalizeError.ts:26`) plus an explicit- `meta.shouldRetry === false`. So `httpStatus:500` โ retryable โ the toast shows a Retry- action; 401/403 suppress it.-- **Gotcha โ reverting the injection triggers a FULL page reload.** `git checkout --`- on a service file makes Vite do a full reload (not just HMR), so the SPA resets to- a blank Main Layout (Case 1 trap: a blank shell with only the `Debug ID` tag).- After reverting, **re-navigate** (`agent-browser open .../task/<id>`) and re-fetch- element refs before continuing the recovery test.--### A7. โ WORKS โ render a message-attached error card (hetero guide, AsyncError) by in-memory store dispatch--- To render an error state that lives on a **chat message** (e.g. the heterogeneous- `overloaded` guide card), no network fault or real agent run is- needed โ inject the error straight into the chat store, **in-memory, no DB write**:- ```js- // agent-browser --cdp <port> eval --stdin- var c = window.__LOBE_STORES.chat();- var id = 'tmp_probe';- // 1. create a temp assistant message (in the ACTIVE conversation)- c.internal_dispatchMessage({- id,- type: 'createMessage',- value: { role: 'assistant', content: 'partial work UNIQUE_MARKER', provider: 'claude-code' },- });- // 2. attach the error whose `body.code` drives the card- c.internal_dispatchMessage({- id,- type: 'updateMessage',- value: {- error: {- type: 'AgentRuntimeError',- message: 'Overloaded',- body: {- agentType: 'claude-code',- code: 'overloaded',- message: 'Overloaded',- },- },- },- });- ```- This renders the real component (real i18n) in the running app. Clean up with- `internal_dispatchMessage({ id, type: 'deleteMessage' })`.-- **`code` must be one of four values, or you get no guide card.**- `isHeterogeneousAgentStatusGuideError` (`src/features/Conversation/Error/heterogeneous.ts:13-31`)- requires `agentType` โ {`claude-code`, `codex`} **and** `code` โ {`auth_required`,- `cli_not_found`, `overloaded`, `rate_limit`}. Anything else falls through to the generic- error path. The switch- (`src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx:28-44`) maps AuthRequired โ- `AuthRequiredState`, RateLimit โ `RateLimitState`, Overloaded โ `OverloadedState`,- **default โ `CliInstallState`**. There is no `InterruptedState`, and `interrupted` is not a- `HeterogeneousAgentSessionErrorCode` at all (it is a `completionReason` / run-`status` value- elsewhere) โ an earlier version of this note used it as the example, and it would have- rendered nothing of the sort.-- **No persistence / no side effects**: `internal_dispatchMessage` is the optimistic- in-memory path (same as `optimisticCreateTmpMessage`). Nothing hits the DB, and a- reload clears it. Safe even against a **real** account's synced data โ do it in an- isolated `electron-dev.sh start <id>` instance (copied login) to be extra safe.-- **Suppress auto-actions on purpose**: the hetero auto-retry only arms when a retry scope- resolves. `src/features/Conversation/Error/index.tsx:260-262` computes- `retryScopeId ?? getDisplayMessageById(data.id)?.parentId`, and `useHeterogeneousAutoRetry`- gates on `!!scopeId`. A tmp message has no `parentId`, so the scope is `undefined` โ the card- renders in its **manual** state (retry button, no countdown) and **does not auto-fire**- (won't spawn a real CLI). (There is no `getRetryScopeId` helper โ an earlier version of this- note invented one. The mechanism is a plain `parentId` lookup, not an ancestor walk.) To- exercise the countdown live you'd need a real userโassistant chain; otherwise cover it with- the component RTL test.-- **Gotcha โ `messagesMap` landing is unreliable to assert; the render is the truth.**- `internal_dispatchMessage` (no explicit context) targets the active conversation and- the message may not show up where a naive `Object.keys(messagesMap)` scan looks, yet- it still renders. Verify by the DOM, not by the store map.-- **Gotcha โ `document.body.innerText` keyword match false-positives in long chats.**- The conversation's own text (and the right-hand diff/review panel) frequently contains- your assert strings (e.g. `่ฟๆฅไธญๆญ`, `้่ฏ`, `Retry`). Match on a **unique injected- marker** instead, `scrollIntoView` its node, then **open the screenshot with Read** to- confirm the card (Case 1 rule). Find + scroll to the node:- ```js- var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null),- n,- hit;- while ((n = w.nextNode())) {- if (n.nodeValue.indexOf('UNIQUE_MARKER') >= 0) {- hit = n;- break;- }- }- var el = hit.parentElement;- for (var i = 0; i < 6 && el.parentElement; i++) el = el.parentElement;- el.scrollIntoView({ block: 'center' });- ```--### A8. โ WORKS โ trigger a REAL failed load-more via store action when scroll/observer won't trip--- **Situation**: verifying an infinite-scroll `loadMoreError` inline retry row. The- `IntersectionObserver` won't fire because the seed data is a short list that fits- the viewport without scrolling (virtua renders no scrollable overflow), so- `scrollTop = scrollHeight` scrolls nothing and `loadMore` is never called.-- **Doesn't work**: scrolling any element to the bottom โ with only 2 rows there is- no scroll container (`scrollHeight <= clientHeight`), and virtua's sentinel never- intersects.-- **Works โ two parts**:- 1. **Force pagination with tiny seed data via HMR**: lower the component's page-size- const so a small dataset paginates. `AgentTopicManager` `PAGE_SIZE = 30` โ `2`,- then an agent with 3 topics loads page-1 = 2, `hasMore = true`.- 2. **Call the real store action directly** (bypasses the observer, but runs the real- fetch + real `catch`): `window.__LOBE_STORES.<store>` is a bound hook โ CALL it to- get live state + actions (`.getState`/`.setState` are NOT exposed, C1).- ```js- // agent-browser --session <s> eval- var c = window.__LOBE_STORES.chat();- await c.loadMoreAgentTopicsView(); // hits the injected getTopics(current>0) throw- // โ real catch sets agentTopicsViewMap[key].loadMoreError โ inline AsyncError row renders- ```- Pair the service injection (A4, throw only when `params.current > 0` so page-1 loads- and page-2 fails) with a **call counter** to prove the observer gate does NOT loop:- `(globalThis).__loadMoreCalls = (โฆ||0)+1` inside the throw; after the failure, wait a- few seconds and assert `window.__loadMoreCalls` stays `1` (no runaway re-trigger).-- **Caveat**: calling the action directly proves the render + the real error code path +- no-runaway, but NOT the observer's `!loadMoreError` gate under real scroll (the gate- lives in the component's IntersectionObserver callback). To exercise the gate live you- need a real scrollable list โ seed `> PAGE_SIZE` visible-source topics on one agent.-- **Gotcha โ the manager view filters by source (`ๆฅๆบ: ๅฏน่ฏ`) by default.** The store's default- filter is `triggers: ['chat']` (`src/features/AgentTopicManager/store.ts:49-51`; the code calls- it the **trigger** filter, the UI labels it ๆฅๆบ /source), so topics with a non-chat trigger- show `0` even though the agent owns them in the DB; click **ๆธ ็ฉบ็ญ้ / Clear filters** (or- `setStatus('all')` + clear) to reveal them.--### A9. โ WORKS โ before/after visual diffing by checking out the OLD file, but HMR is NOT trustworthy for it--- **Situation**: producing labeled beforeโafter evidence for a UI/style change (Case 5 requires a- real "before" render, not a code-derived guess). The clean way is to write the pre-change version- of the file into the working tree (`git show <base>:<path> > <path>`), capture, then restore.-- **Doesn't work โ silently**: assuming Vite HMR applied the swap. In this run the FIRST swap- hot-applied fine, and the SECOND one did not: the file on disk was the old version while the- renderer kept the new computed styles for 24s+ of polling. Screenshots taken then would have been- the AFTER state mislabeled as BEFORE โ a Case-5 failure that no screenshot review would catch,- because both look plausible.-- **Works โ gate every capture on a measured version signal, not on a sleep**: pick a property that- differs between the two versions and read it back with `getComputedStyle` before shooting.- ```bash- # after writing the old file, confirm the OLD css is actually live- agent-browser --cdp 9222 eval '(function(){var i=document.querySelector("<selector>");- var s=getComputedStyle(i);return JSON.stringify({pos:s.position,bg:s.backgroundColor})})()'- # expect the OLD values; if not, force a full reload and re-enter the surface- agent-browser --cdp 9222 eval 'location.reload(); 1'- ```- A full reload resets SPA state, so budget for re-navigating and re-establishing any fixture- (re-open the tab, re-drag a resizable panel, โฆ). Restore the new file the same way and re-measure- before the AFTER shots.-- **Corollary โ a layout change may be invisible at the default size.** A `flex: 1` right-alignment- fix renders identically to the broken version in a narrow container (the content already fills the- row); the difference only appears once there is slack. Drive the app's own resize affordance with- real mouse events before concluding "no visual change":- ```bash- # DraggablePanel handle: .ant-draggable-panel-left-handle (find via getComputedStyle cursor: col-resize)- agent-browser --cdp 9222 mouse move < handleX > 500- agent-browser --cdp 9222 mouse down left- for X in 1050 900 750 600 420; do- agent-browser --cdp 9222 mouse move $X 500- sleep 0.2- done- agent-browser --cdp 9222 mouse up left- ```- (zsh does not word-split unquoted vars โ inline the `--cdp` flags, don't stash them in `$AB`.)--### A10. โ ๏ธ `git checkout -- <file>` to revert an injection DESTROYS the branch's uncommitted changes in that file--- **Situation**: A4/A6/A8/E10 all end with "revert with `git checkout -- <file>`". That is only safe- when the file was **clean** before the injection. When you are verifying a branch that has- **uncommitted working-tree changes** (the common case for a pre-PR review), and your probe lands in- one of those same modified files, `git checkout --` resets it to **HEAD** โ silently wiping the very- feature edits you were sent to verify, not just your probe.-- **Measured**: injecting a one-line probe into a component that the branch had already modified- (uncommitted), then `git checkout -- <file>`, reverted the file to its committed version. The- branch's uncommitted edits (a changed selector + a title fallback) were gone, and the file no longer- matched what the user asked to test. Nothing warns you โ the probe residue check- (`grep -rn AGENT-TEST`) comes back clean either way, because your marker is gone too.+- Use a status the UI treats as **retryable** (commonly anything but 401/403) if you+ want the Retry affordance visible; a non-retryable status suppresses it. The same+ technique works on the **write side** โ inject into the mutation method to exercise+ a failed-save state.+- **Revert carefully.** `git checkout -- <file>` on a service file often triggers a+ FULL reload (not just HMR), resetting the SPA to a blank shell โ after reverting,+ re-navigate and re-fetch element refs. And see A5: `git checkout --` is the WRONG+ revert when the file already had uncommitted changes.++### A4. WORKS โ alternatives when HMR injection isn't available++- **CDP `Network.setBlockedURLs`** โ blocks at the network stack (below `fetch`, so+ it catches requests a page-realm `fetch` override might miss). Needs a raw CDP ws+ connection.+- **Server-side** โ temporarily make the one endpoint return 500.++### A5. `git checkout -- <file>` to revert an injection DESTROYS the branch's uncommitted changes in that file++- When you inject a probe into a file that the branch has **already modified+ (uncommitted)** โ the common case for a pre-PR review โ `git checkout -- <file>`+ resets it to HEAD, silently wiping the very feature edits you were sent to verify,+ not just your probe. Nothing warns you: the residue check (`grep -rn AGENT-TEST`)+ comes back clean either way, because your marker is gone too.- **Works โ snapshot the file yourself before injecting, restore from the snapshot:**```bashcp <file> /tmp/probe-backup-$(basename <file>) # BEFORE the edit# ... inject, HMR, capture ...cp /tmp/probe-backup-$(basename <file>) <file> # restore โ preserves uncommitted work```- Then prove the restore is exact: `git diff -- <file>` must show the SAME blob hash as before the- probe (`index <old>..<new>` โ the right-hand hash is the working-tree blob), and- `grep -rn AGENT-TEST` must be empty. Check `git status --short` before you start so you know which- files are dirty; for a dirty file, `git checkout --` is never the revert.-- **Corollary**: `git stash` has the same failure shape (it takes the branch's edits with it). If you- must use git to revert, scope it to a file you have confirmed is clean.+ Then prove the restore is exact (`git diff -- <file>` shows the same working-tree+ blob as before) and `grep -rn AGENT-TEST` is empty. Check `git status --short`+ before you start so you know which files are dirty; for a dirty file, `git checkout --` is never the revert. `git stash` has the same failure shape.++### A6. WORKS โ before/after visual diffing by checking out the OLD file, gated on a measured version signal++- The clean way to produce a real "before" render is to write the pre-change version+ into the working tree (`git show <base>:<path> > <path>`), capture, then restore โ+ **not** to trust that HMR applied the swap. HMR can silently fail to apply the+ second swap: the file on disk is old while the renderer keeps the new styles, and+ the screenshot is the AFTER state mislabeled BEFORE (an M5 failure no screenshot+ review catches).+- **Works โ gate every capture on a measured version signal, not a sleep.** Pick a+ property that differs between the two versions and read it back with+ `getComputedStyle` before shooting; if it's not the expected value, force a full+ reload and re-enter the surface. A full reload resets SPA state, so budget for+ re-establishing any fixture.+- **Corollary โ a layout change may be invisible at the default size.** A+ right-alignment / `flex` fix can render identically to the broken version in a+ narrow container (content already fills the row); drive the app's own resize+ affordance with real mouse events before concluding "no visual change".---@@ -324,23 +124,13 @@ Re-tested end-to-end against the running dev server. The previous claim ("blocks### B1. A failed revalidation cannot show an error once the data has settled-- **Situation**: a surface loaded successfully once caches the last-good value- (e.g. `[]`). On a later failed fetch, `AsyncBoundary` correctly keeps the- settled content and does NOT show the error (by design: background error must- not blow away loaded content). So your injected failure shows the old content,- not the error.-- **Where the behavior lives**: `AsyncBoundary` itself, not the persisted cache.- `src/components/AsyncBoundary/index.tsx:76,93` gate the error branch on- `if (error && !hasSettled)` where `hasSettled = data !== undefined`. The persisted cache's- only role is making `data` non-`undefined` on first mount.-- **This masking runs deeper than the boundary.** With the TRPC fetch aborted at the network- layer (A1), `refreshUserState()` still resolved successfully โ the rejection never surfaced- to the caller. Assume a failure you inject is invisible until you prove otherwise at the- fetch itself.+- A surface that loaded successfully once caches the last-good value. On a later+ failed fetch, a well-behaved error boundary keeps the settled content and does NOT+ show the error (by design: a background error must not blow away loaded content). So+ your injected failure shows the old content, not the error.- **Works**: to see a genuine FIRST-LOAD error, clear all client storage, then- cold-load. Clearing logs you out โ re-seed auth after.+ cold-load. Clearing usually logs you out โ re-seed auth after.```js- // agent-browser eval --stdin(async () => {try {localStorage.clear();@@ -365,1229 +155,218 @@ Re-tested end-to-end against the running dev server. The previous claim ("blocksreturn 1;})();```- then `setup-auth.sh web-seed`, then `open about:blank` โ `open <target>`.--### B2. SWR retries for \~30s before the error settles--- **Situation**: `useClientDataSWR` retries failed fetches with exponential backoff.- During retries `isLoading` is true โ you screenshot a skeleton, not the error.-- **Mechanism**: there is no `errorRetryCount` prop. `src/libs/swr/index.ts:31-45` supplies a- custom `onErrorRetry` that bails on `retryCount >= 5`, with- `delay = min(1000 * 2^retryCount, 30_000)`. SWR pre-increments the counter before calling the- handler (`swr/dist/index/index.mjs:493` โ `(opts.retryCount || 0) + 1`), so the handler sees- 1..5 and schedules **4 retries** at 2s + 4s + 8s + 16s = **\~30s** cumulative. (The old- "5ร / \~31s" reading assumed the counter starts at 0.)-- **Works**: wait \~35s after load for retries to exhaust, THEN screenshot. (Or- inject `meta.shouldRetry=false` to skip retries โ but that also hides the Retry- button, because `normalizeAsyncError` sets `retryable = false` for it.)--### B3. In-memory SWR cache survives `open`; persisted cache survives everything--- `open about:blank` then `open <target>` forces a fresh JS context (clears- in-memory SWR) but does NOT clear persisted storage โ you still need B1 for a- true cold load.-- **Verified**: a marker set only via `eval` reads back `undefined` after the round-trip while- `localStorage` survives. Set the marker from `eval`, never from the page's own script โ an- inline script re-runs on the second `open` and re-creates it, which reads as "the context- was preserved".-- The cache persists to **two durable tiers** (`src/libs/swr/localStorageProvider.ts`):- IndexedDB for the big collections and localStorage for small shells. That is why B1's- cold-load recipe clears localStorage, sessionStorage, IndexedDB **and** the Cache API.--### B4. Component-local `useState` seeded from a cached list item does NOT reset when fresh data arrives โ re-seeded fixtures render stale flags--- **Situation**: verifying an "unread โ click โ read" flag on a list row whose component- initializes local state from the item (`useState(Boolean(item.readAt))`). The fixture was- re-seeded in the DB with the flag cleared (`read_at` NULL, confirmed by SQL), yet on reload- one row rendered as already-read.-- **Cause (measured)**: the SWR persisted cache (B3's IndexedDB tier) hydrates the list first- with the PREVIOUS round's item (flag set, because an earlier run had clicked it). `useState`- captures that initial value; when the fresh server response (flag clear) replaces the SWR- data, the row does not remount (same React key = same item id), so the stale local state- sticks. No amount of waiting fixes it.-- **Works**: for any assertion on an initial-render flag that flows through `useState(init)`,- force a clean first frame by deleting only the SWR IndexedDB database (`lobehub-local-data`)- and reloading โ login survives (the session cookie is not touched), unlike B1's full clear.- Verify the DB value separately with SQL so a stale render is attributed to cache, not to the- change under test.+ then re-seed auth, then `open about:blank` โ `open <target>`.++### B2. SWR-style clients retry for \~30s before the error settles++- A data client with retry/backoff keeps `isLoading` true during retries, so you+ screenshot a skeleton, not the error. A typical config (5 attempts, exponential+ backoff capped at 30s) settles the error only after \~30s.+- **Works**: wait \~35s after load for retries to exhaust, THEN screenshot. (Or disable+ retries for the probe โ but that can also hide the Retry button, since many clients+ mark a non-retrying error as non-retryable.)++### B3. In-memory cache survives `open`; persisted cache survives everything++- `open about:blank` then `open <target>` forces a fresh JS context (clears in-memory+ cache) but does NOT clear persisted storage โ you still need B1 for a true cold+ load. Verify a marker set via `eval` (not from the page's own script, which re-runs+ on the second `open` and re-creates it, reading as "context preserved"). Persisted+ caches commonly live in **two tiers** โ IndexedDB for big collections and+ localStorage for small shells โ which is why B1 clears both plus the Cache API.++### B4. Component-local state seeded from a cached item does NOT reset when fresh data arrives++- A row component that initializes local state from its item (`useState(() =>+derive(item))`) captures the value at first render. When a persisted cache hydrates+ the list with a stale item first, `useState` captures the stale value; when the+ fresh server response replaces the data, the row does not remount (same React key),+ so the stale local state sticks. No amount of waiting fixes it.+- **Works**: for any assertion on an initial-render flag that flows through+ `useState(init)`, force a clean first frame by clearing only the persisted-cache+ tier and reloading (login usually survives if you don't touch the session cookie),+ and verify the underlying data separately so a stale render is attributed to cache,+ not to the change under test.----## C. Probing app / store runtime state+## C. Probing app / runtime state-### C0. A picker backed by a list store may need fixture hydration after direct-route entry+### C1. WORKS โ read live component state with a temporary debug global-- **Situation**: a modal reads candidate entities from a list store, while the test enters a- detail route directly. The detail route can render from its own entity/config store without- ever mounting the list fetcher, so the picker correctly renders an empty candidate list even- though fixture rows exist in the database.-- **Doesn't work**: inserting database rows alone, or refreshing the detail store. Neither- hydrates a separate list store that has not mounted its fetch hook.-- **Works**: first enter the canonical list/home surface and let its real fetch settle. If the- fixture deliberately bypasses normal creation and the list API still does not expose it,- use the existing C1b dev-only `setState` exposer to hydrate the list store with the exact- fixture shape, then exercise the real picker component and remove the exposer patch after- capture. Keep the report explicit that fixture hydration was test setup; validate the actual- mutation and created entity through the database or network boundary.--### C1. `window.__LOBE_STORES.<name>` has no `.getState` โ CALL it instead--- **Doesn't work**: `window.__LOBE_STORES.page.getState()`. The exposed value is neither the- store nor the hook: `src/store/middleware/expose.ts:11` assigns- `window.__LOBE_STORES[name] = () => store.getState()`, a plain arrow function with no- `.getState` property.-- **Works**: call it โ `window.__LOBE_STORES.page()` returns the state snapshot, actions- included. An earlier version of this note said "state isn't readable from it", which was- wrong and contradicted C1b.--### C1b. โ WORKS โ expose `setState` via HMR to drive a REAL identity/scope change (login repro)--- **Situation**: verifying behavior on an identity/cache-scope change (e.g. login,- `useCacheScope` = `${userId}:${workspaceId}`) on the ALREADY-LOADED app, without a- real OAuth flow. Cold-boot repro is timing-flaky under machine load; the faithful,- deterministic path is to flip `userId` on the live app.-- **Doesn't work**: `window.__LOBE_STORES.user()` returns `getState()` (actions but no- `setState`); there is no public `setUserId` action to call.-- **Works**: patch the dev-only exposer `src/store/middleware/expose.ts` (HMR) to also- attach `setState`, then drive the store from `eval`:- ```ts- // expose.ts, temporary โ REMOVE after: git checkout -- src/store/middleware/expose.ts- const handle = () => store.getState();- (handle as any).setState = (store as any).setState;- window.__LOBE_STORES[name] = handle as any;- ```- `expose()` only runs at store creation, so reload the renderer once after the edit so- stores re-expose with the handle. Then:- ```js- var u = window.__LOBE_STORES.user;- var c = u().user || {};- u.setState({ user: Object.assign({}, c, { id: 'probe_scope_0705' }) }); // โ scope flips- ```- In-memory only (no DB write); a reload restores the real id. Revert the file after.--### C2. โ WORKS โ temporary debug global inside the component--- The decisive way to read a component's live props / store / SWR values: add a+- The decisive way to read a component's live props / store / fetched values: add adebug global in the render, reload, read it, remove it.```tsx- // inside the component render, temporary:+ // inside the component render, temporary โ [AGENT-TEST] REMOVEif (typeof window !== 'undefined')- (window as any).__DBG = {- data: data === undefined ? 'undefined' : `array[${(data as any).length}]`,- hasError: !!error,- isLoading,- };+ (window as any).__DBG = { data: /* ... */, hasError: !!error, isLoading };``````bashagent-browser --session $S eval 'JSON.stringify(window.__DBG)'```- This is exactly what surfaced the Pages `documents=[]` bug (data looked settled- even on error).--### C3. Console capture works โ an empty `agent-browser console` means something else--- The old note said console capture "returned nothing this run" and told you to avoid it.- Re-tested on 0.26.0: `agent-browser console` returned both a page-script `[log]` line and one- emitted later from `eval`. It works.-- `app-probe.sh errors` is a different story: like `app-probe.sh auth`, it talks to the- **Electron CDP endpoint on 9222**, not to your `agent-browser` browser session. Against a web- session it fails with `All CDP discovery methods failed for 127.0.0.1:9222` โ which is not- "console capture is unreliable", it is "you pointed the probe at Electron".-- The debug-global (C2) is still the better tool for reading component state; use console for- what console is for.--### C4. `document.body.innerText` keyword grep false-positives on fixture text--- **Situation**: asserting a state like "ไฟๅญๅคฑ่ดฅ" / "Save failed" via- `body.innerText.includes('ไฟๅญๅคฑ่ดฅ')`. If the test fixture's own content contains- that substring (e.g. a task literally named " ้ช่ฏไฟๅญ**ๅคฑ่ดฅ**ๆ็ๆต่ฏไปปๅก "), the grep- matches the fixture, not the state indicator โ a false PASS on the error state- even when it never rendered (a Case-1 grep trap).-- **Works**: scope the check to the actual UI element, never `body.innerText`:- - the save hint tag โ `[...document.querySelectorAll('[class*=Tag],.ant-tag')].map(t=>t.textContent.trim())`- - the toast โ find the leaf node matching the message, climb while the subtree- text stays short, then read its `button`s (`[Close, ้่ฏ]`).- Pick fixture names that do NOT contain any state keyword you'll assert on.--### C6. โ WORKS โ read a topic's metadata (workingDirectoryConfig etc.) from the chat store, and reset to a fresh topic--- **Doesn't work**: `chat().topicsMap[topicId]` / `chat().topicDataMap[topicId]` โ there is- no per-topic-id map. `topicDataMap` is keyed by **view key** (`agent_<agentId>`), and each- value is a paginated view object (`{ items, total, hasMore, โฆ }`), not a topic.-- **Works** (verified while E2E-testing `git worktree add` side-effect recording):- ```js- var c = window.__LOBE_STORES.chat();- var view = c.topicDataMap['agent_' + agentId];- var topic = (view.items || []).find(function (x) {- return x.id === c.activeTopicId;- });- topic.metadata.workingDirectoryConfig; // โ e.g. git.activeWorktree written by recordGitCommandEffects- ```-- **Fresh topic without touching the UI**: `await c.openNewTopicOrSaveTopic()` โ with an- active topic it saves/exits to the agent's no-topic compose state (activeTopicId โ null),- so the next send creates a new topic. Chain per-case fixtures this way instead of clicking- "Start New Topic". The contenteditable ref changes after the switch โ re-run- `snapshot -i -C` before typing.-- Full E2E loop this enabled: E11 fixture agent (`heterogeneousProvider: { type: 'claude-code' },-executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to run a- specific shell command โ poll `chat().operations` for `running === 0` โ assert the- topic's metadata via the probe above. A real CC one-command turn completes in \~10โ20s.+ This surfaces cases where the data looks settled even on error โ a discrepancy a+ screenshot can't show.++### C2. `agent-browser console` capture works โ use it for what console is for++- Console capture is reliable on current agent-browser (a page-script `[log]` and one+ emitted later from `eval` both appear). An empty console means the page logged+ nothing, not that capture is broken. The debug-global (C1) is still the better tool+ for reading structured component state; use console for what console is for.++### C3. `document.body.innerText` keyword grep false-positives on fixture text++- Asserting a state via `body.innerText.includes('<phrase>')` matches your own fixture+ content if it happens to contain that substring (e.g. a fixture literally named+ "โฆfailureโฆ" when you assert on "failure") โ a false pass on a state that never+ rendered.+- **Works**: scope the check to the actual UI element (`querySelectorAll` on the+ specific tag/toast/alert), never `body.innerText`. And pick fixture names that do+ NOT contain any state keyword you'll assert on.++### C4. `innerText` can be 0 on a rendered page โ use it to tell a wedge from a blank++- On some app shells `document.body.innerText` reads `""` even on a fully rendered+ page (some ancestor collapses the layout-dependent computation); probe a more+ specific container (e.g. the app root element) instead.+- **Diagnostic**: `innerText` needs layout, `textContent` does not. When the root+ gives `innerText === 0` but `textContent > 0`, the DOM is fine and the RENDERER is+ not painting (a compositor wedge โ see D9). When both are 0, the DOM is genuinely+ empty. This distinction tells a non-painting renderer from a blank page.++### C5. A successful ingest does not prove acceptance attachment when the CLI is stale++- A globally installed CLI may accept `ingest-report` and return a run id while+ lacking newer subject/acceptance behavior. The result is an orphan round even+ though the command appears successful.+- Compare `lh --version` with the skill marker before publishing. If the branch+ under test changes the CLI contract, run that branch's CLI; otherwise use+ `npx @lobehub/cli@latest`. Confirm the returned acceptance id or inspect the+ acceptance page rather than treating a run id alone as proof.---## D. agent-browser / CDP mechanics-- **D1. `screenshot` honours a relative path (0.26.0) โ but still pass an absolute one.**- Re-tested: `agent-browser screenshot rel.png` saved to the **caller's cwd**, printed- `โ Screenshot saved to rel.png`, and wrote nothing under `~/.agent-browser/tmp/screenshots/`.- The old "silently ignored" claim is false. An absolute path is still the right habit โ the- cwd of a step in a longer script is easy to lose track of.-- **D2. CDP port is ephemeral.** The browser runs with `--remote-debugging-port=0`; for raw- CDP, read `DevToolsActivePort` in the browser user-data-dir. Note there is **no top-level- `cdp-url` command** โ it is a `get` subject: `agent-browser get cdp-url` (which does return- a `ws://127.0.0.1:<port>/devtools/browser/โฆ` URL). An earlier version of this note reported- `agent-browser cdp-url` "returned empty"; it returned empty because it is not a command.-- **D3. offline is `agent-browser set offline on|off`** (under `set`, with- `viewport`/`geo`/`headers`), not a top-level `offline` command.-- **D4. `wait --load networkidle` HANGS during a retry loop** (network never- idles) and can blow the command timeout โ use a fixed `wait <ms>` instead when- a fetch is stuck retrying. **Confirmed with a control**: on a page polling every 300ms the- command was still blocked after 20s; on an idle page it returned `rc=0` immediately. (macOS- has no `timeout(1)` โ don't try to bound it with coreutils that aren't there.)-- **D5. base-ui `toast` lives in a portal, auto-dismisses in \~5s, and can be- occluded by the dev debug widget.** The portal viewport carries `aria-label="Notifications"`- and base-ui's default `timeout` is `5000`. `snapshot -i` does NOT reliably surface the- portal's action buttons (the `้่ฏ`/Retry ref came back empty); read the toast- via `eval` DOM query instead. The occluding widget is the **DevPanel float button**- (`src/features/DevPanel/features/FloatPanel.tsx`, fixed bottom-right, desktop/Electron only โ- the SPA disables it). There is no FPS meter in this app, despite what an earlier version of- this note said. Relocate the toast region for a clean shot:- ```js- [...document.querySelectorAll('[aria-label=Notifications]')].forEach((r) => {- r.style.cssText +=- ';position:fixed!important;top:100px!important;left:360px!important;right:auto!important;bottom:auto!important;z-index:2147483647!important;';- });- ```- Because it dismisses in 5s, re-trigger the toast immediately before the- screenshot/query; a click-the-Retry-then-observe flow is timing-flaky โ fire it- via `button.click()` in `eval` right after re-triggering, or extend the toast- duration.-- **D6. The singleton hover action bar is hard to drive; its icons are- `div[role=button]`, NOT `<button>`.** The per-message action bar- (`SingletonMessageActionsBar`) is one portal that moves via DOM + a- freeze/commit `MutationObserver`, so it appears only while hovering and- re-hides on the next commit tick. Gotchas that wasted a run:- - `host.querySelectorAll('button')` returns 0 โ the ActionIcon items render as- `<div role="button">`. Query `[role="button"]` (or the broad- `button,[role=button],[class*=ActionIcon]`).- - Between two evals the bar can vanish (commit tick). Do hover + inspect + act- in as few steps as possible.- - โ WORKS to open the overflow menu on a message and read its items:- ```bash- S="--session s9224 --cdp 9224"- agent-browser $S hover "#<messageId>" # ChatItem root id = message id- sleep 1.5- # click the LAST role=button in the host = the "โฆ" overflow trigger- agent-browser $S eval '(function(){var h=document.querySelector("[data-singleton-message-action-bar-host]");var b=h&&h.querySelectorAll("[role=button]");if(!b||!b.length)return "no-bar";b[b.length-1].click();return "clicked";})()'- sleep 1- agent-browser $S screenshot /abs/menu.png- agent-browser $S eval '(function(){var t=[];document.querySelectorAll("[role=menuitem],li").forEach(function(i){var s=(i.innerText||"").trim();if(s)t.push(s);});return JSON.stringify(Array.from(new Set(t)));})()'- ```- A programmatic `.click()` on the ellipsis DOES open the antd dropdown (it sets- `data-popup-open`, which also freezes the bar so it won't vanish). The action- labels are localized (`ๅไบซ`/`ๅค้`/`ๅ ้ค` = share/select/del).-- **D7. To get a _finished_ hetero (CC/Codex) turn that ENDS on a tool block**- (last child has tools โ `getGroupLatestMessageWithoutTools` returns undefined,- the `!contentId` action-bar path): send a single long tool call (e.g.- `็จ Bash ๅทฅๅ ท่ฟ่ก sleep 20`) and, the moment the group's last child is a running- tool, call `stopGenerateMessage()` in the SAME eval to avoid the race where CC- appends a trailing text summary (which would give it a text last-block and a- defined contentId). Poll-then-stop-atomically:- ```bash- agent-browser $S eval '(function(){var c=window.__LOBE_STORES.chat();var t=c.activeTopicId;var a=c.messagesMap["main_"+c.activeAgentId+"_"+t]||[];var g=a.filter(m=>m.role==="assistantGroup").pop();var lc=g&&g.children&&g.children.at(-1);var running=Object.values(c.operations||{}).some(o=>o.status==="running");if(lc&&(lc.tools||[]).length&&running){c.stopGenerateMessage();return "STOPPED";}return "wait";})()'- ```-- **D8. `agent-browser screenshot` can WEDGE the daemon; `eval`/`get` still work.**- agent-browser is a daemon with **one socket per session**, `~/.agent-browser/<session>.sock`- (verified: two live sessions โ two sockets; `default.sock` exists only while the _default_- session runs). Sessions coexist, so a wedge is scoped to one session, not the whole tool.- Commands on a given socket are serialized. A screenshot RPC that is interrupted โ a- mis-invoked flag, a command the harness auto-backgrounds then kills, `--full` on a giant- page โ leaves the socket half-consumed, and every later `screenshot` fails with- `Resource temporarily unavailable (os error 35)` / `CDP response channel closed`- while `eval`/`get url` keep working. **Not** a display-sleep or permission issue.- - **Not reproduced on 0.26.0** with the obvious trigger: SIGKILLing the client 150ms into a- `screenshot` left the session healthy (`eval`, `get url`, and a follow-up `screenshot` all- succeeded). Real, but rarer than the note implies โ don't assume a wedge without seeing- the error string above.- - **Works**: reset with `agent-browser close --all` (respawns the daemon), or- skip the daemon entirely (D9).-- **D9. โ WORKS โ raw-CDP screenshot, bypasses the daemon.**- `scripts/cdp-screenshot.sh [--port 9222] [--out x.png] [--full] [--check]`- opens its own ws to the target, does one `Page.captureScreenshot`, closes- (\~60ms). Immune to the D8 wedge, and **verified robust when the display is- ASLEEP and when the window is MINIMIZED/occluded** (Chromium forces a compositor- frame). Use it for Electron evidence and as a preflight (`--check` โ exit 0 iff a- real, non-black frame was captured). Needs repo `node_modules/ws` (resolved via- NODE\_PATH by the wrapper).-- **D10. OS `screencapture` is BLACK when the display is asleep/locked/screensaver.**- Distinct from D8/D9: `screencapture` (and `capture-app-window.sh`, osascript- grabs) captures the physical framebuffer, so an idle-slept display โ a uniformly- black PNG (mean/max=0; a full-screen black frame has a telltale identical byte- size). Permission can be fine. Gate with `scripts/check-screen-recording.sh`- (checks `CGPreflightScreenCaptureAccess` + a real-frame blackness probe) and keep- the display awake for the whole run: `caffeinate -dimsu &` (or `caffeinate -u`- to wake it). CDP capture (D9) does not have this problem.+- **D1. `screenshot` honours a relative path โ but still pass an absolute one.** A+ relative path saves to the caller's cwd; the cwd of a step in a longer script is+ easy to lose track of, so an absolute path is the right habit.+- **D2. The CDP port can be ephemeral.** A browser launched with+ `--remote-debugging-port=0` picks a random port; read `DevToolsActivePort` in the+ user-data-dir, or use `agent-browser get cdp-url` (note: `cdp-url` is a `get`+ subject, not a top-level command). Electron dev instances usually pin a known port+ (e.g. 9222) โ the project adapter says which.+- **D3. `wait --load networkidle` HANGS during a retry loop** (the network never+ idles) and can blow the command timeout โ use a fixed `wait <ms>` when a fetch is+ stuck retrying. (macOS has no `timeout(1)` to bound it.)+- **D4. Portal toasts auto-dismiss (\~5s) and `snapshot -i` may miss their buttons.** A+ base-ui / portal-rendered toast lives outside the main tree and can be occluded by a+ dev overlay; `snapshot -i` does not reliably surface its action buttons. Read the+ toast via an `eval` DOM query, and because it dismisses in \~5s, re-trigger it+ immediately before the screenshot/query (or fire its button via `.click()` in the+ same `eval`) rather than relying on a timed hover-then-observe.+- **D5. `agent-browser screenshot` can WEDGE the session; `eval`/`get` still work.**+ Each session is one daemon socket, so a wedge is scoped to that session. An+ interrupted screenshot RPC (a killed command, a bad flag, `--full` on a giant page)+ can leave the socket half-consumed, after which every later `screenshot` fails+ (`Resource temporarily unavailable` / `CDP response channel closed`) while+ `eval`/`get url` keep working โ **not** a display-sleep or permission issue. Reset+ with `agent-browser close --all`, or skip the daemon entirely (D6).+- **D6. WORKS โ raw-CDP screenshot bypasses the daemon.** `scripts/cdp-screenshot.sh [--port <n>] [--out x.png] [--full] [--check]` opens its own ws to the target, does+ one `Page.captureScreenshot`, and closes (\~60ms). Immune to the D5 wedge and+ **robust when the display is asleep or the window is minimized/occluded** (the+ engine forces a compositor frame). Use it for Electron evidence and as a preflight+ (`--check` โ exit 0 iff a real, non-black frame was captured).+- **D7. OS `screencapture` is BLACK when the display is asleep/locked/screensaver.**+ Distinct from D5/D6: `screencapture` (and `capture-app-window.sh`, osascript grabs)+ captures the physical framebuffer, so an idle-slept display โ a uniformly black PNG+ (mean/max = 0). Permission can be fine. Gate with `scripts/check-screen-recording.sh`+ (checks the permission bit + a real-frame blackness probe) and keep the display+ awake for the whole run: `caffeinate -dimsu &`. CDP capture (D6) does not have this+ problem.+- **D8. The daemon serializes commands โ `open` queues behind a screenshot loop.**+ While a recording loop (`record-gif.sh`) is running, `agent-browser open <url>`+ lands late/out of order, and your "during navigation" screenshot can show the+ PREVIOUS page (which may look identical to the expected end state โ a false read).+ **Works**: during any recording loop, navigate with+ `agent-browser eval 'location.href="<url>"'` (fire-and-forget) instead of `open`.+- **D9. A mid-session bundler dependency re-optimize can wedge the renderer+ compositor.** Symptom: capture returns black, the app root's `innerText` is 0 while+ `textContent` still holds the full DOM (C4), and `visibilityState` is `visible` with+ real dimensions โ not display sleep or permission (D6/D7 would survive both). It+ often follows a "re-optimizing dependencies" / "failed to fetch dynamically imported+ module" log line. **Works**: restart the dev instance; `location.reload()` alone may+ not clear it.+- **D10. Virtualized lists: driving `scrollTop` by hand blanks the pane โ use a small+ fixture.** A virtualizer unmounts nodes as you scroll past (a `TreeWalker` search+ then "loses" a node that was there a second ago), and forcing `scrollTop` far+ outside the rendered window can make the scroll container itself disappear โ reading+ exactly like a render bug. **Works**: pick a fixture small enough that the target is+ on the first screen; far cheaper and more reliable than fighting the virtualizer.+- **D11. React controlled inputs ignore synthetic events โ use `agent-browser click`+ (trusted CDP input).** `el.click()` and even a full synthetic+ `pointerdown/mousedown/pointerup/click` sequence are `isTrusted: false`, so a+ React-controlled checkbox/toggle never updates its state. **Works**: `snapshot -i`+ for the ref, then `agent-browser click <ref>` โ it goes through CDP+ `Input.dispatchMouseEvent`, which the page sees as a real user click. The snapshot+ also reveals when a control is `[disabled]` (the app deliberately refusing), which a+ coordinate-click never would.+- **D12. Disambiguate elements by geometry or an identifying attribute โ don't+ singular-select.** A page can render a hidden zero-size duplicate of a subtree+ (e.g. an offscreen measurement copy) at `(0,0)`, first in DOM order, so a singular+ `querySelector` grabs the phantom: a `fill` reports success while the visible box+ stays empty, a click on the phantom button is a silent no-op, and an `innerText`/aria+ grep "finds" a control the user can't see. **Works**: enumerate and filter by a+ non-zero `getBoundingClientRect()`, or target by the component's own `aria-label`;+ tag the resolved element with a `data-probe` attribute and drive it with+ `agent-browser click '[data-probe=...]'`.+- **D13. A blank page at `about:blank` with a 1280px viewport usually means the+ previous `open` failed** (exited non-zero without navigating โ e.g. an unrecognized+ global flag). The session still exists and answers every later probe โ against the+ fresh page it was born with, at the default viewport. Read the `open` exit code and+ stderr to learn _why_ rather than assuming the page went blank; treat the+ fingerprint as "the navigation failed".----## E. Env / ports--- **E1. โ ๏ธ This item was wrong on both counts โ do not trust its reasoning.**- It claimed `eval "$(init-dev-env.sh env)"` "can clobber `PATH`". It cannot: the `env`- subcommand prints only the keys in `env_keys()` (`init-dev-env.sh:178-204`), and the string- `PATH` does not appear anywhere in the script. It also told you to hardcode- `http://localhost:20874`; `SERVER_PORT` is **randomly allocated per workspace** in- 20000-40000 (falling back to 3010) and persisted to `.records/env/agent-testing-ports.env`,- so `20874` was one machine's old port (this workspace is on 21912) and it appears nowhere- else in the repo. **Works**: read the port from that file, or export just the one var โ- `export APP_URL="$(init-dev-env.sh env | sed -n 's/^APP_URL=//p')"`. Whatever broke- `awk`/`head` in the original run was never diagnosed.-- **E2. SPA port is configurable to coexist with another worktree.** Vite binds- `SPA_PORT||9876`; Next proxies `VITE_DEV_PORT||9876`. Pass `SPA_PORT=9877` to- `init-dev-env.sh dev` (it exports `VITE_DEV_PORT=$SPA_PORT`) so both agree and- you don't fight a worktree already on 9876.--### E3. Deep-linking to an authed SPA route โ NOT reproduced; soft-nav is still the safer path--- **Original claim**: after `setup-auth.sh web-seed`, a hard `open <app>/agent/<id>/docs`- redirects to `/signin?callbackUrl=...` while `/` stays authed.--- **Did not reproduce** against the current dev server with a seeded web session- (`isSignedIn: true`, `userId: user_agent_testing_001`). Hard-loading `/settings/common` and- the note's exact shape `/agent/<real-id>/docs` both landed on the route itself, with no- `/signin` and no `callbackUrl`. Either it was fixed, or the original run's cookie state- differed. Don't budget for the bounce; check for it.--- **Still true and still useful**: `app-probe.sh auth` "false-negatives" here because it talks- to the **Electron CDP endpoint on 9222**, not to your web browser session โ it fails with- `All CDP discovery methods failed for 127.0.0.1:9222`. Read the auth state out of the page- instead: `window.__LOBE_STORES.user()` โ `{ isSignedIn, user.id }`.--- **Works**: hard-load `/` (authed), confirm by screenshot (not the app-probe auth- JSON โ it false-negatives here, returns `isSignedIn:false` on an authed page),- then **client-side soft-nav** with no server round-trip:-- ```bash- agent-browser eval "history.pushState({},'','/agent/<id>/docs'); window.dispatchEvent(new PopStateEvent('popstate')); 'nav'" --session lobehub-dev- ```-- react-router picks up the popstate and renders the route in-context with the- already-hydrated auth. Right-panels that render at a _layout_ level do NOT see a- child route's `:param` via `useParams()` โ read it from `location.pathname` if- you need it.--- **D11. โ WORKS โ catch a BRIEF blank/transient frame (sub-second) that screencast misses.**- Verifying a momentary full-screen blank (e.g. a React subtree unmounting to `null` for- \~150โ350ms during a scope change): `Page.startScreencast` emits one frame when it starts and- then only on a VISUAL CHANGE, so a _static_ blank produces no further frames โ you see a time- GAP in the manifest, not a blank image. (Measured: 3s of a static page โ **1** frame, the- initial one; 6 background flips โ **6** frames. The old note said "NO frame", which misses- the initial one and can look like the screencast never started.)- Single timed `cdp-screenshot` also loses the race (its own \~200ms latency- overshoots) and `captureScreenshot` can return the prior surface.- - **Works โ two complementary probes**:- 1. **DOM proof (deterministic)**: sample `document.getElementById('root').innerText.trim().length`- at 150/350/600ms after the trigger via one `eval` returning a Promise. A full unmount- drops it to `0`, then it recovers โ unambiguous, load-independent. (Fixed vs broken:- `6064 โ 0 โ 5646` vs `6089 โ 6002 โ 6042` never-0.)- 2. **Freeze the pixels**: to actually capture the blank image, keep the blank ON SCREEN- longer by re-triggering every \~80ms (e.g. flip `userId` to a fresh value each tick so a- `key={scope}` gate stays remounted), while firing raw CDP `Page.captureScreenshot` every- 80ms over the same window. Blank frames come back tiny (\~34KB jpeg) vs content (\~294KB);- convert + Read one to confirm. (A raw-CDP forced capture DOES render a static frame; the- trick is holding the state, not the capture.)- - Byte-size is a reliable auto-flag for near-uniform frames (blank/loading), but two- different near-uniform states (dark loading-screen vs blank) can both be small โ always- Read the frame to tell them apart (Case 1 rule).--### E4. โ WORKS โ keep Electron pool `LOBE_IPC_ID` short--- **Situation**: manually starting an isolated Electron dev instance with a- descriptive `LOBE_IPC_ID` such as `lobehub-desktop-dev-manual-selection-2`.- The main process builds a Unix socket path under `$TMPDIR`, and macOS rejects- overlong socket paths.-- **Doesn't work**: long IPC ids can crash Electron at bootstrap with- `listen EINVAL ... <id>-electron-ipc.sock`, before any renderer/CDP evidence is- available.-- **Works**: use the numeric `electron-dev.sh start <id>` pool path, or keep- manual IPC ids very short, e.g. `LOBE_IPC_ID=lhmsel2`.--### E5. โ WORKS โ no-Docker fallback stack for the isolated no-.env env--- **Situation**: `init-dev-env.sh setup-db` needs Docker (paradedb + redis images), but- Docker Desktop's VM can wedge indefinitely (`no route to host` to 192.168.65.x, empty- vm/console.log). Verified working substitute:- - **Postgres**: local brew Postgres 17 (pgvector available). The only paradedb-specific- migrations are `0090_enable_pg_search` / `0093_add_bm25_indexes_with_icu` โ no-op them- in the worktree (`SELECT 1;`), everything else applies clean.- - **Redis is a hard dependency of Better Auth sign-in** โ with a dead REDIS\_URL the seed- login 500s (`[Better Auth]: Error: Connection is closed`). `brew install redis`,- `redis-server --port 6380 --daemonize yes`.- - **S3**: `s3rver` (npm) on 29000 with a CORS config for the bucket. Its presigned-URL- validation only accepts key id `S3RVER` (secret `S3RVER`) โ `allowMismatchedSignatures`- does NOT rescue an unknown access key id (403 on the browser preflight). Set the dev- server's `S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY=S3RVER`, `S3_ENABLE_PATH_STYLE=1`,- `S3_PUBLIC_DOMAIN=http://127.0.0.1:29000/<bucket>`.--### E8. โ WORKS โ a git-worktree checkout needs its OWN `pnpm install`, not a symlinked `node_modules`--- **Situation**: verifying a UI change from a `git worktree` (e.g. `.claude/worktrees/<name>`), which- starts with no `node_modules`.-- **Doesn't work**: symlinking the main checkout's `node_modules` (root and/or `apps/desktop`) into the- worktree. The workspace links inside it point `@lobechat/*` at the MAIN checkout's `packages/`, which- sits on a different branch โ the Electron main build then dies with- `[MISSING_EXPORT] "X" is not exported by "../../packages/<pkg>/src/..."`. Renderer source resolves from- the worktree while packages resolve from the main repo, so the two disagree.-- **Works**: run `pnpm install` at the worktree root AND `cd apps/desktop && pnpm install` (standalone,- not in the workspace). \~5 min total, mostly hardlinked from the store.-- **Also**: a Vite dev server left over from an earlier failed `electron-dev.sh start <id>` is REUSED by- the retry (`CDP already reachable โฆ Skipping start`) and can keep serving pre-edit module text. If the- DOM shows markup that contradicts the source, curl the dev server for the file and grep for a token you- just added (`curl -s 127.0.0.1:<vitePort>/src/path/File.tsx | grep -c myNewSymbol`) before blaming the- code. `electron-dev.sh stop <id>` then start again to get a clean server.--### E8b. The standalone `apps/desktop` install BREAKS the root workspace's type resolution โ re-run the root install after it--- **Situation**: a worktree set up per E8 (`pnpm install` at the root, then- `cd apps/desktop && pnpm install`). Everything runs โ Electron boots, the renderer serves live- code โ but a full `bun run type-check` that passed BEFORE the desktop install now fails with- dozens of errors that have nothing to do with the change under test:- `Module '"@lobechat/types"' has no exported member 'MetaData' | 'HotkeyId' | โฆ` plus- `Type 'UserHotkeyConfig' is missing the following properties from type 'UserHotkeyConfig'` โ- the same name on both sides, i.e. **two copies of `@lobechat/types` in one program**.-- **Doesn't work**: chasing it as a code defect, or checking the symlink- (`node_modules/@lobechat/types โ ../../packages/types` looks correct) and `packages/types/node_modules`- (its deps are all present). Both look fine while the program still sees two instances.-- **Cause**: `apps/desktop` is NOT in the root pnpm workspace (see E8). Its standalone install- re-resolves the `packages/*` links from its own lockfile and rewrites shared package deps under- `packages/*/node_modules`, leaving the root workspace pointing at a second instance.-- **Works**: run `pnpm install` at the worktree root ONE MORE TIME, after the desktop install- (\~1.5 min, mostly cached). Type-check goes back to 0 errors and Electron keeps working.- So the safe order is: root install โ desktop install โ root install again. And never publish a- "type-check failed" verdict from a worktree until you've re-run the root install โ the failure is- environmental, and the error text (a type "missing properties from" itself) is the tell.--### E9. Electron dev's FIRST cold boot sits on the splash with an empty `#root` for 1โ3 minutes--- **Situation**: after `electron-dev.sh start <id>`, `app-probe.sh auth` returns `isSignedIn:false`,- `#root` has providers but `innerText.length === 0`, and the screenshot is just the LobeHub splash. The- main log shows `Proactive token refresh failed` / `invalid_grant`.-- **Doesn't work**: concluding the copied login state expired. That refresh error is a red herring โ the- app recovers, and `RENDERER_WAIT_S` (60s) can expire while Vite is still on- `[optimizer] bundling dependencies`, which ends in `optimized dependencies changed. reloading`.-- **Works**: poll until the DOM actually has content instead of sleeping a fixed amount:- ```bash- until [ "$(agent-browser --session s \- '(function(){return String(document.getElementById("root").innerText.trim().length>50)})()' < port > --cdp < port > eval \- | tr -d '"')" = "true" ]; do sleep 5; done- ```- Also note `zsh does NOT word-split unquoted vars` โ `S="--session x --cdp 9226"; agent-browser $S eval`- fails with `Unknown command`. Inline the flags or use an array.--### E10. โ WORKS โ stop the main process from yanking the renderer back to its last tab--- **Situation**: driving the SPA to a specific route for a screenshot. `history.pushState` + `popstate`- lands correctly, then \~15โ20s later `location.pathname` snaps back to whatever tab the main process- has stored (e.g. `/devtools/claude-code`). A hard `location.href` nav is reverted the same way.-- **Cause**: the main process broadcasts `navigate`, and `src/features/DesktopNavigationBridge` obeys it.-- **Works**: HMR-neutralize the bridge for the run, then revert:- ```tsx- // src/features/DesktopNavigationBridge/index.tsx โ [AGENT-TEST] REMOVE- useWatchBroadcast('navigate', () => {- void handleNavigate;- });- ```- `git checkout -- src/features/DesktopNavigationBridge/index.tsx` afterwards; `grep -rn AGENT-TEST src/`- must come back empty.--### E11. โ WORKS โ drive the working-directory / git-status ControlBar without the native dir picker--- The picker opens a native dialog, but the same write path is reachable from the store. With no active- topic, `commit()` persists to `agencyConfig.workingDirByDevice[deviceId]`:- ```js- const a = window.__LOBE_STORES.agent(),- d = window.__LOBE_STORES.device();- const did = window.__LOBE_STORES.electron().gatewayDeviceInfo.deviceId;- const entry = { path: '/abs/repo', repoType: 'git' };- await a.updateAgentConfigById(agentId, {- agencyConfig: { workingDirByDevice: { [did]: entry } },- });- await d.updateDeviceCwd(did, entry, { setDefault: false }); // so the entry exists โ sourcePath resolves- ```- Create a throwaway agent with `agent().createAgent({ title })` and delete it afterwards with- `session().removeSession(agentId)` (there is no `deleteAgent` on the agent store) plus- `device().removeDeviceWorkingDir(did, path)` โ otherwise the fixture cwd lingers in the real account.-- **Identify icons precisely**: lucide renders `svg.lucide.lucide-git-fork`. Several git icons live in the- same bar (the dir picker's `DirIcon` is `git-branch`, the review toggle is `git-compare`), so scope the- assertion to the trigger: `document.querySelector('[role=button][aria-label="Worktrees"]') svg`, and- still open the PNG to confirm (Case 1).--### E6. code-inspector-plugin breaks Turbopack compile of Next-served authed pages--- **Situation**: the first AUTHENTICATED render of a Next-served (non-SPA) page whose client- graph pulls the chat store dies in `next dev` (Turbopack) with Build Error `Resource path-"worker/browser/createWorker.ts" needs to be on project filesystem` (chain: layout โ- GlobalProvider/Query โ trpc client โ image/chat store โ python-interpreter worker).- Unauthenticated curl 302s BEFORE the client graph compiles, so it false-passes; a fresh- no-lockfile `pnpm install` can resolve a broken plugin version.-- **Works**: `E2E=1` (or `TEST=1`) โ `defineConfig`'s `isTest` skips `codeInspectorPlugin`,- the only thing it gates. Webpack mode (`next dev --webpack`) is NOT a viable fallback- (react version mismatch when two next versions are hoisted; `zlib-sync` unresolved for- discord.js).--### D12. agent-browser daemon serializes commands โ `open` queues behind a record-gif loop--- **Situation**: `record-gif.sh` (a screenshot loop) running while you issue- `agent-browser open <url>` โ the daemon socket serializes, the open lands late/out of- order, and your "during navigation" screenshot actually shows the PREVIOUS page (which can- look identical to the expected end state โ false read).-- **Works**: during any recording loop, navigate with- `agent-browser eval 'location.href="<url>"'` (fire-and-forget) instead of `open`. To hold- a streaming loading state on screen, inject a server-side `await sleep(8000)` before the- slow lookup in the page (\[AGENT-TEST], revert) โ TTFB stays \~0.3s so loading.tsx renders- while the route hangs, giving a wide static-capture window.--### E7. curl "502" on localhost with nothing listening = shell proxy env โ **only if `NO_PROXY` omits localhost**--- The causal mechanism is real: force a dead host through a proxy- (`curl --proxy http://127.0.0.1:7890 โฆ`) and you get the proxy's `502`, not- connection-refused โ a "server up but broken" mirage.-- **But it does not reproduce in this environment**, and the note used to state it- unconditionally. `HTTP_PROXY`/`HTTPS_PROXY` are set here, yet- `NO_PROXY="localhost, 127.0.0.1, ::1"` exempts exactly the hosts you probe locally.- Measured against a dead port: with and without `--noproxy '*'`, both give curl exit 7 /- `code=000` (connection refused). No 502 either way.-- **Works**: `curl --noproxy '*'` is a harmless belt-and-braces habit, but if you actually see- a 502 from a local port, check `NO_PROXY` before believing this note โ the proxy is only in- the path when localhost is missing from it.--### E14. โ WORKS โ Electron pool instance boots BLANK because the copied golden login is dead--- **Situation**: `electron-dev.sh start <id>` seeds userData from the golden dev profile,- but the app renders an empty `#root` (innerText length 0, only the LobeHub watermark) and- `app-probe.sh auth` returns `isSignedIn:false`. The instance log shows- `Refresh response missing access_token or refresh_token { error: 'invalid_grant' }`.-- **Cause (measured, not guessed)**: OIDC refresh tokens are single-use. Every prior- `start <id>` copied the same golden profile and consumed/rotated its refresh token, so the- copy's token is already dead. A blank shell here is an AUTH failure, not a render bug โ- read the instance log before chasing the SPA.-- **Doesn't work**: pointing `LOBE_GOLDEN_PROFILE` at the packaged app's profile- (`~/Library/Application Support/LobeHub`) โ the pool instance's startup refresh will rotate- that token too and log the user out of their real desktop app.-- **Works โ inject a valid credential the app already owns, no new OAuth grant**:- the prod lambda accepts any of the user's valid OIDC access tokens via the `Oidc-Auth`- header, and the CLI keeps one in `~/.lobehub`. Extract it with the CLI's own- `getValidToken()` (it auto-refreshes), then override the single main-process accessor:- ```ts- // apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts โ [AGENT-TEST] REMOVE- async getAccessToken(): Promise<string | null> {- if (process.env.LOBE_TEST_ACCESS_TOKEN) return process.env.LOBE_TEST_ACCESS_TOKEN;- ...- ```- `export LOBE_TEST_ACCESS_TOKEN=...` before `electron-dev.sh start <id>` (the script forwards- the shell env). This authenticates BOTH the renderer (BackendProxyProtocolManager injects the- same token) and any main-process fetch, so the whole app comes up signed in. Revert with- `git checkout --` + `grep -rn AGENT-TEST` afterwards, and never echo the token.-- **Works โ alternative, no source edit, when you can approve a browser prompt**: seed a- PRISTINE profile so the app takes the signed-out path and renders the real login screen- instead of hanging:- ```bash- mkdir -p /tmp/empty-golden- LOBE_GOLDEN_PROFILE=/tmp/empty-golden ./electron-dev.sh start <id>- ```- Drive onboarding (`ๅผๅง` โ `ไธไธๆญฅ` ร2 โ `็ปๅฝ LobeHub Cloud`). The device-code flow opens the- browser and auto-approves against an existing app.lobehub.com session, giving the instance its- OWN token โ so it never rotates the one the user's resident app holds.-- **Why the blank shell has no login button**: the failed refresh leaves `isUserStateInit:false`- (with `isLoaded:true, user:null`), and the desktop first-frame gate waits on it forever. Every- route โ `/`, `/desktop-onboarding` โ renders empty. Reloading, soft-navving, and waiting all- fail to resolve it, so it reads exactly like a Case-1 blank page.-- **Gotcha**: a worktree installed with `pnpm install --ignore-scripts` has NO electron binary- (`node_modules/.pnpm/electron@*/node_modules/electron/dist` missing). Fix with- `cd apps/desktop && pnpm rebuild electron`. Also remember `apps/desktop` and `apps/cli` are- NOT in the root pnpm workspace โ install inside each.-- **Gotcha**: `electron-dev.sh restart <id>` keeps the userData dir, but a device-code session- did NOT survive it โ budget for one more login after any restart (e.g. when a main-process- change forces one, see E9).--### C5. โ WORKS โ main-process `logger.info` is invisible unless `DEBUG` is set--- **Situation**: proving WHICH code path the Electron main process took (e.g. hetero- `ClaudeAgentSdkSession` vs the CLI-spawn `AgentStreamPipeline`). Both produce identical- user-visible output, so the verdict needs a main-process log line.-- **Doesn't work**: grepping the instance log for the `logger.info('Starting Claude Code SDK-session:')` line. In development `createLogger().info` routes to the `debug` package, which- prints nothing unless its namespace is enabled (only `console.error` shows up unconditionally).- Absence of the line is NOT evidence the branch didn't run.-- **Works**: `export DEBUG='controllers:*'` before `electron-dev.sh start <id>`, then- `grep -oE "controllers:HeterogeneousAgentCtr INFO: [^']*" /tmp/lobe-electron-pool/instance-<id>.log`.- Don't trust the hetero tracing dir for this โ it is gated and the copied golden profile ships- STALE trace sessions from months earlier that look like a fresh run.--### E15. Main-process code changes need a restart; Vite HMR only covers the renderer--- Adapters under `packages/heterogeneous-agents` run in the **main** process- (JSONL framing + adapter + `toStreamEvent`). Editing one and reloading the- renderer verifies nothing โ the old adapter is still running.-- Prove which code each process has before trusting a run:- ```bash- # renderer: vite serves working-tree src (VITE_BASE + id)- curl -s --noproxy '*' "http://127.0.0.1:<vitePort>/src/<path>.ts" | grep -c '<marker>'- # main: rebuilt on start into the desktop dist bundle- grep -c '<marker>' apps/desktop/dist/main/index.js- ```--### D13. `record-electron-demo.sh` IS real 30fps capture โ but raw avfoundation timestamps are unusable--- **Don't assume the whole skill is 1-2 fps.** `record-gif.sh` and `record-app-screen.sh` are- CDP-screenshot loops (capped by screenshot latency). `record-electron-demo.sh` is different:- `ffmpeg -f avfoundation -framerate 30` (see `scripts/record-electron-demo.sh:152-153`) โ a- true OS screen recording, fast enough for sub-second UI transitions.-- **Doesn't work**: a naive `ffmpeg -f avfoundation -framerate 30 -i "1:" -t 14 out.mp4`.- Measured on one 14s capture: **133332 frames muxed into a 0.13s file at 4.7 Gbit/s, 79 MB**.- `-ss <n>` then fails with `Output file is empty, nothing was encoded`. Cause not established- (avfoundation's own PTS appear near-identical); the fix below is empirical.-- **Works**: rebuild the time base โ `-use_wallclock_as_timestamps 1` on the input plus- `-vf fps=20` on the output. Same 14s capture โ **14.00s / 136 KB**.- ```bash- ffmpeg -y -use_wallclock_as_timestamps 1 -f avfoundation -framerate 30 -capture_cursor 0 \- -i "1:" -t 14 -vf "fps=20,scale=1200:-2" -c:v libx264 -crf 26 -pix_fmt yuv420p out.mp4- ```-- **`ffprobe` may be absent even when `ffmpeg` is installed.** Validate with- `ffmpeg -v error -i out.mp4 -f null -` (silence = decodes fine) and read `Duration` from- `ffmpeg -i out.mp4 2>&1 | grep Duration`.-- Being an OS capture it is subject to D10 (black frames when the display sleeps): gate with- `check-screen-recording.sh` and hold `caffeinate -dimsu` for the WHOLE run โ re-check right- before recording if the run has been long, since the display can sleep mid-session.-- **Pick evidence by what you're asserting, not by a rule.** A state transition lasting seconds- (a loading label flipping) is fine as a 2fps CDP GIF. Reach for 30fps OS capture only when the- asserted change is sub-second. And when the asserted quantity is a **prop, not a pixel** (e.g.- `animated = enableStream && transitionMode === 'fadeIn' && isGenerating`, see- `src/features/Conversation/Messages/useChatMarkdown.tsx:43`), record it with a timestamped- debug-global (C2) in the same render: failing to film a flicker proves nothing about whether it- flickers, whereas `0ms:true โ 7386ms:false` pins the exact flip.--### D14. A blank page at `about:blank` with a 1280px viewport = the navigation never happened--- **Situation**: driving navigation through `agent-browser-klm.mjs --klm-* ... open <url>` (to- record interaction atoms). The probe afterwards reports `location.pathname === "blank"`,- `document.body.innerText.length === 0`, `innerWidth === 1280`, and a screenshot captures an- empty frame.-- **Not the cause** (verified against `agent-browser 0.26.0`): the KLM wrapper does not blank- the page โ a wrapped `open` navigates identically to a plain one โ and `open` does not reset- the viewport; a viewport set beforehand survives it.-- **What that state actually means**: the `open` exited non-zero without navigating. The- session still exists, so every later probe succeeds โ against the fresh page it was born- with: `about:blank` at the default 1280ร720 viewport. The "reset viewport" is simply a- viewport that was never set on _that_ page. One confirmed trigger is an unrecognized or- misplaced global flag (`agent-browser --session S --headless open <url>` โ- `Unknown command: --headless`, exit 1). It is **not** established that this is the only- trigger: a `--klm-command-timeout-ms` SIGKILL landing mid-navigation, or a daemon restart,- would leave the same fingerprint. Treat the fingerprint as "the navigation failed", then read- _why_ off the exit code and stderr rather than assuming a cause.-- **Works**: read the exit code, and read the error. The wrapper used to send the child's stdio- to `/dev/null`, which is what made a loud `Unknown command: โฆ` look like a silent blank page;- it now captures the output, echoes it on failure, and records a failed atom as- `category: "blocked"` with zeroed operators (so phantom work never enters the cost model).--### E12. `next dev` appends a managed block to `AGENTS.md` โ once, not every start--- **Situation**: `init-dev-env.sh dev` / `bun run dev` prints `Generated AGENTS.md for AI-agents. Set` `agentRules: false` `in next.config to disable.` and leaves the worktree dirty.-- **Mechanism** (Next.js 16,- `next/dist/esm/server/lib/{start-server,app-info-log,generate-agent-files}.js`): `next dev`- calls `ensureAgentRulesForDev(dir)`, gated three ways โ `agentRules !== false` in next.config- (the option is real: `agentRules?: boolean`, default true), `detectAgent()` returning non-null- (an AI coding agent is in the env), and the managed marker `<!-- BEGIN:nextjs-agent-rules -->`- being **absent** from `AGENTS.md` / `CLAUDE.md`. It then upserts the block into whichever file- exists. `upsertFile` compares content and reports `unchanged` without writing, so it is- idempotent: the block is appended **once**, later starts are no-ops. (Verified twice: calling- Next's own `writeAgentFiles` against a scratch project returns `updated` then `unchanged`,- byte-identical; and a real `next dev` printed the line once, after which- `hasAgentRulesInstalled(repo)` returns true.)-- **Doesn't work โ and causes the "every start" illusion**: `git checkout -- AGENTS.md` at- teardown. That strips the marker, so the very next `next dev` re-appends it. Reverting is what- makes it look like a per-start rewrite. The block's own text says so: _"Keep this block,- including in commits. โฆ If it appears as an uncommitted change, that is intentional โ commit- it as-is. Do not remove it to clean up a diff; it will be regenerated."_-- **Works**: commit the block once (Next.js's intent โ this repo has not), or opt out with- `agentRules: false` in `next.config.ts`. Either way it stops recurring. Still check- `git status` before reporting "worktree clean".--### E13. The shell's `grep` honors `.gitignore` โ "not found anywhere" can be a false negative--- **Situation**: proving a symbol/config option does not exist, e.g.- `grep -rl "agentRules" . --exclude-dir=.git` โ one hit (a doc), concluding the option is- fictional.-- **Doesn't work**: `grep` in this environment is a shell function wrapping- `ugrep --ignore-files`, which skips `.gitignore`d paths. Searching `.` therefore **silently- omits `node_modules`**. The option existed in 26 files there.-- **Works**: name the ignored directory explicitly (`grep -rl "agentRules" node_modules`), which- overrides the ignore, or call `/usr/bin/grep` directly. Before asserting "X exists nowhere",- re-run the search with an explicit path into the dependency tree.--### E25. Electron `will-attach-webview` params carry NO custom attributes โ identity via data-\* never arrives--- **Situation**: a main-process controller needs to know WHICH renderer feature a mounting- `<webview>` belongs to (e.g. a per-conversation session id), and the renderer put it in a- custom `data-*` attribute on the element.-- **Doesn't work**: reading `params['data-โฆ']` in `will-attach-webview`. Measured live: params- only contains the standard set (`instanceId, partition, src, httpreferrer, useragent,-nodeintegration, plugins, disablewebsecurity, allowpopups, preload, โฆ`). The handler silently- no-ops and โ trap โ a unit test that mocks params WITH the custom key passes green.-- **Works**: two-channel design. (1) Recognition/hardening keyed off the **`partition`- attribute** set by the renderer (it IS forwarded); (2) identity bound after mount via an- explicit IPC โ renderer listens for the webview's `dom-ready`, calls- `attach({ sessionId, webContentsId: el.getWebContentsId() })`, main process- `webContents.fromId()` + validates the guest's session belongs to the expected partition.--### E16. agent-browser session silently re-targets to a newly created `<webview>` guest--- **Situation**: driving an Electron app over CDP while the app itself spawns a `<webview>`- (in-app browser). After the guest mounts, `eval` on the SAME session suddenly returns the- guest page's DOM (`__LOBE_STORES` undefined, app selectors empty) โ looks like the app broke.-- **Doesn't work**: assuming a session stays pinned to the app target; also assuming- `document.querySelectorAll('webview').length === 0` means "no webview" (you may be evaluating- INSIDE the guest).-- **Works**: `curl -s localhost:<cdp>/json/list` to see targets (`page` = app, `webview` =- guest), then use **separate session names** per target (`--session app-x` re-picks the `page`- target; the old session keeps following the guest โ handy for driving the embedded page).- Verify with `get url` (`app://` vs the site URL) before trusting any eval result.--### E17. Dev-mode main-process `logger.warn/debug` is invisible without DEBUG env โ probe with console.log--- **Situation**: adding a temporary probe log in Electron main code and watching the dev- instance log; nothing prints, which reads as "code path never runs".-- **Doesn't work**: `createLogger(ns).warn/debug` in development โ it routes to the `debug`- package, which is silent unless `DEBUG=<ns>` was set when the process started.-- **Works**: temporary probes use `console.log('[AGENT-TEST] โฆ')` (always reaches the instance- log via stdout); confirm the rebuilt bundle actually contains the probe string- (`grep "<probe>" apps/desktop/dist/main/index.js`) before interpreting silence.--### D15. Host-page CDP screenshot renders the `<webview>` region BLACK intermittently โ guest DOM eval is ground truth--- **Situation**: capturing evidence of an Electron in-app browser (`<webview>` in a sidebar).- Early `Page.captureScreenshot` shots of the host page included the guest's pixels; minutes- later the same command on the same target returned the webview region uniformly black- (byte-identical output across retries), while the app chrome around it rendered fine.-- **Doesn't work**: concluding the embedded page went blank/failed from the host screenshot,- or retrying the host capture. The guest was healthy the whole time: an `agent-browser`- session following the webview target (E16) read `document.title` = the expected page and- full body text.-- **Works**: treat the guest target as the source of truth โ eval `title`/`innerText` in the- webview target for the assertion, and capture the guest's own pixels via a session pinned- to the `webview` target (`agent-browser screenshot` there) when the embedded page's visual- matters. Use host-page screenshots only for the app chrome around the webview. Cause of the- black compositing not established (OOPIF surface not composited into the host capture).--### E18. Cloud-connected desktop routes even `local` agents to the SERVER runtime โ force client with `disableGatewayMode`--- **Situation**: verifying a **client-only** builtin tool (`executors: ['client']`) via a real agent turn on the desktop. The agent's `executionTarget` is `local` and the tool-enable gate (`isLocalSystemEnabled` = runtime `local`) passes, so it _looks_ like it will run client-side.-- **Doesn't work**: sending the message as-is. On a cloud-connected desktop, gateway mode is on by default, so the run dispatches to `execServerAgentRuntime` (server/queue path) even for a `local` agent. The client-only tool isn't executable there โ the model flails and returns a non-answer (e.g. "browser closed") with no real tool effect. Confirm the path by reading the running op's `type` in `window.__LOBE_STORES.chat().operations` (`execServerAgentRuntime` = server; `executeToolCall` = client).-- **Works**: set the agent's `chatConfig.disableGatewayMode = true` (via `agentStore.updateAgentChatConfigById(id, { disableGatewayMode: true })`) before sending. The run then goes through `executeToolCall` (client runtime); the composer's runtime chip flips to "Local device" and the client executor runs. The gate (`isLocalSystemEnabled`) and the transport (`disableGatewayMode`) are INDEPENDENT โ enabling the tool does not force client execution.--### E19. Desktop has no classic session store โ reconfigure the existing agent, don't `createSession`--- **Situation**: wanting a throwaway agent for a real-turn test without polluting the user's agent.-- **Doesn't work**: `sessionStore.createSession({...})` โ the desktop app doesn't use the classic session store (`sessions` is `[]`, `activeId` is `'inbox'`); agents are a server-backed model in `agentStore.agentMap` keyed by `agt_...`. The created session never becomes the active agent.-- **Works**: back up the active agent's full config (`model`, `provider`, `agencyConfig`, relevant `chatConfig`), reconfigure it in place (`updateAgentConfigById` + `updateAgentChatConfigById`), run the test, then restore every field and clear any injected key-vault entry. Also: `chat.sendMessage` requires `context: { agentId, topicId, isNew }` or it throws `Cannot destructure property 'agentId' of 'context'`. Reads right after an `updateAgent*` can be stale โ re-read after \~1.5s to confirm persistence.--### C7. DB-seeded task rows need a `task_`-prefixed id or `resolve()` silently misses them--- **Situation**: seeding a `tasks` row directly in SQL for a router probe, with a- hand-written id like `tsk_foo`, then calling a task procedure โ it 404s- ("Task not found") even though the row exists and the caller is a member.-- **Doesn't work**: any id not starting with `task_`. `TaskModel.resolve()`- (`packages/database/src/models/task.ts:220-223`) only treats the input as a row- id when it starts with `task_`; everything else is upper-cased and looked up as- a workspace `identifier` (e.g. `T-1`), so `tsk_foo` becomes the identifier- lookup `TSK_FOO` โ null.-- **Works**: use the idGenerator prefix (`task_<suffix>`) for seeded ids, or pass- the row's `identifier` (`T-<seq>`) to the procedure instead.--### F1. Seeding a shared topic by raw SQL: messages MUST carry `agent_id`, or the share page renders skeletons forever--- **Situation**: fixture-seeding a `/share/t/<id>` page (topics + messages + `topic_shares`- rows inserted directly). `share.getSharedTopic` returns fine, but the message list stays on- skeletons; `message.getMessages` with `topicShareId` returns `[]`.-- **Cause**: the client passes `agentId` in the query context and `MessageModel.query` filters- on it โ messages inserted with `agent_id` NULL are silently excluded (no error anywhere).-- **Works**: set `agent_id` on every seeded message row (matching the topic's `agent_id`).- Probe the endpoint directly before blaming the UI:- `/trpc/lambda/message.getMessages?input={"json":{"topicId":..,"topicShareId":..,"agentId":..}}`.--### F2. Seeded share topics also need `topics.agent_id`, or the client never fires the message fetch--- **Situation**: same setup as F1, but the failure is one layer earlier โ metadata (title)- renders while `message.getMessages` never even appears in network requests.-- **Doesn't work**: assuming the fetch failed โ it was never fired. `useFetchMessages`- gates on `!!context.agentId && !!context.topicId`- (`src/store/chat/slices/message/actions/query.ts:268`), and the share page passes- `agentId: data.agentId ?? ''` โ a topic seeded without `agent_id` yields `''` โ SWR key- is null โ no request, silent skeleton (a Case-1 lookalike with no error anywhere).-- **Works**: seed an `agents` row and set `topics.agent_id` (and `messages.agent_id`)- before opening the share page. Verify the fetch actually fired via- `agent-browser network requests | grep getMessages`, not by waiting on the UI.--### E26. โ Next dev does NOT hot-reload `apps/server/**` โ you are testing STALE compiled server code--- **Situation**: verifying a working-tree change inside `apps/server/src/**` (an agent-runtime- service, a tool executor, a router) against a `bun run dev` server that was started before the- edit. The app behaves normally, the feature simply does nothing.-- **Doesn't work**: assuming HMR covers it because `@/server/*` maps to `apps/server/src/*` in- `tsconfig.json` (source, no `dist`), so it "should" recompile. It does not, at least for large- service files. Measured: a `console.error` added at the top of a code path that demonstrably ran- (child ops were created, the DB rows appeared) printed **zero** lines across four separate runs;- after a dev-server restart, the same line printed on the first run. The whole feature under test- had never executed once.-- **Why this is a trap and not a nuisance**: the failure mode is silent and looks exactly like a- logic bug. You will go hunting in your own diff for a fault that is not there.-- **Works**: after ANY edit under `apps/server/**`, restart the dev server before drawing a- conclusion. If a run "should" have hit your code and didn't, prove the server is running your- code FIRST โ drop a `console.error` on the path and restart โ before debugging the code itself.--### E27. โ `source`-ing an unquoted JSON env var silently corrupts it (JWKS\_KEY โ gateway auth\_failed)--- **Situation**: writing an env file for the local gateway loop with- `JWKS_KEY={"keys":[{"kty":"RSA",...}]}` on one line, then `set -a; source that-file`.-- **Doesn't work**: the shell strips every double quote from an unquoted assignment, so the process- receives `{keys:[{kty:RSA,...}]}` โ invalid JSON. `getJwksKey()` (`packages/trpc/src/utils/internalJwt.ts:13-20`)- throws on `JSON.parse`, `signUserJWT` throws, and the server hands the client an **empty** gateway- token. The browser sends `{"token":"","type":"auth"}` and the gateway answers `auth_failed`.-- **What makes it genuinely deceptive**: `local-gateway-setup.sh` and `local-gateway-probe.mjs` read- `JWKS_KEY` out of the file with a **regex**, not by sourcing it โ so both are unaffected. The probe- cheerfully prints `โ auth_success` while the real browser path is broken. A green probe is NOT- evidence the app's own token works.-- **Works**: single-quote the value in the env file (`export JWKS_KEY='{"keys":[...]}'`) and prove the- round-trip before starting the server:- ```bash- (source env-file && node -e 'JSON.parse(process.env.JWKS_KEY); console.log("ok")')- ```- To diagnose an `auth_failed`, hook `ws.send` in the page and read the token the client actually- sends โ an empty string means the SERVER failed to sign, not that the gateway rejected a signature.--### E28. The chat input silently refuses to send when the agent's model is retired--- **Situation**: driving a real turn (store `sendMessage` or type+Enter). The call resolves, no error- is thrown, `activeTopicId` stays `null`, and no `agent_operations` row appears. Nothing in the dev- server log โ the request is never even issued.-- **Cause**: the composer shows a small inline warning ("ๅฝๅๆจกๅๅทฒไธ็บฟใ่ฏท้ๆฉๅ ถไปๆจกๅๅ็ปง็ปญไฝฟ็จใ")- and disables send. A model id that was valid a while ago (e.g. `deepseek-chat`) can be retired from- the model bank while the agent row still points at it.-- **Works**: read the actually-enabled models out of the store before configuring a fixture agent โ- `window.__LOBE_STORES.aiInfra().enabledChatModelList` โ `[{id: provider, children: [{id: model}]}]` โ- and pick one from there. Also: a send that "resolves fine but creates no operation" is a UI-gate- symptom; **screenshot the composer** instead of re-reading your store call.--### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` โ NODE\_PATH into .pnpm fixes it--- **Situation**: in a fresh git-worktree install, `init-dev-env.sh seed-user`- (which runs `node <<'NODE'` from the repo root) throws MODULE\_NOT\_FOUND for- `bcryptjs`, even though `pnpm install` succeeded.-- **Cause not fully established**: `bcryptjs` exists in `node_modules/.pnpm/`- but is not linked at the repo-root `node_modules` top level in that install- (`pg` was linked, `bcryptjs` wasn't), so a root-cwd stdin script can't- resolve it.-- **Works**: prefix the call with- `NODE_PATH="$PWD/node_modules/.pnpm/bcryptjs@<ver>/node_modules"` (check the- exact version dir first). CJS stdin scripts honor NODE\_PATH; seeding then- completes normally.-- Same run also (re)confirmed: `init-dev-env.sh dev` ports are DYNAMIC (e.g.- next on 33803, vite on 32459) โ never hardcode 3010; re-run- `scripts/test-env.sh` after the server is up, it reads the ports-file. And- the `os error 35` agent-browser daemon wedge (D8) recovers with- `agent-browser close --all` + re-running `setup-auth.sh web-seed`.--### C10. `document.body.innerText` is ALWAYS 0 in this app โ probe `#root`, and use textContent to tell a wedge from a blank--- **Situation**: asserting rendered text with `document.body.innerText.includes(...)`. It returns `""` / length 0 even on a fully rendered page, so every text assertion silently fails and reads as "the page is blank".-- **Works**: probe `document.getElementById('root').innerText`. (Cause not established โ some ancestor of `#root` makes body's inner-text computation collapse; `#root` itself is fine.)-- **Bonus diagnostic**: `innerText` needs layout, `textContent` does not. When `#root` gives `innerText === 0` but `textContent > 0`, the DOM is fine and the RENDERER is not painting (see D16) โ as opposed to a genuinely empty DOM, where both are 0.--### D16. Electron renderer compositor wedges after a mid-session Vite dep re-optimize โ restart the instance--- **Situation**: partway through a long Electron run the app stops painting: `cdp-screenshot.sh` returns `CAPTURED BUT BLACK`, `#root` `innerText` is 0 while `textContent` still holds the full DOM, and `document.visibilityState` reports `visible` with real `innerWidth/innerHeight`.-- **Not the cause**: display sleep or Screen Recording permission (`check-screen-recording.sh` passes), and the window is not hidden โ CDP capture would survive both (D9/D10).-- **What precedes it**: the instance log shows Vite re-optimizing (`[vite] Re-optimizing dependencies because vite config has changed`) followed by `Failed to fetch dynamically imported module: .../node_modules/.vite/deps/โฆ`. The renderer keeps its DOM but never composites another frame.-- **Works**: `electron-dev.sh restart <id>`. `location.reload()` alone does NOT clear it. Login survives the restart (the userData dir is kept).--### D17. Virtua message lists: driving `scrollTop` by hand blanks the conversation pane โ use a SMALL fixture instead--- **Situation**: hunting one specific message in a long imported conversation (400+ messages). Stepping `scrollContainer.scrollTop` in a loop to bring it into the virtualizer's window.-- **Doesn't work**: the virtualizer unmounts the node as you scroll past it (a `TreeWalker` search then reports "not found" on a node that was there a second ago), and forcing `scrollTop` far outside the rendered window leaves the pane **completely blank** โ the scroll container itself disappears from the DOM, which reads exactly like a render bug.-- **Works**: pick a fixture with few messages so the target is on the first screen (for transcript-import tests: scan the corpus for a session with < \~15 messages that still has the feature under test). Cheaper and far more reliable than fighting the virtualizer.--### D18. React controlled checkboxes ignore synthetic MouseEvents โ use `agent-browser click <ref>` (trusted CDP input)--- **Situation**: selecting a row in a modal list. `el.click()`, and even a full `pointerdown/mousedown/pointerup/mouseup/click` `dispatchEvent` sequence with correct coordinates, leave `checked === false` and the footer's primary button disabled.-- **Cause**: the value is React-controlled; synthetic events are `isTrusted: false` and the component's state never updates.-- **Works**: `agent-browser snapshot -i` for the ref, then `agent-browser click <ref>` โ it goes through CDP `Input.dispatchMouseEvent`, which the page sees as a real user click. The same snapshot also tells you when a row is `[disabled]` (i.e. the app is deliberately refusing the selection), which a coordinate-click would never reveal.--### E20. Killing the dev server mid-write corrupts `.next/dev` โ every route 404s and `/` โ `/signin` ping-pong--- **Situation**: after `init-dev-env.sh clean` (or any kill) and a restart, the whole app is broken: `/` 302s to `/signin`, `/signin` 307s back to `/` (`ERR_TOO_MANY_REDIRECTS` in the browser, `redirect count exceeded` in the dev server's own prewarm), and even API routes like `/api/auth/sign-in/email` return the app-router not-found. It looks like an auth/OIDC misconfiguration.-- **Cause**: a corrupt Turbopack build in `.next/dev` โ the route manifest is gone, so every path falls through to `GlobalNotFound`, whose redirect collides with the middleware's.-- **Works**: `rm -rf .next` then restart. Diagnose it in one step: if `/signin` does not return 200, the routes are not compiled โ stop debugging auth.--### E21. โ WORKS โ a QStash-protected workflow endpoint can't be curl'd; publish through local QStash to get a signed delivery--- **Situation**: driving a cron-style workflow handler under `/api/workflows/**` (e.g. a dispatcher you want to fire on demand instead of waiting for its schedule).-- **Doesn't work**: `curl -X POST <app>/api/workflows/<...>` โ `{"error":"Invalid signature"}` / HTTP 401. The `qstashAuth` middleware verifies the Upstash signature whenever `QSTASH_CURRENT_SIGNING_KEY` is set โ and `init-dev-env.sh` exports it, so the local env DOES verify. (Do not "fix" this by unsetting the key: you would then be testing an unauthenticated path that production doesn't have.)-- **Works**: start local QStash (`init-dev-env.sh qstash`) and publish to the endpoint with the QStash client โ QStash signs the delivery, so the handler sees exactly the production shape:- ```ts- // must live INSIDE the repo (a script under /tmp cannot resolve @upstash/qstash)- import { Client } from '@upstash/qstash';- const client = new Client({ baseUrl: process.env.QSTASH_URL!, token: process.env.QSTASH_TOKEN! });- await client.publishJSON({- body: { dryRun: false },- url: `${process.env.APP_URL}/api/workflows/<path>`,- });- ```- Run it with `eval "$(init-dev-env.sh env)" && bunx tsx ./scripts/<probe>.mts`, then read the outcome from **DB side effects**, not the HTTP body โ QStash swallows the response. (A claim/lease row, a status transition, or new message rows are all observable; the handler's JSON return is not.)-- **Time-travel a schedule instead of waiting**: for a "runs at T" feature, `UPDATE ... SET metadata = jsonb_set(metadata, '{...,runAt}', '"<past ISO>"')` and then fire the dispatcher. Cheaper and more deterministic than sleeping until the real due time.--### E22. Local dev env has no `JWKS_KEY` โ every hetero agent run dies at `signOperationJwt`--- **Situation**: a real Claude Code / Codex run in the local no-`.env` env fails immediately with `Failed to sign operation JWT for hetero agent` (`apps/server/src/services/aiAgent/index.ts`). Nothing in the UI explains it; the topic just fails.-- **Cause**: `signOperationJwt` โ `getSigningKey()` โ `getJwksKey()` needs the `JWKS_KEY` RSA JWK, and `init-dev-env.sh` does not export one.-- **Works**: the repo ships a generator โ `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.-- **Note the failure is downstream-honest**: with `JWKS_KEY` set, the run proceeds and then fails at the hetero _sandbox_ (`Hetero sandbox spawn failed / unauthorized`) unless the agent has a real Claude Code token. Those are two different walls โ don't read the second as the first.--### D19. A hidden zero-size duplicate of the composer sits at (0,0) โ `querySelector` grabs IT, not the visible one--- **Situation**: driving the chat composer. `document.querySelector('[contenteditable]')` reads back `""` right after a successful `fill`, and `svg.lucide-plus` โ `.closest('button')` resolves to a button whose click does nothing.-- **Cause (measured, not guessed)**: the page renders a SECOND, hidden copy of the composer subtree at `x:0, y:0, width:0` โ including its own contenteditable and its own action-bar buttons. It is first in DOM order, so every `querySelector` singular lookup picks the phantom. The real one is the second match. Cause of the duplicate not established (likely a measurement/offscreen render), but the fingerprint is unambiguous: a `getBoundingClientRect()` of all-zeros.-- **Doesn't work**: `document.querySelector('[contenteditable]')`, `document.querySelector('svg.lucide-plus')` โ both silently target the phantom. A `fill` that reports `โ Done` can still leave the visible box empty-looking, and a click on the phantom button is a no-op with no error. This burned a full round chasing a "menu won't open" regression that did not exist.-- **Works โ always disambiguate by geometry or by an identifying attribute**:- ```js- // enumerate, never singular-select- [...document.querySelectorAll('[contenteditable]')]- .filter(e => e.getBoundingClientRect().width > 0)[0]- // or target by the component's own aria-label (survives DOM order)- [...document.querySelectorAll('[role=button],button')]- .find(b => b.getAttribute('aria-label') === '<the tooltip text>')- ```- Tag the resolved element with a `data-probe` attribute and drive it with `agent-browser click '[data-probe=...]'` (trusted CDP input, D18).-- **Corollary**: the phantom also owns the tooltip text of whatever component it duplicates, so an `innerText`/aria grep can "find" a control that the user cannot see. Assert on `getBoundingClientRect()` before believing a control is present.--### C8. โ An agent-browser session can silently LOSE its seeded cookies โ a 401, not `document.cookie`, is the signal--- **Situation**: verifying an owner-only affordance (a link the server renders only for the- report's author). The page rendered without it, and the bundle came back `isOwner: false`- even though the row's `userId` matched the seeded user โ which reads exactly like a bug in- the ownership check.-- **Doesn't work**: `document.cookie` as the auth probe. Better Auth's session cookie is- **httpOnly**, so `document.cookie` is legitimately `[]` on a fully authenticated page โ- `cookieCount: 0` proves nothing either way.-- **Doesn't work**: trusting `setup-auth.sh web-seed`'s success line for the rest of the run.- It verified the session at `/`; the session can still be empty later (this run's page had- also drifted to `about:blank` at one point โ see D14).-- **Works**: probe the SERVER, not the document โ call any authed procedure from the page and- read the status. `401` = no session reached the server; `200` = you are really signed in.- ```js- const r = await fetch(- base +- '/trpc/lambda/user.getUserState?input=' +- encodeURIComponent(JSON.stringify({ json: {} })),- { credentials: 'include' },- );- r.status; // 401 โ re-seed; 200 โ the session is live- ```- Recover with `agent-browser close --all` + `setup-auth.sh web-seed`, then re-open the route.- After re-seeding, the same bundle returned `isOwner: true` with the owner-only link rendered โ- the code was correct all along.-- **Why it matters**: an auth-scoped assertion (owner-only / permission-gated UI) fails- IDENTICALLY whether the gate is broken or the session is missing. Always establish that the- session is live (a 200 from an authed procedure) BEFORE concluding the gate is wrong โ- otherwise you publish a false bug against your own change.--### E23. In zsh, a loop variable named `path` overwrites the command search path--- **Situation**: parsing a Netscape cookie jar with `while read ... path ...` and then invoking- browser commands inside the loop. The first iteration succeeds at assigning the fields, but the- next executable fails with `command not found`.-- **Cause**: zsh exposes `path` as a special array tied to `PATH`; assigning the cookie path field- (usually `/`) replaces the process command search path.-- **Works**: name the field `cookie_path` (and similarly avoid other zsh special parameter names),- then pass it to the cookie command. This is a shell failure, not an auth or browser failure.--### E24. Vite throws `EMFILE` โ terminate Agent Testing and ask the user for help--- **Situation**: an isolated frontend-only Vite surface exits at startup with `EMFILE: too many open files, watch`, while the intended port is free and the shell can successfully create thousands of `fs.watch` handles in a control process.-- **Likely causes (not established)**: multiple LobeHub Cloud worktrees or clones are running file watchers; or a previously used workspace still has watchers owned by a surviving terminal process or a VS Code window, even after its visible terminal was closed.-- **Required action**: immediately terminate Agent Testing, report the observed `EMFILE`, and ask the user to inspect and clean up other worktrees, terminal processes, or VS Code windows. Do not kill user-owned processes, close editor windows, change Vite watch mode, fall back to a one-shot static build, or publish a Verify report from a degraded surface.--### D20. โ Main-process `WebContentsView` pages are their own CDP page targets โ they hijack target selection, AND they are the best pool probe--- **Situation**: verifying an in-app browser whose pages are owned by the MAIN process as- `WebContentsView`s (not renderer `<webview>` guests โ that is E16/D15, a different shape).-- **Doesn't work**: assuming any tool that "just connects to the CDP port" lands on the app.- Every live page shows up in `/json/list` as its own `type: page` target, so both- `agent-browser` and `scripts/cdp-screenshot.sh` can silently attach to a _web page the app- is hosting_ instead of the app itself. Measured: `cdp-screenshot.sh` reported- `targetUrl: https://example.com/` and wrote that page's pixels while the intended evidence- was the app window; an `agent-browser get url` on the same port hung.-- **Works โ pin the target by URL prefix.** Raw CDP, pick the target whose `url` starts with- `app://renderer`, and evaluate against that:- ```js- const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();- const target = list.find((t) => t.type === 'page' && t.url.startsWith('app://renderer'));- new WebSocket(target.webSocketDebuggerUrl); // โ Runtime.evaluate- ```-- **Works โ the same property is the cheapest page-pool probe there is.** One live page ==- one `page` target, so `/json/list` filtered to non-`app://` URLs _is_ the pool's contents.- Use it to assert per-session isolation (N sessions โ N coexisting pages, and a page that- should have survived an action is still listed) without adding any IPC or store probe:- ```bash- curl -s --noproxy '*' http://127.0.0.1: < cdp > /json/list \- | python3 -c "import json,sys; print([t['url'] for t in json.load(sys.stdin) if t['type']=='page'])"- ```-- **Pixels still need an OS capture.** A `WebContentsView` does not composite into the host- page's `Page.captureScreenshot`, so app-window evidence that must _show the embedded page_- has to come from `capture-app-window.sh` (macOS `screencapture -l <windowid>`), which does- not require bringing the window to the front.--### C9. A component-scoped "consumed" ref is not a one-shot guard once the component can remount--- **Situation**: a persisted store field carries a one-shot request (`{ nonce, url }`) and the- consuming component guards against re-consumption with a `useRef` holding the last nonce.-- **Why it silently breaks**: the ref dies with the component. Any change that starts remounting- the consumer (e.g. giving it a `key` that now varies per topic/session) resurrects the guard as- `undefined`, so a request that is still sitting in _persisted_ state is re-consumed on every- remount โ and, on a fresh boot, once more. The symptom looks nothing like the cause: a page the- agent had just loaded gets navigated to a URL from days ago.-- **Works**: retire the request in the store the moment it is consumed, so the one-shot is one-shot- across mounts and restarts. Watch the merge semantics โ if the store patches with lodash `merge`,- clearing with `undefined` is a **no-op** and the field must be set to `null`.-- **Test for it**: assert the field is `null` (not `undefined`) after the consume action; a test that- only checks "the request was acted on" passes in both the broken and fixed versions.--### E30. โ "Failed to fetch dynamically imported module" points at the WRONG file โ the failure is downstream--- **Situation**: the SPA renders as a Case-1 blank page; console names a dynamic-import route module.-- **Doesn't work**: investigating only the named module. It may return 200 because the actual failure- is in its transitive import graph; changing `?t=` values are ordinary HMR invalidation.-- **Works**: take and read a screenshot. Vite's HMR overlay contains the real transform/import error.- After a rebase or pull, refresh dependencies and restart before treating the blank SPA as a code bug.--### C11. Persisted SWR cache serves a STALE agent config after a direct DB write--- **Situation**: seeding `agents.agency_config` or `agents.model` directly in Postgres, then using- the app to drive an assertion.-- **Doesn't work**: reload or `internal_refreshAgentConfig`; IndexedDB/localStorage can retain the- previous config and make a fixture issue look like a product regression.-- **Works**: cold-load by clearing browser storage/caches, re-seed auth, reopen, and assert the- fixture in `__LOBE_STORES.agent().agentMap[id]` before testing downstream behavior.--### E31. Web agent turns run the CLIENT runtime โ no `agent_operations` row will appear--- **Situation**: driving a real web turn and polling `agent_operations` for the run.-- **Doesn't work**: waiting for a server operation when the web surface dispatched the client runtime.-- **Works**: use client observables (`messages.model`, thread ids, and chat-store operations) for web;- use CLI/server execution and `agent_operations` for the server runtime. A change affecting both paths- needs evidence from both paths.--### E32. โ WORKS โ driving `heteroIngest`/`heteroFinish` directly needs an OIDC token, and bun's spawn-ENOENT message differs from node's--- **Situation**: E2E-testing the hetero server-ingest chain by running `lh hetero exec --topic <t> --operation-id <op>` manually (the exact command a device daemon spawns), against a local dev- server, with the seeded CLI API key.-- **Doesn't work**: the seeded `LOBE_API_KEY`. `heteroAuthedProcedure` requires `ctx.oidcAuth`- (`packages/trpc/src/lambda/middleware/heteroOperationAuth.ts`) โ an API key never populates it, so- `heteroFinish` 401s. Also note the local no-`.env` env has no `JWKS_KEY` (E22), so the server- cannot even validate a JWT until restarted with one.-- **Works** โ production-shape auth in three steps:- 1. `node scripts/generate-oidc-jwk.mjs > /tmp/jwks.json`- 2. restart the dev server with `JWKS_KEY="$(cat /tmp/jwks.json)"` (must be present at start)- 3. sign a 4h `hetero-operation` JWT with the SAME key via `signOperationJwt(<userId>)`- (`packages/trpc/src/utils/internalJwt.ts`; run a small `.mts` inside the repo with `bunx tsx`),- then run the CLI with `LOBEHUB_JWT=<token> LOBEHUB_SERVER=<app-url>` โ the CLI forwards it as- the `Oidc-Auth` header.- The fixture side needs `topics.metadata.runningOperation = { operationId, assistantMessageId }`- seeded, and the operationId must embed real ids (`op_<ts>_agt_<id>_tpc_<id>_<suffix>`).-- **Bonus trap**: under bun, a spawn failure reads `ENOENT: no such file or directory,-posix_spawn '<cmd>'` โ NOT node's `spawn <cmd> ENOENT`. Any stderr-text pattern keyed to the node- format silently misses on bun; classification/assertions should key on the raw error's- `err.code === 'ENOENT'` (runtime-agnostic) and treat text matching as fallback only.-- **Persistence shape worth knowing**: a process-level failure that produced ZERO stream events- never creates op state, so `HeterogeneousPersistenceHandler.finish` early-returns โ the message- error is written by `CompletionLifecycle.completeOperation`'s onError branch instead- (`body: messageError.body ?? { message }`). Assert on `messages.error`, not on which writer ran.--### E33. โ WORKS โ keep the Electron supervisor session alive in process-reaping runners--- **Situation**: `electron-dev.sh start <id>` reports `Ready`, but CDP and the Vite port disappear- immediately after the shell command returns. The Electron log contains no crash or product error.-- **Doesn't work**: repeatedly restarting and treating the vanished CDP endpoint as an app crash.-- **Works**: keep the launcher shell alive for the test session (for example, run `start` followed by- a short periodic wait loop in the same PTY), drive CDP from a second shell, then stop with- `electron-dev.sh stop <id>` and terminate the holder. Some execution harnesses reap descendants when- the command cell closes even though the launcher normally survives an interactive terminal.--### F3. โ WORKS โ render the `/verify-im` messenger bind SUCCESS state without a real platform token--- **Situation**: verifying the messenger verify page's success card (`SuccessCard`) for- Telegram/Slack/Discord. A real bind needs a live bot issuing a `random_id` link token โ- unavailable in an isolated env.-- **Works**: take the page's own refresh-after-link path instead. With a signed-in user, seed- (1) a `messenger_account_links` row for (user, platform, tenant\_id='') and (2) an enabled- `system_bot_providers` row for the platform โ `credentials` must be encrypted with- `KeyVaultsGateKeeper.initWithEnvKey()` (same `KEY_VAULTS_SECRET` as the dev server), e.g.- telegram `{ botToken, botUsername }`. Then open- `/verify-im?random_id=<anything>&im_type=<platform>`: the peek-token query fails, but the- existing-link lookup succeeds and the page falls through to the real success card- (`shouldShowSingleAccountSuccess` โ existing link + no active token โ success).-- `botUsername` drives the "Open in <platform>" deep-link CTA; re-encrypt the credentials- WITHOUT it to exercise the no-deep-link fallback. Note the platform config is cached- in-process for 30s (`packages/app-config/src/messenger.ts` CACHE\_TTL\_MS) โ wait out the TTL- after editing the row before reloading.-- Locale for evidence shots: `window.__LOBE_STORES.global().switchLocale('zh-CN')` then reload.--### D21. โ WORKS โ when `click @ref` reports Done but the React onClick never fires, click via `eval` `element.click()`--**Situation**: on a dense list row (acceptance check rows with hover-revealed ActionIcons and-expanded-area buttons), `agent-browser click @ref` returned `โ Done` but no TRPC mutation fired and-no state changed โ the pointer click seemingly landed on an overlaying/other element. Repeated for-both hover icons and regular buttons inside the row.--**Doesn't work**: re-snapshotting and clicking the fresh `@ref`; the command still reports success-with no effect (so the failure is silent โ always verify the click by its observable side effect,-e.g. the network request or a DB row, never by the driver's `Done`).--**Works**: locate the element in-page and call the DOM `element.click()` via `eval` โ React's-synthetic onClick fires reliably:--```bash-agent-browser --session "(()=>{const b=[...document.querySelectorAll('button')]- .find(x=>x.textContent.trim()==='<label>'); b.click(); return 'clicked'})()" < s > eval-```--Scope the query to the intended row/container first (climb from a unique text node, stop before the-ancestor contains other rows' text) โ a page-wide `find(...)` picks the FIRST match and can submit-an action against the wrong row. For drag interactions (annotation canvases), dispatch synthetic-`MouseEvent`s (`mousedown/mousemove/mouseup` with `bubbles:true` and computed `clientX/Y`) on the-target element.--### E34. Shell proxy env (HTTP\_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops--**Situation**: `init-dev-env.sh dev` launched from a shell where a system proxy (Clash etc.) exported-`HTTP_PROXY`/`HTTPS_PROXY`. The server booted fine, pages served, but `POST /api/auth/sign-in/email`-returned a bare `307 โ /` with NO `set-cookie` (body = Next `__next_error__` page), the boot prewarm-logged `redirect count exceeded`, and `setup-auth.sh web-seed` failed with "sign-in succeeded but no-cookies were written" (307 matches its `^[23]` success check).--**Doesn't work**: retrying the seed, restarting the agent-browser daemon โ the failure is in the-server process env, not the client.--**Works**: strip proxy vars when starting the dev server:--```bash-env -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy -u ALL_PROXY -u all_proxy \- -u NO_PROXY -u no_proxy ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-```--Symptom fingerprint: every auth POST answers 307 in \~25ms with `application-code` time present, and-the prewarm warning mentions `redirect count exceeded`.--### C12. A globally installed `lh` ingest-report can silently create an ORPHAN verify run (no acceptance attach) when the branch's CLI contract is newer--- **Situation**: publishing/ingesting a report while verifying a branch that extends the verify CLI- (e.g. adds `--subject` / acceptance attach). The global `lh` accepted the report, returned a- `verifyRunId`, and printed no error โ but the run's `acceptance_id` was NULL, so it never appeared- on the acceptance page, which reads as "my ingest didn't show up / the page is stale".-- **Doesn't work**: trusting a green `verifyRunId` from the global CLI as proof of attachment, or- passing `--subject` to it (`error: unknown option '--subject'` is the tell that it predates the- branch contract).-- **Works**: run the branch's own CLI from the worktree โ `cd apps/cli && bun src/index.ts verify-ingest-report <dir> --subject topic:<id> โฆ` โ and verify attachment in the DB- (`select acceptance_id from verify_runs where id='<runId>'`) before driving the UI against it.--### D22. โ WORKS โ driving the manual-approval intervention chain (ๆนๅ / ๆไบค cards) in web chat--- **Situation**: a real agent turn under the default manual-approval mode stops at an- intervention card (`lobe-activator โ ๆฟๆดปๅทฅๅ ท`, `Task Tools โ createTask`, โฆ) after EVERY tool- call. `snapshot -i` does not reliably expose the card's option rows / submit button as refs,- and one turn can chain 4โ5 sequential interventions โ a fixed approve-once script stalls.-- **Doesn't work**: matching the option row by exact text `ๆนๅ` (the row nests the label; the- filtered element list often misses it), or assuming one approval finishes the turn.-- **Works**: the "approve" option is pre-selected by default, so clicking the card's **ๆไบค**- button alone approves. Loop until quiescent: each round, find the LAST visible element whose- text includes `ๆไบค` via `eval`, tag it `data-probe`, click through agent-browser (trusted- input), then poll `chat().operations` for zero `running` AND no remaining ๆไบค button before- declaring the turn done. Log which tool each round approved by grabbing the last visible- `โฆ โ โฆ` header text. One creation turn (activate + createTask + setTaskVerify + runTask)- took 5 approvals.-- **Also measured (fixture note)**: a task's verify requirement is visible to the RUNNER agent,- which will optimize toward the acceptance criteria (a "200 ๅญ๏ผno code" instruction with a- "โฅ1500 ๅญ + Python code" requirement produced a 3.5k-char deliverable) โ a contradictory-criteria- fixture still fails verification, but not for the reason you scripted; assert on the verifier's- recorded rationale, not on your intended contradiction.--### E35. A listening port is NOT the product under test โ another project's dev server can own it--- **Situation**: `.env` says `PORT=<n>`, something answers on `<n>`, and a prior session recorded- "dev server running on `<n>`" โ so the run plans a mere restart.-- **Doesn't work**: trusting liveness (an HTTP response, an open socket) as identity. A sibling- project's dev server started on the same port responds happily; every request then exercises the- wrong codebase, and hook/DB assertions fail in ways that read as product bugs.-- **Works**: fingerprint the app before using it: `ps -o command= -p <pid>` of the listener shows the- repo path in the `next dev`/`node` command line, and an unauthenticated `GET /` redirect is a- cheap signature (this repo's better-auth redirects to `/signin`; a Clerk app redirects to- `/login` with `x-clerk-*` headers). If it is the wrong app, free the port and start the right- server โ and re-verify with the same fingerprint after boot.--### C13. better-auth email-verification cannot be completed from the outside โ treat real-mail paths as blocked--- **Situation**: an assertion requires a REAL email-verification event (e.g. a hook that only fires- on better-auth verification routes), and the test inbox does not exist.-- **Doesn't work**: recovering the token from the database. The `/verify-email` link token is a- signed JWT that is never stored; the email-otp OTP did not appear in the `verifications` table- either (only unrelated OIDC rows), and the send endpoint returns `{"success":true}` regardless.- Flipping `email_verified` in the DB is a fixture, not a verification โ route-gated hooks- correctly ignore it (which is itself a useful negative check).-- **Works**: mark the case `blocked` and cover the path with unit tests, or run the flow with a- real receivable mailbox (staging/prod smoke). Use the DB flip only to unblock downstream- fixtures, and assert it does NOT produce the event as a bonus authenticity check.--### E36. Desktop main-process `logger.info` is invisible in dev without `DEBUG`--- **Situation**: verifying desktop main-process behavior (e.g. perf probes in a manager/module) by- reading the dev log.-- **Doesn't work**: expecting `createLogger(ns).info(...)` lines in `/tmp/electron-dev.log` from a- plain dev start โ in dev (`app.isPackaged` false) `info` only goes through the `debug` package,- which is silent unless its namespace is enabled.-- **Works**: start the instance with the namespace enabled, e.g.- `DEBUG="screenCapture:*" electron-dev.sh restart`, then grep the log. In packaged builds the same- lines land in electron-log's file instead.--### E37. osascript keystrokes go to the frontmost app โ never send Escape--- **Situation**: driving a desktop flow with synthetic keys (global shortcut trigger is fine โ it's- registered globally), then trying to dismiss a window with `key code 53` (Escape).-- **Doesn't work**: the Escape lands on whatever app is frontmost โ typically the terminal running- the agent session, which interprets it as an interrupt and kills the agent's own turn.-- **Works**: close app surfaces in-band instead: eval the app's own close IPC via CDP on that- window's target (`window.electronAPI.invoke('...close')`), or click its close affordance. Reserve- synthetic keys for globally-registered shortcuts that don't depend on focus.--### E38. Bimodal timings from a globalShortcut handler = idle-event-loop stall (and `setTimeout` probes mask it)--- **Situation**: timing a flow triggered from an Electron `globalShortcut` callback; measurements- are wildly bimodal (sub-ms vs multi-second) and "fix" themselves when extra probes are added.-- **Doesn't work**: attributing the multi-second gap to whatever awaited call sits at that milestone- (it may be a cached no-op), or keeping a `setTimeout(0)` diagnostic probe while re-measuring โ a- pending timer wakes the loop and hides the stall entirely.-- **Works**: bracket the suspect `await` with markers plus one `queueMicrotask` and one- `setTimeout(0)` marker ONCE to classify the stall, then remove them and re-measure. If the- continuation only runs when an external event arrives (a CDP poll, mouse move), the cause is the- native-callback context not draining microtasks on an idle loop โ fix by deferring the handler- body via `setImmediate` at the registration site, then verify variance collapses.+## E. Environment / shell gotchas++- **E1. Not every layer hot-reloads โ restart and prove which code the process runs.**+ A dev server's HMR typically covers the renderer/client only. Server code,+ main-process code, and adapters that run out-of-process are often NOT recompiled on+ edit, so reloading the client verifies nothing โ the old code is still running, and+ the failure looks exactly like a logic bug in your own diff. **Works**: after an+ edit to a non-client layer, restart before drawing a conclusion, and prove the+ process has your code before debugging it โ e.g. curl the dev bundler for the source+ and grep for a marker (renderer), or grep the built bundle for the marker (server /+ main).+- **E2. The shell's `grep` may honor `.gitignore` โ "not found anywhere" can be a+ false negative.** Some environments alias `grep` to a wrapper (e.g. `ugrep --ignore-files`) that skips `.gitignore`d paths, silently omitting `node_modules`.+ Before asserting "X exists nowhere", name the ignored directory explicitly+ (`grep -rl X node_modules`) or call `/usr/bin/grep` directly.+- **E3. In zsh, a loop variable named `path` overwrites the command search path.** zsh+ ties `path` to `PATH` as a special array; assigning it (e.g. parsing a cookie jar's+ path field) replaces the process command search path, and the next executable fails+ with `command not found`. Name the field something else (`cookie_path`); this is a+ shell failure, not an auth/browser failure. (Similarly, `zsh does NOT word-split+unquoted vars` โ stashing `S="--session x --cdp 9226"` then `agent-browser $S`+ fails; inline the flags or use an array.)+- **E4. A curl "502" from a local port with nothing listening can be a shell proxy+ env.** If `HTTP_PROXY`/`HTTPS_PROXY` are set and `NO_PROXY` does not exempt+ localhost, a dead local host is forced through the proxy and returns the proxy's+ 502 โ a "server up but broken" mirage. `curl --noproxy '*'` is a harmless+ belt-and-braces habit; if you actually see a 502 from a local port, check `NO_PROXY`+ before believing the server is up.+- **E5. Dev servers can write managed files on start โ check `git status` before+ reporting the tree clean.** Some frameworks append a managed block to a repo file on+ `dev` start (once, idempotently). Reverting it at teardown makes it look like+ per-start churn and causes it to be re-appended on the next start. Commit the block+ or opt out per the framework, and always check `git status` before claiming a clean+ tree.+- **E6. Persistent resource exhaustion (e.g. Vite `EMFILE: too many open files`) is a+ stop-and-ask, not a workaround.** If a surface exits at startup with a+ file-watcher/resource-exhaustion error while the port is free, the likely cause is+ other running watchers (extra worktrees, surviving terminals, an editor window) that+ you must not kill. Terminate the run, report the exact error, and ask the user to+ clean up other processes โ do not change watch mode, fall back to a static build, or+ publish a report from a degraded surface.diff --git a/.agents/skills/agent-testing/references/project-adapter.md b/.agents/skills/agent-testing/references/project-adapter.mdnew file mode 100644index 00000000000..267a180c6d9--- /dev/null+++ b/.agents/skills/agent-testing/references/project-adapter.md@@ -0,0 +1,162 @@+# Project Adapter (`.agents/verify/PROJECT.md`)++This skill is project-agnostic. Everything specific to the project under test โ how+to start and stop it, which ports and services it needs, how auth works, which+surfaces it has, and how to jump straight into app state โ lives in a per-project+adapter at `.agents/verify/PROJECT.md`. The skill reads it; it never guesses the+project's commands.++## Where the adapter lives++```text+<repo>/.agents/verify/ # committed โ the adapter and project logs are team assets+โโโ PROJECT.md # the adapter (this contract)+โโโ common-mistakes.md # PROJECT-layer living log (writable)+โโโ probe-mock-patterns.md # PROJECT-layer living log (writable)+โโโ scripts/ # optional: project env / probe scripts+```++`.agents/verify/` is **committed** (the adapter and the project living logs are+shared, versioned team assets). The report output directory `.records/` is+**gitignored** โ reports are per-run artifacts, published to the verify platform,+not committed.++## Fixed section skeleton++`PROJECT.md` always has these six sections, in this order. Sections the skill refers+to by number (`PROJECT.md ยง2`, `ยง3`, โฆ), so keep the numbering.++1. **Project summary** โ what the product is, and the repo layout relevant to+ testing (which package holds the server, the web app, the desktop shell, the+ CLI).+2. **Environment** โ how to start and stop the dev environment; the required+ services (database, cache, queue, object store) and how to start each; how to+ detect "already running" so a run does not clobber a user's server; how env and+ ports are resolved (the project's own env-resolver command, if any) so the skill+ never hard-codes a port table.+3. **Auth** โ test accounts, seeding commands, and a per-surface status check (one+ command per surface that answers "am I signed in on this surface?").+4. **Surfaces** โ which of CLI / Web / Electron apply, and for each that applies:+ launch command, base URL / port, agent-browser session name (web/electron), and+ which probe scripts drive it.+5. **Project probes & quick navigation** โ the fast paths into app state: an auth+ probe, a current-route probe, a running-operations probe, and a `goto <route>`+ quick-navigation, plus the routes worth jumping to. These are the project's+ equivalent of a state-introspection helper; the skill uses them instead of+ hand-rolling store-eval snippets.+6. **Known constraints** โ anything the generic gates must know before running:+ services that are hard prerequisites for a code path (e.g. "agent runs require+ the queue service up"), standalone sub-packages that need their own install,+ surfaces that only work on macOS, or any repo-specific gotcha a run must respect.++`PROJECT.md` may reference project scripts under `.agents/verify/scripts/` or+anywhere in the repo.++## Copy-pasteable template++```markdown+# PROJECT.md โ agent-testing adapter for <project name>++## 1. Project summary++<One paragraph: what the product is. Then the repo layout that matters for testing โ+which directory/package is the server, the web app, the desktop shell, the CLI.>++## 2. Environment++- **Start dev server:** `<command>` (base URL: `<url>`, port: `<port>`)+- **Stop dev server:** `<command>` (must stop only what this run started)+- **Required services:** <db / cache / queue / object store โ with the start command+ for each, or "none">+- **Already-running detection:** `<health-check command>` โ how to tell the server is+ up before starting another one.+- **Env / port resolution:** `<command or file>` โ the source of truth for ports and+ URLs. Do NOT hard-code a port table; read it here.++## 3. Auth++- **Test account(s):** <how to obtain โ seeded, fixture, or a real login>+- **Seeding command:** `<command>` (or "n/a")+- **Per-surface status check:**+ - CLI: `<command>` โ signed-in when <...>+ - Web: `<command>` โ signed-in when <...>+ - Electron: `<command>` โ signed-in when <...>++## 4. Surfaces++<For each surface that applies. Delete the ones that don't.>++### CLI++- Invocation: `<how the CLI is run โ from source or built binary>`+- Auth: <see ยง3 CLI>+- Standalone install: `<command>` or "covered by root install"++### Web++- Launch: `<dev server command>` (from ยง2)+- Base URL: `<url>`+- agent-browser session: `<session name>`++### Electron++- Launch: `<start command>` โ CDP port `<port>`+- Stop: `<command>`+- Login persistence: <how login survives across runs>++## 5. Project probes & quick navigation++- Auth probe: `<command>` โ `{ isSignedIn, userId }`+- Route probe: `<command>` โ current route+- Operations probe: `<command>` โ running operations+- Quick navigation: `<command> goto <route>`+- Routes worth jumping to: <list>++## 6. Known constraints++- <e.g. "agent runs require the queue service (ยง2) up, or the run dies before any+ real work">+- <e.g. "the desktop and CLI packages are standalone โ install inside each">+- <e.g. "OS-capture surfaces are macOS-only">+```++## First-run bootstrap (SKILL.md Step 0.5)++When `.agents/verify/PROJECT.md` is absent, build it before doing anything else:++1. **Explore the repo.** Read the signals that reveal how the project runs:+ `package.json` scripts, `README`, CI workflows (`.github/workflows/**`),+ `Makefile` / `Justfile`, `docker-compose*.yml` / `compose.yaml`, `.env.example`,+ and any existing test/dev docs. Note the dev-server command, the services it+ needs, the ports, the auth story, and which surfaces exist.+2. **Draft `PROJECT.md`** from the fixed skeleton above, filling every section from+ what you found. Where a value is uncertain, mark it explicitly as a guess rather+ than inventing a command.+3. **Present it for confirmation.** Show the draft to the user and ask them to+ confirm or correct it โ especially the start/stop commands, the required+ services, and the auth path. Do not run a dev server or write test steps against+ an unconfirmed adapter.+4. **Write it only after approval**, to `.agents/verify/PROJECT.md`. Create+ `.agents/verify/` if it does not exist.++`install` (the CLI's `lh verify install`) only places the skill files; it does no repo+exploration. The adapter draft needs a model, so the first verification run is what+bootstraps `PROJECT.md`.++## Drift rule++Treat the adapter like a living log: when observed reality diverges from it during a+run (a port moved, a start command changed, a service is now required), **fix+`PROJECT.md` in place during the run** rather than working around it silently. The+next run should not rediscover the same divergence.++## Two living-log layers++The skill's `references/common-mistakes.md` and `references/probe-mock-patterns.md`+are the **generic layer** โ product-independent, read-only in consumer repos,+updated only by PR to the CLI repo. The project's own+`.agents/verify/common-mistakes.md` and `.agents/verify/probe-mock-patterns.md` are+the **project layer** โ writable, and the only place a run records project-specific+learnings. At runtime the agent reads both layers and writes only the project layer.+When a project-layer entry turns out to be product-independent, genericize it (drop+every project-specific noun) and PR it to the generic layer upstream.diff --git a/.agents/skills/agent-testing/references/record-app-screen.md b/.agents/skills/agent-testing/references/record-app-screen.mdindex 1f06192d3b9..3a74e361772 100644--- a/.agents/skills/agent-testing/references/record-app-screen.md+++ b/.agents/skills/agent-testing/references/record-app-screen.md@@ -1,24 +1,26 @@# record-app-screen.sh-General-purpose screen recording tool for the Electron app. Captures CDP screenshots as video frames and gallery snapshots, then assembles into an MP4 on stop.+General-purpose screen recording for a CDP-driven Electron/Chrome app. Captures CDP+screenshots as video frames and gallery snapshots, then assembles them into an MP4+on stop. Because it renders from the browser engine over CDP (not the OS screen), it+works under Xvfb and is unaffected by display sleep.## Why CDP Screenshots Instead of ffmpeg Screen Capture-- **Works on any screen** โ CDP screenshots capture the browser viewport directly, so external monitors, Retina scaling, and window positioning are all handled automatically-- **No signal handling issues** โ ffmpeg-static (npm) produces corrupt MP4 files when killed (missing moov atom). CDP screenshots avoid this entirely-- **Consistent output** โ Screenshots are resolution-independent and don't require crop coordinate calculations+- **Works on any screen** โ CDP screenshots capture the browser viewport directly,+ so external monitors, Retina scaling, and window positioning are handled+ automatically.+- **No signal-handling issues** โ `ffmpeg-static` (npm) can produce corrupt MP4+ files when killed (missing moov atom). CDP screenshots avoid this entirely.+- **Consistent output** โ resolution-independent, no crop-coordinate math.## Commands```bash-# Start recording (Electron must be running with CDP)-.agents/skills/agent-testing/scripts/record-app-screen.sh start [output_name]--# Stop recording and assemble video-.agents/skills/agent-testing/scripts/record-app-screen.sh stop--# Check if recording is active-.agents/skills/agent-testing/scripts/record-app-screen.sh status+# $SKILL_DIR = the skill's install dir; the target app must be running with CDP+"$SKILL_DIR/scripts/record-app-screen.sh" start [output_name] # start recording+"$SKILL_DIR/scripts/record-app-screen.sh" stop # stop + assemble video+"$SKILL_DIR/scripts/record-app-screen.sh" status # is recording active?```### Arguments@@ -43,100 +45,72 @@ General-purpose screen recording tool for the Electron app. Captures CDP screens<name>/ # Gallery screenshots (every 3s)0000.png0001.png- 0002.png...```-The `.records/` directory is at the project root and is gitignored.+The `.records/` directory is at the repo root and is gitignored.## How It Works### Start1. Creates two background loops:- - **Video frames** โ `agent-browser screenshot` every `VIDEO_FRAME_INTERVAL` seconds into a temp directory (`/tmp/record-frames-XXXXXX/`)- - **Gallery screenshots** โ `agent-browser screenshot` every `SCREENSHOT_INTERVAL` seconds into `.records/<name>/`-2. Saves PIDs and paths to `/tmp/record-app-screen.pids` and `/tmp/record-app-screen.state`+ - **Video frames** โ `agent-browser screenshot` every `VIDEO_FRAME_INTERVAL`+ seconds into a temp directory.+ - **Gallery screenshots** โ `agent-browser screenshot` every+ `SCREENSHOT_INTERVAL` seconds into `.records/<name>/`.+2. Saves PIDs and paths to `/tmp/record-app-screen.pids` and+ `/tmp/record-app-screen.state`.### Stop-1. Kills both background loops-2. Assembles video frames into MP4 using ffmpeg:+1. Kills both background loops.+2. Assembles video frames into MP4 with ffmpeg:```ffmpeg -framerate 2 -i frame_%06d.png -c:v libx264 -crf 23 -pix_fmt yuv420p <output>.mp4```-3. Cleans up temp frame directory-4. Reports file sizes and paths--## Usage Examples+3. Cleans up the temp frame directory.+4. Reports file sizes and paths.-### Basic Test Recording+## Usage Example```bash-# Start Electron-.agents/skills/agent-testing/scripts/electron-dev.sh start+# 1. Start the Electron dev instance (launch command from PROJECT.md ยง4)-# Start recording-.agents/skills/agent-testing/scripts/record-app-screen.sh start my-test+# 2. Start recording+"$SKILL_DIR/scripts/record-app-screen.sh" start my-test-# Run automation+# 3. Drive the automationagent-browser --cdp 9222 click @e61agent-browser --cdp 9222 type @e42 "hello"agent-browser --cdp 9222 press Entersleep 10-# Stop and get results-.agents/skills/agent-testing/scripts/record-app-screen.sh stop+# 4. Stop and get results+"$SKILL_DIR/scripts/record-app-screen.sh" stop# โ .records/my-test.mp4 + .records/my-test/*.png```-### Gateway Streaming Demo+## When to use a GIF instead-```bash-.agents/skills/agent-testing/scripts/electron-dev.sh start--# Inject gateway URL-agent-browser --cdp 9222 eval --stdin << 'EOF'-(function() {- var store = window.global_serverConfigStore;- store.setState({ serverConfig: { ...store.getState().serverConfig,- agentGatewayUrl: 'https://agent-gateway.lobehub.com' } });- return 'ready';-})()-EOF--# Record-.agents/skills/agent-testing/scripts/record-app-screen.sh start gateway-demo--# Navigate to agent, send message, wait for completion...-# (automation commands here)--.agents/skills/agent-testing/scripts/record-app-screen.sh stop-open .records/gateway-demo.mp4-```--### Check Active Recording--```bash-.agents/skills/agent-testing/scripts/record-app-screen.sh status-# [record] Active recording-# Frames: 42 captured (running: yes)-# Screenshots: 14 captured (running: yes)-# Output: .records/my-test.mp4-```+For a short, time-based assertion (streaming output, a ticking timer, a loading+state) attach a GIF from `scripts/record-gif.sh` to the case's evidence โ it is+lighter than a full recording and embeds inline on the verify page. Reach for a full+MP4 recording only when a longer flow needs to be watched end to end.## Prerequisites-- **ffmpeg** โ For video assembly. Install via `bun add -g ffmpeg-static` or `brew install ffmpeg`-- **agent-browser** โ For CDP screenshots. Install via `npm i -g agent-browser`-- **Electron app running** โ With CDP enabled (use `electron-dev.sh start`)+- **ffmpeg** โ for video assembly. Install via `bun add -g ffmpeg-static` or+ `brew install ffmpeg`.+- **agent-browser** โ for CDP screenshots. Install via `npm i -g agent-browser`.+- **The app running with CDP enabled** โ start the dev instance per `PROJECT.md`.## Troubleshooting-| Problem | Solution |-| ----------------------------------- | ------------------------------------------------------------------------------------------------------------ |-| "No active recording found" on stop | PID file was cleaned up. Check if background processes are still running with `ps aux \| grep agent-browser` |-| "A recording is already active" | Run `stop` first, or manually clean: `rm /tmp/record-app-screen.pids /tmp/record-app-screen.state` |-| Video is 0 bytes | No frames were captured. Ensure Electron is running and CDP port is correct |-| Screenshots are blank/white | SPA may not have loaded yet. Wait for `electron-dev.sh` to report "Renderer ready" |-| ffmpeg assembly fails | Check `/tmp/ffmpeg-assemble.log`. Ensure ffmpeg is installed and frames exist |+| Problem | Solution |+| ----------------------------------- | ----------------------------------------------------------------------------------------- |+| "No active recording found" on stop | PID file was cleaned up; check for background loops with `ps aux \| grep agent-browser` |+| "A recording is already active" | Run `stop` first, or clean: `rm /tmp/record-app-screen.pids /tmp/record-app-screen.state` |+| Video is 0 bytes | No frames captured. Ensure the app is running and the CDP port is correct |+| Screenshots are blank/white | The app may not have finished loading yet. Wait for renderer readiness first |+| ffmpeg assembly fails | Check `/tmp/ffmpeg-assemble.log`; ensure ffmpeg is installed and frames exist |diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.mdindex e56e96bd7d4..fe0b46cbd41 100644--- a/.agents/skills/agent-testing/references/report.md+++ b/.agents/skills/agent-testing/references/report.md@@ -1,170 +1,147 @@# Structured Test Reports-Every automated test session ends with a structured, evidence-backed report.-A chat-only summary is not an acceptable deliverable: the report is what the-user (or a reviewer, or a later agent) audits without replaying the session.+Every automated test session ends with a structured, evidence-backed report. A+chat-only summary is not an acceptable deliverable: the report is what the user (or+a reviewer, or a later agent) audits without replaying the session.## Location & layoutReports live under `.records/reports/` (gitignored, like all `.records/`-output), **grouped by the acceptance they belong to**: one directory per-subject, one subdirectory per verification run (round). The subject key is the-ingest subject with `:` โ `-`.+output), grouped by acceptance subject. One subject directory contains one+subdirectory per immutable verification round:```-.records/reports/<subject-key>/ # e.g. topic-tpc_acceptreview001-โโโ acceptance.json # group marker: subject, title, lastRun-โโโ <YYYYMMDD-HHMMSS>-<slug>/ # one run = one round on the acceptance-โ โโโ report.md # narrative TAIL only (่ท่ฟ / ๆฌ่ฝฎ้ช่ฏ / ่ฏๅ) โ the page's "Details"-โ โโโ result.json # the structured source: scenario + context + cases + summary.conclusion-โ โโโ assets/ # evidence: screenshots, HAR files, CLI transcripts-โโโ <YYYYMMDD-HHMMSS>-<slug>/ # the next round, and so on+.records/reports/<subject-key>/+โโโ acceptance.json+โโโ <YYYYMMDD-HHMMSS>-<slug>/+โ โโโ report.md+โ โโโ result.json+โ โโโ assets/+โโโ <YYYYMMDD-HHMMSS>-<slug>/```-Every run belongs to a subject acceptance (SKILL.md Step 6), so the group is-known before the round starts โ pass it to the scaffold:-`report-init.sh --subject topic:tpc_xxx <slug> "<title>"`. The scaffold also-pre-fills `result.json.subject`, so `lh verify ingest-report` attaches the run-without an explicit `--subject`. Runs scaffolded without `--subject` fall back-to a flat `.records/reports/<ts>-<slug>/` (legacy layout, still readable by-`ingest-report` โ but new runs should always carry their subject).--Reusable per-check fixture assets live NEXT to the report groups under-`.records/fixtures/<subject-key>/<check-id>/` โ `check.json` plus `seed/`-(INPUTS a run consumes: files to upload, DB seed fragments, replay steps'-material). Execution OUTPUTS (screenshots, transcripts) are per-run evidence-and belong only in the round dir's `assets/`. See `scripts/fixture.mjs` and-SKILL.md "Fixtures: reusable per-check assets".+`<subject-key>` is the ingest subject with `:` replaced by `-`. Scaffold with+`report-init.sh --subject topic:tpc_xxx <slug> "<title>"`; this also pre-fills+`result.json.subject`. The legacy flat layout remains readable, but new runs+should always carry their subject.++Reusable per-check inputs live separately under+`.records/fixtures/<subject-key>/<check-id>/` as `check.json` plus `seed/`.+Execution outputs remain in the round directory's `assets/`. See+`scripts/fixture.mjs` and the skill's fixture workflow.**`result.json` is the report โ `report.md` is just its tail.** The publishedverify page (`/verify/<id>`) renders itself from `result.json`: one line ofprovenance (PR / branch / commit / date / surfaces), the overall conclusion from`summary.conclusion` directly under the title, and the check list from `plan[]`-paired with `cases[]`. So `report.md` must NOT repeat the scope block or a ็จไพ+paired with `cases[]`. So `report.md` must NOT repeat the scope block or a casetable โ those double up on the page. It carries only the non-duplicate narrative-(ไป้่ท่ฟ / ๆฌ่ฝฎ้ช่ฏ / ่ฏๅ), rendered as the page's collapsible "Details".+(follow-ups / this-round notes / score), rendered as the page's collapsible+"Details".## Workflow1. **Scaffold up front** โ before running the first test step:```bash- DIR=$(./.agents/skills/agent-testing/scripts/report-init.sh --subject topic:tpc_xxx < slug > "<title>")+ # $SKILL_DIR = the skill's install dir+ DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-slug "My title")```The script creates the directory, pre-fills branch / commit / date in both- files, and prints the directory path. The scaffold uses the compact report- shape below; translate its headings and table labels to the user's language- before delivery if needed.+ files, and prints the directory path. Translate its headings and table labels to+ the user's language before delivery if needed.2. **Collect evidence as you test** โ every asserted behavior gets one evidenceitem in `$DIR/assets/`:- - UI (static state): `agent-browser screenshot` or `capture-app-window.sh`,- then **verify the screenshot with the Read tool before citing it** โ- never cite an image you haven't looked at.+ - UI (static state): `agent-browser screenshot` or `capture-app-window.sh`, then+ **verify the screenshot with the Read tool before citing it** โ never cite an+ image you haven't looked at.- - UI (time-based behavior): **screenshot vs GIF is a judgment you must- make per case.** If the assertion is about change over time โ streaming- output, a ticking timer, loading/progress states, animations,- appear/disappear transitions โ a static screenshot cannot prove it.- Record a frame sequence and synthesize a GIF:+ - UI (time-based behavior): **screenshot vs GIF is a judgment you make per+ case.** If the assertion is about change over time โ streaming output, a+ ticking timer, loading/progress states, animations, appear/disappear+ transitions โ a static screenshot cannot prove it. Record a frame sequence and+ synthesize a GIF:```bash# start recording (background), trigger the behavior, wait for it to finish- ../scripts/record-gif.sh "$DIR/assets/case2-streaming.gif" 12 2 &+ "$SKILL_DIR/scripts/record-gif.sh" "$DIR/assets/case2-streaming.gif" 12 2 &GIF_PID=$!# ... drive the scenario ...wait $GIF_PID```- Embed it like an image: ``. Verify- at least the first/last frames visually (Read the GIF) before citing.+ Verify at least the first/last frames visually (Read the GIF) before citing.- UI (before/after comparison): capture and visually verify both original- screenshots. Do not ask the agent to compose them into a new image. In the- case's `evidence` array, pair them with a shared comparison id.+ screenshots. Do not compose them into a new image. In the case's `evidence`+ array, pair them with a shared comparison id.- **A `comparison` pair means ONE view in two states** โ the same surface- before and after a change (the red/green role bands say "was / is now").- Two sequential steps of a FLOW (a dialog, then the state after submitting- it) are NOT a before/after: labeling them so misstates the semantics and- reads as if the first shot were a defect. For flow steps, attach plain- ordered evidence items and let each caption name its step:+ A comparison pair means the same view in two states. Sequential steps of a+ flow are not before/after states; attach those as ordinary ordered evidence+ items with captions naming each step.```json"evidence": [{"path": "assets/before.png",- "comparison": {- "id": "topic-row",- "role": "before",- "layout": "vertical",- "label": "ๅฏๆ ้ข 11px๏ผ่ก้ซ 40px"- }+ "comparison": { "id": "topic-row", "role": "before", "layout": "vertical", "label": "before: 11px, line-height 40px" }},{"path": "assets/after.png",- "comparison": {- "id": "topic-row",- "role": "after",- "layout": "vertical",- "label": "ๅฏๆ ้ข 12px๏ผ่ก้ซ 44px"- }+ "comparison": { "id": "topic-row", "role": "after", "layout": "vertical", "label": "after: 12px, line-height 44px" }}]```The verify page renders a complete pair with each screenshot under its own- tinted band โ red for `before`, green for `after` โ so which state you are- looking at survives a glance. A group contains exactly one `before` and one- `after`, and **both halves need the same string `id`**; a half without an `id`- can never pair. Incomplete groups render as ordinary evidence.+ tinted band โ red for `before`, green for `after`. A group contains exactly one+ `before` and one `after`, and **both halves need the same string `id`**; a half+ without an `id` can never pair. Incomplete groups render as ordinary evidence.Two fields are worth setting on every pair:- **`layout`** โ `horizontal` (default, side by side) or `vertical` (stacked).- Pick by the shape of the crop: a tall, narrow capture (a sidebar, a form,- a list) reads well side by side; a **wide, short strip** (a toolbar, a- one-line footer) must be `vertical`, because two of them in a two-column- grid become illegible slivers. Set it on both halves.+ A tall, narrow crop (a sidebar, a form, a list) reads well side by side; a+ **wide, short strip** (a toolbar, a one-line footer) must be `vertical`,+ because two of them in a two-column grid become illegible slivers. Set it on+ both halves.- **`label`** โ the caption shown next to the role word in the band. This is- where the before/after contrast is actually _stated_: put the measured- delta on each side (`"11px๏ผ่ก้ซ 40px"` vs `"12px๏ผ่ก้ซ 44px"`), so the two- captions read as a comparison rather than repeating the case title.+ where the before/after contrast is actually _stated_: put the measured delta+ on each side, so the two captions read as a comparison rather than repeating+ the case title.- - CLI: exact command + trimmed output (`$CLI task list | tee "$DIR/assets/task-list.txt"`).+ - CLI: exact command + trimmed output (`<cli> <command> | tee "$DIR/assets/x.txt"`).- Network: `agent-browser network requests` dumps or HAR files.-3. **Write `plan[]` BEFORE you run anything.** The approved plan from Step 1 is- part of the report, not scaffolding you throw away: each item is- `{ id, title, verifier, method, expected, requiredEvidence }` โ what you will- check, how it is judged, how you will exercise it, what would make it pass,- and the artifact it must produce. `verifier` and `requiredEvidence` are closed- sets the pipeline acts on (see the schema below); `method` / `expected` are- prose. `cases[]` later reuses the same `id`s, which is what lets the report- pair intent against outcome. A planned item that never produces a case renders- as **ๆชๆง่ก** rather than vanishing, so cut coverage in the open โ silently- dropping a check now shows up as a hole in the report.--4. **Fill `result.json` as you go** โ it is the report. Each tested behavior is- one entry in `cases[]` (`{ id, name, result, observation, evidence }`), where- `evidence` is a path under `assets/` (screenshot / GIF / transcript). Set the- scope fields (`scenario: "coding"`, `branch`, `commit`, `surfaces`, `entry`)- and write the one-paragraph verdict into `summary.conclusion`. The page pairs- each check with its evidence inline, so you don't hand-build a table.- `report.md` holds only the narrative tail (่ท่ฟ / ๆฌ่ฝฎ้ช่ฏ / ่ฏๅ).--5. **Set the verdict** in both `report.md` and `result.json`, then link the- report directory in your final answer to the user. If UI evidence exists,- list the key screenshot/GIF links in the final chat response. Use Markdown- link text as the evidence caption, for example:- `[Image #1 - observed outcome](<report-dir>/assets/case1.png)`.--6. **Publish to LobeHub** (Step 4 of the skill) โ upload the finished session so- it's viewable in-app, not just on disk. **Publish to PRODUCTION- (`app.lobehub.com`) with the user's real login, NOT the local dev CLI** โ- strip the local dev overrides so `lh` uses its production defaults:+3. **Write `plan[]` BEFORE you run anything.** The approved plan from Step 1 is part+ of the report, not scaffolding you throw away: each item is+ `{ id, title, category, verifier, method, expected, requiredEvidence }` โ what+ you will check, which requirement area it belongs to, how it is judged, how you+ will exercise it, what would make it pass, and the artifact it must produce.+ `verifier` and `requiredEvidence` are closed sets the pipeline acts on (schema+ below); `method` / `expected` are prose. `cases[]` later reuses the same `id`s,+ which is what lets the report pair intent against outcome. A planned item that+ never produces a case renders as **ๆชๆง่ก** rather than vanishing, so cut coverage+ in the open.++4. **Fill `result.json` as you go** โ it is the report. Each tested behavior is one+ entry in `cases[]` (`{ id, name, result, observation, evidence }`), where+ `evidence` is a path under `assets/`. Set the scope fields (`scenario`, `branch`,+ `commit`, `surfaces`, `entry`) and write the one-paragraph verdict into+ `summary.conclusion`. The page pairs each check with its evidence inline, so you+ don't hand-build a table. `report.md` holds only the narrative tail.++5. **Set the verdict** in both `report.md` and `result.json`. Describe key visual+ outcomes in prose; the published verify URL is the only visual pointer in the+ final chat reply.++6. **Publish** (SKILL.md Step 6) โ upload the finished session so it's viewable on+ the verify platform, not just on disk. **Publish to PRODUCTION defaults with the+ user's real login, NOT a local-dev CLI override** โ strip the local dev overrides+ so `lh` uses its production defaults. Clearing an override profile looks like:```bashenv -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \@@ -173,79 +150,32 @@ table โ those double up on the page. It carries only the non-duplicate narratiThis creates a new immutable verification run, attaches it to the requiredsubject acceptance, uploads the cases, evidence, and report body, then prints- both `/verify/<verifyRunId>` and `/acceptance/<acceptanceId>`.- Include that full production link in the final reply alongside the local- report dir. See SKILL.md โ Step 4 for why production (a localhost URL isn't- shareable and a local stub S3 fails file-evidence uploads), the production- login check, and the atomic commands (`verify run|result|evidence|report โฆ`).+ both `/verify/<verifyRunId>` and `/acceptance/<acceptanceId>`. Include that full+ production link in the final reply alongside the local report dir. See SKILL.md โ+ Step 6 for why production defaults (a localhost URL isn't shareable and a local+ stub storage fails file-evidence uploads), the production login check, and the+ atomic commands (`verify run|result|evidence|report โฆ`).## Report language (hard rule)-**`report.md` MUST be written in the language the user is conversing in** โ-the whole file, headings included. If the conversation is in Chinese, the-report is in Chinese; do not mix English prose into it. The scaffold headings-are placeholders โ translate them when filling if the user is not conversing in-the scaffold language. Exceptions that stay as-is: code/commands, identifiers,-log excerpts, and `result.json` (its keys and status values are machine-read-and stay English; the `title` and case `name` fields follow the user's-language).+**`report.md` MUST be written in the language the user is conversing in** โ the+whole file, headings included. If the conversation is in Chinese, the report is in+Chinese; do not mix English prose into it. The scaffold headings are placeholders โ+translate them when filling. Exceptions that stay as-is: code/commands,+identifiers, log excerpts, and `result.json` (its keys and status values are+machine-read and stay English; the `title` and case `name` fields follow the+user's language).## report.md sections-Default report shape:--| Section | Content |-| ---------------- | -------------------------------------------------------------------------------------------- |-| **Scope** | What changed / what is being verified; branch, commit, date, surface, entry URL/page, focus |-| **Cases** | Compact table: `# \| Case \| Result \| Key observation \| Evidence` |-| **Verdict** | Overall verdict first (`pass` / `partial` / `fail`), then the concise reasons and follow-ups |-| **Verification** | Commands or automated checks run in this session, with trimmed results |-| **Score** | Pass/fail/blocked counts, optional 0โ100 score |--The case table is the main reading surface. Prefer one clear row per user-scenario or regression assertion, and put the screenshot/GIF directly in the-`Evidence` cell:--```markdown-| # | Case | Result | Key observation | Evidence |-| --- | ------------------------ | ------ | ----------------------------------------------------------------- | ------------------------------------------------ |-| 1 | Create a new page | pass | Title and body persisted after refresh |  |-| 2 | Respect requested length | fail | Requested about 600 Chinese characters; final body was about 1286 |  |-```--## Inline visual evidence--Screenshots and GIFs must be embedded so the report shows the image inline:--```markdown---```--Do **not** use these as the primary evidence for UI cases:--```markdown-[case 1 result](assets/case1-result.png)-assets/case1-result.png-file:///tmp/case1-result.png-```--Links are acceptable for non-visual artifacts such as CLI transcripts, HAR-files, or long logs. For videos, embed a representative screenshot/GIF inline in-the case row and link the full video as supplemental evidence.+Default report shape (a case table doubles the page and is only for a purely+non-visual run; for UI runs, leave the case list to `result.json`):-Avoid the old wide table with separate `steps`, `expected`, and `actual`-columns unless the test is purely non-visual and truly needs that breakdown.-For UI reports, those columns make screenshot-backed reading harder. Put-procedural detail in the row's key observation only when it changes the-interpretation of the result.--Use an extra evidence/detail section only when the inline table cannot carry-the material cleanly, such as long CLI transcripts, HAR summaries, or multiple-screenshots for one case. In that situation, keep the table evidence cell as an-inline visual proof for UI cases or a concise link for non-visual artifacts,-then put the longer material under `Verification` or a brief-`Additional Evidence` section.+| Section | Content |+| ---------------- | ---------------------------------------------------------------------------------------- |+| **Verdict** | Overall verdict first (`pass` / `partial` / `fail`), then concise reasons and follow-ups |+| **Verification** | Commands or automated checks run in this session, with trimmed results |+| **Score** | Pass/fail/blocked counts, optional 0โ100 score |Status values: `pass` / `fail` / `blocked` (couldn't run โ e.g. auth or envmissing; a blocked case is not a pass).@@ -256,12 +186,12 @@ missing; a blocked case is not a pass).REQUIRED on every ingest:**- `title` (top level) โ without it the run lists as "ๆชๅฝๅ้ช่ฏ" forever.-- `summary.verdict` (`pass` / `fail` / `partial`) โ without it the list glyph is- a permanent amber "?" instead of the green pass. The CLI now derives a- fallback from the cases, but an explicit verdict is still the author's job.-- Every `comparison` pair side should carry a `label` โ the role band renders- it as the explanation ("ไผๅๅ๏ผๆธ ๅๅคด้จ่ขซๆคๅโฆ"); a pair without labels shows- two bare role words and reads as unexplained.+- `summary.verdict` (`pass` / `fail` / `partial`) โ without it the list glyph is a+ permanent amber "?" instead of the green pass. The CLI derives a fallback from the+ cases, but an explicit verdict is still the author's job.+- Every `comparison` pair side should carry a `label` โ the role band renders it as+ the explanation; a pair without labels shows two bare role words and reads as+ unexplained.```json{@@ -292,8 +222,9 @@ REQUIRED on every ingest:**{"id": "1","title": "task tree returns nested children",+ "category": "Task hierarchy","verifier": "program",- "method": "lh task list --tree against a 3-level fixture",+ "method": "<cli> task list --tree against a 3-level fixture","expected": "root shows 3 nested children at depth 2","requiredEvidence": ["text"]}@@ -301,7 +232,7 @@ REQUIRED on every ingest:**"pullRequest": {"number": 17152,"title": "feat(task): nested task tree",- "url": "https://github.com/lobehub/lobe-chat/pull/17152"+ "url": "https://github.com/<org>/<repo>/pull/17152"},"summary": {"total": 1,@@ -317,87 +248,78 @@ REQUIRED on every ingest:**````plan[]` is the checks you committed to **before running them**, and it shares-`id`s with `cases[]`. Every agent-testing plan item must carry a `category` that-names its user-facing business scenario or requirement area (for example `Task-hierarchy`, `Rate-limit recovery`, or `Browser actions`). It must not name a-technical surface such as `Desktop`, `CLI`, or `Backend`: Acceptance groups are-organized by what the user is accepting, while `surface` separately records-where the check ran. A plan item with no matching case renders as **ๆชๆง่ก**:-cutting coverage is allowed, hiding that you cut it is not.--Two of its fields are a **closed vocabulary**, because the pipeline acts on them-โ they are not labels:--| field | values | what it does |-| ------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |-| `verifier` | `program` \| `agent` \| `llm` (default `agent`) | How the verdict is reached. A command-asserted check is `program`; calling it `agent` hides what actually judged it. |-| `requiredEvidence` | `screenshot` \| `gif` \| `video` \| `text` \| `dom_snapshot` \| `transcript` | The artifact this check **must** produce. The executor's coverage gate **fails** an item whose required medium is missing. |+`id`s with `cases[]`. Every plan item must carry a `category` that names its+user-facing business scenario or requirement area (for example `Task hierarchy`,+`Rate-limit recovery`, `Browser actions`). It must not name a technical surface such+as `Desktop`, `CLI`, or `Backend`: Acceptance groups are organized by what the user+is accepting, while `surface` separately records where the check ran. A plan item+with no matching case renders as **ๆชๆง่ก**: cutting coverage is allowed, hiding that+you cut it is not.++Two of its fields are a **closed vocabulary**, because the pipeline acts on them โ+they are not labels:++| field | values | what it does |+| ------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |+| `verifier` | `program` \| `agent` \| `llm` (default `agent`) | How the verdict is reached. A command-asserted check is `program`; calling it `agent` hides what actually judged it. |+| `requiredEvidence` | `screenshot` \| `gif` \| `video` \| `text` \| `dom_snapshot` \| `transcript` | The artifact this check **must** produce. The coverage gate **fails** an item whose required medium is missing. |An out-of-vocabulary value in either fails the ingest โ an unrecognized mediumwould silently gate on nothing, which is worse than no gate at all.-`method` (how you would exercise it) and `expected` (what would make it pass)-stay **free prose** โ they carry intent no enum can, and both render under the-check on the page next to the outcome.+`method` (how you would exercise it) and `expected` (what would make it pass) stay+**free prose** โ they carry intent no enum can, and both render under the check on+the page next to the outcome.A plan item may also carry a per-item `surface` (same closed set as the run-level-`surfaces` below; `electron` normalizes to `desktop`). It says which product-surface THIS check ran on. It is metadata, never an Acceptance grouping key. An-unknown value is warned about and dropped, never stored.--`surfaces` is a **closed set** โ `web` | `desktop` | `cli` | `mobile` | `bot` โ-and names the product surface a check ran **on**. `electron` is accepted and-normalized to `desktop`. Anything else fails the ingest, so don't reach for it:--- A **test kind** is not a surface. `unit`, `backend`, `database`, `type-check`- do not belong here; a backend change verified through the CLI has surface- `cli`.-- A **runtime mode** is not a surface. "packaged build (app.isPackaged=true)",- "CDP dev instance" โ that detail belongs on the plan item's `method`.--`entry` is the command or URL exercised (`lh task list --tree`,-`/chat/settings`) โ **not** a PR title and not a description of the change.--`pullRequest` is optional: when it is absent, the ingest asks `gh` for the PR of-`branch` and fills it in. Write it explicitly only when the report verifies a PR-that isn't the branch's own.--`score` is optional โ use it when the verdict has a subjective component (UI-polish, copy quality); omit it for purely binary runs. `verdict` is the single-word the user reads first: `pass`, `fail`, or `partial`.--`subject` identifies the business subject whose **acceptance aggregate** owns-this immutable run: either-`"subject": "task:<id>"` (`task` | `topic` | `document`) or+`surfaces`; `electron` normalizes to `desktop`). It says which product surface THIS+check ran on. It is metadata, never an Acceptance grouping key.++`surfaces` is a **closed set** โ `web` | `desktop` | `cli` | `mobile` | `bot` โ and+names the product surface a check ran **on**. `electron` is accepted and normalized+to `desktop`. Anything else fails the ingest:++- A **test kind** is not a surface. `unit`, `backend`, `database`, `type-check` do+ not belong here; a backend change verified through the CLI has surface `cli`.+- A **runtime mode** is not a surface. "packaged build", "CDP dev instance" โ that+ detail belongs on the plan item's `method`.++`entry` is the command or URL exercised (`<cli> task list --tree`, `/chat/settings`)+โ **not** a PR title and not a description of the change.++`pullRequest` is optional: when absent, the ingest asks `gh` for the PR of `branch`+and fills it in. Write it explicitly only when the report verifies a PR that isn't+the branch's own.++`score` is optional โ use it when the verdict has a subjective component (UI polish,+copy quality); omit it for purely binary runs. `verdict` is the single word the user+reads first: `pass`, `fail`, or `partial`.++`subject` identifies the business subject whose **acceptance aggregate** owns this+immutable run: either `"subject": "task:<id>"` (`task` | `topic` | `document`) or`{ "type": "task", "id": "task_โฆ", "requirement": "one-sentence acceptance bar" }`.-The `--subject` flag overrides this field. Inside a LobeHub conversation, both-may be omitted because `ingest-report` defaults to-`topic:$LOBEHUB_TOPIC_ID`; outside a topic, an explicit subject is mandatory.-Every ingest creates a new immutable run. Never update a prior run after a fix;-publish the re-verification as the next round on the same acceptance.+The `--subject` flag overrides this field. Inside a LobeHub conversation, both may+be omitted because `ingest-report` defaults to `topic:$LOBEHUB_TOPIC_ID`; outside a+topic, an explicit subject is mandatory. Every ingest creates a new immutable run;+never update a prior run after a fix, publish the re-verification as the next round.`interactionCost` is optional and run-level. For UI runs driven through-`agent-browser`, create `interaction-trace.jsonl` with-`scripts/agent-browser-klm.mjs`, then run-`scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`. The summary is a user-equivalent GOMS-KLM-estimate: physical browser actions are derived from agent-browser commands,-while mental operators (`M`) are explicit agent estimates recorded with the-wrapper's `mental` subcommand.--When published (Step 4), `verify ingest-report` maps each case onto a check-result: `name`โtitle, `status`/`result`โverdict, `observation` (or-`keyObservation`)โthe result's key observation, and `evidence` pathsโuploaded-artifacts. `summary.{total,passed,failed,blocked}` and `verdict` become the-report's stats + overall verdict; `report.md` becomes the report body.+`agent-browser`, create `interaction-trace.jsonl` with `scripts/agent-browser-klm.mjs`,+then run `scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`.++When published, `verify ingest-report` maps each case onto a check result:+`name`โtitle, `status`/`result`โverdict, `observation`โthe result's key+observation, and `evidence` pathsโuploaded artifacts. `summary.{total,passed,failed,blocked}`+and `verdict` become the report's stats + overall verdict; `report.md` becomes the+report body.## Rules-- **No evidence, no claim** โ every `pass`/`fail` in the case table must link- at least one asset. UI cases must inline-embed their primary screenshot/GIF;+- **No evidence, no claim** โ every `pass`/`fail` in `cases[]` must link at least+ one asset. UI cases must attach their primary screenshot/GIF as evidence;non-visual CLI/network cases may link transcripts, HAR files, or logs.-- **Screenshots must be visually verified** with the Read tool before being- cited.+- **Screenshots must be visually verified** with the Read tool before being cited.- **Report failures faithfully** โ a failing case with clear evidence is a goodreport; a vague green one is not.-- If coverage was cut (cases skipped, surfaces not exercised), say so in the- Verdict section โ silent truncation reads as "covered everything".+- If coverage was cut (cases skipped, surfaces not exercised), say so in the Verdict+ section โ silent truncation reads as "covered everything".diff --git a/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs b/.agents/skills/agent-testing/scripts/agent-browser-klm.mjsindex 0d76e0a1175..671b0d8d35c 100755--- a/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs+++ b/.agents/skills/agent-testing/scripts/agent-browser-klm.mjs@@ -82,7 +82,7 @@ const usage = () => {Examples:AGENT_BROWSER_KLM_TRACE="$DIR/interaction-trace.jsonl" \\- agent-browser-klm.mjs --klm-phase login --klm-check case-1 --session lobehub-dev click @e3+ agent-browser-klm.mjs --klm-phase login --klm-check case-1 --session app-dev click @e3agent-browser-klm.mjs mental --m 2 --score 3 --confidence 0.75 \\--reason "First view requires understanding status and next action"`);diff --git a/.agents/skills/agent-testing/scripts/cdp-capture.cjs b/.agents/skills/agent-testing/scripts/cdp-capture.cjsold mode 100644new mode 100755index 19d71e828e2..cdbd16b0d60--- a/.agents/skills/agent-testing/scripts/cdp-capture.cjs+++ b/.agents/skills/agent-testing/scripts/cdp-capture.cjs@@ -8,10 +8,68 @@// Usage: node cdp-capture.cjs --port 9222 --out shot.png [--full] [--target-url <substr>] [--timeout 12000]// Prints one line of JSON: {"ok":true,"bytes":N,"ms":N,"targetUrl":"..."} or {"ok":false,"error":"..."}// Exit 0 on success, non-zero on failure/timeout.+//+// Requires the `ws` package to be resolvable from this file's own location โ+// Node's require() walks up ancestor node_modules automatically, so this works+// whether the skill ships inside @lobehub/cli's own node_modules or a hoisted+// monorepo root; no manual NODE_PATH wiring needed. A `lh verify install`-copied+// skill dir lives inside a consumer repo's harness skills dir, though, so the+// ancestor walk from there never reaches @lobehub/cli's node_modules โ fall+// back to the `cliRoot` recorded in the sibling `.skill-meta.json`.const http = require('node:http');const fs = require('node:fs');-const WebSocket = require('ws');+const path = require('node:path');++function resolveWs() {+ const attempted = [];+ try {+ return require('ws');+ } catch {+ attempted.push('ancestor node_modules walk from ' + __filename);+ }++ const markerDir = path.join(__dirname, '..');+ const metaPath = path.join(markerDir, '.skill-meta.json');+ let cliRoot;+ try {+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));+ cliRoot = meta && meta.cliRoot;+ if (cliRoot && !path.isAbsolute(cliRoot)) {+ cliRoot = path.resolve(markerDir, cliRoot);+ }+ } catch {+ attempted.push(metaPath + ' (missing or unreadable)');+ }++ if (cliRoot) {+ // createRequire, not a hand-built <cliRoot>/node_modules/ws path: pnpm+ // links a package's deps NEXT TO it (.pnpm/<pkg>@<v>/node_modules/ws),+ // so only Node's real resolution walk anchored inside cliRoot finds ws+ // across both npm and pnpm layouts.+ try {+ return require('node:module').createRequire(path.join(cliRoot, 'package.json'))('ws');+ } catch {+ attempted.push("createRequire('ws') from " + cliRoot + ' (via .skill-meta.json cliRoot)');+ }+ }++ console.log(+ JSON.stringify({+ ok: false,+ error:+ "Cannot find module 'ws'. Tried: " ++ attempted.join('; ') ++ ". This script requires the 'ws' package to be resolvable " ++ 'from its own install location (a dependency of @lobehub/cli, or installed ' ++ "alongside it). Run 'npm install ws' in the consuming project if using this " ++ 'script standalone.',+ }),+ );+ process.exit(7);+}++const WebSocket = resolveWs();const arg = (k, d) => {const i = process.argv.indexOf(k);diff --git a/.agents/skills/agent-testing/scripts/cdp-screenshot.sh b/.agents/skills/agent-testing/scripts/cdp-screenshot.shindex 339eedb9372..cd37a93e844 100755--- a/.agents/skills/agent-testing/scripts/cdp-screenshot.sh+++ b/.agents/skills/agent-testing/scripts/cdp-screenshot.sh@@ -17,11 +17,10 @@# --check preflight mode: capture a throwaway frame, verify it is non-black,# print a PASS/FAIL verdict. Exit 0 only if a real frame was captured.#-# Exit codes: 0 ok ยท 5 capture failed/timeout ยท 6 captured but BLACK ยท 7 node/ws missing+# Exit codes: 0 ok ยท 5 capture failed/timeout ยท 6 captured but BLACK ยท 7 node/dependency missingset -uo pipefailSCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-REPO_DIR="$(cd "$SCRIPT_DIR/../../../.." && pwd)"PORT=9222; OUT=""; CHECK=0; PASS=()while [ $# -gt 0 ]; docase "$1" in@@ -35,12 +34,19 @@ done[ -z "$OUT" ] && OUT="${TMPDIR:-/tmp}/cdp-shot-$PORT.png"command -v node >/dev/null 2>&1 || { echo "[cdp-shot] node not found"; exit 7; }-[ -d "$REPO_DIR/node_modules/ws" ] || { echo "[cdp-shot] node_modules/ws not found under $REPO_DIR (run pnpm install)"; exit 7; }-res="$(NODE_PATH="$REPO_DIR/node_modules" node "$SCRIPT_DIR/cdp-capture.cjs" --port "$PORT" --out "$OUT" --timeout 12000 ${PASS[@]+"${PASS[@]}"} 2>&1)"+# cdp-capture.cjs resolves the `ws` package itself via Node's normal ancestor+# node_modules lookup from its own file location โ no NODE_PATH plumbing needed.+res="$(node "$SCRIPT_DIR/cdp-capture.cjs" --port "$PORT" --out "$OUT" --timeout 12000 ${PASS[@]+"${PASS[@]}"} 2>&1)"ok="$(printf '%s' "$res" | sed -n 's/.*"ok":\([a-z]*\).*/\1/p')"if [ "$ok" != "true" ]; then+ case "$res" in+ *"Cannot find module 'ws'"*)+ echo "[cdp-shot] MISSING DEPENDENCY: $res"+ exit 7+ ;;+ esacecho "[cdp-shot] CAPTURE FAILED: $res"echo "[cdp-shot] Fix: ensure the app runs with --remote-debugging-port=$PORT and CDP is reachable (curl 127.0.0.1:$PORT/json/version). If agent-browser wedged the session earlier, reset it: 'agent-browser close --all'. Raw CDP here does not use that daemon."exit 5diff --git a/.agents/skills/agent-testing/scripts/fixture.mjs b/.agents/skills/agent-testing/scripts/fixture.mjsindex 0160e1f9671..e859a18e7c2 100755--- a/.agents/skills/agent-testing/scripts/fixture.mjs+++ b/.agents/skills/agent-testing/scripts/fixture.mjs@@ -37,22 +37,14 @@* fixture.mjs list --subject topic:tpc_xxx* List the subject's check fixtures.*/-import { execFileSync } from 'node:child_process';import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';-import { basename, dirname, join, resolve } from 'node:path';-import { fileURLToPath } from 'node:url';+import path from 'node:path';-// Anchor to the checkout being TESTED (cwd's git toplevel โ correct when the-// main checkout's script is invoked inside a worktree), not the script's own-// checkout; fall back to script-relative outside any repo.-const repoRoot = () => {- try {- return execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim();- } catch {- return resolve(dirname(fileURLToPath(import.meta.url)), '../../../..');- }-};-const REPO_ROOT = repoRoot();+const { basename, join } = path;++// The generic skill is invoked from the consumer repository. Keep all+// generated fixtures and reports anchored to that explicit working directory.+const REPO_ROOT = process.cwd();const fail = (msg) => {console.error(`fixture.mjs: ${msg}`);diff --git a/.agents/skills/agent-testing/scripts/record-app-screen.sh b/.agents/skills/agent-testing/scripts/record-app-screen.shindex 853b5a335d8..f5c4f1bd6f7 100755--- a/.agents/skills/agent-testing/scripts/record-app-screen.sh+++ b/.agents/skills/agent-testing/scripts/record-app-screen.sh@@ -10,6 +10,9 @@# ./record-app-screen.sh stop # Stop and save# ./record-app-screen.sh status # Check recording state#+# Run this from the CONSUMER repo root โ output goes to .records/ under the+# current working directory, not relative to this script's own location.+## Outputs to .records/ directory:# .records/<name>.mp4 โ Video assembled from screenshots (~2 fps)# .records/<name>/ โ Screenshots every SCREENSHOT_INTERVAL seconds@@ -25,17 +28,13 @@# VIDEO_FRAME_INTERVAL โ Seconds between video frames (default: 0.5)## Examples:-# ./electron-dev.sh start-# ./record-app-screen.sh start gateway-demo+# record-app-screen.sh start gateway-demo# # ... run automation via agent-browser ...-# ./record-app-screen.sh stop+# record-app-screen.sh stop#set -euo pipefail-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-PROJECT_DIR="$(cd "$SCRIPT_DIR/../../../.." && pwd)"--RECORDS_DIR="$PROJECT_DIR/.records"+RECORDS_DIR="$(pwd)/.records"PID_FILE="/tmp/record-app-screen.pids"STATE_FILE="/tmp/record-app-screen.state"diff --git a/.agents/skills/agent-testing/scripts/record-gif.sh b/.agents/skills/agent-testing/scripts/record-gif.shindex 07bcc26c549..d352c3c9e1b 100755--- a/.agents/skills/agent-testing/scripts/record-gif.sh+++ b/.agents/skills/agent-testing/scripts/record-gif.sh@@ -11,7 +11,7 @@# record-gif.sh <output.gif> <duration_seconds> [fps]## AB_TARGET="--cdp 9222" # Electron (default; CDP_PORT honored)-# AB_TARGET="--session lobehub-dev" # web agent-browser session+# AB_TARGET="--session your-session" # web agent-browser session# GIF_WIDTH=960 # output width (px), default 960## Requires ffmpeg (`brew install ffmpeg`). Effective fps is capped bydiff --git a/.agents/skills/agent-testing/scripts/report-init.sh b/.agents/skills/agent-testing/scripts/report-init.shindex d45a9f40626..d2ada73d3d9 100755--- a/.agents/skills/agent-testing/scripts/report-init.sh+++ b/.agents/skills/agent-testing/scripts/report-init.sh@@ -9,13 +9,11 @@# With --subject (task:<id> | topic:<id> | document:<id>) the run is grouped# under its acceptance:# .records/reports/<type>-<id>/<YYYYMMDD-HHMMSS>-<slug>/-# and the group dir gets an acceptance.json marker (created once, updatedAt-# bumped per run). The subject is also pre-filled into result.json so-# `lh verify ingest-report` attaches the run without an explicit --subject.+# and the group directory gets an acceptance.json marker. The subject is also+# pre-filled into result.json so ingest-report attaches the run automatically.#-# Without --subject the legacy flat layout is used:-# .records/reports/<YYYYMMDD-HHMMSS>-<slug>/-# Every run ultimately needs a subject at ingest time โ prefer passing it here.+# Run this from the CONSUMER repo root โ the report is created relative to the+# current working directory, not relative to this script's own location.## Prints the report directory path (capture it: DIR=$(report-init.sh my-test)).@@ -30,10 +28,17 @@ fiSLUG="${1:?Usage: report-init.sh [--subject <type:id>] <slug> [title]}"TITLE="${2:-$SLUG}"-# Anchor to the checkout being TESTED (cwd's git toplevel โ correct when the-# main checkout's script is invoked inside a worktree); fall back to the-# script's own checkout outside any repo.-REPO_ROOT="$(git rev-parse --show-toplevel 2> /dev/null || { cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd; })"+json_escape() {+ local s=$1+ s=${s//\\/\\\\}+ s=${s//\"/\\\"}+ s=${s//$'\n'/\\n}+ s=${s//$'\r'/\\r}+ s=${s//$'\t'/\\t}+ printf '%s' "$s"+}++REPO_ROOT="$(pwd)"TS="$(date +%Y%m%d-%H%M%S)"SUBJECT_JSON="null"@@ -45,7 +50,7 @@ if [[ -n "$SUBJECT" ]]; thenSUBJECT_KEY="${SUBJECT/:/-}"GROUP_DIR="$REPO_ROOT/.records/reports/$SUBJECT_KEY"DIR="$GROUP_DIR/$TS-$SLUG"- SUBJECT_JSON="\"$SUBJECT\""+ SUBJECT_JSON="\"$(json_escape "$SUBJECT")\""elseDIR="$REPO_ROOT/.records/reports/$TS-$SLUG"fi@@ -55,28 +60,27 @@ BRANCH=$(git -C "$REPO_ROOT" branch --show-current 2> /dev/null || echo "unknownCOMMIT=$(git -C "$REPO_ROOT" rev-parse --short HEAD 2> /dev/null || echo "unknown")DATE_ISO=$(date '+%Y-%m-%dT%H:%M:%S%z')-# acceptance.json marks the group dir: what acceptance these runs belong to.-# Created on the first run; only updatedAt/lastRun move afterwards (the title-# from the first scaffold wins โ it names the acceptance, not the round).+# acceptance.json records the group identity. The first title names the+# acceptance; later runs update only the timestamp and latest round.if [[ -n "$SUBJECT" ]]; thenACCEPTANCE_JSON="$GROUP_DIR/acceptance.json"if [[ ! -f "$ACCEPTANCE_JSON" ]]; thencat > "$ACCEPTANCE_JSON" << EOF{- "subject": "$SUBJECT",- "title": "$TITLE",- "createdAt": "$DATE_ISO",- "updatedAt": "$DATE_ISO",- "lastRun": "$TS-$SLUG"+ "subject": "$(json_escape "$SUBJECT")",+ "title": "$(json_escape "$TITLE")",+ "createdAt": "$(json_escape "$DATE_ISO")",+ "updatedAt": "$(json_escape "$DATE_ISO")",+ "lastRun": "$(json_escape "$TS-$SLUG")"}EOFelsenode -e 'const fs = require("fs");- const [file, ts, iso] = process.argv.slice(1);+ const [file, run, iso] = process.argv.slice(1);const data = JSON.parse(fs.readFileSync(file, "utf8"));data.updatedAt = iso;- data.lastRun = ts;+ data.lastRun = run;fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");' "$ACCEPTANCE_JSON" "$TS-$SLUG" "$DATE_ISO"fi@@ -111,12 +115,12 @@ EOF# build / CDP dev instance; that goes on the plan item's \`method\`).cat > "$DIR/result.json" << EOF{- "title": "$TITLE",+ "title": "$(json_escape "$TITLE")","scenario": "coding",- "createdAt": "$DATE_ISO",+ "createdAt": "$(json_escape "$DATE_ISO")","subject": $SUBJECT_JSON,- "branch": "$BRANCH",- "commit": "$COMMIT",+ "branch": "$(json_escape "$BRANCH")",+ "commit": "$(json_escape "$COMMIT")","surfaces": [],"entry": "","plan": [],diff --git a/.agents/skills/agent-testing/surfaces/cli.md b/.agents/skills/agent-testing/surfaces/cli.mdnew file mode 100644index 00000000000..d4650d9b20f--- /dev/null+++ b/.agents/skills/agent-testing/surfaces/cli.md@@ -0,0 +1,103 @@+# CLI Backend Verification++Default surface for verifying **backend changes** (routers, services, models,+migrations) end-to-end: fastest loop, text-assertable output, zero UI flakiness.+The project's CLI, its invocation, and its auth all come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) โ this guide is the+methodology, not the commands.++## When to use++- Verifying router / service / model changes end-to-end+- Testing new API fields or response-structure changes+- Validating CLI command output after backend modifications+- Debugging data flow between server and client++## Prerequisites++| Requirement | Where it comes from |+| ----------------- | --------------------------------------------------------------------------------------------------------------- |+| Dev server | `PROJECT.md` ยง2 (base URL/port, start command, health check) |+| Project CLI | `PROJECT.md` ยง4 (how the CLI is invoked โ run-from-source or built binary โ and its standalone install, if any) |+| Auth | `PROJECT.md` ยง3 (test account / seeded key / device-code login) |+| Required services | `PROJECT.md` ยง6 (any queue/worker/store a command path depends on) |++If the CLI runs from source, code changes on the CLI side usually take effect+immediately without a rebuild; if it is a built binary, rebuild per `PROJECT.md`+before re-testing. Confirm which from the adapter.++## Workflow++### 1 โ Server up?++Health-check per `PROJECT.md` ยง2. Server-side code changes require a restart; the+CLI keeps talking to the old process until you restart it.++### 2 โ Auth ready?++Run the CLI auth status check from `PROJECT.md` ยง3. If it is not authed, follow the+adapter's auth path (seeded credential first, interactive/device-code login as+fallback). Drive the login yourself โ do not hand the user the step unless it needs+a secret or device action only they can supply.++### 3 โ Test with CLI commands++Run the project's CLI commands for the behavior under test. Capture output for the+report as you go:++```bash+# $CLI = the project's CLI invocation from PROJECT.md+$CLI some-command | tee "$DIR/assets/case.txt"+```++CLI evidence for the report = the **exact command + trimmed output**. That is a+non-visual artifact, so a link/transcript in the report is fine (unlike UI cases,+which must inline a screenshot).++### 4 โ Clean up test data++Delete any entities the run created (the adapter lists the CLI's delete commands if+the project has them). Leaving fixtures behind pollutes the next run.++### 5 โ Report++Finish with a structured report โ [../references/report.md](../references/report.md).++## Method notes (project-independent)++- **A backend change is still often a UI-visible change.** A permission tightening,+ a new field, a changed error โ the blocked/changed state is something a user+ sees. If the change alters product behavior a user can observe, add a UI case in+ the same run (see [web.md](./web.md) / [electron.md](./electron.md)); do not ship+ a UI-touching change with only CLI transcripts.+- **Prove which runtime ran.** If a command can dispatch to more than one execution+ path (client vs server/queue), confirm the path you intended actually executed โ+ a server operation row, a queue step, or a server-only log line โ before trusting+ a green result.+- **A required service down looks like a logic bug.** If a command path POSTs to a+ queue/worker/store that is not running, the run can fail before any real work+ happens, with an error that reads as unrelated. Gate on the services `PROJECT.md`+ ยง6 marks as prerequisites.++## Dev-test cycle++```+1. Make code changes (service / model / router / type)+ |+2. Run unit tests (fast feedback)+ |+3. Restart dev server (if server-side changes)+ |+4. CLI verification (end-to-end): <cli> <command>+ |+5. Clean up test data + write the report+```++## Troubleshooting++| Issue | Direction |+| --------------------------- | ------------------------------------------------------------------------ |+| `No authentication found` | Re-run the adapter's auth path (ยง3); source any generated credential env |+| `UNAUTHORIZED` on API calls | Re-seed / re-login per ยง3 |+| `ECONNREFUSED` | Dev server not running โ start per ยง2 |+| CLI shows old data/behavior | Server needs a restart to pick up code changes |diff --git a/.agents/skills/agent-testing/surfaces/electron.md b/.agents/skills/agent-testing/surfaces/electron.mdnew file mode 100644index 00000000000..e9f1d4587c2--- /dev/null+++ b/.agents/skills/agent-testing/surfaces/electron.md@@ -0,0 +1,119 @@+# Electron (Desktop) UI Testing++Default surface for verifying **pure frontend changes** (components, store logic,+styles, interactions) in a project that ships an Electron desktop shell. Drives the+Electron renderer over CDP with `agent-browser` โ see+[../references/agent-browser.md](../references/agent-browser.md) for the full+command reference.++The launch/stop of the desktop dev instance, its CDP port, its login persistence,+and any state probes all come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) ยง4/ยง5. This guide is+the CDP methodology; the project supplies the commands.++## Auth++Sign in once, not once per run โ the project's desktop dev tooling should persist+login across runs (`PROJECT.md` ยง3 says how). If an instance still comes up signed+out, **drive the sign-in yourself**; never ask the user to click it. Run the+desktop auth status check from `PROJECT.md` ยง3 before testing.++## Linux / headless (cloud)++Electron runs on Linux but has no true headless mode โ it needs a display server.+In a headless environment wrap the launch with `xvfb-run` (virtual framebuffer).+Everything CDP-based keeps working under Xvfb: the `agent-browser --cdp <port>`+connection, snapshots, eval, and `agent-browser screenshot` (captured from the+renderer via CDP, not the OS screen). What does NOT work on Linux:+`capture-app-window.sh` (macOS `screencapture`), osascript, and OS-level recording.++## Setup / Teardown++Start and stop the desktop dev instance with the project's own script (per+`PROJECT.md` ยง4) โ it should handle process lifecycle and reliably kill all child+processes (main + helpers + bundler). After start succeeds, connect with:++```bash+PORT=9222 # the CDP port from PROJECT.md+agent-browser --cdp "$PORT" snapshot -i+```++**Always run the project's stop command when done** โ a bare `pkill -f "Electron"`+does not catch all helper processes (GPU, renderer, network), which survive and+corrupt the next run.++## Project probes & quick navigation++A project may ship a **state probe** โ a fast path into app state (auth check,+current route, running operations, and a `goto <path>` quick-navigation that jumps+straight to the state under test instead of clicking through the UI). If it does,+`PROJECT.md` ยง5 documents it; use it instead of hand-rolling store-introspection+eval snippets. When the project has no probe, fall back to raw `agent-browser eval`+against the renderer, reading whatever store/global the app exposes for debugging.++For one-off state inspection, `agent-browser eval` against the CDP target is always+available:++```bash+agent-browser --cdp "$PORT" eval --stdin << 'EVALEOF'+(function() { /* read app state here */ })()+EVALEOF+```++## Method notes (project-independent)++- **A running desktop instance may serve a STALE built bundle, not your working+ tree.** A resident/packaged app serves a built renderer snapshot; it does not+ reflect uncommitted or HMR src changes. Verify working-tree UI in an isolated dev+ instance that loads live code, and **prove it is live by measuring a+ known-changed value** (a computed style, a new string) before trusting any+ screenshot. Don't disturb the user's resident instance โ use a separate dev+ instance/port.+- **Main-process code changes need a restart; renderer HMR does not cover them.**+ If the change lives in the main process (or a package that runs there), reloading+ the renderer verifies nothing โ the old main-process code is still running. Prove+ which code each process has (curl the dev bundler for the renderer source and+ grep for a marker; grep the built main bundle for the marker) before trusting a+ run.+- **Distinguish a non-painting renderer from an empty DOM.** `innerText` needs+ layout, `textContent` does not. If a probe reads `innerText.length === 0` while+ `textContent` still holds the full DOM, the DOM is fine and the renderer is not+ compositing โ often after a mid-session bundler dependency re-optimize; a restart+ of the instance clears it, a `location.reload()` alone may not.++## Electron Gotchas++- **`agent-browser screenshot` can wedge the daemon; prefer raw-CDP capture.**+ agent-browser routes captures through a long-lived daemon. An interrupted or+ mis-invoked screenshot can leave the daemon's CDP session half-open, after which+ **every** later screenshot fails (`CDP response channel closed` / `daemon busy`)+ even though `eval` / `get url` still work. This is **not** a display-sleep or+ permission problem: raw `Page.captureScreenshot` is fast and works even when the+ display is asleep or the window is minimized/occluded. Use the raw-CDP helper for+ Electron evidence and as a preflight:++ ```bash+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --check # preflight: PASS โ capture works+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --out shot.png # viewport+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --out full.png --full # full page (captureBeyondViewport)+ ```++ If agent-browser's own screenshot has already wedged, reset it with+ `agent-browser close --all` (raw-CDP does not use that daemon and is unaffected).++- **Dev builds may auto-open DevTools, which hijacks the CDP target** โ+ `agent-browser --cdp <port>` may attach to the DevTools page (`devtools://โฆ`)+ instead of the app. Symptom: `get url` returns a `devtools://` URL. Fix: close the+ DevTools target and reconnect:++ ```bash+ DT_ID=$(curl -s "http://localhost:$PORT/json/list" | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")+ curl -s "http://localhost:$PORT/json/close/$DT_ID" > /dev/null+ agent-browser close --all && agent-browser --cdp "$PORT" get url # expect the app URL+ ```++- **Don't resize the Electron window after load** โ resizing can trigger a full SPA+ reload and lose your state.++- **Streaming / ticking UI needs GIF evidence** โ see `scripts/record-gif.sh`; a+ static screenshot cannot prove time-based behavior.diff --git a/.agents/skills/agent-testing/surfaces/web.md b/.agents/skills/agent-testing/surfaces/web.mdnew file mode 100644index 00000000000..9488555f89f--- /dev/null+++ b/.agents/skills/agent-testing/surfaces/web.md@@ -0,0 +1,95 @@+# Web (Full-Stack) Testing++Default surface for **full-stack changes** โ a new/changed API plus the UI that+consumes it. The browser is the one surface where network requests and UI state are+observable together, so you can assert both sides of the contract in a single run.++For pure-frontend changes in a project that ships a desktop shell, prefer+[electron.md](./electron.md); for backend-only changes prefer [cli.md](./cli.md).++The base URL, session name, and auth for the web surface come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) ยง4/ยง3. This guide is+the methodology.++## Prerequisites++- Complete [Step 2.0](../SKILL.md#20-resolve-the-current-test-environment) (resolve+ ports) and the [Phase 1 approval gate](../SKILL.md#phase-1-approval-gate--report-environment--plan-to-the-user) first.+- Local dev server running โ start command from `PROJECT.md` ยง2.+- Web auth verified in the agent-browser session โ status check and seeding from+ `PROJECT.md` ยง3.++## Option A โ agent-browser with seeded auth (recommended)++Seed/verify the web session per `PROJECT.md` ยง3, then drive it. Use one named+session as the single evidence source:++```bash+SESSION=your-session # session name from PROJECT.md ยง4+BASE_URL=http://localhost:3000 # base URL from PROJECT.md ยง4++agent-browser --session $SESSION open "$BASE_URL/"+agent-browser --session $SESSION snapshot -i+# interact via refs โ full command reference: ../references/agent-browser.md+```++Use this session as the evidence source. Do not use ordinary Chrome screenshots or+Chrome Network records as proof; ordinary Chrome is only a fallback source for+copying cookies into agent-browser when the seeded login is not available.++### Watch the API while driving the UI++```bash+# After triggering the UI action under test:+agent-browser --session $SESSION network requests --type xhr,fetch+agent-browser --session $SESSION network requests --method POST++# Record a full HAR for the report+agent-browser --session $SESSION network har start+# ... drive the scenario ...+agent-browser --session $SESSION network har stop ./capture.har+```++Assert both layers: the request/response shape (network) and the rendered result+(snapshot/screenshot). Both belong in the report as evidence โ the network dump or+HAR as a linked non-visual artifact, the rendered state as an inline screenshot.++## Option B โ real Chrome with remote debugging++For flows that need a real, visible browser (e.g. exercising the login UI itself):++```bash+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \+ --remote-debugging-port=9222 \+ --user-data-dir=/tmp/chrome-test-profile \+ "<URL>" &+sleep 5+agent-browser --cdp 9222 snapshot -i++# Or auto-discover a running Chrome with remote debugging+agent-browser --auto-connect snapshot -i+```++## Method notes (project-independent)++- **Prove the session is live before trusting an auth-scoped result.** An+ owner-only / permission-gated UI fails identically whether the gate is broken or+ the session is simply missing. `document.cookie` is not the probe โ session+ cookies are often httpOnly, so it reads empty on a fully authenticated page.+ Instead call any authed endpoint from the page and read the status: `401` = no+ session reached the server (re-seed), `200` = you are really signed in. Only then+ conclude anything about the gate.+- **The app can swallow an injected fetch failure.** A store action may resolve+ even when the underlying fetch was aborted, so the UI/promise is not a reliable+ signal that your fault landed. Judge interception by the **fetch's own outcome**+ (wrap `window.fetch` and record each request's resolve/reject) โ see+ [../references/probe-mock-patterns.md](../references/probe-mock-patterns.md) A.+- **A cached first-load can mask a failure.** A surface that loaded once caches the+ last-good value; a later failed fetch keeps showing the settled content instead+ of the error. To see a genuine first-load error, cold-load (clear+ localStorage / sessionStorage / IndexedDB / Cache API), which usually logs you+ out โ re-seed auth after. See probe-mock-patterns B.+- **Enumerate every surface a shared component renders on.** A shared input/toolbar+ can be composed differently on the home page vs an inner page; verify each place+ the changed component appears, with separate evidence, and mark any skipped+ surface explicitly.diff --git a/.agents/skills/agent-testing/ui/electron.md b/.agents/skills/agent-testing/ui/electron.mddeleted file mode 100644index 1ef96bc2c4f..00000000000--- a/.agents/skills/agent-testing/ui/electron.md+++ /dev/null@@ -1,188 +0,0 @@-# Electron (LobeHub Desktop) UI Testing--Default surface for verifying **pure frontend changes** (components, store logic, styles, interactions) in the primary product shape. Drives the Electron renderer over CDP with `agent-browser` โ see [../references/agent-browser.md](../references/agent-browser.md) for the full command reference.--**Auth**: `electron-dev.sh` persists the login across runs โ `stop` snapshots it to `~/.lobehub/agent-testing/electron-login`, `start` seeds each new instance from there (`login-status` inspects it, `save-login <id>` captures a live instance). Sign in once, not once per run โ and if an instance still comes up signed out, **drive the sign-in yourself**; never ask the user to click it. Run `../scripts/setup-auth.sh status` before testing (see [../references/auth.md](../references/auth.md)).--**Linux / headless (cloud)**: Electron itself runs on Linux, but it has no true headless mode โ it needs a display server. In a headless environment wrap the launch with `xvfb-run` (virtual framebuffer). Everything CDP-based keeps working under Xvfb: the `agent-browser --cdp 9222` connection, snapshots, eval, and `agent-browser screenshot` (captured from the renderer via CDP, not the OS screen). What does NOT work on Linux: `capture-app-window.sh` (macOS `screencapture`), osascript, and the ffmpeg recording scripts in their current form.--### Setup / Teardown--Use the `electron-dev.sh` script to manage the Electron dev environment. It handles process lifecycle, waits for SPA readiness, and reliably kills all child processes (main + helpers + vite).--```bash-SCRIPT=".agents/skills/agent-testing/scripts/electron-dev.sh"--# Start Electron dev with CDP (idempotent โ skips if already running)-$SCRIPT start--# Check if Electron is running and CDP is reachable-$SCRIPT status--# Kill all Electron-related processes (main + helper + vite)-$SCRIPT stop--# Force fresh restart-$SCRIPT restart-```--After `start` succeeds, connect with: `agent-browser --cdp 9222 snapshot -i`--**Always run `$SCRIPT stop` when done testing** โ `pkill -f "Electron"` alone won't catch all helper processes.--> **Concurrent instances (N worktrees / parallel verification)?** `electron-dev.sh`-> drives a pool: `start <id>` gives each instance its own CDP port, userData dir-> (with copied login state), and โ via env โ its own Vite port + IPC id, so-> multiple isolated dev instances run at once. Drive each with a distinct-> `agent-browser --session s<port> --cdp <port>` (the daemon otherwise reuses one-> session across ports). Full design, the collision matrix, and the login-copy-> recipe: [../references/multi-instance.md](../references/multi-instance.md).--#### Environment Variables--| Variable | Default | Description |-| ---------------------- | ----------------------------------------- | ------------------------------------------------- |-| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |-| `ELECTRON_LOG` | `/tmp/electron-dev.log` | Electron process log |-| `ELECTRON_WAIT_S` | `60` | Max seconds to wait for Electron process |-| `RENDERER_WAIT_S` | `60` | Max seconds to wait for SPA to load |-| `LOBE_LOGIN_STATE_DIR` | `~/.lobehub/agent-testing/electron-login` | Persistent login snapshot (survives `/tmp` wipes) |-| `KEEP_DATA` | `0` | `1` = `stop <id>` keeps the instance's userData |-| `SKIP_LOGIN_SAVE` | `0` | `1` = `stop <id>` does not snapshot the login |--### LobeHub Probes & Quick Navigation--`scripts/app-probe.sh` is the standard fast path into app state โ **use it-instead of hand-rolling `__LOBE_STORES` eval snippets** for these common needs:--```bash-PROBE=".agents/skills/agent-testing/scripts/app-probe.sh"--$PROBE auth # login check (Step 2.4) โ { isSignedIn, userId }-$PROBE route # current SPA route-$PROBE ops # running chat operations (type / startTime)-$PROBE goto /settings # jump the SPA straight to a route (full reload)-$PROBE errors-install # install console.error interceptor-$PROBE errors # dump captured errors-```--`goto` lets a test enter the state under test directly instead of clicking-through the UI. Common desktop routes:--| Route | Where it lands |-| ---------------------------- | --------------------------------- |-| `/` | Home (has a chat input) |-| `/agent/<agentId>` | Agent conversation (latest topic) |-| `/agent/<agentId>/<topicId>` | Specific topic in a conversation |-| `/task` ยท `/task/<taskId>` | Task list / task detail |-| `/page` | Documents (ๆ็จฟ) |-| `/settings` | Settings |-| `/community` | Discover / community |--Targets default to Electron (`--cdp 9222`); set `AB_TARGET="--session <name>"`-for web sessions. For deeper or one-off state inspection, fall back to raw-eval below.--### LobeHub-Specific Patterns--#### Access Zustand Store State--```bash-agent-browser --cdp 9222 eval --stdin << 'EVALEOF'-(function() {- var chat = window.__LOBE_STORES.chat();- var ops = Object.values(chat.operations);- return JSON.stringify({- ops: ops.map(function(o) { return { type: o.type, status: o.status }; }),- activeAgent: chat.activeAgentId,- activeTopic: chat.activeTopicId,- });-})()-EVALEOF-```--#### Find and Use the Chat Input--```bash-# The chat input is contenteditable โ must use -C flag-agent-browser --cdp 9222 snapshot -i -C 2>&1 | grep "editable"--agent-browser --cdp 9222 click @e48-agent-browser --cdp 9222 type @e48 "Hello world"-agent-browser --cdp 9222 press Enter-```--#### Wait for Agent to Complete--```bash-agent-browser --cdp 9222 eval --stdin << 'EVALEOF'-(function() {- var chat = window.__LOBE_STORES.chat();- var ops = Object.values(chat.operations);- var running = ops.filter(function(o) { return o.status === 'running'; });- return running.length === 0 ? 'done' : 'running: ' + running.length;-})()-EVALEOF-```--#### Install Error Interceptor--```bash-agent-browser --cdp 9222 eval --stdin << 'EVALEOF'-(function() {- window.__CAPTURED_ERRORS = [];- var orig = console.error;- console.error = function() {- var msg = Array.from(arguments).map(function(a) {- if (a instanceof Error) return a.message;- return typeof a === 'object' ? JSON.stringify(a) : String(a);- }).join(' ');- window.__CAPTURED_ERRORS.push(msg);- orig.apply(console, arguments);- };- return 'installed';-})()-EVALEOF--# Later, check captured errors:-agent-browser --cdp 9222 eval "JSON.stringify(window.__CAPTURED_ERRORS)"-```--## Electron Gotchas--- **`agent-browser screenshot` can wedge; prefer raw-CDP capture.** `agent-browser`- routes captures through a long-lived daemon. An interrupted or mis-invoked- screenshot (a stalled `--full` on a huge page, a killed/backgrounded command, a- bad flag) can leave the daemon's CDP session half-open, after which **every**- later screenshot fails with `CDP response channel closed` / `daemon busy` โ even- though `eval` / `get url` still work. This is **not** a display-sleep or- permission problem: raw `Page.captureScreenshot` is fast (\~60ms) and works even- when the display is asleep or the window is minimized/occluded (verified). Use- the raw-CDP helper for Electron evidence and as a preflight:-- ```bash- ./.agents/skills/agent-testing/scripts/cdp-screenshot.sh --check # preflight: PASS โ capture works- ./.agents/skills/agent-testing/scripts/cdp-screenshot.sh --out shot.png # viewport- ./.agents/skills/agent-testing/scripts/cdp-screenshot.sh --out full.png --full # full page (captureBeyondViewport)- ```-- If agent-browser's own screenshot has already wedged, reset it with- `agent-browser close --all` (raw-CDP does not use that daemon and is unaffected).--- **Always use `electron-dev.sh stop` to clean up** โ `pkill -f "Electron"` only kills the main process; helper processes (GPU, renderer, network) survive. The script finds and kills all of them via PID matching against the project's electron binary path.--- **`pnpm dev` must run from `apps/desktop/`** โ running from project root starts the web app instead. The `electron-dev.sh` script handles this automatically.--- **Dev build auto-opens DevTools, which hijacks the CDP target** โ `agent-browser --cdp 9222` may attach to the DevTools page (`devtools://โฆ`) instead of the app (`app://renderer/`). Symptom: `get url` returns a `devtools://` URL. Fix: close the DevTools target and reconnect:-- ```bash- DT_ID=$(curl -s http://localhost:9222/json/list | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")- curl -s "http://localhost:9222/json/close/$DT_ID" > /dev/null- agent-browser close --all && agent-browser --cdp 9222 get url # expect app://renderer/- ```--- **Don't resize the Electron window after load** โ resizing triggers full SPA reload--- **Store is at `window.__LOBE_STORES`** not `window.__ZUSTAND_STORES__`--- **Streaming / ticking UI needs GIF evidence** โ see `scripts/record-gif.sh`; a static screenshot cannot prove time-based behavior.diff --git a/.agents/skills/agent-testing/ui/web.md b/.agents/skills/agent-testing/ui/web.mddeleted file mode 100644index 39be53f00ca..00000000000--- a/.agents/skills/agent-testing/ui/web.md+++ /dev/null@@ -1,78 +0,0 @@-# Web (Full-Stack) Testing--Default surface for **full-stack changes** โ a new/changed API plus the UI that-consumes it. The browser is the one surface where network requests and UI state-are observable together, so you can assert both sides of the contract in a-single run.--For pure-frontend changes prefer [electron.md](./electron.md); for-backend-only changes prefer [../cli/index.md](../cli/index.md).--## Prerequisites--- Complete [Step 2.0](../SKILL.md#20-resolve-the-current-test-environment) (resolve ports) and the [Phase 1 approval gate](../SKILL.md#phase-1-approval-gate--report-environment--plan-to-the-user) first.-- Local dev server running โ [../references/dev-server.md](../references/dev-server.md)-- Web auth verified in agent-browser โ prefer `setup-auth.sh web-seed`, see [auth decision flow](../references/auth.md#web--decision-flow).--## Option A โ agent-browser with seeded auth (recommended)--```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user-./.agents/skills/agent-testing/scripts/setup-auth.sh web-seed-```--Then drive the verified session:--```bash-SESSION=lobehub-dev--agent-browser --session $SESSION open "$SERVER_URL/"-agent-browser --session $SESSION snapshot -i-# interact via refs โ full command reference: ../references/agent-browser.md-```--Use this session as the evidence source. Do not use ordinary Chrome screenshots-or Chrome Network records as proof for Web tests; ordinary Chrome is only a-fallback source for copying cookies into agent-browser when the seeded login is-not available.--### Watch the API while driving the UI--```bash-# After triggering the UI action under test:-agent-browser --session $SESSION network requests --type xhr,fetch-agent-browser --session $SESSION network requests --method POST--# Record a full HAR for the report-agent-browser --session $SESSION network har start-# ... drive the scenario ...-agent-browser --session $SESSION network har stop ./capture.har-```--Assert both layers: the request/response shape (network) and the rendered-result (snapshot/screenshot). Both belong in the report as evidence.--## Option B โ real Chrome with remote debugging--For flows that need a real, visible browser (e.g. exercising the login UI-itself):--```bash-/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \- --remote-debugging-port=9222 \- --user-data-dir=/tmp/chrome-test-profile \- "<URL>" &-sleep 5-agent-browser --cdp 9222 snapshot -i--# Or auto-discover running Chrome with remote debugging-agent-browser --auto-connect snapshot -i-```--## Option C โ Debug Proxy (local frontend, production backend)--`bun run dev:spa` prints a **Debug Proxy** URL-(`https://app.lobehub.com/_dangerous_local_dev_proxy?debug-host=โฆ`) that loads-your local Vite SPA inside the online environment โ HMR against real server-config. Useful for verifying frontend behavior against production data, **not**-for testing backend changes (the backend is production, not your branch).diff --git a/.agents/skills/ux-audit/references/layer-3-dynamic.md b/.agents/skills/ux-audit/references/layer-3-dynamic.mdindex 7eb0b06f893..061eb6e82e3 100644--- a/.agents/skills/ux-audit/references/layer-3-dynamic.md+++ b/.agents/skills/ux-audit/references/layer-3-dynamic.md@@ -15,13 +15,13 @@ Part of the **ux-audit** skill โ see [`../SKILL.md`](../SKILL.md).Connect to the running app (Electron or web) and use:-| Command | Use in an audit |-| ------------------------------------------ | ------------------------------------------------------------------------------ |-| `agent-browser --cdp 9222 snapshot -i` | accessibility/DOM tree + interactive elements (find controls, assert presence) |-| `agent-browser --cdp 9222 screenshot` | render evidence at each step (feeds L2 checks) |-| `agent-browser --cdp 9222 eval "<js>"` | **instrument** โ inject web-vitals, read state, force conditions |-| `type` / `click` (see agent-testing `ui/`) | drive the journey |-| `scripts/record-gif.sh` | time-based evidence (streaming, a layout jump) |+| Command | Use in an audit |+| ------------------------------------------------ | ------------------------------------------------------------------------------ |+| `agent-browser --cdp 9222 snapshot -i` | accessibility/DOM tree + interactive elements (find controls, assert presence) |+| `agent-browser --cdp 9222 screenshot` | render evidence at each step (feeds L2 checks) |+| `agent-browser --cdp 9222 eval "<js>"` | **instrument** โ inject web-vitals, read state, force conditions |+| `type` / `click` (see agent-testing `surfaces/`) | drive the journey |+| `scripts/record-gif.sh` | time-based evidence (streaming, a layout jump) |> **Constraint:** resizing the Electron window triggers a full SPA reload โ do **responsive> / multi-viewport** sweeps against **web Chrome over CDP**, not by resizing Electron.diff --git a/.agents/verify/PROJECT.md b/.agents/verify/PROJECT.mdnew file mode 100644index 00000000000..76496df629f--- /dev/null+++ b/.agents/verify/PROJECT.md@@ -0,0 +1,326 @@+# PROJECT.md โ agent-testing adapter for LobeHub++This is the LobeHub adapter for the generic `agent-testing` skill. The skill is+project-agnostic; every LobeHub-specific command, port, service, and probe lives+here. The skill reads this file โ it never guesses LobeHub's commands.++Scripts referenced below live under `.agents/verify/scripts/`. The generic skill+and its own scripts (`report-init.sh`, `cdp-screenshot.sh`, `record-gif.sh`,+`check-screen-recording.sh`, โฆ) are installed at `.agents/skills/agent-testing/`.++## 1. Project summary++LobeHub is a chat/agent product with a Next.js server, a Vite + React SPA, an+Electron desktop shell, and a CLI (`lh`). Repo layout that matters for testing:++- `apps/server/` โ the Next.js backend (TRPC routers, services, modules, auth).+- `apps/desktop/` โ the Electron shell. **Standalone install** (see ยง6).+- `apps/cli/` โ the `lh` CLI; runs from source (`bun src/index.ts`), no rebuild.+ **Standalone install** (see ยง6).+- `packages/**`, `e2e`, `apps/server` โ covered by the root pnpm workspace.+- `src/` โ the SPA and shared web app; `src/server/` holds agent-hono /+ workflows-hono.++**The root pnpm workspace does NOT cover `apps/desktop` or `apps/cli`.**+`pnpm-workspace.yaml` lists `packages/**`, `e2e`, `apps/server`, and only+`apps/desktop/src/main`. Those two apps keep their own `node_modules` with their+own links into `packages/`; a root install does not refresh them. Symptom of a+stale standalone install: a recently added workspace package fails to resolve โ+`Rolldown failed to resolve import "@lobechat/<pkg>"` (Electron) or+`Cannot find module '@lobechat/<pkg>'` (CLI).++## 2. Environment++- **Start dev server:**++ - With repo-root `.env` present: use the existing local config โ `bun run dev`+ (full-stack, needed for Web smoke) or `AGENT_RUNTIME_MODE=queue pnpm run dev:next`+ (backend only). Do NOT call any `init-dev-env.sh` subcommand when `.env` exists.+ - Without `.env`: use the skill-owned bootstrap `.agents/verify/scripts/init-dev-env.sh`+ (Postgres, Redis, migrations, auth/key-vault/S3 test env, seed user, then the+ repo's own dev server โ not `e2e/scripts/setup.ts`). It hard-blocks when+ root `.env` exists, so it can never override a user's local config.++ ```bash+ if [[ -f .env ]]; then+ bun run dev+ else+ .agents/verify/scripts/init-dev-env.sh setup-db+ .agents/verify/scripts/init-dev-env.sh s3 # terminal B โ keep running+ .agents/verify/scripts/init-dev-env.sh seed-user+ .agents/verify/scripts/init-dev-env.sh dev+ fi+ ```++ `dev-next` starts the Next.js backend only; Web smoke needs the full-stack+ `dev` so Next proxies the SPA HTML from Vite. `bun run dev:spa` runs the Vite+ SPA alone, proxying the API to `PORT`.++- **Stop dev server (must stop only what THIS run started):**++ ```bash+ .agents/verify/scripts/init-dev-env.sh clean # stop the recorded dev-server PID tree; keep DB/Redis+ .agents/verify/scripts/init-dev-env.sh stop-dev # just the server, no note+ ```++ `clean` stops only the recorded dev-server PID tree after verifying its PID+ start time, command, and working directory; it never matches by process name+ and never kills a listener merely because it owns a persisted port. It leaves+ the managed Postgres/Redis containers running (reused across runs โ `setup-db`+ is a no-op when they are up). `clean-db` removes the managed DB container;+ `clean-s3` removes persisted local S3 objects. If the user started their own+ `.env` dev server, leave it โ you did not start it.++- **Required services:**+ - **Postgres + Redis** โ `init-dev-env.sh setup-db` (managed Docker containers+ `lobehub-agent-testing-postgres` / `lobehub-agent-testing-redis`; requires+ Docker Desktop). To use an existing DB instead, set `DATABASE_URL` /+ `REDIS_URL` and skip `setup-db` (run `migrate` + `seed-user` with those env).+ - **s3rver (local S3)** โ `init-dev-env.sh s3` (terminal B). A hard prerequisite+ for browser uploads, presigned URLs, attachments, and generated files: the+ no-`.env` bootstrap points the app at local `s3rver` so those exercise a real+ S3 HTTP round trip. Creates `agent-testing-bucket`, configures CORS for the+ allocated local origins, persists objects under+ `.records/data/agent-testing-s3`. Fixed `S3RVER` credentials are required by+ the emulator's presigned-URL validation. `preflight` does HeadBucket + a real+ Put/Get/Delete round trip; a listening port alone is not "ready".+ - **QStash** โ `init-dev-env.sh qstash` (terminal B). A hard prerequisite for+ ANY agent-runtime test (see ยง6).++- **Already-running detection:**++ ```bash+ curl -s -o /dev/null -w '%{http_code}' "$SERVER_URL/"+ ```++- **Env / port resolution:** `.agents/verify/scripts/test-env.sh` is the source+ of truth for local test ports โ do NOT hard-code a port table. It reads the+ current shell plus `.env` files with the same precedence as+ `scripts/runWithEnv.mts` and prints `APP_URL`, `PORT`, `SERVER_URL`,+ `AUTH_TRUSTED_ORIGINS`, `SPA_PORT`, `MOBILE_SPA_PORT`, `DESKTOP_PORT`.++ ```bash+ .agents/verify/scripts/test-env.sh # print resolved env + ports+ eval "$(.agents/verify/scripts/test-env.sh --exports)" # export them+ ```++ Default script env (no-`.env` bootstrap): `APP_URL=http://localhost:3010`,+ `DATABASE_URL=postgresql://postgres:postgres@localhost:5433/postgres`,+ `DATABASE_DRIVER=node`, `AGENT_RUNTIME_MODE=queue`,+ `REDIS_URL=redis://localhost:6380`, `FEATURE_FLAGS=-agent_self_iteration`,+ `KEY_VAULTS_SECRET`, `AUTH_SECRET`, auth verification off, plus local `s3rver`+ and local QStash vars. Treat the dev-server terminal output as final when the+ port is non-standard, then `export SERVER_URL=http://localhost:<port>`.++ In the cloud repo (this repo as the `lobehub/` submodule), worktree names map+ to fallback `SERVER_URL` defaults only when `.env` and shell env give none:+ `lobehub`โ3010, `lobehub-cloud`โ3020, `lobehub-cloud-N`โ`3020+N`.++- **Cucumber note:** when running Cucumber against this dev server in the no-`.env`+ branch, pass the same script env into the test process (`eval "$(.agents/verify/scripts/init-dev-env.sh env)"`)+ โ Cucumber's own `BeforeAll` seed path must see `DATABASE_URL` or it silently+ skips setup.++- **Ports/modes table, the per-path server-restart matrix, and env+ troubleshooting:** `.agents/verify/references/dev-server.md`.++## 3. Auth++- **Test account:** `[email protected]` / `TestPassword123!`, onboarding+ completed. Created by `init-dev-env.sh seed-user`, which also writes a local+ CLI API key to `.records/env/agent-testing-cli.env`.++- **Seeding command:** `.agents/verify/scripts/init-dev-env.sh seed-user`.++- **Setup helper:** `.agents/verify/scripts/setup-auth.sh` โ `status` (all+ surfaces), `status --surface <cli|web|electron>`, `cli-seed`, `cli` (interactive+ device-code, user runs it), `web-seed`, `open-chrome`, `web` (inject a copied+ Cookie header), `web-verify`. Auth is a surface-scoped gate: pick the intended+ surface and check only it (do not block a Web test on CLI device-code auth).++- **Per-surface status check:**++ | Surface | Mechanism | One-key path | Standard check |+ | -------- | --------------------------------------------- | ------------------------ | ----------------------------------------- |+ | CLI | Seeded API key, device-code fallback | `setup-auth.sh cli-seed` | `setup-auth.sh status --surface cli` |+ | Web | Seeded better-auth login into `agent-browser` | `setup-auth.sh web-seed` | `setup-auth.sh status --surface web` |+ | Electron | The app's own persistent login state | log in once in the app | `setup-auth.sh status --surface electron` |++- **Chrome-cookie fallback (Web only):** ordinary Chrome is only a source for+ copying the better-auth session cookie into the `agent-browser` session+ (`lobehub-dev`) when seed auth is unavailable or `status --surface web` still+ fails. Copy the `Cookie:` header from the Network tab (NOT `document.cookie` โ+ HttpOnly cookies are invisible there), then `pbpaste | setup-auth.sh web`. Use+ `localhost`, not `127.0.0.1` (better-auth cookies are stored for `localhost`).+ Never do this against production. Full decision flow, seeded-login mechanics,+ and failure modes: `.agents/verify/references/auth.md`.++- **Login-state check** is standardized โ do NOT hand-roll a `window.__LOBE_STORES`+ eval; use `.agents/verify/scripts/app-probe.sh auth` (returns `{ isSignedIn, userId }`,+ works for Electron CDP and web sessions via `AB_TARGET`).++## 4. Surfaces++### CLI++- Invocation: from source, no rebuild โ `cd apps/cli && bun src/index.ts <cmd>`+ (referred to as `$CLI`). CLI-side code changes take effect immediately.+- Auth: see ยง3 CLI. Source the seeded profile first:+ `source .records/env/agent-testing-cli.env`. It sets `LOBE_API_KEY` /+ `LOBEHUB_CLI_API_KEY`, `LOBEHUB_SERVER=http://localhost:3010`, and+ `LOBEHUB_CLI_HOME=.lobehub-dev` for isolated settings.+- **Local-run vs publish env distinction:** those seeded overrides are for+ _running_ the local backend test. They are WRONG for _publishing_ โ a localhost+ run yields a verify URL nobody else can open, and the local stub S3 makes+ evidence upload fail. Strip them for the publish step (the skill's Step 6 does+ `env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME lh verify ingest-report โฆ`+ so `lh` uses production defaults + the user's real `~/.lobehub` login).+- Standalone install: `cd apps/cli && pnpm install` (root install does not cover it).++### Web++- Launch: full-stack dev server from ยง2 (`bun run dev` or `init-dev-env.sh dev`).+- Base URL: `$SERVER_URL` (default `http://localhost:3010`).+- agent-browser session: `lobehub-dev`. Seed it with `setup-auth.sh web-seed`;+ drive it as the sole evidence source (do not use ordinary Chrome screenshots+ or Network records as proof). Full-stack is the one surface where network+ requests and rendered UI are observable together โ assert both.+- SPA proxying note: Web smoke needs the full-stack `dev` so Next proxies the+ SPA HTML from Vite; `dev-next` alone will not serve the SPA.+- Local frontend against production backend: `bun run dev:spa` prints a+ `_dangerous_local_dev_proxy` URL that loads your local Vite SPA inside the+ online environment (HMR against real server config) โ for verifying frontend+ behavior against production data only, NOT for testing backend branch changes.++### Electron++- Launch: `.agents/verify/scripts/electron-dev.sh start` โ CDP port `9222`+ (idempotent; `status` / `stop` / `restart`; env `CDP_PORT`, `ELECTRON_LOG`,+ `ELECTRON_WAIT_S`, `RENDERER_WAIT_S`, `LOBE_LOGIN_STATE_DIR`, `KEEP_DATA`,+ `SKIP_LOGIN_SAVE`). Connect with `agent-browser --cdp 9222 snapshot -i`.+- Stop: `.agents/verify/scripts/electron-dev.sh stop` โ always use this;+ `pkill -f "Electron"` leaves helper processes (GPU, renderer, network) alive.+- Login persistence: `stop` snapshots the login to+ `~/.lobehub/agent-testing/electron-login`; `start` seeds each new instance+ from it (`login-status` inspects it, `save-login <id>` captures a live one).+ Sign in once, not once per run โ and if an instance comes up signed out, drive+ the sign-in yourself (the OAuth+PKCE recipe and the three token-rotation traps+ are in `.agents/verify/references/auth.md`); never ask the user to click it.+- Concurrent instances (N worktrees / parallel runs): `electron-dev.sh` drives a+ pool โ `start <id>` gives each its own CDP port, userData dir (with copied+ login), Vite port, and IPC id. Drive each with a distinct+ `agent-browser --session s<port> --cdp <port>`. Pool design, the collision+ matrix, and the login-copy recipe: `.agents/verify/references/multi-instance.md`.++### Bot channels (project skill)++Bot-channel surfaces (Discord / Slack / Telegram / WeChat / Lark / QQ / iMessage)+live in a separate LobeHub project skill, `agent-testing-bot`+(`.agents/skills/agent-testing-bot/`). It extends this same Plan/Execute/Finish+process and report pipeline for the native-app surfaces (osascript / bridge,+macOS-only). Route bot tests there.++## 5. Project probes & quick navigation++`.agents/verify/scripts/app-probe.sh` is the LobeHub fast path into app state โ+use it instead of hand-rolling `window.__LOBE_STORES` eval snippets. Targets+default to Electron (`--cdp 9222`); set `AB_TARGET="--session <name>"` for web+sessions.++```bash+PROBE=.agents/verify/scripts/app-probe.sh+$PROBE auth # login check โ { isSignedIn, userId }+$PROBE route # current SPA route+$PROBE ops # running chat operations (type / startTime)+$PROBE goto /settings # jump the SPA straight to a route (full reload)+$PROBE errors-install # install console.error interceptor+$PROBE errors # dump captured errors+```++Routes worth jumping to:++| Route | Where it lands |+| ---------------------------- | --------------------------------- |+| `/` | Home (has a chat input) |+| `/agent/<agentId>` | Agent conversation (latest topic) |+| `/agent/<agentId>/<topicId>` | Specific topic in a conversation |+| `/task` ยท `/task/<taskId>` | Task list / task detail |+| `/page` | Documents (ๆ็จฟ) |+| `/settings` | Settings |+| `/community` | Discover / community |++The Zustand store is at `window.__LOBE_STORES` (not `__ZUSTAND_STORES__`); the+chat input is `contenteditable` (snapshot with `-C`). For deeper one-off state+inspection, fall back to raw `agent-browser --cdp 9222 eval`. The agent-gateway+closed-loop probe/dump/analyze tooling lives at+`.agents/verify/scripts/agent-gateway/`; the closed-loop + JWKS setup workflow is+in `.agents/verify/references/agent-gateway.md`.++## 6. Known constraints++- **QStash is a hard prerequisite for ANY agent-runtime test.** Any test that+ runs an agent (`lh agent run`, durable ops, `/api/agent/run`, the server agent+ runtime) goes through `AGENT_RUNTIME_MODE=queue` (the default here and in+ production). Creating an agent operation POSTs to local QStash+ (`127.0.0.1:8080`); if QStash is down the run dies at operation creation with+ `TypeError: fetch failed` / `ECONNREFUSED 127.0.0.1:8080` **before any LLM+ call** โ no trace is recorded and it reads as unrelated to the env. Start it+ and gate before the first `agent run`:++ ```bash+ .agents/verify/scripts/init-dev-env.sh qstash # terminal B โ keep running+ .agents/verify/scripts/init-dev-env.sh preflight # non-zero exit if QStash (or Redis) is down+ ```++ `FEATURE_FLAGS=-agent_self_iteration` only drops the self-iteration workflow+ (so a simple chat does not fan out); it does NOT remove QStash from the+ agent-runtime dispatch path. Treat QStash as required, not an "only-for-workflow"+ nicety.++- **Verify which runtime actually ran โ do not assume.** Some features have two+ execution paths and the UI silently picks one. Group orchestration is the+ concrete example: the chat UI defaults to the **client** runtime, while a fix+ may live in the **server** runtime / `AGENT_RUNTIME_MODE=queue` durable-op path.+ A test that exercises the wrong path passes green without touching the code+ under test. Prove which ran (a server `agent_operations` row, the QStash+ `/api/agent/run` steps, server-only log lines); if the UI will not take the+ server path, drive it directly (call the server TRPC mutation / endpoint).++- **`apps/desktop` and `apps/cli` are standalone installs** (see ยง1) โ run+ `pnpm install` inside each app the test will touch, not only at the root.++- **Server restart picks up server-side code changes.** Next.js hot-reload may+ miss changes in workspace packages. Restart when changing `apps/server/src/`,+ `src/server/`, `packages/database/`, `packages/types/`, `packages/prompts/`;+ `apps/cli/` needs none (runs from source).++- **OS-capture surfaces are macOS-only** (bot channels, `capture-app-window.sh`,+ osascript screenshots): they come out black without Screen Recording (TCC)+ permission or when the display is asleep/locked. CDP-based evidence+ (`agent-browser screenshot`, the installed skill's `cdp-screenshot.sh`) is+ unaffected. Electron runs on Linux/cloud only under `xvfb-run`, and there OS+ capture does not work โ prefer CDP evidence for cloud-portable runs.++- **`ENABLE_MOCK_DEV_USER` is not Web auth** โ it only affects server-side API+ context and does not satisfy Better Auth or stop the SPA redirect to `/signin`.++- Marketplace/community endpoints are not part of the local auth gate; do not+ block local verification on marketplace API auth unless the change targets it.++## Project references++Deeper LobeHub-specific notes kept alongside the moved scripts:++- `.agents/verify/references/auth.md` โ per-surface auth mechanics, the seeded+ web-login flow, the Electron OAuth+PKCE sign-in recipe and token-rotation traps,+ and the Chrome cookie-injection fallback + failure modes.+- `.agents/verify/references/agent-gateway.md` โ the local agent-gateway+ closed-loop setup / probe / dump / analyze workflow (scripts under+ `.agents/verify/scripts/agent-gateway/`).+- `.agents/verify/references/multi-instance.md` โ the concurrent Electron+ instance pool (N worktrees / parallel runs): per-instance CDP port, userData,+ Vite port, IPC id, the collision matrix, and the login-copy recipe.++The living logs (`.agents/verify/common-mistakes.md`,+`.agents/verify/probe-mock-patterns.md`) hold the LobeHub-specific probe/mock and+mistake recipes; the generic layer lives in the installed skill's `references/`.diff --git a/.agents/verify/common-mistakes.md b/.agents/verify/common-mistakes.mdnew file mode 100644index 00000000000..459876b1cbc--- /dev/null+++ b/.agents/verify/common-mistakes.md@@ -0,0 +1,108 @@+# Common Mistakes โ PROJECT layer (LobeHub)++> **PROJECT layer โ writable, LobeHub-specific.** Append project learnings here+> during runs (each: Wrong approach / Why it's wrong / What it breaks / Correct+> approach). The generic, product-independent mistake catalogue lives in the+> installed skill's `references/common-mistakes.md` (read-only in this repo,+> updated by PR to `@lobehub/cli`) โ read BOTH layers before a run. When an entry+> here turns out to be product-independent, genericize it (drop the LobeHub+> nouns) and PR it upstream.+>+> Most of the historically accumulated cases were promoted to the generic layer;+> what remains here is the LobeHub-platform-specific residue (the verify /+> Acceptance page mechanics, permission-surface framing). Cases keep their+> original numbers so older cross-references still resolve; a reference to a case+> not in this file now lives in the generic layer.++---++## Case 25 โ Building a surface's "twin" without walking the sibling implementation feature-by-feature++**Wrong approach**: when asked to make surface B "consistent with" an existing surface A (a list+panel, an evidence renderer, a link chip), skimming A for its visual language (colors, spacing,+component choices) and rebuilding B from that impression โ instead of walking A's implementation+feature-by-feature and porting each one deliberately. In one round this dropped: A's search box,+A's before/after comparison rendering, and A's authored-report field conventions (title / verdict /+comparison labels), while a hover state contradicted the intended text-emphasis semantics.++**Why it's wrong**: "consistency" is a checklist over the sibling's FEATURES, not a style match.+Every capability the sibling has that the twin lacks is a bug the user will find one screenshot+later. The ux skill's own line โ "compose the canonical surface component, don't re-derive it" โ+covers exactly this, but it only bites if the sibling is actually enumerated before building.++**What it breaks**: the user gets a surface that looks 90% right and is missing load-bearing+features; a round of "ไธบไปไน่ฟ้็ผบ X / ไธขไบ Y" feedback that a 10-minute sibling walk would have+prevented; trust that "ๅฏน้ฝ" means aligned.++**Correct approach**: before building a twin surface, enumerate the sibling's implementation โ+grep its component for every rendered affordance (search, empty states, comparison views, hover+behaviors, drawer wiring) and its data conventions (which fields the author must supply) โ and+turn that list into the build checklist. After building, diff the two surfaces side by side in+screenshots before publishing. For authored artifacts (result.json), re-read the field spec in+the report reference instead of writing from memory: `title` and `summary.verdict` are identity+fields, and comparison pairs need per-side `label`s.++---++## Case 20 (a) โ Publishing a replacement as a second Acceptance row and passing UI from text-only evidence++**Wrong approach**: giving a refined check a new id without declaring `supersedes`, then marking+visual UI checks passed from unit-test output or computed-style text without capturing and opening a+screenshot of each claimed surface. A layout probe also accepted an absolutely positioned sidebar+because it was right-aligned, without checking whether it covered the report.++**Why it's wrong**: the Acceptance union intentionally does no fuzzy title matching; without an explicit+replacement edge, both ids are valid independent requirements. Program output proves logic, not the+rendered Markdown entity or the absence of visual overlap. A single CSS property is not the layout+contract.++**What it breaks**: superseded wording remains as a duplicate row, UI changes have no inspectable proof,+and a green report can visibly cover its own content.++**Correct approach**: when a new check replaces an older semantic requirement, put the prior stable id in+the new plan item's `supersedes` array. Every user-visible UI case must require its own screenshot, open+that image before passing, and assert the complete spatial outcome (right attachment plus zero overlap),+not an isolated computed-style value. Never reuse one screenshot as evidence for unrelated UI cases.++---++## Case 20 (b) โ Calling a server-side permission change "no UI surface" and shipping an API-transcript-only report++> The generic layer covers the broad rule (a UI-touching change needs visual evidence); this entry+> keeps the LobeHub-specific framing of an authorization/permission change as a UI surface. Candidate+> to genericize + upstream if it stops being LobeHub-specific.++**Wrong approach**: for a change that only edits TRPC routers (tightening who may+mutate a shared resource), classifying the run as backend-only and publishing a+verify report whose evidence is exclusively curl/API probe transcripts. The user+opened the report and asked "ๅฎๅ จๆฒกๆๆชๅพๅ๏ผ".++**Why it's wrong**: a permission tightening IS a UI-visible state โ the blocked+user still sees the edit/delete affordances and now gets a rejection (error toast /+failed action) when clicking them. "The diff touches no .tsx file" does not mean+"no UI surface"; the UI surface is the product behavior the change alters, not the+files it edits.++**What it breaks**: the report cannot show what a real blocked user experiences+(is the rejection surfaced comprehensibly? silently swallowed? a raw error?), and+it misses UX follow-ups the screenshot would expose (e.g. affordances that should+be hidden/disabled for users who will always be rejected).++**Correct approach**: for any authorization/permission change, drive the REAL UI+as the blocked role and screenshot the rejection state (and the allowed role's+success state) in addition to API probes. If the rejection renders as a raw or+missing error message, report that as a finding instead of leaving it undiscovered.++---++## Case 26 โ Applying dual scope to only one bulk-maintenance action++**Wrong approach**: introduce own-scope and workspace-scope variants for one+bulk action while leaving sibling maintenance actions owner-own-only.++**Why it is wrong**: authority was evaluated per menu entry rather than across+the complete role ร action ร scope matrix.++**Correct approach**: enumerate every matrix cell. Members receive own-only+actions; owners receive both own and workspace variants for each applicable+action, with elevated confirmation for destructive workspace-wide operations.diff --git a/.agents/verify/probe-mock-patterns.md b/.agents/verify/probe-mock-patterns.mdnew file mode 100644index 00000000000..5d1ba75c94e--- /dev/null+++ b/.agents/verify/probe-mock-patterns.md@@ -0,0 +1,1063 @@+# Probe / Mock Pattern Library โ PROJECT layer (LobeHub)++> **PROJECT layer โ writable, LobeHub-specific.** Append project learnings here during runs (each: Situation / Doesn't work / Works). The generic, product-independent recipes live in the installed skill's `references/probe-mock-patterns.md` (read-only in this repo, updated by PR to `@lobehub/cli`) โ read BOTH layers before any run that forces an error state or inspects runtime state. When an entry here turns out to be product-independent, genericize it (drop the LobeHub nouns) and PR it upstream.+> Keep the original discipline: cite `file:line` for any mechanism claim; if you only saw a symptom, write "cause not established" rather than guess.++---++## A. Forcing a fetch to FAIL (error-state testing)++### A7. โ WORKS โ render a message-attached error card (hetero guide, AsyncError) by in-memory store dispatch++- To render an error state that lives on a **chat message** (e.g. the heterogeneous+ `overloaded` guide card), no network fault or real agent run is+ needed โ inject the error straight into the chat store, **in-memory, no DB write**:+ ```js+ // agent-browser --cdp <port> eval --stdin+ var c = window.__LOBE_STORES.chat();+ var id = 'tmp_probe';+ // 1. create a temp assistant message (in the ACTIVE conversation)+ c.internal_dispatchMessage({+ id,+ type: 'createMessage',+ value: { role: 'assistant', content: 'partial work UNIQUE_MARKER', provider: 'claude-code' },+ });+ // 2. attach the error whose `body.code` drives the card+ c.internal_dispatchMessage({+ id,+ type: 'updateMessage',+ value: {+ error: {+ type: 'AgentRuntimeError',+ message: 'Overloaded',+ body: {+ agentType: 'claude-code',+ code: 'overloaded',+ message: 'Overloaded',+ },+ },+ },+ });+ ```+ This renders the real component (real i18n) in the running app. Clean up with+ `internal_dispatchMessage({ id, type: 'deleteMessage' })`.+- **`code` must be one of four values, or you get no guide card.**+ `isHeterogeneousAgentStatusGuideError` (`src/features/Conversation/Error/heterogeneous.ts:13-31`)+ requires `agentType` โ {`claude-code`, `codex`} **and** `code` โ {`auth_required`,+ `cli_not_found`, `overloaded`, `rate_limit`}. Anything else falls through to the generic+ error path. The switch+ (`src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx:28-44`) maps AuthRequired โ+ `AuthRequiredState`, RateLimit โ `RateLimitState`, Overloaded โ `OverloadedState`,+ **default โ `CliInstallState`**. There is no `InterruptedState`, and `interrupted` is not a+ `HeterogeneousAgentSessionErrorCode` at all (it is a `completionReason` / run-`status` value+ elsewhere) โ an earlier version of this note used it as the example, and it would have+ rendered nothing of the sort.+- **No persistence / no side effects**: `internal_dispatchMessage` is the optimistic+ in-memory path (same as `optimisticCreateTmpMessage`). Nothing hits the DB, and a+ reload clears it. Safe even against a **real** account's synced data โ do it in an+ isolated `electron-dev.sh start <id>` instance (copied login) to be extra safe.+- **Suppress auto-actions on purpose**: the hetero auto-retry only arms when a retry scope+ resolves. `src/features/Conversation/Error/index.tsx:260-262` computes+ `retryScopeId ?? getDisplayMessageById(data.id)?.parentId`, and `useHeterogeneousAutoRetry`+ gates on `!!scopeId`. A tmp message has no `parentId`, so the scope is `undefined` โ the card+ renders in its **manual** state (retry button, no countdown) and **does not auto-fire**+ (won't spawn a real CLI). (There is no `getRetryScopeId` helper โ an earlier version of this+ note invented one. The mechanism is a plain `parentId` lookup, not an ancestor walk.) To+ exercise the countdown live you'd need a real userโassistant chain; otherwise cover it with+ the component RTL test.+- **Gotcha โ `messagesMap` landing is unreliable to assert; the render is the truth.**+ `internal_dispatchMessage` (no explicit context) targets the active conversation and+ the message may not show up where a naive `Object.keys(messagesMap)` scan looks, yet+ it still renders. Verify by the DOM, not by the store map.+- **Gotcha โ `document.body.innerText` keyword match false-positives in long chats.**+ The conversation's own text (and the right-hand diff/review panel) frequently contains+ your assert strings (e.g. `่ฟๆฅไธญๆญ`, `้่ฏ`, `Retry`). Match on a **unique injected+ marker** instead, `scrollIntoView` its node, then **open the screenshot with Read** to+ confirm the card (Case 1 rule). Find + scroll to the node:+ ```js+ var w = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null),+ n,+ hit;+ while ((n = w.nextNode())) {+ if (n.nodeValue.indexOf('UNIQUE_MARKER') >= 0) {+ hit = n;+ break;+ }+ }+ var el = hit.parentElement;+ for (var i = 0; i < 6 && el.parentElement; i++) el = el.parentElement;+ el.scrollIntoView({ block: 'center' });+ ```++### A8. โ WORKS โ trigger a REAL failed load-more via store action when scroll/observer won't trip++- **Situation**: verifying an infinite-scroll `loadMoreError` inline retry row. The+ `IntersectionObserver` won't fire because the seed data is a short list that fits+ the viewport without scrolling (virtua renders no scrollable overflow), so+ `scrollTop = scrollHeight` scrolls nothing and `loadMore` is never called.+- **Doesn't work**: scrolling any element to the bottom โ with only 2 rows there is+ no scroll container (`scrollHeight <= clientHeight`), and virtua's sentinel never+ intersects.+- **Works โ two parts**:+ 1. **Force pagination with tiny seed data via HMR**: lower the component's page-size+ const so a small dataset paginates. `AgentTopicManager` `PAGE_SIZE = 30` โ `2`,+ then an agent with 3 topics loads page-1 = 2, `hasMore = true`.+ 2. **Call the real store action directly** (bypasses the observer, but runs the real+ fetch + real `catch`): `window.__LOBE_STORES.<store>` is a bound hook โ CALL it to+ get live state + actions (`.getState`/`.setState` are NOT exposed, C1).+ ```js+ // agent-browser --session <s> eval+ var c = window.__LOBE_STORES.chat();+ await c.loadMoreAgentTopicsView(); // hits the injected getTopics(current>0) throw+ // โ real catch sets agentTopicsViewMap[key].loadMoreError โ inline AsyncError row renders+ ```+ Pair the service injection (A4, throw only when `params.current > 0` so page-1 loads+ and page-2 fails) with a **call counter** to prove the observer gate does NOT loop:+ `(globalThis).__loadMoreCalls = (โฆ||0)+1` inside the throw; after the failure, wait a+ few seconds and assert `window.__loadMoreCalls` stays `1` (no runaway re-trigger).+- **Caveat**: calling the action directly proves the render + the real error code path ++ no-runaway, but NOT the observer's `!loadMoreError` gate under real scroll (the gate+ lives in the component's IntersectionObserver callback). To exercise the gate live you+ need a real scrollable list โ seed `> PAGE_SIZE` visible-source topics on one agent.+- **Gotcha โ the manager view filters by source (`ๆฅๆบ: ๅฏน่ฏ`) by default.** The store's default+ filter is `triggers: ['chat']` (`src/features/AgentTopicManager/store.ts:49-51`; the code calls+ it the **trigger** filter, the UI labels it ๆฅๆบ /source), so topics with a non-chat trigger+ show `0` even though the agent owns them in the DB; click **ๆธ ็ฉบ็ญ้ / Clear filters** (or+ `setStatus('all')` + clear) to reveal them.++---++## C. Probing app / store runtime state++### C0. A picker backed by a list store may need fixture hydration after direct-route entry++- **Situation**: a modal reads candidate entities from a list store, while the test enters a+ detail route directly. The detail route can render from its own entity/config store without+ ever mounting the list fetcher, so the picker correctly renders an empty candidate list even+ though fixture rows exist in the database.+- **Doesn't work**: inserting database rows alone, or refreshing the detail store. Neither+ hydrates a separate list store that has not mounted its fetch hook.+- **Works**: first enter the canonical list/home surface and let its real fetch settle. If the+ fixture deliberately bypasses normal creation and the list API still does not expose it,+ use the existing C1b dev-only `setState` exposer to hydrate the list store with the exact+ fixture shape, then exercise the real picker component and remove the exposer patch after+ capture. Keep the report explicit that fixture hydration was test setup; validate the actual+ mutation and created entity through the database or network boundary.++### C1. `window.__LOBE_STORES.<name>` has no `.getState` โ CALL it instead++- **Doesn't work**: `window.__LOBE_STORES.page.getState()`. The exposed value is neither the+ store nor the hook: `src/store/middleware/expose.ts:11` assigns+ `window.__LOBE_STORES[name] = () => store.getState()`, a plain arrow function with no+ `.getState` property.+- **Works**: call it โ `window.__LOBE_STORES.page()` returns the state snapshot, actions+ included. An earlier version of this note said "state isn't readable from it", which was+ wrong and contradicted C1b.++### C1b. โ WORKS โ expose `setState` via HMR to drive a REAL identity/scope change (login repro)++- **Situation**: verifying behavior on an identity/cache-scope change (e.g. login,+ `useCacheScope` = `${userId}:${workspaceId}`) on the ALREADY-LOADED app, without a+ real OAuth flow. Cold-boot repro is timing-flaky under machine load; the faithful,+ deterministic path is to flip `userId` on the live app.+- **Doesn't work**: `window.__LOBE_STORES.user()` returns `getState()` (actions but no+ `setState`); there is no public `setUserId` action to call.+- **Works**: patch the dev-only exposer `src/store/middleware/expose.ts` (HMR) to also+ attach `setState`, then drive the store from `eval`:+ ```ts+ // expose.ts, temporary โ REMOVE after: git checkout -- src/store/middleware/expose.ts+ const handle = () => store.getState();+ (handle as any).setState = (store as any).setState;+ window.__LOBE_STORES[name] = handle as any;+ ```+ `expose()` only runs at store creation, so reload the renderer once after the edit so+ stores re-expose with the handle. Then:+ ```js+ var u = window.__LOBE_STORES.user;+ var c = u().user || {};+ u.setState({ user: Object.assign({}, c, { id: 'probe_scope_0705' }) }); // โ scope flips+ ```+ In-memory only (no DB write); a reload restores the real id. Revert the file after.++### C5. โ WORKS โ main-process `logger.info` is invisible unless `DEBUG` is set++- **Situation**: proving WHICH code path the Electron main process took (e.g. hetero+ `ClaudeAgentSdkSession` vs the CLI-spawn `AgentStreamPipeline`). Both produce identical+ user-visible output, so the verdict needs a main-process log line.+- **Doesn't work**: grepping the instance log for the `logger.info('Starting Claude Code SDK+session:')` line. In development `createLogger().info` routes to the `debug` package, which+ prints nothing unless its namespace is enabled (only `console.error` shows up unconditionally).+ Absence of the line is NOT evidence the branch didn't run.+- **Works**: `export DEBUG='controllers:*'` before `electron-dev.sh start <id>`, then+ `grep -oE "controllers:HeterogeneousAgentCtr INFO: [^']*" /tmp/lobe-electron-pool/instance-<id>.log`.+ Don't trust the hetero tracing dir for this โ it is gated and the copied golden profile ships+ STALE trace sessions from months earlier that look like a fresh run.++### C6. โ WORKS โ read a topic's metadata (workingDirectoryConfig etc.) from the chat store, and reset to a fresh topic++- **Doesn't work**: `chat().topicsMap[topicId]` / `chat().topicDataMap[topicId]` โ there is+ no per-topic-id map. `topicDataMap` is keyed by **view key** (`agent_<agentId>`), and each+ value is a paginated view object (`{ items, total, hasMore, โฆ }`), not a topic.+- **Works** (verified while E2E-testing `git worktree add` side-effect recording):+ ```js+ var c = window.__LOBE_STORES.chat();+ var view = c.topicDataMap['agent_' + agentId];+ var topic = (view.items || []).find(function (x) {+ return x.id === c.activeTopicId;+ });+ topic.metadata.workingDirectoryConfig; // โ e.g. git.activeWorktree written by recordGitCommandEffects+ ```+- **Fresh topic without touching the UI**: `await c.openNewTopicOrSaveTopic()` โ with an+ active topic it saves/exits to the agent's no-topic compose state (activeTopicId โ null),+ so the next send creates a new topic. Chain per-case fixtures this way instead of clicking+ "Start New Topic". The contenteditable ref changes after the switch โ re-run+ `snapshot -i -C` before typing.+- Full E2E loop this enabled: E11 fixture agent (`heterogeneousProvider: { type: 'claude-code' },+executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to run a+ specific shell command โ poll `chat().operations` for `running === 0` โ assert the+ topic's metadata via the probe above. A real CC one-command turn completes in \~10โ20s.++### C7. DB-seeded task rows need a `task_`-prefixed id or `resolve()` silently misses them++- **Situation**: seeding a `tasks` row directly in SQL for a router probe, with a+ hand-written id like `tsk_foo`, then calling a task procedure โ it 404s+ ("Task not found") even though the row exists and the caller is a member.+- **Doesn't work**: any id not starting with `task_`. `TaskModel.resolve()`+ (`packages/database/src/models/task.ts:220-223`) only treats the input as a row+ id when it starts with `task_`; everything else is upper-cased and looked up as+ a workspace `identifier` (e.g. `T-1`), so `tsk_foo` becomes the identifier+ lookup `TSK_FOO` โ null.+- **Works**: use the idGenerator prefix (`task_<suffix>`) for seeded ids, or pass+ the row's `identifier` (`T-<seq>`) to the procedure instead.++### C8. โ An agent-browser session can silently LOSE its seeded cookies โ a 401, not `document.cookie`, is the signal++- **Situation**: verifying an owner-only affordance (a link the server renders only for the+ report's author). The page rendered without it, and the bundle came back `isOwner: false`+ even though the row's `userId` matched the seeded user โ which reads exactly like a bug in+ the ownership check.+- **Doesn't work**: `document.cookie` as the auth probe. Better Auth's session cookie is+ **httpOnly**, so `document.cookie` is legitimately `[]` on a fully authenticated page โ+ `cookieCount: 0` proves nothing either way.+- **Doesn't work**: trusting `setup-auth.sh web-seed`'s success line for the rest of the run.+ It verified the session at `/`; the session can still be empty later (this run's page had+ also drifted to `about:blank` at one point โ see D14).+- **Works**: probe the SERVER, not the document โ call any authed procedure from the page and+ read the status. `401` = no session reached the server; `200` = you are really signed in.+ ```js+ const r = await fetch(+ base ++ '/trpc/lambda/user.getUserState?input=' ++ encodeURIComponent(JSON.stringify({ json: {} })),+ { credentials: 'include' },+ );+ r.status; // 401 โ re-seed; 200 โ the session is live+ ```+ Recover with `agent-browser close --all` + `setup-auth.sh web-seed`, then re-open the route.+ After re-seeding, the same bundle returned `isOwner: true` with the owner-only link rendered โ+ the code was correct all along.+- **Why it matters**: an auth-scoped assertion (owner-only / permission-gated UI) fails+ IDENTICALLY whether the gate is broken or the session is missing. Always establish that the+ session is live (a 200 from an authed procedure) BEFORE concluding the gate is wrong โ+ otherwise you publish a false bug against your own change.++### C9. A component-scoped "consumed" ref is not a one-shot guard once the component can remount++- **Situation**: a persisted store field carries a one-shot request (`{ nonce, url }`) and the+ consuming component guards against re-consumption with a `useRef` holding the last nonce.+- **Why it silently breaks**: the ref dies with the component. Any change that starts remounting+ the consumer (e.g. giving it a `key` that now varies per topic/session) resurrects the guard as+ `undefined`, so a request that is still sitting in _persisted_ state is re-consumed on every+ remount โ and, on a fresh boot, once more. The symptom looks nothing like the cause: a page the+ agent had just loaded gets navigated to a URL from days ago.+- **Works**: retire the request in the store the moment it is consumed, so the one-shot is one-shot+ across mounts and restarts. Watch the merge semantics โ if the store patches with lodash `merge`,+ clearing with `undefined` is a **no-op** and the field must be set to `null`.+- **Test for it**: assert the field is `null` (not `undefined`) after the consume action; a test that+ only checks "the request was acted on" passes in both the broken and fixed versions.++### C11. Persisted SWR cache serves a STALE agent config after a direct DB write++- **Situation**: seeding `agents.agency_config` or `agents.model` directly in Postgres, then using+ the app to drive an assertion.+- **Doesn't work**: reload or `internal_refreshAgentConfig`; IndexedDB/localStorage can retain the+ previous config and make a fixture issue look like a product regression.+- **Works**: cold-load by clearing browser storage/caches, re-seed auth, reopen, and assert the+ fixture in `__LOBE_STORES.agent().agentMap[id]` before testing downstream behavior.++---++## D. agent-browser / CDP mechanics++- **D3. offline is `agent-browser set offline on|off`** (under `set`, with+ `viewport`/`geo`/`headers`), not a top-level `offline` command.+- **D6. The singleton hover action bar is hard to drive; its icons are+ `div[role=button]`, NOT `<button>`.** The per-message action bar+ (`SingletonMessageActionsBar`) is one portal that moves via DOM + a+ freeze/commit `MutationObserver`, so it appears only while hovering and+ re-hides on the next commit tick. Gotchas that wasted a run:+ - `host.querySelectorAll('button')` returns 0 โ the ActionIcon items render as+ `<div role="button">`. Query `[role="button"]` (or the broad+ `button,[role=button],[class*=ActionIcon]`).+ - Between two evals the bar can vanish (commit tick). Do hover + inspect + act+ in as few steps as possible.+ - โ WORKS to open the overflow menu on a message and read its items:+ ```bash+ S="--session s9224 --cdp 9224"+ agent-browser $S hover "#<messageId>" # ChatItem root id = message id+ sleep 1.5+ # click the LAST role=button in the host = the "โฆ" overflow trigger+ agent-browser $S eval '(function(){var h=document.querySelector("[data-singleton-message-action-bar-host]");var b=h&&h.querySelectorAll("[role=button]");if(!b||!b.length)return "no-bar";b[b.length-1].click();return "clicked";})()'+ sleep 1+ agent-browser $S screenshot /abs/menu.png+ agent-browser $S eval '(function(){var t=[];document.querySelectorAll("[role=menuitem],li").forEach(function(i){var s=(i.innerText||"").trim();if(s)t.push(s);});return JSON.stringify(Array.from(new Set(t)));})()'+ ```+ A programmatic `.click()` on the ellipsis DOES open the antd dropdown (it sets+ `data-popup-open`, which also freezes the bar so it won't vanish). The action+ labels are localized (`ๅไบซ`/`ๅค้`/`ๅ ้ค` = share/select/del).+- **D7. To get a _finished_ hetero (CC/Codex) turn that ENDS on a tool block**+ (last child has tools โ `getGroupLatestMessageWithoutTools` returns undefined,+ the `!contentId` action-bar path): send a single long tool call (e.g.+ `็จ Bash ๅทฅๅ ท่ฟ่ก sleep 20`) and, the moment the group's last child is a running+ tool, call `stopGenerateMessage()` in the SAME eval to avoid the race where CC+ appends a trailing text summary (which would give it a text last-block and a+ defined contentId). Poll-then-stop-atomically:+ ```bash+ agent-browser $S eval '(function(){var c=window.__LOBE_STORES.chat();var t=c.activeTopicId;var a=c.messagesMap["main_"+c.activeAgentId+"_"+t]||[];var g=a.filter(m=>m.role==="assistantGroup").pop();var lc=g&&g.children&&g.children.at(-1);var running=Object.values(c.operations||{}).some(o=>o.status==="running");if(lc&&(lc.tools||[]).length&&running){c.stopGenerateMessage();return "STOPPED";}return "wait";})()'+ ```+- **D11. โ WORKS โ catch a BRIEF blank/transient frame (sub-second) that screencast misses.**+ Verifying a momentary full-screen blank (e.g. a React subtree unmounting to `null` for+ \~150โ350ms during a scope change): `Page.startScreencast` emits one frame when it starts and+ then only on a VISUAL CHANGE, so a _static_ blank produces no further frames โ you see a time+ GAP in the manifest, not a blank image. (Measured: 3s of a static page โ **1** frame, the+ initial one; 6 background flips โ **6** frames. The old note said "NO frame", which misses+ the initial one and can look like the screencast never started.)+ Single timed `cdp-screenshot` also loses the race (its own \~200ms latency+ overshoots) and `captureScreenshot` can return the prior surface.+ - **Works โ two complementary probes**:+ 1. **DOM proof (deterministic)**: sample `document.getElementById('root').innerText.trim().length`+ at 150/350/600ms after the trigger via one `eval` returning a Promise. A full unmount+ drops it to `0`, then it recovers โ unambiguous, load-independent. (Fixed vs broken:+ `6064 โ 0 โ 5646` vs `6089 โ 6002 โ 6042` never-0.)+ 2. **Freeze the pixels**: to actually capture the blank image, keep the blank ON SCREEN+ longer by re-triggering every \~80ms (e.g. flip `userId` to a fresh value each tick so a+ `key={scope}` gate stays remounted), while firing raw CDP `Page.captureScreenshot` every+ 80ms over the same window. Blank frames come back tiny (\~34KB jpeg) vs content (\~294KB);+ convert + Read one to confirm. (A raw-CDP forced capture DOES render a static frame; the+ trick is holding the state, not the capture.)+ - Byte-size is a reliable auto-flag for near-uniform frames (blank/loading), but two+ different near-uniform states (dark loading-screen vs blank) can both be small โ always+ Read the frame to tell them apart (Case 1 rule).++### D13. `record-electron-demo.sh` IS real 30fps capture โ but raw avfoundation timestamps are unusable++- **Don't assume the whole skill is 1-2 fps.** `record-gif.sh` and `record-app-screen.sh` are+ CDP-screenshot loops (capped by screenshot latency). `record-electron-demo.sh` is different:+ `ffmpeg -f avfoundation -framerate 30` (see `scripts/record-electron-demo.sh:152-153`) โ a+ true OS screen recording, fast enough for sub-second UI transitions.+- **Doesn't work**: a naive `ffmpeg -f avfoundation -framerate 30 -i "1:" -t 14 out.mp4`.+ Measured on one 14s capture: **133332 frames muxed into a 0.13s file at 4.7 Gbit/s, 79 MB**.+ `-ss <n>` then fails with `Output file is empty, nothing was encoded`. Cause not established+ (avfoundation's own PTS appear near-identical); the fix below is empirical.+- **Works**: rebuild the time base โ `-use_wallclock_as_timestamps 1` on the input plus+ `-vf fps=20` on the output. Same 14s capture โ **14.00s / 136 KB**.+ ```bash+ ffmpeg -y -use_wallclock_as_timestamps 1 -f avfoundation -framerate 30 -capture_cursor 0 \+ -i "1:" -t 14 -vf "fps=20,scale=1200:-2" -c:v libx264 -crf 26 -pix_fmt yuv420p out.mp4+ ```+- **`ffprobe` may be absent even when `ffmpeg` is installed.** Validate with+ `ffmpeg -v error -i out.mp4 -f null -` (silence = decodes fine) and read `Duration` from+ `ffmpeg -i out.mp4 2>&1 | grep Duration`.+- Being an OS capture it is subject to D10 (black frames when the display sleeps): gate with+ `check-screen-recording.sh` and hold `caffeinate -dimsu` for the WHOLE run โ re-check right+ before recording if the run has been long, since the display can sleep mid-session.+- **Pick evidence by what you're asserting, not by a rule.** A state transition lasting seconds+ (a loading label flipping) is fine as a 2fps CDP GIF. Reach for 30fps OS capture only when the+ asserted change is sub-second. And when the asserted quantity is a **prop, not a pixel** (e.g.+ `animated = enableStream && transitionMode === 'fadeIn' && isGenerating`, see+ `src/features/Conversation/Messages/useChatMarkdown.tsx:43`), record it with a timestamped+ debug-global (C2) in the same render: failing to film a flicker proves nothing about whether it+ flickers, whereas `0ms:true โ 7386ms:false` pins the exact flip.++### D15. Host-page CDP screenshot renders the `<webview>` region BLACK intermittently โ guest DOM eval is ground truth++- **Situation**: capturing evidence of an Electron in-app browser (`<webview>` in a sidebar).+ Early `Page.captureScreenshot` shots of the host page included the guest's pixels; minutes+ later the same command on the same target returned the webview region uniformly black+ (byte-identical output across retries), while the app chrome around it rendered fine.+- **Doesn't work**: concluding the embedded page went blank/failed from the host screenshot,+ or retrying the host capture. The guest was healthy the whole time: an `agent-browser`+ session following the webview target (E16) read `document.title` = the expected page and+ full body text.+- **Works**: treat the guest target as the source of truth โ eval `title`/`innerText` in the+ webview target for the assertion, and capture the guest's own pixels via a session pinned+ to the `webview` target (`agent-browser screenshot` there) when the embedded page's visual+ matters. Use host-page screenshots only for the app chrome around the webview. Cause of the+ black compositing not established (OOPIF surface not composited into the host capture).++### D20. โ Main-process `WebContentsView` pages are their own CDP page targets โ they hijack target selection, AND they are the best pool probe++- **Situation**: verifying an in-app browser whose pages are owned by the MAIN process as+ `WebContentsView`s (not renderer `<webview>` guests โ that is E16/D15, a different shape).+- **Doesn't work**: assuming any tool that "just connects to the CDP port" lands on the app.+ Every live page shows up in `/json/list` as its own `type: page` target, so both+ `agent-browser` and `scripts/cdp-screenshot.sh` can silently attach to a _web page the app+ is hosting_ instead of the app itself. Measured: `cdp-screenshot.sh` reported+ `targetUrl: https://example.com/` and wrote that page's pixels while the intended evidence+ was the app window; an `agent-browser get url` on the same port hung.+- **Works โ pin the target by URL prefix.** Raw CDP, pick the target whose `url` starts with+ `app://renderer`, and evaluate against that:+ ```js+ const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();+ const target = list.find((t) => t.type === 'page' && t.url.startsWith('app://renderer'));+ new WebSocket(target.webSocketDebuggerUrl); // โ Runtime.evaluate+ ```+- **Works โ the same property is the cheapest page-pool probe there is.** One live page ==+ one `page` target, so `/json/list` filtered to non-`app://` URLs _is_ the pool's contents.+ Use it to assert per-session isolation (N sessions โ N coexisting pages, and a page that+ should have survived an action is still listed) without adding any IPC or store probe:+ ```bash+ curl -s --noproxy '*' http://127.0.0.1: < cdp > /json/list \+ | python3 -c "import json,sys; print([t['url'] for t in json.load(sys.stdin) if t['type']=='page'])"+ ```+- **Pixels still need an OS capture.** A `WebContentsView` does not composite into the host+ page's `Page.captureScreenshot`, so app-window evidence that must _show the embedded page_+ has to come from `capture-app-window.sh` (macOS `screencapture -l <windowid>`), which does+ not require bringing the window to the front.++---++## E. Env / ports++- **E1. โ ๏ธ This item was wrong on both counts โ do not trust its reasoning.**+ It claimed `eval "$(init-dev-env.sh env)"` "can clobber `PATH`". It cannot: the `env`+ subcommand prints only the keys in `env_keys()` (`init-dev-env.sh:178-204`), and the string+ `PATH` does not appear anywhere in the script. It also told you to hardcode+ `http://localhost:20874`; `SERVER_PORT` is **randomly allocated per workspace** in+ 20000-40000 (falling back to 3010) and persisted to `.records/env/agent-testing-ports.env`,+ so `20874` was one machine's old port (this workspace is on 21912) and it appears nowhere+ else in the repo. **Works**: read the port from that file, or export just the one var โ+ `export APP_URL="$(init-dev-env.sh env | sed -n 's/^APP_URL=//p')"`. Whatever broke+ `awk`/`head` in the original run was never diagnosed.+- **E2. SPA port is configurable to coexist with another worktree.** Vite binds+ `SPA_PORT||9876`; Next proxies `VITE_DEV_PORT||9876`. Pass `SPA_PORT=9877` to+ `init-dev-env.sh dev` (it exports `VITE_DEV_PORT=$SPA_PORT`) so both agree and+ you don't fight a worktree already on 9876.++### E3. Deep-linking to an authed SPA route โ NOT reproduced; soft-nav is still the safer path++- **Original claim**: after `setup-auth.sh web-seed`, a hard `open <app>/agent/<id>/docs`+ redirects to `/signin?callbackUrl=...` while `/` stays authed.++- **Did not reproduce** against the current dev server with a seeded web session+ (`isSignedIn: true`, `userId: user_agent_testing_001`). Hard-loading `/settings/common` and+ the note's exact shape `/agent/<real-id>/docs` both landed on the route itself, with no+ `/signin` and no `callbackUrl`. Either it was fixed, or the original run's cookie state+ differed. Don't budget for the bounce; check for it.++- **Still true and still useful**: `app-probe.sh auth` "false-negatives" here because it talks+ to the **Electron CDP endpoint on 9222**, not to your web browser session โ it fails with+ `All CDP discovery methods failed for 127.0.0.1:9222`. Read the auth state out of the page+ instead: `window.__LOBE_STORES.user()` โ `{ isSignedIn, user.id }`.++- **Works**: hard-load `/` (authed), confirm by screenshot (not the app-probe auth+ JSON โ it false-negatives here, returns `isSignedIn:false` on an authed page),+ then **client-side soft-nav** with no server round-trip:++ ```bash+ agent-browser eval "history.pushState({},'','/agent/<id>/docs'); window.dispatchEvent(new PopStateEvent('popstate')); 'nav'" --session lobehub-dev+ ```++ react-router picks up the popstate and renders the route in-context with the+ already-hydrated auth. Right-panels that render at a _layout_ level do NOT see a+ child route's `:param` via `useParams()` โ read it from `location.pathname` if+ you need it.++### E4. โ WORKS โ keep Electron pool `LOBE_IPC_ID` short++- **Situation**: manually starting an isolated Electron dev instance with a+ descriptive `LOBE_IPC_ID` such as `lobehub-desktop-dev-manual-selection-2`.+ The main process builds a Unix socket path under `$TMPDIR`, and macOS rejects+ overlong socket paths.+- **Doesn't work**: long IPC ids can crash Electron at bootstrap with+ `listen EINVAL ... <id>-electron-ipc.sock`, before any renderer/CDP evidence is+ available.+- **Works**: use the numeric `electron-dev.sh start <id>` pool path, or keep+ manual IPC ids very short, e.g. `LOBE_IPC_ID=lhmsel2`.++### E5. โ WORKS โ no-Docker fallback stack for the isolated no-.env env++- **Situation**: `init-dev-env.sh setup-db` needs Docker (paradedb + redis images), but+ Docker Desktop's VM can wedge indefinitely (`no route to host` to 192.168.65.x, empty+ vm/console.log). Verified working substitute:+ - **Postgres**: local brew Postgres 17 (pgvector available). The only paradedb-specific+ migrations are `0090_enable_pg_search` / `0093_add_bm25_indexes_with_icu` โ no-op them+ in the worktree (`SELECT 1;`), everything else applies clean.+ - **Redis is a hard dependency of Better Auth sign-in** โ with a dead REDIS\_URL the seed+ login 500s (`[Better Auth]: Error: Connection is closed`). `brew install redis`,+ `redis-server --port 6380 --daemonize yes`.+ - **S3**: `s3rver` (npm) on 29000 with a CORS config for the bucket. Its presigned-URL+ validation only accepts key id `S3RVER` (secret `S3RVER`) โ `allowMismatchedSignatures`+ does NOT rescue an unknown access key id (403 on the browser preflight). Set the dev+ server's `S3_ACCESS_KEY_ID/S3_SECRET_ACCESS_KEY=S3RVER`, `S3_ENABLE_PATH_STYLE=1`,+ `S3_PUBLIC_DOMAIN=http://127.0.0.1:29000/<bucket>`.++### E6. code-inspector-plugin breaks Turbopack compile of Next-served authed pages++- **Situation**: the first AUTHENTICATED render of a Next-served (non-SPA) page whose client+ graph pulls the chat store dies in `next dev` (Turbopack) with Build Error `Resource path+"worker/browser/createWorker.ts" needs to be on project filesystem` (chain: layout โ+ GlobalProvider/Query โ trpc client โ image/chat store โ python-interpreter worker).+ Unauthenticated curl 302s BEFORE the client graph compiles, so it false-passes; a fresh+ no-lockfile `pnpm install` can resolve a broken plugin version.+- **Works**: `E2E=1` (or `TEST=1`) โ `defineConfig`'s `isTest` skips `codeInspectorPlugin`,+ the only thing it gates. Webpack mode (`next dev --webpack`) is NOT a viable fallback+ (react version mismatch when two next versions are hoisted; `zlib-sync` unresolved for+ discord.js).++### E8. โ WORKS โ a git-worktree checkout needs its OWN `pnpm install`, not a symlinked `node_modules`++- **Situation**: verifying a UI change from a `git worktree` (e.g. `.claude/worktrees/<name>`), which+ starts with no `node_modules`.+- **Doesn't work**: symlinking the main checkout's `node_modules` (root and/or `apps/desktop`) into the+ worktree. The workspace links inside it point `@lobechat/*` at the MAIN checkout's `packages/`, which+ sits on a different branch โ the Electron main build then dies with+ `[MISSING_EXPORT] "X" is not exported by "../../packages/<pkg>/src/..."`. Renderer source resolves from+ the worktree while packages resolve from the main repo, so the two disagree.+- **Works**: run `pnpm install` at the worktree root AND `cd apps/desktop && pnpm install` (standalone,+ not in the workspace). \~5 min total, mostly hardlinked from the store.+- **Also**: a Vite dev server left over from an earlier failed `electron-dev.sh start <id>` is REUSED by+ the retry (`CDP already reachable โฆ Skipping start`) and can keep serving pre-edit module text. If the+ DOM shows markup that contradicts the source, curl the dev server for the file and grep for a token you+ just added (`curl -s 127.0.0.1:<vitePort>/src/path/File.tsx | grep -c myNewSymbol`) before blaming the+ code. `electron-dev.sh stop <id>` then start again to get a clean server.++### E8b. The standalone `apps/desktop` install BREAKS the root workspace's type resolution โ re-run the root install after it++- **Situation**: a worktree set up per E8 (`pnpm install` at the root, then+ `cd apps/desktop && pnpm install`). Everything runs โ Electron boots, the renderer serves live+ code โ but a full `bun run type-check` that passed BEFORE the desktop install now fails with+ dozens of errors that have nothing to do with the change under test:+ `Module '"@lobechat/types"' has no exported member 'MetaData' | 'HotkeyId' | โฆ` plus+ `Type 'UserHotkeyConfig' is missing the following properties from type 'UserHotkeyConfig'` โ+ the same name on both sides, i.e. **two copies of `@lobechat/types` in one program**.+- **Doesn't work**: chasing it as a code defect, or checking the symlink+ (`node_modules/@lobechat/types โ ../../packages/types` looks correct) and `packages/types/node_modules`+ (its deps are all present). Both look fine while the program still sees two instances.+- **Cause**: `apps/desktop` is NOT in the root pnpm workspace (see E8). Its standalone install+ re-resolves the `packages/*` links from its own lockfile and rewrites shared package deps under+ `packages/*/node_modules`, leaving the root workspace pointing at a second instance.+- **Works**: run `pnpm install` at the worktree root ONE MORE TIME, after the desktop install+ (\~1.5 min, mostly cached). Type-check goes back to 0 errors and Electron keeps working.+ So the safe order is: root install โ desktop install โ root install again. And never publish a+ "type-check failed" verdict from a worktree until you've re-run the root install โ the failure is+ environmental, and the error text (a type "missing properties from" itself) is the tell.++### E9. Electron dev's FIRST cold boot sits on the splash with an empty `#root` for 1โ3 minutes++- **Situation**: after `electron-dev.sh start <id>`, `app-probe.sh auth` returns `isSignedIn:false`,+ `#root` has providers but `innerText.length === 0`, and the screenshot is just the LobeHub splash. The+ main log shows `Proactive token refresh failed` / `invalid_grant`.+- **Doesn't work**: concluding the copied login state expired. That refresh error is a red herring โ the+ app recovers, and `RENDERER_WAIT_S` (60s) can expire while Vite is still on+ `[optimizer] bundling dependencies`, which ends in `optimized dependencies changed. reloading`.+- **Works**: poll until the DOM actually has content instead of sleeping a fixed amount:+ ```bash+ until [ "$(agent-browser --session s \+ '(function(){return String(document.getElementById("root").innerText.trim().length>50)})()' < port > --cdp < port > eval \+ | tr -d '"')" = "true" ]; do sleep 5; done+ ```+ Also note `zsh does NOT word-split unquoted vars` โ `S="--session x --cdp 9226"; agent-browser $S eval`+ fails with `Unknown command`. Inline the flags or use an array.++### E10. โ WORKS โ stop the main process from yanking the renderer back to its last tab++- **Situation**: driving the SPA to a specific route for a screenshot. `history.pushState` + `popstate`+ lands correctly, then \~15โ20s later `location.pathname` snaps back to whatever tab the main process+ has stored (e.g. `/devtools/claude-code`). A hard `location.href` nav is reverted the same way.+- **Cause**: the main process broadcasts `navigate`, and `src/features/DesktopNavigationBridge` obeys it.+- **Works**: HMR-neutralize the bridge for the run, then revert:+ ```tsx+ // src/features/DesktopNavigationBridge/index.tsx โ [AGENT-TEST] REMOVE+ useWatchBroadcast('navigate', () => {+ void handleNavigate;+ });+ ```+ `git checkout -- src/features/DesktopNavigationBridge/index.tsx` afterwards; `grep -rn AGENT-TEST src/`+ must come back empty.++### E11. โ WORKS โ drive the working-directory / git-status ControlBar without the native dir picker++- The picker opens a native dialog, but the same write path is reachable from the store. With no active+ topic, `commit()` persists to `agencyConfig.workingDirByDevice[deviceId]`:+ ```js+ const a = window.__LOBE_STORES.agent(),+ d = window.__LOBE_STORES.device();+ const did = window.__LOBE_STORES.electron().gatewayDeviceInfo.deviceId;+ const entry = { path: '/abs/repo', repoType: 'git' };+ await a.updateAgentConfigById(agentId, {+ agencyConfig: { workingDirByDevice: { [did]: entry } },+ });+ await d.updateDeviceCwd(did, entry, { setDefault: false }); // so the entry exists โ sourcePath resolves+ ```+ Create a throwaway agent with `agent().createAgent({ title })` and delete it afterwards with+ `session().removeSession(agentId)` (there is no `deleteAgent` on the agent store) plus+ `device().removeDeviceWorkingDir(did, path)` โ otherwise the fixture cwd lingers in the real account.+- **Identify icons precisely**: lucide renders `svg.lucide.lucide-git-fork`. Several git icons live in the+ same bar (the dir picker's `DirIcon` is `git-branch`, the review toggle is `git-compare`), so scope the+ assertion to the trigger: `document.querySelector('[role=button][aria-label="Worktrees"]') svg`, and+ still open the PNG to confirm (Case 1).++### E14. โ WORKS โ Electron pool instance boots BLANK because the copied golden login is dead++- **Situation**: `electron-dev.sh start <id>` seeds userData from the golden dev profile,+ but the app renders an empty `#root` (innerText length 0, only the LobeHub watermark) and+ `app-probe.sh auth` returns `isSignedIn:false`. The instance log shows+ `Refresh response missing access_token or refresh_token { error: 'invalid_grant' }`.+- **Cause (measured, not guessed)**: OIDC refresh tokens are single-use. Every prior+ `start <id>` copied the same golden profile and consumed/rotated its refresh token, so the+ copy's token is already dead. A blank shell here is an AUTH failure, not a render bug โ+ read the instance log before chasing the SPA.+- **Doesn't work**: pointing `LOBE_GOLDEN_PROFILE` at the packaged app's profile+ (`~/Library/Application Support/LobeHub`) โ the pool instance's startup refresh will rotate+ that token too and log the user out of their real desktop app.+- **Works โ inject a valid credential the app already owns, no new OAuth grant**:+ the prod lambda accepts any of the user's valid OIDC access tokens via the `Oidc-Auth`+ header, and the CLI keeps one in `~/.lobehub`. Extract it with the CLI's own+ `getValidToken()` (it auto-refreshes), then override the single main-process accessor:+ ```ts+ // apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts โ [AGENT-TEST] REMOVE+ async getAccessToken(): Promise<string | null> {+ if (process.env.LOBE_TEST_ACCESS_TOKEN) return process.env.LOBE_TEST_ACCESS_TOKEN;+ ...+ ```+ `export LOBE_TEST_ACCESS_TOKEN=...` before `electron-dev.sh start <id>` (the script forwards+ the shell env). This authenticates BOTH the renderer (BackendProxyProtocolManager injects the+ same token) and any main-process fetch, so the whole app comes up signed in. Revert with+ `git checkout --` + `grep -rn AGENT-TEST` afterwards, and never echo the token.+- **Works โ alternative, no source edit, when you can approve a browser prompt**: seed a+ PRISTINE profile so the app takes the signed-out path and renders the real login screen+ instead of hanging:+ ```bash+ mkdir -p /tmp/empty-golden+ LOBE_GOLDEN_PROFILE=/tmp/empty-golden ./electron-dev.sh start <id>+ ```+ Drive onboarding (`ๅผๅง` โ `ไธไธๆญฅ` ร2 โ `็ปๅฝ LobeHub Cloud`). The device-code flow opens the+ browser and auto-approves against an existing app.lobehub.com session, giving the instance its+ OWN token โ so it never rotates the one the user's resident app holds.+- **Why the blank shell has no login button**: the failed refresh leaves `isUserStateInit:false`+ (with `isLoaded:true, user:null`), and the desktop first-frame gate waits on it forever. Every+ route โ `/`, `/desktop-onboarding` โ renders empty. Reloading, soft-navving, and waiting all+ fail to resolve it, so it reads exactly like a Case-1 blank page.+- **Gotcha**: a worktree installed with `pnpm install --ignore-scripts` has NO electron binary+ (`node_modules/.pnpm/electron@*/node_modules/electron/dist` missing). Fix with+ `cd apps/desktop && pnpm rebuild electron`. Also remember `apps/desktop` and `apps/cli` are+ NOT in the root pnpm workspace โ install inside each.+- **Gotcha**: `electron-dev.sh restart <id>` keeps the userData dir, but a device-code session+ did NOT survive it โ budget for one more login after any restart (e.g. when a main-process+ change forces one, see E9).++### E15. Main-process code changes need a restart; Vite HMR only covers the renderer++- Adapters under `packages/heterogeneous-agents` run in the **main** process+ (JSONL framing + adapter + `toStreamEvent`). Editing one and reloading the+ renderer verifies nothing โ the old adapter is still running.+- Prove which code each process has before trusting a run:+ ```bash+ # renderer: vite serves working-tree src (VITE_BASE + id)+ curl -s --noproxy '*' "http://127.0.0.1:<vitePort>/src/<path>.ts" | grep -c '<marker>'+ # main: rebuilt on start into the desktop dist bundle+ grep -c '<marker>' apps/desktop/dist/main/index.js+ ```++### E16. agent-browser session silently re-targets to a newly created `<webview>` guest++- **Situation**: driving an Electron app over CDP while the app itself spawns a `<webview>`+ (in-app browser). After the guest mounts, `eval` on the SAME session suddenly returns the+ guest page's DOM (`__LOBE_STORES` undefined, app selectors empty) โ looks like the app broke.+- **Doesn't work**: assuming a session stays pinned to the app target; also assuming+ `document.querySelectorAll('webview').length === 0` means "no webview" (you may be evaluating+ INSIDE the guest).+- **Works**: `curl -s localhost:<cdp>/json/list` to see targets (`page` = app, `webview` =+ guest), then use **separate session names** per target (`--session app-x` re-picks the `page`+ target; the old session keeps following the guest โ handy for driving the embedded page).+ Verify with `get url` (`app://` vs the site URL) before trusting any eval result.++### E17. Dev-mode main-process `logger.warn/debug` is invisible without DEBUG env โ probe with console.log++- **Situation**: adding a temporary probe log in Electron main code and watching the dev+ instance log; nothing prints, which reads as "code path never runs".+- **Doesn't work**: `createLogger(ns).warn/debug` in development โ it routes to the `debug`+ package, which is silent unless `DEBUG=<ns>` was set when the process started.+- **Works**: temporary probes use `console.log('[AGENT-TEST] โฆ')` (always reaches the instance+ log via stdout); confirm the rebuilt bundle actually contains the probe string+ (`grep "<probe>" apps/desktop/dist/main/index.js`) before interpreting silence.++### E18. Cloud-connected desktop routes even `local` agents to the SERVER runtime โ force client with `disableGatewayMode`++- **Situation**: verifying a **client-only** builtin tool (`executors: ['client']`) via a real agent turn on the desktop. The agent's `executionTarget` is `local` and the tool-enable gate (`isLocalSystemEnabled` = runtime `local`) passes, so it _looks_ like it will run client-side.+- **Doesn't work**: sending the message as-is. On a cloud-connected desktop, gateway mode is on by default, so the run dispatches to `execServerAgentRuntime` (server/queue path) even for a `local` agent. The client-only tool isn't executable there โ the model flails and returns a non-answer (e.g. "browser closed") with no real tool effect. Confirm the path by reading the running op's `type` in `window.__LOBE_STORES.chat().operations` (`execServerAgentRuntime` = server; `executeToolCall` = client).+- **Works**: set the agent's `chatConfig.disableGatewayMode = true` (via `agentStore.updateAgentChatConfigById(id, { disableGatewayMode: true })`) before sending. The run then goes through `executeToolCall` (client runtime); the composer's runtime chip flips to "Local device" and the client executor runs. The gate (`isLocalSystemEnabled`) and the transport (`disableGatewayMode`) are INDEPENDENT โ enabling the tool does not force client execution.++### E19. Desktop has no classic session store โ reconfigure the existing agent, don't `createSession`++- **Situation**: wanting a throwaway agent for a real-turn test without polluting the user's agent.+- **Doesn't work**: `sessionStore.createSession({...})` โ the desktop app doesn't use the classic session store (`sessions` is `[]`, `activeId` is `'inbox'`); agents are a server-backed model in `agentStore.agentMap` keyed by `agt_...`. The created session never becomes the active agent.+- **Works**: back up the active agent's full config (`model`, `provider`, `agencyConfig`, relevant `chatConfig`), reconfigure it in place (`updateAgentConfigById` + `updateAgentChatConfigById`), run the test, then restore every field and clear any injected key-vault entry. Also: `chat.sendMessage` requires `context: { agentId, topicId, isNew }` or it throws `Cannot destructure property 'agentId' of 'context'`. Reads right after an `updateAgent*` can be stale โ re-read after \~1.5s to confirm persistence.++### E20. Killing the dev server mid-write corrupts `.next/dev` โ every route 404s and `/` โ `/signin` ping-pong++- **Situation**: after `init-dev-env.sh clean` (or any kill) and a restart, the whole app is broken: `/` 302s to `/signin`, `/signin` 307s back to `/` (`ERR_TOO_MANY_REDIRECTS` in the browser, `redirect count exceeded` in the dev server's own prewarm), and even API routes like `/api/auth/sign-in/email` return the app-router not-found. It looks like an auth/OIDC misconfiguration.+- **Cause**: a corrupt Turbopack build in `.next/dev` โ the route manifest is gone, so every path falls through to `GlobalNotFound`, whose redirect collides with the middleware's.+- **Works**: `rm -rf .next` then restart. Diagnose it in one step: if `/signin` does not return 200, the routes are not compiled โ stop debugging auth.++### E21. โ WORKS โ a QStash-protected workflow endpoint can't be curl'd; publish through local QStash to get a signed delivery++- **Situation**: driving a cron-style workflow handler under `/api/workflows/**` (e.g. a dispatcher you want to fire on demand instead of waiting for its schedule).+- **Doesn't work**: `curl -X POST <app>/api/workflows/<...>` โ `{"error":"Invalid signature"}` / HTTP 401. The `qstashAuth` middleware verifies the Upstash signature whenever `QSTASH_CURRENT_SIGNING_KEY` is set โ and `init-dev-env.sh` exports it, so the local env DOES verify. (Do not "fix" this by unsetting the key: you would then be testing an unauthenticated path that production doesn't have.)+- **Works**: start local QStash (`init-dev-env.sh qstash`) and publish to the endpoint with the QStash client โ QStash signs the delivery, so the handler sees exactly the production shape:+ ```ts+ // must live INSIDE the repo (a script under /tmp cannot resolve @upstash/qstash)+ import { Client } from '@upstash/qstash';+ const client = new Client({ baseUrl: process.env.QSTASH_URL!, token: process.env.QSTASH_TOKEN! });+ await client.publishJSON({+ body: { dryRun: false },+ url: `${process.env.APP_URL}/api/workflows/<path>`,+ });+ ```+ Run it with `eval "$(init-dev-env.sh env)" && bunx tsx ./scripts/<probe>.mts`, then read the outcome from **DB side effects**, not the HTTP body โ QStash swallows the response. (A claim/lease row, a status transition, or new message rows are all observable; the handler's JSON return is not.)+- **Time-travel a schedule instead of waiting**: for a "runs at T" feature, `UPDATE ... SET metadata = jsonb_set(metadata, '{...,runAt}', '"<past ISO>"')` and then fire the dispatcher. Cheaper and more deterministic than sleeping until the real due time.++### E22. Local dev env has no `JWKS_KEY` โ every hetero agent run dies at `signOperationJwt`++- **Situation**: a real Claude Code / Codex run in the local no-`.env` env fails immediately with `Failed to sign operation JWT for hetero agent` (`apps/server/src/services/aiAgent/index.ts`). Nothing in the UI explains it; the topic just fails.+- **Cause**: `signOperationJwt` โ `getSigningKey()` โ `getJwksKey()` needs the `JWKS_KEY` RSA JWK, and `init-dev-env.sh` does not export one.+- **Works**: the repo ships a generator โ `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/verify/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.+- **Note the failure is downstream-honest**: with `JWKS_KEY` set, the run proceeds and then fails at the hetero _sandbox_ (`Hetero sandbox spawn failed / unauthorized`) unless the agent has a real Claude Code token. Those are two different walls โ don't read the second as the first.++### E25. Electron `will-attach-webview` params carry NO custom attributes โ identity via data-\* never arrives++- **Situation**: a main-process controller needs to know WHICH renderer feature a mounting+ `<webview>` belongs to (e.g. a per-conversation session id), and the renderer put it in a+ custom `data-*` attribute on the element.+- **Doesn't work**: reading `params['data-โฆ']` in `will-attach-webview`. Measured live: params+ only contains the standard set (`instanceId, partition, src, httpreferrer, useragent,+nodeintegration, plugins, disablewebsecurity, allowpopups, preload, โฆ`). The handler silently+ no-ops and โ trap โ a unit test that mocks params WITH the custom key passes green.+- **Works**: two-channel design. (1) Recognition/hardening keyed off the **`partition`+ attribute** set by the renderer (it IS forwarded); (2) identity bound after mount via an+ explicit IPC โ renderer listens for the webview's `dom-ready`, calls+ `attach({ sessionId, webContentsId: el.getWebContentsId() })`, main process+ `webContents.fromId()` + validates the guest's session belongs to the expected partition.++### E26. โ Next dev does NOT hot-reload `apps/server/**` โ you are testing STALE compiled server code++- **Situation**: verifying a working-tree change inside `apps/server/src/**` (an agent-runtime+ service, a tool executor, a router) against a `bun run dev` server that was started before the+ edit. The app behaves normally, the feature simply does nothing.+- **Doesn't work**: assuming HMR covers it because `@/server/*` maps to `apps/server/src/*` in+ `tsconfig.json` (source, no `dist`), so it "should" recompile. It does not, at least for large+ service files. Measured: a `console.error` added at the top of a code path that demonstrably ran+ (child ops were created, the DB rows appeared) printed **zero** lines across four separate runs;+ after a dev-server restart, the same line printed on the first run. The whole feature under test+ had never executed once.+- **Why this is a trap and not a nuisance**: the failure mode is silent and looks exactly like a+ logic bug. You will go hunting in your own diff for a fault that is not there.+- **Works**: after ANY edit under `apps/server/**`, restart the dev server before drawing a+ conclusion. If a run "should" have hit your code and didn't, prove the server is running your+ code FIRST โ drop a `console.error` on the path and restart โ before debugging the code itself.++### E27. โ `source`-ing an unquoted JSON env var silently corrupts it (JWKS\_KEY โ gateway auth\_failed)++- **Situation**: writing an env file for the local gateway loop with+ `JWKS_KEY={"keys":[{"kty":"RSA",...}]}` on one line, then `set -a; source that-file`.+- **Doesn't work**: the shell strips every double quote from an unquoted assignment, so the process+ receives `{keys:[{kty:RSA,...}]}` โ invalid JSON. `getJwksKey()` (`packages/trpc/src/utils/internalJwt.ts:13-20`)+ throws on `JSON.parse`, `signUserJWT` throws, and the server hands the client an **empty** gateway+ token. The browser sends `{"token":"","type":"auth"}` and the gateway answers `auth_failed`.+- **What makes it genuinely deceptive**: `local-gateway-setup.sh` and `local-gateway-probe.mjs` read+ `JWKS_KEY` out of the file with a **regex**, not by sourcing it โ so both are unaffected. The probe+ cheerfully prints `โ auth_success` while the real browser path is broken. A green probe is NOT+ evidence the app's own token works.+- **Works**: single-quote the value in the env file (`export JWKS_KEY='{"keys":[...]}'`) and prove the+ round-trip before starting the server:+ ```bash+ (source env-file && node -e 'JSON.parse(process.env.JWKS_KEY); console.log("ok")')+ ```+ To diagnose an `auth_failed`, hook `ws.send` in the page and read the token the client actually+ sends โ an empty string means the SERVER failed to sign, not that the gateway rejected a signature.++### E28. The chat input silently refuses to send when the agent's model is retired++- **Situation**: driving a real turn (store `sendMessage` or type+Enter). The call resolves, no error+ is thrown, `activeTopicId` stays `null`, and no `agent_operations` row appears. Nothing in the dev+ server log โ the request is never even issued.+- **Cause**: the composer shows a small inline warning ("ๅฝๅๆจกๅๅทฒไธ็บฟใ่ฏท้ๆฉๅ ถไปๆจกๅๅ็ปง็ปญไฝฟ็จใ")+ and disables send. A model id that was valid a while ago (e.g. `deepseek-chat`) can be retired from+ the model bank while the agent row still points at it.+- **Works**: read the actually-enabled models out of the store before configuring a fixture agent โ+ `window.__LOBE_STORES.aiInfra().enabledChatModelList` โ `[{id: provider, children: [{id: model}]}]` โ+ and pick one from there. Also: a send that "resolves fine but creates no operation" is a UI-gate+ symptom; **screenshot the composer** instead of re-reading your store call.++### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` โ NODE\_PATH into .pnpm fixes it++- **Situation**: in a fresh git-worktree install, `init-dev-env.sh seed-user`+ (which runs `node <<'NODE'` from the repo root) throws MODULE\_NOT\_FOUND for+ `bcryptjs`, even though `pnpm install` succeeded.+- **Cause not fully established**: `bcryptjs` exists in `node_modules/.pnpm/`+ but is not linked at the repo-root `node_modules` top level in that install+ (`pg` was linked, `bcryptjs` wasn't), so a root-cwd stdin script can't+ resolve it.+- **Works**: prefix the call with+ `NODE_PATH="$PWD/node_modules/.pnpm/bcryptjs@<ver>/node_modules"` (check the+ exact version dir first). CJS stdin scripts honor NODE\_PATH; seeding then+ completes normally.+- Same run also (re)confirmed: `init-dev-env.sh dev` ports are DYNAMIC (e.g.+ next on 33803, vite on 32459) โ never hardcode 3010; re-run+ `scripts/test-env.sh` after the server is up, it reads the ports-file. And+ the `os error 35` agent-browser daemon wedge (D8) recovers with+ `agent-browser close --all` + re-running `setup-auth.sh web-seed`.++### E30. โ "Failed to fetch dynamically imported module" points at the WRONG file โ the failure is downstream++- **Situation**: the SPA renders as a Case-1 blank page; console names a dynamic-import route module.+- **Doesn't work**: investigating only the named module. It may return 200 because the actual failure+ is in its transitive import graph; changing `?t=` values are ordinary HMR invalidation.+- **Works**: take and read a screenshot. Vite's HMR overlay contains the real transform/import error.+ After a rebase or pull, refresh dependencies and restart before treating the blank SPA as a code bug.++### E31. Web agent turns run the CLIENT runtime โ no `agent_operations` row will appear++- **Situation**: driving a real web turn and polling `agent_operations` for the run.+- **Doesn't work**: waiting for a server operation when the web surface dispatched the client runtime.+- **Works**: use client observables (`messages.model`, thread ids, and chat-store operations) for web;+ use CLI/server execution and `agent_operations` for the server runtime. A change affecting both paths+ needs evidence from both paths.++---++## F. Fixture-seeding by raw SQL++### F1. Seeding a shared topic by raw SQL: messages MUST carry `agent_id`, or the share page renders skeletons forever++- **Situation**: fixture-seeding a `/share/t/<id>` page (topics + messages + `topic_shares`+ rows inserted directly). `share.getSharedTopic` returns fine, but the message list stays on+ skeletons; `message.getMessages` with `topicShareId` returns `[]`.+- **Cause**: the client passes `agentId` in the query context and `MessageModel.query` filters+ on it โ messages inserted with `agent_id` NULL are silently excluded (no error anywhere).+- **Works**: set `agent_id` on every seeded message row (matching the topic's `agent_id`).+ Probe the endpoint directly before blaming the UI:+ `/trpc/lambda/message.getMessages?input={"json":{"topicId":..,"topicShareId":..,"agentId":..}}`.++### F2. Seeded share topics also need `topics.agent_id`, or the client never fires the message fetch++- **Situation**: same setup as F1, but the failure is one layer earlier โ metadata (title)+ renders while `message.getMessages` never even appears in network requests.+- **Doesn't work**: assuming the fetch failed โ it was never fired. `useFetchMessages`+ gates on `!!context.agentId && !!context.topicId`+ (`src/store/chat/slices/message/actions/query.ts:268`), and the share page passes+ `agentId: data.agentId ?? ''` โ a topic seeded without `agent_id` yields `''` โ SWR key+ is null โ no request, silent skeleton (a Case-1 lookalike with no error anywhere).+- **Works**: seed an `agents` row and set `topics.agent_id` (and `messages.agent_id`)+ before opening the share page. Verify the fetch actually fired via+ `agent-browser network requests | grep getMessages`, not by waiting on the UI.++---++## Post-migration findings preserved from canary++### E32. โ WORKS โ driving `heteroIngest`/`heteroFinish` directly needs an OIDC token, and bun's spawn-ENOENT message differs from node's++- **Situation**: E2E-testing the hetero server-ingest chain by running `lh hetero exec --topic <t> --operation-id <op>` manually (the exact command a device daemon spawns), against a local dev+ server, with the seeded CLI API key.+- **Doesn't work**: the seeded `LOBE_API_KEY`. `heteroAuthedProcedure` requires `ctx.oidcAuth`+ (`packages/trpc/src/lambda/middleware/heteroOperationAuth.ts`) โ an API key never populates it, so+ `heteroFinish` 401s. Also note the local no-`.env` env has no `JWKS_KEY` (E22), so the server+ cannot even validate a JWT until restarted with one.+- **Works** โ production-shape auth in three steps:+ 1. `node scripts/generate-oidc-jwk.mjs > /tmp/jwks.json`+ 2. restart the dev server with `JWKS_KEY="$(cat /tmp/jwks.json)"` (must be present at start)+ 3. sign a 4h `hetero-operation` JWT with the SAME key via `signOperationJwt(<userId>)`+ (`packages/trpc/src/utils/internalJwt.ts`; run a small `.mts` inside the repo with `bunx tsx`),+ then run the CLI with `LOBEHUB_JWT=<token> LOBEHUB_SERVER=<app-url>` โ the CLI forwards it as+ the `Oidc-Auth` header.+ The fixture side needs `topics.metadata.runningOperation = { operationId, assistantMessageId }`+ seeded, and the operationId must embed real ids (`op_<ts>_agt_<id>_tpc_<id>_<suffix>`).+- **Bonus trap**: under bun, a spawn failure reads `ENOENT: no such file or directory,+posix_spawn '<cmd>'` โ NOT node's `spawn <cmd> ENOENT`. Any stderr-text pattern keyed to the node+ format silently misses on bun; classification/assertions should key on the raw error's+ `err.code === 'ENOENT'` (runtime-agnostic) and treat text matching as fallback only.+- **Persistence shape worth knowing**: a process-level failure that produced ZERO stream events+ never creates op state, so `HeterogeneousPersistenceHandler.finish` early-returns โ the message+ error is written by `CompletionLifecycle.completeOperation`'s onError branch instead+ (`body: messageError.body ?? { message }`). Assert on `messages.error`, not on which writer ran.++### E33. โ WORKS โ keep the Electron supervisor session alive in process-reaping runners++- **Situation**: `electron-dev.sh start <id>` reports `Ready`, but CDP and the Vite port disappear+ immediately after the shell command returns. The Electron log contains no crash or product error.+- **Doesn't work**: repeatedly restarting and treating the vanished CDP endpoint as an app crash.+- **Works**: keep the launcher shell alive for the test session (for example, run `start` followed by+ a short periodic wait loop in the same PTY), drive CDP from a second shell, then stop with+ `electron-dev.sh stop <id>` and terminate the holder. Some execution harnesses reap descendants when+ the command cell closes even though the launcher normally survives an interactive terminal.++### F3. โ WORKS โ render the `/verify-im` messenger bind SUCCESS state without a real platform token++- **Situation**: verifying the messenger verify page's success card (`SuccessCard`) for+ Telegram/Slack/Discord. A real bind needs a live bot issuing a `random_id` link token โ+ unavailable in an isolated env.+- **Works**: take the page's own refresh-after-link path instead. With a signed-in user, seed+ (1) a `messenger_account_links` row for (user, platform, tenant\_id='') and (2) an enabled+ `system_bot_providers` row for the platform โ `credentials` must be encrypted with+ `KeyVaultsGateKeeper.initWithEnvKey()` (same `KEY_VAULTS_SECRET` as the dev server), e.g.+ telegram `{ botToken, botUsername }`. Then open+ `/verify-im?random_id=<anything>&im_type=<platform>`: the peek-token query fails, but the+ existing-link lookup succeeds and the page falls through to the real success card+ (`shouldShowSingleAccountSuccess` โ existing link + no active token โ success).+- `botUsername` drives the "Open in <platform>" deep-link CTA; re-encrypt the credentials+ WITHOUT it to exercise the no-deep-link fallback. Note the platform config is cached+ in-process for 30s (`packages/app-config/src/messenger.ts` CACHE\_TTL\_MS) โ wait out the TTL+ after editing the row before reloading.+- Locale for evidence shots: `window.__LOBE_STORES.global().switchLocale('zh-CN')` then reload.++### D21. โ WORKS โ when `click @ref` reports Done but the React onClick never fires, click via `eval` `element.click()`++**Situation**: on a dense list row (acceptance check rows with hover-revealed ActionIcons and+expanded-area buttons), `agent-browser click @ref` returned `โ Done` but no TRPC mutation fired and+no state changed โ the pointer click seemingly landed on an overlaying/other element. Repeated for+both hover icons and regular buttons inside the row.++**Doesn't work**: re-snapshotting and clicking the fresh `@ref`; the command still reports success+with no effect (so the failure is silent โ always verify the click by its observable side effect,+e.g. the network request or a DB row, never by the driver's `Done`).++**Works**: locate the element in-page and call the DOM `element.click()` via `eval` โ React's+synthetic onClick fires reliably:++```bash+agent-browser --session "(()=>{const b=[...document.querySelectorAll('button')]+ .find(x=>x.textContent.trim()==='<label>'); b.click(); return 'clicked'})()" < s > eval+```++Scope the query to the intended row/container first (climb from a unique text node, stop before the+ancestor contains other rows' text) โ a page-wide `find(...)` picks the FIRST match and can submit+an action against the wrong row. For drag interactions (annotation canvases), dispatch synthetic+`MouseEvent`s (`mousedown/mousemove/mouseup` with `bubbles:true` and computed `clientX/Y`) on the+target element.++### E34. Shell proxy env (HTTP\_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops++**Situation**: `init-dev-env.sh dev` launched from a shell where a system proxy (Clash etc.) exported+`HTTP_PROXY`/`HTTPS_PROXY`. The server booted fine, pages served, but `POST /api/auth/sign-in/email`+returned a bare `307 โ /` with NO `set-cookie` (body = Next `__next_error__` page), the boot prewarm+logged `redirect count exceeded`, and `setup-auth.sh web-seed` failed with "sign-in succeeded but no+cookies were written" (307 matches its `^[23]` success check).++**Doesn't work**: retrying the seed, restarting the agent-browser daemon โ the failure is in the+server process env, not the client.++**Works**: strip proxy vars when starting the dev server:++```bash+env -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy -u ALL_PROXY -u all_proxy \+ -u NO_PROXY -u no_proxy ./.agents/verify/scripts/init-dev-env.sh dev+```++Symptom fingerprint: every auth POST answers 307 in \~25ms with `application-code` time present, and+the prewarm warning mentions `redirect count exceeded`.++### C12. A globally installed `lh` ingest-report can silently create an ORPHAN verify run (no acceptance attach) when the branch's CLI contract is newer++- **Situation**: publishing/ingesting a report while verifying a branch that extends the verify CLI+ (e.g. adds `--subject` / acceptance attach). The global `lh` accepted the report, returned a+ `verifyRunId`, and printed no error โ but the run's `acceptance_id` was NULL, so it never appeared+ on the acceptance page, which reads as "my ingest didn't show up / the page is stale".+- **Doesn't work**: trusting a green `verifyRunId` from the global CLI as proof of attachment, or+ passing `--subject` to it (`error: unknown option '--subject'` is the tell that it predates the+ branch contract).+- **Works**: run the branch's own CLI from the worktree โ `cd apps/cli && bun src/index.ts verify+ingest-report <dir> --subject topic:<id> โฆ` โ and verify attachment in the DB+ (`select acceptance_id from verify_runs where id='<runId>'`) before driving the UI against it.++### D22. โ WORKS โ driving the manual-approval intervention chain (ๆนๅ / ๆไบค cards) in web chat++- **Situation**: a real agent turn under the default manual-approval mode stops at an+ intervention card (`lobe-activator โ ๆฟๆดปๅทฅๅ ท`, `Task Tools โ createTask`, โฆ) after EVERY tool+ call. `snapshot -i` does not reliably expose the card's option rows / submit button as refs,+ and one turn can chain 4โ5 sequential interventions โ a fixed approve-once script stalls.+- **Doesn't work**: matching the option row by exact text `ๆนๅ` (the row nests the label; the+ filtered element list often misses it), or assuming one approval finishes the turn.+- **Works**: the "approve" option is pre-selected by default, so clicking the card's **ๆไบค**+ button alone approves. Loop until quiescent: each round, find the LAST visible element whose+ text includes `ๆไบค` via `eval`, tag it `data-probe`, click through agent-browser (trusted+ input), then poll `chat().operations` for zero `running` AND no remaining ๆไบค button before+ declaring the turn done. Log which tool each round approved by grabbing the last visible+ `โฆ โ โฆ` header text. One creation turn (activate + createTask + setTaskVerify + runTask)+ took 5 approvals.+- **Also measured (fixture note)**: a task's verify requirement is visible to the RUNNER agent,+ which will optimize toward the acceptance criteria (a "200 ๅญ๏ผno code" instruction with a+ "โฅ1500 ๅญ + Python code" requirement produced a 3.5k-char deliverable) โ a contradictory-criteria+ fixture still fails verification, but not for the reason you scripted; assert on the verifier's+ recorded rationale, not on your intended contradiction.++### E35. A listening port is NOT the product under test โ another project's dev server can own it++- **Situation**: `.env` says `PORT=<n>`, something answers on `<n>`, and a prior session recorded+ "dev server running on `<n>`" โ so the run plans a mere restart.+- **Doesn't work**: trusting liveness (an HTTP response, an open socket) as identity. A sibling+ project's dev server started on the same port responds happily; every request then exercises the+ wrong codebase, and hook/DB assertions fail in ways that read as product bugs.+- **Works**: fingerprint the app before using it: `ps -o command= -p <pid>` of the listener shows the+ repo path in the `next dev`/`node` command line, and an unauthenticated `GET /` redirect is a+ cheap signature (this repo's better-auth redirects to `/signin`; a Clerk app redirects to+ `/login` with `x-clerk-*` headers). If it is the wrong app, free the port and start the right+ server โ and re-verify with the same fingerprint after boot.++### C13. better-auth email-verification cannot be completed from the outside โ treat real-mail paths as blocked++- **Situation**: an assertion requires a REAL email-verification event (e.g. a hook that only fires+ on better-auth verification routes), and the test inbox does not exist.+- **Doesn't work**: recovering the token from the database. The `/verify-email` link token is a+ signed JWT that is never stored; the email-otp OTP did not appear in the `verifications` table+ either (only unrelated OIDC rows), and the send endpoint returns `{"success":true}` regardless.+ Flipping `email_verified` in the DB is a fixture, not a verification โ route-gated hooks+ correctly ignore it (which is itself a useful negative check).+- **Works**: mark the case `blocked` and cover the path with unit tests, or run the flow with a+ real receivable mailbox (staging/prod smoke). Use the DB flip only to unblock downstream+ fixtures, and assert it does NOT produce the event as a bonus authenticity check.++### E36. Desktop main-process `logger.info` is invisible in dev without `DEBUG`++- **Situation**: verifying desktop main-process behavior (e.g. perf probes in a manager/module) by+ reading the dev log.+- **Doesn't work**: expecting `createLogger(ns).info(...)` lines in `/tmp/electron-dev.log` from a+ plain dev start โ in dev (`app.isPackaged` false) `info` only goes through the `debug` package,+ which is silent unless its namespace is enabled.+- **Works**: start the instance with the namespace enabled, e.g.+ `DEBUG="screenCapture:*" electron-dev.sh restart`, then grep the log. In packaged builds the same+ lines land in electron-log's file instead.++### E37. osascript keystrokes go to the frontmost app โ never send Escape++- **Situation**: driving a desktop flow with synthetic keys (global shortcut trigger is fine โ it's+ registered globally), then trying to dismiss a window with `key code 53` (Escape).+- **Doesn't work**: the Escape lands on whatever app is frontmost โ typically the terminal running+ the agent session, which interprets it as an interrupt and kills the agent's own turn.+- **Works**: close app surfaces in-band instead: eval the app's own close IPC via CDP on that+ window's target (`window.electronAPI.invoke('...close')`), or click its close affordance. Reserve+ synthetic keys for globally-registered shortcuts that don't depend on focus.++### E38. Bimodal timings from a globalShortcut handler = idle-event-loop stall (and `setTimeout` probes mask it)++- **Situation**: timing a flow triggered from an Electron `globalShortcut` callback; measurements+ are wildly bimodal (sub-ms vs multi-second) and "fix" themselves when extra probes are added.+- **Doesn't work**: attributing the multi-second gap to whatever awaited call sits at that milestone+ (it may be a cached no-op), or keeping a `setTimeout(0)` diagnostic probe while re-measuring โ a+ pending timer wakes the loop and hides the stall entirely.+- **Works**: bracket the suspect `await` with markers plus one `queueMicrotask` and one+ `setTimeout(0)` marker ONCE to classify the stall, then remove them and re-measure. If the+ continuation only runs when an external event arrives (a CDP poll, mouse move), the cause is the+ native-callback context not draining microtasks on an idle loop โ fix by deferring the handler+ body via `setImmediate` at the registration site, then verify variance collapses.diff --git a/.agents/skills/agent-testing/references/agent-gateway.md b/.agents/verify/references/agent-gateway.mdsimilarity index 90%rename from .agents/skills/agent-testing/references/agent-gateway.mdrename to .agents/verify/references/agent-gateway.mdindex 90525880b3a..a4b4a3d8b5d 100644--- a/.agents/skills/agent-testing/references/agent-gateway.md+++ b/.agents/verify/references/agent-gateway.md@@ -34,14 +34,14 @@ local JWT โ `auth_success` โ full local loop.# reuse of AGENT_GATEWAY_SERVICE_TOKEN). Source resolves to# .records/env/gateway.env by default, else .env.local; override with# JWKS_SOURCE=<env file>. (Managed agent-testing runs have NO .env.local.)-.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh+.agents/verify/scripts/agent-gateway/local-gateway-setup.sh# 2. Start the worker (separate terminal) โ http://localhost:8787cd ../agent-gateway && bun run devcurl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/health # โ 200# 3. Decisive check โ does the local gateway accept the app's JWT?-node .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs+node .agents/verify/scripts/agent-gateway/local-gateway-probe.mjs# โ RECV: {"type":"auth_success"} โ feasible# 4. Point the APP at the local gateway and RESTART its dev server:@@ -67,26 +67,26 @@ exactly why the gateway must already trust the signing key via`scripts/agent-gateway/`-| File | Role |-| ------------------------- | ---------------------------------------------------------------- |-| `local-gateway-setup.sh` | Writes `agent-gateway/.dev.vars` from the app's `.env.local` |-| `local-gateway-probe.mjs` | Signs an app JWT, asserts the local gateway returns auth_success |-| `probe.js` | Injects a 200ms sampler + `__PROBE_EVENT` marker + `__switchTab` |-| `probe-dump.js` | Stops the sampler and returns `{events, samples}` as JSON string |-| `tab-switch.js` | Runs N round-trip switches between two tabs, marks each step |-| `analyze.mjs` | Node post-processor: timeline + regression detection |+| File | Role |+| ------------------------- | ----------------------------------------------------------------- |+| `local-gateway-setup.sh` | Writes `agent-gateway/.dev.vars` from the app's `.env.local` |+| `local-gateway-probe.mjs` | Signs an app JWT, asserts the local gateway returns auth\_success |+| `probe.js` | Injects a 200ms sampler + `__PROBE_EVENT` marker + `__switchTab` |+| `probe-dump.js` | Stops the sampler and returns `{events, samples}` as JSON string |+| `tab-switch.js` | Runs N round-trip switches between two tabs, marks each step |+| `analyze.mjs` | Node post-processor: timeline + regression detection |## Standard workflow```bash# 1. Start Electron with CDP-./.agents/skills/agent-testing/scripts/electron-dev.sh start+.agents/verify/scripts/electron-dev.sh start# 2. Navigate to a chat, switch runtime to Cloud Sandbox (gateway mode)# 3. Install the probe + helpersagent-browser --cdp 9222 eval --stdin \- < .agents/skills/agent-testing/scripts/agent-gateway/probe.js+ < .agents/verify/scripts/agent-gateway/probe.js# 4. Send a tool-call message โ manually or via type+pressagent-browser --cdp 9222 eval "window.__PROBE_EVENT('SENT')"@@ -95,15 +95,15 @@ agent-browser --cdp 9222 eval "window.__PROBE_EVENT('SENT')"# rightmost inactive tab as AWAY โ edit ROUND_TRIPS / DWELL_MS in the# file if you want different timing)agent-browser --cdp 9222 eval --stdin \- < .agents/skills/agent-testing/scripts/agent-gateway/tab-switch.js+ < .agents/verify/scripts/agent-gateway/tab-switch.js# 6. Wait for streaming to finish, then dumpagent-browser --cdp 9222 eval --stdin \- < .agents/skills/agent-testing/scripts/agent-gateway/probe-dump.js \+ < .agents/verify/scripts/agent-gateway/probe-dump.js \> /tmp/probe.json# 7. Analyze-node .agents/skills/agent-testing/scripts/agent-gateway/analyze.mjs /tmp/probe.json+node .agents/verify/scripts/agent-gateway/analyze.mjs /tmp/probe.json```The analyzer prints three sections: EVENTS, TIMELINE, REGRESSIONS. Ifdiff --git a/.agents/skills/agent-testing/references/auth.md b/.agents/verify/references/auth.mdsimilarity index 95%rename from .agents/skills/agent-testing/references/auth.mdrename to .agents/verify/references/auth.mdindex 0858a68bc6d..33da8a3dc56 100644--- a/.agents/skills/agent-testing/references/auth.md+++ b/.agents/verify/references/auth.md@@ -1,15 +1,15 @@# Auth Setup for Local Agent Testing**Auth is the gate for all automated testing.** Complete-[Step 2.0](../SKILL.md#20-resolve-the-current-test-environment) first so+[Step 2.0](../../skills/agent-testing/SKILL.md#20-resolve-the-current-test-environment) first so`SERVER_URL` and ports are resolved, then verify auth before writing any teststep.Initialize helpers first:```bash-SCRIPT="./.agents/skills/agent-testing/scripts/setup-auth.sh"-TEST_ENV="./.agents/skills/agent-testing/scripts/test-env.sh"+SCRIPT=".agents/verify/scripts/setup-auth.sh"+TEST_ENV=".agents/verify/scripts/test-env.sh"eval "$($TEST_ENV --exports)"```@@ -44,9 +44,9 @@ For the self-contained no-root-`.env` dev environment, seed the baseline userand API key once:```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user+.agents/verify/scripts/init-dev-env.sh seed-usersource .records/env/agent-testing-cli.env-./.agents/skills/agent-testing/scripts/setup-auth.sh cli-seed+.agents/verify/scripts/setup-auth.sh cli-seed```The seed step writes `LOBE_API_KEY` for humans and maps it to the CLI's current@@ -88,8 +88,8 @@ is authenticated.For the seeded local dev environment, use the automatic path:```bash-./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user-./.agents/skills/agent-testing/scripts/setup-auth.sh web-seed+.agents/verify/scripts/init-dev-env.sh seed-user+.agents/verify/scripts/setup-auth.sh web-seed````web-seed` posts the seeded email/password to@@ -154,7 +154,7 @@ and `start` seeds every new instance from that snapshot. Sign in once, not onceper run.```bash-EDEV=./.agents/skills/agent-testing/scripts/electron-dev.sh+EDEV=.agents/verify/scripts/electron-dev.sh$EDEV login-status # which source seeds the next instance, and its expiry$EDEV save-login <id> # snapshot a live instance without stopping it```@@ -162,7 +162,7 @@ $EDEV save-login <id> # snapshot a live instance without stopping itThe standard check (do NOT hand-roll a store eval) once Electron is up with CDP:```bash-./.agents/skills/agent-testing/scripts/app-probe.sh auth+.agents/verify/scripts/app-probe.sh auth# โ {"ok":true,"isSignedIn":true,"userId":"user_xxx"}```diff --git a/.agents/skills/agent-testing/references/dev-server.md b/.agents/verify/references/dev-server.mdsimilarity index 91%rename from .agents/skills/agent-testing/references/dev-server.mdrename to .agents/verify/references/dev-server.mdindex 85409be86f0..ed98a7c2331 100644--- a/.agents/skills/agent-testing/references/dev-server.md+++ b/.agents/verify/references/dev-server.md@@ -6,7 +6,7 @@ surfaces (CLI, Electron, Web) hit.## Resolve ports firstRun `test-env.sh` as described in-[SKILL.md Step 2.0](../SKILL.md#20-resolve-the-current-test-environment)+[SKILL.md Step 2.0](../../skills/agent-testing/SKILL.md#20-resolve-the-current-test-environment)before starting or probing any local test surface.## Ports & modes@@ -52,22 +52,22 @@ curl -s -o /dev/null -w '%{http_code}' "$SERVER_URL/"AGENT_RUNTIME_MODE=queue pnpm run dev:next# Without root .env: use the self-contained agent-testing env.-./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-next+.agents/verify/scripts/init-dev-env.sh dev-next# Full-stack SPA + backend. Required for Web smoke.# With root .env:AGENT_RUNTIME_MODE=queue bun run dev# Without root .env:-./.agents/skills/agent-testing/scripts/init-dev-env.sh dev+.agents/verify/scripts/init-dev-env.sh dev# Local QStash. Run in a separate terminal only when testing workflow paths.-./.agents/skills/agent-testing/scripts/init-dev-env.sh qstash+.agents/verify/scripts/init-dev-env.sh qstash# Restart โ required to pick up server-side code changes.# For a no-.env server started by init-dev-env.sh, stop only its owned process tree:-./.agents/skills/agent-testing/scripts/init-dev-env.sh stop-dev-./.agents/skills/agent-testing/scripts/init-dev-env.sh dev-next+.agents/verify/scripts/init-dev-env.sh stop-dev+.agents/verify/scripts/init-dev-env.sh dev-next```## When a server restart is neededdiff --git a/.agents/skills/agent-testing/references/multi-instance.md b/.agents/verify/references/multi-instance.mdsimilarity index 100%rename from .agents/skills/agent-testing/references/multi-instance.mdrename to .agents/verify/references/multi-instance.mddiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/analyze-events.ts b/.agents/verify/scripts/agent-gateway/analyze-events.tssimilarity index 98%rename from .agents/skills/agent-testing/scripts/agent-gateway/analyze-events.tsrename to .agents/verify/scripts/agent-gateway/analyze-events.tsindex 82895013cfd..3eda8a1be16 100644--- a/.agents/skills/agent-testing/scripts/agent-gateway/analyze-events.ts+++ b/.agents/verify/scripts/agent-gateway/analyze-events.ts@@ -11,7 +11,7 @@// 6. ROLLBACKS โ msgN / childN / role drops in the active-topic timeline//// Usage:-// bun run .agents/skills/agent-testing/scripts/agent-gateway/analyze-events.ts <dump.json>+// bun run .agents/verify/scripts/agent-gateway/analyze-events.ts <dump.json>import { readFileSync } from 'node:fs';@@ -96,8 +96,7 @@ for (const c of actionCalls) {continue;}const snapshot = (c.args as any)?.snapshot as- | Array<{ id: string; role: string; cLen: number; rLen: number }>- | undefined;+ Array<{ id: string; role: string; cLen: number; rLen: number }> | undefined;const snapStr = snapshot?.length? ' snapshot=' + snapshot.map((m) => `${m.id}:${m.role}/c${m.cLen}/r${m.rLen}`).join(' | '): '';diff --git a/.agents/skills/agent-testing/scripts/agent-gateway/analyze.mjs b/.agents/verify/scripts/agent-gateway/analyze.mjssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/analyze.mjsrename to .agents/verify/scripts/agent-gateway/analyze.mjsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs b/.agents/verify/scripts/agent-gateway/local-gateway-probe.mjssimilarity index 93%rename from .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjsrename to .agents/verify/scripts/agent-gateway/local-gateway-probe.mjsindex a41f0e64197..97ae712aaaa 100644--- a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs+++ b/.agents/verify/scripts/agent-gateway/local-gateway-probe.mjs@@ -15,7 +15,7 @@// 3. .records/env/gateway.env (managed flow default)//// Run from the lobehub repo root (needs `jose` from its node_modules):-// JWKS_KEY="$JWKS_KEY" node .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-probe.mjs+// JWKS_KEY="$JWKS_KEY" node .agents/verify/scripts/agent-gateway/local-gateway-probe.mjs// JWKS_SOURCE=.env.local node .../local-gateway-probe.mjs # explicit file// GATEWAY_WS=ws://localhost:8787 node .../local-gateway-probe.mjs # override ws@@ -33,7 +33,7 @@ const fromFile = (p) => {const jwksRaw =process.env.JWKS_KEY?.trim() ||fromFile(process.env.JWKS_SOURCE) ||- fromFile(new URL('../../../../../.records/env/gateway.env', import.meta.url).pathname);+ fromFile(new URL('../../../../.records/env/gateway.env', import.meta.url).pathname);if (!jwksRaw) {console.error('โ no JWKS_KEY found โ export JWKS_KEY, or set JWKS_SOURCE=<env file>, or create .records/env/gateway.env',diff --git a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh b/.agents/verify/scripts/agent-gateway/local-gateway-setup.shsimilarity index 96%rename from .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.shrename to .agents/verify/scripts/agent-gateway/local-gateway-setup.shindex 587b6e5d938..8c520cc666c 100755--- a/.agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh+++ b/.agents/verify/scripts/agent-gateway/local-gateway-setup.sh@@ -19,11 +19,11 @@# It then prints the app-side env you must set + how to start the worker.## Usage (from the lobehub repo root):-# .agents/skills/agent-testing/scripts/agent-gateway/local-gateway-setup.sh+# .agents/verify/scripts/agent-gateway/local-gateway-setup.shset -euo pipefail-REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../../.." && pwd)"+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"GATEWAY_DIR="$(cd "$REPO_ROOT/.." && pwd)/agent-gateway"PORT="${GATEWAY_PORT:-8787}"diff --git a/.agents/skills/agent-testing/scripts/agent-gateway/probe-dump.js b/.agents/verify/scripts/agent-gateway/probe-dump.jssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/probe-dump.jsrename to .agents/verify/scripts/agent-gateway/probe-dump.jsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/probe-dump.ts b/.agents/verify/scripts/agent-gateway/probe-dump.tssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/probe-dump.tsrename to .agents/verify/scripts/agent-gateway/probe-dump.tsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/probe-events.ts b/.agents/verify/scripts/agent-gateway/probe-events.tssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/probe-events.tsrename to .agents/verify/scripts/agent-gateway/probe-events.tsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/probe.js b/.agents/verify/scripts/agent-gateway/probe.jssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/probe.jsrename to .agents/verify/scripts/agent-gateway/probe.jsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/run.ts b/.agents/verify/scripts/agent-gateway/run.tssimilarity index 94%rename from .agents/skills/agent-testing/scripts/agent-gateway/run.tsrename to .agents/verify/scripts/agent-gateway/run.tsindex 03b909d4e04..b6af7317320 100644--- a/.agents/skills/agent-testing/scripts/agent-gateway/run.ts+++ b/.agents/verify/scripts/agent-gateway/run.ts@@ -5,16 +5,16 @@// streaming-replay test fixtures.//// Commands:-// bun run .agents/skills/agent-testing/scripts/agent-gateway/run.ts install+// bun run .agents/verify/scripts/agent-gateway/run.ts install// Bundle probe-events.ts and inject into the CDP-attached browser.// Re-installing clears all buffers and re-patches WebSocket / fetch.//-// bun run .agents/skills/agent-testing/scripts/agent-gateway/run.ts dump [name]+// bun run .agents/verify/scripts/agent-gateway/run.ts dump [name]// Stop the timeline timer, fetch the capture as JSON, write it to// `.agent-gateway/<name>-<YYYYMMDD-HHmmss>.json`. `name` defaults to// `dump`. Prints the absolute path written.//-// bun run .agents/skills/agent-testing/scripts/agent-gateway/run.ts analyze [path]+// bun run .agents/verify/scripts/agent-gateway/run.ts analyze [path]// Run analyze-events.ts on the dump. `path` defaults to the most// recently modified file in `.agent-gateway/`.//@@ -28,8 +28,8 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));-// .agents/skills/agent-testing/scripts/agent-gateway/ โ 5 levels up-const PROJECT_ROOT = path.resolve(SCRIPT_DIR, '../../../../..');+// .agents/verify/scripts/agent-gateway/ โ 4 levels up+const PROJECT_ROOT = path.resolve(SCRIPT_DIR, '../../../..');const DUMP_DIR = path.join(PROJECT_ROOT, '.agent-gateway');interface Flags {diff --git a/.agents/skills/agent-testing/scripts/agent-gateway/tab-switch.js b/.agents/verify/scripts/agent-gateway/tab-switch.jssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/tab-switch.jsrename to .agents/verify/scripts/agent-gateway/tab-switch.jsdiff --git a/.agents/skills/agent-testing/scripts/agent-gateway/types.ts b/.agents/verify/scripts/agent-gateway/types.tssimilarity index 100%rename from .agents/skills/agent-testing/scripts/agent-gateway/types.tsrename to .agents/verify/scripts/agent-gateway/types.tsdiff --git a/.agents/skills/agent-testing/scripts/app-probe.sh b/.agents/verify/scripts/app-probe.shsimilarity index 100%rename from .agents/skills/agent-testing/scripts/app-probe.shrename to .agents/verify/scripts/app-probe.shdiff --git a/.agents/skills/agent-testing/scripts/check-s3.mjs b/.agents/verify/scripts/check-s3.mjssimilarity index 100%rename from .agents/skills/agent-testing/scripts/check-s3.mjsrename to .agents/verify/scripts/check-s3.mjsdiff --git a/.agents/skills/agent-testing/scripts/electron-dev.sh b/.agents/verify/scripts/electron-dev.shsimilarity index 99%rename from .agents/skills/agent-testing/scripts/electron-dev.shrename to .agents/verify/scripts/electron-dev.shindex 99113abd0e4..a4e09450d78 100755--- a/.agents/skills/agent-testing/scripts/electron-dev.sh+++ b/.agents/verify/scripts/electron-dev.sh@@ -64,7 +64,7 @@ VITE_BASE="${VITE_BASE:-5173}"ELECTRON_WAIT_S="${ELECTRON_WAIT_S:-90}"RENDERER_WAIT_S="${RENDERER_WAIT_S:-60}"SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"-PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"+PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"POOL_DIR="${POOL_DIR:-/tmp/lobe-electron-pool}"GOLDEN_PROFILE="${LOBE_GOLDEN_PROFILE:-$HOME/Library/Application Support/lobehub-desktop-dev}"# Persistent across runs AND across /tmp cleanup โ the pool dir is not.diff --git a/.agents/skills/agent-testing/scripts/init-dev-env.sh b/.agents/verify/scripts/init-dev-env.shsimilarity index 98%rename from .agents/skills/agent-testing/scripts/init-dev-env.shrename to .agents/verify/scripts/init-dev-env.shindex f260b42e8a5..388982c9f21 100755--- a/.agents/skills/agent-testing/scripts/init-dev-env.sh+++ b/.agents/verify/scripts/init-dev-env.sh@@ -31,7 +31,7 @@set -euo pipefail-REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"ROOT_ENV_FILE="$REPO_ROOT/.env"# Resolve the workspace root the SAME way test-env.sh does, so both scripts@@ -503,7 +503,7 @@ cmd_status() {elsenote "QStash is not answering as QStash at $QSTASH_URL (needed for agent-runtime / queue mode)"fi- if node "$REPO_ROOT/.agents/skills/agent-testing/scripts/check-s3.mjs" > /dev/null 2>&1; then+ if node "$REPO_ROOT/.agents/verify/scripts/check-s3.mjs" > /dev/null 2>&1; thenok "S3 reachable and writable: $S3_ENDPOINT/$S3_BUCKET"elsenote "S3 is not ready at $S3_ENDPOINT (start it with: $0 s3)"@@ -541,7 +541,7 @@ cmd_preflight() {note "AGENT_RUNTIME_MODE=$AGENT_RUNTIME_MODE (not queue) โ QStash not required"fi- if node "$REPO_ROOT/.agents/skills/agent-testing/scripts/check-s3.mjs" > /dev/null 2>&1; then+ if node "$REPO_ROOT/.agents/verify/scripts/check-s3.mjs" > /dev/null 2>&1; thenok "S3 read/write/delete passed: $S3_ENDPOINT/$S3_BUCKET"elsebad "S3 preflight failed at $S3_ENDPOINT/$S3_BUCKET"@@ -655,7 +655,7 @@ cmd_s3() {note "starting local S3 server at $S3_ENDPOINT"note "bucket=$S3_BUCKET; data=$S3_DATA_DIR"note "keep this process running while testing file uploads"- exec node .agents/skills/agent-testing/scripts/start-s3.mjs+ exec node .agents/verify/scripts/start-s3.mjs}cmd_dev_next() {diff --git a/.agents/skills/agent-testing/scripts/init-dev-env.test.sh b/.agents/verify/scripts/init-dev-env.test.shsimilarity index 100%rename from .agents/skills/agent-testing/scripts/init-dev-env.test.shrename to .agents/verify/scripts/init-dev-env.test.shdiff --git a/.agents/skills/agent-testing/scripts/record-electron-demo.sh b/.agents/verify/scripts/record-electron-demo.shsimilarity index 100%rename from .agents/skills/agent-testing/scripts/record-electron-demo.shrename to .agents/verify/scripts/record-electron-demo.shdiff --git a/.agents/skills/agent-testing/scripts/setup-auth.sh b/.agents/verify/scripts/setup-auth.shsimilarity index 97%rename from .agents/skills/agent-testing/scripts/setup-auth.shrename to .agents/verify/scripts/setup-auth.shindex 64132d39ff7..aee9bfe0e85 100755--- a/.agents/skills/agent-testing/scripts/setup-auth.sh+++ b/.agents/verify/scripts/setup-auth.sh@@ -22,7 +22,7 @@set -euo pipefail-REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)"+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"workspace_root_for_port() {local root="$REPO_ROOT"@@ -143,7 +143,7 @@ check_cli() {bad "CLI API-key auth failed for $SERVER_URL (http_code='$code')"note "seed the local API key first:"- note "./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user"+ note "./.agents/verify/scripts/init-dev-env.sh seed-user"note "source $CLI_ENV_FILE"rm -f "$body_file"return 1@@ -154,7 +154,7 @@ check_cli() {elsebad "CLI not logged in to $SERVER_URL"note "automated path:"- note "./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user && source $CLI_ENV_FILE && $0 cli-seed"+ note "./.agents/verify/scripts/init-dev-env.sh seed-user && source $CLI_ENV_FILE && $0 cli-seed"note "interactive fallback:"note "cd apps/cli && LOBEHUB_CLI_HOME=.lobehub-dev bun src/index.ts login --server $SERVER_URL"return 1@@ -487,7 +487,7 @@ PYnote "Use Chrome Cookie injection instead: $0 open-chrome, then pbpaste | $0 web"elsenote "make sure the seed user exists:"- note "./.agents/skills/agent-testing/scripts/init-dev-env.sh seed-user"+ note "./.agents/verify/scripts/init-dev-env.sh seed-user"fireturn 1fidiff --git a/.agents/skills/agent-testing/scripts/setup-auth.test.sh b/.agents/verify/scripts/setup-auth.test.shsimilarity index 100%rename from .agents/skills/agent-testing/scripts/setup-auth.test.shrename to .agents/verify/scripts/setup-auth.test.shdiff --git a/.agents/skills/agent-testing/scripts/start-s3.mjs b/.agents/verify/scripts/start-s3.mjssimilarity index 100%rename from .agents/skills/agent-testing/scripts/start-s3.mjsrename to .agents/verify/scripts/start-s3.mjsdiff --git a/.agents/skills/agent-testing/scripts/test-env.sh b/.agents/verify/scripts/test-env.shsimilarity index 99%rename from .agents/skills/agent-testing/scripts/test-env.shrename to .agents/verify/scripts/test-env.shindex c15d6eb5372..a6467901d9b 100755--- a/.agents/skills/agent-testing/scripts/test-env.sh+++ b/.agents/verify/scripts/test-env.sh@@ -7,7 +7,7 @@set -euo pipefailSCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-REPO_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"NODE_ENV="${NODE_ENV:-development}"VALUE_APP_URL=""diff --git a/.agents/skills/agent-testing/scripts/test-env.test.sh b/.agents/verify/scripts/test-env.test.shsimilarity index 78%rename from .agents/skills/agent-testing/scripts/test-env.test.shrename to .agents/verify/scripts/test-env.test.shindex f778ef01744..5356e314cef 100755--- a/.agents/skills/agent-testing/scripts/test-env.test.sh+++ b/.agents/verify/scripts/test-env.test.sh@@ -25,12 +25,12 @@ assert_contains() {tmp_dir="$(mktemp -d)"trap 'rm -rf "$tmp_dir"' EXIT-mkdir -p "$tmp_dir/lobehub-cloud-1/.agents/skills" "$tmp_dir/lobehub/.agents/skills"-ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub-cloud-1/.agents/skills/agent-testing"-ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub/.agents/skills/agent-testing"+mkdir -p "$tmp_dir/lobehub-cloud-1/.agents" "$tmp_dir/lobehub/.agents"+ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub-cloud-1/.agents/verify"+ln -s "$SCRIPT_DIR/.." "$tmp_dir/lobehub/.agents/verify"-cloud_script="$tmp_dir/lobehub-cloud-1/.agents/skills/agent-testing/scripts/test-env.sh"-oss_script="$tmp_dir/lobehub/.agents/skills/agent-testing/scripts/test-env.sh"+cloud_script="$tmp_dir/lobehub-cloud-1/.agents/verify/scripts/test-env.sh"+oss_script="$tmp_dir/lobehub/.agents/verify/scripts/test-env.sh"assert_eq "$("$cloud_script" --value SERVER_URL)" "http://localhost:3021"assert_eq "$("$cloud_script" --value SPA_PORT)" "9801"diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex bb3844e9b8c..fb67013317c 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -14,7 +14,8 @@],"files": ["dist",- "man"+ "man",+ "skills"],"scripts": {"build": "tsdown",@@ -27,6 +28,9 @@"test:coverage": "bunx vitest run --config vitest.config.mts --coverage","type-check": "tsc --noEmit"},+ "dependencies": {+ "ws": "^8.21.0"+ },"devDependencies": {"@lobechat/agent-gateway-client": "workspace:*","@lobechat/const": "workspace:*",@@ -52,8 +56,7 @@"superjson": "^2.2.6","tree-kill": "^1.2.2","tsdown": "^0.21.10",- "typescript": "^6.0.3",- "ws": "^8.21.0"+ "typescript": "^6.0.3"},"publishConfig": {"access": "public",diff --git a/apps/cli/skills/agent-testing/SKILL.md b/apps/cli/skills/agent-testing/SKILL.mdnew file mode 100644index 00000000000..e8f3efa7c84--- /dev/null+++ b/apps/cli/skills/agent-testing/SKILL.md@@ -0,0 +1,573 @@+---+name: agent-testing+description: >+ Agentic end-to-end testing for any project: backend verification via the+ project CLI, frontend verification via agent-browser (web), and desktop+ verification via CDP (Electron). Drives the real surface, captures visually+ confirmed evidence, and publishes a structured report to the LobeHub verify+ platform. Triggers on 'cli test', 'test with cli', 'verify with cli',+ 'backend test with cli', 'local test', 'test in electron', 'test desktop',+ 'manual test', 'test report', or any local end-to-end verification task.+---++# Agent Testing (Agentic End-to-End Verification)++One skill for agentic end-to-end testing of any project โ backend through the+project CLI, web through a browser, desktop through Electron/CDP. Every session+follows three phases:++```text+PLAN (Steps 0โ2) โ EXECUTE (Steps 3โ6) โ FINISH (Step 7)+```++Do not enter Execute until Plan has confirmed both the environment state and the+execution plan. Treat Steps 3โ6 as one continuous execution phase: select the+surface, run the cases, produce the report, and publish it. Always end with+Finish unless the user explicitly asks to keep the environment running.++**Everything project-specific comes from an adapter, not from this skill.** The+concrete start/stop commands, ports, auth, surfaces, and probes for the project+under test live in `.agents/verify/PROJECT.md`. This skill supplies the process,+the evidence discipline, and the surface methodology; `PROJECT.md` supplies the+commands. When a step below says "from `PROJECT.md`", read that file for the+actual command instead of guessing. See+[references/project-adapter.md](./references/project-adapter.md).++## Phase 1 โ Plan++Confirm what will run and whether the environment is ready before changing or+starting anything.++Skill-internal setup โ loading this skill, reading the living logs and reference+files โ is silent preparation: never narrate it to the user ("I'll load the+mandatory living logs firstโฆ" is noise). The first user-visible message of a+session is about the user's test โ the target confirmation (Step 0) or the+Phase 1 approval gate โ in one message, not a setup announcement followed by the+same question again.++### Step 0 โ Ground the target, then read the two living-log layers (mandatory)++**A test target must exist before anything else happens.** When the invocation+carries none (bare skill invocation, no pending ask in the conversation), ground+it first โ do NOT read the living logs or touch the environment yet:++1. Take the target from the user's words in this conversation when they exist โ+ the task lives in their words, not in git (common-mistakes: task from the ask,+ not the branch).+2. Otherwise, infer the most likely candidate from observable context (current+ branch, recent commits, working-tree changes) and confirm it with one+ structured question โ the candidate as the recommended option, clearly labeled+ as a guess. Never start executing against an unconfirmed guess.+3. Only when nothing is inferable, ask one direct open question. Asking "what+ should I verify" is the one legitimate opening question โ but asking it+ open-ended when a candidate was inferable wastes the user's turn.++**Once the target is known**, read both layers of both living logs in full and+hold them in mind for this run. Reading them before a target exists wastes+context that may be compacted away before Execute โ they inform execution, not+target selection.++- **Generic layer** (ships with this skill, read-only here):+ [references/common-mistakes.md](./references/common-mistakes.md) and+ [references/probe-mock-patterns.md](./references/probe-mock-patterns.md).+ Two mistakes that keep biting:+ - **Never declare a case `passed` from grep/skeleton-count heuristics โ open the+ actual screenshot with Read and confirm it rendered the expected content.** A+ blank/white page also has 0 skeletons and still matches persistent nav text.+ - **If the goal is verifying error/failure states, do NOT stop at happy-path+ when injection is hard.** Escalate (see the pattern library) until you have+ real failure-state evidence.+- **Project layer** (writable, owned by the project): `.agents/verify/common-mistakes.md`+ and `.agents/verify/probe-mock-patterns.md`, when they exist. These carry what+ earlier runs learned about THIS project.++**The project layer is a living log โ append to it during the run**, in English:++- User gives negative feedback โ new case in `.agents/verify/common-mistakes.md`+ (Wrong approach / Why / What it breaks / Correct approach).+- You hit any probe/mock that is blocked, bypassed, or needs a workaround โ new+ item in `.agents/verify/probe-mock-patterns.md` (Situation / Doesn't work /+ Works).++Write project-specific learnings to the **project layer only**. Never edit the+generic layer from a consumer repo โ it is read-only and updated by PR to the CLI+repo. **Confidentiality of the generic layer:** its entries must be+product-independent. If a learning turns out to be product-independent and worth+sharing, genericize it and open a PR upstream; keep anything naming a project's+packages, routes, schemas, env vars, service names, or business logic in the+project layer.++### Step 0.5 โ Adapter check (mandatory when `PROJECT.md` is missing)++If `.agents/verify/PROJECT.md` does not exist, run the first-run bootstrap in+[references/project-adapter.md](./references/project-adapter.md) BEFORE anything+else: explore the repo (package.json / README / CI workflows / Makefile / compose+files), draft a `PROJECT.md` from the fixed section skeleton, present it to the+user for confirmation, and write it only after approval. Do not start a dev+server or write test steps against an unconfirmed adapter.++When `PROJECT.md` exists, read it now โ every concrete command in Steps 1โ7 comes+from it. When observed reality diverges from it during the run, fix the adapter in+place (adapter drift is a living-log entry: amend the file during the run).++### Step 1 โ Prepare the execution plan++Skip directly to Step 2 if: the test is a single re-run after a fix, the plan was+already agreed on, or the user gave exact commands.++Prepare the proposed surface, cases, expected evidence, assumptions, and report+deliverable. Do not ask for approval yet: Step 2 must establish the real+environment state first so the user can approve one complete, evidence-backed plan+instead of separate plan and environment prompts.++### Step 2 โ Confirm environment state and auth (mandatory)++Step 2 is about getting the environment ready: **dependencies are healthy** and+**auth is green**. A test run that dies halfway on a missing dependency or a login+wall wastes the whole session โ clear both gates BEFORE writing a single test+step. The concrete commands for each check come from `PROJECT.md`; the rules below+are the ones that hold for every project.++#### 2.0 Resolve the current test environment++Before starting a dev server, checking auth, opening agent-browser, or writing+test steps, resolve and confirm the environment `PROJECT.md` describes โ the base+URLs, ports, and required services. Do not rely on a hard-coded port table: read+the values from the project's own env resolver (per `PROJECT.md` ยง2). If the+resolved values do not match a running dev server, fix/export the env first, then+continue.++#### 2.1 Dependencies are installed++Install per `PROJECT.md` ยง2. **Universal rule: a monorepo root install does not+always cover every app.** If the project has standalone sub-packages with their+own `node_modules` (the adapter says which), install in each one the test will+touch โ a stale standalone install typically fails at build/launch with an+unresolved workspace import.++#### 2.2 Run long-lived scripts from the repo root++Background commands inherit the current working directory. Relative paths in this+skill and in `PROJECT.md` are repo-root-relative, so a script launched while `cwd`+is a sub-package can fail with `No such file or directory`. Verify `pwd` is the+repo root before launching long-running scripts.++#### 2.3 Start the dev environment++Start the environment per `PROJECT.md` ยง2 (dev server, plus any required services+such as a database, cache, queue, or object store). **Universal rules:**++- Prefer the project's own already-configured local environment when one exists;+ do not clobber a user's running config.+- Any service the feature under test depends on is a **hard prerequisite**, not an+ "only when needed" nicety. If a run touches a code path that dispatches to a+ queue/worker/object store, that service must be up first or the run dies before+ reaching the code under test โ and the failure often reads as unrelated to the+ env. `PROJECT.md` ยง6 lists these constraints; gate on them.++#### 2.4 Auth is green for the selected surface++**Auth is the gate for automated testing, but the gate is surface-scoped.** Pick+the intended surface first when it is already clear from the task, then check only+that surface. Do not block a web test on CLI auth or a desktop login state unless+the test spans those surfaces. Run the per-surface status check from `PROJECT.md`+ยง3. If a surface is signed out, **drive the sign-in yourself** โ auth is+environment mechanics the skill owns; never hand the user the sign-in click unless+a step genuinely needs something only they can supply (a 2FA push), and then name+the exact blocking step.++#### 2.5 Screen-recording preflight (OS-capture surfaces only)++macOS `screencapture` / osascript captures come out **entirely black** when Screen+Recording (TCC) permission is missing OR โ just as often โ the **display is+asleep / locked / on a screensaver** (permission is fine, but there is nothing lit+to capture; this bites after a long idle run). A black PNG is easy to mistake for+a real capture, so gate BEFORE any OS-capture step:++```bash+# $SKILL_DIR = wherever this skill is installed+"$SKILL_DIR/scripts/check-screen-recording.sh" # exit 0 = OS capture will work+```++It checks both layers โ permission and a real one-frame blackness probe โ and+prints the exact fix. `capture-app-window.sh` runs it automatically and refuses to+write a black artifact (bypass with `SKIP_SCREEN_CHECK=1`). This gate is **only**+for OS-capture surfaces. CDP-based evidence (`agent-browser screenshot`,+`cdp-screenshot.sh`, `record-app-screen.sh`) renders from the browser engine and+is unaffected. Because the display can sleep mid-run, keep it awake for the whole+capture session:++```bash+caffeinate -dimsu & # prevent display/idle sleep for the run; kill when done+```++#### Phase 1 approval gate โ report environment + plan to the user++At the end of Step 2, always send one user-facing Plan feedback before entering+Execute. Read and follow [references/plan.md](./references/plan.md). It requires:++- an overall environment verdict with concrete checks and evidence;+- emoji-prefixed status markers in the verdict and every table row+ (`โ Ready`, `โ ๏ธ Warning`, `โ Blocked`, `โณ Pending`);+- the proposed execution plan, cases, and expected evidence;+- every unresolved prerequisite, clearly assigned to the agent or the user;+- an explicit statement that nothing is needed from the user when that is true;+- one structured confirmation question after the feedback.++Resolve safe, agent-owned environment mechanics before presenting the gate. Ask+the user only for prerequisites that genuinely require their authority, secret,+device action, or product decision. Do not enter Phase 2 until the user approves+the plan and all blocking user-owned prerequisites are satisfied.++## Phase 2 โ Execute++Carry the approved plan through surface selection, verification, reporting, and+publication without reopening environment decisions unless observed state+invalidates the plan.++### Step 3 โ Pick the surface by change scope++| Change scope | Default surface | Why | Guide |+| -------------------------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | ---------------------------------------------- |+| **Backend** (router / service / model / migration) | **CLI** | Fastest loop, text-assertable output, zero UI flakiness | [surfaces/cli.md](./surfaces/cli.md) |+| **Pure frontend** (components, store, styles, UX) | **Electron** (agent-browser + CDP) if the project ships a desktop shell, else **Web** | Primary product shape; live state introspection | [surfaces/electron.md](./surfaces/electron.md) |+| **Full-stack** (new API + UI consuming it) | **Web** (browser + local dev server) | One surface where network requests and UI are observable together | [surfaces/web.md](./surfaces/web.md) |++Which of these surfaces the project actually has, and how each one launches, comes+from `PROJECT.md` ยง4. Escalate, don't duplicate: verify a backend change with the+CLI first; only add a UI pass when the change actually affects the UI.++**Verify the change runs where you think it does โ confirm runtime, don't assume.**+Some features have two execution paths and the UI silently picks one (e.g. a client+runtime vs a server/queue runtime). A test that exercises the wrong path can pass+green without ever touching the code under test. Before trusting a result, **prove+which runtime ran** โ a server-side operation row, a queue step, a server-only log+line. If the UI won't take the intended path, drive it directly (call the server+endpoint) so that runtime actually executes.++#### Environment support (local macOS vs cloud Linux)++The decisive constraint per surface is **how evidence (screenshots) is captured**:+CDP-based capture (`agent-browser screenshot`) renders from the browser engine and+needs no real display; OS-level capture (`screencapture`, osascript) is macOS-only.++| Surface | macOS (local) | Linux / cloud (headless) | Screenshot mechanism |+| -------- | ------------- | --------------------------------------------------------- | ------------------------------------------------------ |+| CLI | โ | โ | n/a โ text output |+| Web | โ | โ headless Chromium works natively | CDP โ no display needed |+| Electron | โ | โ ๏ธ runs, but needs a display server: wrap with `xvfb-run` | CDP works under Xvfb; `capture-app-window.sh` does NOT |++When a test must stay cloud-portable, prefer CDP-based evidence over OS-level+capture wherever both exist.++### Step 4 โ Run++Surface guides above carry the detailed workflows. Shared infrastructure:++| Need | Where |+| ---------------------------------- | -------------------------------------------------------------------- |+| `agent-browser` command reference | [references/agent-browser.md](./references/agent-browser.md) |+| osascript patterns (general macOS) | [references/osascript.md](./references/osascript.md) |+| Screen recording | [references/record-app-screen.md](./references/record-app-screen.md) |++#### Scripts++All under `<skill-dir>/scripts/` (resolve `<skill-dir>` to wherever this skill is+installed; `chmod +x` is applied on install):++| Script | Usage |+| ------------------------------- | ----------------------------------------------------------------------------------------------- |+| `report-init.sh` | Scaffold a structured report grouped by acceptance subject (Step 5) |+| `fixture.mjs` | Per-check fixtures: `init-check`, `list`, and `compose` an ingest-ready round (Step 5) |+| `record-gif.sh` | Frame-sequence โ GIF for time-based behavior (streaming, timers, animations) |+| `check-screen-recording.sh` | Preflight: OS screen-capture works (macOS Screen Recording + display awake) |+| `cdp-screenshot.sh` | Electron/Chrome screenshot via RAW CDP (bypasses the agent-browser daemon); `--check` preflight |+| `capture-app-window.sh` | Screenshot a specific app window (general; macOS OS capture) |+| `record-app-screen.sh` | Record app screen (CDP screenshots โ video + gallery) |+| `agent-browser-klm.mjs` | Wrap `agent-browser`, run the real action, append a GOMS-KLM interaction atom JSONL |+| `agent-browser-klm-analyze.mjs` | Summarize interaction JSONL into `result.json.interactionCost` |++Project-specific probes and env scripts (the "jump straight to app state" fast+paths) live in the project's own `.agents/verify/scripts/` and are described in+`PROJECT.md` ยง5 โ not here.++#### Agent-browser interaction-cost tracing (optional, UI runs)++For UI verification runs, drive cost-bearing browser actions through the KLM+wrapper so the same action also records a user-equivalent interaction atom:++```bash+TRACE="$DIR/interaction-trace.jsonl"+SESSION=your-session # from PROJECT.md++"$SKILL_DIR/scripts/agent-browser-klm.mjs" \+ --klm-trace "$TRACE" --klm-phase login --klm-check case-1 \+ --session "$SESSION" click @e3++"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \+ --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \+ --confidence 0.75 --reason "First view requires understanding state and next action"+```++The wrapper forwards every non-`--klm-*` argument to `agent-browser`. Physical+actions are inferred from the browser command (`click โ P+K`, `fill/type โ+P+T(n)`, `press โ K`, `wait โ R`). Mental operators (`M`) are explicit agent+estimates recorded with the `mental` subcommand. Analyze before publishing:++```bash+"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \+ --trace "$TRACE" --result "$DIR/result.json" --write+```++This writes `result.json.interactionCost`; `verify ingest-report` stores it on the+run metadata so the report can render a separate interaction-cost section.++### Step 5 โ Structured report (mandatory deliverable)++Every automated test session ends with a structured, evidence-backed report โ not+a chat-only summary. Scaffold it up front and fill it as you test:++```bash+# Pass the acceptance subject up front so every round is grouped correctly.+DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-feature "Verify my feature")+# ... test, saving screenshots / CLI transcripts into $DIR/assets/ ...+# fill $DIR/result.json (scenario, context, plan[], cases[], summary.conclusion) โ the report;+# $DIR/report.md holds only the narrative tail (follow-ups / notes / score)+```++Reports live in `.records/reports/<subject-key>/<timestamp>-<slug>/` (instruct+the project to gitignore `.records/`), grouped by acceptance. The subject+directory contains an `acceptance.json` marker and one subdirectory per+immutable round. Passing `--subject` also pre-fills `result.json.subject`.+Format and evidence rules: [references/report.md](./references/report.md).++#### Fixtures: reusable per-check inputs++When a check needs reusable seed data or replay steps, keep it under+`.records/fixtures/<subject-key>/<check-id>/`: `check.json` stores the plan and+case template; `seed/` stores reusable inputs. Execution outputs such as+screenshots and transcripts remain in the round's `assets/` and must never be+copied back into a fixture.++```bash+F="$SKILL_DIR/scripts/fixture.mjs"+$F init-check --subject topic:tpc_xxx palette-long-list+$F list --subject topic:tpc_xxx+DIR=$($F compose --subject topic:tpc_xxx --slug round4 --title "Full regression" \+ palette-open palette-long-list)+```++Hard rules worth front-loading:++- **Report language = the user's conversation language.** Write `report.md` and+ every human-facing string in `result.json` (case `name`/`observation`,+ `summary.conclusion`, scope `focus`/`entry`) in the language the user is+ conversing in. `result.json` keys/status values stay English.+- **`result.json` is the report; the verify page renders it.** Each tested+ behavior is one entry in `cases[]` (`{ name, result, observation, evidence }`);+ the page builds the scope header from `scenario`+`context`, the check list from+ `plan[]`+`cases[]`, and the verdict from `summary.conclusion`. Do NOT hand-build+ a case table or a scope block in `report.md` โ they double up on the page.+- **Visual evidence lives in `result.json`, NOT in `report.md`.** Attach each+ screenshot/GIF to its case via `cases[].evidence`; the page renders it next to+ the check. Do NOT embed images/GIFs in `report.md`.+- **Final replies lead with the published `/acceptance/<id>` link; the round's+ `/verify/<id>` link may follow as the immutable record. Put no images or local+ file links in the chat reply.** The acceptance page is the stable cross-round+ decision surface; the verify page renders that round's evidence inline. You+ may mention the local report directory as plain text.+- **Time-based behavior needs a GIF, not a screenshot.** Streaming output, a+ ticking timer, loading states, animations โ record with `scripts/record-gif.sh`+ and attach the GIF as that case's evidence; a static screenshot cannot prove it.++### Step 6 โ Publish to the LobeHub verify platform (mandatory)++The local report under `.records/reports/` is the working artifact; the+**deliverable is the report opened on the verify platform**. Do not stop at local+files โ push the session up with the CLI so the user (and later reviewers) can open+it at a stable URL with the evidence rendered inline.++**Publish targets PRODUCTION defaults (`https://app.lobehub.com`), not a local-dev+override profile.** When the product-under-test runs against a local env, the CLI+may be pointed at that local server through override env vars โ those overrides are+for _running_ the test, and they are wrong for _publishing_: a localhost run yields+a URL nobody else can open, and a local env's stub storage makes file-evidence+uploads fail. Publish in a CLEAN environment that strips those overrides so `lh`+falls back to its production defaults and the user's real login. Clear whatever+override vars the project uses; for reference, clearing a local-server override+profile looks like:++```bash+# Strip local-dev CLI overrides so `lh` uses production defaults + the user's real login.+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh verify ingest-report "$DIR" --source agent-testing --open --json+```++Production auth is the user's own device-code login. Verify it first in the same+clean env; if it returns "No authentication found", have the user log in+(`lh login` prints a URL + code), then re-run the publish.++**Check the CLI version before publishing.** The publish flags this step relies on+(`--subject`, `--source agent-testing`) require `lh` >= the version recorded in+this skill's `.skill-meta.json`. The `lh` on PATH in a consumer repo is often+older and fails only at this final step (`unknown option '--subject'`). Run+`lh --version` first; when it is older than the marker version, publish through+`npx @lobehub/cli@latest` instead of the PATH binary.++`verify ingest-report` reads `$DIR` and, in one call, creates a new immutable+verification run, attaches it to the subject acceptance, and uploads everything:++- `result.json.plan[]` โ the frozen check plan, with a business-scenario+ `category` on every item (categories name requirements or features, never+ execution surfaces such as Desktop / CLI / Backend);+- `result.json.cases[]` โ one check result each, paired to its plan item by `id`;+ a planned item with no case renders as **ๆชๆง่ก** instead of silently vanishing;+- each case's `evidence` file(s) โ uploaded and attached to that result;+- `report.md` โ the report body, plus the `summary` stats.++It prints the `verifyRunId`, `acceptanceId`, and their in-app paths. The final+reply leads with `https://app.lobehub.com/acceptance/<acceptanceId>` as the+latest cross-round state; the round-specific+`https://app.lobehub.com/verify/<verifyRunId>` may follow as supporting detail.++#### Every run belongs to a subject acceptance (mandatory)++Every run MUST be chained onto a task, topic, or document **acceptance aggregate**,+so every round lands on one auditable decision page. When the harness runs inside a+LobeHub topic, `ingest-report` automatically uses `LOBEHUB_TOPIC_ID` as+`topic:<id>` โ do not ask the user for it and do not omit the acceptance. Outside a+LobeHub topic, an explicit subject is required and publishing without one fails:++```bash+# SUBJECT is task:$TASK_ID, topic:$TOPIC_ID, or document:$DOC_ID+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh verify ingest-report "$DIR" --source agent-testing --subject "$SUBJECT" \+ --requirement "$REQUIREMENT" --open --json+```++`--subject` accepts `task:<id> | topic:<id> | document:<id>`; `result.json` may+instead use the string form or+`{ "type": "task", "id": "<id>", "requirement": "<goal>" }`.++**Always supply the acceptance requirement on the first ingest.** It is not+generated automatically. Write the one-sentence business goal against which the+whole acceptance is judged, not the current round's narrower scope. A recorded+requirement is immutable; an initially empty value may be backfilled by the first+later round that supplies one.++The first ingest creates the acceptance and every ingest creates its next+immutable round. The user closes the loop on `/acceptance/<acceptanceId>`; the+same state is available through+`lh verify acceptance view|accept|reject <id | type:id>`.++When no subject exists yet (first verification in a repo, no tracked task),+create one with the CLI instead of asking the user for an id โ a dedicated task+is the natural acceptance subject for the run:++```bash+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh task create -n "<project>: <what this run verifies>" -i "<one-line goal>"+# prints: Task created: T-<n> <name> โ the T-<n> identifier works directly:+SUBJECT="task:T-<n>"+```++Tell the user which task was created. Reuse the same subject for every follow-up+round in that repo so all rounds land on one acceptance page.++#### Before a follow-up round: read user feedback++When the subject already has an acceptance, planning starts from its current+state rather than memory:++```bash+env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh verify acceptance view "$SUBJECT" --json+```++- `checks[].userReview.action === "accept"`: user-settled; omit it from the new+ plan and do not re-run it.+- `action === "reject"` with `stale: false`: address its comment and annotations,+ and reuse the exact stable check id so the next result lands on the same row.+- For a semantic replacement, create a new id with `supersedes: ['old-id']`.+ A fresh id without `supersedes` creates an unrelated parallel check.+- Treat `stale: true` feedback as history already consumed by a newer round.++#### Every verification run is an immutable snapshot++One call to `ingest-report` creates one immutable `/verify/<id>` snapshot. Never+overwrite, replace, prune, or re-ingest into an earlier run. A fix followed by+re-verification MUST create another run on the same acceptance, preserving the+earlier plan, results, evidence, and verdict exactly as observed. Use a fresh+report directory for every execution round.++Notes:++- `result.json` cases use `{ id?, name, result, observation?, evidence? }`;+ `evidence` is a path (or array) relative to `$DIR`. `result`/`verdict` map onto+ `passed | failed | uncertain`.+- Finer control is available through the atomic commands โ `verify run create`,+ `verify result ingest`, `verify evidence upload` (`--file` or `--content`),+ `verify report upsert`.+- File evidence uploads through the platform's storage. Against a stub or+ unreachable bucket (common in local dev) the PUT fails; `ingest-report` warns,+ **skips that one artifact**, and still finishes โ so the published session is+ real and openable but **missing the skipped evidence**. Publish against real+ storage (production defaults) if the evidence must appear.++## Phase 3 โ Finish++Close the run cleanly and leave behind only intentional, auditable artifacts.++### Step 7 โ Teardown and handoff (default: stop what you started)++A test run leaves processes and code edits behind. Clean them up by default once+the report is published โ a dev server left listening or an injection left in a+source file silently corrupts the next run (and the next agent's mental model).++- **Stop what you started.** Stop the dev server and any services you started,+ using the stop commands from `PROJECT.md` ยง2. Stop only what THIS run started โ+ never a global process-name kill, and never a listener you didn't launch. If the+ user started their own dev server, leave it.+- **Revert every code injection.** Any fault-injection or debug global you added+ (see [references/probe-mock-patterns.md](./references/probe-mock-patterns.md))+ must be undone and verified: restore the file, then `grep -rn AGENT-TEST` returns+ nothing. Never leave an injection or a debug global behind. Note: when you+ injected into a file that already had uncommitted changes, `git checkout --` is+ the WRONG revert โ it wipes the branch's edits too; snapshot the file first and+ restore from the snapshot (probe-mock-patterns covers this).+- **Keep the report + evidence.** `.records/reports/**` is the deliverable โ do NOT+ delete it in teardown; it is gitignored and the published verify run points at+ it.+- **Check `git status` before reporting the tree clean.** Some dev servers write+ managed files on start; reverting them can make them look like per-start churn.+ Confirm what is dirty rather than assuming.++Skip teardown only when the user explicitly wants the environment left up (e.g.+"leave the dev server running, I'll keep poking at it").++## Directory map++```text+agent-testing/+โโโ SKILL.md # this router+โโโ surfaces/+โ โโโ cli.md # backend verification via the project CLI+โ โโโ web.md # full-stack verification in the browser+โ โโโ electron.md # desktop verification over CDP+โโโ references/ # shared knowledge (generic, read-only in consumers)+โ โโโ plan.md # Phase 1 approval-gate format+โ โโโ report.md # result.json / report.md / evidence spec+โ โโโ agent-browser.md # agent-browser CLI reference+โ โโโ osascript.md # general macOS automation+โ โโโ record-app-screen.md # screen recording+โ โโโ project-adapter.md # PROJECT.md template + first-run bootstrap+โ โโโ common-mistakes.md # GENERIC living log โ read-only, PR upstream+โ โโโ probe-mock-patterns.md # GENERIC living log โ read-only, PR upstream+โโโ scripts/ # generic scripts+```++## Gotchas++- agent-browser: see [references/agent-browser.md](./references/agent-browser.md#gotchas)+- Electron: see [surfaces/electron.md](./surfaces/electron.md#electron-gotchas)+- osascript: see [references/osascript.md](./references/osascript.md#gotchas)diff --git a/apps/cli/skills/agent-testing/references/agent-browser.md b/apps/cli/skills/agent-testing/references/agent-browser.mdnew file mode 100644index 00000000000..3f0f4a3c501--- /dev/null+++ b/apps/cli/skills/agent-testing/references/agent-browser.md@@ -0,0 +1,276 @@+# agent-browser CLI Reference++Generic reference for the `agent-browser` CLI โ automate Chromium-based apps+(Electron, Chrome, web) via Chrome DevTools Protocol. Surface-specific patterns+live in [../surfaces/web.md](../surfaces/web.md) and+[../surfaces/electron.md](../surfaces/electron.md); project auth recipes live in+`.agents/verify/PROJECT.md`.++Install via `npm i -g agent-browser`, `brew install agent-browser`, or+`cargo install agent-browser`. Run `agent-browser install` to download Chrome. Run+`agent-browser upgrade` to update.++## Core Workflow++Every browser automation follows this pattern:++1. **Navigate**: `agent-browser open <url>`+2. **Snapshot**: `agent-browser snapshot -i` (get element refs like `@e1`, `@e2`)+3. **Interact**: Use refs to click, fill, select+4. **Re-snapshot**: After navigation or DOM changes, get fresh refs++```bash+agent-browser open https://example.com/form+agent-browser snapshot -i+# Output: @e1 [input type="email"], @e2 [input type="password"], @e3 [button] "Submit"++agent-browser fill @e1 "[email protected]"+agent-browser fill @e2 "password123"+agent-browser click @e3+agent-browser wait --load networkidle+agent-browser snapshot -i # Check result+```++## GOMS-KLM interaction tracing++When a UI verification should report user-side interaction cost, run+`agent-browser` through the agent-testing wrapper:++```bash+TRACE="$DIR/interaction-trace.jsonl"+SESSION=your-session # from PROJECT.md; $SKILL_DIR = the skill's install dir++"$SKILL_DIR/scripts/agent-browser-klm.mjs" \+ --klm-trace "$TRACE" --klm-phase settings --klm-check case-1 \+ --session "$SESSION" click @e4+```++The wrapper forwards the real command to `agent-browser` and appends one JSONL+event. Physical actions are inferred from the command (`click โ P+K`,+`fill/type โ P+T(n)`, `press โ K`, `wait โ R`). A click only counts the user+activation; if it causes loading or async work, follow it with an explicit+`agent-browser wait ...` so response time is counted as `R`.++Mental effort is intentionally not guessed from DOM shape. After the first+meaningful page view, add an explicit agent estimate:++```bash+"$SKILL_DIR/scripts/agent-browser-klm.mjs" mental \+ --klm-trace "$TRACE" --klm-phase first-view --m 2 --score 3 \+ --confidence 0.75 --reason "Need to understand current page state and choose the verify path"+```++Before publish, summarize the trace into the structured report:++```bash+"$SKILL_DIR/scripts/agent-browser-klm-analyze.mjs" \+ --trace "$TRACE" --result "$DIR/result.json" --write+```++This populates `result.json.interactionCost` with the `goms-klm@lobe-v1` summary.+The raw trace stays in the local report directory for audit/debug.++## Command Chaining++```bash+# Chain open + wait + snapshot in one call+agent-browser open https://example.com && agent-browser wait --load networkidle && agent-browser snapshot -i+```++Use `&&` when you don't need to read intermediate output. Run commands separately+when you need to parse output first (e.g. snapshot to discover refs, then interact).++## Essential Commands++```bash+# Navigation+agent-browser open <url> # Navigate (aliases: goto, navigate)+agent-browser close # Close browser+agent-browser close --all # Close all active sessions++# Snapshot+agent-browser snapshot -i # Interactive elements with refs (recommended)+agent-browser snapshot -s "#selector" # Scope to CSS selector++# Interaction (use @refs from snapshot)+agent-browser click @e1 # Click element+agent-browser click @e1 --new-tab # Click and open in new tab+agent-browser fill @e2 "text" # Clear and type text+agent-browser type @e2 "text" # Type without clearing+agent-browser select @e1 "option" # Select dropdown option+agent-browser check @e1 # Check checkbox+agent-browser press Enter # Press key+agent-browser keyboard type "text" # Type at current focus (no selector)+agent-browser keyboard inserttext "text" # Insert without key events+agent-browser scroll down 500 # Scroll page+agent-browser scroll down 500 --selector "div.content" # Scroll within container++# Get information+agent-browser get text @e1 # Get element text+agent-browser get url # Get current URL+agent-browser get title # Get page title+agent-browser get cdp-url # Get CDP WebSocket URL++# Wait+agent-browser wait @e1 # Wait for element+agent-browser wait --load networkidle # Wait for network idle+agent-browser wait --url "**/page" # Wait for URL pattern+agent-browser wait 2000 # Wait milliseconds+agent-browser wait --text "Welcome" # Wait for text to appear+agent-browser wait --fn "!document.body.innerText.includes('Loading...')" # Wait for text to disappear+agent-browser wait "#spinner" --state hidden # Wait for element to disappear++# Downloads+agent-browser download @e1 ./file.pdf # Click element to trigger download+agent-browser wait --download ./output.zip # Wait for any download to complete++# Network+agent-browser network requests # Inspect tracked requests+agent-browser network requests --type xhr,fetch # Filter by resource type+agent-browser network requests --method POST # Filter by HTTP method+agent-browser network route "**/api/*" --abort # Block matching requests+agent-browser network har start # Start HAR recording+agent-browser network har stop ./capture.har # Stop and save HAR file++# Viewport & Device Emulation+agent-browser set viewport 1920 1080 # Set viewport size (default: 1280x720)+agent-browser set viewport 1920 1080 2 # 2x retina+agent-browser set device "iPhone 14" # Emulate device (viewport + user agent)+agent-browser set offline on|off # Toggle offline (under `set`, not a top-level cmd)++# Capture+agent-browser screenshot # Screenshot to temp dir+agent-browser screenshot --full # Full page screenshot+agent-browser screenshot --annotate # Annotated screenshot with numbered element labels+agent-browser pdf output.pdf # Save as PDF++# Diff (compare page states)+agent-browser diff snapshot # Compare current vs last snapshot+agent-browser diff screenshot --baseline before.png # Visual pixel diff+agent-browser diff url <url1> <url2> # Compare two pages+```++## Batch Execution++```bash+echo '[+ ["open", "https://example.com"],+ ["snapshot", "-i"],+ ["click", "@e1"],+ ["screenshot", "result.png"]+]' | agent-browser batch --json+```++## Authentication++```bash+# Option 1: Auth vault (credentials stored encrypted)+echo "$PASSWORD" | agent-browser auth save myapp --url https://app.example.com/login --username user --password-stdin+agent-browser auth login myapp++# Option 2: Session name (auto-save/restore cookies + localStorage)+agent-browser --session-name myapp open https://app.example.com/login+agent-browser close # State auto-saved+agent-browser --session-name myapp open https://app.example.com/dashboard # Auto-restored++# Option 3: Persistent profile+agent-browser --profile ~/.myapp open https://app.example.com/login++# Option 4: State file+agent-browser state save auth.json+agent-browser state load auth.json+```++For a local dev server where a headed login is awkward, copy the session cookie out+of a **Network request** in your own browser's DevTools and load it via+`state load`. The exact cookie name and origin for the project under test come from+`PROJECT.md` ยง3.++## Semantic Locators (Alternative to Refs)++```bash+agent-browser find text "Sign In" click+agent-browser find label "Email" fill "[email protected]"+agent-browser find role button click --name "Submit"+agent-browser find placeholder "Search" type "query"+agent-browser find testid "submit-btn" click+```++## JavaScript Evaluation (eval)++```bash+# Simple expressions+agent-browser eval 'document.title'++# Complex JS: use --stdin with heredoc (RECOMMENDED)+agent-browser eval --stdin << 'EVALEOF'+JSON.stringify(+ Array.from(document.querySelectorAll("img"))+ .filter(i => !i.alt)+ .map(i => ({ src: i.src.split("/").pop(), width: i.width }))+)+EVALEOF++# Base64 encoding (avoids all shell escaping issues)+agent-browser eval -b "$(echo -n 'document.title' | base64)"+```++## Ref Lifecycle++Refs (`@e1`, `@e2`, etc.) are invalidated when the page changes. Always re-snapshot+after clicking links/buttons that navigate, form submissions, or dynamic content+loading.++## Parallel Sessions++```bash+agent-browser --session site1 open https://site-a.com+agent-browser --session site2 open https://site-b.com+agent-browser session list+```++Each session is a separate daemon socket, so a wedge in one session is scoped to+that session, not the whole tool. Use distinct session names per target when driving+more than one page.++## Connect to Existing Chrome / Electron++```bash+agent-browser --auto-connect snapshot # Auto-discover running Chrome+agent-browser --cdp 9222 snapshot # Explicit CDP port (Electron dev, remote-debugging Chrome)+```++## Gotchas++- **Daemon can get stuck** โ if commands hang, `agent-browser close --all` or+ `pkill -f agent-browser` to reset. A screenshot RPC that is interrupted can leave+ the session's socket half-consumed, after which every later `screenshot` fails+ (`CDP response channel closed` / `Resource temporarily unavailable`) while+ `eval` / `get url` keep working โ reset with `close --all`, or bypass the daemon+ with `scripts/cdp-screenshot.sh` (raw CDP).+- **HMR invalidates everything** โ after code changes, refs break. Re-snapshot or+ restart.+- **`snapshot -i` doesn't find contenteditable** โ use `snapshot -i -C` for rich+ text editors.+- **`fill` doesn't work on contenteditable** โ use `type` for rich-text inputs.+- **Screenshots go to `~/.agent-browser/tmp/screenshots/`** unless you pass a path โ+ a relative path saves to the caller's cwd; pass an absolute path in longer scripts+ so a lost cwd doesn't misplace the file. Read them with the `Read` tool.+- **`network requests` under-reports** โ it is not ground truth for "did the request+ happen". To judge whether a fault landed, wrap `window.fetch` and record each+ request's own outcome (see probe-mock-patterns).+- **`set offline` trips Chrome's own offline interstitial**, not the app's error+ state โ its "Reconnect" copy also false-matches error-copy greps. Use it to break+ connectivity, not to assert an app-level error.+- **`wait --load networkidle` HANGS during a retry loop** (the network never idles)+ and can blow the command timeout โ use a fixed `wait <ms>` when a fetch is stuck+ retrying. (macOS has no `timeout(1)` to bound it.)+- **Dialogs block all commands** โ if commands time out, check+ `agent-browser dialog status`.+- **Default timeout is 25s** โ override with `AGENT_BROWSER_DEFAULT_TIMEOUT` (ms) or+ use explicit waits.+- **Shell quoting corrupts eval** โ use `eval --stdin <<'EVALEOF'` for complex JS.+- **A blank page at `about:blank` with a 1280px viewport usually means the previous+ `open` failed** (exited non-zero without navigating). The session still answers+ every later probe โ against the fresh page it was born with. Read the `open` exit+ code and stderr rather than assuming the page went blank.diff --git a/apps/cli/skills/agent-testing/references/common-mistakes.md b/apps/cli/skills/agent-testing/references/common-mistakes.mdnew file mode 100644index 00000000000..8e395a1e983--- /dev/null+++ b/apps/cli/skills/agent-testing/references/common-mistakes.md@@ -0,0 +1,540 @@+# Common Mistakes (generic layer)++> **This is the GENERIC layer of the living log.** It is read-only in a consumer+> repo and updated only by PR to the CLI repo that ships this skill. Every entry+> here must be **product-independent** โ no project's packages, routes, schemas,+> env vars, service names, or business logic. Project-specific learnings go to+> `.agents/verify/common-mistakes.md` (the writable project layer).+>+> **Mandatory:** read this file in full before every agent-testing run and+> self-check against each case. When the user gives negative feedback that is+> product-independent, genericize it and PR it here; otherwise record it in the+> project layer. Each case: Wrong approach / Why it's wrong / What it breaks /+> Correct approach.++---++## M1 โ Judging `passed` from heuristics instead of looking at the screenshot++**Wrong approach**: after navigating to a surface, deciding "renders fine / passed"+from only `innerText` keyword greps + a skeleton/element count, without ever opening+the screenshot.++**Why it's wrong**: the persistent nav / layout-shell text is always in the DOM, so+an `innerText` grep almost always false-positives. A blank/white page also has 0+skeletons, so `skeletons === 0` cannot tell "rendered successfully" from "rendered+blank".++**What it breaks**: publishes a **false `passed`** โ a blank or watermark-only page+reported as working, hiding a real regression.++**Correct approach**: every screenshot destined for a report `evidence` **must first+be opened with the Read tool and visually confirmed to render the expected content**+before pass/fail. Greps/counts are supporting signals only, never the verdict. A+blank page / watermark / layout-shell-only = fail or uncertain โ go find the root+cause.++---++## M2 โ Goal is verifying error states, but stopping at happy-path because injection is hard++**Wrong approach**: after the first batch of fault-injection methods fails to force+an error, giving up on the error-state screenshots and shipping only happy-path ++unit tests, marking the core goal uncertain/blocked.++**Why it's wrong**: the **entire point** of the task was verifying the error states.+Abandoning that = task not done โ especially when other viable methods exist+unattempted.++**What it breaks**: the deliverable doesn't cover what the user asked for โ a wasted+round that needs redoing.++**Correct approach**: **do not stop until the core goal is met.** When the first+batch of methods fails, immediately switch to the next known-working one โ see+[probe-mock-patterns.md](./probe-mock-patterns.md) for the escalation ladder (code+injection via HMR, CDP `Network.setBlockedURLs`, server-side fault injection). Get+the **real failure-state evidence** before writing the report.++---++## M3 โ Deriving the task from commit messages / branch name instead of the actual ask++**Wrong approach**: on a resumed session with lost prior context, reading the branch+name and top commits and concluding _that_ is the thing to verify โ then building a+whole test run around it โ when the user's real task was a different feature.++**Why it's wrong**: a branch's committed work is not necessarily the current ask.+When context was summarized/lost, the commit history is a _hypothesis_, not the task.+The task lives in the user's words.++**What it breaks**: burns a full test run and clarifying rounds on the wrong feature+before course-correcting.++**Correct approach**: when the user references a task you don't have in context, say+so plainly and RECOVER it before acting โ check `.records/reports/` for prior+sessions on this branch, read the live conversation's own messages (the first user+turn is usually the task), or ask for a pointer. Only translate the ask into+code/commits after it's grounded.++---++## M4 โ Asserting a capture/tooling root cause from plausibility instead of measuring it++**Wrong approach**: when a screenshot came out black or a capture failed, declaring a+root cause from what "sounds right" (missing permission, display sleep, tool bug) and+publishing it โ before running the experiment.++**Why it's wrong**: each of these is falsifiable in seconds and often wrong. A black+frame can be display sleep OR a wedged capture daemon OR a real blank page; guessing+sends the next reader to fix the wrong thing.++**What it breaks**: a published report with a wrong root cause, plus wasted+round-trips retracting each claim.++**Correct approach**: for any capture / permission / timing / "environment" failure,+**reproduce and measure before asserting or publishing** โ pixel brightness for+blackness, the permission bit for TCC, an A/B with the variable toggled to isolate+the cause. State "confirmed by X" vs "suspected", and never ship a root cause a+one-line probe could have checked.++---++## M5 โ Attaching a stale "before" screenshot as a passed case's evidence (unlabeled)++**Wrong approach**: putting BOTH the "after" and a stale "before" screenshot into the+same `cases[].evidence` array, unlabeled. The verify page renders every evidence+image with its filename as a heading, so the user opens the stale shots and concludes+the fix didn't land.++**Why it's wrong**: a passed case's evidence must show the PASSING (after) state. An+unlabeled before-shot next to it reads as "the current result", making a correct fix+look broken. Filenames are not captions.++**What it breaks**: the user reads a green report as a failure, loses trust, and it+takes another round to re-explain.++**Correct approach**: never ship a raw stale/before screenshot as standalone+evidence. When a contrast helps, use the report format's **native comparison+pairing** โ attach both raw screenshots tagged with a shared `comparison` id and the+page renders them under Before / After bands (see+[report.md](./report.md)). **Do NOT hand-compose the two shots into one image** โ the+page owns the labeling. Two more traps: one evidence item per case (don't reuse the+same pair across cases), and a group needs **exactly one `before` and one `after`**+or it silently degrades to unlabeled evidence.++---++## M6 โ Verifying against a stale build, not your working-tree code++**Wrong approach**: driving an already-running app instance to verify a working-tree+change, and eyeballing the first screenshot as "looks changed".++**Why it's wrong**: a resident or packaged app serves a BUILT snapshot โ it does not+reflect uncommitted / HMR src changes. The change under test may not be running at+all, so the screenshot proves nothing about your code.++**What it breaks**: verifying against code that isn't your change โ a false pass (or+false fail) on the wrong bundle entirely.++**Correct approach**: verify working-tree code in an instance that actually loads it+(a dev instance with HMR/live reload), and **prove it's live by MEASURING a+known-changed value** (a computed style, a new string) before trusting any+screenshot. Don't disturb the user's resident instance โ use a separate+instance/port. Remember main-process / server / adapter code often does not+hot-reload; restart the process and prove which code it runs before concluding a+logic bug.++---++## M7 โ Embedding a local-path screenshot in the chat reply++**Wrong approach**: ending the final reply with an inline image embed or link+pointing at the local report dir, believing it will render as a picture in chat.++**Why it's wrong**: the chat UI cannot load a local filesystem path. An image embed+of a local path renders as an empty broken-image box, and a markdown link to a local+path is an un-openable dead link. Local report paths only resolve on the machine,+never inside the message.++**What it breaks**: the reply looks like it has evidence but shows nothing โ the user+gets a broken box and has to go find the verify link anyway.++**Correct approach**: put NO images and NO local-file links in the chat reply. The+published `/verify/<id>` page already renders every screenshot inline โ that URL is+the only visual deliverable. Describe key visual outcomes in prose; mention the local+report dir as a plain string (not a markdown link) if a reference is useful.++---++## M8 โ Asking the user "how should I run this?" instead of defaulting to a full isolated run++**Wrong approach**: when a visual/screenshot request needs a non-trivial environment+(the app must run a specific branch, a fixture must be built, an isolated instance is+needed), stopping to ask the user which approach to take โ full isolated run vs a+lighter shot vs a static prototype.++**Why it's wrong**: environment mechanics are the skill's job to own. Presenting env+difficulty as a menu of shortcuts pushes setup decisions back onto the user and+signals the agent will cut corners on fidelity when the env is inconvenient.++**What it breaks**: wastes a round on a question the user doesn't want.++**Correct approach**: for any "run it and show me" request, default to the **full+isolated run** that ends in a published verify report โ spin up whatever dedicated+instance and fixture data the surface needs (a throwaway repo, an isolated dev+instance, seeded data), capture the real rendered evidence, verify it by opening the+image, and publish. Only surface a plan-approval question when the _product decision_+is ambiguous (what to test), never for _environment mechanics_ (how to render it).++---++## M9 โ Handing the user the sign-in click when the app under test is signed out++**Wrong approach**: an isolated instance came up signed out, so the run stopped and+offered the user a choice: "I click Sign in and you authorize" vs "skip the+screenshot".++**Why it's wrong**: auth is environment mechanics, and the skill owns those end to+end. "Log in once in the app" is addressed to the **agent**, not the user.++**What it breaks**: burns a round on a question the user doesn't want, and stalls a+UI-touching change one click short of its screenshot.++**Correct approach**: drive the sign-in yourself โ click the app's own "Sign in"+entry, follow the OAuth flow in the browser it opens, and get back into the app. Only+escalate when a step genuinely needs something you cannot supply (a 2FA push on their+phone), and then name the exact blocking step instead of offering to drop the+evidence. Corollary: never assume a profile is signed in because it exists โ probe+for a real signed-in state (a cheap authed call) before building a fixture on top of+it; a rendered shell is not proof (a signed-out onboarding screen has text too).++---++## M10 โ Self-judging a screenshot as "too costly" and asking the user to picture the result++**Wrong approach**: after a small user-facing UI change, skipping the rendered+screenshot with "it's a trivial style change; restarting to screenshot costs more+than it's worth โ tell me if you want one." Deciding the cost/benefit for the user and+shipping a diff they had to picture.++**Why it's wrong**: whether a verification artifact is "worth it" is not the agent's+to decide. The measuring stick is _whether the user can conveniently inspect the+product_, not how much effort the agent spends rendering it. Making the user guess the+visual effect from a diff is the actually-expensive outcome.++**What it breaks**: the user can't check the deliverable, loses trust, and has to push+back โ burning a round to get the screenshot that should have been produced up front.++**Correct approach**: for ANY user-facing change (even one line of padding/color),+default to rendering it and attaching the screenshot as a record point โ open the+image to confirm, publish. Never offer the screenshot as an opt-in.++---++## M11 โ Reporting a UI-touching change with only CLI transcripts and no screenshot++**Wrong approach**: when a change includes visible UI (copy, badges, alerts, a+rejection state), treating the run as purely backend/service validation and+publishing only command-output evidence.++**Why it's wrong**: CLI transcripts prove code paths and tests passed, but they do not+let the reviewer inspect the rendered UI. "The diff touches no UI file" does not mean+"no UI surface" โ a permission tightening, for instance, IS a UI-visible state (the+blocked user still sees the affordance and now gets a rejection).++**What it breaks**: the user opens the report expecting visual proof and finds none.++**Correct approach**: if any UI surface changed, include a visual case in the same+run. Drive the real UI and attach a screenshot of the changed/blocked state (and the+success state where relevant), or explicitly mark the UI screenshot case blocked with+the measured environment blocker. Do not present a UI-touching report as complete with+only CLI evidence.++---++## M12 โ Verifying the UI state but not the final effect / payload++**Wrong approach**: marking a "inject context / apply setting / send data" feature+verified because the UI showed the expected chip/badge/state โ without checking the+actual payload or side effect the feature is supposed to produce.++**Why it's wrong**: UI metadata can be saved and displayed while a later+runtime/transport gate drops it before the real effect. The UI looks successful while+the underlying behavior never happened.++**What it breaks**: ships a feature that looks right in the UI but has no effect;+the user must inspect the network/DB to discover it.++**Correct approach**: for any feature that claims to change what the system _does_,+verify the last mile โ assert against the transformed request/payload or the observed+side effect (a network body, a DB row, a downstream call), and treat the UI state as+supporting evidence only.++---++## M13 โ GIF evidence ending on an expected-failure frame reads as "the page failed"++**Wrong approach**: for a loading/streaming case, attaching a GIF that records the+full timeline through to a terminal error state that the test data inevitably+produces. The GIF loops and rests on its final frames, so the viewer opens the report+and sees the error, not the asserted state.++**Why it's wrong**: the LAST frame of a GIF is its de-facto headline. An+expected-failure terminal state without explanation reads as the case failing, even+when the asserted behavior passed.++**What it breaks**: the user reads a passed case as a failure and a round is burned+re-explaining.++**Correct approach**: trim evidence to the asserted state โ end the GIF on the phase+you're asserting (cut frames after the terminal state), or attach a static shot of the+asserted state as primary evidence. If the terminal state is worth showing, say so in+the case's `observation` so the viewer is told before they see it.++---++## M14 โ Verifying only the entry surface when a shared component also renders deeper++**Wrong approach**: after changing a shared UI component, publishing a passing report+from one surface only, even though the same component also renders on other pages.++**Why it's wrong**: shared components are composed with different wrappers, slots, and+responsive containers across surfaces. A fix that looks correct in one place can still+be misplaced elsewhere.++**What it breaks**: the report goes green while a deeper product path still shows the+old or awkward behavior, and the user has to point out the surface that was never+checked.++**Correct approach**: enumerate every product surface where the changed shared UI+renders before publishing, attach separate screenshot evidence for each, and mark any+skipped surface explicitly blocked or untested.++---++## M15 โ Verifying a UI change only in its default state, not its collapsed/overflow state++**Wrong approach**: after changing something inside an action bar / toolbar / list+row, checking only the normal expanded state and publishing, without forcing the+collapsed / auto-collapsed / overflow state.++**Why it's wrong**: bars and rows often have their own overflow behavior and saved+user preference. A change can shrink the available width enough to trigger a collapse,+or a previously saved collapsed preference can hide the exact affordance the change+sits beside.++**What it breaks**: the screenshot looks fine for a fresh profile while real users+with a collapsed toolbar or narrower container see something different.++**Correct approach**: for any UI change inside a bar/row with overflow behavior,+verify both the default and the collapsed/overflow state, with evidence for each.++---++## M16 โ Publishing a component harness when the user asked for full product verification++**Wrong approach**: when the product surface hit friction once, declaring it blocked+and publishing a narrow component harness as the main answer โ even though another+live path (a running dev instance, a sibling worktree) was available.++**Why it's wrong**: a component harness proves a narrow render contract; it does not+prove the full product composition, layout, theming, or that the evidence is+inspectable in the real surface. Environment friction is the skill's job to solve, not+a reason to downgrade before exhausting known-working paths.++**What it breaks**: the user opens a report expecting full product evidence and gets a+partial proof.++**Correct approach**: before marking a product surface blocked, inventory existing dev+instances and running surfaces, measure the target to confirm it renders current code,+and use that path if it does. Keep a harness only as supporting evidence; the primary+UI evidence must come from the product surface, or the report must clearly fail/block+after every known path is measured.++---++## M17 โ Turning a feature verification into an unbounded environment repair++**Wrong approach**: after the normal surface fails to boot, repeatedly modifying+shared dev configuration, reinstalling the whole workspace, and chasing unrelated+dependency problems before running any assertion for the feature under test.++**Why it's wrong**: environment readiness is a gate, not the test goal. A workaround+that changes shared configuration can also make the verification less representative,+while an open-ended repair loop produces no feature evidence.++**What it breaks**: the user waits through a long sequence of setup experiments, the+tree gains unrelated edits, and the run still has no reportable result.++**Correct approach**: follow only recovery paths documented by this skill or the+project adapter. If the failure mode is not covered, stop, revert any experimental+changes, summarize the exact checks and evidence collected, and ask the user before+continuing. Do not repair the environment, switch surfaces, or invent a fallback+without direction.++---++## M18 โ Probing the wrong layer: asserting a fixture landed because the write succeeded++**Wrong approach**: writing a fixture directly to the database, reloading the page, and+reading what the UI shows โ then treating a stale value as a product bug.++**Why it's wrong**: a persisted client cache (SWR / IndexedDB / localStorage) can keep+serving the old value. A successful DB write proves the row changed; it proves nothing+about what the app is _running on_. A fixture bug wearing a product-bug costume is the+most expensive kind.++**What it breaks**: you nearly file your own fixture as a regression.++**Correct approach**: after any direct-DB fixture write, cold-load (clear client+storage/caches, re-seed auth, reopen) and then **assert the fixture in the store+before asserting anything downstream of it**. The DB is where you _wrote_ it; the store+is where the behavior _reads_ it โ verify at the layer the behavior reads. See+[probe-mock-patterns.md](./probe-mock-patterns.md) B.++---++## M19 โ Building an elaborate mock before checking whether the env already has the real thing++**Wrong approach**: needing a capability (a working provider key, a service) and,+finding none in the shell env, building a mock server and seeding it โ then watching+the mock receive **zero** requests while the run produces real output.++**Why it's wrong**: the capability may already exist somewhere the runtime actually+reads (a different config store than the one you checked). Two unmeasured assumptions+stack: that no capability existed, and that you knew where it comes from.++**What it breaks**: a chunk of the run spent building an apparatus the test didn't+need, plus a fixture to tear down. Worse, had the mock _partially_ worked, the run+would have silently verified a fake path.++**Correct approach**: before constructing any mock, **probe the env for the real+capability** โ query the config the runtime reads, or fire one cheap real call and see+whether it completes. Only mock what is provably absent. And when a mock records+nothing while the feature clearly works, that is the signal the mock is _not in the+path_ โ everything "verified" through it is unverified.++---++## M20 โ Bare invocation: narrating skill setup, then asking an open "what should I test?"++**Wrong approach**: invoked with no test target, the agent announces "I'm loading the+mandatory living logs first", reads both logs in full, then asks an open "what should I+verify?" that ignores the visible candidate (the current branch and its commits).++**Why it's wrong**: the living logs inform execution, not target selection โ reading+them before a target exists burns context that may be compacted away before the run.+Narrating internal setup is compliance-reporting the user never asked for. And an open+question pushes work onto the user that observable context could have pre-filled.++**What it breaks**: two user-visible turns whose combined value is one clarifying+question, asked twice.++**Correct approach**: ground the target first (SKILL.md Step 0): the user's words > an+inferred candidate from branch/commits/working tree, confirmed via one structured+question and labeled as a guess (never executed on unconfirmed) > an open question only+as last resort. Read the living logs once the target is known, and never narrate+skill-internal setup.++---++## M21 โ A status badge is not proof the error message rendered++**Wrong approach**: marking an error-state UI case passed because the page showed a+`Failed` badge, while the screenshot did not actually contain the error alert or its+translated message.++**Why it's wrong**: the badge proves only that a failed state reached the page. It does+not prove the error was translated and presented to the user, which is the core+assertion of an error-message verification.++**What it breaks**: a report claims users receive an actionable explanation while its+evidence shows none.++**Correct approach**: for an error-presentation case, visually require all the signals+in the same screenshot: the failed status AND the error alert containing the expected+user-facing message. An unrelated warning or setup reminder does not satisfy the+assertion.++---++## M22 โ Coordinator hand-driving a broken flow instead of re-delegating++**Wrong approach**: after a delegated verification subagent dies mid-case, the+coordinator takes over and drives the remaining flow inline โ dozens of small steps+plus a deep root-cause dig into a flapping shared dependency, all in the main loop.++**Why it's wrong**: the coordinator's per-step latency and context cost are far higher+than a subagent's, and inline grinding turns one recoverable failure into a long+visible stall. Root-causing an env flake is also not the test's goal.++**What it breaks**: the user watches minutes of micro-steps with no case progress;+total wall-clock and token spend balloon for zero extra evidence value.++**Correct approach**: when a delegated case dies, repackage the _remaining_ steps into+a fresh, tightly-scoped subagent prompt (include everything already learned: working+recipes, seeded fixtures, exact remaining assertions). Timebox any environment rabbit+hole to a couple of probes, then switch to a disposable local substitute instead of+diagnosing shared infrastructure.++---++## M23 โ Stopping after a fix without publishing the next verification round++**Wrong approach**: implementing and locally validating a requested iteration, then+ending the task without committing, pushing, or publishing a fresh immutable verify run+to the existing acceptance.++**Why it's wrong**: an acceptance is the cross-round audit trail. A local-only fix+leaves the PR stale and makes the acceptance claim the previous round is still the+latest result. Local tests are preparation, not delivery.++**What it breaks**: reviewers can't inspect the updated code, the acceptance timeline+misses the iteration, and the user has to ask whether anything shipped.++**Correct approach**: after every requested iteration, complete the whole delivery loop+unless told not to: validate the new state, commit and push the branch, create a fresh+report directory, ingest exactly once as the next immutable run on the same subject+acceptance, verify the new round appears, then return both the commit and the+production link.++---++## M24 โ Labeling sequential flow steps as a before/after comparison++**Wrong approach**: attaching two sequential steps of one flow as a `comparison`+pair with `before` and `after` roles.++**Why it is wrong**: comparison rendering means the same surface before and after+a change. Sequential steps are neither a defect nor its remediation.++**Correct approach**: reserve `comparison` for one view in two states. Attach+flow steps as ordinary ordered evidence with a caption naming each step.++---++## M25 โ Publishing locally because the acceptance subject exists only locally++**Wrong approach**: ingesting the primary report into a local instance because+its task or topic is absent from production.++**Why it is wrong**: localhost links disappear with the environment and cannot+serve as shared deliverables. Subject convenience does not change the production+publication requirement.++**Correct approach**: create a production task or topic as the acceptance anchor,+then publish in a clean environment against `app.lobehub.com`. A local ingest may+supplement the run, but never replace the production deliverable.++---++## M26 โ Creating an acceptance without its requirement++**Wrong approach**: using a bare subject string on the first ingest and assuming+the acceptance goal is inferred automatically.++**Why it is wrong**: the requirement is author-supplied. Omitting it leaves the+decision page without the business goal against which all rounds are judged.++**Correct approach**: supply `--requirement` or the object subject form on the+first ingest. State the cross-round business goal, not the current round's scope.diff --git a/apps/cli/skills/agent-testing/references/osascript.md b/apps/cli/skills/agent-testing/references/osascript.mdnew file mode 100644index 00000000000..9d80a426f16--- /dev/null+++ b/apps/cli/skills/agent-testing/references/osascript.md@@ -0,0 +1,202 @@+# osascript Common Patterns++General macOS automation via AppleScript / `osascript` โ activating apps, typing,+pasting, keyboard shortcuts, clicking, screenshots, and accessibility reads. This is+a general macOS-automation asset, not tied to any one app or surface. Use it when a+test needs to drive a native macOS app that is not reachable over CDP.++macOS only. See also [record-app-screen.md](./record-app-screen.md) for capture and+the screen-recording preflight (`scripts/check-screen-recording.sh`) before any+OS-level capture.++## Core Patterns++### Activate an App++```bash+osascript -e 'tell application "AppName" to activate'+```++### Type Text++```bash+# Type character by character (reliable, but slow for long text)+osascript -e 'tell application "System Events" to keystroke "Hello world"'++# Press Enter+osascript -e 'tell application "System Events" to key code 36'++# Press Tab+osascript -e 'tell application "System Events" to key code 48'++# Press Escape+osascript -e 'tell application "System Events" to key code 53'+```++### Paste from Clipboard (fast, for long text)++```bash+# Set clipboard and paste โ much faster than keystroke for long messages+osascript -e 'set the clipboard to "Your long message here"'+osascript -e 'tell application "System Events" to keystroke "v" using command down'+```++Or in one shot:++```bash+osascript -e '+set the clipboard to "Your long message here"+tell application "System Events" to keystroke "v" using command down+'+```++### Keyboard Shortcuts++```bash+osascript -e 'tell application "System Events" to keystroke "k" using command down' # Cmd+K+osascript -e 'tell application "System Events" to keystroke "f" using command down' # Cmd+F+osascript -e 'tell application "System Events" to keystroke "n" using command down' # Cmd+N+osascript -e 'tell application "System Events" to keystroke "k" using {command down, shift down}' # multi-modifier+```++### Click at Position++```bash+osascript -e '+tell application "System Events"+ click at {500, 300}+end tell+'+```++### Get Window Info++```bash+osascript -e '+tell application "System Events"+ tell process "AppName"+ get {position, size} of window 1+ end tell+end tell+'+```++### Screenshot++```bash+screencapture /tmp/screenshot.png # Full screen+screencapture -i /tmp/screenshot.png # Interactive region select+screencapture -l "$WINDOW_ID" /tmp/shot.png # Specific window (id from CGWindowList)+```++To get the window id for a specific app:++```bash+osascript -e '+tell application "System Events"+ tell process "AppName"+ get id of window 1+ end tell+end tell+'+```++### Read Accessibility Elements++```bash+# Get all UI elements of the frontmost window (can be slow/large)+osascript -e '+tell application "System Events"+ tell process "AppName"+ entire contents of window 1+ end tell+end tell+'++# Get a specific element's value+osascript -e '+tell application "System Events"+ tell process "AppName"+ get value of text field 1 of window 1+ end tell+end tell+'+```++> **Warning:** `entire contents` can be extremely slow on complex UIs. Prefer+> screenshots + the `Read` tool for visual verification.++### Read Screen Text via Clipboard++```bash+osascript -e '+tell application "System Events"+ keystroke "a" using command down+ keystroke "c" using command down+end tell+'+sleep 0.5+pbpaste+```++## General App-Automation Workflow++```bash+APP_NAME="AppName"+TARGET="some-target"+MESSAGE="Hello!"+WAIT_SECONDS=10++# 1. Activate+osascript -e "tell application \"$APP_NAME\" to activate"+sleep 1++# 2. Navigate (via the app's own quick switcher / search shortcut)+osascript -e 'tell application "System Events" to keystroke "k" using command down'+sleep 0.5+osascript -e "tell application \"System Events\" to keystroke \"$TARGET\""+sleep 1+osascript -e 'tell application "System Events" to key code 36'+sleep 2++# 3. Input (clipboard paste for long/non-ASCII text)+osascript -e "set the clipboard to \"$MESSAGE\""+osascript -e '+tell application "System Events"+ keystroke "v" using command down+ delay 0.3+ key code 36+end tell+'++# 4. Wait for the app to react+sleep "$WAIT_SECONDS"++# 5. Screenshot for verification+screencapture /tmp/app-test.png+```++### Tips++- **Use clipboard paste** (`Cmd+V`) for messages with special characters or long+ text โ `keystroke` can mangle non-ASCII.+- **Add `delay`** between actions โ apps need time to process UI events.+- **Screenshot for verification** โ `screencapture` + the `Read` tool.+- **Accessibility permission required** โ System Events automation requires+ Accessibility access for the driving app (Terminal / iTerm / the agent host) in+ System Settings > Privacy & Security > Accessibility.++## Gotchas++- **Accessibility permission required** โ first run prompts for access; grant it in+ System Settings > Privacy & Security > Accessibility.+- **`keystroke` is slow for long text** โ use clipboard paste (`Cmd+V`) for anything+ over \~20 characters.+- **`keystroke` can mangle non-ASCII** โ use clipboard paste for CJK, emoji, or+ special characters.+- **`key code 36` is Enter** โ hardware key code, works regardless of keyboard+ layout.+- **`entire contents` is extremely slow** โ avoid for complex UIs; use screenshots.+- **OS screenshots go BLACK when the display is asleep/locked/screensaver** โ gate+ with `scripts/check-screen-recording.sh` and keep the display awake with+ `caffeinate -dimsu &` for the whole capture run.diff --git a/apps/cli/skills/agent-testing/references/plan.md b/apps/cli/skills/agent-testing/references/plan.mdnew file mode 100644index 00000000000..5e268238bf4--- /dev/null+++ b/apps/cli/skills/agent-testing/references/plan.md@@ -0,0 +1,107 @@+# Phase 1 Plan Feedback++Use this template at the end of Phase 1. Match the user's conversation language.+Keep it concrete and compact: report observed state, not generic readiness claims.++## Readiness verdicts++- **โ Ready**: every prerequisite for the proposed run is verified.+- **โ ๏ธ Ready with warnings**: execution can proceed; list non-blocking limitations+ and their effect on evidence or scope.+- **โ Blocked**: execution cannot start until one or more prerequisites are+ resolved.+- **โณ Pending**: an agent-owned check is actively being resolved and has not+ reached a final readiness verdict yet.++Always prefix the overall verdict and every Status cell with its emoji marker:+`โ Ready`, `โ ๏ธ Warning`, `โ Blocked`, or `โณ Pending`. Do not use color words or+bare status text without the marker; the table must remain scannable in clients+that do not render semantic colors.++Fix safe environment mechanics yourself before reporting. Separate remaining items+by owner:++- **Agent-owned**: dependencies, processes, ports, generated local env, seeded+ fixtures, navigation, retries, and other work possible within the task's scope.+- **User-owned**: secrets the user must supply, device/2FA approval, permissions+ only the user can grant, destructive authorization, or an unresolved product+ choice that materially changes the plan.++Never put an agent-owned item under "Needed from you." If none remain, write `None`+explicitly.++## Template++```markdown+Verification plan โ Environment: <โ Ready | โ ๏ธ Ready with warnings | โ Blocked>++Environment++| Check | Status | Observed state |+| ------------------ | ------------------------------------------- | --------------------------------------------------- |+| Workspace / branch | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <path, branch/worktree, relevant dirty-state note> |+| Dependencies | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <root and selected standalone app status> |+| Runtime / ports | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <resolved URLs/ports and ownership or availability> |+| Required services | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <DB, cache, queue, dev serverโonly those in scope> |+| Auth | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <selected surface and verified signed-in state> |+| Evidence capture | <โ Ready/โ ๏ธ Warning/โ Blocked/โณ Pending> | <CDP or OS capture readiness> |++Execution plan++1. <Surface and entry point>+2. <Case 1: behavior โ expected result โ evidence>+3. <Case 2: behavior โ expected result โ evidence>+4. <Report and publication deliverable>++Scope and assumptions++- In scope: <what this run proves>+- Out of scope: <intentional exclusions, or None>+- Assumptions / warnings: <items that may affect interpretation, or None>++Needed before execution++- Agent will resolve: <remaining non-blocking or in-progress agent-owned work, or None>+- Needed from you: <exact user-owned prerequisite and why it is required, or None>+```++Do not include irrelevant environment rows. Add a row when the run has another hard+prerequisite, such as a native app, gateway, fixture repository, or specific+external account.++When a check refines or replaces a requirement from an earlier Acceptance round,+keep the old stable id if it is the same assertion. If the semantic assertion needs+a new id, declare the replacement explicitly with `supersedes: ['old-check-id']`;+title similarity is never a merge signal. For every user-visible UI case, plan a+dedicated screenshot or recording for that exact claim โ program output may+supplement it but cannot replace visual evidence.++On a follow-up round, seed the plan from+`lh verify acceptance view <subject> --json` before writing any case:++- Accepted checks are user-settled; omit them from the new plan.+- Rejected, non-stale checks are the primary repair items. Carry their comments+ and annotations into the expected outcome, and reuse their exact stable ids.+- Plan all remaining checks from their current state, again reusing stable ids.+ A semantic replacement requires a new id plus `supersedes: ['old-id']`.++## Confirmation behavior++After the feedback, use the runtime structured question tool+(`request_user_input` / ask-user-question equivalent). Do not bury the question+inside the template text.++When the verdict is **Ready** or **Ready with warnings**, use:++1. `Start (Recommended)` โ approve the displayed environment and plan; enter Execute.+2. `Discuss first` โ revise scope, cases, assumptions, or environment handling.++When the verdict is **Blocked**, do not offer Start. Use:++1. `I'll provide it (Recommended)` โ the user will supply or complete the listed+ user-owned prerequisite.+2. `Revise the plan` โ change the scope or approach to remove the blocker.++Match button labels to the user's language. Wait for the user's response. If the+user resolves a blocker, re-check the affected environment item and present an+updated gate; do not rely only on the user's statement that it is fixed.diff --git a/apps/cli/skills/agent-testing/references/probe-mock-patterns.md b/apps/cli/skills/agent-testing/references/probe-mock-patterns.mdnew file mode 100644index 00000000000..67c1d716348--- /dev/null+++ b/apps/cli/skills/agent-testing/references/probe-mock-patterns.md@@ -0,0 +1,372 @@+# Probe / Mock Pattern Library (generic layer)++> **This is the GENERIC layer of the living log.** It is read-only in a consumer+> repo and updated only by PR to the CLI repo that ships this skill. Every recipe+> here must be **product-independent** โ framework-level or tool-level, no project's+> stores, routes, tables, env vars, or file paths. Project-specific probes and mocks+> go to `.agents/verify/probe-mock-patterns.md` (the writable project layer).+>+> **Read this before any run that must force an error state or inspect runtime+> state.** Each item: Situation / Doesn't work / Works.+>+> **Separate the observation from the explanation.** When you add an item, cite the+> exact mechanism (a `file:line`, a measured A/B) โ and if you only saw a symptom,+> write "cause not established" instead of guessing. A wrong mechanism is worse than+> none: it sends the next reader to fix the wrong thing.++---++## A. Forcing a fetch to FAIL (error-state testing)++### A1. Judge interception by the fetch's own outcome, not by the UI or the promise++- Apps commonly **swallow** a failed fetch: a store action can resolve successfully+ even when its underlying request was aborted, so the UI and the action's promise+ both "look like" a 200. Never judge whether your fault landed by the action or the+ UI.+- **Works**: wrap `window.fetch` post-load and record each request's own resolve /+ reject. Use a guard so a second `eval` doesn't wrap the wrapper (stack overflow):+ ```js+ if (!window.__W) {+ window.__W = 1;+ window.__R = [];+ const of = window.fetch;+ window.fetch = function (...a) {+ const p = of.apply(this, a);+ if (String(a[0]).includes('<url-fragment>'))+ p.then(+ (r) => window.__R.push('resolved_' + r.status),+ (e) => window.__R.push('REJECTED_' + e.message),+ );+ return p;+ };+ }+ ```+- **`agent-browser network route --abort` glob matching is finicky.** A bare `**/x`+ or `*/path/*` can match nothing on a nested path; an absolute-URL prefix with a+ trailing `*` matches reliably (the trailing `*` also covers a `?query` string). And+ `agent-browser network requests` **under-reports** โ it is not ground truth for+ "did the request happen"; trust the `window.fetch` wrapper instead.++### A2. `set offline` shows the browser's page, not the component error++- `agent-browser set offline on` trips Chrome's document-level offline interstitial+ ("Reconnect to Wi-Fi"), not the app's own error component. Its copy (and the dino+ game) also false-matches naive error-copy greps, and offline breaks lazy+ route-chunk loading โ a hard-nav fallback to the browser page. Use it to break+ connectivity, not to assert an app-level error state.++### A3. WORKS โ force an error by injecting a throw into the code path via HMR++- Add a throw at the top of the client method the data fetcher / mutation calls, let+ the dev server hot-apply it, capture, then revert:+ ```ts+ // <the service method the fetcher calls> โ [AGENT-TEST] REMOVE+ list = async (params) => {+ if (true) throw Object.assign(new Error('injected'), { data: { httpStatus: 500 } });+ return realClient.list(params);+ };+ ```+- Use a status the UI treats as **retryable** (commonly anything but 401/403) if you+ want the Retry affordance visible; a non-retryable status suppresses it. The same+ technique works on the **write side** โ inject into the mutation method to exercise+ a failed-save state.+- **Revert carefully.** `git checkout -- <file>` on a service file often triggers a+ FULL reload (not just HMR), resetting the SPA to a blank shell โ after reverting,+ re-navigate and re-fetch element refs. And see A5: `git checkout --` is the WRONG+ revert when the file already had uncommitted changes.++### A4. WORKS โ alternatives when HMR injection isn't available++- **CDP `Network.setBlockedURLs`** โ blocks at the network stack (below `fetch`, so+ it catches requests a page-realm `fetch` override might miss). Needs a raw CDP ws+ connection.+- **Server-side** โ temporarily make the one endpoint return 500.++### A5. `git checkout -- <file>` to revert an injection DESTROYS the branch's uncommitted changes in that file++- When you inject a probe into a file that the branch has **already modified+ (uncommitted)** โ the common case for a pre-PR review โ `git checkout -- <file>`+ resets it to HEAD, silently wiping the very feature edits you were sent to verify,+ not just your probe. Nothing warns you: the residue check (`grep -rn AGENT-TEST`)+ comes back clean either way, because your marker is gone too.+- **Works โ snapshot the file yourself before injecting, restore from the snapshot:**+ ```bash+ cp <file> /tmp/probe-backup-$(basename <file>) # BEFORE the edit+ # ... inject, HMR, capture ...+ cp /tmp/probe-backup-$(basename <file>) <file> # restore โ preserves uncommitted work+ ```+ Then prove the restore is exact (`git diff -- <file>` shows the same working-tree+ blob as before) and `grep -rn AGENT-TEST` is empty. Check `git status --short`+ before you start so you know which files are dirty; for a dirty file, `git checkout --` is never the revert. `git stash` has the same failure shape.++### A6. WORKS โ before/after visual diffing by checking out the OLD file, gated on a measured version signal++- The clean way to produce a real "before" render is to write the pre-change version+ into the working tree (`git show <base>:<path> > <path>`), capture, then restore โ+ **not** to trust that HMR applied the swap. HMR can silently fail to apply the+ second swap: the file on disk is old while the renderer keeps the new styles, and+ the screenshot is the AFTER state mislabeled BEFORE (an M5 failure no screenshot+ review catches).+- **Works โ gate every capture on a measured version signal, not a sleep.** Pick a+ property that differs between the two versions and read it back with+ `getComputedStyle` before shooting; if it's not the expected value, force a full+ reload and re-enter the surface. A full reload resets SPA state, so budget for+ re-establishing any fixture.+- **Corollary โ a layout change may be invisible at the default size.** A+ right-alignment / `flex` fix can render identically to the broken version in a+ narrow container (content already fills the row); drive the app's own resize+ affordance with real mouse events before concluding "no visual change".++---++## B. Cache / stale state that MASKS the failure++### B1. A failed revalidation cannot show an error once the data has settled++- A surface that loaded successfully once caches the last-good value. On a later+ failed fetch, a well-behaved error boundary keeps the settled content and does NOT+ show the error (by design: a background error must not blow away loaded content). So+ your injected failure shows the old content, not the error.+- **Works**: to see a genuine FIRST-LOAD error, clear all client storage, then+ cold-load. Clearing usually logs you out โ re-seed auth after.+ ```js+ (async () => {+ try {+ localStorage.clear();+ sessionStorage.clear();+ } catch {}+ try {+ const d = await indexedDB.databases();+ await Promise.all(+ (d || []).map(+ (x) =>+ new Promise((r) => {+ const q = indexedDB.deleteDatabase(x.name);+ q.onsuccess = q.onerror = q.onblocked = () => r();+ }),+ ),+ );+ } catch {}+ try {+ const k = await caches.keys();+ await Promise.all(k.map((c) => caches.delete(c)));+ } catch {}+ return 1;+ })();+ ```+ then re-seed auth, then `open about:blank` โ `open <target>`.++### B2. SWR-style clients retry for \~30s before the error settles++- A data client with retry/backoff keeps `isLoading` true during retries, so you+ screenshot a skeleton, not the error. A typical config (5 attempts, exponential+ backoff capped at 30s) settles the error only after \~30s.+- **Works**: wait \~35s after load for retries to exhaust, THEN screenshot. (Or disable+ retries for the probe โ but that can also hide the Retry button, since many clients+ mark a non-retrying error as non-retryable.)++### B3. In-memory cache survives `open`; persisted cache survives everything++- `open about:blank` then `open <target>` forces a fresh JS context (clears in-memory+ cache) but does NOT clear persisted storage โ you still need B1 for a true cold+ load. Verify a marker set via `eval` (not from the page's own script, which re-runs+ on the second `open` and re-creates it, reading as "context preserved"). Persisted+ caches commonly live in **two tiers** โ IndexedDB for big collections and+ localStorage for small shells โ which is why B1 clears both plus the Cache API.++### B4. Component-local state seeded from a cached item does NOT reset when fresh data arrives++- A row component that initializes local state from its item (`useState(() =>+derive(item))`) captures the value at first render. When a persisted cache hydrates+ the list with a stale item first, `useState` captures the stale value; when the+ fresh server response replaces the data, the row does not remount (same React key),+ so the stale local state sticks. No amount of waiting fixes it.+- **Works**: for any assertion on an initial-render flag that flows through+ `useState(init)`, force a clean first frame by clearing only the persisted-cache+ tier and reloading (login usually survives if you don't touch the session cookie),+ and verify the underlying data separately so a stale render is attributed to cache,+ not to the change under test.++---++## C. Probing app / runtime state++### C1. WORKS โ read live component state with a temporary debug global++- The decisive way to read a component's live props / store / fetched values: add a+ debug global in the render, reload, read it, remove it.+ ```tsx+ // inside the component render, temporary โ [AGENT-TEST] REMOVE+ if (typeof window !== 'undefined')+ (window as any).__DBG = { data: /* ... */, hasError: !!error, isLoading };+ ```+ ```bash+ agent-browser --session $S eval 'JSON.stringify(window.__DBG)'+ ```+ This surfaces cases where the data looks settled even on error โ a discrepancy a+ screenshot can't show.++### C2. `agent-browser console` capture works โ use it for what console is for++- Console capture is reliable on current agent-browser (a page-script `[log]` and one+ emitted later from `eval` both appear). An empty console means the page logged+ nothing, not that capture is broken. The debug-global (C1) is still the better tool+ for reading structured component state; use console for what console is for.++### C3. `document.body.innerText` keyword grep false-positives on fixture text++- Asserting a state via `body.innerText.includes('<phrase>')` matches your own fixture+ content if it happens to contain that substring (e.g. a fixture literally named+ "โฆfailureโฆ" when you assert on "failure") โ a false pass on a state that never+ rendered.+- **Works**: scope the check to the actual UI element (`querySelectorAll` on the+ specific tag/toast/alert), never `body.innerText`. And pick fixture names that do+ NOT contain any state keyword you'll assert on.++### C4. `innerText` can be 0 on a rendered page โ use it to tell a wedge from a blank++- On some app shells `document.body.innerText` reads `""` even on a fully rendered+ page (some ancestor collapses the layout-dependent computation); probe a more+ specific container (e.g. the app root element) instead.+- **Diagnostic**: `innerText` needs layout, `textContent` does not. When the root+ gives `innerText === 0` but `textContent > 0`, the DOM is fine and the RENDERER is+ not painting (a compositor wedge โ see D9). When both are 0, the DOM is genuinely+ empty. This distinction tells a non-painting renderer from a blank page.++### C5. A successful ingest does not prove acceptance attachment when the CLI is stale++- A globally installed CLI may accept `ingest-report` and return a run id while+ lacking newer subject/acceptance behavior. The result is an orphan round even+ though the command appears successful.+- Compare `lh --version` with the skill marker before publishing. If the branch+ under test changes the CLI contract, run that branch's CLI; otherwise use+ `npx @lobehub/cli@latest`. Confirm the returned acceptance id or inspect the+ acceptance page rather than treating a run id alone as proof.++---++## D. agent-browser / CDP mechanics++- **D1. `screenshot` honours a relative path โ but still pass an absolute one.** A+ relative path saves to the caller's cwd; the cwd of a step in a longer script is+ easy to lose track of, so an absolute path is the right habit.+- **D2. The CDP port can be ephemeral.** A browser launched with+ `--remote-debugging-port=0` picks a random port; read `DevToolsActivePort` in the+ user-data-dir, or use `agent-browser get cdp-url` (note: `cdp-url` is a `get`+ subject, not a top-level command). Electron dev instances usually pin a known port+ (e.g. 9222) โ the project adapter says which.+- **D3. `wait --load networkidle` HANGS during a retry loop** (the network never+ idles) and can blow the command timeout โ use a fixed `wait <ms>` when a fetch is+ stuck retrying. (macOS has no `timeout(1)` to bound it.)+- **D4. Portal toasts auto-dismiss (\~5s) and `snapshot -i` may miss their buttons.** A+ base-ui / portal-rendered toast lives outside the main tree and can be occluded by a+ dev overlay; `snapshot -i` does not reliably surface its action buttons. Read the+ toast via an `eval` DOM query, and because it dismisses in \~5s, re-trigger it+ immediately before the screenshot/query (or fire its button via `.click()` in the+ same `eval`) rather than relying on a timed hover-then-observe.+- **D5. `agent-browser screenshot` can WEDGE the session; `eval`/`get` still work.**+ Each session is one daemon socket, so a wedge is scoped to that session. An+ interrupted screenshot RPC (a killed command, a bad flag, `--full` on a giant page)+ can leave the socket half-consumed, after which every later `screenshot` fails+ (`Resource temporarily unavailable` / `CDP response channel closed`) while+ `eval`/`get url` keep working โ **not** a display-sleep or permission issue. Reset+ with `agent-browser close --all`, or skip the daemon entirely (D6).+- **D6. WORKS โ raw-CDP screenshot bypasses the daemon.** `scripts/cdp-screenshot.sh [--port <n>] [--out x.png] [--full] [--check]` opens its own ws to the target, does+ one `Page.captureScreenshot`, and closes (\~60ms). Immune to the D5 wedge and+ **robust when the display is asleep or the window is minimized/occluded** (the+ engine forces a compositor frame). Use it for Electron evidence and as a preflight+ (`--check` โ exit 0 iff a real, non-black frame was captured).+- **D7. OS `screencapture` is BLACK when the display is asleep/locked/screensaver.**+ Distinct from D5/D6: `screencapture` (and `capture-app-window.sh`, osascript grabs)+ captures the physical framebuffer, so an idle-slept display โ a uniformly black PNG+ (mean/max = 0). Permission can be fine. Gate with `scripts/check-screen-recording.sh`+ (checks the permission bit + a real-frame blackness probe) and keep the display+ awake for the whole run: `caffeinate -dimsu &`. CDP capture (D6) does not have this+ problem.+- **D8. The daemon serializes commands โ `open` queues behind a screenshot loop.**+ While a recording loop (`record-gif.sh`) is running, `agent-browser open <url>`+ lands late/out of order, and your "during navigation" screenshot can show the+ PREVIOUS page (which may look identical to the expected end state โ a false read).+ **Works**: during any recording loop, navigate with+ `agent-browser eval 'location.href="<url>"'` (fire-and-forget) instead of `open`.+- **D9. A mid-session bundler dependency re-optimize can wedge the renderer+ compositor.** Symptom: capture returns black, the app root's `innerText` is 0 while+ `textContent` still holds the full DOM (C4), and `visibilityState` is `visible` with+ real dimensions โ not display sleep or permission (D6/D7 would survive both). It+ often follows a "re-optimizing dependencies" / "failed to fetch dynamically imported+ module" log line. **Works**: restart the dev instance; `location.reload()` alone may+ not clear it.+- **D10. Virtualized lists: driving `scrollTop` by hand blanks the pane โ use a small+ fixture.** A virtualizer unmounts nodes as you scroll past (a `TreeWalker` search+ then "loses" a node that was there a second ago), and forcing `scrollTop` far+ outside the rendered window can make the scroll container itself disappear โ reading+ exactly like a render bug. **Works**: pick a fixture small enough that the target is+ on the first screen; far cheaper and more reliable than fighting the virtualizer.+- **D11. React controlled inputs ignore synthetic events โ use `agent-browser click`+ (trusted CDP input).** `el.click()` and even a full synthetic+ `pointerdown/mousedown/pointerup/click` sequence are `isTrusted: false`, so a+ React-controlled checkbox/toggle never updates its state. **Works**: `snapshot -i`+ for the ref, then `agent-browser click <ref>` โ it goes through CDP+ `Input.dispatchMouseEvent`, which the page sees as a real user click. The snapshot+ also reveals when a control is `[disabled]` (the app deliberately refusing), which a+ coordinate-click never would.+- **D12. Disambiguate elements by geometry or an identifying attribute โ don't+ singular-select.** A page can render a hidden zero-size duplicate of a subtree+ (e.g. an offscreen measurement copy) at `(0,0)`, first in DOM order, so a singular+ `querySelector` grabs the phantom: a `fill` reports success while the visible box+ stays empty, a click on the phantom button is a silent no-op, and an `innerText`/aria+ grep "finds" a control the user can't see. **Works**: enumerate and filter by a+ non-zero `getBoundingClientRect()`, or target by the component's own `aria-label`;+ tag the resolved element with a `data-probe` attribute and drive it with+ `agent-browser click '[data-probe=...]'`.+- **D13. A blank page at `about:blank` with a 1280px viewport usually means the+ previous `open` failed** (exited non-zero without navigating โ e.g. an unrecognized+ global flag). The session still exists and answers every later probe โ against the+ fresh page it was born with, at the default viewport. Read the `open` exit code and+ stderr to learn _why_ rather than assuming the page went blank; treat the+ fingerprint as "the navigation failed".++---++## E. Environment / shell gotchas++- **E1. Not every layer hot-reloads โ restart and prove which code the process runs.**+ A dev server's HMR typically covers the renderer/client only. Server code,+ main-process code, and adapters that run out-of-process are often NOT recompiled on+ edit, so reloading the client verifies nothing โ the old code is still running, and+ the failure looks exactly like a logic bug in your own diff. **Works**: after an+ edit to a non-client layer, restart before drawing a conclusion, and prove the+ process has your code before debugging it โ e.g. curl the dev bundler for the source+ and grep for a marker (renderer), or grep the built bundle for the marker (server /+ main).+- **E2. The shell's `grep` may honor `.gitignore` โ "not found anywhere" can be a+ false negative.** Some environments alias `grep` to a wrapper (e.g. `ugrep --ignore-files`) that skips `.gitignore`d paths, silently omitting `node_modules`.+ Before asserting "X exists nowhere", name the ignored directory explicitly+ (`grep -rl X node_modules`) or call `/usr/bin/grep` directly.+- **E3. In zsh, a loop variable named `path` overwrites the command search path.** zsh+ ties `path` to `PATH` as a special array; assigning it (e.g. parsing a cookie jar's+ path field) replaces the process command search path, and the next executable fails+ with `command not found`. Name the field something else (`cookie_path`); this is a+ shell failure, not an auth/browser failure. (Similarly, `zsh does NOT word-split+unquoted vars` โ stashing `S="--session x --cdp 9226"` then `agent-browser $S`+ fails; inline the flags or use an array.)+- **E4. A curl "502" from a local port with nothing listening can be a shell proxy+ env.** If `HTTP_PROXY`/`HTTPS_PROXY` are set and `NO_PROXY` does not exempt+ localhost, a dead local host is forced through the proxy and returns the proxy's+ 502 โ a "server up but broken" mirage. `curl --noproxy '*'` is a harmless+ belt-and-braces habit; if you actually see a 502 from a local port, check `NO_PROXY`+ before believing the server is up.+- **E5. Dev servers can write managed files on start โ check `git status` before+ reporting the tree clean.** Some frameworks append a managed block to a repo file on+ `dev` start (once, idempotently). Reverting it at teardown makes it look like+ per-start churn and causes it to be re-appended on the next start. Commit the block+ or opt out per the framework, and always check `git status` before claiming a clean+ tree.+- **E6. Persistent resource exhaustion (e.g. Vite `EMFILE: too many open files`) is a+ stop-and-ask, not a workaround.** If a surface exits at startup with a+ file-watcher/resource-exhaustion error while the port is free, the likely cause is+ other running watchers (extra worktrees, surviving terminals, an editor window) that+ you must not kill. Terminate the run, report the exact error, and ask the user to+ clean up other processes โ do not change watch mode, fall back to a static build, or+ publish a report from a degraded surface.diff --git a/apps/cli/skills/agent-testing/references/project-adapter.md b/apps/cli/skills/agent-testing/references/project-adapter.mdnew file mode 100644index 00000000000..267a180c6d9--- /dev/null+++ b/apps/cli/skills/agent-testing/references/project-adapter.md@@ -0,0 +1,162 @@+# Project Adapter (`.agents/verify/PROJECT.md`)++This skill is project-agnostic. Everything specific to the project under test โ how+to start and stop it, which ports and services it needs, how auth works, which+surfaces it has, and how to jump straight into app state โ lives in a per-project+adapter at `.agents/verify/PROJECT.md`. The skill reads it; it never guesses the+project's commands.++## Where the adapter lives++```text+<repo>/.agents/verify/ # committed โ the adapter and project logs are team assets+โโโ PROJECT.md # the adapter (this contract)+โโโ common-mistakes.md # PROJECT-layer living log (writable)+โโโ probe-mock-patterns.md # PROJECT-layer living log (writable)+โโโ scripts/ # optional: project env / probe scripts+```++`.agents/verify/` is **committed** (the adapter and the project living logs are+shared, versioned team assets). The report output directory `.records/` is+**gitignored** โ reports are per-run artifacts, published to the verify platform,+not committed.++## Fixed section skeleton++`PROJECT.md` always has these six sections, in this order. Sections the skill refers+to by number (`PROJECT.md ยง2`, `ยง3`, โฆ), so keep the numbering.++1. **Project summary** โ what the product is, and the repo layout relevant to+ testing (which package holds the server, the web app, the desktop shell, the+ CLI).+2. **Environment** โ how to start and stop the dev environment; the required+ services (database, cache, queue, object store) and how to start each; how to+ detect "already running" so a run does not clobber a user's server; how env and+ ports are resolved (the project's own env-resolver command, if any) so the skill+ never hard-codes a port table.+3. **Auth** โ test accounts, seeding commands, and a per-surface status check (one+ command per surface that answers "am I signed in on this surface?").+4. **Surfaces** โ which of CLI / Web / Electron apply, and for each that applies:+ launch command, base URL / port, agent-browser session name (web/electron), and+ which probe scripts drive it.+5. **Project probes & quick navigation** โ the fast paths into app state: an auth+ probe, a current-route probe, a running-operations probe, and a `goto <route>`+ quick-navigation, plus the routes worth jumping to. These are the project's+ equivalent of a state-introspection helper; the skill uses them instead of+ hand-rolling store-eval snippets.+6. **Known constraints** โ anything the generic gates must know before running:+ services that are hard prerequisites for a code path (e.g. "agent runs require+ the queue service up"), standalone sub-packages that need their own install,+ surfaces that only work on macOS, or any repo-specific gotcha a run must respect.++`PROJECT.md` may reference project scripts under `.agents/verify/scripts/` or+anywhere in the repo.++## Copy-pasteable template++```markdown+# PROJECT.md โ agent-testing adapter for <project name>++## 1. Project summary++<One paragraph: what the product is. Then the repo layout that matters for testing โ+which directory/package is the server, the web app, the desktop shell, the CLI.>++## 2. Environment++- **Start dev server:** `<command>` (base URL: `<url>`, port: `<port>`)+- **Stop dev server:** `<command>` (must stop only what this run started)+- **Required services:** <db / cache / queue / object store โ with the start command+ for each, or "none">+- **Already-running detection:** `<health-check command>` โ how to tell the server is+ up before starting another one.+- **Env / port resolution:** `<command or file>` โ the source of truth for ports and+ URLs. Do NOT hard-code a port table; read it here.++## 3. Auth++- **Test account(s):** <how to obtain โ seeded, fixture, or a real login>+- **Seeding command:** `<command>` (or "n/a")+- **Per-surface status check:**+ - CLI: `<command>` โ signed-in when <...>+ - Web: `<command>` โ signed-in when <...>+ - Electron: `<command>` โ signed-in when <...>++## 4. Surfaces++<For each surface that applies. Delete the ones that don't.>++### CLI++- Invocation: `<how the CLI is run โ from source or built binary>`+- Auth: <see ยง3 CLI>+- Standalone install: `<command>` or "covered by root install"++### Web++- Launch: `<dev server command>` (from ยง2)+- Base URL: `<url>`+- agent-browser session: `<session name>`++### Electron++- Launch: `<start command>` โ CDP port `<port>`+- Stop: `<command>`+- Login persistence: <how login survives across runs>++## 5. Project probes & quick navigation++- Auth probe: `<command>` โ `{ isSignedIn, userId }`+- Route probe: `<command>` โ current route+- Operations probe: `<command>` โ running operations+- Quick navigation: `<command> goto <route>`+- Routes worth jumping to: <list>++## 6. Known constraints++- <e.g. "agent runs require the queue service (ยง2) up, or the run dies before any+ real work">+- <e.g. "the desktop and CLI packages are standalone โ install inside each">+- <e.g. "OS-capture surfaces are macOS-only">+```++## First-run bootstrap (SKILL.md Step 0.5)++When `.agents/verify/PROJECT.md` is absent, build it before doing anything else:++1. **Explore the repo.** Read the signals that reveal how the project runs:+ `package.json` scripts, `README`, CI workflows (`.github/workflows/**`),+ `Makefile` / `Justfile`, `docker-compose*.yml` / `compose.yaml`, `.env.example`,+ and any existing test/dev docs. Note the dev-server command, the services it+ needs, the ports, the auth story, and which surfaces exist.+2. **Draft `PROJECT.md`** from the fixed skeleton above, filling every section from+ what you found. Where a value is uncertain, mark it explicitly as a guess rather+ than inventing a command.+3. **Present it for confirmation.** Show the draft to the user and ask them to+ confirm or correct it โ especially the start/stop commands, the required+ services, and the auth path. Do not run a dev server or write test steps against+ an unconfirmed adapter.+4. **Write it only after approval**, to `.agents/verify/PROJECT.md`. Create+ `.agents/verify/` if it does not exist.++`install` (the CLI's `lh verify install`) only places the skill files; it does no repo+exploration. The adapter draft needs a model, so the first verification run is what+bootstraps `PROJECT.md`.++## Drift rule++Treat the adapter like a living log: when observed reality diverges from it during a+run (a port moved, a start command changed, a service is now required), **fix+`PROJECT.md` in place during the run** rather than working around it silently. The+next run should not rediscover the same divergence.++## Two living-log layers++The skill's `references/common-mistakes.md` and `references/probe-mock-patterns.md`+are the **generic layer** โ product-independent, read-only in consumer repos,+updated only by PR to the CLI repo. The project's own+`.agents/verify/common-mistakes.md` and `.agents/verify/probe-mock-patterns.md` are+the **project layer** โ writable, and the only place a run records project-specific+learnings. At runtime the agent reads both layers and writes only the project layer.+When a project-layer entry turns out to be product-independent, genericize it (drop+every project-specific noun) and PR it to the generic layer upstream.diff --git a/apps/cli/skills/agent-testing/references/record-app-screen.md b/apps/cli/skills/agent-testing/references/record-app-screen.mdnew file mode 100644index 00000000000..3a74e361772--- /dev/null+++ b/apps/cli/skills/agent-testing/references/record-app-screen.md@@ -0,0 +1,116 @@+# record-app-screen.sh++General-purpose screen recording for a CDP-driven Electron/Chrome app. Captures CDP+screenshots as video frames and gallery snapshots, then assembles them into an MP4+on stop. Because it renders from the browser engine over CDP (not the OS screen), it+works under Xvfb and is unaffected by display sleep.++## Why CDP Screenshots Instead of ffmpeg Screen Capture++- **Works on any screen** โ CDP screenshots capture the browser viewport directly,+ so external monitors, Retina scaling, and window positioning are handled+ automatically.+- **No signal-handling issues** โ `ffmpeg-static` (npm) can produce corrupt MP4+ files when killed (missing moov atom). CDP screenshots avoid this entirely.+- **Consistent output** โ resolution-independent, no crop-coordinate math.++## Commands++```bash+# $SKILL_DIR = the skill's install dir; the target app must be running with CDP+"$SKILL_DIR/scripts/record-app-screen.sh" start [output_name] # start recording+"$SKILL_DIR/scripts/record-app-screen.sh" stop # stop + assemble video+"$SKILL_DIR/scripts/record-app-screen.sh" status # is recording active?+```++### Arguments++| Argument | Default | Description |+| ------------- | --------------------------- | -------------------------- |+| `output_name` | `recording-YYYYMMDD-HHMMSS` | Base name for output files |++### Environment Variables++| Variable | Default | Description |+| ---------------------- | ------- | -------------------------------------- |+| `CDP_PORT` | `9222` | Chrome DevTools Protocol port |+| `SCREENSHOT_INTERVAL` | `3` | Seconds between gallery screenshots |+| `VIDEO_FRAME_INTERVAL` | `0.5` | Seconds between video frames (\~2 fps) |++## Output Structure++```+.records/+ <name>.mp4 # Video assembled from frames (~2 fps)+ <name>/ # Gallery screenshots (every 3s)+ 0000.png+ 0001.png+ ...+```++The `.records/` directory is at the repo root and is gitignored.++## How It Works++### Start++1. Creates two background loops:+ - **Video frames** โ `agent-browser screenshot` every `VIDEO_FRAME_INTERVAL`+ seconds into a temp directory.+ - **Gallery screenshots** โ `agent-browser screenshot` every+ `SCREENSHOT_INTERVAL` seconds into `.records/<name>/`.+2. Saves PIDs and paths to `/tmp/record-app-screen.pids` and+ `/tmp/record-app-screen.state`.++### Stop++1. Kills both background loops.+2. Assembles video frames into MP4 with ffmpeg:+ ```+ ffmpeg -framerate 2 -i frame_%06d.png -c:v libx264 -crf 23 -pix_fmt yuv420p <output>.mp4+ ```+3. Cleans up the temp frame directory.+4. Reports file sizes and paths.++## Usage Example++```bash+# 1. Start the Electron dev instance (launch command from PROJECT.md ยง4)++# 2. Start recording+"$SKILL_DIR/scripts/record-app-screen.sh" start my-test++# 3. Drive the automation+agent-browser --cdp 9222 click @e61+agent-browser --cdp 9222 type @e42 "hello"+agent-browser --cdp 9222 press Enter+sleep 10++# 4. Stop and get results+"$SKILL_DIR/scripts/record-app-screen.sh" stop+# โ .records/my-test.mp4 + .records/my-test/*.png+```++## When to use a GIF instead++For a short, time-based assertion (streaming output, a ticking timer, a loading+state) attach a GIF from `scripts/record-gif.sh` to the case's evidence โ it is+lighter than a full recording and embeds inline on the verify page. Reach for a full+MP4 recording only when a longer flow needs to be watched end to end.++## Prerequisites++- **ffmpeg** โ for video assembly. Install via `bun add -g ffmpeg-static` or+ `brew install ffmpeg`.+- **agent-browser** โ for CDP screenshots. Install via `npm i -g agent-browser`.+- **The app running with CDP enabled** โ start the dev instance per `PROJECT.md`.++## Troubleshooting++| Problem | Solution |+| ----------------------------------- | ----------------------------------------------------------------------------------------- |+| "No active recording found" on stop | PID file was cleaned up; check for background loops with `ps aux \| grep agent-browser` |+| "A recording is already active" | Run `stop` first, or clean: `rm /tmp/record-app-screen.pids /tmp/record-app-screen.state` |+| Video is 0 bytes | No frames captured. Ensure the app is running and the CDP port is correct |+| Screenshots are blank/white | The app may not have finished loading yet. Wait for renderer readiness first |+| ffmpeg assembly fails | Check `/tmp/ffmpeg-assemble.log`; ensure ffmpeg is installed and frames exist |diff --git a/apps/cli/skills/agent-testing/references/report.md b/apps/cli/skills/agent-testing/references/report.mdnew file mode 100644index 00000000000..fe0b46cbd41--- /dev/null+++ b/apps/cli/skills/agent-testing/references/report.md@@ -0,0 +1,325 @@+# Structured Test Reports++Every automated test session ends with a structured, evidence-backed report. A+chat-only summary is not an acceptable deliverable: the report is what the user (or+a reviewer, or a later agent) audits without replaying the session.++## Location & layout++Reports live under `.records/reports/` (gitignored, like all `.records/`+output), grouped by acceptance subject. One subject directory contains one+subdirectory per immutable verification round:++```+.records/reports/<subject-key>/+โโโ acceptance.json+โโโ <YYYYMMDD-HHMMSS>-<slug>/+โ โโโ report.md+โ โโโ result.json+โ โโโ assets/+โโโ <YYYYMMDD-HHMMSS>-<slug>/+```++`<subject-key>` is the ingest subject with `:` replaced by `-`. Scaffold with+`report-init.sh --subject topic:tpc_xxx <slug> "<title>"`; this also pre-fills+`result.json.subject`. The legacy flat layout remains readable, but new runs+should always carry their subject.++Reusable per-check inputs live separately under+`.records/fixtures/<subject-key>/<check-id>/` as `check.json` plus `seed/`.+Execution outputs remain in the round directory's `assets/`. See+`scripts/fixture.mjs` and the skill's fixture workflow.++**`result.json` is the report โ `report.md` is just its tail.** The published+verify page (`/verify/<id>`) renders itself from `result.json`: one line of+provenance (PR / branch / commit / date / surfaces), the overall conclusion from+`summary.conclusion` directly under the title, and the check list from `plan[]`+paired with `cases[]`. So `report.md` must NOT repeat the scope block or a case+table โ those double up on the page. It carries only the non-duplicate narrative+(follow-ups / this-round notes / score), rendered as the page's collapsible+"Details".++## Workflow++1. **Scaffold up front** โ before running the first test step:++ ```bash+ # $SKILL_DIR = the skill's install dir+ DIR=$("$SKILL_DIR/scripts/report-init.sh" --subject topic:tpc_xxx my-slug "My title")+ ```++ The script creates the directory, pre-fills branch / commit / date in both+ files, and prints the directory path. Translate its headings and table labels to+ the user's language before delivery if needed.++2. **Collect evidence as you test** โ every asserted behavior gets one evidence+ item in `$DIR/assets/`:+ - UI (static state): `agent-browser screenshot` or `capture-app-window.sh`, then+ **verify the screenshot with the Read tool before citing it** โ never cite an+ image you haven't looked at.++ - UI (time-based behavior): **screenshot vs GIF is a judgment you make per+ case.** If the assertion is about change over time โ streaming output, a+ ticking timer, loading/progress states, animations, appear/disappear+ transitions โ a static screenshot cannot prove it. Record a frame sequence and+ synthesize a GIF:++ ```bash+ # start recording (background), trigger the behavior, wait for it to finish+ "$SKILL_DIR/scripts/record-gif.sh" "$DIR/assets/case2-streaming.gif" 12 2 &+ GIF_PID=$!+ # ... drive the scenario ...+ wait $GIF_PID+ ```++ Verify at least the first/last frames visually (Read the GIF) before citing.++ - UI (before/after comparison): capture and visually verify both original+ screenshots. Do not compose them into a new image. In the case's `evidence`+ array, pair them with a shared comparison id.++ A comparison pair means the same view in two states. Sequential steps of a+ flow are not before/after states; attach those as ordinary ordered evidence+ items with captions naming each step.++ ```json+ "evidence": [+ {+ "path": "assets/before.png",+ "comparison": { "id": "topic-row", "role": "before", "layout": "vertical", "label": "before: 11px, line-height 40px" }+ },+ {+ "path": "assets/after.png",+ "comparison": { "id": "topic-row", "role": "after", "layout": "vertical", "label": "after: 12px, line-height 44px" }+ }+ ]+ ```++ The verify page renders a complete pair with each screenshot under its own+ tinted band โ red for `before`, green for `after`. A group contains exactly one+ `before` and one `after`, and **both halves need the same string `id`**; a half+ without an `id` can never pair. Incomplete groups render as ordinary evidence.++ Two fields are worth setting on every pair:++ - **`layout`** โ `horizontal` (default, side by side) or `vertical` (stacked).+ A tall, narrow crop (a sidebar, a form, a list) reads well side by side; a+ **wide, short strip** (a toolbar, a one-line footer) must be `vertical`,+ because two of them in a two-column grid become illegible slivers. Set it on+ both halves.+ - **`label`** โ the caption shown next to the role word in the band. This is+ where the before/after contrast is actually _stated_: put the measured delta+ on each side, so the two captions read as a comparison rather than repeating+ the case title.++ - CLI: exact command + trimmed output (`<cli> <command> | tee "$DIR/assets/x.txt"`).++ - Network: `agent-browser network requests` dumps or HAR files.++3. **Write `plan[]` BEFORE you run anything.** The approved plan from Step 1 is part+ of the report, not scaffolding you throw away: each item is+ `{ id, title, category, verifier, method, expected, requiredEvidence }` โ what+ you will check, which requirement area it belongs to, how it is judged, how you+ will exercise it, what would make it pass, and the artifact it must produce.+ `verifier` and `requiredEvidence` are closed sets the pipeline acts on (schema+ below); `method` / `expected` are prose. `cases[]` later reuses the same `id`s,+ which is what lets the report pair intent against outcome. A planned item that+ never produces a case renders as **ๆชๆง่ก** rather than vanishing, so cut coverage+ in the open.++4. **Fill `result.json` as you go** โ it is the report. Each tested behavior is one+ entry in `cases[]` (`{ id, name, result, observation, evidence }`), where+ `evidence` is a path under `assets/`. Set the scope fields (`scenario`, `branch`,+ `commit`, `surfaces`, `entry`) and write the one-paragraph verdict into+ `summary.conclusion`. The page pairs each check with its evidence inline, so you+ don't hand-build a table. `report.md` holds only the narrative tail.++5. **Set the verdict** in both `report.md` and `result.json`. Describe key visual+ outcomes in prose; the published verify URL is the only visual pointer in the+ final chat reply.++6. **Publish** (SKILL.md Step 6) โ upload the finished session so it's viewable on+ the verify platform, not just on disk. **Publish to PRODUCTION defaults with the+ user's real login, NOT a local-dev CLI override** โ strip the local dev overrides+ so `lh` uses its production defaults. Clearing an override profile looks like:++ ```bash+ env -u LOBEHUB_SERVER -u LOBE_API_KEY -u LOBEHUB_CLI_API_KEY -u LOBEHUB_CLI_HOME \+ lh verify ingest-report "$DIR" --source agent-testing --open --json+ ```++ This creates a new immutable verification run, attaches it to the required+ subject acceptance, uploads the cases, evidence, and report body, then prints+ both `/verify/<verifyRunId>` and `/acceptance/<acceptanceId>`. Include that full+ production link in the final reply alongside the local report dir. See SKILL.md โ+ Step 6 for why production defaults (a localhost URL isn't shareable and a local+ stub storage fails file-evidence uploads), the production login check, and the+ atomic commands (`verify run|result|evidence|report โฆ`).++## Report language (hard rule)++**`report.md` MUST be written in the language the user is conversing in** โ the+whole file, headings included. If the conversation is in Chinese, the report is in+Chinese; do not mix English prose into it. The scaffold headings are placeholders โ+translate them when filling. Exceptions that stay as-is: code/commands,+identifiers, log excerpts, and `result.json` (its keys and status values are+machine-read and stay English; the `title` and case `name` fields follow the+user's language).++## report.md sections++Default report shape (a case table doubles the page and is only for a purely+non-visual run; for UI runs, leave the case list to `result.json`):++| Section | Content |+| ---------------- | ---------------------------------------------------------------------------------------- |+| **Verdict** | Overall verdict first (`pass` / `partial` / `fail`), then concise reasons and follow-ups |+| **Verification** | Commands or automated checks run in this session, with trimmed results |+| **Score** | Pass/fail/blocked counts, optional 0โ100 score |++Status values: `pass` / `fail` / `blocked` (couldn't run โ e.g. auth or env+missing; a blocked case is not a pass).++## result.json schema++**Two fields are the report's identity in every list surface โ treat them as+REQUIRED on every ingest:**++- `title` (top level) โ without it the run lists as "ๆชๅฝๅ้ช่ฏ" forever.+- `summary.verdict` (`pass` / `fail` / `partial`) โ without it the list glyph is a+ permanent amber "?" instead of the green pass. The CLI derives a fallback from the+ cases, but an explicit verdict is still the author's job.+- Every `comparison` pair side should carry a `label` โ the role band renders it as+ the explanation; a pair without labels shows two bare role words and reads as+ unexplained.++```json+{+ "branch": "feat/task-tree",+ "cases": [+ {+ "category": "Task hierarchy",+ "id": "1",+ "name": "task tree returns nested children",+ "surface": "cli",+ "status": "pass",+ "observation": "root returned 3 nested children, depth 2",+ "evidence": ["assets/task-tree.txt"]+ }+ ],+ "commit": "abc1234",+ "createdAt": "2026-06-11T15:30:00+08:00",+ "interactionCost": {+ "model": "goms-klm@lobe-v1",+ "scope": "user-equivalent",+ "totalSeconds": 8.1,+ "activeSeconds": 6.1,+ "waitSeconds": 2,+ "operators": { "K": 1, "P": 2, "H": 0, "M": 2, "T_chars": 5, "R_ms": 2000 },+ "phases": []+ },+ "plan": [+ {+ "id": "1",+ "title": "task tree returns nested children",+ "category": "Task hierarchy",+ "verifier": "program",+ "method": "<cli> task list --tree against a 3-level fixture",+ "expected": "root shows 3 nested children at depth 2",+ "requiredEvidence": ["text"]+ }+ ],+ "pullRequest": {+ "number": 17152,+ "title": "feat(task): nested task tree",+ "url": "https://github.com/<org>/<repo>/pull/17152"+ },+ "summary": {+ "total": 1,+ "passed": 1,+ "failed": 0,+ "blocked": 0,+ "score": 100,+ "verdict": "pass"+ },+ "surfaces": ["cli"],+ "title": "Verify task tree API"+}+```++`plan[]` is the checks you committed to **before running them**, and it shares+`id`s with `cases[]`. Every plan item must carry a `category` that names its+user-facing business scenario or requirement area (for example `Task hierarchy`,+`Rate-limit recovery`, `Browser actions`). It must not name a technical surface such+as `Desktop`, `CLI`, or `Backend`: Acceptance groups are organized by what the user+is accepting, while `surface` separately records where the check ran. A plan item+with no matching case renders as **ๆชๆง่ก**: cutting coverage is allowed, hiding that+you cut it is not.++Two of its fields are a **closed vocabulary**, because the pipeline acts on them โ+they are not labels:++| field | values | what it does |+| ------------------ | ---------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |+| `verifier` | `program` \| `agent` \| `llm` (default `agent`) | How the verdict is reached. A command-asserted check is `program`; calling it `agent` hides what actually judged it. |+| `requiredEvidence` | `screenshot` \| `gif` \| `video` \| `text` \| `dom_snapshot` \| `transcript` | The artifact this check **must** produce. The coverage gate **fails** an item whose required medium is missing. |++An out-of-vocabulary value in either fails the ingest โ an unrecognized medium+would silently gate on nothing, which is worse than no gate at all.++`method` (how you would exercise it) and `expected` (what would make it pass) stay+**free prose** โ they carry intent no enum can, and both render under the check on+the page next to the outcome.++A plan item may also carry a per-item `surface` (same closed set as the run-level+`surfaces`; `electron` normalizes to `desktop`). It says which product surface THIS+check ran on. It is metadata, never an Acceptance grouping key.++`surfaces` is a **closed set** โ `web` | `desktop` | `cli` | `mobile` | `bot` โ and+names the product surface a check ran **on**. `electron` is accepted and normalized+to `desktop`. Anything else fails the ingest:++- A **test kind** is not a surface. `unit`, `backend`, `database`, `type-check` do+ not belong here; a backend change verified through the CLI has surface `cli`.+- A **runtime mode** is not a surface. "packaged build", "CDP dev instance" โ that+ detail belongs on the plan item's `method`.++`entry` is the command or URL exercised (`<cli> task list --tree`, `/chat/settings`)+โ **not** a PR title and not a description of the change.++`pullRequest` is optional: when absent, the ingest asks `gh` for the PR of `branch`+and fills it in. Write it explicitly only when the report verifies a PR that isn't+the branch's own.++`score` is optional โ use it when the verdict has a subjective component (UI polish,+copy quality); omit it for purely binary runs. `verdict` is the single word the user+reads first: `pass`, `fail`, or `partial`.++`subject` identifies the business subject whose **acceptance aggregate** owns this+immutable run: either `"subject": "task:<id>"` (`task` | `topic` | `document`) or+`{ "type": "task", "id": "task_โฆ", "requirement": "one-sentence acceptance bar" }`.+The `--subject` flag overrides this field. Inside a LobeHub conversation, both may+be omitted because `ingest-report` defaults to `topic:$LOBEHUB_TOPIC_ID`; outside a+topic, an explicit subject is mandatory. Every ingest creates a new immutable run;+never update a prior run after a fix, publish the re-verification as the next round.++`interactionCost` is optional and run-level. For UI runs driven through+`agent-browser`, create `interaction-trace.jsonl` with `scripts/agent-browser-klm.mjs`,+then run `scripts/agent-browser-klm-analyze.mjs --trace "$DIR/interaction-trace.jsonl" --result "$DIR/result.json" --write`.++When published, `verify ingest-report` maps each case onto a check result:+`name`โtitle, `status`/`result`โverdict, `observation`โthe result's key+observation, and `evidence` pathsโuploaded artifacts. `summary.{total,passed,failed,blocked}`+and `verdict` become the report's stats + overall verdict; `report.md` becomes the+report body.++## Rules++- **No evidence, no claim** โ every `pass`/`fail` in `cases[]` must link at least+ one asset. UI cases must attach their primary screenshot/GIF as evidence;+ non-visual CLI/network cases may link transcripts, HAR files, or logs.+- **Screenshots must be visually verified** with the Read tool before being cited.+- **Report failures faithfully** โ a failing case with clear evidence is a good+ report; a vague green one is not.+- If coverage was cut (cases skipped, surfaces not exercised), say so in the Verdict+ section โ silent truncation reads as "covered everything".diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs b/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjsnew file mode 100755index 00000000000..1239ec826c1--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/agent-browser-klm-analyze.mjs@@ -0,0 +1,232 @@+#!/usr/bin/env node+/**+ * Analyze agent-browser KLM trace JSONL into a compact interactionCost object.+ */++import { readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const MODEL = 'goms-klm@lobe-v1';+const TIMING_SECONDS = {+ H: 0.4,+ K: 0.2,+ M: 1.35,+ P: 1.1,+ T_char: 0.2,+};++const emptyOperators = () => ({+ H: 0,+ K: 0,+ M: 0,+ P: 0,+ R_ms: 0,+ T_chars: 0,+});++const usage = () => {+ console.log(`Usage:+ agent-browser-klm-analyze.mjs --trace interaction-trace.jsonl [--result result.json --write] [--markdown]++Options:+ --trace <file> JSONL trace from agent-browser-klm.mjs+ --result <file> result.json to patch with interactionCost+ --write overwrite --result with interactionCost+ --markdown print a markdown section instead of JSON+ --model <id> model id label (default: ${MODEL})`);+};++const parseArgs = (argv) => {+ const options = { markdown: false, model: MODEL, write: false };++ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === '--help' || arg === '-h') {+ usage();+ process.exit(0);+ } else if (arg === '--trace') options.trace = argv[++index];+ else if (arg === '--result') options.result = argv[++index];+ else if (arg === '--model') options.model = argv[++index] ?? MODEL;+ else if (arg === '--write') options.write = true;+ else if (arg === '--markdown') options.markdown = true;+ else throw new Error(`Unknown option: ${arg}`);+ }++ if (!options.trace) throw new Error('--trace is required');+ if (options.write && !options.result) throw new Error('--write requires --result');++ return options;+};++const addOperators = (target, source = {}) => {+ target.H += Number(source.H ?? 0);+ target.K += Number(source.K ?? 0);+ target.M += Number(source.M ?? 0);+ target.P += Number(source.P ?? 0);+ target.R_ms += Number(source.R_ms ?? 0);+ target.T_chars += Number(source.T_chars ?? 0);+};++const round = (value) => Math.round(value * 100) / 100;++const secondsFromOperators = (operators) =>+ round(+ operators.H * TIMING_SECONDS.H ++ operators.K * TIMING_SECONDS.K ++ operators.M * TIMING_SECONDS.M ++ operators.P * TIMING_SECONDS.P ++ operators.T_chars * TIMING_SECONDS.T_char ++ operators.R_ms / 1000,+ );++const activeSecondsFromOperators = (operators) =>+ round(+ operators.H * TIMING_SECONDS.H ++ operators.K * TIMING_SECONDS.K ++ operators.M * TIMING_SECONDS.M ++ operators.P * TIMING_SECONDS.P ++ operators.T_chars * TIMING_SECONDS.T_char,+ );++const phaseKey = (event) =>+ event.phase?.id || event.phase?.checkItemId || event.checkItemId || 'unscoped';++const phaseLabel = (event, key) =>+ event.phase?.label || (key === 'unscoped' ? event.phase?.checkItemId : key) || 'Unscoped actions';++const parseTrace = async (tracePath) => {+ const raw = await readFile(tracePath, 'utf8');+ return raw+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean)+ .map((line, index) => {+ try {+ return JSON.parse(line);+ } catch (error) {+ throw new Error(`Invalid JSONL at line ${index + 1}: ${error.message}`, { cause: error });+ }+ });+};++const summarize = (events, { model, tracePath }) => {+ const operators = emptyOperators();+ const phases = new Map();+ const categoryCounts = {};+ const mentalEstimates = [];+ let actualAgentMs = 0;++ for (const event of events) {+ const eventOperators = event.klm?.operators ?? emptyOperators();+ addOperators(operators, eventOperators);++ const category = event.klm?.category ?? 'unknown';+ categoryCounts[category] = (categoryCounts[category] ?? 0) + 1;+ actualAgentMs += Number(event.durationMs ?? 0);++ if (event.type === 'mental_estimate' && event.mentalEstimate) {+ mentalEstimates.push({+ confidence: event.mentalEstimate.confidence,+ mOperators: event.mentalEstimate.mOperators,+ phaseId: event.phase?.id,+ reason: event.mentalEstimate.reason,+ score: event.mentalEstimate.score,+ });+ }++ const key = phaseKey(event);+ const existing = phases.get(key) ?? {+ actionCount: 0,+ actualAgentMs: 0,+ checkItemId: event.phase?.checkItemId,+ id: key,+ label: phaseLabel(event, key),+ operators: emptyOperators(),+ };++ addOperators(existing.operators, eventOperators);+ existing.actionCount += 1;+ existing.actualAgentMs += Number(event.durationMs ?? 0);+ phases.set(key, existing);+ }++ const phaseItems = [...phases.values()].map((phase) => ({+ ...phase,+ activeSeconds: activeSecondsFromOperators(phase.operators),+ actualAgentSeconds: round(phase.actualAgentMs / 1000),+ seconds: secondsFromOperators(phase.operators),+ waitSeconds: round(phase.operators.R_ms / 1000),+ }));++ return {+ actionCount: events.length,+ activeSeconds: activeSecondsFromOperators(operators),+ actualAgentSeconds: round(actualAgentMs / 1000),+ categoryCounts,+ generatedAt: new Date().toISOString(),+ mentalEstimates,+ model,+ operators,+ phases: phaseItems.sort((a, b) => b.seconds - a.seconds),+ scope: 'user-equivalent',+ sourceTrace: path.basename(tracePath),+ timingSeconds: TIMING_SECONDS,+ totalSeconds: secondsFromOperators(operators),+ waitSeconds: round(operators.R_ms / 1000),+ };+};++const toMarkdown = (summary) => {+ const topPhases = summary.phases.slice(0, 5);+ const phaseRows = topPhases+ .map(+ (phase) =>+ `| ${phase.label} | ${phase.seconds.toFixed(2)}s | ${phase.activeSeconds.toFixed(2)}s | ${phase.waitSeconds.toFixed(2)}s |`,+ )+ .join('\n');++ return `## GOMS-KLM ไบคไบๆๆฌ++- ๆจกๅ๏ผ\`${summary.model}\`+- ็จๆท็ญๆๆปๆๆฌ๏ผ${summary.totalSeconds.toFixed(2)}s+- ไธปๅจๆไฝๆๆฌ๏ผ${summary.activeSeconds.toFixed(2)}s+- ็ณป็ป็ญๅพ ๆๆฌ๏ผ${summary.waitSeconds.toFixed(2)}s+- ๆไฝ็ฌฆ๏ผK=${summary.operators.K}, P=${summary.operators.P}, H=${summary.operators.H}, M=${summary.operators.M}, T=${summary.operators.T_chars} chars, R=${summary.operators.R_ms}ms++| ้ถๆฎต | ๆปๆๆฌ | ไธปๅจ | ็ญๅพ |+| --- | ---: | ---: | ---: |+${phaseRows || '| ๆ | 0.00s | 0.00s | 0.00s |'}+`;+};++const patchResult = async (resultPath, summary, write) => {+ const raw = await readFile(resultPath, 'utf8');+ const result = JSON.parse(raw);+ result.interactionCost = summary;++ if (write) {+ await writeFile(resultPath, `${JSON.stringify(result, null, 2)}\n`, 'utf8');+ }++ return result;+};++const main = async () => {+ const options = parseArgs(process.argv.slice(2));+ const tracePath = path.resolve(options.trace);+ const events = await parseTrace(tracePath);+ const summary = summarize(events, { model: options.model, tracePath });++ if (options.result) await patchResult(path.resolve(options.result), summary, options.write);++ if (options.markdown) console.log(toMarkdown(summary));+ else console.log(JSON.stringify(summary, null, 2));+};++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ main().catch((error) => {+ console.error('[agent-browser-klm-analyze]', error.message);+ process.exit(1);+ });+}diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjs b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjsnew file mode 100755index 00000000000..671b0d8d35c--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.mjs@@ -0,0 +1,494 @@+#!/usr/bin/env node+/**+ * agent-browser-klm.mjs+ *+ * Thin wrapper around `agent-browser` that records each executed command as an+ * interaction atom for GOMS-KLM analysis. Unknown flags are forwarded.+ *+ * Browser output is captured through temp files rather than pipes: the+ * agent-browser daemon can inherit and hold the child's stdio descriptors, so a+ * pipe might never reach EOF and `spawnSync` would block on it. A file has no+ * such dependency. The output is attached to the trace atom, and on failure it+ * is echoed to stderr โ a swallowed error reads exactly like a successful step+ * (the page simply never navigated), which is far worse than noisy output.+ */++import { spawnSync } from 'node:child_process';+import { randomUUID } from 'node:crypto';+import { closeSync, mkdtempSync, openSync, readFileSync, rmSync } from 'node:fs';+import { appendFile, mkdir } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const SCHEMA = 'lobehub.agentBrowserKlmTrace@1';+const DEFAULT_TRACE = '.records/interaction-trace.jsonl';++// Enough to carry an agent-browser diagnostic; keeps one JSONL atom on one line.+const MAX_CAPTURED_CHARS = 4000;++const optionValueFlags = new Set([+ '--browser',+ '--cdp',+ '--device',+ '--engine',+ '--args',+ '--host',+ '--port',+ '--profile',+ '--proxy',+ '--proxy-bypass',+ '--session',+ '--session-name',+ '--state',+ '--timeout',+ '--url',+ '--user-data-dir',+ '--executable-path',+ '--extension',+ '--headers',+ '--user-agent',+ '--screenshot-dir',+ '--screenshot-quality',+ '--screenshot-format',+ '--download-path',+ '--allowed-domains',+ '--action-policy',+ '--confirm-actions',+ '--config',+ '--model',+]);++const forwardedBooleanGlobalFlags = new Set([+ '--auto-connect',+ '--headless',+ '--headed',+ '--no-sandbox',+]);++const defaultOperators = () => ({+ H: 0,+ K: 0,+ M: 0,+ P: 0,+ R_ms: 0,+ T_chars: 0,+});++const usage = () => {+ console.log(`Usage:+ agent-browser-klm.mjs [--klm-trace file] [--klm-phase id] [--klm-check id] [--klm-command-timeout-ms ms] -- <agent-browser args...>+ agent-browser-klm.mjs mental [--m n] [--reason text] [--confidence n] [--score n] [--klm-trace file]++Examples:+ AGENT_BROWSER_KLM_TRACE="$DIR/interaction-trace.jsonl" \\+ agent-browser-klm.mjs --klm-phase login --klm-check case-1 --session app-dev click @e3++ agent-browser-klm.mjs mental --m 2 --score 3 --confidence 0.75 \\+ --reason "First view requires understanding status and next action"`);+};++const parseNumber = (value, fallback) => {+ if (value === undefined) return fallback;+ const number = Number(value);+ return Number.isFinite(number) ? number : fallback;+};++const parseOwnFlags = (argv) => {+ const meta = {+ checkItemId: process.env.AGENT_BROWSER_KLM_CHECK || process.env.KLM_CHECK_ITEM_ID,+ label: process.env.AGENT_BROWSER_KLM_LABEL || process.env.KLM_LABEL,+ phaseId: process.env.AGENT_BROWSER_KLM_PHASE || process.env.KLM_PHASE_ID,+ surface: process.env.AGENT_BROWSER_KLM_SURFACE || process.env.KLM_SURFACE || 'web',+ commandTimeoutMs: parseNumber(process.env.AGENT_BROWSER_KLM_COMMAND_TIMEOUT_MS, undefined),+ trace:+ process.env.AGENT_BROWSER_KLM_TRACE ||+ process.env.INTERACTION_TRACE ||+ path.resolve(process.cwd(), DEFAULT_TRACE),+ };+ let binary = process.env.AGENT_BROWSER_BIN || 'agent-browser';+ const forwarded = [];++ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === '--') {+ forwarded.push(...argv.slice(index + 1));+ break;+ }++ if (arg === '--klm-help' || arg === '-h') {+ usage();+ process.exit(0);+ }++ if (arg === '--klm-trace') meta.trace = path.resolve(argv[++index] ?? DEFAULT_TRACE);+ else if (arg === '--klm-phase') meta.phaseId = argv[++index];+ else if (arg === '--klm-label') meta.label = argv[++index];+ else if (arg === '--klm-check') meta.checkItemId = argv[++index];+ else if (arg === '--klm-surface') meta.surface = argv[++index] ?? meta.surface;+ else if (arg === '--klm-command-timeout-ms')+ meta.commandTimeoutMs = parseNumber(argv[++index], meta.commandTimeoutMs);+ else if (arg === '--klm-agent-browser') binary = argv[++index] ?? binary;+ else forwarded.push(arg);+ }++ return { binary, forwarded, meta };+};++const appendEvent = async (trace, event) => {+ await mkdir(path.dirname(path.resolve(trace)), { recursive: true });+ await appendFile(trace, `${JSON.stringify(event)}\n`, 'utf8');+};++const findCommandIndex = (args) => {+ for (let index = 0; index < args.length; index += 1) {+ const arg = args[index];++ if (arg === '--') continue;+ if (optionValueFlags.has(arg)) {+ index += 1;+ continue;+ }+ if (arg.startsWith('--')) {+ if (!forwardedBooleanGlobalFlags.has(arg) && arg.includes('=')) continue;+ continue;+ }+ if (arg.startsWith('-')) continue;++ return index;+ }++ return -1;+};++const normalizeCommand = (args) => {+ const index = findCommandIndex(args);+ if (index < 0) return { argsAfterCommand: [], command: null };+ return {+ argsAfterCommand: args.slice(index + 1),+ command: args[index],+ };+};++const textLength = (value) => (typeof value === 'string' ? [...value].length : 0);++const lastNonFlag = (args) => {+ for (let index = args.length - 1; index >= 0; index -= 1) {+ const arg = args[index];+ if (!arg.startsWith('-')) return arg;+ }+};++const numericWaitMs = (args) => {+ const direct = args.find((arg) => /^\d+(?:\.\d+)?$/.test(arg));+ return direct ? Number(direct) : undefined;+};++const classifyFindCommand = (args) => {+ const action = [...args]+ .reverse()+ .find((arg) => ['check', 'click', 'fill', 'press', 'select', 'type'].includes(arg));+ if (!action)+ return {+ assumptions: ['Semantic lookup only; no user-equivalent action counted.'],+ category: 'probe',+ operators: defaultOperators(),+ };++ return classifyCommand(action, args.slice(args.indexOf(action) + 1), 0);+};++function classifyCommand(command, args, durationMs) {+ const operators = defaultOperators();+ const assumptions = [];+ let category = 'probe';++ switch (command) {+ case 'check':+ case 'click':+ case 'download':+ case 'select': {+ operators.P = 1;+ operators.K = 1;+ category = 'interaction';+ assumptions.push(`${command} maps to pointer acquisition plus one activation.`);+ break;+ }++ case 'dblclick': {+ operators.P = 1;+ operators.K = 2;+ category = 'interaction';+ assumptions.push('dblclick maps to pointer acquisition plus two activations.');+ break;+ }++ case 'fill':+ case 'type': {+ operators.P = 1;+ operators.T_chars = textLength(lastNonFlag(args));+ category = 'interaction';+ assumptions.push(`${command} maps to pointer acquisition plus user-equivalent text entry.`);+ break;+ }++ case 'keyboard': {+ const subcommand = args[0];+ if (subcommand === 'type' || subcommand === 'inserttext') {+ operators.T_chars = textLength(args.at(-1));+ category = 'interaction';+ assumptions.push(`keyboard ${subcommand} maps to user-equivalent text entry.`);+ } else if (subcommand === 'press') {+ operators.K = 1;+ category = 'interaction';+ assumptions.push('keyboard press maps to one keystroke.');+ }+ break;+ }++ case 'press': {+ operators.K = 1;+ category = 'interaction';+ assumptions.push('press maps to one keystroke.');+ break;+ }++ case 'scroll': {+ operators.P = 1;+ operators.K = 1;+ category = 'interaction';+ assumptions.push('scroll maps to target acquisition plus one wheel/gesture action.');+ break;+ }++ case 'open':+ case 'goto':+ case 'navigate': {+ operators.R_ms = Math.max(0, Math.round(durationMs));+ category = 'navigation';+ assumptions.push('Direct navigation is counted as system response time, not URL typing.');+ break;+ }++ case 'wait': {+ operators.R_ms = Math.max(0, Math.round(numericWaitMs(args) ?? durationMs));+ category = 'wait';+ assumptions.push('wait maps to system response time.');+ break;+ }++ case 'find': {+ return classifyFindCommand(args);+ }++ case 'screenshot':+ case 'pdf': {+ category = 'evidence';+ assumptions.push(+ `${command} is evidence capture and is not counted as user-side interaction.`,+ );+ break;+ }++ case 'snapshot':+ case 'eval':+ case 'get':+ case 'network':+ case 'stream': {+ category = 'probe';+ assumptions.push(+ `${command} is an agent probe and is not counted unless paired with a mental estimate.`,+ );+ break;+ }++ default: {+ category = 'unknown';+ assumptions.push('Unknown agent-browser command; no user-equivalent operators inferred.');+ }+ }++ return { assumptions, category, operators };+}++const buildPhase = (meta) => {+ if (!meta.phaseId && !meta.label && !meta.checkItemId) return undefined;+ return {+ checkItemId: meta.checkItemId,+ id: meta.phaseId ?? meta.checkItemId ?? 'unscoped',+ label: meta.label,+ };+};++const readCapture = (file) => {+ try {+ const text = readFileSync(file, 'utf8').trim();+ if (!text) return undefined;+ return text.length > MAX_CAPTURED_CHARS+ ? `${text.slice(0, MAX_CAPTURED_CHARS)}โฆ [truncated]`+ : text;+ } catch {+ return undefined;+ }+};++const spawnCapturing = (binary, args, timeout) => {+ const captureDir = mkdtempSync(path.join(tmpdir(), 'agent-browser-klm-'));+ const stdoutPath = path.join(captureDir, 'stdout.log');+ const stderrPath = path.join(captureDir, 'stderr.log');+ const stdoutFd = openSync(stdoutPath, 'w');+ const stderrFd = openSync(stderrPath, 'w');+ let open = true;+ const closeBoth = () => {+ if (!open) return;+ open = false;+ closeSync(stdoutFd);+ closeSync(stderrFd);+ };++ try {+ const result = spawnSync(binary, args, {+ killSignal: 'SIGKILL',+ stdio: ['ignore', stdoutFd, stderrFd],+ timeout,+ });+ // Close before reading so a SIGKILLed child's last writes are flushed.+ closeBoth();+ return { result, stderr: readCapture(stderrPath), stdout: readCapture(stdoutPath) };+ } finally {+ closeBoth();+ rmSync(captureDir, { force: true, recursive: true });+ }+};++const runAgentBrowser = async (binary, args, meta) => {+ if (args.length === 0) {+ usage();+ process.exit(1);+ }++ const startedAtMs = Date.now();+ const startedAt = new Date(startedAtMs).toISOString();+ const { argsAfterCommand, command } = normalizeCommand(args);++ const { result, stderr, stdout } = spawnCapturing(+ binary,+ args,+ meta.commandTimeoutMs && meta.commandTimeoutMs > 0 ? meta.commandTimeoutMs : undefined,+ );++ if (result.error && result.error.code !== 'ETIMEDOUT') {+ console.error(`[agent-browser-klm] failed to start ${binary}:`, result.error.message);+ }++ const timedOut = result.error?.code === 'ETIMEDOUT';+ const exitCode = timedOut ? 124 : (result.status ?? (result.error ? 127 : 1));++ const completedAtMs = Date.now();+ const durationMs = completedAtMs - startedAtMs;+ const klm = classifyCommand(command, argsAfterCommand, durationMs);+ if (timedOut) {+ klm.category = 'blocked';+ klm.operators = defaultOperators();+ klm.assumptions.push('agent-browser command timed out; no user-equivalent cost counted.');+ } else if (exitCode !== 0) {+ // The action never happened, so charging it as a completed interaction (or+ // as navigation response time) would inflate the cost model with phantom work.+ klm.category = 'blocked';+ klm.operators = defaultOperators();+ klm.assumptions.push(+ `agent-browser exited ${exitCode}; the action did not happen, so no user-equivalent cost counted.`,+ );+ }++ if (exitCode !== 0) {+ const detail = stderr ?? stdout;+ console.error(+ `[agent-browser-klm] ${binary} ${command ?? '<no command>'} exited ${exitCode}` ++ (detail ? `:\n${detail}` : ' with no output.'),+ );+ }++ const event = {+ agentBrowser: { args, command },+ completedAt: new Date(completedAtMs).toISOString(),+ durationMs,+ exitCode,+ id: randomUUID(),+ klm,+ phase: buildPhase(meta),+ schema: SCHEMA,+ source: 'agent-browser',+ startedAt,+ stderr,+ stdout,+ surface: meta.surface,+ timedOut,+ type: 'agent_browser_action',+ };++ await appendEvent(meta.trace, event);+ process.exit(exitCode);+};++const recordMentalEstimate = async (argv, baseMeta) => {+ const mental = {+ confidence: undefined,+ mOperators: 1,+ reason: undefined,+ score: undefined,+ };++ const { meta } = parseOwnFlags(argv);+ const mergedMeta = { ...baseMeta, ...meta };++ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index];+ if (arg === '--m') mental.mOperators = parseNumber(argv[++index], mental.mOperators);+ else if (arg === '--reason') mental.reason = argv[++index];+ else if (arg === '--confidence') mental.confidence = parseNumber(argv[++index], undefined);+ else if (arg === '--score') mental.score = parseNumber(argv[++index], undefined);+ }++ const operators = defaultOperators();+ operators.M = mental.mOperators;+ await appendEvent(mergedMeta.trace, {+ id: randomUUID(),+ klm: {+ assumptions: ['Mental operators are estimated by the agent from the observed page/context.'],+ category: 'mental',+ operators,+ },+ mentalEstimate: mental,+ phase: buildPhase(mergedMeta),+ recordedAt: new Date().toISOString(),+ schema: SCHEMA,+ source: 'agent',+ surface: mergedMeta.surface,+ type: 'mental_estimate',+ });+};++const main = async () => {+ const argv = process.argv.slice(2);+ if (argv[0] === '--klm-help' || argv[0] === '-h') {+ usage();+ return;+ }++ if (argv[0] === 'mental') {+ const { meta } = parseOwnFlags(argv.slice(1));+ await recordMentalEstimate(argv.slice(1), meta);+ return;+ }++ const { binary, forwarded, meta } = parseOwnFlags(argv);+ await runAgentBrowser(binary, forwarded, meta);+};++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ main().catch((error) => {+ console.error('[agent-browser-klm]', error);+ process.exit(1);+ });+}diff --git a/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.sh b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.shnew file mode 100755index 00000000000..db38f5a79dc--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/agent-browser-klm.test.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# Smoke tests for agent-browser KLM wrapper + analyzer. Uses a stub+# agent-browser, so no real browser is required.++set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+WRAPPER="$SCRIPT_DIR/agent-browser-klm.mjs"+ANALYZER="$SCRIPT_DIR/agent-browser-klm-analyze.mjs"++fail() {+ echo "FAIL: $*" >&2+ exit 1+}++tmp_dir="$(mktemp -d)"+trap 'rm -rf "$tmp_dir"' EXIT++mkdir -p "$tmp_dir/bin"+cat > "$tmp_dir/bin/agent-browser" << 'SH'+#!/usr/bin/env bash+set -euo pipefail+printf '%s\n' "$*" >> "${AGENT_BROWSER_STUB_LOG:?}"+SH+chmod +x "$tmp_dir/bin/agent-browser"++export PATH="$tmp_dir/bin:$PATH"+export AGENT_BROWSER_STUB_LOG="$tmp_dir/agent-browser.log"++trace="$tmp_dir/interaction-trace.jsonl"+trace_flags="$tmp_dir/flags-trace.jsonl"+result="$tmp_dir/result.json"++node "$WRAPPER" --klm-trace "$trace" --klm-phase first --klm-check case-1 --session app click @e1+node "$WRAPPER" --klm-trace "$trace" --klm-phase form --klm-check case-1 fill @e2 hello+node "$WRAPPER" --klm-trace "$trace" --klm-phase wait --session app wait 2000+node "$WRAPPER" mental --klm-trace "$trace" --klm-phase first --m 2 --score 3 --confidence 0.75 --reason "first view"+node "$WRAPPER" --klm-trace "$trace_flags" --klm-phase nav --engine chrome --args --no-proxy-server open about:blank++node "$ANALYZER" --trace "$trace" > "$tmp_dir/summary.json"++node - "$tmp_dir/summary.json" << 'JS'+const fs = require('fs');+const summary = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));++function eq(actual, expected, label) {+ if (actual !== expected) {+ throw new Error(`${label}: expected ${expected}, got ${actual}`);+ }+}++eq(summary.operators.P, 2, 'P');+eq(summary.operators.K, 1, 'K');+eq(summary.operators.M, 2, 'M');+eq(summary.operators.T_chars, 5, 'T_chars');+eq(summary.operators.R_ms, 2000, 'R_ms');+eq(summary.totalSeconds, 8.1, 'totalSeconds');+eq(summary.activeSeconds, 6.1, 'activeSeconds');+eq(summary.waitSeconds, 2, 'waitSeconds');+eq(summary.phases[0].id, 'first', 'top phase');+JS++cat > "$result" << 'JSON'+{+ "title": "KLM smoke",+ "cases": [],+ "summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending" }+}+JSON++node "$ANALYZER" --trace "$trace" --result "$result" --write > /dev/null++node - "$result" << 'JS'+const fs = require('fs');+const result = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));+if (!result.interactionCost) throw new Error('interactionCost missing');+if (result.interactionCost.totalSeconds !== 8.1) {+ throw new Error(`unexpected patched total: ${result.interactionCost.totalSeconds}`);+}+JS++grep -Fq -- "--session app click @e1" "$AGENT_BROWSER_STUB_LOG" || fail "wrapper did not forward click"+grep -Fq -- "--engine chrome --args --no-proxy-server open about:blank" "$AGENT_BROWSER_STUB_LOG" ||+ fail "wrapper did not forward global flags"++node - "$trace_flags" << 'JS'+const fs = require('fs');+const event = JSON.parse(fs.readFileSync(process.argv[2], 'utf8').trim());+if (event.agentBrowser.command !== 'open') {+ throw new Error(`expected open command, got ${event.agentBrowser.command}`);+}+if (event.klm.category !== 'navigation') {+ throw new Error(`expected navigation category, got ${event.klm.category}`);+}+JS++# A failing agent-browser must not look like a successful step: the wrapper has to+# echo the browser's own diagnostic and charge the atom no interaction cost.+cat > "$tmp_dir/bin/agent-browser" << 'SH'+#!/usr/bin/env bash+echo "โ Element not found." >&2+exit 1+SH+chmod +x "$tmp_dir/bin/agent-browser"++trace_fail="$tmp_dir/fail-trace.jsonl"+set +e+fail_output="$(node "$WRAPPER" --klm-trace "$trace_fail" --klm-phase nav --session app click @e9 2>&1)"+fail_code=$?+set -e++[ "$fail_code" -eq 1 ] || fail "expected exit 1 from failing agent-browser, got $fail_code"+case "$fail_output" in+ *"Element not found"*) ;;+ *) fail "wrapper swallowed the agent-browser diagnostic: <$fail_output>" ;;+esac++node - "$trace_fail" << 'JS'+const fs = require('fs');+const event = JSON.parse(fs.readFileSync(process.argv[2], 'utf8').trim());+if (event.exitCode !== 1) throw new Error(`expected exitCode 1, got ${event.exitCode}`);+if (event.klm.category !== 'blocked') {+ throw new Error(`a failed command must be blocked, got ${event.klm.category}`);+}+if (event.klm.operators.P !== 0 || event.klm.operators.K !== 0) {+ throw new Error('a failed click must not be charged pointer/keystroke cost');+}+if (!String(event.stderr).includes('Element not found')) {+ throw new Error('captured stderr missing from the trace atom');+}+JS++echo "agent-browser KLM tests passed"diff --git a/apps/cli/skills/agent-testing/scripts/capture-app-window.sh b/apps/cli/skills/agent-testing/scripts/capture-app-window.shnew file mode 100755index 00000000000..5a04cd19c2a--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/capture-app-window.sh@@ -0,0 +1,65 @@+#!/usr/bin/env bash+#+# capture-app-window.sh โ Capture a screenshot of a specific app window+#+# Uses CGWindowList via Swift to find the window by process name, then+# screencapture -l <windowID> to capture only that window.+# Falls back to full-screen capture if the window is not found.+#+# Usage:+# ./capture-app-window.sh <process_name> <output_path>+#+# Arguments:+# process_name โ The process/owner name as shown in Activity Monitor+# (e.g., "Discord", "Slack", "Telegram", "WeChat", "QQ", "Lark")+# output_path โ Path to save the screenshot (e.g., /tmp/screenshot.png)+#+# Examples:+# ./capture-app-window.sh "Discord" /tmp/discord.png+# ./capture-app-window.sh "Slack" /tmp/slack.png+# ./capture-app-window.sh "ๅพฎไฟก" /tmp/wechat.png+#+set -euo pipefail++PROCESS="${1:?Usage: capture-app-window.sh <process_name> <output_path>}"+OUTPUT="${2:?Usage: capture-app-window.sh <process_name> <output_path>}"++# Preflight: OS screen capture returns a fully-black image when Screen Recording+# permission is missing OR the display is asleep/locked/screensavered. Fail fast with+# remediation instead of silently writing a black artifact. Set SKIP_SCREEN_CHECK=1 to bypass.+if [ "${SKIP_SCREEN_CHECK:-0}" != "1" ]; then+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+ if ! "$SCRIPT_DIR/check-screen-recording.sh"; then+ echo "[capture] Aborting: OS screen capture would be black. Fix the above, or wrap the run in 'caffeinate -dimsu' to keep the display awake." >&2+ exit 1+ fi+fi++# Find the CGWindowID for the target process using Swift + CGWindowList+# Pass process name via environment variable (swift -e doesn't support -- args)+WINDOW_ID=$(TARGET_PROCESS="$PROCESS" swift -e '+import Cocoa+import Foundation+let target = ProcessInfo.processInfo.environment["TARGET_PROCESS"] ?? ""+let windowList = CGWindowListCopyWindowInfo([.optionAll], kCGNullWindowID) as! [[String: Any]]+for w in windowList {+ let owner = w["kCGWindowOwnerName"] as? String ?? ""+ let layer = w["kCGWindowLayer"] as? Int ?? -1+ let bounds = w["kCGWindowBounds"] as? [String: Any] ?? [:]+ let ww = bounds["Width"] as? Double ?? 0+ let wh = bounds["Height"] as? Double ?? 0+ let wid = w["kCGWindowNumber"] as? Int ?? 0+ // Match process name, normal window layer (0), and reasonable size+ if owner == target && layer == 0 && ww > 200 && wh > 200 {+ print(wid)+ break+ }+}+' 2>/dev/null || true)++if [ -n "$WINDOW_ID" ]; then+ screencapture -l "$WINDOW_ID" -x "$OUTPUT"+else+ echo "[capture] Warning: Could not find window for '$PROCESS', falling back to full screen"+ screencapture -x "$OUTPUT"+fidiff --git a/apps/cli/skills/agent-testing/scripts/cdp-capture.cjs b/apps/cli/skills/agent-testing/scripts/cdp-capture.cjsnew file mode 100755index 00000000000..cdbd16b0d60--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/cdp-capture.cjs@@ -0,0 +1,166 @@+#!/usr/bin/env node+// cdp-capture.cjs โ capture a screenshot from a CDP target via RAW DevTools protocol,+// bypassing the agent-browser daemon. Proven reliable against headful Electron/Chrome+// regardless of display sleep or window minimization/occlusion (Page.captureScreenshot+// forces a compositor frame). Every CDP call is hard-timeout guarded so a stall fails+// fast instead of wedging anything.+//+// Usage: node cdp-capture.cjs --port 9222 --out shot.png [--full] [--target-url <substr>] [--timeout 12000]+// Prints one line of JSON: {"ok":true,"bytes":N,"ms":N,"targetUrl":"..."} or {"ok":false,"error":"..."}+// Exit 0 on success, non-zero on failure/timeout.+//+// Requires the `ws` package to be resolvable from this file's own location โ+// Node's require() walks up ancestor node_modules automatically, so this works+// whether the skill ships inside @lobehub/cli's own node_modules or a hoisted+// monorepo root; no manual NODE_PATH wiring needed. A `lh verify install`-copied+// skill dir lives inside a consumer repo's harness skills dir, though, so the+// ancestor walk from there never reaches @lobehub/cli's node_modules โ fall+// back to the `cliRoot` recorded in the sibling `.skill-meta.json`.++const http = require('node:http');+const fs = require('node:fs');+const path = require('node:path');++function resolveWs() {+ const attempted = [];+ try {+ return require('ws');+ } catch {+ attempted.push('ancestor node_modules walk from ' + __filename);+ }++ const markerDir = path.join(__dirname, '..');+ const metaPath = path.join(markerDir, '.skill-meta.json');+ let cliRoot;+ try {+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));+ cliRoot = meta && meta.cliRoot;+ if (cliRoot && !path.isAbsolute(cliRoot)) {+ cliRoot = path.resolve(markerDir, cliRoot);+ }+ } catch {+ attempted.push(metaPath + ' (missing or unreadable)');+ }++ if (cliRoot) {+ // createRequire, not a hand-built <cliRoot>/node_modules/ws path: pnpm+ // links a package's deps NEXT TO it (.pnpm/<pkg>@<v>/node_modules/ws),+ // so only Node's real resolution walk anchored inside cliRoot finds ws+ // across both npm and pnpm layouts.+ try {+ return require('node:module').createRequire(path.join(cliRoot, 'package.json'))('ws');+ } catch {+ attempted.push("createRequire('ws') from " + cliRoot + ' (via .skill-meta.json cliRoot)');+ }+ }++ console.log(+ JSON.stringify({+ ok: false,+ error:+ "Cannot find module 'ws'. Tried: " ++ attempted.join('; ') ++ ". This script requires the 'ws' package to be resolvable " ++ 'from its own install location (a dependency of @lobehub/cli, or installed ' ++ "alongside it). Run 'npm install ws' in the consuming project if using this " ++ 'script standalone.',+ }),+ );+ process.exit(7);+}++const WebSocket = resolveWs();++const arg = (k, d) => {+ const i = process.argv.indexOf(k);+ return i > -1 ? process.argv[i + 1] : d;+};+const has = (k) => process.argv.includes(k);+const PORT = parseInt(arg('--port', '9222'), 10);+const OUT = arg('--out', '/tmp/cdp-capture.png');+const FULL = has('--full');+const TURL = arg('--target-url', '');+const TIMEOUT = parseInt(arg('--timeout', '12000'), 10);++const done = (obj, code) => {+ console.log(JSON.stringify(obj));+ process.exit(code);+};+const httpGet = (path) =>+ new Promise((res, rej) => {+ const req = http.get({ host: '127.0.0.1', port: PORT, path }, (r) => {+ let d = '';+ r.on('data', (c) => (d += c));+ r.on('end', () => {+ try {+ res(JSON.parse(d));+ } catch (e) {+ rej(e);+ }+ });+ });+ req.on('error', rej);+ req.setTimeout(4000, () =>+ req.destroy(+ new Error(+ 'CDP HTTP timeout โ is the app running with --remote-debugging-port=' + PORT + '?',+ ),+ ),+ );+ });++function client(url) {+ const ws = new WebSocket(url, { maxPayload: 512 * 1024 * 1024 });+ const pending = new Map();+ let id = 0;+ const ready = new Promise((r, j) => {+ ws.on('open', r);+ ws.on('error', j);+ });+ ws.on('message', (m) => {+ const o = JSON.parse(m);+ if (o.id && pending.has(o.id)) {+ pending.get(o.id)(o);+ pending.delete(o.id);+ }+ });+ const send = (method, params = {}, timeout = TIMEOUT) =>+ new Promise((res, rej) => {+ const myid = ++id;+ pending.set(myid, (o) =>+ o.error ? rej(new Error(method + ': ' + o.error.message)) : res(o.result),+ );+ ws.send(JSON.stringify({ id: myid, method, params }));+ setTimeout(() => {+ if (pending.has(myid)) {+ pending.delete(myid);+ rej(new Error('TIMEOUT ' + method + ' after ' + timeout + 'ms'));+ }+ }, timeout);+ });+ return { ws, ready, send };+}++(async () => {+ const targets = await httpGet('/json');+ const pages = targets.filter((t) => t.type === 'page' && t.webSocketDebuggerUrl);+ const page = TURL ? pages.find((t) => (t.url || '').includes(TURL)) : pages[0];+ if (!page) throw new Error('no page target found' + (TURL ? ' matching "' + TURL + '"' : ''));+ const pg = client(page.webSocketDebuggerUrl);+ await pg.ready;+ let params = { format: 'png' };+ if (FULL) {+ const m = await pg.send('Page.getLayoutMetrics', {});+ const s = m.cssContentSize || m.contentSize;+ params = {+ format: 'png',+ captureBeyondViewport: true,+ clip: { x: 0, y: 0, width: Math.ceil(s.width), height: Math.ceil(s.height), scale: 1 },+ };+ }+ const t0 = Date.now();+ const r = await pg.send('Page.captureScreenshot', params);+ const buf = Buffer.from(r.data, 'base64');+ fs.writeFileSync(OUT, buf);+ done({ ok: true, bytes: buf.length, ms: Date.now() - t0, targetUrl: page.url }, 0);+})().catch((e) => done({ ok: false, error: e.message }, 1));diff --git a/apps/cli/skills/agent-testing/scripts/cdp-screenshot.sh b/apps/cli/skills/agent-testing/scripts/cdp-screenshot.shnew file mode 100755index 00000000000..cd37a93e844--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/cdp-screenshot.sh@@ -0,0 +1,83 @@+#!/usr/bin/env bash+#+# cdp-screenshot.sh โ Reliable Electron/Chrome screenshot via RAW CDP (bypasses the+# agent-browser daemon) + optional preflight verdict.+#+# Why this exists: agent-browser's `screenshot` goes through a long-lived daemon that+# can wedge ("CDP response channel closed" / "daemon busy") after an interrupted or+# mis-invoked capture โ and once wedged, every later screenshot fails while eval/get+# still work. Raw `Page.captureScreenshot` is fast (~60ms) and robust: it forces a+# compositor frame, so it works even when the DISPLAY IS ASLEEP or the WINDOW IS+# MINIMIZED/OCCLUDED (both verified). Use this instead of `agent-browser screenshot`+# for Electron evidence, and as a preflight to prove capture works before relying on it.+#+# Usage:+# ./cdp-screenshot.sh [--port 9222] [--out shot.png] [--full] [--target-url <substr>] [--check]+#+# --check preflight mode: capture a throwaway frame, verify it is non-black,+# print a PASS/FAIL verdict. Exit 0 only if a real frame was captured.+#+# Exit codes: 0 ok ยท 5 capture failed/timeout ยท 6 captured but BLACK ยท 7 node/dependency missing+set -uo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+PORT=9222; OUT=""; CHECK=0; PASS=()+while [ $# -gt 0 ]; do+ case "$1" in+ --port) PORT="$2"; shift 2 ;;+ --out) OUT="$2"; shift 2 ;;+ --check) CHECK=1; shift ;;+ --full|--target-url) PASS+=("$1"); [ "$1" = "--target-url" ] && { PASS+=("$2"); shift; }; shift ;;+ *) PASS+=("$1"); shift ;;+ esac+done+[ -z "$OUT" ] && OUT="${TMPDIR:-/tmp}/cdp-shot-$PORT.png"++command -v node >/dev/null 2>&1 || { echo "[cdp-shot] node not found"; exit 7; }++# cdp-capture.cjs resolves the `ws` package itself via Node's normal ancestor+# node_modules lookup from its own file location โ no NODE_PATH plumbing needed.+res="$(node "$SCRIPT_DIR/cdp-capture.cjs" --port "$PORT" --out "$OUT" --timeout 12000 ${PASS[@]+"${PASS[@]}"} 2>&1)"+ok="$(printf '%s' "$res" | sed -n 's/.*"ok":\([a-z]*\).*/\1/p')"++if [ "$ok" != "true" ]; then+ case "$res" in+ *"Cannot find module 'ws'"*)+ echo "[cdp-shot] MISSING DEPENDENCY: $res"+ exit 7+ ;;+ esac+ echo "[cdp-shot] CAPTURE FAILED: $res"+ echo "[cdp-shot] Fix: ensure the app runs with --remote-debugging-port=$PORT and CDP is reachable (curl 127.0.0.1:$PORT/json/version). If agent-browser wedged the session earlier, reset it: 'agent-browser close --all'. Raw CDP here does not use that daemon."+ exit 5+fi++# blackness verdict (sips + python3; skip silently if unavailable)+verdict="unknown"; maxv=""+if command -v sips >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then+ sips -z 16 16 "$OUT" --out "$OUT.s.png" >/dev/null 2>&1+ sips -s format bmp "$OUT.s.png" --out "$OUT.bmp" >/dev/null 2>&1+ maxv="$(python3 - "$OUT.bmp" <<'PY' 2>/dev/null || echo -1+import sys+d=open(sys.argv[1],'rb').read();off=int.from_bytes(d[10:14],'little');w=int.from_bytes(d[18:22],'little');h=abs(int.from_bytes(d[22:26],'little',signed=True))+bpp=int.from_bytes(d[28:30],'little') or 24;B=bpp//8;row=((w*bpp+31)//32)*4;mx=0+for y in range(h):+ for x in range(w):+ q=off+y*row+x*B+ if q+2<len(d): mx=max(mx,d[q],d[q+1],d[q+2])+print(mx)+PY+)"+ rm -f "$OUT.s.png" "$OUT.bmp" 2>/dev/null+ [[ "$maxv" =~ ^[0-9]+$ ]] && { (( maxv < 12 )) && verdict="black" || verdict="live"; }+fi++if [ "$verdict" = "black" ]; then+ echo "[cdp-shot] CAPTURED BUT BLACK ($res). Unusual for CDP โ check the page actually rendered (not a blank route)."+ [ "$CHECK" = "1" ] && exit 6+ exit 6+fi++echo "[cdp-shot] OK ($res)${maxv:+ maxBrightness=$maxv}"+[ "$CHECK" = "1" ] && { rm -f "$OUT" 2>/dev/null; echo "[cdp-shot] PREFLIGHT PASS โ CDP screenshot works on port $PORT."; }+exit 0diff --git a/apps/cli/skills/agent-testing/scripts/check-screen-recording.sh b/apps/cli/skills/agent-testing/scripts/check-screen-recording.shnew file mode 100755index 00000000000..0aa88278aca--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/check-screen-recording.sh@@ -0,0 +1,144 @@+#!/usr/bin/env bash+#+# check-screen-recording.sh โ Preflight gate for OS-level screen capture (macOS).+#+# OS screenshots (`screencapture`, osascript, bot-channel captures) come out+# ENTIRELY BLACK when either:+# 1. Screen Recording (TCC) permission is not granted to the responsible app, or+# 2. the display is asleep / locked / running a screensaver (permission is fine+# but there is nothing lit to capture โ common after a long idle test run).+# A black artifact is easy to mistake for a real capture, so gate on this BEFORE+# any OS-capture step. CDP-based evidence (agent-browser screenshot, record-app-screen)+# renders from the browser engine and is NOT affected โ this check is only for the+# OS-capture surfaces (bot tests, capture-app-window.sh, osascript screenshots).+#+# Usage:+# ./check-screen-recording.sh # human-readable; exit 0 if OS capture will work+# ./check-screen-recording.sh --json # machine-readable one-line JSON+#+# Exit codes:+# 0 OS capture works (permission granted AND a live, non-black frame captured)+# 0 non-macOS (OS capture N/A โ use CDP evidence)+# 3 permission NOT granted โ grant Screen Recording, then restart the app+# 4 permission ok but frame BLACK โ wake/unlock display, quit screensaver, or restart app+# 2 could not determine (no screencapture/toolchain)+#+set -uo pipefail++JSON=0+for a in "$@"; do case "$a" in --json) JSON=1 ;; esac; done++emit() { # $1=ok(true/false) $2=perm $3=capture $4=exit $5=message [$6=app]+ if [[ $JSON == 1 ]]; then+ printf '{"platform":"%s","ok":%s,"permission":"%s","capture":"%s","responsibleApp":"%s","message":"%s"}\n' \+ "$(uname -s)" "$1" "${2:-unknown}" "${3:-unknown}" "${6:-}" "$5"+ else+ echo "[screen-recording] $5"+ fi+ exit "$4"+}++os=$(uname -s)+if [[ "$os" != "Darwin" ]]; then+ emit true "n/a" "n/a" 0 "non-macOS ($os): OS screen capture N/A; CDP-based evidence is unaffected. OK."+fi++# --- responsible app: TCC attributes Screen Recording to the ancestor .app bundle ---+responsible_app() {+ local pid=$$ ppid comm+ for _ in $(seq 1 12); do+ if ! read -r ppid comm < <(ps -o ppid=,comm= -p "$pid" 2>/dev/null); then break; fi+ [[ -z "${ppid:-}" ]] && break+ if [[ "$comm" == *.app/Contents/MacOS/* ]]; then+ local app="${comm%%.app/*}"; echo "${app##*/}.app"; return 0+ fi+ [[ "${ppid:-0}" -le 1 ]] && break+ pid=$ppid+ done+ echo "${TERM_PROGRAM:-your terminal app}"+}+APP="$(responsible_app)"++# --- layer 1: TCC permission via CGPreflightScreenCaptureAccess (no prompt, no display) ---+perm="unknown"+bin="${TMPDIR:-/tmp}/lobehub-scrcheck"+if [[ ! -x "$bin" ]] && command -v clang >/dev/null 2>&1; then+ src="${TMPDIR:-/tmp}/lobehub-scrcheck.c"+ cat > "$src" <<'EOF'+#include <CoreGraphics/CoreGraphics.h>+#include <stdio.h>+int main(void){ bool ok = CGPreflightScreenCaptureAccess(); printf(ok?"granted\n":"denied\n"); return ok?0:1; }+EOF+ clang -framework CoreGraphics -o "$bin" "$src" 2>/dev/null || rm -f "$bin"+fi+if [[ -x "$bin" ]]; then+ perm="$("$bin" 2>/dev/null || echo denied)"+elif command -v swift >/dev/null 2>&1; then+ perm="$(swift - <<'EOF' 2>/dev/null || echo denied+import CoreGraphics+print(CGPreflightScreenCaptureAccess() ? "granted" : "denied")+EOF+)"+fi++# --- layer 2: liveness โ capture one real frame and detect a fully-black image ---+# Uses the brightest pixel across a downscaled grid: a live desktop always has some+# lit chrome (menu bar / cursor / window), a blocked/asleep capture is uniformly ~0.+capture="unknown"; maxv=""+if command -v screencapture >/dev/null 2>&1; then+ shot="${TMPDIR:-/tmp}/lobehub-scrlive.png"+ small="${TMPDIR:-/tmp}/lobehub-scrlive.bmp"+ rm -f "$shot" "$small"+ screencapture -x "$shot" 2>/dev/null || true+ if [[ -s "$shot" ]] && command -v sips >/dev/null 2>&1 && command -v python3 >/dev/null 2>&1; then+ sips -z 16 16 "$shot" --out "${shot}.s.png" >/dev/null 2>&1+ sips -s format bmp "${shot}.s.png" --out "$small" >/dev/null 2>&1+ if [[ -s "$small" ]]; then+ maxv="$(python3 - "$small" <<'PY' 2>/dev/null || echo -1+import sys+d=open(sys.argv[1],'rb').read()+off=int.from_bytes(d[10:14],'little')+w=int.from_bytes(d[18:22],'little')+h=abs(int.from_bytes(d[22:26],'little',signed=True))+bpp=int.from_bytes(d[28:30],'little') or 24+Bpp=bpp//8+row=((w*bpp+31)//32)*4+mx=0+for y in range(h):+ base=off+y*row+ for x in range(w):+ p=base+x*Bpp+ if p+2 < len(d):+ mx=max(mx, d[p], d[p+1], d[p+2])+print(mx)+PY+)"+ if [[ "${maxv:-}" =~ ^[0-9]+$ ]]; then+ # brightest channel < 12/255 across the whole screen โ effectively black+ if (( maxv < 12 )); then capture="black"; else capture="live"; fi+ fi+ fi+ fi+ rm -f "$shot" "${shot}.s.png" "$small" 2>/dev/null || true+fi++# --- decision ---+if [[ "$capture" == "live" ]]; then+ emit true "$perm" "$capture" 0 "OK โ Screen Recording works (permission granted, display live). OS captures and bot tests will render real frames." "$APP"+fi++if [[ "$capture" == "black" ]]; then+ if [[ "$perm" == "denied" ]]; then+ emit false "$perm" "$capture" 3 "BLOCKED โ Screen Recording permission is NOT granted to '$APP'. Enable it in: System Settings โธ Privacy & Security โธ Screen Recording โธ turn ON '$APP', then FULLY QUIT & reopen '$APP' (TCC only takes effect on a fresh launch). Until then every OS screenshot/recording and bot test will be BLACK." "$APP"+ fi+ emit false "$perm" "$capture" 4 "BLACK FRAME โ permission looks OK but the capture is black. The display is likely asleep / locked / on a screensaver, or '$APP' was just granted permission but not restarted. Wake & unlock the display, disable the screensaver for the test run (caffeinate -d), or restart '$APP', then re-run this check." "$APP"+fi++# capture couldn't be measured โ fall back to the permission verdict+if [[ "$perm" == "denied" ]]; then+ emit false "$perm" "$capture" 3 "BLOCKED โ Screen Recording permission is NOT granted to '$APP'. Enable it: System Settings โธ Privacy & Security โธ Screen Recording โธ turn ON '$APP', then fully quit & reopen '$APP'." "$APP"+elif [[ "$perm" == "granted" ]]; then+ emit true "$perm" "$capture" 0 "Permission granted for '$APP'; could not verify a live frame (no screencapture/sips/python3). Proceeding โ if OS captures come out black, wake/unlock the display." "$APP"+else+ emit false "$perm" "$capture" 2 "UNDETERMINED โ could not check Screen Recording permission or capture a test frame (missing clang/swift/screencapture). Verify manually in System Settings โธ Privacy & Security โธ Screen Recording for '$APP'." "$APP"+fidiff --git a/apps/cli/skills/agent-testing/scripts/fixture.mjs b/apps/cli/skills/agent-testing/scripts/fixture.mjsnew file mode 100755index 00000000000..e859a18e7c2--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/fixture.mjs@@ -0,0 +1,192 @@+#!/usr/bin/env node+/**+ * fixture.mjs โ reusable per-check fixture assets for agent-testing.+ *+ * Fixtures are the durable half of a verification: for each CHECK ITEM (the+ * business check that recurs across acceptance rounds) we keep one directory+ * holding its plan fragment, case template, seed inputs, and (optionally)+ * replayable steps. Rounds are then COMPOSED from checks instead of hand-writing+ * a fresh result.json every time.+ *+ * INPUTS vs OUTPUTS โ only inputs are reusable. `seed/` holds what a run+ * CONSUMES (files to upload, DB seed fragments, config, stand-in evidence for+ * synthetic ingest rounds). What a run PRODUCES (screenshots, transcripts) is+ * tied to that one execution and lives only in the round dir's assets/ under+ * .records/reports/ โ never copy it back into the fixture.+ *+ * Layout (gitignored, like all .records/ output):+ * .records/fixtures/<subject-key>/<check-id>/+ * โโโ check.json # plan fragment + case template (+ steps for future replay)+ * โโโ seed/ # reusable INPUT assets referenced by check.json / steps+ *+ * <subject-key> = task-<id> | topic-<id> | document-<id> (subject with ':'โ'-'),+ * matching the report group dirs under .records/reports/.+ *+ * Usage:+ * fixture.mjs init-check --subject topic:tpc_xxx <check-id>+ * Scaffold .records/fixtures/topic-tpc_xxx/<check-id>/{check.json,seed/}+ *+ * fixture.mjs compose --subject topic:tpc_xxx --slug <slug> [--title "..."]+ * [--focus "..."] [--entry "..."] <check-id> [<check-id>...]+ * Assemble a report-shaped round dir from the given checks:+ * .records/reports/topic-tpc_xxx/<ts>-<slug>/ (ready for+ * `lh verify ingest-report <dir>`). Files referenced by case.evidence+ * (seed/โฆ) are copied into the round's assets/<check-id>/ and paths+ * rewritten. Prints the dir path.+ *+ * fixture.mjs list --subject topic:tpc_xxx+ * List the subject's check fixtures.+ */+import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';+import path from 'node:path';++const { basename, join } = path;++// The generic skill is invoked from the consumer repository. Keep all+// generated fixtures and reports anchored to that explicit working directory.+const REPO_ROOT = process.cwd();++const fail = (msg) => {+ console.error(`fixture.mjs: ${msg}`);+ process.exit(1);+};++const parseArgs = (argv) => {+ const opts = {};+ const positional = [];+ for (let i = 0; i < argv.length; i++) {+ const arg = argv[i];+ if (arg.startsWith('--')) {+ opts[arg.slice(2)] = argv[++i];+ } else {+ positional.push(arg);+ }+ }+ return { opts, positional };+};++const subjectKey = (subject) => {+ if (!/^(?:task|topic|document):.+$/.test(subject || '')) {+ fail(`--subject must be task:<id> | topic:<id> | document:<id>, got '${subject}'`);+ }+ return subject.replace(':', '-');+};++const [command, ...rest] = process.argv.slice(2);+const { opts, positional } = parseArgs(rest);++if (command === 'init-check') {+ const key = subjectKey(opts.subject);+ const checkId = positional[0] || fail('init-check needs a <check-id>');+ const dir = join(REPO_ROOT, '.records/fixtures', key, checkId);+ if (existsSync(join(dir, 'check.json'))) fail(`${dir}/check.json already exists`);+ mkdirSync(join(dir, 'seed'), { recursive: true });+ const template = {+ id: checkId,+ category: '',+ title: '',+ verifier: 'agent',+ method: '',+ expected: '',+ requiredEvidence: [],+ // Case template used by `compose`: the default verdict + observation this+ // fixture reproduces. Evidence paths point at reusable INPUTS under seed/+ // (relative to this check dir) โ real execution outputs stay in the round.+ case: { result: 'passed', observation: '', evidence: [] },+ // Reserved for the JSON-replay runner: deterministic steps that set up and+ // verify this check without an agent improvising them each round.+ steps: [],+ notes: '',+ };+ writeFileSync(join(dir, 'check.json'), JSON.stringify(template, null, 2) + '\n');+ console.log(dir);+} else if (command === 'list') {+ const key = subjectKey(opts.subject);+ const root = join(REPO_ROOT, '.records/fixtures', key);+ if (!existsSync(root)) fail(`no fixtures under ${root}`);+ for (const entry of readdirSync(root, { withFileTypes: true })) {+ if (!entry.isDirectory()) continue;+ const checkFile = join(root, entry.name, 'check.json');+ if (!existsSync(checkFile)) continue;+ const check = JSON.parse(readFileSync(checkFile, 'utf8'));+ console.log(`${entry.name}\t[${check.category}] ${check.title} โ ${check.case?.result}`);+ }+} else if (command === 'compose') {+ const key = subjectKey(opts.subject);+ const slug = opts.slug || fail('compose needs --slug');+ if (positional.length === 0) fail('compose needs at least one <check-id>');++ const fixturesRoot = join(REPO_ROOT, '.records/fixtures', key);+ const now = new Date();+ const pad = (n) => String(n).padStart(2, '0');+ const ts = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;+ const dir = join(REPO_ROOT, '.records/reports', key, `${ts}-${slug}`);+ mkdirSync(join(dir, 'assets'), { recursive: true });++ const plan = [];+ const cases = [];+ for (const checkId of positional) {+ const checkDir = join(fixturesRoot, checkId);+ const checkFile = join(checkDir, 'check.json');+ if (!existsSync(checkFile)) fail(`missing ${checkFile} (run init-check first)`);+ const check = JSON.parse(readFileSync(checkFile, 'utf8'));++ plan.push({+ id: check.id,+ category: check.category,+ title: check.title,+ verifier: check.verifier || 'agent',+ method: check.method,+ expected: check.expected,+ ...(check.requiredEvidence?.length ? { requiredEvidence: check.requiredEvidence } : {}),+ });++ const evidenceList = [check.case?.evidence ?? []].flat();+ const evidence = evidenceList.map((entry) => {+ const src = typeof entry === 'string' ? entry : entry.path;+ const target = join('assets', check.id, basename(src));+ mkdirSync(join(dir, 'assets', check.id), { recursive: true });+ cpSync(join(checkDir, src), join(dir, target));+ return typeof entry === 'string' ? target : { ...entry, path: target };+ });++ cases.push({+ id: check.id,+ name: check.title,+ result: check.case?.result ?? 'passed',+ observation: check.case?.observation ?? '',+ ...(evidence.length ? { evidence: evidence.length === 1 ? evidence[0] : evidence } : {}),+ });+ }++ const passed = cases.filter((c) => c.result === 'passed').length;+ const failed = cases.filter((c) => c.result === 'failed').length;+ const blocked = cases.filter((c) => c.result === 'blocked').length;+ const result = {+ title: opts.title || slug,+ scenario: 'coding',+ subject: opts.subject,+ context: {+ focus: opts.focus || '',+ entry: opts.entry || '',+ branch: '',+ commit: '',+ },+ surfaces: ['web'],+ plan,+ cases,+ summary: {+ total: cases.length,+ passed,+ failed,+ blocked,+ verdict: failed > 0 ? 'fail' : 'pass',+ conclusion: opts.conclusion || `${passed}/${cases.length} ้่ฟ`,+ },+ };+ writeFileSync(join(dir, 'result.json'), JSON.stringify(result, null, 2) + '\n');+ writeFileSync(join(dir, 'report.md'), `${opts.title || slug}\n`);+ console.log(dir);+} else {+ fail(`unknown command '${command}' (init-check | compose | list)`);+}diff --git a/apps/cli/skills/agent-testing/scripts/record-app-screen.sh b/apps/cli/skills/agent-testing/scripts/record-app-screen.shnew file mode 100755index 00000000000..f5c4f1bd6f7--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/record-app-screen.sh@@ -0,0 +1,188 @@+#!/usr/bin/env bash+#+# record-app-screen.sh โ Record the Electron app window (video + screenshots)+#+# Captures screenshots via agent-browser (CDP), then assembles into video on stop.+# Works on any screen (including external monitors) since it uses CDP, not screen capture.+#+# Usage:+# ./record-app-screen.sh start [output_name] # Begin recording+# ./record-app-screen.sh stop # Stop and save+# ./record-app-screen.sh status # Check recording state+#+# Run this from the CONSUMER repo root โ output goes to .records/ under the+# current working directory, not relative to this script's own location.+#+# Outputs to .records/ directory:+# .records/<name>.mp4 โ Video assembled from screenshots (~2 fps)+# .records/<name>/ โ Screenshots every SCREENSHOT_INTERVAL seconds+#+# Prerequisites:+# - ffmpeg installed (bun add -g ffmpeg-static, or brew install ffmpeg)+# - agent-browser CLI installed+# - Electron app already running with CDP enabled+#+# Environment variables:+# CDP_PORT โ Chrome DevTools Protocol port (default: 9222)+# SCREENSHOT_INTERVAL โ Seconds between gallery screenshots (default: 3)+# VIDEO_FRAME_INTERVAL โ Seconds between video frames (default: 0.5)+#+# Examples:+# record-app-screen.sh start gateway-demo+# # ... run automation via agent-browser ...+# record-app-screen.sh stop+#+set -euo pipefail++RECORDS_DIR="$(pwd)/.records"+PID_FILE="/tmp/record-app-screen.pids"+STATE_FILE="/tmp/record-app-screen.state"++CDP_PORT="${CDP_PORT:-9222}"+SCREENSHOT_INTERVAL="${SCREENSHOT_INTERVAL:-3}"+VIDEO_FRAME_INTERVAL="${VIDEO_FRAME_INTERVAL:-0.5}"++AB="agent-browser --cdp $CDP_PORT"++# โโโ Commands โโโ++cmd_start() {+ local output_name="${1:-recording-$(date +%Y%m%d-%H%M%S)}"+ local output_video="$RECORDS_DIR/${output_name}.mp4"+ local screenshot_dir="$RECORDS_DIR/${output_name}"+ local frames_dir+ frames_dir=$(mktemp -d /tmp/record-frames-XXXXXX)++ if [ -f "$PID_FILE" ]; then+ echo "[record] A recording is already active. Run '$0 stop' first."+ exit 1+ fi++ mkdir -p "$RECORDS_DIR" "$screenshot_dir"++ # Video frames loop (~2 fps via agent-browser CDP screenshots)+ (+ local idx=0+ while true; do+ local fname+ fname=$(printf "%s/frame_%06d.png" "$frames_dir" "$idx")+ $AB screenshot "$fname" 2>/dev/null || true+ idx=$((idx + 1))+ sleep "$VIDEO_FRAME_INTERVAL"+ done+ ) &+ local frames_pid=$!++ # Gallery screenshots loop (every N seconds for human review)+ (+ local idx=0+ while true; do+ local fname+ fname=$(printf "%s/%04d.png" "$screenshot_dir" "$idx")+ $AB screenshot "$fname" 2>/dev/null || true+ idx=$((idx + 1))+ sleep "$SCREENSHOT_INTERVAL"+ done+ ) &+ local screenshot_pid=$!++ # Save state+ echo "$frames_pid $screenshot_pid" > "$PID_FILE"+ echo "$output_video $frames_dir $screenshot_dir" > "$STATE_FILE"++ echo "[record] Started!"+ echo " Video frames: every ${VIDEO_FRAME_INTERVAL}s (PID $frames_pid)"+ echo " Screenshots: every ${SCREENSHOT_INTERVAL}s โ $screenshot_dir/"+ echo " Stop with: $0 stop"+}++cmd_stop() {+ if [ ! -f "$PID_FILE" ] || [ ! -f "$STATE_FILE" ]; then+ echo "[record] No active recording found."+ return 0+ fi++ local frames_pid screenshot_pid+ read -r frames_pid screenshot_pid < "$PID_FILE"++ local output_video frames_dir screenshot_dir+ read -r output_video frames_dir screenshot_dir < "$STATE_FILE"++ # Stop both capture loops+ kill "$frames_pid" 2>/dev/null || true+ kill "$screenshot_pid" 2>/dev/null || true+ wait "$frames_pid" 2>/dev/null || true+ wait "$screenshot_pid" 2>/dev/null || true++ # Assemble frames into video+ local frame_count+ frame_count=$(ls -1 "$frames_dir"/frame_*.png 2>/dev/null | wc -l | tr -d ' ')++ if [ "$frame_count" -gt 0 ]; then+ echo "[record] Assembling $frame_count frames into video..."+ ffmpeg -y -framerate 2 -i "$frames_dir/frame_%06d.png" \+ -c:v libx264 -crf 23 -pix_fmt yuv420p -an \+ "$output_video" > /tmp/ffmpeg-assemble.log 2>&1++ if [ ! -s "$output_video" ]; then+ echo " [warn] Video assembly failed. Check /tmp/ffmpeg-assemble.log"+ echo " Frames preserved in: $frames_dir/"+ fi+ else+ echo " [warn] No frames captured."+ fi++ rm -rf "$frames_dir" 2>/dev/null+ rm -f "$PID_FILE" "$STATE_FILE"++ local video_size screenshot_count+ video_size=$(ls -lh "$output_video" 2>/dev/null | awk '{print $5}' || echo "?")+ screenshot_count=$(ls -1 "$screenshot_dir"/*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")++ echo "[record] Stopped!"+ echo " Video: $output_video ($video_size)"+ echo " Screenshots: ${screenshot_count} files in $screenshot_dir/"+ echo " Play: open $output_video"+}++cmd_status() {+ if [ ! -f "$PID_FILE" ]; then+ echo "[record] No active recording."+ return 0+ fi++ local frames_pid screenshot_pid+ read -r frames_pid screenshot_pid < "$PID_FILE"++ local frames_ok="no" screenshot_ok="no"+ kill -0 "$frames_pid" 2>/dev/null && frames_ok="yes"+ kill -0 "$screenshot_pid" 2>/dev/null && screenshot_ok="yes"++ if [ -f "$STATE_FILE" ]; then+ local output_video frames_dir screenshot_dir+ read -r output_video frames_dir screenshot_dir < "$STATE_FILE"+ local frame_count ss_count+ frame_count=$(ls -1 "$frames_dir"/frame_*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")+ ss_count=$(ls -1 "$screenshot_dir"/*.png 2>/dev/null | wc -l | tr -d ' ' || echo "0")+ echo "[record] Active recording"+ echo " Frames: $frame_count captured (running: $frames_ok)"+ echo " Screenshots: $ss_count captured (running: $screenshot_ok)"+ echo " Output: $output_video"+ fi+}++# โโโ Main โโโ++case "${1:-}" in+ start) shift; cmd_start "$@" ;;+ stop) cmd_stop ;;+ status) cmd_status ;;+ *)+ echo "Usage: $0 {start [name] | stop | status}"+ echo ""+ echo " start [name] Start recording (default: recording-YYYYMMDD-HHMMSS)"+ echo " stop Stop recording and save outputs"+ echo " status Check if recording is active"+ exit 1+ ;;+esacdiff --git a/apps/cli/skills/agent-testing/scripts/record-gif.sh b/apps/cli/skills/agent-testing/scripts/record-gif.shnew file mode 100755index 00000000000..d352c3c9e1b--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/record-gif.sh@@ -0,0 +1,61 @@+#!/usr/bin/env bash+# record-gif.sh โ capture a frame sequence via agent-browser (CDP) and+# synthesize a GIF for embedding in a test report.+#+# Use this whenever the asserted behavior is about CHANGE OVER TIME โ+# streaming output, a ticking timer, loading states, animations. A static+# screenshot cannot prove those; a GIF can. Cloud-portable: frames come from+# CDP rendering, no OS-level screen capture.+#+# Usage:+# record-gif.sh <output.gif> <duration_seconds> [fps]+#+# AB_TARGET="--cdp 9222" # Electron (default; CDP_PORT honored)+# AB_TARGET="--session your-session" # web agent-browser session+# GIF_WIDTH=960 # output width (px), default 960+#+# Requires ffmpeg (`brew install ffmpeg`). Effective fps is capped by+# screenshot latency (~0.3-0.5s per frame); 1-2 fps is the realistic range.+#+# Example โ record a 12s run and embed it in the report:+# ./record-gif.sh "$DIR/assets/case2-tray-running.gif" 12 2 &+# GIF_PID=$!+# # ... trigger the streaming behavior ...+# wait $GIF_PID++set -euo pipefail++OUT="${1:?Usage: record-gif.sh <output.gif> <duration_seconds> [fps]}"+DUR="${2:?Usage: record-gif.sh <output.gif> <duration_seconds> [fps]}"+FPS="${3:-2}"+AB_TARGET="${AB_TARGET:---cdp ${CDP_PORT:-9222}}"+GIF_WIDTH="${GIF_WIDTH:-960}"++command -v ffmpeg > /dev/null || {+ echo "ffmpeg not found โ install with: brew install ffmpeg" >&2+ exit 1+}++TMP=$(mktemp -d)+trap 'rm -rf "$TMP"' EXIT++FRAMES=$((DUR * FPS))+INTERVAL=$(python3 -c "print(1 / $FPS)")++for i in $(seq -f '%04g' 1 "$FRAMES"); do+ # shellcheck disable=SC2086+ agent-browser $AB_TARGET screenshot "$TMP/frame-$i.png" > /dev/null 2>&1 || true+ sleep "$INTERVAL"+done++CAPTURED=$(find "$TMP" -name 'frame-*.png' | wc -l | tr -d ' ')+[ "$CAPTURED" -gt 0 ] || {+ echo "no frames captured โ is the app reachable via $AB_TARGET?" >&2+ exit 1+}++ffmpeg -y -loglevel error -framerate "$FPS" -pattern_type glob -i "$TMP/frame-*.png" \+ -vf "fps=$FPS,scale=$GIF_WIDTH:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse" \+ "$OUT"++echo "$OUT ($CAPTURED frames @ ${FPS}fps)"diff --git a/apps/cli/skills/agent-testing/scripts/report-init.sh b/apps/cli/skills/agent-testing/scripts/report-init.shnew file mode 100755index 00000000000..d2ada73d3d9--- /dev/null+++ b/apps/cli/skills/agent-testing/scripts/report-init.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+# report-init.sh โ scaffold a structured test report under .records/reports/.+#+# Format spec and evidence rules: ../references/report.md+#+# Usage:+# report-init.sh [--subject <type:id>] <slug> [title]+#+# With --subject (task:<id> | topic:<id> | document:<id>) the run is grouped+# under its acceptance:+# .records/reports/<type>-<id>/<YYYYMMDD-HHMMSS>-<slug>/+# and the group directory gets an acceptance.json marker. The subject is also+# pre-filled into result.json so ingest-report attaches the run automatically.+#+# Run this from the CONSUMER repo root โ the report is created relative to the+# current working directory, not relative to this script's own location.+#+# Prints the report directory path (capture it: DIR=$(report-init.sh my-test)).++set -euo pipefail++SUBJECT=""+if [[ "${1:-}" == "--subject" ]]; then+ SUBJECT="${2:?--subject requires a value like topic:tpc_xxx}"+ shift 2+fi++SLUG="${1:?Usage: report-init.sh [--subject <type:id>] <slug> [title]}"+TITLE="${2:-$SLUG}"++json_escape() {+ local s=$1+ s=${s//\\/\\\\}+ s=${s//\"/\\\"}+ s=${s//$'\n'/\\n}+ s=${s//$'\r'/\\r}+ s=${s//$'\t'/\\t}+ printf '%s' "$s"+}++REPO_ROOT="$(pwd)"+TS="$(date +%Y%m%d-%H%M%S)"++SUBJECT_JSON="null"+if [[ -n "$SUBJECT" ]]; then+ if [[ ! "$SUBJECT" =~ ^(task|topic|document):.+$ ]]; then+ echo "report-init.sh: --subject must be task:<id> | topic:<id> | document:<id>, got '$SUBJECT'" >&2+ exit 1+ fi+ SUBJECT_KEY="${SUBJECT/:/-}"+ GROUP_DIR="$REPO_ROOT/.records/reports/$SUBJECT_KEY"+ DIR="$GROUP_DIR/$TS-$SLUG"+ SUBJECT_JSON="\"$(json_escape "$SUBJECT")\""+else+ DIR="$REPO_ROOT/.records/reports/$TS-$SLUG"+fi+mkdir -p "$DIR/assets"++BRANCH=$(git -C "$REPO_ROOT" branch --show-current 2> /dev/null || echo "unknown")+COMMIT=$(git -C "$REPO_ROOT" rev-parse --short HEAD 2> /dev/null || echo "unknown")+DATE_ISO=$(date '+%Y-%m-%dT%H:%M:%S%z')++# acceptance.json records the group identity. The first title names the+# acceptance; later runs update only the timestamp and latest round.+if [[ -n "$SUBJECT" ]]; then+ ACCEPTANCE_JSON="$GROUP_DIR/acceptance.json"+ if [[ ! -f "$ACCEPTANCE_JSON" ]]; then+ cat > "$ACCEPTANCE_JSON" << EOF+{+ "subject": "$(json_escape "$SUBJECT")",+ "title": "$(json_escape "$TITLE")",+ "createdAt": "$(json_escape "$DATE_ISO")",+ "updatedAt": "$(json_escape "$DATE_ISO")",+ "lastRun": "$(json_escape "$TS-$SLUG")"+}+EOF+ else+ node -e '+ const fs = require("fs");+ const [file, run, iso] = process.argv.slice(1);+ const data = JSON.parse(fs.readFileSync(file, "utf8"));+ data.updatedAt = iso;+ data.lastRun = run;+ fs.writeFileSync(file, JSON.stringify(data, null, 2) + "\n");+ ' "$ACCEPTANCE_JSON" "$TS-$SLUG" "$DATE_ISO"+ fi+fi++# report.md is rendered as the verify page's "Details" tail โ free-form COMMENT.+# The scope (่ๅด), per-case table (็จไพ), overall conclusion, and the score are+# all STRUCTURED on the page now (result.json scenario/context + cases ++# summary.conclusion + summary.score), so DON'T repeat any of them here or they+# double up. Keep only non-duplicate detail: repro commands, caveats, follow-ups.+cat > "$DIR/report.md" << EOF+## ๅคๆณจ / ่ฏดๆ++<!-- ๅค็ฐๅฝไปคใๆณจๆไบ้กนใไป้่ท่ฟ้กน๏ผๆฒกๆๅๅโๆ โใไธ่ฆ่ดดๅพ็/GIFโโ่ง่ง่ฏๆฎๆพๅจ+ result.json ็ cases[].evidence ้๏ผ้กต้ขไผๆธฒๆ๏ผreport.md ้้ๅคไผ้ๅคๅฑ็คบใ -->++\`\`\`bash+# command+\`\`\`+EOF++# result.json drives the structured page. \`summary.conclusion\` is the overall+# conclusion shown at the top (under the title); \`summary.score\` (0-100) becomes+# the \`score\` stat; branch/commit/surfaces/entry render the one-line provenance.+#+# \`plan\` is filled BEFORE the run: {id, title, method, expected} per check. It+# shares ids with \`cases\`, so the page pairs intent against outcome and shows a+# planned item that never ran as ๆชๆง่ก rather than dropping it.+#+# \`surfaces\` is a closed set: web | desktop | cli | mobile | bot. It is where a+# check RAN โ not a test kind (unit/backend) and not a runtime mode (packaged+# build / CDP dev instance; that goes on the plan item's \`method\`).+cat > "$DIR/result.json" << EOF+{+ "title": "$(json_escape "$TITLE")",+ "scenario": "coding",+ "createdAt": "$(json_escape "$DATE_ISO")",+ "subject": $SUBJECT_JSON,+ "branch": "$(json_escape "$BRANCH")",+ "commit": "$(json_escape "$COMMIT")",+ "surfaces": [],+ "entry": "",+ "plan": [],+ "cases": [],+ "interactionCost": null,+ "summary": { "total": 0, "passed": 0, "failed": 0, "blocked": 0, "verdict": "pending", "conclusion": "", "score": null }+}+EOF++echo "$DIR"diff --git a/apps/cli/skills/agent-testing/surfaces/cli.md b/apps/cli/skills/agent-testing/surfaces/cli.mdnew file mode 100644index 00000000000..d4650d9b20f--- /dev/null+++ b/apps/cli/skills/agent-testing/surfaces/cli.md@@ -0,0 +1,103 @@+# CLI Backend Verification++Default surface for verifying **backend changes** (routers, services, models,+migrations) end-to-end: fastest loop, text-assertable output, zero UI flakiness.+The project's CLI, its invocation, and its auth all come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) โ this guide is the+methodology, not the commands.++## When to use++- Verifying router / service / model changes end-to-end+- Testing new API fields or response-structure changes+- Validating CLI command output after backend modifications+- Debugging data flow between server and client++## Prerequisites++| Requirement | Where it comes from |+| ----------------- | --------------------------------------------------------------------------------------------------------------- |+| Dev server | `PROJECT.md` ยง2 (base URL/port, start command, health check) |+| Project CLI | `PROJECT.md` ยง4 (how the CLI is invoked โ run-from-source or built binary โ and its standalone install, if any) |+| Auth | `PROJECT.md` ยง3 (test account / seeded key / device-code login) |+| Required services | `PROJECT.md` ยง6 (any queue/worker/store a command path depends on) |++If the CLI runs from source, code changes on the CLI side usually take effect+immediately without a rebuild; if it is a built binary, rebuild per `PROJECT.md`+before re-testing. Confirm which from the adapter.++## Workflow++### 1 โ Server up?++Health-check per `PROJECT.md` ยง2. Server-side code changes require a restart; the+CLI keeps talking to the old process until you restart it.++### 2 โ Auth ready?++Run the CLI auth status check from `PROJECT.md` ยง3. If it is not authed, follow the+adapter's auth path (seeded credential first, interactive/device-code login as+fallback). Drive the login yourself โ do not hand the user the step unless it needs+a secret or device action only they can supply.++### 3 โ Test with CLI commands++Run the project's CLI commands for the behavior under test. Capture output for the+report as you go:++```bash+# $CLI = the project's CLI invocation from PROJECT.md+$CLI some-command | tee "$DIR/assets/case.txt"+```++CLI evidence for the report = the **exact command + trimmed output**. That is a+non-visual artifact, so a link/transcript in the report is fine (unlike UI cases,+which must inline a screenshot).++### 4 โ Clean up test data++Delete any entities the run created (the adapter lists the CLI's delete commands if+the project has them). Leaving fixtures behind pollutes the next run.++### 5 โ Report++Finish with a structured report โ [../references/report.md](../references/report.md).++## Method notes (project-independent)++- **A backend change is still often a UI-visible change.** A permission tightening,+ a new field, a changed error โ the blocked/changed state is something a user+ sees. If the change alters product behavior a user can observe, add a UI case in+ the same run (see [web.md](./web.md) / [electron.md](./electron.md)); do not ship+ a UI-touching change with only CLI transcripts.+- **Prove which runtime ran.** If a command can dispatch to more than one execution+ path (client vs server/queue), confirm the path you intended actually executed โ+ a server operation row, a queue step, or a server-only log line โ before trusting+ a green result.+- **A required service down looks like a logic bug.** If a command path POSTs to a+ queue/worker/store that is not running, the run can fail before any real work+ happens, with an error that reads as unrelated. Gate on the services `PROJECT.md`+ ยง6 marks as prerequisites.++## Dev-test cycle++```+1. Make code changes (service / model / router / type)+ |+2. Run unit tests (fast feedback)+ |+3. Restart dev server (if server-side changes)+ |+4. CLI verification (end-to-end): <cli> <command>+ |+5. Clean up test data + write the report+```++## Troubleshooting++| Issue | Direction |+| --------------------------- | ------------------------------------------------------------------------ |+| `No authentication found` | Re-run the adapter's auth path (ยง3); source any generated credential env |+| `UNAUTHORIZED` on API calls | Re-seed / re-login per ยง3 |+| `ECONNREFUSED` | Dev server not running โ start per ยง2 |+| CLI shows old data/behavior | Server needs a restart to pick up code changes |diff --git a/apps/cli/skills/agent-testing/surfaces/electron.md b/apps/cli/skills/agent-testing/surfaces/electron.mdnew file mode 100644index 00000000000..e9f1d4587c2--- /dev/null+++ b/apps/cli/skills/agent-testing/surfaces/electron.md@@ -0,0 +1,119 @@+# Electron (Desktop) UI Testing++Default surface for verifying **pure frontend changes** (components, store logic,+styles, interactions) in a project that ships an Electron desktop shell. Drives the+Electron renderer over CDP with `agent-browser` โ see+[../references/agent-browser.md](../references/agent-browser.md) for the full+command reference.++The launch/stop of the desktop dev instance, its CDP port, its login persistence,+and any state probes all come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) ยง4/ยง5. This guide is+the CDP methodology; the project supplies the commands.++## Auth++Sign in once, not once per run โ the project's desktop dev tooling should persist+login across runs (`PROJECT.md` ยง3 says how). If an instance still comes up signed+out, **drive the sign-in yourself**; never ask the user to click it. Run the+desktop auth status check from `PROJECT.md` ยง3 before testing.++## Linux / headless (cloud)++Electron runs on Linux but has no true headless mode โ it needs a display server.+In a headless environment wrap the launch with `xvfb-run` (virtual framebuffer).+Everything CDP-based keeps working under Xvfb: the `agent-browser --cdp <port>`+connection, snapshots, eval, and `agent-browser screenshot` (captured from the+renderer via CDP, not the OS screen). What does NOT work on Linux:+`capture-app-window.sh` (macOS `screencapture`), osascript, and OS-level recording.++## Setup / Teardown++Start and stop the desktop dev instance with the project's own script (per+`PROJECT.md` ยง4) โ it should handle process lifecycle and reliably kill all child+processes (main + helpers + bundler). After start succeeds, connect with:++```bash+PORT=9222 # the CDP port from PROJECT.md+agent-browser --cdp "$PORT" snapshot -i+```++**Always run the project's stop command when done** โ a bare `pkill -f "Electron"`+does not catch all helper processes (GPU, renderer, network), which survive and+corrupt the next run.++## Project probes & quick navigation++A project may ship a **state probe** โ a fast path into app state (auth check,+current route, running operations, and a `goto <path>` quick-navigation that jumps+straight to the state under test instead of clicking through the UI). If it does,+`PROJECT.md` ยง5 documents it; use it instead of hand-rolling store-introspection+eval snippets. When the project has no probe, fall back to raw `agent-browser eval`+against the renderer, reading whatever store/global the app exposes for debugging.++For one-off state inspection, `agent-browser eval` against the CDP target is always+available:++```bash+agent-browser --cdp "$PORT" eval --stdin << 'EVALEOF'+(function() { /* read app state here */ })()+EVALEOF+```++## Method notes (project-independent)++- **A running desktop instance may serve a STALE built bundle, not your working+ tree.** A resident/packaged app serves a built renderer snapshot; it does not+ reflect uncommitted or HMR src changes. Verify working-tree UI in an isolated dev+ instance that loads live code, and **prove it is live by measuring a+ known-changed value** (a computed style, a new string) before trusting any+ screenshot. Don't disturb the user's resident instance โ use a separate dev+ instance/port.+- **Main-process code changes need a restart; renderer HMR does not cover them.**+ If the change lives in the main process (or a package that runs there), reloading+ the renderer verifies nothing โ the old main-process code is still running. Prove+ which code each process has (curl the dev bundler for the renderer source and+ grep for a marker; grep the built main bundle for the marker) before trusting a+ run.+- **Distinguish a non-painting renderer from an empty DOM.** `innerText` needs+ layout, `textContent` does not. If a probe reads `innerText.length === 0` while+ `textContent` still holds the full DOM, the DOM is fine and the renderer is not+ compositing โ often after a mid-session bundler dependency re-optimize; a restart+ of the instance clears it, a `location.reload()` alone may not.++## Electron Gotchas++- **`agent-browser screenshot` can wedge the daemon; prefer raw-CDP capture.**+ agent-browser routes captures through a long-lived daemon. An interrupted or+ mis-invoked screenshot can leave the daemon's CDP session half-open, after which+ **every** later screenshot fails (`CDP response channel closed` / `daemon busy`)+ even though `eval` / `get url` still work. This is **not** a display-sleep or+ permission problem: raw `Page.captureScreenshot` is fast and works even when the+ display is asleep or the window is minimized/occluded. Use the raw-CDP helper for+ Electron evidence and as a preflight:++ ```bash+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --check # preflight: PASS โ capture works+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --out shot.png # viewport+ "$SKILL_DIR/scripts/cdp-screenshot.sh" --out full.png --full # full page (captureBeyondViewport)+ ```++ If agent-browser's own screenshot has already wedged, reset it with+ `agent-browser close --all` (raw-CDP does not use that daemon and is unaffected).++- **Dev builds may auto-open DevTools, which hijacks the CDP target** โ+ `agent-browser --cdp <port>` may attach to the DevTools page (`devtools://โฆ`)+ instead of the app. Symptom: `get url` returns a `devtools://` URL. Fix: close the+ DevTools target and reconnect:++ ```bash+ DT_ID=$(curl -s "http://localhost:$PORT/json/list" | python3 -c "import json,sys; ts=json.load(sys.stdin); print(next(t['id'] for t in ts if t['type']=='page' and t['url'].startswith('devtools://')))")+ curl -s "http://localhost:$PORT/json/close/$DT_ID" > /dev/null+ agent-browser close --all && agent-browser --cdp "$PORT" get url # expect the app URL+ ```++- **Don't resize the Electron window after load** โ resizing can trigger a full SPA+ reload and lose your state.++- **Streaming / ticking UI needs GIF evidence** โ see `scripts/record-gif.sh`; a+ static screenshot cannot prove time-based behavior.diff --git a/apps/cli/skills/agent-testing/surfaces/web.md b/apps/cli/skills/agent-testing/surfaces/web.mdnew file mode 100644index 00000000000..9488555f89f--- /dev/null+++ b/apps/cli/skills/agent-testing/surfaces/web.md@@ -0,0 +1,95 @@+# Web (Full-Stack) Testing++Default surface for **full-stack changes** โ a new/changed API plus the UI that+consumes it. The browser is the one surface where network requests and UI state are+observable together, so you can assert both sides of the contract in a single run.++For pure-frontend changes in a project that ships a desktop shell, prefer+[electron.md](./electron.md); for backend-only changes prefer [cli.md](./cli.md).++The base URL, session name, and auth for the web surface come from+[`.agents/verify/PROJECT.md`](../references/project-adapter.md) ยง4/ยง3. This guide is+the methodology.++## Prerequisites++- Complete [Step 2.0](../SKILL.md#20-resolve-the-current-test-environment) (resolve+ ports) and the [Phase 1 approval gate](../SKILL.md#phase-1-approval-gate--report-environment--plan-to-the-user) first.+- Local dev server running โ start command from `PROJECT.md` ยง2.+- Web auth verified in the agent-browser session โ status check and seeding from+ `PROJECT.md` ยง3.++## Option A โ agent-browser with seeded auth (recommended)++Seed/verify the web session per `PROJECT.md` ยง3, then drive it. Use one named+session as the single evidence source:++```bash+SESSION=your-session # session name from PROJECT.md ยง4+BASE_URL=http://localhost:3000 # base URL from PROJECT.md ยง4++agent-browser --session $SESSION open "$BASE_URL/"+agent-browser --session $SESSION snapshot -i+# interact via refs โ full command reference: ../references/agent-browser.md+```++Use this session as the evidence source. Do not use ordinary Chrome screenshots or+Chrome Network records as proof; ordinary Chrome is only a fallback source for+copying cookies into agent-browser when the seeded login is not available.++### Watch the API while driving the UI++```bash+# After triggering the UI action under test:+agent-browser --session $SESSION network requests --type xhr,fetch+agent-browser --session $SESSION network requests --method POST++# Record a full HAR for the report+agent-browser --session $SESSION network har start+# ... drive the scenario ...+agent-browser --session $SESSION network har stop ./capture.har+```++Assert both layers: the request/response shape (network) and the rendered result+(snapshot/screenshot). Both belong in the report as evidence โ the network dump or+HAR as a linked non-visual artifact, the rendered state as an inline screenshot.++## Option B โ real Chrome with remote debugging++For flows that need a real, visible browser (e.g. exercising the login UI itself):++```bash+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \+ --remote-debugging-port=9222 \+ --user-data-dir=/tmp/chrome-test-profile \+ "<URL>" &+sleep 5+agent-browser --cdp 9222 snapshot -i++# Or auto-discover a running Chrome with remote debugging+agent-browser --auto-connect snapshot -i+```++## Method notes (project-independent)++- **Prove the session is live before trusting an auth-scoped result.** An+ owner-only / permission-gated UI fails identically whether the gate is broken or+ the session is simply missing. `document.cookie` is not the probe โ session+ cookies are often httpOnly, so it reads empty on a fully authenticated page.+ Instead call any authed endpoint from the page and read the status: `401` = no+ session reached the server (re-seed), `200` = you are really signed in. Only then+ conclude anything about the gate.+- **The app can swallow an injected fetch failure.** A store action may resolve+ even when the underlying fetch was aborted, so the UI/promise is not a reliable+ signal that your fault landed. Judge interception by the **fetch's own outcome**+ (wrap `window.fetch` and record each request's resolve/reject) โ see+ [../references/probe-mock-patterns.md](../references/probe-mock-patterns.md) A.+- **A cached first-load can mask a failure.** A surface that loaded once caches the+ last-good value; a later failed fetch keeps showing the settled content instead+ of the error. To see a genuine first-load error, cold-load (clear+ localStorage / sessionStorage / IndexedDB / Cache API), which usually logs you+ out โ re-seed auth after. See probe-mock-patterns B.+- **Enumerate every surface a shared component renders on.** A shared input/toolbar+ can be composed differently on the home page vs an inner page; verify each place+ the changed component appears, with separate evidence, and mark any skipped+ surface explicitly.diff --git a/apps/cli/src/commands/verify.ts b/apps/cli/src/commands/verify.tsindex 4570364c977..ea347a852bb 100644--- a/apps/cli/src/commands/verify.ts+++ b/apps/cli/src/commands/verify.ts@@ -23,6 +23,7 @@ import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/forimport { log } from '../utils/logger';import { uploadLocalFile } from '../utils/uploadLocalFile';import { registerAcceptanceCommands } from './verifyAcceptance';+import { registerVerifyInstallCommand } from './verifyInstall';// โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@@ -524,6 +525,11 @@ export function registerVerifyCommand(program: Command) {// `verify acceptance โฆ` โ subject-level acceptance aggregates.registerAcceptanceCommands(verify);+ // `verify install` โ install the bundled agent-testing skill from this CLI+ // package into the consumer repo. Distinct from `verify init` below, which+ // pulls a named skill bundle live from the server.+ registerVerifyInstallCommand(verify);+// โโโโโโโโโโโโ init (materialize the portable verify skill) โโโโโโโโโโโโverify.command('init')diff --git a/apps/cli/src/commands/verifyInstall.test.ts b/apps/cli/src/commands/verifyInstall.test.tsnew file mode 100644index 00000000000..1984b502e6c--- /dev/null+++ b/apps/cli/src/commands/verifyInstall.test.ts@@ -0,0 +1,434 @@+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ HARNESS_SKILL_DIRS,+ isVerifyInstallSuccess,+ NoHarnessDirError,+ registerVerifyInstallCommand,+ runVerifyInstall,+} from './verifyInstall';++const { mockLocateBundledSkill } = vi.hoisted(() => ({+ mockLocateBundledSkill: vi.fn(),+}));+vi.mock('../utils/skillLocator', () => ({ locateBundledSkill: mockLocateBundledSkill }));+vi.mock('../utils/logger', () => ({+ log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },+ setVerbose: vi.fn(),+}));++let root: string;+let bundleDir: string;++function writeBundledSkill(dir: string) {+ mkdirSync(path.join(dir, 'scripts'), { recursive: true });+ writeFileSync(path.join(dir, 'SKILL.md'), '# agent-testing');+ writeFileSync(path.join(dir, 'scripts', 'run.sh'), '#!/bin/sh\necho hi\n');+ writeFileSync(path.join(dir, 'scripts', 'analyze.mjs'), 'console.log(1)');+ writeFileSync(path.join(dir, 'scripts', 'note.txt'), 'not executable');+}++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'verify-install-'));+ bundleDir = path.join(root, '__bundle__', 'agent-testing');+ writeBundledSkill(bundleDir);+ mockLocateBundledSkill.mockReset().mockReturnValue({+ cliRoot: path.join(root, '__bundle__'),+ skillDir: bundleDir,+ version: '1.0.0',+ });+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function makeCwd(): string {+ return mkdtempSync(path.join(root, 'consumer-'));+}++describe('runVerifyInstall โ no harness dir found', () => {+ it('throws NoHarnessDirError listing recognized dirs, without --target', () => {+ const cwd = makeCwd();+ expect(() => runVerifyInstall({ cwd })).toThrow(NoHarnessDirError);+ try {+ runVerifyInstall({ cwd });+ } catch (e) {+ expect((e as Error).message).toContain('.claude/skills');+ expect((e as Error).message).toContain('.codex/skills');+ expect((e as Error).message).toContain('.agents/skills');+ expect((e as Error).message).toContain('--target');+ }+ });+});++describe('runVerifyInstall โ fresh install', () => {+ it('installs into a single existing harness dir', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });++ const result = runVerifyInstall({ cwd });++ expect(result.results).toHaveLength(1);+ expect(result.results[0].status).toBe('installed');+ const target = path.join(cwd, '.claude', 'skills', 'agent-testing');+ expect(result.results[0].target).toBe(target);+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');++ const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));+ expect(meta).toEqual({+ cliRoot: path.join(root, '__bundle__'),+ name: 'agent-testing',+ version: '1.0.0',+ });+ });++ it('cliRoot outside the consumer repo โ marker keeps the absolute path', () => {+ // bundleDir/cliRoot live under `root`, sibling to (not inside) `cwd` โ+ // simulates a global install / npx where @lobehub/cli sits outside the+ // consumer repo entirely.+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });++ const result = runVerifyInstall({ cwd });++ const target = result.results[0].target;+ const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));+ expect(meta.cliRoot).toBe(path.join(root, '__bundle__'));+ expect(path.isAbsolute(meta.cliRoot)).toBe(true);+ });++ it('cliRoot inside the consumer repo โ marker stores a POSIX-relative path from the marker dir', () => {+ // Simulates @lobehub/cli vendored inside the consumer repo itself (e.g.+ // this monorepo): cliRoot sits under cwd, so baking in an absolute path+ // would commit a machine-specific filesystem layout.+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ const inRepoCliRoot = path.join(cwd, 'apps', 'cli');+ mkdirSync(inRepoCliRoot, { recursive: true });+ mockLocateBundledSkill.mockReturnValue({+ cliRoot: inRepoCliRoot,+ skillDir: bundleDir,+ version: '1.0.0',+ });++ const result = runVerifyInstall({ cwd });++ const target = result.results[0].target;+ const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));+ expect(meta.cliRoot).toBe('../../../apps/cli');+ expect(path.isAbsolute(meta.cliRoot)).toBe(false);+ expect(path.resolve(target, meta.cliRoot)).toBe(inRepoCliRoot);+ });++ it('installs into every existing harness dir (multi-harness)', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ mkdirSync(path.join(cwd, '.codex', 'skills'), { recursive: true });+ // .agents/skills intentionally absent++ const result = runVerifyInstall({ cwd });++ expect(result.results.map((r) => r.status)).toEqual(['installed', 'installed']);+ expect(result.results.map((r) => r.target).sort()).toEqual(+ [+ path.join(cwd, '.claude', 'skills', 'agent-testing'),+ path.join(cwd, '.codex', 'skills', 'agent-testing'),+ ].sort(),+ );+ });++ it('re-applies chmod +x to .sh/.mjs/.cjs after copying, leaves other files untouched', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ const result = runVerifyInstall({ cwd });+ const target = result.results[0].target;++ const shMode = statSync(path.join(target, 'scripts', 'run.sh')).mode & 0o777;+ const mjsMode = statSync(path.join(target, 'scripts', 'analyze.mjs')).mode & 0o777;+ expect(shMode & 0o111).toBe(0o111);+ expect(mjsMode & 0o111).toBe(0o111);+ });++ it('respects --target, creating the dir if missing, and does not touch harness dirs', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true }); // present but must be ignored++ const result = runVerifyInstall({ cwd, target: 'custom/skills-dir' });++ expect(result.results).toHaveLength(1);+ const target = path.join(cwd, 'custom', 'skills-dir', 'agent-testing');+ expect(result.results[0].target).toBe(target);+ expect(existsSync(target)).toBe(true);+ expect(existsSync(path.join(cwd, '.claude', 'skills', 'agent-testing'))).toBe(false);+ });+});++describe('runVerifyInstall โ edge cases', () => {+ it('version marker present, bundled version newer โ overwrites skill body', () => {+ const cwd = makeCwd();+ const skillsDir = path.join(cwd, '.claude', 'skills');+ mkdirSync(skillsDir, { recursive: true });+ runVerifyInstall({ cwd }); // installs 1.0.0++ mockLocateBundledSkill.mockReturnValue({+ cliRoot: path.join(root, '__bundle__'),+ skillDir: bundleDir,+ version: '2.0.0',+ });+ writeFileSync(path.join(bundleDir, 'SKILL.md'), '# agent-testing v2');++ const result = runVerifyInstall({ cwd });+ expect(result.results[0].status).toBe('updated');+ const target = path.join(skillsDir, 'agent-testing');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing v2');+ const meta = JSON.parse(readFileSync(path.join(target, '.skill-meta.json'), 'utf8'));+ expect(meta.version).toBe('2.0.0');+ });++ it('marker present, same version โ no-op with message', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ runVerifyInstall({ cwd });++ const result = runVerifyInstall({ cwd });+ expect(result.results[0].status).toBe('no-op');+ });++ it('marker present, bundled version older โ no-op with message', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ mockLocateBundledSkill.mockReturnValue({+ cliRoot: path.join(root, '__bundle__'),+ skillDir: bundleDir,+ version: '5.0.0',+ });+ runVerifyInstall({ cwd }); // installs 5.0.0++ mockLocateBundledSkill.mockReturnValue({+ cliRoot: path.join(root, '__bundle__'),+ skillDir: bundleDir,+ version: '1.0.0',+ });+ const result = runVerifyInstall({ cwd });+ expect(result.results[0].status).toBe('no-op');+ });++ it('target agent-testing dir exists WITHOUT marker โ refuses; --force replaces', () => {+ const cwd = makeCwd();+ const skillsDir = path.join(cwd, '.claude', 'skills');+ const target = path.join(skillsDir, 'agent-testing');+ mkdirSync(target, { recursive: true });+ writeFileSync(path.join(target, 'SKILL.md'), '# hand-written predecessor');++ const refused = runVerifyInstall({ cwd });+ expect(refused.results[0].status).toBe('refused');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# hand-written predecessor');++ const forced = runVerifyInstall({ cwd, force: true });+ expect(forced.results[0].status).toBe('updated');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');+ expect(forced.results[0].message).toBe('replaced unversioned install with 1.0.0');+ });++ it('marker present but with invalid/missing version โ refuses; --force replaces', () => {+ const cwd = makeCwd();+ const skillsDir = path.join(cwd, '.claude', 'skills');+ const target = path.join(skillsDir, 'agent-testing');+ mkdirSync(target, { recursive: true });+ writeFileSync(path.join(target, 'SKILL.md'), '# hand-written predecessor');+ writeFileSync(path.join(target, '.skill-meta.json'), '{}');++ const refused = runVerifyInstall({ cwd });+ expect(refused.results[0].status).toBe('refused');++ const forced = runVerifyInstall({ cwd, force: true });+ expect(forced.results[0].status).toBe('updated');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');+ });++ it('marker from another tool โ refuses instead of trusting its version; --force replaces', () => {+ const cwd = makeCwd();+ const target = path.join(cwd, '.claude', 'skills', 'agent-testing');+ mkdirSync(target, { recursive: true });+ writeFileSync(path.join(target, 'SKILL.md'), '# someone elseโs skill');+ writeFileSync(+ path.join(target, '.skill-meta.json'),+ JSON.stringify({ name: 'other', version: '999.0.0' }),+ );++ const refused = runVerifyInstall({ cwd });+ expect(refused.results[0].status).toBe('refused');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# someone elseโs skill');++ const forced = runVerifyInstall({ cwd, force: true });+ expect(forced.results[0].status).toBe('updated');+ expect(readFileSync(path.join(target, 'SKILL.md'), 'utf8')).toBe('# agent-testing');+ });++ it('consumer cwd not a git repo โ installs anyway, reports isGitRepo: false', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ const result = runVerifyInstall({ cwd });+ expect(result.isGitRepo).toBe(false);+ expect(result.results[0].status).toBe('installed');+ });++ it('cwd is a git repo โ reports isGitRepo: true', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ mkdirSync(path.join(cwd, '.git'), { recursive: true });+ const result = runVerifyInstall({ cwd });+ expect(result.isGitRepo).toBe(true);+ });++ it('no .gitignore at cwd โ creates one containing .records/', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ const result = runVerifyInstall({ cwd });+ expect(result.gitignore.action).toBe('created');+ expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe('.records/\n');+ });++ it('.gitignore without .records/ entry โ appends it, no dupes on re-run', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ writeFileSync(path.join(cwd, '.gitignore'), 'node_modules/\n');++ const result = runVerifyInstall({ cwd });+ expect(result.gitignore.action).toBe('appended');+ const content = readFileSync(path.join(cwd, '.gitignore'), 'utf8');+ expect(content).toBe('node_modules/\n.records/\n');++ const again = runVerifyInstall({ cwd });+ expect(again.gitignore.action).toBe('no-op');+ expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe(content);+ });++ it('.gitignore already covers .records/ โ no-op', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ writeFileSync(path.join(cwd, '.gitignore'), 'dist/\n.records/\n');++ const result = runVerifyInstall({ cwd });+ expect(result.gitignore.action).toBe('no-op');+ expect(readFileSync(path.join(cwd, '.gitignore'), 'utf8')).toBe('dist/\n.records/\n');+ });++ it('never creates or touches .agents/verify/', () => {+ const cwd = makeCwd();+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ const verifyAdapterDir = path.join(cwd, '.agents', 'verify');+ mkdirSync(verifyAdapterDir, { recursive: true });+ writeFileSync(path.join(verifyAdapterDir, 'PROJECT.md'), 'existing adapter content');++ runVerifyInstall({ cwd });++ expect(readFileSync(path.join(verifyAdapterDir, 'PROJECT.md'), 'utf8')).toBe(+ 'existing adapter content',+ );+ expect(existsSync(path.join(cwd, '.agents', 'skills', 'agent-testing'))).toBe(false);+ });+});++describe('isVerifyInstallSuccess', () => {+ it('is true when at least one target installed/updated/no-op', () => {+ expect(isVerifyInstallSuccess([{ message: '', status: 'installed', target: 'a' }])).toBe(true);+ expect(isVerifyInstallSuccess([{ message: '', status: 'no-op', target: 'a' }])).toBe(true);+ expect(+ isVerifyInstallSuccess([+ { message: '', status: 'refused', target: 'a' },+ { message: '', status: 'installed', target: 'b' },+ ]),+ ).toBe(true);+ });++ it('is false when every target refused, or there are no targets', () => {+ expect(isVerifyInstallSuccess([{ message: '', status: 'refused', target: 'a' }])).toBe(false);+ expect(isVerifyInstallSuccess([])).toBe(false);+ });+});++describe('HARNESS_SKILL_DIRS', () => {+ it('lists the three recognized harness dirs', () => {+ expect(HARNESS_SKILL_DIRS).toEqual(['.claude/skills', '.codex/skills', '.agents/skills']);+ });+});++describe('lh verify install โ command registration', () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let cwd: string;+ let cwdSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never);+ cwd = makeCwd();+ cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(cwd);+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ exitSpy.mockRestore();+ cwdSpy.mockRestore();+ });++ const run = async (args: string[]) => {+ const program = new Command();+ program.exitOverride();+ const verify = program.command('verify');+ registerVerifyInstallCommand(verify);+ await program.parseAsync(['node', 'lh', 'verify', ...args]);+ };++ it('is registered as `verify install`, distinct from `verify init`', async () => {+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ await run(['install']);++ expect(existsSync(path.join(cwd, '.claude', 'skills', 'agent-testing', 'SKILL.md'))).toBe(true);+ expect(exitSpy).not.toHaveBeenCalledWith(1);+ });++ it('happy path installs and prints a per-target result line', async () => {+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ await run(['install']);++ const printed = consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(printed).toContain('installed');+ expect(printed).toContain('agent-testing');+ expect(printed).toContain('PROJECT.md');+ });++ it('--json outputs the structured result and exits 0 on success', async () => {+ mkdirSync(path.join(cwd, '.claude', 'skills'), { recursive: true });+ await run(['install', '--json']);++ const out = JSON.parse(consoleSpy.mock.calls.map((c) => String(c[0])).join(''));+ expect(out.results[0].status).toBe('installed');+ expect(exitSpy).toHaveBeenCalledWith(0);+ });++ it('--target installs into the given dir even without a recognized harness dir', async () => {+ await run(['install', '--target', 'custom-dir']);+ expect(existsSync(path.join(cwd, 'custom-dir', 'agent-testing', 'SKILL.md'))).toBe(true);+ });++ it('exits non-zero and logs an error when no harness dir and no --target', async () => {+ await run(['install']);+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+});diff --git a/apps/cli/src/commands/verifyInstall.ts b/apps/cli/src/commands/verifyInstall.tsnew file mode 100644index 00000000000..dc476507d05--- /dev/null+++ b/apps/cli/src/commands/verifyInstall.ts@@ -0,0 +1,276 @@+import {+ chmodSync,+ cpSync,+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import path from 'node:path';++import type { Command } from 'commander';+import pc from 'picocolors';+import semver from 'semver';++import { outputJson } from '../utils/format';+import { log } from '../utils/logger';+import { type BundledSkill, locateBundledSkill } from '../utils/skillLocator';++export const SKILL_NAME = 'agent-testing';+export const HARNESS_SKILL_DIRS = ['.claude/skills', '.codex/skills', '.agents/skills'];+const GITIGNORE_ENTRY = '.records/';+const EXECUTABLE_EXTENSIONS = new Set(['.sh', '.mjs', '.cjs']);++export interface SkillMeta {+ cliRoot: string;+ name: string;+ version: string;+}++export type InstallStatus = 'installed' | 'no-op' | 'refused' | 'updated';++export interface InstallResult {+ message: string;+ status: InstallStatus;+ target: string;+}++export interface VerifyInstallOptions {+ cwd: string;+ force?: boolean;+ target?: string;+}++export interface VerifyInstallResult {+ bundled: BundledSkill;+ gitignore: { action: 'appended' | 'created' | 'no-op'; path: string };+ isGitRepo: boolean;+ results: InstallResult[];+}++export class NoHarnessDirError extends Error {+ constructor(cwd: string) {+ super(+ `No harness skills directory found under ${cwd} ` ++ `(looked for ${HARNESS_SKILL_DIRS.join(', ')}). ` ++ 'Pass --target <dir> to install into a specific directory.',+ );+ this.name = 'NoHarnessDirError';+ }+}++function findHarnessDirs(cwd: string): string[] {+ return HARNESS_SKILL_DIRS.map((d) => path.join(cwd, d)).filter((d) => existsSync(d));+}++function readSkillMeta(skillDir: string): SkillMeta | undefined {+ const metaPath = path.join(skillDir, '.skill-meta.json');+ if (!existsSync(metaPath)) return undefined;+ try {+ const parsed = JSON.parse(readFileSync(metaPath, 'utf8'));+ if (parsed?.name !== SKILL_NAME) return undefined;+ if (!semver.valid(parsed.version)) return undefined;+ return parsed;+ } catch {+ return undefined;+ }+}++function chmodExecutablesRecursive(dir: string): void {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) {+ chmodExecutablesRecursive(full);+ } else if (EXECUTABLE_EXTENSIONS.has(path.extname(entry.name))) {+ chmodSync(full, 0o755);+ }+ }+}++function writeSkillMeta(skillDir: string, meta: SkillMeta): void {+ writeFileSync(path.join(skillDir, '.skill-meta.json'), JSON.stringify(meta, null, 2) + '\n');+}++// The consumer repo may vendor @lobehub/cli inside itself (e.g. this very+// monorepo), in which case cliRoot sits under cwd and an absolute path would+// bake this machine's filesystem layout into a committed marker file. Resolve+// relative to the marker's own directory instead, so the marker stays+// portable across machines and CI. Global installs / npx still resolve+// cliRoot outside the consumer repo, so those keep the absolute path โ there+// is no repo-relative path to express.+function resolveCliRootForMeta(cliRoot: string, cwd: string, targetDir: string): string {+ const relFromCwd = path.relative(cwd, cliRoot);+ const isInsideRepo =+ relFromCwd !== '' && !relFromCwd.startsWith('..') && !path.isAbsolute(relFromCwd);+ if (!isInsideRepo) return cliRoot;++ const relFromTarget = path.relative(targetDir, cliRoot);+ return relFromTarget.split(path.sep).join('/');+}++function installOne(+ harnessDir: string,+ bundled: BundledSkill,+ force: boolean | undefined,+ cwd: string,+): InstallResult {+ const target = path.join(harnessDir, SKILL_NAME);+ const exists = existsSync(target);+ const meta = exists ? readSkillMeta(target) : undefined;++ if (exists && !meta && !force) {+ return {+ message: `${path.join(target, '.skill-meta.json')} is missing or is not a ${SKILL_NAME} marker โ this looks like a hand-written or pre-existing skill dir, refusing to overwrite. Pass --force to replace it.`,+ status: 'refused',+ target,+ };+ }++ if (meta && !force && semver.compare(bundled.version, meta.version) <= 0) {+ return {+ message: `already at version ${meta.version} (bundled: ${bundled.version})`,+ status: 'no-op',+ target,+ };+ }++ if (exists) rmSync(target, { recursive: true, force: true });+ cpSync(bundled.skillDir, target, { recursive: true });+ chmodExecutablesRecursive(target);+ writeSkillMeta(target, {+ cliRoot: resolveCliRootForMeta(bundled.cliRoot, cwd, target),+ name: SKILL_NAME,+ version: bundled.version,+ });++ return {+ message: exists+ ? meta+ ? `updated ${meta.version} โ ${bundled.version}`+ : `replaced unversioned install with ${bundled.version}`+ : `installed ${bundled.version}`,+ status: exists ? 'updated' : 'installed',+ target,+ };+}++function ensureGitignore(cwd: string): { action: 'appended' | 'created' | 'no-op'; path: string } {+ const gitignorePath = path.join(cwd, '.gitignore');+ if (!existsSync(gitignorePath)) {+ writeFileSync(gitignorePath, `${GITIGNORE_ENTRY}\n`);+ return { action: 'created', path: gitignorePath };+ }++ const content = readFileSync(gitignorePath, 'utf8');+ const covered = content+ .split('\n')+ .map((line) => line.trim())+ .some((line) => line === GITIGNORE_ENTRY || line === GITIGNORE_ENTRY.replace(/\/$/, ''));+ if (covered) return { action: 'no-op', path: gitignorePath };++ const needsLeadingNewline = content.length > 0 && !content.endsWith('\n');+ writeFileSync(+ gitignorePath,+ content + (needsLeadingNewline ? '\n' : '') + `${GITIGNORE_ENTRY}\n`,+ );+ return { action: 'appended', path: gitignorePath };+}++export function runVerifyInstall(options: VerifyInstallOptions): VerifyInstallResult {+ const bundled = locateBundledSkill(SKILL_NAME);+ const cwd = options.cwd;++ let targets: string[];+ if (options.target) {+ const resolved = path.resolve(cwd, options.target);+ mkdirSync(resolved, { recursive: true });+ targets = [resolved];+ } else {+ targets = findHarnessDirs(cwd);+ if (targets.length === 0) throw new NoHarnessDirError(cwd);+ }++ const results = targets.map((dir) => installOne(dir, bundled, options.force, cwd));+ const isGitRepo = existsSync(path.join(cwd, '.git'));+ const gitignore = ensureGitignore(cwd);++ return { bundled, gitignore, isGitRepo, results };+}++export function isVerifyInstallSuccess(results: InstallResult[]): boolean {+ return results.some((r) => r.status !== 'refused');+}++// โโ Command Registration โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++const STATUS_GLYPH: Record<InstallStatus, string> = {+ 'installed': pc.green('โ installed'),+ 'no-op': pc.dim('ยท no-op'),+ 'refused': pc.red('โ refused'),+ 'updated': pc.yellow('โ updated'),+};++export function registerVerifyInstallCommand(verify: Command) {+ verify+ .command('install')+ .description(+ "Install the bundled agent-testing skill into this repo's agent skill dirs (.claude/.codex/.agents)",+ )+ .option('--target <dir>', 'Install into a specific directory instead of auto-detecting')+ .option('--force', 'Replace an existing install even without a recognized version marker')+ .option('--json [fields]', 'Output JSON')+ .action(async (options: { force?: boolean; json?: boolean | string; target?: string }) => {+ let result: VerifyInstallResult;+ try {+ result = runVerifyInstall({+ cwd: process.cwd(),+ force: options.force,+ target: options.target,+ });+ } catch (e) {+ if (e instanceof NoHarnessDirError) {+ log.error(e.message);+ process.exit(1);+ return;+ }+ throw e;+ }++ const success = isVerifyInstallSuccess(result.results);++ if (options.json !== undefined) {+ outputJson(result, typeof options.json === 'string' ? options.json : undefined);+ process.exit(success ? 0 : 1);+ return;+ }++ for (const r of result.results) {+ console.log(+ `${STATUS_GLYPH[r.status]} ${pc.dim(path.relative(process.cwd(), r.target) || r.target)} ${pc.dim(`โ ${r.message}`)}`,+ );+ }++ if (!result.isGitRepo) {+ console.log(+ pc.yellow(' (not a git repository โ .records/ hygiene must be handled manually)'),+ );+ }+ if (result.gitignore.action !== 'no-op') {+ console.log(+ pc.dim(+ ` .gitignore ${result.gitignore.action === 'created' ? 'created with' : 'updated with'} ${GITIGNORE_ENTRY}`,+ ),+ );+ }++ console.log(+ pc.dim(+ ' First verification run bootstraps .agents/verify/PROJECT.md โ see the skill docs.',+ ),+ );++ if (!success) process.exit(1);+ });+}diff --git a/apps/cli/src/utils/skillLocator.test.ts b/apps/cli/src/utils/skillLocator.test.tsnew file mode 100644index 00000000000..35ded6fc89f--- /dev/null+++ b/apps/cli/src/utils/skillLocator.test.ts@@ -0,0 +1,104 @@+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { findCliRoot, locateBundledSkill } from './skillLocator';++let root: string;++beforeEach(() => {+ root = mkdtempSync(path.join(tmpdir(), 'skill-locator-'));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++function writeCliPackage(cliRoot: string, version = '1.2.3') {+ mkdirSync(cliRoot, { recursive: true });+ writeFileSync(+ path.join(cliRoot, 'package.json'),+ JSON.stringify({ name: '@lobehub/cli', version }),+ );+}++describe('findCliRoot', () => {+ it('finds the package root from a built dist/ layout', () => {+ const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');+ writeCliPackage(cliRoot);+ const distDir = path.join(cliRoot, 'dist');+ mkdirSync(distDir, { recursive: true });++ expect(findCliRoot(distDir)).toBe(cliRoot);+ });++ it('finds the package root from the monorepo dev entry (src/) layout', () => {+ const cliRoot = path.join(root, 'apps', 'cli');+ writeCliPackage(cliRoot);+ const srcDir = path.join(cliRoot, 'src');+ mkdirSync(srcDir, { recursive: true });++ expect(findCliRoot(srcDir)).toBe(cliRoot);+ });++ it('ignores intermediate package.json files that are not @lobehub/cli', () => {+ const cliRoot = path.join(root, 'apps', 'cli');+ writeCliPackage(cliRoot);+ const utilsDir = path.join(cliRoot, 'src', 'utils');+ mkdirSync(utilsDir, { recursive: true });+ writeFileSync(+ path.join(cliRoot, 'src', 'package.json'),+ JSON.stringify({ name: 'not-the-cli' }),+ );++ expect(findCliRoot(utilsDir)).toBe(cliRoot);+ });++ it('returns undefined when no matching package.json exists up to the filesystem root', () => {+ const dir = path.join(root, 'some', 'unrelated', 'dir');+ mkdirSync(dir, { recursive: true });++ expect(findCliRoot(dir)).toBeUndefined();+ });+});++describe('locateBundledSkill', () => {+ it('resolves cliRoot, skillDir, and version from a simulated package layout', () => {+ const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');+ writeCliPackage(cliRoot, '9.9.9');+ const skillDir = path.join(cliRoot, 'skills', 'agent-testing');+ mkdirSync(skillDir, { recursive: true });+ writeFileSync(path.join(skillDir, 'SKILL.md'), '# agent-testing');+ const distDir = path.join(cliRoot, 'dist');+ mkdirSync(distDir, { recursive: true });++ const result = locateBundledSkill('agent-testing', distDir);++ expect(result.cliRoot).toBe(cliRoot);+ expect(result.skillDir).toBe(skillDir);+ expect(result.version).toBe('9.9.9');+ });++ it('throws when the package root cannot be found', () => {+ const dir = path.join(root, 'nowhere');+ mkdirSync(dir, { recursive: true });++ expect(() => locateBundledSkill('agent-testing', dir)).toThrow(/package root/);+ });++ it('throws when the package root exists but the skill directory is missing', () => {+ const cliRoot = path.join(root, 'node_modules', '@lobehub', 'cli');+ writeCliPackage(cliRoot);+ const distDir = path.join(cliRoot, 'dist');+ mkdirSync(distDir, { recursive: true });++ expect(() => locateBundledSkill('agent-testing', distDir)).toThrow(/not found/);+ });++ it('resolves against the real apps/cli agent-testing skill by default', () => {+ const result = locateBundledSkill();+ expect(result.skillDir.endsWith(path.join('skills', 'agent-testing'))).toBe(true);+ });+});diff --git a/apps/cli/src/utils/skillLocator.ts b/apps/cli/src/utils/skillLocator.tsnew file mode 100644index 00000000000..e4c30277114--- /dev/null+++ b/apps/cli/src/utils/skillLocator.ts@@ -0,0 +1,59 @@+import { existsSync, readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++export interface BundledSkill {+ cliRoot: string;+ skillDir: string;+ version: string;+}++// Anchored to a package.json name match rather than a fixed relative depth+// because the caller's own file lives at a different depth in the built+// dist/index.js layout (global install / npx) vs. the monorepo dev entry+// (bun src/index.ts).+export function findCliRoot(startDir: string): string | undefined {+ let dir = startDir;+ while (true) {+ const pkgPath = path.join(dir, 'package.json');+ if (existsSync(pkgPath)) {+ try {+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));+ if (pkg && pkg.name === '@lobehub/cli') return dir;+ } catch {+ // Not a readable/valid package.json โ keep walking up.+ }+ }+ const parent = path.dirname(dir);+ if (parent === dir) return undefined;+ dir = parent;+ }+}++// startDir is anchored to this module's own location by the caller+// (import.meta.url), never process.cwd() โ resolution must not depend on+// where the CLI happens to be invoked from.+export function locateBundledSkill(+ skillName = 'agent-testing',+ startDir: string = path.dirname(fileURLToPath(import.meta.url)),+): BundledSkill {+ const cliRoot = findCliRoot(startDir);+ if (!cliRoot) {+ throw new Error(+ `Could not locate the @lobehub/cli package root walking up from ${startDir}. ` ++ 'The CLI install may be corrupted.',+ );+ }++ const skillDir = path.join(cliRoot, 'skills', skillName);+ if (!existsSync(skillDir)) {+ throw new Error(+ `Bundled skill "${skillName}" not found at ${skillDir}. ` ++ 'The @lobehub/cli install may be missing its skills/ directory.',+ );+ }++ const pkg = JSON.parse(readFileSync(path.join(cliRoot, 'package.json'), 'utf8'));++ return { cliRoot, skillDir, version: pkg.version };+}