Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Release app carries no engine seed: sync online on the first start
v0lumehi50fe2f1ad91b
diff --git a/.github/workflows/build-mac-app.yml b/.github/workflows/build-mac-app.ymlindex 4eb171cd..610350c3 100644--- a/.github/workflows/build-mac-app.yml+++ b/.github/workflows/build-mac-app.yml@@ -8,7 +8,7 @@# "up to date" — a silent failure of the update path for every existing install. Copies from before# the app was renamed (NS Port Builder) look for NS-Port-Builder-macOS-arm64.zip, so that one goes up too.#-# The app also carries the pinned engine as a seed for `tools/engine.py sync` (Resources/engine.git, issue #214), and its build tools (zstd, glslangValidator, spirv-cross, xcodegen) and a Python with the packages the build scripts import,+# The app carries no engine (issue #214): the launcher runs `tools/engine.py sync` on the first start and after updates, from GitHub. It carries its build tools (zstd, glslangValidator, spirv-cross, xcodegen) and a Python with the packages the build scripts import,# so a player installs neither Homebrew nor Python (frontend/tools/bundle_tools.sh builds them from pinned, checksummed sources; check_bundle.sh# runs each from the assembled bundle with a clean PATH, checks the load paths and the signature).#@@ -73,18 +73,6 @@ jobs:# The build tools and the Python go into Resources before the bundle is signed (bundle_tools.sh signs each nested Mach-O file# itself: --deep below does not reach code that sits in Resources).tools/bundle_tools.sh "$APP/Contents/Resources" "$RUNNER_TEMP/bundle-tools-work"- # The engine (issue #214): the pinned seedds/nxnative commit as a bare one-commit repository, about 80 MB. The launcher passes- # it to `tools/engine.py sync --seed`, so the player's checkout builds engine/ without a download while its pin is this one,- # and fetches only what changed once the pin moved. The patches come from the checkout, so they always match its pin.- python3 ../tools/engine.py sync- SEED="$APP/Contents/Resources/engine.git"- PIN=$(cat ../.upstream-ref)- git init -q --bare "$SEED"- git -C "$SEED" fetch -q --no-tags --depth 1 "file://$PWD/../engine" "$PIN"- git -C "$SEED" update-ref refs/heads/main "$PIN"- git -C "$SEED" symbolic-ref HEAD refs/heads/main- rm -rf "$SEED/hooks"- du -sh "$SEED"V="${{ steps.ver.outputs.version }}"cat > "$APP/Contents/Info.plist" <<PLIST<?xml version="1.0" encoding="UTF-8"?>diff --git a/frontend-qt/nspb_qt/build_failure.py b/frontend-qt/nspb_qt/build_failure.pyindex be8e0a77..f612e2fb 100644--- a/frontend-qt/nspb_qt/build_failure.py+++ b/frontend-qt/nspb_qt/build_failure.py@@ -61,6 +61,7 @@ KINDS = [ROSETTA, TRANSLATOR, ZBIC, IOS_SDK, CLT_SELECTED, OTHER_METAL, SHADER_R# The Swift app has four more rows that no log line sets (a drive that is gone, a signing team, a device transfer):# they belong to the Mac launcher's install on a device and to /Volumes, which this front end does not have.# cloudFolder is a row of the table, so it is here, but the check that stops a build before it starts is the Mac launcher's.+# The engine's online sync has two more (engine.py's ENGINE_OFFLINE and ENGINE_SYNC): no log line of the script sets them either._A32_NAME = re.compile(r'^(?:\[RED\] )?(.+?) \([0-9A-Fa-f]{16}\) is a 32-bit ARM program', re.M)diff --git a/frontend-qt/nspb_qt/engine.py b/frontend-qt/nspb_qt/engine.pyindex e956ef41..d3ddeab6 100644--- a/frontend-qt/nspb_qt/engine.py+++ b/frontend-qt/nspb_qt/engine.py@@ -2,7 +2,8 @@Since #214 the engine is built into `<checkout>/engine/` (seedds/nxnative at `.upstream-ref` plus `patches/`). Until thecommitted copy goes (step 2), a checkout has both, and one from before the switch has only the committed copy. The rule, the-same as the Mac launcher's (frontend/Sources/NSPortBuilder/Engine.swift):+same as the Mac launcher's (frontend/Sources/NSPortBuilder/Engine.swift). A release carries no engine: the sync downloads it from+GitHub on the first start and after updates, and a failed one becomes a failure row (`failure_kind`):- engine/ when it is synced and current,- else the committed tree (dm/, scripts/ at the checkout's root) when the checkout has one,@@ -14,7 +15,9 @@ the launcher can tell a stale engine without starting Python. Pure stdlib, no Qtfrom __future__ import annotationsimport hashlib+import subprocessfrom pathlib import Path+from typing import CallableMARKER = ('dm', 'tools', 'nx_extract', 'Program.cs') # the file that tells an engine tree (as BuildModel.is_repo always did)STAMP = Path('.git', 'nx2apple-stamp')@@ -103,3 +106,28 @@ def needs_sync_before_build(repo: str) -> bool:def sync_command(repo: str, python: str) -> list[str]:return [python, str(Path(repo, 'tools', 'engine.py')), 'sync']+++ENGINE_OFFLINE = 'engineOffline' # the fetch of the pinned commit failed: no network, GitHub unreachable, a proxy+ENGINE_SYNC = 'engineSync' # any other stop of the sync+++def failure_kind(log: str) -> str:+ """What a failed sync was, from its output: tools/engine.py says "cannot fetch" when the pinned commit cannot be fetched."""+ return ENGINE_OFFLINE if 'cannot fetch ' in log else ENGINE_SYNC+++def run_sync(cmd: list[str], cwd: str, line: Callable[[str], None], **popen) -> tuple[bool, str | None]:+ """Run the sync command, pass its lines on, and return (ok, failure kind or None). Blocking: call it off the UI thread."""+ tail = ''+ try:+ p = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, errors='replace', **popen)+ assert p.stdout is not None+ for out in p.stdout:+ line(out)+ tail = (tail + out)[-4000:]+ ok = p.wait() == 0+ except OSError as e:+ line(f'{e}\n')+ return False, ENGINE_SYNC+ return ok, None if ok else failure_kind(tail)diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.pyindex 250915dc..46dd5392 100644--- a/frontend-qt/nspb_qt/localization.py+++ b/frontend-qt/nspb_qt/localization.py@@ -797,6 +797,11 @@ TABLE: dict[str, tuple[str, str, str, str]] = {'fail.showFolder': ('显示文件夹', 'Show folder', 'Visa mapp', 'Ordner zeigen'),'fail.openXcode': ('打开 Xcode', 'Open Xcode', 'Öppna Xcode', 'Xcode öffnen'),'fail.retry': ('重试', 'Try again', 'Försök igen', 'Erneut versuchen'),+ 'engine.syncing': ('正在从 GitHub 获取引擎(约 80 MB)。首次启动和更新后会运行一次,需要一两分钟。', 'Fetching the engine from GitHub (about 80 MB). This runs on the first start and after updates and takes a minute or two.', 'Hämtar motorn från GitHub (cirka 80 MB). Det körs vid första starten och efter uppdateringar och tar en till två minuter.', 'Fetching the engine from GitHub (about 80 MB). This runs on the first start and after updates and takes a minute or two.'),+ 'fail.engineOffline.what': ('无法从 GitHub 下载引擎。', 'The engine could not be downloaded from GitHub.', 'Det gick inte att hämta motorn från GitHub.', 'The engine could not be downloaded from GitHub.'),+ 'fail.engineOffline.next': ('请检查网络连接,并确认可以访问 github.com,然后点「重试」。没有引擎就无法构建游戏。', 'Check your internet connection and that github.com can be reached, then press Try again. Games cannot be built without the engine.', 'Kontrollera internetanslutningen och att github.com kan nås. Tryck sedan på Försök igen. Spel kan inte byggas utan motorn.', 'Check your internet connection and that github.com can be reached, then press Try again. Games cannot be built without the engine.'),+ 'fail.engineSync.what': ('引擎准备失败。', 'The engine could not be prepared.', 'Det gick inte att förbereda motorn.', 'The engine could not be prepared.'),+ 'fail.engineSync.next': ('请点「重试」。原因见日志。如果一直失败,请用「复制诊断信息」连同日志一起反馈。', 'Press Try again. The log shows the reason. If it keeps failing, report it with Copy diagnostics and the log.', 'Tryck på Försök igen. Loggen visar orsaken. Om det fortsätter att misslyckas, rapportera det med Kopiera diagnostik och loggen.', 'Press Try again. The log shows the reason. If it keeps failing, report it with Copy diagnostics and the log.'),'dep.metal.other': ('%@(测试用的是 %@)', '%@ (tested: %@)', '%@ (tested: %@)', '%@ (getestet: %@)'),'dep.fix.metalPin': ('这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.', 'This is not the Metal compiler the shaders were tested with. Games that use NVN stop before the shader steps. Install Xcode 27.1 (macOS 26.6 or later) and its Metal toolchain.', 'Das ist nicht der Metal-Compiler, mit dem die Shader getestet wurden. Spiele mit NVN stoppen vor den Shader-Schritten. Installiere Xcode 27.1 (macOS 26.6 oder neuer) samt Metal-Toolchain.'),'msg.exitCode': ('退出码 %d', 'exit code %d', 'slutkod %d', 'Exit-Code %d'),diff --git a/frontend-qt/nspb_qt/model.py b/frontend-qt/nspb_qt/model.pyindex d8b7cfbc..8429631d 100644--- a/frontend-qt/nspb_qt/model.py+++ b/frontend-qt/nspb_qt/model.py@@ -96,6 +96,8 @@ class Model(QObject):self.stages: list[Stage] = []self.running = Falseself.log_tail = ''+ self.engine_syncing = False # tools/engine.py sync runs: the window shows a status line+ self.engine_failure: bf.Failure | None = None # how the last sync stopped (engine.py's failure_kind), shown as a failure row with Try againself.failure: bf.Failure | None = None # the script's known early stop (build_failure.py), None for any otherself.override = bf.OverrideState() # "Build anyway": one confirmed --allow-* for the next buildself._last_error = '' # the last real log line: the failure note names it (issue #52)@@ -164,31 +166,39 @@ class Model(QObject):def sync_engine(self, then: Callable[[bool], None] | None = None) -> None:"""Run `tools/engine.py sync` on a thread when engine/ is stale (after a pull, at the start, before a build thatneeds it). A no-op for a checkout from before #214 or a current engine/. `then(ok)` runs after it."""- if not engine.is_stale(self.repo_path) or getattr(self, '_engine_syncing', False):+ if getattr(self, '_engine_syncing', False):+ if then: then(True)+ return+ if not engine.is_stale(self.repo_path):+ self.engine_failure = Noneif then: then(True)returnpy = self.python_path or ('python' if pu.IS_WIN else '/usr/bin/python3')cmd = engine.sync_command(self.repo_path, py)self._engine_syncing = True+ self.engine_syncing = True+ self.engine_failure = Noneself.log('$ ' + ' '.join(cmd) + '\n')+ self.repoChanged.emit() # the window shows the status linedef work() -> None:- ok = False- try:- p = subprocess.Popen(cmd, cwd=self.repo_path, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,- errors='replace', env=pu.child_env(), **pu.no_window_kwargs())- assert p.stdout is not None- for line in p.stdout:- self.log(line)- ok = p.wait() == 0- except OSError as e:- self.log(f'{e}\n')+ ok, kind = engine.run_sync(cmd, self.repo_path, self.log, env=pu.child_env(), **pu.no_window_kwargs())self._engine_syncing = False+ self.engine_syncing = False+ self.engine_failure = None if ok else bf.Failure(kind or engine.ENGINE_SYNC)self.repoChanged.emit()if then: then(ok)threading.Thread(target=work, daemon=True).start()+ def retry_engine_sync(self) -> None:+ """The failure row's Try again: clears the row and runs the sync again."""+ if self.engine_syncing:+ return+ self.engine_failure = None+ self.sync_engine()+ self.repoChanged.emit()+def _find_repo(self) -> str:saved = os.environ.get('NSPB_REPO', '')if self.is_repo(saved):diff --git a/frontend-qt/nspb_qt/ui.py b/frontend-qt/nspb_qt/ui.pyindex 5beea0ad..219736fd 100644--- a/frontend-qt/nspb_qt/ui.py+++ b/frontend-qt/nspb_qt/ui.py@@ -172,6 +172,46 @@ class MainWindow(QMainWindow):self.repo_status = QLabel('')self.repo_status.setObjectName('note')lay.addWidget(self.repo_status)+ # The engine's online sync (first start, after updates): a status line while it runs, and its failure row with Try again.+ self.engine_status = QLabel('')+ self.engine_status.setObjectName('note')+ self.engine_status.setWordWrap(True)+ self.engine_status.hide()+ lay.addWidget(self.engine_status)+ self.engine_failure_box = QFrame()+ self.engine_failure_box.setObjectName('card')+ fbox = QVBoxLayout(self.engine_failure_box)+ fbox.setContentsMargins(12, 8, 12, 8)+ fbox.setSpacing(4)+ self.engine_failure_what = QLabel('')+ self.engine_failure_what.setWordWrap(True)+ self.engine_failure_what.setStyleSheet(f'color: {ORANGE}; font-weight: 600;')+ self.engine_failure_next = QLabel('')+ self.engine_failure_next.setWordWrap(True)+ self.engine_failure_next.setObjectName('note')+ self.engine_retry_btn = QPushButton(self.m.t('fail.retry'))+ self._translatable.append((self.engine_retry_btn, 'fail.retry'))+ self.engine_retry_btn.clicked.connect(self.m.retry_engine_sync)+ retry_row = QHBoxLayout()+ retry_row.addWidget(self.engine_retry_btn)+ retry_row.addStretch(1)+ fbox.addWidget(self.engine_failure_what)+ fbox.addWidget(self.engine_failure_next)+ fbox.addLayout(retry_row)+ self.engine_failure_box.hide()+ lay.addWidget(self.engine_failure_box)++ def _show_engine_sync(self) -> None:+ """The status line while tools/engine.py sync runs, or its failure row (what happened, what to do, Try again)."""+ self.engine_status.setVisible(self.m.engine_syncing)+ self.engine_status.setText(self.m.t('engine.syncing') if self.m.engine_syncing else '')+ f = self.m.engine_failure+ if f is None or self.m.engine_syncing:+ self.engine_failure_box.hide()+ return+ self.engine_failure_what.setText(self.m.t(f.what_key))+ self.engine_failure_next.setText(self.m.t(f.next_key))+ self.engine_failure_box.show()def _build_inputs(self) -> None:box, lay = self._card('data.title', 'data.note')@@ -416,6 +456,7 @@ class MainWindow(QMainWindow):for w, key in self._translatable:w.setText(self.m.t(key))self._show_failure()+ self._show_engine_sync()full = (pu.short_path(self.m.repo_path) if self.m.repo_okelse (self.m.repo_path or self.m.t('repo.notFound')))self.repo_path_label.setText(full)@@ -433,6 +474,7 @@ class MainWindow(QMainWindow):busy = self.m.repo_busy or self.m.runningfor b in (self.download_btn, self.update_btn, self.choose_btn):b.setEnabled(not busy)+ self.engine_retry_btn.setEnabled(not self.m.engine_syncing)if getattr(self.m, 'log_path', None):self.log_path_label.setText(self.m.t('log.at', str(self.m.log_path)))self._refresh_inputs()diff --git a/frontend-qt/tests/test_build_failure_hints.py b/frontend-qt/tests/test_build_failure_hints.pyindex 298f8dc7..0d053869 100644--- a/frontend-qt/tests/test_build_failure_hints.py+++ b/frontend-qt/tests/test_build_failure_hints.py@@ -195,7 +195,8 @@ class Strings(unittest.TestCase):keys = ['fail.section', 'fail.buildAnyway', 'fail.confirm.title', 'fail.confirm.go', 'fail.confirm.cancel','fail.override.note', 'fail.a32Program.whatNamed', 'fail.translator.button', 'fail.iosSDK.button','fail.cltSelected.button', 'dep.metal.other', 'dep.fix.metalPin']- for kind in bf.KINDS:+ keys += ['fail.retry', 'engine.syncing']+ for kind in bf.KINDS + ['engineOffline', 'engineSync']: # the last two are the engine sync's rows (engine.py's failure_kind)keys += [f'fail.{kind}.what', f'fail.{kind}.next']if kind in bf.OVERRIDE_FLAGS:keys.append(f'fail.{kind}.risk')diff --git a/frontend-qt/tests/test_engine_layout.py b/frontend-qt/tests/test_engine_layout.pyindex 2e9be771..d11a6fb7 100644--- a/frontend-qt/tests/test_engine_layout.py+++ b/frontend-qt/tests/test_engine_layout.py@@ -82,5 +82,44 @@ class EngineLayoutTests(unittest.TestCase):self.assertEqual(engine.sync_command('/c', 'py'), ['py', str(Path('/c/tools/engine.py')), 'sync'])+class OnlineSync(unittest.TestCase):+ """A release carries no engine: the first start downloads it, and a failed fetch is a failure row (no Qt needed)."""++ def setUp(self):+ self.r = Path(tempfile.mkdtemp(prefix='qt-engine-sync-'))+ self.addCleanup(shutil.rmtree, self.r, True)++ def tool(self, source: str) -> list[str]:+ (self.r / 'engine.py').write_text(source)+ return [sys.executable, str(self.r / 'engine.py')]++ def test_a_failed_fetch_is_the_offline_row_and_any_other_stop_the_general_one(self):+ src = (ROOT / 'tools' / 'engine.py').read_text(encoding='utf-8')+ self.assertIn('cannot fetch ', src, 'tools/engine.py no longer says "cannot fetch": update engine.failure_kind')+ self.assertEqual(engine.failure_kind('engine: cannot fetch aaaaaaaaaaaa from https://github.com/seedds/nxnative.git: Could not resolve host\n'),+ engine.ENGINE_OFFLINE)+ self.assertEqual(engine.failure_kind('0003-x.patch does not apply to the pin aaaaaaaaaaaa\n'), engine.ENGINE_SYNC)+ self.assertEqual(engine.failure_kind(''), engine.ENGINE_SYNC)++ def test_no_network_ends_in_the_offline_kind_with_the_tools_lines_in_the_log(self):+ cmd = self.tool("import sys\nprint('engine: cannot fetch abc from https://github.com/seedds/nxnative.git: Could not resolve host: github.com')\nsys.exit(2)\n")+ lines: list[str] = []+ ok, kind = engine.run_sync(cmd, str(self.r), lines.append)+ self.assertFalse(ok)+ self.assertEqual(kind, engine.ENGINE_OFFLINE)+ self.assertIn('cannot fetch', ''.join(lines))++ def test_another_stop_is_the_general_kind_and_a_working_sync_has_none(self):+ ok, kind = engine.run_sync(self.tool("import sys\nprint('boom')\nsys.exit(1)\n"), str(self.r), lambda _l: None)+ self.assertEqual((ok, kind), (False, engine.ENGINE_SYNC))+ self.assertEqual(engine.run_sync(self.tool("print('engine: ready')\n"), str(self.r), lambda _l: None), (True, None))++ def test_a_tool_that_cannot_start_is_a_general_stop(self):+ lines: list[str] = []+ ok, kind = engine.run_sync([str(self.r / 'no-such-python')], str(self.r), lines.append)+ self.assertEqual((ok, kind), (False, engine.ENGINE_SYNC))+ self.assertTrue(lines)++if __name__ == '__main__':unittest.main()diff --git a/frontend/Sources/NSPortBuilder/BuildFailure.swift b/frontend/Sources/NSPortBuilder/BuildFailure.swiftindex d82723c6..e5c06b0b 100644--- a/frontend/Sources/NSPortBuilder/BuildFailure.swift+++ b/frontend/Sources/NSPortBuilder/BuildFailure.swift@@ -13,6 +13,8 @@ enum BuildFailureKind: String, CaseIterable {/// The build folder is in iCloud Drive or another cloud folder (CloudFolder.swift): the launcher stops before the build, and the/// codesign line of xcodebuild is the same stop for a build that got past that check.case cloudFolder+ /// The engine's online sync (tools/engine.py sync, Engine.swift): no network or GitHub unreachable, or any other stop of it.+ case engineOffline, engineSynccase unknown/// The script's override for this stop, offered as "Build anyway". Only these three have one that the launcherdiff --git a/frontend/Sources/NSPortBuilder/BuildFailureView.swift b/frontend/Sources/NSPortBuilder/BuildFailureView.swiftindex 56e13772..4ca1e3c0 100644--- a/frontend/Sources/NSPortBuilder/BuildFailureView.swift+++ b/frontend/Sources/NSPortBuilder/BuildFailureView.swift@@ -4,9 +4,16 @@ import SwiftUI/// button that does it (a dependency's own install command, or "Build anyway" for the three stops that have an override).struct BuildFailureCard: View {@ObservedObject var m: BuildModel+ /// The failure to show: the build's (`m.failure`) unless the caller passes another one, such as the engine sync's.+ var failure: BuildFailure?++ init(m: BuildModel, failure: BuildFailure? = nil) {+ self.m = m+ self.failure = failure+ }var body: some View {- if let f = m.failure {+ if let f = failure ?? m.failure {VStack(alignment: .leading, spacing: 10) {Text(m.t("fail.section")).font(.manrope(15, .semibold)).foregroundStyle(.secondary).padding(.leading, 2)VStack(alignment: .leading, spacing: 8) {@@ -53,6 +60,8 @@ struct BuildFailureCard: View {if BuildModel.installedXcode() != nil { fix(kind, "fail.openXcode") }case .deviceTransfer:fix(kind, "fail.retry")+ case .engineOffline, .engineSync:+ Button(m.t("fail.retry")) { m.retryEngineSync() }.disabled(m.engineSyncing)default: EmptyView()}if kind.overrideFlag != nil {@@ -72,3 +81,24 @@ struct BuildFailureCard: View {}}}++/// Above every page of the launcher while the engine is fetched and patched (tools/engine.py sync, run on the first start and after+/// updates), and its failure row when that stops: what happened, what to do, and Try again.+struct EngineSyncBanner: View {+ @ObservedObject var m: BuildModel++ var body: some View {+ if m.engineSyncing {+ HStack(spacing: 10) {+ ProgressView().controlSize(.small)+ Text(m.t("engine.syncing")).font(.manrope(13)).foregroundStyle(LauncherPalette.building)+ .fixedSize(horizontal: false, vertical: true)+ Spacer(minLength: 0)+ }+ .padding(.horizontal, 24).padding(.vertical, 10)+ .accessibilityIdentifier("engine.syncing")+ } else if let f = m.engineFailure {+ BuildFailureCard(m: m, failure: f).padding(.horizontal, 24).padding(.vertical, 10)+ }+ }+}diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swiftindex 730d0ae0..c804cb77 100644--- a/frontend/Sources/NSPortBuilder/ContentView.swift+++ b/frontend/Sources/NSPortBuilder/ContentView.swift@@ -623,27 +623,45 @@ final class BuildModel: ObservableObject {/// What waits for the running `tools/engine.py sync` (nil: none runs), and whether another one is due when it ends.private var engineSyncWaiting: [(Bool) -> Void]?private var engineSyncAgain = false+ /// A sync runs: the launcher shows a status line with a spinner (EngineSyncBanner).+ @Published var engineSyncing = false+ /// How the last sync stopped (no network or GitHub unreachable, or another stop), as a failure row with a retry button. nil: none.+ @Published var engineFailure: BuildFailure?/// `tools/engine.py sync` when engine/ is stale (#214, Engine.swift): at launch, after a clone, a pull or an adoption, and before a- /// build that has no other engine. A no-op for a checkout from before #214 or a current engine/. `then(ok)` runs on the main queue.+ /// build that has no other engine. A release app carries no engine, so the first start downloads it here. A no-op for a checkout+ /// from before #214 or a current engine/. `then(ok)` runs on the main queue.func syncEngine(then: ((Bool) -> Void)? = nil) {if engineSyncWaiting != nil { engineSyncAgain = true; if let then { engineSyncWaiting?.append(then) }; return }- guard EngineLayout.isStale(repoPath) else { then?(true); return }+ guard EngineLayout.isStale(repoPath) else { engineFailure = nil; then?(true); return }engineSyncWaiting = then.map { [$0] } ?? []+ engineSyncing = true; engineFailure = nillet repo = repoPath, chosen = pythonPathappend("$ python3 tools/engine.py sync\n")+ var tail = "" // what failureKind reads when the sync stops (only touched on the main queue)DispatchQueue.global().async {let py = chosen.isEmpty ? Self.findPython().path : chosen- let ok = EngineLayout.runSync(repo: repo, python: py) { line in DispatchQueue.main.async { self.append(line + "\n") } }+ let ok = EngineLayout.runSync(repo: repo, python: py) { line in+ DispatchQueue.main.async { self.append(line + "\n"); tail = String((tail + line + "\n").suffix(4000)) }+ }DispatchQueue.main.async {let waiting = self.engineSyncWaiting ?? [], again = self.engineSyncAgain && okself.engineSyncWaiting = nil; self.engineSyncAgain = false+ self.engineSyncing = false+ self.engineFailure = ok ? nil : BuildFailure(kind: EngineLayout.failureKind(tail), gameName: nil)if again { self.syncEngine { ok in waiting.forEach { $0(ok) } } } else { waiting.forEach { $0(ok) } }self.objectWillChange.send() // repoOK and the engine's paths may have changed}}}+ /// The failure row's Try again: clears the row and runs the sync again.+ func retryEngineSync() {+ guard !engineSyncing else { return }+ engineFailure = nil+ syncEngine()+ }+// ---- App self-update (GitHub Releases) ----// The rules (what is verified, which copies replace themselves, never during a build) are in AppUpdate.swift.diff --git a/frontend/Sources/NSPortBuilder/Engine.swift b/frontend/Sources/NSPortBuilder/Engine.swiftindex a252d7c5..bbeae806 100644--- a/frontend/Sources/NSPortBuilder/Engine.swift+++ b/frontend/Sources/NSPortBuilder/Engine.swift@@ -12,8 +12,8 @@ import Foundation/// - else `engine/` as it is (stale or missing: the build syncs it first).////// `stampKey` is tools/engine.py's digest of the pin and the series, compared with the stamp sync wrote into engine/.git, so the-/// launcher tells a stale engine without starting Python. A release app carries the synced engine as `Resources/engine.git`-/// (build-mac-app.yml), the seed sync fetches from before it goes to the network.+/// launcher tells a stale engine without starting Python. A release app carries no engine: the launcher runs the sync on the first+/// start and after updates, which downloads it from GitHub (about 80 MB), and shows a failure row when that does not work.enum EngineLayout {/// The file that tells an engine tree (BuildModel.isRepo always looked for it).static let marker = "dm/tools/nx_extract/Program.cs"@@ -91,15 +91,15 @@ enum EngineLayout {hasEngineTool(repo) && isStale(repo) && !FileManager.default.fileExists(atPath: repo + "/" + marker)}- /// The engine a release app carries (build-mac-app.yml), when this is such an app.- static func seed(in resources: URL? = BundledTools.resources) -> String? {- guard let dir = resources?.appendingPathComponent("engine.git"), FileManager.default.fileExists(atPath: dir.path + "/HEAD") else { return nil }- return dir.path+ /// `python tools/engine.py sync`+ static func syncArguments(repo: String, python: String) -> [String] {+ [python, repo + "/tools/engine.py", "sync"]}- /// `python tools/engine.py [--seed <the app's engine.git>] sync`- static func syncArguments(repo: String, python: String, seed: String? = EngineLayout.seed()) -> [String] {- [python, repo + "/tools/engine.py"] + (seed.map { ["--seed", $0] } ?? []) + ["sync"]+ /// What a failed sync was, from its output: the fetch of the pinned commit (no network, GitHub unreachable, a proxy) says+ /// "cannot fetch" (tools/engine.py), anything else is a sync that could not build the engine.+ static func failureKind(_ log: String) -> BuildFailureKind {+ log.contains("cannot fetch ") ? .engineOffline : .engineSync}/// Run the sync and stream its lines (blocking: call it off the main thread). git comes from the system's or Homebrew's PATH.diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swiftindex f2b48839..11bc894e 100644--- a/frontend/Sources/NSPortBuilder/LauncherView.swift+++ b/frontend/Sources/NSPortBuilder/LauncherView.swift@@ -127,6 +127,7 @@ struct ContentView: View {VStack(spacing: 0) {topBarDivider().opacity(0.3)+ EngineSyncBanner(m: m)if page == .library {libraryPage} else {diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swiftindex 22354811..e3306284 100644--- a/frontend/Sources/NSPortBuilder/Localization.swift+++ b/frontend/Sources/NSPortBuilder/Localization.swift@@ -959,6 +959,14 @@ enum L10n {"fail.showFolder": ("显示文件夹", "Show folder"),"fail.openXcode": ("打开 Xcode", "Open Xcode"),"fail.retry": ("重试", "Try again"),+ "engine.syncing": ("正在从 GitHub 获取引擎(约 80 MB)。首次启动和更新后会运行一次,需要一两分钟。",+ "Fetching the engine from GitHub (about 80 MB). This runs on the first start and after updates and takes a minute or two."),+ "fail.engineOffline.what": ("无法从 GitHub 下载引擎。", "The engine could not be downloaded from GitHub."),+ "fail.engineOffline.next": ("请检查网络连接,并确认可以访问 github.com,然后点「重试」。没有引擎就无法构建游戏。",+ "Check your internet connection and that github.com can be reached, then press Try again. Games cannot be built without the engine."),+ "fail.engineSync.what": ("引擎准备失败。", "The engine could not be prepared."),+ "fail.engineSync.next": ("请点「重试」。原因见日志。如果一直失败,请用「复制诊断信息」连同日志一起反馈。",+ "Press Try again. The log shows the reason. If it keeps failing, report it with Copy diagnostics and the log."),"dep.metal.other": ("%@(测试用的是 %@)","%@ (tested: %@)"),"dep.fix.metalPin": ("这不是着色器测试时用的 Metal 编译器。使用 NVN 的游戏会在着色器步骤前停下。请安装 Xcode 27.1(macOS 26.6 或更新)和它的 Metal 工具链。",@@ -1767,6 +1775,11 @@ enum L10n {"fail.showFolder": "Visa mapp","fail.openXcode": "Öppna Xcode","fail.retry": "Försök igen",+ "engine.syncing": "Hämtar motorn från GitHub (cirka 80 MB). Det körs vid första starten och efter uppdateringar och tar en till två minuter.",+ "fail.engineOffline.what": "Det gick inte att hämta motorn från GitHub.",+ "fail.engineOffline.next": "Kontrollera internetanslutningen och att github.com kan nås. Tryck sedan på Försök igen. Spel kan inte byggas utan motorn.",+ "fail.engineSync.what": "Det gick inte att förbereda motorn.",+ "fail.engineSync.next": "Tryck på Försök igen. Loggen visar orsaken. Om det fortsätter att misslyckas, rapportera det med Kopiera diagnostik och loggen.",]/// German translations, an overlay like Swedish: informal "du", Apple's German terms for systemdiff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swiftindex a44f43cf..852842e8 100644--- a/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureRowsTests.swift@@ -116,7 +116,7 @@ final class BuildFailureRowsTests: XCTestCase {}func testTheNewRowsAreInAllThreeLanguagesWithoutSemicolonsOrTheProductName() {- var keys = ["fail.showFolder", "fail.openXcode", "fail.retry", "fail.keys.button", "fail.driveMissing.whatNamed", "fail.diskFull.whatNeeds", "fail.cloudFolder.button"]+ var keys = ["fail.showFolder", "fail.openXcode", "fail.retry", "fail.keys.button", "fail.driveMissing.whatNamed", "fail.diskFull.whatNeeds", "fail.cloudFolder.button", "engine.syncing"]let kinds = BuildFailureTests.stateKinds.union([.keys, .severalGames, .noTitleID, .diskFull, .cloudFolder])for k in BuildFailureKind.allCases where kinds.contains(k) { keys += [k.whatKey, k.nextKey] }for key in keys {diff --git a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swiftindex 50cc53dd..de0bb347 100644--- a/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift+++ b/frontend/Tests/NSPortBuilderTests/BuildFailureTests.swift@@ -35,7 +35,7 @@ final class BuildFailureTests: XCTestCase {}/// The rows that no log line sets: the launcher's own state (a drive, a team) or the step that failed (the install).- static let stateKinds: Set<BuildFailureKind> = [.driveMissing, .teamTaken, .noSigningAccount, .deviceTransfer]+ static let stateKinds: Set<BuildFailureKind> = [.driveMissing, .teamTaken, .noSigningAccount, .deviceTransfer, .engineOffline, .engineSync]/// A sync of scripts/ or dm/ that rewords a message must fail here, not turn a hint into the raw last line.func testTheVendoredScriptsStillSayWhatThePatternsExpect() throws {diff --git a/frontend/Tests/NSPortBuilderTests/EngineLayoutTests.swift b/frontend/Tests/NSPortBuilderTests/EngineLayoutTests.swiftindex 12bd6551..e821b2a8 100644--- a/frontend/Tests/NSPortBuilderTests/EngineLayoutTests.swift+++ b/frontend/Tests/NSPortBuilderTests/EngineLayoutTests.swift@@ -85,10 +85,79 @@ final class EngineLayoutTests: XCTestCase {XCTAssertFalse(EngineLayout.needsSyncBeforeBuild(repo))}- func testTheSyncCommandPassesTheAppsSeed() {- XCTAssertEqual(EngineLayout.syncArguments(repo: "/c", python: "py", seed: nil), ["py", "/c/tools/engine.py", "sync"])- XCTAssertEqual(EngineLayout.syncArguments(repo: "/c", python: "py", seed: "/A.app/Contents/Resources/engine.git"),- ["py", "/c/tools/engine.py", "--seed", "/A.app/Contents/Resources/engine.git", "sync"])+ func testTheSyncCommandHasNoSeed() {+ XCTAssertEqual(EngineLayout.syncArguments(repo: "/c", python: "py"), ["py", "/c/tools/engine.py", "sync"])+ }++ // ---- the online sync of a release app (no engine in the bundle)++ private var toolSource: String {+ let tools = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ .deletingLastPathComponent().appendingPathComponent("tools/engine.py")+ return (try? String(contentsOf: tools, encoding: .utf8)) ?? ""+ }++ func testAFailedFetchIsTheOfflineRowAndAnyOtherStopIsTheGeneralOne() {+ XCTAssertTrue(toolSource.contains("cannot fetch "), "tools/engine.py no longer says \"cannot fetch\": update EngineLayout.failureKind")+ let offline = "engine: cannot fetch aaaaaaaaaaaa from https://github.com/seedds/nxnative.git: fatal: unable to access: Could not resolve host\n"+ XCTAssertEqual(EngineLayout.failureKind(offline), .engineOffline)+ XCTAssertEqual(EngineLayout.failureKind("0003-x.patch does not apply to the pin aaaaaaaaaaaa\n"), .engineSync)+ XCTAssertEqual(EngineLayout.failureKind(""), .engineSync)+ }++ /// A checkout whose tools/engine.py is `script` (a stand-in for the real one) and a model on it.+ private func model(engineScript script: String) throws -> BuildModel {+ try newLayout()+ try touch("tools/engine.py", script)+ let m = BuildModel()+ m.repoPath = repo+ m.pythonPath = "/usr/bin/python3"+ return m+ }++ private func waitForSync(_ m: BuildModel, file: StaticString = #filePath, line: UInt = #line) {+ let deadline = Date().addingTimeInterval(20)+ while m.engineSyncing && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.05)) }+ XCTAssertFalse(m.engineSyncing, "the sync did not end", file: file, line: line)+ }++ func testNoNetworkShowsTheStatusThenTheOfflineRowAndRetryRunsTheSyncAgain() throws {+ let counter = root.appendingPathComponent("runs.txt").path+ let m = try model(engineScript: """+ import sys+ open(\(String(reflecting: counter)), 'a').write('x')+ print('engine: cannot fetch aaaaaaaaaaaa from https://github.com/seedds/nxnative.git: Could not resolve host: github.com')+ sys.exit(2)+ """)+ XCTAssertNil(m.engineFailure)+ m.syncEngine()+ XCTAssertTrue(m.engineSyncing, "the status line shows while the engine is fetched")+ waitForSync(m)+ XCTAssertEqual(m.engineFailure?.kind, .engineOffline)+ XCTAssertTrue(m.logTail.contains("cannot fetch"), "the log has the tool's line")+ m.retryEngineSync()+ XCTAssertNil(m.engineFailure, "Try again clears the row")+ XCTAssertTrue(m.engineSyncing)+ waitForSync(m)+ XCTAssertEqual(m.engineFailure?.kind, .engineOffline)+ XCTAssertEqual(try String(contentsOfFile: counter, encoding: .utf8), "xx", "the retry ran the tool again")+ }++ func testASyncThatWorksLeavesNoRow() throws {+ let m = try model(engineScript: "print('engine: ready')\n")+ m.engineFailure = BuildFailure(kind: .engineOffline, gameName: nil)+ m.syncEngine()+ waitForSync(m)+ XCTAssertNil(m.engineFailure)+ }++ func testOfflineRowsHaveARetryButtonAndTheStatusLineHasText() {+ for k in [BuildFailureKind.engineOffline, .engineSync] {+ XCTAssertNotNil(L10n.table[k.whatKey]); XCTAssertNotNil(L10n.table[k.nextKey])+ }+ let en = L10n.table["fail.engineOffline.next"]?.en ?? ""+ for w in ["internet connection", "github.com", "Try again"] { XCTAssertTrue(en.contains(w), w) }+ XCTAssertNotNil(L10n.table["engine.syncing"]); XCTAssertNotNil(L10n.sv["engine.syncing"])}/// The launcher's key and tools/engine.py's agree, so a sync's stamp reads as current here.diff --git a/patches/README.md b/patches/README.mdindex 5e19013e..3462880f 100644--- a/patches/README.md+++ b/patches/README.md@@ -16,7 +16,7 @@> ```>> `sync` never throws away work in `engine/`: with commits or changes there it stops and names `export` (or `--force`, which keeps-> them on a backup branch). Offline, it says so. A release app carries the pinned commit (`Resources/engine.git`) as a seed.+> them on a backup branch). Offline, it says so and names the fix. A release app carries no engine: the launcher runs `sync` on the first start and after updates, which downloads about 80 MB from GitHub.`dm/`, `scripts/`, `docs/`, `ref/` and `AGENTS.md` are not edited by hand. They are[seedds/nxnative](https://github.com/seedds/nxnative) at the commit in `../.upstream-ref`, plus the patches in this folderdiff --git a/tools/engine.py b/tools/engine.pyindex 26665d4f..71313782 100755--- a/tools/engine.py+++ b/tools/engine.py@@ -9,7 +9,7 @@ dm/fork_patches.txt). A stamp in engine/.git records the pin and the series it wneither changed.Subcommands (Python 3.9+, stdlib and git):- sync [--seed DIR] [--force] make engine/ match the pin and the series. A no-op when the stamp matches. Refuses to throw+ sync [--force] make engine/ match the pin and the series. A no-op when the stamp matches. Refuses to throwaway commits or changes made in engine/ (export them first, or --force keeps them on a branch)stale exit 0 when engine/ matches the pin and the series, 1 when a sync is needed (prints why)hook for an agent's session start (.claude/settings.json): sync when stale, print one line, always exit 0@@ -23,10 +23,9 @@ Subcommands (Python 3.9+, stdlib and git):patches/ and .upstream-ref (the committed tree is tools/patches.py bump's job while it exists)refresh WORKTREE --to SHA after a conflicting bump was resolved by hand in WORKTREE: its commits become the series-The upstream URL is https://github.com/seedds/nxnative.git, or $NX2APPLE_ENGINE_URL. A seed (--seed or $NX2APPLE_ENGINE_SEED)-is a local git repository that holds the pin, such as the engine.git a release app carries: sync fetches from it first and-needs the network only for what the seed lacks. Scratch worktrees go to $PATCHES_TMP (or --tmp), else the system's temporary-folder.+The upstream URL is https://github.com/seedds/nxnative.git, or $NX2APPLE_ENGINE_URL (a mirror, or a local clone that holds the+pin, which needs no network). A release app carries no engine: the launcher runs `sync` on the first start and after updates.+Scratch worktrees go to $PATCHES_TMP (or --tmp), else the system's temporary folder."""import argparseimport contextlib@@ -133,22 +132,16 @@ def have_commit(eng, sha):return git('cat-file', '-e', f'{sha}^{{commit}}', cwd=eng, check=False).returncode == 0-def fetch(eng, sha, seed=None, url=None):- """Bring the commit into engine/: from the seed first (no network), then from upstream, one commit deep."""+def fetch(eng, sha, url=None):+ """Bring the commit into engine/ from upstream, one commit deep."""if have_commit(eng, sha): return 'already here'- seed = seed or os.environ.get('NX2APPLE_ENGINE_SEED')- if seed and Path(seed).exists():- git('fetch', '--quiet', '--no-tags', '--depth', '1', str(Path(seed).resolve()), sha, cwd=eng, check=False)- if have_commit(eng, sha): return f'from the seed {seed}'- # The seed is an older pin: fetch it anyway, so the shallow fetch below can send only what changed since.- git('fetch', '--quiet', '--no-tags', '--depth', '1', str(Path(seed).resolve()), 'HEAD', cwd=eng, check=False)url = url or os.environ.get('NX2APPLE_ENGINE_URL') or UPSTREAM_URLr = git('fetch', '--quiet', '--no-tags', '--depth', '1', url, sha, cwd=eng, check=False)if r.returncode or not have_commit(eng, sha):err = (r.stderr or '').strip().splitlines()raise Fail(f'cannot fetch {sha[:12]} from {url}: {err[-1] if err else "unknown error"}\n'- f' Offline? Connect and run `python3 tools/engine.py sync` again, or point --seed at a local copy that has the commit '- f'(a release app carries one: NX2Apple.app/Contents/Resources/engine.git). Behind a mirror: set NX2APPLE_ENGINE_URL.')+ f' Offline or GitHub unreachable? Check the connection and run `python3 tools/engine.py sync` again. '+ f'Behind a mirror or with a local clone that has the commit: set NX2APPLE_ENGINE_URL.')return f'from {url}'@@ -207,7 +200,7 @@ def cmd_sync(a):git('branch', '--force', keep, 'HEAD', cwd=eng, check=False)say(f'engine: kept the previous HEAD on branch {keep} (and uncommitted changes in `git -C engine stash list`)')sha = pin(root)- got = fetch(eng, sha, a.seed)+ got = fetch(eng, sha)say(f'engine: building {sha[:12]} + {len(patches)} patches ({reason or "forced"}; upstream commit {got})')applied, _ = build(root, eng, patches, sha)write_stamp(eng, root, head(eng))@@ -324,7 +317,7 @@ def cmd_check(a):if stray: bad.append('patch files not in patches/series: ' + ', '.join(stray))eng = scratch_root(root)sha = pin(root)- fetch(eng, sha, a.seed)+ fetch(eng, sha)# The chain rule reads AGENTS.md at the pin plus the series; the pin's own copy is close enough for the globs.rules = eng if (eng / 'AGENTS.md').is_file() else rootfor p in patches:@@ -360,7 +353,7 @@ def cmd_check(a):# ---- bump, refresh -----def resolve_target(eng, to, seed=None):+def resolve_target(eng, to):if re.fullmatch(r'[0-9a-f]{40}', to): return tourl = os.environ.get('NX2APPLE_ENGINE_URL') or UPSTREAM_URLr = git('ls-remote', url, to, cwd=eng, check=False)@@ -374,7 +367,7 @@ def cmd_bump(a):patches = P.load(root)eng = scratch_root(root)old = pin(root)- fetch(eng, old, a.seed) # the old pin's blobs let `git am -3` merge three ways+ fetch(eng, old) # the old pin's blobs let `git am -3` merge three wayssha = resolve_target(eng, a.to)fetch(eng, sha)s = P.Scratch(eng, sha, a.tmp, keep=not a.dry)@@ -423,7 +416,6 @@ def main(argv=None):ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)ap.add_argument('--repo', default=str(REPO), help="the checkout (default: this script's)")ap.add_argument('--tmp', help='folder for scratch worktrees (default $PATCHES_TMP, else the system temporary folder)')- ap.add_argument('--seed', help='a local git repository holding the pin, tried before the network (default $NX2APPLE_ENGINE_SEED)')ap.add_argument('-q', '--quiet', action='store_true', help='print nothing when there is nothing to do')sub = ap.add_subparsers(dest='cmd', required=True)s = sub.add_parser('sync'); s.add_argument('--force', action='store_true', help='rebuild even when up to date; local work goes to a backup branch'); s.set_defaults(f=cmd_sync)diff --git a/tools/tests/test_engine.py b/tools/tests/test_engine.pyindex 16402766..bdeac34f 100644--- a/tools/tests/test_engine.py+++ b/tools/tests/test_engine.py@@ -19,7 +19,6 @@ E = importlib.import_module('engine')BASE_ENV = dict(os.environ, GIT_AUTHOR_NAME='t', GIT_AUTHOR_EMAIL='[email protected]', GIT_COMMITTER_NAME='t', GIT_COMMITTER_EMAIL='[email protected]',GIT_CONFIG_GLOBAL='/dev/null', GIT_CONFIG_SYSTEM='/dev/null')-BASE_ENV.pop('NX2APPLE_ENGINE_SEED', None)HEADER = 'Upstream-Status: forwarded seedds/nxnative#475\nReason: the fork needs line 2\nIssue: LNPANDY/NX2Apple#1\n'@@ -131,16 +130,21 @@ class Sync(Fixture):self.assertIn('0002-conflict.patch does not apply', out); self.assertIn('a reason to show', out)self.assertFalse((self.eng / '.git' / 'rebase-apply').exists())- def test_offline_names_the_fix_and_a_seed_needs_no_network(self):+ def test_offline_names_the_fix_and_a_local_clone_needs_no_network(self):offline = dict(self.env, NX2APPLE_ENGINE_URL=str(self.tmp / 'nowhere'))out = self.tool('sync', expect=2, env=offline)- self.assertIn('cannot fetch', out); self.assertIn('Offline?', out); self.assertIn('--seed', out)- seed = self.tmp / 'seed.git'- git(self.tmp, 'clone', '-q', '--bare', '--depth', '1', 'file://' + str(self.up), str(seed))- out = self.tool('--seed', str(seed), 'sync', env=offline)- self.assertIn('from the seed', out)+ self.assertIn('cannot fetch', out); self.assertIn('unreachable', out); self.assertIn('Check the connection', out)+ self.assertNotIn('--seed', out); self.assertFalse((self.eng / '.git' / 'nx2apple-stamp').exists())+ self.tool('stale', expect=1)+ local = self.tmp / 'local.git'+ git(self.tmp, 'clone', '-q', '--bare', '--depth', '1', 'file://' + str(self.up), str(local))+ out = self.tool('sync', env=dict(self.env, NX2APPLE_ENGINE_URL=str(local)))+ self.assertIn('engine: ready', out)self.tool('stale')+ def test_the_seed_option_is_gone(self):+ self.tool('--seed', str(self.tmp), 'sync', expect=2)+class Hook(Fixture):def test_the_session_hook_syncs_and_prints_one_line(self):