diff --git a/.github/workflows/release-candidate.yml b/.github/workflows/release-candidate.yml
index 6dec9010..2fe01b93 100644
--- a/.github/workflows/release-candidate.yml
+++ b/.github/workflows/release-candidate.yml
@@ -58,24 +58,24 @@ jobs:
name: snapmaker-studio-installer
path: rc
- - name: Download the published v1.1.0 installer, verify its checksum
+ - name: Download the published v1.5.0 installer, verify its checksum
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
if ($env:GITHUB_ACTIONS -ne 'true' -or $env:RUNNER_ENVIRONMENT -ne 'github-hosted' -or [string]::IsNullOrWhiteSpace($env:ImageOS) -or $env:GITHUB_REPOSITORY -ne 'DVOpenLabs/snapmaker-studio' `
-or $env:ACT -or $env:WDAGUtilityAccount) { throw 'Disposable preflight failed.' }
- $url = "https://github.com/DVOpenLabs/snapmaker-studio/releases/download/v1.1.0/Snapmaker.Studio_1.1.0_x64-setup.exe"
- $dest = "old\Snapmaker.Studio_1.1.0_x64-setup.exe"
+ $url = "https://github.com/DVOpenLabs/snapmaker-studio/releases/download/v1.5.0/Snapmaker.Studio_1.5.0_x64-setup.exe"
+ $dest = "old\Snapmaker.Studio_1.5.0_x64-setup.exe"
New-Item -ItemType Directory -Force -Path old | Out-Null
Invoke-WebRequest -Uri $url -OutFile $dest
$hash = (Get-FileHash -Algorithm SHA256 $dest).Hash.ToLower()
- $expected = "b41931774eac5586bc31746599d4a637e89eda195c620067dc1c756281b217ee"
+ $expected = "d443f64f5167239f1422c719882cf245cff5d00d40c55fb67fc5a1e497b84e82"
if ($hash -ne $expected) {
- throw "Downloaded v1.1.0 installer hash $hash does not match the published $expected"
+ throw "Downloaded v1.5.0 installer hash $hash does not match the published $expected"
}
- Write-Host "v1.1.0 installer verified: $hash"
+ Write-Host "v1.5.0 installer verified: $hash"
- - name: Install v1.1.0 (default path), record its registration
+ - name: Install v1.5.0 (default path), record its registration
shell: pwsh
run: |
$ErrorActionPreference = "Stop"
@@ -90,14 +90,14 @@ jobs:
if ((Test-Path -LiteralPath $userKey) -or (Test-Path -LiteralPath $machine64Key) -or (Test-Path -LiteralPath $machine32Key) -or (Test-Path -LiteralPath $rememberedKey) -or (Test-Path `
-LiteralPath $manufacturerKey) -or (Test-Path -LiteralPath $defaultExe) -or (Get-Process -Name 'snapmaker-studio-desktop' -ErrorAction SilentlyContinue)) { throw `
'Initial exact production state is not clean.' }
- $old = (Resolve-Path "old\Snapmaker.Studio_1.1.0_x64-setup.exe").Path
+ $old = (Resolve-Path "old\Snapmaker.Studio_1.5.0_x64-setup.exe").Path
$p = Start-Process -FilePath $old -ArgumentList '/S', '/NCRC' -PassThru -Wait
- if ($p.ExitCode -ne 0) { throw "v1.1.0 silent install failed, exit $($p.ExitCode)" }
+ if ($p.ExitCode -ne 0) { throw "v1.5.0 silent install failed, exit $($p.ExitCode)" }
Start-Sleep -Seconds 2
$beforePath = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\Snapmaker Studio'
- if (-not (Test-Path -LiteralPath $beforePath)) { throw 'Exact v1.1.0 registration is absent' }
+ if (-not (Test-Path -LiteralPath $beforePath)) { throw 'Exact v1.5.0 registration is absent' }
$beforeProps = Get-ItemProperty -LiteralPath $beforePath
- if ($beforeProps.DisplayVersion -ne "1.1.0") { throw "v1.1.0 registration says DisplayVersion=$($beforeProps.DisplayVersion), expected 1.1.0" }
+ if ($beforeProps.DisplayVersion -ne "1.5.0") { throw "v1.5.0 registration says DisplayVersion=$($beforeProps.DisplayVersion), expected 1.5.0" }
# NSIS can write InstallLocation wrapped in literal quote
# characters (part of the string value itself, not just how it
# displays) — trim them unconditionally so every later
@@ -112,7 +112,7 @@ jobs:
if ($installLocation -ne (Join-Path $env:LOCALAPPDATA 'Snapmaker Studio')) { throw 'First install did not use the exact default path.' }
"owned_uninstaller=$ownedUninstaller" >> $env:GITHUB_ENV
"owned_uninstaller_sha256=$((Get-FileHash -LiteralPath $ownedUninstaller -Algorithm SHA256).Hash)" >> $env:GITHUB_ENV
- Write-Host "v1.1.0 installed at $installLocation, DisplayVersion 1.1.0"
+ Write-Host "v1.5.0 installed at $installLocation, DisplayVersion 1.5.0"
pwsh -NoProfile -File .github/scripts/ci-assert-registry.ps1 -Action Assert -InstallDir $installLocation -OutFile $env:RUNNER_TEMP\rc-before.json
if ($LASTEXITCODE -ne 0) { throw 'Registry assertion failed.' }
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16acd56d..e3c06642 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,37 @@ All notable changes to this project are documented here. The format is based on
## [Unreleased]
+## [1.5.1] - 2026-10-09
+
+**Clearer Prepare, easier spool choices, and controls that work from the keyboard and with a screen reader.**
+
+### Added
+- **Choose any spool from your inventory** (Project Materials). Each slot can open the provider's
+ whole spool list, searchable by vendor, material, colour or id, showing colour, vendor, material,
+ spool id, weight status and the status of the mapped Orca preset. When a spool is picked with no
+ Orca preset, the slot and the review say the project's existing filament preset will remain.
+- **Forget saved mapping.** A mapping Studio remembered for one spool, or for similar spools, can be
+ forgotten from the slot. The confirmation says what is forgotten and what is not changed (your
+ inventory, your Orca presets and the project).
+- **Why a setting changed.** The Prepare summary shows a short reason under each setting Studio
+ changed for the U1 and labels where the statement comes from: "Studio's check" or "Verify in
+ Snapmaker Orca". Lists Studio had to repair say exactly what was done.
+- **User guide links.** Help and Get Started link to the task-first user guide, which shows where
+ each statement comes from and which Studio version it was checked against. Its screenshots were
+ captured from v1.5.0 and have not been retaken.
+
+### Fixed
+- **A saved-mappings file Studio could not read is no longer treated as damaged.** If another
+ program briefly holds the file, Studio waits and retries; if it still cannot read it, it changes
+ nothing and asks you to try again.
+- **Printer-action confirmation is an accessible dialog.** Start, Cancel print and Emergency stop
+ now open a named, described dialog that starts on Cancel, is dismissed only by Escape or Cancel,
+ names the printer (and the file for Start), and is withdrawn if the printer changes or can no
+ longer take the action.
+- **Tool tabs work from the keyboard.** The Compatibility / Source Check and Print Quality / First
+ Layer tab rows respond to the arrow keys, Home and End, show a focus outline and wrap on narrow
+ windows. Moving along the row does not open or re-run a tool.
+
## [1.5.0] - 2026-10-06
**Project Materials: pick the real spool, and the real Snapmaker Orca preset, for each colour (#39).**
diff --git a/README.md b/README.md
index 9749c374..c5dffb28 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ changed. Snapmaker Orca still does the slicing.**
Free, open source, and local. No account, no cloud, nothing uploaded off your
local network. Your original file is never modified.
-### [▶ Watch it work — 66 seconds](https://github.com/DVOpenLabs/snapmaker-studio/blob/main/docs/media/snapmaker-studio-demo.mp4) · [⬇ Download for Windows or Linux](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.0) · [What it is, in 5 minutes](docs/innovation-fund/JUDGE_OVERVIEW.md)
+### [▶ Watch it work — 66 seconds](https://github.com/DVOpenLabs/snapmaker-studio/blob/main/docs/media/snapmaker-studio-demo.mp4) · [⬇ Download for Windows or Linux](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.1) · [What it is, in 5 minutes](docs/innovation-fund/JUDGE_OVERVIEW.md)
[](https://github.com/DVOpenLabs/snapmaker-studio/blob/main/docs/media/snapmaker-studio-demo.mp4)
@@ -71,30 +71,30 @@ recording, so it also shows what Studio says when it cannot reach one:
**Windows 10/11 (x64)** ✅ · **Linux x86_64 (.deb)** ✅ · **macOS** not supported.
-**[⬇ Download for Windows](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.0)**
+**[⬇ Download for Windows](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.1)**
— one click, no Python, runs offline.
-**[⬇ Download for Linux](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.0)**
+**[⬇ Download for Linux](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.1)**
— one `.deb`, no Python, no Node, no Rust. Install guide:
[docs/linux-install.md](docs/linux-install.md).
-**v1.5.0 is the current stable release** — not a prerelease, so this is also what
+**v1.5.1 is the current stable release** — not a prerelease, so this is also what
GitHub's [latest release](https://github.com/DVOpenLabs/snapmaker-studio/releases/latest)
points at. Every build ever published is on the
[Releases page](https://github.com/DVOpenLabs/snapmaker-studio/releases).
Verify it before you run it:
-- Release: [v1.5.0](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.0)
-- Windows installer: `Snapmaker.Studio_1.5.0_x64-setup.exe`
- — 21,944,474 bytes — SHA256: `d443f64f5167239f1422c719882cf245cff5d00d40c55fb67fc5a1e497b84e82`
-- Linux package: `snapmaker-studio_1.5.0_amd64_5245cf9f9664.deb`
- — 25,944,098 bytes — SHA256: `7fca28d9d4e2558f8a6bdc765b121e2290c54abd39e2a1b9b2efaeea6d923e5a`
+- Release: [v1.5.1](https://github.com/DVOpenLabs/snapmaker-studio/releases/tag/v1.5.1)
+- Windows installer: `Snapmaker.Studio_1.5.1_x64-setup.exe`
+ — 21,962,736 bytes — SHA256: `8955097365b12e9eb1405a098c1f6ab345d56d397681a67f0cb08257d1471be3`
+- Linux package: `snapmaker-studio_1.5.1_amd64_abf20bf0f74d.deb`
+ — 25,954,272 bytes — SHA256: `c5766900437fa9826eefdb970c0ed21894b4f5f4b4795518993677ca6eeed08b`
```powershell
-Get-FileHash -Algorithm SHA256 .\Snapmaker.Studio_1.5.0_x64-setup.exe
+Get-FileHash -Algorithm SHA256 .\Snapmaker.Studio_1.5.1_x64-setup.exe
```
```bash
-sha256sum snapmaker-studio_1.5.0_amd64_5245cf9f9664.deb
+sha256sum snapmaker-studio_1.5.1_amd64_abf20bf0f74d.deb
```
Neither installer is code-signed yet, so Windows SmartScreen will show "Unknown
@@ -127,11 +127,11 @@ sliced job back**.
| The problem, named exactly | The fix, in a new copy — and where Studio says it can't tell |
|---|---|
-|  |  |
+|  |  |
| **Painted colour, read before slicing** | **What to load — and where Studio says it cannot tell** |
-|  |  |
+|  |  |
-From the v1.5.0 build's own installed-application run: the problem and prepared views on the sample project in [`examples/demo_u1_showcase.3mf`](examples/demo_u1_showcase.3mf); the painted view on the acceptance harness's dedicated multi-colour fixture; the what-to-load view on a sliced-job fixture the harness supplies to exercise that screen. Reproduce them with [docs/innovation-fund/JUDGE_WALKTHROUGH.md](docs/innovation-fund/JUDGE_WALKTHROUGH.md). Submission package: [docs/innovation-fund/FINAL_SUBMISSION.md](docs/innovation-fund/FINAL_SUBMISSION.md).
+From the v1.5.1 build's own installed-application run: the problem and prepared views on the sample project in [`examples/demo_u1_showcase.3mf`](examples/demo_u1_showcase.3mf); the painted view on the acceptance harness's dedicated multi-colour fixture; the what-to-load view on a sliced-job fixture the harness supplies to exercise that screen. Reproduce them with [docs/innovation-fund/JUDGE_WALKTHROUGH.md](docs/innovation-fund/JUDGE_WALKTHROUGH.md). Submission package: [docs/innovation-fund/FINAL_SUBMISSION.md](docs/innovation-fund/FINAL_SUBMISSION.md).
## Why this isn't a slicer, a dashboard, or a converter
@@ -165,7 +165,7 @@ its licence in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
## Evidence
-Everything below was run against the v1.5.0 release-candidate build — the
+Everything below was run against the v1.5.1 release-candidate build — the
same application and Linux package published on the release page, checked by
SHA256 — not against a development build. The Windows installed-application
run used an acceptance copy of the release-candidate installer (same application
@@ -179,24 +179,26 @@ counts come from the source at the release commit, not from the installer. Comma
| What | Result |
|---|---|
-| Installed-application acceptance, driven through the real UI | **45/45** |
-| Read-only checks against a real Snapmaker U1, from the Windows-installed app | **58/58** |
+| Installed-application acceptance, driven through the real UI | **50/50** |
+| Read-only checks against a real Snapmaker U1, from the Windows-installed app, with Spoolman and Bambuddy | **76/76** |
| Linux clean-image validation, Ubuntu 22.04 + 24.04 | **49/49** each |
| Regression tests against genuine OrcaSlicer / BambuStudio / PrusaSlicer projects | **36 tests** |
| End-to-end pipeline self-check (`u1convert selfcheck`) | **27/27** |
-| Backend / desktop / TypeScript / Rust | 2804 · 725 · clean · clean |
+| Backend / desktop / TypeScript / Rust | 2927 · 852 · clean · clean |
-The installed-application acceptance count (45/45) is a different total from
-v1.2.0's: this release adds two checks for the SpoolEase provider and
-three checks that the test lane itself leaves nothing behind, and drops one
-older bookkeeping check — see [docs/TRUST_STATUS.md](docs/TRUST_STATUS.md).
+The installed-application acceptance count (50/50) is a different total from
+the previous release's: this run is the upgrade variant, started from the previous
+release's installer, and adds five checks that the previous version installs, leaves its state
+to migrate, and that the upgrade keeps your data and registers the new version — see
+[docs/TRUST_STATUS.md](docs/TRUST_STATUS.md).
The real-U1 verification for this release ran read-only through the
-Windows-installed application itself, 58/58, with no printer-control action
-called. The Spoolman/Bambuddy-seeded provider-on-hardware checks were not run
-this release, no real SpoolEase device has been tested yet, this printer's four
-toolheads all carry the same 0.4 mm nozzle, and the Linux-installed app was not
-run against the real printer. Full detail:
+Windows-installed application itself, 76/76, with no printer-control action
+called. Both Spoolman (0.27.0) and Bambuddy (1.2.5.7) took part, as disposable
+local containers seeded with anonymous spools, and the provider-on-hardware checks
+for each ran and none were skipped. No real SpoolEase device has been tested yet,
+this printer's four toolheads all carry the same 0.4 mm nozzle, and the
+Linux-installed app was not run against the real printer. Full detail:
[docs/TRUST_STATUS.md](docs/TRUST_STATUS.md).
Reproduce any of it yourself:
@@ -208,6 +210,25 @@ files produced structurally valid U1 profile copies ([PROOF.md](PROOF.md)); that
number measures structure, not print success, and the checks above are the
stronger evidence.
+## What's new in v1.5.1
+
+**Clearer Prepare, easier spool choices, and controls that work from the keyboard and with a screen reader.**
+
+- **Choose any spool from your inventory.** Each slot can open your provider's whole spool list,
+ searchable by vendor, material, colour or id. If you pick a spool but no Orca preset, the slot and
+ the review say the project's existing filament preset will remain.
+- **Forget a saved mapping.** A remembered spool-to-preset mapping now has a **Forget saved mapping**
+ button; the confirmation says what is forgotten and what is not changed.
+- **A saved-mappings file that is briefly locked is no longer treated as damaged.** Studio retries,
+ and if it still cannot read the file it changes nothing and asks you to try again.
+- **Prepare says why a setting changed**, and whether the statement is Studio's own check or advice to
+ verify in Snapmaker Orca.
+- **Accessible printer-action confirmation and tool tabs.** The Start, Cancel print and Emergency stop
+ confirmation is a proper dialog that starts on Cancel; the tool tab rows work with the arrow keys,
+ Home and End.
+- **User guide links** from Help and Get Started. The guide's screenshots were captured from v1.5.0
+ and have not been retaken.
+
## What's new in v1.5.0
**Project Materials: the real spool and the real Snapmaker Orca preset, for each colour.**
@@ -225,13 +246,6 @@ Presets you made yourself can be found and mapped, but are shown as **"Confirmed
**"Manual check in Orca required"**: in testing Snapmaker Orca kept the project's own values for such
a preset, so Studio does not say Orca will apply them. Check the filament in Orca before slicing.
-| Suggested spools, nothing selected | Review before Prepare | Orca's presets and yours, told apart |
-|---|---|---|
-|  |  |  |
-
-From the v1.5.0 release-candidate build's own installed-application run, against anonymised
-disposable spools and presets.
-
## What's new in v1.4.1
**A readable spool picker.** Settings → Materials provider now has a Studio list in place of the
diff --git a/backend/pyproject.toml b/backend/pyproject.toml
index 304a6bcc..853f2eed 100644
--- a/backend/pyproject.toml
+++ b/backend/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "snapmaker-studio"
-version = "1.5.0"
+version = "1.5.1"
description = "Snapmaker Studio engine — a local-first workflow platform for modern 3D printing: understand, validate, and prepare designs print-ready (Bambu/Orca/STL today; Snapmaker U1 as the first printer target)."
readme = "README.md"
requires-python = ">=3.13"
diff --git a/backend/snapstudio_core/convert.py b/backend/snapstudio_core/convert.py
index f0545a02..0b40194a 100644
--- a/backend/snapstudio_core/convert.py
+++ b/backend/snapstudio_core/convert.py
@@ -94,12 +94,12 @@ def _starter_summary(*, geometry_only: bool) -> dict:
}
-def _action_reasons(report: dict) -> tuple[dict[str, str], set[str], set[str], dict[str, str]]:
+def _action_reasons(report: dict) -> tuple[dict[str, dict], set[str], set[str]]:
"""Consume RepairOutcome detail while the independent diff remains authoritative.
- The last item is the plain-language explanation some pipeline steps write next to their reason."""
- reasons: dict[str, str] = {}
- explanations: dict[str, str] = {}
+ Each key has one atomic record. A later record replaces or clears all four
+ provenance fields together, so an explanation can never retain old source data."""
+ records: dict[str, dict] = {}
cleared: set[str] = set()
mapped: set[str] = set()
groups = [report.get("normalizations", []), report.get("profile_changes", []),
@@ -119,19 +119,26 @@ def _action_reasons(report: dict) -> tuple[dict[str, str], set[str], set[str], d
for item in group:
if not isinstance(item, dict) or "key" not in item:
continue
+ key = item["key"]
reason = item.get("reason")
if isinstance(reason, str) and reason:
- reasons[item["key"]] = reason
- explanations.pop(item["key"], None) # an explanation belongs to the reason it came with
- explanation = item.get("explanation")
- if isinstance(explanation, str) and explanation:
- explanations[item["key"]] = explanation
+ # reason always; the other three only when this step supplied them, so a
+ # later record never inherits an earlier explanation, source or kind.
+ records[key] = {"reason": reason, **{field: item[field] for field in ("explanation", "source", "kind")
+ if isinstance(item.get(field), str) and item[field]}}
+ elif reason == "":
+ # An explicit empty reason clears the complete atomic record.
+ records.pop(key, None)
+ else:
+ # A later report item without a reason is not a clear marker.
+ # Preserve the prior complete record.
+ pass
if item.get("category") == "mapped":
mapped.add(item["key"])
for item in report.get("foreign_cleared", []):
if isinstance(item, dict):
cleared.add(item["key"])
- return reasons, cleared, mapped, explanations
+ return records, cleared, mapped
def _strict_value_equal(a, b) -> bool:
@@ -174,7 +181,7 @@ def _settings_summary(before: dict, after: dict, raw_config: bytes, outcome,
recommended_after: dict | None = None) -> dict:
profile = load_profile(profile_name)
diffs = config_diff(before, after) # independent source of truth (A13)
- reasons, cleared, mapped_keys, explanations = _action_reasons(outcome.report)
+ records, cleared, mapped_keys = _action_reasons(outcome.report)
allowlist = machine_compat_keys(profile)
slice_info = {
item["key"]: item["reason"]
@@ -189,19 +196,16 @@ def _settings_summary(before: dict, after: dict, raw_config: bytes, outcome,
if key in cleared:
# Values in this category were deliberately discarded. They may
# be credentials or arbitrary creator G-code, so never echo them.
- could_not_carry.append({"key": key, "reason": reasons[key]})
+ could_not_carry.append({"key": key, "reason": records[key]["reason"]})
elif key in mapped_keys and _is_preserved_value_mapping(item["old"], item["new"]):
mapped_to_u1.append({
"key": key, "old": display_value(item["old"], key=key),
"new": display_value(item["new"], key=key),
"reason": "carried over to U1 toolheads (values preserved)",
})
- elif key in reasons:
+ elif key in records:
entry = {"key": key, "old": display_value(item["old"], key=key),
- "new": display_value(item["new"], key=key),
- "reason": reasons[key]}
- if key in explanations:
- entry["explanation"] = explanations[key]
+ "new": display_value(item["new"], key=key), **records[key]}
compat.append(entry)
elif key in allowlist:
compat.append({"key": key, "old": display_value(item["old"], key=key),
diff --git a/backend/snapstudio_core/orca_import.py b/backend/snapstudio_core/orca_import.py
index 95250f80..e7c40bc1 100644
--- a/backend/snapstudio_core/orca_import.py
+++ b/backend/snapstudio_core/orca_import.py
@@ -69,9 +69,11 @@ def _num(cfg: dict, key: str):
return None
-def _change(changes: list, key: str, old, new, reason: str, why: str) -> None:
+def _change(changes: list, key: str, old, new, reason: str, why: str,
+ *, kind: str = "engine", source: str = "Studio's import rule for this setting") -> None:
changes.append({"key": key, "old": old, "new": new, "reason": reason,
- "explanation": why, "category": "orca-compatibility"})
+ "explanation": why, "source": source,
+ "kind": kind, "category": "orca-compatibility"})
# --- individual rules -------------------------------------------------------
@@ -89,9 +91,7 @@ def _enable_exclude_object(cfg: dict, changes: list) -> None:
cfg["exclude_object"] = "1"
_change(changes, "exclude_object", old, "1",
"enabled so the U1 can skip a failed object and probe adaptively",
- "With Exclude Object off, the U1 cannot cancel one failed object "
- "without losing the whole plate, and adaptive bed mesh has no object "
- "outlines to work from.")
+ "Studio's import rule turns Exclude Object on for every U1 copy; the original had it off.")
def _fix_auto_brim(cfg: dict, changes: list) -> None:
@@ -107,10 +107,9 @@ def _fix_auto_brim(cfg: dict, changes: list) -> None:
if brim == "auto_brim":
cfg["brim_type"] = "no_brim"
_change(changes, "brim_type", brim, "no_brim",
- "the creator left the brim on automatic, and Snapmaker Orca decides "
- "differently from the slicer this was made in",
- "Automatic means the slicer chooses. Snapmaker Orca's choice can add "
- "a brim this project never had. A brim you asked for yourself is kept.")
+ "Studio replaced an automatic brim choice with no brim for this U1 copy",
+ "Studio replaced the automatic brim choice with no brim. A brim you chose yourself is kept.",
+ kind="orca")
def _fix_tree_support_with_adaptive_layers(cfg: dict, changes: list) -> None:
@@ -128,11 +127,8 @@ def _fix_tree_support_with_adaptive_layers(cfg: dict, changes: list) -> None:
if style in ("organic", "tree_slim", "tree_strong"):
cfg["support_style"] = "tree_hybrid"
_change(changes, "support_style", style, "tree_hybrid",
- "tree support with variable layer height needs the hybrid style on the U1",
- "This project uses variable layer height with tree supports. The "
- "slicer it was made in silently switches that combination to hybrid "
- "when it opens the file; Snapmaker Orca does not, so Studio applies "
- "the same correction.")
+ "Studio replaced the tree support style with the hybrid style for this U1 copy",
+ "Studio replaced the tree support style with the hybrid style for this U1 copy.", kind="orca")
def _fix_filament_array_validity(cfg: dict, changes: list, count: int) -> None:
@@ -154,14 +150,38 @@ def pad_from_self(key: str, why: str, reason: str) -> None:
filled = [v for v in value if str(v).strip() != ""]
if not filled:
return
+ # Only entries that survive truncation can have been filled, trimmed or converted;
+ # dropped entries are reported once, as a resize.
+ retained = value[:count]
+ had_empty = any(str(v).strip() == "" for v in retained)
+ trimmed = any(isinstance(v, str) and v.strip() != v for v in retained)
new = [(str(v).strip() or str(filled[-1])) for v in value]
if len(new) < count:
new = new + [new[-1]] * (count - len(new))
elif len(new) > count:
new = new[:count]
if new != value:
+ resized = len(new) != len(value)
+ converted = any(not isinstance(v, str) for v in retained)
+ parts = []
+ if had_empty:
+ parts.append("Studio filled an empty entry with the last non-empty value in this list.")
+ if resized:
+ parts.append("Studio resized this list to cover every filament slot.")
+ if trimmed:
+ parts.append("Studio trimmed whitespace around a string value.")
+ if converted:
+ parts.append("Studio wrote each value in this list as text.")
+ actual_why = " ".join(parts)
+ actual_reason = "; ".join(filter(None, [
+ "filled an empty entry with the last non-empty value" if had_empty else "",
+ "resized the list" if resized else "",
+ "trimmed whitespace from a string" if trimmed else "",
+ "wrote each value in the list as text" if converted else "",
+ ]))
cfg[key] = new
- _change(changes, key, value, new, reason, why)
+ _change(changes, key, value, new, actual_reason, actual_why,
+ kind="engine", source="Studio's import rule for this setting")
pad_from_self(
"filament_adaptive_volumetric_speed",
@@ -184,18 +204,15 @@ def pad_from_self(key: str, why: str, reason: str) -> None:
cfg["filament_self_index"] = expected
_change(changes, "filament_self_index", self_index, expected,
"renumbered so every filament slot identifies itself correctly",
- "Each filament slot has to carry its own position. When the "
- "numbering is missing or out of step the slicer reports an "
- "invalid project configuration.")
+ "Studio renumbered each filament slot so the list matches its position.")
# The raft expansion has two owners: the U1 clamp table (data/u1_rules.json), which runs in every mode and fixes -1, and
# the rule below, which runs in Preserve/U1/Optimize and fixes any negative value. They must agree on the value (the clamp's
# "good" is the U1 template default, checked by a test) and say the same thing about why, so the reason shown to the person
# does not depend on which of them acted.
-RAFT_EXPANSION_REASON = "restored to the U1 default (a negative value is out of range)"
-RAFT_EXPANSION_WHY = ("Snapmaker Orca and OrcaSlicer both reject a negative raft expansion "
- "and warn when the project is opened.")
+RAFT_EXPANSION_REASON = "replaced a negative raft expansion with the U1 base-profile value"
+RAFT_EXPANSION_WHY = "A negative raft expansion was replaced with the value from Studio's U1 base profile."
def _fix_negative_raft_expansion(cfg: dict, changes: list) -> None:
@@ -212,7 +229,8 @@ def _fix_negative_raft_expansion(cfg: dict, changes: list) -> None:
old = cfg.get("raft_first_layer_expansion")
cfg["raft_first_layer_expansion"] = default
_change(changes, "raft_first_layer_expansion", old, default,
- RAFT_EXPANSION_REASON, RAFT_EXPANSION_WHY)
+ RAFT_EXPANSION_REASON, RAFT_EXPANSION_WHY, kind="orca",
+ source="Studio's import rule for this setting")
# --- entry points -----------------------------------------------------------
diff --git a/backend/snapstudio_core/repair.py b/backend/snapstudio_core/repair.py
index bd117ce9..978f5c24 100644
--- a/backend/snapstudio_core/repair.py
+++ b/backend/snapstudio_core/repair.py
@@ -2,7 +2,7 @@
import copy
from .container import ThreeMF
from .config_io import load_project_settings, dump_project_settings
-from .rules import load_rules, apply_clamps, clamp_explanation
+from .rules import load_rules, apply_clamps
from .profile import load_profile, apply_swap
from .filaments import apply_remap, filament_count, conform_filament_arrays
from .preserve import machine_compat_keys, prepare_preserved_values
@@ -39,7 +39,8 @@ def repair(tm: ThreeMF, mode: str = "u1", remap: dict | None = None,
change["reason"] = (
orca_import.RAFT_EXPANSION_REASON if change["key"] == "raft_first_layer_expansion"
else f"U1 compatibility clamp: {change['old']} → {change['new']}")
- change["explanation"] = clamp_explanation(change)
+ # Explanation and provenance are one record. apply_clamps creates the
+ # complete evidence pair before this step adds the action reason.
# U1 supports >4 filament colours (verified: real U1 files carry 8 colours
# with 4 toolheads). Never auto-cap; preserve all filament arrays in every
diff --git a/backend/snapstudio_core/rules.py b/backend/snapstudio_core/rules.py
index d367d10a..bb8f3112 100644
--- a/backend/snapstudio_core/rules.py
+++ b/backend/snapstudio_core/rules.py
@@ -10,7 +10,13 @@ def apply_clamps(cfg: dict, rules: dict) -> list[dict]:
for c in rules["clamps"]:
k = c["key"]
if k in cfg and str(cfg[k]) == c["bad"]:
- findings.append({"key": k, "old": cfg[k], "new": c["good"]})
+ change = {"key": k, "old": cfg[k], "new": c["good"],
+ "explanation": clamp_explanation({"key": k, "old": cfg[k], "new": c["good"]}),
+ "source": ("Studio's import rule for this setting" if k == "raft_first_layer_expansion"
+ else "the Compatibility check's valid range"),
+ # the raft explanation ends with advice to check the raft in Snapmaker Orca
+ "kind": "orca" if k == "raft_first_layer_expansion" else "engine"}
+ findings.append(change)
cfg[k] = c["good"]
return findings
diff --git a/backend/tests/test_guide_claims.py b/backend/tests/test_guide_claims.py
index 8eb04f5b..f0494c0b 100644
--- a/backend/tests/test_guide_claims.py
+++ b/backend/tests/test_guide_claims.py
@@ -9,14 +9,23 @@
the engine really produces, the original stays byte-identical, and the guide's
printer-name explanation matches the confidence the engine actually assigns.
What they cannot establish: that the prose around those facts is well explained,
-or anything about a physical printer or Snapmaker Orca.
+that a source is the right source, honest review dates, paraphrased overclaims,
+screen-reader behavior, or anything about a physical printer or Snapmaker Orca.
"""
import hashlib
+import importlib
+import importlib.util
import json
+import os
import re
import shutil
+import subprocess
+import sys
+import tempfile
from pathlib import Path
+import pytest
+
from snapstudio_core import plate_placement as pp
from snapstudio_core import post_slice
@@ -48,6 +57,57 @@ def _sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
+ENGINE_FACTS = {
+ "setting-why": ("engine-reason", "backend:rules.apply_clamps"),
+ "size-or-placement": ("placement-move", "backend:plate_placement.EDGE_MARGIN_MM"),
+ "unknown-compatible": ("unknown-gap", "backend:post_slice._machine_match"),
+ "sliced-for-u1": ("sliced-header", "backend:post_slice._machine_match"),
+ "original-unchanged": ("copy-only", "test:backend/tests/test_guide_claims.py::test_original_unchanged_answer_uses_real_convert_path"),
+ "print-success": ("readiness-estimate", "backend:success_predict.predict"),
+}
+
+
+def check_answers(manifest, pages, tmp_path):
+ """Check code-derived tokens and ownership; this cannot judge prose clarity, source fitness, dates, paraphrased overclaims, physical behavior, Orca behavior, or screen readers."""
+ from snapstudio_core import success_predict
+ from snapstudio_core.convert import convert_to_u1
+ from snapstudio_core.rules import apply_clamps, load_rules
+ by_id = {answer["id"]: answer for answer in manifest["answers"]}
+ table = {
+ "setting-why": lambda: ("engine-reason", "backend:rules.apply_clamps", {"valid range", "U1 default"}),
+ "size-or-placement": lambda: ("placement-move", "backend:plate_placement.EDGE_MARGIN_MM", {"one move cannot fix the layout", "multi-plate"}),
+ "unknown-compatible": lambda: ("unknown-gap", "backend:post_slice._machine_match", {"does not guess", "no printer is connected"}),
+ "sliced-for-u1": lambda: ("sliced-header", "backend:post_slice._machine_match", {"Studio reads the header", "not simulated"}),
+ "original-unchanged": lambda: ("copy-only", "test:backend/tests/test_guide_claims.py::test_original_unchanged_answer_uses_real_convert_path", {"SnapmakerU1", "original file is not modified"}),
+ "print-success": lambda: ("readiness-estimate", "backend:success_predict.predict", {"takes points off for each risk signal", "not a probability of print success", "at least 75"}),
+ }
+ assert set(table) == set(ENGINE_FACTS)
+ assert set(ENGINE_FACTS) | {"kept-orca"} == set(by_id)
+ asserted = set()
+ for answer_id, (expected_id, expected_derive, expected_tokens) in ((a, table[a]()) for a in table):
+ answer = by_id[answer_id]
+ assert len(answer["requiredFacts"]) == 1
+ fact = answer["requiredFacts"][0]
+ assert (fact["id"], fact["derive"]) == (expected_id, expected_derive)
+ assert set(fact["tokens"]) == expected_tokens
+ assert all(token in json.dumps(pages) for token in expected_tokens)
+ asserted.add(fact["id"])
+ # Exercise real behavior for the facts whose tokens summarize it.
+ clamp = apply_clamps({"prime_tower_brim_width": "-1"}, load_rules())
+ assert "valid range" in clamp[0]["explanation"] and "U1 default" in clamp[0]["explanation"]
+ assert clamp[0]["kind"] == "engine"
+ assert post_slice._machine_match({"printer_model": "Snapmaker U1"}, {})["confidence"] == post_slice.CONFIRMED
+ assert post_slice._machine_match({"printer_model": "not a known printer"}, {})["confidence"] == post_slice.LIKELY
+ assert success_predict.predict(readiness={"ready": True})["likelihood"] == 100
+ src = tmp_path / "answer-source.3mf"
+ shutil.copy(ROOT / "examples" / "demo_offplate_foreign.3mf", src)
+ before = _sha(src)
+ out = convert_to_u1(str(src), out_dir=str(tmp_path), dry_run=False)
+ assert out.output_name.endswith("_SnapmakerU1.3mf") and _sha(src) == before
+ assert asserted == {fact["id"] for answer in manifest["answers"] for fact in answer["requiredFacts"] if fact["derive"].startswith(("backend:", "test:"))}
+ return True
+
+
def test_placement_example_matches_the_engine(tmp_path):
src = tmp_path / "demo_offplate_foreign.3mf"
shutil.copy(ROOT / "examples" / "demo_offplate_foreign.3mf", src)
@@ -98,3 +158,210 @@ def test_printer_name_confidence_matches_the_guide():
def test_matching_header_is_confirmed_and_looks_right():
ok = post_slice._machine_match({"printer_model": "Snapmaker U1"}, {})
assert ok["result"] == "ok" and ok["confidence"] == post_slice.CONFIRMED
+
+
+def test_original_unchanged_answer_uses_real_convert_path(tmp_path):
+ """The conversion path preserves the input; this does not establish prose clarity, source choice, dates, physical behavior, paraphrased overclaims, or screen-reader behavior."""
+ from snapstudio_core.convert import convert_to_u1
+ src = tmp_path / "source.3mf"
+ shutil.copy(ROOT / "examples" / "demo_offplate_foreign.3mf", src)
+ before = _sha(src)
+ result = convert_to_u1(str(src), out_dir=str(tmp_path), dry_run=False)
+ assert result.output_name.endswith("_SnapmakerU1.3mf")
+ assert (tmp_path / result.output_name).exists()
+ assert _sha(src) == before
+
+
+def _resolve_engine_derive(derive, package="snapstudio_core"):
+ """Resolve a backend: or test: derive for real. Raises AttributeError or returns None when it does not resolve."""
+ if derive.startswith("backend:"):
+ module_name, symbol = derive[8:].rsplit(".", 1)
+ return getattr(importlib.import_module(f"{package}.{module_name}"), symbol)
+ if derive.startswith("test:"):
+ file_name, test_name = derive[5:].split("::", 1)
+ path = (ROOT / file_name) if not Path(file_name).is_absolute() else Path(file_name)
+ if not path.is_file():
+ return None
+ if path.resolve() == Path(__file__).resolve():
+ module = sys.modules[__name__] # this module is already loaded; never execute it twice
+ else:
+ module_name = "_derive_" + hashlib.sha1(str(path.resolve()).encode()).hexdigest()[:12]
+ spec = importlib.util.spec_from_file_location(module_name, path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ member = getattr(module, test_name, None)
+ return member if callable(member) else None
+
+
+def test_every_manifest_derive_resolves_to_code():
+ """Resolution is mechanical; it cannot establish prose clarity, source fitness, honest dates, physical printer or Snapmaker Orca behavior, paraphrased overclaims, or screen-reader behavior. App derives are resolved in guideClaims.test.ts."""
+ seen = 0
+ for answer in _guide("answers")["answers"]:
+ for fact in answer["requiredFacts"]:
+ if fact["derive"].startswith(("backend:", "test:")):
+ assert _resolve_engine_derive(fact["derive"]) is not None, fact["derive"]
+ seen += 1
+ else:
+ assert fact["derive"].startswith("app:"), fact["derive"]
+ assert seen >= 5
+
+
+def test_engine_derive_resolution_rejects_near_misses(tmp_path, monkeypatch):
+ """Real getattr resolution: a name that only appears in a comment, a comparison or a docstring is not a symbol."""
+ package = tmp_path / "fixturepkg"
+ package.mkdir()
+ (package / "__init__.py").write_text("", encoding="utf-8")
+ (package / "mod.py").write_text(
+ '"""Module docstring mentions docstring_only."""\n'
+ "# comment_only is described here\n"
+ "REAL = 1\n"
+ "def real_fn():\n"
+ ' """real_fn mentions inner_docstring."""\n'
+ " return REAL == 1\n"
+ "async def real_async():\n"
+ " return 1\n"
+ "value = REAL\n"
+ "check = (missing_eq == 1) if False else None\n",
+ encoding="utf-8",
+ )
+ monkeypatch.syspath_prepend(str(tmp_path))
+ assert _resolve_engine_derive("backend:mod.REAL", package="fixturepkg") == 1
+ assert _resolve_engine_derive("backend:mod.real_async", package="fixturepkg")
+ for name in ["REA", "real_f", "comment_only", "docstring_only", "inner_docstring", "missing_eq", "real_fn_"]:
+ with pytest.raises(AttributeError):
+ _resolve_engine_derive(f"backend:mod.{name}", package="fixturepkg")
+
+
+def test_test_derive_resolution_imports_the_real_function(tmp_path):
+ """A test: derive resolves by importing the file and calling getattr, so text that only looks like a definition fails."""
+ ref = "test:backend/tests/test_guide_claims.py::"
+ assert callable(_resolve_engine_derive(ref + "test_original_unchanged_answer_uses_real_convert_path"))
+ assert _resolve_engine_derive(ref + "test_original_unchanged_answer_uses_real_convert_pat") is None
+ assert _resolve_engine_derive("test:backend/tests/no_such_file.py::test_x") is None
+ fixture = tmp_path / "fixture_tests.py"
+ fixture.write_text(
+ '"""def spoofed_in_docstring(): pass"""\n'
+ "TEXT = \"\"\"\ndef spoofed_test():\n pass\n\"\"\"\n"
+ "ESCAPED = \"\\\"\\\"\\\" def spoofed_escaped(): pass\"\n"
+ "# def spoofed_comment(): pass\n"
+ "NOT_CALLABLE = 5\n"
+ "def test_real():\n return 1\n",
+ encoding="utf-8",
+ )
+ ref = f"test:{fixture}::"
+ assert _resolve_engine_derive(ref + "test_real")() == 1
+ for name in ["spoofed_test", "spoofed_in_docstring", "spoofed_escaped", "spoofed_comment", "test_rea", "NOT_CALLABLE", "TEXT"]:
+ assert _resolve_engine_derive(ref + name) is None, name
+
+
+def test_golden_answer_engine_assertion_table_has_exact_manifest_coverage(tmp_path):
+ """The table checks code facts only; it cannot establish prose clarity, source fitness, honest dates, physical printer or Snapmaker Orca behavior, paraphrased overclaims, or screen readers."""
+ assert check_answers(_guide("answers"), {name: _guide(name) for name in ("path", "tasks", "problems")}, tmp_path)
+
+
+def test_print_readiness_is_a_risk_signal_score_not_a_measured_chance():
+ """The formula check cannot establish that the score predicts physical printer behavior, prose clarity, source fitness, honest dates, paraphrased overclaims, or screen-reader behavior."""
+ from snapstudio_core import success_predict
+ baseline = success_predict.predict(readiness={"ready": True})
+ one_warning = success_predict.predict(readiness={"ready": False, "warnings": ["one"]})
+ two_warnings = success_predict.predict(readiness={"ready": False, "warnings": ["one", "two"]})
+ assert baseline["likelihood"] == 100
+ assert one_warning["likelihood"] == 100 - (20 + 5 * 1) == 75
+ assert two_warnings["likelihood"] == 100 - (20 + 5 * 2) == 70
+ assert one_warning["band"] == "likely" and two_warnings["band"] == "uncertain"
+ assert success_predict.predict(readiness={"ready": False, "warnings": []})["band"] == "likely"
+ assert success_predict._band(75) == "likely" and success_predict._band(74) == "uncertain"
+ assert "Likely to print" in success_predict._verdict(80, "likely")
+
+
+def _run_guide_build(content, output):
+ env = os.environ.copy()
+ env["SNAPSTUDIO_GUIDE_CONTENT"] = str(content)
+ env["SNAPSTUDIO_GUIDE_OUTPUT"] = str(output)
+ return subprocess.run(["node", "tools/build.mjs"], cwd=ROOT / "site" / "guide", env=env, capture_output=True, text=True)
+
+
+def test_build_rejects_invalid_answers_and_source_refs():
+ """These negative cases test the validator; they cannot establish prose clarity, source fitness, honest dates, physical behavior, paraphrased overclaims, or screen readers."""
+ with tempfile.TemporaryDirectory() as raw:
+ content = Path(raw) / "content"
+ shutil.copytree(GUIDE, content)
+ output = Path(raw) / "index.html"
+ answers_path = content / "answers.json"
+ original = json.loads(answers_path.read_text(encoding="utf-8"))
+ cases = []
+ bad = json.loads(json.dumps(original)); bad["answers"][0]["requiredFacts"] = []; cases.append(bad)
+ bad = json.loads(json.dumps(original)); bad["answers"][0]["unknown"] = True; cases.append(bad)
+ bad = json.loads(json.dumps(original)); bad["answers"][1]["requiredFacts"][0]["id"] = bad["answers"][0]["requiredFacts"][0]["id"]; cases.append(bad)
+ for bad in cases:
+ answers_path.write_text(json.dumps(bad), encoding="utf-8")
+ assert _run_guide_build(content, output).returncode != 0
+ # the build checks shape and file existence only; symbol resolution is tested separately above
+ for derive in ["bogus:thing", "backend:no_such_module.symbol", "backend:rules.not-an-identifier", "backend:rules", "app:desktop/src/lib/no_such_file.ts#X", "app:desktop/src/lib/fidelity.ts", "app:desktop/src/lib/fidelity.ts#not-an-id", "test:backend/tests/no_such_file.py::test_x", "test:backend/tests/test_guide_claims.py::"]:
+ bad = json.loads(json.dumps(original)); bad["answers"][0]["requiredFacts"][0]["derive"] = derive
+ answers_path.write_text(json.dumps(bad), encoding="utf-8")
+ assert _run_guide_build(content, output).returncode != 0
+ path_path = content / "path.json"
+ path_data = json.loads(path_path.read_text(encoding="utf-8"))
+ source_page_index = next(i for i, page in enumerate(path_data) if page.get("sources"))
+ for ref in [
+ "https://github.com/DVOpenLabs/snapmaker-studio/blob/v1.5.0/backend/DOES_NOT_EXIST.py",
+ "https://github.com/DVOpenLabs/snapmaker-studio/blob/v1.5.0/desktop/src/lib/fidelity.ts#DOES_NOT_EXIST",
+ "https://github.com/DVOpenLabs/snapmaker-studio/blob/main/backend/snapstudio_core/rules.py",
+ "https://github.com/DVOpenLabs/snapmaker-studio/blob/v1.5.0/../backend/snapstudio_core/rules.py",
+ "/absolute/backend/snapstudio_core/rules.py",
+ "@does_not_exist",
+ ]:
+ bad_path = json.loads(json.dumps(path_data)); bad_path[source_page_index]["sources"][0]["ref"] = ref
+ path_path.write_text(json.dumps(bad_path), encoding="utf-8")
+ assert _run_guide_build(content, output).returncode != 0
+ path_path.write_text(json.dumps(path_data), encoding="utf-8")
+
+
+@pytest.mark.parametrize("answer_id,changed", [
+ ("size-or-placement", "Studio shrinks the object to fit"),
+ ("sliced-for-u1", "Studio simulates every command"),
+ ("original-unchanged", "Studio edits your original in place"),
+])
+def test_mutated_manifest_and_page_fails_real_engine_checker(tmp_path, answer_id, changed):
+ """Mutation checks call check_answers, the real engine-layer checker; they cannot judge general prose clarity or accessibility."""
+ manifest = json.loads(json.dumps(_guide("answers")))
+ pages = {name: _guide(name) for name in ("path", "tasks", "problems")}
+ answer = next(a for a in manifest["answers"] if a["id"] == answer_id)
+ answer["requiredFacts"][0]["tokens"] = [changed]
+ move = next(t for t in pages["tasks"]["tasks"] if t["id"] == "move-onto-plate")
+ prepare = next(t for t in pages["tasks"]["tasks"] if t["id"] == "prepare-u1-copy")
+ if answer_id == "size-or-placement": move["differs"][0]["then"] = changed
+ elif answer_id == "sliced-for-u1": pages["path"][5]["means"][1]["meaning"] = changed
+ else: prepare["success"][0] = changed
+ import pytest
+ with pytest.raises(AssertionError):
+ check_answers(manifest, pages, tmp_path)
+
+
+def test_extra_contradictory_fact_fails_real_engine_checker(tmp_path):
+ """An extra fact must fail the real checker; this cannot judge general prose clarity or accessibility."""
+ manifest = json.loads(json.dumps(_guide("answers")))
+ pages = {name: _guide(name) for name in ("path", "tasks", "problems")}
+ manifest["answers"][0]["requiredFacts"].append({"id": "contradiction", "derive": "backend:rules.apply_clamps", "tokens": ["shrinks"]})
+ import pytest
+ with pytest.raises(AssertionError):
+ check_answers(manifest, pages, tmp_path)
+
+
+def test_renamed_fact_id_fails_real_engine_checker_from_fresh_manifest(tmp_path):
+ """A fact-id mutation calls the real checker; it cannot establish prose clarity, source fitness, dates, physical behavior, Orca behavior, paraphrased overclaims, or screen readers."""
+ manifest = json.loads(json.dumps(_guide("answers")))
+ pages = {name: _guide(name) for name in ("path", "tasks", "problems")}
+ manifest["answers"][0]["requiredFacts"][0]["id"] = "renamed-fact"
+ with pytest.raises(AssertionError):
+ check_answers(manifest, pages, tmp_path)
+
+
+def test_dropped_token_fails_real_engine_checker_without_page_mutation(tmp_path):
+ """A pure token deletion calls the real checker; it cannot establish prose clarity, source fitness, dates, physical behavior, Orca behavior, paraphrased overclaims, or screen readers."""
+ manifest = json.loads(json.dumps(_guide("answers")))
+ pages = {name: _guide(name) for name in ("path", "tasks", "problems")}
+ manifest["answers"][5]["requiredFacts"][0]["tokens"] = ["SnapmakerU1"]
+ with pytest.raises(AssertionError):
+ check_answers(manifest, pages, tmp_path)
diff --git a/backend/tests/test_orca_import.py b/backend/tests/test_orca_import.py
index 5af8ce5b..e065626d 100644
--- a/backend/tests/test_orca_import.py
+++ b/backend/tests/test_orca_import.py
@@ -23,7 +23,9 @@ def test_exclude_object_is_enabled_when_off():
assert cfg["exclude_object"] == "1"
change = next(c for c in changes if c["key"] == "exclude_object")
assert change["old"] == "0"
- assert "adaptive" in change["explanation"].lower() or "cancel" in change["explanation"].lower()
+ # the explanation describes only Studio's operation, not external slicer behavior
+ assert change["explanation"] == "Studio's import rule turns Exclude Object on for every U1 copy; the original had it off."
+ assert change["kind"] == "engine"
def test_exclude_object_already_on_is_not_reported_as_a_change():
diff --git a/backend/tests/test_public_claims.py b/backend/tests/test_public_claims.py
index b65b802a..34473935 100644
--- a/backend/tests/test_public_claims.py
+++ b/backend/tests/test_public_claims.py
@@ -10,6 +10,7 @@
for every future release, not just one.
"""
import os
+import json
import re
import pytest
@@ -35,8 +36,7 @@
@pytest.mark.parametrize("rel", _PUBLIC_DOCS)
def test_no_print_success_guarantees(rel):
path = os.path.join(_ROOT, rel)
- if not os.path.exists(path):
- pytest.skip(f"{rel} not present")
+ assert os.path.exists(path), f"required public file is missing: {rel}"
text = open(path, encoding="utf-8").read().lower()
for phrase in _BANNED:
assert phrase not in text, f"banned claim '{phrase}' found in {rel}"
@@ -66,8 +66,7 @@ def test_no_print_success_guarantees(rel):
])
def test_public_docs_have_no_tooling_names(rel):
path = os.path.join(_ROOT, rel)
- if not os.path.exists(path):
- pytest.skip(f"{rel} not present")
+ assert os.path.exists(path), f"required public file is missing: {rel}"
text = open(path, encoding="utf-8").read().lower()
for label, pattern in _BANNED_TOOLS:
assert not re.search(pattern, text), f"tooling term '{label}' found in {rel}"
@@ -106,8 +105,7 @@ def test_public_docs_have_no_tooling_names(rel):
@pytest.mark.parametrize("rel", _RELEASE_SURFACES)
def test_release_notes_have_no_internal_tooling_terms(rel):
path = os.path.join(_ROOT, rel)
- if not os.path.exists(path):
- pytest.skip(f"{rel} not present")
+ assert os.path.exists(path), f"required public file is missing: {rel}"
text = open(path, encoding="utf-8").read().lower()
for label, pattern in _BANNED_INTERNAL:
assert not re.search(pattern, text), f"internal/tooling term '{label}' found in {rel}"
@@ -138,3 +136,25 @@ def test_intelligence_report_copy_is_advisory():
def test_success_predict_verdict_not_overconfident():
v = _sp.predict(readiness={"ready": True, "warnings": []})["verdict"].lower()
assert "good to go" not in v
+
+
+def test_readme_and_release_notes_keep_the_golden_answer_for_success_unknown():
+ """Public-copy checks cannot detect a paraphrased overclaim or judge prose clarity."""
+ for rel in ("README.md", os.path.join("docs", "RELEASE_NOTES.md")):
+ path = os.path.join(_ROOT, rel)
+ assert os.path.exists(path), f"required public file is missing: {rel}"
+ text = open(path, encoding="utf-8").read().lower()
+ assert "guaranteed print" not in text
+ assert "100% print success" not in text
+
+
+def test_answers_forbidden_phrases_are_absent_from_all_public_guide_content():
+ """Forbidden-phrase coverage cannot judge prose clarity, source fitness, honest dates, physical behavior, paraphrased overclaims, or screen readers."""
+ answers = json.load(open(os.path.join(_ROOT, "site", "guide", "content", "answers.json"), encoding="utf-8"))
+ public = "\n".join(
+ json.dumps(json.load(open(os.path.join(_ROOT, "site", "guide", "content", name), encoding="utf-8")))
+ for name in ("guide.json", "examples.json", "shots.json")
+ ).lower()
+ for answer in answers["answers"]:
+ for phrase in answer["forbidden"]:
+ assert phrase.lower() not in public, f"forbidden phrase '{phrase}' found in guide content"
diff --git a/backend/tests/test_setting_explanations.py b/backend/tests/test_setting_explanations.py
index 8ecf5512..19cb8340 100644
--- a/backend/tests/test_setting_explanations.py
+++ b/backend/tests/test_setting_explanations.py
@@ -22,7 +22,9 @@
def _project(tmp_path, settings: dict):
path = tmp_path / "foreign.3mf"
- base = {"printer_model": "Bambu Lab X1 Carbon", "filament_colour": ["#FF0000"], "filament_type": ["PLA"]}
+ array_lengths = [len(value) for value in settings.values() if isinstance(value, list)]
+ count = max(array_lengths or [1])
+ base = {"printer_model": "Bambu Lab X1 Carbon", "filament_colour": ["#FF0000"] * count, "filament_type": ["PLA"] * count}
with zipfile.ZipFile(path, "w") as z:
z.writestr("3D/3dmodel.model", '')
z.writestr("Metadata/project_settings.config", json.dumps({**base, **settings}))
@@ -82,6 +84,9 @@ def test_a_negative_raft_expansion_has_one_owner_per_run_and_one_explained_recor
assert records[0]["explanation"] == orca_import.RAFT_EXPANSION_WHY
# the reason is the engine's own, never empty, and never shown instead of the explanation
assert records[0]["reason"] == orca_import.RAFT_EXPANSION_REASON
+ # whichever step wrote the surviving explanation also wrote its source and kind: never a mixed pair
+ assert records[0]["source"] == "Studio's import rule for this setting"
+ assert records[0]["kind"] == "orca"
@pytest.mark.parametrize("mode", ["safe", "preserve", "u1", "optimize"])
@@ -109,10 +114,23 @@ def test_each_clamped_setting_reaches_the_summary_with_its_explanation(tmp_path)
def test_an_ordinary_orca_import_change_keeps_its_own_explanation(tmp_path):
summary, _ = _prepare(tmp_path, {"brim_type": "auto_brim"})
(brim,) = [c for c in summary["compat_changed"] if c["key"] == "brim_type"]
- assert "Snapmaker Orca" in brim["explanation"]
+ assert brim["explanation"] == "Studio replaced the automatic brim choice with no brim. A brim you chose yourself is kept."
+ assert brim["kind"] == "orca"
+ assert brim["source"] == "Studio's import rule for this setting"
+ assert brim["kind"] == "orca"
assert brim["reason"] and brim["reason"] != brim["explanation"]
+@pytest.mark.parametrize("settings,key,phrase", [
+ ({"adaptive_layer_height": "1", "support_type": "tree", "support_style": "organic"}, "support_style", "Studio replaced the tree support style with the hybrid style for this U1 copy."),
+])
+def test_orca_verify_advice_names_only_studios_operation(settings, key, phrase, tmp_path):
+ summary, _ = _prepare(tmp_path, settings)
+ change = next(c for c in summary["compat_changed"] if c["key"] == key)
+ assert change["explanation"] == phrase
+ assert change["kind"] == "orca"
+
+
def test_explanations_are_absent_or_non_empty_and_recommendations_carry_none(tmp_path):
summary, _ = _prepare(tmp_path, {"layer_height": "0.16", "printer_settings_id": "Bambu Lab X1 Carbon 0.4 nozzle"})
assert isinstance(summary["kept_count"], int)
@@ -121,3 +139,95 @@ def test_explanations_are_absent_or_non_empty_and_recommendations_carry_none(tmp
# optional recommendations are a separate list and are not explained here
for change in summary["recommended_changes"]:
assert "explanation" not in change
+
+
+@pytest.mark.parametrize("key", ["filament_flush_temp", "filament_adaptive_volumetric_speed"])
+@pytest.mark.parametrize("value,count,expected,reason", [
+ ([220], 1, "Studio wrote each value in this list as text.", "wrote each value in the list as text"),
+ ([5, 5, 5, 5], 4, "Studio wrote each value in this list as text.", "wrote each value in the list as text"),
+ ([0, 0, 0, 0, 0], 5, "Studio wrote each value in this list as text.", "wrote each value in the list as text"),
+ ([" 5 ", 220, "", "7"], 4, "Studio filled an empty entry with the last non-empty value in this list. Studio trimmed whitespace around a string value. Studio wrote each value in this list as text.", "filled an empty entry with the last non-empty value; trimmed whitespace from a string; wrote each value in the list as text"),
+ (["", "5"], 2, "Studio filled an empty entry with the last non-empty value in this list.", "filled an empty entry with the last non-empty value"),
+ (["1", "2", "3", "4", "5", "6"], 4, "Studio resized this list to cover every filament slot.", "resized the list"),
+ ([" 1 ", "2", "3", "4", "5"], 4, "Studio resized this list to cover every filament slot. Studio trimmed whitespace around a string value.", "resized the list; trimmed whitespace from a string"),
+])
+def test_filament_import_explanation_matches_each_operation(key, value, count, expected, reason):
+ from snapstudio_core.orca_import import _fix_filament_array_validity
+ changes = []
+ cfg = {key: list(value)}
+ _fix_filament_array_validity(cfg, changes, count)
+ assert changes[0]["explanation"] == expected
+ assert changes[0]["kind"] == "engine"
+ assert cfg[key] != value
+ assert changes[0]["reason"] == reason
+ assert all(part in changes[0]["explanation"] for part in expected.split(". ") if part)
+
+
+@pytest.mark.parametrize("mode", ["preserve", "recommended"])
+@pytest.mark.parametrize("key", ["filament_flush_temp", "filament_adaptive_volumetric_speed"])
+@pytest.mark.parametrize("value", [[220], [5, 5, 5, 5], [0, 0, 0, 0, 0], [" 5 ", 220, "", "7"]])
+def test_filament_array_conversion_passes_real_convert_preservation_invariant(tmp_path, mode, key, value):
+ """The real converter records every normalization; this cannot establish prose clarity, source choice, physical behavior, Orca behavior, dates, paraphrased overclaims, or screen-reader behavior."""
+ summary, after = _prepare(tmp_path, {key: value}, mode=mode)
+ change = next(c for c in summary["compat_changed"] if c["key"] == key)
+ assert change["reason"] and change["explanation"]
+ assert all(isinstance(item, str) for item in after[key])
+ assert after[key] != value
+
+
+def test_action_reasons_replace_all_four_provenance_fields_as_one_record():
+ from snapstudio_core.convert import _action_reasons
+ records, _, _, = _action_reasons({"normalizations": [
+ {"key": "raft", "reason": "first", "explanation": "old", "source": "old source", "kind": "engine"},
+ ], "orca_compatibility": [
+ {"key": "raft", "reason": "second", "explanation": "new", "source": "new source", "kind": "engine"},
+ ]})
+ assert records["raft"] == {"reason": "second", "explanation": "new", "source": "new source", "kind": "engine"}
+
+
+def test_action_reasons_clear_a_stale_explanation_only_with_an_explicit_clear():
+ from snapstudio_core.convert import _action_reasons
+ records, _, _, = _action_reasons({"normalizations": [
+ {"key": "raft", "reason": "first", "explanation": "old", "source": "old source", "kind": "engine"},
+ {"key": "raft", "reason": ""},
+ ]})
+ assert "raft" not in records
+
+
+def test_action_reasons_keep_prior_record_when_later_item_has_no_reason():
+ from snapstudio_core.convert import _action_reasons
+ records, _, _, = _action_reasons({"normalizations": [
+ {"key": "raft", "reason": "first", "explanation": "old", "source": "old source", "kind": "engine"},
+ {"key": "raft"},
+ ]})
+ assert records["raft"] == {"reason": "first", "explanation": "old", "source": "old source", "kind": "engine"}
+
+
+@pytest.mark.parametrize("key", ["filament_flush_temp", "filament_adaptive_volumetric_speed"])
+@pytest.mark.parametrize("value,expected,reason", [
+ (["1", "2", "3", "4", " 5 "], "Studio resized this list to cover every filament slot.", "resized the list"),
+ (["1", "2", "3", "4", ""], "Studio resized this list to cover every filament slot.", "resized the list"),
+ (["1", "2", "3", "4", 5], "Studio resized this list to cover every filament slot.", "resized the list"),
+])
+def test_entries_dropped_by_truncation_are_reported_only_as_a_resize(key, value, expected, reason):
+ """An entry beyond the slot count is dropped, so no trim, fill or text conversion may be claimed for it."""
+ from snapstudio_core.orca_import import _fix_filament_array_validity
+ changes = []
+ cfg = {key: list(value)}
+ _fix_filament_array_validity(cfg, changes, 4)
+ assert cfg[key] == ["1", "2", "3", "4"]
+ assert changes[0]["explanation"] == expected
+ assert changes[0]["reason"] == reason
+
+
+@pytest.mark.parametrize("mode", ["preserve", "recommended"])
+@pytest.mark.parametrize("key", ["filament_flush_temp", "filament_adaptive_volumetric_speed"])
+@pytest.mark.parametrize("dropped", [" 5 ", "", 5])
+def test_truncation_through_the_real_convert_path_reports_only_a_resize(tmp_path, mode, key, dropped):
+ """Same rule end to end: the dropped entry never leaks a trim, fill or conversion claim into the summary."""
+ four = ["#FF0000"] * 4
+ summary, after = _prepare(tmp_path, {key: ["1", "2", "3", "4", dropped], "filament_colour": four, "filament_type": ["PLA"] * 4}, mode=mode)
+ change = next(c for c in summary["compat_changed"] if c["key"] == key)
+ assert after[key] == ["1", "2", "3", "4"]
+ assert change["explanation"] == "Studio resized this list to cover every filament slot."
+ assert change["reason"] == "resized the list"
diff --git a/desktop/package-lock.json b/desktop/package-lock.json
index 68c2dcb1..21918cd8 100644
--- a/desktop/package-lock.json
+++ b/desktop/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "snapmaker-studio-desktop",
- "version": "1.5.0",
+ "version": "1.5.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "snapmaker-studio-desktop",
- "version": "1.5.0",
+ "version": "1.5.1",
"dependencies": {
"@radix-ui/react-slot": "^1",
"@tanstack/react-query": "^5",
diff --git a/desktop/package.json b/desktop/package.json
index c156e6e9..4d1ca855 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "snapmaker-studio-desktop",
"private": true,
- "version": "1.5.0",
+ "version": "1.5.1",
"description": "Snapmaker Studio — the local-first workflow platform for modern 3D printing. Understand any design, check if it will print, get it ready, and monitor your Snapmaker U1.",
"type": "module",
"scripts": {
diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock
index 269709ca..911f1a25 100644
--- a/desktop/src-tauri/Cargo.lock
+++ b/desktop/src-tauri/Cargo.lock
@@ -2787,7 +2787,7 @@ checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
[[package]]
name = "snapmaker-studio-desktop"
-version = "1.5.0"
+version = "1.5.1"
dependencies = [
"libc",
"serde",
diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml
index 007faea8..1ef36180 100644
--- a/desktop/src-tauri/Cargo.toml
+++ b/desktop/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "snapmaker-studio-desktop"
-version = "1.5.0"
+version = "1.5.1"
description = "Snapmaker Studio desktop shell"
edition = "2021"
diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json
index 60a928e6..99b38148 100644
--- a/desktop/src-tauri/tauri.conf.json
+++ b/desktop/src-tauri/tauri.conf.json
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Snapmaker Studio",
- "version": "1.5.0",
+ "version": "1.5.1",
"identifier": "com.snapmakerstudio.desktop",
"build": {
"frontendDist": "../dist",
diff --git a/desktop/src/api.ts b/desktop/src/api.ts
index 2be05629..27fee06b 100644
--- a/desktop/src/api.ts
+++ b/desktop/src/api.ts
@@ -127,6 +127,9 @@ export interface SettingsChange {
reason?: string;
/** Plain-language explanation some steps add next to the reason. */
explanation?: string;
+ /** Evidence provenance for the explanation, replaced or cleared with it. */
+ source?: string;
+ kind?: "file" | "engine" | "estimate" | "orca";
}
export interface SettingsSummary {
diff --git a/desktop/src/components/BusinessDoctors.tsx b/desktop/src/components/BusinessDoctors.tsx
index 3380402c..a82f1093 100644
--- a/desktop/src/components/BusinessDoctors.tsx
+++ b/desktop/src/components/BusinessDoctors.tsx
@@ -120,7 +120,7 @@ export function BusinessDoctors({ filePath, host }: { filePath: string; host?: s
+ sub="estimated cost" />
diff --git a/desktop/src/components/PrepareSettingsSummary.test.tsx b/desktop/src/components/PrepareSettingsSummary.test.tsx
index d5cd8bc1..491b75d6 100644
--- a/desktop/src/components/PrepareSettingsSummary.test.tsx
+++ b/desktop/src/components/PrepareSettingsSummary.test.tsx
@@ -112,17 +112,19 @@ describe("PrepareSettingsSummary explanations", () => {
kept_count: 12,
mapped_to_u1: [{ key: "nozzle_temperature", old: "[200]", new: "[200,200,200,200]", reason: "carried over to U1 toolheads (values preserved)" }],
compat_changed: [
- { key: "prime_tower_brim_width", old: "-1", new: "5", reason: "U1 compatibility clamp: -1 → 5", explanation: "-1 is outside the valid range for this setting (0 or more), which the Compatibility check flags as an invalid value. Studio used 5, the U1 default." },
- { key: "brim_type", old: "auto_brim", new: "no_brim", reason: "the creator left the brim on automatic", explanation: "Automatic means the slicer chooses." },
+ { key: "prime_tower_brim_width", old: "-1", new: "5", reason: "U1 compatibility clamp: -1 → 5", explanation: "-1 is outside the valid range for this setting (0 or more), which the Compatibility check flags as an invalid value. Studio used 5, the U1 default.", source: "Studio's valid range for this setting", kind: "engine" as const },
+ { key: "brim_type", old: "auto_brim", new: "no_brim", reason: "the creator left the brim on automatic", explanation: "Automatic means the slicer chooses.", source: "Studio's rule for how Snapmaker Orca imports this setting", kind: "orca" as const },
{ key: "some_setting", old: "1", new: "2", reason: "changed only for U1 compatibility" },
],
recommended_changes: [{ key: "speed", old: 20, new: 40, reason: "available with the recommended U1 profile" }],
};
it("shows the engine's explanation under each compatibility change that has one", () => {
- const html = renderToStaticMarkup();
+ const html = renderToStaticMarkup().replace(/'/g, "'");
expect(html).toContain("which the Compatibility check flags as an invalid value");
expect(html).toContain("Automatic means the slicer chooses.");
+ expect(html).toContain("Studio's check");
+ expect(html).toContain("Studio's rule for how Snapmaker Orca imports this setting");
});
it("does not repeat a reason that only restates the change", () => {
diff --git a/desktop/src/components/PrepareSettingsSummary.tsx b/desktop/src/components/PrepareSettingsSummary.tsx
index 8dd31bd5..223b5791 100644
--- a/desktop/src/components/PrepareSettingsSummary.tsx
+++ b/desktop/src/components/PrepareSettingsSummary.tsx
@@ -2,6 +2,7 @@ import type { SettingsChange, SettingsSummary } from "@/api";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { settingNote } from "@/lib/settingNotes";
+import { evidenceKindLabel } from "@/lib/evidenceKind";
function value(value: unknown) {
const text = typeof value === "string" ? value : JSON.stringify(value);
@@ -16,7 +17,7 @@ function Changes({ changes, explain = false }: { changes: SettingsChange[]; expl
return (
,
+ }));
+
+const tab = (name: string) => screen.getByRole("tab", { name });
+const press = (el: HTMLElement, key: string) => fireEvent.keyDown(el, { key });
+
+describe("ToolTabs", () => {
+ it("names the tab row and wires tab and panel together with ids", () => {
+ render();
+ expect(screen.getByRole("tablist", { name: "Example tools" })).toBeTruthy();
+ const a = tab("Tab a");
+ const panel = screen.getByRole("tabpanel");
+ expect(a.id).toBeTruthy();
+ expect(a.getAttribute("aria-controls")).toBe(panel.id);
+ expect(panel.getAttribute("aria-labelledby")).toBe(a.id);
+ expect(screen.getByRole("tabpanel", { name: "Tab a" })).toBe(panel);
+ });
+
+ it("only the selected tab has aria-controls, because inactive panels are not in the page", () => {
+ render();
+ expect(tab("Tab a").getAttribute("aria-controls")).toBeTruthy();
+ expect(tab("Tab b").hasAttribute("aria-controls")).toBe(false);
+ });
+
+ it("ignores navigation keys pressed with Alt, Ctrl or Meta", () => {
+ render();
+ tab("Tab a").focus();
+ for (const init of [
+ { key: "ArrowLeft", altKey: true }, { key: "Home", ctrlKey: true }, { key: "ArrowRight", metaKey: true },
+ { key: "Enter", ctrlKey: true },
+ ]) {
+ const notPrevented = fireEvent.keyDown(tab("Tab a"), { ...init, cancelable: true });
+ expect(notPrevented).toBe(true); // dispatchEvent returns false when preventDefault ran
+ expect(document.activeElement).toBe(tab("Tab a"));
+ expect(tab("Tab a").getAttribute("aria-selected")).toBe("true");
+ }
+ });
+
+ it("keeps only the selected panel in the page", () => {
+ render();
+ expect(screen.queryByText("Heading a")).not.toBeNull();
+ expect(screen.queryByText("Heading b")).toBeNull();
+ expect(screen.getAllByRole("tabpanel")).toHaveLength(1);
+ });
+
+ it("puts only the selected tab in the Tab order, and the panel is not a tab stop", () => {
+ render();
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([0, -1, -1]);
+ expect(screen.getByRole("tabpanel").tabIndex).toBe(-1);
+ });
+
+ it("moves focus with the arrow keys, wrapping at both ends, without switching the panel", () => {
+ render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "ArrowRight");
+ expect(document.activeElement).toBe(tab("Tab b"));
+ press(tab("Tab b"), "ArrowRight");
+ press(tab("Tab c"), "ArrowRight");
+ expect(document.activeElement).toBe(tab("Tab a"));
+ press(tab("Tab a"), "ArrowLeft");
+ expect(document.activeElement).toBe(tab("Tab c"));
+ expect(tab("Tab a").getAttribute("aria-selected")).toBe("true");
+ expect(tab("Tab c").getAttribute("aria-selected")).toBe("false");
+ expect(screen.queryByText("Heading a")).not.toBeNull();
+ expect(screen.queryByText("Heading c")).toBeNull();
+ });
+
+ it("moves the single tab stop with focus, leaving the selected tab as it was", () => {
+ render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "ArrowRight");
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([-1, 0, -1]);
+ expect(screen.getAllByRole("tab").map((t) => t.getAttribute("aria-selected"))).toEqual(["true", "false", "false"]);
+ });
+
+ it("after arrowing to another tab and leaving the row, focus comes back to the selected tab", () => {
+ render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "ArrowRight");
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([-1, 0, -1]);
+ act(() => { screen.getByRole("button", { name: "Action a" }).focus(); }); // focus leaves the row
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([0, -1, -1]);
+ expect(tab("Tab a").getAttribute("aria-selected")).toBe("true");
+ });
+
+ it("Home and End jump to the first and last tab, and Up and Down do nothing", () => {
+ render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "End");
+ expect(document.activeElement).toBe(tab("Tab c"));
+ press(tab("Tab c"), "Home");
+ expect(document.activeElement).toBe(tab("Tab a"));
+ press(tab("Tab a"), "ArrowDown");
+ press(tab("Tab a"), "ArrowUp");
+ expect(document.activeElement).toBe(tab("Tab a"));
+ });
+
+ it("Enter selects the focused tab and shows its panel", () => {
+ render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "ArrowRight");
+ press(tab("Tab b"), "Enter");
+ expect(tab("Tab b").getAttribute("aria-selected")).toBe("true");
+ expect(screen.queryByText("Heading b")).not.toBeNull();
+ expect(screen.queryByText("Heading a")).toBeNull();
+ expect(screen.getByRole("tabpanel").getAttribute("aria-labelledby")).toBe(tab("Tab b").id);
+ });
+
+ it("Space selects the focused tab", () => {
+ render();
+ tab("Tab b").focus();
+ press(tab("Tab b"), " ");
+ expect(screen.queryByText("Heading b")).not.toBeNull();
+ });
+
+ it("a click selects the tab and makes it the tab stop", () => {
+ render();
+ fireEvent.click(tab("Tab b"));
+ expect(screen.queryByText("Heading b")).not.toBeNull();
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([-1, 0]);
+ });
+
+ it("honors the initial tab", () => {
+ render();
+ expect(screen.queryByText("Heading b")).not.toBeNull();
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([-1, 0]);
+ });
+
+ it("renders nothing, without throwing, when there are no tabs", () => {
+ const { container } = render();
+ expect(container.innerHTML).toBe("");
+ });
+
+ it("uses the shared focus ring tokens on each tab", () => {
+ render();
+ for (const t of screen.getAllByRole("tab")) {
+ expect(t.className).toContain("focus-visible:ring-2");
+ expect(t.className).toContain("focus-visible:ring-ring");
+ expect(t.className).toContain("focus-visible:ring-offset-background");
+ expect(t.className).toContain("focus-visible:outline-none");
+ }
+ });
+});
+
+function Removable({ ids }: { ids: string[] }) {
+ return ;
+}
+
+function Dropper() {
+ const [ids, setIds] = useState(["a", "b"]);
+ return (
+
+
+
+
+ );
+}
+
+describe("ToolTabs when a tab disappears", () => {
+ it("selects the first remaining tab when the selected tab is removed", () => {
+ const { rerender } = render();
+ rerender();
+ expect(tab("Tab b").getAttribute("aria-selected")).toBe("true");
+ expect(screen.queryByText("Heading b")).not.toBeNull();
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([0, -1]);
+ });
+
+ it("moves the tab stop to the selected tab when the focused tab is removed", () => {
+ const { rerender } = render();
+ tab("Tab a").focus();
+ press(tab("Tab a"), "End");
+ rerender();
+ expect(tab("Tab a").getAttribute("aria-selected")).toBe("true");
+ expect(screen.getAllByRole("tab").map((t) => t.tabIndex)).toEqual([0, -1]);
+ expect(document.activeElement).toBe(tab("Tab a"));
+ });
+
+ it("moves real focus to the new selected tab when the focused, selected tab is removed", () => {
+ const { rerender } = render();
+ tab("Tab a").focus();
+ rerender();
+ expect(document.activeElement).toBe(tab("Tab b"));
+ });
+
+ it("moves focus to the selected tab when focus was inside a panel that is unmounted", () => {
+ render();
+ const inside = screen.getByRole("button", { name: "Action a" });
+ inside.focus();
+ expect(document.activeElement).toBe(inside);
+ act(() => { fireEvent.click(screen.getByRole("button", { name: "drop a" })); });
+ expect(document.activeElement).toBe(tab("Tab b"));
+ });
+
+ it("does not take focus back after the tabs went empty and came back", () => {
+ function Toggle({ ids }: { ids: string[] }) {
+ return (
+
+
+
+
+ );
+ }
+ const { rerender } = render();
+ screen.getByRole("button", { name: "Action a" }).focus();
+ rerender();
+ const outside = screen.getByRole("button", { name: "outside" });
+ outside.focus();
+ rerender();
+ expect(document.activeElement).toBe(outside);
+ });
+
+ it("does not take focus from elsewhere on the page when a tab is removed", () => {
+ render();
+ const drop = screen.getByRole("button", { name: "drop a" });
+ drop.focus();
+ fireEvent.click(drop);
+ expect(document.activeElement).toBe(drop);
+ });
+});
diff --git a/desktop/src/components/ui/ToolTabs.tsx b/desktop/src/components/ui/ToolTabs.tsx
index 0188b95b..05d6c6e6 100644
--- a/desktop/src/components/ui/ToolTabs.tsx
+++ b/desktop/src/components/ui/ToolTabs.tsx
@@ -1,10 +1,24 @@
-import { useState, type ReactNode } from "react";
+import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
-// Lightweight tab switcher used to merge two closely-related tools onto one page
-// (one sidebar item, two panels) instead of two duplicate nav entries. Each panel
-// is an existing route component rendered as-is.
+// Tab switcher used to merge two closely-related tools onto one page (one sidebar
+// item, two panels) instead of two duplicate nav entries. Each panel is an existing
+// route component rendered as-is.
+//
+// Keyboard model (WAI-ARIA tabs pattern, manual activation):
+// - Only one tab is in the Tab order (roving tabindex): the focused tab while focus is
+// in the row, otherwise the selected tab.
+// - Arrow Left/Right (with wrap), Home and End move focus only. They never switch the
+// panel. Enter, Space or a click selects the focused tab.
+// - Manual activation is deliberate. Switching unmounts one route and mounts the
+// other, which re-runs that route's engine requests. Moving focus along the tab row
+// must not trigger that. The pattern allows manual activation for panels that are
+// expensive to show.
+// - Focus entering the row always lands on the selected tab: the tab stop resets to it
+// when focus leaves the row.
+// - The selected tab and the tab that owns the tab stop are tracked separately
+// (`active` and `focused`).
export interface ToolTab {
id: string;
label: string;
@@ -12,25 +26,113 @@ export interface ToolTab {
el: ReactNode;
}
-export function ToolTabs({ tabs, initial }: { tabs: ToolTab[]; initial?: string }) {
+export function ToolTabs({ tabs, initial, label }: {
+ tabs: ToolTab[];
+ initial?: string;
+ /** Accessible name of the tab row (rendered as aria-label), for example "Print quality tools". */
+ label: string;
+}) {
+ const uid = useId();
const [active, setActive] = useState(initial ?? tabs[0]?.id);
- const current = tabs.find((t) => t.id === active) ?? tabs[0];
+ const [focused, setFocused] = useState(active);
+ const rootRef = useRef(null);
+ const tabRefs = useRef(new Map());
+ // True while keyboard focus is somewhere inside this component (tab row or panel).
+ const focusInside = useRef(false);
+
+ // A tab can disappear while selected or focused. Fall back to the first remaining tab.
+ const activeId = tabs.some((t) => t.id === active) ? active : tabs[0]?.id;
+ const focusedId = tabs.some((t) => t.id === focused) ? focused : activeId;
+ const idKey = tabs.map((t) => t.id).join("\u0000");
+
+ useEffect(() => {
+ // With no tabs the root is gone and no blur fired; forget any focus that was inside it.
+ if (!activeId) focusInside.current = false;
+ // Keep the stored state in step with what is shown, so a removed tab that
+ // returns later does not silently become selected again.
+ if (activeId !== active) setActive(activeId);
+ if (focusedId !== focused) setFocused(focusedId);
+ // If focus was on the removed tab, or inside the panel that was unmounted, the
+ // browser has dropped it to the page body. Put it on the selected tab.
+ const now = document.activeElement;
+ const lost = !now || now === document.body || !now.isConnected || !rootRef.current?.contains(now);
+ if (focusInside.current && lost && activeId) tabRefs.current.get(activeId)?.focus();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [idKey]);
+
+ if (tabs.length === 0 || !activeId) return null;
+ const current = tabs.find((t) => t.id === activeId) ?? tabs[0];
+ const tabDomId = (id: string) => `${uid}-tab-${id}`;
+ const panelDomId = (id: string) => `${uid}-panel-${id}`;
+
+ const moveFocus = (id: string) => {
+ setFocused(id);
+ tabRefs.current.get(id)?.focus();
+ };
+ const select = (id: string) => {
+ setFocused(id);
+ setActive(id);
+ };
+ const onKeyDown = (e: KeyboardEvent, index: number) => {
+ // Browser and assistive-technology shortcuts (Alt+Left is Back, Ctrl+Home scrolls) are left alone.
+ if (e.altKey || e.ctrlKey || e.metaKey) return;
+ const last = tabs.length - 1;
+ let next: number | null = null;
+ if (e.key === "ArrowRight") next = index === last ? 0 : index + 1;
+ else if (e.key === "ArrowLeft") next = index === 0 ? last : index - 1;
+ else if (e.key === "Home") next = 0;
+ else if (e.key === "End") next = last;
+ if (next !== null) {
+ e.preventDefault();
+ moveFocus(tabs[next].id);
+ } else if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ select(tabs[index].id);
+ }
+ };
+
return (
-