A platform for community discussion. Free, open, simple.
DEV: Add theme screenshots system spec and skill (#39426)
Penar Musarajef406fc8c080
diff --git a/.skills/discourse-screenshots/SKILL.md b/.skills/discourse-screenshots/SKILL.mdnew file mode 100644index 00000000000..584cb1d4cba--- /dev/null+++ b/.skills/discourse-screenshots/SKILL.md@@ -0,0 +1,112 @@+---+name: discourse-screenshots+description: Capture screenshots of the local Discourse site across the two core themes (Foundation, Horizon) and color modes (light, dark). Use when the user asks for "screenshots of themes", "light/dark mode shots", or similar.+---++# Discourse screenshots++Drives a system spec (`spec/system/theme_screenshots_spec.rb`) that discovers all system specs containing `screenshot_marker` marker calls, runs them under each combination of theme × device × color mode, and outputs PNGs plus a single `compare.html` viewer.++## How it works++Spec authors place `screenshot_marker(label: "my-label")` at the moment they want to capture. The orchestrator auto-discovers those specs and runs only the `it` blocks that contain a marker, skipping everything else. The `only:` kwarg restricts a capture to one device leg:++```ruby+screenshot_marker(label: "search-menu", only: :desktop)+```++Output files: `tmp/theme-screenshots/raw/{device}-{theme}-{mode}-{label}.png`+Comparison viewer: `tmp/theme-screenshots/compare.html` (tabs for device and color mode)++## Matrix (default)++| Theme | Modes | Devices |+|------------|-------------|-----------------|+| Foundation | light, dark | desktop, mobile |+| Horizon | light, dark | desktop, mobile |++## How to run++```bash+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 bin/rspec spec/system/theme_screenshots_spec.rb+```++`LOAD_PLUGINS=1` is always included so chat routes work.++### Arguments (env vars)++| Var | Default | Purpose |+|-------------------------|---------------------|---------------------------------------------------------------|+| `TAKE_SCREENSHOTS` | *(required)* | Must be `1` for the spec to run. |+| `LOAD_PLUGINS` | `1` | Always set so chat and plugin routes work. |+| `SCREENSHOTS_DIR` | `tmp/theme-screenshots` | Where PNGs and the HTML viewer are written. |+| `SCREENSHOTS_MODES` | `light,dark` | Comma-separated color modes. |+| `SCREENSHOTS_DEVICES` | `desktop,mobile` | Comma-separated devices. Mobile uses Playwright WebKit. |+| `SCREENSHOTS_THEMES` | `foundation,horizon`| Comma-separated built-in theme names to include. |+| `SCREENSHOTS_THEME_URL` | *(unset)* | Git URL of a remote theme to install and add to the matrix. |+| `SCREENSHOTS_THEME_NAME`| repo name | Filename label for the remote/extra theme. |+| `SCREENSHOTS_SUBSET` | *(unset)* | Substring filter on marker labels — only captures markers whose label contains this string. |++### Examples++```bash+# Default — all themes × light/dark × desktop/mobile+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 bin/rspec spec/system/theme_screenshots_spec.rb++# Desktop, light mode only+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 SCREENSHOTS_DEVICES=desktop SCREENSHOTS_MODES=light \+ bin/rspec spec/system/theme_screenshots_spec.rb++# Foundation only, dark only+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 SCREENSHOTS_THEMES=foundation SCREENSHOTS_MODES=dark \+ bin/rspec spec/system/theme_screenshots_spec.rb++# Add a remote theme alongside the built-ins+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 \+ SCREENSHOTS_THEME_URL=https://github.com/org/my-theme \+ SCREENSHOTS_THEME_NAME=my-theme \+ bin/rspec spec/system/theme_screenshots_spec.rb++# Only capture markers whose label contains "topic"+TAKE_SCREENSHOTS=1 LOAD_PLUGINS=1 SCREENSHOTS_SUBSET=topic \+ bin/rspec spec/system/theme_screenshots_spec.rb+```++## Invocation instructions++When this skill is invoked:++1. Build the command from `$ARGUMENTS`. If no arguments are given, use the default matrix.+2. Parse free-form args into env vars (composable — handle multiple at once):+ - "dark only" / "light only" → `SCREENSHOTS_MODES=…`+ - "desktop only" / "mobile only" → `SCREENSHOTS_DEVICES=…`+ - "foundation only" / "just horizon" → `SCREENSHOTS_THEMES=…`+ - A git URL for a theme → `SCREENSHOTS_THEME_URL=…`; also set `SCREENSHOTS_THEME_NAME=<label>` if the user provides a name+ - A label substring (e.g. "only topic markers", "just signup") → `SCREENSHOTS_SUBSET=…`+ - A directory path (e.g. "save to /tmp/foo") → `SCREENSHOTS_DIR=…`+3. Always include `LOAD_PLUGINS=1`.+4. Always prefix with `TAKE_SCREENSHOTS=1`.+5. If the user requests an unknown built-in theme name, tell them only `foundation` and `horizon` are supported — for any other theme use `SCREENSHOTS_THEME_URL`.+6. Run via `bin/rspec spec/system/theme_screenshots_spec.rb` from the repo root.+7. After the run, list the files saved (`ls` on the raw dir) and surface the `compare.html` path to the user. Show failures if `bin/rspec` exits non-zero.++## Adding markers to a spec++In any system spec, `include ThemeScreenshotMarker` and call `screenshot_marker` at the point you want to capture:++```ruby+describe "Search" do+ include ThemeScreenshotMarker++ it "shows search results" do+ visit "/search"+ search_page.type_in_search("test")+ search_page.click_search_button++ screenshot_marker(label: "search-results") # captured on all devices+ screenshot_marker(label: "search-menu", only: :desktop) # desktop only+ end+end+```++The `include ThemeScreenshotMarker` line is required — without it, `screenshot_marker` is undefined when the spec is run directly. The orchestrator also auto-includes it as a safety net, but relying on that alone will break direct spec runs.diff --git a/plugins/chat/spec/system/chat/composer/channel_spec.rb b/plugins/chat/spec/system/chat/composer/channel_spec.rbindex 7d08965c922..8bc22c87368 100644--- a/plugins/chat/spec/system/chat/composer/channel_spec.rb+++ b/plugins/chat/spec/system/chat/composer/channel_spec.rb@@ -56,6 +56,8 @@ RSpec.describe "Chat | composer | channel" dochannel_page.reply_to(message_1)expect(thread_page.composer).to be_focused++ screenshot_marker(label: "chat-thread", only: "desktop")endendenddiff --git a/plugins/chat/spec/system/reply_to_message/full_page_spec.rb b/plugins/chat/spec/system/reply_to_message/full_page_spec.rbindex 2a33073e659..5d47eb502ab 100644--- a/plugins/chat/spec/system/reply_to_message/full_page_spec.rb+++ b/plugins/chat/spec/system/reply_to_message/full_page_spec.rb@@ -37,6 +37,7 @@ RSpec.describe "Reply to message - channel - full page" doexpect(thread_page.messages).to have_message(text: "reply to message")expect(channel_page).to have_thread_indicator(original_message)+ screenshot_marker(label: "chat-reply", only: "desktop")endcontext "when reloading after creating thread" dodiff --git a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rbindex 1178dcf1f74..2d62c8de026 100644--- a/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb+++ b/plugins/discourse-ai/spec/system/admin_ai_features_spec.rb@@ -44,6 +44,8 @@ RSpec.describe "Admin AI features configuration" doai_features_page.toggle_unconfiguredexpect(ai_features_page).to have_listed_modules(all_modules.size - configured_count)++ screenshot_marker(label: "ai-admin-features")endit "lists the agent used for the corresponding AI feature" dodiff --git a/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rbindex 6b4bfcb0de3..51381a63d75 100644--- a/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb+++ b/plugins/discourse-ai/spec/system/admin_ai_translations_spec.rb@@ -47,6 +47,8 @@ RSpec.describe "Admin AI translations" doexpect(translations_page).to have_charts_sectionexpect(translations_page).to have_chart++ screenshot_marker(label: "ai-admin-translations", only: "desktop")endit "navigates to translation settings when clicking the settings button" dodiff --git a/spec/fabricators/post_fabricator.rb b/spec/fabricators/post_fabricator.rbindex 8e908b8bae5..7116aef24c0 100644--- a/spec/fabricators/post_fabricator.rb+++ b/spec/fabricators/post_fabricator.rb@@ -137,6 +137,28 @@ Fabricator(:post_with_external_links, from: :post) doMDend+Fabricator(:post_with_rich_content, from: :post) do+ user { Fabricate(:user, refresh_auto_groups: true) }+ topic+ raw <<~MD+ Here is a link to http://google.com now then.++ > What's up with this quote? It's just that, a quote.++ And this is an unordered list:++ - list item 1 is about this long+ - list item 2 with a longer description for testing purposes+ - third list item with a date: [date=2026-03-18 timezone=America/Toronto]++ [details="Summary"]+ Gotta add some stuff inside the fold.+ [/details]++ :smile:+ MD+end+Fabricator(:private_message_post, from: :post) dotransient :recipientuserdiff --git a/spec/rails_helper.rb b/spec/rails_helper.rbindex a8add1118e2..53d13e285bd 100644--- a/spec/rails_helper.rb+++ b/spec/rails_helper.rb@@ -268,6 +268,7 @@ RSpec.configure do |config|config.include RSpecHtmlMatchersconfig.include IntegrationHelpers, type: :requestconfig.include SystemHelpers, type: :system+ config.include ThemeScreenshotMarker, type: :systemconfig.include DiscourseWebauthnIntegrationHelpersconfig.include SiteSettingsHelpersconfig.include SidekiqHelpersdiff --git a/spec/support/theme_screenshot_marker.rb b/spec/support/theme_screenshot_marker.rbnew file mode 100644index 00000000000..d2fcf2d578e--- /dev/null+++ b/spec/support/theme_screenshot_marker.rb@@ -0,0 +1,78 @@+# frozen_string_literal: true++# Included in all system specs (via rails_helper) to provide screenshot_marker.+#+# Usage:+# it "opens the composer" do+# # ... set up state ...+# screenshot_marker(label: "composer-open")+# # ... assertions ...+# end+#+# screenshot_marker is a no-op unless TAKE_SCREENSHOTS=1 is set.+# Output lands in tmp/theme-screenshots/raw/ (or SCREENSHOTS_DIR/raw/).+#+# When run via the theme_screenshots_spec matrix runner, SCREENSHOTS_THEME_ID,+# SCREENSHOTS_THEME_NAME, SCREENSHOTS_MODE, and SCREENSHOTS_DEVICE are injected+# internally as env vars. The before hook sets SiteSetting.default_theme_id so+# every subsequent page visit in the example renders with the correct theme.+#+module ThemeScreenshotMarker+ def self.included(base)+ base.before do+ next unless ENV["TAKE_SCREENSHOTS"] == "1"++ SiteSetting.global_notice = ""++ if (theme_id = ENV["SCREENSHOTS_THEME_ID"].presence&.to_i) && theme_id != 0+ SiteSetting.default_theme_id = theme_id+ end++ if (mode = ENV["SCREENSHOTS_MODE"].presence)+ page.driver.with_playwright_page { |pw_page| pw_page.emulate_media(colorScheme: mode) }+ end++ page.driver.with_playwright_page do |pw_page|+ pw_page.add_style_tag(content: "#global-notice-theme-preview { display: none !important; }")+ end+ end+ end++ # `only:` constrains which device leg of the matrix the screenshot belongs+ # to. Use it for features that don't exist on the other device (e.g. the+ # full search menu is desktop-only). The orchestrator parses this kwarg+ # from the source to also skip the surrounding example on the wrong leg —+ # this in-method check is a belt-and-braces fallback.+ def screenshot_marker(label:, only: nil)+ return unless ENV["TAKE_SCREENSHOTS"] == "1"++ device = ENV["SCREENSHOTS_DEVICE"] || "desktop"++ return if only && only.to_s != device++ output_dir = ENV["SCREENSHOTS_DIR"] || Rails.root.join("tmp/theme-screenshots").to_s+ raw_dir = File.join(output_dir, "raw")+ FileUtils.mkdir_p(raw_dir)+ theme_name = ENV["SCREENSHOTS_THEME_NAME"] || "default"+ mode = ENV["SCREENSHOTS_MODE"] || "light"++ page.driver.with_playwright_page do |pw_page|+ unless @message_bus_blocked+ pw_page.route(%r{/message-bus/}, ->(route, _request) { route.abort })+ @message_bus_blocked = true+ end+ pw_page.wait_for_load_state(state: "networkidle", timeout: 10_000)+ rescue Playwright::TimeoutError+ # page is visually complete; a stray background request is still open+ end++ filename = File.join(raw_dir, "#{device}-#{theme_name}-#{mode}-#{label}.png")++ page.driver.with_playwright_page do |pw_page|+ pw_page.set_viewport_size(width: pw_page.viewport_size[:width], height: 1200)+ pw_page.screenshot(path: filename)+ end++ puts "📸 #{filename}"+ end+enddiff --git a/spec/system/admin_customize_themes_config_area_spec.rb b/spec/system/admin_customize_themes_config_area_spec.rbindex 147bad95a44..863ec70d06a 100644--- a/spec/system/admin_customize_themes_config_area_spec.rb+++ b/spec/system/admin_customize_themes_config_area_spec.rb@@ -19,6 +19,8 @@ describe "Admin Customize Themes Config Area Page" doit "has an install button in the subheader" doconfig_area.visit+ screenshot_marker(label: "admin-themes", only: "desktop")+install_modal = config_area.click_install_buttonexpect(install_modal.popular_options.first).to have_text("Graceful")enddiff --git a/spec/system/admin_dashboard_general_spec.rb b/spec/system/admin_dashboard_general_spec.rbindex 432169bef02..dd2adf3accc 100644--- a/spec/system/admin_dashboard_general_spec.rb+++ b/spec/system/admin_dashboard_general_spec.rb@@ -15,6 +15,8 @@ describe "Admin Dashboard General Tab" doit "displays correct visit counters combining desktop and mobile visits" dovisit("/admin")+ screenshot_marker(label: "admin-dashboard")+within ".admin-report.visits .admin-report-counters" doexpect(page).to have_css(".today-count", text: "2")expect(page).to have_css(".yesterday-count", text: "1")diff --git a/spec/system/groups/group_spec.rb b/spec/system/groups/group_spec.rbindex fa89b9342be..dbe5e60d967 100644--- a/spec/system/groups/group_spec.rb+++ b/spec/system/groups/group_spec.rb@@ -14,6 +14,9 @@ describe "Group" docontext "when there are no existing users matching the auto e-mail domains" doit "creates a new group" dogroup_index_page.visit++ screenshot_marker(label: "groups")+group_index_page.click_new_groupgroup_form_page.fill_in("name", with: "illuminati")diff --git a/spec/system/login_spec.rb b/spec/system/login_spec.rbindex 551f25d0d98..41c71c2d4dd 100644--- a/spec/system/login_spec.rb+++ b/spec/system/login_spec.rb@@ -128,10 +128,14 @@ shared_examples "login scenarios" doit "cannot browse annonymously" dovisit "/"++ screenshot_marker(label: "login-required")expect(page).to have_css(".login-welcome")expect(page).to have_css(".site-logo")find(".login-welcome .login-button").click+ screenshot_marker(label: "login-form")+EmailToken.confirm(Fabricate(:email_token, user: user).token)login_form.fill(username: "john", password: "supersecurepassword").click_loginexpect(page).to have_css(".header-dropdown-toggle.current-user")diff --git a/spec/system/search_spec.rb b/spec/system/search_spec.rbindex f53b94e9337..c1ba73d030f 100644--- a/spec/system/search_spec.rb+++ b/spec/system/search_spec.rb@@ -125,6 +125,7 @@ describe "Search" dovisit("/")search_page.click_search_iconsearch_page.type_in_search_menu("test")+search_page.click_search_menu_linkexpect(search_page).to have_topic_title_for_first_search_result(topic.title)search_page.click_first_topicdiff --git a/spec/system/signup_spec.rb b/spec/system/signup_spec.rbindex 80fb4b6a9f4..24ca617e8fe 100644--- a/spec/system/signup_spec.rb+++ b/spec/system/signup_spec.rb@@ -20,6 +20,8 @@ shared_examples "signup scenarios" do.fill_password("supersecurepassword")expect(signup_page).to have_valid_fields+ screenshot_marker(label: "signup")+signup_page.click_create_accountexpect(page).to have_current_path("/u/account-created")@@ -42,6 +44,8 @@ shared_examples "signup scenarios" dovisit activation_link+ screenshot_marker(label: "signup-activation")+activate_account.click_activate_accountactivate_account.click_continuediff --git a/spec/system/theme_screenshots_spec.rb b/spec/system/theme_screenshots_spec.rbnew file mode 100644index 00000000000..9565679b225--- /dev/null+++ b/spec/system/theme_screenshots_spec.rb@@ -0,0 +1,517 @@+# frozen_string_literal: true++# System spec for capturing screenshots at marked points in other system specs.+# Run via:+#+# TAKE_SCREENSHOTS=1 bin/rspec spec/system/theme_screenshots_spec.rb+#+# Discovers all system specs that call `screenshot_marker` and runs them under+# each combination of theme × device × color mode, then generates a single+# HTML comparison page with tabs for device and color mode.+#+# Optional env vars:+# SCREENSHOTS_DIR — output directory (default: tmp/theme-screenshots)+# SCREENSHOTS_MODES — comma-separated modes (default: light,dark)+# SCREENSHOTS_DEVICES — comma-separated devices (default: desktop,mobile)+# SCREENSHOTS_THEMES — comma-separated theme names (default: foundation,horizon)+# SCREENSHOTS_THEME_URL — git URL of a remote theme to install into the test DB+# (theme name is deduced from the repo name in the URL)+# SCREENSHOTS_SUBSET — substring filter on marker labels; only examples whose+# label contains this string are captured (e.g. "topic")++DEVICES = (ENV["SCREENSHOTS_DEVICES"] || "desktop,mobile").split(",").map(&:strip).freeze++describe "Theme screenshots" do+ before { skip "Set TAKE_SCREENSHOTS=1 to run this spec" if ENV["TAKE_SCREENSHOTS"] != "1" }++ let(:output_dir) do+ dir = ENV["SCREENSHOTS_DIR"] || Rails.root.join("tmp/theme-screenshots").to_s+ FileUtils.mkdir_p(dir)+ dir+ end++ let(:raw_dir) do+ dir = File.join(output_dir, "raw")+ FileUtils.mkdir_p(dir)+ dir+ end++ let(:modes) { (ENV["SCREENSHOTS_MODES"] || "light,dark").split(",").map(&:strip) }++ let(:themes) do+ core = Theme::CORE_THEMES.map { |name, id| { name: name, id: id } }+ base =+ if ENV["SCREENSHOTS_THEMES"].present?+ requested = ENV["SCREENSHOTS_THEMES"].split(",").map { |n| n.downcase.strip }+ core.select { |t| requested.include?(t[:name]) }+ else+ core+ end++ if (url = ENV["SCREENSHOTS_THEME_URL"].presence)+ name = File.basename(url.chomp("/"), ".git")+ tmpdir = Dir.mktmpdir("discourse_theme_screenshot_")+ system("git", "clone", "--depth", "1", url, tmpdir, exception: true)+ theme = RemoteTheme.import_theme_from_directory(tmpdir)+ theme.update!(user_selectable: true)+ Stylesheet::Manager.clear_theme_cache!+ base = base + [{ name: name, id: theme.id }]+ end++ base+ end++ before do+ Theme.where(id: themes.map { |t| t[:id] }).update_all(user_selectable: true)++ themes.each do |t|+ SystemThemesManager.sync_theme!(t[:name]) if Theme::CORE_THEMES.key?(t[:name])+ end++ SiteIconManager.clear_cache!++ allow(TopicUser).to receive(:track_visit!)+ end++ it "captures screenshots" do+ FileUtils.rm_f(Dir.glob(File.join(raw_dir, "*.png")))++ run_marker_matrix(device: "desktop") if DEVICES.include?("desktop")+ run_marker_matrix(device: "mobile") if DEVICES.include?("mobile")++ generate_comparison_html+ end++ private++ def discover_marker_specs+ patterns = [+ Rails.root.join("spec/system/**/*.rb").to_s,+ Rails.root.join("plugins/*/spec/system/**/*.rb").to_s,+ ]+ Dir+ .glob(patterns)+ .reject { |f| File.realpath(f) == File.realpath(__FILE__) }+ .select { |f| File.read(f).include?("screenshot_marker") }+ end++ def run_marker_matrix(device:)+ specs = discover_marker_specs+ if specs.empty?+ puts "No specs with screenshot_marker markers found."+ return+ end++ puts "Found #{specs.size} spec(s) with markers: #{specs.map { |s| File.basename(s) }.join(", ")}"++ marker_groups = load_marker_groups(specs)+ filter_marker_examples(marker_groups, specs, device)+ filter_device_split(marker_groups, device)+ apply_device_metadata(marker_groups, device)++ # `group.run` sets `RSpec.current_example` per inner example and leaves it+ # `nil` when the group finishes. The outer example's after-hooks (e.g.+ # rails_helper's `extra_failure_lines`) read it, so restore it after each+ # inner run.+ outer_example = RSpec.current_example+ begin+ themes.each do |theme|+ modes.each do |mode|+ with_screenshot_env(theme: theme, mode: mode, device: device) do+ marker_groups.each do |group|+ group.run(RSpec.configuration.reporter)+ RSpec.current_example = outer_example+ end+ end+ end+ end+ ensure+ RSpec.current_example = outer_example+ cleanup_marker_groups(marker_groups)+ end+ end++ # Loads each marker spec file via `load` so its `describe` blocks register new+ # example groups in `RSpec.world`.+ def load_marker_groups(spec_files)+ groups = []+ spec_files.each do |spec_file|+ before = RSpec.world.example_groups.dup+ load spec_file+ groups.concat(RSpec.world.example_groups - before)+ end+ groups+ end++ # Filter specs that don't include a `screenshot_marker`+ # Examples whose `screenshot_marker` was called with `only: :desktop` (or+ # `:mobile`) are kept only on the matching leg.+ def filter_marker_examples(groups, spec_files, device)+ constraints = spec_files.to_h { |f| [File.expand_path(f), screenshot_example_constraints(f)] }+ groups.each { |g| keep_screenshot_examples(g, constraints, device) }+ end++ # Returns a hash mapping the line number of each `it` / `scenario` / `example`+ # / `specify` block that contains `screenshot_marker` to a constraint hash:+ # { only: :desktop, labels: ["my-label"] } — call site has `only: :desktop` or `only: "desktop"`+ # { only: nil, labels: ["a", "b"] } — call site has no constraint+ #+ # If a single example contains multiple `screenshot_marker` calls with+ # conflicting constraints, the most permissive (no `only`) wins.+ # All labels across all markers in the example are collected.+ def screenshot_example_constraints(spec_file)+ lines = File.readlines(spec_file)+ result = {}+ lines.each_with_index do |line, idx|+ next if line.exclude?("screenshot_marker")+ only_match = line.match(/only:\s*(?::(\w+)|["'](\w+)["'])/)+ only = only_match ? (only_match[1] || only_match[2]).to_sym : nil+ label_match = line.match(/label:\s*["']([^"']+)["']/)+ label = label_match ? label_match[1] : nil+ (idx - 1).downto(0) do |i|+ if lines[i] =~ /^\s*(it|scenario|example|specify)\b/+ existing = result[i + 1]+ if existing+ existing[:only] = only if existing[:only] # most permissive (nil) wins+ existing[:labels] << label if label+ else+ result[i + 1] = { only: only, labels: label ? [label] : [] }+ end+ break+ end+ end+ end+ result+ end++ def keep_screenshot_examples(group, constraints_per_file, device)+ subset = ENV["SCREENSHOTS_SUBSET"].presence+ group.examples.select! do |ex|+ file = File.expand_path(ex.metadata[:file_path])+ constraint = (constraints_per_file[file] || {})[ex.metadata[:line_number]]+ next false unless constraint+ only = constraint[:only]+ next false unless only.nil? || only.to_s == device+ next false if subset && constraint[:labels].none? { |l| l.include?(subset) }+ true+ end+ group.children.each { |child| keep_screenshot_examples(child, constraints_per_file, device) }+ group.children.reject! { |child| empty_group?(child) }+ end++ def empty_group?(group)+ group.examples.empty? && group.children.all? { |c| empty_group?(c) }+ end++ # Some specs split their suite by device with sibling contexts — one tagged+ # `mobile: true`, the other left as desktop (e.g. signup_spec's+ # "when desktop" / "when mobile" using shared_examples). Detect that pattern+ # by spotting a group whose children have a mix of mobile and non-mobile+ # metadata, and keep only the side that matches the current leg. Specs+ # without this pattern are unaffected.+ def filter_device_split(groups, device)+ groups.each { |g| filter_device_split_recursively(g, device) }+ groups.reject! { |g| empty_group?(g) }+ end++ def filter_device_split_recursively(group, device)+ group.children.each { |child| filter_device_split_recursively(child, device) }++ has_mobile = group.children.any? { |c| c.metadata[:mobile] }+ has_non_mobile = group.children.any? { |c| !c.metadata[:mobile] }+ return unless has_mobile && has_non_mobile++ if device == "mobile"+ group.children.select! { |c| c.metadata[:mobile] }+ else+ group.children.select! { |c| !c.metadata[:mobile] }+ end+ end++ # The `:mobile` metadata is what triggers the global `before(:each)` hook in+ # rails_helper to switch the Capybara driver to the mobile WebKit driver.+ # Marker specs don't tag themselves `:mobile`, so we stamp it on at runtime+ # when we're in the mobile leg of the matrix.+ def apply_device_metadata(groups, device)+ return unless device == "mobile"+ groups.each { |g| set_mobile_recursively(g) }+ end++ def set_mobile_recursively(group)+ group.metadata[:mobile] = true+ group.examples.each { |ex| ex.metadata[:mobile] = true }+ group.children.each { |child| set_mobile_recursively(child) }+ end++ def cleanup_marker_groups(groups)+ groups.each { |g| RSpec.world.example_groups.delete(g) }+ end++ def with_screenshot_env(theme:, mode:, device:)+ saved = {}+ overrides = {+ "TAKE_SCREENSHOTS" => "1",+ "SCREENSHOTS_DIR" => output_dir,+ "SCREENSHOTS_THEME_NAME" => theme[:name],+ "SCREENSHOTS_THEME_ID" => theme[:id].to_s,+ "SCREENSHOTS_MODE" => mode.to_s,+ "SCREENSHOTS_DEVICE" => device,+ }+ overrides.each do |k, v|+ saved[k] = ENV[k]+ ENV[k] = v+ end+ yield+ ensure+ saved.each { |k, v| v.nil? ? ENV.delete(k) : ENV[k] = v }+ end++ # Scans raw_dir for all captured PNGs and builds an HTML comparison page.+ def generate_comparison_html+ theme_names = themes.map { |t| t[:name] }++ # panels[device][mode][label] = [{label: theme_name, file: abs_path}, ...]+ panels =+ Hash.new { |h, k| h[k] = Hash.new { |h2, k2| h2[k2] = Hash.new { |h3, k3| h3[k3] = [] } } }++ Dir+ .glob(File.join(raw_dir, "*.png"))+ .sort+ .each do |file|+ basename = File.basename(file, ".png")+ DEVICES.each do |device|+ next unless basename.start_with?("#{device}-")+ rest = basename.delete_prefix("#{device}-")+ theme_names.each do |theme_name|+ next unless rest.start_with?("#{theme_name}-")+ rest2 = rest.delete_prefix("#{theme_name}-")+ modes.each do |mode|+ next unless rest2.start_with?("#{mode}-")+ label = rest2.delete_prefix("#{mode}-")+ panels[device][mode][label] << { label: theme_name, file: file }+ break+ end+ break+ end+ break+ end+ end++ return if panels.empty?++ html_path = File.join(output_dir, "compare.html")+ write_comparison_html(html_path, panels)+ puts "🌐 Comparison: file://#{html_path}"+ end++ def write_comparison_html(html_path, panels)+ html_dir = File.dirname(html_path)++ available_devices = DEVICES.select { |d| panels[d].any? }+ available_modes = modes.select { |m| panels.values.any? { |dm| dm[m]&.any? } }+ all_labels = panels.values.flat_map { |modes_h| modes_h.values.flat_map(&:keys) }.uniq++ panels_html =+ available_devices+ .flat_map do |device|+ available_modes.flat_map do |mode|+ all_labels.map do |label|+ entries = panels[device][mode][label]+ next "" if entries.empty?++ cols =+ entries.map do |entry|+ rel = Pathname.new(entry[:file]).relative_path_from(Pathname.new(html_dir)).to_s+ <<~COL+ <div class="col">+ <div class="col-label">#{entry[:label]}</div>+ <img src="#{rel}" loading="lazy" onclick="openLightbox(this)">+ </div>+ COL+ end++ panel_id = "panel-#{device}-#{mode}-#{label}"+ <<~PANEL+ <div class="panel" id="#{panel_id}" data-device="#{device}" data-mode="#{mode}" data-label="#{label}">+ #{cols.join}+ </div>+ PANEL+ end+ end+ end+ .join("\n")++ device_tabs_html =+ available_devices+ .map do |d|+ active = d == available_devices.first ? " active" : ""+ %(<button class="tab#{active}" data-device="#{d}" onclick="selectDevice('#{d}')">#{d.capitalize}</button>)+ end+ .join("\n ")++ mode_tabs_html =+ available_modes+ .map do |m|+ active = m == available_modes.first ? " active" : ""+ %(<button class="tab#{active}" data-mode="#{m}" onclick="selectMode('#{m}')">#{m.capitalize}</button>)+ end+ .join("\n ")++ panels_json =+ available_devices.flat_map do |device|+ available_modes.flat_map do |mode|+ all_labels.filter_map do |label|+ next if panels[device][mode][label].empty?+ %({ "device": "#{device}", "mode": "#{mode}", "label": "#{label}" })+ end+ end+ end++ File.write(html_path, <<~HTML)+ <!doctype html>+ <html>+ <head>+ <meta charset="utf-8">+ <title>Theme Screenshots</title>+ <style>+ * { box-sizing: border-box; margin: 0; padding: 0; }+ body { background: #111; color: #eee; font-family: system-ui, sans-serif; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }+ header { display: grid; grid-template-columns: 1fr auto 1fr; align-items: center; gap: 8px; padding: 7px 12px; background: #1a1a1a; border-bottom: 1px solid #333; flex-shrink: 0; }+ .header-left { display: flex; align-items: center; gap: 4px; }+ .header-center { display: flex; justify-content: center; }+ .header-right { display: flex; align-items: center; justify-content: flex-end; gap: 6px; }+ .tab-group { display: flex; gap: 4px; }+ .tab { padding: 3px 12px; background: #2a2a2a; color: #888; border: 1px solid #444; border-radius: 4px; cursor: pointer; font-size: 13px; }+ .tab.active { background: #3a3a3a; color: #fff; border-color: #666; }+ .sep { width: 1px; background: #333; height: 22px; margin: 0 4px; }+ .btn { padding: 3px 10px; background: #2a2a2a; color: #ccc; border: 1px solid #444; border-radius: 4px; cursor: pointer; font-size: 14px; line-height: 1.4; }+ .btn:disabled { opacity: 0.3; cursor: default; }+ #counter { font-size: 12px; color: #666; min-width: 44px; text-align: center; }+ #label-display { font-size: 14px; font-weight: 600; color: #fff; text-align: center; letter-spacing: 0.01em; }+ .content { flex: 1; overflow: hidden; }+ .panel { display: none; flex-direction: row; gap: 2px; height: 100%; }+ .panel.active { display: flex; }+ .col { flex: 1; min-width: 0; display: flex; flex-direction: column; }+ .col-label { flex-shrink: 0; background: #1a1a1a; padding: 5px 10px; font-size: 12px; font-weight: 600; text-align: center; border-bottom: 1px solid #222; }+ .col img { flex: 1; min-height: 0; width: 100%; object-fit: contain; object-position: top center; display: block; cursor: zoom-in; }+ .lightbox { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.92); z-index: 100; flex-direction: column; align-items: center; justify-content: center; gap: 8px; cursor: zoom-out; }+ .lightbox.active { display: flex; }+ .lightbox-label { color: #bbb; font-size: 13px; font-weight: 600; flex-shrink: 0; }+ .lightbox img { max-width: 95vw; max-height: calc(95vh - 32px); object-fit: contain; cursor: zoom-out; }+ </style>+ </head>+ <body>+ <header>+ <div class="header-left">+ <div class="tab-group" id="device-tabs">+ #{device_tabs_html}+ </div>+ <div class="sep"></div>+ <div class="tab-group" id="mode-tabs">+ #{mode_tabs_html}+ </div>+ </div>+ <div class="header-center">+ <span id="label-display"></span>+ </div>+ <div class="header-right">+ <button class="btn" id="btn-prev" onclick="navigate(-1)">←</button>+ <span id="counter"></span>+ <button class="btn" id="btn-next" onclick="navigate(1)">→</button>+ </div>+ </header>+ <div class="content">+ #{panels_html}+ </div>+ <div class="lightbox" id="lightbox" onclick="closeLightbox()">+ <div class="lightbox-label" id="lightbox-label"></div>+ <img id="lightbox-img" src="">+ </div>+ <script>+ var allPanels = [#{panels_json.join(",\n")}];+ var currentDevice = #{available_devices.first.to_json};+ var currentMode = #{available_modes.first.to_json};+ var labelIndex = 0;++ function filtered() {+ return allPanels.filter(function(p) {+ return p.device === currentDevice && p.mode === currentMode;+ });+ }++ function show() {+ var set = filtered();+ labelIndex = Math.max(0, Math.min(set.length - 1, labelIndex));+ document.querySelectorAll('.panel').forEach(function(el) {+ el.classList.remove('active');+ });+ if (!set.length) return;+ var p = set[labelIndex];+ var el = document.getElementById('panel-' + p.device + '-' + p.mode + '-' + p.label);+ if (el) el.classList.add('active');+ document.getElementById('counter').textContent = (labelIndex + 1) + ' / ' + set.length;+ document.getElementById('label-display').textContent = p.label;+ document.getElementById('btn-prev').disabled = labelIndex === 0;+ document.getElementById('btn-next').disabled = labelIndex === set.length - 1;+ }++ function navigate(dir) {+ labelIndex += dir;+ show();+ }++ function selectDevice(device) {+ currentDevice = device;+ document.querySelectorAll('#device-tabs .tab').forEach(function(t) {+ t.classList.toggle('active', t.dataset.device === device);+ });+ show();+ }++ function selectMode(mode) {+ currentMode = mode;+ document.querySelectorAll('#mode-tabs .tab').forEach(function(t) {+ t.classList.toggle('active', t.dataset.mode === mode);+ });+ show();+ }++ var lightboxImages = [];+ var lightboxIndex = 0;++ function showLightboxImage() {+ var img = lightboxImages[lightboxIndex];+ document.getElementById('lightbox-label').textContent = img.closest('.col').querySelector('.col-label').textContent;+ document.getElementById('lightbox-img').src = img.src;+ }++ function openLightbox(img) {+ var panel = img.closest('.panel');+ lightboxImages = Array.from(panel.querySelectorAll('.col img'));+ lightboxIndex = lightboxImages.indexOf(img);+ showLightboxImage();+ document.getElementById('lightbox').classList.add('active');+ }++ function closeLightbox() {+ document.getElementById('lightbox').classList.remove('active');+ }++ document.addEventListener('keydown', function(e) {+ if (e.key === 'Escape') { closeLightbox(); return; }+ if (document.getElementById('lightbox').classList.contains('active')) {+ if (e.key === 'ArrowLeft') { lightboxIndex = (lightboxIndex - 1 + lightboxImages.length) % lightboxImages.length; showLightboxImage(); }+ if (e.key === 'ArrowRight') { lightboxIndex = (lightboxIndex + 1) % lightboxImages.length; showLightboxImage(); }+ return;+ }+ if (e.key === 'ArrowLeft') navigate(-1);+ if (e.key === 'ArrowRight') navigate(1);+ });++ show();+ </script>+ </body>+ </html>+ HTML+ end+enddiff --git a/spec/system/topic_list_spec.rb b/spec/system/topic_list_spec.rbindex b7b55348c4c..9f07af6ee38 100644--- a/spec/system/topic_list_spec.rb+++ b/spec/system/topic_list_spec.rb@@ -2,6 +2,7 @@describe "Topic list" dofab!(:topics) { Fabricate.times(10, :post).map(&:topic) }+ fab!(:admin)before_all dosidebar_url = Fabricate(:sidebar_url, name: "my topic link", value: "/t/#{topics[4].id}")@@ -87,7 +88,7 @@ describe "Topic list" doendit "refocusses properly when there are multiple pages of topics" do- extra_topics = Fabricate.times(25, :post).map(&:topic)+ Fabricate.times(25, :post).map(&:topic)oldest_topic = Fabricate(:post).topicoldest_topic.update(bumped_at: 1.day.ago)@@ -117,4 +118,40 @@ describe "Topic list" dowithin_window(new_window) { expect(topic).to have_topic_title(topics[5].title) }end++ it "shows a topic list" do+ sign_in(admin)++ users =+ 8.times.map do+ Fabricate(:user, username: Faker::Internet.username(specifier: 6..15, separators: %w[_ .]))+ end++ categories = 5.times.map { Fabricate(:category) }++ 25.times do+ views = rand(80..8_000)+ topic =+ Fabricate(+ :topic,+ title: Faker::Lorem.sentence(word_count: rand(3..12)).chomp("."),+ category: categories.sample,+ )+ Fabricate(:post, topic: topic)+ rand(2..5).times { Fabricate(:post, topic: topic, user: users.sample) }+ topic.feature_topic_users+ topic.update!(views: views, like_count: rand(views / 100..views / 4))+ end++ visit("/latest")+ expect(discovery.topic_list).to have_topics+ screenshot_marker(label: "topic-list")++ visit "/categories"+ screenshot_marker(label: "categories")++ find("#create-topic").click+ expect(page).to have_css("#reply-control.open")+ screenshot_marker(label: "composer-new-topic")+ endenddiff --git a/spec/system/topic_page_spec.rb b/spec/system/topic_page_spec.rbindex b4debea7e1c..741cf3516ba 100644--- a/spec/system/topic_page_spec.rb+++ b/spec/system/topic_page_spec.rb@@ -9,7 +9,7 @@ describe "Topic page" do<a name="toc-h2-testing" class="anchor" href="#toc-h2-testing" aria-label="Heading link">x</a>Testing</h2>- <p id="test-last-cooked-paragraph">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer tempor.</p>+ <p id="test-last-cooked-paragraph">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis volutpat risus. Nulla ac faucibus quam, quis cursus lorem. Sed rutrum eget nunc sed accumsan. Vestibulum feugiat mi vitae turpis tempor dignissim.</p>HTMLit "allows TOC anchor navigation" do@@ -96,6 +96,62 @@ describe "Topic page" doendend+ context "with rich content" do+ fab!(:user_1, :user)+ fab!(:user_2, :user)+ fab!(:topic2, :topic)++ before do+ Fabricate(:post, topic: topic2, user: user_1, cooked: <<~HTML)+ <h2>Key Takeaways</h2>+ <p>After reviewing this topic, here are the main points:</p>+ <ul>+ <li><strong>Performance matters</strong>: always benchmark first</li>+ <li><em>Readability</em>: code is read more often than written</li>+ <li>Testing: write tests before writing code</li>+ </ul>+ <p>Use <code>inline code</code> to clarify technical details.</p>+ <aside class="onebox githubpullrequest" data-onebox-src="https://github.com/discourse/discourse/pull/38698">+ <header class="source">+ <a href="https://github.com/discourse/discourse/pull/38698" target="_blank" rel="noopener">github.com</a>+ </header>+ <article class="onebox-body">+ <div class="github-row">+ <div class="github-icon-container" title="Pull Request">+ <svg width="60" height="60" class="github-icon" viewBox="0 0 14 16" aria-hidden="true"><path fill-rule="evenodd" d="M10.86 7c-.45-1.72-2-3-3.86-3-1.86 0-3.41 1.28-3.86 3H0v2h3.14c.45 1.72 2 3 3.86 3 1.86 0 3.41-1.28 3.86-3H14V7h-3.14zM7 10.2c-1.22 0-2.2-.98-2.2-2.2 0-1.22.98-2.2 2.2-2.2 1.22 0 2.2.98 2.2 2.2 0 1.22-.98 2.2-2.2 2.2z"></path></svg>+ </div>+ <div class="github-info-container">+ <h4><a href="https://github.com/discourse/discourse/pull/38698" target="_blank" rel="noopener">DEV: Add example pull request for onebox testing</a></h4>+ <div class="github-info">+ <div class="date">opened Jan 15, 2026</div>+ <div class="user">discourse</div>+ </div>+ </div>+ </div>+ </article>+ <div class="onebox-metadata"></div>+ <div style="clear: both"></div>+ </aside>+ <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean eget ex id diam pulvinar tempor ut id nisi. Nam non nisl tellus. Cras sodales eu diam scelerisque molestie. Curabitur neque ante, feugiat sit amet nisl vitae, accumsan convallis lacus. Nam nec velit dolor. Morbi vulputate erat lorem, et semper ex sodales id. In non iaculis dui. Morbi dolor est, pulvinar vel gravida ut, feugiat sed mi. Praesent tincidunt dictum turpis.</p>+ HTML++ Fabricate(:post_with_rich_content, topic: topic2, user: admin)+ end++ it "renders all content types and scrolls to the last post" do+ visit "/t/#{topic2.slug}/#{topic2.id}"++ expect(page).to have_css("h2", text: "Key Takeaways")+ expect(page).to have_css("blockquote")+ expect(page).to have_css(".emoji")++ screenshot_marker(label: "topic-rich-content")++ send_keys(:end)+ expect(find("#post_#{topic2.reload.highest_post_number}")).to be_visible+ end+ end+context "when triple clicking to select a paragraph" doit "select the last paragraph" dovisit "/t/#{topic.slug}/#{topic.id}/1"@@ -121,7 +177,7 @@ describe "Topic page" do# compare the selected text with the last paragraphexpect(select_content).to eq(- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer tempor.",+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc convallis volutpat risus. Nulla ac faucibus quam, quis cursus lorem. Sed rutrum eget nunc sed accumsan. Vestibulum feugiat mi vitae turpis tempor dignissim.",)endenddiff --git a/spec/system/user_api_key_show_spec.rb b/spec/system/user_api_key_show_spec.rbindex 24746da67be..798e3532a83 100644--- a/spec/system/user_api_key_show_spec.rb+++ b/spec/system/user_api_key_show_spec.rb@@ -14,6 +14,8 @@ RSpec.describe "User API Key Show Page" do# Visit the authorization page (no auth_redirect means show page after submit)visit "/user-api-key/new?#{URI.encode_www_form(scopes: "read", client_id: "x" * 32, application_name: "Test Application", public_key: public_key, nonce: SecureRandom.hex)}"+ screenshot_marker(label: "user-api-key-auth")+# Submit the authorization formclick_button I18n.t("user_api_key.authorize")diff --git a/spec/system/wizard_spec.rb b/spec/system/wizard_spec.rbindex 2c77670623e..d6fcd835177 100644--- a/spec/system/wizard_spec.rb+++ b/spec/system/wizard_spec.rb@@ -9,6 +9,8 @@ describe "Wizard" doit "successfully completes the setup wizard" dovisit("/wizard")+ screenshot_marker(label: "wizard")+expect(wizard_page).to be_on_step("setup")wizard_page.fill_field("text", "title", "My Test Site")wizard_page.select_dropdown_option("default-locale", "en")