test(desktop): lock cross-layer Windows input lifecycle contract

Signed-off-by: Alan Z <3347202+A1aZ@users.noreply.github.com>
This commit is contained in:
Alan Z
2026-09-10 14:15:54 +08:00
parent c5a610e32a
commit 0b926345ec
4 changed files with 728 additions and 9 deletions

View File

@@ -70,11 +70,37 @@ fn emit(value: &Value) -> io::Result<()> {
}
fn presence(family: &str, device: Option<&Device>) -> io::Result<()> {
emit(&match device {
Some(device) => json!({ "kind": "presence", "family": family, "present": true,
"name": device.name, "category": "Windows.Gaming.Input", "transport": "unknown" }),
emit(&presence_message(
family,
device.map(|device| device.name.as_str()),
))
}
fn presence_message(family: &str, name: Option<&str>) -> Value {
match name {
Some(name) => json!({ "kind": "presence", "family": family, "present": true,
"name": name, "category": "Windows.Gaming.Input", "transport": "unknown" }),
None => json!({ "kind": "presence", "family": family, "present": false }),
})
}
}
/// Pure wire projection shared with contract tests; replacement releases the old
/// slot before exposing the new device, while unchanged snapshots preserve holds.
fn snapshot_messages(
family: &str,
old: Option<(&str, &str)>,
new: Option<(&str, &str)>,
force: bool,
) -> Vec<Value> {
let unchanged = old.map(|(id, _)| id) == new.map(|(id, _)| id);
let mut messages = Vec::new();
if !unchanged && old.is_some() && new.is_some() {
messages.push(presence_message(family, None));
}
if force || !unchanged {
messages.push(presence_message(family, new.map(|(_, name)| name)));
}
messages
}
/// Re-enumeration handles hotplug without callbacks racing the polling thread.
@@ -151,6 +177,114 @@ fn select_devices<T, E>(
mod discovery_tests {
use super::*;
#[test]
fn lifecycle_messages_match_the_host_controller_contract_fixture() {
#[derive(Clone)]
struct FixtureDevice {
handle: String,
id: String,
name: String,
triggers: mapping::TriggerState,
}
let mut fixture: Value = serde_json::from_str(include_str!(
"../../../../src/main/xbox-gamepad/__tests__/fixtures/windowsLifecycle.json"
))
.unwrap();
// JavaScript JSON has one number type; native axes/triggers are f64.
// Normalize only these declared numeric fields, not arbitrary payloads.
for frame in fixture["frames"].as_object_mut().unwrap().values_mut() {
for group in ["axes", "triggers"] {
for number in frame[group].as_object_mut().unwrap().values_mut() {
*number = json!(number.as_f64().unwrap());
}
}
}
for scenario in fixture["scenarios"].as_array().unwrap() {
let mut current: BTreeMap<&'static str, FixtureDevice> = BTreeMap::new();
for step in scenario["steps"].as_array().unwrap() {
for _ in 0..step["repeat"].as_u64().unwrap_or(1) {
let messages = match step["kind"].as_str().unwrap() {
"snapshot" => {
let preferred = current
.iter()
.map(|(&family, device)| (family, device.id.clone()))
.collect();
let candidates =
step["devices"].as_array().unwrap().iter().map(|record| {
let handle = record["handle"].as_str().unwrap();
let existing = current
.iter()
.find(|(_, device)| device.handle == handle)
.map(|(&family, device)| (family, device));
reuse_live_device(existing, || {
if record["metadataOk"] == false {
return Err("metadata unavailable");
}
Ok((
"xbox",
FixtureDevice {
handle: handle.into(),
id: record["id"].as_str().unwrap().into(),
name: record["name"].as_str().unwrap().into(),
triggers: mapping::TriggerState::default(),
},
))
})
});
let next =
select_devices(candidates, &preferred, |device| device.id.as_str());
let messages = snapshot_messages(
"xbox",
current
.get("xbox")
.map(|d| (d.id.as_str(), d.name.as_str())),
next.get("xbox").map(|d| (d.id.as_str(), d.name.as_str())),
step["force"].as_bool().unwrap_or(false),
);
current = next;
messages
}
"frame" => {
let reading = &fixture["readings"][step["frame"].as_str().unwrap()];
let reading = windows::Gaming::Input::GamepadReading {
LeftTrigger: reading["lt"].as_f64().unwrap(),
RightThumbstickY: reading["ry"].as_f64().unwrap(),
..Default::default()
};
vec![mapping::frame(
"xbox",
&reading,
&mut current.get_mut("xbox").unwrap().triggers,
)]
}
"read-error" => {
current.remove("xbox");
vec![presence_message("xbox", None)]
}
other => panic!("unknown fixture step {other}"),
};
let expected: Vec<Value> = step["messages"]
.as_array()
.unwrap()
.iter()
.map(|m| match m.as_str() {
Some(key) => fixture["frames"][key].clone(),
None => m.clone(),
})
.collect();
assert_eq!(
messages, expected,
"scenario: {}, step: {}",
scenario["name"], step["kind"]
);
assert_eq!(
current.get("xbox").map(|d| d.name.as_str()),
step["expect"]["name"].as_str()
);
}
}
}
}
#[test]
fn a_selected_live_handle_does_not_depend_on_fallible_metadata_refresh() {
let old = "selected".to_string();
let candidate = reuse_live_device(Some(("xbox", &old)), || Err("transient metadata error"));
@@ -256,12 +390,15 @@ fn poll() -> Result<(), Box<dyn std::error::Error>> {
old.last_frame.clone()
};
}
} else if old.is_some() && new.is_some() {
// Reset held input before selecting a replacement controller.
presence(family, None)?;
}
if refresh || !unchanged {
presence(family, next.get(family))?;
for message in snapshot_messages(
family,
old.map(|device| (device.id.as_str(), device.name.as_str())),
next.get(family)
.map(|device| (device.id.as_str(), device.name.as_str())),
refresh,
) {
emit(&message)?;
}
}
devices = next;

View File

@@ -0,0 +1,417 @@
{
"schemaVersion": 1,
"readings": {
"neutral": {
"lt": 0,
"ry": 0
},
"held": {
"lt": 1,
"ry": 1
}
},
"frames": {
"neutral": {
"kind": "frame",
"family": "xbox",
"buttons": {
"lt": false,
"rt": false,
"a": false,
"b": false,
"x": false,
"y": false,
"lb": false,
"rb": false,
"view": false,
"menu": false,
"ls": false,
"rs": false,
"dpadUp": false,
"dpadDown": false,
"dpadLeft": false,
"dpadRight": false
},
"axes": {
"lx": 0,
"ly": 0,
"rx": 0,
"ry": 0
},
"triggers": {
"lt": 0,
"rt": 0
}
},
"held": {
"kind": "frame",
"family": "xbox",
"buttons": {
"lt": true,
"rt": false,
"a": false,
"b": false,
"x": false,
"y": false,
"lb": false,
"rb": false,
"view": false,
"menu": false,
"ls": false,
"rs": false,
"dpadUp": false,
"dpadDown": false,
"dpadLeft": false,
"dpadRight": false
},
"axes": {
"lx": 0,
"ly": 0,
"rx": 0,
"ry": 1
},
"triggers": {
"lt": 1,
"rt": 0
}
}
},
"scenarios": [
{
"name": "metadata failures preserve held input and same-family selection until physical removal",
"steps": [
{
"kind": "snapshot",
"devices": [
{
"handle": "a",
"id": "a",
"name": "Xbox 测试 A",
"metadataOk": true
}
],
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": true,
"name": "Xbox 测试 A",
"category": "Windows.Gaming.Input",
"transport": "unknown"
}
],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "neutral",
"messages": ["neutral"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "held",
"messages": ["held"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": true,
"scrollHeld": true,
"releases": 0
}
},
{
"kind": "snapshot",
"devices": [
{
"handle": "b",
"id": "b",
"name": "Xbox 测试 B",
"metadataOk": true
},
{
"handle": "a",
"id": "a",
"name": "Xbox 测试 A",
"metadataOk": false
}
],
"repeat": 3,
"messages": [],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": true,
"scrollHeld": true,
"releases": 0
}
},
{
"kind": "snapshot",
"devices": [
{
"handle": "b",
"id": "b",
"name": "Xbox 测试 B",
"metadataOk": true
},
{
"handle": "a",
"id": "a",
"name": "Xbox 测试 A",
"metadataOk": false
}
],
"force": true,
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": true,
"name": "Xbox 测试 A",
"category": "Windows.Gaming.Input",
"transport": "unknown"
}
],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": true,
"scrollHeld": true,
"releases": 0
}
},
{
"kind": "snapshot",
"devices": [],
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": false
}
],
"expect": {
"present": false,
"name": null,
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
},
{
"kind": "snapshot",
"devices": [],
"messages": [],
"expect": {
"present": false,
"name": null,
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
}
]
},
{
"name": "reading failure releases voice and scroll once",
"steps": [
{
"kind": "snapshot",
"devices": [
{
"handle": "a",
"id": "a",
"name": "Xbox 测试 A",
"metadataOk": true
}
],
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": true,
"name": "Xbox 测试 A",
"category": "Windows.Gaming.Input",
"transport": "unknown"
}
],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "neutral",
"messages": ["neutral"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "held",
"messages": ["held"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": true,
"scrollHeld": true,
"releases": 0
}
},
{
"kind": "read-error",
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": false
}
],
"expect": {
"present": false,
"name": null,
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
},
{
"kind": "snapshot",
"devices": [],
"messages": [],
"expect": {
"present": false,
"name": null,
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
}
]
},
{
"name": "real replacement releases old holds before the new same-family device is exposed",
"steps": [
{
"kind": "snapshot",
"devices": [
{
"handle": "a",
"id": "a",
"name": "Xbox 测试 A",
"metadataOk": true
}
],
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": true,
"name": "Xbox 测试 A",
"category": "Windows.Gaming.Input",
"transport": "unknown"
}
],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "neutral",
"messages": ["neutral"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": false,
"scrollHeld": false,
"releases": 0
}
},
{
"kind": "frame",
"frame": "held",
"messages": ["held"],
"expect": {
"present": true,
"name": "Xbox 测试 A",
"voiceHeld": true,
"scrollHeld": true,
"releases": 0
}
},
{
"kind": "snapshot",
"devices": [
{
"handle": "b",
"id": "b",
"name": "Xbox 测试 B",
"metadataOk": true
}
],
"messages": [
{
"kind": "presence",
"family": "xbox",
"present": false
},
{
"kind": "presence",
"family": "xbox",
"present": true,
"name": "Xbox 测试 B",
"category": "Windows.Gaming.Input",
"transport": "unknown"
}
],
"expect": {
"present": true,
"name": "Xbox 测试 B",
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
},
{
"kind": "frame",
"frame": "neutral",
"messages": ["neutral"],
"expect": {
"present": true,
"name": "Xbox 测试 B",
"voiceHeld": false,
"scrollHeld": false,
"releases": 1
}
}
]
}
]
}

View File

@@ -0,0 +1,140 @@
import { EventEmitter } from 'node:events';
import { PassThrough } from 'node:stream';
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
import { describe, expect, it, vi } from 'vitest';
import { createXboxGamepadDefaultSettings } from '../../../shared/xboxGamepad.js';
import { XboxGamepadController } from '../controller.js';
import { createXboxGamepadHost } from '../host.js';
import fixture from './fixtures/windowsLifecycle.json';
vi.mock('electron', () => ({ app: { isPackaged: true } }));
vi.mock('../../logger.js', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));
interface Step {
messages: unknown[];
repeat?: number;
expect: {
present: boolean;
name: string | null;
voiceHeld: boolean;
scrollHeld: boolean;
releases: number;
};
}
/** The Rust producer validates the same fixture against its real snapshot/message functions. */
describe('Windows snapshot → NDJSON host → controller lifecycle contract', () => {
it.each(['disable', 'background', 'preview'] as const)(
'%s releases held input once and blocks further dispatch',
async (reason) => {
const child = Object.assign(new EventEmitter(), {
stdin: new PassThrough(),
stdout: new PassThrough(),
stderr: new PassThrough(),
kill: vi.fn(),
});
let frontmost = true;
const dispatch = vi.fn();
const controller = new XboxGamepadController({ isCindyFrontmost: () => frontmost, dispatch });
const enabled = { ...createXboxGamepadDefaultSettings(), deviceEnabled: true };
controller.applySettings('xbox', enabled);
const spawnHelper = vi.fn(() => child as unknown as ChildProcessWithoutNullStreams);
const host = createXboxGamepadHost((message) => controller.handleHostMessage(message), {
resolveHelperPath: async () => 'fixture-helper',
spawnHelper,
});
const send = (message: unknown) => child.stdout.write(`${JSON.stringify(message)}\n`);
try {
host.start();
await vi.waitFor(() => expect(spawnHelper).toHaveBeenCalledOnce());
send({ kind: 'presence', family: 'xbox', present: true, name: 'Xbox Test' });
send(fixture.frames.neutral);
send(fixture.frames.held);
expect(dispatch).toHaveBeenCalledWith({ type: 'voice', phase: 'press' });
dispatch.mockClear();
if (reason === 'disable')
controller.applySettings('xbox', { ...enabled, deviceEnabled: false });
if (reason === 'background') {
frontmost = false;
controller.setCindyFrontmost(false);
}
if (reason === 'preview') controller.setLayoutPreviewActive(true, 'xbox');
send(fixture.frames.held);
send(fixture.frames.neutral);
expect(dispatch.mock.calls.map(([action]) => action)).toEqual([
{ type: 'voice', phase: 'release' },
{ type: 'scroll-stop' },
]);
} finally {
host.stop();
}
},
);
for (const scenario of fixture.scenarios) {
it(scenario.name, async () => {
const child = Object.assign(new EventEmitter(), {
stdin: new PassThrough(),
stdout: new PassThrough(),
stderr: new PassThrough(),
kill: vi.fn(),
});
const held = { voice: false, scroll: false, releases: 0, scrollStops: 0 };
const controller = new XboxGamepadController({
isCindyFrontmost: () => true,
dispatch: (action) => {
if (action.type === 'voice') {
held.voice = action.phase === 'press';
if (action.phase === 'release') held.releases++;
}
if (action.type === 'scroll') held.scroll = true;
if (action.type === 'scroll-stop') {
held.scroll = false;
held.scrollStops++;
}
},
});
controller.applySettings('xbox', {
...createXboxGamepadDefaultSettings(),
deviceEnabled: true,
});
const spawnHelper = vi.fn(() => child as unknown as ChildProcessWithoutNullStreams);
const host = createXboxGamepadHost((message) => controller.handleHostMessage(message), {
resolveHelperPath: async () => 'fixture-helper',
spawnHelper,
});
try {
host.start();
await vi.waitFor(() => expect(spawnHelper).toHaveBeenCalledOnce());
for (const step of scenario.steps as Step[]) {
for (let repeat = 0; repeat < (step.repeat ?? 1); repeat++) {
const messages = step.messages.map((message) =>
typeof message === 'string'
? fixture.frames[message as keyof typeof fixture.frames]
: message,
);
if (messages.length) {
const bytes = Buffer.from(
messages.map((message) => JSON.stringify(message)).join('\n') + '\n',
);
// Fragment both JSON lines and UTF-8 device names through the actual stream decoder.
for (let offset = 0; offset < bytes.length; offset += 7)
child.stdout.write(bytes.subarray(offset, offset + 7));
}
const state = controller.getState('xbox');
expect(state.devicePresent).toBe(step.expect.present);
expect(state.deviceName).toBe(step.expect.name);
expect(state.connectionStatus).toBe(step.expect.present ? 'connected' : 'not-detected');
expect(held.voice).toBe(step.expect.voiceHeld);
expect(held.scroll).toBe(step.expect.scrollHeld);
expect(held.releases).toBe(step.expect.releases);
expect(held.scrollStops).toBe(step.expect.releases);
}
}
} finally {
host.stop();
}
});
}
});

View File

@@ -148,6 +148,31 @@ A pre-migration stash was retained as a recovery copy.
## Delivery self-check
### Issue #4212 acceptance follow-up
- Action plan posted to #4212 before implementation (issuecomment-5613783170).
- Extracted the existing native presence/snapshot message projection without
changing state semantics. Rust producer tests and TypeScript consumer tests use
the same windowsLifecycle.json contract fixture. The producer exercises live
metadata reuse, stable selection, real removal, read failure and frame mapping;
the consumer streams fragmented JSON/UTF-8 through the actual Host and controller.
- Assertions cover repeated recoverable metadata failures while voice/scroll are
held, no same-family switch, exactly-once releases for real disconnect/read error,
and replacement ordering. Additional Host/controller tests cover disable, loss of
foreground and layout preview. These are simulated fault/contract tests, not
physical-device or full-UI evidence.
- The consumer baseline passed before refactoring. The producer contract initially
lacked a pure message projection seam; after extraction, all 11 gamepad Rust
tests and all 6 cross-layer consumer tests passed. No new product bug was claimed
from the test-seam or JSON numeric-representation setup failures.
- An actual active Xbox One Game Controller was enumerated on this Windows host.
Complete UI/hardware operation acceptance and final-head installer evidence are
still pending. Final acceptance will be reported in #4212 only after all checks,
physical operation evidence and maintainer approval are satisfied.
- Pre-commit validation passed: related Desktop unit gate (432.3 seconds), Desktop
typecheck, 11 gamepad / 14 Micro Rust tests, both Clippy checks, 9 license/SBOM
tests, targeted ESLint and diff checks.
### Follow-up: transient metadata is not unplug (Greptile 3975106066)
- Fresh WGI list membership is checked by COM object identity. A selected handle