In this section
- Orient16 Recovery Safe Test test · gridatlas / tools/satnav/line/orient16-recovery-safe.test.mjs lines 1–19
- Orient16 Recovery transform · gridatlas / tools/satnav/line/orient16-recovery.mjs lines 1–120
- Orient16 Recovery Test test · gridatlas / tools/satnav/line/orient16-recovery.test.mjs lines 1–14
- SatNav Offline Plan Browser render · gridatlas / tools/satnav/offline-plan-browser.py lines 1–212
- SatNav Orient14 Browser render · gridatlas / tools/satnav/orient14-browser.py lines 1–58
- SatNav Orient16 Browser render · gridatlas / tools/satnav/orient16-browser.py lines 1–63
- SatNav Orient16 Recovery Browser render · gridatlas / tools/satnav/orient16-recovery-browser.py lines 1–171
Orient16 Recovery Safe Test
A test in the line folder of GridAtlas that checks Orient16 Recovery Safe.
testgridatlas / tools/satnav/line/orient16-recovery-safe.test.mjs · lines 1–19 of 19 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Uses libraries node:assert/strict.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Guards the behaviour of Orient16 Recovery Safe.
- Application
- gridatlas · tools/satnav/line · test
- Uses
- Orient16 Recovery Safe (import), node:assert/strict
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/line/orient16-recovery-safe.test.mjs:1-19 · blob b092c06b1920d9ca2158a1f839671cfd89905268 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
import assert from 'node:assert/strict';
import {createRecovery} from './orient16-recovery-safe.mjs';
const maths={distanceKm:(a,b,c,d)=>Math.hypot(c-a,d-b)*100,initialBearingDeg:()=>90,distanceToSegmentKm:(x,y,a,b,c,d)=>{const t=Math.max(0,Math.min(1,((x-a)*(c-a)+(y-b)*(d-b))/((c-a)**2+(d-b)**2)));return {t,foot:[a+t*(c-a),b+t*(d-b)],km:Math.hypot(x-a-t*(c-a),y-b-t*(d-b))*100}}};
let assertions=0;const eq=(a,b)=>{assert.deepEqual(a,b);assertions++};const settle=async()=>{for(let i=0;i<12;i++)await Promise.resolve()};
for(const mode of ['walking','driving']){
let t=100000,calls=0;
const c=createRecovery({maths,clock:()=>t,cooldownMs:0,maxAttempts:3,provider:async req=>{calls++;return {...req,eligible:true,graphRevision:'fixture',geometry:{type:'LineString',coordinates:[req.origin,[.01,0]]}}}});
c.setJourney({mode,target:[.002,0]});c.start();c.ingest({longitude:0,latitude:0,accuracyM:4,timestampMs:t});await settle();eq(c.snapshot().status,'unavailable');eq(c.snapshot().geometry,null);
for(let i=0;i<100;i++){t++;c.tick();await settle()}eq(calls,1);eq(c.snapshot().instruction,null);
let attempts=0;const r=createRecovery({maths,clock:()=>t,cooldownMs:0,maxAttempts:3,provider:async()=>{attempts++;throw Error('fixture transient')}});
r.setJourney({mode,target:[.002,0]});r.start();r.ingest({longitude:0,latitude:0,accuracyM:4,timestampMs:t});await settle();
for(let i=0;i<100;i++){t++;r.tick();await settle()}eq(attempts,3);eq(r.snapshot().status,'retry-exhausted');eq(r.snapshot().geometry,null);
}
console.log(JSON.stringify({suite:'ORIENT-16 endpoint/retry',assertions,status:'PASS'}));
for(const [metres,accuracy,want] of [[0,4,null],[2,4,null],[4,4,null],[5,4,90],[25,30,null],[31,30,90]]){
const c=createRecovery({maths,clock:()=>100000});c.setJourney({mode:'direct',target:[metres/100000,0]});c.start();c.ingest({longitude:0,latitude:0,accuracyM:accuracy,timestampMs:100000});eq(c.snapshot().instruction.bearingDeg,want);
}
console.log(JSON.stringify({suite:'ORIENT-16 recovery near-target boundary',assertions:6,status:'PASS'}));Orient16 Recovery
A JavaScript module in the line folder of GridAtlas that sets journey (`setJourney`). It creates recovery (`createRecovery`) and sets journey (`setJourney`).
Set aside from the main view: 98% of its lines are the same as tools/satnav/line/orient16-recovery-safe.mjs (gridatlas), which stays. (near-copy-of, proposed by families.py). 98% of lines shared with Orient16 Recovery Safe; read that one first. All set-aside files, with reasons. Nothing was deleted.
Evidence
- line-jaccard 0.981 to gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/line/orient16-recovery-safe.mjs:1-120 feeb1c776e95e7b3c141428aee21a594d857f81c
- sha256 217759372fcdd98e4a75b7dd28850c36d05867fca46471b2c3ffd18e18b39419
- target sha256 d5131cc0c39cec9f9132c26ed2e27f1ba8ea66f03dbf2c6301d5e30f31527643
- group of 2 (identity.json near-copy edges >= 0.9)
- canonical rule: reachable, newest stamp, core repo, most lines
transformgridatlas / tools/satnav/line/orient16-recovery.mjs · lines 1–120 of 120 · Not reached from any entry point (candidate for review) · pattern createRecovery (shared by 3 files)
- What it does
- It calculates its inputs. Defines 23 functions or classes, including point, finite, createRecovery, now, policy.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Downstream impact
- Used directly by 1 file: Orient16 Recovery Test (gridatlas).
- What it achieves
- Defines `point`, `finite`, `createRecovery` and 20 more.
- Why it matters
- Checked by Orient16 Recovery Test.
- Application
- gridatlas · tools/satnav/line · JavaScript module
- Uses
- Route Follower (import)
- Used by
- imported by Orient16 Recovery Test (import)
- Produces
- policies, createRecovery
- Defines here
- point, finite, createRecovery, now, policy, usable, clearOutput, cancel, clearRoute, invalidate, snapshot, setJourney, start, stop, pause, resume, network, requestRoute, current, close, evaluate, tick, ingest
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/line/orient16-recovery.mjs:1-120 · blob 309bcba3d217f88926d290196e095679e6918fcb · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: duplicate_candidate
// SPDX-License-Identifier: Apache-2.0
// ORIENT-16 derived candidate: pure recovery ownership; no GPS watch, camera writes or network service.
import {createRouteFollower} from './route-follower.mjs';
export const policies = Object.freeze({
walking:Object.freeze({margin:20,accuracy:15,maxSpeed:3,fixAge:8000,confirm:3,span:2000}),
driving:Object.freeze({margin:35,accuracy:30,maxSpeed:55,fixAge:5000,confirm:3,span:2000}),
direct:Object.freeze({accuracy:30,fixAge:10000})
});
const point=p=>Array.isArray(p)&&p.length===2&&p.every(Number.isFinite)&&Math.abs(p[0])<=180&&Math.abs(p[1])<=90;
const finite=n=>Number.isFinite(n);
export function createRecovery({maths,provider=null,clock=Date.now,timeoutMs=8000,cooldownMs=10000,maxAttempts=3}){
if(!finite(timeoutMs)||timeoutMs<=0||!finite(cooldownMs)||cooldownMs<0)throw Error('INVALID_BUDGET');
if(!Number.isInteger(maxAttempts)||maxAttempts<1||maxAttempts>10)throw Error('INVALID_ATTEMPTS');
let attempts=0,terminal=false;
let mode='walking',target=null,objective='shortest',revision=0,serial=0,fix=null,last=-Infinity,online=true,active=false,paused=false;
let route=null,pending=null,progress=null,off=[],attemptAt=-Infinity,status='choose',output=null;
const now=()=>clock();
const policy=()=>policies[mode];
const usable=(f,t)=>f&&point([f.longitude,f.latitude])&&finite(f.accuracyM)&&f.accuracyM>=0&&f.accuracyM<=policy().accuracy&&finite(f.timestampMs)&&f.timestampMs<=t&&t-f.timestampMs<=policy().fixAge;
const clearOutput=()=>{output=null;};
function cancel(){const p=pending;pending=null;if(p)p.abort.abort();}
function clearRoute(){route=null;progress=null;off=[];clearOutput();}
function invalidate(next){cancel();clearRoute();status=next;}
function snapshot(){
return {mode,target:target?.slice()??null,objective,revision,status,active,follow:!paused,
request:pending?.id??null,geometry:output?.kind==='route'?structuredClone(route.geometry):null,
instruction:output?structuredClone(output):null};
}
function setJourney({mode:m,target:t,objective:o='shortest'}){
if(!Object.hasOwn(policies,m)||!point(t)||!['shortest','fastest'].includes(o)||(m!=='driving'&&o!=='shortest'))throw Error('INVALID_JOURNEY');
revision++;invalidate('ready');mode=m;target=t.slice();objective=o;active=false;attemptAt=-Infinity;attempts=0;terminal=false;
// Explicit mode selection is required. Existing fix and camera pause are retained.
return snapshot();
}
function start(){if(!target)return snapshot();active=true;status='waiting-gps';return tick();}
function stop(){active=false;invalidate('stopped');return snapshot();}
function pause(){paused=true;return snapshot();}
function resume(){paused=false;return snapshot();}
function network(value){
online=Boolean(value);
if(active&&mode!=='direct'&&!online)invalidate('offline');
if(online&&status==='offline'){attemptAt=-Infinity;status='waiting-gps';return tick();}
return snapshot();
}
function requestRoute(t){
if(pending||!active||mode==='direct'||!online||!usable(fix,t))return;
if(!provider||terminal){status='unavailable';return;}
if(attempts>=maxAttempts){status='retry-exhausted';return;}
if(t-attemptAt<cooldownMs){status='retry-wait';return;}
attemptAt=t;attempts++;clearRoute();status='routing';
const job={id:++serial,revision,deadline:t+timeoutMs,abort:new AbortController()};
pending=job;
const req={mode,objective,target:target.slice(),origin:[fix.longitude,fix.latitude],revision,requestId:job.id,signal:job.abort.signal};
const current=()=>pending===job&&job.revision===revision&&active&&online&&mode===req.mode;
Promise.resolve().then(()=>{if(current())return provider(req);}).then(result=>{
if(!current())return;
if(now()>=job.deadline||!usable(fix,now())){invalidate('waiting-gps');return;}
pending=null;
if(result?.terminal===true){terminal=true;invalidate('unavailable');return;}
if(result?.eligible!==true||result?.graphRevision==null||result?.requestId!==job.id||result?.revision!==revision||result?.mode!==mode||result?.objective!==objective){invalidate('unavailable');return;}
try{
const geometry=structuredClone(result.geometry);
const coords=geometry?.coordinates;
const close=(a,b)=>point(a)&&point(b)&&maths.distanceKm(...a,...b)*1000<=policy().accuracy;
if(!Array.isArray(coords)||!close(coords[0],req.origin)||!close(coords.at(-1),req.target)){terminal=true;invalidate('unavailable');return;}
const locate=createRouteFollower(geometry,maths);
route={geometry,locate,graphRevision:result.graphRevision};
status='tracking';evaluate(fix,now());
}catch{invalidate('unavailable');}
}).catch(()=>{if(current())invalidate('unavailable');});
}
function evaluate(f,t){
clearOutput();
if(mode==='direct'){
const d=maths.distanceKm(f.longitude,f.latitude,...target)*1000;
const b=d>0?maths.initialBearingDeg(f.longitude,f.latitude,...target):null;
if(!finite(d)||d<0){status='uncertain';return;}
status='manual';output={kind:'direct',distanceM:d,bearingDeg:finite(b)?b:null};return;
}
if(!online){invalidate('offline');return;}
if(!route){requestRoute(t);return;}
const p=route.locate(f,t);
if(p.status!=='ok'||!finite(p.progressM)||!finite(p.offsetM)){off=[];status='uncertain';return;}
const q=policy();
if(p.offsetM-f.accuracyM>q.margin){
status='suspect';if(off.at(-1)!==f.timestampMs)off.push(f.timestampMs);
if(off.length>q.confirm)off.shift();
if(off.length===q.confirm&&off.at(-1)-off[0]>=q.span){invalidate('deviated');requestRoute(t);}
return;
}
off=[];
if(progress){
const dt=(f.timestampMs-progress.time)/1000;
const allowance=q.maxSpeed*Math.max(0,dt)+f.accuracyM+progress.accuracy+10;
if(dt<0||Math.abs(p.progressM-progress.metres)>allowance){status='uncertain';return;}
}
progress={metres:p.progressM,time:f.timestampMs,accuracy:f.accuracyM};
status='tracking';
output={kind:'route',remainingM:p.remainingM,segmentIndex:p.segmentIndex,next:route.geometry.coordinates[p.segmentIndex+1].slice(),graphRevision:route.graphRevision};
}
function tick(){
if(!active)return snapshot();
const t=now();
if(!usable(fix,t)){invalidate('waiting-gps');return snapshot();}
if(mode!=='direct'&&!online){invalidate('offline');return snapshot();}
if(pending&&t>=pending.deadline){invalidate('timeout');return snapshot();}
if(!pending)evaluate(fix,t);
return snapshot();
}
function ingest(f){
const t=now();
if(!active)return snapshot();
if(!finite(f?.timestampMs)||f.timestampMs<=last)return tick();
// A future timestamp must not poison the ordering ledger.
if(f.timestampMs>t){invalidate('waiting-gps');return snapshot();}
last=f.timestampMs;fix={...f};
return tick();
}
return {setJourney,start,stop,pause,resume,network,ingest,tick,snapshot};
}Orient16 Recovery Test
A test in the line folder of GridAtlas that checks Orient16 Recovery.
testgridatlas / tools/satnav/line/orient16-recovery.test.mjs · lines 1–14 of 14 · Not reached from any entry point (candidate for review)
- What it does
- It tests its inputs. Uses libraries node:assert/strict.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- No statement of purpose was found in the file, a README line naming it, or its name.
- Why it matters
- Guards the behaviour of Orient16 Recovery.
- Application
- gridatlas · tools/satnav/line · test
- Uses
- Orient16 Recovery (import), node:assert/strict
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/line/orient16-recovery.test.mjs:1-14 · blob 8ebea97ad78b972c1f54c1cae9592d21a7bec198 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
import assert from 'node:assert/strict';
import {createRecovery} from './orient16-recovery.mjs';
const maths={distanceKm:(a,b,c,d)=>Math.hypot(c-a,d-b)*100,initialBearingDeg:()=>90,distanceToSegmentKm:(x,y,a,b,c,d)=>{const t=Math.max(0,Math.min(1,((x-a)*(c-a)+(y-b)*(d-b))/((c-a)**2+(d-b)**2)));return {t,foot:[a+t*(c-a),b+t*(d-b)],km:Math.hypot(x-a-t*(c-a),y-b-t*(d-b))*100}}};
let assertions=0;const eq=(a,b)=>{assert.deepEqual(a,b);assertions++};const settle=async()=>{for(let i=0;i<12;i++)await Promise.resolve()};
for(const mode of ['walking','driving']){
let t=100000,calls=0;
const c=createRecovery({maths,clock:()=>t,cooldownMs:0,maxAttempts:3,provider:async req=>{calls++;return {...req,eligible:true,graphRevision:'fixture',geometry:{type:'LineString',coordinates:[req.origin,[.01,0]]}}}});
c.setJourney({mode,target:[.002,0]});c.start();c.ingest({longitude:0,latitude:0,accuracyM:4,timestampMs:t});await settle();eq(c.snapshot().status,'unavailable');eq(c.snapshot().geometry,null);
for(let i=0;i<100;i++){t++;c.tick();await settle()}eq(calls,1);eq(c.snapshot().instruction,null);
let attempts=0;const r=createRecovery({maths,clock:()=>t,cooldownMs:0,maxAttempts:3,provider:async()=>{attempts++;throw Error('fixture transient')}});
r.setJourney({mode,target:[.002,0]});r.start();r.ingest({longitude:0,latitude:0,accuracyM:4,timestampMs:t});await settle();
for(let i=0;i<100;i++){t++;r.tick();await settle()}eq(attempts,3);eq(r.snapshot().status,'retry-exhausted');eq(r.snapshot().geometry,null);
}
console.log(JSON.stringify({suite:'ORIENT-16 endpoint/retry',assertions,status:'PASS'}));SatNav Offline Plan Browser
A Python command-line tool in the tools folder of GridAtlas that sets pins (`set_pins`).
rendergridatlas / tools/satnav/offline-plan-browser.py · lines 1–212 of 212 · Entry point · pattern end_headers (shared by 3 files)
- What it does
- It fetches data. Defines 10 functions or classes, including test_site, Handler, log_message, end_headers, do_GET. Uses libraries argparse, json, socket, contextlib, functools. Side effects: changes the web page (DOM); reads or writes files; makes network requests; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It is built from the handler class (`Handler`), the log message helper (`log_message`) and the end headers helper (`end_headers`). Exercise the offline plan module and worker in a real browser against a local origin. It accepts `--executable` and `--geodesy`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- gridatlas · tools/satnav · Python CLI
- Uses
- argparse, json, socket, contextlib, functools, http.server, pathlib, shutil
- Used by
- none found
- Produces
- test_site, scopes_and_keys, set_pins, save, expect_plan, exercise
- Defines here
- test_site, Handler, log_message, end_headers, do_GET, scopes_and_keys, set_pins, save, expect_plan, exercise
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/offline-plan-browser.py:1-212 · blob 2cdecb59ac0e278a78e09da50d9e48c2fb562b71 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, storage · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: production_core
"""Exercise the offline plan module and worker in a real browser against a local origin."""
import argparse
import json
import socket
from contextlib import contextmanager
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from shutil import copyfile
from tempfile import TemporaryDirectory
from threading import Event, Thread
from playwright.sync_api import expect, sync_playwright
ROOT = Path(__file__).resolve().parents[2]
CARTRIDGE = "atlas/modules/202611281256-satnav-offline-plan.js"
MODULE = "tools/satnav/field-reliability/offline-plan.mjs"
PINNED = "tools/satnav/vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs"
WORKER = "atlas/v/satnav-offline-plan-202611281315-worker.js"
PREVIOUS_WORKER = "atlas/v/satnav-offline-plan-20261128-worker.js"
CACHE = "ventus-satnav-offline-plans-v1"
VERSIONS = ("satnav-field-test-a", "satnav-field-test-b")
PLAN_A = [[0, 0], [0.001, 0], [0.001, 0.001]]
PLAN_B = [[5, 10], [5, 10.001]]
PRIVATE_FIX = "test-private-measured-fix"
# The fixture supplies only the waypoint map's documented handoff. The installed
# cartridge, module, worker and pinned maths run unmodified inside each browser.
FIXTURE = """<!doctype html><html lang="en"><meta charset="utf-8"><title>Live plan</title>
<section id="satnav-compact"><div id="satnav-field-tools"></div></section>
<script src="/atlas/modules/202611281256-satnav-offline-plan.js"></script>
<script>
window.pins = [];
document.getElementById('satnav-compact').satnavSurvey = {
getPins: () => window.pins,
getFix: () => { throw new Error('Offline plan must not read measured position'); },
};
document.dispatchEvent(new Event('satnav:ready'));
</script></html>"""
@contextmanager
def test_site(geodesy):
with TemporaryDirectory() as directory:
root = Path(directory)
for path in (CARTRIDGE, MODULE, WORKER, PREVIOUS_WORKER, PINNED):
destination = root / path
destination.parent.mkdir(parents=True, exist_ok=True)
copyfile(geodesy if path == PINNED else ROOT / path, destination)
for version in VERSIONS:
folder = root / "atlas/v" / version
folder.mkdir()
(folder / "index.html").write_text(FIXTURE, encoding="utf-8")
(root / "sample-tile.pbf").write_bytes(b"test basemap tile")
unavailable = Event()
class Handler(SimpleHTTPRequestHandler):
def log_message(self, *args):
pass
def end_headers(self):
# Pages can keep its small HTML loader fresh after the network
# goes away. The worker still needs to detect a disconnected origin.
entry = self.path.split("?", 1)[0]
self.send_header("Cache-Control", "public, max-age=600" if entry.endswith(("/", "/index.html")) else "no-store")
super().end_headers()
def do_GET(self):
if unavailable.is_set():
self.close_connection = True
self.connection.shutdown(socket.SHUT_RDWR)
return
super().do_GET()
with ThreadingHTTPServer(("127.0.0.1", 0), partial(Handler, directory=directory)) as server:
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_port}", unavailable
finally:
server.shutdown()
thread.join()
def scopes_and_keys(page):
return page.evaluate("""async name => {
const registrations = await navigator.serviceWorker.getRegistrations();
const items = (await caches.keys()).includes(name) ? await (await caches.open(name)).keys() : [];
return {
scopes: registrations.map(r => r.scope).sort(),
keys: items.map(key => key.url).sort(),
local: localStorage.length, session: sessionStorage.length,
};
}""", CACHE)
def set_pins(page, points):
page.evaluate("(pins) => window.pins = pins", [
{"id": str(i), "coordinate": at, "ignoredMetadata": PRIVATE_FIX}
for i, at in enumerate(points)
])
def save(page, pins):
set_pins(page, pins)
page.get_by_role("button", name="Save plan", exact=True).click()
expect(page.get_by_role("status")).to_contain_text("Saved. Reopen", timeout=20000)
def expect_plan(page, url, expected):
response = page.goto(url, wait_until="domcontentloaded", timeout=20000)
assert response is not None and response.status == 200
expect(page.get_by_role("heading", name="Saved field plan")).to_be_visible()
stored = json.loads(page.locator("#saved-plan").text_content())
assert stored["coordinates"] == expected
assert set(stored) == {"coordinates", "legs", "totalM", "savedAt"}
assert PRIVATE_FIX not in page.content()
expect(page.locator("#pin")).to_have_text(f"Pin 1 of {len(expected)}")
expect(page.locator("#previous")).to_be_disabled()
return stored
def exercise(browser, origin, unavailable):
urls = [f"{origin}/atlas/v/{name}/" for name in VERSIONS]
keys = [url + "__saved-field-plan__" for url in urls]
context = browser.new_context(viewport={"width": 390, "height": 664}, has_touch=True)
try:
pages = [context.new_page(), context.new_page()]
for page, url in zip(pages, urls):
page.goto(url)
page.get_by_text("Offline plan", exact=True).click()
assert scopes_and_keys(pages[0]) == {"scopes": [], "keys": [], "local": 0, "session": 0}
# Upgrading a previously saved version must take over its original scope.
legacy_url = f"{origin}/{PREVIOUS_WORKER}"
pages[1].evaluate("url => navigator.serviceWorker.register(url, {scope: './'}).then(() => navigator.serviceWorker.ready).then(() => true)", legacy_url)
save(pages[0], PLAN_A)
save(pages[1], PLAN_B)
pages[1].wait_for_function("url => navigator.serviceWorker.controller?.scriptURL === url",
arg=f"{origin}/{WORKER}")
# Ordinary basemap fetches, unread GPS and unrelated metadata never enter the cache.
assert pages[0].evaluate("async () => (await fetch('/sample-tile.pbf')).ok")
assert scopes_and_keys(pages[0]) == {"scopes": urls, "keys": keys, "local": 0, "session": 0}
set_pins(pages[0], [[200, 0], [0, 1]])
pages[0].get_by_role("button", name="Save plan", exact=True).click()
expect(pages[0].get_by_role("status")).to_contain_text("invalid coordinates")
assert scopes_and_keys(pages[0])["keys"] == keys
# Drop all origin connections in both engines. Chromium also supports offline
# emulation during navigation. The WebKit inspector switch cancels even
# navigation handled by a worker returning a constant, before fetch fires.
unavailable.set()
pages[0].reload(wait_until="domcontentloaded")
expect(pages[0].get_by_role("heading", name="Saved field plan")).to_be_visible()
fresh = context.new_page()
expect_plan(fresh, urls[0], PLAN_A)
if browser.browser_type.name == "chromium":
context.set_offline(True)
plan = expect_plan(fresh, urls[0] + "index.html?field=1", PLAN_A)
assert plan["legs"] == [[111, 90], [111, 0]] and plan["totalM"] == 223
expect(fresh.locator("#coordinate")).to_have_text("0.00000°, 0.00000°")
expect(fresh.locator("#leg")).to_contain_text("111 m · 90° true")
fresh.locator("#next").click()
expect(fresh.locator("#coordinate")).to_have_text("0.00000°, 0.00100°")
expect(fresh.locator("#leg")).to_contain_text("111 m · 0° true")
fresh.locator("#next").click()
expect(fresh.locator("#leg")).to_have_text("Last planned pin")
expect(fresh.locator("#next")).to_be_disabled()
fresh.locator("#previous").click()
expect(fresh.locator("#pin")).to_have_text("Pin 2 of 3")
second = context.new_page()
expect_plan(second, urls[1], PLAN_B)
second.locator("#forget").click()
expect(second.get_by_text("Saved plan removed from this device.")).to_be_visible()
assert scopes_and_keys(second)["keys"] == [keys[0]]
empty = second.goto(urls[1], wait_until="domcontentloaded")
assert empty is not None and empty.status == 503
expect(second.locator("body")).to_contain_text("no saved field plan")
expect_plan(fresh, urls[0], PLAN_A)
# When the connection returns, the live page wins even with a saved copy.
if browser.browser_type.name == "chromium":
context.set_offline(False)
unavailable.clear()
fresh.reload()
expect(fresh).to_have_title("Live plan")
fresh.get_by_text("Offline plan", exact=True).click()
fresh.get_by_role("button", name="Forget saved plan").click()
expect(fresh.get_by_role("status")).to_contain_text("removed")
assert scopes_and_keys(fresh)["keys"] == []
finally:
unavailable.clear()
context.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("browser", choices=("chromium", "webkit"))
parser.add_argument("--executable", help="Optional path to a local browser binary")
parser.add_argument("--geodesy", type=Path, default=ROOT / PINNED,
help="Canonical geodesy.mjs from the pinned SatNav release")
args = parser.parse_args()
if not args.geodesy.is_file():
parser.error("Pass --geodesy with the pinned SatNav geodesy.mjs or run from the integrated waypoint checkout")
with test_site(args.geodesy) as (origin, unavailable), sync_playwright() as playwright:
options = {"executable_path": args.executable} if args.executable else {}
browser = getattr(playwright, args.browser).launch(**options)
try:
exercise(browser, origin, unavailable)
print(f"{args.browser}: explicit save, offline reload/new tab, bearings, isolation, invalid edits and forget passed")
finally:
browser.close()SatNav Orient14 Browser
A Python module in the tools folder of GridAtlas.
rendergridatlas / tools/satnav/orient14-browser.py · lines 1–58 of 58 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries os, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/satnav · Python module
- Uses
- os, pathlib, runpy, playwright.sync_api
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/orient14-browser.py:1-58 · blob 42203dd8cb31e0706c28e6e97a7b0e6e6061d1f4 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
"""ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated."""
import os
from pathlib import Path
from runpy import run_path
from playwright.sync_api import expect, sync_playwright
gps=run_path(str(Path(__file__).with_name('compact-browser.py')))['GPS_SPY']
site='http://127.0.0.1:8873/atlas/v/202612030153/'
with sync_playwright() as p:
engine=os.environ['ORIENT_BROWSER']
browser=getattr(p,engine).launch()
with browser.new_context(viewport={'width':390,'height':844},is_mobile=True,has_touch=True) as ctx:
ctx.add_init_script(gps)
page=ctx.new_page()
page.goto(site,wait_until='domcontentloaded',timeout=90000)
page.wait_for_function("""() => document.querySelector('#satnav-compact')?.satnavSurvey?.getMap()?.getLayer('l-sat') && document.querySelector('#satnav-walk-mode')""",timeout=120000)
panel=page.locator('#satnav-compact')
if not panel.is_visible():
page.locator('#satnav-toggle').tap()
expect(panel).to_be_visible()
page.evaluate("""() => document.querySelector('#satnav-compact').satnavSurvey.replacePlan([[-0.4,51.55],[-0.4,51.65]])""")
endpoint="document.querySelector('#satnav-compact').satnavSurvey.getEndpoints()"
initial=page.evaluate(endpoint)
assert initial==[[-0.4,51.55],[-0.4,51.65]],initial
mode=page.locator('#satnav-walk-mode')
objective=page.locator('#satnav-route-objective')
start=page.locator('#satnav-walk-start')
guidance=page.locator('#satnav-walk-guidance')
expect(mode).to_have_value('walking')
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest walking route unavailable')
assert page.evaluate('window.__lineGpsTest.records.starts')==[]
mode.select_option('driving')
expect(objective).to_be_visible()
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest driving route unavailable')
objective.select_option('fastest')
expect(guidance).to_contain_text('Estimated fastest route unavailable')
assert page.evaluate(endpoint)==initial
mode.select_option('direct')
expect(start).to_be_enabled()
start.tap()
page.evaluate("window.__lineGpsTest.emit([-0.4,51.551],4)")
expect(guidance).to_contain_text('straight-line guidance')
expect(guidance).to_contain_text('straight to destination')
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
for k in range(10):
mode.select_option('walking' if k%2==0 else 'driving')
expect(start).to_be_disabled()
assert page.evaluate(endpoint)==initial
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
mode.select_option('direct')
start.tap()
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
page.locator('#satnav-walk-stop').tap()
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[1]}
assert page.evaluate(endpoint)==initial
print(f'PASS {engine}: composed three-mode UI, shared plan, unavailable states, one GPS watch and stop')
browser.close()SatNav Orient16 Browser
A Python module in the tools folder of GridAtlas.
rendergridatlas / tools/satnav/orient16-browser.py · lines 1–63 of 63 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries os, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/satnav · Python module
- Uses
- os, pathlib, runpy, playwright.sync_api
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/orient16-browser.py:1-63 · blob a41e07a8e1556eada667bc3909fedb4ac484a42c · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
"""ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated."""
import os
from pathlib import Path
from runpy import run_path
from playwright.sync_api import expect, sync_playwright
gps=run_path(str(Path(__file__).with_name('compact-browser.py')))['GPS_SPY']
site='http://127.0.0.1:8873/atlas/v/202612031130/'
with sync_playwright() as p:
engine=os.environ['ORIENT_BROWSER']
browser=getattr(p,engine).launch()
for width,height,mobile in [(390,844,True),(844,390,True),(1280,800,False)]:
with browser.new_context(viewport={'width':width,'height':height},is_mobile=mobile,has_touch=True) as ctx:
ctx.add_init_script(gps)
page=ctx.new_page()
page.goto(site,wait_until='domcontentloaded',timeout=90000)
page.wait_for_function("""() => document.querySelector('#satnav-compact')?.satnavSurvey?.getMap()?.getLayer('l-sat') && document.querySelector('#satnav-walk-mode')""",timeout=120000)
panel=page.locator('#satnav-compact')
if not panel.is_visible():
page.locator('#satnav-toggle').tap()
expect(panel).to_be_visible()
page.evaluate("""() => document.querySelector('#satnav-compact').satnavSurvey.replacePlan([[-0.4,51.55],[-0.4,51.65]])""")
endpoint="document.querySelector('#satnav-compact').satnavSurvey.getEndpoints()"
initial=page.evaluate(endpoint)
assert initial==[[-0.4,51.55],[-0.4,51.65]],initial
mode=page.locator('#satnav-walk-mode')
objective=page.locator('#satnav-route-objective')
start=page.locator('#satnav-walk-start')
guidance=page.locator('#satnav-walk-guidance')
expect(mode).to_have_value('walking')
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest walking route unavailable')
assert page.evaluate('window.__lineGpsTest.records.starts')==[]
mode.select_option('driving')
expect(objective).to_be_visible()
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest driving route unavailable')
objective.select_option('fastest')
expect(guidance).to_contain_text('Estimated fastest route unavailable')
assert page.evaluate(endpoint)==initial
mode.select_option('direct')
expect(start).to_be_enabled()
start.tap()
page.evaluate("window.__lineGpsTest.emit([-0.4,51.551],4)")
expect(guidance).to_contain_text('straight-line guidance')
expect(guidance).to_contain_text('straight to destination')
page.wait_for_timeout(11000)
expect(guidance).to_contain_text('Waiting for a fresh GPS fix')
page.evaluate("window.__lineGpsTest.emit([-0.4,51.552],4)")
expect(guidance).to_contain_text('straight to destination')
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
for k in range(10):
mode.select_option('walking' if k%2==0 else 'driving')
expect(start).to_be_disabled()
assert page.evaluate(endpoint)==initial
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
mode.select_option('direct')
start.tap()
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
page.locator('#satnav-walk-stop').tap()
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[1]}
assert page.evaluate(endpoint)==initial
print(f'PASS {engine} {width}x{height}: composed three-mode UI, shared plan, unavailable states, one GPS watch and stop')
browser.close()SatNav Orient16 Recovery Browser
A Python module in the tools folder of GridAtlas.
rendergridatlas / tools/satnav/orient16-recovery-browser.py · lines 1–171 of 171 · Not reached from any entry point (candidate for review)
- What it does
- Uses libraries os, json, pathlib, runpy, playwright.sync_api. Side effects: changes the web page (DOM); reads or writes files.
- Why it exists in the grid workflow
- Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
- What it achieves
- ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated.
- Why it matters
- No other file in the estate was found to import it.
- Application
- gridatlas · tools/satnav · Python module
- Uses
- os, json, pathlib, runpy, playwright.sync_api
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- gridatlas@98b5004c5eda9f2ed915fb6fca4b9bbcaa426ca5 tools/satnav/orient16-recovery-browser.py:1-171 · blob 0d798254f098873d7fa4a749c30fa112065b4b8b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unreached_review
"""ORIENT-14: real numbered GridAtlas composition; only the GPS boundary is simulated."""
import os
import json
from pathlib import Path
from runpy import run_path
from playwright.sync_api import expect, sync_playwright
helpers=run_path(str(Path(__file__).with_name('compact-browser.py')))
gps=helpers['GPS_SPY']
map_canvas_tap=helpers['map_canvas_tap']
surface_distance=helpers['surface_distance']
site='http://127.0.0.1:8873/atlas/v/202612031235/'
with sync_playwright() as p:
engine=os.environ['ORIENT_BROWSER']
browser=getattr(p,engine).launch()
for width,height,mobile in [(390,844,True),(844,390,True),(1280,800,False),(1366,768,False)]:
with browser.new_context(viewport={'width':width,'height':height},is_mobile=mobile,has_touch=True) as ctx:
ctx.add_init_script(gps)
page=ctx.new_page()
page.goto(site,wait_until='domcontentloaded',timeout=90000)
page.wait_for_function("""() => document.querySelector('#satnav-compact')?.satnavSurvey?.getMap()?.getLayer('l-sat') && document.querySelector('#satnav-walk-mode')""",timeout=120000)
panel=page.locator('#satnav-compact')
if not panel.is_visible():
page.locator('#satnav-toggle').tap()
expect(panel).to_be_visible()
page.evaluate("window.__GRIDATLAS_V9_MAP__.jumpTo({center: [-1.5, 51.5], zoom: 16})")
page.locator('#satnav-to').tap()
tap=map_canvas_tap(page)
actual=page.evaluate("document.querySelector('#satnav-compact').satnavSurvey.getEndpoints()[1]")
assert surface_distance(tap['coordinates'],actual)<2,(tap,actual)
page.evaluate("""() => document.querySelector('#satnav-compact').satnavSurvey.replacePlan([[-0.4,51.55],[-0.4,51.65]])""")
endpoint="document.querySelector('#satnav-compact').satnavSurvey.getEndpoints()"
initial=page.evaluate(endpoint)
assert initial==[[-0.4,51.55],[-0.4,51.65]],initial
mode=page.locator('#satnav-walk-mode')
objective=page.locator('#satnav-route-objective')
start=page.locator('#satnav-walk-start')
guidance=page.locator('#satnav-walk-guidance')
expect(mode).to_have_value('walking')
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest walking route unavailable')
assert page.evaluate('window.__lineGpsTest.records.starts')==[]
mode.select_option('driving')
expect(objective).to_be_visible()
expect(start).to_be_disabled()
expect(guidance).to_contain_text('Shortest driving route unavailable')
objective.select_option('fastest')
expect(guidance).to_contain_text('Estimated fastest route unavailable')
assert page.evaluate(endpoint)==initial
mode.select_option('direct')
expect(start).to_be_enabled()
start.tap()
page.evaluate("window.__lineGpsTest.emit([-0.4,51.551],4)")
expect(guidance).to_contain_text('straight-line guidance')
expect(guidance).to_contain_text('straight to destination')
# No directional bearing within GPS uncertainty; do not imply arrival.
page.evaluate("window.__lineGpsTest.emit([-0.4,51.64999],4)")
expect(guidance).to_contain_text('straight to destination')
expect(guidance).not_to_contain_text('° true')
page.wait_for_timeout(20)
page.evaluate("window.__lineGpsTest.emit([-0.4,51.551],4)")
expect(guidance).to_contain_text('° true')
# Deterministically emulate document suspension and resume, not physical OS suspension.
page.evaluate("Object.defineProperty(document,'hidden',{configurable:true,value:true});document.dispatchEvent(new Event('visibilitychange'))")
expect(guidance).to_contain_text('Guidance suspended')
expect(guidance).not_to_contain_text('° true')
page.evaluate("Object.defineProperty(document,'hidden',{configurable:true,value:false});document.dispatchEvent(new Event('visibilitychange'))")
expect(guidance).to_contain_text('Waiting for a fresh GPS fix')
page.wait_for_timeout(20)
page.evaluate("window.__lineGpsTest.emit([-0.4,51.552],4)")
expect(guidance).to_contain_text('° true')
# Panel collapse/reopen must not change destination or acquire a second GPS watch.
for _ in range(3):
page.locator('#satnav-toggle').tap()
expect(panel).to_be_hidden()
assert page.evaluate(endpoint)==initial
page.locator('#satnav-toggle').tap()
expect(panel).to_be_visible()
expect(page.get_by_role('combobox',name='Guidance mode')).to_be_visible()
expect(guidance).to_have_attribute('role','status')
expect(page.get_by_role('button',name='Stop guidance')).to_be_visible()
assert mode.bounding_box()['height']>=44
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
page.wait_for_timeout(11000)
expect(guidance).to_contain_text('Waiting for a fresh GPS fix')
page.evaluate("window.__lineGpsTest.emit([-0.4,51.552],4)")
expect(guidance).to_contain_text('straight to destination')
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
for k in range(10):
mode.select_option('walking' if k%2==0 else 'driving')
expect(start).to_be_disabled()
assert page.evaluate(endpoint)==initial
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[]}
mode.select_option('direct')
start.tap()
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
# Real pointer and keyboard acceptance, not synthetic MapLibre events.
api="document.querySelector('#satnav-compact').satnavSurvey"
map_js="window.__GRIDATLAS_V9_MAP__"
layer_state="""() => [...document.querySelectorAll('#scada-ui-container input[data-layer-id]')].map(x=>[x.dataset.layerId,x.checked]).sort()"""
saved_layers=page.evaluate(layer_state)
toggle=page.locator('#satnav-toggle')
toggle.focus()
toggle.press('Enter')
expect(panel).to_be_hidden()
expect(toggle).to_have_attribute('aria-expanded','false')
assert page.evaluate(endpoint)==initial
layers=page.locator('#gridatlas-dash-toggle')
dash_state="""()=>({full:!!(document.fullscreenElement||document.webkitFullscreenElement||document.body.classList.contains('fs-active')||document.getElementById('map-container')?.classList.contains('is-fullscreen')),curtain:document.getElementById('fs-curtain')?.classList.contains('curtain-open'),collapsed:window.__GRIDATLAS_DASH__?.collapsed})"""
before=page.evaluate(dash_state)
state_key='curtain' if before['full'] else 'collapsed'
assert isinstance(before[state_key],bool),before
layers.click()
page.wait_for_function("(arg)=>("+dash_state+")()[arg.key]!==arg.value",arg={'key':state_key,'value':before[state_key]})
layers.click()
page.wait_for_function("(arg)=>("+dash_state+")()[arg.key]===arg.value",arg={'key':state_key,'value':before[state_key]})
assert page.evaluate(layer_state)==saved_layers
# Reopen by keyboard; location is the existing sole camera controller.
toggle.focus()
toggle.press('Enter')
expect(panel).to_be_visible()
expect(toggle).to_have_attribute('aria-expanded','true')
location=page.locator('#satnav-location')
location.click()
page.wait_for_timeout(30)
page.evaluate("window.__lineGpsTest.emit([-0.4,51.553],4)")
page.wait_for_function("()=>"+api+".isFollowing()")
zoom=page.evaluate(map_js+".getZoom()")
toggle.click()
expect(panel).to_be_hidden()
# Choose a completely exposed horizontal segment of the map canvas.
segment=page.wait_for_function("""()=>{const m=window.__GRIDATLAS_V9_MAP__;if(m.isMoving())return null;const c=m.getCanvas(),r=c.getBoundingClientRect();
for(const fy of [.72,.62,.52,.42])for(const fx of [.24,.44,.64]){
const x=Math.round(r.left+r.width*fx),y=Math.round(r.top+r.height*fy);
if([0,15,30,45,60].every(d=>document.elementFromPoint(x+d,y)===c))return {x,y};}
return null;}""",timeout=15000).json_value()
page.mouse.move(segment['x'],segment['y'])
page.mouse.down()
page.mouse.move(segment['x']+60,segment['y'],steps=12)
page.mouse.up()
page.wait_for_function("()=>!"+api+".isFollowing() && !"+map_js+".isMoving()",timeout=15000)
paused=page.evaluate(map_js+".getCenter().toArray()")
page.wait_for_timeout(30)
page.evaluate("window.__lineGpsTest.emit([-0.4,51.554],4)")
assert surface_distance(paused,page.evaluate(map_js+".getCenter().toArray()"))<2
assert abs(page.evaluate(map_js+".getZoom()")-zoom)<0.01
toggle.click()
expect(location).to_contain_text('Resume follow')
location.click()
page.wait_for_function("()=>"+api+".isFollowing()")
page.wait_for_timeout(30)
page.evaluate("window.__lineGpsTest.emit([-0.4,51.555],4)")
page.wait_for_function("()=>Math.abs("+map_js+".getCenter().lat-51.555)<0.00001")
assert abs(page.evaluate(map_js+".getZoom()")-zoom)<0.01
assert page.evaluate(endpoint)==initial
assert page.evaluate(layer_state)==saved_layers
assert page.evaluate('window.__lineGpsTest.records.starts')==[1]
# Measure actual unobstructed hit area, not only canvas CSS dimensions.
toggle.click()
expect(panel).to_be_hidden()
usable=page.evaluate("""()=>{const c=window.__GRIDATLAS_V9_MAP__.getCanvas();let hit=0,total=0;
for(let y=10;y<innerHeight;y+=20)for(let x=10;x<innerWidth;x+=20){total++;if(document.elementFromPoint(x,y)===c)hit++;}
return {hit,total,ratio:hit/total};}""")
print('ORIENT16_INTERACTION',json.dumps({'engine':engine,'width':width,'height':height,'map_hit_area':usable,'zoom':zoom,'destination_preserved':True,'follow_resumed':True}),flush=True)
assert usable['ratio']>0.5,usable
toggle.click()
expect(panel).to_be_visible()
page.locator('#satnav-walk-stop').tap()
assert page.evaluate('window.__lineGpsTest.records')=={'starts':[1],'stops':[1]}
assert page.evaluate(endpoint)==initial
print(f'PASS {engine} {width}x{height}: composed three-mode UI, shared plan, unavailable states, one GPS watch and stop')
browser.close()