Skip to content
Back to search

opendesigner

OpenDesigner: create a design system with your own AI, one sourced decision at a time.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/ckryptickunal/OpenDesigner with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/ckryptickunal/OpenDesigner'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ckryptickunal--opendesigner/badge.svg)](/listings/ckryptickunal--opendesigner)

HTML

<a href="/listings/ckryptickunal--opendesigner"><img src="/api/listings/ckryptickunal--opendesigner/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. Add OpenDesigner to your AI tool. Pick yours below. 2. Open your project and say: **"Create a design system for this project."** 3. Answer a few short questions. It reads your files first, so it asks less.

**Claude Code**

/plugin marketplace add ckryptickunal/OpenDesigner
/plugin install opendesigner@opendesigner

<details> <summary><b>Claude app</b> (claude.ai or Desktop)</summary>

Build the skill zip, then upload `dist/opendesigner.zip` under Customize > Skills. Code execution must be on.

git clone https://github.com/ckryptickunal/OpenDesigner && cd OpenDesigner
python3 tools/build_dist.py        # writes the zip files into dist/

</details>

<details> <summary><b>Codex, Cursor, VS Code with Copilot, Gemini CLI and other agents</b></summary>

These tools read skills from `.agents/skills/`. Copy the OpenDesigner skills into your project. Tools that support Agent Plugins can also read the root `plugin.json`.

git clone https://github.com/ckryptickunal/OpenDesigner
mkdir -p your-project/.agents/skills
cp -R OpenDesigner/.agents/skills/opendesigner* your-project/.agents/skills/

</details>

<details> <summary><b>ChatGPT</b> (web, any plan, nothing to install)</summary>

1. Create a Project. 2. Paste [`chatgpt-project/instructions.md`](chatgpt-project/instructions.md) (the part below its line) into the Project instructions. 3. Upload the five files in [`chatgpt-project/knowledge/`](chatgpt-project/knowledge/).

</details>

<details> <summary><b>No AI at all</b> (the engine on its own)</summary>

The engine is one Python file (Python 3.10 or newer, nothing to install). It writes `DESIGN.md`, `PRODUCT.md` and an `opendesigner/` folder with tokens, exports and an overview page.

python3 path/to/OpenDesigner/skills/opendesigner/scripts/engine.py sketch --name "Acme" --feel friendly,minimal

</details>

You need your own AI tool and Python 3.10 or newer. The engine makes no network calls ([privacy](docs/PRIVACY.md)). Help for each tool: [install guide](https://opendesigner.dev/docs/install/).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 14 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. {
  2. "name": "opendesigner",
  3. "owner": { "name": "ckryptickunal", "url": "https://github.com/ckryptickunal" },
  4. "description": "OpenDesigner: create a design system with your own AI, one sourced decision at a time.",
  5. "plugins": [
  6. {
  7. "name": "opendesigner",
  8. "source": "./",
  9. "description": "Nine skills: opendesigner (the interview), opendesigner-extract (learn from a reference without copying identity), opendesigner-extend (change a system safely), opendesigner-export (code, Figma, Paper), opendesigner-illustrate (open-licence illustrations recolored to your tokens), opendesigner-review (check a built UI at every size, theme, state and motion, with measurements and evidence), opendesigner-paint (original art and films painted in code in your palette), opendesigner-preflight (the silly mistakes to check before exporting anything visual), opendesigner-search (get a site found by search engines and AI answers).",
  10. "category": "design",
  11. "tags": ["design-system", "design-tokens", "theme", "figma"]
  12. }
  13. ]
  14. }
README.md · README · 175 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. <p align="center">
  2. <a href="https://opendesigner.dev">
  3. <picture>
  4. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/banner-narrow.png">
  5. <img src="brand/kit/readme/banner.png" width="1012" alt="OpenDesigner. Make everything you build look like it belongs together. Your AI tools know what to build. OpenDesigner tells them how it should look.">
  6. </picture>
  7. </a>
  8. </p>
  9. <p align="center">
  10. <a href="https://opendesigner.dev"><b>Website</b></a> &nbsp;·&nbsp;
  11. <a href="https://opendesigner.dev/docs/">Docs</a> &nbsp;·&nbsp;
  12. <a href="https://opendesigner.dev/showcase/">Showcase</a> &nbsp;·&nbsp;
  13. <a href="#quickstart">Install</a> &nbsp;·&nbsp;
  14. <a href="CONTRIBUTING.md">Contribute</a> &nbsp;·&nbsp;
  15. <a href="https://calendar.app.google/42qSQUrBiSL4CHfv6">Book a 20-minute intro call</a>
  16. </p>
  17. **A free, open-source (MIT) add-on for your AI coding tool. It gives your product one design system and checks every screen against it.**
  18. ```
  19. /plugin marketplace add ckryptickunal/OpenDesigner
  20. /plugin install opendesigner@opendesigner
  21. ```
  22. Two commands in Claude Code. Then up to five questions, planned at about 3 minutes, give you a first version.
  23. On the Claude app, ChatGPT, Cursor or Codex, or have no terminal? [Pick your tool below](#quickstart).
  24. <p align="center">
  25. <picture>
  26. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/works-in-narrow.png">
  27. <img src="brand/kit/readme/works-in.png" width="1012" alt="Works in Claude Code and the Claude app, ChatGPT and Codex, Cursor, GitHub Copilot and Gemini CLI.">
  28. </picture>
  29. </p>
  30. ## Two ways in
  31. **Fix what you built.** It audits every button, font, size, color and alignment on your pages, marks each problem with the rule it breaks, and fixes it after your yes.
  32. **Build a system.** It reads your repo, studies your competitors, proposes a positioning and three directions, then writes the rules your AI follows.
  33. <picture>
  34. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/before-after-narrow.png">
  35. <img src="brand/kit/readme/before-after.png" width="1012" alt="Two versions of an invoices page. Today: seven issues boxed and numbered, such as three filled buttons, gray text at 2.54:1, amounts that don't line up and status shown by color alone. Fixed: the same page on its own design system, with a check where each fix landed and the money shown as a bento of small charts.">
  36. </picture>
  37. ## Smart UI
  38. **Answer with interface, not paragraphs.** Your assistant shows a part of your own system, like a fine with a Pay button, made ahead of time from your components. Your data fills it and picks its colours, and anything that pays or books asks first.
  39. <picture>
  40. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/smart-ui-live-narrow.png">
  41. <img src="brand/kit/readme/smart-ui-live.png" width="1012" alt="A council assistant has answered 'Do I have any fines?' with one sentence, then an unpaid-fine card: reference, date, place, reason, full amount £70.00, £35.00 if paid by Thursday 19 November, status Unpaid, and a Pay £35.00 button. Beside it, every step is done: the agent fetched the fines and wrote the sentence, Smart UI matched a ready-made card, drew its outline, filled it in and checked it.">
  42. </picture>
  43. <picture>
  44. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/smart-ui-screens-narrow.png">
  45. <img src="brand/kit/readme/smart-ui-screens.png" width="1012" alt="Three finished answers from three example apps: a council's table of parking fines, a billing tool's line chart of API calls this year, and a travel assistant's three flights from Bristol to Lisbon.">
  46. </picture>
  47. [Watch the recorded demo](https://opendesigner.dev/smart-ui/) · [Add it to your assistant](https://opendesigner.dev/docs/smart-ui-quickstart/)
  48. ## Every round
  49. - **A plan you sign off,** step by step, written to `opendesigner/PROTOCOL.md` so any AI follows it.
  50. - **Checks before you see it:** contrast, tap targets, type scale, letter-spacing, alignment, buttons, text over images.
  51. - **Screenshots,** before and after. Not a link to open.
  52. - **Your notes stick.** Say something twice and it becomes a rule.
  53. ## What lands in your repo
  54. `DESIGN.md`, `PRODUCT.md`, design tokens (DTCG), CSS, Tailwind, Figma, Swift and Compose exports, a brand and press page, and a log of every choice with its reason.
  55. ## Quickstart
  56. 1. Add OpenDesigner to your AI tool. Pick yours below.
  57. 2. Open your project and say: **"Create a design system for this project."** Already built something? Say: **"Make this app look professional."** It audits first and changes nothing until you say yes.
  58. 3. Answer a few short questions. It reads your files first, so it asks less.
  59. The audit measures your running app in a browser, so it needs a coding agent that can drive one or run Playwright, such as Claude Code. The ChatGPT bundle doesn't include it.
  60. **Claude Code:** the two commands at the top of this page, then start a new session.
  61. <details>
  62. <summary><b>Claude app</b> (claude.ai or Desktop, no terminal)</summary>
  63. Download [opendesigner.zip](https://opendesigner.dev/.well-known/agent-skills/opendesigner.zip) and upload it under Customize > Skills. Code execution must be on. That zip builds a system. To audit an app you already built, also upload [opendesigner-review.zip](https://opendesigner.dev/.well-known/agent-skills/opendesigner-review.zip) and [opendesigner-extract.zip](https://opendesigner.dev/.well-known/agent-skills/opendesigner-extract.zip). The [install guide](https://opendesigner.dev/docs/install/) lists the other seven.
  64. To build the zips yourself, clone the repo and run `python3 tools/build_dist.py`. They land in `dist/`.
  65. </details>
  66. <details>
  67. <summary><b>Codex, Cursor, VS Code with Copilot, Gemini CLI and other agents</b></summary>
  68. These tools read skills from `.agents/skills/`. Run this inside your project. It copies in the ten skill folders and leaves nothing else behind.
  69. ```bash
  70. git clone --depth 1 https://github.com/ckryptickunal/OpenDesigner .opendesigner-tmp
  71. mkdir -p .agents/skills
  72. cp -R .opendesigner-tmp/.agents/skills/opendesigner* .agents/skills/
  73. rm -rf .opendesigner-tmp
  74. ```
  75. Tools that support Agent Plugins can also read the root `plugin.json`.
  76. </details>
  77. <details>
  78. <summary><b>ChatGPT</b> (a Project, nothing to install)</summary>
  79. 1. Download [opendesigner-chatgpt.zip](https://opendesigner.dev/downloads/opendesigner-chatgpt.zip) and unzip it.
  80. 2. Create a Project and paste `instructions.txt` into the Project instructions.
  81. 3. Upload the five files in the `knowledge` folder.
  82. </details>
  83. <details>
  84. <summary><b>No AI at all</b> (the engine on its own)</summary>
  85. The engine is one Python file (Python 3.10 or newer, nothing to install). It writes `DESIGN.md`, `PRODUCT.md` and an `opendesigner/` folder with tokens, exports and an overview page.
  86. ```bash
  87. python3 path/to/OpenDesigner/skills/opendesigner/scripts/engine.py sketch --name "Acme" --feel friendly,minimal
  88. ```
  89. </details>
  90. You need your own AI tool and Python 3.10 or newer. The engine makes no network calls ([privacy](docs/PRIVACY.md)). Help for each tool: [install guide](https://opendesigner.dev/docs/install/).
  91. Tested so far: the Claude Code install (2026-10-21) and the engine on Python 3.10.11. Not yet recorded: a run in the Claude app, Codex, Cursor, other agents or ChatGPT. Tried one? Say what you saw in [issue #19](https://github.com/ckryptickunal/OpenDesigner/issues/19) or in [Discussions](https://github.com/ckryptickunal/OpenDesigner/discussions).
  92. New to the repo? You only need `skills/` or a zip from above. Everything else here (research, benchmarks, the website, the brand kit) is how OpenDesigner is made.
  93. ## Component library
  94. <picture>
  95. <source media="(max-width: 600px)" srcset="https://raw.githubusercontent.com/ckryptickunal/OpenDesigner/main/brand/kit/readme/library-narrow.png">
  96. <img src="brand/kit/readme/library.png" width="1012" alt="Six ready-made parts: an approval panel, a monthly spend chart, a command menu, an AI answer with citations, an order summary and settings switches.">
  97. </picture>
  98. 129 ready-made parts built only on your tokens, each with its words and numbers marked so an app or assistant can fill it. Optional. [Browse them](https://opendesigner.dev/library/).
  99. ## Status
  100. - Version 0.3.1, 11 November 2026. The first tagged release was 0.2.0, on 5 November. One maintainer.
  101. - Engine tests pass locally. No CI runs, and no watched user trials yet.
  102. - Next: choices you can click inside your AI tool ([#20](https://github.com/ckryptickunal/OpenDesigner/issues/20)).
  103. [Changelog](CHANGELOG.md) · [How it works](docs/HOW-IT-WORKS.md) · [Research behind the defaults](docs/RESEARCH.md) · [Showcase](https://opendesigner.dev/showcase/)
  104. ## Help it get better
  105. Tell your AI what went wrong. It saves the note and gives you a ready-to-file GitHub link; nothing is posted until you send it. Or [open an issue](https://github.com/ckryptickunal/OpenDesigner/issues/new/choose). Contributions: [CONTRIBUTING.md](CONTRIBUTING.md). Sponsorship: [docs/SPONSORSHIP.md](docs/SPONSORSHIP.md#for-sponsors).
  106. <!-- Partners: large logos. Companies: small logos. Backers: names. Supported by: in-kind credit programs (never leave the wall empty). -->
  107. <!-- When GitHub Sponsors is approved, point the link above at https://github.com/sponsors/ckryptickunal (see docs/SPONSORSHIP.md). -->
  108. ## Star history
  109. <a href="https://github.com/ckryptickunal/OpenDesigner/stargazers">
  110. <picture>
  111. <source media="(prefers-color-scheme: dark)" srcset="brand/kit/readme/stars-dark.svg">
  112. <img src="brand/kit/readme/stars-light.svg" width="600" alt="OpenDesigner's GitHub stars over time, redrawn from GitHub every 3 hours">
  113. </picture>
  114. </a>
  115. ## License
  116. Code, skills, templates and data files are under the [MIT license](LICENSE). Written research and documentation are under [CC BY 4.0](LICENSE-CONTENT), so you can reuse them with credit. That covers `research/`, `benchmarks/`, `sources/`, `traces/`, `synthesis/` Markdown and `docs/`. Product and design-system names in the research belong to their owners. The tool marks in the "works in" row belong to their owners and only show where OpenDesigner runs (from [Simple Icons](https://simpleicons.org), CC0). Photos in the README images are from Unsplash: [Philipp Hubert](https://unsplash.com/photos/dVVjhUcdb30) (banner), [Annie Spratt](https://unsplash.com/photos/5yKrcO8FKwM) (before and after), and [Adam Rasheed](https://unsplash.com/photos/BGEqCc-bQHg) and [Brina Blum](https://unsplash.com/photos/mNXTZu7AeGA) (component library).
  117. To cite OpenDesigner or its research, use [CITATION.cff](CITATION.cff) (GitHub's "Cite this repository" button).
.agents/skills/opendesigner-extract/scripts/test_extract.py · Bundled script · 724 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """Tests for css_scan.py and read_page.js (reference measurement). Standard library only, no network.
  3. The read_page.js tests need Node and are skipped without it. Fixtures are small pages written here.
  4. python3 skills/opendesigner-extract/scripts/test_extract.py
  5. """
  6. import contextlib, importlib.util, io, json, shutil, subprocess, sys, tempfile, unittest
  7. from pathlib import Path
  8. HERE = Path(__file__).resolve().parent
  9. sys.path.insert(0, str(HERE))
  10. import css_scan # noqa: E402
  11. NODE = shutil.which("node")
  12. ENGINE = next((p for p in (HERE / "engine.py", HERE.parent.parent / "opendesigner" / "scripts" / "engine.py") if p.exists()), None)
  13. # A docs-like page: many short nav and caption rules, headings, one body size, slate text colors,
  14. # a decorative chromatic blob, 1 px radius on inline links, pills as badges, a white fade "shadow".
  15. SITE_CSS = """
  16. :root { --brand: #5469d4; --radius-control: 6px; --shadow-card: 0 2px 5px rgba(60,66,87,.08), 0 1px 1px rgba(0,0,0,.12); }
  17. html { font-size: 16px; }
  18. body { font-size: 16px; color: #3c4257; font-family: "Sohne", -apple-system, sans-serif; }
  19. p { font-size: 1rem; color: #3c4257; }
  20. li { font-size: 16px; }
  21. h1 { font-size: 48px; text-shadow: 0 1px 2px #000; }
  22. h2 { font-size: 32px; } h3 { font-size: 24px; } h4 { font-size: 20px; }
  23. nav a { font-size: 14px; color: #414552; border-radius: 1px; }
  24. .nav-item { font-size: 14px; } .nav-link { font-size: 14px; } .menu-item { font-size: 14px; }
  25. .sidebar-link { font-size: 14px; } .breadcrumb { font-size: 14px; }
  26. .caption { font-size: 12px; } .legal { font-size: 12px; } small { font-size: 12px; } footer p { font-size: 12px; }
  27. a { color: var(--brand); border-radius: 1px; }
  28. a.inline { border-radius: 1px; } .prose a { border-radius: 1px; }
  29. .btn { border-radius: var(--radius-control); background: var(--brand); color: #fff;
  30. transition: opacity .2s cubic-bezier(0.25, 0.1, 0.25, 1), transform 300ms linear(0, 0.5 50%, 1); }
  31. .btn-secondary { border-radius: 6px; background: #fff; color: #3c4257; border: 1px solid #d4dee9; }
  32. input, select { border-radius: 6px; border: 1px solid #d4dee9; }
  33. :focus-visible { outline: 2px solid #5469d4; }
  34. [aria-selected="true"] { background: #5469d4; color: #fff; }
  35. .badge { border-radius: 9999px; background: #e5edf5; } .pill { border-radius: 9999px; } .tag { border-radius: 9999px; }
  36. .avatar { border-radius: 50%; }
  37. .card { border-radius: 12px; box-shadow: var(--shadow-card); background: #fff; }
  38. .modal { border-radius: 12px; box-shadow: 0 15px 35px rgba(50,50,93,.1), 0 5px 15px rgba(0,0,0,.07); }
  39. .fade-edge { box-shadow: 0 0 64px 64px rgba(255,255,255,.75); }
  40. .hidden-ring { box-shadow: 0 0 0 0 rgba(0,0,0,0); }
  41. .hero-blob { background: #ff5996; } .hero-blob-2 { background: #ffc043; }
  42. .heading-slate { color: #0a2540; }
  43. """
  44. SYSTEM_ONLY_CSS = "body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; }"
  45. def scan(css, name="site.css"):
  46. d = Path(tempfile.mkdtemp())
  47. (d / name).write_text(css, encoding="utf-8")
  48. try:
  49. return css_scan.analyse(css_scan.scan_files([str(d)]))
  50. finally:
  51. shutil.rmtree(d)
  52. class Helpers(unittest.TestCase):
  53. def test_split_top_keeps_function_commas(self):
  54. v = "opacity .2s cubic-bezier(0.25, 0.1, 0.25, 1), transform 300ms linear(0, 0.5 50%, 1), color 1s ease"
  55. self.assertEqual(len(css_scan.split_top(v)), 3)
  56. self.assertIn("cubic-bezier(0.25, 0.1, 0.25, 1)", css_scan.split_top(v)[0])
  57. def test_parse_color_forms(self):
  58. self.assertEqual(css_scan.parse_color("#abc"), ("#aabbcc", 1.0))
  59. self.assertEqual(css_scan.parse_color("rgba(84, 105, 212, 0.5)"), ("#5469d4", 0.5))
  60. self.assertEqual(css_scan.parse_color("rgb(84 105 212 / 50%)"), ("#5469d4", 0.5))
  61. self.assertEqual(css_scan.parse_color("hsl(0, 100%, 50%)")[0], "#ff0000")
  62. L, C, H = css_scan.oklch("#5469d4")
  63. back = css_scan.parse_color(f"oklch({L} {C} {H})")[0] # oklch() rounds to 3 decimals
  64. self.assertTrue(all(abs(int(back[i:i + 2], 16) - int("5469d4"[i - 1:i + 1], 16)) <= 2 for i in (1, 3, 5)), back)
  65. self.assertEqual(css_scan.parse_color("transparent")[1], 0.0)
  66. def test_shadow_classification(self):
  67. cls = lambda s: css_scan.classify_layer(css_scan.parse_shadow_layer(s))
  68. self.assertEqual(cls("0 0 64px 64px rgba(255,255,255,.75)"), "fade")
  69. self.assertEqual(cls("rgba(0, 0, 0, 0) 0px 0px 0px 1px"), "transparent")
  70. self.assertEqual(cls("rgb(84, 105, 212) 0px 0px 0px 1px"), "ring")
  71. self.assertEqual(cls("inset 0 1px 0 rgba(0,0,0,.1)"), "inset")
  72. self.assertEqual(cls("0 1px 1px rgba(0,0,0,.12)"), "low")
  73. self.assertEqual(cls("rgba(50, 50, 93, 0.12) 0px 16px 32px 0px"), "high")
  74. self.assertEqual(cls("0 30px 60px -12px rgba(50,50,93,.25)"), "overlay")
  75. class DeclaredScan(unittest.TestCase):
  76. @classmethod
  77. def setUpClass(cls):
  78. cls.a = scan(SITE_CSS)
  79. def test_body_size_is_running_text_not_nav_or_captions(self):
  80. t = self.a["type"]
  81. self.assertEqual(t["body"]["px"], 16)
  82. self.assertEqual(self.a["bodySize"], 16)
  83. self.assertEqual(t["scale"]["base"], 16)
  84. self.assertEqual(t["largestHeading"]["px"], 48)
  85. self.assertEqual(t["headingRatio"]["value"], 3.0)
  86. def test_accent_from_interactive_skips_neutrals(self):
  87. c = self.a["color"]
  88. self.assertEqual(c["accents"][0]["hex"], "#5469d4")
  89. hexes = [x["hex"] for x in c["accents"]]
  90. for gray in ("#3c4257", "#414552", "#ffffff", "#000000", "#d4dee9"):
  91. self.assertNotIn(gray, hexes)
  92. self.assertNotIn("#ff5996", hexes) # decorative, not interactive
  93. self.assertIn(c["confidence"], ("high", "medium"))
  94. self.assertTrue({"button", "focus", "selected", "link"} <= set(c["accents"][0]["sources"]))
  95. def test_radius_control_and_container_apart(self):
  96. r = self.a["radius"]
  97. self.assertEqual(r["control"]["px"], 6)
  98. self.assertEqual(r["container"]["px"], 12)
  99. self.assertEqual(r["mostCommon"], 6)
  100. self.assertGreaterEqual(r["ignored"].get("link", 0), 3)
  101. self.assertGreaterEqual(r["ignored"].get("decor", 0), 3)
  102. def test_shadows_ignore_fades_and_text_shadows(self):
  103. d = self.a["depth"]
  104. self.assertEqual(d["hint"], "shadow-ladder")
  105. joined = " ".join(d["shadows"])
  106. self.assertNotIn("255, 255, 255", joined)
  107. self.assertNotIn("64px", joined)
  108. self.assertIn("fade", d["ignored"])
  109. self.assertEqual({l["level"] for l in d["levels"]}, {"low", "medium", "overlay"}) # 35 px modal blur = overlay
  110. self.assertEqual(d["count"], 3) # .card (via var), --shadow-card token, .modal
  111. def test_motion_keeps_easing_commas(self):
  112. m = self.a["motion"]
  113. self.assertIn("cubic-bezier(0.25, 0.1, 0.25, 1)", m["easings"])
  114. self.assertIn("linear(0, 0.5 50%, 1)", m["easings"])
  115. self.assertEqual(sorted(m["durations"]), [200.0, 300.0])
  116. def test_identity_and_confidence(self):
  117. t = self.a["type"]
  118. self.assertEqual(t["families"], ["Sohne"])
  119. self.assertFalse(t["primaryIsSystem"])
  120. s = self.a["summary"]
  121. for k in ("bodySize", "headingRatio", "accent", "radiusControl", "radiusContainer", "depth", "motionMedianMs"):
  122. self.assertIn(k, s)
  123. self.assertIn(s[k]["confidence"], ("high", "medium", "low"))
  124. self.assertIsInstance(s[k]["count"], int)
  125. self.assertNotIn("#5469d4", json.dumps(s)) # the summary never offers the hue as a value
  126. self.assertEqual(self.a["identity"]["accentHue"], "#5469d4")
  127. self.assertIn("never values to adopt", self.a["identity"]["rule"])
  128. def test_system_faces_are_not_identity(self):
  129. a = scan(SYSTEM_ONLY_CSS)
  130. self.assertEqual(a["type"]["families"], [])
  131. self.assertTrue(a["type"]["primaryIsSystem"])
  132. self.assertIn("-apple-system", a["type"]["systemFaces"])
  133. def test_html_inline_styles_and_style_blocks(self):
  134. html = """<html><head><style>.card{border-radius:10px} p{font-size:17px}</style></head>
  135. <body><button class="cta" style="border-radius: 4px; background: #1f6f5c">Go</button>
  136. <a href="#" style="border-radius:1px">link</a></body></html>"""
  137. a = scan(html, "index.html")
  138. self.assertEqual(a["radius"]["control"]["px"], 4)
  139. self.assertEqual(a["radius"]["container"]["px"], 10)
  140. self.assertEqual(a["bodySize"], 17)
  141. self.assertEqual(a["color"]["accents"][0]["hex"], "#1f6f5c")
  142. def test_resets_vars_and_unknown_class_names(self):
  143. css = """:root { --font-text: "Inter", sans-serif; }
  144. button, input, select { border-radius: 0; font-family: inherit; }
  145. body { font-family: var(--font-text); }
  146. .TransactionRow { border-radius: 10px; } .surface { border-radius: 10px; } .avatar { border-radius: 50%; }"""
  147. a = scan(css)
  148. self.assertEqual(a["type"]["families"], ["Inter"])
  149. self.assertEqual(a["radius"]["control"]["px"], 10)
  150. self.assertEqual(a["radius"]["control"]["confidence"], "low")
  151. def test_report_is_readable(self):
  152. text = css_scan.report(self.a)
  153. self.assertIn("Body size: 16 px", text)
  154. self.assertIn("Control radius: 6 px", text)
  155. self.assertIn("[", text)
  156. def capture(**values):
  157. base = {k: {} for k in ("colors", "fontFamilies", "fontSizes", "lineHeights", "fontWeights", "spacing",
  158. "radii", "shadows", "durations", "easings")}
  159. base.update(values)
  160. return {"source": "fixture", "method": "computed", "elements": 400, "values": base}
  161. class ComputedCapture(unittest.TestCase):
  162. def test_old_capture_without_roles_falls_back_with_low_confidence(self):
  163. # the shape the designer tester saved: counts only, header nav first in DOM order
  164. a = css_scan.analyse(capture(fontSizes={"16": 460, "12": 18, "20": 10, "11": 5, "34": 4, "14": 1},
  165. radii={"1": 31, "5": 10, "6": 8, "100": 3},
  166. colors={"#3c4257": 300, "#5469d4": 113, "#ffffff": 23},
  167. easings={"cubic-bezier(0.25": 150}))
  168. self.assertEqual(a["bodySize"], 16)
  169. self.assertEqual(a["type"]["body"]["confidence"], "low")
  170. self.assertEqual(a["radius"]["mostCommon"], 5) # 1 px corners dropped
  171. self.assertEqual(a["color"]["accents"][0]["hex"], "#5469d4")
  172. self.assertEqual(a["color"]["confidence"], "low")
  173. def test_ring_colors_count_toward_accent(self):
  174. a = css_scan.analyse(capture(shadows={"rgb(84, 105, 212) 0px 0px 0px 1px, rgba(0, 0, 0, 0.12) 0px 1px 1px 0px": 4}))
  175. self.assertEqual(a["depth"]["hint"], "ring+faint-shadow")
  176. self.assertEqual(a["color"]["accents"][0]["hex"], "#5469d4")
  177. self.assertNotIn("84, 105, 212", " ".join(a["depth"]["shadows"]))
  178. @unittest.skipUnless(NODE, "node not installed")
  179. class ReadPageJs(unittest.TestCase):
  180. """read_page.js core (collect) on synthetic element descriptions, then css_scan on its output."""
  181. def node(self, script):
  182. r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=30,
  183. env={"RP": str(HERE / "read_page.js"), "PATH": ""})
  184. self.assertEqual(r.returncode, 0, r.stderr)
  185. return json.loads(r.stdout)
  186. def collect(self, items):
  187. return self.node("const a=require(process.env.RP);const r=a.collect(" + json.dumps(items) + ",1280);"
  188. "console.log(JSON.stringify({source:'fixture',method:'computed',elements:" + str(len(items)) +
  189. ",values:r.values,targetsUnder24:r.targetsUnder24}))")
  190. def test_directory_page_reads_card_copy(self):
  191. # a docs hub: 16 px product names and link lists, 14 px one-line descriptions, no paragraphs
  192. base = {"w": 200, "h": 20, "ctx": None, "prose": False, "linkText": False, "fontFamily": "-apple-system",
  193. "fontWeight": "400", "lineHeight": "20px", "radius": "0px", "boxShadow": "none", "spacing": []}
  194. items = [{**base, "own": 30, "fontSize": 14} for _ in range(30)]
  195. items += [{**base, "own": 10, "fontSize": 16, "linkText": True} for _ in range(20)]
  196. items += [{**base, "own": 22, "fontSize": 16, "prose": True, "linkText": True} for _ in range(10)]
  197. items += [{**base, "own": 24, "fontSize": 32, "ctx": "heading"}]
  198. a = css_scan.analyse(self.collect(items))
  199. self.assertEqual(a["bodySize"], 14)
  200. self.assertEqual(a["type"]["body"]["confidence"], "medium")
  201. self.assertIn("mostly short text", a["type"]["body"]["basis"])
  202. self.assertEqual(a["type"]["families"], [])
  203. self.assertTrue(a["type"]["primaryIsSystem"])
  204. def test_split_and_durations(self):
  205. out = self.node("const a=require(process.env.RP);console.log(JSON.stringify(["
  206. "a.splitTop('cubic-bezier(0.25, 0.1, 0.25, 1), linear(0, 0.25 25%, 1), ease'),"
  207. "a.toMs('0.3s'), a.toMs('150ms'), a.radiusValue('50%', 40, 40), a.radiusValue('9999px', 80, 32),"
  208. "a.radiusValue('6px', 80, 32), a.parseRgb('rgba(84, 105, 212, 0.5)')]))")
  209. self.assertEqual(out[0], ["cubic-bezier(0.25, 0.1, 0.25, 1)", "linear(0, 0.25 25%, 1)", "ease"])
  210. self.assertEqual(out[1:6], [300, 150, "full", "full", 6])
  211. self.assertEqual(out[6], {"hex": "#5469d4", "a": 0.5})
  212. vis = self.node("const a=require(process.env.RP);console.log(JSON.stringify(["
  213. "a.shadowVisible('rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 1px'),"
  214. "a.shadowVisible('rgba(0, 0, 0, 0.12) 0px 1px 1px 0px'), a.shadowVisible('none'),"
  215. "a.shadowVisible('rgb(227, 232, 238) 0px -1px 0px 0px inset')]))")
  216. self.assertEqual(vis, [False, True, False, False])
  217. def test_collect_then_scan(self):
  218. items = []
  219. white, ink, accent, slate = ({"hex": h, "a": 1} for h in ("#ffffff", "#0a2540", "#533afd", "#50617a"))
  220. none = {"hex": "#000000", "a": 0}
  221. base = {"w": 100, "h": 20, "own": 0, "ctx": None, "prose": False, "buttonLike": False, "link": False,
  222. "formField": False, "selected": False, "media": False, "containerHint": False, "fontSize": 16,
  223. "fontFamily": "sohne-var", "fontWeight": "400", "lineHeight": "normal", "color": slate, "bg": none,
  224. "border": None, "accentColor": None, "radius": "0px", "boxShadow": "none", "spacing": [],
  225. "transition": ["all", "0s", "ease"], "animation": None}
  226. el = lambda **k: items.append({**base, **k})
  227. for _ in range(60): # header nav: many short 14 px labels
  228. el(own=8, ctx="nav", fontSize=14)
  229. for _ in range(12): # running text at 16 px (fewer elements, more characters)
  230. el(own=220, prose=True, fontSize=16)
  231. for _ in range(6): # short 16 px card labels
  232. el(own=12, fontSize=16)
  233. el(own=30, ctx="heading", fontSize=56, color=ink)
  234. el(own=20, ctx="heading", fontSize=32, color=ink)
  235. for _ in range(3): # small print
  236. el(own=90, ctx="caption", fontSize=12, prose=True)
  237. for _ in range(30): # inline links with a 1 px radius
  238. el(own=10, prose=True, link=True, radius="1px", color=accent)
  239. for _ in range(4): # pill buttons
  240. el(own=10, ctx="control", buttonLike=True, w=120, h=36, radius="9999px", bg=accent, color=white,
  241. transition=["opacity, transform", "0.3s, 150ms", "cubic-bezier(0.25, 0.1, 0.25, 1), linear(0, 0.5 50%, 1)"])
  242. for _ in range(3): # cards
  243. el(w=320, h=200, radius="8px", bg=white,
  244. boxShadow="rgba(50, 50, 93, 0.12) 0px 16px 32px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 0px")
  245. el(w=900, h=40, radius="0px", boxShadow="rgba(255, 255, 255, 0.75) 0px 0px 64px 64px") # fade glow
  246. el(w=40, h=20, radius="9999px", bg={"hex": "#e5edf5", "a": 1}) # badge
  247. for _ in range(10): # transparent accordion buttons (shadow reset to transparent): no visible corner
  248. el(own=30, ctx="control", buttonLike=True, w=450, h=60, radius="0px",
  249. boxShadow="rgba(0, 0, 0, 0) 0px 0px 0px 0px, rgba(0, 0, 0, 0) 0px 0px 0px 1px")
  250. for _ in range(20): # a link list at 14 px inside li: labels, not running text
  251. el(own=25, prose=True, linkText=True, link=True, fontSize=14, color=accent)
  252. cap = self.collect(items)
  253. v = cap["values"]
  254. self.assertEqual(v["radiiByRole"]["control"], {"full": 4})
  255. self.assertEqual(v["textSizes"]["label"]["14"], 500)
  256. self.assertIn("cubic-bezier(0.25, 0.1, 0.25, 1)", v["easings"])
  257. self.assertIn("linear(0, 0.5 50%, 1)", v["easings"])
  258. a = css_scan.analyse(cap)
  259. self.assertEqual(a["bodySize"], 16)
  260. self.assertEqual(a["type"]["body"]["confidence"], "high")
  261. self.assertEqual(a["type"]["headingRatio"]["value"], 3.5)
  262. self.assertEqual(a["radius"]["control"]["px"], "full")
  263. self.assertEqual(a["radius"]["container"]["px"], 8)
  264. self.assertEqual(a["radius"]["ignored"]["link"], 30)
  265. self.assertEqual(a["color"]["accents"][0]["hex"], "#533afd")
  266. self.assertNotIn("#50617a", [x["hex"] for x in a["color"]["accents"]])
  267. self.assertEqual(a["depth"]["hint"], "shadow-ladder")
  268. self.assertEqual(a["depth"]["ignored"].get("fade"), 1)
  269. self.assertEqual(sorted(a["motion"]["durations"]), [150.0, 300.0])
  270. self.assertEqual(a["type"]["families"], ["sohne-var"])
  271. cap["values"]["fontFamilies"] = {"-apple-system": 1966, "Menlo": 1003, "Source Code Pro": 20}
  272. t = css_scan.analyse(cap)["type"]
  273. self.assertEqual((t["families"], t["minorFaces"], t["primaryIsSystem"]), ([], ["Source Code Pro"], True))
  274. class SixMeasurementFixes(unittest.TestCase):
  275. """The six bugs found on 2026-10-23 by reading typesafe.ai and davecto.com against davecto's Taste Index reel."""
  276. def test_1_hard_shadows_frames_and_windows(self):
  277. cls = lambda s: css_scan.classify_layer(css_scan.parse_shadow_layer(s))
  278. self.assertEqual(cls("4px 4px 0 #000"), "hard")
  279. self.assertEqual(cls("0 1px 0 rgba(31, 35, 40, 0.04)"), "line") # a hairline under a button, not a shadow style
  280. win = json.dumps({"bar": "#1e1e1e", "barHeight": 20, "body": "#c4c4c4", "border": "1px #1e1e1e", "radius": 0})
  281. a = css_scan.analyse(capture(shadows={"rgba(0, 0, 0, 0.25) 0px 4px 4px 0px": 1}, borders={"1px drawn": 60}) | {
  282. "patterns": {"windows": {win: 8}, "frames": {"3px #c4c4c4": 5}, "drawnOffsets": {}}})
  283. d = a["depth"]
  284. self.assertEqual(d["hint"], "borders") # one soft shadow among 60 drawn borders is minor
  285. self.assertEqual((d["windowCount"], d["windows"][0]["bar"], d["minorShadows"]), (8, "#1e1e1e", 1))
  286. self.assertEqual(d["frames"][0]["band"], "3px")
  287. h = css_scan.analyse(capture(shadows={"rgb(30, 30, 30) 3px 3px 0px 0px": 6}))["depth"]
  288. self.assertEqual(h["hint"], "hard-offset")
  289. o = css_scan.analyse(capture() | {"patterns": {"drawnOffsets": {"3px 3px 0px 0px #000000": 4}}})["depth"]
  290. self.assertEqual(o["hint"], "hard-offset")
  291. self.assertIn("(drawn with boxes)", o["hard"][0])
  292. def test_2_loops_apart_from_ui_motion(self):
  293. a = css_scan.analyse(capture(durations={"500": 7}, easings={"cubic-bezier(0.12, 0.23, 0.5, 1)": 7}, transitionKinds={"color": 7},
  294. loops={"count": 10, "durations": {"2000": 5, "18248": 5}, "easings": {"linear": 10}}))
  295. m = a["motion"]
  296. self.assertEqual(m["durations"], [500.0])
  297. self.assertTrue(m["fadesOnly"])
  298. self.assertEqual((m["loops"]["count"], m["loops"]["character"]), (10, "linear"))
  299. self.assertEqual([css_scan.ease_kind(e) for e in ("steps(4, end)", "linear", "cubic-bezier(0.3, 1.4, 0.6, 1)",
  300. "linear(0, 1.1 60%, 1)", "ease-out")],
  301. ["stepped", "linear", "springy", "springy", "eased"])
  302. declared = scan(".ticker { animation: spin 18s linear infinite; } .btn { transition: color 150ms ease; }")["motion"]
  303. self.assertEqual(declared["durations"], [150.0])
  304. self.assertEqual(declared["loops"]["count"], 1)
  305. def test_3_browser_link_blue_and_error_colours_never_win(self):
  306. a = css_scan.analyse(capture(accentSources={"link": {"#0000ee": 13}, "button": {"#f386a1": 1}}))
  307. self.assertEqual(a["color"]["accents"][0]["hex"], "#f386a1")
  308. b = scan(":root { --accent: #0f766e; --ring: #0f766e; --destructive: #8c3b2e; } .error:focus-visible { outline: 2px solid #8c3b2e; }")
  309. self.assertEqual(b["color"]["accents"][0]["hex"], "#0f766e")
  310. def test_4_and_5_and_6_space_colour_area_and_sections(self):
  311. surfaces = {"grid": 16, "pageBg": "#fefefe", "areas": {"#f386a1": 0.58, "#1e1e1e": 0.19, "#fefefe": 0.13, "#03aa5c": 0.08},
  312. "text": {"#1e1e1e": 0.9, "#fefefe": 0.1}, "textShare": 0.05, "whitespace": 0.83, "blankRows": 0.17, "air": 0.63,
  313. "sections": [{"hex": "#f386a1", "y": 2322, "h": 5946}, {"hex": "#03aa5c", "y": 8268, "h": 972},
  314. {"hex": "#1e1e1e", "y": 9240, "h": 2092}], "gradients": 0, "imagery": 0.4}
  315. a = css_scan.analyse(capture() | {"surfaces": surfaces, "layout": {"docHeight": 11362}})
  316. sf = a["surfaces"]
  317. self.assertEqual([w["hex"] for w in sf["worlds"]], ["#f386a1", "#1e1e1e", "#03aa5c"])
  318. self.assertTrue(sf["colourIsPlace"])
  319. self.assertAlmostEqual(sf["chromaticShare"], 0.66, places=2)
  320. self.assertEqual((a["air"], a["blankRows"]), (0.63, 0.17))
  321. quiet = css_scan.analyse(capture() | {"surfaces": {**surfaces, "areas": {"#f7f5f0": 1.0}, "sections": [],
  322. "text": {"#181614": 0.55, "#6b655c": 0.35, "#0f766e": 0.1}}})
  323. self.assertLess(quiet["surfaces"]["chromaticShare"], 0.01)
  324. self.assertFalse(quiet["surfaces"]["colourIsPlace"])
  325. def test_type_roles_and_names(self):
  326. self.assertEqual(css_scan.face_name("Die Grotesk C Medium"), "Die Grotesk C")
  327. self.assertEqual(css_scan.face_name("'LisaTerminal Paper 2X3Y Medium'"), "LisaTerminal Paper 2X3Y")
  328. self.assertEqual(css_scan.face_name("sohne-var"), "sohne-var")
  329. roles = {"heading": {"families": {"Die Grotesk C Medium": 259}, "weights": {"500": 259}, "sizes": {"150": 140}, "tracking": {"-0.02": 259},
  330. "transform": {"capitalize": 200}, "lineHeight": {}, "chars": 259},
  331. "body": {"families": {"Die Grotesk C Regular": 2126, "LisaTerminal Paper 2X3Y Medium": 543}, "weights": {"400": 2126},
  332. "sizes": {"22": 1150}, "tracking": {}, "transform": {}, "lineHeight": {"1.2": 2000}, "chars": 2669},
  333. "noise": {"families": {"JetBrains Mono": 828}, "weights": {}, "sizes": {"12": 828}, "tracking": {}, "transform": {}, "lineHeight": {}, "chars": 828}}
  334. t = css_scan.analyse(capture(typeRoles=roles))["type"]
  335. self.assertEqual(t["roles"]["heading"]["family"], "Die Grotesk C")
  336. self.assertEqual(t["roles"]["heading"]["case"], "capitalize")
  337. self.assertEqual([v["family"] for v in t["voices"]], ["Die Grotesk C", "JetBrains Mono", "LisaTerminal Paper 2X3Y"])
  338. def test_merge_two_pages(self):
  339. p1 = capture(durations={"150": 4}) | {"surfaces": {"areas": {"#ffffff": 1.0}, "whitespace": 0.9, "blankRows": 0.5, "air": 3.0,
  340. "sections": [], "text": {}}, "layout": {"docHeight": 1000}, "viewport": [1000, 800]}
  341. p2 = capture(durations={"150": 6}) | {"surfaces": {"areas": {"#0f766e": 1.0}, "whitespace": 0.5, "blankRows": 0.1, "air": 1.0,
  342. "sections": [{"hex": "#0f766e", "y": 0, "h": 900}], "text": {}},
  343. "layout": {"docHeight": 1000}, "viewport": [1000, 800]}
  344. m = css_scan.merge_captures([p1, p2])
  345. self.assertEqual(m["values"]["durations"]["150"], 10)
  346. self.assertEqual(m["surfaces"]["areas"], {"#ffffff": 0.5, "#0f766e": 0.5})
  347. self.assertEqual(m["surfaces"]["sections"][0]["y"], 1000)
  348. self.assertEqual(css_scan.analyse(m)["pages"], 2)
  349. retro = capture(shadows={"rgba(30, 30, 30, 0.55) 3px 3px 0px 0px": 40}) | {"surfaces": {**p2["surfaces"], "areas": {"#f386a1": 0.7, "#ffffff": 0.3}}}
  350. quiet = capture(borders={"1px": 30}) | {"surfaces": {**p1["surfaces"], "areas": {"#f7f5f0": 1.0}}}
  351. self.assertEqual(css_scan.look_differences([quiet, quiet]), [])
  352. self.assertIn("give a different look its own Taste Index", css_scan.look_differences([quiet, retro])[0])
  353. @unittest.skipUnless(NODE, "node not installed")
  354. class ReadPageCollect(unittest.TestCase):
  355. def test_loops_links_noise_and_emphasis(self):
  356. base = {"w": 100, "h": 20, "own": 0, "ctx": None, "prose": False, "fontSize": 16, "fontFamily": "Inter", "fontWeight": "400",
  357. "lineHeight": "24px", "radius": "0px", "boxShadow": "none", "spacing": [], "color": {"hex": "#181614", "a": 1}}
  358. items = [{**base, "animation": ["blink", "2s", "linear", "infinite"]},
  359. {**base, "transition": ["color", "0.5s", "ease-out"]},
  360. {**base, "link": True, "own": 0, "color": {"hex": "#0000ee", "a": 1}}, # a wrapper link: no text of its own
  361. {**base, "link": True, "own": 12, "color": {"hex": "#0000ee", "a": 1}}, # the browser's link blue
  362. {**base, "own": 900, "noise": True, "fontSize": 12}, # a base-64 string used as decoration
  363. {**base, "own": 30, "emphasis": True, "color": {"hex": "#0f766e", "a": 1}},
  364. {**base, "own": 300, "prose": True, "fontSize": 18, "border": {"hex": "#1e1e1e", "a": 1, "w": 1, "pseudo": True}}]
  365. r = subprocess.run([NODE, "-e", "const a=require(process.env.RP);console.log(JSON.stringify(a.collect(" + json.dumps(items) + ",1280)))"],
  366. capture_output=True, text=True, timeout=30, env={"RP": str(HERE / "read_page.js"), "PATH": ""})
  367. self.assertEqual(r.returncode, 0, r.stderr)
  368. v = json.loads(r.stdout)["values"]
  369. self.assertEqual(v["loops"]["count"], 1)
  370. self.assertEqual(v["durations"], {"500": 1})
  371. self.assertEqual(v["transitionKinds"], {"color": 1})
  372. self.assertNotIn("link", v["accentSources"])
  373. self.assertEqual(v["accentSources"]["emphasis"], {"#0f766e": 3})
  374. self.assertNotIn("12", v["textSizes"].get("body", {}))
  375. self.assertEqual(v["textSizes"]["noise"], {"12": 900})
  376. self.assertEqual(v["borders"], {"1px drawn": 1})
  377. @unittest.skipUnless(ENGINE, "engine.py not found")
  378. class EngineIntakeCompat(unittest.TestCase):
  379. """engine.py intake reads css_scan --json output unchanged (read-only use of the engine)."""
  380. def test_intake_reads_body_radius_accent(self):
  381. spec = importlib.util.spec_from_file_location("od_engine", ENGINE)
  382. eng = importlib.util.module_from_spec(spec)
  383. spec.loader.exec_module(eng)
  384. a = scan(SITE_CSS)
  385. a["tag"] = "inspiration"
  386. fit = eng.fit_reference(json.loads(json.dumps(a)))
  387. by = {p["path"]: p for p in fit["proposals"]}
  388. self.assertIn("dials.roundness", by)
  389. self.assertIn("6", by["dials.roundness"]["basis"])
  390. self.assertIn("dials.density", by)
  391. self.assertIn("16", by["dials.density"]["basis"])
  392. self.assertIn("dials.colorfulness", by)
  393. self.assertNotIn("raw.brandColor", by) # inspiration: the accent hue is never proposed
  394. def test_space_motion_and_colour_area_reach_the_dials(self):
  395. spec = importlib.util.spec_from_file_location("od_engine", ENGINE)
  396. eng = importlib.util.module_from_spec(spec)
  397. spec.loader.exec_module(eng)
  398. dial = lambda ref, k: {p["path"]: p["value"] for p in eng.fit_reference(ref)["proposals"]}.get("dials." + k)
  399. airy = {"bodySize": 14, "air": 2.86, "blankRows": 0.48, "method": "computed"}
  400. self.assertLess(dial(airy, "density"), 34) # small type in a lot of empty space is spacious, not compact
  401. self.assertGreater(dial({"bodySize": 13, "air": 0.7, "blankRows": 0.05, "method": "computed"}, "density"), 66)
  402. retro = {"method": "computed", "motion": {"durationMultiplier": 1.82, "median": 500, "fadesOnly": True, "fades": 7,
  403. "loops": {"count": 10, "character": "linear"}}}
  404. self.assertEqual(dial(retro, "energy"), 35) # was 100: slow colour fades plus linear loops are not energetic
  405. self.assertEqual(dial({"method": "computed", "depth": {"hint": "hard-offset"}}, "depth"), 5)
  406. col = lambda share: {"method": "computed", "color": {"accents": [{"hex": "#f386a1"}], "chromaticShare": share}}
  407. self.assertGreater(dial(col(0.66), "colorfulness"), 75)
  408. self.assertLess(dial({"method": "computed", "color": {"accents": [{"hex": "#0f766e"}], "chromaticShare": 0.004}}, "colorfulness"), 35)
  409. def png_bytes(rows):
  410. """A small 8-bit RGB PNG, each row with a different filter (0 to 4), so the reader's unfiltering is exercised."""
  411. import struct, zlib
  412. def paeth(a, b, c):
  413. p = a + b - c
  414. pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
  415. return a if pa <= pb and pa <= pc else b if pb <= pc else c
  416. raw, prev = b"", bytes(len(rows[0]) * 3)
  417. for y, row in enumerate(rows):
  418. line, f = bytes(v for px in row for v in px), y % 5
  419. out = bytearray()
  420. for i, v in enumerate(line):
  421. a, b, c = (line[i - 3] if i >= 3 else 0), prev[i], (prev[i - 3] if i >= 3 else 0)
  422. out.append((v - [0, a, b, (a + b) // 2, paeth(a, b, c)][f]) & 255)
  423. raw += bytes([f]) + bytes(out)
  424. prev = line
  425. chunk = lambda t, d: struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
  426. return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", len(rows[0]), len(rows), 8, 2, 0, 0, 0))
  427. + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
  428. import taste_index # noqa: E402
  429. class TasteIndexTool(unittest.TestCase):
  430. """taste_index.py: the reel's structure from measurements, under the owner decision of 2026-10-23."""
  431. @staticmethod
  432. def retro_scan():
  433. win = json.dumps({"bar": "#1e1e1e", "barHeight": 20, "body": "#c4c4c4", "border": "1px #1e1e1e", "radius": 0})
  434. roles = {"heading": {"families": {"Die Grotesk C Medium": 260}, "weights": {"500": 260}, "sizes": {"150": 140, "64": 120}, "tracking": {},
  435. "transform": {"capitalize": 260}, "lineHeight": {"0.8": 260}, "chars": 260,
  436. "faces": {"Die Grotesk C Medium": {"sizes": {"150": 140, "64": 120}, "weights": {"500": 260}}}},
  437. "body": {"families": {"Die Grotesk C Regular": 2100}, "weights": {"400": 2100}, "sizes": {"22": 2100}, "tracking": {},
  438. "transform": {}, "lineHeight": {"1.2": 2100}, "chars": 2100, "faces": {}},
  439. "noise": {"families": {"JetBrains Mono": 800}, "weights": {"300": 800}, "sizes": {"12": 800}, "tracking": {}, "transform": {},
  440. "lineHeight": {}, "chars": 800, "faces": {}}}
  441. cap = capture(radiiByRole={"control": {"0": 6}, "container": {"0": 4}}, borders={"1px drawn": 60}, borderColors={"#1e1e1e": 60},
  442. accentSources={"button": {"#f386a1": 2}}, typeRoles=roles, textSizes={"body": {"22": 2100}, "heading": {"150": 140}},
  443. durations={"500": 7}, easings={"cubic-bezier(0.12, 0.23, 0.5, 1)": 7}, transitionKinds={"color": 7},
  444. loops={"count": 10, "durations": {"2000": 10}, "easings": {"linear": 10}})
  445. cap |= {"patterns": {"windows": {win: 8}, "frames": {"3px #c4c4c4": 5}},
  446. "surfaces": {"pageBg": "#fefefe", "areas": {"#f386a1": 0.58, "#1e1e1e": 0.19, "#fefefe": 0.13, "#03aa5c": 0.08},
  447. "text": {"#1e1e1e": 0.7, "#3d3d3d": 0.3}, "textShare": 0.05, "whitespace": 0.8, "blankRows": 0.17, "air": 0.63,
  448. "sections": [{"hex": "#f386a1", "y": 2000, "h": 6000}, {"hex": "#03aa5c", "y": 8000, "h": 900},
  449. {"hex": "#1e1e1e", "y": 8900, "h": 2000}], "gradients": 0},
  450. "layout": {"docHeight": 11000, "maxTextWidth": 600},
  451. "components": {"button": {json.dumps({"bg": "#f386a1", "text": "#111111", "border": None, "radius": 0, "height": 36, "padX": 12,
  452. "family": "Die Grotesk C Medium", "size": 16, "weight": "500", "case": None, "tracking": 0}): 2}},
  453. "voice": {"heading": {"n": 11, "words": 4.4, "case": {"title": 8, "sentence": 3}, "period": 2, "exclaim": 0, "question": 0,
  454. "digits": 3, "emoji": 0},
  455. "button": {"n": 25, "words": 3.1, "case": {"title": 15}, "period": 0, "exclaim": 0, "question": 0, "digits": 0, "emoji": 0},
  456. "prose": {"paragraphs": 14, "wordsPerSentence": 12.6, "you": 3, "contractions": 3, "exclaim": 0, "emoji": 1}}}
  457. return css_scan.analyse(cap)
  458. def test_draft_has_the_reels_structure(self):
  459. ix = taste_index.draft(self.retro_scan(), "retro-os")
  460. names = [p["name"] for p in ix["principles"] if p["keep"]]
  461. self.assertEqual(names[:2], ["Everything is a window", "Colour is a place"])
  462. self.assertIn("Square corners", names)
  463. self.assertIn("Something small is always running", names)
  464. self.assertTrue(all(p["status"] == "measured" and p["whyStatus"] == "inferred" and p["why"] for p in ix["principles"]))
  465. jobs = {c["hex"]: c for c in ix["colors"]}
  466. self.assertEqual(jobs["#fefefe"]["var"], "--ti-color-ground")
  467. self.assertEqual(jobs["#1e1e1e"]["var"], "--ti-color-ink")
  468. self.assertTrue(jobs["#f386a1"]["jobs"][0].startswith("world"))
  469. self.assertAlmostEqual(jobs["#f386a1"]["area"], 0.58)
  470. display = next(t for t in ix["type"] if t["role"] == "display")
  471. self.assertEqual((display["family"], display["substitute"], display["licence"]), ("Die Grotesk C", "Inter Tight", "not known"))
  472. mono = next(t for t in ix["type"] if t["family"] == "JetBrains Mono")
  473. self.assertEqual((mono["substitute"], mono["licence"]), ("JetBrains Mono", "open"))
  474. nevers = [n["rule"] for n in ix["never"]]
  475. for rule in ("Rounded corners", "Gradients", "Bounce or overshoot", "Emoji in headlines, buttons or navigation"):
  476. self.assertIn(rule, nevers)
  477. self.assertTrue(any(c["name"] == "window" for c in ix["components"]))
  478. self.assertIn("loop", " ".join(r["rule"] for r in ix["motion"]["rules"]))
  479. self.assertEqual(ix["notice"], taste_index.NOTICE)
  480. v = ix["variables"]
  481. for k in ("--ti-color-ground", "--ti-font-display", "--ti-radius-control", "--ti-duration-loop", "--ti-ease-loop", "--ti-frame-band"):
  482. self.assertIn(k, v)
  483. self.assertIn('"Die Grotesk C", "Inter Tight"', v["--ti-font-display"])
  484. errs, warns = taste_index.check(ix)
  485. self.assertEqual(errs, [])
  486. self.assertTrue(any("picture" in w for w in warns))
  487. def test_render_files_and_no_copy(self):
  488. ix = taste_index.draft(self.retro_scan(), "retro-os", picture="A desktop computer pinned onto pink paper")
  489. md, css, page = taste_index.render_md(ix), taste_index.css_for(ix), taste_index.specimen(ix)
  490. for part in ("## Principles", "## Colour", "## Type", "## Components", "## Motion", "## Voice", "## Never", "## Variables",
  491. "*(measured)*", "*(inferred)*", taste_index.NOTICE):
  492. self.assertIn(part, md)
  493. self.assertIn(":root {", css)
  494. self.assertIn("prefers-reduced-motion", css)
  495. self.assertIn('href="taste.css"', page)
  496. self.assertNotIn("fonts.googleapis", page + css) # fonts are named, never fetched
  497. self.assertNotIn("@font-face", css)
  498. def test_check_catches_gaps(self):
  499. ix = taste_index.draft(self.retro_scan(), "retro-os")
  500. ix["notice"] = "edited"
  501. ix["never"] = []
  502. for p in ix["principles"]:
  503. p["keep"] = False
  504. errs, _ = taste_index.check(ix)
  505. self.assertTrue(any("notice" in e for e in errs))
  506. self.assertTrue(any("Never" in e for e in errs))
  507. self.assertTrue(any("principle" in e for e in errs))
  508. def test_free_substitutes(self):
  509. sub = taste_index.substitute
  510. self.assertEqual(sub("Die Grotesk C", "heading"), "Inter Tight")
  511. self.assertEqual(sub("Die Grotesk C", "body"), "Inter")
  512. self.assertEqual(sub("LisaTerminal Paper 2X3Y"), "VT323")
  513. self.assertEqual(sub("Tiempos Headline", "heading"), "Newsreader")
  514. self.assertEqual(sub("Fraunces"), "Fraunces")
  515. self.assertEqual(taste_index.licence("Fraunces"), "open")
  516. self.assertEqual(taste_index.licence("Söhne"), "not known")
  517. def test_screenshot_reference_for_intake(self):
  518. pink, paper = (243, 134, 161), (254, 254, 254)
  519. rows = [[pink] * 64 for _ in range(200)] + [[paper] * 64 for _ in range(240)]
  520. rows[220][10:20] = [(30, 30, 30)] * 10 # a line of "text" in the paper band
  521. d = Path(tempfile.mkdtemp())
  522. try:
  523. (d / "shot.png").write_bytes(png_bytes(rows))
  524. w, h, px = taste_index.read_png(d / "shot.png")
  525. self.assertEqual((w, h, px[0][0], px[439][63], px[220][15]), (64, 440, pink, paper, (30, 30, 30)))
  526. with contextlib.redirect_stdout(io.StringIO()):
  527. out = taste_index.cmd_screenshot(str(d / "shot.png"), "pink-paper", ["radius=0", "body=16"], str(d), "inspiration")
  528. ref = json.loads(out.read_text())
  529. self.assertEqual((ref["kind"], ref["method"], ref["estimated"]), ("screenshot", "estimated", {"radius": "0", "body": "16"}))
  530. self.assertEqual(ref["surfaces"]["pageBg"], "#fefefe")
  531. self.assertEqual(ref["surfaces"]["order"], ["#f386a1"])
  532. self.assertAlmostEqual(ref["surfaces"]["worlds"][0]["share"], 0.44, places=1)
  533. if ENGINE:
  534. spec = importlib.util.spec_from_file_location("od_engine", ENGINE)
  535. eng = importlib.util.module_from_spec(spec)
  536. spec.loader.exec_module(eng)
  537. fit = eng.fit_reference(ref)
  538. paths = {p["path"] for p in fit["proposals"]}
  539. self.assertEqual(fit["kind"], "screenshot")
  540. self.assertIn("dials.roundness", paths)
  541. self.assertNotIn("dials.energy", paths) # a still image has no motion
  542. finally:
  543. shutil.rmtree(d)
  544. @unittest.skipUnless(ENGINE, "engine.py not found")
  545. def test_use_needs_the_persons_font_choice_then_follows(self):
  546. d = Path(tempfile.mkdtemp())
  547. try:
  548. eng = taste_index.engine()
  549. with contextlib.redirect_stdout(io.StringIO()):
  550. eng.cmd_sketch(str(d / "opendesigner"), name="Trial", audience="regular", platforms="web", feel="friendly,minimal", quiet=True)
  551. scan = d / "scan.json"
  552. scan.write_text(json.dumps(self.retro_scan()))
  553. with contextlib.redirect_stdout(io.StringIO()):
  554. taste_index.cmd_draft(str(scan), "retro-os", "inspiration", None, str(d))
  555. state = json.loads((d / "opendesigner" / "state.json").read_text())
  556. self.assertTrue(state["references"]["retro-os"]["index"]) # taste.py reads its dials as inspiration evidence
  557. self.assertNotIn("tasteIndex", state) # drafting never decides which index the system follows
  558. with self.assertRaises(SystemExit), contextlib.redirect_stdout(io.StringIO()):
  559. taste_index.cmd_use("retro-os", None, str(d))
  560. with contextlib.redirect_stdout(io.StringIO()):
  561. taste_index.cmd_use("retro-os", "free", str(d))
  562. state = json.loads((d / "opendesigner" / "state.json").read_text())
  563. self.assertEqual(state["tasteIndex"]["follows"], "retro-os")
  564. self.assertEqual(state["raw"]["brandColor"], "#f386a1")
  565. self.assertEqual(state["raw"]["displayFace"], "Inter Tight") # free substitute, as chosen
  566. for f in ("index.json", "TASTE-INDEX.md", "taste.css", "specimen.html", "measured.json"):
  567. self.assertTrue((d / "opendesigner" / "taste-indexes" / "retro-os" / f).exists(), f)
  568. finally:
  569. shutil.rmtree(d)
  570. class ReviewFixes(unittest.TestCase):
  571. """Bugs a fresh-eyes review found on 2026-10-23, each reproduced before the fix."""
  572. @unittest.skipUnless(NODE, "node not installed")
  573. def test_noise_is_base64_not_cjk(self):
  574. r = subprocess.run([NODE, "-e", "const a=require(process.env.RP);console.log(JSON.stringify(["
  575. "a.noiseText('ZmxvYXRpbmcgcG9pbnQgbnVtYmVycyBhcmUgYXBwcm94aW1hdGlvbnM='),"
    • Dismissed after review: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 641 on GitHub
  576. "a.noiseText('\u8fd9\u662f\u4e00\u4e2a\u5f88\u957f\u7684\u4e2d\u6587\u6bb5\u843d\u6ca1\u6709\u7a7a\u683c\u4f46\u662f\u5b83\u662f\u6b63\u5e38\u7684\u6587\u5b57\u5185\u5bb9\u800c\u4e0d\u662f\u88c5\u9970'),"
  577. "a.noiseText('A short line of ordinary words.')]))"],
  578. capture_output=True, text=True, timeout=30, env={"RP": str(HERE / "read_page.js"), "PATH": ""})
  579. self.assertEqual(json.loads(r.stdout), [True, False, False])
  580. def test_merge_skips_missing_numbers_and_averages_sentences(self):
  581. a = capture() | {"voice": {"prose": {"paragraphs": 0, "wordsPerSentence": None}}}
  582. b = capture() | {"voice": {"prose": {"paragraphs": 4, "wordsPerSentence": 12.6}}}
  583. c = capture() | {"voice": {"prose": {"paragraphs": 4, "wordsPerSentence": 12.6}}}
  584. self.assertEqual(css_scan.merge_captures([a, b])["voice"]["prose"]["wordsPerSentence"], 12.6)
  585. self.assertEqual(css_scan.merge_captures([b, c])["voice"]["prose"]["wordsPerSentence"], 12.6)
  586. def test_page_colour_is_not_the_accent_without_a_coloured_control(self):
  587. cap = capture(accentSources={"button": {"#111111": 6}}) | {"surfaces": {"areas": {"#f386a1": 0.25, "#ffffff": 0.75}, "sections": [], "text": {}}}
  588. self.assertNotIn("area", json.dumps(css_scan.analyse(cap)["color"]["accents"])) # black buttons: no accent from the page's pink
  589. cap["values"]["accentSources"]["button"]["#f386a1"] = 1
  590. self.assertIn("area", css_scan.analyse(cap)["color"]["accents"][0]["sources"]) # a pink button: the pink area backs it
  591. def test_set_numbering_and_validation(self):
  592. d = Path(tempfile.mkdtemp())
  593. try:
  594. ix = taste_index.draft(TasteIndexTool.retro_scan(), "retro-os")
  595. taste_index.save_index(str(d), ix)
  596. quiet = contextlib.redirect_stdout(io.StringIO())
  597. with quiet:
  598. taste_index.cmd_set("retro-os", "principle", ["2"], str(d), drop=True)
  599. taste_index.cmd_set("retro-os", "why", ["2", "A new reason"], str(d))
  600. ps = taste_index.load_index(str(d), "retro-os")["principles"]
  601. self.assertFalse(ps[1]["keep"])
  602. self.assertEqual(ps[1]["why"], "A new reason") # the same principle 2, kept or not
  603. for args in (("why", ["99", "x"], None), ("never", [], None), ("picture", [], None), ("principle", ["0"], True)):
  604. with self.assertRaises(SystemExit), contextlib.redirect_stdout(io.StringIO()):
  605. taste_index.cmd_set("retro-os", args[0], args[1], str(d), drop=args[2])
  606. with contextlib.redirect_stdout(io.StringIO()):
  607. taste_index.cmd_set("retro-os", "never", ["Paragraphs in pixel type"], str(d))
  608. self.assertEqual(taste_index.load_index(str(d), "retro-os")["never"][-1]["status"], "inferred")
  609. finally:
  610. shutil.rmtree(d)
  611. def test_screenshot_index_marks_estimates(self):
  612. scan = css_scan.analyse({"method": "estimated", "values": {"colors": {"#f7f5f0": 900}},
  613. "surfaces": {"pageBg": "#f7f5f0", "areas": {"#f7f5f0": 1.0}, "sections": [], "text": {}, "gradients": 0,
  614. "whitespace": 0.9, "blankRows": 0.5}})
  615. scan["radius"] = {"mostCommon": 0, "control": {"px": 0, "confidence": "low"}}
  616. ix = taste_index.draft(scan, "shot")
  617. rules = {n["rule"]: n["status"] for n in ix["never"]}
  618. self.assertNotIn("Gradients", rules) # a screenshot cannot show there are none
  619. self.assertNotIn("Soft drop shadows", rules)
  620. self.assertEqual(rules.get("Rounded corners"), "estimated")
  621. def test_card_wears_what_the_depth_model_says(self):
  622. flat = taste_index.draft(TasteIndexTool.retro_scan(), "retro-os")
  623. self.assertEqual(flat["variables"]["--ti-shadow-card"], "none")
  624. self.assertIn("var(--ti-shadow-card, none)", taste_index.css_for(flat))
  625. hard = css_scan.analyse(capture(shadows={"rgb(30, 30, 30) 3px 3px 0px 0px": 6}))
  626. self.assertEqual(taste_index.draft(hard, "hard")["variables"]["--ti-shadow-card"], "var(--ti-shadow-hard)")
  627. def test_redraft_keeps_hand_written_parts(self):
  628. d = Path(tempfile.mkdtemp())
  629. try:
  630. scan = d / "scan.json"
  631. scan.write_text(json.dumps(TasteIndexTool.retro_scan()))
  632. with contextlib.redirect_stdout(io.StringIO()):
  633. taste_index.cmd_draft(str(scan), "retro-os", "inspiration", "A desktop on pink paper", str(d))
  634. taste_index.cmd_set("retro-os", "never", ["Paragraphs in pixel type"], str(d))
  635. taste_index.cmd_draft(str(scan), "retro-os", "inspiration", None, str(d))
  636. ix = taste_index.load_index(str(d), "retro-os")
  637. self.assertEqual(ix["picture"]["text"], "A desktop on pink paper")
  638. self.assertIn("Paragraphs in pixel type", [n["rule"] for n in ix["never"]])
  639. self.assertEqual(ix["source"], None if not ix["source"] else ix["source"].split("/")[0]) # host only, never a path
  640. finally:
  641. shutil.rmtree(d)
  642. @unittest.skipUnless(ENGINE, "engine.py not found")
  643. def test_exact_fonts_keep_their_free_substitute(self):
  644. eng = taste_index.engine()
  645. faces = eng.font_faces({"textFace": ["Die Grotesk C", "Inter"], "displayFace": ["Die Grotesk C", "Inter Tight"]})
  646. self.assertEqual(faces["text"]["stack"], ["Die Grotesk C", "Inter"])
  647. self.assertEqual(eng.font_faces({"textFace": "Inter"})["text"].get("stack"), None)
  648. if __name__ == "__main__":
  649. unittest.main(verbosity=1)
server/mcp/test_server.py · Bundled script · 234 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """Tests for the library MCP server, over real stdio: python3 server/mcp/test_server.py
  3. Starts server.py as a subprocess the way a host does, sends JSON-RPC lines and checks the answers. Standard library only.
  4. get_tokens_template runs the engine (a few seconds); everything else is instant.
  5. """
  6. import json
  7. import pathlib
  8. import re
  9. import subprocess
  10. import sys
  11. import unittest
  12. HERE = pathlib.Path(__file__).resolve().parent
  13. ROOT = HERE.parent.parent
  14. CATALOG = json.loads((ROOT / "skills/opendesigner/assets/library/library.json").read_text())
  15. MODERN = {"io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "1"},
  16. "io.modelcontextprotocol/clientCapabilities": {"extensions": {"io.modelcontextprotocol/ui": {"mimeTypes": ["text/html;profile=mcp-app"]}}}}
  17. class Session:
  18. def __init__(self):
  19. self.p = subprocess.Popen([sys.executable, str(HERE / "server.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  20. stderr=subprocess.PIPE, text=True)
  21. self.n = 0
  22. def send(self, method, params=None, notify=False):
  23. msg = {"jsonrpc": "2.0", "method": method, **({"params": params} if params is not None else {})}
  24. if not notify:
  25. self.n += 1
  26. msg["id"] = self.n
  27. self.p.stdin.write(json.dumps(msg) + "\n")
  28. self.p.stdin.flush()
  29. if notify:
  30. return None
  31. line = self.p.stdout.readline()
  32. out = json.loads(line)
  33. assert out["id"] == self.n, out
  34. return out
  35. def raw(self, text):
  36. self.p.stdin.write(text + "\n")
  37. self.p.stdin.flush()
  38. return json.loads(self.p.stdout.readline())
  39. def close(self):
  40. self.p.stdin.close()
  41. code = self.p.wait(timeout=10)
  42. err = self.p.stderr.read()
  43. self.p.stdout.close()
  44. self.p.stderr.close()
  45. return code, err
  46. class Legacy(unittest.TestCase):
  47. """The initialize handshake (what Claude Desktop and most hosts send today)."""
  48. @classmethod
  49. def setUpClass(cls):
  50. cls.s = Session()
  51. cls.init = cls.s.send("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}})
  52. cls.s.send("notifications/initialized", notify=True)
  53. @classmethod
  54. def tearDownClass(cls):
  55. code, err = cls.s.close()
  56. assert code == 0, err
  57. def test_initialize_echoes_version(self):
  58. r = self.init["result"]
  59. self.assertEqual(r["protocolVersion"], "2025-06-18")
  60. self.assertEqual(r["serverInfo"]["name"], "opendesigner-library")
  61. self.assertIn("tools", r["capabilities"])
  62. def test_unknown_version_gets_ours(self):
  63. s = Session()
  64. r = s.send("initialize", {"protocolVersion": "1999-01-01", "capabilities": {}, "clientInfo": {"name": "t"}})
  65. self.assertIn(r["result"]["protocolVersion"], ["2025-11-25", "2025-06-18", "2025-03-26"])
  66. s.close()
  67. def test_initialize_never_agrees_to_the_handshake_free_version(self):
  68. s = Session()
  69. r = s.send("initialize", {"protocolVersion": "2026-07-28", "capabilities": {}, "clientInfo": {"name": "t"}})
  70. self.assertEqual(r["result"]["protocolVersion"], "2025-11-25")
  71. s.close()
  72. def test_wrong_argument_types_are_tool_errors(self):
  73. for name, args in (("get_tokens_template", {"brand": 123}), ("suggest_components", {"screen": "a table", "limit": "abc"}),
  74. ("suggest_components", {"screen": 5}), ("suggest_components", {"screen": "x" * 501}),
  75. ("suggest_components", {"screen": "a table", "limit": 99}), ("get_component", {}),
  76. ("get_component", {"id": "Bad Id"})):
  77. r = self.s.send("tools/call", {"name": name, "arguments": args})
  78. self.assertTrue(r["result"]["isError"], (name, args, r))
  79. def test_tools_are_read_only_and_described(self):
  80. tools = self.s.send("tools/list")["result"]["tools"]
  81. self.assertEqual({t["name"] for t in tools}, {"list_components", "get_component", "get_tokens_template", "suggest_components", "show_ui"})
  82. for t in tools:
  83. a = t["annotations"]
  84. self.assertTrue(a["readOnlyHint"], t["name"])
  85. self.assertFalse(a["destructiveHint"], t["name"])
  86. self.assertEqual(t["inputSchema"]["type"], "object")
  87. self.assertTrue(t["description"])
  88. lc = next(t for t in tools if t["name"] == "list_components")
  89. self.assertEqual(lc["_meta"]["ui"]["resourceUri"], "ui://opendesigner/library-gallery")
  90. def test_list_all_and_filtered(self):
  91. r = self.s.send("tools/call", {"name": "list_components", "arguments": {}})["result"]
  92. self.assertEqual(r["structuredContent"]["count"], CATALOG["count"])
  93. self.assertTrue(all(c["use"] == "OD:add library." + c["id"] for c in r["structuredContent"]["components"]))
  94. r = self.s.send("tools/call", {"name": "list_components", "arguments": {"type": "chart"}})["result"]
  95. self.assertTrue(r["structuredContent"]["count"] > 0)
  96. self.assertTrue(all(c["type"] == "chart" for c in r["structuredContent"]["components"]))
  97. def test_bad_filter_is_a_tool_error(self):
  98. r = self.s.send("tools/call", {"name": "list_components", "arguments": {"type": "spaceship"}})["result"]
  99. self.assertTrue(r["isError"])
  100. r = self.s.send("tools/call", {"name": "list_components", "arguments": {"colour": "red"}})["result"]
  101. self.assertTrue(r["isError"])
  102. def test_get_component(self):
  103. r = self.s.send("tools/call", {"name": "get_component", "arguments": {"id": "approval-panel"}})["result"]
  104. sc = r["structuredContent"]
  105. self.assertEqual(sc["entry"]["id"], "approval-panel")
  106. self.assertIn('class="odl-approval-panel', sc["html"])
  107. self.assertIn(".odl-approval-panel", sc["css"])
  108. self.assertNotIn("<style>", sc["markup"])
  109. self.assertEqual(set(sc["entry"]["states"]["edge"]), {"empty", "loading", "error", "disabled", "overflow", "long_text", "missing_image"})
  110. def test_get_unknown_component(self):
  111. r = self.s.send("tools/call", {"name": "get_component", "arguments": {"id": "../../etc/passwd"}})["result"]
  112. self.assertTrue(r["isError"])
  113. r = self.s.send("tools/call", {"name": "get_component", "arguments": {"id": "no-such-part"}})["result"]
  114. self.assertTrue(r["isError"])
  115. self.assertIn("No component", r["content"][0]["text"])
  116. def test_suggest(self):
  117. r = self.s.send("tools/call", {"name": "suggest_components", "arguments": {"screen": "a finance tool where a manager approves invoices"}})["result"]
  118. ids = [p["id"] for p in r["structuredContent"]["suggestions"]]
  119. self.assertIn("approval-panel", ids[:3])
  120. r = self.s.send("tools/call", {"name": "suggest_components", "arguments": {"screen": "a music player with a track list", "audience": "consumer"}})["result"]
  121. ids = [p["id"] for p in r["structuredContent"]["suggestions"]]
  122. self.assertTrue({"music-player", "track-list"} & set(ids[:3]), ids)
  123. r = self.s.send("tools/call", {"name": "suggest_components", "arguments": {"screen": ""}})["result"]
  124. self.assertTrue(r["isError"])
  125. def test_tokens_template(self):
  126. r = self.s.send("tools/call", {"name": "get_tokens_template", "arguments": {"brand": "#167874"}})["result"]
  127. sc = r["structuredContent"]
  128. self.assertEqual(sc["missing"], [], "the template must define every variable the library reads")
  129. self.assertIn("--ds-color-border-focus", sc["css"])
  130. bad = self.s.send("tools/call", {"name": "get_tokens_template", "arguments": {"brand": "red; rm -rf /"}})["result"]
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 152 on GitHub
  131. self.assertTrue(bad["isError"])
  132. bad = self.s.send("tools/call", {"name": "get_tokens_template", "arguments": {"feel": "calm --dir /tmp"}})["result"]
  133. self.assertTrue(bad["isError"])
  134. def test_resources(self):
  135. res = self.s.send("resources/list")["result"]["resources"]
  136. view = next(r for r in res if r["uri"] == "ui://opendesigner/library-gallery")
  137. self.assertEqual(view["mimeType"], "text/html;profile=mcp-app")
  138. r = self.s.send("resources/read", {"uri": "ui://opendesigner/library-gallery"})["result"]["contents"][0]
  139. self.assertEqual(r["mimeType"], "text/html;profile=mcp-app")
  140. self.assertEqual(r["_meta"]["ui"]["csp"]["resourceDomains"], ["https://images.unsplash.com"])
  141. self.assertIn("ui/message", r["text"])
  142. self.assertIn("OD:add library.", r["text"])
  143. err = self.s.send("resources/read", {"uri": "file:///etc/passwd"})
  144. self.assertEqual(err["error"]["code"], -32002)
  145. def test_errors(self):
  146. self.assertEqual(self.s.send("no/such/method")["error"]["code"], -32601)
  147. self.assertEqual(self.s.send("tools/call", {"name": "write_files", "arguments": {}})["error"]["code"], -32602)
  148. self.assertEqual(self.s.raw("{not json")["error"]["code"], -32700)
  149. self.assertEqual(self.s.raw("[]")["error"]["code"], -32600)
  150. self.assertEqual(self.s.send("ping")["result"], {})
  151. class Modern(unittest.TestCase):
  152. """MCP 2026-07-28: no handshake, version and client info in every request's _meta."""
  153. def test_discover_and_call(self):
  154. s = Session()
  155. d = s.send("server/discover", {"_meta": MODERN})["result"]
  156. self.assertEqual(d["resultType"], "complete")
  157. self.assertIn("2026-07-28", d["supportedVersions"])
  158. self.assertIn("io.modelcontextprotocol/ui", d["capabilities"]["extensions"])
  159. t = s.send("tools/list", {"_meta": MODERN})["result"]
  160. self.assertIn("ttlMs", t)
  161. self.assertEqual(t["_meta"]["io.modelcontextprotocol/serverInfo"]["name"], "opendesigner-library")
  162. r = s.send("tools/call", {"name": "list_components", "arguments": {"width": "narrow"}, "_meta": MODERN})["result"]
  163. self.assertEqual(r["resultType"], "complete")
  164. bad = s.send("tools/list", {"_meta": {**MODERN, "io.modelcontextprotocol/protocolVersion": "2099-01-01"}})
  165. self.assertEqual(bad["error"]["code"], -32022)
  166. self.assertEqual(bad["error"]["data"]["supported"], ["2026-07-28"])
  167. self.assertEqual(s.send("resources/read", {"uri": "od://nothing", "_meta": MODERN})["error"]["code"], -32602)
  168. self.assertEqual(s.send("ping", {"_meta": MODERN})["error"]["code"], -32601)
  169. no_caps = {k: v for k, v in MODERN.items() if k != "io.modelcontextprotocol/clientCapabilities"}
  170. self.assertEqual(s.send("tools/list", {"_meta": no_caps})["error"]["code"], -32602)
  171. code, _ = s.close()
  172. self.assertEqual(code, 0)
  173. def test_no_view_for_a_host_without_apps(self):
  174. s = Session()
  175. meta = {**MODERN, "io.modelcontextprotocol/clientCapabilities": {"extensions": {}}}
  176. tools = s.send("tools/list", {"_meta": meta})["result"]["tools"]
  177. self.assertTrue(all("_meta" not in t for t in tools))
  178. s.close()
  179. class Static(unittest.TestCase):
  180. def test_stdout_is_only_json(self):
  181. """Nothing but MCP messages on stdout: the start-up line goes to stderr."""
  182. p = subprocess.run([sys.executable, str(HERE / "server.py")], input="", capture_output=True, text=True, timeout=30)
  183. self.assertEqual(p.stdout, "")
  184. self.assertIn("read-only", p.stderr)
  185. def test_server_writes_and_fetches_nothing(self):
  186. src = (HERE / "server.py").read_text()
  187. self.assertIsNone(re.search(r"^\s*(import|from)\s+(urllib|http|socket|requests|ssl|ftplib|smtplib)\b", src, re.M))
  188. for bad in ("open(", "write_text", "write_bytes", "unlink", "rmtree", "os.remove", "shell=True"):
  189. self.assertFalse(bad in src, bad)
  190. def test_view_floors(self):
  191. """The gallery keeps the MCP Apps floors: 44 px targets, visible focus, reduced motion, dark mode, no external loads."""
  192. v = (HERE / "views/gallery.html").read_text()
  193. self.assertIn("min-height: 44px", v)
  194. self.assertIn(":focus-visible", v)
  195. self.assertIn("prefers-reduced-motion", v)
  196. self.assertIn("prefers-color-scheme: dark", v)
  197. self.assertIsNone(re.search(r"<(script|link)[^>]+(src|href)=\"https?:", v))
  198. self.assertNotRegex(v, r"\bfetch\(|XMLHttpRequest|WebSocket|localStorage")
  199. if __name__ == "__main__":
  200. unittest.main(verbosity=1)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.