{"owner":"Floorp-Projects","repo":"Floorp","hasSkills":true,"totalSkillsCount":5,"totalTokensCount":17957,"categories":["anthropic-skill","cursor-rule","root-instruction","claude-rule","copilot-instructions"],"hasMcp":false,"mcpConfig":null,"found":["tools/os-test/perf-report-2026-03-24.md",".cursorrules","AGENTS.md","CLAUDE.md",".github/copilot-instructions.md"],"skills":{"tools/os-test/perf-report-2026-03-24.md":"# Floorp OS API Server Performance Report\n\n- **Date**: 2026-03-24\n- **Environment**: Windows 11 Pro, dev build (`deno task dev`)\n- **Target page**: `https://example.com`\n- **Server**: `http://127.0.0.1:58261`\n- **Method**: curl with `%{time_total}`, 3-5 iterations per endpoint, median reported\n\n---\n\n## Summary\n\n| Category | Endpoint Count | Latency Range | Assessment |\n|---|---|---|---|\n| Tier 1: Instant | 18 | < 5ms | Excellent |\n| Tier 2: Fast | 8 | 5-10ms | Good |\n| Tier 3: Moderate | 4 | 40-100ms | Acceptable (I/O bound) |\n| Tier 4: Slow | 2 | > 100ms | Needs investigation |\n\n**Overall**: Most endpoints respond in under 5ms. The server's HTTP routing and IPC layer add minimal overhead (~2-3ms baseline from `/health`). Performance bottlenecks are concentrated in a few specific operations.\n\n---\n\n## Detailed Results\n\n### Tier 1: Instant (< 5ms)\n\nThese endpoints respond near the server's baseline latency. No optimization needed.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/health` | GET | 2.7ms | 7.4ms | 17B |\n| `/tabs/list` | GET | 3.0ms | 3.4ms | - |\n| `/browser/tabs` | GET | 2.9ms | 3.3ms | - |\n| `/workspaces` | GET | 2.8ms | 4.0ms | - |\n| `/instances/:id/cookies` | GET | 2.8ms | 5.9ms | - |\n| `/instances/:id/uri` | GET | 3.8ms | 4.8ms | 33B |\n| `/instances/:id/title` | GET | 4.1ms | 7.5ms | 27B |\n| `/instances/:id/element?selector=h1` | GET | 4.0ms | 4.6ms | 36B |\n| `/instances/:id/elementText?selector=h1` | GET | 3.7ms | 4.1ms | 26B |\n| `/instances/:id/elementTextContent?selector=h1` | GET | 4.0ms | 4.4ms | 26B |\n| `/instances/:id/attribute?selector=a&name=href` | GET | 3.8ms | 4.3ms | 47B |\n| `/instances/:id/isVisible?selector=a` | GET | 3.3ms | 3.9ms | 16B |\n| `/instances/:id/isEnabled?selector=a` | GET | 3.7ms | 3.8ms | 16B |\n| `/instances/:id/ax-tree` | GET | 2.7ms | 3.0ms | 46B |\n| `/instances/:id/waitForElement` (existing) | POST | 3.8ms | 4.6ms | 27B |\n| `/instances/:id/clearEffects` | POST | 3.4ms | 4.0ms | 11B |\n| `/instances/:id/article` | GET | 2.8ms | 14.8ms | 36B |\n| `DELETE /instances/:id` | DELETE | 3.0ms | - | 11B |\n\n### Tier 2: Fast (5-10ms)\n\nSlightly above baseline due to DOM traversal, serialization, or coordinate computation.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/instances/:id/html` | GET | 6.5ms | 6.7ms | ~15KB |\n| `/instances/:id/text` | GET | 8.7ms | 11.3ms | 270B |\n| `POST /instances/:id/text` (fingerprints) | POST | 6.7ms | 8.3ms | 629B |\n| `/instances/:id/hover` | POST | 6.7ms | 8.5ms | 11B |\n| `/instances/:id/scrollTo` | POST | 5.7ms | 6.5ms | 11B |\n| `/instances/:id/focus` | POST | 5.1ms | 7.2ms | 11B |\n| `/browser/history?limit=10` | GET | 3.5ms | 4.0ms | - |\n| `/browser/context` | GET | 4.8ms | 143.7ms | - |\n\n**Note**: `/browser/context` has an occasional spike (~144ms) likely caused by GC pause or event loop contention.\n\n### Tier 3: Moderate (40-100ms)\n\nLatency is driven by I/O (network, rendering engine).\n\n| Endpoint | Method | Median | p95 | Payload | Bottleneck |\n|---|---|---|---|---|---|\n| `/instances/:id/exists` | GET | **41ms** | 99ms | 15B | Unknown - needs investigation |\n| `/instances/:id/navigate` | POST | **49ms** | 59ms | 11B | Network round-trip |\n| `/instances/:id/screenshot` | GET | **76ms** | 80ms | 217KB | Canvas rendering + PNG encode |\n| `/instances/:id/fullPageScreenshot` | GET | **86ms** | 92ms | 217KB | Canvas rendering + PNG encode |\n\n### Tier 4: Slow (> 100ms)\n\n| Endpoint | Method | Median | p95 | Bottleneck |\n|---|---|---|---|---|\n| `POST /instances/:id/click` | POST | **165ms** | 230ms | `waitForStable` 100ms delay + actionability checks |\n| `POST /instances` (create) | POST | **6.9s** | - | Tab creation + full page load |\n\n---\n\n## Analysis & Recommendations\n\n### 1. `/exists` is 10x slower than similar read endpoints (41ms vs 3-4ms)\n\n**Expected**: `exists` should be a simple lookup (like `uri` or `title`).\n**Observed**: 41ms median, with first call at 99ms.\n**Action**: Investigate the implementation. Likely doing an unnecessary async round-trip to the content process or awaiting a promise that could be resolved synchronously.\n\n### 2. `/click` latency is dominated by `waitForStable` (100ms fixed delay)\n\n**Breakdown**:\n- `waitForStable`: 100ms (fixed `timerSetTimeout`)\n- Actionability checks + scroll: ~15ms\n- `sendMouseEvent`: ~5ms\n- IPC overhead: ~45ms\n\n**Tradeoff**: The 100ms delay catches CSS transitions/animations. Removing it risks clicking moving elements. Consider:\n- Making `waitForStable` timeout configurable via request body (e.g., `stabilityTimeout: 50`)\n- Reducing default from 100ms to 50ms for simple pages\n- Skipping entirely when `force: true` (already implemented)\n\n### 3. Instance creation is very slow (6.9s)\n\nThis includes full page load (`https://example.com`). The time is mostly network + rendering. Consider:\n- Allowing `POST /instances` to return immediately after tab creation (before load completes)\n- Adding a separate `waitForLoad` endpoint for callers that need load completion\n\n### 4. Screenshot latency is reasonable (76-86ms)\n\nFor PNG encoding of a full viewport, 76ms is acceptable. If lower latency is needed:\n- Consider JPEG output option (faster encoding, smaller payload)\n- Consider returning raw bitmap data for local consumers\n\n### 5. Occasional spikes (~150ms) on fast endpoints\n\nObserved on `/isEnabled` (157ms) and `/browser/context` (144ms). These are likely:\n- JavaScript GC pauses in the parent process\n- Event loop contention from other Floorp operations\n- Not actionable without profiling, and acceptable for an API server\n\n### 6. `/ax-tree` returns only 46 bytes\n\nFor `example.com` this returned `{\"error\":\"ax-tree not available\"}` or a minimal response. Needs verification that the accessibility tree is being correctly extracted for complex pages.\n\n---\n\n## Latency Budget (typical MCP tool call)\n\nA typical MCP interaction involves multiple API calls. Example workflow:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~7000ms |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Wait for navigation | `POST /waitForElement` | ~4ms |\n| 5. Get new text | `GET /text` | ~9ms |\n| 6. Cleanup | `DELETE /instances/:id` | ~3ms |\n| **Total** | | **~7190ms** |\n\nWithout instance creation (reusing existing tab via `/attach`):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Get new text | `GET /text` | ~9ms |\n| **Total** | | **~188ms** |\n\n*Estimated based on similar lightweight operations.\n\n**Conclusion**: Instance creation dominates total latency. For interactive use, reusing tabs via `/attach` brings total workflow time under 200ms, which is excellent.\n\n---\n\n## Large-Scale Site Benchmark: Gmail\n\nGmail (inbox with 243 messages) was tested to evaluate performance on a complex, real-world SPA with heavy DOM.\n\n### Test Conditions\n\n- **Page**: `https://mail.google.com/mail/u/0/#inbox` (logged in, 243 messages)\n- **DOM complexity**: ~1MB HTML, deeply nested SPA structure\n- **Instance creation**: 4.2s (faster than example.com — likely cached assets)\n\n### Results Comparison: example.com vs Gmail\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 1.0x | No DOM access needed |\n| `GET /title` | 4.1ms | 40ms | **10x** | Spikes to 449ms observed |\n| `GET /exists` | 41ms | 80ms | **2x** | Consistently slow |\n| `GET /html` | 6.5ms (15KB) | **1.0s** (950KB) | **150x** | Serializing ~1MB DOM |\n| `GET /text` | 8.7ms (270B) | **2.4s** (107KB) | **275x** | DOM traversal + Turndown conversion |\n| `POST /text` (fps) | 6.7ms (629B) | **2.7s** (220KB) | **400x** | + fingerprint generation |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 1.5x | Returns 46B on both — likely broken |\n| `GET /screenshot` | 76ms (217KB) | **134ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /fullPageScreenshot` | 86ms (217KB) | **157ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /element` | 4.0ms | 11ms | 2.8x | |\n| `GET /elementText` | 3.7ms | 13ms | 3.5x | |\n| `GET /attribute` | 3.8ms | 7.0ms | 1.8x | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 2.3x | |\n| `GET /cookies` | 2.8ms | **8.8ms** (14KB) | 3.1x | More cookies on Google |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | **73ms** | **11x** | Coordinate computation on complex layout |\n| `POST /scrollTo` | 5.7ms | **45ms** | **8x** | First call 111ms (layout recalc?) |\n| `POST /focus` | 5.1ms | **42ms** | **8x** | First call 112ms |\n| `POST /click` | 165ms | **318ms** | 1.9x | waitForStable + complex layout |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **600x** | SPA doesn't fire `load` event |\n| `GET /regionScreenshot` | - | 39ms (68KB) | - | Efficient partial capture |\n\n### Critical Issues Found\n\n#### 1. `navigate` times out on SPA pages (30s)\n\n**Severity**: Critical\n**Observed**: `POST /navigate` to `#inbox` on Gmail takes exactly 30 seconds — hitting the timeout.\n**Root cause**: `navigate` waits for a `load` event, but Gmail is a SPA that uses `pushState`/`hashchange` for navigation. The `load` event never fires for in-app navigations.\n**Impact**: Any workflow that navigates within a SPA (Gmail, YouTube, Twitter, etc.) will block for 30 seconds.\n**Recommendation**: Detect SPA navigation (same-origin hash/pushState changes) and resolve immediately or use a shorter timeout with `DOMContentLoaded` / network idle detection.\n\n#### 2. `text` extraction takes 2.4-3.7s on complex pages\n\n**Severity**: High\n**Observed**: `GET /text` = 2.4s, `POST /text` with fingerprints = 2.7s (107-220KB output).\n**Root cause**: Turndown (HTML-to-Markdown) conversion traverses the entire DOM tree. Gmail's DOM is extremely deep (~1MB HTML).\n**Impact**: This is the primary endpoint for MCP tool use — AI agents call `text` on every page interaction. 2-3s per call significantly impacts agent loop latency.\n**Recommendation**:\n- Support `selector` scoping in GET/POST to limit traversal (e.g., only extract the email list, not the entire UI)\n- Consider caching/diffing for repeated calls on the same page state\n- Profile Turndown to find hotspots (likely in node visibility checks)\n\n#### 3. `html` takes 1s for ~1MB\n\n**Severity**: Medium\n**Observed**: 1.0s to serialize and transfer ~950KB of HTML.\n**Root cause**: Combination of `outerHTML` serialization in content process + IPC transfer + HTTP response writing.\n**Impact**: Less critical than `text` since `html` is used less frequently, but still notable.\n\n#### 4. `title` has unpredictable latency (4ms to 449ms)\n\n**Severity**: Low\n**Observed**: Varies from 4ms to 449ms across 5 calls on Gmail.\n**Root cause**: Likely contention with Gmail's JavaScript execution (timers, XHR callbacks, mutation observers).\n**Impact**: Usually fast, but occasional spikes could affect perceived responsiveness.\n\n#### 5. `ax-tree` returns 46 bytes on Gmail\n\n**Severity**: Medium (functional issue)\n**Observed**: Same 46-byte response on both example.com and Gmail. This is likely `{\"error\":\"...\"}` or an empty tree.\n**Impact**: Accessibility tree is unusable. Should be investigated separately.\n\n### Gmail Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~4200ms |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~11s** |\n\nWith `/attach` (reusing existing tab):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~6.8s** |\n\n**Conclusion**: On large-scale SPAs, `text` extraction dominates latency at 2-4s per call. This is 250-400x slower than on simple pages. Scoped text extraction (passing a selector to limit DOM traversal) would be the highest-impact optimization.\n\n---\n\n## Large-Scale Site Benchmark: X (Twitter)\n\nX home timeline was tested as another complex SPA with infinite scroll and dynamic content loading.\n\n### Test Conditions\n\n- **Page**: `https://x.com/home` (logged in, home timeline)\n- **DOM complexity**: ~836KB HTML, React-based SPA\n- **Instance creation**: 2.2s\n\n### Results: X vs Gmail vs example.com\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | Consistent across all |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | Gmail is the outlier |\n| `GET /exists` | 41ms | 80ms | **97ms** | Consistently slow on all sites |\n| `GET /html` | 6.5ms (15KB) | 1.0s (950KB) | **252ms** (836KB) | X DOM is similar size but faster |\n| `GET /text` | 8.7ms (270B) | 2.4s (107KB) | **1.7s** (44KB) | Heavy DOM traversal |\n| `POST /text` (fps) | 6.7ms (629B) | 2.7s (220KB) | **1.4s** (112KB) | Fingerprint version faster than plain on X |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | Broken on all sites |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | **157ms** (527KB) | Scales with image size |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | **163ms** (527KB) | |\n| `GET /element` (article) | 4.0ms | 11ms | **11ms** (34KB) | X articles are large |\n| `GET /elementText` | 3.7ms | 13ms | **4.6ms** | |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 3.9ms | |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | **3.8ms** (2.8KB) | Fewer cookies than Gmail |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | **11ms** | First call 273ms (cold), then 10-11ms |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | `article:nth-of-type(3)` returned `ok:false` — not found |\n| `POST /focus` | 5.1ms | 42ms | **27ms** | First call 329ms (cold), then 24-30ms |\n| `POST /click` | 165ms | 318ms | **403ms** | Slowest of all three sites |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **175ms / 45ms** | X works! No load event issue |\n| `POST /waitForElement` | 3.8ms | 5s (timeout) | **73ms-5s** | Inconsistent — first call timed out |\n| `POST /regionScreenshot` | - | 39ms | **120-197ms** | Higher on X |\n\n### Key Findings for X\n\n#### 1. SPA Navigate works on X but not Gmail\n\n**Observed**: `POST /navigate` to `/explore` took 175ms, back to `/home` took 45ms. No 30s timeout.\n**Explanation**: X likely triggers a full page `load` event on navigation (or uses a different routing strategy than Gmail). This confirms the Gmail timeout is specific to Gmail's SPA implementation, not a universal SPA issue.\n\n#### 2. Click is slowest on X (403ms)\n\n**Observed**: 403ms on X vs 318ms on Gmail vs 165ms on example.com.\n**Breakdown estimate**: waitForStable 100ms + actionability checks on complex DOM ~50ms + scroll/coordinate computation ~150ms + sendMouseEvent ~5ms + IPC overhead ~100ms.\n**Root cause**: X's deeply nested React component tree and heavy event handlers likely slow down coordinate computation and the scroll-into-view step.\n\n#### 3. First-call penalty on hover/focus (270-330ms)\n\n**Observed**: First `hover` took 273ms, subsequent calls 10-11ms. First `focus` took 329ms, then 24-30ms.\n**Root cause**: JIT compilation or lazy initialization of the coordinate/actionability pipeline. After warm-up, performance stabilizes.\n**Impact**: Minimal — only affects the very first interaction after instance creation.\n\n#### 4. Text extraction is faster than Gmail despite similar DOM size\n\n**Observed**: X text = 1.7s (44KB) vs Gmail text = 2.4s (107KB). HTML size is comparable (~836KB vs ~950KB).\n**Explanation**: Gmail's DOM is more deeply nested with more visible text nodes (email previews, labels, folders). X's timeline has more hidden/clipped content that Turndown skips.\n\n#### 5. `waitForElement` is unreliable after SPA navigation\n\n**Observed**: First call after navigating back to `/home` timed out at 5s. Second call found the element in 736ms. Third call in 72ms.\n**Root cause**: After SPA navigation, X lazy-loads timeline content. The first `article` element may not exist immediately. This is expected behavior, but the 5s default timeout may be too short for slow connections.\n\n### X Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~2200ms |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~4800ms** |\n\nWith `/attach`:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~2600ms** |\n\n---\n\n## Cross-Site Summary\n\n### Performance Tiers by Site\n\n| Endpoint | example.com | Gmail | X | Category |\n|---|---|---|---|---|\n| Simple reads (uri/title/visible) | 3-4ms | 4-40ms | 4-6ms | Fast everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | Slow everywhere — investigate |\n| `GET /html` | 7ms | 1.0s | 252ms | Scales with DOM size |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | **Primary bottleneck** |\n| `POST /text` (fps) | 7ms | **2.7s** | **1.4s** | **Primary bottleneck** |\n| `POST /click` | 165ms | 318ms | 403ms | Scales with DOM complexity |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | Gmail-specific timeout issue |\n| `GET /screenshot` | 76ms | 134ms | 157ms | Scales with pixel content |\n| `GET /ax-tree` | 46B | 46B | 46B | **Broken on all sites** |\n\n### Top Optimization Priorities (updated)\n\n| Priority | Issue | Impact | Affected Sites |\n|---|---|---|---|\n| 1 | **`text` extraction 1.4-2.7s** | Blocks every MCP agent loop | Gmail, X |\n| 2 | **SPA `navigate` 30s timeout** | Completely broken workflow | Gmail |\n| 3 | **`exists` 41-97ms** | 10-25x slower than similar endpoints | All |\n| 4 | **`ax-tree` non-functional** | Accessibility data unavailable | All |\n| 5 | **`click` 165-403ms** | 100ms of fixed `waitForStable` delay | All |\n| 6 | **First-call penalty** | 270-330ms on first hover/focus | X |\n\n---\n\n## Large-Scale Site Benchmark: YouTube\n\nYouTube home page was tested as a heavy media-centric SPA with Web Components (custom elements like `ytd-rich-item-renderer`).\n\n### Test Conditions\n\n- **Page**: `https://www.youtube.com/` (logged in, home feed)\n- **DOM complexity**: ~850KB HTML, Polymer/Lit-based Web Components\n- **Instance creation**: **19.4s** — by far the slowest (heavy JS bundles + video preloading)\n\n### Results: YouTube vs All Sites\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | 3.5ms | Consistent |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | 4.4ms | |\n| `GET /exists` | 41ms | 80ms | 97ms | **33ms** | Fastest — still slow vs uri/title |\n| `GET /html` | 7ms (15KB) | 1.0s (950KB) | 252ms (836KB) | **256ms** (853KB) | Similar to X |\n| `GET /text` | 9ms (270B) | 2.4s (107KB) | 1.7s (44KB) | **960ms** (7.9KB) | Fastest large site — little visible text |\n| `POST /text` (fps) | 7ms (629B) | 2.7s (220KB) | 1.4s (112KB) | **1.0s** (32KB) | |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | 5.0ms (46B) | Still broken |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | 157ms (527KB) | **47ms** (60KB) | Small — dark theme, simple thumbnails |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | 163ms (527KB) | **35ms** (60KB) | Same as viewport |\n| `GET /element` (video) | 4.0ms | 11ms | 11ms (34KB) | 5.0ms (**2B**) | **Empty** — Web Component not traversable |\n| `GET /elementText` (video) | 3.7ms | 13ms | 4.6ms | 4.2ms (**2B**) | **Empty** |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | 4.7ms (`null`) | **null** — selector not found |\n| `GET /isVisible` (search) | 3.3ms | 7.7ms | 3.9ms | 4.9ms (`false`) | Shadow DOM barrier? |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | 3.8ms (2.8KB) | 5.5ms (6.9KB) | |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | 11ms | **8.5ms** | Fast after warm-up (first: 19ms) |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | **6.1ms** | |\n| `POST /focus` | 5.1ms | 42ms | 27ms | **7.5ms** | |\n| `POST /click` | 165ms | 318ms | 403ms | **333ms** (`ok:false`) | **Failed** — click didn't register |\n| `POST /navigate` (SPA) | 49ms | 30s | 175ms | **31ms-2.2s** | Variable — home=2.2s, trending=31ms |\n| `POST /waitForElement` | 3.8ms | 5s | 73ms-5s | **105ms-5s** | `ytd-video-renderer` not found on trending |\n| `POST /regionScreenshot` | - | 39ms | 120ms | **11ms** (12.5KB) | Very fast — small content |\n\n### Key Findings for YouTube\n\n#### 1. Web Components are opaque to element queries\n\n**Severity**: Critical (functional)\n**Observed**: `element?selector=ytd-rich-item-renderer` returns 2 bytes (empty). `attribute?selector=a#video-title-link&name=href` returns `null`. `isVisible?selector=input#search` returns `false`.\n**Root cause**: YouTube uses Polymer/Lit Web Components with Shadow DOM. Standard `querySelector` cannot pierce shadow boundaries. The API's DOM operations only search the light DOM.\n**Impact**: Most element-targeting operations are effectively broken on YouTube. Selectors like `ytd-rich-item-renderer`, `a#thumbnail`, `input#search` exist inside shadow roots and are invisible to the API.\n**Recommendation**: Implement `deepQuerySelector` that traverses into shadow roots, or provide a `piercesShadow: true` option.\n\n#### 2. Click returned `ok:false` on video thumbnail\n\n**Severity**: High\n**Observed**: `POST /click` with `selector: \"a#thumbnail\"` returned `{\"ok\":false}` in 333ms. URL didn't change.\n**Root cause**: Related to Shadow DOM issue — the element was likely found in light DOM but actionability checks or coordinate computation failed because the rendered element is inside a shadow root.\n\n#### 3. Instance creation is extremely slow (19.4s)\n\n**Observed**: 19.4s vs Gmail 4.2s vs X 2.2s vs example.com 6.9s.\n**Root cause**: YouTube loads very heavy JS bundles, preloads video content, and runs extensive initialization. The `load` event fires late.\n**Impact**: First-time access to YouTube via the API is very slow.\n\n#### 4. SPA navigate latency is inconsistent\n\n**Observed**: Navigate to `/feed/trending` = 31ms (fast). Navigate back to home = 2.2s (slow).\n**Root cause**: YouTube's home page triggers heavy content loading (video thumbnails, recommendations). Trending page is lighter. The `load`/`DOMContentLoaded` event timing varies dramatically.\n\n#### 5. Text extraction is fast but returns very little\n\n**Observed**: `GET /text` = 960ms but only 7.9KB of text. Gmail returns 107KB, X returns 44KB.\n**Root cause**: Most of YouTube's visible text is inside Web Components' shadow DOMs. Turndown can only see the light DOM text, which is minimal.\n**Impact**: The text endpoint is nearly useless on YouTube — it misses video titles, descriptions, channel names, etc.\n\n#### 6. Screenshots are very small (60KB)\n\n**Observed**: 47ms for a 60KB screenshot. Gmail = 397KB, X = 527KB.\n**Root cause**: YouTube's dark theme with simple thumbnail grid produces a highly compressible PNG. Screenshots DO render correctly (they capture the visual output, not DOM), so screenshots are the most reliable way to \"see\" YouTube's content.\n\n### YouTube Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time | Status |\n|---|---|---|---|\n| 1. Create instance | `POST /instances` | ~19400ms | Very slow |\n| 2. Get page text | `GET /text` | ~960ms | Fast but mostly empty |\n| 3. Click video | `POST /click` | ~333ms | **FAILS** (Shadow DOM) |\n| 4. Get video text | `GET /text` | ~850ms | Mostly empty |\n| **Total** | | **~21.5s** | **Partially broken** |\n\n**Conclusion**: YouTube is largely non-functional with the current API due to Shadow DOM. Screenshots work, but text extraction and element interaction are severely limited.\n\n---\n\n## Cross-Site Summary (Final)\n\n### Performance Matrix\n\n| Endpoint | example.com | Gmail | X | YouTube | Category |\n|---|---|---|---|---|---|\n| Simple reads | 3-4ms | 4-40ms | 4-6ms | 3-5ms | OK everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | 33ms | Slow everywhere |\n| `GET /html` | 7ms | 1.0s | 252ms | 256ms | Scales with DOM |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | 960ms* | *YouTube: mostly empty |\n| `POST /click` | 165ms | 318ms | 403ms | 333ms** | **YouTube: fails |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | 31ms-2.2s | Gmail broken |\n| `GET /screenshot` | 76ms | 134ms | 157ms | 47ms | Always works |\n| `GET /ax-tree` | 46B | 46B | 46B | 46B | Broken everywhere |\n| Instance creation | 6.9s | 4.2s | 2.2s | **19.4s** | YouTube very slow |\n\n### Final Priority List\n\n| Priority | Issue | Impact | Sites Affected |\n|---|---|---|---|\n| **1** | **Shadow DOM not supported** | Element queries, click, text extraction all fail | YouTube (and any Web Component site) |\n| **2** | **`text` extraction 1-2.7s** | Primary MCP endpoint, blocks every agent loop | Gmail, X, YouTube |\n| **3** | **SPA `navigate` 30s timeout** | Workflow completely blocked | Gmail |\n| **4** | **`ax-tree` non-functional** | Accessibility data unavailable | All sites |\n| **5** | **`exists` 33-97ms** | 10-25x slower than similar endpoints | All sites |\n| **6** | **`click` 165-403ms** | 100ms fixed `waitForStable` delay | All sites |\n| **7** | **Instance creation 2-19s** | Slow first access, especially YouTube | All sites |\n\n---\n\n## Raw Data\n\nAll measurements taken with:\n```bash\ncurl -s -w \"%{time_total}\" -o /dev/null <url>\n```\n\n- Iterations: 3-5 per endpoint\n- Warm-up: Server was idle before measurements; first call to each endpoint may include JIT compilation overhead\n- Pages: `https://example.com` (15KB), Gmail inbox (~950KB, 243 messages), X home timeline (~836KB), YouTube home (~853KB)\n- Network: Localhost loopback (127.0.0.1), no auth token configured\n",".cursorrules":"# Floorp プロジェクトルール\n\nこのプロジェクトは Mozilla Firefox をベースにした Web ブラウザ \"Floorp\" です。\n\n## 必読ドキュメント\n\nコーディング前に以下のドキュメントを参照してください：\n\n- `docs/llm/README.md` - LLM 向けドキュメントの索引\n- `docs/llm/project-overview.md` - プロジェクト全体の概要\n- `docs/llm/development-notes.md` - 開発ガイドとベストプラクティス\n- `docs/llm/architecture-deep-dive.md` - アーキテクチャ詳細\n- `.claude/context.md` - クイックリファレンス\n\n## 技術スタック\n\n- **ランタイム**: Deno 2.x (メイン), Node.js 22 (一部)\n- **UI**: SolidJS (ブラウザクローム), React (設定ページ)\n- **ビルド**: Vite, feles-build\n- **言語**: TypeScript\n- **CSS**: Tailwind CSS\n\n## コーディング規約\n\n### 型定義\n\n**重要**: 型定義は可能な限り別ファイルに分離してください。\n\n```typescript\n// Good: 型定義を types.ts に分離\n// types.ts\nexport interface Config {\n  enabled: boolean;\n  timeout: number;\n}\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n\n// Bad: 実装と型を混在させる\nexport interface Config { /* ... */ }\nexport class Feature { /* ... */ }\n```\n\n**例外**: `.sys.mts` ファイルでは Firefox API との統合のため、型定義を同じファイルに書いても構いません。\n\n### TypeScript\n\n- `any` 型は避ける\n- 明確な型定義を使用\n- 型推論を活用\n- null/undefined のチェックを忘れずに\n\n```typescript\n// Good\ninterface User {\n  id: number;\n  name: string;\n}\n\nfunction getUser(id: number): User | null {\n  // ...\n}\n\n// Bad\nfunction getUser(id: any): any {\n  // ...\n}\n```\n\n### SolidJS (ブラウザクローム機能)\n\n- リアクティブな状態管理には `createSignal` を使用\n- 直接変数を変更しない\n- HMR サポートのために `@noraComponent(import.meta.hot)` デコレーターを使用\n\n```typescript\n// Good\nimport { createSignal } from \"solid-js\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n\n// Bad\nlet count = 0;\ncount++; // 動作しない\n```\n\n### React (設定ページ)\n\n- 関数コンポーネントを使用\n- Hooks を適切に使用\n- Tailwind CSS でスタイリング\n\n```typescript\n// Good\nexport default function SettingsPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### ファイル配置\n\n- **ブラウザ UI 機能**: `browser-features/chrome/common/{feature-name}/`\n- **Firefox API モジュール**: `browser-features/modules/modules/{module-name}.sys.mts`\n- **設定ページ**: `browser-features/pages-settings/src/pages/`\n- **型定義**: 各機能の `types.ts` ファイル（`.sys.mts` を除く）\n\n### エラーハンドリング\n\n常に適切なエラーハンドリングを実装してください。\n\n```typescript\n// Good\ntry {\n  const data = await fetchData(url);\n  return data;\n} catch (error) {\n  console.error(\"[FeatureName] Failed to fetch:\", error);\n  return null; // フォールバック\n}\n\n// Bad\nconst data = await fetchData(url); // エラーが伝播\n```\n\n### コメント\n\n- 複雑なロジックには日本語または英語でコメントを追加\n- 関数の目的は JSDoc で説明\n- TODO コメントには担当者を明記\n\n```typescript\n/**\n * ユーザー設定を取得します\n * @param userId ユーザー ID\n * @returns ユーザー設定オブジェクト、存在しない場合は null\n */\nfunction getUserConfig(userId: string): UserConfig | null {\n  // TODO(@username): キャッシュ機構を実装\n  return null;\n}\n```\n\n## 新機能追加のチェックリスト\n\n1. **適切な場所に配置**\n   - ブラウザ UI → `browser-features/chrome/common/`\n   - システムモジュール → `browser-features/modules/modules/`\n   - 設定ページ → `browser-features/pages-settings/`\n\n2. **型定義を別ファイルに**\n   - `types.ts` を作成（`.sys.mts` 以外）\n   - インターフェースと型を定義\n\n3. **HMR サポートを追加**（ブラウザクローム機能のみ）\n   ```typescript\n   @noraComponent(import.meta.hot)\n   export default class MyFeature extends NoraComponentBase {\n     init(): void { /* ... */ }\n   }\n   ```\n\n4. **機能を登録**\n   - `browser-features/chrome/common/mod.ts` に追加\n\n5. **翻訳を追加**\n   - 少なくとも `i18n/en-US/` と `i18n/ja-JP/` に追加\n\n6. **必要に応じて Actor を追加**（マルチプロセス通信が必要な場合）\n   - Parent: `browser-features/modules/actors/{Name}Parent.sys.mts`\n   - Child: `browser-features/modules/actors/{Name}Child.sys.mts`\n   - 登録: `browser-features/modules/modules/BrowserGlue.sys.mts`\n\n## 開発コマンド\n\n```bash\n# 開発モード（HMR 付き）\ndeno task feles-build dev\n\n# 本番ビルド\ndeno task feles-build build\n\n# ステージングビルド\ndeno task feles-build stage\n\n# 依存関係のインストール\ndeno install\n```\n\n## モジュールパスエイリアス\n\n```typescript\nimport { foo } from \"#i18n/utils\";           // i18n/\nimport { bar } from \"#chrome/common/tab\";    // chrome/\nimport { baz } from \"#libs/shared\";          // libs/\nimport { qux } from \"#modules/experiments\";  // browser-features/modules/\n```\n\n## よくある問題\n\n### HMR が動作しない\n- `@noraComponent(import.meta.hot)` デコレーターが付いているか確認\n- `NoraComponentBase` を継承しているか確認\n\n### Firefox API にアクセスできない\n- `.sys.mts` ファイルから ChromeUtils.importESModule() を使用\n\n### 型エラー\n- 型定義を別ファイル（`types.ts`）に分離\n- `any` 型を使用していないか確認\n\n## パフォーマンス\n\n- `init()` メソッドで重い処理を避ける\n- 遅延初期化を活用\n- イベントリスナーを適切にクリーンアップ\n- メモリリークに注意\n\n## テスト\n\n- 新機能には可能な限りテストを追加\n- テストは `browser-features/chrome/test/unit/` に配置\n- Deno のテストフレームワークを使用\n\n## Git コミット\n\n- 意味のあるコミットメッセージ\n- 1 コミット = 1 つの論理的な変更\n- コミット前に `deno fmt` で整形\n\n## 参考リンク\n\n- プロジェクトドキュメント: `docs/llm/`\n- Deno: https://docs.deno.com/\n- SolidJS: https://www.solidjs.com/\n- React: https://react.dev/\n- Firefox Source: https://firefox-source-docs.mozilla.org/\n\n---\n\nこれらのルールに従って、一貫性のある高品質なコードを書いてください。\n","AGENTS.md":"# AGENTS.md\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Runtime changes\n\nRuntime changes must be maintained as patches, not direct edits to a sibling\nFloorp-Runtime checkout. Cross-platform source patches belong in\n`.github/patches/floorp-runtime/common/` and are applied by `package.yml`.\nValidate them against the source commit in `floorp-runtime.lock.json` in isolation.\nThe package workflow uses prebuilt native artifacts; changes requiring native\nrecompilation cannot be delivered through source patches in that step alone.\n\n## Architecture (5 Layers)\n\n```text\nFirefox Base  <- patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     |\nESM Modules   <- .sys.mts files with direct Firefox API access, Window Actors\n     |\nBridge        <- startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     |\nChrome UI     <- SolidJS -> XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     |\nPages         <- React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              -> ./i18n/\n#chrome/            -> ./chrome/\n#libs/              -> ./libs/\n#features-chrome/   -> ./browser-features/chrome/\n#modules/           -> ./browser-features/modules/\n#ui/                -> ./src/ui/\n#themes/            -> ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` -- adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state -- never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174-5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool -- Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot -> _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) -- browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` -- web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` -- launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` -- check for runtime errors\n4. `deno task dev-tool eval \"...\"` -- inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` -- visually verify UI changes\n6. `deno task dev-tool rebuild` -- if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` -- shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` -- Full project overview\n- `docs/llm/architecture-deep-dive.md` -- 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` -- Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Architecture (5 Layers)\n\n```notes\nFirefox Base  ← patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     ↓\nESM Modules   ← .sys.mts files with direct Firefox API access, Window Actors\n     ↓\nBridge        ← startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     ↓\nChrome UI     ← SolidJS → XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     ↓\nPages         ← React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              → ./i18n/\n#chrome/            → ./chrome/\n#libs/              → ./libs/\n#features-chrome/   → ./browser-features/chrome/\n#modules/           → ./browser-features/modules/\n#ui/                → ./src/ui/\n#themes/            → ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` — adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state — never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174–5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool — Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot → _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) — browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` — web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` — launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` — check for runtime errors\n4. `deno task dev-tool eval \"...\"` — inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` — visually verify UI changes\n6. `deno task dev-tool rebuild` — if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` — shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` — Full project overview\n- `docs/llm/architecture-deep-dive.md` — 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` — Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n",".github/copilot-instructions.md":"# AI Coding Agent Instructions\n\nThis workspace contains multiple interconnected projects: **Floorp** (Firefox-based browser), **Sapphillon** (workflow automation backend), **Floorp-OS-Automator-Frontend**, and **web-store**.\n\n## Project Overview\n\n### Floorp (`floorp/`)\nFirefox-based browser built with Deno 2.x, SolidJS, and React. Custom browser features overlay Firefox's Gecko engine.\n\n### Sapphillon Backend (`Floorp-OS-Automator-Backend/`)\nRust-based workflow automation backend using gRPC (tonic), SeaORM, and Deno runtime for executing JavaScript workflows.\n\n### Frontend Projects\n- **Floorp-OS-Automator-Frontend**: React + TypeScript + Vite UI for workflow management\n- **web-store**: Plugin marketplace with React + Vite\n\n---\n\n## Cross-Project Integration\n\nThis workspace contains interconnected projects. Understanding data flow and integration points is crucial for full-stack development.\n\n### Data Flow Architecture\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│                    Floorp Browser                        │\n│              (Mozilla Firefox + Custom Features)           │\n│  Location: /Users/user/dev-source/floorp-dev/floorp/     │\n│  Dev: deno task dev (ports: 5173-5186)              │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ Floorp OS API (OpenAPI)\n                          │ openapi.yaml:\n                          │ Floorp-OS-Automator-Backend/plugins/floorp/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│              Sapphillon Backend (Rust)                │\n│  Location: ../Floorp-OS-Automator-Backend/          │\n│  Dev: make run (gRPC on localhost:50051)            │\n│  - Plugin system (floorp, fetch, filesystem, etc.)    │\n│  - Workflow engine (Deno Core runtime)                 │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ gRPC (tonic + prost)\n                          │ protobuf in:\n                          │ Floorp-OS-Automator-Frontend/vender/Sapphillon_API/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│         Floorp-OS-Automator-Frontend (React)          │\n│  Location: ../Floorp-OS-Automator-Frontend/          │\n│  Dev: pnpm dev (port 8081)                          │\n│  - gRPC-Web client (@connectrpc/connect-web)           │\n│  - Workflow management UI                                │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ (optional, disabled)\n                          │ PostMessage to Floorp\n                          │ Progress Window\n                          ▼\n                   ┌────────────────┐\n                   │  Floorp       │\n                   │  Progress     │\n                   │  Window       │\n                   └────────────────┘\n\n                          ▲\n                          │\n                ┌─────────┴──────────┐\n                │                    │\n┌───────────────┐      ┌────────────────┐\n│  Web Store    │      │  External     │\n│  (Plugin      │      │  Plugins     │\n│   Marketplace)│      │              │\n└───────────────┘      └────────────────┘\n```\n\n### Integration Points\n\n**1. Floorp → Sapphillon** (Browser Automation):\n- Floorp exposes browser automation via OpenAPI spec at `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`\n- Sapphillon's `floorp` plugin consumes this API to control browser tabs, navigation, etc.\n- Workflows can automate browser interactions (open tabs, navigate, fill forms)\n\n**2. Sapphillon → Frontend** (Workflow Management):\n- gRPC communication using `tonic` (server) and `@connectrpc/connect-web` (client)\n- Protobuf definitions in `Floorp-OS-Automator-Frontend/vender/Sapphillon_API/proto/`\n- Frontend generates TypeScript clients from `.proto` files\n- Services: Workflow, Plugin, Version, Model, Provider\n\n**3. Frontend → Floorp** (Progress Tracking):\n- Disabled by default (see `lib/workflow-progress.ts`)\n- Uses `window.OSAutomotor?.sendWorkflowProgress()` for real-time updates\n- Would show workflow progress in Floorp's native progress window\n\n**4. Web Store → Sapphillon** (Plugin Distribution):\n- Plugin marketplace at `../web-store/`\n- Plugins installed via Sapphillon's plugin installer\n- External plugins run in separate processes with gRPC communication\n\n### Development Setup for Full Stack\n\n**Recommended workflow for full-stack development**:\n```bash\n# Terminal 1: Start Floorp Browser\ncd /Users/user/dev-source/floorp-dev/floorp\ndeno task dev\n\n# Terminal 2: Start Sapphillon Backend\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Backend\nmake run  # Starts gRPC server on localhost:50051\n\n# Terminal 3: Start Frontend (production mode)\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:prod  # Connects to localhost:50051\n```\n\n**Frontend-only development** (no backend needed):\n```bash\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:mock  # Mock gRPC on port 50099, Vite on 5199\n```\n\n---\n\n## Floorp Development Patterns\n\n### Build System\n- **Primary**: `deno task dev` - Runs custom feles-build system\n- **Build orchestration**: `tools/feles-build.ts` orchestrates patches, symlinks, Vite dev servers\n- **Dev server ports**: 5173 (main), 5178 (settings), 5186 (newtab), 5174-5177 (other pages)\n\n### Code Organization\n\n**Type Definitions**: Always separate types into dedicated files (`types.ts`), not mixed with implementation.\n```typescript\n// Good: types.ts\nexport interface Config { enabled: boolean; }\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n```\n**Exception**: `.sys.mts` files can include types with Firefox API integration.\n\n**File Extensions**:\n- `.ts` - General TypeScript\n- `.sys.mts` - Firefox ESM modules (loaded via `ChromeUtils.importESModule()`)\n- `.jsx` - React components in pages-*/ directories\n\n### UI Framework Usage\n\n**SolidJS** (`browser-features/chrome/`):\n- Use `createSignal` for reactive state (never mutate directly)\n- `@noraComponent(import.meta.hot)` decorator for HMR support\n- Import from `@nora/solid-xul` for rendering:\n```typescript\nimport { render, createSignal } from \"@nora/solid-xul\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n```\n\n**React** (`browser-features/pages-*/`):\n- Functional components with hooks\n- Tailwind CSS for styling\n- `import { createRootHMR } from \"@nora/solid-xul\"` for i18n integration\n\n### Firefox API Integration\nAccess Firefox APIs via ESM modules in `.sys.mts` files:\n```typescript\nconst { I18nUtils } = ChromeUtils.importESModule(\"resource://floorp/lib/I18nUtils.sys.mjs\");\n```\n\n---\n\n## Sapphillon Backend Patterns\n\n### Architecture\n- **gRPC Service Layer**: `src/services/` - Tonic-based services (workflow, plugin, model, version, provider)\n- **Plugin System**: Modular plugins in `plugins/` (fetch, filesystem, floorp, vscode, git, finder, etc.)\n- **Database**: SeaORM with SQLite, migrations in `migration/`, entities in `entity/`\n- **Workflow Engine**: Deno Core runtime executes JavaScript workflows with plugin permissions\n\n### Common Commands\n```bash\nmake rust_test          # Run all workspace tests\nmake rust_build         # Build entire workspace\nmake migrate            # Run SeaORM migrations\nmake entity_generate    # Generate entities from DB\nmake run                # Run with debug DB at ./debug/sqlite.db\nmake grpcui            # Launch gRPC UI on localhost:50051\n```\n\n### Testing\n- Unit tests: `cargo test --lib`\n- External plugin tests: `cargo test --test external_plugin`\n- Ignored tests: `cargo test --lib external_plugin -- --ignored`\n\n### Plugin Development\nEach plugin crate exposes Deno-compatible functions. See `plugins/floorp/` for OpenAPI-based Floorp browser control.\n\n**Debug Workflows**: Place JS files in `debug_workflow/` directory - auto-registered every 10s in debug builds with full permissions (`[DEBUG]` prefix).\n\n### gRPC & Protocol Buffers\n- Uses `tonic` for server, `prost` for code generation\n- `buf.yaml` and `buf.gen.yaml` configuration\n- Generate with `buf generate`\n\n---\n\n## Frontend Patterns (Both Projects)\n\n### Build Commands\n```bash\nnpm run dev              # Vite dev server\nnpm run build            # TypeScript check + Vite build\nnpm run test             # Vitest\nnpm run lint             # ESLint\n```\n\n### Component Patterns\n- **Chakra UI**: Primary component library\n- **i18next**: Internationalization via `src/i18n/config.ts`\n- **React Router**: Routing in `src/routes/`\n- **Type Definitions**: Export from `src/types/`, not inline\n\n### gRPC Communication\n- `@connectrpc/connect-web` for browser-based gRPC\n- `@connectrpc/connect` for Node-based\n- Generated clients in `src/gen/` from proto definitions\n\n---\n\n## Cross-Project Integration\n\n### Floorp OS API\nFloorp exposes browser automation via OpenAPI spec in `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`. The Sapphillon floorp plugin consumes this for workflow automation.\n\n### Data Flow\n```\nFloorp Browser\n    ↓ (Floorp OS API)\nSapphillon Backend (floorp plugin)\n    ↓ (gRPC)\nFloorp-OS-Automator-Frontend\n```\n\n### Plugin System\nWorkflows in Sapphillon can invoke plugins including:\n- **floorp**: Control Floorp browser (tabs, navigation, etc.)\n- **fetch**: HTTP requests\n- **filesystem**: File operations\n- **vscode**: VS Code control\n- **finder**: macOS Finder automation\n- And more in `plugins/`\n\n---\n\n## Key Conventions\n\n### Error Handling\n- **Floorp**: Use `Result<T, E>` from fp-ts for type-safe error handling\n- **Sapphillon**: `anyhow::Result<T>` and `tonic::Status` for gRPC errors\n\n### State Management\n- **SolidJS**: `createSignal` - never mutate directly\n- **React**: `useState`, `useContext` for global state\n\n### Database Operations\n- Use SeaORM `Entity::find().all(db).await?` pattern\n- Migrations: `sea-orm-cli migrate generate <name>`\n- Entities are auto-generated - don't edit manually\n\n### Permissions\nSapphillon uses wildcard `*` plugin_function_id to grant workflows full access. Used for trusted workflows and testing.\n\n---\n\n## Language-Specific Notes\n\n### Rust\n- Edition 2024, workspace resolver \"3\"\n- Async/await with tokio runtime\n- `#[tonic::async_trait]` for gRPC service implementations\n\n### TypeScript/Deno\n- No `any` types - use explicit types or `unknown`\n- Null/undefined checks required\n- Deno permissions: `--allow-all` often needed for build scripts\n\n### React\n- Functional components only\n- Hooks over class components\n- Tailwind CSS classes (e.g., `className=\"p-4\"`)\n\n---\n\n## Critical Files Reference\n\n| Purpose | File |\n|---------|------|\n| Floorp build system | `floorp/tools/feles-build.ts` |\n| Floorp dev config | `floorp/deno.json` |\n| Sapphillon main entry | `Floorp-OS-Automator-Backend/src/main.rs` |\n| Sapphillon workflow service | `Floorp-OS-Automator-Backend/src/services/workflow.rs` |\n| Frontend Vite config | `Floorp-OS-Automator-Frontend/vite.config.ts` |\n| Floorp SolidJS renderer | `floorp/libs/solid-xul/index.ts` |\n| Plugin permissions | `Floorp-OS-Automator-Backend/src/services/workflow.rs:make_plugin_permission()` |\n"},"files":{"tools/os-test/perf-report-2026-03-24.md":"# Floorp OS API Server Performance Report\n\n- **Date**: 2026-03-24\n- **Environment**: Windows 11 Pro, dev build (`deno task dev`)\n- **Target page**: `https://example.com`\n- **Server**: `http://127.0.0.1:58261`\n- **Method**: curl with `%{time_total}`, 3-5 iterations per endpoint, median reported\n\n---\n\n## Summary\n\n| Category | Endpoint Count | Latency Range | Assessment |\n|---|---|---|---|\n| Tier 1: Instant | 18 | < 5ms | Excellent |\n| Tier 2: Fast | 8 | 5-10ms | Good |\n| Tier 3: Moderate | 4 | 40-100ms | Acceptable (I/O bound) |\n| Tier 4: Slow | 2 | > 100ms | Needs investigation |\n\n**Overall**: Most endpoints respond in under 5ms. The server's HTTP routing and IPC layer add minimal overhead (~2-3ms baseline from `/health`). Performance bottlenecks are concentrated in a few specific operations.\n\n---\n\n## Detailed Results\n\n### Tier 1: Instant (< 5ms)\n\nThese endpoints respond near the server's baseline latency. No optimization needed.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/health` | GET | 2.7ms | 7.4ms | 17B |\n| `/tabs/list` | GET | 3.0ms | 3.4ms | - |\n| `/browser/tabs` | GET | 2.9ms | 3.3ms | - |\n| `/workspaces` | GET | 2.8ms | 4.0ms | - |\n| `/instances/:id/cookies` | GET | 2.8ms | 5.9ms | - |\n| `/instances/:id/uri` | GET | 3.8ms | 4.8ms | 33B |\n| `/instances/:id/title` | GET | 4.1ms | 7.5ms | 27B |\n| `/instances/:id/element?selector=h1` | GET | 4.0ms | 4.6ms | 36B |\n| `/instances/:id/elementText?selector=h1` | GET | 3.7ms | 4.1ms | 26B |\n| `/instances/:id/elementTextContent?selector=h1` | GET | 4.0ms | 4.4ms | 26B |\n| `/instances/:id/attribute?selector=a&name=href` | GET | 3.8ms | 4.3ms | 47B |\n| `/instances/:id/isVisible?selector=a` | GET | 3.3ms | 3.9ms | 16B |\n| `/instances/:id/isEnabled?selector=a` | GET | 3.7ms | 3.8ms | 16B |\n| `/instances/:id/ax-tree` | GET | 2.7ms | 3.0ms | 46B |\n| `/instances/:id/waitForElement` (existing) | POST | 3.8ms | 4.6ms | 27B |\n| `/instances/:id/clearEffects` | POST | 3.4ms | 4.0ms | 11B |\n| `/instances/:id/article` | GET | 2.8ms | 14.8ms | 36B |\n| `DELETE /instances/:id` | DELETE | 3.0ms | - | 11B |\n\n### Tier 2: Fast (5-10ms)\n\nSlightly above baseline due to DOM traversal, serialization, or coordinate computation.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/instances/:id/html` | GET | 6.5ms | 6.7ms | ~15KB |\n| `/instances/:id/text` | GET | 8.7ms | 11.3ms | 270B |\n| `POST /instances/:id/text` (fingerprints) | POST | 6.7ms | 8.3ms | 629B |\n| `/instances/:id/hover` | POST | 6.7ms | 8.5ms | 11B |\n| `/instances/:id/scrollTo` | POST | 5.7ms | 6.5ms | 11B |\n| `/instances/:id/focus` | POST | 5.1ms | 7.2ms | 11B |\n| `/browser/history?limit=10` | GET | 3.5ms | 4.0ms | - |\n| `/browser/context` | GET | 4.8ms | 143.7ms | - |\n\n**Note**: `/browser/context` has an occasional spike (~144ms) likely caused by GC pause or event loop contention.\n\n### Tier 3: Moderate (40-100ms)\n\nLatency is driven by I/O (network, rendering engine).\n\n| Endpoint | Method | Median | p95 | Payload | Bottleneck |\n|---|---|---|---|---|---|\n| `/instances/:id/exists` | GET | **41ms** | 99ms | 15B | Unknown - needs investigation |\n| `/instances/:id/navigate` | POST | **49ms** | 59ms | 11B | Network round-trip |\n| `/instances/:id/screenshot` | GET | **76ms** | 80ms | 217KB | Canvas rendering + PNG encode |\n| `/instances/:id/fullPageScreenshot` | GET | **86ms** | 92ms | 217KB | Canvas rendering + PNG encode |\n\n### Tier 4: Slow (> 100ms)\n\n| Endpoint | Method | Median | p95 | Bottleneck |\n|---|---|---|---|---|\n| `POST /instances/:id/click` | POST | **165ms** | 230ms | `waitForStable` 100ms delay + actionability checks |\n| `POST /instances` (create) | POST | **6.9s** | - | Tab creation + full page load |\n\n---\n\n## Analysis & Recommendations\n\n### 1. `/exists` is 10x slower than similar read endpoints (41ms vs 3-4ms)\n\n**Expected**: `exists` should be a simple lookup (like `uri` or `title`).\n**Observed**: 41ms median, with first call at 99ms.\n**Action**: Investigate the implementation. Likely doing an unnecessary async round-trip to the content process or awaiting a promise that could be resolved synchronously.\n\n### 2. `/click` latency is dominated by `waitForStable` (100ms fixed delay)\n\n**Breakdown**:\n- `waitForStable`: 100ms (fixed `timerSetTimeout`)\n- Actionability checks + scroll: ~15ms\n- `sendMouseEvent`: ~5ms\n- IPC overhead: ~45ms\n\n**Tradeoff**: The 100ms delay catches CSS transitions/animations. Removing it risks clicking moving elements. Consider:\n- Making `waitForStable` timeout configurable via request body (e.g., `stabilityTimeout: 50`)\n- Reducing default from 100ms to 50ms for simple pages\n- Skipping entirely when `force: true` (already implemented)\n\n### 3. Instance creation is very slow (6.9s)\n\nThis includes full page load (`https://example.com`). The time is mostly network + rendering. Consider:\n- Allowing `POST /instances` to return immediately after tab creation (before load completes)\n- Adding a separate `waitForLoad` endpoint for callers that need load completion\n\n### 4. Screenshot latency is reasonable (76-86ms)\n\nFor PNG encoding of a full viewport, 76ms is acceptable. If lower latency is needed:\n- Consider JPEG output option (faster encoding, smaller payload)\n- Consider returning raw bitmap data for local consumers\n\n### 5. Occasional spikes (~150ms) on fast endpoints\n\nObserved on `/isEnabled` (157ms) and `/browser/context` (144ms). These are likely:\n- JavaScript GC pauses in the parent process\n- Event loop contention from other Floorp operations\n- Not actionable without profiling, and acceptable for an API server\n\n### 6. `/ax-tree` returns only 46 bytes\n\nFor `example.com` this returned `{\"error\":\"ax-tree not available\"}` or a minimal response. Needs verification that the accessibility tree is being correctly extracted for complex pages.\n\n---\n\n## Latency Budget (typical MCP tool call)\n\nA typical MCP interaction involves multiple API calls. Example workflow:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~7000ms |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Wait for navigation | `POST /waitForElement` | ~4ms |\n| 5. Get new text | `GET /text` | ~9ms |\n| 6. Cleanup | `DELETE /instances/:id` | ~3ms |\n| **Total** | | **~7190ms** |\n\nWithout instance creation (reusing existing tab via `/attach`):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Get new text | `GET /text` | ~9ms |\n| **Total** | | **~188ms** |\n\n*Estimated based on similar lightweight operations.\n\n**Conclusion**: Instance creation dominates total latency. For interactive use, reusing tabs via `/attach` brings total workflow time under 200ms, which is excellent.\n\n---\n\n## Large-Scale Site Benchmark: Gmail\n\nGmail (inbox with 243 messages) was tested to evaluate performance on a complex, real-world SPA with heavy DOM.\n\n### Test Conditions\n\n- **Page**: `https://mail.google.com/mail/u/0/#inbox` (logged in, 243 messages)\n- **DOM complexity**: ~1MB HTML, deeply nested SPA structure\n- **Instance creation**: 4.2s (faster than example.com — likely cached assets)\n\n### Results Comparison: example.com vs Gmail\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 1.0x | No DOM access needed |\n| `GET /title` | 4.1ms | 40ms | **10x** | Spikes to 449ms observed |\n| `GET /exists` | 41ms | 80ms | **2x** | Consistently slow |\n| `GET /html` | 6.5ms (15KB) | **1.0s** (950KB) | **150x** | Serializing ~1MB DOM |\n| `GET /text` | 8.7ms (270B) | **2.4s** (107KB) | **275x** | DOM traversal + Turndown conversion |\n| `POST /text` (fps) | 6.7ms (629B) | **2.7s** (220KB) | **400x** | + fingerprint generation |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 1.5x | Returns 46B on both — likely broken |\n| `GET /screenshot` | 76ms (217KB) | **134ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /fullPageScreenshot` | 86ms (217KB) | **157ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /element` | 4.0ms | 11ms | 2.8x | |\n| `GET /elementText` | 3.7ms | 13ms | 3.5x | |\n| `GET /attribute` | 3.8ms | 7.0ms | 1.8x | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 2.3x | |\n| `GET /cookies` | 2.8ms | **8.8ms** (14KB) | 3.1x | More cookies on Google |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | **73ms** | **11x** | Coordinate computation on complex layout |\n| `POST /scrollTo` | 5.7ms | **45ms** | **8x** | First call 111ms (layout recalc?) |\n| `POST /focus` | 5.1ms | **42ms** | **8x** | First call 112ms |\n| `POST /click` | 165ms | **318ms** | 1.9x | waitForStable + complex layout |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **600x** | SPA doesn't fire `load` event |\n| `GET /regionScreenshot` | - | 39ms (68KB) | - | Efficient partial capture |\n\n### Critical Issues Found\n\n#### 1. `navigate` times out on SPA pages (30s)\n\n**Severity**: Critical\n**Observed**: `POST /navigate` to `#inbox` on Gmail takes exactly 30 seconds — hitting the timeout.\n**Root cause**: `navigate` waits for a `load` event, but Gmail is a SPA that uses `pushState`/`hashchange` for navigation. The `load` event never fires for in-app navigations.\n**Impact**: Any workflow that navigates within a SPA (Gmail, YouTube, Twitter, etc.) will block for 30 seconds.\n**Recommendation**: Detect SPA navigation (same-origin hash/pushState changes) and resolve immediately or use a shorter timeout with `DOMContentLoaded` / network idle detection.\n\n#### 2. `text` extraction takes 2.4-3.7s on complex pages\n\n**Severity**: High\n**Observed**: `GET /text` = 2.4s, `POST /text` with fingerprints = 2.7s (107-220KB output).\n**Root cause**: Turndown (HTML-to-Markdown) conversion traverses the entire DOM tree. Gmail's DOM is extremely deep (~1MB HTML).\n**Impact**: This is the primary endpoint for MCP tool use — AI agents call `text` on every page interaction. 2-3s per call significantly impacts agent loop latency.\n**Recommendation**:\n- Support `selector` scoping in GET/POST to limit traversal (e.g., only extract the email list, not the entire UI)\n- Consider caching/diffing for repeated calls on the same page state\n- Profile Turndown to find hotspots (likely in node visibility checks)\n\n#### 3. `html` takes 1s for ~1MB\n\n**Severity**: Medium\n**Observed**: 1.0s to serialize and transfer ~950KB of HTML.\n**Root cause**: Combination of `outerHTML` serialization in content process + IPC transfer + HTTP response writing.\n**Impact**: Less critical than `text` since `html` is used less frequently, but still notable.\n\n#### 4. `title` has unpredictable latency (4ms to 449ms)\n\n**Severity**: Low\n**Observed**: Varies from 4ms to 449ms across 5 calls on Gmail.\n**Root cause**: Likely contention with Gmail's JavaScript execution (timers, XHR callbacks, mutation observers).\n**Impact**: Usually fast, but occasional spikes could affect perceived responsiveness.\n\n#### 5. `ax-tree` returns 46 bytes on Gmail\n\n**Severity**: Medium (functional issue)\n**Observed**: Same 46-byte response on both example.com and Gmail. This is likely `{\"error\":\"...\"}` or an empty tree.\n**Impact**: Accessibility tree is unusable. Should be investigated separately.\n\n### Gmail Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~4200ms |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~11s** |\n\nWith `/attach` (reusing existing tab):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~6.8s** |\n\n**Conclusion**: On large-scale SPAs, `text` extraction dominates latency at 2-4s per call. This is 250-400x slower than on simple pages. Scoped text extraction (passing a selector to limit DOM traversal) would be the highest-impact optimization.\n\n---\n\n## Large-Scale Site Benchmark: X (Twitter)\n\nX home timeline was tested as another complex SPA with infinite scroll and dynamic content loading.\n\n### Test Conditions\n\n- **Page**: `https://x.com/home` (logged in, home timeline)\n- **DOM complexity**: ~836KB HTML, React-based SPA\n- **Instance creation**: 2.2s\n\n### Results: X vs Gmail vs example.com\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | Consistent across all |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | Gmail is the outlier |\n| `GET /exists` | 41ms | 80ms | **97ms** | Consistently slow on all sites |\n| `GET /html` | 6.5ms (15KB) | 1.0s (950KB) | **252ms** (836KB) | X DOM is similar size but faster |\n| `GET /text` | 8.7ms (270B) | 2.4s (107KB) | **1.7s** (44KB) | Heavy DOM traversal |\n| `POST /text` (fps) | 6.7ms (629B) | 2.7s (220KB) | **1.4s** (112KB) | Fingerprint version faster than plain on X |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | Broken on all sites |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | **157ms** (527KB) | Scales with image size |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | **163ms** (527KB) | |\n| `GET /element` (article) | 4.0ms | 11ms | **11ms** (34KB) | X articles are large |\n| `GET /elementText` | 3.7ms | 13ms | **4.6ms** | |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 3.9ms | |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | **3.8ms** (2.8KB) | Fewer cookies than Gmail |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | **11ms** | First call 273ms (cold), then 10-11ms |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | `article:nth-of-type(3)` returned `ok:false` — not found |\n| `POST /focus` | 5.1ms | 42ms | **27ms** | First call 329ms (cold), then 24-30ms |\n| `POST /click` | 165ms | 318ms | **403ms** | Slowest of all three sites |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **175ms / 45ms** | X works! No load event issue |\n| `POST /waitForElement` | 3.8ms | 5s (timeout) | **73ms-5s** | Inconsistent — first call timed out |\n| `POST /regionScreenshot` | - | 39ms | **120-197ms** | Higher on X |\n\n### Key Findings for X\n\n#### 1. SPA Navigate works on X but not Gmail\n\n**Observed**: `POST /navigate` to `/explore` took 175ms, back to `/home` took 45ms. No 30s timeout.\n**Explanation**: X likely triggers a full page `load` event on navigation (or uses a different routing strategy than Gmail). This confirms the Gmail timeout is specific to Gmail's SPA implementation, not a universal SPA issue.\n\n#### 2. Click is slowest on X (403ms)\n\n**Observed**: 403ms on X vs 318ms on Gmail vs 165ms on example.com.\n**Breakdown estimate**: waitForStable 100ms + actionability checks on complex DOM ~50ms + scroll/coordinate computation ~150ms + sendMouseEvent ~5ms + IPC overhead ~100ms.\n**Root cause**: X's deeply nested React component tree and heavy event handlers likely slow down coordinate computation and the scroll-into-view step.\n\n#### 3. First-call penalty on hover/focus (270-330ms)\n\n**Observed**: First `hover` took 273ms, subsequent calls 10-11ms. First `focus` took 329ms, then 24-30ms.\n**Root cause**: JIT compilation or lazy initialization of the coordinate/actionability pipeline. After warm-up, performance stabilizes.\n**Impact**: Minimal — only affects the very first interaction after instance creation.\n\n#### 4. Text extraction is faster than Gmail despite similar DOM size\n\n**Observed**: X text = 1.7s (44KB) vs Gmail text = 2.4s (107KB). HTML size is comparable (~836KB vs ~950KB).\n**Explanation**: Gmail's DOM is more deeply nested with more visible text nodes (email previews, labels, folders). X's timeline has more hidden/clipped content that Turndown skips.\n\n#### 5. `waitForElement` is unreliable after SPA navigation\n\n**Observed**: First call after navigating back to `/home` timed out at 5s. Second call found the element in 736ms. Third call in 72ms.\n**Root cause**: After SPA navigation, X lazy-loads timeline content. The first `article` element may not exist immediately. This is expected behavior, but the 5s default timeout may be too short for slow connections.\n\n### X Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~2200ms |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~4800ms** |\n\nWith `/attach`:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~2600ms** |\n\n---\n\n## Cross-Site Summary\n\n### Performance Tiers by Site\n\n| Endpoint | example.com | Gmail | X | Category |\n|---|---|---|---|---|\n| Simple reads (uri/title/visible) | 3-4ms | 4-40ms | 4-6ms | Fast everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | Slow everywhere — investigate |\n| `GET /html` | 7ms | 1.0s | 252ms | Scales with DOM size |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | **Primary bottleneck** |\n| `POST /text` (fps) | 7ms | **2.7s** | **1.4s** | **Primary bottleneck** |\n| `POST /click` | 165ms | 318ms | 403ms | Scales with DOM complexity |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | Gmail-specific timeout issue |\n| `GET /screenshot` | 76ms | 134ms | 157ms | Scales with pixel content |\n| `GET /ax-tree` | 46B | 46B | 46B | **Broken on all sites** |\n\n### Top Optimization Priorities (updated)\n\n| Priority | Issue | Impact | Affected Sites |\n|---|---|---|---|\n| 1 | **`text` extraction 1.4-2.7s** | Blocks every MCP agent loop | Gmail, X |\n| 2 | **SPA `navigate` 30s timeout** | Completely broken workflow | Gmail |\n| 3 | **`exists` 41-97ms** | 10-25x slower than similar endpoints | All |\n| 4 | **`ax-tree` non-functional** | Accessibility data unavailable | All |\n| 5 | **`click` 165-403ms** | 100ms of fixed `waitForStable` delay | All |\n| 6 | **First-call penalty** | 270-330ms on first hover/focus | X |\n\n---\n\n## Large-Scale Site Benchmark: YouTube\n\nYouTube home page was tested as a heavy media-centric SPA with Web Components (custom elements like `ytd-rich-item-renderer`).\n\n### Test Conditions\n\n- **Page**: `https://www.youtube.com/` (logged in, home feed)\n- **DOM complexity**: ~850KB HTML, Polymer/Lit-based Web Components\n- **Instance creation**: **19.4s** — by far the slowest (heavy JS bundles + video preloading)\n\n### Results: YouTube vs All Sites\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | 3.5ms | Consistent |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | 4.4ms | |\n| `GET /exists` | 41ms | 80ms | 97ms | **33ms** | Fastest — still slow vs uri/title |\n| `GET /html` | 7ms (15KB) | 1.0s (950KB) | 252ms (836KB) | **256ms** (853KB) | Similar to X |\n| `GET /text` | 9ms (270B) | 2.4s (107KB) | 1.7s (44KB) | **960ms** (7.9KB) | Fastest large site — little visible text |\n| `POST /text` (fps) | 7ms (629B) | 2.7s (220KB) | 1.4s (112KB) | **1.0s** (32KB) | |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | 5.0ms (46B) | Still broken |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | 157ms (527KB) | **47ms** (60KB) | Small — dark theme, simple thumbnails |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | 163ms (527KB) | **35ms** (60KB) | Same as viewport |\n| `GET /element` (video) | 4.0ms | 11ms | 11ms (34KB) | 5.0ms (**2B**) | **Empty** — Web Component not traversable |\n| `GET /elementText` (video) | 3.7ms | 13ms | 4.6ms | 4.2ms (**2B**) | **Empty** |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | 4.7ms (`null`) | **null** — selector not found |\n| `GET /isVisible` (search) | 3.3ms | 7.7ms | 3.9ms | 4.9ms (`false`) | Shadow DOM barrier? |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | 3.8ms (2.8KB) | 5.5ms (6.9KB) | |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | 11ms | **8.5ms** | Fast after warm-up (first: 19ms) |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | **6.1ms** | |\n| `POST /focus` | 5.1ms | 42ms | 27ms | **7.5ms** | |\n| `POST /click` | 165ms | 318ms | 403ms | **333ms** (`ok:false`) | **Failed** — click didn't register |\n| `POST /navigate` (SPA) | 49ms | 30s | 175ms | **31ms-2.2s** | Variable — home=2.2s, trending=31ms |\n| `POST /waitForElement` | 3.8ms | 5s | 73ms-5s | **105ms-5s** | `ytd-video-renderer` not found on trending |\n| `POST /regionScreenshot` | - | 39ms | 120ms | **11ms** (12.5KB) | Very fast — small content |\n\n### Key Findings for YouTube\n\n#### 1. Web Components are opaque to element queries\n\n**Severity**: Critical (functional)\n**Observed**: `element?selector=ytd-rich-item-renderer` returns 2 bytes (empty). `attribute?selector=a#video-title-link&name=href` returns `null`. `isVisible?selector=input#search` returns `false`.\n**Root cause**: YouTube uses Polymer/Lit Web Components with Shadow DOM. Standard `querySelector` cannot pierce shadow boundaries. The API's DOM operations only search the light DOM.\n**Impact**: Most element-targeting operations are effectively broken on YouTube. Selectors like `ytd-rich-item-renderer`, `a#thumbnail`, `input#search` exist inside shadow roots and are invisible to the API.\n**Recommendation**: Implement `deepQuerySelector` that traverses into shadow roots, or provide a `piercesShadow: true` option.\n\n#### 2. Click returned `ok:false` on video thumbnail\n\n**Severity**: High\n**Observed**: `POST /click` with `selector: \"a#thumbnail\"` returned `{\"ok\":false}` in 333ms. URL didn't change.\n**Root cause**: Related to Shadow DOM issue — the element was likely found in light DOM but actionability checks or coordinate computation failed because the rendered element is inside a shadow root.\n\n#### 3. Instance creation is extremely slow (19.4s)\n\n**Observed**: 19.4s vs Gmail 4.2s vs X 2.2s vs example.com 6.9s.\n**Root cause**: YouTube loads very heavy JS bundles, preloads video content, and runs extensive initialization. The `load` event fires late.\n**Impact**: First-time access to YouTube via the API is very slow.\n\n#### 4. SPA navigate latency is inconsistent\n\n**Observed**: Navigate to `/feed/trending` = 31ms (fast). Navigate back to home = 2.2s (slow).\n**Root cause**: YouTube's home page triggers heavy content loading (video thumbnails, recommendations). Trending page is lighter. The `load`/`DOMContentLoaded` event timing varies dramatically.\n\n#### 5. Text extraction is fast but returns very little\n\n**Observed**: `GET /text` = 960ms but only 7.9KB of text. Gmail returns 107KB, X returns 44KB.\n**Root cause**: Most of YouTube's visible text is inside Web Components' shadow DOMs. Turndown can only see the light DOM text, which is minimal.\n**Impact**: The text endpoint is nearly useless on YouTube — it misses video titles, descriptions, channel names, etc.\n\n#### 6. Screenshots are very small (60KB)\n\n**Observed**: 47ms for a 60KB screenshot. Gmail = 397KB, X = 527KB.\n**Root cause**: YouTube's dark theme with simple thumbnail grid produces a highly compressible PNG. Screenshots DO render correctly (they capture the visual output, not DOM), so screenshots are the most reliable way to \"see\" YouTube's content.\n\n### YouTube Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time | Status |\n|---|---|---|---|\n| 1. Create instance | `POST /instances` | ~19400ms | Very slow |\n| 2. Get page text | `GET /text` | ~960ms | Fast but mostly empty |\n| 3. Click video | `POST /click` | ~333ms | **FAILS** (Shadow DOM) |\n| 4. Get video text | `GET /text` | ~850ms | Mostly empty |\n| **Total** | | **~21.5s** | **Partially broken** |\n\n**Conclusion**: YouTube is largely non-functional with the current API due to Shadow DOM. Screenshots work, but text extraction and element interaction are severely limited.\n\n---\n\n## Cross-Site Summary (Final)\n\n### Performance Matrix\n\n| Endpoint | example.com | Gmail | X | YouTube | Category |\n|---|---|---|---|---|---|\n| Simple reads | 3-4ms | 4-40ms | 4-6ms | 3-5ms | OK everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | 33ms | Slow everywhere |\n| `GET /html` | 7ms | 1.0s | 252ms | 256ms | Scales with DOM |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | 960ms* | *YouTube: mostly empty |\n| `POST /click` | 165ms | 318ms | 403ms | 333ms** | **YouTube: fails |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | 31ms-2.2s | Gmail broken |\n| `GET /screenshot` | 76ms | 134ms | 157ms | 47ms | Always works |\n| `GET /ax-tree` | 46B | 46B | 46B | 46B | Broken everywhere |\n| Instance creation | 6.9s | 4.2s | 2.2s | **19.4s** | YouTube very slow |\n\n### Final Priority List\n\n| Priority | Issue | Impact | Sites Affected |\n|---|---|---|---|\n| **1** | **Shadow DOM not supported** | Element queries, click, text extraction all fail | YouTube (and any Web Component site) |\n| **2** | **`text` extraction 1-2.7s** | Primary MCP endpoint, blocks every agent loop | Gmail, X, YouTube |\n| **3** | **SPA `navigate` 30s timeout** | Workflow completely blocked | Gmail |\n| **4** | **`ax-tree` non-functional** | Accessibility data unavailable | All sites |\n| **5** | **`exists` 33-97ms** | 10-25x slower than similar endpoints | All sites |\n| **6** | **`click` 165-403ms** | 100ms fixed `waitForStable` delay | All sites |\n| **7** | **Instance creation 2-19s** | Slow first access, especially YouTube | All sites |\n\n---\n\n## Raw Data\n\nAll measurements taken with:\n```bash\ncurl -s -w \"%{time_total}\" -o /dev/null <url>\n```\n\n- Iterations: 3-5 per endpoint\n- Warm-up: Server was idle before measurements; first call to each endpoint may include JIT compilation overhead\n- Pages: `https://example.com` (15KB), Gmail inbox (~950KB, 243 messages), X home timeline (~836KB), YouTube home (~853KB)\n- Network: Localhost loopback (127.0.0.1), no auth token configured\n",".cursorrules":"# Floorp プロジェクトルール\n\nこのプロジェクトは Mozilla Firefox をベースにした Web ブラウザ \"Floorp\" です。\n\n## 必読ドキュメント\n\nコーディング前に以下のドキュメントを参照してください：\n\n- `docs/llm/README.md` - LLM 向けドキュメントの索引\n- `docs/llm/project-overview.md` - プロジェクト全体の概要\n- `docs/llm/development-notes.md` - 開発ガイドとベストプラクティス\n- `docs/llm/architecture-deep-dive.md` - アーキテクチャ詳細\n- `.claude/context.md` - クイックリファレンス\n\n## 技術スタック\n\n- **ランタイム**: Deno 2.x (メイン), Node.js 22 (一部)\n- **UI**: SolidJS (ブラウザクローム), React (設定ページ)\n- **ビルド**: Vite, feles-build\n- **言語**: TypeScript\n- **CSS**: Tailwind CSS\n\n## コーディング規約\n\n### 型定義\n\n**重要**: 型定義は可能な限り別ファイルに分離してください。\n\n```typescript\n// Good: 型定義を types.ts に分離\n// types.ts\nexport interface Config {\n  enabled: boolean;\n  timeout: number;\n}\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n\n// Bad: 実装と型を混在させる\nexport interface Config { /* ... */ }\nexport class Feature { /* ... */ }\n```\n\n**例外**: `.sys.mts` ファイルでは Firefox API との統合のため、型定義を同じファイルに書いても構いません。\n\n### TypeScript\n\n- `any` 型は避ける\n- 明確な型定義を使用\n- 型推論を活用\n- null/undefined のチェックを忘れずに\n\n```typescript\n// Good\ninterface User {\n  id: number;\n  name: string;\n}\n\nfunction getUser(id: number): User | null {\n  // ...\n}\n\n// Bad\nfunction getUser(id: any): any {\n  // ...\n}\n```\n\n### SolidJS (ブラウザクローム機能)\n\n- リアクティブな状態管理には `createSignal` を使用\n- 直接変数を変更しない\n- HMR サポートのために `@noraComponent(import.meta.hot)` デコレーターを使用\n\n```typescript\n// Good\nimport { createSignal } from \"solid-js\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n\n// Bad\nlet count = 0;\ncount++; // 動作しない\n```\n\n### React (設定ページ)\n\n- 関数コンポーネントを使用\n- Hooks を適切に使用\n- Tailwind CSS でスタイリング\n\n```typescript\n// Good\nexport default function SettingsPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### ファイル配置\n\n- **ブラウザ UI 機能**: `browser-features/chrome/common/{feature-name}/`\n- **Firefox API モジュール**: `browser-features/modules/modules/{module-name}.sys.mts`\n- **設定ページ**: `browser-features/pages-settings/src/pages/`\n- **型定義**: 各機能の `types.ts` ファイル（`.sys.mts` を除く）\n\n### エラーハンドリング\n\n常に適切なエラーハンドリングを実装してください。\n\n```typescript\n// Good\ntry {\n  const data = await fetchData(url);\n  return data;\n} catch (error) {\n  console.error(\"[FeatureName] Failed to fetch:\", error);\n  return null; // フォールバック\n}\n\n// Bad\nconst data = await fetchData(url); // エラーが伝播\n```\n\n### コメント\n\n- 複雑なロジックには日本語または英語でコメントを追加\n- 関数の目的は JSDoc で説明\n- TODO コメントには担当者を明記\n\n```typescript\n/**\n * ユーザー設定を取得します\n * @param userId ユーザー ID\n * @returns ユーザー設定オブジェクト、存在しない場合は null\n */\nfunction getUserConfig(userId: string): UserConfig | null {\n  // TODO(@username): キャッシュ機構を実装\n  return null;\n}\n```\n\n## 新機能追加のチェックリスト\n\n1. **適切な場所に配置**\n   - ブラウザ UI → `browser-features/chrome/common/`\n   - システムモジュール → `browser-features/modules/modules/`\n   - 設定ページ → `browser-features/pages-settings/`\n\n2. **型定義を別ファイルに**\n   - `types.ts` を作成（`.sys.mts` 以外）\n   - インターフェースと型を定義\n\n3. **HMR サポートを追加**（ブラウザクローム機能のみ）\n   ```typescript\n   @noraComponent(import.meta.hot)\n   export default class MyFeature extends NoraComponentBase {\n     init(): void { /* ... */ }\n   }\n   ```\n\n4. **機能を登録**\n   - `browser-features/chrome/common/mod.ts` に追加\n\n5. **翻訳を追加**\n   - 少なくとも `i18n/en-US/` と `i18n/ja-JP/` に追加\n\n6. **必要に応じて Actor を追加**（マルチプロセス通信が必要な場合）\n   - Parent: `browser-features/modules/actors/{Name}Parent.sys.mts`\n   - Child: `browser-features/modules/actors/{Name}Child.sys.mts`\n   - 登録: `browser-features/modules/modules/BrowserGlue.sys.mts`\n\n## 開発コマンド\n\n```bash\n# 開発モード（HMR 付き）\ndeno task feles-build dev\n\n# 本番ビルド\ndeno task feles-build build\n\n# ステージングビルド\ndeno task feles-build stage\n\n# 依存関係のインストール\ndeno install\n```\n\n## モジュールパスエイリアス\n\n```typescript\nimport { foo } from \"#i18n/utils\";           // i18n/\nimport { bar } from \"#chrome/common/tab\";    // chrome/\nimport { baz } from \"#libs/shared\";          // libs/\nimport { qux } from \"#modules/experiments\";  // browser-features/modules/\n```\n\n## よくある問題\n\n### HMR が動作しない\n- `@noraComponent(import.meta.hot)` デコレーターが付いているか確認\n- `NoraComponentBase` を継承しているか確認\n\n### Firefox API にアクセスできない\n- `.sys.mts` ファイルから ChromeUtils.importESModule() を使用\n\n### 型エラー\n- 型定義を別ファイル（`types.ts`）に分離\n- `any` 型を使用していないか確認\n\n## パフォーマンス\n\n- `init()` メソッドで重い処理を避ける\n- 遅延初期化を活用\n- イベントリスナーを適切にクリーンアップ\n- メモリリークに注意\n\n## テスト\n\n- 新機能には可能な限りテストを追加\n- テストは `browser-features/chrome/test/unit/` に配置\n- Deno のテストフレームワークを使用\n\n## Git コミット\n\n- 意味のあるコミットメッセージ\n- 1 コミット = 1 つの論理的な変更\n- コミット前に `deno fmt` で整形\n\n## 参考リンク\n\n- プロジェクトドキュメント: `docs/llm/`\n- Deno: https://docs.deno.com/\n- SolidJS: https://www.solidjs.com/\n- React: https://react.dev/\n- Firefox Source: https://firefox-source-docs.mozilla.org/\n\n---\n\nこれらのルールに従って、一貫性のある高品質なコードを書いてください。\n","AGENTS.md":"# AGENTS.md\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Runtime changes\n\nRuntime changes must be maintained as patches, not direct edits to a sibling\nFloorp-Runtime checkout. Cross-platform source patches belong in\n`.github/patches/floorp-runtime/common/` and are applied by `package.yml`.\nValidate them against the source commit in `floorp-runtime.lock.json` in isolation.\nThe package workflow uses prebuilt native artifacts; changes requiring native\nrecompilation cannot be delivered through source patches in that step alone.\n\n## Architecture (5 Layers)\n\n```text\nFirefox Base  <- patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     |\nESM Modules   <- .sys.mts files with direct Firefox API access, Window Actors\n     |\nBridge        <- startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     |\nChrome UI     <- SolidJS -> XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     |\nPages         <- React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              -> ./i18n/\n#chrome/            -> ./chrome/\n#libs/              -> ./libs/\n#features-chrome/   -> ./browser-features/chrome/\n#modules/           -> ./browser-features/modules/\n#ui/                -> ./src/ui/\n#themes/            -> ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` -- adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state -- never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174-5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool -- Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot -> _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) -- browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` -- web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` -- launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` -- check for runtime errors\n4. `deno task dev-tool eval \"...\"` -- inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` -- visually verify UI changes\n6. `deno task dev-tool rebuild` -- if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` -- shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` -- Full project overview\n- `docs/llm/architecture-deep-dive.md` -- 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` -- Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n","CLAUDE.md":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Architecture (5 Layers)\n\n```notes\nFirefox Base  ← patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     ↓\nESM Modules   ← .sys.mts files with direct Firefox API access, Window Actors\n     ↓\nBridge        ← startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     ↓\nChrome UI     ← SolidJS → XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     ↓\nPages         ← React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              → ./i18n/\n#chrome/            → ./chrome/\n#libs/              → ./libs/\n#features-chrome/   → ./browser-features/chrome/\n#modules/           → ./browser-features/modules/\n#ui/                → ./src/ui/\n#themes/            → ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` — adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state — never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174–5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool — Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot → _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) — browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` — web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` — launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` — check for runtime errors\n4. `deno task dev-tool eval \"...\"` — inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` — visually verify UI changes\n6. `deno task dev-tool rebuild` — if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` — shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` — Full project overview\n- `docs/llm/architecture-deep-dive.md` — 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` — Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n",".github/copilot-instructions.md":"# AI Coding Agent Instructions\n\nThis workspace contains multiple interconnected projects: **Floorp** (Firefox-based browser), **Sapphillon** (workflow automation backend), **Floorp-OS-Automator-Frontend**, and **web-store**.\n\n## Project Overview\n\n### Floorp (`floorp/`)\nFirefox-based browser built with Deno 2.x, SolidJS, and React. Custom browser features overlay Firefox's Gecko engine.\n\n### Sapphillon Backend (`Floorp-OS-Automator-Backend/`)\nRust-based workflow automation backend using gRPC (tonic), SeaORM, and Deno runtime for executing JavaScript workflows.\n\n### Frontend Projects\n- **Floorp-OS-Automator-Frontend**: React + TypeScript + Vite UI for workflow management\n- **web-store**: Plugin marketplace with React + Vite\n\n---\n\n## Cross-Project Integration\n\nThis workspace contains interconnected projects. Understanding data flow and integration points is crucial for full-stack development.\n\n### Data Flow Architecture\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│                    Floorp Browser                        │\n│              (Mozilla Firefox + Custom Features)           │\n│  Location: /Users/user/dev-source/floorp-dev/floorp/     │\n│  Dev: deno task dev (ports: 5173-5186)              │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ Floorp OS API (OpenAPI)\n                          │ openapi.yaml:\n                          │ Floorp-OS-Automator-Backend/plugins/floorp/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│              Sapphillon Backend (Rust)                │\n│  Location: ../Floorp-OS-Automator-Backend/          │\n│  Dev: make run (gRPC on localhost:50051)            │\n│  - Plugin system (floorp, fetch, filesystem, etc.)    │\n│  - Workflow engine (Deno Core runtime)                 │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ gRPC (tonic + prost)\n                          │ protobuf in:\n                          │ Floorp-OS-Automator-Frontend/vender/Sapphillon_API/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│         Floorp-OS-Automator-Frontend (React)          │\n│  Location: ../Floorp-OS-Automator-Frontend/          │\n│  Dev: pnpm dev (port 8081)                          │\n│  - gRPC-Web client (@connectrpc/connect-web)           │\n│  - Workflow management UI                                │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ (optional, disabled)\n                          │ PostMessage to Floorp\n                          │ Progress Window\n                          ▼\n                   ┌────────────────┐\n                   │  Floorp       │\n                   │  Progress     │\n                   │  Window       │\n                   └────────────────┘\n\n                          ▲\n                          │\n                ┌─────────┴──────────┐\n                │                    │\n┌───────────────┐      ┌────────────────┐\n│  Web Store    │      │  External     │\n│  (Plugin      │      │  Plugins     │\n│   Marketplace)│      │              │\n└───────────────┘      └────────────────┘\n```\n\n### Integration Points\n\n**1. Floorp → Sapphillon** (Browser Automation):\n- Floorp exposes browser automation via OpenAPI spec at `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`\n- Sapphillon's `floorp` plugin consumes this API to control browser tabs, navigation, etc.\n- Workflows can automate browser interactions (open tabs, navigate, fill forms)\n\n**2. Sapphillon → Frontend** (Workflow Management):\n- gRPC communication using `tonic` (server) and `@connectrpc/connect-web` (client)\n- Protobuf definitions in `Floorp-OS-Automator-Frontend/vender/Sapphillon_API/proto/`\n- Frontend generates TypeScript clients from `.proto` files\n- Services: Workflow, Plugin, Version, Model, Provider\n\n**3. Frontend → Floorp** (Progress Tracking):\n- Disabled by default (see `lib/workflow-progress.ts`)\n- Uses `window.OSAutomotor?.sendWorkflowProgress()` for real-time updates\n- Would show workflow progress in Floorp's native progress window\n\n**4. Web Store → Sapphillon** (Plugin Distribution):\n- Plugin marketplace at `../web-store/`\n- Plugins installed via Sapphillon's plugin installer\n- External plugins run in separate processes with gRPC communication\n\n### Development Setup for Full Stack\n\n**Recommended workflow for full-stack development**:\n```bash\n# Terminal 1: Start Floorp Browser\ncd /Users/user/dev-source/floorp-dev/floorp\ndeno task dev\n\n# Terminal 2: Start Sapphillon Backend\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Backend\nmake run  # Starts gRPC server on localhost:50051\n\n# Terminal 3: Start Frontend (production mode)\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:prod  # Connects to localhost:50051\n```\n\n**Frontend-only development** (no backend needed):\n```bash\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:mock  # Mock gRPC on port 50099, Vite on 5199\n```\n\n---\n\n## Floorp Development Patterns\n\n### Build System\n- **Primary**: `deno task dev` - Runs custom feles-build system\n- **Build orchestration**: `tools/feles-build.ts` orchestrates patches, symlinks, Vite dev servers\n- **Dev server ports**: 5173 (main), 5178 (settings), 5186 (newtab), 5174-5177 (other pages)\n\n### Code Organization\n\n**Type Definitions**: Always separate types into dedicated files (`types.ts`), not mixed with implementation.\n```typescript\n// Good: types.ts\nexport interface Config { enabled: boolean; }\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n```\n**Exception**: `.sys.mts` files can include types with Firefox API integration.\n\n**File Extensions**:\n- `.ts` - General TypeScript\n- `.sys.mts` - Firefox ESM modules (loaded via `ChromeUtils.importESModule()`)\n- `.jsx` - React components in pages-*/ directories\n\n### UI Framework Usage\n\n**SolidJS** (`browser-features/chrome/`):\n- Use `createSignal` for reactive state (never mutate directly)\n- `@noraComponent(import.meta.hot)` decorator for HMR support\n- Import from `@nora/solid-xul` for rendering:\n```typescript\nimport { render, createSignal } from \"@nora/solid-xul\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n```\n\n**React** (`browser-features/pages-*/`):\n- Functional components with hooks\n- Tailwind CSS for styling\n- `import { createRootHMR } from \"@nora/solid-xul\"` for i18n integration\n\n### Firefox API Integration\nAccess Firefox APIs via ESM modules in `.sys.mts` files:\n```typescript\nconst { I18nUtils } = ChromeUtils.importESModule(\"resource://floorp/lib/I18nUtils.sys.mjs\");\n```\n\n---\n\n## Sapphillon Backend Patterns\n\n### Architecture\n- **gRPC Service Layer**: `src/services/` - Tonic-based services (workflow, plugin, model, version, provider)\n- **Plugin System**: Modular plugins in `plugins/` (fetch, filesystem, floorp, vscode, git, finder, etc.)\n- **Database**: SeaORM with SQLite, migrations in `migration/`, entities in `entity/`\n- **Workflow Engine**: Deno Core runtime executes JavaScript workflows with plugin permissions\n\n### Common Commands\n```bash\nmake rust_test          # Run all workspace tests\nmake rust_build         # Build entire workspace\nmake migrate            # Run SeaORM migrations\nmake entity_generate    # Generate entities from DB\nmake run                # Run with debug DB at ./debug/sqlite.db\nmake grpcui            # Launch gRPC UI on localhost:50051\n```\n\n### Testing\n- Unit tests: `cargo test --lib`\n- External plugin tests: `cargo test --test external_plugin`\n- Ignored tests: `cargo test --lib external_plugin -- --ignored`\n\n### Plugin Development\nEach plugin crate exposes Deno-compatible functions. See `plugins/floorp/` for OpenAPI-based Floorp browser control.\n\n**Debug Workflows**: Place JS files in `debug_workflow/` directory - auto-registered every 10s in debug builds with full permissions (`[DEBUG]` prefix).\n\n### gRPC & Protocol Buffers\n- Uses `tonic` for server, `prost` for code generation\n- `buf.yaml` and `buf.gen.yaml` configuration\n- Generate with `buf generate`\n\n---\n\n## Frontend Patterns (Both Projects)\n\n### Build Commands\n```bash\nnpm run dev              # Vite dev server\nnpm run build            # TypeScript check + Vite build\nnpm run test             # Vitest\nnpm run lint             # ESLint\n```\n\n### Component Patterns\n- **Chakra UI**: Primary component library\n- **i18next**: Internationalization via `src/i18n/config.ts`\n- **React Router**: Routing in `src/routes/`\n- **Type Definitions**: Export from `src/types/`, not inline\n\n### gRPC Communication\n- `@connectrpc/connect-web` for browser-based gRPC\n- `@connectrpc/connect` for Node-based\n- Generated clients in `src/gen/` from proto definitions\n\n---\n\n## Cross-Project Integration\n\n### Floorp OS API\nFloorp exposes browser automation via OpenAPI spec in `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`. The Sapphillon floorp plugin consumes this for workflow automation.\n\n### Data Flow\n```\nFloorp Browser\n    ↓ (Floorp OS API)\nSapphillon Backend (floorp plugin)\n    ↓ (gRPC)\nFloorp-OS-Automator-Frontend\n```\n\n### Plugin System\nWorkflows in Sapphillon can invoke plugins including:\n- **floorp**: Control Floorp browser (tabs, navigation, etc.)\n- **fetch**: HTTP requests\n- **filesystem**: File operations\n- **vscode**: VS Code control\n- **finder**: macOS Finder automation\n- And more in `plugins/`\n\n---\n\n## Key Conventions\n\n### Error Handling\n- **Floorp**: Use `Result<T, E>` from fp-ts for type-safe error handling\n- **Sapphillon**: `anyhow::Result<T>` and `tonic::Status` for gRPC errors\n\n### State Management\n- **SolidJS**: `createSignal` - never mutate directly\n- **React**: `useState`, `useContext` for global state\n\n### Database Operations\n- Use SeaORM `Entity::find().all(db).await?` pattern\n- Migrations: `sea-orm-cli migrate generate <name>`\n- Entities are auto-generated - don't edit manually\n\n### Permissions\nSapphillon uses wildcard `*` plugin_function_id to grant workflows full access. Used for trusted workflows and testing.\n\n---\n\n## Language-Specific Notes\n\n### Rust\n- Edition 2024, workspace resolver \"3\"\n- Async/await with tokio runtime\n- `#[tonic::async_trait]` for gRPC service implementations\n\n### TypeScript/Deno\n- No `any` types - use explicit types or `unknown`\n- Null/undefined checks required\n- Deno permissions: `--allow-all` often needed for build scripts\n\n### React\n- Functional components only\n- Hooks over class components\n- Tailwind CSS classes (e.g., `className=\"p-4\"`)\n\n---\n\n## Critical Files Reference\n\n| Purpose | File |\n|---------|------|\n| Floorp build system | `floorp/tools/feles-build.ts` |\n| Floorp dev config | `floorp/deno.json` |\n| Sapphillon main entry | `Floorp-OS-Automator-Backend/src/main.rs` |\n| Sapphillon workflow service | `Floorp-OS-Automator-Backend/src/services/workflow.rs` |\n| Frontend Vite config | `Floorp-OS-Automator-Frontend/vite.config.ts` |\n| Floorp SolidJS renderer | `floorp/libs/solid-xul/index.ts` |\n| Plugin permissions | `Floorp-OS-Automator-Backend/src/services/workflow.rs:make_plugin_permission()` |\n"},"items":[{"name":"AGENTS.md","path":"AGENTS.md","rawUrl":"https://raw.githubusercontent.com/Floorp-Projects/Floorp/HEAD/AGENTS.md","title":"AI Agent Protocol & Instructions","category":"root-instruction","format":"markdown","content":"# AGENTS.md\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Runtime changes\n\nRuntime changes must be maintained as patches, not direct edits to a sibling\nFloorp-Runtime checkout. Cross-platform source patches belong in\n`.github/patches/floorp-runtime/common/` and are applied by `package.yml`.\nValidate them against the source commit in `floorp-runtime.lock.json` in isolation.\nThe package workflow uses prebuilt native artifacts; changes requiring native\nrecompilation cannot be delivered through source patches in that step alone.\n\n## Architecture (5 Layers)\n\n```text\nFirefox Base  <- patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     |\nESM Modules   <- .sys.mts files with direct Firefox API access, Window Actors\n     |\nBridge        <- startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     |\nChrome UI     <- SolidJS -> XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     |\nPages         <- React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              -> ./i18n/\n#chrome/            -> ./chrome/\n#libs/              -> ./libs/\n#features-chrome/   -> ./browser-features/chrome/\n#modules/           -> ./browser-features/modules/\n#ui/                -> ./src/ui/\n#themes/            -> ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` -- adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state -- never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174-5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool -- Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot -> _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) -- browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` -- web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` -- launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` -- check for runtime errors\n4. `deno task dev-tool eval \"...\"` -- inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` -- visually verify UI changes\n6. `deno task dev-tool rebuild` -- if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` -- shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` -- Full project overview\n- `docs/llm/architecture-deep-dive.md` -- 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` -- Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n","isInternal":false,"tokens":2320,"sizeBytes":9819},{"name":"perf-report-2026-03-24.md","path":"tools/os-test/perf-report-2026-03-24.md","rawUrl":"https://raw.githubusercontent.com/Floorp-Projects/Floorp/HEAD/tools/os-test/perf-report-2026-03-24.md","title":"Os-test Skill","category":"anthropic-skill","format":"markdown","content":"# Floorp OS API Server Performance Report\n\n- **Date**: 2026-03-24\n- **Environment**: Windows 11 Pro, dev build (`deno task dev`)\n- **Target page**: `https://example.com`\n- **Server**: `http://127.0.0.1:58261`\n- **Method**: curl with `%{time_total}`, 3-5 iterations per endpoint, median reported\n\n---\n\n## Summary\n\n| Category | Endpoint Count | Latency Range | Assessment |\n|---|---|---|---|\n| Tier 1: Instant | 18 | < 5ms | Excellent |\n| Tier 2: Fast | 8 | 5-10ms | Good |\n| Tier 3: Moderate | 4 | 40-100ms | Acceptable (I/O bound) |\n| Tier 4: Slow | 2 | > 100ms | Needs investigation |\n\n**Overall**: Most endpoints respond in under 5ms. The server's HTTP routing and IPC layer add minimal overhead (~2-3ms baseline from `/health`). Performance bottlenecks are concentrated in a few specific operations.\n\n---\n\n## Detailed Results\n\n### Tier 1: Instant (< 5ms)\n\nThese endpoints respond near the server's baseline latency. No optimization needed.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/health` | GET | 2.7ms | 7.4ms | 17B |\n| `/tabs/list` | GET | 3.0ms | 3.4ms | - |\n| `/browser/tabs` | GET | 2.9ms | 3.3ms | - |\n| `/workspaces` | GET | 2.8ms | 4.0ms | - |\n| `/instances/:id/cookies` | GET | 2.8ms | 5.9ms | - |\n| `/instances/:id/uri` | GET | 3.8ms | 4.8ms | 33B |\n| `/instances/:id/title` | GET | 4.1ms | 7.5ms | 27B |\n| `/instances/:id/element?selector=h1` | GET | 4.0ms | 4.6ms | 36B |\n| `/instances/:id/elementText?selector=h1` | GET | 3.7ms | 4.1ms | 26B |\n| `/instances/:id/elementTextContent?selector=h1` | GET | 4.0ms | 4.4ms | 26B |\n| `/instances/:id/attribute?selector=a&name=href` | GET | 3.8ms | 4.3ms | 47B |\n| `/instances/:id/isVisible?selector=a` | GET | 3.3ms | 3.9ms | 16B |\n| `/instances/:id/isEnabled?selector=a` | GET | 3.7ms | 3.8ms | 16B |\n| `/instances/:id/ax-tree` | GET | 2.7ms | 3.0ms | 46B |\n| `/instances/:id/waitForElement` (existing) | POST | 3.8ms | 4.6ms | 27B |\n| `/instances/:id/clearEffects` | POST | 3.4ms | 4.0ms | 11B |\n| `/instances/:id/article` | GET | 2.8ms | 14.8ms | 36B |\n| `DELETE /instances/:id` | DELETE | 3.0ms | - | 11B |\n\n### Tier 2: Fast (5-10ms)\n\nSlightly above baseline due to DOM traversal, serialization, or coordinate computation.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/instances/:id/html` | GET | 6.5ms | 6.7ms | ~15KB |\n| `/instances/:id/text` | GET | 8.7ms | 11.3ms | 270B |\n| `POST /instances/:id/text` (fingerprints) | POST | 6.7ms | 8.3ms | 629B |\n| `/instances/:id/hover` | POST | 6.7ms | 8.5ms | 11B |\n| `/instances/:id/scrollTo` | POST | 5.7ms | 6.5ms | 11B |\n| `/instances/:id/focus` | POST | 5.1ms | 7.2ms | 11B |\n| `/browser/history?limit=10` | GET | 3.5ms | 4.0ms | - |\n| `/browser/context` | GET | 4.8ms | 143.7ms | - |\n\n**Note**: `/browser/context` has an occasional spike (~144ms) likely caused by GC pause or event loop contention.\n\n### Tier 3: Moderate (40-100ms)\n\nLatency is driven by I/O (network, rendering engine).\n\n| Endpoint | Method | Median | p95 | Payload | Bottleneck |\n|---|---|---|---|---|---|\n| `/instances/:id/exists` | GET | **41ms** | 99ms | 15B | Unknown - needs investigation |\n| `/instances/:id/navigate` | POST | **49ms** | 59ms | 11B | Network round-trip |\n| `/instances/:id/screenshot` | GET | **76ms** | 80ms | 217KB | Canvas rendering + PNG encode |\n| `/instances/:id/fullPageScreenshot` | GET | **86ms** | 92ms | 217KB | Canvas rendering + PNG encode |\n\n### Tier 4: Slow (> 100ms)\n\n| Endpoint | Method | Median | p95 | Bottleneck |\n|---|---|---|---|---|\n| `POST /instances/:id/click` | POST | **165ms** | 230ms | `waitForStable` 100ms delay + actionability checks |\n| `POST /instances` (create) | POST | **6.9s** | - | Tab creation + full page load |\n\n---\n\n## Analysis & Recommendations\n\n### 1. `/exists` is 10x slower than similar read endpoints (41ms vs 3-4ms)\n\n**Expected**: `exists` should be a simple lookup (like `uri` or `title`).\n**Observed**: 41ms median, with first call at 99ms.\n**Action**: Investigate the implementation. Likely doing an unnecessary async round-trip to the content process or awaiting a promise that could be resolved synchronously.\n\n### 2. `/click` latency is dominated by `waitForStable` (100ms fixed delay)\n\n**Breakdown**:\n- `waitForStable`: 100ms (fixed `timerSetTimeout`)\n- Actionability checks + scroll: ~15ms\n- `sendMouseEvent`: ~5ms\n- IPC overhead: ~45ms\n\n**Tradeoff**: The 100ms delay catches CSS transitions/animations. Removing it risks clicking moving elements. Consider:\n- Making `waitForStable` timeout configurable via request body (e.g., `stabilityTimeout: 50`)\n- Reducing default from 100ms to 50ms for simple pages\n- Skipping entirely when `force: true` (already implemented)\n\n### 3. Instance creation is very slow (6.9s)\n\nThis includes full page load (`https://example.com`). The time is mostly network + rendering. Consider:\n- Allowing `POST /instances` to return immediately after tab creation (before load completes)\n- Adding a separate `waitForLoad` endpoint for callers that need load completion\n\n### 4. Screenshot latency is reasonable (76-86ms)\n\nFor PNG encoding of a full viewport, 76ms is acceptable. If lower latency is needed:\n- Consider JPEG output option (faster encoding, smaller payload)\n- Consider returning raw bitmap data for local consumers\n\n### 5. Occasional spikes (~150ms) on fast endpoints\n\nObserved on `/isEnabled` (157ms) and `/browser/context` (144ms). These are likely:\n- JavaScript GC pauses in the parent process\n- Event loop contention from other Floorp operations\n- Not actionable without profiling, and acceptable for an API server\n\n### 6. `/ax-tree` returns only 46 bytes\n\nFor `example.com` this returned `{\"error\":\"ax-tree not available\"}` or a minimal response. Needs verification that the accessibility tree is being correctly extracted for complex pages.\n\n---\n\n## Latency Budget (typical MCP tool call)\n\nA typical MCP interaction involves multiple API calls. Example workflow:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~7000ms |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Wait for navigation | `POST /waitForElement` | ~4ms |\n| 5. Get new text | `GET /text` | ~9ms |\n| 6. Cleanup | `DELETE /instances/:id` | ~3ms |\n| **Total** | | **~7190ms** |\n\nWithout instance creation (reusing existing tab via `/attach`):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Get new text | `GET /text` | ~9ms |\n| **Total** | | **~188ms** |\n\n*Estimated based on similar lightweight operations.\n\n**Conclusion**: Instance creation dominates total latency. For interactive use, reusing tabs via `/attach` brings total workflow time under 200ms, which is excellent.\n\n---\n\n## Large-Scale Site Benchmark: Gmail\n\nGmail (inbox with 243 messages) was tested to evaluate performance on a complex, real-world SPA with heavy DOM.\n\n### Test Conditions\n\n- **Page**: `https://mail.google.com/mail/u/0/#inbox` (logged in, 243 messages)\n- **DOM complexity**: ~1MB HTML, deeply nested SPA structure\n- **Instance creation**: 4.2s (faster than example.com — likely cached assets)\n\n### Results Comparison: example.com vs Gmail\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 1.0x | No DOM access needed |\n| `GET /title` | 4.1ms | 40ms | **10x** | Spikes to 449ms observed |\n| `GET /exists` | 41ms | 80ms | **2x** | Consistently slow |\n| `GET /html` | 6.5ms (15KB) | **1.0s** (950KB) | **150x** | Serializing ~1MB DOM |\n| `GET /text` | 8.7ms (270B) | **2.4s** (107KB) | **275x** | DOM traversal + Turndown conversion |\n| `POST /text` (fps) | 6.7ms (629B) | **2.7s** (220KB) | **400x** | + fingerprint generation |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 1.5x | Returns 46B on both — likely broken |\n| `GET /screenshot` | 76ms (217KB) | **134ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /fullPageScreenshot` | 86ms (217KB) | **157ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /element` | 4.0ms | 11ms | 2.8x | |\n| `GET /elementText` | 3.7ms | 13ms | 3.5x | |\n| `GET /attribute` | 3.8ms | 7.0ms | 1.8x | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 2.3x | |\n| `GET /cookies` | 2.8ms | **8.8ms** (14KB) | 3.1x | More cookies on Google |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | **73ms** | **11x** | Coordinate computation on complex layout |\n| `POST /scrollTo` | 5.7ms | **45ms** | **8x** | First call 111ms (layout recalc?) |\n| `POST /focus` | 5.1ms | **42ms** | **8x** | First call 112ms |\n| `POST /click` | 165ms | **318ms** | 1.9x | waitForStable + complex layout |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **600x** | SPA doesn't fire `load` event |\n| `GET /regionScreenshot` | - | 39ms (68KB) | - | Efficient partial capture |\n\n### Critical Issues Found\n\n#### 1. `navigate` times out on SPA pages (30s)\n\n**Severity**: Critical\n**Observed**: `POST /navigate` to `#inbox` on Gmail takes exactly 30 seconds — hitting the timeout.\n**Root cause**: `navigate` waits for a `load` event, but Gmail is a SPA that uses `pushState`/`hashchange` for navigation. The `load` event never fires for in-app navigations.\n**Impact**: Any workflow that navigates within a SPA (Gmail, YouTube, Twitter, etc.) will block for 30 seconds.\n**Recommendation**: Detect SPA navigation (same-origin hash/pushState changes) and resolve immediately or use a shorter timeout with `DOMContentLoaded` / network idle detection.\n\n#### 2. `text` extraction takes 2.4-3.7s on complex pages\n\n**Severity**: High\n**Observed**: `GET /text` = 2.4s, `POST /text` with fingerprints = 2.7s (107-220KB output).\n**Root cause**: Turndown (HTML-to-Markdown) conversion traverses the entire DOM tree. Gmail's DOM is extremely deep (~1MB HTML).\n**Impact**: This is the primary endpoint for MCP tool use — AI agents call `text` on every page interaction. 2-3s per call significantly impacts agent loop latency.\n**Recommendation**:\n- Support `selector` scoping in GET/POST to limit traversal (e.g., only extract the email list, not the entire UI)\n- Consider caching/diffing for repeated calls on the same page state\n- Profile Turndown to find hotspots (likely in node visibility checks)\n\n#### 3. `html` takes 1s for ~1MB\n\n**Severity**: Medium\n**Observed**: 1.0s to serialize and transfer ~950KB of HTML.\n**Root cause**: Combination of `outerHTML` serialization in content process + IPC transfer + HTTP response writing.\n**Impact**: Less critical than `text` since `html` is used less frequently, but still notable.\n\n#### 4. `title` has unpredictable latency (4ms to 449ms)\n\n**Severity**: Low\n**Observed**: Varies from 4ms to 449ms across 5 calls on Gmail.\n**Root cause**: Likely contention with Gmail's JavaScript execution (timers, XHR callbacks, mutation observers).\n**Impact**: Usually fast, but occasional spikes could affect perceived responsiveness.\n\n#### 5. `ax-tree` returns 46 bytes on Gmail\n\n**Severity**: Medium (functional issue)\n**Observed**: Same 46-byte response on both example.com and Gmail. This is likely `{\"error\":\"...\"}` or an empty tree.\n**Impact**: Accessibility tree is unusable. Should be investigated separately.\n\n### Gmail Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~4200ms |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~11s** |\n\nWith `/attach` (reusing existing tab):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~6.8s** |\n\n**Conclusion**: On large-scale SPAs, `text` extraction dominates latency at 2-4s per call. This is 250-400x slower than on simple pages. Scoped text extraction (passing a selector to limit DOM traversal) would be the highest-impact optimization.\n\n---\n\n## Large-Scale Site Benchmark: X (Twitter)\n\nX home timeline was tested as another complex SPA with infinite scroll and dynamic content loading.\n\n### Test Conditions\n\n- **Page**: `https://x.com/home` (logged in, home timeline)\n- **DOM complexity**: ~836KB HTML, React-based SPA\n- **Instance creation**: 2.2s\n\n### Results: X vs Gmail vs example.com\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | Consistent across all |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | Gmail is the outlier |\n| `GET /exists` | 41ms | 80ms | **97ms** | Consistently slow on all sites |\n| `GET /html` | 6.5ms (15KB) | 1.0s (950KB) | **252ms** (836KB) | X DOM is similar size but faster |\n| `GET /text` | 8.7ms (270B) | 2.4s (107KB) | **1.7s** (44KB) | Heavy DOM traversal |\n| `POST /text` (fps) | 6.7ms (629B) | 2.7s (220KB) | **1.4s** (112KB) | Fingerprint version faster than plain on X |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | Broken on all sites |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | **157ms** (527KB) | Scales with image size |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | **163ms** (527KB) | |\n| `GET /element` (article) | 4.0ms | 11ms | **11ms** (34KB) | X articles are large |\n| `GET /elementText` | 3.7ms | 13ms | **4.6ms** | |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 3.9ms | |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | **3.8ms** (2.8KB) | Fewer cookies than Gmail |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | **11ms** | First call 273ms (cold), then 10-11ms |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | `article:nth-of-type(3)` returned `ok:false` — not found |\n| `POST /focus` | 5.1ms | 42ms | **27ms** | First call 329ms (cold), then 24-30ms |\n| `POST /click` | 165ms | 318ms | **403ms** | Slowest of all three sites |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **175ms / 45ms** | X works! No load event issue |\n| `POST /waitForElement` | 3.8ms | 5s (timeout) | **73ms-5s** | Inconsistent — first call timed out |\n| `POST /regionScreenshot` | - | 39ms | **120-197ms** | Higher on X |\n\n### Key Findings for X\n\n#### 1. SPA Navigate works on X but not Gmail\n\n**Observed**: `POST /navigate` to `/explore` took 175ms, back to `/home` took 45ms. No 30s timeout.\n**Explanation**: X likely triggers a full page `load` event on navigation (or uses a different routing strategy than Gmail). This confirms the Gmail timeout is specific to Gmail's SPA implementation, not a universal SPA issue.\n\n#### 2. Click is slowest on X (403ms)\n\n**Observed**: 403ms on X vs 318ms on Gmail vs 165ms on example.com.\n**Breakdown estimate**: waitForStable 100ms + actionability checks on complex DOM ~50ms + scroll/coordinate computation ~150ms + sendMouseEvent ~5ms + IPC overhead ~100ms.\n**Root cause**: X's deeply nested React component tree and heavy event handlers likely slow down coordinate computation and the scroll-into-view step.\n\n#### 3. First-call penalty on hover/focus (270-330ms)\n\n**Observed**: First `hover` took 273ms, subsequent calls 10-11ms. First `focus` took 329ms, then 24-30ms.\n**Root cause**: JIT compilation or lazy initialization of the coordinate/actionability pipeline. After warm-up, performance stabilizes.\n**Impact**: Minimal — only affects the very first interaction after instance creation.\n\n#### 4. Text extraction is faster than Gmail despite similar DOM size\n\n**Observed**: X text = 1.7s (44KB) vs Gmail text = 2.4s (107KB). HTML size is comparable (~836KB vs ~950KB).\n**Explanation**: Gmail's DOM is more deeply nested with more visible text nodes (email previews, labels, folders). X's timeline has more hidden/clipped content that Turndown skips.\n\n#### 5. `waitForElement` is unreliable after SPA navigation\n\n**Observed**: First call after navigating back to `/home` timed out at 5s. Second call found the element in 736ms. Third call in 72ms.\n**Root cause**: After SPA navigation, X lazy-loads timeline content. The first `article` element may not exist immediately. This is expected behavior, but the 5s default timeout may be too short for slow connections.\n\n### X Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~2200ms |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~4800ms** |\n\nWith `/attach`:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~2600ms** |\n\n---\n\n## Cross-Site Summary\n\n### Performance Tiers by Site\n\n| Endpoint | example.com | Gmail | X | Category |\n|---|---|---|---|---|\n| Simple reads (uri/title/visible) | 3-4ms | 4-40ms | 4-6ms | Fast everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | Slow everywhere — investigate |\n| `GET /html` | 7ms | 1.0s | 252ms | Scales with DOM size |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | **Primary bottleneck** |\n| `POST /text` (fps) | 7ms | **2.7s** | **1.4s** | **Primary bottleneck** |\n| `POST /click` | 165ms | 318ms | 403ms | Scales with DOM complexity |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | Gmail-specific timeout issue |\n| `GET /screenshot` | 76ms | 134ms | 157ms | Scales with pixel content |\n| `GET /ax-tree` | 46B | 46B | 46B | **Broken on all sites** |\n\n### Top Optimization Priorities (updated)\n\n| Priority | Issue | Impact | Affected Sites |\n|---|---|---|---|\n| 1 | **`text` extraction 1.4-2.7s** | Blocks every MCP agent loop | Gmail, X |\n| 2 | **SPA `navigate` 30s timeout** | Completely broken workflow | Gmail |\n| 3 | **`exists` 41-97ms** | 10-25x slower than similar endpoints | All |\n| 4 | **`ax-tree` non-functional** | Accessibility data unavailable | All |\n| 5 | **`click` 165-403ms** | 100ms of fixed `waitForStable` delay | All |\n| 6 | **First-call penalty** | 270-330ms on first hover/focus | X |\n\n---\n\n## Large-Scale Site Benchmark: YouTube\n\nYouTube home page was tested as a heavy media-centric SPA with Web Components (custom elements like `ytd-rich-item-renderer`).\n\n### Test Conditions\n\n- **Page**: `https://www.youtube.com/` (logged in, home feed)\n- **DOM complexity**: ~850KB HTML, Polymer/Lit-based Web Components\n- **Instance creation**: **19.4s** — by far the slowest (heavy JS bundles + video preloading)\n\n### Results: YouTube vs All Sites\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | 3.5ms | Consistent |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | 4.4ms | |\n| `GET /exists` | 41ms | 80ms | 97ms | **33ms** | Fastest — still slow vs uri/title |\n| `GET /html` | 7ms (15KB) | 1.0s (950KB) | 252ms (836KB) | **256ms** (853KB) | Similar to X |\n| `GET /text` | 9ms (270B) | 2.4s (107KB) | 1.7s (44KB) | **960ms** (7.9KB) | Fastest large site — little visible text |\n| `POST /text` (fps) | 7ms (629B) | 2.7s (220KB) | 1.4s (112KB) | **1.0s** (32KB) | |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | 5.0ms (46B) | Still broken |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | 157ms (527KB) | **47ms** (60KB) | Small — dark theme, simple thumbnails |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | 163ms (527KB) | **35ms** (60KB) | Same as viewport |\n| `GET /element` (video) | 4.0ms | 11ms | 11ms (34KB) | 5.0ms (**2B**) | **Empty** — Web Component not traversable |\n| `GET /elementText` (video) | 3.7ms | 13ms | 4.6ms | 4.2ms (**2B**) | **Empty** |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | 4.7ms (`null`) | **null** — selector not found |\n| `GET /isVisible` (search) | 3.3ms | 7.7ms | 3.9ms | 4.9ms (`false`) | Shadow DOM barrier? |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | 3.8ms (2.8KB) | 5.5ms (6.9KB) | |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | 11ms | **8.5ms** | Fast after warm-up (first: 19ms) |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | **6.1ms** | |\n| `POST /focus` | 5.1ms | 42ms | 27ms | **7.5ms** | |\n| `POST /click` | 165ms | 318ms | 403ms | **333ms** (`ok:false`) | **Failed** — click didn't register |\n| `POST /navigate` (SPA) | 49ms | 30s | 175ms | **31ms-2.2s** | Variable — home=2.2s, trending=31ms |\n| `POST /waitForElement` | 3.8ms | 5s | 73ms-5s | **105ms-5s** | `ytd-video-renderer` not found on trending |\n| `POST /regionScreenshot` | - | 39ms | 120ms | **11ms** (12.5KB) | Very fast — small content |\n\n### Key Findings for YouTube\n\n#### 1. Web Components are opaque to element queries\n\n**Severity**: Critical (functional)\n**Observed**: `element?selector=ytd-rich-item-renderer` returns 2 bytes (empty). `attribute?selector=a#video-title-link&name=href` returns `null`. `isVisible?selector=input#search` returns `false`.\n**Root cause**: YouTube uses Polymer/Lit Web Components with Shadow DOM. Standard `querySelector` cannot pierce shadow boundaries. The API's DOM operations only search the light DOM.\n**Impact**: Most element-targeting operations are effectively broken on YouTube. Selectors like `ytd-rich-item-renderer`, `a#thumbnail`, `input#search` exist inside shadow roots and are invisible to the API.\n**Recommendation**: Implement `deepQuerySelector` that traverses into shadow roots, or provide a `piercesShadow: true` option.\n\n#### 2. Click returned `ok:false` on video thumbnail\n\n**Severity**: High\n**Observed**: `POST /click` with `selector: \"a#thumbnail\"` returned `{\"ok\":false}` in 333ms. URL didn't change.\n**Root cause**: Related to Shadow DOM issue — the element was likely found in light DOM but actionability checks or coordinate computation failed because the rendered element is inside a shadow root.\n\n#### 3. Instance creation is extremely slow (19.4s)\n\n**Observed**: 19.4s vs Gmail 4.2s vs X 2.2s vs example.com 6.9s.\n**Root cause**: YouTube loads very heavy JS bundles, preloads video content, and runs extensive initialization. The `load` event fires late.\n**Impact**: First-time access to YouTube via the API is very slow.\n\n#### 4. SPA navigate latency is inconsistent\n\n**Observed**: Navigate to `/feed/trending` = 31ms (fast). Navigate back to home = 2.2s (slow).\n**Root cause**: YouTube's home page triggers heavy content loading (video thumbnails, recommendations). Trending page is lighter. The `load`/`DOMContentLoaded` event timing varies dramatically.\n\n#### 5. Text extraction is fast but returns very little\n\n**Observed**: `GET /text` = 960ms but only 7.9KB of text. Gmail returns 107KB, X returns 44KB.\n**Root cause**: Most of YouTube's visible text is inside Web Components' shadow DOMs. Turndown can only see the light DOM text, which is minimal.\n**Impact**: The text endpoint is nearly useless on YouTube — it misses video titles, descriptions, channel names, etc.\n\n#### 6. Screenshots are very small (60KB)\n\n**Observed**: 47ms for a 60KB screenshot. Gmail = 397KB, X = 527KB.\n**Root cause**: YouTube's dark theme with simple thumbnail grid produces a highly compressible PNG. Screenshots DO render correctly (they capture the visual output, not DOM), so screenshots are the most reliable way to \"see\" YouTube's content.\n\n### YouTube Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time | Status |\n|---|---|---|---|\n| 1. Create instance | `POST /instances` | ~19400ms | Very slow |\n| 2. Get page text | `GET /text` | ~960ms | Fast but mostly empty |\n| 3. Click video | `POST /click` | ~333ms | **FAILS** (Shadow DOM) |\n| 4. Get video text | `GET /text` | ~850ms | Mostly empty |\n| **Total** | | **~21.5s** | **Partially broken** |\n\n**Conclusion**: YouTube is largely non-functional with the current API due to Shadow DOM. Screenshots work, but text extraction and element interaction are severely limited.\n\n---\n\n## Cross-Site Summary (Final)\n\n### Performance Matrix\n\n| Endpoint | example.com | Gmail | X | YouTube | Category |\n|---|---|---|---|---|---|\n| Simple reads | 3-4ms | 4-40ms | 4-6ms | 3-5ms | OK everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | 33ms | Slow everywhere |\n| `GET /html` | 7ms | 1.0s | 252ms | 256ms | Scales with DOM |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | 960ms* | *YouTube: mostly empty |\n| `POST /click` | 165ms | 318ms | 403ms | 333ms** | **YouTube: fails |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | 31ms-2.2s | Gmail broken |\n| `GET /screenshot` | 76ms | 134ms | 157ms | 47ms | Always works |\n| `GET /ax-tree` | 46B | 46B | 46B | 46B | Broken everywhere |\n| Instance creation | 6.9s | 4.2s | 2.2s | **19.4s** | YouTube very slow |\n\n### Final Priority List\n\n| Priority | Issue | Impact | Sites Affected |\n|---|---|---|---|\n| **1** | **Shadow DOM not supported** | Element queries, click, text extraction all fail | YouTube (and any Web Component site) |\n| **2** | **`text` extraction 1-2.7s** | Primary MCP endpoint, blocks every agent loop | Gmail, X, YouTube |\n| **3** | **SPA `navigate` 30s timeout** | Workflow completely blocked | Gmail |\n| **4** | **`ax-tree` non-functional** | Accessibility data unavailable | All sites |\n| **5** | **`exists` 33-97ms** | 10-25x slower than similar endpoints | All sites |\n| **6** | **`click` 165-403ms** | 100ms fixed `waitForStable` delay | All sites |\n| **7** | **Instance creation 2-19s** | Slow first access, especially YouTube | All sites |\n\n---\n\n## Raw Data\n\nAll measurements taken with:\n```bash\ncurl -s -w \"%{time_total}\" -o /dev/null <url>\n```\n\n- Iterations: 3-5 per endpoint\n- Warm-up: Server was idle before measurements; first call to each endpoint may include JIT compilation overhead\n- Pages: `https://example.com` (15KB), Gmail inbox (~950KB, 243 messages), X home timeline (~836KB), YouTube home (~853KB)\n- Network: Localhost loopback (127.0.0.1), no auth token configured\n","isInternal":false,"tokens":8398,"sizeBytes":26159},{"name":".cursorrules","path":".cursorrules","rawUrl":"https://raw.githubusercontent.com/Floorp-Projects/Floorp/HEAD/.cursorrules","title":"Cursor IDE Native Rules","category":"cursor-rule","format":"markdown","content":"# Floorp プロジェクトルール\n\nこのプロジェクトは Mozilla Firefox をベースにした Web ブラウザ \"Floorp\" です。\n\n## 必読ドキュメント\n\nコーディング前に以下のドキュメントを参照してください：\n\n- `docs/llm/README.md` - LLM 向けドキュメントの索引\n- `docs/llm/project-overview.md` - プロジェクト全体の概要\n- `docs/llm/development-notes.md` - 開発ガイドとベストプラクティス\n- `docs/llm/architecture-deep-dive.md` - アーキテクチャ詳細\n- `.claude/context.md` - クイックリファレンス\n\n## 技術スタック\n\n- **ランタイム**: Deno 2.x (メイン), Node.js 22 (一部)\n- **UI**: SolidJS (ブラウザクローム), React (設定ページ)\n- **ビルド**: Vite, feles-build\n- **言語**: TypeScript\n- **CSS**: Tailwind CSS\n\n## コーディング規約\n\n### 型定義\n\n**重要**: 型定義は可能な限り別ファイルに分離してください。\n\n```typescript\n// Good: 型定義を types.ts に分離\n// types.ts\nexport interface Config {\n  enabled: boolean;\n  timeout: number;\n}\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n\n// Bad: 実装と型を混在させる\nexport interface Config { /* ... */ }\nexport class Feature { /* ... */ }\n```\n\n**例外**: `.sys.mts` ファイルでは Firefox API との統合のため、型定義を同じファイルに書いても構いません。\n\n### TypeScript\n\n- `any` 型は避ける\n- 明確な型定義を使用\n- 型推論を活用\n- null/undefined のチェックを忘れずに\n\n```typescript\n// Good\ninterface User {\n  id: number;\n  name: string;\n}\n\nfunction getUser(id: number): User | null {\n  // ...\n}\n\n// Bad\nfunction getUser(id: any): any {\n  // ...\n}\n```\n\n### SolidJS (ブラウザクローム機能)\n\n- リアクティブな状態管理には `createSignal` を使用\n- 直接変数を変更しない\n- HMR サポートのために `@noraComponent(import.meta.hot)` デコレーターを使用\n\n```typescript\n// Good\nimport { createSignal } from \"solid-js\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n\n// Bad\nlet count = 0;\ncount++; // 動作しない\n```\n\n### React (設定ページ)\n\n- 関数コンポーネントを使用\n- Hooks を適切に使用\n- Tailwind CSS でスタイリング\n\n```typescript\n// Good\nexport default function SettingsPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### ファイル配置\n\n- **ブラウザ UI 機能**: `browser-features/chrome/common/{feature-name}/`\n- **Firefox API モジュール**: `browser-features/modules/modules/{module-name}.sys.mts`\n- **設定ページ**: `browser-features/pages-settings/src/pages/`\n- **型定義**: 各機能の `types.ts` ファイル（`.sys.mts` を除く）\n\n### エラーハンドリング\n\n常に適切なエラーハンドリングを実装してください。\n\n```typescript\n// Good\ntry {\n  const data = await fetchData(url);\n  return data;\n} catch (error) {\n  console.error(\"[FeatureName] Failed to fetch:\", error);\n  return null; // フォールバック\n}\n\n// Bad\nconst data = await fetchData(url); // エラーが伝播\n```\n\n### コメント\n\n- 複雑なロジックには日本語または英語でコメントを追加\n- 関数の目的は JSDoc で説明\n- TODO コメントには担当者を明記\n\n```typescript\n/**\n * ユーザー設定を取得します\n * @param userId ユーザー ID\n * @returns ユーザー設定オブジェクト、存在しない場合は null\n */\nfunction getUserConfig(userId: string): UserConfig | null {\n  // TODO(@username): キャッシュ機構を実装\n  return null;\n}\n```\n\n## 新機能追加のチェックリスト\n\n1. **適切な場所に配置**\n   - ブラウザ UI → `browser-features/chrome/common/`\n   - システムモジュール → `browser-features/modules/modules/`\n   - 設定ページ → `browser-features/pages-settings/`\n\n2. **型定義を別ファイルに**\n   - `types.ts` を作成（`.sys.mts` 以外）\n   - インターフェースと型を定義\n\n3. **HMR サポートを追加**（ブラウザクローム機能のみ）\n   ```typescript\n   @noraComponent(import.meta.hot)\n   export default class MyFeature extends NoraComponentBase {\n     init(): void { /* ... */ }\n   }\n   ```\n\n4. **機能を登録**\n   - `browser-features/chrome/common/mod.ts` に追加\n\n5. **翻訳を追加**\n   - 少なくとも `i18n/en-US/` と `i18n/ja-JP/` に追加\n\n6. **必要に応じて Actor を追加**（マルチプロセス通信が必要な場合）\n   - Parent: `browser-features/modules/actors/{Name}Parent.sys.mts`\n   - Child: `browser-features/modules/actors/{Name}Child.sys.mts`\n   - 登録: `browser-features/modules/modules/BrowserGlue.sys.mts`\n\n## 開発コマンド\n\n```bash\n# 開発モード（HMR 付き）\ndeno task feles-build dev\n\n# 本番ビルド\ndeno task feles-build build\n\n# ステージングビルド\ndeno task feles-build stage\n\n# 依存関係のインストール\ndeno install\n```\n\n## モジュールパスエイリアス\n\n```typescript\nimport { foo } from \"#i18n/utils\";           // i18n/\nimport { bar } from \"#chrome/common/tab\";    // chrome/\nimport { baz } from \"#libs/shared\";          // libs/\nimport { qux } from \"#modules/experiments\";  // browser-features/modules/\n```\n\n## よくある問題\n\n### HMR が動作しない\n- `@noraComponent(import.meta.hot)` デコレーターが付いているか確認\n- `NoraComponentBase` を継承しているか確認\n\n### Firefox API にアクセスできない\n- `.sys.mts` ファイルから ChromeUtils.importESModule() を使用\n\n### 型エラー\n- 型定義を別ファイル（`types.ts`）に分離\n- `any` 型を使用していないか確認\n\n## パフォーマンス\n\n- `init()` メソッドで重い処理を避ける\n- 遅延初期化を活用\n- イベントリスナーを適切にクリーンアップ\n- メモリリークに注意\n\n## テスト\n\n- 新機能には可能な限りテストを追加\n- テストは `browser-features/chrome/test/unit/` に配置\n- Deno のテストフレームワークを使用\n\n## Git コミット\n\n- 意味のあるコミットメッセージ\n- 1 コミット = 1 つの論理的な変更\n- コミット前に `deno fmt` で整形\n\n## 参考リンク\n\n- プロジェクトドキュメント: `docs/llm/`\n- Deno: https://docs.deno.com/\n- SolidJS: https://www.solidjs.com/\n- React: https://react.dev/\n- Firefox Source: https://firefox-source-docs.mozilla.org/\n\n---\n\nこれらのルールに従って、一貫性のある高品質なコードを書いてください。\n","isInternal":false,"tokens":2196,"sizeBytes":6589},{"name":"CLAUDE.md","path":"CLAUDE.md","rawUrl":"https://raw.githubusercontent.com/Floorp-Projects/Floorp/HEAD/CLAUDE.md","title":"Claude Agent Guidelines & System Prompt","category":"claude-rule","format":"markdown","content":"# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Architecture (5 Layers)\n\n```notes\nFirefox Base  ← patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     ↓\nESM Modules   ← .sys.mts files with direct Firefox API access, Window Actors\n     ↓\nBridge        ← startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     ↓\nChrome UI     ← SolidJS → XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     ↓\nPages         ← React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              → ./i18n/\n#chrome/            → ./chrome/\n#libs/              → ./libs/\n#features-chrome/   → ./browser-features/chrome/\n#modules/           → ./browser-features/modules/\n#ui/                → ./src/ui/\n#themes/            → ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` — adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state — never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174–5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool — Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot → _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) — browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` — web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` — launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` — check for runtime errors\n4. `deno task dev-tool eval \"...\"` — inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` — visually verify UI changes\n6. `deno task dev-tool rebuild` — if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` — shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` — Full project overview\n- `docs/llm/architecture-deep-dive.md` — 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` — Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n","isInternal":false,"tokens":2251,"sizeBytes":9485},{"name":"copilot-instructions.md","path":".github/copilot-instructions.md","rawUrl":"https://raw.githubusercontent.com/Floorp-Projects/Floorp/HEAD/.github/copilot-instructions.md","title":"GitHub Copilot Instructions","category":"copilot-instructions","format":"markdown","content":"# AI Coding Agent Instructions\n\nThis workspace contains multiple interconnected projects: **Floorp** (Firefox-based browser), **Sapphillon** (workflow automation backend), **Floorp-OS-Automator-Frontend**, and **web-store**.\n\n## Project Overview\n\n### Floorp (`floorp/`)\nFirefox-based browser built with Deno 2.x, SolidJS, and React. Custom browser features overlay Firefox's Gecko engine.\n\n### Sapphillon Backend (`Floorp-OS-Automator-Backend/`)\nRust-based workflow automation backend using gRPC (tonic), SeaORM, and Deno runtime for executing JavaScript workflows.\n\n### Frontend Projects\n- **Floorp-OS-Automator-Frontend**: React + TypeScript + Vite UI for workflow management\n- **web-store**: Plugin marketplace with React + Vite\n\n---\n\n## Cross-Project Integration\n\nThis workspace contains interconnected projects. Understanding data flow and integration points is crucial for full-stack development.\n\n### Data Flow Architecture\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│                    Floorp Browser                        │\n│              (Mozilla Firefox + Custom Features)           │\n│  Location: /Users/user/dev-source/floorp-dev/floorp/     │\n│  Dev: deno task dev (ports: 5173-5186)              │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ Floorp OS API (OpenAPI)\n                          │ openapi.yaml:\n                          │ Floorp-OS-Automator-Backend/plugins/floorp/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│              Sapphillon Backend (Rust)                │\n│  Location: ../Floorp-OS-Automator-Backend/          │\n│  Dev: make run (gRPC on localhost:50051)            │\n│  - Plugin system (floorp, fetch, filesystem, etc.)    │\n│  - Workflow engine (Deno Core runtime)                 │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ gRPC (tonic + prost)\n                          │ protobuf in:\n                          │ Floorp-OS-Automator-Frontend/vender/Sapphillon_API/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│         Floorp-OS-Automator-Frontend (React)          │\n│  Location: ../Floorp-OS-Automator-Frontend/          │\n│  Dev: pnpm dev (port 8081)                          │\n│  - gRPC-Web client (@connectrpc/connect-web)           │\n│  - Workflow management UI                                │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ (optional, disabled)\n                          │ PostMessage to Floorp\n                          │ Progress Window\n                          ▼\n                   ┌────────────────┐\n                   │  Floorp       │\n                   │  Progress     │\n                   │  Window       │\n                   └────────────────┘\n\n                          ▲\n                          │\n                ┌─────────┴──────────┐\n                │                    │\n┌───────────────┐      ┌────────────────┐\n│  Web Store    │      │  External     │\n│  (Plugin      │      │  Plugins     │\n│   Marketplace)│      │              │\n└───────────────┘      └────────────────┘\n```\n\n### Integration Points\n\n**1. Floorp → Sapphillon** (Browser Automation):\n- Floorp exposes browser automation via OpenAPI spec at `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`\n- Sapphillon's `floorp` plugin consumes this API to control browser tabs, navigation, etc.\n- Workflows can automate browser interactions (open tabs, navigate, fill forms)\n\n**2. Sapphillon → Frontend** (Workflow Management):\n- gRPC communication using `tonic` (server) and `@connectrpc/connect-web` (client)\n- Protobuf definitions in `Floorp-OS-Automator-Frontend/vender/Sapphillon_API/proto/`\n- Frontend generates TypeScript clients from `.proto` files\n- Services: Workflow, Plugin, Version, Model, Provider\n\n**3. Frontend → Floorp** (Progress Tracking):\n- Disabled by default (see `lib/workflow-progress.ts`)\n- Uses `window.OSAutomotor?.sendWorkflowProgress()` for real-time updates\n- Would show workflow progress in Floorp's native progress window\n\n**4. Web Store → Sapphillon** (Plugin Distribution):\n- Plugin marketplace at `../web-store/`\n- Plugins installed via Sapphillon's plugin installer\n- External plugins run in separate processes with gRPC communication\n\n### Development Setup for Full Stack\n\n**Recommended workflow for full-stack development**:\n```bash\n# Terminal 1: Start Floorp Browser\ncd /Users/user/dev-source/floorp-dev/floorp\ndeno task dev\n\n# Terminal 2: Start Sapphillon Backend\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Backend\nmake run  # Starts gRPC server on localhost:50051\n\n# Terminal 3: Start Frontend (production mode)\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:prod  # Connects to localhost:50051\n```\n\n**Frontend-only development** (no backend needed):\n```bash\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:mock  # Mock gRPC on port 50099, Vite on 5199\n```\n\n---\n\n## Floorp Development Patterns\n\n### Build System\n- **Primary**: `deno task dev` - Runs custom feles-build system\n- **Build orchestration**: `tools/feles-build.ts` orchestrates patches, symlinks, Vite dev servers\n- **Dev server ports**: 5173 (main), 5178 (settings), 5186 (newtab), 5174-5177 (other pages)\n\n### Code Organization\n\n**Type Definitions**: Always separate types into dedicated files (`types.ts`), not mixed with implementation.\n```typescript\n// Good: types.ts\nexport interface Config { enabled: boolean; }\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n```\n**Exception**: `.sys.mts` files can include types with Firefox API integration.\n\n**File Extensions**:\n- `.ts` - General TypeScript\n- `.sys.mts` - Firefox ESM modules (loaded via `ChromeUtils.importESModule()`)\n- `.jsx` - React components in pages-*/ directories\n\n### UI Framework Usage\n\n**SolidJS** (`browser-features/chrome/`):\n- Use `createSignal` for reactive state (never mutate directly)\n- `@noraComponent(import.meta.hot)` decorator for HMR support\n- Import from `@nora/solid-xul` for rendering:\n```typescript\nimport { render, createSignal } from \"@nora/solid-xul\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n```\n\n**React** (`browser-features/pages-*/`):\n- Functional components with hooks\n- Tailwind CSS for styling\n- `import { createRootHMR } from \"@nora/solid-xul\"` for i18n integration\n\n### Firefox API Integration\nAccess Firefox APIs via ESM modules in `.sys.mts` files:\n```typescript\nconst { I18nUtils } = ChromeUtils.importESModule(\"resource://floorp/lib/I18nUtils.sys.mjs\");\n```\n\n---\n\n## Sapphillon Backend Patterns\n\n### Architecture\n- **gRPC Service Layer**: `src/services/` - Tonic-based services (workflow, plugin, model, version, provider)\n- **Plugin System**: Modular plugins in `plugins/` (fetch, filesystem, floorp, vscode, git, finder, etc.)\n- **Database**: SeaORM with SQLite, migrations in `migration/`, entities in `entity/`\n- **Workflow Engine**: Deno Core runtime executes JavaScript workflows with plugin permissions\n\n### Common Commands\n```bash\nmake rust_test          # Run all workspace tests\nmake rust_build         # Build entire workspace\nmake migrate            # Run SeaORM migrations\nmake entity_generate    # Generate entities from DB\nmake run                # Run with debug DB at ./debug/sqlite.db\nmake grpcui            # Launch gRPC UI on localhost:50051\n```\n\n### Testing\n- Unit tests: `cargo test --lib`\n- External plugin tests: `cargo test --test external_plugin`\n- Ignored tests: `cargo test --lib external_plugin -- --ignored`\n\n### Plugin Development\nEach plugin crate exposes Deno-compatible functions. See `plugins/floorp/` for OpenAPI-based Floorp browser control.\n\n**Debug Workflows**: Place JS files in `debug_workflow/` directory - auto-registered every 10s in debug builds with full permissions (`[DEBUG]` prefix).\n\n### gRPC & Protocol Buffers\n- Uses `tonic` for server, `prost` for code generation\n- `buf.yaml` and `buf.gen.yaml` configuration\n- Generate with `buf generate`\n\n---\n\n## Frontend Patterns (Both Projects)\n\n### Build Commands\n```bash\nnpm run dev              # Vite dev server\nnpm run build            # TypeScript check + Vite build\nnpm run test             # Vitest\nnpm run lint             # ESLint\n```\n\n### Component Patterns\n- **Chakra UI**: Primary component library\n- **i18next**: Internationalization via `src/i18n/config.ts`\n- **React Router**: Routing in `src/routes/`\n- **Type Definitions**: Export from `src/types/`, not inline\n\n### gRPC Communication\n- `@connectrpc/connect-web` for browser-based gRPC\n- `@connectrpc/connect` for Node-based\n- Generated clients in `src/gen/` from proto definitions\n\n---\n\n## Cross-Project Integration\n\n### Floorp OS API\nFloorp exposes browser automation via OpenAPI spec in `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`. The Sapphillon floorp plugin consumes this for workflow automation.\n\n### Data Flow\n```\nFloorp Browser\n    ↓ (Floorp OS API)\nSapphillon Backend (floorp plugin)\n    ↓ (gRPC)\nFloorp-OS-Automator-Frontend\n```\n\n### Plugin System\nWorkflows in Sapphillon can invoke plugins including:\n- **floorp**: Control Floorp browser (tabs, navigation, etc.)\n- **fetch**: HTTP requests\n- **filesystem**: File operations\n- **vscode**: VS Code control\n- **finder**: macOS Finder automation\n- And more in `plugins/`\n\n---\n\n## Key Conventions\n\n### Error Handling\n- **Floorp**: Use `Result<T, E>` from fp-ts for type-safe error handling\n- **Sapphillon**: `anyhow::Result<T>` and `tonic::Status` for gRPC errors\n\n### State Management\n- **SolidJS**: `createSignal` - never mutate directly\n- **React**: `useState`, `useContext` for global state\n\n### Database Operations\n- Use SeaORM `Entity::find().all(db).await?` pattern\n- Migrations: `sea-orm-cli migrate generate <name>`\n- Entities are auto-generated - don't edit manually\n\n### Permissions\nSapphillon uses wildcard `*` plugin_function_id to grant workflows full access. Used for trusted workflows and testing.\n\n---\n\n## Language-Specific Notes\n\n### Rust\n- Edition 2024, workspace resolver \"3\"\n- Async/await with tokio runtime\n- `#[tonic::async_trait]` for gRPC service implementations\n\n### TypeScript/Deno\n- No `any` types - use explicit types or `unknown`\n- Null/undefined checks required\n- Deno permissions: `--allow-all` often needed for build scripts\n\n### React\n- Functional components only\n- Hooks over class components\n- Tailwind CSS classes (e.g., `className=\"p-4\"`)\n\n---\n\n## Critical Files Reference\n\n| Purpose | File |\n|---------|------|\n| Floorp build system | `floorp/tools/feles-build.ts` |\n| Floorp dev config | `floorp/deno.json` |\n| Sapphillon main entry | `Floorp-OS-Automator-Backend/src/main.rs` |\n| Sapphillon workflow service | `Floorp-OS-Automator-Backend/src/services/workflow.rs` |\n| Frontend Vite config | `Floorp-OS-Automator-Frontend/vite.config.ts` |\n| Floorp SolidJS renderer | `floorp/libs/solid-xul/index.ts` |\n| Plugin permissions | `Floorp-OS-Automator-Backend/src/services/workflow.rs:make_plugin_permission()` |\n","isInternal":false,"tokens":2792,"sizeBytes":12431}],"systemPromptSnippet":"<yakaai_skills repo=\"Floorp-Projects/Floorp\">\n<!-- File: AGENTS.md (Tokens: ~2320 | Category: root-instruction) -->\n# AGENTS.md\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Runtime changes\n\nRuntime changes must be maintained as patches, not direct edits to a sibling\nFloorp-Runtime checkout. Cross-platform source patches belong in\n`.github/patches/floorp-runtime/common/` and are applied by `package.yml`.\nValidate them against the source commit in `floorp-runtime.lock.json` in isolation.\nThe package workflow uses prebuilt native artifacts; changes requiring native\nrecompilation cannot be delivered through source patches in that step alone.\n\n## Architecture (5 Layers)\n\n```text\nFirefox Base  <- patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     |\nESM Modules   <- .sys.mts files with direct Firefox API access, Window Actors\n     |\nBridge        <- startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     |\nChrome UI     <- SolidJS -> XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     |\nPages         <- React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              -> ./i18n/\n#chrome/            -> ./chrome/\n#libs/              -> ./libs/\n#features-chrome/   -> ./browser-features/chrome/\n#modules/           -> ./browser-features/modules/\n#ui/                -> ./src/ui/\n#themes/            -> ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` -- adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state -- never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174-5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool -- Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot -> _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) -- browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` -- web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` -- launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` -- check for runtime errors\n4. `deno task dev-tool eval \"...\"` -- inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` -- visually verify UI changes\n6. `deno task dev-tool rebuild` -- if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` -- shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` -- Full project overview\n- `docs/llm/architecture-deep-dive.md` -- 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` -- Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n\n<!-- File: tools/os-test/perf-report-2026-03-24.md (Tokens: ~8398 | Category: anthropic-skill) -->\n# Floorp OS API Server Performance Report\n\n- **Date**: 2026-03-24\n- **Environment**: Windows 11 Pro, dev build (`deno task dev`)\n- **Target page**: `https://example.com`\n- **Server**: `http://127.0.0.1:58261`\n- **Method**: curl with `%{time_total}`, 3-5 iterations per endpoint, median reported\n\n---\n\n## Summary\n\n| Category | Endpoint Count | Latency Range | Assessment |\n|---|---|---|---|\n| Tier 1: Instant | 18 | < 5ms | Excellent |\n| Tier 2: Fast | 8 | 5-10ms | Good |\n| Tier 3: Moderate | 4 | 40-100ms | Acceptable (I/O bound) |\n| Tier 4: Slow | 2 | > 100ms | Needs investigation |\n\n**Overall**: Most endpoints respond in under 5ms. The server's HTTP routing and IPC layer add minimal overhead (~2-3ms baseline from `/health`). Performance bottlenecks are concentrated in a few specific operations.\n\n---\n\n## Detailed Results\n\n### Tier 1: Instant (< 5ms)\n\nThese endpoints respond near the server's baseline latency. No optimization needed.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/health` | GET | 2.7ms | 7.4ms | 17B |\n| `/tabs/list` | GET | 3.0ms | 3.4ms | - |\n| `/browser/tabs` | GET | 2.9ms | 3.3ms | - |\n| `/workspaces` | GET | 2.8ms | 4.0ms | - |\n| `/instances/:id/cookies` | GET | 2.8ms | 5.9ms | - |\n| `/instances/:id/uri` | GET | 3.8ms | 4.8ms | 33B |\n| `/instances/:id/title` | GET | 4.1ms | 7.5ms | 27B |\n| `/instances/:id/element?selector=h1` | GET | 4.0ms | 4.6ms | 36B |\n| `/instances/:id/elementText?selector=h1` | GET | 3.7ms | 4.1ms | 26B |\n| `/instances/:id/elementTextContent?selector=h1` | GET | 4.0ms | 4.4ms | 26B |\n| `/instances/:id/attribute?selector=a&name=href` | GET | 3.8ms | 4.3ms | 47B |\n| `/instances/:id/isVisible?selector=a` | GET | 3.3ms | 3.9ms | 16B |\n| `/instances/:id/isEnabled?selector=a` | GET | 3.7ms | 3.8ms | 16B |\n| `/instances/:id/ax-tree` | GET | 2.7ms | 3.0ms | 46B |\n| `/instances/:id/waitForElement` (existing) | POST | 3.8ms | 4.6ms | 27B |\n| `/instances/:id/clearEffects` | POST | 3.4ms | 4.0ms | 11B |\n| `/instances/:id/article` | GET | 2.8ms | 14.8ms | 36B |\n| `DELETE /instances/:id` | DELETE | 3.0ms | - | 11B |\n\n### Tier 2: Fast (5-10ms)\n\nSlightly above baseline due to DOM traversal, serialization, or coordinate computation.\n\n| Endpoint | Method | Median | p95 | Payload |\n|---|---|---|---|---|\n| `/instances/:id/html` | GET | 6.5ms | 6.7ms | ~15KB |\n| `/instances/:id/text` | GET | 8.7ms | 11.3ms | 270B |\n| `POST /instances/:id/text` (fingerprints) | POST | 6.7ms | 8.3ms | 629B |\n| `/instances/:id/hover` | POST | 6.7ms | 8.5ms | 11B |\n| `/instances/:id/scrollTo` | POST | 5.7ms | 6.5ms | 11B |\n| `/instances/:id/focus` | POST | 5.1ms | 7.2ms | 11B |\n| `/browser/history?limit=10` | GET | 3.5ms | 4.0ms | - |\n| `/browser/context` | GET | 4.8ms | 143.7ms | - |\n\n**Note**: `/browser/context` has an occasional spike (~144ms) likely caused by GC pause or event loop contention.\n\n### Tier 3: Moderate (40-100ms)\n\nLatency is driven by I/O (network, rendering engine).\n\n| Endpoint | Method | Median | p95 | Payload | Bottleneck |\n|---|---|---|---|---|---|\n| `/instances/:id/exists` | GET | **41ms** | 99ms | 15B | Unknown - needs investigation |\n| `/instances/:id/navigate` | POST | **49ms** | 59ms | 11B | Network round-trip |\n| `/instances/:id/screenshot` | GET | **76ms** | 80ms | 217KB | Canvas rendering + PNG encode |\n| `/instances/:id/fullPageScreenshot` | GET | **86ms** | 92ms | 217KB | Canvas rendering + PNG encode |\n\n### Tier 4: Slow (> 100ms)\n\n| Endpoint | Method | Median | p95 | Bottleneck |\n|---|---|---|---|---|\n| `POST /instances/:id/click` | POST | **165ms** | 230ms | `waitForStable` 100ms delay + actionability checks |\n| `POST /instances` (create) | POST | **6.9s** | - | Tab creation + full page load |\n\n---\n\n## Analysis & Recommendations\n\n### 1. `/exists` is 10x slower than similar read endpoints (41ms vs 3-4ms)\n\n**Expected**: `exists` should be a simple lookup (like `uri` or `title`).\n**Observed**: 41ms median, with first call at 99ms.\n**Action**: Investigate the implementation. Likely doing an unnecessary async round-trip to the content process or awaiting a promise that could be resolved synchronously.\n\n### 2. `/click` latency is dominated by `waitForStable` (100ms fixed delay)\n\n**Breakdown**:\n- `waitForStable`: 100ms (fixed `timerSetTimeout`)\n- Actionability checks + scroll: ~15ms\n- `sendMouseEvent`: ~5ms\n- IPC overhead: ~45ms\n\n**Tradeoff**: The 100ms delay catches CSS transitions/animations. Removing it risks clicking moving elements. Consider:\n- Making `waitForStable` timeout configurable via request body (e.g., `stabilityTimeout: 50`)\n- Reducing default from 100ms to 50ms for simple pages\n- Skipping entirely when `force: true` (already implemented)\n\n### 3. Instance creation is very slow (6.9s)\n\nThis includes full page load (`https://example.com`). The time is mostly network + rendering. Consider:\n- Allowing `POST /instances` to return immediately after tab creation (before load completes)\n- Adding a separate `waitForLoad` endpoint for callers that need load completion\n\n### 4. Screenshot latency is reasonable (76-86ms)\n\nFor PNG encoding of a full viewport, 76ms is acceptable. If lower latency is needed:\n- Consider JPEG output option (faster encoding, smaller payload)\n- Consider returning raw bitmap data for local consumers\n\n### 5. Occasional spikes (~150ms) on fast endpoints\n\nObserved on `/isEnabled` (157ms) and `/browser/context` (144ms). These are likely:\n- JavaScript GC pauses in the parent process\n- Event loop contention from other Floorp operations\n- Not actionable without profiling, and acceptable for an API server\n\n### 6. `/ax-tree` returns only 46 bytes\n\nFor `example.com` this returned `{\"error\":\"ax-tree not available\"}` or a minimal response. Needs verification that the accessibility tree is being correctly extracted for complex pages.\n\n---\n\n## Latency Budget (typical MCP tool call)\n\nA typical MCP interaction involves multiple API calls. Example workflow:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~7000ms |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Wait for navigation | `POST /waitForElement` | ~4ms |\n| 5. Get new text | `GET /text` | ~9ms |\n| 6. Cleanup | `DELETE /instances/:id` | ~3ms |\n| **Total** | | **~7190ms** |\n\nWithout instance creation (reusing existing tab via `/attach`):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~9ms |\n| 3. Click element | `POST /click` | ~165ms |\n| 4. Get new text | `GET /text` | ~9ms |\n| **Total** | | **~188ms** |\n\n*Estimated based on similar lightweight operations.\n\n**Conclusion**: Instance creation dominates total latency. For interactive use, reusing tabs via `/attach` brings total workflow time under 200ms, which is excellent.\n\n---\n\n## Large-Scale Site Benchmark: Gmail\n\nGmail (inbox with 243 messages) was tested to evaluate performance on a complex, real-world SPA with heavy DOM.\n\n### Test Conditions\n\n- **Page**: `https://mail.google.com/mail/u/0/#inbox` (logged in, 243 messages)\n- **DOM complexity**: ~1MB HTML, deeply nested SPA structure\n- **Instance creation**: 4.2s (faster than example.com — likely cached assets)\n\n### Results Comparison: example.com vs Gmail\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 1.0x | No DOM access needed |\n| `GET /title` | 4.1ms | 40ms | **10x** | Spikes to 449ms observed |\n| `GET /exists` | 41ms | 80ms | **2x** | Consistently slow |\n| `GET /html` | 6.5ms (15KB) | **1.0s** (950KB) | **150x** | Serializing ~1MB DOM |\n| `GET /text` | 8.7ms (270B) | **2.4s** (107KB) | **275x** | DOM traversal + Turndown conversion |\n| `POST /text` (fps) | 6.7ms (629B) | **2.7s** (220KB) | **400x** | + fingerprint generation |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 1.5x | Returns 46B on both — likely broken |\n| `GET /screenshot` | 76ms (217KB) | **134ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /fullPageScreenshot` | 86ms (217KB) | **157ms** (397KB) | 1.8x | Reasonable scaling |\n| `GET /element` | 4.0ms | 11ms | 2.8x | |\n| `GET /elementText` | 3.7ms | 13ms | 3.5x | |\n| `GET /attribute` | 3.8ms | 7.0ms | 1.8x | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 2.3x | |\n| `GET /cookies` | 2.8ms | **8.8ms** (14KB) | 3.1x | More cookies on Google |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | Slowdown | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | **73ms** | **11x** | Coordinate computation on complex layout |\n| `POST /scrollTo` | 5.7ms | **45ms** | **8x** | First call 111ms (layout recalc?) |\n| `POST /focus` | 5.1ms | **42ms** | **8x** | First call 112ms |\n| `POST /click` | 165ms | **318ms** | 1.9x | waitForStable + complex layout |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **600x** | SPA doesn't fire `load` event |\n| `GET /regionScreenshot` | - | 39ms (68KB) | - | Efficient partial capture |\n\n### Critical Issues Found\n\n#### 1. `navigate` times out on SPA pages (30s)\n\n**Severity**: Critical\n**Observed**: `POST /navigate` to `#inbox` on Gmail takes exactly 30 seconds — hitting the timeout.\n**Root cause**: `navigate` waits for a `load` event, but Gmail is a SPA that uses `pushState`/`hashchange` for navigation. The `load` event never fires for in-app navigations.\n**Impact**: Any workflow that navigates within a SPA (Gmail, YouTube, Twitter, etc.) will block for 30 seconds.\n**Recommendation**: Detect SPA navigation (same-origin hash/pushState changes) and resolve immediately or use a shorter timeout with `DOMContentLoaded` / network idle detection.\n\n#### 2. `text` extraction takes 2.4-3.7s on complex pages\n\n**Severity**: High\n**Observed**: `GET /text` = 2.4s, `POST /text` with fingerprints = 2.7s (107-220KB output).\n**Root cause**: Turndown (HTML-to-Markdown) conversion traverses the entire DOM tree. Gmail's DOM is extremely deep (~1MB HTML).\n**Impact**: This is the primary endpoint for MCP tool use — AI agents call `text` on every page interaction. 2-3s per call significantly impacts agent loop latency.\n**Recommendation**:\n- Support `selector` scoping in GET/POST to limit traversal (e.g., only extract the email list, not the entire UI)\n- Consider caching/diffing for repeated calls on the same page state\n- Profile Turndown to find hotspots (likely in node visibility checks)\n\n#### 3. `html` takes 1s for ~1MB\n\n**Severity**: Medium\n**Observed**: 1.0s to serialize and transfer ~950KB of HTML.\n**Root cause**: Combination of `outerHTML` serialization in content process + IPC transfer + HTTP response writing.\n**Impact**: Less critical than `text` since `html` is used less frequently, but still notable.\n\n#### 4. `title` has unpredictable latency (4ms to 449ms)\n\n**Severity**: Low\n**Observed**: Varies from 4ms to 449ms across 5 calls on Gmail.\n**Root cause**: Likely contention with Gmail's JavaScript execution (timers, XHR callbacks, mutation observers).\n**Impact**: Usually fast, but occasional spikes could affect perceived responsiveness.\n\n#### 5. `ax-tree` returns 46 bytes on Gmail\n\n**Severity**: Medium (functional issue)\n**Observed**: Same 46-byte response on both example.com and Gmail. This is likely `{\"error\":\"...\"}` or an empty tree.\n**Impact**: Accessibility tree is unusable. Should be investigated separately.\n\n### Gmail Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~4200ms |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~11s** |\n\nWith `/attach` (reusing existing tab):\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get page text | `GET /text` | ~2400ms |\n| 3. Click email | `POST /click` | ~318ms |\n| 4. Get email text | `GET /text` | ~4064ms |\n| **Total** | | **~6.8s** |\n\n**Conclusion**: On large-scale SPAs, `text` extraction dominates latency at 2-4s per call. This is 250-400x slower than on simple pages. Scoped text extraction (passing a selector to limit DOM traversal) would be the highest-impact optimization.\n\n---\n\n## Large-Scale Site Benchmark: X (Twitter)\n\nX home timeline was tested as another complex SPA with infinite scroll and dynamic content loading.\n\n### Test Conditions\n\n- **Page**: `https://x.com/home` (logged in, home timeline)\n- **DOM complexity**: ~836KB HTML, React-based SPA\n- **Instance creation**: 2.2s\n\n### Results: X vs Gmail vs example.com\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | Consistent across all |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | Gmail is the outlier |\n| `GET /exists` | 41ms | 80ms | **97ms** | Consistently slow on all sites |\n| `GET /html` | 6.5ms (15KB) | 1.0s (950KB) | **252ms** (836KB) | X DOM is similar size but faster |\n| `GET /text` | 8.7ms (270B) | 2.4s (107KB) | **1.7s** (44KB) | Heavy DOM traversal |\n| `POST /text` (fps) | 6.7ms (629B) | 2.7s (220KB) | **1.4s** (112KB) | Fingerprint version faster than plain on X |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | Broken on all sites |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | **157ms** (527KB) | Scales with image size |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | **163ms** (527KB) | |\n| `GET /element` (article) | 4.0ms | 11ms | **11ms** (34KB) | X articles are large |\n| `GET /elementText` | 3.7ms | 13ms | **4.6ms** | |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | |\n| `GET /isVisible` | 3.3ms | 7.7ms | 3.9ms | |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | **3.8ms** (2.8KB) | Fewer cookies than Gmail |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | Notes |\n|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | **11ms** | First call 273ms (cold), then 10-11ms |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | `article:nth-of-type(3)` returned `ok:false` — not found |\n| `POST /focus` | 5.1ms | 42ms | **27ms** | First call 329ms (cold), then 24-30ms |\n| `POST /click` | 165ms | 318ms | **403ms** | Slowest of all three sites |\n| `POST /navigate` (SPA) | 49ms | **30s** (timeout) | **175ms / 45ms** | X works! No load event issue |\n| `POST /waitForElement` | 3.8ms | 5s (timeout) | **73ms-5s** | Inconsistent — first call timed out |\n| `POST /regionScreenshot` | - | 39ms | **120-197ms** | Higher on X |\n\n### Key Findings for X\n\n#### 1. SPA Navigate works on X but not Gmail\n\n**Observed**: `POST /navigate` to `/explore` took 175ms, back to `/home` took 45ms. No 30s timeout.\n**Explanation**: X likely triggers a full page `load` event on navigation (or uses a different routing strategy than Gmail). This confirms the Gmail timeout is specific to Gmail's SPA implementation, not a universal SPA issue.\n\n#### 2. Click is slowest on X (403ms)\n\n**Observed**: 403ms on X vs 318ms on Gmail vs 165ms on example.com.\n**Breakdown estimate**: waitForStable 100ms + actionability checks on complex DOM ~50ms + scroll/coordinate computation ~150ms + sendMouseEvent ~5ms + IPC overhead ~100ms.\n**Root cause**: X's deeply nested React component tree and heavy event handlers likely slow down coordinate computation and the scroll-into-view step.\n\n#### 3. First-call penalty on hover/focus (270-330ms)\n\n**Observed**: First `hover` took 273ms, subsequent calls 10-11ms. First `focus` took 329ms, then 24-30ms.\n**Root cause**: JIT compilation or lazy initialization of the coordinate/actionability pipeline. After warm-up, performance stabilizes.\n**Impact**: Minimal — only affects the very first interaction after instance creation.\n\n#### 4. Text extraction is faster than Gmail despite similar DOM size\n\n**Observed**: X text = 1.7s (44KB) vs Gmail text = 2.4s (107KB). HTML size is comparable (~836KB vs ~950KB).\n**Explanation**: Gmail's DOM is more deeply nested with more visible text nodes (email previews, labels, folders). X's timeline has more hidden/clipped content that Turndown skips.\n\n#### 5. `waitForElement` is unreliable after SPA navigation\n\n**Observed**: First call after navigating back to `/home` timed out at 5s. Second call found the element in 736ms. Third call in 72ms.\n**Root cause**: After SPA navigation, X lazy-loads timeline content. The first `article` element may not exist immediately. This is expected behavior, but the 5s default timeout may be too short for slow connections.\n\n### X Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Create instance | `POST /instances` | ~2200ms |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~4800ms** |\n\nWith `/attach`:\n\n| Step | Endpoint | Time |\n|---|---|---|\n| 1. Attach to tab | `POST /attach` | ~5ms* |\n| 2. Get timeline text | `GET /text` | ~1700ms |\n| 3. Click tweet | `POST /click` | ~403ms |\n| 4. Get tweet text | `GET /text` | ~497ms |\n| **Total** | | **~2600ms** |\n\n---\n\n## Cross-Site Summary\n\n### Performance Tiers by Site\n\n| Endpoint | example.com | Gmail | X | Category |\n|---|---|---|---|---|\n| Simple reads (uri/title/visible) | 3-4ms | 4-40ms | 4-6ms | Fast everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | Slow everywhere — investigate |\n| `GET /html` | 7ms | 1.0s | 252ms | Scales with DOM size |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | **Primary bottleneck** |\n| `POST /text` (fps) | 7ms | **2.7s** | **1.4s** | **Primary bottleneck** |\n| `POST /click` | 165ms | 318ms | 403ms | Scales with DOM complexity |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | Gmail-specific timeout issue |\n| `GET /screenshot` | 76ms | 134ms | 157ms | Scales with pixel content |\n| `GET /ax-tree` | 46B | 46B | 46B | **Broken on all sites** |\n\n### Top Optimization Priorities (updated)\n\n| Priority | Issue | Impact | Affected Sites |\n|---|---|---|---|\n| 1 | **`text` extraction 1.4-2.7s** | Blocks every MCP agent loop | Gmail, X |\n| 2 | **SPA `navigate` 30s timeout** | Completely broken workflow | Gmail |\n| 3 | **`exists` 41-97ms** | 10-25x slower than similar endpoints | All |\n| 4 | **`ax-tree` non-functional** | Accessibility data unavailable | All |\n| 5 | **`click` 165-403ms** | 100ms of fixed `waitForStable` delay | All |\n| 6 | **First-call penalty** | 270-330ms on first hover/focus | X |\n\n---\n\n## Large-Scale Site Benchmark: YouTube\n\nYouTube home page was tested as a heavy media-centric SPA with Web Components (custom elements like `ytd-rich-item-renderer`).\n\n### Test Conditions\n\n- **Page**: `https://www.youtube.com/` (logged in, home feed)\n- **DOM complexity**: ~850KB HTML, Polymer/Lit-based Web Components\n- **Instance creation**: **19.4s** — by far the slowest (heavy JS bundles + video preloading)\n\n### Results: YouTube vs All Sites\n\n#### Read-Only Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `GET /uri` | 3.8ms | 3.7ms | 4.6ms | 3.5ms | Consistent |\n| `GET /title` | 4.1ms | 40ms | 5.9ms | 4.4ms | |\n| `GET /exists` | 41ms | 80ms | 97ms | **33ms** | Fastest — still slow vs uri/title |\n| `GET /html` | 7ms (15KB) | 1.0s (950KB) | 252ms (836KB) | **256ms** (853KB) | Similar to X |\n| `GET /text` | 9ms (270B) | 2.4s (107KB) | 1.7s (44KB) | **960ms** (7.9KB) | Fastest large site — little visible text |\n| `POST /text` (fps) | 7ms (629B) | 2.7s (220KB) | 1.4s (112KB) | **1.0s** (32KB) | |\n| `GET /ax-tree` | 2.7ms (46B) | 4.3ms (46B) | 2.7ms (46B) | 5.0ms (46B) | Still broken |\n| `GET /screenshot` | 76ms (217KB) | 134ms (397KB) | 157ms (527KB) | **47ms** (60KB) | Small — dark theme, simple thumbnails |\n| `GET /fullPageScreenshot` | 86ms (217KB) | 157ms (397KB) | 163ms (527KB) | **35ms** (60KB) | Same as viewport |\n| `GET /element` (video) | 4.0ms | 11ms | 11ms (34KB) | 5.0ms (**2B**) | **Empty** — Web Component not traversable |\n| `GET /elementText` (video) | 3.7ms | 13ms | 4.6ms | 4.2ms (**2B**) | **Empty** |\n| `GET /attribute` | 3.8ms | 7.0ms | 4.5ms | 4.7ms (`null`) | **null** — selector not found |\n| `GET /isVisible` (search) | 3.3ms | 7.7ms | 3.9ms | 4.9ms (`false`) | Shadow DOM barrier? |\n| `GET /cookies` | 2.8ms | 8.8ms (14KB) | 3.8ms (2.8KB) | 5.5ms (6.9KB) | |\n\n#### Action Endpoints\n\n| Endpoint | example.com | Gmail | X | YouTube | Notes |\n|---|---|---|---|---|---|\n| `POST /hover` | 6.7ms | 73ms | 11ms | **8.5ms** | Fast after warm-up (first: 19ms) |\n| `POST /scrollTo` | 5.7ms | 45ms | 7ms | **6.1ms** | |\n| `POST /focus` | 5.1ms | 42ms | 27ms | **7.5ms** | |\n| `POST /click` | 165ms | 318ms | 403ms | **333ms** (`ok:false`) | **Failed** — click didn't register |\n| `POST /navigate` (SPA) | 49ms | 30s | 175ms | **31ms-2.2s** | Variable — home=2.2s, trending=31ms |\n| `POST /waitForElement` | 3.8ms | 5s | 73ms-5s | **105ms-5s** | `ytd-video-renderer` not found on trending |\n| `POST /regionScreenshot` | - | 39ms | 120ms | **11ms** (12.5KB) | Very fast — small content |\n\n### Key Findings for YouTube\n\n#### 1. Web Components are opaque to element queries\n\n**Severity**: Critical (functional)\n**Observed**: `element?selector=ytd-rich-item-renderer` returns 2 bytes (empty). `attribute?selector=a#video-title-link&name=href` returns `null`. `isVisible?selector=input#search` returns `false`.\n**Root cause**: YouTube uses Polymer/Lit Web Components with Shadow DOM. Standard `querySelector` cannot pierce shadow boundaries. The API's DOM operations only search the light DOM.\n**Impact**: Most element-targeting operations are effectively broken on YouTube. Selectors like `ytd-rich-item-renderer`, `a#thumbnail`, `input#search` exist inside shadow roots and are invisible to the API.\n**Recommendation**: Implement `deepQuerySelector` that traverses into shadow roots, or provide a `piercesShadow: true` option.\n\n#### 2. Click returned `ok:false` on video thumbnail\n\n**Severity**: High\n**Observed**: `POST /click` with `selector: \"a#thumbnail\"` returned `{\"ok\":false}` in 333ms. URL didn't change.\n**Root cause**: Related to Shadow DOM issue — the element was likely found in light DOM but actionability checks or coordinate computation failed because the rendered element is inside a shadow root.\n\n#### 3. Instance creation is extremely slow (19.4s)\n\n**Observed**: 19.4s vs Gmail 4.2s vs X 2.2s vs example.com 6.9s.\n**Root cause**: YouTube loads very heavy JS bundles, preloads video content, and runs extensive initialization. The `load` event fires late.\n**Impact**: First-time access to YouTube via the API is very slow.\n\n#### 4. SPA navigate latency is inconsistent\n\n**Observed**: Navigate to `/feed/trending` = 31ms (fast). Navigate back to home = 2.2s (slow).\n**Root cause**: YouTube's home page triggers heavy content loading (video thumbnails, recommendations). Trending page is lighter. The `load`/`DOMContentLoaded` event timing varies dramatically.\n\n#### 5. Text extraction is fast but returns very little\n\n**Observed**: `GET /text` = 960ms but only 7.9KB of text. Gmail returns 107KB, X returns 44KB.\n**Root cause**: Most of YouTube's visible text is inside Web Components' shadow DOMs. Turndown can only see the light DOM text, which is minimal.\n**Impact**: The text endpoint is nearly useless on YouTube — it misses video titles, descriptions, channel names, etc.\n\n#### 6. Screenshots are very small (60KB)\n\n**Observed**: 47ms for a 60KB screenshot. Gmail = 397KB, X = 527KB.\n**Root cause**: YouTube's dark theme with simple thumbnail grid produces a highly compressible PNG. Screenshots DO render correctly (they capture the visual output, not DOM), so screenshots are the most reliable way to \"see\" YouTube's content.\n\n### YouTube Latency Budget (typical MCP workflow)\n\n| Step | Endpoint | Time | Status |\n|---|---|---|---|\n| 1. Create instance | `POST /instances` | ~19400ms | Very slow |\n| 2. Get page text | `GET /text` | ~960ms | Fast but mostly empty |\n| 3. Click video | `POST /click` | ~333ms | **FAILS** (Shadow DOM) |\n| 4. Get video text | `GET /text` | ~850ms | Mostly empty |\n| **Total** | | **~21.5s** | **Partially broken** |\n\n**Conclusion**: YouTube is largely non-functional with the current API due to Shadow DOM. Screenshots work, but text extraction and element interaction are severely limited.\n\n---\n\n## Cross-Site Summary (Final)\n\n### Performance Matrix\n\n| Endpoint | example.com | Gmail | X | YouTube | Category |\n|---|---|---|---|---|---|\n| Simple reads | 3-4ms | 4-40ms | 4-6ms | 3-5ms | OK everywhere |\n| `GET /exists` | 41ms | 80ms | 97ms | 33ms | Slow everywhere |\n| `GET /html` | 7ms | 1.0s | 252ms | 256ms | Scales with DOM |\n| `GET /text` | 9ms | **2.4s** | **1.7s** | 960ms* | *YouTube: mostly empty |\n| `POST /click` | 165ms | 318ms | 403ms | 333ms** | **YouTube: fails |\n| `POST /navigate` (SPA) | 49ms | **30s** | 175ms | 31ms-2.2s | Gmail broken |\n| `GET /screenshot` | 76ms | 134ms | 157ms | 47ms | Always works |\n| `GET /ax-tree` | 46B | 46B | 46B | 46B | Broken everywhere |\n| Instance creation | 6.9s | 4.2s | 2.2s | **19.4s** | YouTube very slow |\n\n### Final Priority List\n\n| Priority | Issue | Impact | Sites Affected |\n|---|---|---|---|\n| **1** | **Shadow DOM not supported** | Element queries, click, text extraction all fail | YouTube (and any Web Component site) |\n| **2** | **`text` extraction 1-2.7s** | Primary MCP endpoint, blocks every agent loop | Gmail, X, YouTube |\n| **3** | **SPA `navigate` 30s timeout** | Workflow completely blocked | Gmail |\n| **4** | **`ax-tree` non-functional** | Accessibility data unavailable | All sites |\n| **5** | **`exists` 33-97ms** | 10-25x slower than similar endpoints | All sites |\n| **6** | **`click` 165-403ms** | 100ms fixed `waitForStable` delay | All sites |\n| **7** | **Instance creation 2-19s** | Slow first access, especially YouTube | All sites |\n\n---\n\n## Raw Data\n\nAll measurements taken with:\n```bash\ncurl -s -w \"%{time_total}\" -o /dev/null <url>\n```\n\n- Iterations: 3-5 per endpoint\n- Warm-up: Server was idle before measurements; first call to each endpoint may include JIT compilation overhead\n- Pages: `https://example.com` (15KB), Gmail inbox (~950KB, 243 messages), X home timeline (~836KB), YouTube home (~853KB)\n- Network: Localhost loopback (127.0.0.1), no auth token configured\n\n<!-- File: .cursorrules (Tokens: ~2196 | Category: cursor-rule) -->\n# Floorp プロジェクトルール\n\nこのプロジェクトは Mozilla Firefox をベースにした Web ブラウザ \"Floorp\" です。\n\n## 必読ドキュメント\n\nコーディング前に以下のドキュメントを参照してください：\n\n- `docs/llm/README.md` - LLM 向けドキュメントの索引\n- `docs/llm/project-overview.md` - プロジェクト全体の概要\n- `docs/llm/development-notes.md` - 開発ガイドとベストプラクティス\n- `docs/llm/architecture-deep-dive.md` - アーキテクチャ詳細\n- `.claude/context.md` - クイックリファレンス\n\n## 技術スタック\n\n- **ランタイム**: Deno 2.x (メイン), Node.js 22 (一部)\n- **UI**: SolidJS (ブラウザクローム), React (設定ページ)\n- **ビルド**: Vite, feles-build\n- **言語**: TypeScript\n- **CSS**: Tailwind CSS\n\n## コーディング規約\n\n### 型定義\n\n**重要**: 型定義は可能な限り別ファイルに分離してください。\n\n```typescript\n// Good: 型定義を types.ts に分離\n// types.ts\nexport interface Config {\n  enabled: boolean;\n  timeout: number;\n}\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n\n// Bad: 実装と型を混在させる\nexport interface Config { /* ... */ }\nexport class Feature { /* ... */ }\n```\n\n**例外**: `.sys.mts` ファイルでは Firefox API との統合のため、型定義を同じファイルに書いても構いません。\n\n### TypeScript\n\n- `any` 型は避ける\n- 明確な型定義を使用\n- 型推論を活用\n- null/undefined のチェックを忘れずに\n\n```typescript\n// Good\ninterface User {\n  id: number;\n  name: string;\n}\n\nfunction getUser(id: number): User | null {\n  // ...\n}\n\n// Bad\nfunction getUser(id: any): any {\n  // ...\n}\n```\n\n### SolidJS (ブラウザクローム機能)\n\n- リアクティブな状態管理には `createSignal` を使用\n- 直接変数を変更しない\n- HMR サポートのために `@noraComponent(import.meta.hot)` デコレーターを使用\n\n```typescript\n// Good\nimport { createSignal } from \"solid-js\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n\n// Bad\nlet count = 0;\ncount++; // 動作しない\n```\n\n### React (設定ページ)\n\n- 関数コンポーネントを使用\n- Hooks を適切に使用\n- Tailwind CSS でスタイリング\n\n```typescript\n// Good\nexport default function SettingsPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### ファイル配置\n\n- **ブラウザ UI 機能**: `browser-features/chrome/common/{feature-name}/`\n- **Firefox API モジュール**: `browser-features/modules/modules/{module-name}.sys.mts`\n- **設定ページ**: `browser-features/pages-settings/src/pages/`\n- **型定義**: 各機能の `types.ts` ファイル（`.sys.mts` を除く）\n\n### エラーハンドリング\n\n常に適切なエラーハンドリングを実装してください。\n\n```typescript\n// Good\ntry {\n  const data = await fetchData(url);\n  return data;\n} catch (error) {\n  console.error(\"[FeatureName] Failed to fetch:\", error);\n  return null; // フォールバック\n}\n\n// Bad\nconst data = await fetchData(url); // エラーが伝播\n```\n\n### コメント\n\n- 複雑なロジックには日本語または英語でコメントを追加\n- 関数の目的は JSDoc で説明\n- TODO コメントには担当者を明記\n\n```typescript\n/**\n * ユーザー設定を取得します\n * @param userId ユーザー ID\n * @returns ユーザー設定オブジェクト、存在しない場合は null\n */\nfunction getUserConfig(userId: string): UserConfig | null {\n  // TODO(@username): キャッシュ機構を実装\n  return null;\n}\n```\n\n## 新機能追加のチェックリスト\n\n1. **適切な場所に配置**\n   - ブラウザ UI → `browser-features/chrome/common/`\n   - システムモジュール → `browser-features/modules/modules/`\n   - 設定ページ → `browser-features/pages-settings/`\n\n2. **型定義を別ファイルに**\n   - `types.ts` を作成（`.sys.mts` 以外）\n   - インターフェースと型を定義\n\n3. **HMR サポートを追加**（ブラウザクローム機能のみ）\n   ```typescript\n   @noraComponent(import.meta.hot)\n   export default class MyFeature extends NoraComponentBase {\n     init(): void { /* ... */ }\n   }\n   ```\n\n4. **機能を登録**\n   - `browser-features/chrome/common/mod.ts` に追加\n\n5. **翻訳を追加**\n   - 少なくとも `i18n/en-US/` と `i18n/ja-JP/` に追加\n\n6. **必要に応じて Actor を追加**（マルチプロセス通信が必要な場合）\n   - Parent: `browser-features/modules/actors/{Name}Parent.sys.mts`\n   - Child: `browser-features/modules/actors/{Name}Child.sys.mts`\n   - 登録: `browser-features/modules/modules/BrowserGlue.sys.mts`\n\n## 開発コマンド\n\n```bash\n# 開発モード（HMR 付き）\ndeno task feles-build dev\n\n# 本番ビルド\ndeno task feles-build build\n\n# ステージングビルド\ndeno task feles-build stage\n\n# 依存関係のインストール\ndeno install\n```\n\n## モジュールパスエイリアス\n\n```typescript\nimport { foo } from \"#i18n/utils\";           // i18n/\nimport { bar } from \"#chrome/common/tab\";    // chrome/\nimport { baz } from \"#libs/shared\";          // libs/\nimport { qux } from \"#modules/experiments\";  // browser-features/modules/\n```\n\n## よくある問題\n\n### HMR が動作しない\n- `@noraComponent(import.meta.hot)` デコレーターが付いているか確認\n- `NoraComponentBase` を継承しているか確認\n\n### Firefox API にアクセスできない\n- `.sys.mts` ファイルから ChromeUtils.importESModule() を使用\n\n### 型エラー\n- 型定義を別ファイル（`types.ts`）に分離\n- `any` 型を使用していないか確認\n\n## パフォーマンス\n\n- `init()` メソッドで重い処理を避ける\n- 遅延初期化を活用\n- イベントリスナーを適切にクリーンアップ\n- メモリリークに注意\n\n## テスト\n\n- 新機能には可能な限りテストを追加\n- テストは `browser-features/chrome/test/unit/` に配置\n- Deno のテストフレームワークを使用\n\n## Git コミット\n\n- 意味のあるコミットメッセージ\n- 1 コミット = 1 つの論理的な変更\n- コミット前に `deno fmt` で整形\n\n## 参考リンク\n\n- プロジェクトドキュメント: `docs/llm/`\n- Deno: https://docs.deno.com/\n- SolidJS: https://www.solidjs.com/\n- React: https://react.dev/\n- Firefox Source: https://firefox-source-docs.mozilla.org/\n\n---\n\nこれらのルールに従って、一貫性のある高品質なコードを書いてください。\n\n<!-- File: CLAUDE.md (Tokens: ~2251 | Category: claude-rule) -->\n# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\nFloorp is a Firefox-based web browser (\"Noraneko\") built on top of the Gecko engine. This repo contains the custom browser features that overlay Firefox — not the Firefox source itself.\n\n## Commands\n\n```bash\ndeno install                        # Install dependencies\ndeno task feles-build dev           # Dev mode with HMR (ports 5173–5186)\ndeno task feles-build build         # Production build (two-phase: --phase before-mach / --phase after-mach)\ndeno task feles-build stage         # Staging build\ndeno task feles-build test          # Launch browser with Marionette for automated testing\ndeno task feles-build misc patch    # Manage Firefox source patches (apply/create/init)\ndeno task test                      # Run unit tests (browser-integrated, uses colocated test runner)\ndeno task test -- --near <path>     # Run tests near a specific file/directory\ndeno task test -- --layer chrome    # Run only chrome-layer tests (also: esm, pages, all)\ndeno task test:host                 # Run tool tests (Deno native)\ndeno task test:smoke                # Smoke tests\ndeno task dev-tool                  # Development utility CLI\n```\n\n## Architecture (5 Layers)\n\n```notes\nFirefox Base  ← patched Gecko, pref overrides (static/gecko/pref/override.ini)\n     ↓\nESM Modules   ← .sys.mts files with direct Firefox API access, Window Actors\n     ↓\nBridge        ← startup scripts that load features from Vite dev servers (HTTP) or chrome://noraneko/ (prod)\n     ↓\nChrome UI     ← SolidJS → XUL via custom solid-xul renderer, auto-discovered by import.meta.glob\n     ↓\nPages         ← React + Tailwind full-page UIs (settings, new tab, welcome, notes, etc.)\n```\n\nThe bridge (`bridge/startup/src/chrome_root.ts`) is the bootstrap: in dev/test mode it loads from `http://localhost:5181/loader/index.ts` with retry logic; in production it loads `chrome://noraneko/content/core.js`.\n\n## Tech Stack\n\n- **Runtime**: Deno 2.x (primary), Node.js 22 (some pages)\n- **Browser Chrome UI**: SolidJS + `@nora/solid-xul` (custom renderer that uses `document.createXULElement()` via `solid-js/universal`'s `createRenderer`)\n- **Settings/Pages UI**: React + Tailwind CSS\n- **Build**: Vite via custom `feles-build` system (`tools/feles-build.ts`)\n- **Language**: TypeScript (strict)\n\n## Path Aliases (deno.json)\n\n```typescript\n#i18n/              → ./i18n/\n#chrome/            → ./chrome/\n#libs/              → ./libs/\n#features-chrome/   → ./browser-features/chrome/\n#modules/           → ./browser-features/modules/\n#ui/                → ./src/ui/\n#themes/            → ./src/themes/\n```\n\n## Coding Conventions\n\n### File Placement\n\n| What               | Where                                                         | Framework   |\n| ------------------ | ------------------------------------------------------------- | ----------- |\n| Browser UI feature | `browser-features/chrome/common/{name}/`                      | SolidJS     |\n| Firefox API module | `browser-features/modules/modules/{name}.sys.mts`             | Firefox ESM |\n| Settings page      | `browser-features/pages-settings/src/app/{name}/`             | React       |\n| Actor (IPC)        | `browser-features/modules/actors/{Name}Parent\\|Child.sys.mts` | Firefox ESM |\n\n### Feature Auto-Discovery\n\n`browser-features/chrome/common/mod.ts` uses `import.meta.glob(\"./*/index.ts\")` — adding a directory with an `index.ts` under `common/` is sufficient. No manual registration needed.\n\nActor registration is manual: add entries to the `JS_WINDOW_ACTORS` object in `browser-features/modules/modules/BrowserGlue.sys.mts`.\n\n### Type Definitions\n\nSeparate types into dedicated `types.ts` files. Exception: `.sys.mts` files may include inline types.\n\n### No `any`\n\nNever use `any`. Use explicit types or `unknown`.\n\n### SolidJS Pattern (Browser Chrome)\n\n```typescript\nimport { noraComponent, NoraComponentBase } from \"#features-chrome/utils/base\";\nimport { render } from \"@nora/solid-xul\";\nimport { createSignal } from \"solid-js\";\n\n@noraComponent(import.meta.hot)\nexport default class MyFeature extends NoraComponentBase {\n  init(): void {\n    /* ... */\n  }\n}\n```\n\n- Always use `@noraComponent(import.meta.hot)` decorator for HMR support\n- Use `createSignal` / `createMemo` for reactive state — never mutate variables directly\n\n### Firefox ESM Modules (.sys.mts)\n\n```typescript\nconst { SomeService } = ChromeUtils.importESModule(\n  \"resource://floorp/lib/SomeService.sys.mjs\",\n);\n```\n\n### React Pattern (Settings Pages)\n\n```typescript\nexport default function MyPage() {\n  const [value, setValue] = useState(\"\");\n  return <div className=\"p-4\">...</div>;\n}\n```\n\n### i18n\n\nTranslations use i18next-style `{{variable}}` interpolation and `_plural` suffix keys. Add strings to at least `i18n/en-US/` and `i18n/ja-JP/`. Organized by feature namespace in `browser-chrome.json`.\n\n### Error Handling\n\nUse try/catch with `console.error(\"[FeatureName]\", ...)` prefix for log messages.\n\n## Testing\n\nTests run **inside the actual Firefox browser**, not in Deno/Node. They are plain TypeScript functions with a custom harness (`test_harness.ts` providing `assert`, `assertEquals`, `TestCase`), not `Deno.test()`.\n\n```typescript\n// @colocated-env browser\nimport { type TestCase, assert } from \"../../../test/utils/test_harness.ts\";\n\nfunction testSomething(): void {\n  assert(condition, \"message\");\n}\n\nexport function runAllTests(): void {\n  const tests: TestCase[] = [{ name: \"something works\", fn: testSomething }];\n  // ...run and collect failures\n}\n```\n\nColocated in `test/` directories next to source. The runner discovers them automatically.\n\n## Dev Server Ports\n\n- 5173: Main features\n- 5174–5177: Other pages\n- 5178: Settings pages\n- 5181: Feature loader (bridge)\n- 5186: New tab page\n\n## dev-tool — Browser Inspection CLI\n\n`deno task dev-tool` communicates with a running Floorp instance via the **Marionette protocol** (Firefox's TCP-based WebDriver). All browser commands require the browser to be running (started via `dev-tool start` or `feles-build dev`).\n\n### Process Management\n\n```bash\ndeno task dev-tool start      # Start dev server + browser in background (waits for Marionette ready)\ndeno task dev-tool stop       # Stop dev processes belonging to this checkout\ndeno task dev-tool stop --all # Recovery: stop dev processes across ALL checkouts\ndeno task dev-tool restart    # Stop then start\ndeno task dev-tool rebuild    # Rebuild startup + modules + inject XHTML without restarting browser (HMR handles loader-features)\n```\n\nProcess identities are stored in this checkout's `_dist/dev-processes.json`.\nUse `stop --all` only for machine-wide recovery, including older orphaned runs\nwithout recorded identities; it also stops other checkouts.\n\n### Browser Commands\n\n```bash\ndeno task dev-tool status                                      # Check connection: shows page title, URL, tab count, active tab\ndeno task dev-tool eval \"JSON.stringify(Services.prefs.getStringPref('floorp.some.pref'))\"  # Execute JS in browser (returns result)\ndeno task dev-tool console                                     # Last 50 console messages (via Services.console)\ndeno task dev-tool console -l 100 -f \"workspace\" -l error      # Filtered: 100 messages, text filter \"workspace\", errors only\ndeno task dev-tool console --level error                       # Level filter: error/warn/info/debug/all\ndeno task dev-tool screenshot                                  # Full-page screenshot → _dist/screenshot.png\ndeno task dev-tool screenshot -s \"#tabbrowser-tabs\" -o out.png # Element screenshot by CSS selector\ndeno task dev-tool navigate about:preferences                  # Navigate browser to URL\ndeno task dev-tool dom \"#sidebar-box\"                          # Inspect DOM: tag, id, class, text, attributes, child count\ndeno task dev-tool title                                       # Get current page title\n```\n\n### Context Flag (`--context` / `-c`)\n\nAll browser commands accept `--context` to choose the JS execution context:\n\n- `chrome` (default) — browser chrome scope. Access `Services`, `gBrowser`, XUL elements, Firefox internals, prefs\n- `content` — web content scope. Interact with loaded page DOM as a normal web page\n\n```bash\ndeno task dev-tool eval \"gBrowser.tabs.length\" -c chrome    # Count open tabs (chrome context)\ndeno task dev-tool eval \"document.title\" -c content         # Get page title from content context\n```\n\n### Typical LLM Workflow\n\n1. `deno task dev-tool start` — launch browser\n2. Edit source files (HMR updates chrome UI automatically)\n3. `deno task dev-tool console --level error` — check for runtime errors\n4. `deno task dev-tool eval \"...\"` — inspect live state (prefs, DOM, services)\n5. `deno task dev-tool screenshot` — visually verify UI changes\n6. `deno task dev-tool rebuild` — if HMR didn't pick up changes (modules/startup only)\n7. `deno task dev-tool stop` — shut down when done\n\n## Debugging\n\n- Browser Console: `Ctrl+Shift+J` / `Cmd+Option+J`\n- DevTools: `Ctrl+Shift+I` / `Cmd+Option+I`\n- Log convention: `console.log(\"[FeatureName]\", ...)`\n\n## Further Reading\n\n- `docs/llm/project-overview.md` — Full project overview\n- `docs/llm/architecture-deep-dive.md` — 5-layer architecture, Window Actor patterns, build system internals\n- `docs/llm/development-notes.md` — Setup requirements, .sys.mts vs .ts decision matrix, dev-tool CLI\n\n<!-- File: .github/copilot-instructions.md (Tokens: ~2792 | Category: copilot-instructions) -->\n# AI Coding Agent Instructions\n\nThis workspace contains multiple interconnected projects: **Floorp** (Firefox-based browser), **Sapphillon** (workflow automation backend), **Floorp-OS-Automator-Frontend**, and **web-store**.\n\n## Project Overview\n\n### Floorp (`floorp/`)\nFirefox-based browser built with Deno 2.x, SolidJS, and React. Custom browser features overlay Firefox's Gecko engine.\n\n### Sapphillon Backend (`Floorp-OS-Automator-Backend/`)\nRust-based workflow automation backend using gRPC (tonic), SeaORM, and Deno runtime for executing JavaScript workflows.\n\n### Frontend Projects\n- **Floorp-OS-Automator-Frontend**: React + TypeScript + Vite UI for workflow management\n- **web-store**: Plugin marketplace with React + Vite\n\n---\n\n## Cross-Project Integration\n\nThis workspace contains interconnected projects. Understanding data flow and integration points is crucial for full-stack development.\n\n### Data Flow Architecture\n\n```\n┌──────────────────────────────────────────────────────────────┐\n│                    Floorp Browser                        │\n│              (Mozilla Firefox + Custom Features)           │\n│  Location: /Users/user/dev-source/floorp-dev/floorp/     │\n│  Dev: deno task dev (ports: 5173-5186)              │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ Floorp OS API (OpenAPI)\n                          │ openapi.yaml:\n                          │ Floorp-OS-Automator-Backend/plugins/floorp/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│              Sapphillon Backend (Rust)                │\n│  Location: ../Floorp-OS-Automator-Backend/          │\n│  Dev: make run (gRPC on localhost:50051)            │\n│  - Plugin system (floorp, fetch, filesystem, etc.)    │\n│  - Workflow engine (Deno Core runtime)                 │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ gRPC (tonic + prost)\n                          │ protobuf in:\n                          │ Floorp-OS-Automator-Frontend/vender/Sapphillon_API/\n                          │\n                          ▼\n┌──────────────────────────────────────────────────────────────┐\n│         Floorp-OS-Automator-Frontend (React)          │\n│  Location: ../Floorp-OS-Automator-Frontend/          │\n│  Dev: pnpm dev (port 8081)                          │\n│  - gRPC-Web client (@connectrpc/connect-web)           │\n│  - Workflow management UI                                │\n└───────────────────────────┬────────────────────────────────┘\n                          │\n                          │ (optional, disabled)\n                          │ PostMessage to Floorp\n                          │ Progress Window\n                          ▼\n                   ┌────────────────┐\n                   │  Floorp       │\n                   │  Progress     │\n                   │  Window       │\n                   └────────────────┘\n\n                          ▲\n                          │\n                ┌─────────┴──────────┐\n                │                    │\n┌───────────────┐      ┌────────────────┐\n│  Web Store    │      │  External     │\n│  (Plugin      │      │  Plugins     │\n│   Marketplace)│      │              │\n└───────────────┘      └────────────────┘\n```\n\n### Integration Points\n\n**1. Floorp → Sapphillon** (Browser Automation):\n- Floorp exposes browser automation via OpenAPI spec at `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`\n- Sapphillon's `floorp` plugin consumes this API to control browser tabs, navigation, etc.\n- Workflows can automate browser interactions (open tabs, navigate, fill forms)\n\n**2. Sapphillon → Frontend** (Workflow Management):\n- gRPC communication using `tonic` (server) and `@connectrpc/connect-web` (client)\n- Protobuf definitions in `Floorp-OS-Automator-Frontend/vender/Sapphillon_API/proto/`\n- Frontend generates TypeScript clients from `.proto` files\n- Services: Workflow, Plugin, Version, Model, Provider\n\n**3. Frontend → Floorp** (Progress Tracking):\n- Disabled by default (see `lib/workflow-progress.ts`)\n- Uses `window.OSAutomotor?.sendWorkflowProgress()` for real-time updates\n- Would show workflow progress in Floorp's native progress window\n\n**4. Web Store → Sapphillon** (Plugin Distribution):\n- Plugin marketplace at `../web-store/`\n- Plugins installed via Sapphillon's plugin installer\n- External plugins run in separate processes with gRPC communication\n\n### Development Setup for Full Stack\n\n**Recommended workflow for full-stack development**:\n```bash\n# Terminal 1: Start Floorp Browser\ncd /Users/user/dev-source/floorp-dev/floorp\ndeno task dev\n\n# Terminal 2: Start Sapphillon Backend\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Backend\nmake run  # Starts gRPC server on localhost:50051\n\n# Terminal 3: Start Frontend (production mode)\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:prod  # Connects to localhost:50051\n```\n\n**Frontend-only development** (no backend needed):\n```bash\ncd /Users/user/dev-source/sapphillon-dev/Floorp-OS-Automator-Frontend\npnpm dev:mock  # Mock gRPC on port 50099, Vite on 5199\n```\n\n---\n\n## Floorp Development Patterns\n\n### Build System\n- **Primary**: `deno task dev` - Runs custom feles-build system\n- **Build orchestration**: `tools/feles-build.ts` orchestrates patches, symlinks, Vite dev servers\n- **Dev server ports**: 5173 (main), 5178 (settings), 5186 (newtab), 5174-5177 (other pages)\n\n### Code Organization\n\n**Type Definitions**: Always separate types into dedicated files (`types.ts`), not mixed with implementation.\n```typescript\n// Good: types.ts\nexport interface Config { enabled: boolean; }\n\n// index.ts\nimport type { Config } from \"./types.ts\";\n```\n**Exception**: `.sys.mts` files can include types with Firefox API integration.\n\n**File Extensions**:\n- `.ts` - General TypeScript\n- `.sys.mts` - Firefox ESM modules (loaded via `ChromeUtils.importESModule()`)\n- `.jsx` - React components in pages-*/ directories\n\n### UI Framework Usage\n\n**SolidJS** (`browser-features/chrome/`):\n- Use `createSignal` for reactive state (never mutate directly)\n- `@noraComponent(import.meta.hot)` decorator for HMR support\n- Import from `@nora/solid-xul` for rendering:\n```typescript\nimport { render, createSignal } from \"@nora/solid-xul\";\nconst [count, setCount] = createSignal(0);\nsetCount(c => c + 1);\n```\n\n**React** (`browser-features/pages-*/`):\n- Functional components with hooks\n- Tailwind CSS for styling\n- `import { createRootHMR } from \"@nora/solid-xul\"` for i18n integration\n\n### Firefox API Integration\nAccess Firefox APIs via ESM modules in `.sys.mts` files:\n```typescript\nconst { I18nUtils } = ChromeUtils.importESModule(\"resource://floorp/lib/I18nUtils.sys.mjs\");\n```\n\n---\n\n## Sapphillon Backend Patterns\n\n### Architecture\n- **gRPC Service Layer**: `src/services/` - Tonic-based services (workflow, plugin, model, version, provider)\n- **Plugin System**: Modular plugins in `plugins/` (fetch, filesystem, floorp, vscode, git, finder, etc.)\n- **Database**: SeaORM with SQLite, migrations in `migration/`, entities in `entity/`\n- **Workflow Engine**: Deno Core runtime executes JavaScript workflows with plugin permissions\n\n### Common Commands\n```bash\nmake rust_test          # Run all workspace tests\nmake rust_build         # Build entire workspace\nmake migrate            # Run SeaORM migrations\nmake entity_generate    # Generate entities from DB\nmake run                # Run with debug DB at ./debug/sqlite.db\nmake grpcui            # Launch gRPC UI on localhost:50051\n```\n\n### Testing\n- Unit tests: `cargo test --lib`\n- External plugin tests: `cargo test --test external_plugin`\n- Ignored tests: `cargo test --lib external_plugin -- --ignored`\n\n### Plugin Development\nEach plugin crate exposes Deno-compatible functions. See `plugins/floorp/` for OpenAPI-based Floorp browser control.\n\n**Debug Workflows**: Place JS files in `debug_workflow/` directory - auto-registered every 10s in debug builds with full permissions (`[DEBUG]` prefix).\n\n### gRPC & Protocol Buffers\n- Uses `tonic` for server, `prost` for code generation\n- `buf.yaml` and `buf.gen.yaml` configuration\n- Generate with `buf generate`\n\n---\n\n## Frontend Patterns (Both Projects)\n\n### Build Commands\n```bash\nnpm run dev              # Vite dev server\nnpm run build            # TypeScript check + Vite build\nnpm run test             # Vitest\nnpm run lint             # ESLint\n```\n\n### Component Patterns\n- **Chakra UI**: Primary component library\n- **i18next**: Internationalization via `src/i18n/config.ts`\n- **React Router**: Routing in `src/routes/`\n- **Type Definitions**: Export from `src/types/`, not inline\n\n### gRPC Communication\n- `@connectrpc/connect-web` for browser-based gRPC\n- `@connectrpc/connect` for Node-based\n- Generated clients in `src/gen/` from proto definitions\n\n---\n\n## Cross-Project Integration\n\n### Floorp OS API\nFloorp exposes browser automation via OpenAPI spec in `Floorp-OS-Automator-Backend/plugins/floorp/api-spec/openapi.yaml`. The Sapphillon floorp plugin consumes this for workflow automation.\n\n### Data Flow\n```\nFloorp Browser\n    ↓ (Floorp OS API)\nSapphillon Backend (floorp plugin)\n    ↓ (gRPC)\nFloorp-OS-Automator-Frontend\n```\n\n### Plugin System\nWorkflows in Sapphillon can invoke plugins including:\n- **floorp**: Control Floorp browser (tabs, navigation, etc.)\n- **fetch**: HTTP requests\n- **filesystem**: File operations\n- **vscode**: VS Code control\n- **finder**: macOS Finder automation\n- And more in `plugins/`\n\n---\n\n## Key Conventions\n\n### Error Handling\n- **Floorp**: Use `Result<T, E>` from fp-ts for type-safe error handling\n- **Sapphillon**: `anyhow::Result<T>` and `tonic::Status` for gRPC errors\n\n### State Management\n- **SolidJS**: `createSignal` - never mutate directly\n- **React**: `useState`, `useContext` for global state\n\n### Database Operations\n- Use SeaORM `Entity::find().all(db).await?` pattern\n- Migrations: `sea-orm-cli migrate generate <name>`\n- Entities are auto-generated - don't edit manually\n\n### Permissions\nSapphillon uses wildcard `*` plugin_function_id to grant workflows full access. Used for trusted workflows and testing.\n\n---\n\n## Language-Specific Notes\n\n### Rust\n- Edition 2024, workspace resolver \"3\"\n- Async/await with tokio runtime\n- `#[tonic::async_trait]` for gRPC service implementations\n\n### TypeScript/Deno\n- No `any` types - use explicit types or `unknown`\n- Null/undefined checks required\n- Deno permissions: `--allow-all` often needed for build scripts\n\n### React\n- Functional components only\n- Hooks over class components\n- Tailwind CSS classes (e.g., `className=\"p-4\"`)\n\n---\n\n## Critical Files Reference\n\n| Purpose | File |\n|---------|------|\n| Floorp build system | `floorp/tools/feles-build.ts` |\n| Floorp dev config | `floorp/deno.json` |\n| Sapphillon main entry | `Floorp-OS-Automator-Backend/src/main.rs` |\n| Sapphillon workflow service | `Floorp-OS-Automator-Backend/src/services/workflow.rs` |\n| Frontend Vite config | `Floorp-OS-Automator-Frontend/vite.config.ts` |\n| Floorp SolidJS renderer | `floorp/libs/solid-xul/index.ts` |\n| Plugin permissions | `Floorp-OS-Automator-Backend/src/services/workflow.rs:make_plugin_permission()` |\n</yakaai_skills>"}