dev-tools: the generic development harnesses (perf probes, close check, tab and webview stress)
Moved from wayBetter for X; an app passes its own origin, process name, scripts and fixtures.
This commit is contained in:
parent
3d1c08bba4
commit
5c64f2f6f8
10 changed files with 1106 additions and 0 deletions
27
dev-tools/README.md
Normal file
27
dev-tools/README.md
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
# dev-tools
|
||||||
|
|
||||||
|
Development harnesses for a wayBetter app. They are not part of the npm package and nothing here
|
||||||
|
ships in an app: they probe a build you start yourself. Each file's header says exactly what it
|
||||||
|
does and what it never does (site pages are only read and reloaded, never clicked; nothing is
|
||||||
|
uploaded; the owner's session is not touched unless the header says a disposable profile is
|
||||||
|
needed).
|
||||||
|
|
||||||
|
An app calls them with its own values. wayBetter for X keeps thin wrappers
|
||||||
|
(`apps/desktop/scripts/*`, `verification/live-check/*`) that pass X's origin, process name, theme
|
||||||
|
commands, scripts and fixtures.
|
||||||
|
|
||||||
|
| Tool | Runs against | What it measures or checks |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `perf-probe.mjs` (`runPerfProbe`) | headless Chromium, the app's injected scripts, the app's fixtures | script evaluation time, fetch/XHR wrapper layers and overhead, Response clones, large JSON parses, observer / rAF / timer work of the scripts, long tasks |
|
||||||
|
| `runtime-start-check.mjs` (`runtimeStartCheck`) | headless Chromium, the built page runtime, static fixtures | the runtime installs at document start; every feature flag on, off, default without a console or page error |
|
||||||
|
| `resize-perf.mjs` | a running release build with a WebView2 CDP port | `theme` (first paint vs. theme applied), `drag` (divider drag: shell frames, `tabs_sync`, native lag), `switch` (click to tab visible), `window` (with `window-resize.ps1`) |
|
||||||
|
| `window-resize.ps1` | the app's window (Windows) | a repeatable ~2 s resize workload; never activates the window |
|
||||||
|
| `close-check.ps1` | the app's release exe (Windows) | the app exits on a plain `taskkill /PID` in every window state and on a simulated sign-out |
|
||||||
|
| `native-tab-stress.mjs` | a running build with a CDP port | opens shell start tabs, measures responsiveness, closes them |
|
||||||
|
| `native-webview-stress.mjs` | a running build with a CDP port, a fresh WebView2 profile | ramps native site tabs (6, 12, 24) and records process memory; stops at a memory limit |
|
||||||
|
| `native-stress-watch.ps1` | the app's process tree (Windows) | independent CPU and memory telemetry while a stress run is going |
|
||||||
|
| `native-stale-shortcut-check.mjs` | an isolated release build with a CDP port | a stale tab id in a shortcut never targets the active tab |
|
||||||
|
|
||||||
|
Requirements: Node 24+, and for the headless probes `playwright` in the app (the probe takes the
|
||||||
|
app's `chromium`). The CDP tools need the app started with
|
||||||
|
`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>`.
|
||||||
137
dev-tools/close-check.ps1
Normal file
137
dev-tools/close-check.ps1
Normal file
|
|
@ -0,0 +1,137 @@
|
||||||
|
# Graceful-close regression check (Windows): the app must exit on a plain `taskkill /PID` (WM_CLOSE,
|
||||||
|
# no /F) in every window state, and on a simulated sign-out (WM_QUERYENDSESSION + WM_ENDSESSION).
|
||||||
|
#
|
||||||
|
# Why: tao's thread event target and the single-instance plugin's message window are visible 1 px
|
||||||
|
# unowned top-level windows. taskkill closes only the first such window in z-order; a minimized
|
||||||
|
# window sinks below them, so before the fix the close destroyed a helper and the app stayed alive.
|
||||||
|
#
|
||||||
|
# powershell -ExecutionPolicy Bypass -File dev-tools/close-check.ps1 -Exe <the app's release exe> [-Cases normal,minimized,...]
|
||||||
|
#
|
||||||
|
# Cases: normal, minimized, maximized,
|
||||||
|
# unfocused (another window in front), debugport (WebView2 remote debugging on), endsession
|
||||||
|
# (minimized, then the sign-out messages). Every case restarts the app with the owner's saved
|
||||||
|
# layout (tabs, deck columns); "webviews" counts the shell plus every tab/column webview. Any
|
||||||
|
# running copy of the same exe is closed first; a copy that does not exit is only force-killed when
|
||||||
|
# its path is this exe. Relaunch the app normally afterwards.
|
||||||
|
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][string]$Exe,
|
||||||
|
[string[]]$Cases = @('normal', 'minimized', 'maximized', 'unfocused', 'debugport', 'endsession'),
|
||||||
|
[int]$StartupSeconds = 10,
|
||||||
|
[int]$ExitSeconds = 10
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$Exe = (Resolve-Path $Exe).Path
|
||||||
|
$ProcessName = [IO.Path]::GetFileNameWithoutExtension($Exe)
|
||||||
|
|
||||||
|
Add-Type @"
|
||||||
|
using System; using System.Text; using System.Runtime.InteropServices; using System.Collections.Generic;
|
||||||
|
public static class CloseCheckWin {
|
||||||
|
public delegate bool EnumProc(IntPtr h, IntPtr l);
|
||||||
|
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc p, IntPtr l);
|
||||||
|
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
|
||||||
|
[DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int GetClassName(IntPtr h, StringBuilder s, int n);
|
||||||
|
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
|
||||||
|
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
||||||
|
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int c);
|
||||||
|
[DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
|
||||||
|
[DllImport("user32.dll")] public static extern IntPtr SendMessageTimeout(IntPtr h, uint m, IntPtr w, IntPtr l, uint flags, uint ms, out IntPtr r);
|
||||||
|
public static List<IntPtr> Windows(uint pid) {
|
||||||
|
var r = new List<IntPtr>();
|
||||||
|
EnumWindows((h, l) => { uint p; GetWindowThreadProcessId(h, out p); if (p == pid) r.Add(h); return true; }, IntPtr.Zero);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
[DllImport("user32.dll")] static extern bool EnumChildWindows(IntPtr h, EnumProc p, IntPtr l);
|
||||||
|
public static int CountChildren(IntPtr parent, string cls) {
|
||||||
|
int n = 0;
|
||||||
|
EnumChildWindows(parent, (h, l) => { if (ClassOf(h) == cls) n++; return true; }, IntPtr.Zero);
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
public static string ClassOf(IntPtr h) { var c = new StringBuilder(256); GetClassName(h, c, 256); return c.ToString(); }
|
||||||
|
}
|
||||||
|
"@
|
||||||
|
|
||||||
|
function Get-Ours { Get-Process $ProcessName -ErrorAction SilentlyContinue | Where-Object { $_.Path -eq $Exe } }
|
||||||
|
|
||||||
|
function Describe-Windows([int]$ProcessId) {
|
||||||
|
([CloseCheckWin]::Windows([uint32]$ProcessId) | Where-Object { [CloseCheckWin]::IsWindowVisible($_) } | ForEach-Object {
|
||||||
|
$class = [CloseCheckWin]::ClassOf($_)
|
||||||
|
if ([CloseCheckWin]::IsIconic($_)) { "$class(min)" } else { $class }
|
||||||
|
}) -join ' > '
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stop-Ours {
|
||||||
|
foreach ($p in @(Get-Ours)) {
|
||||||
|
& taskkill.exe /PID $p.Id 2>&1 | Out-Null
|
||||||
|
if (-not $p.WaitForExit($ExitSeconds * 1000)) {
|
||||||
|
Write-Host " (force-killing leftover $($p.Id) at $($p.Path))"
|
||||||
|
Stop-Process -Id $p.Id -Force
|
||||||
|
$p.WaitForExit(5000) | Out-Null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Start-Ours([hashtable]$Vars = @{}) {
|
||||||
|
$saved = @{}
|
||||||
|
foreach ($key in $Vars.Keys) { $saved[$key] = [Environment]::GetEnvironmentVariable($key); [Environment]::SetEnvironmentVariable($key, $Vars[$key]) }
|
||||||
|
try { Start-Process $Exe -WindowStyle Normal } finally {
|
||||||
|
foreach ($key in $saved.Keys) { [Environment]::SetEnvironmentVariable($key, $saved[$key]) }
|
||||||
|
}
|
||||||
|
$deadline = (Get-Date).AddSeconds(30)
|
||||||
|
do {
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
$p = Get-Ours | Select-Object -First 1
|
||||||
|
$main = if ($p) { [CloseCheckWin]::Windows([uint32]$p.Id) | Where-Object { [CloseCheckWin]::ClassOf($_) -eq 'Tauri Window' -and [CloseCheckWin]::IsWindowVisible($_) } | Select-Object -First 1 }
|
||||||
|
} until ($main -or (Get-Date) -gt $deadline)
|
||||||
|
if (-not $main) { throw "the app window did not appear" }
|
||||||
|
Start-Sleep -Seconds $StartupSeconds # tabs, deck columns and plugins load
|
||||||
|
return @{ Process = $p; Main = $main }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Wait-Exit($p) {
|
||||||
|
$watch = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
$exited = $p.WaitForExit($ExitSeconds * 1000)
|
||||||
|
return @{ Exited = $exited; Seconds = [math]::Round($watch.Elapsed.TotalSeconds, 1) }
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = @()
|
||||||
|
Stop-Ours
|
||||||
|
foreach ($case in $Cases) {
|
||||||
|
$extra = if ($case -eq 'debugport') { @{ WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = '--remote-debugging-port=9333' } } else { @{} }
|
||||||
|
$app = Start-Ours $extra
|
||||||
|
$p = $app.Process; $main = $app.Main
|
||||||
|
switch ($case) {
|
||||||
|
'minimized' { [CloseCheckWin]::ShowWindow($main, 6) | Out-Null }
|
||||||
|
'endsession' { [CloseCheckWin]::ShowWindow($main, 6) | Out-Null }
|
||||||
|
'maximized' { [CloseCheckWin]::ShowWindow($main, 3) | Out-Null }
|
||||||
|
'unfocused' {
|
||||||
|
[CloseCheckWin]::ShowWindow($main, 9) | Out-Null
|
||||||
|
$shell = Get-Process explorer -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1
|
||||||
|
if ($shell) { [CloseCheckWin]::SetForegroundWindow($shell.MainWindowHandle) | Out-Null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
$order = Describe-Windows $p.Id
|
||||||
|
$webviews = [CloseCheckWin]::CountChildren($main, 'WRY_WEBVIEW')
|
||||||
|
if ($case -eq 'endsession') {
|
||||||
|
# What Windows sends every top-level window at sign-out (ENDSESSION_LOGOFF).
|
||||||
|
$r = [IntPtr]::Zero
|
||||||
|
foreach ($h in [CloseCheckWin]::Windows([uint32]$p.Id)) { [CloseCheckWin]::SendMessageTimeout($h, 0x11, [IntPtr]::Zero, [IntPtr]0x80000000, 2, 2000, [ref]$r) | Out-Null }
|
||||||
|
foreach ($h in [CloseCheckWin]::Windows([uint32]$p.Id)) { [CloseCheckWin]::SendMessageTimeout($h, 0x16, [IntPtr]1, [IntPtr]0x80000000, 2, 2000, [ref]$r) | Out-Null }
|
||||||
|
} else {
|
||||||
|
& taskkill.exe /PID $p.Id 2>&1 | Out-Null
|
||||||
|
}
|
||||||
|
$outcome = Wait-Exit $p
|
||||||
|
$leftover = if ($outcome.Exited) { '' } else { Describe-Windows $p.Id }
|
||||||
|
$pass = $outcome.Exited
|
||||||
|
$results += [pscustomobject]@{ Case = $case; Pass = $pass; Seconds = $outcome.Seconds; Webviews = $webviews; WindowsBefore = $order; Leftover = $leftover }
|
||||||
|
Write-Host ('{0} {1,-16} exited={2} in {3}s webviews={5} [{4}]' -f ($(if ($pass) { 'ok ' } else { 'FAIL' })), $case, $outcome.Exited, $outcome.Seconds, $order, $webviews)
|
||||||
|
if (-not $pass) { Write-Host " still open: $leftover"; Stop-Ours }
|
||||||
|
}
|
||||||
|
|
||||||
|
$failed = @($results | Where-Object { -not $_.Pass })
|
||||||
|
Write-Host ''
|
||||||
|
Write-Host ("{0}/{1} close cases passed" -f ($results.Count - $failed.Count), $results.Count)
|
||||||
|
if ($failed.Count) { exit 1 }
|
||||||
|
exit 0
|
||||||
52
dev-tools/native-stale-shortcut-check.mjs
Normal file
52
dev-tools/native-stale-shortcut-check.mjs
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
// In an isolated release flavor, verify a stale explicit tab ID never targets the active tab.
|
||||||
|
// Usage: node dev-tools/native-stale-shortcut-check.mjs <cdp-port> <a page of the site, e.g. https://x.com/home>
|
||||||
|
const port = Number(process.argv[2]);
|
||||||
|
if (!Number.isInteger(port)) throw new Error('Invalid CDP port');
|
||||||
|
const sitePage = process.argv[3] ?? process.env.SITE_PAGE;
|
||||||
|
if (!sitePage) throw new Error('A page of the site to open is required (argument 2 or SITE_PAGE)');
|
||||||
|
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||||
|
const target = list.find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/'));
|
||||||
|
if (!target) throw new Error('Shell CDP target not found');
|
||||||
|
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
await new Promise(resolve => { socket.onopen = resolve; });
|
||||||
|
let serial = 0;
|
||||||
|
const pending = new Map();
|
||||||
|
socket.onmessage = event => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||||
|
};
|
||||||
|
const evaluate = expression => new Promise((resolve, reject) => {
|
||||||
|
const id = ++serial;
|
||||||
|
const timer = setTimeout(() => { pending.delete(id); reject(new Error('Shell CDP timed out')); }, 30_000);
|
||||||
|
pending.set(id, message => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if (message.result?.exceptionDetails) reject(new Error(JSON.stringify(message.result.exceptionDetails).slice(0, 500)));
|
||||||
|
else resolve(message.result?.result?.value);
|
||||||
|
});
|
||||||
|
socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, awaitPromise: true, returnByValue: true } }));
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const result = await evaluate(`(async () => {
|
||||||
|
const ids = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')]
|
||||||
|
.map(tab => tab.dataset.panelId);
|
||||||
|
const before = ids();
|
||||||
|
if (before.length !== 1) throw new Error('Expected one isolated initial tab');
|
||||||
|
await window.__TAURI__.event.emit('tab-open', { url: ${JSON.stringify(sitePage)}, background: true });
|
||||||
|
const waitFor = async count => {
|
||||||
|
const deadline = performance.now() + 10_000;
|
||||||
|
while (ids().length !== count && performance.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
if (ids().length !== count) throw new Error('Timed out waiting for ' + count + ' tabs');
|
||||||
|
};
|
||||||
|
await waitFor(2);
|
||||||
|
const created = ids().find(id => !before.includes(id));
|
||||||
|
await window.__TAURI__.event.emit('tab-shortcut', { id: created, shortcut: 'close-tab' });
|
||||||
|
await waitFor(1);
|
||||||
|
for (const shortcut of ['close-tab', 'split-right', 'open-panel']) {
|
||||||
|
await window.__TAURI__.event.emit('tab-shortcut', { id: created, shortcut });
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200));
|
||||||
|
if (ids().join() !== before.join()) throw new Error('Stale ' + shortcut + ' changed live tabs');
|
||||||
|
}
|
||||||
|
return { before, created, after: ids(), staleShortcuts: ['close-tab', 'split-right', 'open-panel'] };
|
||||||
|
})()`);
|
||||||
|
console.log(JSON.stringify(result));
|
||||||
|
} finally { socket.close(); }
|
||||||
57
dev-tools/native-stress-watch.ps1
Normal file
57
dev-tools/native-stress-watch.ps1
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)][int]$AppPid,
|
||||||
|
[Parameter(Mandatory = $true)][string]$OutputPath,
|
||||||
|
[int]$Seconds = 90,
|
||||||
|
[int]$IntervalSeconds = 2,
|
||||||
|
[int]$AbortAtWorkingSetMB = 0,
|
||||||
|
[string]$ExpectedExecutable = ''
|
||||||
|
)
|
||||||
|
|
||||||
|
# Independent telemetry for native-webview-stress.mjs. Follow only descendants of the
|
||||||
|
# isolated app PID; a hung shell CDP target cannot stop this watcher from recording CPU.
|
||||||
|
$previousCpu = @{}
|
||||||
|
$watch = [System.Diagnostics.Stopwatch]::StartNew()
|
||||||
|
while ($watch.Elapsed.TotalSeconds -lt $Seconds) {
|
||||||
|
$all = @(Get-CimInstance Win32_Process | Select-Object ProcessId, ParentProcessId)
|
||||||
|
$ids = @($AppPid)
|
||||||
|
do {
|
||||||
|
$children = @($all | Where-Object {
|
||||||
|
$ids -contains $_.ParentProcessId -and $ids -notcontains $_.ProcessId
|
||||||
|
} | Select-Object -ExpandProperty ProcessId)
|
||||||
|
$ids += $children
|
||||||
|
} while ($children.Count -gt 0)
|
||||||
|
|
||||||
|
$processes = @(Get-Process -Id $ids -ErrorAction SilentlyContinue)
|
||||||
|
if (-not ($processes | Where-Object Id -EQ $AppPid)) { break }
|
||||||
|
$rows = @($processes | ForEach-Object {
|
||||||
|
$cpu = if ($null -eq $_.CPU) { 0 } else { [double]$_.CPU }
|
||||||
|
$before = if ($previousCpu.ContainsKey($_.Id)) { $previousCpu[$_.Id] } else { $cpu }
|
||||||
|
$previousCpu[$_.Id] = $cpu
|
||||||
|
[pscustomobject]@{
|
||||||
|
pid = $_.Id
|
||||||
|
name = $_.ProcessName
|
||||||
|
cpuDeltaSeconds = [math]::Round($cpu - $before, 3)
|
||||||
|
cpuTotalSeconds = [math]::Round($cpu, 3)
|
||||||
|
workingSetMB = [math]::Round($_.WorkingSet64 / 1MB)
|
||||||
|
privateMB = [math]::Round($_.PrivateMemorySize64 / 1MB)
|
||||||
|
}
|
||||||
|
} | Sort-Object cpuDeltaSeconds -Descending)
|
||||||
|
$totalWorkingSetMB = ($rows | Measure-Object workingSetMB -Sum).Sum
|
||||||
|
[pscustomobject]@{
|
||||||
|
elapsedSeconds = [math]::Round($watch.Elapsed.TotalSeconds, 2)
|
||||||
|
processCount = $rows.Count
|
||||||
|
totalCpuDeltaSeconds = [math]::Round(($rows | Measure-Object cpuDeltaSeconds -Sum).Sum, 3)
|
||||||
|
totalWorkingSetMB = $totalWorkingSetMB
|
||||||
|
top = @($rows | Select-Object -First 8)
|
||||||
|
} | ConvertTo-Json -Depth 5 -Compress | Add-Content -LiteralPath $OutputPath
|
||||||
|
if ($AbortAtWorkingSetMB -gt 0 -and $totalWorkingSetMB -ge $AbortAtWorkingSetMB) {
|
||||||
|
$app = Get-CimInstance Win32_Process -Filter "ProcessId=$AppPid"
|
||||||
|
if ($app -and $ExpectedExecutable -and $app.ExecutablePath -ieq $ExpectedExecutable) {
|
||||||
|
[pscustomobject]@{ event = 'memory-abort'; appPid = $AppPid; workingSetMB = $totalWorkingSetMB } |
|
||||||
|
ConvertTo-Json -Compress | Add-Content -LiteralPath $OutputPath
|
||||||
|
Stop-Process -Id $AppPid -Force
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
Start-Sleep -Seconds $IntervalSeconds
|
||||||
|
}
|
||||||
70
dev-tools/native-tab-stress.mjs
Normal file
70
dev-tools/native-tab-stress.mjs
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
// Native shell stress for a wayBetter app through WebView2 CDP. Run only against an app started with
|
||||||
|
// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>.
|
||||||
|
// Opens 24 shell start tabs, measures responsiveness, then closes those tabs.
|
||||||
|
const port = process.argv[2] ?? '9344';
|
||||||
|
const count = Number(process.argv[3] ?? 24);
|
||||||
|
const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json();
|
||||||
|
const target = list.find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/'));
|
||||||
|
if (!target) throw new Error('Shell CDP target not found');
|
||||||
|
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
const ready = new Promise(resolve => { socket.onopen = resolve; });
|
||||||
|
const pending = new Map();
|
||||||
|
let serial = 0;
|
||||||
|
socket.onmessage = event => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||||
|
};
|
||||||
|
await ready;
|
||||||
|
const send = (method, params = {}) => new Promise(resolve => {
|
||||||
|
const id = ++serial;
|
||||||
|
pending.set(id, resolve);
|
||||||
|
socket.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
const evaluate = async expression => {
|
||||||
|
let timeout;
|
||||||
|
const result = await Promise.race([
|
||||||
|
send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }),
|
||||||
|
new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Shell unresponsive for 20 s')), 20_000); }),
|
||||||
|
]).finally(() => clearTimeout(timeout));
|
||||||
|
if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails));
|
||||||
|
return result.result?.result?.value;
|
||||||
|
};
|
||||||
|
const expression = `\n(async () => {
|
||||||
|
const count = ${count};
|
||||||
|
const before = document.querySelectorAll('.dv-tab').length;
|
||||||
|
const delays = [];
|
||||||
|
const longTasks = [];
|
||||||
|
const observer = new PerformanceObserver(list => {
|
||||||
|
for (const entry of list.getEntries()) longTasks.push(entry.duration);
|
||||||
|
});
|
||||||
|
observer.observe({ entryTypes: ['longtask'] });
|
||||||
|
let expected = performance.now() + 50;
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
const now = performance.now();
|
||||||
|
delays.push(Math.max(0, now - expected));
|
||||||
|
expected = now + 50;
|
||||||
|
}, 50);
|
||||||
|
const key = key => window.dispatchEvent(new KeyboardEvent('keydown', { key, ctrlKey: true, bubbles: true }));
|
||||||
|
const start = performance.now();
|
||||||
|
for (let i = 0; i < count; i++) key('t');
|
||||||
|
const dispatchMs = performance.now() - start;
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||||
|
const opened = document.querySelectorAll('.dv-tab').length;
|
||||||
|
for (let i = 0; i < count; i++) key('w');
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 300));
|
||||||
|
clearInterval(interval);
|
||||||
|
observer.disconnect();
|
||||||
|
return {
|
||||||
|
before, opened, afterCleanup: document.querySelectorAll('.dv-tab').length,
|
||||||
|
dispatchMs: Math.round(dispatchMs),
|
||||||
|
maxDelayMs: Math.round(Math.max(0, ...delays)),
|
||||||
|
maxLongTaskMs: Math.round(Math.max(0, ...longTasks)),
|
||||||
|
};
|
||||||
|
})()`;
|
||||||
|
try {
|
||||||
|
const result = await evaluate(expression);
|
||||||
|
console.log(JSON.stringify(result, null, 2));
|
||||||
|
if (result.opened !== result.before + count || result.afterCleanup !== result.before) process.exitCode = 1;
|
||||||
|
} finally {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
203
dev-tools/native-webview-stress.mjs
Normal file
203
dev-tools/native-webview-stress.mjs
Normal file
|
|
@ -0,0 +1,203 @@
|
||||||
|
// Exercise native WebView creation with actual site pages. Start the app's release build with
|
||||||
|
// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port> and, preferably,
|
||||||
|
// WEBVIEW2_USER_DATA_FOLDER pointing to a fresh directory. Nothing is clicked on the site.
|
||||||
|
// Usage: SITE_PAGES=https://x.com/home,https://x.com/explore node dev-tools/native-webview-stress.mjs <port> [6,12,24] [app-pid]
|
||||||
|
// (the first page is opened in every tab; with the mixed route mode the second in every other tab)
|
||||||
|
import { writeFile, unlink } from 'node:fs/promises';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
|
||||||
|
const port = process.argv[2] ?? '9344';
|
||||||
|
const stages = (process.argv[3] ?? '6,12,24').split(',').map(Number);
|
||||||
|
const appPid = process.argv[4] ? Number(process.argv[4]) : null;
|
||||||
|
const memoryLimitMB = Number(process.env.WAYBETTER_STRESS_MEMORY_LIMIT_MB ?? 6144);
|
||||||
|
const sitePages = (process.env.SITE_PAGES ?? '').split(',').map(page => page.trim()).filter(Boolean);
|
||||||
|
if (!sitePages.length) throw new Error('SITE_PAGES is required (pages of the site to open, comma separated)');
|
||||||
|
const siteOrigin = new URL(sitePages[0]).origin;
|
||||||
|
const routeMode = process.env.WAYBETTER_STRESS_ROUTE_MODE ?? 'home';
|
||||||
|
if (!stages.length || stages.some((n, i) => !Number.isInteger(n) || n < 1 || n > 24 || (i && n <= stages[i - 1]))) {
|
||||||
|
throw new Error('Stages must increase from 1 to at most 24');
|
||||||
|
}
|
||||||
|
if (appPid !== null && (!Number.isInteger(appPid) || appPid < 1)) throw new Error('Invalid app PID');
|
||||||
|
if (!Number.isFinite(memoryLimitMB) || memoryLimitMB < 1) throw new Error('Invalid memory limit');
|
||||||
|
if (!['home', 'mixed-home-explore'].includes(routeMode)) throw new Error('Invalid route mode');
|
||||||
|
const run = promisify(execFile);
|
||||||
|
async function processSnapshot() {
|
||||||
|
if (!appPid) return null;
|
||||||
|
const command = `$all=Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId;$ids=@(${appPid});do{$n=@($all | Where-Object { $ids -contains $_.ParentProcessId -and $ids -notcontains $_.ProcessId } | Select-Object -ExpandProperty ProcessId);$ids+= $n}while($n.Count -gt 0);@(Get-Process -Id $ids -ErrorAction SilentlyContinue | Select-Object Id,ProcessName,CPU,WorkingSet64) | ConvertTo-Json -Compress`;
|
||||||
|
const { stdout } = await run('powershell', ['-NoProfile', '-Command', command], { timeout: 15_000 });
|
||||||
|
const parsed = JSON.parse(stdout);
|
||||||
|
return Array.isArray(parsed) ? parsed : [parsed];
|
||||||
|
}
|
||||||
|
function processDelta(before, after) {
|
||||||
|
if (!before || !after) return null;
|
||||||
|
const old = new Map(before.map(item => [item.Id, item.CPU ?? 0]));
|
||||||
|
const rows = after.map(item => ({
|
||||||
|
pid: item.Id, name: item.ProcessName,
|
||||||
|
cpuSeconds: Math.round(((item.CPU ?? 0) - (old.get(item.Id) ?? 0)) * 10) / 10,
|
||||||
|
memoryMB: Math.round((item.WorkingSet64 ?? 0) / 1024 / 1024),
|
||||||
|
})).sort((a, b) => b.cpuSeconds - a.cpuSeconds);
|
||||||
|
return {
|
||||||
|
totalCpuSeconds: Math.round(rows.reduce((sum, row) => sum + row.cpuSeconds, 0) * 10) / 10,
|
||||||
|
totalMemoryMB: rows.reduce((sum, row) => sum + row.memoryMB, 0),
|
||||||
|
top: rows.slice(0, 6),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const targets = async () => (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json());
|
||||||
|
const target = (await targets()).find(item => item.type === 'page' && item.url.startsWith('http://tauri.localhost/'));
|
||||||
|
if (!target) throw new Error('Shell CDP target not found');
|
||||||
|
const socket = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
const ready = new Promise(resolve => { socket.onopen = resolve; });
|
||||||
|
const pending = new Map();
|
||||||
|
let serial = 0;
|
||||||
|
socket.onmessage = event => {
|
||||||
|
const message = JSON.parse(event.data);
|
||||||
|
if (message.id) { pending.get(message.id)?.(message); pending.delete(message.id); }
|
||||||
|
};
|
||||||
|
await ready;
|
||||||
|
const send = (method, params = {}) => new Promise(resolve => {
|
||||||
|
const id = ++serial;
|
||||||
|
pending.set(id, resolve);
|
||||||
|
socket.send(JSON.stringify({ id, method, params }));
|
||||||
|
});
|
||||||
|
const evaluate = async (expression, timeoutMs = 45_000) => {
|
||||||
|
let timeout;
|
||||||
|
const result = await Promise.race([
|
||||||
|
send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }),
|
||||||
|
new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error(`Shell unresponsive for ${timeoutMs / 1000} s`)), timeoutMs); }),
|
||||||
|
]).finally(() => clearTimeout(timeout));
|
||||||
|
if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails).slice(0, 600));
|
||||||
|
return result.result?.result?.value;
|
||||||
|
};
|
||||||
|
|
||||||
|
const backup = join(tmpdir(), `waybetter-layout-before-stress-${process.pid}.json`);
|
||||||
|
let completed = false;
|
||||||
|
try {
|
||||||
|
const original = await evaluate(`(() => {
|
||||||
|
if (!window.__TAURI__?.event?.emit) throw new Error('Tauri event API unavailable');
|
||||||
|
const liveIds = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')]
|
||||||
|
.map(tab => tab.dataset.panelId);
|
||||||
|
const originalIds = liveIds();
|
||||||
|
if (new Set(originalIds).size !== originalIds.length) throw new Error('Duplicate live panel IDs');
|
||||||
|
const saved = JSON.parse(localStorage.getItem('bt.shell.layout.v1') || 'null');
|
||||||
|
if (Object.keys(saved?.panels ?? {}).length !== originalIds.length) {
|
||||||
|
throw new Error('Saved panel count does not match live tabs; wait for initial layout persistence');
|
||||||
|
}
|
||||||
|
window.__webStress = {
|
||||||
|
originalIds: new Set(originalIds),
|
||||||
|
initialCount: originalIds.length,
|
||||||
|
layout: localStorage.getItem('bt.shell.layout.v1'),
|
||||||
|
delays: [], longTasks: [], expected: performance.now() + 50,
|
||||||
|
};
|
||||||
|
const s = window.__webStress;
|
||||||
|
s.observer = new PerformanceObserver(list => {
|
||||||
|
for (const entry of list.getEntries()) s.longTasks.push(entry.duration);
|
||||||
|
});
|
||||||
|
s.observer.observe({ entryTypes: ['longtask'] });
|
||||||
|
s.interval = setInterval(() => {
|
||||||
|
const now = performance.now();
|
||||||
|
s.delays.push(Math.max(0, now - s.expected));
|
||||||
|
s.expected = now + 50;
|
||||||
|
}, 50);
|
||||||
|
return { initialCount: s.initialCount, layout: s.layout };
|
||||||
|
})()`);
|
||||||
|
// This file is a recovery copy if the shell dies before its tabs can be closed. It is deleted
|
||||||
|
// after a successful cleanup; its contents are never printed or committed.
|
||||||
|
await writeFile(backup, JSON.stringify({ layout: original.layout }), { mode: 0o600 });
|
||||||
|
console.log(JSON.stringify({ initialTabs: original.initialCount, recoveryFile: backup }));
|
||||||
|
let previous = 0;
|
||||||
|
let stopReason = null;
|
||||||
|
for (const count of stages) {
|
||||||
|
const beforeProcesses = await processSnapshot();
|
||||||
|
const added = count - previous;
|
||||||
|
const urls = Array.from({ length: added }, (_, index) =>
|
||||||
|
routeMode === 'mixed-home-explore' && (previous + index) % 2 === 1
|
||||||
|
? sitePages[1] ?? sitePages[0] : sitePages[0]);
|
||||||
|
const stage = await evaluate(`(async () => {
|
||||||
|
const s = window.__webStress;
|
||||||
|
const start = performance.now();
|
||||||
|
const calls = ${JSON.stringify(urls)}.map(url => window.__TAURI__.event.emit('tab-open', {
|
||||||
|
url, background: true,
|
||||||
|
}));
|
||||||
|
await Promise.all(calls);
|
||||||
|
const dispatchMs = performance.now() - start;
|
||||||
|
const expected = s.initialCount + ${count};
|
||||||
|
const deadline = performance.now() + 30_000;
|
||||||
|
while (document.querySelectorAll('.dv-tab').length < expected && performance.now() < deadline) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 8_000));
|
||||||
|
const saved = JSON.parse(localStorage.getItem('bt.shell.layout.v1') || 'null');
|
||||||
|
const liveIds = [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')]
|
||||||
|
.map(tab => tab.dataset.panelId);
|
||||||
|
const extraIds = liveIds.filter(id => !s.originalIds.has(id));
|
||||||
|
return {
|
||||||
|
requested: ${count}, routeMode: ${JSON.stringify(routeMode)}, tabs: liveIds.length, liveExtraIds: extraIds.length,
|
||||||
|
savedExtraIds: Object.keys(saved?.panels ?? {}).filter(id => !s.originalIds.has(id)).length,
|
||||||
|
dispatchMs: Math.round(dispatchMs),
|
||||||
|
maxDelayMs: Math.round(Math.max(0, ...s.delays)),
|
||||||
|
maxLongTaskMs: Math.round(Math.max(0, ...s.longTasks)),
|
||||||
|
};
|
||||||
|
})()`, 50_000);
|
||||||
|
const list = await targets();
|
||||||
|
stage.xTargets = list.filter(item => item.type === 'page' && item.url.startsWith(`${siteOrigin}/`)).length;
|
||||||
|
stage.processes = processDelta(beforeProcesses, await processSnapshot());
|
||||||
|
console.log(JSON.stringify(stage));
|
||||||
|
if (stage.tabs !== original.initialCount + count || stage.liveExtraIds !== count) {
|
||||||
|
throw new Error('New live tab count or panel ID count did not reach target');
|
||||||
|
}
|
||||||
|
previous = count;
|
||||||
|
if (stage.maxDelayMs > 1500 || (stage.processes?.totalMemoryMB ?? 0) > memoryLimitMB) {
|
||||||
|
stopReason = stage.maxDelayMs > 1500 ? 'shell timer lag exceeded 1.5 s' : `process working sets exceeded ${memoryLimitMB} MB`;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (stopReason) console.log(JSON.stringify({ stoppedAt: previous, reason: stopReason }));
|
||||||
|
completed = previous === stages.at(-1);
|
||||||
|
if (!completed) console.error(`Ramp incomplete: reached ${previous} of ${stages.at(-1)} requested site tabs`);
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
const cleaned = await evaluate(`(async () => {
|
||||||
|
const s = window.__webStress;
|
||||||
|
if (!s) return { error: 'probe missing' };
|
||||||
|
clearInterval(s.interval);
|
||||||
|
s.observer.disconnect();
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 600));
|
||||||
|
const panelIds = () => [...document.querySelectorAll('.dv-tabs-container .dv-tab .bt-tab[data-panel-id]')]
|
||||||
|
.map(tab => tab.dataset.panelId);
|
||||||
|
const extras = panelIds().filter(id => !s.originalIds.has(id));
|
||||||
|
for (const id of extras) {
|
||||||
|
// Explicit missing IDs are ignored. Confirm each live ID before sending, then wait for
|
||||||
|
// that exact panel to disappear before closing the next one.
|
||||||
|
if (!panelIds().includes(id)) continue;
|
||||||
|
await window.__TAURI__.event.emit('tab-shortcut', { id, shortcut: 'close-tab' });
|
||||||
|
const deadline = performance.now() + 3000;
|
||||||
|
while (panelIds().includes(id) && performance.now() < deadline) {
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 50));
|
||||||
|
}
|
||||||
|
if (panelIds().includes(id)) throw new Error('Panel close did not persist: ' + id);
|
||||||
|
}
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 500));
|
||||||
|
const remainingIds = panelIds();
|
||||||
|
if (s.layout === null) localStorage.removeItem('bt.shell.layout.v1');
|
||||||
|
else localStorage.setItem('bt.shell.layout.v1', s.layout);
|
||||||
|
return { extraTabs: extras.length, remainingTabs: remainingIds.length,
|
||||||
|
expectedTabs: s.initialCount,
|
||||||
|
originalIdsRestored: remainingIds.length === s.originalIds.size && remainingIds.every(id => s.originalIds.has(id)),
|
||||||
|
layoutRestored: localStorage.getItem('bt.shell.layout.v1') === s.layout };
|
||||||
|
})()`, 90_000);
|
||||||
|
console.log(JSON.stringify({ cleanup: cleaned }));
|
||||||
|
if (cleaned.remainingTabs !== cleaned.expectedTabs || !cleaned.originalIdsRestored || !cleaned.layoutRestored) {
|
||||||
|
completed = false;
|
||||||
|
} else {
|
||||||
|
await unlink(backup);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
completed = false;
|
||||||
|
console.error(`Cleanup failed: ${error.message}; recovery layout is at ${backup}`);
|
||||||
|
}
|
||||||
|
socket.close();
|
||||||
|
if (!completed) process.exitCode = 1;
|
||||||
|
}
|
||||||
189
dev-tools/perf-probe.mjs
Normal file
189
dev-tools/perf-probe.mjs
Normal file
|
|
@ -0,0 +1,189 @@
|
||||||
|
// Performance probe for what a wayBetter app injects into its site's tabs. Loads the app's
|
||||||
|
// document-start scripts (the tab bridge, its observer, its page runtime) as init scripts, like the
|
||||||
|
// native tab webview does, into headless Chromium and measures: script evaluation time, fetch/XHR
|
||||||
|
// wrapper layers and their synchronous overhead, Response clones and large JSON.parse calls made by
|
||||||
|
// the scripts, MutationObserver callbacks / rAF / timer work attributed to them, and main-thread
|
||||||
|
// long tasks. The app supplies the scripts and its scenarios (fixtures that intercept every request
|
||||||
|
// locally, or a live page); see wayBetter for X's scripts/perf-probe.mjs.
|
||||||
|
//
|
||||||
|
// import { chromium } from 'playwright';
|
||||||
|
// import { runPerfProbe } from '<waybetter>/dev-tools/perf-probe.mjs';
|
||||||
|
// const results = await runPerfProbe({ chromium, scripts: [{ name: 'runtime', code }], seconds: 8, runs: 3,
|
||||||
|
// nativeReplies: { some_command: [] },
|
||||||
|
// scenarios: [{ name: 'fixture /home', url: 'https://site.test/home', route: async context => { … } }] });
|
||||||
|
//
|
||||||
|
// Numbers are headless Chromium, not WebView2; compare runs on the same machine only. PROFILE=1
|
||||||
|
// adds the scripts' self time per function.
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------ probe
|
||||||
|
function prelude(names, replies) {
|
||||||
|
// Work is "ours" when one of the probed scripts is on the stack (they are evaluated as bt-<name>.js).
|
||||||
|
const pattern = new RegExp('bt-(?:' + names.join('|') + ')\\.js');
|
||||||
|
const ours = () => pattern.test(new Error().stack || '');
|
||||||
|
const P = window.__probe = {
|
||||||
|
evals: [], fetchSets: 0, xhrOpenSets: 0, xhrSendSets: 0, fetchCalls: 0, fetchOverheadMs: 0, xhrCalls: 0,
|
||||||
|
clones: 0, cloneReads: 0, bigParses: 0, bigParseMs: 0, bigParseBytes: 0,
|
||||||
|
mo: { ours: 0, oursMs: 0, oursObservers: 0, page: 0 }, raf: { ours: 0, oursMs: 0 }, timers: { ours: 0, oursMs: 0, intervals: 0 },
|
||||||
|
longtasks: [], outerStart: 0,
|
||||||
|
};
|
||||||
|
const nativeFetch = window.fetch;
|
||||||
|
let current = function probeInner(...a) {
|
||||||
|
if (P.outerStart) { P.fetchOverheadMs += performance.now() - P.outerStart; P.outerStart = 0; }
|
||||||
|
return Reflect.apply(nativeFetch, this, a);
|
||||||
|
};
|
||||||
|
Object.defineProperty(window, 'fetch', {
|
||||||
|
configurable: true, get: () => current,
|
||||||
|
set: value => { if (ours()) P.fetchSets++; current = value; },
|
||||||
|
});
|
||||||
|
const xproto = XMLHttpRequest.prototype;
|
||||||
|
for (const [key, counter] of [['open', 'xhrOpenSets'], ['send', 'xhrSendSets']]) {
|
||||||
|
let fn = xproto[key];
|
||||||
|
Object.defineProperty(xproto, key, { configurable: true, get: () => fn, set: v => { if (ours()) P[counter]++; fn = v; } });
|
||||||
|
}
|
||||||
|
const clone = Response.prototype.clone;
|
||||||
|
const cloned = new WeakSet();
|
||||||
|
Response.prototype.clone = function () { P.clones++; const c = clone.call(this); cloned.add(c); return c; };
|
||||||
|
for (const reader of ['text', 'json', 'arrayBuffer']) {
|
||||||
|
const orig = Response.prototype[reader];
|
||||||
|
Response.prototype[reader] = function () { if (cloned.has(this)) P.cloneReads++; return orig.call(this); };
|
||||||
|
}
|
||||||
|
const parse = JSON.parse;
|
||||||
|
JSON.parse = function (text, reviver) {
|
||||||
|
if (typeof text === 'string' && text.length > 20000 && ours()) {
|
||||||
|
const t = performance.now();
|
||||||
|
try { return parse.call(this, text, reviver); } finally { P.bigParses++; P.bigParseMs += performance.now() - t; P.bigParseBytes += text.length; }
|
||||||
|
}
|
||||||
|
return parse.call(this, text, reviver);
|
||||||
|
};
|
||||||
|
const MO = window.MutationObserver;
|
||||||
|
window.MutationObserver = class extends MO {
|
||||||
|
constructor(cb) {
|
||||||
|
const mine = ours();
|
||||||
|
super((records, obs) => {
|
||||||
|
if (!mine) { P.mo.page++; return cb(records, obs); }
|
||||||
|
const t = performance.now();
|
||||||
|
try { return cb(records, obs); } finally { P.mo.ours++; P.mo.oursMs += performance.now() - t; }
|
||||||
|
});
|
||||||
|
if (mine) P.mo.oursObservers++;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const raf = window.requestAnimationFrame.bind(window);
|
||||||
|
window.requestAnimationFrame = cb => {
|
||||||
|
if (!ours()) return raf(cb);
|
||||||
|
return raf(ts => { const t = performance.now(); try { cb(ts); } finally { P.raf.ours++; P.raf.oursMs += performance.now() - t; } });
|
||||||
|
};
|
||||||
|
for (const name of ['setTimeout', 'setInterval']) {
|
||||||
|
const orig = window[name].bind(window);
|
||||||
|
window[name] = (cb, ms, ...rest) => {
|
||||||
|
if (typeof cb !== 'function' || !ours()) return orig(cb, ms, ...rest);
|
||||||
|
if (name === 'setInterval') P.timers.intervals++;
|
||||||
|
return orig((...a) => { const t = performance.now(); try { cb(...a); } finally { P.timers.ours++; P.timers.oursMs += performance.now() - t; } }, ms, ...rest);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
new PerformanceObserver(list => { for (const e of list.getEntries()) P.longtasks.push(e.duration); })
|
||||||
|
.observe({ type: 'longtask', buffered: true });
|
||||||
|
} catch { /* unsupported */ }
|
||||||
|
// What the native app provides to site tabs: every command answers null unless `replies` names it.
|
||||||
|
const invoke = (cmd) => Promise.resolve(cmd in replies ? replies[cmd] : null);
|
||||||
|
window.__TAURI_INTERNALS__ = { invoke };
|
||||||
|
window.__TAURI__ = { core: { invoke } };
|
||||||
|
}
|
||||||
|
function postlude() {
|
||||||
|
const P = window.__probe;
|
||||||
|
const inner = window.fetch;
|
||||||
|
// The outermost layer: the site's own calls start here.
|
||||||
|
const outer = function probeOuter(...a) { P.fetchCalls++; P.outerStart = performance.now(); return Reflect.apply(inner, this, a); };
|
||||||
|
const set = Object.getOwnPropertyDescriptor(window, 'fetch').set;
|
||||||
|
Object.defineProperty(window, 'fetch', { configurable: true, get: () => outer, set });
|
||||||
|
const open = XMLHttpRequest.prototype.open;
|
||||||
|
XMLHttpRequest.prototype.open = function (...a) { P.xhrCalls++; return open.apply(this, a); };
|
||||||
|
}
|
||||||
|
const wrap = ({ name, code }) =>
|
||||||
|
`window.__probe.evals.push(['${name}', performance.now()]);\n${code}\n;window.__probe.evals.push(['${name}:end', performance.now()]);\n//# sourceURL=bt-${name}.js`;
|
||||||
|
|
||||||
|
async function run(browser, options, { name, url, route, scroll }) {
|
||||||
|
const { scripts, seconds, nativeReplies = {} } = options;
|
||||||
|
const userAgent = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${browser.version().split('.')[0]}.0.0.0 Safari/537.36`;
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, userAgent });
|
||||||
|
if (route) await route(context);
|
||||||
|
await context.addInitScript({ content: `(${prelude})(${JSON.stringify(scripts.map(script => script.name))}, ${JSON.stringify(nativeReplies)});\n//# sourceURL=bt-probe-prelude.js` });
|
||||||
|
for (const script of scripts) await context.addInitScript({ content: wrap(script) });
|
||||||
|
await context.addInitScript({ content: `(${postlude})();\n//# sourceURL=bt-probe-postlude.js` });
|
||||||
|
const page = await context.newPage();
|
||||||
|
const cdp = await context.newCDPSession(page);
|
||||||
|
await cdp.send('Performance.enable');
|
||||||
|
if (process.env.PROFILE) { await cdp.send('Profiler.enable'); await cdp.send('Profiler.setSamplingInterval', { interval: 50 }); await cdp.send('Profiler.start'); }
|
||||||
|
const started = Date.now();
|
||||||
|
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 });
|
||||||
|
const deadline = started + seconds * 1000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
if (scroll) await page.mouse.wheel(0, 700).catch(() => {});
|
||||||
|
await page.waitForTimeout(500);
|
||||||
|
}
|
||||||
|
const result = await page.evaluate(() => {
|
||||||
|
const P = window.__probe;
|
||||||
|
const nav = performance.getEntriesByType('navigation')[0];
|
||||||
|
const paint = Object.fromEntries(performance.getEntriesByType('paint').map(e => [e.name, e.startTime]));
|
||||||
|
const evals = {};
|
||||||
|
for (let i = 0; i < P.evals.length; i += 2) evals[P.evals[i][0]] = +(P.evals[i + 1][1] - P.evals[i][1]).toFixed(2);
|
||||||
|
return {
|
||||||
|
evalMs: evals, fetchWrapperLayers: P.fetchSets, xhrOpenLayers: P.xhrOpenSets, xhrSendLayers: P.xhrSendSets,
|
||||||
|
fetchCalls: P.fetchCalls, fetchOverheadMsTotal: +P.fetchOverheadMs.toFixed(2), xhrCalls: P.xhrCalls,
|
||||||
|
responseClones: P.clones, cloneReads: P.cloneReads, bigJsonParses: P.bigParses, bigJsonParseMs: +P.bigParseMs.toFixed(1),
|
||||||
|
bigJsonParseMB: +(P.bigParseBytes / 1e6).toFixed(1),
|
||||||
|
observers: P.mo.oursObservers, observerCallbacks: P.mo.ours, observerMs: +P.mo.oursMs.toFixed(1), pageObserverCallbacks: P.mo.page,
|
||||||
|
rafCallbacks: P.raf.ours, rafMs: +P.raf.oursMs.toFixed(1), timerCallbacks: P.timers.ours, timerMs: +P.timers.oursMs.toFixed(1), intervals: P.timers.intervals,
|
||||||
|
longTasks: P.longtasks.length, longTaskMs: Math.round(P.longtasks.reduce((a, b) => a + b, 0)),
|
||||||
|
domContentLoadedMs: nav ? Math.round(nav.domContentLoadedEventEnd) : null, fcpMs: paint['first-contentful-paint'] != null ? Math.round(paint['first-contentful-paint']) : null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const secs = (Date.now() - started) / 1000;
|
||||||
|
if (process.env.PROFILE) {
|
||||||
|
const { profile } = await cdp.send('Profiler.stop');
|
||||||
|
const dt = new Map(); const byId = new Map(profile.nodes.map(n => [n.id, n]));
|
||||||
|
const counts = new Map(); profile.samples.forEach((id, i) => counts.set(id, (counts.get(id) ?? 0) + (profile.timeDeltas[i] ?? 0)));
|
||||||
|
for (const [id, us] of counts) { const n = byId.get(id); const f = n.callFrame; if (!/bt-/.test(f.url)) continue; const k = f.url.replace(/.*bt-/, '') + ':' + (f.functionName || '(anon)') + ':' + f.lineNumber; dt.set(k, (dt.get(k) ?? 0) + us / 1000); }
|
||||||
|
result.selfMs = Object.fromEntries([...dt].sort((a, b) => b[1] - a[1]).slice(0, 25).map(([k, v]) => [k, +v.toFixed(1)]));
|
||||||
|
}
|
||||||
|
// Whole-page main-thread totals (the site or fixture + ours), from Chromium's own counters.
|
||||||
|
const metrics = Object.fromEntries((await cdp.send('Performance.getMetrics')).metrics.map(m => [m.name, m.value]));
|
||||||
|
result.pageScriptMs = Math.round(metrics.ScriptDuration * 1000);
|
||||||
|
result.pageTaskMs = Math.round(metrics.TaskDuration * 1000);
|
||||||
|
result.pageLayoutMs = Math.round(metrics.LayoutDuration * 1000);
|
||||||
|
result.pageStyleMs = Math.round(metrics.RecalcStyleDuration * 1000);
|
||||||
|
result.layoutCount = metrics.LayoutCount;
|
||||||
|
result.styleRecalcCount = metrics.RecalcStyleCount;
|
||||||
|
result.observerCallbacksPerSec = +(result.observerCallbacks / secs).toFixed(1);
|
||||||
|
result.ourMainThreadMsPerSec = +((result.observerMs + result.rafMs + result.timerMs + result.fetchOverheadMsTotal + result.bigJsonParseMs) / secs).toFixed(2);
|
||||||
|
await context.close();
|
||||||
|
return { scenario: name, ...result };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs every scenario `runs` times and returns the median of each numeric field per scenario.
|
||||||
|
* `scripts`: `{ name, code }` in injection order (none: the page alone, for a baseline).
|
||||||
|
* `scenarios`: `{ name, url, route?(context), scroll? }`.
|
||||||
|
*/
|
||||||
|
export async function runPerfProbe(options) {
|
||||||
|
const { chromium, scenarios, runs = 3 } = options;
|
||||||
|
const settings = { scripts: options.scripts ?? [], seconds: options.seconds ?? 8, nativeReplies: options.nativeReplies ?? {} };
|
||||||
|
const browser = await chromium.launch({ headless: true });
|
||||||
|
const results = [];
|
||||||
|
try {
|
||||||
|
for (const scenario of scenarios) {
|
||||||
|
const all = [];
|
||||||
|
for (let i = 0; i < runs; i++) all.push(await run(browser, settings, scenario));
|
||||||
|
const out = { ...all[0] };
|
||||||
|
for (const [key, value] of Object.entries(out)) {
|
||||||
|
if (typeof value !== 'number') continue;
|
||||||
|
const sorted = all.map(result => result[key]).sort((a, b) => a - b);
|
||||||
|
out[key] = sorted[Math.floor(sorted.length / 2)];
|
||||||
|
}
|
||||||
|
results.push(out);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
return results;
|
||||||
|
}
|
||||||
266
dev-tools/resize-perf.mjs
Normal file
266
dev-tools/resize-perf.mjs
Normal file
|
|
@ -0,0 +1,266 @@
|
||||||
|
// Layout/theme performance probe for a running wayBetter app (release build started with
|
||||||
|
// WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=<port>). Plain CDP. Site pages are
|
||||||
|
// only read and reloaded, never clicked. Shell input is synthesized with CDP (no OS input, no focus
|
||||||
|
// change).
|
||||||
|
//
|
||||||
|
// SITE_ORIGIN=https://x.com node dev-tools/resize-perf.mjs <port> <case...>
|
||||||
|
// theme reload the first site tab 3x: first paint vs. theme applied, unthemed frames
|
||||||
|
// (needs THEME_GET and THEME_SET: the app's theme commands; THEME_PRESET=<id> measures
|
||||||
|
// with that theme and gives the owner's back)
|
||||||
|
// drag drag the first split divider for 2 s: shell frames, tabs_sync calls, native lag
|
||||||
|
// switch click between two tabs of one group 10x: click -> tab visible latency
|
||||||
|
// window (driven by window-resize.ps1 in parallel) shell resize -> native resize lag
|
||||||
|
//
|
||||||
|
// Lag is measured across processes with epoch timestamps (performance.timeOrigin + now) taken in
|
||||||
|
// the shell (when a layout was sent) and in the site tab (its own `resize` event, i.e. when the
|
||||||
|
// native bounds reached the page). SKIP_PATH=/compose leaves pages under that path out of `theme`.
|
||||||
|
const [port = '9333', ...cases] = process.argv.slice(2);
|
||||||
|
const origin = process.env.SITE_ORIGIN;
|
||||||
|
if (!origin) throw new Error('SITE_ORIGIN is required (the site\'s origin, e.g. https://x.com)');
|
||||||
|
const skipPath = process.env.SKIP_PATH ?? '';
|
||||||
|
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
|
||||||
|
async function targets() { return (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); }
|
||||||
|
function connect(target) {
|
||||||
|
const ws = new WebSocket(target.webSocketDebuggerUrl);
|
||||||
|
let id = 0;
|
||||||
|
const pending = new Map();
|
||||||
|
ws.onmessage = event => { const msg = JSON.parse(event.data); if (msg.id) { pending.get(msg.id)?.(msg); pending.delete(msg.id); } };
|
||||||
|
const ready = new Promise(resolve => { ws.onopen = resolve; });
|
||||||
|
const send = async (method, params = {}) => { await ready; return new Promise(resolve => { const n = ++id; pending.set(n, resolve); ws.send(JSON.stringify({ id: n, method, params })); }); };
|
||||||
|
// A frozen page (a parked, hidden tab) never answers: give up after 5 s.
|
||||||
|
const evaluate = async expression => {
|
||||||
|
const result = await Promise.race([
|
||||||
|
send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }),
|
||||||
|
wait(5000).then(() => { throw new Error(`${target.url}: no answer`); }),
|
||||||
|
]);
|
||||||
|
if (result.result?.exceptionDetails) throw new Error(JSON.stringify(result.result.exceptionDetails).slice(0, 400));
|
||||||
|
return result.result?.result?.value;
|
||||||
|
};
|
||||||
|
return { send, evaluate, close: () => ws.close(), url: target.url, id: target.id };
|
||||||
|
}
|
||||||
|
const pct = (values, p) => { if (!values.length) return null; const s = [...values].sort((a, b) => a - b); return +s[Math.min(s.length - 1, Math.floor(p * s.length))].toFixed(1); };
|
||||||
|
const stats = values => ({ n: values.length, p50: pct(values, 0.5), p95: pct(values, 0.95), max: values.length ? +Math.max(...values).toFixed(1) : null });
|
||||||
|
|
||||||
|
const list = await targets();
|
||||||
|
const shell = connect(list.find(t => t.type === 'page' && t.url.startsWith('http://tauri.localhost')));
|
||||||
|
const xTargets = list.filter(t => t.type === 'page' && t.url.startsWith(`${origin}/`));
|
||||||
|
const xs = [];
|
||||||
|
for (const x of xTargets.map(connect)) {
|
||||||
|
try { await x.evaluate('1'); xs.push(x); } catch { x.close(); }
|
||||||
|
}
|
||||||
|
const results = {};
|
||||||
|
|
||||||
|
/** Shell recorder: frame times and every tabs_sync (send epoch, round trip, rects). */
|
||||||
|
const SHELL_PROBE = `(() => {
|
||||||
|
if (window.__perf) return;
|
||||||
|
const P = window.__perf = { frames: [], syncs: [], on: false };
|
||||||
|
const now = () => performance.timeOrigin + performance.now();
|
||||||
|
const loop = t => { if (P.on) P.frames.push(t); requestAnimationFrame(loop); };
|
||||||
|
requestAnimationFrame(loop);
|
||||||
|
// __TAURI_INTERNALS__.invoke is read-only; its IPC goes through fetch (http://ipc.localhost/<cmd>).
|
||||||
|
const original = window.fetch.bind(window);
|
||||||
|
window.fetch = (input, init) => {
|
||||||
|
const url = String(input && input.url || input);
|
||||||
|
if (!P.on || !url.includes('/tabs_sync')) return original(input, init);
|
||||||
|
let items = [];
|
||||||
|
try { items = JSON.parse(init.body).items; } catch {}
|
||||||
|
const entry = { at: now(), items: items.map(i => [i.id, i.x, i.y, i.width, i.height, i.visible]) };
|
||||||
|
P.syncs.push(entry);
|
||||||
|
return original(input, init).finally(() => { entry.rtt = now() - entry.at; });
|
||||||
|
};
|
||||||
|
})()`;
|
||||||
|
/** Site tab recorder: its own resize and visibility events, epoch timestamps. */
|
||||||
|
const X_PROBE = `(() => {
|
||||||
|
if (window.__perf) return;
|
||||||
|
const P = window.__perf = { resizes: [], vis: [] };
|
||||||
|
const now = () => performance.timeOrigin + performance.now();
|
||||||
|
addEventListener('resize', () => P.resizes.push([now(), innerWidth, innerHeight]));
|
||||||
|
document.addEventListener('visibilitychange', () => P.vis.push([now(), document.visibilityState]));
|
||||||
|
})()`;
|
||||||
|
|
||||||
|
async function arm() {
|
||||||
|
await shell.evaluate(SHELL_PROBE);
|
||||||
|
for (const x of xs) await x.evaluate(X_PROBE);
|
||||||
|
await shell.evaluate('(__perf.frames = [], __perf.syncs = [], __perf.on = true)');
|
||||||
|
for (const x of xs) await x.evaluate('(__perf.resizes = [], __perf.vis = [])');
|
||||||
|
}
|
||||||
|
async function collect() {
|
||||||
|
const shellData = await shell.evaluate('(__perf.on = false, { frames: __perf.frames, syncs: __perf.syncs })');
|
||||||
|
const xData = [];
|
||||||
|
for (const x of xs) xData.push({ id: await x.evaluate('(window.__wbTabId ?? null)'), ...(await x.evaluate('({ resizes: __perf.resizes, vis: __perf.vis, w: innerWidth, h: innerHeight })')) });
|
||||||
|
return { shellData, xData };
|
||||||
|
}
|
||||||
|
/** For every site tab resize: the latest earlier sync that carried that width for some tab = its cause. */
|
||||||
|
function lagOf(shellData, xData) {
|
||||||
|
const lags = [];
|
||||||
|
let unmatched = 0;
|
||||||
|
for (const x of xData) {
|
||||||
|
for (const [at, w, h] of x.resizes) {
|
||||||
|
const cause = [...shellData.syncs].reverse().find(s => s.at <= at && s.items.some(i => Math.abs(i[3] - w) <= 1));
|
||||||
|
if (cause) lags.push(at - cause.at); else unmatched++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { lag: stats(lags), unmatched };
|
||||||
|
}
|
||||||
|
const frameStats = frames => stats(frames.slice(1).map((t, i) => t - frames[i]));
|
||||||
|
|
||||||
|
if (cases.includes('theme')) {
|
||||||
|
// A visible site page (a hidden one gets no animation frames to sample).
|
||||||
|
let x = null;
|
||||||
|
for (const candidate of xs) if (!x && await candidate.evaluate(`document.visibilityState === 'visible' && !(${JSON.stringify(skipPath)} && location.pathname.startsWith(${JSON.stringify(skipPath)}))`)) x = candidate;
|
||||||
|
if (!x) throw new Error('no visible site tab');
|
||||||
|
const themeGet = process.env.THEME_GET;
|
||||||
|
const themeSet = process.env.THEME_SET;
|
||||||
|
if (!themeGet || !themeSet) throw new Error('the theme case needs THEME_GET and THEME_SET (the app\'s theme commands)');
|
||||||
|
results.themeTarget = x.url;
|
||||||
|
// THEME_PRESET=nord: measure with that theme, then give the owner's theme back.
|
||||||
|
const invoke = (cmd, args) => shell.evaluate(`window.__TAURI_INTERNALS__.invoke(${JSON.stringify(cmd)}, ${JSON.stringify(args)})`);
|
||||||
|
const original = await invoke(themeGet, {});
|
||||||
|
if (process.env.THEME_PRESET) { await invoke(themeSet, { theme: { preset: process.env.THEME_PRESET } }); await wait(1500); }
|
||||||
|
await x.send('Page.enable');
|
||||||
|
// Before every other document script: record paints, theme style arrival and each frame's body color.
|
||||||
|
const probe = `(() => {
|
||||||
|
const t0 = performance.now();
|
||||||
|
const P = window.__themeProbe = { style: null, vars: null, frames: [], dcl: null };
|
||||||
|
const seen = () => {
|
||||||
|
const s = document.getElementById('bt-theme');
|
||||||
|
if (P.style === null && s && s.textContent) P.style = performance.now();
|
||||||
|
const v = document.getElementById('wb-theme-vars') || document.getElementById('bt-theme-snapshot');
|
||||||
|
if (P.vars === null && v) P.vars = performance.now();
|
||||||
|
};
|
||||||
|
new MutationObserver(seen).observe(document, { childList: true, subtree: true, characterData: true });
|
||||||
|
document.addEventListener('DOMContentLoaded', () => { P.dcl = performance.now(); });
|
||||||
|
const frame = t => {
|
||||||
|
seen();
|
||||||
|
// The color the page shows: <html>'s (themes paint the canvas there, <body> stays transparent),
|
||||||
|
// else <body>'s (X's own inline color before a theme).
|
||||||
|
const shown = () => { const h = document.documentElement && getComputedStyle(document.documentElement).backgroundColor; const b = document.body && getComputedStyle(document.body).backgroundColor; return h && h !== 'rgba(0, 0, 0, 0)' ? h : b || h || ''; };
|
||||||
|
const bg = shown();
|
||||||
|
P.frames.push([Math.round(t), bg, !!(document.getElementById('bt-theme')?.textContent), !!document.body]);
|
||||||
|
if (t - t0 < 6000) requestAnimationFrame(frame);
|
||||||
|
};
|
||||||
|
requestAnimationFrame(frame);
|
||||||
|
})()`;
|
||||||
|
const { result } = await x.send('Page.addScriptToEvaluateOnNewDocument', { source: probe });
|
||||||
|
const runs = [];
|
||||||
|
for (let run = 0; run < 3; run++) {
|
||||||
|
await x.send('Page.reload', {});
|
||||||
|
await wait(7000);
|
||||||
|
const data = await x.evaluate(`(() => {
|
||||||
|
const P = window.__themeProbe;
|
||||||
|
const paint = Object.fromEntries(performance.getEntriesByType('paint').map(e => [e.name, Math.round(e.startTime)]));
|
||||||
|
const h = getComputedStyle(document.documentElement).backgroundColor;
|
||||||
|
const themedBg = h !== 'rgba(0, 0, 0, 0)' ? h : getComputedStyle(document.body).backgroundColor;
|
||||||
|
// Frames once there is a body to paint (paint timing entries are not exposed in every run).
|
||||||
|
const painted = P.frames.filter(f => f[3]);
|
||||||
|
const unthemed = painted.filter(f => f[1] !== themedBg);
|
||||||
|
return { paint, firstBody: painted[0]?.[0] ?? null, firstThemedFrame: P.frames.find(f => f[3] && f[1] === themedBg)?.[0] ?? null, style: P.style && Math.round(P.style), vars: P.vars && Math.round(P.vars), dcl: P.dcl && Math.round(P.dcl), themedBg,
|
||||||
|
framesAfterFirstPaint: painted.length, unthemedFrames: unthemed.length, lastUnthemedAt: unthemed.length ? unthemed[unthemed.length - 1][0] : null,
|
||||||
|
firstBg: painted[0]?.[1] ?? null };
|
||||||
|
})()`);
|
||||||
|
runs.push(data);
|
||||||
|
}
|
||||||
|
await x.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: result.identifier });
|
||||||
|
if (process.env.THEME_PRESET) await invoke(themeSet, { theme: original });
|
||||||
|
results.theme = runs;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cases.includes('drag')) {
|
||||||
|
await arm();
|
||||||
|
const sash = await shell.evaluate(`(() => { const s = document.querySelector('.dv-split-view-container.dv-horizontal > .dv-sash-container > .dv-sash'); const b = s.getBoundingClientRect(); return [b.left + b.width / 2, b.top + b.height / 2]; })()`);
|
||||||
|
const [sx, sy] = sash;
|
||||||
|
const mouse = (type, x, buttons = 1) => shell.send('Input.dispatchMouseEvent', { type, x, y: sy, button: 'left', buttons, clickCount: 1 });
|
||||||
|
await mouse('mousePressed', sx);
|
||||||
|
const start = Date.now();
|
||||||
|
let steps = 0;
|
||||||
|
while (Date.now() - start < 2000) {
|
||||||
|
const phase = (Date.now() - start) / 2000;
|
||||||
|
await mouse('mouseMoved', sx - 200 * Math.sin(phase * Math.PI * 2));
|
||||||
|
steps++;
|
||||||
|
await wait(8);
|
||||||
|
}
|
||||||
|
await mouse('mouseMoved', sx);
|
||||||
|
const release = await shell.evaluate('performance.timeOrigin + performance.now()');
|
||||||
|
await mouse('mouseReleased', sx, 0);
|
||||||
|
await wait(1000);
|
||||||
|
const { shellData, xData } = await collect();
|
||||||
|
const lastX = Math.max(0, ...xData.flatMap(x => x.resizes.map(r => r[0])));
|
||||||
|
results.drag = {
|
||||||
|
moves: steps,
|
||||||
|
shellFrames: frameStats(shellData.frames.filter(t => true)),
|
||||||
|
syncs: shellData.syncs.length,
|
||||||
|
syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)),
|
||||||
|
xResizes: xData.map(x => x.resizes.length),
|
||||||
|
...lagOf(shellData, xData),
|
||||||
|
settleAfterRelease: +(lastX - release).toFixed(1),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cases.includes('window')) {
|
||||||
|
// window-resize.ps1 resizes the (non-foreground) window for ~2 s while this records.
|
||||||
|
await arm();
|
||||||
|
await shell.evaluate(`(() => { __perf.win = []; addEventListener('resize', () => __perf.win.push([performance.timeOrigin + performance.now(), innerWidth])); })()`);
|
||||||
|
await wait(Number(process.env.WINDOW_MS ?? 3500));
|
||||||
|
const { shellData, xData } = await collect();
|
||||||
|
const win = await shell.evaluate('__perf.win');
|
||||||
|
const shellLag = [];
|
||||||
|
// Native first (the site tab resized before the shell even saw the window change) counts as <= 0.
|
||||||
|
for (const x of xData) for (const [at] of x.resizes) {
|
||||||
|
const cause = [...win].reverse().find(w => w[0] <= at);
|
||||||
|
const after = win.find(w => w[0] > at);
|
||||||
|
if (cause) shellLag.push(at - cause[0]); else if (after) shellLag.push(-(after[0] - at));
|
||||||
|
}
|
||||||
|
results.window = {
|
||||||
|
shellResizes: win.length,
|
||||||
|
shellFrames: frameStats(shellData.frames),
|
||||||
|
syncs: shellData.syncs.length,
|
||||||
|
syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)),
|
||||||
|
xResizes: xData.map(x => x.resizes.length),
|
||||||
|
xAfterShellResize: stats(shellLag),
|
||||||
|
// With window-resize.ps1's printed restore time: how long the site tab keeps resizing after the window stopped.
|
||||||
|
lastXResize: Math.round(Math.max(0, ...xData.flatMap(x => x.resizes.map(r => r[0])))),
|
||||||
|
lastShellResize: Math.round(Math.max(0, ...win.map(w => w[0]))),
|
||||||
|
...lagOf(shellData, xData),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cases.includes('switch')) {
|
||||||
|
await arm();
|
||||||
|
// Two web tabs in one group: click the inactive one, wait, click back. Latency = click -> the
|
||||||
|
// clicked tab's page becomes visible.
|
||||||
|
const group = await shell.evaluate(`(() => {
|
||||||
|
const g = [...document.querySelectorAll('.dv-groupview')].map(g => g.closest('.dv-view')).find(v => v && v.querySelectorAll('.dv-tab').length >= 2);
|
||||||
|
return !!g;
|
||||||
|
})()`);
|
||||||
|
const latencies = [];
|
||||||
|
if (group) {
|
||||||
|
for (let i = 0; i < 20; i++) {
|
||||||
|
const clicked = await shell.evaluate(`(() => {
|
||||||
|
const tabs = [...document.querySelectorAll('.dv-tab')];
|
||||||
|
const next = tabs.find(t => t.classList.contains('dv-inactive-tab'));
|
||||||
|
const at = performance.timeOrigin + performance.now();
|
||||||
|
next.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
|
||||||
|
next.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0 }));
|
||||||
|
next.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, button: 0 }));
|
||||||
|
next.click();
|
||||||
|
return at;
|
||||||
|
})()`);
|
||||||
|
await wait(600);
|
||||||
|
const shown = [];
|
||||||
|
for (const x of xs) {
|
||||||
|
const vis = await x.evaluate('__perf.vis');
|
||||||
|
const hit = vis.find(v => v[1] === 'visible' && v[0] >= clicked);
|
||||||
|
if (hit) shown.push(hit[0] - clicked);
|
||||||
|
await x.evaluate('(__perf.vis = [])');
|
||||||
|
}
|
||||||
|
if (shown.length) latencies.push(Math.min(...shown));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const { shellData } = await collect();
|
||||||
|
results.switch = { group, latency: stats(latencies), syncRtt: stats(shellData.syncs.map(s => s.rtt).filter(v => v != null)) };
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(JSON.stringify(results, null, 1));
|
||||||
|
shell.close();
|
||||||
|
for (const x of xs) x.close();
|
||||||
57
dev-tools/runtime-start-check.mjs
Normal file
57
dev-tools/runtime-start-check.mjs
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// Document-start check for an app's page runtime: the built runtime injected the way the app does
|
||||||
|
// it, as an init script that runs before the parser has created <html>, into static fixtures of the
|
||||||
|
// site. Every feature flag is switched on, then off, then back to its default; any console error,
|
||||||
|
// any message with the app's `[label]` prefix or any page error fails the check. Not a live test.
|
||||||
|
//
|
||||||
|
// import { chromium } from 'playwright';
|
||||||
|
// import { runtimeStartCheck } from '<waybetter>/dev-tools/runtime-start-check.mjs';
|
||||||
|
// const { problems, checked } = await runtimeStartCheck({
|
||||||
|
// chromium, runtime: code, global: 'MyApp', label: 'wayBetter for Site', origin: 'https://site.test',
|
||||||
|
// queued: 'window.__btPane={redundantNav:true};', // what native code queues before the runtime exists
|
||||||
|
// featureDefaults: { someFlag: true },
|
||||||
|
// pages: [{ name: 'home', path: '/home', html: '<!doctype html>…' }],
|
||||||
|
// verify: { expression: '({ … })', check: (result, page) => 'a problem' | null },
|
||||||
|
// });
|
||||||
|
|
||||||
|
/** Runs the check; resolves to `{ problems, checked }`. */
|
||||||
|
export async function runtimeStartCheck(options) {
|
||||||
|
const { chromium, runtime, global, label, origin, pages, featureDefaults = {}, queued = '', verify } = options;
|
||||||
|
const browser = await chromium.launch();
|
||||||
|
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
|
||||||
|
if (queued) await context.addInitScript({ content: queued });
|
||||||
|
await context.addInitScript({ content: runtime });
|
||||||
|
const problems = [];
|
||||||
|
let checked = 0;
|
||||||
|
try {
|
||||||
|
for (const item of pages) {
|
||||||
|
const page = await context.newPage();
|
||||||
|
page.on('console', message => { if (message.type() === 'error' || message.text().includes(`[${label}]`)) problems.push(`${item.name}: ${message.text().slice(0, 240)}`); });
|
||||||
|
page.on('pageerror', error => problems.push(`${item.name}: page error ${String(error).slice(0, 240)}`));
|
||||||
|
await page.route(`${origin}/**`, route => route.fulfill({ contentType: 'text/html', body: item.html }));
|
||||||
|
await page.goto(`${origin}${item.path}`);
|
||||||
|
const result = await page.evaluate(async ({ name, defaults, expression }) => {
|
||||||
|
const runtime = window[name];
|
||||||
|
if (!runtime) return { runtime: false };
|
||||||
|
const all = value => Object.fromEntries(Object.keys(defaults).map(key => [key, value]));
|
||||||
|
runtime.features.apply(all(true));
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 200));
|
||||||
|
runtime.features.apply(all(false));
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
|
runtime.features.apply(defaults);
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 300));
|
||||||
|
// The app's own expression over the page (what it expects to be there after the toggles).
|
||||||
|
return { runtime: true, details: expression ? (0, eval)(expression) : null };
|
||||||
|
}, { name: global, defaults: featureDefaults, expression: verify?.expression ?? '' });
|
||||||
|
if (!result.runtime) problems.push(`${item.name}: runtime did not install`);
|
||||||
|
else {
|
||||||
|
const problem = verify?.check?.(result.details, item);
|
||||||
|
if (problem) problems.push(`${item.name}: ${problem}`);
|
||||||
|
}
|
||||||
|
checked += 1;
|
||||||
|
await page.close();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
}
|
||||||
|
return { problems, checked };
|
||||||
|
}
|
||||||
48
dev-tools/window-resize.ps1
Normal file
48
dev-tools/window-resize.ps1
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
# Resizes a wayBetter app's window (never activated, never while it is the foreground window) for
|
||||||
|
# ~2 s, then puts it back: a repeatable window-resize workload for resize-perf.mjs `window`.
|
||||||
|
# powershell -ExecutionPolicy Bypass -File dev-tools/window-resize.ps1 -Process <process name or pattern> [-Ms 2000] [-Amplitude 200]
|
||||||
|
param([Parameter(Mandatory = $true)][string]$Process, [int]$Ms = 2000, [int]$Amplitude = 200)
|
||||||
|
Add-Type @"
|
||||||
|
using System; using System.Runtime.InteropServices;
|
||||||
|
public static class WinResize {
|
||||||
|
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
|
||||||
|
[DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
|
||||||
|
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int cx, int cy, uint flags);
|
||||||
|
[DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
|
||||||
|
[DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr h);
|
||||||
|
[DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);
|
||||||
|
public delegate bool EnumProc(IntPtr h, IntPtr l);
|
||||||
|
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc p, IntPtr l);
|
||||||
|
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint p);
|
||||||
|
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr h, System.Text.StringBuilder s, int n);
|
||||||
|
// The app window itself: MainWindowHandle may be the single-instance or event-loop helper window.
|
||||||
|
public static IntPtr AppWindow(uint pid) {
|
||||||
|
IntPtr found = IntPtr.Zero;
|
||||||
|
EnumWindows((h, l) => { uint p; GetWindowThreadProcessId(h, out p); var c = new System.Text.StringBuilder(64); GetClassName(h, c, 64);
|
||||||
|
if (p == pid && c.ToString() == "Tauri Window") { found = h; return false; } return true; }, IntPtr.Zero);
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"@
|
||||||
|
$proc = Get-Process $Process -ErrorAction Stop | Select-Object -First 1
|
||||||
|
$hwnd = [WinResize]::AppWindow([uint32]$proc.Id)
|
||||||
|
if ($hwnd -eq [IntPtr]::Zero) { 'skipped: no app window'; exit 2 }
|
||||||
|
if ([WinResize]::IsIconic($hwnd)) { 'skipped: minimized'; exit 2 }
|
||||||
|
if ([WinResize]::GetForegroundWindow() -eq $hwnd) { 'skipped: the app is the foreground window'; exit 2 }
|
||||||
|
if ([WinResize]::IsZoomed($hwnd)) { 'skipped: maximized'; exit 2 }
|
||||||
|
$r = New-Object WinResize+RECT
|
||||||
|
[void][WinResize]::GetWindowRect($hwnd, [ref]$r)
|
||||||
|
$w = $r.Right - $r.Left; $h = $r.Bottom - $r.Top
|
||||||
|
# SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER
|
||||||
|
$flags = 0x0002 -bor 0x0004 -bor 0x0010 -bor 0x0200
|
||||||
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
$steps = 0
|
||||||
|
while ($sw.ElapsedMilliseconds -lt $Ms) {
|
||||||
|
$phase = $sw.ElapsedMilliseconds / $Ms
|
||||||
|
$dw = [int]($Amplitude * [Math]::Sin($phase * [Math]::PI * 2))
|
||||||
|
[void][WinResize]::SetWindowPos($hwnd, [IntPtr]::Zero, 0, 0, $w - [Math]::Abs($dw), $h - [int]([Math]::Abs($dw) / 2), $flags)
|
||||||
|
$steps++
|
||||||
|
Start-Sleep -Milliseconds 8
|
||||||
|
}
|
||||||
|
[void][WinResize]::SetWindowPos($hwnd, [IntPtr]::Zero, 0, 0, $w, $h, $flags)
|
||||||
|
"resized $steps times, restored ${w}x${h} at $([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds())"
|
||||||
Loading…
Add table
Add a link
Reference in a new issue