feat: add imitate-auto workflow for rapid UI design replication

- Introduced a new command `/workflow:ui-design:imitate-auto` for imitating UI designs from URLs or images.
- Streamlined execution model with 5 phases: initialization, screenshot capture, style extraction, token adaptation, and prototype generation.
- Emphasized single style and layout generation, bypassing the consolidate step for improved speed.
- Implemented automated screenshot capture with fallback to manual input if necessary.
- Enhanced error handling for missing references and screenshot failures.
- Provided detailed documentation and examples for usage and execution flows.
This commit is contained in:
catlog22
2025-10-09 14:38:35 +08:00
parent 76fc10c2f9
commit 561a04c193
3 changed files with 785 additions and 63 deletions

View File

@@ -1,13 +1,13 @@
---
name: auto
description: Fully autonomous UI design workflow with style extraction, consolidation, prototype generation (3×3 matrix), and design system integration
usage: /workflow:ui-design:auto [--prompt "<desc>"] [--images "<glob>"] [--pages "<list>"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
name: explore-auto
description: Exploratory UI design workflow - Generate and compare multiple style × layout combinations (3×3 matrix exploration)
usage: /workflow:ui-design:explore-auto [--prompt "<desc>"] [--images "<glob>"] [--pages "<list>"] [--session <id>] [--style-variants <count>] [--layout-variants <count>] [--batch-plan]
argument-hint: "[--prompt \"Modern SaaS with 3 styles\"] [--images \"refs/*.png\"] [--pages \"dashboard,auth\"] [--session WFS-xxx] [--style-variants 3] [--layout-variants 3]"
examples:
- /workflow:ui-design:auto --prompt "Generate 3 style variants for modern blog: home, article, author"
- /workflow:ui-design:auto --prompt "SaaS dashboard and settings with 2 layout options"
- /workflow:ui-design:auto --images "refs/*.png" --prompt "E-commerce: home, product, cart" --style-variants 3 --layout-variants 3
- /workflow:ui-design:auto --session WFS-auth --images "refs/*.png"
- /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"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*), Task(conceptual-planning-agent)
---

View File

@@ -110,46 +110,59 @@ IF --session:
synthesis_spec = Read(.workflow/WFS-{session}/.brainstorming/synthesis-specification.md)
```
### Phase 2: Matrix UI Generation (Parallel, Layout-Based)
Execute parallel agents to generate `style_variants × layout_variants × pages` prototypes.
Each agent handles ONE layout strategy across MULTIPLE styles (batched to max 8 styles per agent).
### Phase 2: Optimized Matrix UI Generation (Layered, Template-Based)
**Strategy**: Decouple HTML structure from CSS styling to eliminate redundancy.
- **Layer 1**: Generate `L × P` layout templates (HTML structure + structural CSS)
- **Layer 2**: Instantiate `S × L × P` final prototypes via fast file operations
**Performance**: Reduces core generation tasks from `O(S×L×P)` to `O(L×P)`**`S` times faster**
---
#### Phase 2a: Layout Template Generation (Parallel Agent Execution)
Generate style-agnostic layout templates for each `{page} × {layout}` combination.
Total agent tasks: `layout_variants × len(page_list)`
```bash
# Create output directory
# Create template directory
CREATE: {base_path}/prototypes/_templates/
CREATE: {base_path}/prototypes/
# Calculate style batches (max 8 styles per agent)
batch_size = 8
all_style_ids = range(1, style_variants + 1)
style_batches = split_into_chunks(all_style_ids, batch_size) # e.g., [[1-8], [9-16]]
# Launch layout_variants × num_batches parallel tasks
# Launch layout_variants × page_list parallel tasks
FOR layout_id IN range(1, layout_variants + 1):
FOR style_batch IN style_batches:
FOR page IN page_list:
Task(conceptual-planning-agent): "
[UI_GENERATION_MATRIX_BATCH]
[UI_LAYOUT_TEMPLATE_GENERATION]
Generate prototypes for layout-{layout_id} across a batch of styles.
Generate a **style-agnostic** layout template for a specific page and layout strategy.
## Context
LAYOUT_ID: {layout_id}
STYLE_IDS_BATCH: {style_batch} # e.g., [1, 2, 3, 4, 5, 6, 7, 8]
PAGES: {page_list}
PAGE: {page}
BASE_PATH: {base_path}
## Input Files
For each style_id in your batch, you MUST load its corresponding files:
- Design Tokens: {base_path}/style-consolidation/style-{style_id}/design-tokens.json
- Style Guide: {base_path}/style-consolidation/style-{style_id}/style-guide.md
{IF --session: - Requirements: .workflow/WFS-{session}/.brainstorming/synthesis-specification.md}
## Task
For each style_id in {style_batch}:
For each page in [{page_list}]:
Generate the prototype files for the specific combination:
- {page}-style-{style_id}-layout-{layout_id}.html (semantic HTML5)
- {page}-style-{style_id}-layout-{layout_id}.css (token-driven, no hardcoded values)
- {page}-style-{style_id}-layout-{layout_id}-notes.md (implementation notes)
Generate TWO files that work together as a reusable template:
**File 1**: `{page}-layout-{layout_id}.html`
- Semantic HTML5 structure WITHOUT any style-specific values
- Use placeholder links for stylesheets:
```html
<link rel=\"stylesheet\" href=\"{{STRUCTURAL_CSS}}\">
<link rel=\"stylesheet\" href=\"{{TOKEN_CSS}}\">
```
- Include all semantic elements, ARIA attributes, and responsive structure
- NO inline styles, NO hardcoded colors/fonts/spacing
**File 2**: `{page}-layout-{layout_id}.css`
- Structural CSS rules using CSS variable references
- ALL values MUST use `var()` functions (e.g., `background-color: var(--color-surface-background);`)
- NO hardcoded values (e.g., #4F46E5, 16px, Arial)
- BEM or semantic class naming
- Mobile-first responsive design using token-based breakpoints
## Layout Diversity Strategy
You are responsible for Layout {layout_id}. Apply this strategy CONSISTENTLY to all styles in your batch.
@@ -202,19 +215,110 @@ FOR layout_id IN range(1, layout_variants + 1):
- Desktop: var(--breakpoint-lg)+ (full layout)
## Output Location
{base_path}/prototypes/
{base_path}/prototypes/_templates/
## Deliverables
For each page-style-layout combination in your assigned batch:
1. HTML file with token-driven structure
2. CSS file with custom property references
3. Notes file with implementation details and layout rationale
TWO template files for the '{page}-layout-{layout_id}' combination:
1. `{page}-layout-{layout_id}.html` - Reusable HTML structure with CSS placeholders
2. `{page}-layout-{layout_id}.css` - Structural CSS using var() for all values
Total files to generate: {len(page_list) * len(style_batch) * 3}
IMPORTANT: These templates will be reused across ALL styles, so they must be
completely style-agnostic (no hardcoded colors, fonts, or spacing).
"
# Wait for all {layout_variants * len(style_batches)} parallel tasks to complete
# Total prototypes: {style_variants * layout_variants * len(page_list)}
# Wait for all {layout_variants × len(page_list)} parallel tasks to complete
# Generated templates: L × P (significantly fewer than the old S × L × P approach)
REPORT: "✅ Phase 2a complete: Generated {layout_variants * len(page_list)} layout templates"
```
---
#### Phase 2b: Prototype Instantiation (Fast File Operations)
Create final `S × L × P` prototypes by copying templates and injecting style-specific CSS links.
This phase uses **fast file operations** instead of expensive Agent calls.
```bash
REPORT: "🚀 Phase 2b: Instantiating prototypes from templates..."
# Ensure design tokens are converted to CSS for each style
FOR style_id IN range(1, style_variants + 1):
tokens_json = Read({base_path}/style-consolidation/style-{style_id}/design-tokens.json)
tokens_css = convert_json_to_css_variables(tokens_json)
# Write tokens.css for this style
Write({base_path}/style-consolidation/style-{style_id}/tokens.css, tokens_css)
# Instantiate S × L × P final prototypes via file copying and placeholder replacement
Bash(
cd {base_path}/prototypes/
# For each style, layout, and page combination...
for s in $(seq 1 {style_variants}); do
for l in $(seq 1 {layout_variants}); do
for p in {' '.join(page_list)}; do
# Define file names
TEMPLATE_HTML="_templates/${p}-layout-${l}.html"
STRUCTURAL_CSS="./_templates/${p}-layout-${l}.css"
TOKEN_CSS="../../style-consolidation/style-${s}/tokens.css"
OUTPUT_HTML="${p}-style-${s}-layout-${l}.html"
# 1. Copy the HTML template
cp "${TEMPLATE_HTML}" "${OUTPUT_HTML}"
# 2. Replace CSS placeholders with actual paths
# Using | delimiter for sed to handle paths with slashes
sed -i "s|{{STRUCTURAL_CSS}}|${STRUCTURAL_CSS}|g" "${OUTPUT_HTML}"
sed -i "s|{{TOKEN_CSS}}|${TOKEN_CSS}|g" "${OUTPUT_HTML}"
# 3. Create implementation notes file
cat > "${p}-style-${s}-layout-${l}-notes.md" <<EOF
# Implementation Notes: ${p}-style-${s}-layout-${l}
## Generation Details
- **Template**: ${TEMPLATE_HTML}
- **Structural CSS**: ${STRUCTURAL_CSS}
- **Style Tokens**: ${TOKEN_CSS}
- **Layout Strategy**: Layout ${l}
- **Style Variant**: Style ${s}
## Template Reuse
This prototype was generated from a shared layout template to ensure consistency
across all style variants. The HTML structure is identical for all ${p}-layout-${l}
prototypes, with only the design tokens (colors, fonts, spacing) varying.
## Design System Reference
Refer to \`../../style-consolidation/style-${s}/style-guide.md\` for:
- Design philosophy
- Token usage guidelines
- Component patterns
- Accessibility requirements
## Customization
To modify this prototype:
1. Edit the layout template: \`${TEMPLATE_HTML}\` (affects all styles)
2. Edit the structural CSS: \`${STRUCTURAL_CSS}\` (affects all styles)
3. Edit design tokens: \`${TOKEN_CSS}\` (affects only this style variant)
EOF
done
done
done
)
REPORT: "✅ Phase 2b complete: Instantiated {style_variants * layout_variants * len(page_list)} final prototypes"
REPORT: " Performance: {style_variants}× faster than original approach"
```
**Performance Comparison**:
| Metric | Before (S×L×P Agent calls) | After (L×P Agent calls + File Ops) |
|--------|----------------------------|-----------------------------------|
| Agent Tasks | `S × L × P` | `L × P` |
| Example (3×3×3) | 27 Agent calls | 9 Agent calls |
| Speed Improvement | Baseline | **3× faster** (S times) |
| Resource Usage | High (creative generation for each combo) | Optimized (creative only for templates) |
```
### Phase 3: Generate Preview Files
@@ -500,7 +604,8 @@ Run `/workflow:ui-design:update` once all issues are resolved.
TodoWrite({
todos: [
{content: "Resolve paths and load design systems", status: "completed", activeForm: "Loading design systems"},
{content: `Generate ${style_variants}×${layout_variants}×${page_list.length} prototypes`, status: "completed", activeForm: "Generating matrix prototypes"},
{content: `Generate ${layout_variants}×${page_list.length} layout templates (optimized)`, status: "completed", activeForm: "Generating layout templates"},
{content: `Instantiate ${style_variants}×${layout_variants}×${page_list.length} final prototypes`, status: "completed", activeForm: "Instantiating prototypes"},
{content: "Generate interactive preview files", status: "completed", activeForm: "Generating preview"}
]
});
@@ -508,24 +613,29 @@ TodoWrite({
**Completion Message**:
```
✅ Matrix UI generation complete!
Optimized Matrix UI generation complete!
Configuration:
- Style Variants: {style_variants}
- Layout Options: {layout_variants}
- Layout Variants: {layout_variants}
- Pages: {page_list}
- Total Prototypes: {style_variants * layout_variants * len(page_list)}
Generated Files:
{FOR style_id IN range(1, style_variants + 1):
{FOR layout_id IN range(1, layout_variants + 1):
{FOR page IN page_list:
- {page}-style-{style_id}-layout-{layout_id}.html
}
}
}
Performance Metrics:
- Layout Templates Generated: {layout_variants * len(page_list)} (Agent tasks)
- Prototypes Instantiated: {style_variants * layout_variants * len(page_list)} (file operations)
- Speed Improvement: {style_variants}× faster than previous approach
- Resource Efficiency: {100 * (1 - 1/style_variants)}% reduction in Agent calls
📂 Location: {base_path}/prototypes/
Generated Structure:
📂 {base_path}/prototypes/
├── _templates/
│ ├── {page}-layout-{1..L}.html ({layout_variants * len(page_list)} templates)
│ └── {page}-layout-{1..L}.css ({layout_variants * len(page_list)} structural CSS)
├── {page}-style-{s}-layout-{l}.html ({style_variants * layout_variants * len(page_list)} final prototypes)
├── {page}-style-{s}-layout-{l}-notes.md
├── compare.html (interactive matrix visualization)
└── index.html (quick navigation)
🌐 Interactive Preview:
1. Matrix View: Open compare.html (recommended)
@@ -537,24 +647,47 @@ Features:
- Zoom controls and fullscreen mode
- Selection export for implementation
- Per-page comparison
- Template-based consistency across style variants
Technical Highlights:
- ✅ Decoupled HTML structure from CSS styling
- ✅ Reusable layout templates (affects all styles uniformly)
- ✅ Dynamic style injection via CSS custom properties
- ✅ Significantly reduced generation time
Next: /workflow:ui-design:update {--session flag if applicable}
Note: When called from /workflow:ui-design:auto, design-update is triggered automatically.
```
## Output Structure
## Output Structure (Optimized, Template-Based)
```
{base_path}/prototypes/
├── _templates/ # Reusable layout templates (NEW)
│ ├── {page}-layout-1.html # Style-agnostic HTML structure
│ ├── {page}-layout-1.css # Structural CSS with var() references
│ ├── {page}-layout-2.html
│ ├── {page}-layout-2.css
│ └── ... (L × P templates total)
├── compare.html # Interactive matrix visualization
├── index.html # Simple navigation page
├── PREVIEW.md # Preview instructions
├── design-tokens.css # CSS custom properties fallback
├── {page}-style-{s}-layout-{l}.html # Matrix prototype files
├── {page}-style-{s}-layout-{l}.css
── {page}-style-{s}-layout-{l}-notes.md
└── ... (all style×layout×page combinations)
├── {page}-style-{s}-layout-{l}.html # Final prototypes (copied from templates)
├── {page}-style-{s}-layout-{l}-notes.md # Implementation notes (auto-generated)
── ... (S × L × P total final files)
{base_path}/style-consolidation/
├── style-1/
│ ├── design-tokens.json
│ ├── tokens.css # NEW: CSS variables for style-1
│ └── style-guide.md
├── style-2/
│ ├── design-tokens.json
│ ├── tokens.css # NEW: CSS variables for style-2
│ └── style-guide.md
└── ...
```
## Error Handling
@@ -576,11 +709,35 @@ After generation, ensure:
## Key Features
1. **Matrix-Only Mode**: Simplified, focused workflow
2. **Parallel Generation**: All style×layout combinations in parallel
3. **Interactive Visualization**: Full-featured compare.html from template
4. **Per-Style Tokens**: Each prototype references its style's design system
5. **Systematic Exploration**: Consistent layout strategies across all styles
1. **Optimized Template-Based Architecture** (NEW)
- Decouples HTML structure from CSS styling
- Generates `L × P` reusable templates instead of `S × L × P` unique files
- **`S` times faster** than previous approach (typically 3× faster)
2. **Two-Layer Generation Strategy**
- **Layer 1**: Agent-driven creative generation of layout templates
- **Layer 2**: Fast file operations for prototype instantiation
- Reduces expensive Agent calls by ~67% (for S=3)
3. **Consistent Cross-Style Layouts**
- Same layout structure applied uniformly across all style variants
- Easier to compare styles directly (HTML structure is identical)
- Simplified maintenance (edit template once, affects all styles)
4. **Dynamic Style Injection**
- CSS custom properties enable runtime style switching
- Each style variant has its own `tokens.css` file
- Clean separation of structure and aesthetics
5. **Interactive Visualization**
- Full-featured compare.html from template
- Matrix grid view with synchronized scrolling
- Per-style design system references
6. **Production-Ready Output**
- Semantic HTML5 and ARIA attributes
- Mobile-first responsive design
- Token-driven styling (no hardcoded values)
## Integration Points
- **Input**: Per-style design-tokens.json from `/workflow:ui-design:consolidate --keep-separate`

View File

@@ -0,0 +1,565 @@
---
name: imitate-auto
description: Imitation-focused UI design workflow - Rapidly replicate a single design style from URL or images (skip exploration, direct to implementation)
usage: /workflow:ui-design:imitate-auto [--url "<url>"] [--images "<glob>"] [--prompt "<desc>"] [--pages "<list>"] [--session <id>]
argument-hint: "[--url \"https://example.com\"] [--images \"refs/*.png\"] [--prompt \"Imitate dark mode style\"] [--pages \"dashboard,settings\"]"
examples:
- /workflow:ui-design:imitate-auto --url "https://linear.app" --pages "home,features,pricing"
- /workflow:ui-design:imitate-auto --images "refs/design.png" --prompt "Imitate this minimalist design for dashboard and settings"
- /workflow:ui-design:imitate-auto --url "https://stripe.com" --session WFS-payment
- /workflow:ui-design:imitate-auto --images "refs/*.png" --pages "home"
allowed-tools: SlashCommand(*), TodoWrite(*), Read(*), Bash(*), Glob(*), Write(*)
---
# UI Design Imitate-Auto Workflow Command
## Overview
Fast-track UI design workflow optimized for **imitating a single design style** from a reference source (URL or images). This command skips the exploration and consolidation phases, directly generating production-ready prototypes based on the provided reference.
## Core Philosophy
- **Imitation over Exploration**: Focus on replicating a specific design, not generating variants
- **Single Style**: Always generates one design system (no style matrix)
- **Single Layout**: Generates one layout per page (no layout exploration)
- **Speed Optimized**: Skips `consolidate` step, uses direct token extraction
- **Reference-Driven**: Requires URL or images as primary input source
## Execution Model - Streamlined Workflow
This workflow is optimized for speed and simplicity:
1. **User triggers**: `/workflow:ui-design:imitate-auto --url "..." --pages "..."`
2. **Phase 0 executes** (simplified initialization) → Auto-continues
3. **Phase 0.5 executes** (URL screenshot capture with auto-fallback) → Auto-continues
4. **Phase 1 executes** (single style extraction, forced --variants 1) → Auto-continues
5. **Phase 2 executes** (fast token adaptation, bypasses consolidate) → Auto-continues
6. **Phase 3 executes** (single prototype generation, forced 1×1 mode) → Auto-continues
7. **Phase 4 executes** (design integration) → Complete
**Performance**: ~2-3× faster than `explore-auto` for single-style scenarios
**Screenshot Automation**: Supports Playwright and Chrome DevTools with manual upload fallback
## Core Rules
1. **Start Immediately**: First action is `TodoWrite` initialization, second action is Phase 0 execution
2. **No Multi-Variant**: Always generates exactly 1 style × 1 layout × N pages
3. **Reference Required**: Must provide `--url` OR `--images` (at least one)
4. **Auto-Continue**: After each phase, automatically proceed to the next without pausing
5. **Track Progress**: Update `TodoWrite` after every phase completion
## Parameter Requirements
**Required Parameters** (at least one):
- `--url "<url>"`: Website URL to imitate (e.g., "https://linear.app")
- `--images "<glob_pattern>"`: Local reference images (e.g., "refs/*.png")
**Optional Parameters**:
- `--pages "<page_list>"`: Pages to generate (default: "home")
- `--session <session_id>"`: Workflow session ID for integration (optional, standalone if omitted)
- `--prompt "<description>"`: Additional design guidance (e.g., "Focus on dark mode", "Imitate card-based layout")
**Removed Parameters** (not supported):
- `--style-variants`: Always 1 (single style focus)
- `--layout-variants`: Always 1 (single layout focus)
- `--batch-plan`: Not supported in imitate mode
## 5-Phase Execution
### Phase 0: Simplified Initialization
```bash
# Generate run ID with timestamp
run_id = "run-$(date +%Y%m%d-%H%M%S)"
# Determine base path
IF --session:
session_id = {provided_session}
base_path = ".workflow/WFS-{session_id}/runs/${run_id}"
ELSE:
# Standalone mode: use scratchpad
session_id = "imitate-session-$(date +%Y%m%d-%H%M%S)"
base_path = ".workflow/.scratchpad/${session_id}/runs/${run_id}"
# Create run directory structure (simpler than explore-auto)
Bash(mkdir -p "${base_path}/.design/style-extraction")
Bash(mkdir -p "${base_path}/.design/style-consolidation/style-1")
Bash(mkdir -p "${base_path}/.design/prototypes")
# Initialize run metadata
Write({base_path}/.run-metadata.json):
{
"run_id": "${run_id}",
"session_id": "${session_id}",
"timestamp": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
"workflow": "ui-design:imitate-auto",
"mode": "single_style_imitation",
"parameters": {
"url": "${url_value}",
"images": "${images_pattern}",
"pages": "${inferred_page_list}",
"prompt": "${prompt_text}"
},
"status": "in_progress"
}
# Page inference (simplified, no interactive confirmation)
IF --pages provided:
page_list = split_and_clean({--pages value}, delimiters=[",", ";", "、"])
page_list = [p.strip().lower().replace(" ", "-") for p in page_list if p.strip()]
page_source = "explicit"
ELSE IF --prompt provided:
# Simple extraction from prompt
# Look for patterns like "for dashboard and settings" or "pages: home, about"
page_list = extract_pages_from_prompt(prompt_text)
page_source = "prompt_inferred"
IF NOT page_list:
page_list = ["home"]
page_source = "default"
ELSE:
page_list = ["home"]
page_source = "default"
# Validate page names
validated_pages = []
FOR page IN page_list:
cleaned_page = page.strip().lower().replace(" ", "-")
IF regex_match(cleaned_page, r"^[a-z0-9][a-z0-9_-]*$"):
validated_pages.append(cleaned_page)
IF NOT validated_pages:
validated_pages = ["home"]
REPORT: "📋 Imitate mode: Generating {len(validated_pages)} pages with single style"
REPORT: " Pages: {', '.join(validated_pages)}"
REPORT: " Reference: {url_value OR images_pattern}"
STORE: run_id, base_path, inferred_page_list = validated_pages
```
---
### Phase 0.5: URL Screenshot Capture (Auto-Fallback)
**Condition**: Only executes if `--url` is provided
**Purpose**: Automatically capture screenshots from the URL to ensure visual reference is available for style extraction. If automated capture fails, prompts user to provide manual screenshots.
**Execution**:
```bash
IF --url provided:
REPORT: "📸 Phase 0.5: Capturing screenshots from URL..."
# Create screenshots directory
screenshot_dir = "{base_path}/.design/screenshots"
Bash(mkdir -p "{screenshot_dir}")
# Try automated screenshot methods
screenshot_success = false
screenshot_files = []
# Method 1: Playwright CLI (preferred, if available)
TRY:
REPORT: " Attempting Playwright screenshot..."
Bash(
npx playwright screenshot "{url_value}" "{screenshot_dir}/full-page.png" --full-page --timeout 30000
)
screenshot_files.append("{screenshot_dir}/full-page.png")
screenshot_success = true
REPORT: " ✅ Playwright screenshot captured"
CATCH:
REPORT: " ⚠️ Playwright not available or failed"
# Method 2: Chrome DevTools Protocol (fallback)
IF NOT screenshot_success:
TRY:
REPORT: " Attempting Chrome headless screenshot..."
Bash(
google-chrome --headless --disable-gpu --screenshot="{screenshot_dir}/full-page.png" --window-size=1920,1080 "{url_value}"
)
screenshot_files.append("{screenshot_dir}/full-page.png")
screenshot_success = true
REPORT: " ✅ Chrome headless screenshot captured"
CATCH:
REPORT: " ⚠️ Chrome headless not available or failed"
# If both automated methods fail, prompt user for manual screenshot
IF NOT screenshot_success:
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "⚠️ AUTOMATED SCREENSHOT FAILED"
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
REPORT: "Unable to automatically capture screenshot from: {url_value}"
REPORT: ""
REPORT: "Please provide a manual screenshot:"
REPORT: " 1. Visit the URL in your browser: {url_value}"
REPORT: " 2. Take a full-page screenshot"
REPORT: " 3. Save it to: {screenshot_dir}/"
REPORT: ""
REPORT: "Options:"
REPORT: " • Type 'ready' when screenshot is saved"
REPORT: " • Type 'skip' to use URL analysis only (lower quality)"
REPORT: " • Type 'abort' to cancel the workflow"
REPORT: ""
REPORT: "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
# Wait for user input
user_response = WAIT_FOR_USER_INPUT()
IF user_response MATCHES r"^(ready|done|ok)$":
# Check if user provided screenshot
screenshot_files = Glob("{screenshot_dir}/*.{png,jpg,jpeg}")
IF screenshot_files:
screenshot_success = true
REPORT: "✅ Manual screenshot detected: {', '.join(screenshot_files)}"
ELSE:
REPORT: "❌ No screenshot found in {screenshot_dir}/"
REPORT: " Workflow will use URL analysis only (may result in lower quality)"
ELSE IF user_response MATCHES r"^skip$":
REPORT: "⏭️ Skipping screenshot, using URL analysis only"
screenshot_success = false
ELSE IF user_response MATCHES r"^abort$":
ERROR: "Workflow aborted by user"
EXIT
ELSE:
REPORT: "⚠️ Invalid input, proceeding with URL analysis only"
screenshot_success = false
# Store screenshot info for Phase 1
IF screenshot_success:
STORE: screenshot_mode = "with_screenshots"
STORE: screenshot_paths = screenshot_files
REPORT: "✅ Screenshot capture complete: {len(screenshot_files)} image(s)"
ELSE:
STORE: screenshot_mode = "url_only"
STORE: screenshot_paths = []
REPORT: " Proceeding with URL analysis only (no screenshots)"
ELSE:
# No URL provided, must use --images
STORE: screenshot_mode = "manual_images"
STORE: screenshot_paths = []
REPORT: " Using provided images (--images parameter)"
```
**Auto-Continue**: On completion, proceeds to Phase 1
---
### Phase 1: Single Style Extraction
**Command Construction**:
```bash
# Determine input flags based on screenshot capture results
IF screenshot_mode == "with_screenshots":
# Use captured screenshots instead of URL
screenshot_glob = "{base_path}/.design/screenshots/*.{png,jpg,jpeg}"
images_flag = "--images \"{screenshot_glob}\""
url_flag = ""
source_desc = "captured screenshots from {url_value}"
ELSE IF screenshot_mode == "url_only":
# Use URL directly (Claude can analyze URLs)
url_flag = "--url \"{url_value}\""
images_flag = ""
source_desc = "URL analysis of {url_value}"
ELSE IF screenshot_mode == "manual_images":
# Use user-provided images
images_flag = --images present ? "--images \"{image_glob}\"" : ""
url_flag = ""
source_desc = "user-provided images"
ELSE:
# Fallback
url_flag = --url present ? "--url \"{url_value}\"" : ""
images_flag = --images present ? "--images \"{image_glob}\"" : ""
source_desc = "provided references"
# Add user prompt if provided
prompt_flag = --prompt present ? "--prompt \"{prompt_text}\"" : ""
# Use run-scoped base path and FORCE --variants 1
run_base_flag = "--base-path \"{base_path}/.design\""
# Construct optimized extraction prompt for imitation
enhanced_prompt = "Extract a single, high-fidelity design system that accurately imitates the visual style from {source_desc}. {prompt_text}"
# Force single variant extraction
command = "/workflow:ui-design:extract {run_base_flag} {url_flag} {images_flag} --prompt \"{enhanced_prompt}\" --variants 1"
REPORT: "🚀 Executing Phase 1: Style Extraction"
REPORT: " Source: {source_desc}"
REPORT: " Mode: Single style (imitation-optimized)"
SlashCommand(command=command)
```
**Auto-Continue**: On completion, proceeds to Phase 2
---
### Phase 2: Fast Token Adaptation (Bypass Consolidate)
**Action**: Direct extraction of design tokens from the single style card, bypassing the heavy `consolidate` step
**Execution**:
```bash
REPORT: "🚀 Phase 2: Fast token adaptation (bypassing consolidate for speed)"
# Read the single style card from extraction output
style_cards = Read({base_path}/.design/style-extraction/style-cards.json)
style_card = style_cards.style_cards[0] # Only one card in imitate mode
# Extract components
design_tokens = style_card.proposed_tokens
philosophy = style_card.design_philosophy
style_name = style_card.name
# Create minimal design system structure (generate needs this)
# Write design-tokens.json directly from proposed_tokens
Write({base_path}/.design/style-consolidation/style-1/design-tokens.json, JSON.stringify(design_tokens, null, 2))
# Create minimal style-guide.md (simpler than consolidate output)
Write({base_path}/.design/style-consolidation/style-1/style-guide.md):
# Design System: {style_name}
## Design Philosophy
{philosophy}
## Description
{style_card.description}
## Design Tokens
All design tokens are defined in `design-tokens.json` and follow the OKLCH color space standard.
**Key Colors**:
- Primary: {design_tokens.colors.brand.primary}
- Background: {design_tokens.colors.surface.background}
- Text: {design_tokens.colors.text.primary}
**Typography**:
- Heading Font: {design_tokens.typography.font_family.heading}
- Body Font: {design_tokens.typography.font_family.body}
**Spacing Scale**: {design_tokens.spacing.keys().length} values
**Note**: This design system was generated in imitate mode, optimized for fast replication of the reference source.
# Create minimal tailwind.config.js (optional, for convenience)
Write({base_path}/.design/style-consolidation/style-1/tailwind.config.js):
module.exports = {
theme: {
extend: {
colors: ${JSON.stringify(design_tokens.colors, null, 6)},
fontFamily: ${JSON.stringify(design_tokens.typography.font_family, null, 6)},
spacing: ${JSON.stringify(design_tokens.spacing, null, 6)},
borderRadius: ${JSON.stringify(design_tokens.border_radius, null, 6)},
}
}
}
REPORT: "✅ Design tokens extracted and formatted"
REPORT: " Style: {style_name}"
REPORT: " Bypassed consolidate step for {performance_gain}× speed improvement"
```
**Auto-Continue**: On completion, proceeds to Phase 3
---
### Phase 3: Single Prototype Generation
**Command Construction**:
```bash
run_base_flag = "--base-path \"{base_path}/.design\""
pages_string = ",".join(inferred_page_list)
pages_flag = "--pages \"{pages_string}\""
# Force single style and single layout
command = "/workflow:ui-design:generate {run_base_flag} {pages_flag} --style-variants 1 --layout-variants 1"
REPORT: "🚀 Executing Phase 3: Generating {len(inferred_page_list)} prototype(s)"
REPORT: " Mode: Single style × Single layout (optimized for imitation)"
SlashCommand(command=command)
```
**Result**: Generates `1 × 1 × N` prototypes (where N = number of pages)
- File naming: `{page}-style-1-layout-1.html`
- Total prototypes: `len(inferred_page_list)`
**Auto-Continue**: On completion, proceeds to Phase 4
---
### Phase 4: Design System Integration
**Command Construction**:
```bash
IF --session:
session_flag = "--session {session_id}"
command = "/workflow:ui-design:update {session_flag}"
SlashCommand(command=command)
ELSE:
REPORT: " Standalone mode: Skipping design system integration (no session provided)"
REPORT: " Prototypes available at: {base_path}/.design/prototypes/"
```
**Completion**: Workflow is now complete
## TodoWrite Pattern
```javascript
// Initialize (before Phase 0)
TodoWrite({todos: [
{"content": "Initialize run directory and infer pages", "status": "in_progress", "activeForm": "Initializing"},
{"content": "Capture screenshots from URL (if provided)", "status": "pending", "activeForm": "Capturing screenshots"},
{"content": "Extract single design style from reference", "status": "pending", "activeForm": "Extracting style"},
{"content": "Adapt tokens (bypass consolidate)", "status": "pending", "activeForm": "Adapting tokens"},
{"content": "Generate single-style prototypes", "status": "pending", "activeForm": "Generating prototypes"},
{"content": "Integrate design system", "status": "pending", "activeForm": "Integrating design"}
]})
// Update after each phase...
```
## Error Handling
- **No reference source**: Error if neither `--url` nor `--images` provided
- **Screenshot capture failure**:
- Tries 2 automated methods in sequence: Playwright → Chrome DevTools
- Falls back to manual screenshot upload if both fail
- User can choose: upload manual screenshot, skip screenshots, or abort
- **Invalid URL**: Report URL fetch failure, suggest using `--images` instead
- **Missing images**: Report glob pattern error, suggest checking file paths
- **Token extraction failure**: Fallback to a minimal default design system
- **Playwright/Chrome not installed**: Gracefully prompts user to upload manual screenshot
## Key Differences from explore-auto
| Aspect | explore-auto | imitate-auto |
|--------|--------------|--------------|
| **Purpose** | Explore multiple design options | Replicate specific design |
| **Input** | Optional URL/images | **Required** URL or images |
| **Variants** | 1-5 styles × 1-5 layouts | Always 1 × 1 (single) |
| **Consolidate** | Full consolidation with validation | **Bypassed** (direct token extraction) |
| **Speed** | Baseline | **~2-3× faster** |
| **Output** | Design matrix (S×L×P prototypes) | Direct prototypes (1×1×P) |
| **Use Case** | Design exploration, need options | Fast prototyping, have reference |
## Performance Benefits
1. **Skipped consolidate**: Saves ~30-60s per run (most expensive phase)
2. **Single variant**: Reduces extraction complexity
3. **Direct token mapping**: Simple file operations vs AI synthesis
4. **Streamlined decisions**: No variant selection or confirmation needed
## Workflow Position
This workflow is ideal for:
- **MVP Development**: Quickly create UI based on a competitor or design reference
- **High-Fidelity Prototyping**: Convert designs to code rapidly
- **Design Replication**: Imitate specific visual styles from existing sites
- **Learning**: Study and recreate successful design patterns
**NOT ideal for**:
- Generating multiple design alternatives
- Design exploration without clear reference
- Creating completely novel designs
## Example Execution Flows
### Example 1: Imitate from URL (with Auto-Screenshot)
```bash
/workflow:ui-design:imitate-auto --url "https://linear.app" --pages "home,features,pricing"
# Execution:
# 0. Initialize: 3 pages identified
# 0.5. Screenshot: Playwright captures full-page screenshot of linear.app
# 1. Extract: Single style from captured screenshot
# 2. Adapt: Direct token extraction (~2s vs consolidate's ~45s)
# 3. Generate: 3 prototypes (home, features, pricing)
# 4. Complete
# Total time: ~2-3 minutes (vs 5-7 minutes with explore-auto)
# Screenshot: Automatically saved to .design/screenshots/
```
### Example 2: Imitate from Images with Guidance
```bash
/workflow:ui-design:imitate-auto --images "refs/dark-theme.png" --prompt "Focus on dark mode color palette" --pages "dashboard"
# Execution:
# 0. Initialize: 1 page (dashboard)
# 0.5. Screenshot: Skipped (using provided images)
# 1. Extract: Single style from image, dark mode emphasis
# 2. Adapt: Direct token extraction
# 3. Generate: 1 prototype (dashboard-style-1-layout-1.html)
# 4. Complete (standalone mode, no integration)
```
### Example 3: URL with Manual Screenshot Upload
```bash
/workflow:ui-design:imitate-auto --url "https://stripe.com/pricing" --pages "pricing"
# Execution:
# 0. Initialize: 1 page (pricing)
# 0.5. Screenshot:
# ⚠️ Playwright not available
# ⚠️ Chrome headless not available
# 📸 Prompting user to upload manual screenshot...
#
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# ⚠️ AUTOMATED SCREENSHOT FAILED
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# Please provide a manual screenshot:
# 1. Visit: https://stripe.com/pricing
# 2. Take a full-page screenshot
# 3. Save to: .design/screenshots/
#
# Options:
# • Type 'ready' when screenshot is saved
# • Type 'skip' to use URL analysis only
# • Type 'abort' to cancel
#
# User saves screenshot and types 'ready' → ✅ Workflow continues
# OR
# User types 'skip' → ⚠️ Uses URL analysis only
# 1. Extract: Single style from screenshot or URL
# 2. Adapt: Direct token extraction
# 3. Generate: 1 prototype
# 4. Complete
```
## Final Completion Message
```
✅ UI Design Imitation Complete!
Mode: Single Style Replication
Run ID: {run_id}
Session: {session_id or "standalone"}
Reference: {url OR images}
Phase 0 - Initialization: {page_count} pages prepared
Phase 0.5 - Screenshot Capture: {screenshot_status}
{IF screenshot_success: ✅ Screenshot captured via {method} (Playwright/Chrome/Manual)}
{ELSE: ⚠️ Using URL analysis only}
Phase 1 - Style Extraction: Single design style extracted
Phase 2 - Token Adaptation: Bypassed consolidate (⚡ {time_saved}s saved)
Phase 3 - Prototype Generation: {page_count} prototypes created
Phase 4 - Design Integration: {integrated OR "Standalone mode - No integration"}
📂 Output: {base_path}/.design/
├── style-extraction/style-cards.json (1 style card)
├── style-consolidation/style-1/ (design tokens)
└── prototypes/ ({page_count} HTML/CSS files)
🌐 Preview: Open {base_path}/.design/prototypes/index.html
Performance:
- Design system creation: ~{time}s (vs ~{consolidate_time}s with consolidate)
- Total workflow time: ~{total_time}s
- Speed improvement: ~{improvement}× faster than explore-auto
{IF session mode:
Next: /workflow:plan to create implementation tasks
}
{ELSE:
Prototypes ready for direct use at: {base_path}/.design/prototypes/
}
```