Add interactive layer exploration workflow for UI design

- Implemented the `/workflow:ui-design:explore-layers` command for depth-controlled UI capture.
- Defined depth levels from full-page screenshots to Shadow DOM exploration.
- Included setup, validation, and navigation phases with error handling.
- Captured screenshots at various depths and generated a comprehensive layer map.
- Added examples and usage instructions for ease of use.
This commit is contained in:
catlog22
2025-10-11 15:29:33 +08:00
parent 980f554b27
commit 9993d599f8
10 changed files with 2191 additions and 3495 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -2,532 +2,323 @@
name: capture
description: Batch screenshot capture for UI design workflows using MCP or local fallback
usage: /workflow:ui-design:capture --url-map "<map>" [--base-path <path>] [--session <id>]
argument-hint: --url-map "target:url,..." [--base-path path] [--session id]
examples:
- /workflow:ui-design:capture --url-map "home:https://linear.app, pricing:https://linear.app/pricing"
- /workflow:ui-design:capture --session WFS-auth --url-map "dashboard:https://app.com/dash"
- /workflow:ui-design:capture --base-path ".workflow/.design/run-20250110" --url-map "hero:https://example.com#hero"
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), mcp__browser__screenshot(*)
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), ListMcpResourcesTool(*), mcp__chrome-devtools__*, mcp__playwright__*
---
# Batch Screenshot Capture Command
# Batch Screenshot Capture (/workflow:ui-design:capture)
## Overview
独立的批量截图命令支持MCP优先策略和多级降级机制。可被其他工作流复用。
Batch screenshot tool with MCP-first strategy and multi-tier fallback. Processes multiple URLs in parallel.
## Core Philosophy
- **MCP优先**优先使用mcp__browser__screenshot如果可用
- **智能降级**MCP失败 → Playwright → Chrome → 手动上传
- **批量处理**一次处理多个URL并行截图
- **结构化输出**按target_name组织截图文件
- **错误容忍**:部分失败不阻塞整体流程
**Strategy**: MCP → Playwright → Chrome → Manual
**Output**: Flat structure `screenshots/{target}.png`
## Execution Protocol
### Phase 0: 初始化和路径解析
## Phase 1: Initialize & Parse
### Step 1: Determine Base Path
```bash
# 确定base path
IF --base-path:
base_path = {provided_base_path}
ELSE IF --session:
# 查找session最新design run
session_design_dirs = Glob(".workflow/WFS-{session}/design-*")
IF session_design_dirs:
base_path = most_recent(session_design_dirs)
ELSE:
# 创建新的design run
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = ".workflow/WFS-{session}/design-{run_id}"
ELSE:
# Standalone模式
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = ".workflow/.design/{run_id}"
# Priority: --base-path > session > standalone
bash(if [ -n "$BASE_PATH" ]; then
echo "$BASE_PATH"
elif [ -n "$SESSION_ID" ]; then
find .workflow/WFS-$SESSION_ID/design-* -type d | head -1 || \
echo ".workflow/WFS-$SESSION_ID/design-run-$(date +%Y%m%d-%H%M%S)"
else
echo ".workflow/.design/run-$(date +%Y%m%d-%H%M%S)"
fi)
# 创建截图目录
screenshot_dir = "{base_path}/screenshots"
Bash(mkdir -p "{screenshot_dir}")
bash(mkdir -p $BASE_PATH/screenshots)
```
REPORT: "📸 Batch Screenshot Capture"
REPORT: " Output: {screenshot_dir}/"
# 解析url-map
url_map_string = {--url-map} # "home:https://a.com, pricing:https://a.com/pricing"
# 解析逻辑
### Step 2: Parse URL Map
```javascript
// Input: "home:https://linear.app, pricing:https://linear.app/pricing"
url_entries = []
FOR pair IN split(url_map_string, ","):
pair = pair.strip()
IF ":" NOT IN pair:
ERROR: "Invalid url-map format: '{pair}'"
ERROR: "Expected format: 'target:url'"
ERROR: "Example: 'home:https://example.com, pricing:https://example.com/pricing'"
EXIT 1
target, url = pair.split(":", 1)
target = target.strip().lower().replace(" ", "-")
url = url.strip()
FOR pair IN split(params["--url-map"], ","):
parts = pair.split(":", 1)
# 验证target名称
IF NOT regex_match(target, r"^[a-z0-9][a-z0-9_-]*$"):
ERROR: "Invalid target name: '{target}'"
ERROR: "Target names must start with alphanumeric and contain only [a-z0-9_-]"
EXIT 1
IF len(parts) != 2:
ERROR: "Invalid format: {pair}. Expected: 'target:url'"
EXIT 1
# 验证URL格式
IF NOT (url.startswith("http://") OR url.startswith("https://")):
WARN: "URL '{url}' does not start with http:// or https://"
WARN: "Prepending https:// automatically"
url = f"https://{url}"
target = parts[0].strip().lower().replace(" ", "-")
url = parts[1].strip()
url_entries.append({"target": target, "url": url})
// Validate target name
IF NOT regex_match(target, r"^[a-z0-9][a-z0-9_-]*$"):
ERROR: "Invalid target: {target}"
EXIT 1
VALIDATE: len(url_entries) > 0, "url-map must contain at least one target:url pair"
// Add https:// if missing
IF NOT url.startswith("http"):
url = f"https://{url}"
total_targets = len(url_entries)
REPORT: " Targets: {total_targets}"
FOR entry IN url_entries:
REPORT: " • {entry.target}: {entry.url}"
url_entries.append({target, url})
```
**Output**: `base_path`, `url_entries[]`
### Step 3: Initialize Todos
```javascript
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: "MCP batch screenshot capture", status: "pending", activeForm: "Capturing via MCP"},
{content: "Local tool fallback (if needed)", status: "pending", activeForm: "Local fallback"},
{content: "Verify and summarize results", status: "pending", activeForm: "Verifying"}
{content: "Parse url-map", status: "completed", activeForm: "Parsing"},
{content: "Detect MCP tools", status: "in_progress", activeForm: "Detecting"},
{content: "Capture screenshots", status: "pending", activeForm: "Capturing"},
{content: "Verify results", status: "pending", activeForm: "Verifying"}
]})
```
### Phase 1: MCP批量截图优先策略
## Phase 2: Detect Screenshot Tools
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 1: MCP Batch Screenshot"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
### Step 1: Check MCP Availability
```javascript
// List available MCP servers
all_resources = ListMcpResourcesTool()
available_servers = unique([r.server for r in all_resources])
# 检测MCP工具可用性
mcp_available = check_tool_availability("mcp__browser__screenshot")
// Check Chrome DevTools MCP
chrome_devtools = "chrome-devtools" IN available_servers
chrome_screenshot = check_tool_exists("mcp__chrome-devtools__take_screenshot")
success_captures = []
failed_captures = []
IF mcp_available:
REPORT: "✓ MCP browser screenshot tool detected"
# 构建MCP调用参数
urls = [entry.url for entry in url_entries]
file_prefixes = [entry.target for entry in url_entries]
TRY:
# MCP批量截图调用
REPORT: " Calling MCP for {len(urls)} URLs..."
result = mcp__browser__screenshot({
urls: urls,
output_dir: screenshot_dir,
file_prefix: file_prefixes,
full_page: true,
viewport: "1920,1080",
timeout: 30000
})
# 处理MCP返回结果
success_count = len(result.success)
failed_count = len(result.failed)
REPORT: " MCP capture complete: {success_count} succeeded, {failed_count} failed"
FOR item IN result.success:
success_captures.append(item.target)
REPORT: " ✓ {item.target}.png"
FOR item IN result.failed:
failed_captures.append({"target": item.target, "url": item.url, "error": item.error})
REPORT: " ✗ {item.target}: {item.error}"
# 如果有部分失败标记需要fallback
IF failed_count > 0:
failed_targets = [item.target for item in result.failed]
REPORT: " → {failed_count} failed, proceeding to local fallback..."
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
ELSE:
REPORT: "✅ All screenshots captured via MCP"
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_completed: "Local tool fallback", mark_in_progress: "Verify results")
GOTO Phase 3 (verification)
CATCH error:
REPORT: "⚠️ MCP call failed: {error}"
REPORT: " Falling back to local tools for all targets"
failed_targets = [entry.target for entry in url_entries]
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
// Check Playwright MCP
playwright_mcp = "playwright" IN available_servers
playwright_screenshot = check_tool_exists("mcp__playwright__screenshot")
// Determine primary tool
IF chrome_devtools AND chrome_screenshot:
tool = "chrome-devtools"
ELSE IF playwright_mcp AND playwright_screenshot:
tool = "playwright"
ELSE:
REPORT: " MCP browser screenshot tool not available"
REPORT: " Using local tool fallback strategy"
failed_targets = [entry.target for entry in url_entries]
TodoWrite(mark_completed: "MCP batch screenshot capture", mark_in_progress: "Local tool fallback")
GOTO Phase 2 (fallback_targets = failed_targets)
tool = null
```
### Phase 2: Local工具降级Playwright → Chrome
**Output**: `tool` (chrome-devtools | playwright | null)
### Step 2: Check Local Fallback
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🔧 Phase 2: Local Tool Fallback"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 仅处理Phase 1失败的targets
targets_to_capture = [entry for entry in url_entries if entry.target IN fallback_targets]
REPORT: "Processing {len(targets_to_capture)} target(s) with local tools..."
# 检测本地工具(检查可执行文件,不触发安装)
playwright_path = Bash(which playwright 2>/dev/null || echo "")
chrome_path = Bash(which google-chrome 2>/dev/null || which chrome 2>/dev/null || which chromium 2>/dev/null || echo "")
playwright_available = playwright_path != ""
chrome_available = chrome_path != ""
REPORT: " Tool availability:"
REPORT: " Playwright: {playwright_available ? '✓ Available' : '✗ Not found'}"
REPORT: " Chrome: {chrome_available ? '✓ Available' : '✗ Not found'}"
local_success = []
local_failed = []
FOR entry IN targets_to_capture:
target = entry.target
url = entry.url
output_file = "{screenshot_dir}/{target}.png"
captured = false
method_used = null
# 尝试Playwright
IF playwright_available AND NOT captured:
TRY:
REPORT: " Trying Playwright for '{target}'..."
Bash({playwright_path} screenshot "{url}" "{output_file}" --full-page --timeout 30000)
IF exists(output_file) AND file_size(output_file) > 1000: # >1KB验证有效
captured = true
method_used = "Playwright"
local_success.append(target)
success_captures.append(target)
REPORT: " ✓ {target}.png (Playwright, {file_size(output_file)/1024:.1f} KB)"
CATCH error:
REPORT: " ⚠️ Playwright failed: {error}"
# 尝试Chrome
IF chrome_available AND NOT captured:
TRY:
REPORT: " Trying Chrome for '{target}'..."
Bash({chrome_path} --headless --disable-gpu --screenshot="{output_file}" --window-size=1920,1080 "{url}")
IF exists(output_file) AND file_size(output_file) > 1000:
captured = true
method_used = "Chrome"
local_success.append(target)
success_captures.append(target)
REPORT: " ✓ {target}.png (Chrome, {file_size(output_file)/1024:.1f} KB)"
CATCH error:
REPORT: " ⚠️ Chrome failed: {error}"
# 标记彻底失败
IF NOT captured:
local_failed.append(entry)
failed_captures.append({"target": target, "url": url, "error": "All local tools failed"})
REPORT: " ✗ {target}: All tools failed"
REPORT: ""
REPORT: "Local fallback summary:"
REPORT: " Succeeded: {len(local_success)}/{len(targets_to_capture)}"
REPORT: " Failed: {len(local_failed)}/{len(targets_to_capture)}"
# 如果仍有失败,进入手动模式
IF len(local_failed) > 0:
TodoWrite(mark_completed: "Local tool fallback", mark_in_progress: "Manual upload mode")
GOTO Phase 2.5 (manual_upload)
ELSE:
TodoWrite(mark_completed: "Local tool fallback", mark_in_progress: "Verify results")
GOTO Phase 3 (verification)
# Only if MCP unavailable
bash(which playwright 2>/dev/null || echo "")
bash(which google-chrome || which chrome || which chromium 2>/dev/null || echo "")
```
### Phase 2.5: 手动上传降级
**Output**: `local_tools[]`
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "⚠️ Phase 2.5: Manual Screenshot Required"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
## Phase 3: Capture Screenshots
REPORT: "Failed to auto-capture {len(local_failed)} target(s):"
REPORT: ""
### Step 1: MCP Capture (If Available)
```javascript
IF tool == "chrome-devtools":
// Get or create page
pages = mcp__chrome-devtools__list_pages()
FOR entry IN local_failed:
REPORT: " {entry.target}:"
REPORT: " URL: {entry.url}"
REPORT: " Save to: {screenshot_dir}/{entry.target}.png"
REPORT: ""
IF pages.length == 0:
mcp__chrome-devtools__new_page({url: url_entries[0].url})
page_idx = 0
ELSE:
page_idx = 0
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "📋 Manual Steps:"
REPORT: " 1. Visit each URL above in your browser"
REPORT: " 2. Take full-page screenshot (Browser DevTools or extensions)"
REPORT: " 3. Save screenshot to specified path"
REPORT: " 4. Return here and choose an option"
REPORT: ""
REPORT: "Options:"
REPORT: " • Type 'ready' : I've uploaded screenshot(s), continue workflow"
REPORT: " • Type 'skip' : Skip failed screenshots, continue with available"
REPORT: " • Type 'abort' : Cancel entire capture workflow"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
mcp__chrome-devtools__select_page({pageIdx: page_idx})
user_response = WAIT_FOR_USER_INPUT()
// Capture each URL
FOR entry IN url_entries:
mcp__chrome-devtools__navigate_page({url: entry.url, timeout: 30000})
bash(sleep 2)
MATCH user_response.lower():
"ready" | "done" | "ok" | "continue":
# 验证手动上传的文件
manual_uploaded = []
REPORT: "🔍 Checking for manual screenshots..."
mcp__chrome-devtools__take_screenshot({
fullPage: true,
format: "png",
quality: 90,
filePath: f"{base_path}/screenshots/{entry.target}.png"
})
FOR entry IN local_failed:
expected_path = f"{screenshot_dir}/{entry.target}.png"
IF exists(expected_path) AND file_size(expected_path) > 1000:
manual_uploaded.append(entry.target)
success_captures.append(entry.target)
REPORT: " ✓ {entry.target}.png (manual, {file_size(expected_path)/1024:.1f} KB)"
ELSE:
REPORT: " ✗ {entry.target}.png not found or invalid"
IF len(manual_uploaded) > 0:
REPORT: "✅ Detected {len(manual_uploaded)} manual screenshot(s)"
# 移除已上传的targets from failed list
failed_captures = [f for f in failed_captures if f.target NOT IN manual_uploaded]
ELSE:
REPORT: "⚠️ No valid manual screenshots detected"
REPORT: " Proceeding with available screenshots only"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
"skip" | "s":
REPORT: "⏭️ Skipping {len(local_failed)} failed screenshot(s)"
REPORT: " Proceeding with {len(success_captures)} available screenshot(s)"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
"abort" | "cancel" | "exit":
ERROR: "Workflow aborted by user"
TodoWrite(mark_failed: "Manual upload mode")
EXIT 1
_:
REPORT: "⚠️ Invalid input '{user_response}', interpreting as 'skip'"
REPORT: " Proceeding with available screenshots"
TodoWrite(mark_completed: "Manual upload mode", mark_in_progress: "Verify results")
GOTO Phase 3
ELSE IF tool == "playwright":
FOR entry IN url_entries:
mcp__playwright__screenshot({
url: entry.url,
output_path: f"{base_path}/screenshots/{entry.target}.png",
full_page: true,
timeout: 30000
})
```
### Phase 3: 验证和总结
### Step 2: Local Fallback (If MCP Failed)
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "✅ Phase 3: Verification & Summary"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Try Playwright CLI
bash(playwright screenshot "$url" "$output_file" --full-page --timeout 30000)
# 扫描实际截图文件
captured_files = Glob("{screenshot_dir}/*.{png,jpg,jpeg,webp}")
captured_targets_actual = [extract_basename_without_ext(f) for f in captured_files]
# Try Chrome headless
bash($chrome --headless --screenshot="$output_file" --window-size=1920,1080 "$url")
```
# 与请求对比
total_requested = len(url_entries)
total_captured = len(captured_targets_actual)
missing_targets = [entry.target for entry in url_entries if entry.target NOT IN captured_targets_actual]
### Step 3: Manual Mode (If All Failed)
```
⚠️ Manual Screenshot Required
REPORT: "📊 Capture Summary:"
REPORT: " Total requested: {total_requested}"
REPORT: " Successfully captured: {total_captured}"
REPORT: " Success rate: {(total_captured / total_requested * 100):.1f}%"
Failed URLs:
home: https://linear.app
Save to: .workflow/.design/run-20250110/screenshots/home.png
IF missing_targets:
REPORT: ""
REPORT: "⚠️ Missing screenshots ({len(missing_targets)}):"
FOR target IN missing_targets:
REPORT: " • {target}"
ELSE:
REPORT: ""
REPORT: "✅ All requested screenshots captured!"
Steps:
1. Visit URL in browser
2. Take full-page screenshot
3. Save to path above
4. Type 'ready' to continue
Options: ready | skip | abort
```
## Phase 4: Verification
### Step 1: Scan Captured Files
```bash
bash(ls -1 $base_path/screenshots/*.{png,jpg,jpeg,webp} 2>/dev/null)
bash(du -h $base_path/screenshots/*.png 2>/dev/null)
```
### Step 2: Generate Metadata
```javascript
captured_files = Glob(f"{base_path}/screenshots/*.{{png,jpg,jpeg,webp}}")
captured_targets = [basename_no_ext(f) for f in captured_files]
# 生成capture元数据
metadata = {
"timestamp": current_timestamp(),
"total_requested": total_requested,
"total_captured": total_captured,
"success_rate": round(total_captured / total_requested * 100, 2),
"screenshots": []
"timestamp": current_timestamp(),
"total_requested": len(url_entries),
"total_captured": len(captured_targets),
"screenshots": []
}
FOR entry IN url_entries:
target = entry.target
url = entry.url
is_captured = target IN captured_targets_actual
is_captured = entry.target IN captured_targets
screenshot_info = {
"target": target,
"url": url,
"captured": is_captured
}
metadata.screenshots.append({
"target": entry.target,
"url": entry.url,
"captured": is_captured,
"path": f"{base_path}/screenshots/{entry.target}.png" IF is_captured ELSE null,
"size_kb": file_size_kb IF is_captured ELSE null
})
IF is_captured:
file_path = f"{screenshot_dir}/{target}.png"
screenshot_info["path"] = file_path
screenshot_info["size_kb"] = round(file_size(file_path) / 1024, 2)
# 查找捕获方法
IF target IN [s.target for s in result.success if mcp_available]:
screenshot_info["method"] = "MCP"
ELSE IF target IN local_success:
screenshot_info["method"] = "Local (Playwright/Chrome)"
ELSE:
screenshot_info["method"] = "Manual"
ELSE:
screenshot_info["path"] = null
screenshot_info["error"] = next((f.error for f in failed_captures if f.target == target), "Unknown error")
metadata.screenshots.append(screenshot_info)
# 写入元数据文件
metadata_path = "{screenshot_dir}/capture-metadata.json"
Write(metadata_path, JSON.stringify(metadata, null, 2))
REPORT: ""
REPORT: "📁 Output:"
REPORT: " Directory: {screenshot_dir}/"
REPORT: " Metadata: capture-metadata.json"
TodoWrite(mark_completed: "Verify and summarize results")
Write(f"{base_path}/screenshots/capture-metadata.json", JSON.stringify(metadata))
```
### Phase 4: 完成
**Output**: `capture-metadata.json`
## Completion
### Todo Update
```javascript
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: "MCP batch screenshot capture", status: "completed", activeForm: "MCP capture"},
{content: "Local tool fallback (if needed)", status: "completed", activeForm: "Local fallback"},
{content: "Verify and summarize results", status: "completed", activeForm: "Verifying"}
]});
{content: "Parse url-map", status: "completed", activeForm: "Parsing"},
{content: "Detect MCP tools", status: "completed", activeForm: "Detecting"},
{content: "Capture screenshots", status: "completed", activeForm: "Capturing"},
{content: "Verify results", status: "completed", activeForm: "Verifying"}
]})
```
**Completion Message**:
### Output Message
```
✅ Batch Screenshot Capture Complete!
✅ Batch screenshot capture complete!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 Capture Summary
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Summary:
- Requested: {total_requested}
- Captured: {total_captured}
- Success rate: {success_rate}%
- Method: {tool || "Local fallback"}
Requested: {total_requested} screenshots
Captured: {total_captured} screenshots
Success Rate: {success_rate}%
Capture Methods:
{IF mcp_available AND mcp_success_count > 0:
• MCP: {mcp_success_count} screenshot(s)
}
{IF local_success_count > 0:
• Local tools: {local_success_count} screenshot(s)
}
{IF manual_count > 0:
• Manual upload: {manual_count} screenshot(s)
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📂 Output Structure
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
{screenshot_dir}/
├── {target1}.png ({size1} KB)
├── {target2}.png ({size2} KB)
{FOR each captured screenshot}
Output:
{base_path}/screenshots/
├── home.png (245.3 KB)
├── pricing.png (198.7 KB)
└── capture-metadata.json
{IF missing_targets:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ Missing Screenshots ({len(missing_targets)})
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
{FOR target IN missing_targets:
• {target} - {get_error_for_target(target)}
}
💡 Tip: Re-run capture command for failed targets:
/workflow:ui-design:capture --base-path "{base_path}" --url-map "{build_failed_url_map()}"
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 Next Steps
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Extract design style from captured screenshots:
/workflow:ui-design:extract --base-path "{base_path}" --images "{screenshot_dir}/*.png" --mode imitate --variants 1
2. Or continue with full imitate workflow:
(capture is automatically called by /workflow:ui-design:imitate-auto-v3)
Next: /workflow:ui-design:extract --images "screenshots/*.png"
```
## MCP API设计假设实现
## Simple Bash Commands
```typescript
// 假设的MCP工具签名
mcp__browser__screenshot({
urls: string[], // 要截图的URL列表
output_dir: string, // 输出目录
file_prefix: string[], // 文件名前缀列表对应urls
full_page?: boolean, // 全页截图默认true
viewport?: string, // 视口大小(默认"1920,1080"
timeout?: number // 每个URL的超时默认30000ms
}): {
success: Array<{
target: string, // file_prefix对应的target名称
url: string, // 成功截图的URL
path: string // 生成的截图文件路径
}>,
failed: Array<{
target: string, // file_prefix对应的target名称
url: string, // 失败的URL
error: string // 错误信息
}>
}
### Path Operations
```bash
# Find design directory
bash(find .workflow -type d -name "design-*" | head -1)
# Create screenshot directory
bash(mkdir -p $BASE_PATH/screenshots)
```
**注意事项**
- 如果`mcp__browser__screenshot`工具不存在,命令会自动降级到本地工具
- MCP工具应该支持并行截图以提高性能
- 返回结果应该区分成功和失败,允许部分失败
### Tool Detection
```bash
# Check MCP
all_resources = ListMcpResourcesTool()
# Check local tools
bash(which playwright 2>/dev/null)
bash(which google-chrome 2>/dev/null)
```
### Verification
```bash
# List captures
bash(ls -1 $base_path/screenshots/*.png 2>/dev/null)
# File sizes
bash(du -h $base_path/screenshots/*.png)
```
## Output Structure
```
{base_path}/
└── screenshots/
├── home.png
├── pricing.png
├── about.png
└── capture-metadata.json
```
## Error Handling
- **无效url-map格式**:清晰的错误信息+格式示例
- **MCP不可用**静默降级到本地工具Playwright/Chrome
- **所有自动工具失败**:进入交互式手动上传模式
- **部分失败**:记录成功项,继续流程(非阻塞),提供重试建议
### Common Errors
```
ERROR: Invalid url-map format
→ Use: "target:url, target2:url2"
ERROR: MCP unavailable
→ Using local fallback
ERROR: All tools failed
→ Manual mode activated
```
### Recovery
- **Partial success**: Keep successful captures
- **Retry**: Re-run with failed targets only
- **Manual**: Follow interactive guidance
## Quality Checklist
- [ ] All requested URLs processed
- [ ] File sizes > 1KB (valid images)
- [ ] Metadata JSON generated
- [ ] No missing targets (or documented)
## Key Features
1. **MCP优先策略** - 使用托管工具提高可靠性和一致性
2. **多级降级机制** - MCP → Playwright → Chrome → 手动上传
3. **批量并行处理** - 一次处理多个URLMCP支持并行
4. **错误容忍设计** - 部分失败不阻塞整体流程
5. **高度可复用** - 可被imitate-auto-v3、explore-auto等工作流调用
6. **结构化输出** - capture-metadata.json记录完整捕获信息
7. **交互式降级** - 手动模式提供清晰的用户指导
8. **智能路径管理** - 支持session集成和standalone模式
- **MCP-first**: Prioritize managed tools
- **Multi-tier fallback**: 4 layers (MCP → Local → Manual)
- **Batch processing**: Parallel capture
- **Error tolerance**: Partial failures handled
- **Structured output**: Flat, predictable
## Integration Points
## Integration
- **Input**: `--url-map` (target:url pairs) + `--base-path` or `--session`
- **Output**: `{base_path}/screenshots/*.png` + `capture-metadata.json`
- **Callers**: `/workflow:ui-design:imitate-auto-v3`, potentially `/workflow:ui-design:explore-auto-v2`
- **Next Command**: `/workflow:ui-design:extract --images "{screenshot_dir}/*.png"`
**Input**: `--url-map` (multiple target:url pairs)
**Output**: `screenshots/*.png` + `capture-metadata.json`
**Called by**: `/workflow:ui-design:imitate-auto`, `/workflow:ui-design:explore-auto`
**Next**: `/workflow:ui-design:extract` or `/workflow:ui-design:explore-layers`

View File

@@ -1,390 +0,0 @@
---
name: explore-auto-v2
description: Exploratory UI design workflow with style-centric batch generation
usage: /workflow:ui-design:explore-auto-v2 [--prompt "<desc>"] [--images "<glob>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
examples:
- /workflow:ui-design:explore-auto-v2 --prompt "Generate 3 style variants for modern blog: home, article, author"
- /workflow:ui-design:explore-auto-v2 --prompt "SaaS dashboard and settings with 2 layout options"
- /workflow:ui-design:explore-auto-v2 --images "refs/*.png" --prompt "E-commerce: home, product, cart" --style-variants 3 --layout-variants 3
- /workflow:ui-design:explore-auto-v2 --session WFS-auth --images "refs/*.png"
- /workflow:ui-design:explore-auto-v2 --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
---
# UI Design Auto Workflow Command
## Overview & Execution Model
**Fully autonomous orchestrator**: Executes all design phases sequentially from style extraction to design integration, with optional batch planning.
**Unified Target System**: Generates `style_variants × layout_variants × targets` prototypes, where targets can be:
- **Pages** (full-page layouts): home, dashboard, settings, etc.
- **Components** (isolated UI elements): navbar, card, hero, form, etc.
- **Mixed**: Can combine both in a single workflow
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:explore-auto-v2 [params]`
2. Phase 0c: Target confirmation → User confirms → **IMMEDIATELY triggers Phase 1**
3. Phase 1 (style-extract) → **WAIT for completion** → Auto-continues
4. Phase 2 (style-consolidate) → **WAIT for completion** → Auto-continues
5. **Phase 3 (ui-generate-v2)****WAIT for completion** → Auto-continues
6. Phase 4 (design-update) → **WAIT for completion** → Auto-continues
7. Phase 5 (batch-plan, optional) → Reports completion
**Phase Transition Mechanism**:
- **Phase 0c (User Interaction)**: User confirms targets → IMMEDIATELY triggers Phase 1
- **Phase 1-5 (Autonomous)**: `SlashCommand` is BLOCKING - execution pauses until completion
- Upon each phase completion: Automatically process output and execute next phase
- No additional user interaction after Phase 0c confirmation
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 4 (or Phase 5 if --batch-plan).
**Target Type Detection**: Automatically inferred from prompt/targets, or explicitly set via `--target-type`.
## Core Rules
1. **Start Immediately**: TodoWrite initialization → Phase 1 execution
2. **No Preliminary Validation**: Sub-commands handle their own validation
3. **Parse & Pass**: Extract data from each output for next phase
4. **Default to All**: When selecting variants/prototypes, use ALL generated items
5. **Track Progress**: Update TodoWrite after each phase
6. **⚠️ CRITICAL: DO NOT STOP** - This is a continuous multi-phase workflow. After each SlashCommand completes, you MUST wait for completion, then immediately execute the next phase. Workflow is NOT complete until Phase 4 (or Phase 5 if --batch-plan).
## Parameter Requirements
**Optional Parameters** (all have smart defaults):
- `--targets "<list>"`: Comma-separated targets (pages/components) to generate (inferred from prompt/session if omitted)
- `--target-type "page|component|auto"`: Explicitly set target type (default: `auto` - intelligent detection)
- `--session <id>`: Workflow session ID (standalone mode if omitted)
- `--images "<glob>"`: Reference image paths (default: `design-refs/*`)
- `--prompt "<description>"`: Design style and target description
- `--style-variants <count>`: Style variants (default: inferred from prompt or 3, range: 1-5)
- `--layout-variants <count>`: Layout variants per style (default: inferred or 3, range: 1-5)
- `--batch-plan`: Auto-generate implementation tasks after design-update
**Legacy Parameters** (maintained for backward compatibility):
- `--pages "<list>"`: Alias for `--targets` with `--target-type page`
- `--components "<list>"`: Alias for `--targets` with `--target-type component`
**Input Rules**:
- Must provide at least one: `--images` or `--prompt` or `--targets`
- Multiple parameters can be combined for guided analysis
- If `--targets` not provided, intelligently inferred from prompt/session
**Supported Target Types**:
- **Pages** (full layouts): home, dashboard, settings, profile, login, etc.
- **Components** (UI elements):
- Navigation: navbar, header, menu, breadcrumb, tabs, sidebar
- Content: hero, card, list, table, grid, timeline
- Input: form, search, filter, input-group
- Feedback: modal, alert, toast, badge, progress
- Media: gallery, carousel, video-player, image-card
- Other: footer, pagination, dropdown, tooltip, avatar
**Intelligent Prompt Parsing**: Extracts variant counts from natural language:
- "Generate **3 style variants**" → `--style-variants 3`
- "**2 layout options**" → `--layout-variants 2`
- "Create **4 styles** with **2 layouts each**" → `--style-variants 4 --layout-variants 2`
- Explicit flags override prompt inference
## Execution Modes
**Matrix Mode** (style-centric):
- Generates `style_variants × layout_variants × targets` prototypes
- **Phase 1**: `style_variants` style options with design_attributes (extract)
- **Phase 2**: `style_variants` independent design systems (consolidate)
- **Phase 3**: Style-centric batch generation (generate-v2)
- Sub-phase 1: `targets × layout_variants` target-specific layout plans
- **Sub-phase 2**: `S` style-centric agents (each handles `L×T` combinations)
- Sub-phase 3: `style_variants × layout_variants × targets` final prototypes
- Performance: Efficient parallel execution with S agents
- Quality: HTML structure adapts to design_attributes
- Pages: Full-page layouts with complete structure
- Components: Isolated elements with minimal wrapper
**Integrated vs. Standalone**:
- `--session` flag determines session integration or standalone execution
## 6-Phase Execution
### Phase 0a: Intelligent Prompt Parsing
```bash
# Parse variant counts from prompt or use explicit/default values
IF --prompt AND (NOT --style-variants OR NOT --layout-variants):
style_variants = regex_extract(prompt, r"(\d+)\s*style") OR --style-variants OR 3
layout_variants = regex_extract(prompt, r"(\d+)\s*layout") OR --layout-variants OR 3
ELSE:
style_variants = --style-variants OR 3
layout_variants = --layout-variants OR 3
VALIDATE: 1 <= style_variants <= 5, 1 <= layout_variants <= 5
```
### Phase 0b: Run Initialization & Directory Setup
```bash
run_id = "run-$(date +%Y%m%d-%H%M%S)"
base_path = --session ? ".workflow/WFS-{session}/design-${run_id}" : ".workflow/.design/${run_id}"
Bash(mkdir -p "${base_path}/{style-extraction,style-consolidation,prototypes}")
Write({base_path}/.run-metadata.json): {
"run_id": "${run_id}", "session_id": "${session_id}", "timestamp": "...",
"workflow": "ui-design:auto-v2",
"version": "2.0",
"architecture": "style-centric-batch-generation",
"parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants},
"targets": "${inferred_target_list}", "target_type": "${target_type}",
"prompt": "${prompt_text}", "images": "${images_pattern}" },
"status": "in_progress",
"performance_mode": "optimized"
}
```
### Phase 0c: Unified Target Inference with Intelligent Type Detection
```bash
# Priority: --pages/--components (legacy) → --targets → --prompt analysis → synthesis → default
target_list = []; target_type = "auto"; target_source = "none"
# Step 1-2: Explicit parameters (legacy or unified)
IF --pages: target_list = split(--pages); target_type = "page"; target_source = "explicit_legacy"
ELSE IF --components: target_list = split(--components); target_type = "component"; target_source = "explicit_legacy"
ELSE IF --targets:
target_list = split(--targets); target_source = "explicit"
target_type = --target-type != "auto" ? --target-type : detect_target_type(target_list)
# Step 3: Prompt analysis (Claude internal analysis)
ELSE IF --prompt:
analysis_result = analyze_prompt("{prompt_text}") # Extract targets, types, purpose
target_list = analysis_result.targets
target_type = analysis_result.primary_type OR detect_target_type(target_list)
target_source = "prompt_analysis"
# Step 4: Session synthesis
ELSE IF --session AND exists(synthesis-specification.md):
target_list = extract_targets_from_synthesis(); target_type = "page"; target_source = "synthesis"
# Step 5: Fallback
IF NOT target_list: target_list = ["home"]; target_type = "page"; target_source = "default"
# Validate and clean
validated_targets = [normalize(t) for t in target_list if is_valid(t)]
IF NOT validated_targets: validated_targets = ["home"]; target_type = "page"
IF --target-type != "auto": target_type = --target-type
# Interactive confirmation
DISPLAY_CONFIRMATION(target_type, target_source, validated_targets):
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"{emoji} {LABEL} CONFIRMATION (v2.0 Style-Centric)"
"Type: {target_type} | Source: {target_source}"
"Targets ({count}): {', '.join(validated_targets)}"
"Performance: {style_variants} agent calls (vs {layout_variants * len(validated_targets)} in v1.0)"
"Options: 'continue/yes' | 'targets: a,b' | 'skip: x' | 'add: y' | 'type: page|component'"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_input = WAIT_FOR_USER_INPUT()
# Process user modifications
MATCH user_input:
"continue|yes|ok" → proceed
"targets: ..."validated_targets = parse_new_list()
"skip: ..."validated_targets = remove_items()
"add: ..."validated_targets = add_items()
"type: ..."target_type = extract_type()
default → proceed with current list
STORE: inferred_target_list, target_type, target_inference_source
# ⚠️ CRITICAL: User confirmation complete, IMMEDIATELY initialize TodoWrite and execute Phase 1
# This is the only user interaction point in the workflow
# After this point, all subsequent phases execute automatically without user intervention
```
**Helper Function: detect_target_type()**
```bash
detect_target_type(target_list):
page_keywords = ["home", "dashboard", "settings", "profile", "login", "signup", "auth", ...]
component_keywords = ["navbar", "header", "footer", "hero", "card", "button", "form", ...]
page_matches = count_matches(target_list, page_keywords + ["page", "screen", "view"])
component_matches = count_matches(target_list, component_keywords + ["component", "widget"])
RETURN "component" IF component_matches > page_matches ELSE "page"
```
### Phase 1: Style Extraction
```bash
command = "/workflow:ui-design:extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
"--variants {style_variants} --mode explore"
SlashCommand(command)
# Output: {style_variants} style cards with design_attributes
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 2 (auto-continue)
```
### Phase 2: Style Consolidation
```bash
command = "/workflow:ui-design:consolidate --base-path \"{base_path}\" " +
"--variants {style_variants}"
SlashCommand(command)
# Output: {style_variants} independent design systems with tokens.css
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 3 (auto-continue)
```
### Phase 3: Style-Centric Matrix UI Generation
```bash
targets_string = ",".join(inferred_target_list)
command = "/workflow:ui-design:generate-v2 --base-path \"{base_path}\" " +
"--targets \"{targets_string}\" --target-type \"{target_type}\" " +
"--style-variants {style_variants} --layout-variants {layout_variants}"
total = style_variants × layout_variants × len(inferred_target_list)
agent_calls = style_variants
REPORT: "🚀 Phase 3: {type_icon} {targets_string} | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: " → Agent calls: {agent_calls} style-centric agents"
REPORT: " → Layout planning: {len(inferred_target_list)}×{layout_variants} target-specific layouts"
REPORT: " → Style-centric generation: Each of {style_variants} agents handles {layout_variants}×{len(inferred_target_list)} combinations"
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 4 (auto-continue)
# Output:
# - {target}-layout-{l}.json (target-specific layout plans)
# - {target}-style-{s}-layout-{l}.html (final prototypes with style-aware structure)
# - compare.html (interactive matrix view)
# - PREVIEW.md (usage instructions)
```
### Phase 4: Design System Integration
```bash
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
SlashCommand(command)
# SlashCommand blocks until phase complete
# Upon completion:
# - If --batch-plan flag present: IMMEDIATELY execute Phase 5 (auto-continue)
# - If no --batch-plan: Workflow complete, display final report
```
### Phase 5: Batch Task Generation (Optional)
```bash
IF --batch-plan:
FOR target IN inferred_target_list:
task_desc = "Implement {target} {target_type} based on design system"
SlashCommand("/workflow:plan --agent \"{task_desc}\"")
```
## TodoWrite Pattern
```javascript
// Initialize IMMEDIATELY after Phase 0c user confirmation to track multi-phase execution
TodoWrite({todos: [
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing..."},
{"content": "Execute style consolidation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute style-centric UI generation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing..."}
]})
// ⚠️ CRITICAL: After EACH SlashCommand completion (Phase 1-5), you MUST:
// 1. SlashCommand blocks and returns when phase is complete
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase SlashCommand (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
```
## Key Features
- **🚀 Performance**: Style-centric batch generation with S agent calls
- **🎨 Style-Aware**: HTML structure adapts to design_attributes
- **✅ Perfect Consistency**: Each style by single agent
- **📦 Autonomous**: No user intervention required between phases
- **🧠 Intelligent**: Parses natural language, infers targets/types
- **🔄 Reproducible**: Deterministic flow with isolated run directories
- **🎯 Flexible**: Supports pages, components, or mixed targets
## Examples
### 1. Page Mode (Prompt Inference)
```bash
/workflow:ui-design:explore-auto-v2 --prompt "Modern blog: home, article, author"
# Result: 27 prototypes (3×3×3)
```
### 2. Custom Matrix with Session
```bash
/workflow:ui-design:explore-auto-v2 --session WFS-ecommerce --images "refs/*.png" --style-variants 2 --layout-variants 2
# Result: 2×2×N prototypes
```
### 3. Component Mode
```bash
/workflow:ui-design:explore-auto-v2 --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
# Result: 12 prototypes (3×2×2) - components with minimal wrapper
```
### 4. Intelligent Parsing + Batch Planning
```bash
/workflow:ui-design:explore-auto-v2 --prompt "Create 4 styles with 2 layouts for dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated tasks
```
### 5. Large Scale
```bash
/workflow:ui-design:explore-auto-v2 --targets "home,dashboard,settings,profile" --style-variants 3 --layout-variants 3
# Result: 36 prototypes (3×3×4)
```
## Completion Output
```
✅ UI Design Explore-Auto Workflow Complete!
Architecture: Style-Centric Batch Generation
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} style variants with design_attributes (extract)
Phase 2: {s} design systems with tokens.css (consolidate)
Phase 3: Style-centric batch generation (generate-v2)
- {n}×{l} target-specific layout plans
- {s} style-centric agents (each handled {l}×{n} combinations)
- {s}×{l}×{n} = {total} final prototypes with style-aware structure
Phase 4: Brainstorming artifacts updated
[Phase 5: {n} implementation tasks created] # if --batch-plan
Agent Execution:
✅ Style-centric agents: {s} agents total
✅ Each agent handles: {l}×{n} combinations
Design Quality:
✅ Style-Aware Structure: HTML adapts to design_attributes
✅ Style Consistency: PERFECT (each style by single agent)
✅ Token-Driven Styling: 100% var() usage
📂 {base_path}/
├── style-extraction/ ({s} style cards + design-space-analysis.json)
├── style-consolidation/ ({s} design systems with tokens.css)
├── prototypes/
│ ├── _templates/ ({n}×{l} layout JSON files)
│ └── ... ({total} final prototypes)
└── .run-metadata.json
🌐 Preview: {base_path}/prototypes/compare.html
- Interactive {s}×{l} matrix view
- Side-by-side comparison
- Target-specific layouts with style-aware structure
- Toggle between {n} targets
{icon} Targets: {', '.join(targets)} (type: {target_type})
- Each target has {l} custom-designed layouts
- Each style × target × layout has unique HTML structure (not just CSS!)
- Layout plans stored as structured JSON
Next: [/workflow:execute] OR [Open compare.html → Select → /workflow:plan]
```

View File

@@ -1,15 +1,13 @@
---
name: explore-auto
description: Exploratory UI design workflow - Generate and compare multiple style × layout combinations (3×3 matrix exploration)
description: Exploratory UI design workflow with style-centric batch generation
usage: /workflow:ui-design:explore-auto [--prompt "<desc>"] [--images "<glob>"] [--targets "<list>"] [--target-type "page|component"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
examples:
- /workflow:ui-design:explore-auto --prompt "Generate 3 style variants for modern blog: home, article, author"
- /workflow:ui-design:explore-auto --prompt "SaaS dashboard and settings with 2 layout options"
- /workflow:ui-design:explore-auto --images "refs/*.png" --prompt "E-commerce: home, product, cart" --style-variants 3 --layout-variants 3
- /workflow:ui-design:explore-auto --session WFS-auth --images "refs/*.png"
- /workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --prompt "Compare 3 navigation bar designs" --style-variants 3 --layout-variants 2
- /workflow:ui-design:explore-auto --targets "card,form,button" --images "refs/*.png" --style-variants 2 --layout-variants 3
- /workflow:ui-design:explore-auto --targets "home,dashboard" --target-type "page"
- /workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
---
@@ -26,11 +24,18 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
**Autonomous Flow** (⚠️ CONTINUOUS EXECUTION - DO NOT STOP):
1. User triggers: `/workflow:ui-design:explore-auto [params]`
2. Phase 1 (style-extract) → **WAIT for completion** → Auto-continues
3. Phase 2 (style-consolidate) → **WAIT for completion** → Auto-continues
4. Phase 3 (ui-generate) → **WAIT for completion** → Auto-continues with unified target list
5. Phase 4 (design-update)**WAIT for completion** → Auto-continues
6. Phase 5 (batch-plan, optional) → Reports completion
2. Phase 0c: Target confirmation → User confirms → **IMMEDIATELY triggers Phase 1**
3. Phase 1 (style-extract) → **WAIT for completion** → Auto-continues
4. Phase 2 (style-consolidate) → **WAIT for completion** → Auto-continues
5. **Phase 3 (ui-generate)****WAIT for completion** → Auto-continues
6. Phase 4 (design-update) → **WAIT for completion** → Auto-continues
7. Phase 5 (batch-plan, optional) → Reports completion
**Phase Transition Mechanism**:
- **Phase 0c (User Interaction)**: User confirms targets → IMMEDIATELY triggers Phase 1
- **Phase 1-5 (Autonomous)**: `SlashCommand` is BLOCKING - execution pauses until completion
- Upon each phase completion: Automatically process output and execute next phase
- No additional user interaction after Phase 0c confirmation
**Auto-Continue Mechanism**: TodoWrite tracks phase status. Upon each phase completion, you MUST immediately construct and execute the next phase command. No user intervention required. The workflow is NOT complete until reaching Phase 4 (or Phase 5 if --batch-plan).
@@ -50,6 +55,11 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
**Optional Parameters** (all have smart defaults):
- `--targets "<list>"`: Comma-separated targets (pages/components) to generate (inferred from prompt/session if omitted)
- `--target-type "page|component|auto"`: Explicitly set target type (default: `auto` - intelligent detection)
- `--device-type "desktop|mobile|tablet|responsive|auto"`: Device type for layout optimization (default: `auto` - intelligent detection)
- **Desktop**: 1920×1080px - Mouse-driven, spacious layouts
- **Mobile**: 375×812px - Touch-friendly, compact layouts
- **Tablet**: 768×1024px - Hybrid touch/mouse layouts
- **Responsive**: 1920×1080px base with mobile-first breakpoints
- `--session <id>`: Workflow session ID (standalone mode if omitted)
- `--images "<glob>"`: Reference image paths (default: `design-refs/*`)
- `--prompt "<description>"`: Design style and target description
@@ -84,17 +94,18 @@ allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*
## Execution Modes
**Matrix Mode** (unified):
**Matrix Mode** (style-centric):
- Generates `style_variants × layout_variants × targets` prototypes
- **Phase 1**: `style_variants` style options (extract)
- **Phase 1**: `style_variants` style options with design_attributes (extract)
- **Phase 2**: `style_variants` independent design systems (consolidate)
- **Phase 3**: Layout planning + UI generation (generate)
- **Phase 3**: Style-centric batch generation (generate)
- Sub-phase 1: `targets × layout_variants` target-specific layout plans
- Sub-phase 2: `layout_variants × targets` HTML/CSS templates
- **Sub-phase 2**: `S` style-centric agents (each handles `L×T` combinations)
- Sub-phase 3: `style_variants × layout_variants × targets` final prototypes
- Performance: Efficient parallel execution with S agents
- Quality: HTML structure adapts to design_attributes
- Pages: Full-page layouts with complete structure
- Components: Isolated elements with minimal wrapper
- Mixed: Combination based on intelligent detection
**Integrated vs. Standalone**:
- `--session` flag determines session integration or standalone execution
@@ -114,6 +125,51 @@ ELSE:
VALIDATE: 1 <= style_variants <= 5, 1 <= layout_variants <= 5
```
### Phase 0a-2: Device Type Inference
```bash
# Device type inference
device_type = "auto"
# Step 1: Explicit parameter (highest priority)
IF --device-type AND --device-type != "auto":
device_type = --device-type
device_source = "explicit"
ELSE:
# Step 2: Prompt analysis
IF --prompt:
device_keywords = {
"desktop": ["desktop", "web", "laptop", "widescreen", "large screen"],
"mobile": ["mobile", "phone", "smartphone", "ios", "android"],
"tablet": ["tablet", "ipad", "medium screen"],
"responsive": ["responsive", "adaptive", "multi-device", "cross-platform"]
}
detected_device = detect_device_from_prompt(--prompt, device_keywords)
IF detected_device:
device_type = detected_device
device_source = "prompt_inference"
# Step 3: Target type inference
IF device_type == "auto":
# Components are typically desktop-first, pages can vary
device_type = target_type == "component" ? "desktop" : "responsive"
device_source = "target_type_inference"
STORE: device_type, device_source
```
**Device Type Presets**:
- **Desktop**: 1920×1080px - Mouse-driven, spacious layouts
- **Mobile**: 375×812px - Touch-friendly, compact layouts
- **Tablet**: 768×1024px - Hybrid touch/mouse layouts
- **Responsive**: 1920×1080px base with mobile-first breakpoints
**Detection Keywords**:
- Prompt contains "mobile", "phone", "smartphone" → mobile
- Prompt contains "tablet", "ipad" → tablet
- Prompt contains "desktop", "web", "laptop" → desktop
- Prompt contains "responsive", "adaptive" → responsive
- Otherwise: Inferred from target type (components→desktop, pages→responsive)
### Phase 0b: Run Initialization & Directory Setup
```bash
run_id = "run-$(date +%Y%m%d-%H%M%S)"
@@ -124,10 +180,13 @@ Bash(mkdir -p "${base_path}/{style-extraction,style-consolidation,prototypes}")
Write({base_path}/.run-metadata.json): {
"run_id": "${run_id}", "session_id": "${session_id}", "timestamp": "...",
"workflow": "ui-design:auto",
"architecture": "style-centric-batch-generation",
"parameters": { "style_variants": ${style_variants}, "layout_variants": ${layout_variants},
"targets": "${inferred_target_list}", "target_type": "${target_type}",
"prompt": "${prompt_text}", "images": "${images_pattern}" },
"status": "in_progress"
"prompt": "${prompt_text}", "images": "${images_pattern}",
"device_type": "${device_type}", "device_source": "${device_source}" },
"status": "in_progress",
"performance_mode": "optimized"
}
```
@@ -163,13 +222,24 @@ IF NOT validated_targets: validated_targets = ["home"]; target_type = "page"
IF --target-type != "auto": target_type = --target-type
# Interactive confirmation
DISPLAY_CONFIRMATION(target_type, target_source, validated_targets):
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"{emoji} {LABEL} CONFIRMATION"
DISPLAY_CONFIRMATION(target_type, target_source, validated_targets, device_type, device_source):
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"{emoji} {LABEL} CONFIRMATION (Style-Centric)"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"Type: {target_type} | Source: {target_source}"
"Targets ({count}): {', '.join(validated_targets)}"
"Options: 'continue/yes' | 'targets: a,b' | 'skip: x' | 'add: y' | 'type: page|component'"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"Device: {device_type} | Source: {device_source}"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"Performance: {style_variants} agent calls"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
"Modification Options:"
" • 'continue/yes/ok' - Proceed with current configuration"
" • 'targets: a,b,c' - Replace target list"
" • 'skip: x,y' - Remove specific targets"
" • 'add: z' - Add new targets"
" • 'type: page|component' - Change target type"
" • 'device: desktop|mobile|tablet|responsive' - Change device type"
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
user_input = WAIT_FOR_USER_INPUT()
@@ -180,9 +250,14 @@ MATCH user_input:
"skip: ..."validated_targets = remove_items()
"add: ..."validated_targets = add_items()
"type: ..."target_type = extract_type()
"device: ..."device_type = extract_device()
default → proceed with current list
STORE: inferred_target_list, target_type, target_inference_source
# ⚠️ CRITICAL: User confirmation complete, IMMEDIATELY initialize TodoWrite and execute Phase 1
# This is the only user interaction point in the workflow
# After this point, all subsequent phases execute automatically without user intervention
```
**Helper Function: detect_target_type()**
@@ -202,11 +277,12 @@ detect_target_type(target_list):
command = "/workflow:ui-design:extract --base-path \"{base_path}\" " +
(--images ? "--images \"{images}\" " : "") +
(--prompt ? "--prompt \"{prompt}\" " : "") +
"--variants {style_variants} --mode explore"
"--mode explore --variants {style_variants}"
SlashCommand(command)
# WAIT for extract command to complete, then IMMEDIATELY continue to Phase 2
# DO NOT STOP - Phase 2 must execute automatically
# Output: {style_variants} style cards with design_attributes
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 2 (auto-continue)
```
### Phase 2: Style Consolidation
@@ -215,30 +291,37 @@ command = "/workflow:ui-design:consolidate --base-path \"{base_path}\" " +
"--variants {style_variants}"
SlashCommand(command)
# WAIT for consolidate command to complete, then IMMEDIATELY continue to Phase 3
# DO NOT STOP - Phase 3 must execute automatically
# Output: style_variants independent design systems (design tokens and style guides)
# Output: {style_variants} independent design systems with tokens.css
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 3 (auto-continue)
```
### Phase 3: Matrix UI Generation (with Layout Planning)
### Phase 3: Style-Centric Matrix UI Generation
```bash
targets_string = ",".join(inferred_target_list)
command = "/workflow:ui-design:generate --base-path \"{base_path}\" " +
"--targets \"{targets_string}\" --target-type \"{target_type}\" " +
"--style-variants {style_variants} --layout-variants {layout_variants}"
"--style-variants {style_variants} --layout-variants {layout_variants} " +
"--device-type \"{device_type}\""
total = style_variants × layout_variants × len(inferred_target_list)
agent_calls = style_variants
REPORT: "🚀 Phase 3: {type_icon} {targets_string} | Matrix: {s}×{l}×{n} = {total} prototypes"
REPORT: " → Device: {device_type}"
REPORT: " → Agent calls: {agent_calls} style-centric agents"
REPORT: " → Layout planning: {len(inferred_target_list)}×{layout_variants} target-specific layouts"
REPORT: " → Style-centric generation: Each of {style_variants} agents handles {layout_variants}×{len(inferred_target_list)} combinations"
SlashCommand(command)
# WAIT for generate command to complete, then IMMEDIATELY continue to Phase 4
# DO NOT STOP - Phase 4 must execute automatically
# SlashCommand blocks until phase complete
# Upon completion, IMMEDIATELY execute Phase 4 (auto-continue)
# Output:
# - {target}-layout-{l}.json (target-specific layout plans)
# - {target}-style-{s}-layout-{l}.html (final prototypes)
# - compare.html (matrix view)
# - {target}-style-{s}-layout-{l}.html (final prototypes with style-aware structure)
# - compare.html (interactive matrix view)
# - PREVIEW.md (usage instructions)
```
### Phase 4: Design System Integration
@@ -246,9 +329,10 @@ SlashCommand(command)
command = "/workflow:ui-design:update" + (--session ? " --session {session_id}" : "")
SlashCommand(command)
# WAIT for update command to complete
# If --batch-plan flag present: IMMEDIATELY continue to Phase 5
# If no --batch-plan: Workflow complete, display final report
# SlashCommand blocks until phase complete
# Upon completion:
# - If --batch-plan flag present: IMMEDIATELY execute Phase 5 (auto-continue)
# - If no --batch-plan: Workflow complete, display final report
```
### Phase 5: Batch Task Generation (Optional)
@@ -261,90 +345,131 @@ IF --batch-plan:
## TodoWrite Pattern
```javascript
// Initialize at workflow start to track multi-phase execution
// Initialize IMMEDIATELY after Phase 0c user confirmation to track multi-phase execution
TodoWrite({todos: [
{"content": "Execute style extraction", "status": "in_progress", "activeForm": "Executing..."},
{"content": "Execute style consolidation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute UI generation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute style-centric UI generation", "status": "pending", "activeForm": "Executing..."},
{"content": "Execute design integration", "status": "pending", "activeForm": "Executing..."}
]})
// ⚠️ CRITICAL: After EACH phase completion, you MUST:
// 1. Update current phase: status → "completed"
// 2. Update next phase: status → "in_progress"
// 3. Continue to execute next phase immediately
// ⚠️ CRITICAL: After EACH SlashCommand completion (Phase 1-5), you MUST:
// 1. SlashCommand blocks and returns when phase is complete
// 2. Update current phase: status → "completed"
// 3. Update next phase: status → "in_progress"
// 4. IMMEDIATELY execute next phase SlashCommand (auto-continue)
// This ensures continuous workflow tracking and prevents premature stopping
```
## Key Features
- **Autonomous**: No user intervention required between phases
- **Intelligent**: Parses natural language, infers targets/types
- **Reproducible**: Deterministic flow with isolated run directories
- **Flexible**: Supports pages, components, or mixed targets
- **🚀 Performance**: Style-centric batch generation with S agent calls
- **🎨 Style-Aware**: HTML structure adapts to design_attributes
- **✅ Perfect Consistency**: Each style by single agent
- **📦 Autonomous**: No user intervention required between phases
- **🧠 Intelligent**: Parses natural language, infers targets/types
- **🔄 Reproducible**: Deterministic flow with isolated run directories
- **🎯 Flexible**: Supports pages, components, or mixed targets
## Examples
### 1. Page Mode (Prompt Inference)
```bash
/workflow:ui-design:explore-auto --prompt "Modern blog: home, article, author"
# Result: 27 prototypes (3×3×3 - inferred defaults)
# Result: 27 prototypes (3×3×3) - responsive layouts (default)
```
### 2. Custom Matrix with Session
### 2. Mobile-First Design
```bash
/workflow:ui-design:explore-auto --prompt "Mobile shopping app: home, product, cart" --device-type mobile
# Result: 27 prototypes (3×3×3) - mobile layouts (375×812px)
```
### 3. Desktop Application
```bash
/workflow:ui-design:explore-auto --targets "dashboard,analytics,settings" --device-type desktop --style-variants 2 --layout-variants 2
# Result: 12 prototypes (2×2×3) - desktop layouts (1920×1080px)
```
### 4. Tablet Interface
```bash
/workflow:ui-design:explore-auto --prompt "Educational app for tablets" --device-type tablet --targets "courses,lessons,profile"
# Result: 27 prototypes (3×3×3) - tablet layouts (768×1024px)
```
### 5. Custom Matrix with Session
```bash
/workflow:ui-design:explore-auto --session WFS-ecommerce --images "refs/*.png" --style-variants 2 --layout-variants 2
# Result: 2×2×N prototypes (targets from synthesis)
# Result: 2×2×N prototypes - device type inferred from session
```
### 3. Component Mode
### 6. Component Mode (Desktop)
```bash
/workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --style-variants 3 --layout-variants 2
# Result: 12 prototypes (3×2×2 components with minimal wrapper)
/workflow:ui-design:explore-auto --targets "navbar,hero" --target-type "component" --device-type desktop --style-variants 3 --layout-variants 2
# Result: 12 prototypes (3×2×2) - desktop components
```
### 4. Intelligent Parsing + Batch Planning
### 7. Intelligent Parsing + Batch Planning
```bash
/workflow:ui-design:explore-auto --prompt "Create 4 styles with 2 layouts for dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated implementation tasks
/workflow:ui-design:explore-auto --prompt "Create 4 styles with 2 layouts for mobile dashboard and settings" --batch-plan
# Result: 16 prototypes (4×2×2) + auto-generated tasks - mobile-optimized (inferred from prompt)
```
### 5. Legacy Support
### 8. Large Scale Responsive
```bash
/workflow:ui-design:explore-auto --pages "home,dashboard,settings"
# Equivalent to: --targets "home,dashboard,settings" --target-type "page"
/workflow:ui-design:explore-auto --targets "home,dashboard,settings,profile" --device-type responsive --style-variants 3 --layout-variants 3
# Result: 36 prototypes (3×3×4) - responsive layouts
```
## Completion Output
```
✅ UI Design Explore-Auto Workflow Complete!
Architecture: Style-Centric Batch Generation
Run ID: {run_id} | Session: {session_id or "standalone"}
Type: {icon} {target_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Type: {icon} {target_type} | Device: {device_type} | Matrix: {s}×{l}×{n} = {total} prototypes
Phase 1: {s} style variants (extract)
Phase 2: {s} design systems (consolidate)
Phase 3: Layout planning + generation (generate)
Phase 1: {s} style variants with design_attributes (extract)
Phase 2: {s} design systems with tokens.css (consolidate)
Phase 3: Style-centric batch generation (generate)
- Device: {device_type} layouts
- {n}×{l} target-specific layout plans
- {l}×{n} HTML/CSS templates
- {s}×{l}×{n} = {total} final prototypes
- {s} style-centric agents (each handled {l}×{n} combinations)
- {s}×{l}×{n} = {total} final prototypes with style-aware structure
Phase 4: Brainstorming artifacts updated
[Phase 5: {n} implementation tasks created] # if --batch-plan
Agent Execution:
✅ Style-centric agents: {s} agents total
✅ Each agent handles: {l}×{n} combinations
✅ Device-optimized: {device_type} layouts
Design Quality:
✅ Style-Aware Structure: HTML adapts to design_attributes
✅ Style Consistency: PERFECT (each style by single agent)
✅ Token-Driven Styling: 100% var() usage
✅ Device-Optimized: Layouts designed for {device_type}
📂 {base_path}/
├── style-consolidation/ ({s} design systems)
├── style-extraction/ ({s} style cards + design-space-analysis.json)
├── style-consolidation/ ({s} design systems with tokens.css)
├── prototypes/
│ ├── _templates/ ({n}×{l} layout JSON + {l}×{n} HTML/CSS)
│ └── ... ({total} final prototypes)
└── .run-metadata.json
│ ├── _templates/ ({n}×{l} layout JSON files)
│ └── ... ({total} final prototypes)
└── .run-metadata.json (includes device type)
🌐 Preview: {base_path}/prototypes/compare.html
- Interactive {s}×{l} matrix view
- Side-by-side comparison
- Target-specific layouts per prototype
- Target-specific layouts with style-aware structure
- Toggle between {n} targets
{icon} Targets: {', '.join(targets)} (type: {target_type})
- Each target has {l} custom-designed layouts
- Each style × target × layout has unique HTML structure (not just CSS!)
- Layout plans stored as structured JSON
- Optimized for {device_type} viewing
Next: [/workflow:execute] OR [Open compare.html → Select → /workflow:plan]
```

View File

@@ -0,0 +1,594 @@
---
name: explore-layers
description: Interactive deep UI capture with depth-controlled layer exploration
usage: /workflow:ui-design:explore-layers --url <url> --depth <1-5> [--session <id>] [--base-path <path>]
argument-hint: --url <url> --depth <1-5> [--session id] [--base-path path]
examples:
- /workflow:ui-design:explore-layers --url "https://app.linear.app" --depth 3
- /workflow:ui-design:explore-layers --url "https://notion.so" --depth 2 --session WFS-notion-ui
- /workflow:ui-design:explore-layers --url "https://app.com/dashboard" --depth 4
allowed-tools: TodoWrite(*), Read(*), Write(*), Bash(*), Glob(*), mcp__chrome-devtools__*
---
# Interactive Layer Exploration (/workflow:ui-design:explore-layers)
## Overview
Single-URL depth-controlled interactive capture. Progressively explores UI layers from pages to Shadow DOM.
**Depth Levels**:
- `1` = Page (full-page screenshot)
- `2` = Elements (key components)
- `3` = Interactions (modals, dropdowns)
- `4` = Embedded (iframes, widgets)
- `5` = Shadow DOM (web components)
**Requirements**: Chrome DevTools MCP
## Phase 1: Setup & Validation
### Step 1: Parse Parameters
```javascript
url = params["--url"]
depth = int(params["--depth"])
// Validate URL
IF NOT url.startswith("http"):
url = f"https://{url}"
// Validate depth
IF depth NOT IN [1, 2, 3, 4, 5]:
ERROR: "Invalid depth: {depth}. Use 1-5"
EXIT 1
```
### Step 2: Determine Base Path
```bash
bash(if [ -n "$BASE_PATH" ]; then
echo "$BASE_PATH"
elif [ -n "$SESSION_ID" ]; then
find .workflow/WFS-$SESSION_ID/design-* -type d | head -1 || \
echo ".workflow/WFS-$SESSION_ID/design-layers-$(date +%Y%m%d-%H%M%S)"
else
echo ".workflow/.design/layers-$(date +%Y%m%d-%H%M%S)"
fi)
# Create depth directories
bash(for i in $(seq 1 $depth); do mkdir -p $BASE_PATH/screenshots/depth-$i; done)
```
**Output**: `url`, `depth`, `base_path`
### Step 3: Validate MCP Availability
```javascript
all_resources = ListMcpResourcesTool()
chrome_devtools = "chrome-devtools" IN [r.server for r in all_resources]
IF NOT chrome_devtools:
ERROR: "explore-layers requires Chrome DevTools MCP"
ERROR: "Install: npm i -g @modelcontextprotocol/server-chrome-devtools"
EXIT 1
```
### Step 4: Initialize Todos
```javascript
todos = [
{content: "Setup and validation", status: "completed", activeForm: "Setting up"}
]
FOR level IN range(1, depth + 1):
todos.append({
content: f"Depth {level}: {DEPTH_NAMES[level]}",
status: "pending",
activeForm: f"Capturing depth {level}"
})
todos.append({content: "Generate layer map", status: "pending", activeForm: "Mapping"})
TodoWrite({todos})
```
## Phase 2: Navigate & Load Page
### Step 1: Get or Create Browser Page
```javascript
pages = mcp__chrome-devtools__list_pages()
IF pages.length == 0:
mcp__chrome-devtools__new_page({url: url, timeout: 30000})
page_idx = 0
ELSE:
page_idx = 0
mcp__chrome-devtools__select_page({pageIdx: page_idx})
mcp__chrome-devtools__navigate_page({url: url, timeout: 30000})
bash(sleep 3) // Wait for page load
```
**Output**: `page_idx`
## Phase 3: Depth 1 - Page Level
### Step 1: Capture Full Page
```javascript
TodoWrite(mark_in_progress: "Depth 1: Page")
output_file = f"{base_path}/screenshots/depth-1/full-page.png"
mcp__chrome-devtools__take_screenshot({
fullPage: true,
format: "png",
quality: 90,
filePath: output_file
})
layer_map = {
"url": url,
"depth": depth,
"layers": {
"depth-1": {
"type": "page",
"captures": [{
"name": "full-page",
"path": output_file,
"size_kb": file_size_kb(output_file)
}]
}
}
}
TodoWrite(mark_completed: "Depth 1: Page")
```
**Output**: `depth-1/full-page.png`
## Phase 4: Depth 2 - Element Level (If depth >= 2)
### Step 1: Analyze Page Structure
```javascript
IF depth < 2: SKIP
TodoWrite(mark_in_progress: "Depth 2: Elements")
snapshot = mcp__chrome-devtools__take_snapshot()
// Filter key elements
key_types = ["nav", "header", "footer", "aside", "button", "form", "article"]
key_elements = [
el for el in snapshot.interactiveElements
if el.type IN key_types OR el.role IN ["navigation", "banner", "main"]
][:10] // Limit to top 10
```
### Step 2: Capture Element Screenshots
```javascript
depth_2_captures = []
FOR idx, element IN enumerate(key_elements):
element_name = sanitize(element.text[:20] or element.type) or f"element-{idx}"
output_file = f"{base_path}/screenshots/depth-2/{element_name}.png"
TRY:
mcp__chrome-devtools__take_screenshot({
uid: element.uid,
format: "png",
quality: 85,
filePath: output_file
})
depth_2_captures.append({
"name": element_name,
"type": element.type,
"path": output_file,
"size_kb": file_size_kb(output_file)
})
CATCH error:
REPORT: f"Skip {element_name}: {error}"
layer_map.layers["depth-2"] = {
"type": "elements",
"captures": depth_2_captures
}
TodoWrite(mark_completed: "Depth 2: Elements")
```
**Output**: `depth-2/{element}.png` × N
## Phase 5: Depth 3 - Interaction Level (If depth >= 3)
### Step 1: Analyze Interactive Triggers
```javascript
IF depth < 3: SKIP
TodoWrite(mark_in_progress: "Depth 3: Interactions")
// Detect structure
structure = mcp__chrome-devtools__evaluate_script({
function: `() => ({
modals: document.querySelectorAll('[role="dialog"], .modal').length,
dropdowns: document.querySelectorAll('[role="menu"], .dropdown').length,
tooltips: document.querySelectorAll('[role="tooltip"], [title]').length
})`
})
// Identify triggers
triggers = []
FOR element IN snapshot.interactiveElements:
IF element.attributes CONTAINS ("data-toggle", "aria-haspopup"):
triggers.append({
uid: element.uid,
type: "modal" IF "modal" IN element.classes ELSE "dropdown",
trigger: "click",
text: element.text
})
ELSE IF element.attributes CONTAINS ("title", "data-tooltip"):
triggers.append({
uid: element.uid,
type: "tooltip",
trigger: "hover",
text: element.text
})
triggers = triggers[:10] // Limit
```
### Step 2: Trigger Interactions & Capture
```javascript
depth_3_captures = []
FOR idx, trigger IN enumerate(triggers):
layer_name = f"{trigger.type}-{sanitize(trigger.text[:15]) or idx}"
output_file = f"{base_path}/screenshots/depth-3/{layer_name}.png"
TRY:
// Trigger interaction
IF trigger.trigger == "click":
mcp__chrome-devtools__click({uid: trigger.uid})
ELSE:
mcp__chrome-devtools__hover({uid: trigger.uid})
bash(sleep 1)
// Capture
mcp__chrome-devtools__take_screenshot({
fullPage: false, // Viewport only
format: "png",
quality: 90,
filePath: output_file
})
depth_3_captures.append({
"name": layer_name,
"type": trigger.type,
"trigger_method": trigger.trigger,
"path": output_file,
"size_kb": file_size_kb(output_file)
})
// Dismiss (ESC key)
mcp__chrome-devtools__evaluate_script({
function: `() => {
document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape'}));
}`
})
bash(sleep 0.5)
CATCH error:
REPORT: f"Skip {layer_name}: {error}"
layer_map.layers["depth-3"] = {
"type": "interactions",
"triggers": structure,
"captures": depth_3_captures
}
TodoWrite(mark_completed: "Depth 3: Interactions")
```
**Output**: `depth-3/{interaction}.png` × N
## Phase 6: Depth 4 - Embedded Level (If depth >= 4)
### Step 1: Detect Iframes
```javascript
IF depth < 4: SKIP
TodoWrite(mark_in_progress: "Depth 4: Embedded")
iframes = mcp__chrome-devtools__evaluate_script({
function: `() => {
return Array.from(document.querySelectorAll('iframe')).map(iframe => ({
src: iframe.src,
id: iframe.id || 'iframe',
title: iframe.title || 'untitled'
})).filter(i => i.src && i.src.startsWith('http'));
}`
})
```
### Step 2: Capture Iframe Content
```javascript
depth_4_captures = []
FOR idx, iframe IN enumerate(iframes):
iframe_name = f"iframe-{sanitize(iframe.title or iframe.id)}-{idx}"
output_file = f"{base_path}/screenshots/depth-4/{iframe_name}.png"
TRY:
// Navigate to iframe URL in new tab
mcp__chrome-devtools__new_page({url: iframe.src, timeout: 30000})
bash(sleep 2)
mcp__chrome-devtools__take_screenshot({
fullPage: true,
format: "png",
quality: 90,
filePath: output_file
})
depth_4_captures.append({
"name": iframe_name,
"url": iframe.src,
"path": output_file,
"size_kb": file_size_kb(output_file)
})
// Close iframe tab
current_pages = mcp__chrome-devtools__list_pages()
mcp__chrome-devtools__close_page({pageIdx: current_pages.length - 1})
CATCH error:
REPORT: f"Skip {iframe_name}: {error}"
layer_map.layers["depth-4"] = {
"type": "embedded",
"captures": depth_4_captures
}
TodoWrite(mark_completed: "Depth 4: Embedded")
```
**Output**: `depth-4/iframe-*.png` × N
## Phase 7: Depth 5 - Shadow DOM (If depth = 5)
### Step 1: Detect Shadow Roots
```javascript
IF depth < 5: SKIP
TodoWrite(mark_in_progress: "Depth 5: Shadow DOM")
shadow_elements = mcp__chrome-devtools__evaluate_script({
function: `() => {
const elements = Array.from(document.querySelectorAll('*'));
return elements
.filter(el => el.shadowRoot)
.map((el, idx) => ({
tag: el.tagName.toLowerCase(),
id: el.id || \`shadow-\${idx}\`,
innerHTML: el.shadowRoot.innerHTML.substring(0, 100)
}));
}`
})
```
### Step 2: Capture Shadow DOM Components
```javascript
depth_5_captures = []
FOR idx, shadow IN enumerate(shadow_elements):
shadow_name = f"shadow-{sanitize(shadow.id)}"
output_file = f"{base_path}/screenshots/depth-5/{shadow_name}.png"
TRY:
// Inject highlight script
mcp__chrome-devtools__evaluate_script({
function: `() => {
const el = document.querySelector('${shadow.tag}${shadow.id ? "#" + shadow.id : ""}');
if (el) {
el.scrollIntoView({behavior: 'smooth', block: 'center'});
el.style.outline = '3px solid red';
}
}`
})
bash(sleep 0.5)
// Full-page screenshot (component highlighted)
mcp__chrome-devtools__take_screenshot({
fullPage: false,
format: "png",
quality: 90,
filePath: output_file
})
depth_5_captures.append({
"name": shadow_name,
"tag": shadow.tag,
"path": output_file,
"size_kb": file_size_kb(output_file)
})
CATCH error:
REPORT: f"Skip {shadow_name}: {error}"
layer_map.layers["depth-5"] = {
"type": "shadow-dom",
"captures": depth_5_captures
}
TodoWrite(mark_completed: "Depth 5: Shadow DOM")
```
**Output**: `depth-5/shadow-*.png` × N
## Phase 8: Generate Layer Map
### Step 1: Compile Metadata
```javascript
TodoWrite(mark_in_progress: "Generate layer map")
// Calculate totals
total_captures = sum(len(layer.captures) for layer in layer_map.layers.values())
total_size_kb = sum(
sum(c.size_kb for c in layer.captures)
for layer in layer_map.layers.values()
)
layer_map["summary"] = {
"timestamp": current_timestamp(),
"total_depth": depth,
"total_captures": total_captures,
"total_size_kb": total_size_kb
}
Write(f"{base_path}/screenshots/layer-map.json", JSON.stringify(layer_map, indent=2))
TodoWrite(mark_completed: "Generate layer map")
```
**Output**: `layer-map.json`
## Completion
### Todo Update
```javascript
all_todos_completed = true
TodoWrite({todos: all_completed_todos})
```
### Output Message
```
✅ Interactive layer exploration complete!
Configuration:
- URL: {url}
- Max depth: {depth}
- Layers explored: {len(layer_map.layers)}
Capture Summary:
Depth 1 (Page): {depth_1_count} screenshot(s)
Depth 2 (Elements): {depth_2_count} screenshot(s)
Depth 3 (Interactions): {depth_3_count} screenshot(s)
Depth 4 (Embedded): {depth_4_count} screenshot(s)
Depth 5 (Shadow DOM): {depth_5_count} screenshot(s)
Total: {total_captures} captures ({total_size_kb:.1f} KB)
Output Structure:
{base_path}/screenshots/
├── depth-1/
│ └── full-page.png
├── depth-2/
│ ├── navbar.png
│ └── footer.png
├── depth-3/
│ ├── modal-login.png
│ └── dropdown-menu.png
├── depth-4/
│ └── iframe-analytics.png
├── depth-5/
│ └── shadow-button.png
└── layer-map.json
Next: /workflow:ui-design:extract --images "screenshots/**/*.png"
```
## Simple Bash Commands
### Directory Setup
```bash
# Create depth directories
bash(for i in $(seq 1 $depth); do mkdir -p $BASE_PATH/screenshots/depth-$i; done)
```
### Validation
```bash
# Check MCP
all_resources = ListMcpResourcesTool()
# Count captures per depth
bash(ls $base_path/screenshots/depth-{1..5}/*.png 2>/dev/null | wc -l)
```
### File Operations
```bash
# List all captures
bash(find $base_path/screenshots -name "*.png" -type f)
# Total size
bash(du -sh $base_path/screenshots)
```
## Output Structure
```
{base_path}/screenshots/
├── depth-1/
│ └── full-page.png
├── depth-2/
│ ├── {element}.png
│ └── ...
├── depth-3/
│ ├── {interaction}.png
│ └── ...
├── depth-4/
│ ├── iframe-*.png
│ └── ...
├── depth-5/
│ ├── shadow-*.png
│ └── ...
└── layer-map.json
```
## Depth Level Details
| Depth | Name | Captures | Time | Use Case |
|-------|------|----------|------|----------|
| 1 | Page | Full page | 30s | Quick preview |
| 2 | Elements | Key components | 1-2min | Component library |
| 3 | Interactions | Modals, dropdowns | 2-4min | UI flows |
| 4 | Embedded | Iframes | 3-6min | Complete context |
| 5 | Shadow DOM | Web components | 4-8min | Full coverage |
## Error Handling
### Common Errors
```
ERROR: Chrome DevTools MCP required
→ Install: npm i -g @modelcontextprotocol/server-chrome-devtools
ERROR: Invalid depth
→ Use: 1-5
ERROR: Interaction trigger failed
→ Some modals may be skipped, check layer-map.json
```
### Recovery
- **Partial success**: Lower depth captures preserved
- **Trigger failures**: Interaction layer may be incomplete
- **Iframe restrictions**: Cross-origin iframes skipped
## Quality Checklist
- [ ] All depths up to specified level captured
- [ ] layer-map.json generated with metadata
- [ ] File sizes valid (> 500 bytes)
- [ ] Interaction triggers executed
- [ ] Shadow DOM elements highlighted
## Key Features
- **Depth-controlled**: Progressive capture 1-5 levels
- **Interactive triggers**: Click/hover for hidden layers
- **Iframe support**: Embedded content captured
- **Shadow DOM**: Web component internals
- **Structured output**: Organized by depth
## Integration
**Input**: Single URL + depth level (1-5)
**Output**: Hierarchical screenshots + layer-map.json
**Complements**: `/workflow:ui-design:capture` (multi-URL batch)
**Next**: `/workflow:ui-design:extract` for design analysis

View File

@@ -1,13 +1,13 @@
---
name: extract
description: Extract design style from reference images or text prompts using Claude's analysis
usage: /workflow:ui-design:extract [--base-path <path>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--variants <count>]
usage: /workflow:ui-design:extract [--base-path <path>] [--session <id>] [--images "<glob>"] [--prompt "<desc>"] [--mode <imitate|explore>] [--variants <count>]
examples:
- /workflow:ui-design:extract --images "design-refs/*.png" --variants 3
- /workflow:ui-design:extract --prompt "Modern minimalist blog, dark theme" --variants 3
- /workflow:ui-design:extract --session WFS-auth --images "refs/*.png" --prompt "Linear.app style" --variants 2
- /workflow:ui-design:extract --base-path ".workflow/WFS-auth/design-run-20250109-143022" --images "refs/*.png" --variants 3
- /workflow:ui-design:extract --prompt "Bold vibrant" --variants 1 # Single variant (default)
- /workflow:ui-design:extract --images "design-refs/*.png" --mode explore --variants 3
- /workflow:ui-design:extract --prompt "Modern minimalist blog, dark theme" --mode explore --variants 3
- /workflow:ui-design:extract --session WFS-auth --images "refs/*.png" --prompt "Linear.app style" --mode imitate
- /workflow:ui-design:extract --base-path ".workflow/WFS-auth/design-run-20250109-143022" --images "refs/*.png" --mode explore --variants 3
- /workflow:ui-design:extract --prompt "Bold vibrant" --mode imitate # High-fidelity single style
allowed-tools: TodoWrite(*), Read(*), Write(*), Glob(*)
---
@@ -24,18 +24,25 @@ Extract design style from reference images or text prompts using Claude's built-
## Phase 0: Setup & Input Validation
### Step 1: Detect Input Mode & Base Path
### Step 1: Detect Input Mode, Extraction Mode & Base Path
```bash
# Detect input source
# Priority: --images + --prompt → hybrid | --images → image | --prompt → text
# Determine extraction mode
# Priority: --mode parameter → default "imitate"
extraction_mode = --mode OR "imitate" # "imitate" or "explore"
# Set variants count based on mode
IF extraction_mode == "imitate":
variants_count = 1 # Force single variant for imitate mode (ignore --variants)
ELSE IF extraction_mode == "explore":
variants_count = --variants OR 3 # Default to 3 for explore mode
VALIDATE: 1 <= variants_count <= 5
# Determine base path
bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect
# OR use --base-path / --session parameters
# Set variant count (default: 1)
# Priority: --variants parameter → default 1
# Validate: 1 <= variants_count <= 5
```
### Step 2: Load Inputs
@@ -59,15 +66,15 @@ bash(test -f {base_path}/style-extraction/style-cards.json && echo "exists")
**If exists**: Skip to completion message
**Output**: `input_mode`, `base_path`, `variants_count`, `loaded_images[]` or `prompt_guidance`
**Output**: `input_mode`, `base_path`, `extraction_mode`, `variants_count`, `loaded_images[]` or `prompt_guidance`
## Phase 1: Design Space Analysis (Explore Mode Only)
### Step 1: Determine Extraction Mode
### Step 1: Check Extraction Mode
```bash
# Auto-detect mode
# variants_count == 1 → imitate mode (skip this phase)
# variants_count > 1 → explore mode (execute this phase)
# Check extraction mode
# extraction_mode == "imitate" → skip this phase
# extraction_mode == "explore" → execute this phase
```
**If imitate mode**: Skip to Phase 2
@@ -119,7 +126,7 @@ AI generates `variants_count` design style proposals:
- WCAG AA accessibility (4.5:1 text, 3:1 UI)
**Output Format**: `style-cards.json` with:
- extraction_metadata (session_id, input_mode, timestamp, variants_count)
- extraction_metadata (session_id, input_mode, extraction_mode, timestamp, variants_count)
- style_cards[] (id, name, description, design_philosophy, preview, proposed_tokens)
### Step 2: Write Style Cards
@@ -146,11 +153,11 @@ TodoWrite({todos: [
Configuration:
- Session: {session_id}
- Mode: {extraction_mode} (imitate/explore)
- Input: {input_mode} (image/text/hybrid)
- Extraction Mode: {extraction_mode} (imitate/explore)
- Input Mode: {input_mode} (image/text/hybrid)
- Variants: {variants_count}
{IF explore mode:
{IF extraction_mode == "explore":
Design Space Analysis:
- {variants_count} maximally contrasting design directions
- Min contrast distance: {design_space_analysis.contrast_verification.min_pairwise_distance}
@@ -161,7 +168,7 @@ Generated Variants:
Output Files:
- {base_path}/style-extraction/style-cards.json
{IF explore mode: - {base_path}/style-extraction/design-space-analysis.json}
{IF extraction_mode == "explore": - {base_path}/style-extraction/design-space-analysis.json}
Next: /workflow:ui-design:consolidate --session {session_id} --variants {variants_count}
```
@@ -216,7 +223,7 @@ bash(test -f design-space-analysis.json && echo "saved")
```json
{
"extraction_metadata": {"session_id": "...", "input_mode": "image|text|hybrid", "timestamp": "...", "variants_count": N},
"extraction_metadata": {"session_id": "...", "input_mode": "image|text|hybrid", "extraction_mode": "imitate|explore", "timestamp": "...", "variants_count": N},
"style_cards": [
{
"id": "variant-1", "name": "Style Name", "description": "...",

View File

@@ -1,321 +0,0 @@
---
name: generate-v2
description: Generate UI prototypes using target-style-centric batch generation
usage: /workflow:ui-design:generate-v2 [--targets "<list>"] [--target-type "page|component"] [--base-path <path>] [--session <id>] [--style-variants <count>] [--layout-variants <count>]
examples:
- /workflow:ui-design:generate-v2 --session WFS-auth --targets "dashboard,settings"
- /workflow:ui-design:generate-v2 --targets "home,pricing" --style-variants 2 --layout-variants 2
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
# Generate UI Prototypes V2 (/workflow:ui-design:generate-v2)
## Overview
Generate matrix of UI prototypes (`style × layout × targets`) using **target-style-centric batch generation**. Each agent handles all layouts for one target × style combination.
**Strategy**: Target-Style-Centric
- **Agent scope**: Each of `T × S` agents generates `L` layouts
- **Component isolation**: Complete task independence
- **Style-aware**: HTML adapts to design_attributes
- **Self-contained CSS**: Direct token values (no var() refs)
**Supports**: Pages (full layouts) and components (isolated elements)
## Phase 1: Setup & Validation
### Step 1: Resolve Base Path & Parse Configuration
```bash
# Determine working directory
bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect
# Get counts (defaults: style=auto, layout=3)
bash(ls {base_path}/style-consolidation/style-* -d | wc -l)
# Parse targets (Priority: --targets → --pages → synthesis-specification.md → default ["home"])
# Target type: "page" (default) or "component"
```
### Step 2: Validate Inputs
```bash
# Check design systems exist
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "valid")
# Validate target names (lowercase, alphanumeric, hyphens only)
# Load design-space-analysis.json (optional, for style-aware generation)
```
**Output**: `base_path`, `style_variants`, `layout_variants`, `target_list[]`, `target_type`, `design_space_analysis` (optional)
### Step 3: Detect Token Sources
```bash
# Priority 1: consolidated tokens (production-ready from /workflow:ui-design:consolidate)
# Priority 2: proposed tokens from style-cards.json (fast-track from /workflow:ui-design:extract)
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "consolidated")
# OR
bash(test -f {base_path}/style-extraction/style-cards.json && echo "proposed")
# If proposed: Create temp consolidation dir + write proposed tokens
bash(mkdir -p {base_path}/style-consolidation/style-{id})
Write({base_path}/style-consolidation/style-{id}/design-tokens.json, proposed_tokens)
```
**Output**: `token_sources{}`, `consolidated_count`, `proposed_count`
### Step 4: Gather Layout Inspiration
```bash
bash(mkdir -p {base_path}/prototypes/_inspirations)
# For each target: Research via MCP
# mcp__exa__web_search_exa(query="{target} {target_type} layout patterns", numResults=5)
# Write simple inspiration file
Write({base_path}/prototypes/_inspirations/{target}-layout-ideas.txt, inspiration_content)
```
**Output**: `L` inspiration text files
## Phase 2: Target-Style-Centric Generation (Agent)
**Executor**: `Task(ui-design-agent)` × `T × S` tasks in parallel
### Step 1: Launch Agent Tasks
```bash
bash(mkdir -p {base_path}/prototypes)
```
For each `target × style_id`:
```javascript
Task(ui-design-agent): `
[TARGET_STYLE_UI_GENERATION]
🎯 ONE component: {target} × Style-{style_id} ({philosophy_name})
Generate: {layout_variants} × 2 files (HTML + CSS per layout)
TARGET: {target} | TYPE: {target_type} | STYLE: {style_id}/{style_variants}
BASE_PATH: {base_path}
${design_attributes ? "DESIGN_ATTRIBUTES: " + JSON.stringify(design_attributes) : ""}
## 参考
- Layout inspiration: Read("{base_path}/prototypes/_inspirations/{target}-layout-ideas.txt")
- Design tokens: Read("{base_path}/style-consolidation/style-{style_id}/design-tokens.json")
Parse ALL token values (colors, typography, spacing, borders, shadows, breakpoints)
${design_attributes ? "- Adapt DOM structure to: density, visual_weight, formality, organic_vs_geometric" : ""}
## 生成
For EACH layout (1 to {layout_variants}):
1. HTML: {base_path}/prototypes/{target}-style-{style_id}-layout-N.html
- Complete HTML5: <!DOCTYPE>, <head>, <body>
- CSS ref: <link href="{target}-style-{style_id}-layout-N.css">
- Semantic: <header>, <nav>, <main>, <footer>
- A11y: ARIA labels, landmarks, responsive meta
${design_attributes ? `
- DOM adaptation:
* density='spacious' → flatter hierarchy
* density='compact' → deeper nesting
* visual_weight='heavy' → extra wrappers
* visual_weight='minimal' → direct structure` : ""}
2. CSS: {base_path}/prototypes/{target}-style-{style_id}-layout-N.css
- Self-contained: Direct token VALUES (no var())
- Use tokens: colors, fonts, spacing, borders, shadows
- Responsive: Mobile-first @media(breakpoints)
${design_attributes ? `
- Token selection:
* density → spacing scale
* visual_weight → shadow strength
* organic_vs_geometric → border-radius` : ""}
## 注意
- ✅ Use token VALUES directly from design-tokens.json
- ❌ NO var() references, NO external dependencies
- Layouts structurally DISTINCT (different grids/regions)
- Write files IMMEDIATELY (per layout, no accumulation)
- CSS filename MUST match HTML <link href="...">
- No text output, write to filesystem only
`
```
### Step 2: Verify Generated Files
```bash
# Count expected vs found
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
# Validate samples
Read({base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html)
# Check: <!DOCTYPE html>, correct CSS href, sufficient CSS length
```
**Output**: `S × L × T × 2` files verified
## Phase 3: Generate Preview Files
### Step 1: Run Preview Generation Script
```bash
bash(~/.claude/scripts/ui-generate-preview-v2.sh "{base_path}/prototypes")
```
**Script generates**:
- `compare.html` (interactive matrix)
- `index.html` (navigation)
- `PREVIEW.md` (instructions)
### Step 2: Verify Preview Files
```bash
bash(ls {base_path}/prototypes/compare.html {base_path}/prototypes/index.html {base_path}/prototypes/PREVIEW.md)
```
**Output**: 3 preview files
## Completion
### Todo Update
```javascript
TodoWrite({todos: [
{content: "Setup and validation", status: "completed", activeForm: "Loading design systems"},
{content: "Gather layout inspiration", status: "completed", activeForm: "Researching layouts"},
{content: "Target-style generation (agent)", status: "completed", activeForm: "Generating prototypes"},
{content: "Verify files", status: "completed", activeForm: "Validating output"},
{content: "Generate previews", status: "completed", activeForm: "Creating preview files"}
]});
```
### Output Message
```
✅ Target-Style-Centric UI generation complete!
Configuration:
- Style Variants: {style_variants}
- Layout Variants: {layout_variants} (inspiration-based)
- Target Type: {target_type}
- Targets: {target_list}
- Total Prototypes: {S × L × T}
Agent Execution:
- Target-style agents: T×S = {T}×{S} = {T×S} agents
- Each agent scope: {L} layouts for one component
- Component isolation: Complete task independence
Quality:
- Style-aware: {design_space_analysis ? 'HTML adapts to design_attributes' : 'Standard structure'}
- CSS: Self-contained (direct token values, no var())
- Tokens: {consolidated_count} consolidated, {proposed_count} proposed
{IF proposed_count > 0: ' 💡 For production: /workflow:ui-design:consolidate'}
Generated Files:
{base_path}/prototypes/
├── _inspirations/ ({T} text files)
├── {target}-style-{s}-layout-{l}.html ({S×L×T} prototypes)
├── {target}-style-{s}-layout-{l}.css
├── compare.html (interactive matrix)
├── index.html (navigation)
└── PREVIEW.md (instructions)
Preview:
1. Open compare.html (recommended)
2. Open index.html
3. Read PREVIEW.md
Next: /workflow:ui-design:update
```
## Simple Bash Commands
### Path Operations
```bash
# Find design directory
bash(find .workflow -type d -name "design-*" | head -1)
# Count style variants
bash(ls {base_path}/style-consolidation/style-* -d | wc -l)
# Check token sources
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "consolidated")
bash(test -f {base_path}/style-extraction/style-cards.json && echo "proposed")
```
### Validation Commands
```bash
# Check design tokens exist
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "valid")
# Count generated files
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
# Verify preview
bash(test -f {base_path}/prototypes/compare.html && echo "exists")
```
### File Operations
```bash
# Create directories
bash(mkdir -p {base_path}/prototypes/_inspirations)
# Run preview script
bash(~/.claude/scripts/ui-generate-preview-v2.sh "{base_path}/prototypes")
```
## Output Structure
```
{base_path}/
├── prototypes/
│ ├── _inspirations/
│ │ └── {target}-layout-ideas.txt # Layout inspiration
│ ├── {target}-style-{s}-layout-{l}.html # Final prototypes
│ ├── {target}-style-{s}-layout-{l}.css
│ ├── compare.html
│ ├── index.html
│ └── PREVIEW.md
└── style-consolidation/
└── style-{s}/
├── design-tokens.json
└── style-guide.md
```
## Error Handling
### Common Errors
```
ERROR: No token sources found
→ Run /workflow:ui-design:extract or /workflow:ui-design:consolidate
ERROR: MCP search failed
→ Check network, retry
ERROR: Agent task failed
→ Check agent output, retry specific target×style
ERROR: Script permission denied
→ chmod +x ~/.claude/scripts/ui-generate-preview-v2.sh
```
### Recovery Strategies
- **Partial success**: Keep successful target×style combinations
- **Missing design_attributes**: Works without (less style-aware)
- **Invalid tokens**: Validate design-tokens.json structure
## Quality Checklist
- [ ] CSS uses direct token values (no var())
- [ ] HTML structure adapts to design_attributes (if available)
- [ ] Semantic HTML5 structure
- [ ] ARIA attributes present
- [ ] Mobile-first responsive
- [ ] Layouts structurally distinct
- [ ] compare.html works
## Key Features
- **Target-Style-Centric**: `T×S` agents, each handles `L` layouts
- **Component Isolation**: Complete task independence
- **Style-Aware**: HTML adapts to design_attributes
- **Self-Contained CSS**: Direct token values (no var())
- **Inspiration-Based**: Simple text research vs complex JSON
- **Production-Ready**: Semantic, accessible, responsive
## Integration
**Input**: design-tokens.json, design-space-analysis.json (optional), targets
**Output**: S×L×T prototypes for `/workflow:ui-design:update`
**Called by**: `/workflow:ui-design:explore-auto-v2`, `/workflow:ui-design:imitate-auto`

View File

@@ -1,225 +1,197 @@
---
name: generate
description: Generate UI prototypes in matrix mode (style × layout combinations) for pages or components
usage: /workflow:ui-design:generate [--targets "<list>"] [--target-type "page|component"] [--base-path <path>] [--session <id>] [--style-variants <count>] [--layout-variants <count>]
description: Generate UI prototypes using target-style-centric batch generation
usage: /workflow:ui-design:generate [--targets "<list>"] [--target-type "page|component"] [--device-type "desktop|mobile|tablet|responsive"] [--base-path <path>] [--session <id>] [--style-variants <count>] [--layout-variants <count>]
examples:
- /workflow:ui-design:generate --base-path ".workflow/WFS-auth/design-run-20250109-143022" --targets "dashboard,settings"
- /workflow:ui-design:generate --session WFS-auth --targets "home,pricing" --style-variants 2 --layout-variants 2
- /workflow:ui-design:generate --targets "navbar,hero,card" --target-type "component"
- /workflow:ui-design:generate --session WFS-auth --targets "dashboard,settings"
- /workflow:ui-design:generate --targets "home,pricing" --style-variants 2 --layout-variants 2
- /workflow:ui-design:generate --targets "app" --device-type mobile
- /workflow:ui-design:generate --targets "dashboard" --device-type desktop
allowed-tools: TodoWrite(*), Read(*), Write(*), Task(ui-design-agent), Bash(*)
---
# Generate UI Prototypes (/workflow:ui-design:generate)
## Overview
Generate matrix of UI prototypes (`style × layout × targets`) with production-ready HTML/CSS. Optimized template-based architecture: **`S` times faster** than direct generation.
Generate matrix of UI prototypes (`style × layout × targets`) using **target-style-centric batch generation**. Each agent handles all layouts for one target × style combination.
**Strategy**: Two-layer generation
- **Layer 1**: Generate `L × T` reusable templates (agent)
- **Layer 2**: Instantiate `S × L × T` final prototypes (script)
**Strategy**: Target-Style-Centric
- **Agent scope**: Each of `T × S` agents generates `L` layouts
- **Component isolation**: Complete task independence
- **Style-aware**: HTML adapts to design_attributes
- **Self-contained CSS**: Direct token values (no var() refs)
**Supports**: Pages (full layouts) and components (isolated elements)
## Phase 1: Setup & Validation
### Step 1: Resolve Base Path
### Step 1: Resolve Base Path & Parse Configuration
```bash
# Determine working directory
bash(find .workflow -type d -name "design-*" | head -1) # Auto-detect
# OR use --base-path / --session parameters
```
### Step 2: Parse Configuration
```bash
# Get style variant count (default: 3)
# Get counts (defaults: style=auto, layout=3)
bash(ls {base_path}/style-consolidation/style-* -d | wc -l)
# Get layout variant count (default: 3, configurable via --layout-variants)
# Parse targets (Priority: --targets → --pages → synthesis-specification.md → default ["home"])
# Target type: "page" (default) or "component"
# Parse targets (pages/components)
# Priority: --targets → --pages (legacy) → synthesis-specification.md → default ["home"]
# Parse device type
device_type = --device-type OR "responsive" # Default: responsive
# Try to load from .run-metadata.json if exists
IF exists({base_path}/.run-metadata.json):
metadata = Read({base_path}/.run-metadata.json)
IF metadata.parameters.device_type:
device_type = metadata.parameters.device_type
```
### Step 3: Validate Inputs
### Step 2: Validate Inputs
```bash
# Check design systems exist
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "valid")
# Validate target names (lowercase, alphanumeric, hyphens only)
# Target type: "page" (default) or "component"
# Load design-space-analysis.json (optional, for style-aware generation)
```
**Output**: `base_path`, `style_variants`, `layout_variants`, `target_list[]`, `target_type`
**Output**: `base_path`, `style_variants`, `layout_variants`, `target_list[]`, `target_type`, `design_space_analysis` (optional), `device_type`
### Step 4: Check Existing Output
### Step 3: Detect Token Sources
```bash
# Skip if already generated
bash(test -f {base_path}/prototypes/compare.html && echo "exists")
# Priority 1: consolidated tokens (production-ready from /workflow:ui-design:consolidate)
# Priority 2: proposed tokens from style-cards.json (fast-track from /workflow:ui-design:extract)
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "consolidated")
# OR
bash(test -f {base_path}/style-extraction/style-cards.json && echo "proposed")
# If proposed: Create temp consolidation dir + write proposed tokens
bash(mkdir -p {base_path}/style-consolidation/style-{id})
Write({base_path}/style-consolidation/style-{id}/design-tokens.json, proposed_tokens)
```
**If exists**: Skip to completion message
**Output**: `token_sources{}`, `consolidated_count`, `proposed_count`
## Phase 2: Layout Planning
### Step 1: Research Layout Patterns (Agent)
### Step 4: Gather Layout Inspiration
```bash
bash(mkdir -p {base_path}/prototypes/_templates)
bash(mkdir -p {base_path}/prototypes/_inspirations)
# For each target: Research via MCP
# mcp__exa__web_search_exa(query="{target} {target_type} layout patterns", numResults=5)
# Write simple inspiration file
Write({base_path}/prototypes/_inspirations/{target}-layout-ideas.txt, inspiration_content)
```
For each `target × layout_id`:
```javascript
Task(ui-design-agent): `
[TARGET_LAYOUT_PLANNING]
TARGET: {target} | TYPE: {target_type} | LAYOUT: {layout_id}/{layout_variants}
BASE_PATH: {base_path}
${--session ? "REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md" : ""}
**Output**: `L` inspiration text files
## 参考
- Research via: mcp__exa__web_search_exa(query="{target} {target_type} layout patterns 2024", numResults=5)
- Layout differentiation: Layout 1=common, Layout 2=alternative, Layout 3=innovative
## Phase 2: Target-Style-Centric Generation (Agent)
## 生成
Write("{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json")
JSON schema:
{
"id": "layout-{layout_id}",
"target": "{target}",
"target_type": "{target_type}",
"name": "2-4 words",
"description": "2-3 sentences",
"structure": {
// Page: type, regions, grid, sidebar, responsive{mobile/tablet/desktop}
// Component: arrangement, alignment, spacing, element_order, variants
},
"semantic_hints": ["<nav>", "<main role='main'>", ...],
"accessibility_features": ["skip-link", "landmarks", ...],
"research_references": ["source URLs/insights"]
}
## 注意
- Layout #{layout_id} must be STRUCTURALLY DIFFERENT from other IDs
- Structure section must match target_type (page vs component)
- Write file directly, no text output
`
```
### Step 2: Verify Layout Plans
```bash
# Verify files created
bash(ls {base_path}/prototypes/_templates/*.json | wc -l) # Should equal L×T
# Validate JSON structure
Read({base_path}/prototypes/_templates/{target}-layout-{layout_id}.json)
```
**Output**: `L × T` layout plan JSON files
## Phase 3: Token Conversion
### Step 1: Convert JSON to CSS Variables
```bash
# Check jq dependency
bash(command -v jq >/dev/null 2>&1 || echo "ERROR: jq not found")
# Convert each style's design-tokens.json to tokens.css
bash(cat {base_path}/style-consolidation/style-1/design-tokens.json | ~/.claude/scripts/convert_tokens_to_css.sh > tokens.css)
```
### Step 2: Extract Variable Names
```bash
# Read generated tokens.css
Read({base_path}/style-consolidation/style-1/tokens.css)
# Extract CSS variable names (pattern: --variable-name:)
# Categorize: colors, typography, spacing, radius, shadows
```
**Output**: `S × tokens.css` files + extracted variable list
## Phase 4: Template Generation (Agent)
**Executor**: `Task(ui-design-agent)` × `L × T` tasks in parallel
**Executor**: `Task(ui-design-agent)` × `T × S` tasks in parallel
### Step 1: Launch Agent Tasks
For each `layout_id × target`:
```bash
bash(mkdir -p {base_path}/prototypes)
```
For each `target × style_id`:
```javascript
Task(ui-design-agent): `
[UI_LAYOUT_TEMPLATE_GENERATION]
🚨 ONE target only: '{target}' (standalone, reusable)
[TARGET_STYLE_UI_GENERATION]
🎯 ONE component: {target} × Style-{style_id} ({philosophy_name})
Generate: {layout_variants} × 2 files (HTML + CSS per layout)
LAYOUT: {layout_id} | TARGET: {target} | TYPE: {target_type}
TARGET: {target} | TYPE: {target_type} | STYLE: {style_id}/{style_variants}
BASE_PATH: {base_path}
${--session ? "REQUIREMENTS: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md" : ""}
DEVICE: {device_type}
${design_attributes ? "DESIGN_ATTRIBUTES: " + JSON.stringify(design_attributes) : ""}
## 参考
- Layout plan: Read("{base_path}/prototypes/_templates/{target}-layout-{layout_id}.json")
- Design tokens: Read("{base_path}/style-consolidation/style-1/tokens.css")
Extract variables: --color-*, --font-*, --spacing-*, --border-radius-*, --shadow-*
## Reference
- Layout inspiration: Read("{base_path}/prototypes/_inspirations/{target}-layout-ideas.txt")
- Design tokens: Read("{base_path}/style-consolidation/style-{style_id}/design-tokens.json")
Parse ALL token values (colors, typography, spacing, borders, shadows, breakpoints)
${design_attributes ? "- Adapt DOM structure to: density, visual_weight, formality, organic_vs_geometric" : ""}
## 生成
1. HTML: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.html
- Complete HTML5 doc with <link href="{{STRUCTURAL_CSS}}"> and <link href="{{TOKEN_CSS}}">
- Body: Full structure (page) OR isolated element (component)
- Semantic: <header>, <nav>, <main>, <footer>, proper heading hierarchy
- A11y: ARIA landmarks, skip-link, alt/labels, focus styles
## Generation
For EACH layout (1 to {layout_variants}):
2. CSS: {base_path}/prototypes/_templates/{target}-layout-{layout_id}.css
- Structure: Flexbox/Grid, positioning, dimensions, responsive
- Mobile-first: base → @media(768px) → @media(1024px)
- Optional: {target}-layout-{layout_id}-tokens.css for --layout-* vars
1. HTML: {base_path}/prototypes/{target}-style-{style_id}-layout-N.html
- Complete HTML5: <!DOCTYPE>, <head>, <body>
- CSS ref: <link href="{target}-style-{style_id}-layout-N.css">
- Semantic: <header>, <nav>, <main>, <footer>
- A11y: ARIA labels, landmarks, responsive meta
- Viewport meta: <meta name="viewport" content="width=device-width, initial-scale=1.0">
${design_attributes ? `
- DOM adaptation:
* density='spacious' → flatter hierarchy
* density='compact' → deeper nesting
* visual_weight='heavy' → extra wrappers
* visual_weight='minimal' → direct structure` : ""}
- Device-specific structure:
* mobile (375×812px): Single column, stacked sections, touch targets ≥44px
* desktop (1920×1080px): Multi-column grids, hover states, larger hit areas
* tablet (768×1024px): Hybrid layouts, flexible columns
* responsive: Breakpoint-driven adaptive layouts (mobile-first)
## 注意
- ✅ ONLY var(--token-name) from tokens.css
- ❌ NO hardcoded: colors (#333, rgb), spacing (16px), fonts ("Arial")
- ❌ NO invented variable names
- Body content matches target_type (page=full, component=isolated)
- Write files directly, no text output
2. CSS: {base_path}/prototypes/{target}-style-{style_id}-layout-N.css
- Self-contained: Direct token VALUES (no var())
- Use tokens: colors, fonts, spacing, borders, shadows
- Device-optimized styles for {device_type}
${device_type === 'responsive' ? '- Responsive: Mobile-first @media(breakpoints)' : '- Fixed device: Optimize for ' + device_type}
${design_attributes ? `
- Token selection:
* density → spacing scale
* visual_weight → shadow strength
* organic_vs_geometric → border-radius` : ""}
- Device-specific CSS:
* mobile: Compact spacing, touch-friendly
* desktop: Generous whitespace, hover effects
* tablet: Medium spacing, flexible grids
* responsive: Fluid typography, breakpoints
## Notes
- ✅ Use token VALUES directly from design-tokens.json
- ✅ Optimize for {device_type} device
- ❌ NO var() references, NO external dependencies
- Layouts structurally DISTINCT (different grids/regions)
- Write files IMMEDIATELY (per layout, no accumulation)
- CSS filename MUST match HTML <link href="...">
- No text output, write to filesystem only
- Device-first approach: Design specifically for {device_type} user experience
`
```
### Step 2: Verify Templates Created
### Step 2: Verify Generated Files
```bash
# Check file count
bash(ls {base_path}/prototypes/_templates/{target}-layout-*.html | wc -l)
# Count expected vs found
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
# Validate structure
Read({base_path}/prototypes/_templates/{target}-layout-{layout_id}.html)
# Check: <!DOCTYPE html>, var(--, placeholders
# Validate samples
Read({base_path}/prototypes/{target}-style-{style_id}-layout-{layout_id}.html)
# Check: <!DOCTYPE html>, correct CSS href, sufficient CSS length
```
**Output**: `L × T` template pairs (HTML + CSS)
**Output**: `S × L × T × 2` files verified
## Phase 5: Prototype Instantiation (Script)
## Phase 3: Generate Preview Files
### Step 1: Execute Instantiation Script
### Step 1: Run Preview Generation Script
```bash
# Verify tokens.css files exist
bash(ls {base_path}/style-consolidation/style-*/tokens.css | wc -l)
# Run instantiation script
bash(~/.claude/scripts/ui-instantiate-prototypes.sh "{base_path}/prototypes" --session-id "{session_id}" --mode "{target_type}")
bash(~/.claude/scripts/ui-generate-preview.sh "{base_path}/prototypes")
```
**Script generates**:
- `S × L × T` HTML prototypes with CSS links
- Implementation notes for each prototype
- `compare.html` (interactive matrix)
- `index.html` (navigation)
- `PREVIEW.md` (documentation)
- `PREVIEW.md` (instructions)
### Step 2: Verify Output Files
### Step 2: Verify Preview Files
```bash
# Check preview files
bash(ls {base_path}/prototypes/compare.html {base_path}/prototypes/index.html {base_path}/prototypes/PREVIEW.md)
# Count final prototypes
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
```
**Output**: `S × L × T` final prototypes + preview files
**Output**: 3 preview files
## Completion
@@ -227,38 +199,46 @@ bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
```javascript
TodoWrite({todos: [
{content: "Setup and validation", status: "completed", activeForm: "Loading design systems"},
{content: "Layout planning (agent)", status: "completed", activeForm: "Planning layouts"},
{content: "Token conversion", status: "completed", activeForm: "Converting tokens"},
{content: "Template generation (agent)", status: "completed", activeForm: "Generating templates"},
{content: "Prototype instantiation (script)", status: "completed", activeForm: "Running script"},
{content: "Verify output", status: "completed", activeForm: "Verifying files"}
{content: "Gather layout inspiration", status: "completed", activeForm: "Researching layouts"},
{content: "Target-style generation (agent)", status: "completed", activeForm: "Generating prototypes"},
{content: "Verify files", status: "completed", activeForm: "Validating output"},
{content: "Generate previews", status: "completed", activeForm: "Creating preview files"}
]});
```
### Output Message
```
Matrix UI generation complete!
Target-Style-Centric UI generation complete!
Configuration:
- Style Variants: {style_variants}
- Layout Variants: {layout_variants}
- Layout Variants: {layout_variants} (inspiration-based)
- Target Type: {target_type}
- Device Type: {device_type}
- Targets: {target_list}
- Total Prototypes: {S × L × T}
Performance:
- Templates: {L × T} (agent)
- Prototypes: {S × L × T} (script)
- Speed: {S}× faster
- Script: ui-instantiate-prototypes.sh v3.0
Agent Execution:
- Target-style agents: T×S = {T}×{S} = {T×S} agents
- Each agent scope: {L} layouts for one component
- Component isolation: Complete task independence
- Device-specific: All layouts optimized for {device_type}
Quality:
- Style-aware: {design_space_analysis ? 'HTML adapts to design_attributes' : 'Standard structure'}
- CSS: Self-contained (direct token values, no var())
- Device-optimized: {device_type} layouts
- Tokens: {consolidated_count} consolidated, {proposed_count} proposed
{IF proposed_count > 0: ' 💡 For production: /workflow:ui-design:consolidate'}
Generated Files:
{base_path}/prototypes/
├── _templates/ ({T×L} JSON + HTML + CSS)
├── _inspirations/ ({T} text files)
├── {target}-style-{s}-layout-{l}.html ({S×L×T} prototypes)
├── {target}-style-{s}-layout-{l}.css
├── compare.html (interactive matrix)
├── index.html (navigation)
└── PREVIEW.md (documentation)
└── PREVIEW.md (instructions)
Preview:
1. Open compare.html (recommended)
@@ -278,8 +258,9 @@ bash(find .workflow -type d -name "design-*" | head -1)
# Count style variants
bash(ls {base_path}/style-consolidation/style-* -d | wc -l)
# List targets from templates
bash(ls {base_path}/prototypes/_templates/*-layout-1.json | sed 's/-layout-1.json//')
# Check token sources
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "consolidated")
bash(test -f {base_path}/style-extraction/style-cards.json && echo "proposed")
```
### Validation Commands
@@ -287,23 +268,20 @@ bash(ls {base_path}/prototypes/_templates/*-layout-1.json | sed 's/-layout-1.jso
# Check design tokens exist
bash(test -f {base_path}/style-consolidation/style-1/design-tokens.json && echo "valid")
# Count template files
bash(ls {base_path}/prototypes/_templates/*.html | wc -l)
# Count generated files
bash(ls {base_path}/prototypes/{target}-style-*-layout-*.html | wc -l)
# Verify output complete
# Verify preview
bash(test -f {base_path}/prototypes/compare.html && echo "exists")
```
### File Operations
```bash
# Create directories
bash(mkdir -p {base_path}/prototypes/_templates)
bash(mkdir -p {base_path}/prototypes/_inspirations)
# Convert tokens to CSS
bash(cat design-tokens.json | ~/.claude/scripts/convert_tokens_to_css.sh > tokens.css)
# Run instantiation script
bash(~/.claude/scripts/ui-instantiate-prototypes.sh "{base_path}/prototypes" --mode "page")
# Run preview script
bash(~/.claude/scripts/ui-generate-preview.sh "{base_path}/prototypes")
```
## Output Structure
@@ -311,19 +289,16 @@ bash(~/.claude/scripts/ui-instantiate-prototypes.sh "{base_path}/prototypes" --m
```
{base_path}/
├── prototypes/
│ ├── _templates/
│ │ ── {target}-layout-{l}.json # Layout plans
│ │ ├── {target}-layout-{l}.html # HTML templates
│ │ └── {target}-layout-{l}.css # CSS templates
│ ├── _inspirations/
│ │ ── {target}-layout-ideas.txt # Layout inspiration
│ ├── {target}-style-{s}-layout-{l}.html # Final prototypes
│ ├── {target}-style-{s}-layout-{l}-notes.md
│ ├── {target}-style-{s}-layout-{l}.css
│ ├── compare.html
│ ├── index.html
│ └── PREVIEW.md
└── style-consolidation/
└── style-{s}/
├── design-tokens.json
├── tokens.css
└── style-guide.md
```
@@ -331,45 +306,45 @@ bash(~/.claude/scripts/ui-instantiate-prototypes.sh "{base_path}/prototypes" --m
### Common Errors
```
ERROR: No design systems found
→ Run /workflow:ui-design:consolidate first
ERROR: No token sources found
→ Run /workflow:ui-design:extract or /workflow:ui-design:consolidate
ERROR: jq not found
Install jq: brew install jq
ERROR: MCP search failed
Check network, retry
ERROR: Agent task failed
→ Check agent output, retry phase
→ Check agent output, retry specific target×style
ERROR: Script permission denied
→ chmod +x ~/.claude/scripts/ui-instantiate-prototypes.sh
→ chmod +x ~/.claude/scripts/ui-generate-preview.sh
```
### Recovery Strategies
- **Partial failure**: Check script logs for counts
- **Missing templates**: Regenerate Phase 4
- **Invalid tokens**: Validate design-tokens.json
- **Partial success**: Keep successful target×style combinations
- **Missing design_attributes**: Works without (less style-aware)
- **Invalid tokens**: Validate design-tokens.json structure
## Quality Checklist
- [ ] CSS uses var(--token-name) only
- [ ] No hardcoded colors/spacing
- [ ] CSS uses direct token values (no var())
- [ ] HTML structure adapts to design_attributes (if available)
- [ ] Semantic HTML5 structure
- [ ] ARIA attributes present
- [ ] Mobile-first responsive
- [ ] Naming: `{target}-style-{s}-layout-{l}`
- [ ] Layouts structurally distinct
- [ ] compare.html works
## Key Features
- **Template-Based**: `S` times faster generation
- **Target Types**: Pages and components
- **Agent-Driven**: Parallel task execution
- **Token-Driven**: No hardcoded values
- **Target-Style-Centric**: `T×S` agents, each handles `L` layouts
- **Component Isolation**: Complete task independence
- **Style-Aware**: HTML adapts to design_attributes
- **Self-Contained CSS**: Direct token values (no var())
- **Inspiration-Based**: Simple text research vs complex JSON
- **Production-Ready**: Semantic, accessible, responsive
- **Interactive Preview**: Matrix comparison view
## Integration
**Input**: design-tokens.json from `/workflow:ui-design:consolidate`
**Output**: Prototypes for `/workflow:ui-design:update`
**Input**: design-tokens.json, design-space-analysis.json (optional), targets
**Output**: S×L×T prototypes for `/workflow:ui-design:update`
**Called by**: `/workflow:ui-design:explore-auto`, `/workflow:ui-design:imitate-auto`

View File

@@ -1,621 +0,0 @@
---
name: imitate-auto-v3
description: High-speed multi-page UI replication with batch screenshot and optional token refinement
usage: /workflow:ui-design:imitate-auto-v3 --url-map "<map>" [--session <id>] [--refine-tokens] [--prompt "<desc>"]
examples:
- /workflow:ui-design:imitate-auto-v3 --url-map "home:https://linear.app, features:https://linear.app/features"
- /workflow:ui-design:imitate-auto-v3 --session WFS-payment --url-map "pricing:https://stripe.com/pricing"
- /workflow:ui-design:imitate-auto-v3 --url-map "dashboard:https://app.com/dash" --refine-tokens
- /workflow:ui-design:imitate-auto-v3 --url-map "home:https://example.com, about:https://example.com/about" --prompt "Focus on minimalist design"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Write(*), Bash(*)
---
# UI Design Imitate-Auto Workflow (V3)
## Overview & Philosophy
**批量多页面快速复现工作流**通过编排器模式组合capture、extract、generate-v2命令实现高效的批量页面复制。
## Parameter Requirements
### Required Parameters
- `--url-map "<map>"` (必需): 目标页面映射
- 格式:`"target1:url1, target2:url2, ..."`
- 示例:`"home:https://linear.app, pricing:https://linear.app/pricing"`
- 第一个target作为主要样式来源
### Optional Parameters
- `--session <id>` (可选): 工作流会话ID
- 集成到现有会话(`.workflow/WFS-{session}/`
- 启用自动设计系统集成Phase 5
- 如不提供standalone模式`.workflow/.design/`
- `--refine-tokens` (可选, 默认: false): 启用完整token refinement
- `false` (默认): 快速路径跳过consolidate~30-60s faster
- `true`: 生产质量执行完整consolidatephilosophy-driven refinement
- `--prompt "<desc>"` (可选): 样式提取指导
- 影响extract命令的分析重点
- 示例:`"Focus on dark mode"`, `"Emphasize minimalist design"`
## 5-Phase Execution Protocol
### Phase 0: 初始化和目标解析
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 UI Design Imitate-Auto V3"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 生成run ID
run_id = "run-$(date +%Y%m%d-%H%M%S)"
# 确定base path和session mode
IF --session:
session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/design-{run_id}"
session_mode = "integrated"
REPORT: "Mode: Integrated (Session: {session_id})"
ELSE:
session_id = null
base_path = ".workflow/.design/{run_id}"
session_mode = "standalone"
REPORT: "Mode: Standalone"
# 创建base目录
Bash(mkdir -p "{base_path}")
# 解析url-map
url_map_string = {--url-map}
VALIDATE: url_map_string is not empty, "--url-map parameter is required"
# 解析target:url pairs
url_map = {} # {target_name: url}
target_names = []
FOR pair IN split(url_map_string, ","):
pair = pair.strip()
IF ":" NOT IN pair:
ERROR: "Invalid url-map format: '{pair}'"
ERROR: "Expected format: 'target:url'"
ERROR: "Example: 'home:https://example.com, pricing:https://example.com/pricing'"
EXIT 1
target, url = pair.split(":", 1)
target = target.strip().lower().replace(" ", "-")
url = url.strip()
url_map[target] = url
target_names.append(target)
VALIDATE: len(target_names) > 0, "url-map must contain at least one target:url pair"
primary_target = target_names[0] # 第一个作为主要样式来源
refine_tokens_mode = --refine-tokens OR false
# 写入元数据
metadata = {
"workflow": "imitate-auto-v3",
"run_id": run_id,
"session_id": session_id,
"timestamp": current_timestamp(),
"parameters": {
"url_map": url_map,
"refine_tokens": refine_tokens_mode,
"prompt": --prompt OR null
},
"targets": target_names,
"status": "in_progress"
}
Write("{base_path}/.run-metadata.json", JSON.stringify(metadata, null, 2))
REPORT: ""
REPORT: "Configuration:"
REPORT: " Targets: {len(target_names)} pages"
REPORT: " Primary source: '{primary_target}' ({url_map[primary_target]})"
REPORT: " All targets: {', '.join(target_names)}"
REPORT: " Token refinement: {refine_tokens_mode ? 'Enabled (production quality)' : 'Disabled (fast-track)'}"
IF --prompt:
REPORT: " Prompt guidance: \"{--prompt}\""
REPORT: ""
# 初始化TodoWrite
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: f"Batch screenshot capture ({len(target_names)} targets)", status: "pending", activeForm: "Capturing screenshots"},
{content: "Extract unified design system", status: "pending", activeForm: "Extracting style"},
{content: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation (skip consolidate)", status: "pending", activeForm: "Processing tokens"},
{content: f"Generate UI for {len(target_names)} targets", status: "pending", activeForm: "Generating UI"},
{content: session_id ? "Integrate design system" : "Standalone completion", status: "pending", activeForm: "Completing"}
]})
```
### Phase 1: 批量截图捕获
```bash
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 1: Batch Screenshot Capture"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 构建url-map字符串传递给capture命令
url_map_command_string = ",".join([f"{name}:{url}" for name, url in url_map.items()])
# 调用capture命令
capture_command = f"/workflow:ui-design:capture --base-path \"{base_path}\" --url-map \"{url_map_command_string}\""
REPORT: "Calling capture command..."
REPORT: f" Command: {capture_command}"
TRY:
SlashCommand(capture_command)
CATCH error:
ERROR: "Screenshot capture failed: {error}"
ERROR: "Cannot proceed without screenshots"
EXIT 1
# capture命令输出到: {base_path}/screenshots/{target}.png + capture-metadata.json
# 验证截图结果
screenshot_metadata_path = "{base_path}/screenshots/capture-metadata.json"
IF NOT exists(screenshot_metadata_path):
ERROR: "capture command did not generate metadata file"
ERROR: "Expected: {screenshot_metadata_path}"
EXIT 1
screenshot_metadata = Read(screenshot_metadata_path)
captured_count = screenshot_metadata.total_captured
total_requested = screenshot_metadata.total_requested
missing_count = total_requested - captured_count
REPORT: ""
REPORT: "✅ Phase 1 complete:"
REPORT: " Captured: {captured_count}/{total_requested} screenshots ({(captured_count/total_requested*100):.1f}%)"
IF missing_count > 0:
missing_targets = [s.target for s in screenshot_metadata.screenshots if not s.captured]
WARN: " ⚠️ Missing {missing_count} screenshots: {', '.join(missing_targets)}"
WARN: " Proceeding with available screenshots for extract phase"
# 如果所有截图都失败,终止
IF captured_count == 0:
ERROR: "No screenshots captured - cannot proceed"
ERROR: "Please check URLs and tool availability"
EXIT 1
TodoWrite(mark_completed: f"Batch screenshot capture ({len(target_names)} targets)",
mark_in_progress: "Extract unified design system")
```
### Phase 2: 统一设计系统提取
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 2: Extract Unified Design System"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 使用所有截图作为输入,提取单一设计系统
images_glob = f"{base_path}/screenshots/*.{{png,jpg,jpeg,webp}}"
# 构建extraction prompt
IF --prompt:
user_guidance = {--prompt}
extraction_prompt = f"Extract a single, high-fidelity design system that accurately imitates the visual style from the '{primary_target}' page. Use other screenshots for component consistency. User guidance: {user_guidance}"
ELSE:
extraction_prompt = f"Extract a single, high-fidelity design system that accurately imitates the visual style from the '{primary_target}' page. Use other screenshots to ensure component and pattern consistency across all pages."
# 调用extract命令imitate模式单变体
extract_command = f"/workflow:ui-design:extract --base-path \"{base_path}\" --images \"{images_glob}\" --prompt \"{extraction_prompt}\" --mode imitate --variants 1"
REPORT: "Calling extract command..."
REPORT: f" Mode: imitate (high-fidelity single style)"
REPORT: f" Primary source: '{primary_target}'"
REPORT: f" Images: {images_glob}"
TRY:
SlashCommand(extract_command)
CATCH error:
ERROR: "Style extraction failed: {error}"
ERROR: "Cannot proceed without design system"
EXIT 1
# extract输出到: {base_path}/style-extraction/style-cards.json
# 验证提取结果
style_cards_path = "{base_path}/style-extraction/style-cards.json"
IF NOT exists(style_cards_path):
ERROR: "extract command did not generate style-cards.json"
ERROR: "Expected: {style_cards_path}"
EXIT 1
style_cards = Read(style_cards_path)
IF len(style_cards.style_cards) != 1:
ERROR: "Expected single variant in imitate mode, got {len(style_cards.style_cards)}"
EXIT 1
extracted_style = style_cards.style_cards[0]
REPORT: ""
REPORT: "✅ Phase 2 complete:"
REPORT: " Style: '{extracted_style.name}'"
REPORT: " Philosophy: {extracted_style.design_philosophy}"
REPORT: " Tokens: {count_tokens(extracted_style.proposed_tokens)} proposed tokens"
TodoWrite(mark_completed: "Extract unified design system",
mark_in_progress: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation")
```
### Phase 3: Token处理条件性Consolidate
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 3: Token Processing"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
IF refine_tokens_mode:
# 路径A完整consolidate生产级质量
REPORT: "🔧 Using full consolidate for production-ready tokens"
REPORT: " Benefits:"
REPORT: " • Philosophy-driven token refinement"
REPORT: " • WCAG AA accessibility validation"
REPORT: " • Complete design system documentation"
REPORT: " • Token gap filling and consistency checks"
REPORT: ""
consolidate_command = f"/workflow:ui-design:consolidate --base-path \"{base_path}\" --variants 1"
REPORT: f"Calling consolidate command..."
TRY:
SlashCommand(consolidate_command)
CATCH error:
ERROR: "Token consolidation failed: {error}"
ERROR: "Cannot proceed without refined tokens"
EXIT 1
# consolidate输出到: {base_path}/style-consolidation/style-1/design-tokens.json
tokens_path = "{base_path}/style-consolidation/style-1/design-tokens.json"
IF NOT exists(tokens_path):
ERROR: "consolidate command did not generate design-tokens.json"
ERROR: "Expected: {tokens_path}"
EXIT 1
REPORT: ""
REPORT: "✅ Full consolidate complete"
REPORT: " Output: style-consolidation/style-1/"
REPORT: " Quality: Production-ready"
token_quality = "production-ready (consolidated)"
time_spent_estimate = "~60s"
ELSE:
# 路径BFast Token Adaptation快速路径
REPORT: "⚡ Fast token adaptation (skipping consolidate for speed)"
REPORT: " Note: Using proposed tokens from extraction phase"
REPORT: " For production quality, re-run with --refine-tokens flag"
REPORT: ""
# 直接复制proposed_tokens到consolidation目录
style_cards = Read("{base_path}/style-extraction/style-cards.json")
proposed_tokens = style_cards.style_cards[0].proposed_tokens
# 创建目录并写入tokens
consolidation_dir = "{base_path}/style-consolidation/style-1"
Bash(mkdir -p "{consolidation_dir}")
tokens_path = f"{consolidation_dir}/design-tokens.json"
Write(tokens_path, JSON.stringify(proposed_tokens, null, 2))
# 创建简化style guide
variant = style_cards.style_cards[0]
simple_guide = f"""# Design System: {variant.name}
## Design Philosophy
{variant.design_philosophy}
## Description
{variant.description}
## Design Tokens
All tokens in `design-tokens.json` follow OKLCH color space.
**Note**: Generated in fast-track imitate mode using proposed tokens from extraction.
For production-ready quality with philosophy-driven refinement, re-run with `--refine-tokens` flag.
## Color Preview
- Primary: {variant.preview.primary if variant.preview else "N/A"}
- Background: {variant.preview.background if variant.preview else "N/A"}
## Typography Preview
- Heading Font: {variant.preview.font_heading if variant.preview else "N/A"}
## Token Categories
{list_token_categories(proposed_tokens)}
"""
Write(f"{consolidation_dir}/style-guide.md", simple_guide)
REPORT: "✅ Fast adaptation complete (~2s vs ~60s with consolidate)"
REPORT: " Output: style-consolidation/style-1/"
REPORT: " Quality: Proposed (not refined)"
REPORT: " Time saved: ~30-60s"
token_quality = "proposed (fast-track)"
time_spent_estimate = "~2s"
REPORT: ""
REPORT: "Token processing summary:"
REPORT: " Path: {refine_tokens_mode ? 'Full consolidate' : 'Fast adaptation'}"
REPORT: " Quality: {token_quality}"
REPORT: " Time: {time_spent_estimate}"
TodoWrite(mark_completed: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation",
mark_in_progress: f"Generate UI for {len(target_names)} targets")
```
### Phase 4: 批量UI生成
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 4: Batch UI Generation"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# 构建targets字符串
targets_string = ",".join(target_names)
# 调用generate-v2智能token源检测会自动选择tokens
generate_command = f"/workflow:ui-design:generate-v2 --base-path \"{base_path}\" --targets \"{targets_string}\" --target-type page --style-variants 1 --layout-variants 1"
REPORT: "Calling generate-v2 command..."
REPORT: f" Targets: {targets_string}"
REPORT: f" Configuration: 1 style × 1 layout × {len(target_names)} pages"
REPORT: f" Token source: generate-v2 will auto-detect ({token_quality})"
TRY:
SlashCommand(generate_command)
CATCH error:
ERROR: "UI generation failed: {error}"
ERROR: "Design tokens may be invalid"
EXIT 1
# generate-v2输出到: {base_path}/prototypes/{target}-style-1-layout-1.html
# 验证生成结果
prototypes_dir = "{base_path}/prototypes"
generated_html_files = Glob(f"{prototypes_dir}/*-style-1-layout-1.html")
generated_count = len(generated_html_files)
REPORT: ""
REPORT: "✅ Phase 4 complete:"
REPORT: " Generated: {generated_count} HTML prototypes"
REPORT: " Targets: {', '.join(target_names)}"
REPORT: " Output: {prototypes_dir}/"
IF generated_count < len(target_names):
WARN: " ⚠️ Expected {len(target_names)} prototypes, generated {generated_count}"
WARN: " Some targets may have failed - check generate-v2 output"
TodoWrite(mark_completed: f"Generate UI for {len(target_names)} targets",
mark_in_progress: session_id ? "Integrate design system" : "Standalone completion")
```
### Phase 5: 设计系统集成
```bash
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "🚀 Phase 5: Design System Integration"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
IF session_id:
REPORT: "Integrating design system into session {session_id}..."
update_command = f"/workflow:ui-design:update --session {session_id}"
TRY:
SlashCommand(update_command)
CATCH error:
WARN: "Design system integration failed: {error}"
WARN: "Prototypes are still available at {base_path}/prototypes/"
# 不终止因为prototypes已经生成
REPORT: "✅ Design system integrated into session {session_id}"
ELSE:
REPORT: " Standalone mode: Skipping integration"
REPORT: " Prototypes available at: {base_path}/prototypes/"
REPORT: " To integrate later:"
REPORT: " 1. Create a workflow session"
REPORT: " 2. Copy design-tokens.json to session artifacts"
# 更新元数据
metadata = Read("{base_path}/.run-metadata.json")
metadata.status = "completed"
metadata.completion_time = current_timestamp()
metadata.outputs = {
"screenshots": f"{base_path}/screenshots/",
"style_system": f"{base_path}/style-consolidation/style-1/",
"prototypes": f"{base_path}/prototypes/",
"token_quality": token_quality,
"captured_count": captured_count,
"generated_count": generated_count
}
Write("{base_path}/.run-metadata.json", JSON.stringify(metadata, null, 2))
TodoWrite(mark_completed: session_id ? "Integrate design system" : "Standalone completion")
```
### Phase 6: 完成报告
```javascript
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "completed", activeForm: "Initializing"},
{content: f"Batch screenshot capture ({len(target_names)} targets)", status: "completed", activeForm: "Capturing"},
{content: "Extract unified design system", status: "completed", activeForm: "Extracting"},
{content: refine_tokens_mode ? "Refine design tokens via consolidate" : "Fast token adaptation", status: "completed", activeForm: "Processing"},
{content: f"Generate UI for {len(target_names)} targets", status: "completed", activeForm: "Generating"},
{content: session_id ? "Integrate design system" : "Standalone completion", status: "completed", activeForm: "Completing"}
]});
```
**Completion Message**:
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ UI Design Imitate-Auto V3 Complete!
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
━━━ 📊 Workflow Summary ━━━
Mode: Batch Multi-Page Replication
Session: {session_id or "standalone"}
Run ID: {run_id}
Phase 1 - Screenshot Capture: ✅ {captured_count}/{total_requested} screenshots
{IF captured_count < total_requested: f"⚠️ {total_requested - captured_count} missing" ELSE: "All targets captured"}
Phase 2 - Style Extraction: ✅ Single unified design system
Style: {extracted_style.name}
Philosophy: {extracted_style.design_philosophy[:80]}...
Phase 3 - Token Processing: ✅ {token_quality}
{IF refine_tokens_mode:
"Full consolidate (~60s)"
"Quality: Production-ready with philosophy-driven refinement"
ELSE:
"Fast adaptation (~2s, saved ~30-60s)"
"Quality: Proposed tokens (for production, use --refine-tokens)"
}
Phase 4 - UI Generation: ✅ {generated_count} pages generated
Targets: {', '.join(target_names)}
Configuration: 1 style × 1 layout × {generated_count} pages
Phase 5 - Integration: {IF session_id: "✅ Integrated into session" ELSE: "⏭️ Standalone mode"}
━━━ 📂 Output Structure ━━━
{base_path}/
├── screenshots/ # {captured_count} screenshots
│ ├── {target1}.png
│ ├── {target2}.png
│ └── capture-metadata.json
├── style-extraction/ # Design analysis
│ └── style-cards.json
├── style-consolidation/ # {token_quality}
│ └── style-1/
│ ├── design-tokens.json
│ └── style-guide.md
└── prototypes/ # {generated_count} HTML/CSS files
├── {target1}-style-1-layout-1.html + .css
├── {target2}-style-1-layout-1.html + .css
├── compare.html # Interactive preview
└── index.html # Quick navigation
━━━ ⚡ Performance ━━━
Total workflow time: ~{estimate_total_time()} minutes
Screenshot capture: ~{capture_time}
Style extraction: ~{extract_time}
Token processing: ~{token_processing_time}
UI generation: ~{generate_time}
vs imitate-auto v1: ✅ Batch support ({len(target_names)} pages vs 1 page limit)
vs explore-auto: ✅ ~2-3× faster (single style focus{" + skipped consolidate" if not refine_tokens_mode else ""})
━━━ 🌐 Next Steps ━━━
1. Preview prototypes:
• Interactive matrix: Open {base_path}/prototypes/compare.html
• Quick navigation: Open {base_path}/prototypes/index.html
{IF session_id:
2. Create implementation tasks:
/workflow:plan --session {session_id}
3. Generate tests (if needed):
/workflow:test-gen {session_id}
ELSE:
2. To integrate into a workflow session:
• Create session: /workflow:session:start
• Copy design-tokens.json to session artifacts
3. Explore prototypes in {base_path}/prototypes/ directory
}
{IF NOT refine_tokens_mode:
💡 Production Quality Tip:
Fast-track mode used proposed tokens for speed.
For production-ready quality with full token refinement:
/workflow:ui-design:imitate-auto-v3 --url-map "{url_map_command_string}" --refine-tokens {f"--session {session_id}" if session_id else ""}
}
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```
## TodoWrite Pattern
```javascript
// Initialize (Phase 0)
TodoWrite({todos: [
{content: "Initialize and parse url-map", status: "in_progress", activeForm: "Initializing"},
{content: "Batch screenshot capture", status: "pending", activeForm: "Capturing screenshots"},
{content: "Extract unified design system", status: "pending", activeForm: "Extracting style"},
{content: refine_tokens ? "Refine tokens via consolidate" : "Fast token adaptation", status: "pending", activeForm: "Processing tokens"},
{content: "Generate UI for all targets", status: "pending", activeForm: "Generating UI"},
{content: "Integrate design system", status: "pending", activeForm: "Integrating"}
]})
// Update after each phase: Mark current completed, next in_progress
```
## Error Handling
### Pre-execution Checks
- **url-map format validation**: Clear error message with format example
- **Empty url-map**: Error and exit
- **Invalid target names**: Regex validation with suggestions
### Phase-Specific Errors
- **Screenshot capture failure (Phase 1)**:
- If total_captured == 0: Terminate workflow
- If partial failure: Warn but continue with available screenshots
- **Style extraction failure (Phase 2)**:
- If extract fails: Terminate with clear error
- If style-cards.json missing: Terminate with debugging info
- **Token processing failure (Phase 3)**:
- Consolidate mode: Terminate if consolidate fails
- Fast mode: Validate proposed_tokens exist before copying
- **UI generation failure (Phase 4)**:
- If generate-v2 fails: Terminate with error
- If generated_count < target_count: Warn but proceed
- **Integration failure (Phase 5)**:
- Non-blocking: Warn but don't terminate
- Prototypes already available
### Recovery Strategies
- **Partial screenshot failure**: Continue with available screenshots, list missing in warning
- **Generate failure**: Report specific target failures, user can re-generate individually
- **Integration failure**: Prototypes still usable, can integrate manually
## Integration Points
- **Input**: `--url-map` (multiple target:url pairs) + optional `--session`, `--refine-tokens`, `--prompt`
- **Output**: Complete design system in `{base_path}/` (screenshots, style-extraction, style-consolidation, prototypes)
- **Sub-commands Called**:
1. `/workflow:ui-design:capture` (Phase 1)
2. `/workflow:ui-design:extract` (Phase 2)
3. `/workflow:ui-design:consolidate` (Phase 3, conditional)
4. `/workflow:ui-design:generate-v2` (Phase 4)
5. `/workflow:ui-design:update` (Phase 5, if --session)
- **Deprecates**: `imitate-auto.md` (v1, single URL only)

File diff suppressed because it is too large Load Diff