import fs from 'node:fs/promises'; import path from 'node:path'; import {spawn} from 'node:child_process'; import assert from 'node:assert/strict'; import { fileURLToPath } from 'node:url'; import net from 'node:net'; const repo=fileURLToPath(new URL('../../',import.meta.url)); const folder=path.join(repo,'target',`mirror-instances-${Date.now()}-${process.pid}`); const exe=process.argv[2] ? path.resolve(process.argv[2]) : path.join(repo,'client/src-tauri/target/x86_64-pc-windows-msvc/debug/cam-desktop.exe'); await fs.access(exe);await fs.mkdir(folder,{recursive:true}); await fs.writeFile(path.join(folder,'team.toml'),'role = "team"\nroleChosen = false\ncameraId = "0x0DE00001"\nmirror = true\nmirrorVertical = false\n'); await fs.writeFile(path.join(folder,'referee.toml'),'role = "referee"\nroleChosen = false\nmirror = true\nmirrorVertical = false\n[referee]\nmanualSlots = true\nslotA = "0x0DE00001"\nslotB = "0x0DE00002"\n'); const freePort=()=>new Promise((resolve,reject)=>{const s=net.createServer();s.on('error',reject);s.listen(0,'127.0.0.1',()=>{const port=s.address().port;s.close(()=>resolve(port));});}); const ports={team:await freePort(),referee:await freePort()}; const pids={}; const clients={};const results=[];const pause=ms=>new Promise(r=>setTimeout(r,ms)); async function connect(name){ const port=ports[name]; for(let attempt=0;attempt<80;attempt++)try{ const tabs=await(await fetch(`http://127.0.0.1:${port}/json`)).json(); const tab=tabs.find(t=>t.type==='page'&&!t.url.startsWith('devtools:')); if(!tab)throw Error('page loading'); const ws=new WebSocket(tab.webSocketDebuggerUrl);await new Promise(r=>ws.addEventListener('open',r,{once:true})); let seq=0;const pending=new Map();ws.onmessage=e=>{const m=JSON.parse(e.data);if(m.id){pending.get(m.id)?.(m);pending.delete(m.id);}}; const run=expression=>new Promise((resolve,reject)=>{const id=++seq;pending.set(id,m=>{if(m.error||m.result?.exceptionDetails)reject(Error(JSON.stringify(m)));else resolve(m.result.result.value);});ws.send(JSON.stringify({id,method:'Runtime.evaluate',params:{expression,awaitPromise:true,returnByValue:true}}));}); clients[name]={ws,run,invoke:(command,args={})=>run(`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(command)},${JSON.stringify(args)})`)}; await clients[name].invoke('get_snapshot');return; }catch(e){if(attempt===79)throw e;await pause(250);} } const snap=name=>clients[name].invoke('get_snapshot'); const set=(name,camera,mirror,mirrorVertical)=>clients[name].invoke('set_camera_mirror',{camera,mirror,mirrorVertical}); const A=0x0de00001,B=0x0de00002; async function waitFor(check,label){for(let n=0;n<60;n++){if(await check()){results.push(label);return;}await pause(100);}throw Error(`Timeout: ${label}`);} async function agree(camera,mirror,vertical){const[a,b]=await Promise.all([snap('team'),snap('referee')]);const x=a.cameraMirrors[camera],y=b.cameraMirrors[camera];return !!x&&!!y&&x.revision===y.revision&&x.origin===y.origin&&x.mirror===y.mirror&&x.mirrorVertical===y.mirrorVertical&&(mirror===undefined||x.mirror===mirror)&&(vertical===undefined||x.mirrorVertical===vertical);} async function stop(name){clients[name]?.ws.close();try{process.kill(pids[name]);}catch{}await pause(800);} async function restart(name){ const env={...process.env,WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS:`--remote-debugging-port=${ports[name]}`,WEBVIEW2_USER_DATA_FOLDER:path.join(folder,name+'-webview')}; const child=spawn(exe,['--config',path.join(folder,name+'.toml')],{env,windowsHide:true,stdio:'ignore'});pids[name]=child.pid; await fs.writeFile(path.join(folder,'pids.json'),JSON.stringify(pids));await connect(name); } try{ await Promise.all([restart('team'),restart('referee')]); for(const name of ['team','referee'])assert.equal((await snap(name)).config.roleChosen,false,'isolated fixtures must never broadcast official match states'); assert.equal((await snap('referee')).slots.cameraA,A);assert.equal((await snap('referee')).slots.cameraB,B); await set('team',A,false,true);await waitFor(()=>agree(A,false,true),'player A → referee A'); await set('referee',B,false,false);await pause(500); assert.equal((await snap('team')).cameraMirrors[B],undefined);assert.equal((await snap('referee')).cameraMirrors[A].mirrorVertical,true);results.push('B independent of A, player ignores unbound B'); await set('referee',A,true,false);await waitFor(()=>agree(A,true,false),'referee A → player A'); for(let n=0;n<12;n++){ await Promise.all([set('team',A,false,!!(n%2)),set('referee',A,true,!(n%2))]); await waitFor(()=>agree(A),`concurrent edit ${n+1} converges`); } await stop('team');await set('referee',A,false,true);await restart('team'); await waitFor(()=>agree(A,false,true),'player restart catches newer referee revision'); await stop('referee');await set('team',A,true,false);await restart('referee'); await waitFor(()=>agree(A,true,false),'referee restart catches newer player revision'); assert.equal((await snap('referee')).cameraMirrors[B].mirror,false);results.push('B persists through referee restart'); await stop('team');let config=await fs.readFile(path.join(folder,'team.toml'),'utf8');config=config.replace('cameraId = "0x0DE00001"','cameraId = "0x0DE00002"');await fs.writeFile(path.join(folder,'team.toml'),config);await restart('team'); assert.equal((await snap('team')).config.cameraId,B); await set('team',B,true,true);await waitFor(()=>agree(B,true,true),'player rebound to B → referee B'); assert.equal((await snap('referee')).cameraMirrors[A].mirror,true);assert.equal((await snap('referee')).cameraMirrors[A].mirrorVertical,false); await set('referee',B,false,true);await waitFor(()=>agree(B,false,true),'referee B → rebound player B'); await stop('team');await stop('referee');await Promise.all([restart('team'),restart('referee')]); await waitFor(()=>agree(B,false,true),'both processes restart with consistent persisted state'); const final={team:await snap('team'),referee:await snap('referee')}; await fs.writeFile(path.join(folder,'report.json'),JSON.stringify({actualNativeProcesses:true,syntheticCameraIds:true,officialClockDisabled:true,results,finalMirrors:{team:final.team.cameraMirrors,referee:final.referee.cameraMirrors}},null,2)); console.log(JSON.stringify({passed:results.length,report:path.join(folder,'report.json'),results},null,2)); }finally{for(const name of ['team','referee'])await stop(name);}