Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Design system: Numbers and rankings, Phone, UI checklist; block new hard-coded styles in Swarm code (#1925)

0xken158cc0c2fe4e9d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 33a91b152..bde056959 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -137,6 +137,13 @@ jobs:
GIT_CONFIG_KEY_0: maintenance.auto
GIT_CONFIG_VALUE_0: "false"
run: python3 -m unittest discover -s scripts/tests -p 'test_*.py' -v
+ - name: Style allowlists only shrink (desktop/design/desktop-design-system.md)
+ if: github.event_name == 'pull_request'
+ env:
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ run: |
+ git fetch --quiet --depth=1 --no-tags origin "$BASE_SHA"
+ python3 scripts/check-ui-style.py --against "$BASE_SHA"
- name: Record source inputs for CI evidence reuse
run: python3 scripts/ci-source-inputs.py process --record "$RUNNER_TEMP/ci-source-inputs.json"
- uses: actions/upload-artifact@v4
@@ -190,6 +197,9 @@ jobs:
sparse-checkout-cone-mode: false
- name: Verify declared source checkout
run: python3 scripts/ci-source-inputs.py desktop
+ - name: No new hard-coded styles in Swarm UI (desktop/design/desktop-design-system.md)
+ if: matrix.shard == 1
+ run: python3 scripts/check-ui-style.py --only desktop/lib/super_tabs
- id: toolchain
run: |
version="$(sed -n "s/^ FLUTTER_VERSION: '\([^']*\)'.*/\1/p" .github/workflows/release-desktop.yml)"
@@ -548,6 +558,8 @@ jobs:
- uses: actions/checkout@v7
with:
ref: ${{ env.CI_SOURCE_SHA }}
+ - name: No new hard-coded styles in Swarm UI (desktop/design/desktop-design-system.md)
+ run: python3 scripts/check-ui-style.py --only mobile/lib/swarm
- id: toolchain
run: |
version="$(sed -n "s/^ FLUTTER_VERSION: '\([^']*\)'.*/\1/p" .github/workflows/release-desktop.yml)"
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index 926253e0c..7549adf95 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -256,6 +256,82 @@ accessory columns align. Specialized harness names need no marketing second
line. Machine menus align to the project popover's top edge with an 8-point gap,
then flip or constrain when the window has insufficient room.
+## Numbers and rankings
+
+A ranking, a score or a count is read by comparing rows, so its figures line
+up and only one of them speaks. Leaderboards, team summaries, usage tables and
+any later list of people or numbers use this recipe and the existing roles;
+there is no number style, ranking palette or medal artwork of its own.
+
+| Part | Role | Rule |
+| --- | --- | --- |
+| Rank | `AppType.label`, `FontWeight.w700`, `AppPalette.textSecondary` | A bold numeral in a fixed leading column. First place differs from tenth only by its number. |
+| Emphasized number (points) | `AppType.label`, `FontWeight.w600`, `AppPalette.textPrimary` | One per row, at the trailing edge. Shown even when it is 0, so the column holds. |
+| Secondary metrics | `AppType.caption`, `AppPalette.textSecondary` | Plain words beneath the name, joined by a spaced middle dot: `3 shipped · 2 unblocked`. A metric at 0 is left out; a row with none has no second line. |
+| Trend | `AppIcons.arrowUp` / `AppIcons.arrowDown` at 14 points, with a caption-size number | Shape and color together: up in `AppPalette.online`, down in the theme's semantic error ink. No change shows nothing. |
+| Current person | `AppSurface.selectedFill` | The sidebar's selected-row fill, not the blue keyboard selection (`AppDesktop.selection`). Text stays in ordinary ink. |
+
+Every figure that sits in a column (rank, points, counts, percentages and
+trend values) passes `fontFeatures: [FontFeature.tabularFigures()]` to its
+existing `AppType` style, so digits keep one width and a column does not
+shimmer as values change. Numeric columns are right-aligned at a fixed width
+sized for the widest expected value; names take the remaining width and
+truncate first. Row anatomy is the list rule above: rank, identity, name with
+its metadata, then trend and the emphasized number at the right.
+
+Medals, cups, trophies, flames and emoji are not icons and not ranks. A place
+is its numeral. Color never carries a trend, a rank or a threshold on its own:
+the arrow's direction, the number and the accessible label ("up 3 from last
+week") say the same thing. Hover and keyboard focus keep their ordinary
+treatment over the current person's fill, so focus stays visible on that row.
+
+## Phone
+
+The phone app speaks the same language at a thumb's scale. It uses the same
+role names in `mobile/lib/shared/theme` (`AppType`, `AppPalette`, `AppSurface`,
+`AppControl`, `AppMenu`, `AppCard`) with the sizes below. A role keeps its
+meaning, color and weight on both; only the size changes, and only where this
+section says so. Every other rule in this document holds on the phone.
+
+| Role | Desktop | Phone |
+| --- | --- | --- |
+| Display (`AppType.display`) | 28, semibold | 34, semibold |
+| Page title (`AppType.title`) | 20, semibold | 22, semibold |
+| Heading (`AppType.heading`) | 17, semibold | 17, semibold |
+| Body and control (`AppType.body`, `AppType.label`) | 13 | 17 |
+| Metadata (`AppType.caption`) | 12 | 13 |
+| Code (`AppType.mono`, `monoLabel`, `monoMeta`) | 13 / 12 / 11 | 13 / 12 / 11 |
+| Touch target | 32 icon, 28 compact | 44 (`minTouchTarget`) |
+| Icon beside text / standalone | 16 / 20 | 20 / 24 |
+| Screen side inset | 24 (dialog content) | 16 |
+| Spacing scale | 4, 8, 12, 16, 24 | 4, 8, 12, 16, 24 |
+| Field / row / pane radius | 10 | 10 |
+| Card / inset tile radius | 12 / 8 | 12 / 8 |
+| Popover and menu radius | 16 | 16 |
+| Dialog radius | 20 | 20 |
+| Action buttons | capsule | capsule |
+
+Every independently tappable control reaches 44 points. A control drawn
+smaller, such as a 32-point icon button in a header, keeps its drawn size and
+extends its hit area with `TouchTarget` rather than growing the row around it.
+Themed buttons and icon buttons reach 44 on their own: they are drawn at their
+usual size, but their layout box is 44 tall, so a row holding one is at least 44.
+A screen's own primary action is drawn 44 points tall.
+
+Deliberate differences from Desktop, and only these:
+
+- Type, touch target, icon and side-inset sizes, as in the table.
+- No hover state and no hand cursor. Press feedback replaces hover; focus
+ outlines appear only with a hardware keyboard.
+- Swarm screens set their top-bar titles in the terminal face, as the approved
+ phone prototype does. Everything else on them uses the system face.
+- The terminal keeps its own font, size and palette, as on Desktop.
+- Bottom sheets, which Desktop does not have, round their top corners at the
+ card radius (12).
+
+The mobile style check (`scripts/check-ui-style.py`) covers `mobile/lib/swarm`
+with the same rules as Desktop's Swarm code and an allowlist of its own.
+
## Surface families
**Titlebar dropdowns** — the avatar's menu, the bell's inbox and the other
@@ -484,6 +560,35 @@ composition. Use synthetic review data, not real agent launches or permissions.
Inspect the rebuilt app; widget tests alone do not prove native VoiceOver or
physical IME behavior. Record evidence and limitations in the migration ledger.
+## UI checklist
+
+Every pull request that changes UI pastes this into its description and ticks
+what it checked, or says why an item does not apply:
+
+```text
+UI checklist (desktop/design/desktop-design-system.md)
+- [ ] ASCII mockup confirmed by the requester before visuals were built
+- [ ] Named roles only (AppType, AppPalette/AppSurface, AppDesktop/AppControl,
+ AppIcons); scripts/check-ui-style.py passes and its allowlist only shrank
+- [ ] Numbers follow Numbers and rankings: tabular, right-aligned, one
+ emphasized number, zeros hidden, no emoji or medals
+- [ ] Color is never the only signal; a trend or state also has a shape or words
+- [ ] Light and dark, 160–200% text, long and missing names, empty, loading and
+ error states, with screenshots
+- [ ] Phone: Phone table sizes, 44-point targets, differences from Desktop listed
+- [ ] Copy follows the Naming System
+- [ ] Keyboard, focus return and hand cursor (Desktop)
+```
+
+`scripts/check-ui-style.py` runs in CI for `desktop/lib/super_tabs` and
+`mobile/lib/swarm`. It fails on a new `Color(0x…)`, Material `Colors.*` other
+than transparent, numeric `fontSize`, `EdgeInsets` with a number, or numeric
+`BorderRadius.circular` outside theme folders. Fix the call site with a role;
+when a count falls, run `python3 scripts/check-ui-style.py --update` and commit
+the smaller allowlist. Each area keeps its list in
+`scripts/ui-style-allowlist/<area>.json`. The update never raises a count, and a
+pull request whose allowlist records more than its base branch fails.
+
## Standard of finish
This specification establishes a direction, not an award or a quality score.
diff --git a/desktop/design/icon-design-system.md b/desktop/design/icon-design-system.md
index 10e9b2b1f..433d51b67 100644
--- a/desktop/design/icon-design-system.md
+++ b/desktop/design/icon-design-system.md
@@ -56,6 +56,10 @@ and disablement. Platform text scaling may grow the containing control; terminal
font size never changes the surrounding app icons. Identity artwork and
illustrations have their own layout dimensions.
+On the phone, icons beside text draw at 20 points and standalone icons at 24,
+each with a 44-point touch target; see Phone in the
+[desktop design system](desktop-design-system.md#phone).
+
The pane close target has a 4-point trailing inset. Tabs retain their 8-point
inset. Glyphs stay centered inside the target; do not move the drawing itself
to compensate for excess container padding.
@@ -99,6 +103,9 @@ These are content or identities, not a second action-icon library:
same `activityColor`, including the monochrome preference. Do not substitute
SF Symbols or add status pills to a different Harness surface. A notification
mark describes its unread receipt; a tab/pane mark describes current activity.
+- Ranks are numerals, never medals, cups, trophies or emoji. A trend is
+ `AppIcons.arrowUp` or `arrowDown` with its number; see
+ [Numbers and rankings](desktop-design-system.md#numbers-and-rankings).
- QR codes, companion artwork, explanatory diagrams, wallpaper, terminal
output and user-selected status/Powerline artwork are content. Keep their
function and authorship; do not round QR modules or replace terminal glyphs.
diff --git a/docs/naming-system.md b/docs/naming-system.md
index 583f10f82..1e3fee242 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -61,6 +61,7 @@ and **Browser**. Technical documentation may still call the terminal interface a
| **Engineer** | An agent carrying out project work. Use **Dev** in a compact role badge. System name: builder. | Atlas is an engineer on Lamp OS. |
| **Reviewer** | An agent that reviews project work. Use **Rev** in a compact role badge. System name: reviewer. | Atlas is a reviewer on Lamp OS. |
| **Workgroup** | A numbered conversation for an independently assignable outcome within a project. | Follow #12 Offline editing. |
+| **Points** | A person's or agent's score in a Swarm's rankings. Other measures are lowercase words after their number, joined by a spaced middle dot; a measure at zero is left out. Presentation follows [Numbers and rankings](../desktop/design/desktop-design-system.md#numbers-and-rankings). | 42 points; 3 shipped · 2 unblocked. |
| **Pane** | A visible view of a harness, terminal, or viewer. | Split right; close pane. |
| **Terminal** | A shell for entering commands. | New terminal. |
| **Project** | The files and working context for the work, on a particular computer. | Choose the website project. |
diff --git a/scripts/check-ui-style.py b/scripts/check-ui-style.py
new file mode 100755
index 000000000..1b970eb89
--- /dev/null
+++ b/scripts/check-ui-style.py
@@ -0,0 +1,281 @@
+#!/usr/bin/env python3
+"""Block new hard-coded styles in Swarm UI code; the design system's roles own them.
+
+desktop/design/desktop-design-system.md names the roles (AppType, AppPalette,
+AppDesktop/AppControl, AppIcons). This counts what bypasses them in each file:
+a Color(0x…) literal, a Material Colors.<name> other than transparent, a
+numeric fontSize, an EdgeInsets with a number in it, and a numeric
+BorderRadius.circular. Theme folders own those numbers and are not scanned.
+
+scripts/ui-style-allowlist/<area>.json holds the offenders that existed when an
+area's check began, as counts per file and rule. A count above its allowance
+fails; one below it fails too, until --update writes the smaller list. --against
+fails when an allowlist records more than the same file on the base branch, so
+the lists only shrink.
+"""
+import argparse
+import json
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+# Each scanned folder and the allowlist file of its area.
+ROOTS = {"desktop/lib/super_tabs": "desktop", "mobile/lib/swarm": "mobile"}
+ALLOWLISTS = Path("scripts/ui-style-allowlist")
+RULES = ("hex-color", "material-color", "font-size", "edge-insets", "border-radius")
+
+NUMBER = r"\d+(?:\.\d+)?"
+HEX_COLOR = re.compile(r"\bColor\(\s*0[xX]")
+MATERIAL_COLOR = re.compile(r"\bColors\.(\w+)")
+FONT_SIZE = re.compile(rf"\bfontSize\s*:\s*{NUMBER}")
+EDGE_INSETS = re.compile(r"\bEdgeInsets(?:Directional)?\.\w+\(")
+BORDER_RADIUS = re.compile(rf"\bBorderRadius\.circular\(\s*({NUMBER})")
+ZERO = re.compile(r"0+(?:\.0+)?")
+
+
+def code_only(text):
+ """The source with comments and string contents blanked, newlines kept."""
+ out, i, n = [], 0, len(text)
+
+ def blank(chunk):
+ out.append(re.sub(r"[^\n]", " ", chunk))
+
+ while i < n:
+ if text.startswith("//", i):
+ end = text.find("\n", i)
+ end = n if end < 0 else end
+ blank(text[i:end])
+ i = end
+ elif text.startswith("/*", i):
+ depth, j = 1, i + 2
+ while j < n and depth:
+ if text.startswith("/*", j):
+ depth, j = depth + 1, j + 2
+ elif text.startswith("*/", j):
+ depth, j = depth - 1, j + 2
+ else:
+ j += 1
+ blank(text[i:j])
+ i = j
+ elif text[i] in "'\"" or (text[i] == "r" and i + 1 < n and text[i + 1] in "'\""
+ and (i == 0 or not (text[i - 1].isalnum() or text[i - 1] == "_"))):
+ raw = text[i] == "r"
+ start = i + 1 if raw else i
+ quote = text[start:start + 3] if text[start:start + 3] in ("'''", '"""') else text[start]
+ j = start + len(quote)
+ while j < n and not text.startswith(quote, j):
+ if text[j] == "\\" and not raw:
+ j += 1
+ elif text[j] == "\n" and len(quote) == 1:
+ break
+ j += 1
+ j = min(n, j + len(quote))
+ out.append(text[i:start + len(quote)])
+ blank(text[start + len(quote):j - len(quote)])
+ out.append(text[j - len(quote):j])
+ i = j
+ else:
+ out.append(text[i])
+ i += 1
+ return "".join(out)
+
+
+def call_arguments(code, open_paren):
+ """The top-level argument values of the call whose '(' is at open_paren."""
+ depth, start, args = 0, open_paren + 1, []
+ for j in range(open_paren, len(code)):
+ char = code[j]
+ if char in "([{":
+ depth += 1
+ elif char in ")]}":
+ depth -= 1
+ if depth == 0:
+ args.append(code[start:j])
+ break
+ elif char == "," and depth == 1:
+ args.append(code[start:j])
+ start = j + 1
+ values = []
+ for arg in args:
+ arg = arg.strip()
+ if arg:
+ name = re.match(r"\w+\s*:(?!:)", arg)
+ values.append(arg[name.end():].strip() if name else arg)
+ return values
+
+
+def findings(text):
+ """(line, rule) for each hard-coded style in a Dart source."""
+ code = code_only(text)
+ found = []
+
+ def line(offset):
+ return code.count("\n", 0, offset) + 1
+
+ for match in HEX_COLOR.finditer(code):
+ found.append((line(match.start()), "hex-color"))
+ for match in MATERIAL_COLOR.finditer(code):
+ if match.group(1) != "transparent":
+ found.append((line(match.start()), "material-color"))
+ for match in FONT_SIZE.finditer(code):
+ found.append((line(match.start()), "font-size"))
+ for match in EDGE_INSETS.finditer(code):
+ values = call_arguments(code, match.end() - 1)
+ if any(re.match(NUMBER, value) and not ZERO.fullmatch(value) for value in values):
+ found.append((line(match.start()), "edge-insets"))
+ for match in BORDER_RADIUS.finditer(code):
+ rest = code[match.end():].lstrip()
+ if rest.startswith((")", ",")) and ZERO.fullmatch(match.group(1)):
+ continue
+ found.append((line(match.start()), "border-radius"))
+ return sorted(found)
+
+
+def dart_files(root, roots):
+ for name in roots:
+ folder = root / name
+ if folder.is_dir():
+ for path in sorted(folder.rglob("*.dart")):
+ relative = path.relative_to(root)
+ if "theme" not in relative.relative_to(name).parts[:-1]:
+ yield relative.as_posix(), path
+
+
+def scan(root, roots, lines=None):
+ """{file: {rule: count}} for the Dart files under roots; files with none are omitted."""
+ counts = {}
+ for name, path in dart_files(Path(root), roots):
+ found = findings(path.read_text(encoding="utf-8"))
+ if lines is not None:
+ lines.extend((name, number, rule) for number, rule in found)
+ for _, rule in found:
+ counts.setdefault(name, {}).setdefault(rule, 0)
+ counts[name][rule] += 1
+ return counts
+
+
+def within(name, root):
+ return name.startswith(root.rstrip("/") + "/")
+
+
+def differences(counts, allowed):
+ """(file, rule, count, allowance) wherever the two disagree."""
+ out = []
+ for name in sorted(set(counts) | set(allowed)):
+ have, limit = counts.get(name, {}), allowed.get(name, {})
+ for rule in RULES:
+ if have.get(rule, 0) != limit.get(rule, 0):
+ out.append((name, rule, have.get(rule, 0), limit.get(rule, 0)))
+ return out
+
+
+def allowlist_file(name):
+ return ALLOWLISTS / f"{ROOTS[name]}.json"
+
+
+def write_allowlist(path, counts):
+ ordered = {name: {rule: counts[name][rule] for rule in RULES if counts[name].get(rule)}
+ for name in sorted(counts)}
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(ordered, indent=2) + "\n")
+
+
+def raised_since(root, ref):
+ """(allowlist, file, rule, count, base count) where an allowlist records more than at ref."""
+ raised = []
+ for name in ROOTS:
+ relative = allowlist_file(name)
+ path = root / relative
+ if not path.exists():
+ continue
+ shown = subprocess.run(["git", "show", f"{ref}:{relative.as_posix()}"], cwd=root,
+ capture_output=True, text=True)
+ if shown.returncode != 0:
+ # The area's first allowlist: today's offenders, recorded once.
+ continue
+ now, base = json.loads(path.read_text()), json.loads(shown.stdout)
+ for file in sorted(now):
+ for rule in RULES:
+ count, before = now[file].get(rule, 0), base.get(file, {}).get(rule, 0)
+ if count > before:
+ raised.append((relative.as_posix(), file, rule, count, before))
+ return raised
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1], help="repository root")
+ parser.add_argument("--only", action="append", choices=list(ROOTS), help="check only this folder (repeatable)")
+ parser.add_argument("--update", action="store_true", help="shrink the allowlists to today's counts; never raises one")
+ parser.add_argument("--init", action="store_true", help="write a folder's first allowlist from today's offenders")
+ parser.add_argument("--against", metavar="REF", help="fail if an allowlist records more than at this base revision")
+ args = parser.parse_args(argv)
+
+ if args.against:
+ raised = raised_since(args.root, args.against)
+ if raised:
+ print(f"An allowlist grew since {args.against}; fix the call sites instead:", file=sys.stderr)
+ for allowlist, file, rule, count, before in raised:
+ print(f" {allowlist}: {file}: {rule} {count}, base {before}", file=sys.stderr)
+ return 1
+ return 0
+
+ # A folder this branch does not have is not checked; its area's list waits for it.
+ roots = [name for name in args.only or ROOTS if (args.root / name).is_dir()]
+ lines = []
+ counts = scan(args.root, roots, lines)
+
+ if args.init:
+ for name in roots:
+ path = args.root / allowlist_file(name)
+ if path.exists():
+ print(f"{allowlist_file(name)} already exists; use --update to shrink it", file=sys.stderr)
+ return 1
+ mine = {file: rules for file, rules in counts.items() if within(file, name)}
+ write_allowlist(path, mine)
+ print(f"wrote {allowlist_file(name)}: {sum(sum(c.values()) for c in mine.values())} offenders "
+ f"in {len(mine)} files")
+ return 0
+
+ allowed = {}
+ for name in roots:
+ path = args.root / allowlist_file(name)
+ if not path.exists():
+ print(f"{allowlist_file(name)} is missing; create it once with "
+ f"scripts/check-ui-style.py --init --only {name}", file=sys.stderr)
+ return 1
+ allowed.update({file: rules for file, rules in json.loads(path.read_text()).items() if within(file, name)})
+
+ diffs = differences(counts, allowed)
+ grown = [diff for diff in diffs if diff[2] > diff[3]]
+ shrunk = [diff for diff in diffs if diff[2] < diff[3]]
+ if grown:
+ over = {(name, rule) for name, rule, _, _ in grown}
+ print("Hard-coded styles in Swarm UI code. Use the design system's roles "
+ "(desktop/design/desktop-design-system.md) instead:", file=sys.stderr)
+ for name, number, rule in lines:
+ if (name, rule) in over:
+ print(f" {name}:{number}: {rule}", file=sys.stderr)
+ for name, rule, have, limit in grown:
+ print(f" {name}: {rule} {have}, allowed {limit}", file=sys.stderr)
+ if args.update:
+ print("--update never raises an allowance; nothing was written.", file=sys.stderr)
+ return 1
+ if shrunk and args.update:
+ for name in roots:
+ write_allowlist(args.root / allowlist_file(name),
+ {file: rules for file, rules in counts.items() if within(file, name)})
+ print("shrank: " + ", ".join(f"{name} {rule} {limit}→{have}" for name, rule, have, limit in shrunk))
+ return 0
+ if shrunk:
+ print("Fewer hard-coded styles than the allowlist records. Shrink it with "
+ "python3 scripts/check-ui-style.py --update and commit the result:", file=sys.stderr)
+ for name, rule, have, limit in shrunk:
+ print(f" {name}: {rule} {have}, allowed {limit}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/tests/test_ui_style_check.py b/scripts/tests/test_ui_style_check.py
new file mode 100644
index 000000000..c6714afb7
--- /dev/null
+++ b/scripts/tests/test_ui_style_check.py
@@ -0,0 +1,267 @@
+import contextlib
+import importlib.util
+import io
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+
+spec = importlib.util.spec_from_file_location("check_ui_style", Path(__file__).resolve().parents[1] / "check-ui-style.py")
+style = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(style)
+
+DESKTOP = "desktop/lib/super_tabs"
+MOBILE = "mobile/lib/swarm"
+
+
+class Repo:
+ """A scratch checkout holding only the files a test writes."""
+
+ def __init__(self):
+ self._dir = tempfile.TemporaryDirectory()
+ self.root = Path(self._dir.name)
+ self.lists = self.root / "scripts" / "ui-style-allowlist"
+
+ def write(self, path, text):
+ target = self.root / path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(text)
+
+ def allow(self, entries, areas=("desktop", "mobile")):
+ """Writes each area's allowlist with the entries under its folder."""
+ self.lists.mkdir(parents=True, exist_ok=True)
+ for area, prefix in (("desktop", DESKTOP), ("mobile", MOBILE)):
+ if area in areas:
+ mine = {k: v for k, v in entries.items() if k.startswith(prefix + "/")}
+ (self.lists / f"{area}.json").write_text(json.dumps(mine))
+
+ def allowed(self):
+ """Every area's allowlist entries, merged."""
+ merged = {}
+ for path in sorted(self.lists.glob("*.json")):
+ merged.update(json.loads(path.read_text()))
+ return merged
+
+ def git(self, *args):
+ subprocess.run(["git", *args], cwd=self.root, check=True, capture_output=True)
+
+ def run(self, *args):
+ out, err = io.StringIO(), io.StringIO()
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
+ code = style.main(["--root", str(self.root), *args])
+ return code, out.getvalue() + err.getvalue()
+
+ def close(self):
+ self._dir.cleanup()
+
+
+class StyleCheckTest(unittest.TestCase):
+ def setUp(self):
+ self.repo = Repo()
+ self.addCleanup(self.repo.close)
+
+ def counts(self, text, path=f"{DESKTOP}/a.dart"):
+ self.repo.write(path, text)
+ return style.scan(self.repo.root, [DESKTOP, MOBILE])
+
+ def test_each_hard_coded_style_is_counted_under_its_rule(self):
+ counts = self.counts(
+ "final a = Color(0xFF112233);\n"
+ "final b = Colors.red;\n"
+ "final c = Colors.white70.withAlpha(3);\n"
+ "final d = TextStyle(fontSize: 13);\n"
+ "final e = TextStyle(fontSize: 12.5 * scale);\n"
+ "final f = EdgeInsets.all(8);\n"
+ "final g = EdgeInsetsDirectional.only(start: 4);\n"
+ "final h = BorderRadius.circular(10);\n"
+ )
+ self.assertEqual(counts, {f"{DESKTOP}/a.dart": {
+ "hex-color": 1, "material-color": 2, "font-size": 2, "edge-insets": 2, "border-radius": 1}})
+
+ def test_named_roles_transparent_and_zero_are_allowed(self):
+ counts = self.counts(
+ "final a = Colors.transparent;\n"
+ "final b = TextStyle(fontSize: AppType.bodySize);\n"
+ "final c = EdgeInsets.all(AppDesktop.groupGap * 2);\n"
+ "final d = EdgeInsets.only(top: 0, left: AppDesktop.controlGap);\n"
+ "final e = EdgeInsets.zero;\n"
+ "final f = BorderRadius.circular(AppDesktop.rowRadius);\n"
+ "final g = BorderRadius.circular(0);\n"
+ "final h = AppPalette.accent;\n"
+ )
+ self.assertEqual(counts, {})
+
+ def test_a_multi_line_edge_insets_with_one_number_counts_once(self):
+ counts = self.counts(
+ "const p = EdgeInsets.symmetric(\n"
+ " horizontal: AppDesktop.controlGap,\n"
+ " vertical: 6,\n"
+ ");\n"
+ "const q = EdgeInsets.fromLTRB(4, 2, 8, 2);\n"
+ )
+ self.assertEqual(counts, {f"{DESKTOP}/a.dart": {"edge-insets": 2}})
+
+ def test_comments_and_strings_are_not_code(self):
+ counts = self.counts(
+ "/// Was Color(0xFF000000) before the token.\n"
+ "// fontSize: 12\n"
+ "/* Colors.red,\n EdgeInsets.all(4) */\n"
+ "final a = 'BorderRadius.circular(8) http://x';\n"
+ "final b = \"Colors.blue ${'Colors.red'}\";\n"
+ "final c = r'''\nfontSize: 9\n''';\n"
+ "final d = AppPalette.accent; // Colors.green\n"
+ )
+ self.assertEqual(counts, {})
+
+ def test_theme_files_and_non_dart_files_are_not_scanned(self):
+ self.repo.write(f"{DESKTOP}/theme/tokens.dart", "final a = Color(0xFF000000);\n")
+ self.repo.write(f"{DESKTOP}/notes.txt", "final a = Color(0xFF000000);\n")
+ self.assertEqual(style.scan(self.repo.root, [DESKTOP, MOBILE]), {})
+
+ def test_a_missing_root_is_skipped(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.assertEqual(style.scan(self.repo.root, [DESKTOP, MOBILE]),
+ {f"{DESKTOP}/a.dart": {"material-color": 1}})
+
+ def test_a_new_offender_fails_with_its_file_line_and_rule(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = AppPalette.accent;\n\nfinal b = Color(0xFF112233);\n")
+ self.repo.allow({})
+ code, output = self.repo.run()
+ self.assertEqual(code, 1)
+ self.assertIn(f"{DESKTOP}/a.dart:3: hex-color", output)
+
+ def test_today_offenders_within_the_allowlist_pass(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\nfinal b = Colors.blue;\n")
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 2}})
+ self.assertEqual(self.repo.run(), (0, ""))
+
+ def test_one_more_than_allowed_fails(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\nfinal b = Colors.blue;\nfinal c = Colors.green;\n")
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 2}})
+ code, output = self.repo.run()
+ self.assertEqual(code, 1)
+ self.assertIn(f"{DESKTOP}/a.dart: material-color 3, allowed 2", output)
+
+ def test_fewer_than_allowed_asks_to_shrink_the_list(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 2, "font-size": 1},
+ f"{DESKTOP}/gone.dart": {"hex-color": 1}})
+ code, output = self.repo.run()
+ self.assertEqual(code, 1)
+ self.assertIn(f"{DESKTOP}/a.dart: material-color 1, allowed 2", output)
+ self.assertIn(f"{DESKTOP}/a.dart: font-size 0, allowed 1", output)
+ self.assertIn(f"{DESKTOP}/gone.dart: hex-color 0, allowed 1", output)
+ self.assertIn("--update", output)
+
+ def test_only_checks_the_named_root_and_ignores_the_other_roots_entries(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.repo.write(f"{MOBILE}/b.dart", "final b = AppPalette.accent;\n")
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 1}, f"{MOBILE}/b.dart": {"hex-color": 4}})
+ self.assertEqual(self.repo.run("--only", DESKTOP), (0, ""))
+ code, output = self.repo.run("--only", MOBILE)
+ self.assertEqual(code, 1)
+ self.assertIn(f"{MOBILE}/b.dart: hex-color 0, allowed 4", output)
+
+ def test_entries_for_a_folder_this_branch_lacks_wait_for_it(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ entries = {f"{DESKTOP}/a.dart": {"material-color": 1}, f"{MOBILE}/b.dart": {"hex-color": 4}}
+ self.repo.allow(entries)
+ self.assertEqual(self.repo.run(), (0, ""))
+ self.assertEqual(self.repo.run("--only", MOBILE), (0, ""))
+ self.assertEqual(self.repo.run("--update")[0], 0)
+ self.assertEqual(self.repo.allowed(), entries)
+
+ def test_update_lowers_counts_and_drops_clean_files(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 2, "font-size": 1},
+ f"{DESKTOP}/gone.dart": {"hex-color": 1}})
+ code, _ = self.repo.run("--update")
+ self.assertEqual(code, 0)
+ self.assertEqual(self.repo.allowed(),
+ {f"{DESKTOP}/a.dart": {"material-color": 1}})
+ self.assertEqual(self.repo.run(), (0, ""))
+
+ def test_update_never_raises_a_count_or_adds_a_file(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\nfinal b = Colors.blue;\n")
+ self.repo.write(f"{DESKTOP}/new.dart", "final a = Color(0xFF000000);\n")
+ before = {f"{DESKTOP}/a.dart": {"material-color": 1}}
+ self.repo.allow(before)
+ code, output = self.repo.run("--update")
+ self.assertEqual(code, 1)
+ self.assertIn(f"{DESKTOP}/a.dart: material-color 2, allowed 1", output)
+ self.assertIn(f"{DESKTOP}/new.dart: hex-color 1, allowed 0", output)
+ self.assertEqual(self.repo.allowed(), before)
+
+ def test_init_records_today_offenders_once_per_area(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.repo.write(f"{MOBILE}/b.dart", "final b = TextStyle(fontSize: 17);\n")
+ self.assertEqual(self.repo.run("--init")[0], 0)
+ self.assertEqual(json.loads((self.repo.lists / "desktop.json").read_text()),
+ {f"{DESKTOP}/a.dart": {"material-color": 1}})
+ self.assertEqual(json.loads((self.repo.lists / "mobile.json").read_text()),
+ {f"{MOBILE}/b.dart": {"font-size": 1}})
+ code, output = self.repo.run("--init")
+ self.assertEqual(code, 1)
+ self.assertIn("already exists", output)
+
+ def test_one_area_can_start_its_list_while_the_other_has_none(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = Colors.red;\n")
+ self.repo.write(f"{MOBILE}/b.dart", "final b = TextStyle(fontSize: 17);\n")
+ self.assertEqual(self.repo.run("--init", "--only", MOBILE)[0], 0)
+ self.assertFalse((self.repo.lists / "desktop.json").exists())
+ self.assertEqual(self.repo.run("--only", MOBILE), (0, ""))
+
+ def test_a_missing_allowlist_fails_instead_of_passing_everything(self):
+ self.repo.write(f"{DESKTOP}/a.dart", "final a = AppPalette.accent;\n")
+ code, output = self.repo.run()
+ self.assertEqual(code, 1)
+ self.assertIn("--init", output)
+
+
+class AgainstBaseTest(unittest.TestCase):
+ """--against: an allowlist may only record less than on the base branch."""
+
+ def setUp(self):
+ self.repo = Repo()
+ self.addCleanup(self.repo.close)
+ self.repo.git("init", "-q")
+ self.repo.git("config", "user.email", "[email protected]")
+ self.repo.git("config", "user.name", "t")
+ self.repo.git("config", "commit.gpgsign", "false")
+
+ def base(self, entries, areas=("desktop",)):
+ self.repo.allow(entries, areas)
+ self.repo.write("README", "base\n")
+ self.repo.git("add", "-A")
+ self.repo.git("commit", "-q", "-m", "base")
+
+ def test_a_raised_count_fails_naming_the_file_and_rule(self):
+ self.base({f"{DESKTOP}/a.dart": {"material-color": 2}})
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 3}}, ("desktop",))
+ code, output = self.repo.run("--against", "HEAD")
+ self.assertEqual(code, 1)
+ self.assertIn(f"scripts/ui-style-allowlist/desktop.json: {DESKTOP}/a.dart: material-color 3, base 2", output)
+
+ def test_a_file_or_rule_the_base_did_not_list_fails(self):
+ self.base({f"{DESKTOP}/a.dart": {"material-color": 2}})
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 2, "font-size": 1},
+ f"{DESKTOP}/new.dart": {"hex-color": 1}}, ("desktop",))
+ code, output = self.repo.run("--against", "HEAD")
+ self.assertEqual(code, 1)
+ self.assertIn(f"{DESKTOP}/a.dart: font-size 1, base 0", output)
+ self.assertIn(f"{DESKTOP}/new.dart: hex-color 1, base 0", output)
+
+ def test_equal_or_lower_counts_pass(self):
+ self.base({f"{DESKTOP}/a.dart": {"material-color": 2}, f"{DESKTOP}/b.dart": {"hex-color": 1}})
+ self.repo.allow({f"{DESKTOP}/a.dart": {"material-color": 1}}, ("desktop",))
+ self.assertEqual(self.repo.run("--against", "HEAD"), (0, ""))
+
+ def test_an_areas_first_list_passes(self):
+ self.base({f"{DESKTOP}/a.dart": {"material-color": 2}})
+ self.repo.allow({f"{MOBILE}/b.dart": {"font-size": 9}}, ("mobile",))
+ self.assertEqual(self.repo.run("--against", "HEAD"), (0, ""))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/ui-style-allowlist/desktop.json b/scripts/ui-style-allowlist/desktop.json
new file mode 100644
index 000000000..9426cf953
--- /dev/null
+++ b/scripts/ui-style-allowlist/desktop.json
@@ -0,0 +1,111 @@
+{
+ "desktop/lib/super_tabs/agent_details.dart": {
+ "edge-insets": 2
+ },
+ "desktop/lib/super_tabs/agent_group_picker.dart": {
+ "edge-insets": 2
+ },
+ "desktop/lib/super_tabs/attachment_chips.dart": {
+ "edge-insets": 2,
+ "border-radius": 2
+ },
+ "desktop/lib/super_tabs/attachment_text_viewer.dart": {
+ "edge-insets": 1
+ },
+ "desktop/lib/super_tabs/confetti.dart": {
+ "hex-color": 6
+ },
+ "desktop/lib/super_tabs/decisions_view.dart": {
+ "edge-insets": 6
+ },
+ "desktop/lib/super_tabs/local_models.dart": {
+ "edge-insets": 7,
+ "border-radius": 3
+ },
+ "desktop/lib/super_tabs/machine_details.dart": {
+ "edge-insets": 6
+ },
+ "desktop/lib/super_tabs/machine_status.dart": {
+ "font-size": 1,
+ "edge-insets": 2
+ },
+ "desktop/lib/super_tabs/machines.dart": {
+ "edge-insets": 16,
+ "border-radius": 5
+ },
+ "desktop/lib/super_tabs/message_receipt.dart": {
+ "font-size": 2,
+ "edge-insets": 5,
+ "border-radius": 1
+ },
+ "desktop/lib/super_tabs/message_row.dart": {
+ "edge-insets": 5
+ },
+ "desktop/lib/super_tabs/message_text.dart": {
+ "edge-insets": 1
+ },
+ "desktop/lib/super_tabs/notifications.dart": {
+ "edge-insets": 8
+ },
+ "desktop/lib/super_tabs/pm_chat_rows.dart": {
+ "edge-insets": 3,
+ "border-radius": 2
+ },
+ "desktop/lib/super_tabs/profile_sheet.dart": {
+ "font-size": 1
+ },
+ "desktop/lib/super_tabs/project_github.dart": {
+ "edge-insets": 4
+ },
+ "desktop/lib/super_tabs/project_sidebar.dart": {
+ "edge-insets": 10
+ },
+ "desktop/lib/super_tabs/pull_requests.dart": {
+ "edge-insets": 12,
+ "border-radius": 2
+ },
+ "desktop/lib/super_tabs/reactions.dart": {
+ "font-size": 2,
+ "edge-insets": 3,
+ "border-radius": 1
+ },
+ "desktop/lib/super_tabs/recording_notice.dart": {
+ "edge-insets": 3
+ },
+ "desktop/lib/super_tabs/roles_editor.dart": {
+ "edge-insets": 1
+ },
+ "desktop/lib/super_tabs/roster.dart": {
+ "edge-insets": 4,
+ "border-radius": 1
+ },
+ "desktop/lib/super_tabs/route_row.dart": {
+ "edge-insets": 6
+ },
+ "desktop/lib/super_tabs/routing_policy_form.dart": {
+ "edge-insets": 3
+ },
+ "desktop/lib/super_tabs/saved_session.dart": {
+ "edge-insets": 4
+ },
+ "desktop/lib/super_tabs/section_heading.dart": {
+ "edge-insets": 1
+ },
+ "desktop/lib/super_tabs/sharing.dart": {
+ "edge-insets": 5
+ },
+ "desktop/lib/super_tabs/ship_row.dart": {
+ "font-size": 1,
+ "edge-insets": 2
+ },
+ "desktop/lib/super_tabs/team_glance_panel.dart": {
+ "edge-insets": 4
+ },
+ "desktop/lib/super_tabs/terminal_row.dart": {
+ "edge-insets": 2
+ },
+ "desktop/lib/super_tabs/view.dart": {
+ "edge-insets": 24,
+ "border-radius": 1
+ }
+}
diff --git a/scripts/ui-style-allowlist/mobile.json b/scripts/ui-style-allowlist/mobile.json
new file mode 100644
index 000000000..22d79145a
--- /dev/null
+++ b/scripts/ui-style-allowlist/mobile.json
@@ -0,0 +1,5 @@
+{
+ "mobile/lib/swarm/swarm_page.dart": {
+ "edge-insets": 2
+ }
+}