From 2be661d619131e7d39370a4d4ad2a43e0ad0f8a0 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 15:33:42 +0800 Subject: [PATCH 1/2] Add opt-in Windows App SDK auto-initialization Add identity-first Python and Node entrypoints without changing explicit initialization or ordinary imports. Use a shared native identity probe that does not activate WinRT or initialize COM. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/README.md | 39 ++++ bindings/js/__test__/auto-init.e2e.cjs | 217 ++++++++++++++++++ bindings/js/package.json | 12 +- bindings/js/scripts/generate-entrypoints.mjs | 13 ++ .../js/scripts/verify-runtime-artifact.mjs | 8 + bindings/js/src/system.rs | 8 +- bindings/py/README.md | 31 +++ bindings/py/python/dynwinrt/auto_init.py | 19 ++ bindings/py/src/runtime.rs | 5 +- bindings/py/tests/test_typing_package.py | 14 ++ bindings/py/tests/test_winappsdk.py | 127 +++++++++- crates/dynwinrt/src/lib.rs | 4 +- crates/dynwinrt/src/winapp.rs | 35 ++- eng/release/RELEASE_NOTES.md | 4 + .../python/test_python_runtime_wheel.ps1 | 3 +- eng/release/python/verify_python_release.py | 1 + 16 files changed, 523 insertions(+), 17 deletions(-) create mode 100644 bindings/js/__test__/auto-init.e2e.cjs create mode 100644 bindings/py/python/dynwinrt/auto_init.py diff --git a/bindings/js/README.md b/bindings/js/README.md index 5c4fbc8a..c076b8db 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -172,6 +172,45 @@ and redistribution as part of a qualifying application remain the producer's responsibility. Without the generation options, existing Windows SDK-only output and calls remain unchanged. +### Opt-in automatic Bootstrap + +`@microsoft/dynwinrt/auto-init` checks Windows package identity before doing any +Bootstrap work. With identity it skips configuration discovery and Bootstrap DLL +lookup, reading, loading, and initialization. Without identity it calls the +existing no-argument `initWinappsdk()`, using the configuration registered by a +previously imported generated package. Configuration and native errors propagate. + +CommonJS preserves the preparation order: + +```js +const { roInitialize } = require('@microsoft/dynwinrt'); +roInitialize(0); // The application chooses STA here. +require('@winapp/bindings'); // Registers the generated Bootstrap configuration. +require('@microsoft/dynwinrt/auto-init'); +// Create and run the application here. +``` + +For ESM, use dynamic import after apartment/configuration preparation; static +imports run before the module body: + +```js +import { roInitialize } from '@microsoft/dynwinrt'; +roInitialize(0); +await import('@winapp/bindings'); +await import('@microsoft/dynwinrt/auto-init'); +// Create and run the application here. +``` + +With package identity, no generated configuration is needed just to skip. +The skip does not validate SDK deployment or readiness. Ordinary runtime and +generated-package imports remain passive (configuration registration is unchanged). +Explicit `initWinappsdk(...)`, including its no-argument form, never skips because +of identity. CJS and ESM share the same entry point, native runtime and registered +configuration; normal module caching applies, not initialization on every import +or a custom retry mechanism. Neither initializer chooses STA/MTA, initializes COM, +creates threads/message loops, or forces an SDK reload/version switch. The +application remains responsible for apartment and runtime lifetimes. + ### Standalone WinRT interface implementations Metadata-generated standalone WinRT interfaces expose `implementation(handlers)` diff --git a/bindings/js/__test__/auto-init.e2e.cjs b/bindings/js/__test__/auto-init.e2e.cjs new file mode 100644 index 00000000..85e1398f --- /dev/null +++ b/bindings/js/__test__/auto-init.e2e.cjs @@ -0,0 +1,217 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +'use strict' + +const assert = require('node:assert/strict') +const { spawnSync } = require('node:child_process') +const { mkdtempSync, writeFileSync, rmSync } = require('node:fs') +const { tmpdir } = require('node:os') +const { join, resolve } = require('node:path') +const { before, after, test } = require('node:test') + +const source = resolve(__dirname, '..') +const consumer = mkdtempSync(join(tmpdir(), 'dynwinrt-auto-init-')) +const packageRoot = join(consumer, 'node_modules', '@microsoft', 'dynwinrt') + +function run(args, cwd = consumer, env = process.env) { + const child = spawnSync(process.execPath, args, { cwd, env, encoding: 'utf8', timeout: 120_000 }) + assert.equal(child.status, 0, `${child.error ?? ''}\n${child.stdout}\n${child.stderr}`) + return child.stdout +} + +before(() => { + assert.ok(process.env.npm_execpath, 'Run via npm run test:winappsdk to test the packed package') + const packed = JSON.parse( + run([process.env.npm_execpath, 'pack', '--json', '--ignore-scripts', '--pack-destination', consumer], source), + ) + const files = packed[0].files.map((file) => file.path) + assert.ok(files.includes('dist/auto-init.js')) + assert.ok(files.includes('dist/auto-init.d.ts')) + writeFileSync(join(consumer, 'package.json'), '{"private":true}') + run([ + process.env.npm_execpath, + 'install', + '--ignore-scripts', + '--no-audit', + '--no-fund', + '--package-lock=false', + '--offline', + join(consumer, packed[0].filename), + ]) +}) + +after(() => rmSync(consumer, { recursive: true, force: true })) + +async function exercise(scenario, mode) { + const assert = require('node:assert/strict') + const { createHash } = require('node:crypto') + const { mkdirSync, writeFileSync } = require('node:fs') + const { join, basename } = require('node:path') + const environment = 'WINAPPSDK_BOOTSTRAP_DLL_PATH' + delete process.env[environment] + const native = require('./node_modules/@microsoft/dynwinrt/dist/index.js') + const calls = [] + const failure = new Error('original native failure') + const realNative = ['passive', 'bad-dll'].includes(scenario) + if (!realNative) { + native.initWinappsdk = (...args) => { + calls.push(args) + if (scenario === 'native-error') throw failure + } + } + const runtime = require('@microsoft/dynwinrt') + const { DynWin32, DynWin32Function } = require('@microsoft/dynwinrt/win32/unsafe') + const apartmentType = DynWin32Function.bind({ + dll: 'ole32.dll', + entryPoint: 'CoGetApartmentType', + parameters: [ + { type: 'i32', direction: 'out' }, + { type: 'i32', direction: 'out' }, + ], + returnType: 'i32', + }) + const apartmentStatus = () => DynWin32.toNumber(apartmentType.invoke([]).returnValue) + assert.equal(apartmentStatus(), -2147221008) // CO_E_NOTINITIALIZED + const esmRuntime = await import('@microsoft/dynwinrt') + assert.equal(runtime.initWinappsdk, esmRuntime.initWinappsdk) + const { __registerWinAppSdkConfig: register } = await import('@microsoft/dynwinrt/winappsdk') + assert.deepEqual(calls, []) + if ('excludeNetwork' in process.report) process.report.excludeNetwork = true + const bootstrapLoaded = () => + process.report + .getReport() + .sharedObjects.some((path) => basename(path).toLowerCase() === 'microsoft.windowsappruntime.bootstrap.dll') + assert.equal(bootstrapLoaded(), false) + assert.equal(typeof runtime.hasPackageIdentity(), 'boolean') + assert.equal(apartmentStatus(), -2147221008) + if (scenario === 'passive') return + + const identity = scenario.startsWith('identity') + let probes = 0 + runtime.hasPackageIdentity = () => { + probes++ + if (scenario === 'probe-error') throw failure + return identity + } + const dll = join(process.cwd(), '_native', 'winappsdk', process.arch, 'Microsoft.WindowsAppRuntime.Bootstrap.dll') + const bytes = Buffer.from('not a native library') + mkdirSync(join(dll, '..'), { recursive: true }) + writeFileSync(dll, bytes) + const config = { + schema_version: 1, + major: 2, + minor: 5, + dlls: { [process.arch]: createHash('sha256').update(bytes).digest('hex') }, + } + if (!['missing', 'identity', 'probe-error'].includes(scenario)) { + register(join(process.cwd(), '_winappsdk.cjs'), config) + } + if (['conflict', 'identity-conflict'].includes(scenario)) { + register(join(process.cwd(), 'second.cjs'), { ...config, minor: 6 }) + } + if (identity || scenario === 'path') process.env[environment] = join(process.cwd(), 'missing.dll') + assert.deepEqual(calls, []) // Generated registration remains passive. + + const load = async () => + mode === 'cjs' ? require('@microsoft/dynwinrt/auto-init') : import('@microsoft/dynwinrt/auto-init') + let nativeFailure + if (scenario === 'bad-dll') { + assert.throws( + () => native.initWinappsdk(2, 5, dll), + (error) => { + nativeFailure = error + return true + }, + ) + } + if (['missing', 'conflict', 'path', 'bad-dll', 'native-error', 'probe-error'].includes(scenario)) { + const expected = { + missing: /No generated Windows App SDK configuration/, + conflict: /Conflicting generated Windows App SDK configurations/, + path: /ENOENT/, + 'bad-dll': (error) => error.message === nativeFailure.message, + 'native-error': (error) => error === failure, + 'probe-error': (error) => error === failure, + }[scenario] + await assert.rejects(load, expected) + assert.equal(calls.length, scenario === 'native-error' ? 1 : 0) + assert.equal(bootstrapLoaded(), false) + return + } + await load() + await load() + const commonjs = require('@microsoft/dynwinrt/auto-init') + const esm = await import('@microsoft/dynwinrt/auto-init') + assert.equal(esm.default, commonjs) + assert.deepEqual(Object.keys(commonjs), []) + assert.equal(probes, 1) + assert.equal(bootstrapLoaded(), false) + if (identity) { + assert.deepEqual(calls, []) + assert.throws(() => runtime.initWinappsdk(), /No generated|Conflicting|ENOENT/) + } else { + assert.deepEqual(calls, [[2, 5, dll]]) + runtime.initWinappsdk() + assert.equal(calls.length, 2) + } + runtime.initWinappsdk(2, 5) + runtime.initWinappsdk(2, 5, dll) + assert.deepEqual(calls.slice(-2), [ + [2, 5], + [2, 5, dll], + ]) + assert.equal(probes, 1) // Explicit initialization never queries identity. +} + +for (const mode of ['cjs', 'esm']) { + for (const scenario of [ + 'passive', + 'identity', + 'identity-conflict', + 'initialize', + 'missing', + 'conflict', + 'path', + 'bad-dll', + 'native-error', + 'probe-error', + ]) { + test(`installed ${mode} auto-init: ${scenario}`, () => { + run([ + '--eval', + `(${exercise.toString()})(${JSON.stringify(scenario)}, ${JSON.stringify(mode)}) + .catch(error => { console.error(error); process.exitCode = 1 })`, + ]) + }) + } +} + +test('packed auto-init has no public API and resolves in CJS and ESM TypeScript', () => { + const manifest = require(join(packageRoot, 'package.json')) + assert.equal(manifest.sideEffects, true) + assert.equal(manifest.exports['./auto-init'].require, manifest.exports['./auto-init'].import) + for (const extension of ['cts', 'mts']) { + writeFileSync( + join(consumer, `consumer.${extension}`), + ` +import '@microsoft/dynwinrt/auto-init' +type AutoInit = typeof import('@microsoft/dynwinrt/auto-init') +const noExports: keyof AutoInit extends never ? true : never = true +void noExports +`, + ) + } + run([ + join(source, 'node_modules', 'typescript', 'bin', 'tsc'), + '--noEmit', + '--strict', + '--module', + 'NodeNext', + '--moduleResolution', + 'NodeNext', + '--noUncheckedSideEffectImports', + 'consumer.cts', + 'consumer.mts', + ]) +}) diff --git a/bindings/js/package.json b/bindings/js/package.json index 6ab222e1..773d9bdf 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -17,6 +17,12 @@ "require": "./dist/winappsdk-config.js", "default": "./dist/winappsdk-config.js" }, + "./auto-init": { + "types": "./dist/auto-init.d.ts", + "import": "./dist/auto-init.js", + "require": "./dist/auto-init.js", + "default": "./dist/auto-init.js" + }, "./com": { "types": "./dist/com.d.ts", "import": "./dist/com.js", @@ -51,6 +57,9 @@ }, "typesVersions": { "*": { + "auto-init": [ + "dist/auto-init.d.ts" + ], "winappsdk": [ "dist/winappsdk-config.d.ts" ], @@ -90,6 +99,7 @@ "LICENSE", "README.md" ], + "sideEffects": true, "napi": { "binaryName": "dynwinrt", "targets": [ @@ -118,7 +128,7 @@ "format:rs": "cargo fmt", "lint": "oxlint", "test": "npm run test:types && ava && npm run test:native-classes && npm run test:interface-inputs && npm run test:winappsdk", - "test:winappsdk": "node --test __test__/winappsdk-config.e2e.cjs", + "test:winappsdk": "node --test __test__/winappsdk-config.e2e.cjs __test__/auto-init.e2e.cjs", "test:interface-inputs": "node --test __test__/interface-inputs.e2e.mjs", "test:native-classes": "node --test __test__/native-class-boundary.e2e.mjs", "test:native-classes:hooks": "node --test __test__/native-class-boundary-hooks.e2e.mjs", diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index be5716aa..ca7395aa 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -515,6 +515,19 @@ writeFileSync(join(distDir, 'winappsdk-config.d.ts'), [ 'export declare function __registerWinAppSdkConfig(source: string, config: unknown): void', '', ].join('\n')) +writeFileSync(join(distDir, 'auto-init.js'), [ + '// Generated by scripts/generate-entrypoints.mjs - do not edit', + "'use strict'", + "const runtime = require('./winrt.js')", + 'if (!runtime.hasPackageIdentity()) runtime.initWinappsdk()', + '', +].join('\n')) +writeFileSync(join(distDir, 'auto-init.d.ts'), [ + '// Generated by scripts/generate-entrypoints.mjs - do not edit', + '/** Opt-in Bootstrap initialization for identityless processes; does not initialize COM. */', + 'export {}', + '', +].join('\n')) function writeFacade( name, diff --git a/bindings/js/scripts/verify-runtime-artifact.mjs b/bindings/js/scripts/verify-runtime-artifact.mjs index 83d4cb62..702754dd 100644 --- a/bindings/js/scripts/verify-runtime-artifact.mjs +++ b/bindings/js/scripts/verify-runtime-artifact.mjs @@ -42,6 +42,14 @@ function artifactFile(target) { for (const [name, target] of Object.entries(manifest.exports)) { if (name === './package.json') continue artifactFile(target.types) + if (name === './auto-init' && !modules.get('.').hasPackageIdentity()) { + // Unlike passive facades, this entry requires application configuration without identity. + const missingConfiguration = /No generated Windows App SDK configuration/ + assert.throws(() => require(artifactFile(target.require)), missingConfiguration) + await assert.rejects(import(pathToFileURL(artifactFile(target.import)).href), missingConfiguration) + console.log('Verified opt-in auto-init reports missing application configuration in CJS and ESM') + continue + } const commonjs = require(artifactFile(target.require)) const esm = await import(pathToFileURL(artifactFile(target.import)).href) for (const key of Object.keys(commonjs)) { diff --git a/bindings/js/src/system.rs b/bindings/js/src/system.rs index 57a4e975..3ee5374e 100644 --- a/bindings/js/src/system.rs +++ b/bindings/js/src/system.rs @@ -4,12 +4,8 @@ use napi_derive::napi; #[napi] -pub fn has_package_identity() -> bool { - use windows::ApplicationModel::AppInfo; - match AppInfo::Current() { - Ok(_) => true, - Err(_) => false, - } +pub fn has_package_identity() -> napi::Result { + dynwinrt::has_package_identity().map_err(|error| napi::Error::from_reason(error.to_string())) } #[napi] diff --git a/bindings/py/README.md b/bindings/py/README.md index 2a3230cb..a84c0d70 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -1029,6 +1029,37 @@ producer's responsibility. This API does not install the Runtime or silently skip initialization merely because the process has package identity. Ordinary Windows SDK-only generated bindings require none of this configuration. +### Opt-in automatic Bootstrap + +Import `dynwinrt.auto_init` on the application's chosen COM thread after preparing +its apartment: + +```python +from dynwinrt import RoApartment, projected_lifetime_scope + +with RoApartment(0): # The application chooses STA here. + import dynwinrt.auto_init + + with projected_lifetime_scope(): + # Import generated bindings and create/run the application here. + ... +``` + +The module checks Windows package identity first, without WinRT activation. With +identity it skips Bootstrap entirely: no generated configuration discovery or +Bootstrap DLL lookup, read, load, or initialization. Without identity it calls +the existing no-argument `init_winappsdk()`, so install a generated package with +Bootstrap configuration as described above; configuration and native errors +propagate unchanged. The skip does not verify SDK deployment or readiness. + +This is opt-in: ordinary `import dynwinrt` and generated-package imports remain +passive. Explicit `init_winappsdk(...)`, including its no-argument form, never +skips because of identity and still returns `WinAppSDKContext`. The automatic +module exposes no context API. Normal import caching applies, not initialization +on every import or a custom retry mechanism. Neither entry point initializes COM, +chooses STA/MTA, creates threads/message loops, or forces an SDK reload/version +switch; the application owns those lifetimes. + ## Experimental WinUI support When the required WinUI metadata is generated, `Application.create()` installs diff --git a/bindings/py/python/dynwinrt/auto_init.py b/bindings/py/python/dynwinrt/auto_init.py new file mode 100644 index 00000000..9deeac4b --- /dev/null +++ b/bindings/py/python/dynwinrt/auto_init.py @@ -0,0 +1,19 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Opt in to identity-aware Windows App SDK Bootstrap initialization. + +Import on the application's chosen COM thread after preparing its apartment. +Packaged processes skip Bootstrap, without checking Runtime deployment. Otherwise +the existing no-argument initializer discovers an installed generated SDK bundle. +Normal Python import caching applies; this module exposes no context or shutdown API. +""" + +from . import has_package_identity as _has_package_identity + +__all__: list[str] = [] + +if not _has_package_identity(): + from . import init_winappsdk as _init_winappsdk + + _init_winappsdk() diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index da94c2e8..3ea3b873 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -3915,9 +3915,8 @@ impl DynWinRtElementFactory { // ====================================================================== #[pyfunction] -pub fn has_package_identity() -> bool { - use windows::ApplicationModel::AppInfo; - AppInfo::Current().is_ok() +pub fn has_package_identity() -> PyResult { + dynwinrt::has_package_identity().map_err(map_windows_error) } /// Return the framework resources.pri path selected by init_winappsdk. diff --git a/bindings/py/tests/test_typing_package.py b/bindings/py/tests/test_typing_package.py index aafc8761..4745128e 100644 --- a/bindings/py/tests/test_typing_package.py +++ b/bindings/py/tests/test_typing_package.py @@ -3,6 +3,8 @@ from pathlib import Path import inspect +import subprocess +import sys import dynwinrt @@ -12,6 +14,18 @@ def test_wheel_contains_typing_metadata(): assert (package_dir / "__init__.pyi").is_file() assert (package_dir / "py.typed").is_file() + assert (package_dir / "auto_init.py").is_file() + + +def test_installed_auto_init_module_is_typed(tmp_path): + consumer = tmp_path / "consumer.py" + consumer.write_text("import dynwinrt.auto_init\n", encoding="utf-8") + result = subprocess.run( + [sys.executable, "-m", "mypy", "--strict", "--no-incremental", + "--cache-dir", str(tmp_path / "cache"), str(consumer)], + capture_output=True, text=True, timeout=60, + ) + assert result.returncode == 0, result.stdout + result.stderr def test_wheel_exports_async_event_scope_without_changing_native_exports(): diff --git a/bindings/py/tests/test_winappsdk.py b/bindings/py/tests/test_winappsdk.py index c5285fc6..ca2d8f2a 100644 --- a/bindings/py/tests/test_winappsdk.py +++ b/bindings/py/tests/test_winappsdk.py @@ -3,7 +3,10 @@ import copy import hashlib +import importlib from pathlib import Path +import subprocess +import sys from types import SimpleNamespace import pytest @@ -230,7 +233,7 @@ def initialize(*args, **kwargs): assert count == 2 -def test_real_native_missing_input_errors_and_return_type_contract(monkeypatch, tmp_path): +def test_real_native_missing_input_errors_and_return_type_contract(monkeypatch, tmp_path, auto_import): import ctypes monkeypatch.delenv(ENVIRONMENT, raising=False) @@ -247,6 +250,10 @@ def test_real_native_missing_input_errors_and_return_type_contract(monkeypatch, try: with pytest.raises(OSError): dynwinrt.init_winappsdk(2, 5, bootstrap_dll_path=not_a_dll) + providers(monkeypatch, bundle(tmp_path / "generated")) + monkeypatch.setattr(dynwinrt, "has_package_identity", lambda: False) + with pytest.raises(OSError): + auto_import() finally: kernel.SetErrorMode(previous) assert hasattr(dynwinrt.WinAppSDKContext, "resource_pri_path") @@ -254,3 +261,121 @@ def test_real_native_missing_input_errors_and_return_type_contract(monkeypatch, stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") assert "def init_winappsdk(*, bootstrap_dll_path:" in stub assert ") -> WinAppSDKContext:" in stub + + +@pytest.fixture +def auto_import(monkeypatch): + monkeypatch.delitem(sys.modules, "dynwinrt.auto_init", raising=False) + monkeypatch.delattr(dynwinrt, "auto_init", raising=False) + yield lambda: importlib.import_module("dynwinrt.auto_init") + sys.modules.pop("dynwinrt.auto_init", None) + if hasattr(dynwinrt, "auto_init"): + del dynwinrt.auto_init + + +def test_auto_identity_skips_before_discovery_or_dll_access( + monkeypatch, tmp_path, native_calls, auto_import +): + monkeypatch.setattr(dynwinrt, "has_package_identity", lambda: True) + monkeypatch.setenv(ENVIRONMENT, str(tmp_path / "does-not-exist.dll")) + monkeypatch.setattr(_winappsdk, "entry_points", lambda **_: pytest.fail("must not discover")) + monkeypatch.setattr(_winappsdk, "_explicit_path", lambda _: pytest.fail("must not read DLL")) + monkeypatch.setattr(_winappsdk, "_resource_path", lambda _: pytest.fail("must not read DLL")) + module = auto_import() + assert auto_import() is module + assert module.__all__ == [] + assert native_calls[0] == [] + + +def test_auto_no_identity_uses_existing_discovery_and_import_cache( + monkeypatch, tmp_path, native_calls, auto_import +): + providers(monkeypatch, bundle(tmp_path / "package")) + calls = [] + monkeypatch.setattr(dynwinrt, "has_package_identity", lambda: calls.append("identity") or False) + module = auto_import() + assert auto_import() is module + assert calls == ["identity"] + assert native_calls[0] == [ + ((2, 5), {"bootstrap_dll_path": str(tmp_path / "package" / "_native" / "winappsdk" / "x64" / DLL)}) + ] + assert dynwinrt.init_winappsdk() is native_calls[1] + assert len(native_calls[0]) == 2 # Explicit calls are not suppressed by an imported module. + + +@pytest.mark.parametrize("failure", ["missing", "conflict", "path", "native", "identity"]) +def test_auto_errors_propagate(monkeypatch, tmp_path, native_calls, auto_import, failure): + monkeypatch.setattr(dynwinrt, "has_package_identity", lambda: False) + expected = RuntimeError + match = "No generated" + if failure == "missing": + providers(monkeypatch) + else: + providers(monkeypatch, bundle(tmp_path / "package")) + if failure == "conflict": + providers(monkeypatch, bundle(tmp_path / "one"), bundle(tmp_path / "two", minor=6)) + match = "Conflicting generated" + elif failure == "path": + monkeypatch.setenv(ENVIRONMENT, str(tmp_path / "missing.dll")) + expected, match = FileNotFoundError, "bootstrap DLL not found" + elif failure in ("native", "identity"): + error = OSError(f"{failure} failure") + + def fail(*args, **kwargs): + raise error + + if failure == "native": + monkeypatch.setattr(_winappsdk._native, "init_winappsdk", fail) + else: + monkeypatch.setattr(dynwinrt, "has_package_identity", fail) + monkeypatch.setattr(_winappsdk, "entry_points", lambda **_: pytest.fail("must not discover")) + expected, match = OSError, f"{failure} failure" + with pytest.raises(expected, match=match) as caught: + auto_import() + if failure in ("native", "identity"): + assert caught.value is error + assert "dynwinrt.auto_init" not in sys.modules + assert native_calls[0] == [] + + +def test_explicit_initializers_do_not_skip_for_identity( + monkeypatch, tmp_path, native_calls, auto_import +): + monkeypatch.setattr(dynwinrt, "has_package_identity", lambda: True) + providers(monkeypatch, bundle(tmp_path / "package")) + auto_import() + explicit = tmp_path / "explicit.dll" + explicit.touch() + assert dynwinrt.init_winappsdk() is native_calls[1] + assert dynwinrt.init_winappsdk(2, 5) is native_calls[1] + assert dynwinrt.init_winappsdk(2, 5, bootstrap_dll_path=explicit) is native_calls[1] + assert len(native_calls[0]) == 3 + + +def test_fresh_import_and_native_identity_are_passive(tmp_path): + script = r""" +import ctypes +import sys +kernel = ctypes.WinDLL("kernel32", use_last_error=True) +kernel.GetCurrentPackageFullName.argtypes = [ctypes.POINTER(ctypes.c_uint), ctypes.c_void_p] +kernel.GetCurrentPackageFullName.restype = ctypes.c_long +kernel.GetModuleHandleW.argtypes = [ctypes.c_wchar_p] +kernel.GetModuleHandleW.restype = ctypes.c_void_p +ole = ctypes.WinDLL("ole32") +ole.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)] +ole.CoGetApartmentType.restype = ctypes.c_long +apartment, qualifier = ctypes.c_int(), ctypes.c_int() +assert ole.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == -2147221008 +length = ctypes.c_uint() +status = kernel.GetCurrentPackageFullName(ctypes.byref(length), None) +assert status in (122, 15700), status +import dynwinrt +assert "dynwinrt.auto_init" not in sys.modules +assert dynwinrt.has_package_identity() == (status == 122) +assert ole.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == -2147221008 +assert not kernel.GetModuleHandleW("Microsoft.WindowsAppRuntime.Bootstrap.dll") +""" + child = subprocess.run( + [sys.executable, "-I", "-c", script], cwd=tmp_path, capture_output=True, text=True, timeout=30 + ) + assert child.returncode == 0, child.stdout + child.stderr diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 59d03ca8..6dda87e8 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -68,8 +68,8 @@ pub use crate::roapi::ro_get_activation_factory_2; pub use crate::signature::{InterfaceSignature, MethodSignature}; pub use crate::value::{ArrayOfIUnknownData, AsyncInfo, WinRTValue}; pub use crate::winapp::{ - WinAppSdkBootstrapOptions, WinAppSdkContext, initialize as initialize_winappsdk_with_options, - initialize_winappsdk, + WinAppSdkBootstrapOptions, WinAppSdkContext, has_package_identity, + initialize as initialize_winappsdk_with_options, initialize_winappsdk, }; pub use crate::winrt_implementation::{ WinRtImplementation, WinRtImplementationCallback, WinRtImplementationPlan, diff --git a/crates/dynwinrt/src/winapp.rs b/crates/dynwinrt/src/winapp.rs index 4a1115b1..92837dcf 100644 --- a/crates/dynwinrt/src/winapp.rs +++ b/crates/dynwinrt/src/winapp.rs @@ -5,10 +5,12 @@ use std::mem::size_of; use std::path::Path; use windows::ApplicationModel::PackageVersion; -use windows::Win32::Foundation::{ERROR_INSUFFICIENT_BUFFER, FreeLibrary}; +use windows::Win32::Foundation::{ + APPMODEL_ERROR_NO_PACKAGE, ERROR_INSUFFICIENT_BUFFER, FreeLibrary, +}; use windows::Win32::Storage::Packaging::Appx::{ - GetCurrentPackageInfo2, PACKAGE_FILTER_DIRECT, PACKAGE_FILTER_DYNAMIC, PACKAGE_INFO, - PackagePathType_Install, + GetCurrentPackageFullName, GetCurrentPackageInfo2, PACKAGE_FILTER_DIRECT, + PACKAGE_FILTER_DYNAMIC, PACKAGE_INFO, PackagePathType_Install, }; use windows::Win32::System::LibraryLoader::{GetProcAddress, LoadLibraryW}; use windows::core::PCSTR; @@ -17,6 +19,17 @@ use windows_core::{Error, HRESULT, HSTRING}; pub struct WinAppSdkContext; +/// Query process identity without activating WinRT or requiring a COM apartment. +pub fn has_package_identity() -> windows::core::Result { + let mut length = 0; + let status = unsafe { GetCurrentPackageFullName(&mut length, None) }; + match status { + APPMODEL_ERROR_NO_PACKAGE => Ok(false), + ERROR_INSUFFICIENT_BUFFER => Ok(true), + _ => status.ok().map(|()| true), + } +} + const E_FAIL: HRESULT = HRESULT(0x80004005_u32 as i32); const E_INVALIDARG: HRESULT = HRESULT(0x80070057_u32 as i32); const WINAPPSDK_BOOTSTRAP_DLL_PATH_ENV: &str = "WINAPPSDK_BOOTSTRAP_DLL_PATH"; @@ -207,6 +220,22 @@ type MddBootstrapInitialize2 = mod tests { use super::*; + #[test] + fn identity_query_does_not_initialize_com() { + std::thread::spawn(|| { + use windows::Win32::System::Com::{APTTYPE, APTTYPEQUALIFIER, CoGetApartmentType}; + let mut apartment = APTTYPE::default(); + let mut qualifier = APTTYPEQUALIFIER::default(); + let before = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); + assert_eq!(before.code(), HRESULT(0x800401F0u32 as i32)); + has_package_identity().unwrap(); + let after = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); + assert_eq!(after.code(), before.code()); + }) + .join() + .unwrap(); + } + #[test] fn bootstrap_version_preserves_release_and_minimum_version() { let options = WinAppSdkBootstrapOptions { diff --git a/eng/release/RELEASE_NOTES.md b/eng/release/RELEASE_NOTES.md index f271b777..27d457f0 100644 --- a/eng/release/RELEASE_NOTES.md +++ b/eng/release/RELEASE_NOTES.md @@ -34,6 +34,10 @@ python -m pip install --pre "dynwinrt==0.1.0rc24" "dynwinrt-codegen==0.1.0rc24" - Generated Python and Node.js packages can include Bootstrap DLLs and SDK configuration for initialization without hard-coded versions or DLL paths. ([#225](https://github.com/microsoft/dynwinrt/pull/225)) +### Opt-in automatic Bootstrap + +- Python `dynwinrt.auto_init` and Node.js `@microsoft/dynwinrt/auto-init` skip Bootstrap for processes with package identity and otherwise use generated SDK configuration. + ### Python AsyncEventScope notifications - `AsyncEventScope` manages async handlers for same-thread notifications and cleans up their subscriptions and tasks. ([#229](https://github.com/microsoft/dynwinrt/pull/229)) diff --git a/eng/release/python/test_python_runtime_wheel.ps1 b/eng/release/python/test_python_runtime_wheel.ps1 index 993ffad2..52b78187 100644 --- a/eng/release/python/test_python_runtime_wheel.ps1 +++ b/eng/release/python/test_python_runtime_wheel.ps1 @@ -28,7 +28,8 @@ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & $venvPython -m pip install --disable-pip-version-check "pytest>=8.3.5" --quiet if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } -& $venvPython -m pytest (Join-Path $repoRoot 'bindings\py\tests\test_async_event_scope.py') -q +& $venvPython -m pytest (Join-Path $repoRoot 'bindings\py\tests\test_async_event_scope.py') ` + (Join-Path $repoRoot 'bindings\py\tests\test_winappsdk.py') -q if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $native = @(Get-ChildItem (Join-Path $root 'venv\Lib\site-packages\dynwinrt') -Filter *.pyd -File) diff --git a/eng/release/python/verify_python_release.py b/eng/release/python/verify_python_release.py index 734d6a3f..3cc10394 100644 --- a/eng/release/python/verify_python_release.py +++ b/eng/release/python/verify_python_release.py @@ -153,6 +153,7 @@ def verify_wheel(args: argparse.Namespace) -> None: ) names = archive.namelist() if args.package == "dynwinrt": + assert "dynwinrt/auto_init.py" in names, "Missing opt-in Bootstrap module" assert any(name.endswith(".pyd") for name in names) assert any(name.endswith("/py.typed") for name in names) assert any(name.endswith(".pyi") for name in names) From d2388ef6d57afcc396713a561411079b63ac0e3e Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 30 Oct 2026 15:58:43 +0800 Subject: [PATCH 2/2] Isolate auto-init environment checks in CI Run the strict uninitialized-COM regression in a separate integration-test process, outside the unit suite's retained MTA. Prepare the effectful Python module's identity branch before recursive stubtest, restoring the real identity probe before checking all public signatures. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- bindings/py/tests/run_stubtest.py | 21 +++++++++++++++++++++ bindings/py/tests/test_typing_package.py | 10 ++++++++++ crates/dynwinrt/src/winapp.rs | 16 ---------------- crates/dynwinrt/tests/winapp_identity.rs | 19 +++++++++++++++++++ eng/coverage/coverage.ps1 | 2 +- 6 files changed, 52 insertions(+), 18 deletions(-) create mode 100644 bindings/py/tests/run_stubtest.py create mode 100644 crates/dynwinrt/tests/winapp_identity.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e71507c2..99ea2345 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -535,7 +535,7 @@ jobs: run: | .\bindings\py\.venv\Scripts\python.exe -m pytest bindings\py\tests -q if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - .\bindings\py\.venv\Scripts\python.exe -m mypy.stubtest dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases + .\bindings\py\.venv\Scripts\python.exe bindings\py\tests\run_stubtest.py dynwinrt --allowlist bindings\py\stubtest_allowlist.txt --ignore-disjoint-bases - name: Test generated Python long paths run: | .\eng\release\python\test_generated_python_long_paths.ps1 ` diff --git a/bindings/py/tests/run_stubtest.py b/bindings/py/tests/run_stubtest.py new file mode 100644 index 00000000..7678d64e --- /dev/null +++ b/bindings/py/tests/run_stubtest.py @@ -0,0 +1,21 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Run recursive stubtest with the opt-in module's import precondition prepared. + +Only its initial import uses a simulated packaged process. The real public +identity probe is restored before stubtest inspects every module and signature. +Actual startup behavior is covered separately by test_winappsdk.py. +""" + +from importlib import import_module +import runpy +from unittest.mock import patch + +import dynwinrt + + +if __name__ == "__main__": + with patch.object(dynwinrt, "has_package_identity", return_value=True): + import_module("dynwinrt.auto_init") + runpy.run_module("mypy.stubtest", run_name="__main__") diff --git a/bindings/py/tests/test_typing_package.py b/bindings/py/tests/test_typing_package.py index 4745128e..e92f2ecc 100644 --- a/bindings/py/tests/test_typing_package.py +++ b/bindings/py/tests/test_typing_package.py @@ -28,6 +28,16 @@ def test_installed_auto_init_module_is_typed(tmp_path): assert result.returncode == 0, result.stdout + result.stderr +def test_installed_public_stubs_include_auto_init(): + tests = Path(__file__).parent + result = subprocess.run( + [sys.executable, str(tests / "run_stubtest.py"), "dynwinrt", + "--allowlist", str(tests.parent / "stubtest_allowlist.txt"), "--ignore-disjoint-bases"], + capture_output=True, text=True, timeout=60, + ) + assert result.returncode == 0, result.stdout + result.stderr + + def test_wheel_exports_async_event_scope_without_changing_native_exports(): stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") assert "class AsyncEventScope:" in stub diff --git a/crates/dynwinrt/src/winapp.rs b/crates/dynwinrt/src/winapp.rs index 92837dcf..be944444 100644 --- a/crates/dynwinrt/src/winapp.rs +++ b/crates/dynwinrt/src/winapp.rs @@ -220,22 +220,6 @@ type MddBootstrapInitialize2 = mod tests { use super::*; - #[test] - fn identity_query_does_not_initialize_com() { - std::thread::spawn(|| { - use windows::Win32::System::Com::{APTTYPE, APTTYPEQUALIFIER, CoGetApartmentType}; - let mut apartment = APTTYPE::default(); - let mut qualifier = APTTYPEQUALIFIER::default(); - let before = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); - assert_eq!(before.code(), HRESULT(0x800401F0u32 as i32)); - has_package_identity().unwrap(); - let after = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); - assert_eq!(after.code(), before.code()); - }) - .join() - .unwrap(); - } - #[test] fn bootstrap_version_preserves_release_and_minimum_version() { let options = WinAppSdkBootstrapOptions { diff --git a/crates/dynwinrt/tests/winapp_identity.rs b/crates/dynwinrt/tests/winapp_identity.rs new file mode 100644 index 00000000..2892fbdd --- /dev/null +++ b/crates/dynwinrt/tests/winapp_identity.rs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt::has_package_identity; +use windows::Win32::Foundation::CO_E_NOTINITIALIZED; +use windows::Win32::System::Com::{APTTYPE, APTTYPEQUALIFIER, CoGetApartmentType}; + +// A new thread still sees the core unit tests' process-lifetime implicit MTA. +// Keep this strict uninitialized-apartment check in its own executable. +#[test] +fn identity_query_does_not_initialize_com() { + let mut apartment = APTTYPE::default(); + let mut qualifier = APTTYPEQUALIFIER::default(); + let before = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); + assert_eq!(before.code(), CO_E_NOTINITIALIZED); + has_package_identity().unwrap(); + let after = unsafe { CoGetApartmentType(&mut apartment, &mut qualifier) }.unwrap_err(); + assert_eq!(after.code(), before.code()); +} diff --git a/eng/coverage/coverage.ps1 b/eng/coverage/coverage.ps1 index 44584a0a..07383bff 100644 --- a/eng/coverage/coverage.ps1 +++ b/eng/coverage/coverage.ps1 @@ -685,7 +685,7 @@ try { & $script:pythonExe -m pytest bindings\py\tests -q } Invoke-Step "Python stubtest" { - & $script:pythonExe -m mypy.stubtest dynwinrt ` + & $script:pythonExe bindings\py\tests\run_stubtest.py dynwinrt ` --allowlist bindings\py\stubtest_allowlist.txt ` --ignore-disjoint-bases }