An AI skill that provides design intelligence for building professional UI/UX across multiple platforms.
Python ai-skillsantigravityclaudeclaude-codecodexcommand-linecopilotcursor-aihtml5kirolanding-pagemobile-uiqoderreacttailwindcsstraeui-designuikitwindsurf-ai
fix(design): image extensions, failure exit status and --pro model id (#532)
Jul11us616663179c5f
diff --git a/.claude/skills/design/SKILL.md b/.claude/skills/design/SKILL.mdindex 6ffc503..0dda900 100644--- a/.claude/skills/design/SKILL.md+++ b/.claude/skills/design/SKILL.md@@ -111,7 +111,7 @@ python3 scripts/cip/generate.py --brand "TopGroup" --logo logo.png --deliverablepython3 scripts/cip/generate.py --brand "TechFlow" --deliverable "business card" --no-logo-prompt```-Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image-preview`)+Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image`). Override the ids with `GEMINI_FLASH_IMAGE_MODEL` / `GEMINI_PRO_IMAGE_MODEL`.### CIP: Render HTML Presentationdiff --git a/.claude/skills/design/references/cip-design.md b/.claude/skills/design/references/cip-design.mdindex 4037769..877ae71 100644--- a/.claude/skills/design/references/cip-design.md+++ b/.claude/skills/design/references/cip-design.md@@ -64,7 +64,9 @@ python3 scripts/cip/render-html.py --brand "TopGroup" --industry "consulting" --## Models- `flash` (default): `gemini-2.5-flash-image` - Fast, cost-effective-- `pro`: `gemini-3-pro-image-preview` - Quality, 4K text rendering+- `pro`: `gemini-3-pro-image` - Quality, 4K text rendering++Set `GEMINI_FLASH_IMAGE_MODEL` or `GEMINI_PRO_IMAGE_MODEL` to use another Gemini model id.## Deliverable Categoriesdiff --git a/.claude/skills/design/scripts/cip/generate.py b/.claude/skills/design/scripts/cip/generate.pyindex e92b2e1..394b06d 100644--- a/.claude/skills/design/scripts/cip/generate.py+++ b/.claude/skills/design/scripts/cip/generate.py@@ -7,11 +7,19 @@ Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality mSupports text-and-image-to-image generation for using actual brand logos.- gemini-2.5-flash-image: Fast generation, cost-effective (default)-- gemini-3-pro-image-preview: Pro quality, 4K text rendering+- gemini-3-pro-image: Pro quality, 4K text rendering++Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini+model id, for example when Google retires one of these.Image Editing (text-and-image-to-image):When --logo is provided, the script uses Gemini's image editing capabilityto incorporate the actual logo into CIP mockups instead of generating one.++Each mockup is saved with the extension of the image type Gemini returns+(.png, .jpg or .webp). Exit status is 1 when nothing was generated: a failed+single deliverable, or a set where every deliverable failed. A set where some+deliverables succeed exits 0 and reports how many were generated."""import argparse@@ -25,13 +33,6 @@ from datetime import datetimesys.path.insert(0, str(Path(__file__).parent))from core import search, get_cip_brief-# Model options-MODELS = {- "flash": "gemini-2.5-flash-image", # Nano Banana Flash - fast, default- "pro": "gemini-3-pro-image-preview" # Nano Banana Pro - quality, 4K text-}-DEFAULT_MODEL = "flash"-def load_logo_image(logo_path):"""Load logo image using PIL for Gemini image editing"""@@ -85,6 +86,16 @@ def load_env():load_env()+# Model options (read after load_env so .env files can override the ids)+MODELS = {+ "flash": os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image", # Nano Banana Flash - fast, default+ "pro": os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image" # Nano Banana Pro - quality, 4K text+}+DEFAULT_MODEL = "flash"++# File extensions for the image types Gemini returns as inline data+IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}+def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False):"""Build an optimized prompt for CIP mockup generation@@ -192,7 +203,7 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", aModels:- flash: gemini-2.5-flash-image (fast, cost-effective) - DEFAULT- - pro: gemini-3-pro-image-preview (quality, 4K text rendering)+ - pro: gemini-3-pro-image (quality, 4K text rendering)Args:prompt_data: Dict with prompt, deliverable, brand, etc.@@ -265,7 +276,9 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", atimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")brand_slug = prompt_data["brand"].lower().replace(" ", "-")deliverable_slug = prompt_data["deliverable"].lower().replace(" ", "-")- filename = f"{brand_slug}-{deliverable_slug}-{timestamp}.png"+ mime_type = (part.inline_data.mime_type or "").split(";")[0].strip().lower()+ extension = IMAGE_EXTENSIONS.get(mime_type, ".png")+ filename = f"{brand_slug}-{deliverable_slug}-{timestamp}{extension}"filepath = output_dir / filenameimage_data = part.inline_data.data@@ -390,7 +403,7 @@ Examples:Models:flash (default): gemini-2.5-flash-image - Fast, cost-effective- pro: gemini-3-pro-image-preview - Quality, 4K text rendering+ pro: gemini-3-pro-image - Quality, 4K text renderingImage Editing Mode:When --logo is provided, uses Gemini's text-and-image-to-image capability@@ -464,6 +477,8 @@ Image Editing Mode:print(json.dumps(results, indent=2))else:print(f"\n✅ Generated {len(results)} CIP mockups")+ if not results:+ sys.exit(1)else:# Generate single deliverabledeliverable = args.deliverable or "business card"@@ -481,6 +496,8 @@ Image Editing Mode:)if args.json:print(json.dumps({"filepath": filepath, **prompt_data}, indent=2))+ if filepath is None:+ sys.exit(1)if __name__ == "__main__":diff --git a/.claude/skills/design/scripts/icon/generate.py b/.claude/skills/design/scripts/icon/generate.pyindex 7d3a338..375f789 100644--- a/.claude/skills/design/scripts/icon/generate.py+++ b/.claude/skills/design/scripts/icon/generate.py@@ -493,7 +493,7 @@ def main():# Multi-size modeif args.sizes:sizes = [int(s.strip()) for s in args.sizes.split(",")]- generate_sizes(+ generated = generate_sizes(prompt=prompt,sizes=sizes,style=args.style,@@ -504,7 +504,7 @@ def main():# Batch modeelif args.batch:output_dir = args.output_dir or "./icons"- generate_batch(+ generated = generate_batch(prompt=prompt,count=args.batch,output_dir=output_dir,@@ -515,7 +515,7 @@ def main():)# Single iconelse:- generate_icon(+ generated = generate_icon(prompt=prompt,style=args.style,category=args.category,@@ -526,6 +526,10 @@ def main():viewbox=args.viewbox)+ # Exit 1 when nothing was generated; a partly generated batch or size set exits 0+ if not generated:+ sys.exit(1)+if __name__ == "__main__":main()diff --git a/.claude/skills/design/scripts/logo/generate.py b/.claude/skills/design/scripts/logo/generate.pyindex d006c13..3b5773f 100644--- a/.claude/skills/design/scripts/logo/generate.py+++ b/.claude/skills/design/scripts/logo/generate.py@@ -8,9 +8,20 @@ with the selected model's prompt/aspect-ratio contract.Models:- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency-- Nano Banana Pro (--pro): gemini-3-pro-image-preview - professional quality, advanced reasoning+- Nano Banana Pro (--pro): gemini-3-pro-image - professional quality, advanced reasoning- MuAPI Nano Banana (--provider muapi): nano-banana - hosted asynchronous image generation+Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini+model id, for example when Google retires one of these.++Gemini returns PNG or JPEG data. The file gets the extension of the returned+type, so ``--output logo.png`` can be saved as ``logo.jpg``; the path actually+written is printed.++Exit status is 1 when nothing was generated: a failed single request, or a+batch where every variant failed. A batch where some variants succeed exits 0+and reports how many were generated.+Usage:python generate.py --prompt "tech startup logo minimalist blue"python generate.py --prompt "coffee shop vintage badge" --style vintage --output logo.png@@ -28,6 +39,7 @@ import argparseimport ipaddressimport jsonimport os+import sysimport timefrom datetime import datetimefrom pathlib import Path@@ -65,8 +77,15 @@ ATLASCLOUD_API_KEY = os.environ.get("ATLASCLOUD_API_KEY")MUAPI_API_KEY = os.environ.get("MUAPI_API_KEY")# Gemini "Nano Banana" model configurations for image generation-GEMINI_FLASH = "gemini-2.5-flash-image" # Nano Banana: fast, high-volume, low-latency-GEMINI_PRO = "gemini-3-pro-image-preview" # Nano Banana Pro: professional quality, advanced reasoning+GEMINI_FLASH = (+ os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image"+) # Nano Banana: fast, high-volume, low-latency+GEMINI_PRO = (+ os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image"+) # Nano Banana Pro: professional quality, advanced reasoning++# File extensions for the image types Gemini returns as inline data+IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}# Atlas Cloud model validated against the live model catalog and schema.ATLAS_MODEL = "google/nano-banana-2-lite/text-to-image"@@ -431,7 +450,21 @@ def _generate_with_muapi(prompt, output_path, aspect_ratio, api_key, model):raise RuntimeError("MuAPI prediction timed out while polling")+def _path_for_image_type(output_path, mime_type):+ """Return output_path with the extension of the returned image type.++ An unknown image type keeps the requested path.+ """+ extension = IMAGE_EXTENSIONS.get(mime_type.split(";")[0].strip().lower())+ path = Path(output_path)+ suffix = path.suffix.lower()+ if extension is None or suffix == extension or (suffix, extension) == (".jpeg", ".jpg"):+ return output_path+ return str(path.with_suffix(extension))++def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):+ """Generate with Gemini and return the path the image was saved to."""if not GEMINI_API_KEY:raise RuntimeError("GEMINI_API_KEY not set")@@ -478,9 +511,15 @@ def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):and part.inline_dataand part.inline_data.mime_type.startswith("image/")):- with open(output_path, "wb") as output_file:+ saved_path = _path_for_image_type(output_path, part.inline_data.mime_type)+ if saved_path != output_path:+ print(+ f"Gemini returned {part.inline_data.mime_type}, "+ f"so saving as {saved_path} instead of {output_path}"+ )+ with open(saved_path, "wb") as output_file:output_file.write(part.inline_data.data)- return+ return saved_pathraise RuntimeError("Gemini did not return an image")@@ -520,9 +559,9 @@ def generate_logo(model_label = f"MuAPI ({muapi_model})"else:model_label = (- "Nano Banana Pro (gemini-3-pro-image-preview)"+ f"Nano Banana Pro ({GEMINI_PRO})"if use_pro- else "Nano Banana (gemini-2.5-flash-image)"+ else f"Nano Banana ({GEMINI_FLASH})")print(f"Generating logo with {model_label}...")@@ -548,7 +587,7 @@ def generate_logo(muapi_model,)else:- _generate_with_gemini(full_prompt, output_path, ratio, use_pro)+ output_path = _generate_with_gemini(full_prompt, output_path, ratio, use_pro)print(f"Logo saved to: {output_path}")return output_path@@ -635,7 +674,7 @@ def generate_batch(if result:results.append(result)- print(f" ✓ Saved: {filename}\n")+ print(f" ✓ Saved: {os.path.basename(result)}\n")else:print(f" ✗ Failed: {style_key}\n")@@ -675,7 +714,7 @@ def main():parser.add_argument("--pro",action="store_true",- help="Use Nano Banana Pro (gemini-3-pro-image-preview) for professional quality",+ help=f"Use Nano Banana Pro ({GEMINI_PRO}) for professional quality",)parser.add_argument("--provider",@@ -738,7 +777,7 @@ def main():output_dir = (args.output_dir or f"./{args.brand.lower().replace(' ', '_')}_logos")- generate_batch(+ results = generate_batch(prompt=prompt,brand_name=args.brand or "Logo",count=args.batch,@@ -750,8 +789,10 @@ def main():atlas_model=args.atlas_model,muapi_model=args.muapi_model,)+ if not results:+ sys.exit(1)else:- generate_logo(+ saved_path = generate_logo(prompt=prompt,style=args.style,industry=args.industry,@@ -763,6 +804,8 @@ def main():atlas_model=args.atlas_model,muapi_model=args.muapi_model,)+ if saved_path is None:+ sys.exit(1)if __name__ == "__main__":diff --git a/.claude/skills/design/scripts/logo/tests/test_generate.py b/.claude/skills/design/scripts/logo/tests/test_generate.pyindex 9c2addc..e0ca6ca 100644--- a/.claude/skills/design/scripts/logo/tests/test_generate.py+++ b/.claude/skills/design/scripts/logo/tests/test_generate.py@@ -1,13 +1,46 @@import importlib.util+import io+import os+import sysimport tempfileimport unittestfrom pathlib import Path-from unittest.mock import call, patch+from types import ModuleType, SimpleNamespace+from unittest.mock import Mock, call, patchMODULE_PATH = Path(__file__).parents[1] / "generate.py"-SPEC = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)-logo_generate = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(logo_generate)+++def _load_module():+ spec = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++logo_generate = _load_module()++JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"+PNG = b"\x89PNG\r\n\x1a\npng-bytes"+++def _image_response(mime_type, data):+ part = SimpleNamespace(inline_data=SimpleNamespace(mime_type=mime_type, data=data))+ return SimpleNamespace(+ candidates=[SimpleNamespace(content=SimpleNamespace(parts=[part]))]+ )+++def _fake_genai(client):+ """sys.modules entries for an offline google.genai whose Client is client."""+ types = ModuleType("google.genai.types")+ types.GenerateContentConfig = types.ImageConfig = types.SafetySetting = dict+ genai = ModuleType("google.genai")+ genai.Client = lambda api_key: client+ genai.types = types+ google = ModuleType("google")+ google.genai = genai+ return {"google": google, "google.genai": genai, "google.genai.types": types}class AtlasGenerationTests(unittest.TestCase):@@ -284,5 +317,138 @@ class MuapiGenerationTests(unittest.TestCase):json_request.assert_called_once()+class GeminiImageTypeTests(unittest.TestCase):+ def setUp(self):+ self.client = Mock()+ for patcher in (+ patch.dict(sys.modules, _fake_genai(self.client)),+ patch.object(logo_generate, "GEMINI_API_KEY", "test-key"),+ ):+ patcher.start()+ self.addCleanup(patcher.stop)+ temp_dir = tempfile.TemporaryDirectory()+ self.addCleanup(temp_dir.cleanup)+ self.dir = Path(temp_dir.name)++ def _generate(self, mime_type, data, requested_name):+ self.client.models.generate_content.return_value = _image_response(+ mime_type, data+ )+ return logo_generate._generate_with_gemini(+ "logo prompt", str(self.dir / requested_name), "1:1", use_pro=True+ )++ def test_jpeg_is_saved_with_jpg_extension(self):+ with patch("sys.stdout", new_callable=io.StringIO):+ saved = self._generate("image/jpeg", JPEG, "logo.png")++ self.assertEqual(saved, str(self.dir / "logo.jpg"))+ self.assertEqual(Path(saved).read_bytes(), JPEG)+ self.assertFalse((self.dir / "logo.png").exists())++ def test_matching_extension_keeps_requested_path(self):+ for mime_type, data, name in (+ ("image/png", PNG, "logo.png"),+ ("image/jpeg", JPEG, "logo.jpeg"),+ ("image/jpeg", JPEG, "logo.JPG"),+ ):+ with self.subTest(name=name):+ saved = self._generate(mime_type, data, name)+ self.assertEqual(saved, str(self.dir / name))+ self.assertEqual(Path(saved).read_bytes(), data)++ def test_unknown_image_type_keeps_requested_path(self):+ self.assertEqual(+ logo_generate._path_for_image_type("logo.png", "image/heic"), "logo.png"+ )++ def test_generate_logo_prints_and_returns_the_saved_path(self):+ self.client.models.generate_content.return_value = _image_response(+ "image/jpeg", JPEG+ )+ with patch("sys.stdout", new_callable=io.StringIO) as stdout:+ saved = logo_generate.generate_logo(+ "test mark", output_path=str(self.dir / "logo.png"), use_pro=True+ )++ self.assertEqual(saved, str(self.dir / "logo.jpg"))+ self.assertIn(f"Logo saved to: {saved}", stdout.getvalue())++ def test_pro_requests_the_configured_pro_model(self):+ self._generate("image/png", PNG, "logo.png")++ self.assertEqual(+ self.client.models.generate_content.call_args.kwargs["model"],+ logo_generate.GEMINI_PRO,+ )+++class GeminiModelIdTests(unittest.TestCase):+ def test_pro_defaults_to_the_ga_model(self):+ with patch.dict(os.environ):+ os.environ.pop("GEMINI_PRO_IMAGE_MODEL", None)+ module = _load_module()++ self.assertEqual(module.GEMINI_PRO, "gemini-3-pro-image")++ def test_model_ids_can_be_overridden_from_the_environment(self):+ with patch.dict(+ os.environ,+ {"GEMINI_FLASH_IMAGE_MODEL": "flash-next", "GEMINI_PRO_IMAGE_MODEL": "pro-next"},+ ):+ module = _load_module()++ self.assertEqual(module.GEMINI_FLASH, "flash-next")+ self.assertEqual(module.GEMINI_PRO, "pro-next")+++class ExitStatusTests(unittest.TestCase):+ def setUp(self):+ temp_dir = tempfile.TemporaryDirectory()+ self.addCleanup(temp_dir.cleanup)+ self.dir = Path(temp_dir.name)++ def _run_main(self, *args):+ with patch.object(sys, "argv", ["generate.py", *args]), patch(+ "sys.stdout", new_callable=io.StringIO+ ):+ logo_generate.main()++ def test_failed_single_request_exits_1(self):+ client = Mock()+ client.models.generate_content.side_effect = RuntimeError(+ "429 RESOURCE_EXHAUSTED"+ )+ with patch.dict(sys.modules, _fake_genai(client)), patch.object(+ logo_generate, "GEMINI_API_KEY", "test-key"+ ), self.assertRaises(SystemExit) as raised:+ self._run_main("--prompt", "test mark", "--output", str(self.dir / "logo.png"))++ self.assertEqual(raised.exception.code, 1)++ @patch.object(logo_generate.time, "sleep")+ @patch.object(logo_generate, "generate_logo", return_value=None)+ def test_batch_with_no_logos_exits_1(self, generate_logo, sleep):+ with self.assertRaises(SystemExit) as raised:+ self._run_main(+ "--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir)+ )++ self.assertEqual(raised.exception.code, 1)+ self.assertEqual(generate_logo.call_count, 2)++ @patch.object(logo_generate.time, "sleep")+ @patch.object(+ logo_generate, "generate_logo", side_effect=[None, "demo_modern_02.png"]+ )+ def test_partial_batch_exits_0(self, generate_logo, sleep):+ self._run_main("--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir))++ self.assertEqual(generate_logo.call_count, 2)++ def test_list_styles_exits_0(self):+ self._run_main("--list-styles")++if __name__ == "__main__":unittest.main()diff --git a/.claude/skills/design/scripts/tests/test_cip_generate.py b/.claude/skills/design/scripts/tests/test_cip_generate.pynew file mode 100644index 0000000..26e3d3b--- /dev/null+++ b/.claude/skills/design/scripts/tests/test_cip_generate.py@@ -0,0 +1,134 @@+"""Offline regression tests for cip/generate.py (no network, stubbed genai)."""++import importlib.util+import sys+import types as pytypes+from pathlib import Path+from unittest import mock++import pytest++SCRIPT = Path(__file__).resolve().parent.parent / "cip" / "generate.py"++JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"+PNG = b"\x89PNG\r\n\x1a\npng-bytes"++PROMPT_DATA = {+ "prompt": "business card mockup",+ "deliverable": "Business Card",+ "brand": "Demo",+ "style": "Corporate Minimal",+ "mockup_context": "desk",+}+++class _Config:+ def __init__(self, **kwargs):+ self.__dict__.update(kwargs)+++def load_cip(monkeypatch):+ """Return a loader for a fresh cip/generate.py with google.genai stubbed.++ cip/generate.py imports its own `core` module, which shares a name with the+ ui-ux-pro-max search core, so sys.modules and sys.path are restored afterwards.+ """+ monkeypatch.setattr(sys, "path", list(sys.path))+ monkeypatch.setenv("GEMINI_API_KEY", "test-key")+ monkeypatch.delenv("GEMINI_FLASH_IMAGE_MODEL", raising=False)+ monkeypatch.delenv("GEMINI_PRO_IMAGE_MODEL", raising=False)++ with mock.patch.dict(sys.modules):+ sys.modules.pop("core", None)+ google = pytypes.ModuleType("google")+ genai = pytypes.ModuleType("google.genai")+ types = pytypes.ModuleType("google.genai.types")+ types.GenerateContentConfig = types.ImageConfig = _Config+ genai.Client = mock.MagicMock()+ genai.types = types+ google.genai = genai+ sys.modules.update(+ {"google": google, "google.genai": genai, "google.genai.types": types}+ )++ def load():+ spec = importlib.util.spec_from_file_location("cip_generate_under_test", SCRIPT)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ mod.client = genai.Client.return_value+ return mod++ yield load+++def cip(load_cip):+ return load_cip()+++def _image_response(mime_type, data):+ part = pytypes.SimpleNamespace(+ inline_data=pytypes.SimpleNamespace(mime_type=mime_type, data=data))+ return pytypes.SimpleNamespace(+ candidates=[pytypes.SimpleNamespace(content=pytypes.SimpleNamespace(parts=[part]))])+++def _run_main(cip, monkeypatch, *args):+ monkeypatch.setattr(sys, "argv", ["generate.py", "--brand", "Demo", *args])+ cip.main()++[email protected]("mime_type, data, extension", [+ ("image/jpeg", JPEG, ".jpg"),+ ("image/png", PNG, ".png"),+ ("image/webp", b"RIFFwebp", ".webp"),+])+def test_mockup_extension_follows_returned_image_type(cip, tmp_path, mime_type, data, extension):+ cip.client.models.generate_content.return_value = _image_response(mime_type, data)+ filepath = cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")+ assert Path(filepath).suffix == extension+ assert Path(filepath).read_bytes() == data+++def test_pro_uses_the_ga_model(cip, tmp_path):+ cip.client.models.generate_content.return_value = _image_response("image/png", PNG)+ cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")+ assert cip.client.models.generate_content.call_args.kwargs["model"] == "gemini-3-pro-image"+++def test_model_ids_can_be_overridden_from_the_environment(load_cip, monkeypatch):+ monkeypatch.setenv("GEMINI_FLASH_IMAGE_MODEL", "flash-next")+ monkeypatch.setenv("GEMINI_PRO_IMAGE_MODEL", "pro-next")+ assert load_cip().MODELS == {"flash": "flash-next", "pro": "pro-next"}+++def test_main_exits_1_when_single_deliverable_fails(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(cip, monkeypatch, "--deliverable", "business card", "--no-logo-prompt",+ "--output", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_1_when_every_deliverable_in_a_set_fails(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",+ "--no-logo-prompt", "--output", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_0_when_part_of_a_set_is_generated(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = [+ RuntimeError("429 RESOURCE_EXHAUSTED"),+ _image_response("image/png", PNG),+ ]+ _run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",+ "--no-logo-prompt", "--output", str(tmp_path))+ assert len(list(tmp_path.glob("*.png"))) == 1+++def test_main_prompt_only_exits_0(cip, monkeypatch):+ _run_main(cip, monkeypatch, "--deliverable", "business card", "--prompt-only")+ cip.client.models.generate_content.assert_not_called()diff --git a/.claude/skills/design/scripts/tests/test_icon_generate.py b/.claude/skills/design/scripts/tests/test_icon_generate.pyindex dc44b62..7fb777a 100644--- a/.claude/skills/design/scripts/tests/test_icon_generate.py+++ b/.claude/skills/design/scripts/tests/test_icon_generate.py@@ -140,3 +140,39 @@ def test_generate_batch_warns_when_truncated_after_some_icons(gen, tmp_path, cap'<svg viewBox="0 0 24 24"><path d="M 15 14 H 19', "MAX_TOKENS")assert len(gen.generate_batch("crane", 2, str(tmp_path))) == 1assert "MAX_TOKENS" in capsys.readouterr().out+++def _run_main(gen, monkeypatch, *args):+ monkeypatch.setattr(sys, "argv", ["generate.py", *args])+ gen.main()+++def test_main_exits_1_when_icon_request_fails(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))+ assert raised.value.code == 1+++def test_main_exits_1_when_batch_generates_nothing(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ resp = _response(None, "SAFETY")+ resp.candidates = []+ client.models.generate_content.return_value = resp+ with pytest.raises(SystemExit) as raised:+ _run_main(gen, monkeypatch, "--prompt", "crane", "--batch", "2",+ "--output-dir", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_0_when_icon_is_saved(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ client.models.generate_content.return_value = _response(+ '<svg viewBox="0 0 24 24"><path d="M0 0"/></svg>')+ _run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))+ assert (tmp_path / "a.svg").exists()+++def test_main_list_styles_exits_0(gen, monkeypatch):+ _run_main(gen, monkeypatch, "--list-styles")diff --git a/cli/assets/skills/design/SKILL.md b/cli/assets/skills/design/SKILL.mdindex 6ffc503..0dda900 100644--- a/cli/assets/skills/design/SKILL.md+++ b/cli/assets/skills/design/SKILL.md@@ -111,7 +111,7 @@ python3 scripts/cip/generate.py --brand "TopGroup" --logo logo.png --deliverablepython3 scripts/cip/generate.py --brand "TechFlow" --deliverable "business card" --no-logo-prompt```-Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image-preview`)+Models: `flash` (default, `gemini-2.5-flash-image`), `pro` (`gemini-3-pro-image`). Override the ids with `GEMINI_FLASH_IMAGE_MODEL` / `GEMINI_PRO_IMAGE_MODEL`.### CIP: Render HTML Presentationdiff --git a/cli/assets/skills/design/references/cip-design.md b/cli/assets/skills/design/references/cip-design.mdindex 4037769..877ae71 100644--- a/cli/assets/skills/design/references/cip-design.md+++ b/cli/assets/skills/design/references/cip-design.md@@ -64,7 +64,9 @@ python3 scripts/cip/render-html.py --brand "TopGroup" --industry "consulting" --## Models- `flash` (default): `gemini-2.5-flash-image` - Fast, cost-effective-- `pro`: `gemini-3-pro-image-preview` - Quality, 4K text rendering+- `pro`: `gemini-3-pro-image` - Quality, 4K text rendering++Set `GEMINI_FLASH_IMAGE_MODEL` or `GEMINI_PRO_IMAGE_MODEL` to use another Gemini model id.## Deliverable Categoriesdiff --git a/cli/assets/skills/design/scripts/cip/generate.py b/cli/assets/skills/design/scripts/cip/generate.pyindex e92b2e1..394b06d 100644--- a/cli/assets/skills/design/scripts/cip/generate.py+++ b/cli/assets/skills/design/scripts/cip/generate.py@@ -7,11 +7,19 @@ Uses Gemini's native image generation (Nano Banana Flash/Pro) for high-quality mSupports text-and-image-to-image generation for using actual brand logos.- gemini-2.5-flash-image: Fast generation, cost-effective (default)-- gemini-3-pro-image-preview: Pro quality, 4K text rendering+- gemini-3-pro-image: Pro quality, 4K text rendering++Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini+model id, for example when Google retires one of these.Image Editing (text-and-image-to-image):When --logo is provided, the script uses Gemini's image editing capabilityto incorporate the actual logo into CIP mockups instead of generating one.++Each mockup is saved with the extension of the image type Gemini returns+(.png, .jpg or .webp). Exit status is 1 when nothing was generated: a failed+single deliverable, or a set where every deliverable failed. A set where some+deliverables succeed exits 0 and reports how many were generated."""import argparse@@ -25,13 +33,6 @@ from datetime import datetimesys.path.insert(0, str(Path(__file__).parent))from core import search, get_cip_brief-# Model options-MODELS = {- "flash": "gemini-2.5-flash-image", # Nano Banana Flash - fast, default- "pro": "gemini-3-pro-image-preview" # Nano Banana Pro - quality, 4K text-}-DEFAULT_MODEL = "flash"-def load_logo_image(logo_path):"""Load logo image using PIL for Gemini image editing"""@@ -85,6 +86,16 @@ def load_env():load_env()+# Model options (read after load_env so .env files can override the ids)+MODELS = {+ "flash": os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image", # Nano Banana Flash - fast, default+ "pro": os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image" # Nano Banana Pro - quality, 4K text+}+DEFAULT_MODEL = "flash"++# File extensions for the image types Gemini returns as inline data+IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}+def build_cip_prompt(deliverable, brand_name, style=None, industry=None, mockup=None, use_logo_image=False):"""Build an optimized prompt for CIP mockup generation@@ -192,7 +203,7 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", aModels:- flash: gemini-2.5-flash-image (fast, cost-effective) - DEFAULT- - pro: gemini-3-pro-image-preview (quality, 4K text rendering)+ - pro: gemini-3-pro-image (quality, 4K text rendering)Args:prompt_data: Dict with prompt, deliverable, brand, etc.@@ -265,7 +276,9 @@ def generate_with_nano_banana(prompt_data, output_dir=None, model_key="flash", atimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")brand_slug = prompt_data["brand"].lower().replace(" ", "-")deliverable_slug = prompt_data["deliverable"].lower().replace(" ", "-")- filename = f"{brand_slug}-{deliverable_slug}-{timestamp}.png"+ mime_type = (part.inline_data.mime_type or "").split(";")[0].strip().lower()+ extension = IMAGE_EXTENSIONS.get(mime_type, ".png")+ filename = f"{brand_slug}-{deliverable_slug}-{timestamp}{extension}"filepath = output_dir / filenameimage_data = part.inline_data.data@@ -390,7 +403,7 @@ Examples:Models:flash (default): gemini-2.5-flash-image - Fast, cost-effective- pro: gemini-3-pro-image-preview - Quality, 4K text rendering+ pro: gemini-3-pro-image - Quality, 4K text renderingImage Editing Mode:When --logo is provided, uses Gemini's text-and-image-to-image capability@@ -464,6 +477,8 @@ Image Editing Mode:print(json.dumps(results, indent=2))else:print(f"\n✅ Generated {len(results)} CIP mockups")+ if not results:+ sys.exit(1)else:# Generate single deliverabledeliverable = args.deliverable or "business card"@@ -481,6 +496,8 @@ Image Editing Mode:)if args.json:print(json.dumps({"filepath": filepath, **prompt_data}, indent=2))+ if filepath is None:+ sys.exit(1)if __name__ == "__main__":diff --git a/cli/assets/skills/design/scripts/icon/generate.py b/cli/assets/skills/design/scripts/icon/generate.pyindex 7d3a338..375f789 100644--- a/cli/assets/skills/design/scripts/icon/generate.py+++ b/cli/assets/skills/design/scripts/icon/generate.py@@ -493,7 +493,7 @@ def main():# Multi-size modeif args.sizes:sizes = [int(s.strip()) for s in args.sizes.split(",")]- generate_sizes(+ generated = generate_sizes(prompt=prompt,sizes=sizes,style=args.style,@@ -504,7 +504,7 @@ def main():# Batch modeelif args.batch:output_dir = args.output_dir or "./icons"- generate_batch(+ generated = generate_batch(prompt=prompt,count=args.batch,output_dir=output_dir,@@ -515,7 +515,7 @@ def main():)# Single iconelse:- generate_icon(+ generated = generate_icon(prompt=prompt,style=args.style,category=args.category,@@ -526,6 +526,10 @@ def main():viewbox=args.viewbox)+ # Exit 1 when nothing was generated; a partly generated batch or size set exits 0+ if not generated:+ sys.exit(1)+if __name__ == "__main__":main()diff --git a/cli/assets/skills/design/scripts/logo/generate.py b/cli/assets/skills/design/scripts/logo/generate.pyindex d006c13..3b5773f 100644--- a/cli/assets/skills/design/scripts/logo/generate.py+++ b/cli/assets/skills/design/scripts/logo/generate.py@@ -8,9 +8,20 @@ with the selected model's prompt/aspect-ratio contract.Models:- Nano Banana (default): gemini-2.5-flash-image - fast, high-volume, low-latency-- Nano Banana Pro (--pro): gemini-3-pro-image-preview - professional quality, advanced reasoning+- Nano Banana Pro (--pro): gemini-3-pro-image - professional quality, advanced reasoning- MuAPI Nano Banana (--provider muapi): nano-banana - hosted asynchronous image generation+Set GEMINI_FLASH_IMAGE_MODEL or GEMINI_PRO_IMAGE_MODEL to use another Gemini+model id, for example when Google retires one of these.++Gemini returns PNG or JPEG data. The file gets the extension of the returned+type, so ``--output logo.png`` can be saved as ``logo.jpg``; the path actually+written is printed.++Exit status is 1 when nothing was generated: a failed single request, or a+batch where every variant failed. A batch where some variants succeed exits 0+and reports how many were generated.+Usage:python generate.py --prompt "tech startup logo minimalist blue"python generate.py --prompt "coffee shop vintage badge" --style vintage --output logo.png@@ -28,6 +39,7 @@ import argparseimport ipaddressimport jsonimport os+import sysimport timefrom datetime import datetimefrom pathlib import Path@@ -65,8 +77,15 @@ ATLASCLOUD_API_KEY = os.environ.get("ATLASCLOUD_API_KEY")MUAPI_API_KEY = os.environ.get("MUAPI_API_KEY")# Gemini "Nano Banana" model configurations for image generation-GEMINI_FLASH = "gemini-2.5-flash-image" # Nano Banana: fast, high-volume, low-latency-GEMINI_PRO = "gemini-3-pro-image-preview" # Nano Banana Pro: professional quality, advanced reasoning+GEMINI_FLASH = (+ os.environ.get("GEMINI_FLASH_IMAGE_MODEL") or "gemini-2.5-flash-image"+) # Nano Banana: fast, high-volume, low-latency+GEMINI_PRO = (+ os.environ.get("GEMINI_PRO_IMAGE_MODEL") or "gemini-3-pro-image"+) # Nano Banana Pro: professional quality, advanced reasoning++# File extensions for the image types Gemini returns as inline data+IMAGE_EXTENSIONS = {"image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp"}# Atlas Cloud model validated against the live model catalog and schema.ATLAS_MODEL = "google/nano-banana-2-lite/text-to-image"@@ -431,7 +450,21 @@ def _generate_with_muapi(prompt, output_path, aspect_ratio, api_key, model):raise RuntimeError("MuAPI prediction timed out while polling")+def _path_for_image_type(output_path, mime_type):+ """Return output_path with the extension of the returned image type.++ An unknown image type keeps the requested path.+ """+ extension = IMAGE_EXTENSIONS.get(mime_type.split(";")[0].strip().lower())+ path = Path(output_path)+ suffix = path.suffix.lower()+ if extension is None or suffix == extension or (suffix, extension) == (".jpeg", ".jpg"):+ return output_path+ return str(path.with_suffix(extension))++def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):+ """Generate with Gemini and return the path the image was saved to."""if not GEMINI_API_KEY:raise RuntimeError("GEMINI_API_KEY not set")@@ -478,9 +511,15 @@ def _generate_with_gemini(prompt, output_path, aspect_ratio, use_pro):and part.inline_dataand part.inline_data.mime_type.startswith("image/")):- with open(output_path, "wb") as output_file:+ saved_path = _path_for_image_type(output_path, part.inline_data.mime_type)+ if saved_path != output_path:+ print(+ f"Gemini returned {part.inline_data.mime_type}, "+ f"so saving as {saved_path} instead of {output_path}"+ )+ with open(saved_path, "wb") as output_file:output_file.write(part.inline_data.data)- return+ return saved_pathraise RuntimeError("Gemini did not return an image")@@ -520,9 +559,9 @@ def generate_logo(model_label = f"MuAPI ({muapi_model})"else:model_label = (- "Nano Banana Pro (gemini-3-pro-image-preview)"+ f"Nano Banana Pro ({GEMINI_PRO})"if use_pro- else "Nano Banana (gemini-2.5-flash-image)"+ else f"Nano Banana ({GEMINI_FLASH})")print(f"Generating logo with {model_label}...")@@ -548,7 +587,7 @@ def generate_logo(muapi_model,)else:- _generate_with_gemini(full_prompt, output_path, ratio, use_pro)+ output_path = _generate_with_gemini(full_prompt, output_path, ratio, use_pro)print(f"Logo saved to: {output_path}")return output_path@@ -635,7 +674,7 @@ def generate_batch(if result:results.append(result)- print(f" ✓ Saved: {filename}\n")+ print(f" ✓ Saved: {os.path.basename(result)}\n")else:print(f" ✗ Failed: {style_key}\n")@@ -675,7 +714,7 @@ def main():parser.add_argument("--pro",action="store_true",- help="Use Nano Banana Pro (gemini-3-pro-image-preview) for professional quality",+ help=f"Use Nano Banana Pro ({GEMINI_PRO}) for professional quality",)parser.add_argument("--provider",@@ -738,7 +777,7 @@ def main():output_dir = (args.output_dir or f"./{args.brand.lower().replace(' ', '_')}_logos")- generate_batch(+ results = generate_batch(prompt=prompt,brand_name=args.brand or "Logo",count=args.batch,@@ -750,8 +789,10 @@ def main():atlas_model=args.atlas_model,muapi_model=args.muapi_model,)+ if not results:+ sys.exit(1)else:- generate_logo(+ saved_path = generate_logo(prompt=prompt,style=args.style,industry=args.industry,@@ -763,6 +804,8 @@ def main():atlas_model=args.atlas_model,muapi_model=args.muapi_model,)+ if saved_path is None:+ sys.exit(1)if __name__ == "__main__":diff --git a/cli/assets/skills/design/scripts/logo/tests/test_generate.py b/cli/assets/skills/design/scripts/logo/tests/test_generate.pyindex 9c2addc..e0ca6ca 100644--- a/cli/assets/skills/design/scripts/logo/tests/test_generate.py+++ b/cli/assets/skills/design/scripts/logo/tests/test_generate.py@@ -1,13 +1,46 @@import importlib.util+import io+import os+import sysimport tempfileimport unittestfrom pathlib import Path-from unittest.mock import call, patch+from types import ModuleType, SimpleNamespace+from unittest.mock import Mock, call, patchMODULE_PATH = Path(__file__).parents[1] / "generate.py"-SPEC = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)-logo_generate = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(logo_generate)+++def _load_module():+ spec = importlib.util.spec_from_file_location("logo_generate", MODULE_PATH)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++logo_generate = _load_module()++JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"+PNG = b"\x89PNG\r\n\x1a\npng-bytes"+++def _image_response(mime_type, data):+ part = SimpleNamespace(inline_data=SimpleNamespace(mime_type=mime_type, data=data))+ return SimpleNamespace(+ candidates=[SimpleNamespace(content=SimpleNamespace(parts=[part]))]+ )+++def _fake_genai(client):+ """sys.modules entries for an offline google.genai whose Client is client."""+ types = ModuleType("google.genai.types")+ types.GenerateContentConfig = types.ImageConfig = types.SafetySetting = dict+ genai = ModuleType("google.genai")+ genai.Client = lambda api_key: client+ genai.types = types+ google = ModuleType("google")+ google.genai = genai+ return {"google": google, "google.genai": genai, "google.genai.types": types}class AtlasGenerationTests(unittest.TestCase):@@ -284,5 +317,138 @@ class MuapiGenerationTests(unittest.TestCase):json_request.assert_called_once()+class GeminiImageTypeTests(unittest.TestCase):+ def setUp(self):+ self.client = Mock()+ for patcher in (+ patch.dict(sys.modules, _fake_genai(self.client)),+ patch.object(logo_generate, "GEMINI_API_KEY", "test-key"),+ ):+ patcher.start()+ self.addCleanup(patcher.stop)+ temp_dir = tempfile.TemporaryDirectory()+ self.addCleanup(temp_dir.cleanup)+ self.dir = Path(temp_dir.name)++ def _generate(self, mime_type, data, requested_name):+ self.client.models.generate_content.return_value = _image_response(+ mime_type, data+ )+ return logo_generate._generate_with_gemini(+ "logo prompt", str(self.dir / requested_name), "1:1", use_pro=True+ )++ def test_jpeg_is_saved_with_jpg_extension(self):+ with patch("sys.stdout", new_callable=io.StringIO):+ saved = self._generate("image/jpeg", JPEG, "logo.png")++ self.assertEqual(saved, str(self.dir / "logo.jpg"))+ self.assertEqual(Path(saved).read_bytes(), JPEG)+ self.assertFalse((self.dir / "logo.png").exists())++ def test_matching_extension_keeps_requested_path(self):+ for mime_type, data, name in (+ ("image/png", PNG, "logo.png"),+ ("image/jpeg", JPEG, "logo.jpeg"),+ ("image/jpeg", JPEG, "logo.JPG"),+ ):+ with self.subTest(name=name):+ saved = self._generate(mime_type, data, name)+ self.assertEqual(saved, str(self.dir / name))+ self.assertEqual(Path(saved).read_bytes(), data)++ def test_unknown_image_type_keeps_requested_path(self):+ self.assertEqual(+ logo_generate._path_for_image_type("logo.png", "image/heic"), "logo.png"+ )++ def test_generate_logo_prints_and_returns_the_saved_path(self):+ self.client.models.generate_content.return_value = _image_response(+ "image/jpeg", JPEG+ )+ with patch("sys.stdout", new_callable=io.StringIO) as stdout:+ saved = logo_generate.generate_logo(+ "test mark", output_path=str(self.dir / "logo.png"), use_pro=True+ )++ self.assertEqual(saved, str(self.dir / "logo.jpg"))+ self.assertIn(f"Logo saved to: {saved}", stdout.getvalue())++ def test_pro_requests_the_configured_pro_model(self):+ self._generate("image/png", PNG, "logo.png")++ self.assertEqual(+ self.client.models.generate_content.call_args.kwargs["model"],+ logo_generate.GEMINI_PRO,+ )+++class GeminiModelIdTests(unittest.TestCase):+ def test_pro_defaults_to_the_ga_model(self):+ with patch.dict(os.environ):+ os.environ.pop("GEMINI_PRO_IMAGE_MODEL", None)+ module = _load_module()++ self.assertEqual(module.GEMINI_PRO, "gemini-3-pro-image")++ def test_model_ids_can_be_overridden_from_the_environment(self):+ with patch.dict(+ os.environ,+ {"GEMINI_FLASH_IMAGE_MODEL": "flash-next", "GEMINI_PRO_IMAGE_MODEL": "pro-next"},+ ):+ module = _load_module()++ self.assertEqual(module.GEMINI_FLASH, "flash-next")+ self.assertEqual(module.GEMINI_PRO, "pro-next")+++class ExitStatusTests(unittest.TestCase):+ def setUp(self):+ temp_dir = tempfile.TemporaryDirectory()+ self.addCleanup(temp_dir.cleanup)+ self.dir = Path(temp_dir.name)++ def _run_main(self, *args):+ with patch.object(sys, "argv", ["generate.py", *args]), patch(+ "sys.stdout", new_callable=io.StringIO+ ):+ logo_generate.main()++ def test_failed_single_request_exits_1(self):+ client = Mock()+ client.models.generate_content.side_effect = RuntimeError(+ "429 RESOURCE_EXHAUSTED"+ )+ with patch.dict(sys.modules, _fake_genai(client)), patch.object(+ logo_generate, "GEMINI_API_KEY", "test-key"+ ), self.assertRaises(SystemExit) as raised:+ self._run_main("--prompt", "test mark", "--output", str(self.dir / "logo.png"))++ self.assertEqual(raised.exception.code, 1)++ @patch.object(logo_generate.time, "sleep")+ @patch.object(logo_generate, "generate_logo", return_value=None)+ def test_batch_with_no_logos_exits_1(self, generate_logo, sleep):+ with self.assertRaises(SystemExit) as raised:+ self._run_main(+ "--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir)+ )++ self.assertEqual(raised.exception.code, 1)+ self.assertEqual(generate_logo.call_count, 2)++ @patch.object(logo_generate.time, "sleep")+ @patch.object(+ logo_generate, "generate_logo", side_effect=[None, "demo_modern_02.png"]+ )+ def test_partial_batch_exits_0(self, generate_logo, sleep):+ self._run_main("--brand", "Demo", "--batch", "2", "--output-dir", str(self.dir))++ self.assertEqual(generate_logo.call_count, 2)++ def test_list_styles_exits_0(self):+ self._run_main("--list-styles")++if __name__ == "__main__":unittest.main()diff --git a/cli/assets/skills/design/scripts/tests/test_cip_generate.py b/cli/assets/skills/design/scripts/tests/test_cip_generate.pynew file mode 100644index 0000000..26e3d3b--- /dev/null+++ b/cli/assets/skills/design/scripts/tests/test_cip_generate.py@@ -0,0 +1,134 @@+"""Offline regression tests for cip/generate.py (no network, stubbed genai)."""++import importlib.util+import sys+import types as pytypes+from pathlib import Path+from unittest import mock++import pytest++SCRIPT = Path(__file__).resolve().parent.parent / "cip" / "generate.py"++JPEG = b"\xff\xd8\xff\xe0jpeg-bytes"+PNG = b"\x89PNG\r\n\x1a\npng-bytes"++PROMPT_DATA = {+ "prompt": "business card mockup",+ "deliverable": "Business Card",+ "brand": "Demo",+ "style": "Corporate Minimal",+ "mockup_context": "desk",+}+++class _Config:+ def __init__(self, **kwargs):+ self.__dict__.update(kwargs)+++def load_cip(monkeypatch):+ """Return a loader for a fresh cip/generate.py with google.genai stubbed.++ cip/generate.py imports its own `core` module, which shares a name with the+ ui-ux-pro-max search core, so sys.modules and sys.path are restored afterwards.+ """+ monkeypatch.setattr(sys, "path", list(sys.path))+ monkeypatch.setenv("GEMINI_API_KEY", "test-key")+ monkeypatch.delenv("GEMINI_FLASH_IMAGE_MODEL", raising=False)+ monkeypatch.delenv("GEMINI_PRO_IMAGE_MODEL", raising=False)++ with mock.patch.dict(sys.modules):+ sys.modules.pop("core", None)+ google = pytypes.ModuleType("google")+ genai = pytypes.ModuleType("google.genai")+ types = pytypes.ModuleType("google.genai.types")+ types.GenerateContentConfig = types.ImageConfig = _Config+ genai.Client = mock.MagicMock()+ genai.types = types+ google.genai = genai+ sys.modules.update(+ {"google": google, "google.genai": genai, "google.genai.types": types}+ )++ def load():+ spec = importlib.util.spec_from_file_location("cip_generate_under_test", SCRIPT)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ mod.client = genai.Client.return_value+ return mod++ yield load+++def cip(load_cip):+ return load_cip()+++def _image_response(mime_type, data):+ part = pytypes.SimpleNamespace(+ inline_data=pytypes.SimpleNamespace(mime_type=mime_type, data=data))+ return pytypes.SimpleNamespace(+ candidates=[pytypes.SimpleNamespace(content=pytypes.SimpleNamespace(parts=[part]))])+++def _run_main(cip, monkeypatch, *args):+ monkeypatch.setattr(sys, "argv", ["generate.py", "--brand", "Demo", *args])+ cip.main()++[email protected]("mime_type, data, extension", [+ ("image/jpeg", JPEG, ".jpg"),+ ("image/png", PNG, ".png"),+ ("image/webp", b"RIFFwebp", ".webp"),+])+def test_mockup_extension_follows_returned_image_type(cip, tmp_path, mime_type, data, extension):+ cip.client.models.generate_content.return_value = _image_response(mime_type, data)+ filepath = cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")+ assert Path(filepath).suffix == extension+ assert Path(filepath).read_bytes() == data+++def test_pro_uses_the_ga_model(cip, tmp_path):+ cip.client.models.generate_content.return_value = _image_response("image/png", PNG)+ cip.generate_with_nano_banana(PROMPT_DATA, tmp_path, model_key="pro")+ assert cip.client.models.generate_content.call_args.kwargs["model"] == "gemini-3-pro-image"+++def test_model_ids_can_be_overridden_from_the_environment(load_cip, monkeypatch):+ monkeypatch.setenv("GEMINI_FLASH_IMAGE_MODEL", "flash-next")+ monkeypatch.setenv("GEMINI_PRO_IMAGE_MODEL", "pro-next")+ assert load_cip().MODELS == {"flash": "flash-next", "pro": "pro-next"}+++def test_main_exits_1_when_single_deliverable_fails(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(cip, monkeypatch, "--deliverable", "business card", "--no-logo-prompt",+ "--output", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_1_when_every_deliverable_in_a_set_fails(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",+ "--no-logo-prompt", "--output", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_0_when_part_of_a_set_is_generated(cip, monkeypatch, tmp_path):+ cip.client.models.generate_content.side_effect = [+ RuntimeError("429 RESOURCE_EXHAUSTED"),+ _image_response("image/png", PNG),+ ]+ _run_main(cip, monkeypatch, "--deliverables", "business card,letterhead",+ "--no-logo-prompt", "--output", str(tmp_path))+ assert len(list(tmp_path.glob("*.png"))) == 1+++def test_main_prompt_only_exits_0(cip, monkeypatch):+ _run_main(cip, monkeypatch, "--deliverable", "business card", "--prompt-only")+ cip.client.models.generate_content.assert_not_called()diff --git a/cli/assets/skills/design/scripts/tests/test_icon_generate.py b/cli/assets/skills/design/scripts/tests/test_icon_generate.pyindex dc44b62..7fb777a 100644--- a/cli/assets/skills/design/scripts/tests/test_icon_generate.py+++ b/cli/assets/skills/design/scripts/tests/test_icon_generate.py@@ -140,3 +140,39 @@ def test_generate_batch_warns_when_truncated_after_some_icons(gen, tmp_path, cap'<svg viewBox="0 0 24 24"><path d="M 15 14 H 19', "MAX_TOKENS")assert len(gen.generate_batch("crane", 2, str(tmp_path))) == 1assert "MAX_TOKENS" in capsys.readouterr().out+++def _run_main(gen, monkeypatch, *args):+ monkeypatch.setattr(sys, "argv", ["generate.py", *args])+ gen.main()+++def test_main_exits_1_when_icon_request_fails(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ client.models.generate_content.side_effect = RuntimeError("429 RESOURCE_EXHAUSTED")+ with pytest.raises(SystemExit) as raised:+ _run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))+ assert raised.value.code == 1+++def test_main_exits_1_when_batch_generates_nothing(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ resp = _response(None, "SAFETY")+ resp.candidates = []+ client.models.generate_content.return_value = resp+ with pytest.raises(SystemExit) as raised:+ _run_main(gen, monkeypatch, "--prompt", "crane", "--batch", "2",+ "--output-dir", str(tmp_path))+ assert raised.value.code == 1+++def test_main_exits_0_when_icon_is_saved(gen, monkeypatch, tmp_path):+ client = gen.genai.Client.return_value+ client.models.generate_content.return_value = _response(+ '<svg viewBox="0 0 24 24"><path d="M0 0"/></svg>')+ _run_main(gen, monkeypatch, "--prompt", "crane", "--output", str(tmp_path / "a.svg"))+ assert (tmp_path / "a.svg").exists()+++def test_main_list_styles_exits_0(gen, monkeypatch):+ _run_main(gen, monkeypatch, "--list-styles")