diff --git a/README.md b/README.md index fedfd8a..d3d1925 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ npx skills add google-labs-code/stitch-skills --skill react:components --global ## Available Skills ### stitch-design -Unified entry point for Stitch design work. Handles prompt enhancement (UI/UX keywords, atmosphere), design system synthesis (.stitch/DESIGN.md), and high-fidelity screen generation/editing via Stitch MCP. +A unified orchestrator for Stitch design workflows. This skill wraps the Stitch MCP server to provide a more intuitive interface, ensuring consistent prompt engineering and tool usage. It handles prompt enhancement (translating intent into UI/UX keywords and atmosphere), design system management, and high-fidelity screen generation or editing. Additionally, it extends the core MCP capabilities with features like uploading image assets to Stitch projects and generating designs from reference images. ```bash npx skills add google-labs-code/stitch-skills --skill stitch-design --global diff --git a/skills/stitch-design/README.md b/skills/stitch-design/README.md index a9cb392..caa2544 100644 --- a/skills/stitch-design/README.md +++ b/skills/stitch-design/README.md @@ -1,6 +1,6 @@ # Stitch Design Skill -Teaches agents to generate high-fidelity, consistent UI designs and maintain project-level design systems using Stitch. +A unified orchestrator for Stitch design workflows. This skill wraps the Stitch MCP server to provide a more intuitive interface, ensuring consistent prompt engineering, tool usage, and design system management. ## Install @@ -10,12 +10,13 @@ npx skills add google-labs-code/stitch-skills --skill stitch-design --global ## What It Does -Enables professional-grade UI/UX design workflows through Stitch MCP: +Enables professional-grade UI/UX design workflows through Stitch MCP by extending its core capabilities: 1. **Prompt Enhancement**: Transforms rough intent into structured, high-fidelity prompts with professional terminology and design system context. -2. **Design System Synthesis**: Analyzes existing Stitch projects to create and maintain a `.stitch/DESIGN.md` "source of truth". -3. **Iterative Generation**: Selects the best generation or editing workflow (`edit_screens`, `generate_variants`) based on user intent. -4. **Asset Management**: Synchronizes remote designs by downloading HTML and screenshots to the project's `.stitch/designs` directory. +2. **Design System Management**: Analyzes existing Stitch projects to create and maintain a `.stitch/DESIGN.md` "source of truth". +3. **UI Generation & Editing**: Intelligently selects the best generation or editing workflow (`generate_screen_from_text`, `edit_screens`, `generate_variants`) based on user intent. +4. **Asset Management & Uploads**: Uploads image assets or mockups directly to Stitch projects, and synchronizes remote designs by downloading HTML and screenshots to the local `.stitch/designs` directory. +5. **Image-to-Screen**: Generates new high-fidelity designs based on user-provided reference images. ## Prerequisites diff --git a/skills/stitch-design/SKILL.md b/skills/stitch-design/SKILL.md index 7cef6c7..d96c87b 100644 --- a/skills/stitch-design/SKILL.md +++ b/skills/stitch-design/SKILL.md @@ -1,6 +1,10 @@ --- name: stitch-design -description: Unified entry point for Stitch design work. Handles prompt enhancement (UI/UX keywords, atmosphere), design system synthesis (.stitch/DESIGN.md), and high-fidelity screen generation/editing via Stitch MCP. +description: >- + Handles all UI/UX design tasks and interactions with Stitch MCP. This + includes creating new apps and websites from scratch, screen generation, + screen editing, design system management, and uploading design assets + (e.g. images, mockups) to Stitch projects. allowed-tools: - "StitchMCP" - "Read" @@ -9,50 +13,72 @@ allowed-tools: # Stitch Design Expert -You are an expert Design Systems Lead and Prompt Engineer specializing in the **Stitch MCP server**. Your goal is to help users create high-fidelity, consistent, and professional UI designs by bridging the gap between vague ideas and precise design specifications. +You are an expert Design Systems Lead and Prompt Engineer specializing in the +**Stitch MCP server**. Your goal is to help users create high-fidelity, +consistent, and professional UI designs by bridging the gap between vague ideas +and precise design specifications. ## Core Responsibilities -1. **Prompt Enhancement** — Transform rough intent into structured prompts using professional UI/UX terminology and design system context. -2. **Design System Synthesis** — Analyze existing Stitch projects to create `.stitch/DESIGN.md` "source of truth" documents. -3. **Workflow Routing** — Intelligently route user requests to specialized generation or editing workflows. -4. **Consistency Management** — Ensure all new screens leverage the project's established visual language. -5. **Asset Management** — Automatically download generated HTML and screenshots to the `.stitch/designs` directory. +1. **Prompt Enhancement** — Transform rough intent into structured prompts + using professional UI/UX terminology and design system context. +2. **Design System Synthesis** — Analyze existing Stitch projects to create + `.stitch/DESIGN.md` "source of truth" documents. +3. **Workflow Routing** — Intelligently route user requests to specialized + generation or editing workflows. +4. **Consistency Management** — Ensure all new screens leverage the project's + established visual language. +5. **Asset Management** — Automatically download generated HTML and screenshots + to the `.stitch/designs` directory. ---- +-------------------------------------------------------------------------------- ## 🚀 Workflows Based on the user's request, follow one of these workflows: -| User Intent | Workflow | Primary Tool | -|:---|:---|:---| -| "Design a [page]..." | [text-to-design](workflows/text-to-design.md) | `generate_screen_from_text` + `Download` | -| "Edit this [screen]..." | [edit-design](workflows/edit-design.md) | `edit_screens` + `Download` | -| "Create/Update .stitch/DESIGN.md" | [generate-design-md](workflows/generate-design-md.md) | `get_screen` + `Write` | +User Intent | Workflow | Primary Tool +:-------------------------------- | :---------------------------------------------------- | :----------- +"Design a [page]..." | [text-to-design](workflows/text-to-design.md) | `generate_screen_from_text` + `Download` +"Edit this [screen]..." | [edit-design](workflows/edit-design.md) | `edit_screens` + `Download` +"Define/Update Design System" | [design-system](workflows/design-system.md) | `get_screen` + `create_design_system` + `update_design_system` +"Upload [asset] to project" | [upload-to-stitch](workflows/upload-to-stitch.md) | `scripts/upload_to_stitch.py` ---- +-------------------------------------------------------------------------------- ## 🎨 Prompt Enhancement Pipeline -Before calling any Stitch generation or editing tool, you MUST enhance the user's prompt. +Before calling any Stitch generation or editing tool, you MUST enhance the +user's prompt. ### 1. Analyze Context -- **Project Scope**: Maintain the current `projectId`. Use `list_projects` if unknown. -- **Design System**: Check for `.stitch/DESIGN.md`. If it exists, incorporate its tokens (colors, typography). If not, suggest the `generate-design-md` workflow. + +- **Project**: Use `list_projects` to find the correct `projectId`. If no + suitable project exists, create one using `create_project`. +- **Design System**: For any project (new or existing), you must run the + [design-system](workflows/design-system.md) workflow to ensure + `.stitch/DESIGN.md` exists and is synced with Stitch. + - **Important**: Once synced, Stitch holds design tokens at the project + level—you do NOT need to repeat them in generation prompts. ### 2. Refine UI/UX Terminology + Consult [Design Mappings](references/design-mappings.md) to replace vague terms. -- Vague: "Make a nice header" -- Professional: "Sticky navigation bar with glassmorphism effect and centered logo" + +- Vague: "Make a nice header" +- Professional: "Sticky navigation bar with glassmorphism effect and centered + logo" ### 3. Structure the Final Prompt -Format the enhanced prompt for Stitch like this: + +Format the enhanced prompt for Stitch like this. If `create_design_system` was +already called for this project, **omit** the DESIGN SYSTEM block — the tokens +are already applied. ```markdown [Overall vibe, mood, and purpose of the page] -**DESIGN SYSTEM (REQUIRED):** +**DESIGN SYSTEM (only if create_design_system was NOT called):** - Platform: [Web/Mobile], [Desktop/Mobile]-first - Palette: [Primary Name] (#hex for role), [Secondary Name] (#hex for role) - Styles: [Roundness description], [Shadow/Elevation style] @@ -65,20 +91,27 @@ Format the enhanced prompt for Stitch like this: ``` ### 4. Present AI Insights -After any tool call, always surface the `outputComponents` (Text Description and Suggestions) to the user. ---- +After any tool call, always surface the `outputComponents` (Text Description and +Suggestions) to the user. + +-------------------------------------------------------------------------------- ## 📚 References -- [Tool Schemas](references/tool-schemas.md) — How to call Stitch MCP tools. -- [Design Mappings](references/design-mappings.md) — UI/UX keywords and atmosphere descriptors. -- [Prompting Keywords](references/prompt-keywords.md) — Technical terms Stitch understands best. +- [Tool Schemas](references/tool-schemas.md) — How to call Stitch MCP tools. +- [Design Mappings](references/design-mappings.md) — UI/UX keywords and + atmosphere descriptors. +- [Prompting Keywords](references/prompt-keywords.md) — Technical terms Stitch + understands best. ---- +-------------------------------------------------------------------------------- ## 💡 Best Practices -- **Iterative Polish**: Prefere `edit_screens` for targeted adjustments over full re-generation. -- **Semantic First**: Name colors by their role (e.g., "Primary Action") as well as their appearance. -- **Atmosphere Matters**: Explicitly set the "vibe" (Minimalist, Vibrant, Brutalist) to guide the generator. +- **Iterative Polish**: Prefer `edit_screens` for targeted adjustments over + full re-generation. +- **Semantic First**: Name colors by their role (e.g., "Primary Action") as + well as their appearance. +- **Atmosphere Matters**: Explicitly set the "vibe" (Minimalist, Vibrant, + Brutalist) to guide the generator. diff --git a/skills/stitch-design/examples/DESIGN.md b/skills/stitch-design/examples/DESIGN.md index c785fb5..eafc94c 100644 --- a/skills/stitch-design/examples/DESIGN.md +++ b/skills/stitch-design/examples/DESIGN.md @@ -1,22 +1,34 @@ --- # The "Solace" Design System -This is a comprehensive design language for a mindfulness and wellness application. +This is a comprehensive design language for a mindfulness and wellness +application. -## 🎨 Color Palette -- **Primary**: Deep Ocean Blue (#1a365d) - for critical navigation and CTAs. -- **Secondary**: Calm Slate (#718096) - for subtexts and secondary buttons. -- **Background**: Soft Mist (#f7fafc) - for main page content. -- **Accent**: Serene Emerald (#38a169) - for positive feedback and completion states. +## 1. Visual Theme & Atmosphere +Calm, airy, and nurturing. Generous whitespace with soft pastel accents creates +a sense of tranquility. The aesthetic is clean and minimal — focused on clarity +and emotional safety. -## 🔡 Typography -- **Heading**: Montserrat, Bold - for titles and hero section headlines. -- **Body**: Inter, Regular - for descriptions and general content. -- **Size**: 16px as base, 48px for H1. +## 2. Color Palette & Roles -## 📐 Components -- **Buttons**: Rounded (12px), subtle hover shadow (4px blur). -- **Cards**: Minimal border (1px, #e2e8f0), soft shadow (8px elevation). -- **Navigation**: Clean, top-aligned, centered menu items. +- **Deep Ocean Blue** (#1a365d) — Primary, for critical navigation and CTAs +- **Calm Slate** (#718096) — Secondary text and secondary buttons +- **Soft Mist** (#f7fafc) — Main page background +- **Serene Emerald** (#38a169) — Positive feedback and completion states ---- -💡 **Tip**: When calling `generate_screen_from_text`, include the tokens above to ensure the new screen matches this design system. +## 3. Typography Rules + +- **Headings**: Montserrat, Bold — for titles and hero section headlines +- **Body**: Inter, Regular — for descriptions and general content +- **Base size**: 16px, H1 at 48px + +## 4. Component Stylings + +* **Buttons**: Rounded (12px), subtle hover shadow (4px blur) +* **Cards**: Minimal border (1px, #e2e8f0), soft shadow (8px elevation) +* **Navigation**: Clean, top-aligned, centered menu items + +## 5. Layout Principles + +- Centered content with max-width container (1200px) +- Comfortable vertical spacing between sections (48-64px) +- Mobile-first responsive breakpoints diff --git a/skills/stitch-design/examples/enhanced-prompt.md b/skills/stitch-design/examples/enhanced-prompt.md index 18fe1c0..1b494c1 100644 --- a/skills/stitch-design/examples/enhanced-prompt.md +++ b/skills/stitch-design/examples/enhanced-prompt.md @@ -1,14 +1,17 @@ # Example: Prompt Enhancement ## User Input (Vague) -> "Make a landing page for my fitness app called 'Pulse'. Use red and black. It should have a place for features and a hero section." +> "Make a landing page for my fitness app called 'Pulse'. Use red and +> black. It should have a place for features and a hero section." --- ## Enhanced Prompt (Stitch-Optimized) -**Overall Purpose**: A high-energy, modern landing page for 'Pulse', a fitness tracking application. The vibe is powerful, motivating, and high-performance. +**Overall Purpose**: A high-energy, modern landing page for 'Pulse', a fitness +tracking application. The vibe is powerful, motivating, and high-performance. **DESIGN SYSTEM (REQUIRED):** + - **Primary Color**: Racing Red (#e11d48) for CTA buttons and active states. - **Secondary Color**: Deep Obsidian (#0f172a) for background and text containers. - **Typography**: Bold, condensed sans-serif headings (e.g., Impact or Inter Tight) to convey speed and strength. @@ -16,7 +19,9 @@ **PAGE STRUCTURE:** 1. **Header**: Minimalist navigation with Pulse logo (left) and "Start Training" primary button (right). -2. **Hero Section**: Large, emotive fitness photography background. Headline: "Elevate Every Beat." Sub-headline: "Track, analyze, and crush your fitness goals with Pulse." Primary red CTA: "Get Started". +2. **Hero Section**: Large, emotive fitness photography background. Headline: + "Elevate Every Beat." Sub-headline: "Track, analyze, and crush your fitness + goals with Pulse." Primary red CTA: "Get Started". 3. **Feature Grid**: Three-column layout highlighting: - **Real-time Tracking**: Live stats from your wearable. - **AI Coaching**: Personalized workouts based on your performance. @@ -25,4 +30,6 @@ 5. **Footer**: Quick links (Training, Pricing, Support), social icons, and legal. --- -💡 **Tip**: Notice how the enhanced prompt adds specific hex codes, defines the typography "vibe", and breaks the page into a logical numbered structure. This gives Stitch much clearer instructions. +💡 **Tip**: Notice how the enhanced prompt adds specific hex codes, defines the +typography "vibe", and breaks the page into a logical numbered structure. This +gives Stitch much clearer instructions. diff --git a/skills/stitch-design/examples/metadata.json b/skills/stitch-design/examples/metadata.json index 1f070b6..b55e1b7 100644 --- a/skills/stitch-design/examples/metadata.json +++ b/skills/stitch-design/examples/metadata.json @@ -14,9 +14,10 @@ } ], "designSystem": { + "assetId": "15996705518239280238", "primaryColor": "#1a365d", "secondaryColor": "#718096", "backgroundColor": "#f7fafc", - "fontFamily": "Inter, sans-serif" + "fontFamily": "INTER" } } diff --git a/skills/stitch-design/references/design-mappings.md b/skills/stitch-design/references/design-mappings.md index 8c0a2c7..83d27fe 100644 --- a/skills/stitch-design/references/design-mappings.md +++ b/skills/stitch-design/references/design-mappings.md @@ -1,6 +1,7 @@ # Design Mappings & Descriptors -Use these mappings to transform vague user requests into precise, high-fidelity design instructions. +Use these mappings to transform vague user requests into precise, high-fidelity +design instructions. ## UI/UX Keyword Refinement diff --git a/skills/stitch-design/references/prompt-keywords.md b/skills/stitch-design/references/prompt-keywords.md index 7bb06ed..5a2bd17 100644 --- a/skills/stitch-design/references/prompt-keywords.md +++ b/skills/stitch-design/references/prompt-keywords.md @@ -1,16 +1,19 @@ # UI/UX Keywords Reference -Progressive disclosure reference for common UI terminology and adjective palettes. +Progressive disclosure reference for common UI terminology and adjective +palettes. ## Component Keywords ### Navigation + - navigation bar, nav menu, header - breadcrumbs, tabs, sidebar - hamburger menu, dropdown menu - back button, close button ### Content Containers + - hero section, hero banner - card, card grid, tile - modal, dialog, popup @@ -18,6 +21,7 @@ Progressive disclosure reference for common UI terminology and adjective palette - carousel, slider ### Forms + - input field, text input - dropdown, select menu - checkbox, radio button @@ -27,18 +31,21 @@ Progressive disclosure reference for common UI terminology and adjective palette - submit button, form actions ### Calls to Action + - primary button, secondary button - ghost button, text link - floating action button (FAB) - icon button ### Feedback + - toast notification, snackbar - alert banner, warning message - loading spinner, skeleton loader - progress bar, step indicator ### Layout + - grid layout, flexbox - sidebar layout, split view - sticky header, fixed footer @@ -48,36 +55,42 @@ Progressive disclosure reference for common UI terminology and adjective palette ## Adjective Palettes ### Minimal / Clean + - minimal, clean, uncluttered - generous whitespace, breathing room - subtle, understated, refined - simple, focused, distraction-free ### Professional / Corporate + - sophisticated, polished, trustworthy - corporate, business-like, formal - subtle shadows, clean lines - structured, organized, hierarchical ### Playful / Fun + - vibrant, colorful, energetic - rounded corners, soft edges - bold, expressive, dynamic - friendly, approachable, warm ### Premium / Luxury + - elegant, luxurious, high-end - dramatic, bold contrasts - sleek, modern, cutting-edge - exclusive, boutique, curated ### Dark Mode + - dark theme, night mode - high-contrast accents - soft glows, subtle highlights - deep backgrounds, muted surfaces ### Organic / Natural + - earthy tones, natural colors - warm, inviting, cozy - textured, tactile, handcrafted @@ -86,17 +99,20 @@ Progressive disclosure reference for common UI terminology and adjective palette ## Color Role Terminology ### Backgrounds + - page background, canvas - surface color, card background - overlay, scrim ### Text + - primary text, heading color - secondary text, body copy - muted text, placeholder - inverse text (on dark backgrounds) ### Accents + - primary accent, brand color - secondary accent, highlight - success, error, warning colors diff --git a/skills/stitch-design/references/tool-schemas.md b/skills/stitch-design/references/tool-schemas.md index 48fd20d..d0ca883 100644 --- a/skills/stitch-design/references/tool-schemas.md +++ b/skills/stitch-design/references/tool-schemas.md @@ -29,6 +29,65 @@ Creates a new Stitch project. } ``` +### `create_design_system` +Creates a new design system for a project. + +> [!IMPORTANT] +> You MUST call `update_design_system` immediately after `create_design_system` + to apply the design tokens to the project and display the design system in + the UI. Use the asset ID returned from `create_design_system` as the `name` + field (format: `assets/{asset_id}`). + +```json +{ + "projectId": "4044680601076201931", + "designSystem": { + "displayName": "My Design System", // OPTIONAL. Display name of the design system + "theme": { // REQUIRED. The design theme object + "colorMode": "LIGHT", // REQUIRED. Options: LIGHT, DARK + "headlineFont": "INTER", // REQUIRED. Options: INTER, ROBOTO, OPEN_SANS, LATO, MONTSERRAT, NOTO_SANS, NOTO_SERIF, etc. + "bodyFont": "INTER", // REQUIRED. Same font options as headlineFont + "labelFont": "INTER", // OPTIONAL. Same font options as headlineFont + "roundness": "ROUND_EIGHT", // REQUIRED. Options: ROUND_FOUR, ROUND_EIGHT, ROUND_TWELVE, ROUND_FULL + "customColor": "#0EA5E9", // REQUIRED. Primary brand color / seed color for dynamic color system (hex) + "colorVariant": "FIDELITY", // OPTIONAL. Options: FIDELITY, TONAL, VIBRANT, EXPRESSIVE, CONTENT, MONOCHROME, FRUIT_SALAD, RAINBOW + "overridePrimaryColor": "#996e47", // OPTIONAL. Override primary color (hex) + "overrideSecondaryColor": "#0EA5E9", // OPTIONAL. Override secondary color (hex) + "overrideTertiaryColor": "#c4956a", // OPTIONAL. Override tertiary color (hex) + "overrideNeutralColor": "#0D0D0D", // OPTIONAL. Override neutral color (hex) + "designMd": "# Design System..." // OPTIONAL. Markdown string with detailed design system spec + } + } +} +``` + +### `update_design_system` +Updates an existing design system for a project, this is needed in order to +display the design system in the UI as well. +```json +{ + "name": "assets/15996705518239280238", + "projectId": "4044680601076201931", + "designSystem": { + "displayName": "My Design System", // OPTIONAL. Display name of the design system + "theme": { // REQUIRED. The design theme object + "colorMode": "LIGHT", // REQUIRED. Options: LIGHT, DARK + "headlineFont": "INTER", // REQUIRED. Options: INTER, ROBOTO, OPEN_SANS, LATO, MONTSERRAT, NOTO_SANS, NOTO_SERIF, etc. + "bodyFont": "INTER", // REQUIRED. Same font options as headlineFont + "labelFont": "INTER", // OPTIONAL. Same font options as headlineFont + "roundness": "ROUND_EIGHT", // REQUIRED. Options: ROUND_FOUR, ROUND_EIGHT, ROUND_TWELVE, ROUND_FULL + "customColor": "#0EA5E9", // REQUIRED. Primary brand color / seed color for dynamic color system (hex) + "colorVariant": "FIDELITY", // OPTIONAL. Options: FIDELITY, TONAL, VIBRANT, EXPRESSIVE, CONTENT, MONOCHROME, FRUIT_SALAD, RAINBOW + "overridePrimaryColor": "#996e47", // OPTIONAL. Override primary color (hex) + "overrideSecondaryColor": "#0EA5E9", // OPTIONAL. Override secondary color (hex) + "overrideTertiaryColor": "#c4956a", // OPTIONAL. Override tertiary color (hex) + "overrideNeutralColor": "#0D0D0D", // OPTIONAL. Override neutral color (hex) + "designMd": "# Design System..." // OPTIONAL. Markdown string with detailed design system spec + } + } +} +``` + --- ## 🎨 Design Generation @@ -73,4 +132,36 @@ Retrieves details of a specific screen. "screenId": "98b50e2ddc9943efb387052637738f61", "name": "projects/4044680601076201931/screens/98b50e2ddc9943efb387052637738f61" } -``` \ No newline at end of file +``` + +### `apply_design_system` +Applies a design system to one or more screens in a project. + +> [!IMPORTANT] +> `selectedScreenInstances` must contain **only** `id` and `sourceScreen` — do NOT +> include position/dimension fields (`x`, `y`, `width`, `height`) or the request +> will fail with "invalid argument". Get the screen instance IDs from +> `get_project`. + +```json +{ + "projectId": "4044680601076201931", + "assetId": "c277fcdfc1e04baf91b92d975ff4c54a", + "selectedScreenInstances": [ + { + "id": "98b50e2ddc9943efb387052637738f61", + "sourceScreen": "projects/4044680601076201931/screens/98b50e2ddc9943efb387052637738f61" + }, + { + "id": "ab12cd34ef56789012345678abcdef01", + "sourceScreen": "projects/4044680601076201931/screens/ab12cd34ef56789012345678abcdef01" + } + ] +} +``` + +**How to get the required IDs:** +1. Call `get_project` to retrieve `screenInstances` — each has an `id` and `sourceScreen`. +2. Call `list_design_systems` to retrieve the design system `name` (format: + `assets/{assetId}`) — use the part after `assets/` as the `assetId`. +3. Filter out any instances with `type: "DESIGN_SYSTEM_INSTANCE"` — only pass real screens. \ No newline at end of file diff --git a/skills/stitch-design/scripts/upload_to_stitch.py b/skills/stitch-design/scripts/upload_to_stitch.py new file mode 100644 index 0000000..085812b --- /dev/null +++ b/skills/stitch-design/scripts/upload_to_stitch.py @@ -0,0 +1,222 @@ +#!/usr/bin/env python3 +r"""Upload an image to a Stitch project via BatchCreateScreens. + +WHY THIS SCRIPT EXISTS: + The AI model cannot upload files via the MCP tool directly because MCP tool + call arguments are part of the model's *output*. The model must re-emit the + entire base64-encoded file as generated text, but its output token limit + (~16K tokens) is far smaller than a typical file's base64 encoding (e.g. + a 53KB PNG becomes ~71K chars of base64). The output gets truncated + mid-string, producing a corrupted payload that the API rejects. + + This script bypasses the model entirely — it reads the file, encodes it + in-process, and sends the full payload directly over HTTP with no token + limits. + +SUPPORTED FILE TYPES: + - Images: .png, .jpg, .jpeg, .webp + +Usage: + python3 upload_to_stitch.py \ + --project-id \ + --file-path \ + [--api-url ] \ + [--api-key ] \ + [--title ] \ + [--create-screen-instances] +""" + +import argparse +import base64 +import json +import pathlib +import sys +from typing import Any +import urllib.request + + +# Maps file extensions to MIME types. +_MIME_TYPES = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", +} + + +def encode_file(path: pathlib.Path) -> str: + """Read and base64-encode a file.""" + with open(path, "rb") as f: + return base64.b64encode(f.read()).decode("utf-8") + + +def call_batch_create_screens( + api_url: str, + api_key: str, + project_id: str, + requests: list[dict[str, Any]], + create_screen_instances: bool = False, + urlopen: Any = urllib.request.urlopen, +) -> dict[str, Any]: + """Call BatchCreateScreens REST API directly. + + Endpoint: POST /v1/{parent=projects/*}/screens:batchCreate + + Args: + api_url: Base URL of the Stitch API (e.g. https://stitch.googleapis.com). + api_key: API key for authentication. + project_id: The Stitch project ID. + requests: List of CreateScreenRequest dicts, each containing a screen. + create_screen_instances: Whether to create screen instances for display. + urlopen: The urlopen function to use (for testing). + + Returns: + Parsed JSON response dict. + """ + url = f"{api_url.rstrip('/')}/v1/projects/{project_id}/screens:batchCreate" + + payload = { + "parent": f"projects/{project_id}", + "requests": requests, + "createScreenInstances": create_screen_instances, + } + + data = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + url, + data=data, + headers={ + "Content-Type": "application/json", + "X-Goog-Api-Key": api_key, + }, + method="POST", + ) + + try: + with urlopen(req) as resp: + body = resp.read().decode("utf-8") + print(f"Response status: {resp.getcode()}") + print(f"Response body (first 1000 chars): {body[:1000]}") + if not body: + print("Error: Empty response body") + sys.exit(1) + return json.loads(body) + except urllib.error.HTTPError as e: + error_body = e.read().decode("utf-8") + print(f"HTTP Error {e.code}: {e.reason}") + print(f"Response: {error_body}") + sys.exit(1) + + +def build_screen_request( + mime_type: str, + b64_data: str, + title: str | None = None, +) -> dict[str, Any]: + """Build a CreateScreenRequest dict from a file. + + For images, the file is set as the screenshot. + + Args: + mime_type: The MIME type of the file. + b64_data: Base64-encoded file content. + title: Optional title for the screen. + + Returns: + A CreateScreenRequest-shaped dict. + """ + file_obj = { + "fileContentBase64": b64_data, + "mimeType": mime_type, + } + + screen = { + "screenshot": file_obj, + "screenType": "IMAGE", + "isCreatedByClient": True, + } + + if title: + screen["title"] = title + + return {"screen": screen} + + +def parse_args(): + """Parse command-line arguments.""" + parser = argparse.ArgumentParser( + description="Upload a file to a Stitch project via BatchCreateScreens." + ) + parser.add_argument("--project-id", required=True, help="Stitch project ID") + parser.add_argument( + "--file-path", + required=True, + type=pathlib.Path, + help=( + "Path to the file to upload. Supported types:" + f" {', '.join(sorted(_MIME_TYPES.keys()))}" + ), + ) + parser.add_argument( + "--api-url", + default="https://stitch.googleapis.com", + help="Stitch API base URL. Defaults to https://stitch.googleapis.com.", + ) + parser.add_argument( + "--api-key", + default="", + help="API key for the Stitch API.", + ) + parser.add_argument( + "--title", + default=None, + help="Optional title for the created screen", + ) + return parser.parse_args() + + +def main(): + args = parse_args() + + file_path = args.file_path + file_suffix = file_path.suffix.lower() + mime_type = _MIME_TYPES.get(file_suffix) + + if mime_type is None: + print( + f"Error: Unsupported file type '{file_suffix}'. Supported types:" + f" {', '.join(sorted(_MIME_TYPES.keys()))}" + ) + sys.exit(1) + + if not file_path.exists(): + print(f"Error: File not found: {file_path}") + sys.exit(1) + + print(f"File: {file_path}") + print(f"MIME type: {mime_type}") + + b64_data = encode_file(file_path) + print(f"Base64: {len(b64_data)} chars") + + screen_request = build_screen_request( + mime_type, b64_data, title=args.title + ) + + print(f"\nUploading to project: {args.project_id}") + print(f"API URL: {args.api_url}") + + result = call_batch_create_screens( + api_url=args.api_url, + api_key=args.api_key, + project_id=args.project_id, + requests=[screen_request], + create_screen_instances=True, + ) + + print("\nResponse:") + print(json.dumps(result, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/skills/stitch-design/workflows/design-system.md b/skills/stitch-design/workflows/design-system.md new file mode 100644 index 0000000..9055c29 --- /dev/null +++ b/skills/stitch-design/workflows/design-system.md @@ -0,0 +1,105 @@ +--- +description: Central workflow for managing a Stitch project's design system. + Handles creating/updating .stitch/DESIGN.md, analyzing existing designs, and + syncing the design system with Stitch MCP via create_design_system and + update_design_system. +--- + +# Workflow: Design System + +Create a "source of truth" for your project's design language to ensure +consistency across all future screens. + +## 📥 Retrieval + +To analyze a Stitch project, you must retrieve metadata and assets using the +Stitch MCP tools: + +1. **Project lookup**: Use `list_projects` to find the target `projectId`. +2. **Screen lookup**: Use `list_screens` for that `projectId` to find +representative screens (e.g., "Home", "Main Dashboard"). +3. **Metadata fetch**: Call `get_screen` for the target screen to get +`screenshot.downloadUrl` and `htmlCode.downloadUrl`. +4. **Asset download**: Use `read_url_content` to fetch the HTML code. + +## 🧠 Analysis & Synthesis + +### 1. Identify Identity + +- Capture Project Title and Project ID. + +### 2. Define Atmosphere + +- Analyze the HTML and screenshot to capture the "vibe" (e.g., "Airy", + "Professional", "Vibrant"). + +### 3. Map Color Palette + +- Extract exact hex codes and assign functional roles (e.g., "Primary Action: #2563eb"). + +### 4. Translate Geometry + +- Convert Tailwind/CSS values into descriptive language (e.g., `rounded-full` → "Pill-shaped"). + +### 5. Document Depth + +- Describe shadow styles and layering (e.g., "Soft, diffused elevation"). + +## 📝 Output Structure + +Create a `.stitch/DESIGN.md` file in the project directory with this structure: + +```markdown +# Design System: [Project Title] +**Project ID:** [Insert Project ID Here] + +## 1. Visual Theme & Atmosphere +(Description of mood and aesthetic philosophy) + +## 2. Color Palette & Roles +(Descriptive Name + Hex Code + Role) + +## 3. Typography Rules +(Font families, weights, and usage) + +## 4. Component Stylings +* **Buttons:** Shape, color, behavior +* **Containers:** Roundness, elevation + +## 5. Layout Principles +(Whitespace strategy and grid alignment) +``` + +## 🚀 Create or Update Design System in Stitch +After generating `.stitch/DESIGN.md`, make sure to also create or update the +design system in Stitch using MCP tools. + +**Two-step design system creation:** +1. Call `create_design_system` with an **empty request** — only pass the +`projectId` and an empty `designSystem` object (`{}`). This creates the asset +and returns the asset ID. +2. Immediately call `update_design_system` with the **full theme configuration** +using the returned asset ID (format: `assets/{asset_id}`). Map DESIGN.md content +to the required `theme` fields (`colorMode`, `headlineFont`, `bodyFont`, +`roundness`, `customColor`) and pass the full markdown verbatim in +`theme.designMd`. See [Tool Schemas](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/references/tool-schemas.md) for the exact format. + +> [!IMPORTANT] +> Do NOT put theme data in `create_design_system`. The `update_design_system` +call is what actually applies the design tokens and displays the design system +in the UI. + +Once both `create_design_system` and `update_design_system` have been called, +Stitch holds the design tokens at the project level — you do NOT need to repeat +them in generation prompts. + +## 📋 Update Project Metadata +After writing `.stitch/DESIGN.md`, also create or update `.stitch/metadata.json` +to track the `projectId`, `title`, all known screens, and design system summary. + See [examples/metadata.json](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/examples/metadata.json) for the format. + +## 💡 Best Practices + +- **Be Precise**: Always include hex codes in parentheses. +- **Be Descriptive**: Use natural language like "Deep Ocean Blue" instead of just "Blue". +- **Be Functional**: Explain *why* an element is used. diff --git a/skills/stitch-design/workflows/edit-design.md b/skills/stitch-design/workflows/edit-design.md index 05fae93..9382781 100644 --- a/skills/stitch-design/workflows/edit-design.md +++ b/skills/stitch-design/workflows/edit-design.md @@ -9,10 +9,12 @@ Make targeted changes to an already generated design. ## Steps ### 1. Identify the Screen -Use `list_screens` or `get_screen` to find the correct `projectId` and `screenId`. +Use `list_screens` or `get_screen` to find the correct `projectId` and +`screenId`. ### 2. Formulate the Edit Prompt -Be specific about the changes you want to make. Do not just say "fix it". +Be specific about the changes you want to make. Do not just say "fix it". + - **Location**: "Change the color of the [primary button] in the [hero section]..." - **Visuals**: "...to a darker blue (#004080) and add a subtle shadow." - **Structure**: "Add a secondary button next to the primary one with the text 'Learn More'." @@ -29,16 +31,26 @@ Call the `mcp_StitchMCP_edit_screens` tool. ``` ### 4. Present AI Feedback -Always show the text description and suggestions from `outputComponents` to the user. +Always show the text description and suggestions from `outputComponents` to the +user. ### 5. Download Design Assets -After editing, download the updated HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory, overwriting previous versions to ensure the local files reflect the latest edits. +After editing, download the updated HTML and screenshot urls from +`outputComponents` to the `.stitch/designs` directory, overwriting previous +versions to ensure the local files reflect the latest edits. + +### 6. Update Project Metadata +After downloading assets, update `.stitch/metadata.json` to reflect any changes +(e.g., updated screen titles or new screen IDs from the edit). +See [examples/metadata.json](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/examples/metadata.json) for the format. + +### 7. Verify and Repeat -### 6. Verify and Repeat - Check the output screen to see if the changes were applied correctly. - If more polish is needed, repeat the process with a new specific prompt. ## Tips + - **Keep it focused**: One edit at a time is often better than a long list of changes. - **Reference components**: Use professional terms like "navigation bar", "hero section", "footer", "card grid". - **Mention colors**: Use hex codes for precise color matching. diff --git a/skills/stitch-design/workflows/text-to-design.md b/skills/stitch-design/workflows/text-to-design.md index 76300f1..190af06 100644 --- a/skills/stitch-design/workflows/text-to-design.md +++ b/skills/stitch-design/workflows/text-to-design.md @@ -9,16 +9,19 @@ Transform a text description into a high-fidelity design screen. ## Steps ### 1. Enhance the User Prompt -Before calling the Stitch MCP tool, apply the [Prompt Enhancement Pipeline](../SKILL.md#prompt-enhancement-pipeline). +Before calling the Stitch MCP tool, apply the [Prompt Enhancement Pipeline](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/SKILL.md#prompt-enhancement-pipeline). + - Identify the platform (Web/Mobile) and page type. - Incorporate any existing project design system from `.stitch/DESIGN.md`. -- Use specific [Design Mappings](../references/design-mappings.md) and [Prompting Keywords](../references/prompt-keywords.md). +- Use specific [Design Mappings](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/references/design-mappings.md) and + [Prompting Keywords](/labs/language/aida/product/appcompanion/stitch_skills/stitch-design/references/prompt-keywords.md). ### 2. Identify the Project Use `list_projects` to find the correct `projectId` if it is not already known. ### 3. Generate the Screen -Call the `mcp_StitchMCP_generate_screen_from_text` tool with the enhanced prompt. +Call the `mcp_StitchMCP_generate_screen_from_text` tool with the enhanced +prompt. ```json { @@ -29,19 +32,27 @@ Call the `mcp_StitchMCP_generate_screen_from_text` tool with the enhanced prompt ``` ### 4. Present AI Feedback -Always show the text description and suggestions from `outputComponents` to the user. +Always show the text description and suggestions from `outputComponents` to the +user. ### 5. Download Design Assets -After generation, download the HTML and screenshot urls from `outputComponents` to the `.stitch/designs` directory. +After generation, download the HTML and screenshot urls from `outputComponents` +to the `.stitch/designs` directory. + - **Naming**: Use the screen ID or a descriptive slug for the filename. - **Tools**: Use `curl -o` via `run_command` or similar. - **Directory**: Ensure `.stitch/designs` exists. ### 6. Review and Refine -- If the result is not exactly as expected, use the [edit-design](edit-design.md) workflow to make targeted adjustments. + +- If the result is not exactly as expected, use the + [edit-design](edit-design.md) workflow to make targeted adjustments. - Do NOT re-generate from scratch unless the fundamental layout is wrong. ## Tips -- **Be structural**: Break the page down into header, hero, features, and footer in your prompt. + +- **Be structural**: Break the page down into header, hero, features, and + footer in your prompt. - **Specify colors**: Use hex codes for precision. -- **Set the tone**: Explicitly mention if the design should be minimal, professional, or vibrant. +- **Set the tone**: Explicitly mention if the design should be minimal, + professional, or vibrant. diff --git a/skills/stitch-design/workflows/upload-to-stitch.md b/skills/stitch-design/workflows/upload-to-stitch.md new file mode 100644 index 0000000..1bbc3a7 --- /dev/null +++ b/skills/stitch-design/workflows/upload-to-stitch.md @@ -0,0 +1,46 @@ +# File Upload Workflow + +When the user wants to upload an image (screenshot, mockup) to a Stitch project, +use the upload script instead of the MCP tool directly (which has base64 size +limits). + +## How to get the MCP URL and API Key + +Locate your active MCP server configuration file (e.g., +`.gemini/jetski/mcp_config.json` for Antigravity, +`~/.gemini/extensions/Stitch/gemini-extension.json` for Gemini Extension, +`~/.gemini/settings.json` for Gemini CLI, `~/.claude.json` for Claude Code, +or the equivalent for your platform) and parse the configuration for the +Stitch MCP server: + +- **MCP URL**: Extract the HTTP URL for the Stitch MCP server (e.g., defined + via `httpUrl` or as an endpoint argument). +- **API Key**: Extract the API key used for authentication (e.g., defined + in the `X-Goog-Api-Key` header or as an auth argument). + +## Script Usage + +You can use the absolute path to run the script from anywhere: + +```bash +python3 /.agent/skills/stitch-design/scripts/upload_to_stitch.py \ + --project-id \ + --file-path \ + --api-key \ + [--api-url ] +``` + +Alternatively, if you are in the local workspace root, you can use the relative +path: + +```bash +python3 .agent/skills/stitch-design/scripts/upload_to_stitch.py \ + --project-id \ + --file-path \ + --api-key \ + [--api-url ] +``` + +The script auto-detects mime type from the file extension (`.png` → `image/png`, etc.). +The default `--api-url` is `https://staging-stitch.sandbox.googleapis.com`. +The `--api-key` is required.