Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio tests: read UI labels from the en catalog, and follow the response-details action into MessageMenuTime (#11949)
Daniel Hane7edce154740
diff --git a/.github/workflows/studio-composer-compatibility.yml b/.github/workflows/studio-composer-compatibility.ymlindex 153a7a5de4a..d7c6c15ae01 100644--- a/.github/workflows/studio-composer-compatibility.yml+++ b/.github/workflows/studio-composer-compatibility.yml@@ -26,6 +26,8 @@ on:# line a PR that changes only the driver never runs the driver.- 'tests/studio/*queue_localization*'- 'tests/studio/_playwright_robust.py'+ # Both drivers find their controls through this reader, so a change to it is a change to them.+ - 'tests/studio/_en_catalog.py'- '.github/workflows/studio-composer-compatibility.yml'- '.github/scripts/retry-with-apt-lock.sh'workflow_dispatch:diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.ymlindex 05b5f8f6211..fdd6d43afc6 100644--- a/.github/workflows/workflow-trigger-lint.yml+++ b/.github/workflows/workflow-trigger-lint.yml@@ -148,6 +148,7 @@ jobs:tests/studio/test_step_scripts_get_the_secrets_they_read.py \tests/studio/test_composer_browser_tmpdir_is_short.py \tests/studio/test_composer_rtl_bidi_attribute.py \+ tests/studio/test_en_catalog.py \tests/studio/test_frontend_dep_removal.py \tests/studio/test_frontend_dist_cache.py \tests/studio/test_gguf_smoke_phases_stay_independent.py \diff --git a/tests/studio/_en_catalog.py b/tests/studio/_en_catalog.pynew file mode 100644index 00000000000..cebe9dfc938--- /dev/null+++ b/tests/studio/_en_catalog.py@@ -0,0 +1,227 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The shipped English UI strings, read by dotted key out of studio/frontend's en.ts.++Browser drivers find controls by their accessible name, and contract tests check that a label+lives in the catalog. Both used to retype the English, so a wording change that is correct by+construction (#11924 dropped the leading "Show" from eight settings labels) turned every Composer+leg and a Repo-tests contract red at once. Reading the catalog keeps them pinned to the key the+component renders, not to its current wording.++A small tokenizer rather than a TypeScript parse: the catalog is a nested object literal of+string values, and the alternative is a Node dependency for suites that are otherwise pure+Python. It tracks nesting, so `settings.chat.showResponseModel` is not confused with another+section's `showResponseModel`, and it accepts a value wrapped onto the line after its key.+"""++from __future__ import annotations++import functools+import json+import re+import string+from pathlib import Path++EN_LOCALE_TS = (+ Path(__file__).resolve().parents[2]+ / "studio"+ / "frontend"+ / "src"+ / "i18n"+ / "locales"+ / "en.ts"+)++_QUOTED = r"""(?:"(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)"""++# Whitespace and comments between tokens. A block comment stops at its own `*/`: a lazy+# `.*?` would stretch to a later comment's close and swallow the code between.+_TRIVIA = r"(?:\s|//[^\n]*|/\*(?:[^*]|\*(?!/))*\*/)*"++_TOKEN = re.compile(+ rf"""+ (?P<comment>//[^\n]*|/\*.*?\*/)+ | (?P<key>(?:[A-Za-z_$][\w$]*|{_QUOTED})){_TRIVIA}:+ | (?P<string>{_QUOTED})+ | (?P<open>\{{)+ | (?P<close>\}})+ | (?P<spread>\.\.\.)+ """,+ re.VERBOSE | re.DOTALL,+)++_STARTS_VALUE = re.compile(rf"{_TRIVIA}[\"'`{{]", re.S)+_ENDS_PROPERTY = re.compile(rf"{_TRIVIA}(?:,|\}}|$)", re.S)++_ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "b": "\b", "f": "\f", "v": "\v", "0": "\0"}+++class _Interpolated(str):+ """A template literal with `${...}` in it: not a label a test can match as written."""+++class _Expression(str):+ """A value built from more than one literal: not something this reader evaluates."""+++def _decode(literal: str) -> str:+ """The value of a JavaScript string literal, in any of its three quote styles.++ Single-quoted values are how the catalog writes English that itself contains double quotes+ (`'Are you sure you want to delete "{name}"?'`); reading only double-quoted ones handed back+ the inner `{name}` as the label.+ """+ body = literal[1:-1]+ out = []+ interpolated = False+ index = 0+ while index < len(body):+ char = body[index]+ if char == "$" and body[index + 1 : index + 2] == "{" and literal.startswith("`"):+ # Reached outside an escape, so this `${` is a live placeholder, not `\${`.+ interpolated = True+ if char == "\\" and index + 1 < len(body):+ nxt = body[index + 1]+ if body.startswith("\r\n", index + 1):+ # A line continuation contributes nothing to the value.+ index += 3+ continue+ if nxt in "\n\r\u2028\u2029":+ # So does one over any other ECMAScript line terminator.+ index += 2+ continue+ braced = re.match(r"u\{([0-9A-Fa-f]{1,6})\}", body[index + 1 :])+ if braced:+ out.append(chr(int(braced.group(1), 16)))+ index += 1 + braced.end()+ continue+ if (+ nxt == "x"+ and len(body[index + 2 : index + 4]) == 2+ and all(c in string.hexdigits for c in body[index + 2 : index + 4])+ ):+ out.append(chr(int(body[index + 2 : index + 4], 16)))+ index += 4+ continue+ if (+ nxt == "u"+ and len(body[index + 2 : index + 6]) == 4+ and all(c in string.hexdigits for c in body[index + 2 : index + 6])+ ):+ out.append(chr(int(body[index + 2 : index + 6], 16)))+ index += 6+ continue+ out.append(_ESCAPES.get(nxt, nxt))+ index += 2+ continue+ out.append(char)+ index += 1+ # `\uD83D\uDE00` decodes as two UTF-16 halves; join valid pairs into their code point.+ value = "".join(out).encode("utf-16-le", "surrogatepass").decode("utf-16-le", "surrogatepass")+ if interpolated:+ return _Interpolated(value)+ return value+++def _flatten(source: str) -> dict[str, str]:+ strings: dict[str, str] = {}+ path: list[str | None] = []+ pending: str | None = None+ pos = 0+ while True:+ match = _TOKEN.search(source, pos)+ if match is None:+ break+ pos = match.end()+ kind = match.lastgroup+ if kind == "comment":+ continue+ if kind == "key":+ # Tried before a plain string, so a quoted key followed by its colon is read as a key.+ raw = match.group("key")+ pending = raw if raw[0] not in "\"'`" else _decode(raw)+ if not _STARTS_VALUE.match(source, match.end()):+ # `flag ? "a" : "b"`, `labels.x` and the like: not a literal this reader can+ # evaluate, so the key is recorded as an expression rather than left to pick up+ # whichever literal comes next.+ dotted = ".".join(p for p in [*path, pending] if p is not None)+ strings[dotted] = _Expression("")+ pending = None+ elif kind == "open":+ path.append(pending)+ pending = None+ elif kind == "close":+ if path:+ path.pop()+ pending = None+ elif kind == "spread":+ # `...shared` applies after the properties before it, so any of them may be+ # replaced by a value this reader cannot see. Properties after it still win.+ prefix = ".".join(p for p in path if p is not None)+ for dotted, value in strings.items():+ if not prefix or dotted.startswith(prefix + "."):+ strings[dotted] = _Expression(value)+ pending = None+ elif kind == "string":+ if pending is not None:+ dotted = ".".join(p for p in [*path, pending] if p is not None)+ value = _decode(match.group("string"))+ # A plain value is the whole property: the next significant token ends it. Anything+ # else (`"a" + "b"`, `"a".toUpperCase()`, `flag ? "a" : "b"` read from its+ # middle) is an expression, and reading only this literal would hand back the+ # wrong label. Comments may sit before the terminator.+ if not _ENDS_PROPERTY.match(source, match.end()):+ value = _Expression(value)+ strings[dotted] = value+ pending = None+ return strings++[email protected]_cache(maxsize = None)+def _catalog(path: str) -> dict[str, str]:+ return _flatten(Path(path).read_text(encoding = "utf-8"))+++def en_string(key: str, catalog: Path = EN_LOCALE_TS) -> str:+ """The English for `key` (for example `composerSettings.showContext`), or fail naming the key.++ A missing key raises rather than returning "": an empty string is a substring of everything,+ and a locator built from it matches the wrong control instead of failing.+ """+ strings = _catalog(str(catalog))+ if key not in strings:+ raise KeyError(f"the en catalog no longer defines {key!r} ({catalog})")+ value = strings[key]+ if isinstance(value, _Interpolated):+ raise ValueError(+ f"{key!r} is a template with ${{...}} in it, not a fixed label ({catalog})"+ )+ if isinstance(value, _Expression):+ raise ValueError(f"{key!r} is an expression, not a single string literal ({catalog})")+ return str(value)+++def aria_label_selector(label: str) -> str:+ """A CSS selector for `[aria-label="<label>"]`, with the label quoted as a CSS string.++ Catalog text is data: English that holds a `"`, a `\\` or a control character such as CR or FF+ would otherwise end the string early or read as an escape, and the selector would be invalid or+ match something else.+ """+ if any("\ud800" <= char <= "\udfff" for char in label):+ # CSS replaces a lone surrogate with U+FFFD too, so the selector could never match.+ raise ValueError(f"a CSS selector cannot match a label with a lone surrogate: {label!r}")+ if "\0" in label:+ # CSS reads an escaped U+0000 as U+FFFD, so no selector can match a NUL in the label.+ raise ValueError(f"a CSS selector cannot match a label containing NUL: {label!r}")+ quoted = "".join(+ "\\" + char+ if char in '\\"'+ # CSS reads CR, LF and FF as line breaks, which end a string; write controls as code points.+ else f"\\{ord(char):x} "+ if ord(char) < 0x20 or char == "\x7f"+ else char+ for char in label+ )+ return f'[aria-label="{quoted}"]'diff --git a/tests/studio/playwright_composer_settings.py b/tests/studio/playwright_composer_settings.pyindex 65bc8b08bd9..b64ade26591 100644--- a/tests/studio/playwright_composer_settings.py+++ b/tests/studio/playwright_composer_settings.py@@ -11,6 +11,7 @@ import osimport refrom pathlib import Pathfrom playwright.sync_api import expect, sync_playwright+from _en_catalog import en_stringfrom _playwright_robust import start_vite, stop_process, wait_for_smoke_pagePAGE = "/smoke-composer-settings.html"@@ -18,9 +19,11 @@ ENTRY = "/smoke-composer-settings-main.tsx"def check_settings(page):- plain = page.get_by_role("switch", name = "Plain text composer", exact = True)- context = page.get_by_role("switch", name = "Show context window usage", exact = True)- select = page.get_by_role("combobox", name = "Send shortcut", exact = True)+ plain = page.get_by_role("switch", name = en_string("composerSettings.plainText"), exact = True)+ context = page.get_by_role("switch", name = en_string("composerSettings.showContext"), exact = True)+ select = page.get_by_role(+ "combobox", name = en_string("composerSettings.sendShortcut"), exact = True+ )editor = page.get_by_role("textbox", name = "Message", exact = True)preview = page.get_by_role("region", name = "Formatted preview", exact = True)submitted = page.get_by_label("Submitted messages")@@ -143,9 +146,9 @@ def main():errors = []page.on("pageerror", lambda error: errors.append(str(error)))page.goto(base + PAGE)- page.get_by_role("switch", name = "Plain text composer", exact = True).wait_for(- state = "visible", timeout = 60_000- )+ page.get_by_role(+ "switch", name = en_string("composerSettings.plainText"), exact = True+ ).wait_for(state = "visible", timeout = 60_000)check_settings(page)assert not errors, errorsfinally:diff --git a/tests/studio/selenium_composer_safari.py b/tests/studio/selenium_composer_safari.pyindex 98f55290165..f05c5e941b3 100644--- a/tests/studio/selenium_composer_safari.py+++ b/tests/studio/selenium_composer_safari.py@@ -11,6 +11,7 @@ from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import SessionNotCreatedException+from _en_catalog import aria_label_selector, en_stringfrom _playwright_robust import (open_session_with_retry,start_vite,@@ -39,7 +40,7 @@ def main():def label(name):return wait.until(- EC.visibility_of_element_located((By.CSS_SELECTOR, f'[aria-label="{name}"]'))+ EC.visibility_of_element_located((By.CSS_SELECTOR, aria_label_selector(name))))def order(ids):@@ -123,7 +124,7 @@ def main():label("Message")driver.execute_script("localStorage.clear()")driver.refresh()- label("Plain text composer").click()+ label(en_string("composerSettings.plainText")).click()editor = label("Message")driver.execute_script("window.composerInputTrace = []; for (const type of ['keydown', 'keyup', 'input']) document.addEventListener(type, e => window.composerInputTrace.push({type, key:e.key, meta:e.metaKey, ctrl:e.ctrlKey, value:e.target.value, label:e.target.getAttribute('aria-label')}), true)"@@ -132,7 +133,7 @@ def main():editor.send_keys("**Safari preview**")wait.until(lambda d: editor.get_attribute("value") == "**Safari preview**")wait.until(lambda d: "Safari preview" in label("Formatted preview").text)- label("Show context window usage").click()+ label(en_string("composerSettings.showContext")).click()text_button("Steer").click()editor.click()editor.send_keys(Keys.ENTER)@@ -149,8 +150,13 @@ def main():== "queue")driver.refresh()- assert label("Plain text composer").get_attribute("aria-checked") == "false"- assert label("Show context window usage").get_attribute("aria-checked") == "false"+ assert (+ label(en_string("composerSettings.plainText")).get_attribute("aria-checked") == "false"+ )+ assert (+ label(en_string("composerSettings.showContext")).get_attribute("aria-checked")+ == "false"+ )report["passed"] = Trueprint("PASS: native Safari queue controls, keyboard, pointer, preview, shortcuts and persistence",diff --git a/tests/studio/test_chat_response_details_ui_contract.py b/tests/studio/test_chat_response_details_ui_contract.pyindex 63c4a68fb3d..a2e84b09e5d 100644--- a/tests/studio/test_chat_response_details_ui_contract.py+++ b/tests/studio/test_chat_response_details_ui_contract.py@@ -8,8 +8,11 @@ from __future__ import annotationsimport refrom pathlib import Path+from _en_catalog import en_string+REPO = Path(__file__).resolve().parents[2]THREAD_TSX = REPO / "studio/frontend/src/components/assistant-ui/thread.tsx"+MESSAGE_MENU_TIME_TSX = REPO / "studio/frontend/src/components/assistant-ui/message-menu-time.tsx"DETAILS_TSX = (REPO / "studio/frontend/src/components/assistant-ui/message-response-details-sheet.tsx")@@ -350,10 +353,46 @@ def _without_comments(tag: str) -> str:def test_assistant_more_menu_exposes_response_details_action():- src = THREAD_TSX.read_text(encoding = "utf-8")+ """The More menu still opens the details sheet. Since #11928 the item lives in+ MessageMenuTime, beside the response's timestamp, so the action is followed through the+ prop thread.tsx hands it.++ Deliberately literal about today's wiring: thread.tsx passes an inline callback that opens+ the sheet and renders the sheet with `open={detailsOpen}`, and the menu item carries both+ the label and `onSelect={onShowDetails}` on one tag and is not disabled. A refactor that respells either line updates this test with it, which is cheaper and+ more honest than a hand-written JavaScript reader that tries to accept every equivalent+ spelling. Comments are removed first, so commented-out wiring does not count.+ """+ src = _without_block_comments(THREAD_TSX.read_text(encoding = "utf-8"))assert "MessageResponseDetailsSheet" in src- assert "See response details" in src- assert "setDetailsOpen(true)" in src+ # The component inspected below is the one thread.tsx imports.+ assert re.search(+ r"""import\s*\{\s*MessageMenuTime\s*\}\s*from\s*["']@/components/assistant-ui/message-menu-time["']""",+ src,+ ), "thread.tsx no longer imports MessageMenuTime from message-menu-time.tsx"+ caller = _opening_tag(src, "<MessageMenuTime ")+ assert (+ caller+ and re.match(+ r"<MessageMenuTime\s+onShowDetails=\{\s*\(\)\s*=>\s*setDetailsOpen\(\s*true\s*\)\s*\}",+ caller,+ )+ ), f"thread.tsx no longer hands MessageMenuTime a callback that opens the details sheet: {caller}"+ assert not _spread_overrides(caller, "onShowDetails"), caller+ sheet = _opening_tag(src, "<MessageResponseDetailsSheet")+ assert sheet and re.search(r"(?<![\w-])open=\{\s*detailsOpen\s*\}", sheet), sheet+ assert not _spread_overrides(sheet, "open"), sheet+ menu = _without_block_comments(MESSAGE_MENU_TIME_TSX.read_text(encoding = "utf-8"))+ item = _opening_tag(menu, "<ActionBarMorePrimitive.Item")+ assert item, "message-menu-time.tsx no longer renders a More-menu item"+ assert re.search(r'(?<![\w-])aria-label="See response details"', item), item+ assert re.search(r"(?<![\w-])onSelect=\{\s*onShowDetails\s*\}", item), item+ # A later `{...props}` could replace either prop.+ assert not _spread_overrides(item, "aria-label"), item+ assert not _spread_overrides(item, "onSelect"), item+ # A statically disabled item cannot be selected at all.+ disabled = re.search(r"(?<![\w-])disabled(?:=\{\s*([^{}]*?)\s*\})?(?=[\s/>])", item)+ assert disabled is None or disabled.group(1) == "false", itemdef test_response_details_sheet_uses_unsloth_sheet_and_key_sections():@@ -422,7 +461,8 @@ def test_response_model_badge_is_user_configurable_and_rendered_once_per_messageassert "showResponseModel: false" in prefs_srcassert "showResponseModel: saved?.showResponseModel ?? false" in prefs_src# The visible label lives in the locale file; the tab holds only the key that resolves to it.- assert 'showResponseModel: "Show response model"' in EN_LOCALE_TS.read_text(encoding = "utf-8")+ # By key, not wording: #11924 dropped the leading "Show" from this and seven other labels.+ assert en_string("settings.chat.showResponseModel", EN_LOCALE_TS)assert 't("settings.chat.showResponseModel")' in chat_tab_srcassert "setShowResponseModel" in chat_tab_srcdetails_src = DETAILS_TSX.read_text(encoding = "utf-8")diff --git a/tests/studio/test_en_catalog.py b/tests/studio/test_en_catalog.pynew file mode 100644index 00000000000..9c2c7446146--- /dev/null+++ b/tests/studio/test_en_catalog.py@@ -0,0 +1,277 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""`_en_catalog.en_string` resolves the key it is asked for, and every key the drivers ask for exists.++The drivers look controls up by `en_string(...)` in browser jobs that take minutes to reach the+lookup. A key renamed in en.ts would surface there as a locator timeout; checked here, it fails in+a second with the key's name.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from _en_catalog import EN_LOCALE_TS, _decode, aria_label_selector, en_string++HERE = Path(__file__).resolve().parent++SAMPLE = """\+// A comment with a key: "that is not one"+export const en = {+ composer: {+ title: "Composer",+ wrapped:+ "A value on the line after its key",+ braces: "Literal { and } inside a string",+ },+ settings: {+ title: "Settings",+ chat: {+ title: "Chat",+ "quoted-key": "Quoted",+ single: 'Delete "{name}"?',+ escaped: 'It\\'s here',+ tick: `Run \\`unsloth\\` now`,+ templated: `Hello ${name}`,+ literalDollar: `Type \\${name} as written`,+ hex: "Context\\x20window",+ codePoint: "Smile \\u{1F600}",+ continued: "one \\\ntwo",+ joined: "Context " + "window usage",+ noted: "Context " /* note */ + "window usage",+ upper: "context".toUpperCase(),+ picked: flag ? "short" : "long",+ separated: "a\\\u2028b",+ annotated /* translator note */: "Annotated",+ lineNoted // translator note+ : "Line noted",+ last: "Last" // trailing comment+ },+ overridden: {+ before: "Before",+ nested: { inner: "Inner" },+ ...shared,+ after: "After",+ },+ },+};+"""+++def sample(tmp_path):+ path = tmp_path / "en.ts"+ path.write_text(SAMPLE, encoding = "utf-8")+ return path+++ "key, expected",+ [+ ("composer.title", "Composer"),+ ("settings.title", "Settings"),+ ("settings.chat.title", "Chat"),+ ("composer.wrapped", "A value on the line after its key"),+ ("composer.braces", "Literal { and } inside a string"),+ ("settings.chat.quoted-key", "Quoted"),+ ("settings.chat.single", 'Delete "{name}"?'),+ ("settings.chat.escaped", "It's here"),+ ("settings.chat.tick", "Run `unsloth` now"),+ ("settings.chat.literalDollar", "Type ${name} as written"),+ ("settings.chat.hex", "Context window"),+ ("settings.chat.codePoint", "Smile \U0001f600"),+ ("settings.chat.continued", "one two"),+ ("settings.chat.last", "Last"),+ ("settings.chat.annotated", "Annotated"),+ ("settings.chat.lineNoted", "Line noted"),+ ("settings.chat.separated", "ab"),+ ("settings.overridden.after", "After"),+ ],+)+def test_a_key_resolves_by_its_full_path(sample, key, expected):+ assert en_string(key, sample) == expected++[email protected]("terminator", ["\n", "\r\n", "\r", "\u2028", "\u2029"])+def test_a_continuation_over_any_line_terminator_contributes_nothing(terminator):+ # Decoded directly: reading a file with read_text folds CR LF to LF before the tokenizer.+ assert _decode(f'"a\\{terminator}b"') == "ab"+++def test_a_missing_key_fails_naming_it(sample):+ with pytest.raises(KeyError, match = "settings.chat.gone"):+ en_string("settings.chat.gone", sample)+++def test_a_template_with_placeholders_is_refused(sample):+ with pytest.raises(ValueError, match = "templated"):+ en_string("settings.chat.templated", sample)+++ "label, selector",+ [+ ("Plain text", '[aria-label="Plain text"]'),+ ('Delete "{name}"?', '[aria-label="Delete \\"{name}\\"?"]'),+ ("C:\\models", '[aria-label="C:\\\\models"]'),+ ("two\nlines", '[aria-label="two\\a lines"]'),+ ("carriage\rreturn", '[aria-label="carriage\\d return"]'),+ ("form\ffeed", '[aria-label="form\\c feed"]'),+ ("tab\there", '[aria-label="tab\\9 here"]'),+ ],+)+def test_a_label_is_quoted_as_a_css_string(label, selector):+ assert aria_label_selector(label) == selector+++def test_a_concatenated_value_is_refused_not_truncated(sample):+ for key in (+ "settings.chat.joined",+ "settings.chat.noted",+ "settings.chat.upper",+ "settings.chat.picked",+ "settings.overridden.before",+ "settings.overridden.nested.inner",+ ):+ with pytest.raises(ValueError, match = "expression"):+ en_string(key, sample)+++def test_a_label_with_nul_is_refused_by_the_selector():+ with pytest.raises(ValueError, match = "NUL"):+ aria_label_selector("a\0b")+++def test_a_surrogate_pair_joins_and_a_lone_half_is_refused_by_the_selector():+ assert _decode('"\\uD83D\\uDE00"') == "\U0001f600"+ with pytest.raises(ValueError, match = "surrogate"):+ aria_label_selector(_decode('"\\uD800"'))+++def test_a_comment_is_not_read_as_a_key(sample):+ with pytest.raises(KeyError):+ en_string("key", sample)+++def test_the_shipped_catalog_resolves():+ assert en_string("composerSettings.showContext")+ assert en_string("settings.chat.showResponseModel")+ # Single-quoted in en.ts because it contains double quotes.+ assert en_string("shell.dialog.deleteChat.description").endswith('"{name}"?')+++def test_every_key_the_studio_tests_ask_for_exists():+ asked = {}+ for path in sorted(HERE.glob("*.py")):+ if path.name in {"_en_catalog.py", Path(__file__).name}:+ continue+ for key in re.findall(+ r"""en_string\(\s*["']([^"']+)["']""", path.read_text(encoding = "utf-8")+ ):+ asked.setdefault(key, path.name)+ assert asked, "no test looks a label up through en_string any more"+ missing = {}+ for key, where in asked.items():+ try:+ en_string(key)+ except KeyError:+ missing[key] = where+ assert not missing, f"keys asked for but not in {EN_LOCALE_TS.name}: {missing}"+++def _imports_catalog(path: Path) -> bool:+ """Whether a module imports `_en_catalog`, in either `import` or `from ... import` form."""+ import ast++ for node in ast.walk(ast.parse(path.read_text(encoding = "utf-8"))):+ if isinstance(node, ast.Import) and any(a.name == "_en_catalog" for a in node.names):+ return True+ if isinstance(node, ast.ImportFrom) and node.module == "_en_catalog":+ return True+ return False+++ "source, imports",+ [+ ("from _en_catalog import en_string\n", True),+ ("import _en_catalog\n", True),+ ("import os, _en_catalog as catalog\n", True),+ ("# from _en_catalog import en_string\n", False),+ ("x = 'from _en_catalog import en_string'\n", False),+ ],+)+def test_both_import_forms_mark_a_catalog_driver(tmp_path, source, imports):+ path = tmp_path / "driver.py"+ path.write_text(source, encoding = "utf-8")+ assert _imports_catalog(path) is imports+++COMPOSER_WORKFLOW = HERE.parents[1] / ".github" / "workflows" / "studio-composer-compatibility.yml"+++# Where each catalog driver runs, pinned literally: the step's `if:` and the matrix leg it+# needs. A new driver, or a restructured workflow, updates this table with it.+DRIVER_STEPS = {+ "playwright_composer_settings.py": (+ "matrix.suite == 'browsers'",+ {"suite": "browsers"},+ # Continues `run_driver "<log>" \`, whose failure the loop turns into the exit status.+ "python tests/studio/playwright_composer_settings.py || status=1",+ ),+ "selenium_composer_safari.py": (+ "${{ !cancelled() && matrix.suite == 'safari' }}",+ {"os": "macos-latest", "suite": "safari"},+ # Last command of a bash -e step, so its exit status is the step's.+ "python tests/studio/selenium_composer_safari.py",+ ),+}+++def test_the_composer_workflow_runs_on_a_catalog_only_change():+ """Both browser drivers find their controls through `_en_catalog.py`, and this workflow is+ the one that runs them. A PR that changes only the reader has to run it too.++ Deliberately literal rather than an evaluator of Actions expressions and shell: the reader+ is listed by name in `pull_request.paths` with no other filter; every catalog driver is+ in `DRIVER_STEPS`; and each runs from a step whose `if:` is exactly the pinned one, on a+ matrix leg that exists, as exactly the pinned command line (so `|| true`, an `echo` of it,+ or any other respelling fails). A workflow restructured some other way updates this test+ with it.+ """+ import yaml++ workflow = yaml.safe_load(COMPOSER_WORKFLOW.read_text(encoding = "utf-8"))+ triggers = workflow.get(True, workflow.get("on")) # PyYAML reads a bare `on:` as True.+ pull_request = triggers["pull_request"]+ assert "tests/studio/_en_catalog.py" in pull_request["paths"]+ assert not {"paths-ignore", "branches", "branches-ignore", "types"} & set(pull_request)+ drivers = sorted(+ path.name+ for path in HERE.glob("*.py")+ if not path.name.startswith(("test_", "_")) and _imports_catalog(path)+ )+ assert drivers, "no browser driver reads the catalog any more"+ assert set(drivers) <= set(DRIVER_STEPS), f"pin where these drivers run: {drivers}"+ for name in drivers:+ condition, leg, command = DRIVER_STEPS[name]+ found = [+ (job, step)+ for job in (workflow.get("jobs") or {}).values()+ for step in job.get("steps") or []+ if command in (line.strip() for line in str(step.get("run") or "").splitlines())+ ]+ assert found, f"no step runs exactly {command!r}"+ assert any(+ "if" not in job+ and str(step.get("if")) == condition+ and any(+ all(include.get(key) == value for key, value in leg.items())+ for include in ((job.get("strategy") or {}).get("matrix") or {}).get("include", [])+ )+ for job, step in found+ ), f"{name} no longer runs from a step gated on {condition!r} with the leg {leg}"