فینورا پرو - سامانه جامع حسابداری و صدور فاکتور

work/a08-memory-stability-20261123
a02/strict-export-preflight-20261018 audit/a01-readonly-invoice-metadata-20261101 ci/a06-require-trusted-issuer-for-release ci/main-postmerge-phase-a-validation-20261020 ci/phase-a-controlled-public-release design/issue-5-commercial-corrections-adr docs/a01-a02-a05-oct23-verified-evidence docs/a01-cheque-endorsement-evidence-20261022 docs/a01-cheque-event-date-evidence-20261021 docs/a01-explicit-refund-reason-evidence-20261021 docs/a01-refund-auth-status-20261020 docs/a01-refund-trace-evidence-20261020 docs/a02-102-evidence-20261018 docs/a02-pr104-evidence-20261018 docs/a02-pr106-evidence-20261019 docs/a02-pr108-ten-tests-20261019 docs/a02-private-sql-backup-evidence-20261111 docs/a03-merge-status-sync-20261020 docs/a04-software-gate-acceptance-20261020 docs/feature-matrix-20261014 docs/finora-master-execution-playbook docs/four-phase-execution-20261014 docs/four-phase-roadmap-20261014 docs/holoo-lab-stabilization-phase1-20261111 docs/holoo-runtime-schema-audit-20261111 docs/ops-142-governance-5-1-3-20261030 docs/phase-a-a01-a02-a06-a08-verified-evidence-20261023 docs/phase-a-a01-a05-a06-evidence-20261023 docs/phase-a-independent-acceptance-evidence docs/phase-a-pr110-evidence-20261019 docs/project-status-phase-a-20261014 feat/a01-referenced-return-corrections feat/a01-referenced-returns-on-main feat/a02-atomic-opening-ledger-preflight feat/a02-holoo-compatibility-preflight feat/a02-holoo-declared-control-totals feat/a02-holoo-explicit-csv-gate feat/a02-holoo-safe-zip-intake-offline-webview2-20261030 feat/a02-offline-sql-server-provisioning-20261030 feat/a02-opening-balance-dry-run feat/a02-opening-ledger-admin-ui feat/a02-opt-in-isolated-sql-restore-executor-20261030 feat/a02-private-holoo-zip-staging-20261030 feat/a02-safe-isolated-restore-plan-20261030 feat/a02-sql-backup-header-verifyonly-20261030 feat/a03-audit-schema-atomic-events feat/a03-complete-manual-journal-audit feat/a05-cheque-treasury-reconciliation feat/a06-signed-offline-license-activation feat/a08-synthetic-performance-baseline feat/phase-a-accounting-benchmark-return-preview feat/phase-a-ledger-settlement-diagnostics feature/v2-reconciliation-20261013 fix/a01-atomic-confirm-ui-one-shot-20261031 fix/a01-cheque-clearance-explicit-account-20261023 fix/a01-cheque-contractual-due-date-validity-20261023 fix/a01-cheque-endorsement-counterparty-20261022 fix/a01-cheque-event-date-open-period-20261021 fix/a01-cumulative-return-amount-cap fix/a01-explicit-refund-reason-approval-20261021 fix/a01-manager-authorized-customer-refunds-20261020 fix/a01-no-implicit-refund fix/a01-one-shot-confirm-on-atomic-import-20261031 fix/a01-refund-and-overcollection-net-cash fix/a01-refund-correction-trace-20261020 fix/a02-atomic-excel-master-merge-20261031 fix/a02-canonical-mapping-contract-20261018 fix/a02-disable-destructive-excel-replace-20261031 fix/a02-holoo-invoice-line-coverage-20261023 fix/a02-holoo-preflight-required-invoice-lines-20261023 fix/a02-mapping-contract-20261018 fix/a02-opening-preflight-unbalanced-report fix/a02-orphan-mapping-20261018 fix/a02-private-excel-import-session-20261031 fix/a02-strict-export-input-20261019 fix/a03-append-only-full-backup-import fix/a03-append-only-write-guard fix/a03-block-transaction-clear-append-only-20261016 fix/a03-chain-validation-20261020 fix/a03-company-scoped-audit-data-access fix/a03-deny-direct-audit-write-20261019 fix/a03-escaped-expense-list-20261031 fix/a03-escaped-financial-record-ids-20261031 fix/a03-financial-ledger-actions-and-print-20261031 fix/a04-backup-checksum-preflight fix/a04-company-audit-replay-stable-compare fix/a04-company-backup-source-isolation-20261020 fix/a04-full-restore-posted-financial-integrity fix/a04-reject-mixed-company-backup-20261019 fix/a04-replace-immutable-posted-ledger fix/a04-restore-financial-journal-references fix/a04-service-source-company-boundary-20261020 fix/a05-block-inactive-treasury-settlements fix/a05-cheque-cash-evidence-reconciliation-20261023 fix/a05-cheque-ledger-and-bank-reconciliation-20261023 fix/a05-fiscal-close-invariant-gates fix/a06-backup-restore-user-privileges fix/a06-license-user-company-quota-20261023 fix/a06-malformed-trial-state-fail-closed fix/a06-offline-clock-fail-closed-20261019 fix/a07-indexeddb-blocked-startup fix/a07-offline-bundled-assets fix/a07-version-and-startup-banner fix/issue-7-company-backup-isolation fix/p0-deterministic-fractional-invoice-money-20261031 fix/p0-fractional-quantity-input-20261031 fix/p0-fractional-quantity-integrated-20261031 fix/p0-invoice-posting-invariants-20261031 fix/p0-legacy-stock-and-product-inputs-20261031 fix/p0-reports-immutable-cogs-20261101 fix/p0-verified-financial-percent-20261031 fix/p0-zero-discount-report-revenue-20261101 fix/phase-a-backup-app-version fix/phase-a-backup-integrity-checksum fix/phase-a-backup-record-id-validation-20261014 fix/phase-a-backup-version-validation-20261014 fix/phase-a-closure-pack3-20261101 fix/phase-a-entitlement-payload-validation fix/phase-a-gate-exact-evidence-20261019 fix/phase-a-pack4-stock-scope-20261101 fix/phase-a-pack5-integrated-evidence-20261101 fix/phase-a-pack6-atomic-legacy-20261101 fix/phase-a-restore-envelope-and-rollback fix/phase-a-settings-admin-gate fix/print-browser-header-footer-20261014 fix/q01-expense-security-probe-exact-option-20261031 fix/q01-financial-grid-labels-20261031 fix/q01-form-label-association-20261031 fix/q01-native-evidence-integrity-20261030 fix/q01-number-input-persian-decimal-20261031 fix/q01-responsive-dashboard-and-cheque-table-20261031 fix/q01-safe-ui-action-audit-coverage-20261031 fix/q01-visible-desktop-sidebar-and-safe-confirm-20261030 fix/roadmap-metadata-sync-20261014 gate/a03-audit-metadata-validation-20261019 integration/a02-windows-holoo-setup-candidate-20261030 license-server main perf/a07-lazy-load-excel perf/a08-cheque-reconciliation-account-index-20261023 perf/a08-paginated-reports-20261101 phase1-restore-hardening planning/holoo-execution-20261013 planning/roadmap-project-management-20261014 qa/native-click-coverage-audit-20261030 release/v2.0.0 test/a01-native-endorsement-mandatory-20261023 test/a01-native-purchase-return-guardrails test/a01-native-sale-return-financial-guardrails test/a01-safe-integer-boundary-20261019 test/a02-native-opening-dry-run-rejections test/a02-native-positive-opening-ledger test/a04-native-corrupt-fbackup-20261016 test/a04-native-encrypted-company-backup test/a04-native-encrypted-company-backup-main test/a04-native-late-transaction-rollback test/a04-native-windows-backup-recovery test/a04-real-edge-v6-v7-migration test/a04-real-native-interrupted-restore test/a05-native-draft-ledger-and-repeat-close-20261016 test/a05-native-fiscal-close-guardrails test/a07-native-multipage-print-engine test/a07-native-origin-provenance test/a07-native-webview2-offline-routes test/a07-windows-offline-startup-smoke test/a08-installed-webview2-60k-baseline test/a08-native-webview2-heap-metrics test/a08-windows-synthetic-performance-baseline test/github-write-access-20261009 test/native-win-ui-routes-after-finance-backup test/phase-a-combined-a01-a05-a08-final-evidence test/phase-a-combined-native-acceptance-matrix test/phase-a-ledger-invariants-20261014 test/phase-a-native-all-routes-on-merged-lab test/phase-a-native-encrypted-backup test/phase-a-native-finance-backup-matrix test/phase-a-native-ui-and-backup-smoke test/phase-a-windows-native-installer-lab work/a08-dispatch-activation-20261123 work/a08-memory-stability-20261123 work/finance-curated-20261123
cjs 779 lines 45.4 KB
Raw
1 'use strict';
2 // Real installed Tauri/WebView2 native-process smoke on a disposable Windows Actions VM.
3 // Runs against a real NSIS-installed .exe, NOT the Vite preview page.
4 // No production data, no publication, and no password/sensitive payload in reports.
5 const assert = require('node:assert/strict');
6 const fs = require('node:fs');
7 const path = require('node:path');
8 const { spawn, execFileSync } = require('node:child_process');
9 const verifyNativeFunctionalMatrix = require('./windows-vm-native-functional-matrix.cjs');
10 const { verifyNativeOrigin } = require('./windows-vm-native-origin.cjs');
11
12 const [exe, profile, mode, expectedVersion, reportPath] = process.argv.slice(2);
13 assert.equal(process.platform, 'win32');
14 assert.ok(['seed','upgrade','reopen','fresh','benchmark','stability','crash-arm','crash-verify'].includes(mode), 'unknown lab mode');
15 assert.ok(fs.existsSync(exe), 'installed Windows executable missing');
16 fs.mkdirSync(profile, { recursive: true });
17 const port = mode === 'seed' ? 9371 : mode === 'upgrade' ? 9372 : mode === 'reopen' ? 9374 : mode === 'benchmark' || mode === 'stability' ? 9375 : mode === 'crash-arm' ? 9376 : mode === 'crash-verify' ? 9377 : 9373;
18 const PASSWORD = 'VmOnly-Factor-83471!'; // Synthetic password, never printed.
19
20 const REG_POLICY = [
21 'HKCU\\Software\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments',
22 'HKLM\\SOFTWARE\\Policies\\Microsoft\\Edge\\WebView2\\AdditionalBrowserArguments'
23 ];
24 const EXE_NAME = path.basename(exe);
25 function setDebugPolicies() {
26 const active = [];
27 for (const key of REG_POLICY) {
28 try {
29 // Newer WebView2 runtimes may ignore the environment variable for
30 // CDP debugging. Microsoft documents the per-EXE policy alternative.
31 execFileSync('reg.exe', [
32 'add', key, '/v', EXE_NAME, '/t', 'REG_SZ', '/d',
33 '--remote-debugging-port=' + port + ' --remote-allow-origins=*', '/f'
34 ], { stdio: 'ignore', timeout: 5000 });
35 active.push(key);
36 } catch (_) { /* Fall back to the documented WebView2 environment variable. */ }
37 }
38 return active;
39 }
40 function cleanDebugPolicies(keys) {
41 for (const key of keys) {
42 try {
43 execFileSync('reg.exe', ['delete', key, '/v', EXE_NAME, '/f'],
44 { stdio: 'ignore', timeout: 5000 });
45 } catch (_) {}
46 }
47 }
48
49 const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
50 async function eventually(fn, timeoutMs = 65000, delayMs = 300) {
51 let last;
52 const until = Date.now() + timeoutMs;
53 while (Date.now() < until) {
54 try { const result = await fn(); if (result) return result; }
55 catch (error) { last = error; }
56 await wait(delayMs);
57 }
58 throw last || Error('Timed out waiting for installed native app');
59 }
60 async function getPages() {
61 const response = await fetch('http://127.0.0.1:' + port + '/json', {
62 signal: AbortSignal.timeout(1500)
63 });
64 if (!response.ok) throw Error('CDP returned ' + response.status);
65 return response.json();
66 }
67 async function connect(url) {
68 const ws = new WebSocket(url);
69 await new Promise((resolve, reject) => {
70 const timer = setTimeout(() => reject(Error('Native WebView2 CDP websocket timeout')), 12000);
71 ws.addEventListener('open', () => { clearTimeout(timer); resolve(); }, { once: true });
72 ws.addEventListener('error', () => { clearTimeout(timer); reject(Error('WebView2 CDP connection failed')); }, { once: true });
73 });
74 let id = 0;
75 const pending = new Map();
76 ws.addEventListener('message', event => {
77 const reply = JSON.parse(event.data);
78 const current = pending.get(reply.id);
79 if (!current) return;
80 clearTimeout(current.timer); pending.delete(reply.id);
81 if (reply.error) current.reject(Error(JSON.stringify(reply.error)));
82 else current.resolve(reply.result);
83 });
84 const command = (method, params = {}, timeoutMs = 12000) => new Promise((resolve, reject) => {
85 const next = ++id;
86 const timer = setTimeout(() => { pending.delete(next); reject(Error('CDP ' + method + ' timed out')); }, timeoutMs);
87 pending.set(next, { resolve, reject, timer });
88 ws.send(JSON.stringify({ id: next, method, params }));
89 });
90 const evaluate = async (expression, timeoutMs = 12000) => {
91 const r = await command('Runtime.evaluate', {
92 expression, awaitPromise: true, returnByValue: true
93 }, timeoutMs);
94 if (r.exceptionDetails) {
95 const detail=r.exceptionDetails;
96 const exception=detail.exception||{};
97 const frames=(detail.stackTrace?.callFrames||[]).slice(0,8).map(frame=>({
98 functionName:frame.functionName||'',url:frame.url||'',
99 line:frame.lineNumber,column:frame.columnNumber
100 }));
101 let pageContext=null;
102 try {
103 const context=await command('Runtime.evaluate',{
104 expression:"JSON.stringify({stage:window.__Q01_AUDIT_STAGE||null,route:window.FINORA?.Router?.current?.()||null,modalDepth:window.FINORA?.Modal?.stack?.length??null})",
105 returnByValue:true
106 },5000);
107 pageContext=context.result?.value||null;
108 } catch (_) {}
109 throw Error('Native UI exception: '+JSON.stringify({
110 text:detail.text||'',description:exception.description||'',
111 value:exception.value??null,line:detail.lineNumber,column:detail.columnNumber,
112 frames,pageContext
113 }));
114 }
115 if (r.result?.subtype === 'error') throw Error('Native UI rejected JavaScript evaluation');
116 return r.result?.value;
117 };
118 await command('Page.enable');
119 await command('Runtime.enable');
120 return { command, evaluate, close: () => ws.close() };
121 }
122 (async () => {
123 const report = {
124 mode, exe: path.basename(exe), expectedVersion,
125 vm: 'github-windows-latest', installedNativeTauri: false,
126 cdpReady: false, login: 'not-run', indexedDb: 'not-run', persistence: 'not-run',
127 dpapi: 'not-run', browserOrigin: null, status: 'FAILED'
128 };
129 let proc, cdp;
130 let debugPolicyKeys = [];
131 try {
132 debugPolicyKeys = setDebugPolicies();
133 report.debugPolicyKeysApplied = debugPolicyKeys.length;
134 const env = {
135 ...process.env,
136 WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS:
137 '--remote-debugging-port=' + port + ' --remote-allow-origins=*',
138 WEBVIEW2_USER_DATA_FOLDER: profile
139 };
140 proc = spawn(exe, [], { env, stdio: 'ignore', windowsHide: false });
141 proc.on('error', error => { report.processError = error.message; });
142 const url = await eventually(async () => {
143 const pages = await getPages();
144 return pages.find(x => x.type === 'page' && x.webSocketDebuggerUrl &&
145 !x.url.startsWith('devtools://'))?.webSocketDebuggerUrl;
146 });
147 cdp = await connect(url);
148 report.cdpReady = true;
149 const ready = await eventually(async () => cdp.evaluate(
150 '(function(){return window.FINORA && document.getElementById("finoraAuthOverlay") && !!globalThis.__TAURI_INTERNALS__?.invoke ? { title:document.title, version:window.FINORA.version, href:location.href, initialMode:document.getElementById("faTitle").textContent, databaseReady:true } : null})()'
151 ), 65000);
152 report.installedNativeTauri = true;
153 report.browserOrigin = verifyNativeOrigin(ready.href);
154 report.displayedVersion = ready.version;
155 report.versionMatchesPackage = ready.version === expectedVersion;
156 // Verified against git tag v2.0.3: that shipped src/main.js hardcodes
157 // FINORA.version = '1.1.1' despite package/installer version 2.0.3.
158 // Record the existing release defect but continue data-preservation checks.
159 if (mode === 'seed' && expectedVersion === '2.0.3' &&
160 ready.version === '1.1.1') {
161 report.knownLegacyVersionLabelDefect = 'public-2.0.3-displays-1.1.1';
162 } else {
163 assert.equal(ready.version, expectedVersion, 'candidate build runtime version mismatch');
164 }
165 const setup = ready.initialMode.includes('تعیین رمز');
166 if (mode === 'seed' || mode === 'fresh' || mode === 'benchmark' || mode === 'stability' || mode === 'crash-arm') {
167 assert.equal(setup, true, 'a new native profile must prompt to set the administrator password');
168 } else {
169 assert.equal(setup, false, 'upgrade/reopen should preserve existing administrator credentials');
170 }
171 await cdp.evaluate('(() => {' +
172 'document.getElementById("faUser").value="مدیر";' +
173 'document.getElementById("faPass").value=' + JSON.stringify(PASSWORD) + ';' +
174 'if(document.getElementById("faPass2").style.display!=="none") document.getElementById("faPass2").value=' + JSON.stringify(PASSWORD) + ';' +
175 'document.getElementById("faSubmit").click();return "submitted"})()');
176 await eventually(async () => cdp.evaluate(
177 'document.getElementById("finoraAuthOverlay") ? null : (window.FINORA && document.getElementById("pageContent") ? true : null)'
178 ), 65000);
179 report.login = setup ? 'first-run-admin-setup-passed' : 'existing-admin-password-passed';
180
181 if (mode === 'crash-arm') {
182 const source = fs.readFileSync(
183 path.join(__dirname, 'windows-vm-native-crash-import-browser.js'), 'utf8');
184 const armed = await cdp.evaluate(source, 90000);
185 assert.equal(armed.scenario, 'real-StorageService.importAll-mid-write');
186 assert.equal(armed.armed, true);
187 assert.equal(armed.committed, false);
188 assert.ok(armed.staged >= 20 && armed.staged < armed.total,
189 'A04 restore must be actively staging before process termination');
190 // Kill the *real Windows native process tree*, including WebView2, not
191 // just abort an IndexedDB request or throw a JS exception.
192 assert.ok(proc?.pid, 'Real native process PID missing for crash test');
193 execFileSync('taskkill.exe', ['/PID', String(proc.pid), '/T', '/F'],
194 { stdio: 'ignore', timeout: 30000 });
195 report.crashInjected = { realWindowsProcessKilled: true,
196 restoreInProgress: true, stagedBeforeCrash: armed.staged };
197 report.status = 'PASSED';
198 return;
199 }
200 if (mode === 'crash-verify') {
201 const result = await cdp.evaluate(`(async () => {
202 const rows=(await FINORA.Storage.getAll('contacts'))
203 .filter(x=>typeof x.id==='string' && x.id.startsWith('vm-a04-crash-contact-'));
204 return { partialRows: rows.length,
205 dbVersion: (await FINORA.Storage.init()).version,
206 signedIn: !document.getElementById('finoraAuthOverlay') };
207 })()`, 60000);
208 assert.deepEqual(result, { partialRows: 0, dbVersion: 7, signedIn: true },
209 'Forced termination left partial restored contacts or lost login');
210 report.crashRollback = 'killed-real-installed-Windows-WebView2-during-importAll-no-partial-rows-on-restart';
211 report.status = 'PASSED';
212 return;
213 }
214
215 if (mode === 'seed') {
216 const seeded = await cdp.evaluate('(async()=>{' +
217 'const S=FINORA.Storage;' +
218 'await S.put("products",{id:"vm-upgrade-product",companyId:"company_default",name:"Synthetic VM product",sellPrice:123456});' +
219 'await S.put("invoices",{id:"vm-upgrade-draft",companyId:"company_default",kind:"sale",isPreInvoice:true,financePosted:false,grandTotal:987654,paidAmount:0,remaining:987654});' +
220 'const db=await S.init();' +
221 // Real v2.0.3 backup format: all stores, v6 schema, credentials excluded.
222 // Keep a synthetic backup only in the disposable Windows profile so the
223 // upgraded app can test restoring the OLD version without cloud artifacts.
224 'const snapshot=await S.exportAll();' +
225 'await S.put("settings",{id:"vm-legacy-backup",companyId:"company_default",payload:snapshot});' +
226 'return {version:db.version,products:(await S.getAll("products")).length,amount:(await S.get("invoices","vm-upgrade-draft")).grandTotal,' +
227 'backupVersion:snapshot.version,backupApp:snapshot.app,' +
228 'backupContainsProduct:snapshot.data.products.some(p=>p.id==="vm-upgrade-product"),' +
229 'backupContainsInvoice:snapshot.data.invoices.some(i=>i.id==="vm-upgrade-draft"),' +
230 'backupCredentialsExcluded:!snapshot.data.users.some(u=>"pwHash" in u||"pwSalt" in u)};' +
231 '})()');
232 assert.equal(seeded.version, 6, 'old release should have IndexedDB v6');
233 assert.equal(seeded.amount, 987654);
234 assert.equal(seeded.backupVersion, 6);
235 assert.equal(seeded.backupApp, 'Factor-easyPro');
236 assert.equal(seeded.backupContainsProduct, true);
237 assert.equal(seeded.backupContainsInvoice, true);
238 assert.equal(seeded.backupCredentialsExcluded, true);
239 report.legacyBackup = 'real-v2.0.3-snapshot-saved-in-test-profile';
240 report.indexedDb = 'v6-written';
241 report.persistence = 'synthetic-legacy-fixtures-created';
242 } else if (mode === 'upgrade' || mode === 'reopen') {
243 const restored = await cdp.evaluate('(async()=>{' +
244 'const S=FINORA.Storage, db=await S.init();' +
245 'const product=await S.get("products","vm-upgrade-product");' +
246 'const invoice=await S.get("invoices","vm-upgrade-draft");' +
247 'return {version:db.version,product:product?.name,amount:invoice?.grandTotal,' +
248 'audits:(await S.getAll("audit_events")).length,corrections:db.objectStoreNames.contains("document_corrections")};' +
249 '})()');
250 assert.equal(restored.version, 7);
251 assert.equal(restored.product, 'Synthetic VM product');
252 assert.equal(restored.amount, 987654);
253 assert.equal(restored.audits, mode === 'upgrade' ? 0 : 1,
254 'migration must not fabricate history; an explicitly created event must persist after restart');
255 assert.equal(restored.corrections, true);
256 report.indexedDb = mode === 'upgrade' ?
257 'real-WebView2-v6-to-v7-passed' : 'persisted-real-WebView2-v7-on-restart';
258 report.persistence = 'product-invoice-and-login-survived-upgrade';
259 if (mode === 'upgrade') {
260 // Exercise the actual importer in the INSTALLED Tauri WebView2 process.
261 // Intentionally delete only the synthetic draft and product, restore an
262 // older real v6 snapshot, verify both records, and assert a corrupted
263 // snapshot cannot produce partial writes.
264 const recovery = await cdp.evaluate('(async()=>{' +
265 'const S=FINORA.Storage;' +
266 'const snapshot=(await S.get("settings","vm-legacy-backup"))?.payload;' +
267 'if(!snapshot || snapshot.version!==6) throw Error("v2.0.3 backup not persisted");' +
268 'await S.delete("products","vm-upgrade-product");' +
269 'await S.delete("invoices","vm-upgrade-draft");' +
270 'const emptyBefore=!(await S.get("products","vm-upgrade-product"))&&!(await S.get("invoices","vm-upgrade-draft"));' +
271 'await S.importAll(snapshot);' +
272 'const p=await S.get("products","vm-upgrade-product");' +
273 'const i=await S.get("invoices","vm-upgrade-draft");' +
274 'const tampered=structuredClone(snapshot);' +
275 'tampered.data.products.push({...p,id:"vm-would-rollback"});' +
276 'tampered.data.invoices.push({...i,grandTotal:1});' +
277 'let blocked=false;' +
278 'try {await S.importAll({...tampered,app:"foreign-finance"});}catch(e){blocked=true;}' +
279 'return {emptyBefore,restoredProduct:p?.name,restoredInvoice:i?.grandTotal,' +
280 'blockedBadApp:blocked,afterBadApp:(await S.get("products","vm-would-rollback"))??null,' +
281 'databaseVersion:(await S.init()).version};' +
282 '})()');
283 assert.deepEqual(recovery, {
284 emptyBefore:true,restoredProduct:'Synthetic VM product',
285 restoredInvoice:987654,blockedBadApp:true,afterBadApp:null,
286 databaseVersion:7
287 });
288 report.backupRecovery = 'actual-v2.0.3-v6-snapshot-restored-on-installed-v7';
289 report.invalidBackup = 'foreign-app-rejected-no-writes';
290
291 const immutable = await cdp.evaluate('(async()=>{' +
292 'const S=FINORA.Storage;' +
293 'const audit={id:"vm-audit-immutable",companyId:"company_default",' +
294 'commandKey:"company_default:vm-native-test",eventType:"journal_posted",' +
295 'actorId:"user_admin",sourceId:"vm-upgrade-draft",safeSummary:{lineCount:2}};' +
296 'await S.importAll({app:"Factor-easyPro",version:6,data:{audit_events:[audit]}});' +
297 'const stored=await S.get("audit_events",audit.id);' +
298 'let refused=false;' +
299 'try {await S.importAll({app:"Factor-easyPro",version:7,data:{' +
300 'products:[{id:"vm-should-roll-back",companyId:"company_default",name:"No partial writes"}],' +
301 'audit_events:[{...stored,eventType:"period_closed"}]}});}' +
302 'catch(e){refused=true;}' +
303 'return {refused,product:(await S.get("products","vm-should-roll-back"))??null,' +
304 'auditType:(await S.get("audit_events",audit.id)).eventType};' +
305 '})()');
306 assert.deepEqual(immutable, {
307 refused:true,product:null,auditType:'journal_posted'
308 });
309 report.immutableRestoreRollback = 'full-restore-transaction-rolled-back-on-audit-conflict';
310 }
311 if (mode === 'reopen') {
312 const persisted = await cdp.evaluate('(async()=>{' +
313 'const S=FINORA.Storage;' +
314 'const audit=await S.get("audit_events","vm-audit-immutable");' +
315 'return {product:(await S.get("products","vm-upgrade-product"))?.name,' +
316 'invoice:(await S.get("invoices","vm-upgrade-draft"))?.grandTotal,' +
317 'auditType:audit?.eventType,dbVersion:(await S.init()).version};' +
318 '})()');
319 assert.deepEqual(persisted, {
320 product:'Synthetic VM product', invoice:987654,
321 auditType:'journal_posted', dbVersion:7
322 });
323 report.persistence = 'v6-backup-recovery-and-audit-survived-real-native-restart';
324 }
325 } else {
326 const fresh = await cdp.evaluate('(async()=>{' +
327 'const S=FINORA.Storage, db=await S.init();' +
328 'return {version:db.version,admin:(await S.get("users","user_admin"))?.role};' +
329 '})()');
330 assert.equal(fresh.version, 7);
331 assert.equal(fresh.admin, 'admin');
332 report.indexedDb = 'fresh-native-v7-passed';
333 report.persistence = 'not-applicable';
334 }
335
336 if (mode !== 'seed') {
337 const dpapi = await cdp.evaluate('(async()=>{' +
338 'const invoke=globalThis.__TAURI_INTERNALS__.invoke;' +
339 'const source="Synthetic DPAPI verification value";' +
340 'const cipher=await invoke("protect_local_state",{value:source});' +
341 'const recovered=await invoke("unprotect_local_state",{value:cipher});' +
342 'return {roundtrip:recovered===source,encrypted:cipher!==source,hex:/^[0-9a-f]+$/i.test(cipher)};' +
343 '})()');
344 assert.deepEqual(dpapi, {roundtrip:true,encrypted:true,hex:true});
345 report.dpapi = 'native-Windows-roundtrip-passed';
346 }
347 if (mode === 'fresh') {
348 // The real installed desktop window, not the browser-only preview:
349 // verify accounting activation, financial journal, stock, backup and RTL.
350 report.nativeFunctional = await verifyNativeFunctionalMatrix(cdp);
351 }
352 if (mode === 'fresh') {
353 // Verify encrypted .fbackup BEFORE sweeping all 10 native UI routes.
354 // Intentional wrong-password toast/dialog are dismissed through the UI;
355 // unexpected errors still fail the following navigation regression.
356 const script = fs.readFileSync(
357 path.join(__dirname, 'windows-vm-encrypted-company-backup-browser.js'), 'utf8'
358 );
359 const validated = await cdp.evaluate(script);
360 assert.deepEqual(validated, {
361 encryptedEnvelope: true,
362 filenameSuffix: '.fbackup',
363 wrongPasswordRejected: true,
364 tamperedCiphertextRejectedWithoutWrites: true,
365 lateFinancialValidationRolledBack: true,
366 sameCompanyRestore: true,
367 restoredContact: true,
368 restoreAudited: true,
369 plaintextSensitiveDataAbsent: true
370 });
371 report.encryptedCompanyBackup =
372 'native-SettingsUI-AES-GCM-PBKDF2-wrong-password-and-audited-restore-passed';
373 }
374 if (mode === 'fresh') {
375 // Drive synthetic records, complete snapshot replay and every SPA route
376 // inside the actually installed Tauri WebView2, not Vite preview.
377 const ui = await cdp.evaluate("(async () => {\n const ensure = (pass, message) => { if (!pass) throw Error(message); };\n ensure(!document.getElementById('finoraAuthOverlay'), 'Cannot test UI before login');\n const person = await window.ContactController.create({\n name: 'شخص آزمایشی ماشین مجازی', role: 'both'\n });\n const product = await window.ProductController.createProduct({\n name: 'کالای آزمایشی ماشین مجازی', code: 'WINDOWS-VM-LAB',\n buyPrice: 150, sellPrice: 250, trackInventory: true\n });\n const db = window.FINORA.Storage;\n const before = {\n contacts: (await db.getAll('contacts')).length,\n products: (await db.getAll('products')).length\n };\n ensure((await db.get('contacts',person.id))?.name === 'شخص آزمایشی ماشین مجازی',\n 'Contact did not persist in the native app');\n ensure((await db.get('products',product.id))?.sellPrice === 250,\n 'Product did not persist in the native app');\n const snapshot = await db.exportAll();\n ensure(snapshot.version === 7 && snapshot.app === 'Factor-easyPro',\n 'Native snapshot identity/version mismatch');\n ensure(snapshot.data.users.every(u => !u.pwHash && !u.pwSalt && !u.pass),\n 'Credential hash leaked into plain export');\n ensure(snapshot.data.contacts.some(c => c.id === person.id) &&\n snapshot.data.products.some(p => p.id === product.id),\n 'Native snapshot missing committed master data');\n ensure(await db.importAll(snapshot) === true,\n 'Native full snapshot replay did not succeed');\n const after = {\n contacts: (await db.getAll('contacts')).length,\n products: (await db.getAll('products')).length\n };\n ensure(before.contacts === after.contacts && before.products === after.products,\n 'Snapshot replay duplicated a contact or product');\n const routes = [\n 'dashboard', 'invoices', 'products', 'contacts', 'treasury',\n 'cheques', 'expenses', 'reports', 'accounting', 'settings'\n ];\n const pages = [];\n for (const route of routes) {\n await FINORA.Router.go(route);\n const view = document.getElementById('pageContent');\n const text = (view?.textContent || '').trim();\n ensure(FINORA.Router.current() === route, 'Unexpected route: ' + route);\n ensure(text.length > 10, 'Empty page: ' + route);\n ensure(!text.includes('خطا در بارگذاری صفحه'),\n 'Router reported a page rendering error: ' + route);\n ensure(!document.querySelector('.toast-error'),\n 'Error toast while navigating to: ' + route);\n pages.push({route, renderedCharacters: text.length});\n }\n await FINORA.Router.go('dashboard');\n ensure(!document.getElementById('finoraAuthOverlay'),\n 'Navigation unexpectedly returned to authentication overlay');\n return {masterData:before, backup:'plain-no-credentials-replay-idempotent',\n routes:pages, visibleVersion:FINORA.version};\n})()", 45000);
378 assert.equal(ui.routes.length, 10);
379 assert.equal(ui.visibleVersion, expectedVersion);
380 report.nativeUI = ui;
381 try {
382 const screen = await cdp.command('Page.captureScreenshot', {
383 format: 'png', captureBeyondViewport: false, fromSurface: true
384 });
385 if (!screen?.data) throw Error('No PNG image data');
386 const filename = path.join(path.dirname(reportPath), 'fresh-native-dashboard.png');
387 fs.writeFileSync(filename, Buffer.from(screen.data, 'base64'));
388 report.screenshot = path.basename(filename);
389 } catch (screenshotError) {
390 // A screenshot is NOT claimed as verified if native CDP denies it.
391 report.screenshot = 'UNVERIFIED: ' + screenshotError.message;
392 }
393 }
394 if (mode === 'fresh') {
395 // Q01: click every safe, visible route/tab/form opener in the installed
396 // WebView2 (not only a preview). Financial writes remain separately
397 // guarded by the real synthetic functional matrix already run above.
398 const auditSource = fs.readFileSync(
399 path.join(__dirname, 'windows-vm-ui-interaction-audit-browser.js'), 'utf8');
400 assert.equal(auditSource.split('const safeConfirmAction =').length-1,1,
401 'native UI audit must define its cancel-only destructive matcher exactly once');
402 assert.ok(auditSource.includes('const q01TextOnlyConfirmCard_20261031='),
403 'native UI audit must use a collision-resistant confirmation-card binding');
404 assert.ok(!auditSource.includes('const safeConfirm='),
405 'generic safeConfirm lexical binding can collide in the long-lived WebView2 realm');
406 assert.ok(auditSource.includes('const deferredSafeActions=[]'),
407 'native UI audit must defer filters until row-scoped probes finish');
408 assert.ok(auditSource.includes('for(const group of deferredSafeActions)'),
409 'native UI audit must execute queued filters after editor/confirmation probes');
410 const audit = await cdp.evaluate(auditSource, 240000);
411 const fixtureCoverage = require('../scripts/q01-native-action-coverage.cjs').annotateAudit(audit, {
412 nativeFunctional: report.nativeFunctional,
413 encryptedCompanyBackup: report.encryptedCompanyBackup ===
414 'native-SettingsUI-AES-GCM-PBKDF2-wrong-password-and-audited-restore-passed',
415 modalKeyboard: audit.shellResults?.modalKeyboard,
416 routesVisited: audit.routesVisited
417 });
418 report.nativeControlCoverage = fixtureCoverage;
419 assert.equal(audit.environment, 'installed-Windows-Tauri-WebView2-synthetic-VM');
420 assert.equal(audit.routesVisited, 10);
421 assert.equal(audit.shellResults.keyboardReachableSidebarLinks, 10);
422 assert.equal(audit.shellResults.sidebarCollapseClickAndPersistence, true);
423 assert.equal(audit.shellResults.themeToggleClickAndPersistence, true);
424 assert.equal(audit.shellResults.activeRouteAriaCurrent, true);
425 assert.equal(audit.shellResults.modalKeyboard.nestedDialogIsolation, true);
426 assert.equal(audit.shellResults.modalKeyboard.modalFormLabelsLinked, true);
427 assert.equal(audit.shellResults.modalKeyboard.expenseUnsafeHtmlEscaped, true);
428 assert.equal(audit.shellResults.modalKeyboard.importedInvoiceHtmlEscaped, true);
429 assert.equal(audit.shellResults.modalKeyboard.excelReplacementRejectedWithoutWrites, true);
430 assert.equal(audit.shellResults.modalKeyboard.financialLedgerContentEscaped, true);
431 assert.equal(audit.shellResults.modalKeyboard.privateExcelPreviewAndSingleFlight, true);
432 assert.equal(audit.shellResults.modalKeyboard.escapeClosesWithoutConfirm, true);
433 assert.equal(audit.shellResults.modalKeyboard.focusReturnsToTrigger, true);
434 assert.equal(audit.shellResults.modalKeyboard.visibleInputAutoFocused, true);
435 assert.equal(audit.problems.filter(x=>x.kind==='modal-a11y-missing').length, 0,
436 'An opened financial dialog failed to move keyboard focus inside itself');
437 const modalInteractionProblems=audit.problems.filter(x=>[
438 'nested-safe-action-did-not-open-dialog',
439 'nested-modal-a11y-missing',
440 'nested-modal-cancel-did-not-restore-parent',
441 'invoice-draft-add-row-failed',
442 'invoice-draft-remove-new-row-missing',
443 'invoice-draft-row-count-not-restored',
444 'invoice-last-row-removal-not-blocked',
445 'unsaved-contact-tag-not-added'
446 ].includes(x.kind) || (
447 x.kind==='no-visible-change' &&
448 /InvoiceFormView\\._addRow/.test(x.handler||'')
449 ));
450 assert.deepEqual(modalInteractionProblems, [],
451 'Native nested-modal, invoice-row or unsaved-contact-tag interaction regressed');
452 assert.equal(audit.shellResults.modalKeyboard.enterOnFocusedCancelDoesNotSave, true);
453 assert.equal(audit.shellResults.modalKeyboard.enterOnInputDoesNotSubmit, true);
454 assert.equal(audit.shellResults.modalKeyboard.tabAndShiftTabStayInsideTopDialog, true);
455 assert.equal(audit.shellResults.modalKeyboard.cancelDoesNotConfirmAndRestoresFocus, true);
456 assert.equal(audit.shellResults.modalKeyboard.syntheticConfirmRunsExactlyOnce, true);
457 assert.equal(audit.shellResults.modalKeyboard.staleFinancialConfirmIgnored, true);
458 assert.equal(audit.shellResults.toastResults.importantErrorsRemain, true);
459 assert.equal(audit.shellResults.toastResults.dismissButtonsWork, true);
460 assert.ok(audit.inventoryCount >= 25, 'Too few visible controls discovered');
461 assert.ok(audit.uniqueActionCount >= 20 &&
462 audit.uniqueActionCount <= audit.inventoryCount,
463 'Unique action signatures have an invalid or unexpectedly small count');
464 assert.ok(audit.uniqueActionClicked <= audit.uniqueActionCount &&
465 audit.uniqueActionUnverified <= audit.uniqueActionCount,
466 'Unique action status totals exceed unique action signatures');
467 assert.equal(audit.duplicateInstanceCount,
468 audit.inventoryCount-audit.uniqueActionCount);
469 assert.ok(audit.controls.every(x=>x.status!=='not-clicked' || !!x.reason),
470 'Every nonclicked control must have a machine-readable reason');
471 assert.ok(audit.fieldsInspected >= 15, 'Visible form-field inventory unexpectedly small');
472 assert.ok(Number.isInteger(audit.fieldsMissingProgrammaticLabel), 'No programmatic label coverage reported');
473 assert.equal(audit.fieldsMissingProgrammaticLabel, 0,
474 'Every visible financial input must have a programmatic label: ' +
475 JSON.stringify((audit.fieldsWithoutLabels || []).map(field => ({
476 route: field.route, section: field.section,
477 id: field.id, tag: field.tag, type: field.type
478 }))));
479 assert.ok(audit.safeClickCount >= 15, 'Safe interaction coverage unexpectedly low');
480 assert.equal(audit.uniqueActionFailed, 0, 'A native UI action click failed');
481 assert.equal(audit.brokenHandlerCount, 0, 'A visible control points to a missing handler');
482 assert.equal(audit.accessibilityNameGaps, 0, 'A visible control has no accessible name');
483 const blockingUiProblems=audit.problems.filter(x=>[
484 'safe-action-vanished','safe-tab-vanished','confirm-action-vanished',
485 'open-action-vanished','confirmation-prompt-missing',
486 'confirmation-cancel-missing','confirmation-cancel-did-not-close',
487 'cancel-mutated-persistent-data','responsive-horizontal-overflow',
488 'cheque-table-horizontal-scroll-accessibility',
489 'cheque-table-scroll-not-keyboard-focusable'
490 ].includes(x.kind));
491 assert.deepEqual(blockingUiProblems,[],
492 'Native UI audit has unresolved action-target, cancel-safety or responsive-layout failures');
493 assert.equal(audit.customerDataUsed, false);
494 assert.equal(audit.financialActionsNotBulkClicked, true);
495 assert.equal(audit.everyActionVerified, false,
496 'A safe-navigation sweep cannot claim every financial action is verified');
497 report.nativeControlAudit = {
498 routesVisited: audit.routesVisited, shellResults: audit.shellResults,
499 inventoryCount: audit.inventoryCount,
500 uniqueActionCount: audit.uniqueActionCount,
501 uniqueActionClicked: audit.uniqueActionClicked,
502 uniqueActionUnverified: audit.uniqueActionUnverified,
503 uniqueActionCoveredByFixture: fixtureCoverage.fixtureCoveredNotClicked,
504 uniqueActionWithoutFixtureEvidence: fixtureCoverage.withoutFixtureEvidence,
505 uniqueActionDisabled: audit.uniqueActionDisabled,
506 uniqueActionFailed: audit.uniqueActionFailed,
507 duplicateInstanceCount: audit.duplicateInstanceCount,
508 unclassifiedInstances: audit.unclassifiedInstances,
509 safeClickCount: audit.safeClickCount, skippedCount: audit.skippedCount,
510 accessibilityNameGaps: audit.accessibilityNameGaps,
511 fieldsInspected: audit.fieldsInspected,
512 fieldsMissingProgrammaticLabel: audit.fieldsMissingProgrammaticLabel,
513 fieldCoverageByRoute: audit.fieldCoverageByRoute,
514 brokenHandlerCount: audit.brokenHandlerCount,
515 problems: audit.problems.length, byRoute: audit.byRoute,
516 evidenceFile: 'fresh-native-ui-control-click-audit.json',
517 claim: 'safe-clicks-and-inventory-only-not-every-button-verified'
518 };
519 fs.writeFileSync(path.join(path.dirname(reportPath),
520 report.nativeControlAudit.evidenceFile),
521 JSON.stringify(audit, null, 2), { flag: 'wx' });
522 // The Markdown matrix is for owner/QA review and includes every
523 // remaining unique action with its route, reason and handler.
524 const gapReport=require('../scripts/q01-native-action-gap-report.cjs').buildReport(audit);
525 report.nativeControlAudit.gapReportFile='q01-native-unverified-controls.md';
526 fs.writeFileSync(path.join(path.dirname(reportPath),
527 report.nativeControlAudit.gapReportFile),gapReport,{flag:'wx'});
528 report.nativeControlAudit.fixtureCoverageFile='q01-native-fixture-coverage.md';
529 fs.writeFileSync(path.join(path.dirname(reportPath),
530 report.nativeControlAudit.fixtureCoverageFile),
531 require('../scripts/q01-native-action-coverage.cjs').buildCoverageReport(fixtureCoverage),
532 {flag:'wx'});
533 const routeScreenshots = [];
534 for (const route of audit.routeNames) {
535 await cdp.evaluate('FINORA.Router.go(' + JSON.stringify(route) + ')', 20000);
536 const screen = await cdp.command('Page.captureScreenshot', {
537 format: 'png', captureBeyondViewport: false, fromSurface: true
538 }, 20000);
539 assert.ok(screen?.data, 'Screenshot missing for route ' + route);
540 const image = Buffer.from(screen.data, 'base64');
541 assert.ok(image.length > 1000 && image.subarray(1,4).toString('ascii') === 'PNG',
542 'Bad native WebView2 PNG for route ' + route);
543 const filename = 'q01-ui-' + route + '.png';
544 fs.writeFileSync(path.join(path.dirname(reportPath), filename), image, { flag: 'wx' });
545 routeScreenshots.push(filename);
546 }
547 report.nativeControlAudit.routeScreenshots = routeScreenshots;
548 await cdp.evaluate('FINORA.Router.go("dashboard")');
549 }
550 if (mode === 'fresh') {
551 // A07: emulate a disconnected WebView2 network on the REAL installed app.
552 // This is stronger than jsdom/offline browser preview but not an OS
553 // Wi-Fi disable, physical power loss, or a disconnected customer device.
554 await cdp.command('Network.enable');
555 await cdp.command('Network.emulateNetworkConditions', {
556 offline: true, latency: 0, downloadThroughput: 0, uploadThroughput: 0
557 });
558 try {
559 const offline = await cdp.evaluate(`(async () => {
560 if (navigator.onLine !== false) throw Error('WebView2 offline emulation did not set navigator offline');
561 const routes = [
562 'dashboard','invoices','products','contacts','treasury',
563 'cheques','expenses','reports','accounting','settings'
564 ];
565 const timings = [];
566 for (const route of routes) {
567 const t = performance.now();
568 await FINORA.Router.go(route);
569 const body = (document.getElementById('pageContent')?.textContent || '').trim();
570 if (FINORA.Router.current() !== route || body.length <= 10 ||
571 body.includes('خطا در بارگذاری صفحه') ||
572 document.querySelector('.toast-error') ||
573 document.getElementById('finoraAuthOverlay')) {
574 throw Error('Installed app route failed while offline: ' + route);
575 }
576 timings.push({ route, milliseconds: Math.round(performance.now() - t) });
577 }
578 await FINORA.Router.go('dashboard');
579 return { simulatedOffline: !navigator.onLine, routesChecked: timings.length,
580 routeDurationsMs: timings };
581 })()`, 45000);
582 assert.equal(offline.simulatedOffline, true);
583 assert.equal(offline.routesChecked, 10);
584 assert.equal(offline.routeDurationsMs.length, 10);
585 report.nativeOffline = offline;
586 } finally {
587 // Preserve the runner's network state for post-run evidence upload.
588 await cdp.command('Network.emulateNetworkConditions', {
589 offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1
590 });
591 }
592 }
593 if (mode === 'benchmark' || mode === 'stability') {
594 // A08 performance sample from the actually installed NSIS/Tauri/WebView2
595 // binary with a brand-new disposable profile, not Node fake-indexeddb.
596 // The separate profile prevents benchmark fixtures from affecting
597 // upgrade, accounting or restoration tests.
598 const code = fs.readFileSync(
599 path.join(__dirname, 'windows-vm-native-performance-browser.js'), 'utf8'
600 );
601 // CDP is attached to the actual installed Windows WebView2 renderer.
602 // JS heap is not total process RSS or Windows working set; record
603 // accurately, without claiming physical memory or SLA verification.
604 const beforeHeap = await cdp.command('Runtime.getHeapUsage', {}, 30000);
605 const measured = await cdp.evaluate(code, 240000);
606 const afterHeap = await cdp.command('Runtime.getHeapUsage', {}, 30000);
607 assert.equal(measured.products, 10000);
608 assert.equal(measured.invoices, 50000);
609 assert.equal(measured.companyInvoices, 50000);
610 assert.equal(measured.environment, 'installed-Tauri-WebView2-IndexedDB');
611 assert.ok(measured.timingsMs.seedProducts >= 0 &&
612 measured.timingsMs.seedInvoices >= 0 &&
613 measured.timingsMs.companyInvoiceReadP95 >= 0 &&
614 measured.timingsMs.snapshotExport >= 0 &&
615 measured.timingsMs.reportsReload >= 0 &&
616 measured.timingsMs.encryptedBackup >= 0);
617 for (const tab of ['pl','sales','products','customers']) {
618 assert.ok(measured.reportTabs?.[tab]?.htmlCharacters >= 200,
619 'A08 installed report tab was not rendered: ' + tab);
620 }
621 assert.equal(measured.encryptedBackup?.schemaVersion, 7);
622 assert.equal(measured.encryptedBackup?.products, 10000);
623 assert.equal(measured.encryptedBackup?.invoices, 50000);
624 assert.equal(measured.encryptedBackup?.filenameSuffix, '.fbackup');
625 assert.equal(measured.encryptedBackup?.companyScoped, true);
626 assert.equal(measured.encryptedBackup?.credentialsExcluded, true);
627 assert.ok(measured.encryptedBackup?.bytes > 100000,
628 'A08 large encrypted backup is suspiciously small');
629 const validHeap = item =>
630 Number.isSafeInteger(item?.usedSize) && item.usedSize >= 0 &&
631 Number.isSafeInteger(item?.totalSize) && item.totalSize >= item.usedSize;
632 assert.ok(validHeap(beforeHeap) && validHeap(afterHeap),
633 'A08 installed WebView2 JS heap size metrics are not valid');
634 measured.jsHeapBytes = {
635 beforeUsed: beforeHeap.usedSize,
636 afterUsed: afterHeap.usedSize,
637 afterAllocated: afterHeap.totalSize,
638 usedChange: afterHeap.usedSize - beforeHeap.usedSize
639 };
640 measured.jsHeapScope = 'renderer-js-heap-not-total-Windows-process-memory';
641 report.nativePerformance = measured;
642 if (mode === 'stability') {
643 const cycleCode = fs.readFileSync(
644 path.join(__dirname, 'windows-vm-native-memory-stability-browser.js'), 'utf8');
645 const cycles = [];
646 const heap = async () => {
647 const usage = await cdp.command('Runtime.getHeapUsage', {}, 30000);
648 assert.ok(Number.isSafeInteger(usage.usedSize) && usage.usedSize >= 0);
649 return { usedBytes: usage.usedSize, allocatedBytes: usage.totalSize };
650 };
651 // Windows process tree metrics are distinct from CDP renderer JS heap.
652 // Capture installed Tauri parent + descendants using OS process counters.
653 // A transient CIM failure is recorded, not converted to a zero reading.
654 const windowsProcessMemory = () => {
655 try {
656 const script = [
657 '$ErrorActionPreference = "Stop"',
658 '$all = @(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,PrivatePageCount)',
659 '$ids = [System.Collections.Generic.HashSet[int]]::new()',
660 '[void]$ids.Add(' + proc.pid + ')',
661 'do { $before = $ids.Count; foreach ($p in $all) { if ($ids.Contains([int]$p.ParentProcessId)) { [void]$ids.Add([int]$p.ProcessId) } } } while ($ids.Count -gt $before)',
662 '$members = @($all | Where-Object { $ids.Contains([int]$_.ProcessId) })',
663 'if ($members.Count -lt 1) { throw "Installed process not found" }',
664 '$ws = ($members | Measure-Object -Property WorkingSetSize -Sum).Sum',
665 '$private = ($members | Measure-Object -Property PrivatePageCount -Sum).Sum',
666 '@{ processCount=$members.Count; workingSetBytes=[long]$ws; privateBytes=[long]$private } | ConvertTo-Json -Compress'
667 ].join('; ');
668 const sample = JSON.parse(execFileSync('powershell.exe',
669 ['-NoProfile', '-NonInteractive', '-Command', script],
670 { encoding: 'utf8', timeout: 30000 }));
671 assert.ok(Number.isSafeInteger(sample.workingSetBytes) &&
672 sample.workingSetBytes > 0 && Number.isSafeInteger(sample.privateBytes) &&
673 sample.privateBytes > 0 && sample.processCount > 0);
674 return sample;
675 } catch (error) {
676 return { unavailable: true, reason: 'Windows CIM process-tree sample unavailable' };
677 }
678 };
679 let gcSupported = true;
680 const collect = async () => {
681 try { await cdp.command('HeapProfiler.collectGarbage', {}, 30000); }
682 catch (_) { gcSupported = false; }
683 };
684 await collect();
685 const baseline = await heap();
686 const processBaseline = windowsProcessMemory();
687 const endurance = process.env.A08_ENDURANCE === '1';
688 const count = endurance ? 240 : 10;
689 const intervalMs = endurance ? 30000 : 0;
690 const started = performance.now();
691 const checkpoint = () => {
692 if (!reportPath) return;
693 const target = path.join(path.dirname(reportPath), 'stability-checkpoint.json');
694 fs.writeFileSync(target + '.tmp', JSON.stringify(report, null, 2));
695 fs.renameSync(target + '.tmp', target);
696 };
697 report.nativeMemoryStability = {
698 status: 'RUNNING', synthetic: true, cycles, baseline, processBaseline,
699 gcSupported, count, intervalMs, endurance
700 };
701 checkpoint();
702 for (let i = 0; i < count; i++) {
703 if (endurance) await wait(Math.max(0, started + i * intervalMs - performance.now()));
704 const elapsedMs = performance.now() - started;
705 const result = await cdp.evaluate(cycleCode, 120000);
706 assert.equal(result.products, 10000);
707 assert.equal(result.invoices, 50000);
708 assert.equal(result.companyInvoices, 50000);
709 assert.equal(result.rounds.length, 1);
710 const raw = await heap();
711 if (gcSupported) await collect();
712 const postGc = gcSupported ? await heap() : null;
713 const windowsProcessTree = windowsProcessMemory();
714 cycles.push({ cycle: i + 1, elapsedMs, durationMs: result.rounds[0].durationMs,
715 raw, postGc, windowsProcessTree });
716 report.nativeMemoryStability.gcSupported = gcSupported;
717 checkpoint();
718 if (endurance) {
719 assert.ok(gcSupported && !windowsProcessTree.unavailable && !processBaseline.unavailable,
720 'Endurance memory evidence unavailable');
721 assert.ok(performance.now() - started <= (i + 1) * intervalMs,
722 'Endurance sample exceeded its scheduled interval');
723 }
724 }
725 if (endurance) await wait(Math.max(0, started + count * intervalMs - performance.now()));
726 report.nativeMemoryStability = {
727 count, intervalMs, endurance, elapsedMs: performance.now() - started,
728 status: 'PASSED', synthetic: true, cycles, baseline, processBaseline,
729 gcSupported, heapScope: 'renderer-js-heap-not-Windows-working-set',
730 windowsProcessScope: 'installed-Tauri-parent-and-descendant-processes',
731 note: 'Diagnostic series only; no leak verdict or SLA implied'
732 };
733 checkpoint();
734 }
735
736 }
737 if (mode === 'fresh') {
738 // LAST operation: real installed WebView2 PDF engine, using production
739 // RTL formal-invoice renderer with 110 synthetic items only.
740 const code = fs.readFileSync(
741 path.join(__dirname, 'windows-vm-native-print-pdf-browser.js'), 'utf8');
742 const template = await cdp.evaluate(code, 60000);
743 assert.equal(template.itemRows, 110);
744 const printed = await cdp.command('Page.printToPDF', {
745 printBackground: true, preferCSSPageSize: true,
746 displayHeaderFooter: false
747 }, 90000);
748 assert.ok(printed?.data, 'Installed WebView2 returned no PDF');
749 const pdf = Buffer.from(printed.data, 'base64');
750 assert.ok(pdf.length > 10000 && pdf.subarray(0, 5).toString('ascii') === '%PDF-',
751 'Invalid WebView2 PDF result');
752 const pages = [...pdf.toString('latin1').matchAll(/\/Type\s*\/Page\b/g)].length;
753 assert.ok(pages >= 2, 'Invoice PDF is not multipage: ' + pages);
754 const filename = 'a07-native-rtl-multipage-invoice.pdf';
755 fs.writeFileSync(path.join(path.dirname(reportPath), filename), pdf);
756 report.nativePrint = { ...template, pages, pdfBytes: pdf.length,
757 filename, physicalPrinter: 'not-tested' };
758 }
759 report.status = 'PASSED';
760 console.log(JSON.stringify(report, null, 2));
761 } catch (err) {
762 report.error = err.stack || String(err);
763 console.error(JSON.stringify(report, null, 2));
764 process.exitCode = 1;
765 } finally {
766 if (reportPath) fs.writeFileSync(reportPath, JSON.stringify(report, null, 2) + '\n');
767 try { cdp?.close(); } catch {}
768 // Ensure no WebView2 child process can hold the previous NSIS executable
769 // open during the subsequent in-place upgrade on this disposable runner.
770 if (proc?.pid) {
771 try {
772 execFileSync('taskkill.exe', ['/PID', String(proc.pid), '/T', '/F'],
773 { stdio: 'ignore', timeout: 10000 });
774 } catch (_) { try { proc.kill(); } catch (_) {} }
775 }
776 cleanDebugPolicies(debugPolicyKeys);
777 await wait(700);
778 }
779 })().catch(error => { console.error(error); process.exitCode = 1; });