fix(tunnelsafety): add best-effort geolocation metadata to hazard reports
Coherence audit (.omo/evidence/coherence-audit/tunnelsafety.md) found navigator.geolocation unused repo-wide while hazard reports carried no location signal beyond a manual segment-name dropdown. ReportHazardForm now reads a best-effort GPS/network fix on mount via useBestEffortGeolocation() and attaches it as an optional coords field on submit - never required, never fabricated on denial/timeout/absence, and never used to auto-select segmentId (GPS alone cannot resolve which named corridor a resident is in; segment selection stays manual and authoritative). tunnelrouting.ts is untouched - routing stays purely segment-id-based. - HazardReportPayload/HazardReport gain an optional coords field (latitude/longitude/accuracy), validated and round-tripped by computeHazardReports; a malformed coords shape is rejected like any other corrupt payload. - The form shows a "Location captured"/"Location unavailable" indicator; the hazard feed renders captured coords per report. - New tests: reportHazard coords round-trip, no-coords unaffected behavior, tampered-coords rejection, and a component test mocking navigator.geolocation.getCurrentPosition for both the success and denied/unavailable paths. - New Playwright e2e (chromium, real context.permissions geolocation grant/deny) proves the full grant and deny flows end to end with screenshot evidence. Co-authored-by: sisyphus-dev-ai <sisyphus-dev-ai@users.noreply.github.com>
This commit is contained in:
1 parent
ba5489ce8a
commit
e321949195
10 files changed
+618
-3
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"task": "Tunnel Safety coherence-audit fix: best-effort navigator.geolocation on ReportHazardForm",
|
||||
"tool": "Playwright (chromium), real Vite dev server, real app UI ('/miniapp/tunnel-safety' -> ReportHazardForm/HazardFeed), real context.permissions/geolocation grant+deny",
|
||||
"run_command": "node e2e/tunnelSafetyGeolocation.e2e.mjs",
|
||||
"selectors_used": [
|
||||
"tunnel-safety-report-location-status",
|
||||
"tunnel-safety-report-segment",
|
||||
"tunnel-safety-report-status",
|
||||
"tunnel-safety-report-submit",
|
||||
"tunnel-safety-report-status-text",
|
||||
"tunnel-safety-hazard-feed"
|
||||
],
|
||||
"timestamp": "2026-11-20T22:46:35.349Z",
|
||||
"results": [
|
||||
{
|
||||
"scenario": "geolocation-granted",
|
||||
"steps": {
|
||||
"locationCaptured": {
|
||||
"statusText": "Location captured (38.8977, -77.0365, ±20m)"
|
||||
},
|
||||
"submitted": {
|
||||
"text": "Hazard reported."
|
||||
},
|
||||
"feedShowsCoords": {
|
||||
"feedText": "Market Junction → Residential Loop\nFLOODED\nUnconfirmed - 1 report\nReported by 9659548c at 5:46:34 PM\nLocation: 38.8977, -77.0365 (±20m)\nMark resolved"
|
||||
}
|
||||
},
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"scenario": "geolocation-denied",
|
||||
"steps": {
|
||||
"locationUnavailable": {
|
||||
"statusText": "Location unavailable - segment selection above is used instead."
|
||||
},
|
||||
"submittedDespiteNoLocation": {
|
||||
"text": "Hazard reported."
|
||||
},
|
||||
"feedShowsReportNoCoords": {
|
||||
"feedText": "South Gate → Lower Commons\nBLOCKED\nUnconfirmed - 1 report\nReported by c52931d8 at 5:46:35 PM\nMark resolved",
|
||||
"hasLocationLine": false
|
||||
}
|
||||
},
|
||||
"pass": true
|
||||
}
|
||||
],
|
||||
"pass": true
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,251 @@
|
||||
// Tunnel Safety best-effort geolocation acceptance test (coherence-audit
|
||||
// gap fix). Self-contained Playwright runner, same shape as
|
||||
// e2e/housingMentorWalletDemo.e2e.mjs: starts a real Vite dev server, opens
|
||||
// a real browser page per scenario with Playwright's real geolocation
|
||||
// permission grant/deny, and drives the real ReportHazardForm UI through
|
||||
// its real submit path - no mocks of navigator.geolocation itself.
|
||||
//
|
||||
// GRANTED: context permissions include "geolocation" with a real fixed
|
||||
// coordinate -> the form must show "Location captured", and the submitted
|
||||
// hazard report must carry those coords through to the feed.
|
||||
// DENIED: context permissions omit "geolocation" -> Chromium resolves
|
||||
// getCurrentPosition with PERMISSION_DENIED -> the form must show
|
||||
// "Location unavailable" and still submit the report successfully (no
|
||||
// crash, no required field), with no coords line rendered for it.
|
||||
import { chromium } from "playwright";
|
||||
import { createServer as createViteServer } from "vite";
|
||||
import * as ed from "@noble/ed25519";
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = resolve(__dirname, "..");
|
||||
const VITE_PORT = 48000 + Math.floor(Math.random() * 10000);
|
||||
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
|
||||
const EV_DIR = resolve(ROOT, ".omo/evidence/coherence-audit");
|
||||
|
||||
const FIXED_COORDS = { latitude: 38.8977, longitude: -77.0365, accuracy: 20 };
|
||||
|
||||
async function seedIdentity(context) {
|
||||
const { secretKey, publicKey } = await ed.keygenAsync();
|
||||
await context.addInitScript(
|
||||
({ secretKey, publicKey }) => {
|
||||
const openReq = indexedDB.open("the-commons-hollow", 4);
|
||||
openReq.onupgradeneeded = () => {
|
||||
const db = openReq.result;
|
||||
if (!db.objectStoreNames.contains("identity")) db.createObjectStore("identity", { keyPath: "id" });
|
||||
if (!db.objectStoreNames.contains("eventLog")) {
|
||||
const store = db.createObjectStore("eventLog", { keyPath: "id", autoIncrement: true });
|
||||
store.createIndex("lamportTs", "lamportTs", { unique: false });
|
||||
}
|
||||
if (!db.objectStoreNames.contains("miniappPackages")) {
|
||||
const store = db.createObjectStore("miniappPackages", { keyPath: "id" });
|
||||
store.createIndex("sourceBlobId", "sourceBlobId", { unique: true });
|
||||
}
|
||||
};
|
||||
openReq.onsuccess = () => {
|
||||
const db = openReq.result;
|
||||
const tx = db.transaction("identity", "readwrite");
|
||||
tx.objectStore("identity").put({
|
||||
id: "local",
|
||||
publicKey: new Uint8Array(publicKey),
|
||||
secretKey: new Uint8Array(secretKey),
|
||||
createdAt: Date.now(),
|
||||
});
|
||||
// Close this raw connection once the seed write lands, so it never
|
||||
// blocks the real app's Dexie connection (which opens the same
|
||||
// database at Dexie's own internal version encoding) from
|
||||
// completing its own open/upgrade a moment later.
|
||||
tx.oncomplete = () => db.close();
|
||||
};
|
||||
},
|
||||
{ secretKey: Array.from(secretKey), publicKey: Array.from(publicKey) },
|
||||
);
|
||||
}
|
||||
|
||||
async function runGrantedScenario(browser) {
|
||||
const context = await browser.newContext({ permissions: ["geolocation"], geolocation: FIXED_COORDS });
|
||||
const evidence = { scenario: "geolocation-granted", steps: {} };
|
||||
try {
|
||||
await seedIdentity(context);
|
||||
const page = await context.newPage();
|
||||
await page.goto(`${APP_URL}/miniapp/tunnel-safety`);
|
||||
|
||||
const locationStatus = page.getByTestId("tunnel-safety-report-location-status");
|
||||
await locationStatus.waitFor();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="tunnel-safety-report-location-status"]')?.textContent?.includes("Location captured"),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
const statusText = await locationStatus.innerText();
|
||||
evidence.steps.locationCaptured = { statusText };
|
||||
if (!statusText.includes("Location captured")) {
|
||||
throw new Error(`granted: expected "Location captured" text, got "${statusText}"`);
|
||||
}
|
||||
if (!statusText.includes("38.8977") || !statusText.includes("-77.0365")) {
|
||||
throw new Error(`granted: expected the real fixed coords in the status text, got "${statusText}"`);
|
||||
}
|
||||
|
||||
await page.getByTestId("tunnel-safety-report-segment").selectOption("seg-market-residential");
|
||||
await page.getByTestId("tunnel-safety-report-status").selectOption("flooded");
|
||||
await page.getByTestId("tunnel-safety-report-submit").click();
|
||||
|
||||
const submitStatus = page.getByTestId("tunnel-safety-report-status-text");
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="tunnel-safety-report-status-text"]')?.textContent?.includes("Hazard reported."),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
evidence.steps.submitted = { text: await submitStatus.innerText() };
|
||||
|
||||
const feed = page.getByTestId("tunnel-safety-hazard-feed");
|
||||
await feed.waitFor();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="tunnel-safety-hazard-feed"]')?.textContent?.includes("Location:"),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
const feedText = await feed.innerText();
|
||||
evidence.steps.feedShowsCoords = { feedText };
|
||||
if (!feedText.includes("38.8977") || !feedText.includes("-77.0365")) {
|
||||
throw new Error(`granted: expected the hazard feed to render the captured coords, got: ${feedText}`);
|
||||
}
|
||||
|
||||
mkdirSync(EV_DIR, { recursive: true });
|
||||
await page.screenshot({ path: resolve(EV_DIR, "tunnelsafety-geolocation-granted.png") });
|
||||
|
||||
evidence.pass = true;
|
||||
return evidence;
|
||||
} catch (err) {
|
||||
evidence.pass = false;
|
||||
evidence.error = String(err && err.message ? err.message : err);
|
||||
throw Object.assign(err, { evidence });
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function runDeniedScenario(browser) {
|
||||
// No "geolocation" permission granted -> Chromium's getCurrentPosition
|
||||
// resolves the error callback with PERMISSION_DENIED, exactly like a
|
||||
// resident declining the browser prompt.
|
||||
const context = await browser.newContext();
|
||||
const evidence = { scenario: "geolocation-denied", steps: {} };
|
||||
try {
|
||||
await seedIdentity(context);
|
||||
const page = await context.newPage();
|
||||
await page.goto(`${APP_URL}/miniapp/tunnel-safety`);
|
||||
|
||||
const locationStatus = page.getByTestId("tunnel-safety-report-location-status");
|
||||
await locationStatus.waitFor();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="tunnel-safety-report-location-status"]')?.textContent?.includes("Location unavailable"),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
const statusText = await locationStatus.innerText();
|
||||
evidence.steps.locationUnavailable = { statusText };
|
||||
if (!statusText.includes("Location unavailable")) {
|
||||
throw new Error(`denied: expected "Location unavailable" text, got "${statusText}"`);
|
||||
}
|
||||
|
||||
await page.getByTestId("tunnel-safety-report-segment").selectOption("seg-south-commons");
|
||||
await page.getByTestId("tunnel-safety-report-status").selectOption("blocked");
|
||||
await page.getByTestId("tunnel-safety-report-submit").click();
|
||||
|
||||
const submitStatus = page.getByTestId("tunnel-safety-report-status-text");
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="tunnel-safety-report-status-text"]')?.textContent?.includes("Hazard reported."),
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
evidence.steps.submittedDespiteNoLocation = { text: await submitStatus.innerText() };
|
||||
|
||||
const feed = page.getByTestId("tunnel-safety-hazard-feed");
|
||||
await feed.waitFor();
|
||||
const feedText = await feed.innerText();
|
||||
evidence.steps.feedShowsReportNoCoords = { feedText, hasLocationLine: feedText.includes("Location:") };
|
||||
if (feedText.includes("Location:")) {
|
||||
throw new Error(`denied: expected NO coords line in the feed for a report with no geolocation fix, got: ${feedText}`);
|
||||
}
|
||||
if (!feedText.includes("South Gate") && !feedText.includes("Lower Commons")) {
|
||||
throw new Error(`denied: expected the hazard to still report and appear in the feed, got: ${feedText}`);
|
||||
}
|
||||
|
||||
mkdirSync(EV_DIR, { recursive: true });
|
||||
await page.screenshot({ path: resolve(EV_DIR, "tunnelsafety-geolocation-denied.png") });
|
||||
|
||||
evidence.pass = true;
|
||||
return evidence;
|
||||
} catch (err) {
|
||||
evidence.pass = false;
|
||||
evidence.error = String(err && err.message ? err.message : err);
|
||||
throw Object.assign(err, { evidence });
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const vite = await createViteServer({
|
||||
root: ROOT,
|
||||
configFile: resolve(ROOT, "vite.config.ts"),
|
||||
logLevel: "warn",
|
||||
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
|
||||
});
|
||||
await vite.listen();
|
||||
|
||||
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
|
||||
|
||||
const results = [];
|
||||
let failed = false;
|
||||
try {
|
||||
for (const run of [runGrantedScenario, runDeniedScenario]) {
|
||||
try {
|
||||
results.push(await run(browser));
|
||||
} catch (e) {
|
||||
failed = true;
|
||||
results.push(e.evidence ?? { pass: false, error: String(e) });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
await vite.close();
|
||||
}
|
||||
|
||||
mkdirSync(EV_DIR, { recursive: true });
|
||||
const now = new Date().toISOString();
|
||||
writeFileSync(
|
||||
resolve(EV_DIR, "tunnelsafety-geolocation-fix.e2e.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
task: "Tunnel Safety coherence-audit fix: best-effort navigator.geolocation on ReportHazardForm",
|
||||
tool: "Playwright (chromium), real Vite dev server, real app UI ('/miniapp/tunnel-safety' -> ReportHazardForm/HazardFeed), real context.permissions/geolocation grant+deny",
|
||||
run_command: "node e2e/tunnelSafetyGeolocation.e2e.mjs",
|
||||
selectors_used: [
|
||||
"tunnel-safety-report-location-status",
|
||||
"tunnel-safety-report-segment",
|
||||
"tunnel-safety-report-status",
|
||||
"tunnel-safety-report-submit",
|
||||
"tunnel-safety-report-status-text",
|
||||
"tunnel-safety-hazard-feed",
|
||||
],
|
||||
timestamp: now,
|
||||
results,
|
||||
pass: results.every((r) => r && r.pass),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
console.log("\n===== e2e RESULTS =====");
|
||||
console.log(JSON.stringify(results, null, 2));
|
||||
const allPass = results.every((r) => r && r.pass);
|
||||
console.log(`\nSUMMARY: geolocation-granted=${results[0] && results[0].pass ? "PASS" : "FAIL"} geolocation-denied=${results[1] && results[1].pass ? "PASS" : "FAIL"}`);
|
||||
if (failed || !allPass) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error("FATAL", e);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -105,6 +105,64 @@ describe("reportHazard (happy path)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("reportHazard (optional best-effort geolocation coords)", () => {
|
||||
it("stores coords on the payload and reads them back correctly via computeHazardReports", async () => {
|
||||
await reportHazard({
|
||||
segmentId: "segment-7",
|
||||
status: "flooded",
|
||||
coords: { latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 },
|
||||
});
|
||||
|
||||
const entries = await readAll();
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].payload).toMatchObject({
|
||||
coords: { latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 },
|
||||
});
|
||||
|
||||
const reports = computeHazardReports(entries);
|
||||
expect(reports).toHaveLength(1);
|
||||
expect(reports[0].coords).toEqual({ latitude: 38.8977, longitude: -77.0365, accuracy: 12.5 });
|
||||
});
|
||||
|
||||
it("works exactly as before with no coords (geolocation denied/unavailable) - no crash, field stays absent", async () => {
|
||||
await reportHazard({ segmentId: "segment-8", status: "blocked" });
|
||||
|
||||
const entries = await readAll();
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].payload).not.toHaveProperty("coords");
|
||||
|
||||
const reports = computeHazardReports(entries);
|
||||
expect(reports).toHaveLength(1);
|
||||
expect(reports[0].coords).toBeUndefined();
|
||||
expect(reports[0]).toMatchObject({ segmentId: "segment-8", status: "blocked", resolved: false });
|
||||
|
||||
// The hazard still closes its segment for routing exactly as before.
|
||||
expect(activeHazardsForSegment(entries, "segment-8")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ignores a tampered/forged coords shape rather than trusting malformed geo data", async () => {
|
||||
const entries = [
|
||||
{
|
||||
id: 1,
|
||||
lamportTs: 0,
|
||||
authorPubkey: new Uint8Array([1]),
|
||||
signature: new Uint8Array([1]),
|
||||
payload: {
|
||||
type: "tunnelsafety.hazard.report",
|
||||
reportId: "h-bad-coords",
|
||||
segmentId: "seg-x",
|
||||
status: "flooded",
|
||||
reportedAt: 0,
|
||||
coords: { latitude: "not-a-number", longitude: -77, accuracy: 10 },
|
||||
},
|
||||
},
|
||||
] as unknown as StoredEventLogEntry[];
|
||||
|
||||
const reports = computeHazardReports(entries);
|
||||
expect(reports).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeSegmentCorroboration (real crowd corroboration by distinct signers)", () => {
|
||||
/** Signs a hazard-report entry with an arbitrary keypair (NOT the local
|
||||
* identity) so a test can forge a second, independent resident the same
|
||||
|
||||
+33
-1
@@ -27,10 +27,24 @@ import { sortForReplay } from "./ledger";
|
||||
export const HAZARD_STATUSES = ["flooded", "blocked"] as const;
|
||||
export type HazardStatus = (typeof HAZARD_STATUSES)[number];
|
||||
|
||||
/** A best-effort device location fix (`navigator.geolocation`), attached to
|
||||
* a hazard report as optional provenance metadata ONLY - it is never
|
||||
* required, never fabricated when unavailable, and never used to resolve
|
||||
* or override the manually-selected `segmentId` (GPS alone cannot tell you
|
||||
* which named corridor you are in, especially underground). */
|
||||
export interface HazardCoords {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
accuracy: number;
|
||||
}
|
||||
|
||||
/** A newly submitted hazard report, before signing/appending. */
|
||||
export interface HazardReportInput {
|
||||
segmentId: string;
|
||||
status: HazardStatus;
|
||||
/** Optional best-effort geolocation fix, present only when the browser
|
||||
* actually supplied one - see `HazardCoords`. */
|
||||
coords?: HazardCoords;
|
||||
}
|
||||
|
||||
export interface HazardReportPayload {
|
||||
@@ -42,6 +56,8 @@ export interface HazardReportPayload {
|
||||
segmentId: string;
|
||||
status: HazardStatus;
|
||||
reportedAt: number;
|
||||
/** Optional best-effort geolocation fix - see `HazardCoords`. */
|
||||
coords?: HazardCoords;
|
||||
}
|
||||
|
||||
export interface HazardResolvePayload {
|
||||
@@ -67,6 +83,9 @@ export interface HazardReport {
|
||||
reporterId: string;
|
||||
resolved: boolean;
|
||||
resolvedAt?: number;
|
||||
/** Optional best-effort geolocation fix carried over from the original
|
||||
* report's payload - see `HazardCoords`. */
|
||||
coords?: HazardCoords;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,6 +124,16 @@ export function validateHazardReportInput(input: HazardReportInput): void {
|
||||
}
|
||||
}
|
||||
|
||||
function isHazardCoords(value: unknown): value is HazardCoords {
|
||||
if (typeof value !== "object" || value === null) return false;
|
||||
const c = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof c.latitude === "number" &&
|
||||
typeof c.longitude === "number" &&
|
||||
typeof c.accuracy === "number"
|
||||
);
|
||||
}
|
||||
|
||||
function isHazardReportPayload(
|
||||
payload: unknown,
|
||||
): payload is HazardReportPayload {
|
||||
@@ -116,7 +145,8 @@ function isHazardReportPayload(
|
||||
typeof p.segmentId === "string" &&
|
||||
p.segmentId.trim().length > 0 &&
|
||||
isHazardStatus(p.status) &&
|
||||
typeof p.reportedAt === "number"
|
||||
typeof p.reportedAt === "number" &&
|
||||
(p.coords === undefined || isHazardCoords(p.coords))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -154,6 +184,7 @@ export async function reportHazard(
|
||||
segmentId: input.segmentId,
|
||||
status: input.status,
|
||||
reportedAt: Date.now(),
|
||||
...(input.coords ? { coords: input.coords } : {}),
|
||||
};
|
||||
return append(payload);
|
||||
}
|
||||
@@ -199,6 +230,7 @@ export function computeHazardReports(
|
||||
reportedAt: entry.payload.reportedAt,
|
||||
reporterId: toHex(entry.authorPubkey),
|
||||
resolved: false,
|
||||
...(entry.payload.coords ? { coords: entry.payload.coords } : {}),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -98,6 +98,12 @@ export function HazardFeed({ reports, corroborationBySegment }: HazardFeedProps)
|
||||
Reported by {report.reporterId.slice(0, 8)} at{" "}
|
||||
{new Date(report.reportedAt).toLocaleTimeString()}
|
||||
</div>
|
||||
{report.coords && (
|
||||
<div className={styles.meta} data-testid={`tunnel-safety-hazard-${report.id}-coords`}>
|
||||
Location: {report.coords.latitude.toFixed(4)}, {report.coords.longitude.toFixed(4)}{" "}
|
||||
(±{Math.round(report.coords.accuracy)}m)
|
||||
</div>
|
||||
)}
|
||||
{!report.resolved && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -52,3 +52,9 @@
|
||||
color: var(--color-ink-faint);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.locationStatus {
|
||||
font-size: 0.7rem;
|
||||
color: var(--color-ink-faint);
|
||||
margin: 0;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
// @vitest-environment happy-dom
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { db } from "../../lib/db.ts";
|
||||
import { init } from "../../lib/identity.ts";
|
||||
import { readAll } from "../../lib/eventlog.ts";
|
||||
import type { HazardReportPayload } from "../../lib/tunnelsafety.ts";
|
||||
import { ReportHazardForm } from "./ReportHazardForm.tsx";
|
||||
|
||||
/** Installs a fake `navigator.geolocation` whose `getCurrentPosition`
|
||||
* resolves (or rejects) exactly like a real browser would, so the
|
||||
* component is exercised against a realistic async geolocation API rather
|
||||
* than a hand-rolled stub of the hook's return value. */
|
||||
function stubGeolocation(
|
||||
outcome:
|
||||
| { kind: "success"; coords: { latitude: number; longitude: number; accuracy: number } }
|
||||
| { kind: "error"; code: number; message: string },
|
||||
) {
|
||||
const getCurrentPosition = vi.fn(
|
||||
(
|
||||
success: PositionCallback,
|
||||
error?: PositionErrorCallback | null,
|
||||
) => {
|
||||
if (outcome.kind === "success") {
|
||||
success({
|
||||
coords: {
|
||||
latitude: outcome.coords.latitude,
|
||||
longitude: outcome.coords.longitude,
|
||||
accuracy: outcome.coords.accuracy,
|
||||
altitude: null,
|
||||
altitudeAccuracy: null,
|
||||
heading: null,
|
||||
speed: null,
|
||||
toJSON() {
|
||||
return this;
|
||||
},
|
||||
} as GeolocationCoordinates,
|
||||
timestamp: Date.now(),
|
||||
toJSON() {
|
||||
return this;
|
||||
},
|
||||
} as GeolocationPosition);
|
||||
return;
|
||||
}
|
||||
error?.({
|
||||
code: outcome.code,
|
||||
message: outcome.message,
|
||||
PERMISSION_DENIED: 1,
|
||||
POSITION_UNAVAILABLE: 2,
|
||||
TIMEOUT: 3,
|
||||
} as GeolocationPositionError);
|
||||
},
|
||||
);
|
||||
vi.stubGlobal("navigator", {
|
||||
...navigator,
|
||||
geolocation: { getCurrentPosition, watchPosition: vi.fn(), clearWatch: vi.fn() },
|
||||
});
|
||||
return getCurrentPosition;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
indexedDB.deleteDatabase(db.name);
|
||||
db.close();
|
||||
await db.open();
|
||||
await init();
|
||||
});
|
||||
|
||||
describe("ReportHazardForm (best-effort geolocation)", () => {
|
||||
it("captures a real GPS fix and submits it as optional coords on the hazard report", async () => {
|
||||
stubGeolocation({
|
||||
kind: "success",
|
||||
coords: { latitude: 40.7128, longitude: -74.006, accuracy: 15 },
|
||||
});
|
||||
|
||||
render(<ReportHazardForm />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-location-status")).toHaveTextContent(
|
||||
"Location captured (40.7128, -74.0060, \u00b115m)",
|
||||
);
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByTestId("tunnel-safety-report-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-status-text")).toHaveTextContent(
|
||||
"Hazard reported.",
|
||||
);
|
||||
});
|
||||
|
||||
const entries = await readAll();
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].payload).toMatchObject({
|
||||
coords: { latitude: 40.7128, longitude: -74.006, accuracy: 15 },
|
||||
} satisfies Partial<HazardReportPayload>);
|
||||
});
|
||||
|
||||
it("falls back to manual-only reporting when geolocation permission is denied - no crash, no coords required", async () => {
|
||||
stubGeolocation({ kind: "error", code: 1, message: "User denied Geolocation" });
|
||||
|
||||
render(<ReportHazardForm />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-location-status")).toHaveTextContent(
|
||||
"Location unavailable - segment selection above is used instead.",
|
||||
);
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByTestId("tunnel-safety-report-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-status-text")).toHaveTextContent(
|
||||
"Hazard reported.",
|
||||
);
|
||||
});
|
||||
|
||||
const entries = await readAll();
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].payload).not.toHaveProperty("coords");
|
||||
});
|
||||
|
||||
it("falls back gracefully when the browser has no geolocation API at all", async () => {
|
||||
vi.stubGlobal("navigator", { ...navigator, geolocation: undefined });
|
||||
|
||||
render(<ReportHazardForm />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-location-status")).toHaveTextContent(
|
||||
"Location unavailable - segment selection above is used instead.",
|
||||
);
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByTestId("tunnel-safety-report-submit"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId("tunnel-safety-report-status-text")).toHaveTextContent(
|
||||
"Hazard reported.",
|
||||
);
|
||||
});
|
||||
|
||||
const entries = await readAll();
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0].payload).not.toHaveProperty("coords");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import {
|
||||
HAZARD_STATUSES,
|
||||
InvalidHazardReportError,
|
||||
@@ -11,18 +11,71 @@ import styles from "./ReportHazardForm.module.css";
|
||||
|
||||
type SubmitStatus = "idle" | "submitting" | "submitted" | "error";
|
||||
|
||||
type GeolocationAvailability = "pending" | "captured" | "unavailable";
|
||||
|
||||
interface BestEffortGeolocation {
|
||||
coords: GeolocationCoordinates | undefined;
|
||||
availability: GeolocationAvailability;
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort device location fix, read once per form mount. Never blocks
|
||||
* submit: a resident can submit a report before (or without) the browser
|
||||
* ever resolving a fix. Permission denial, no API support, or a timeout
|
||||
* all fall back to `availability: "unavailable"` - honest, never a
|
||||
* fabricated coordinate - and the existing manual segment picker remains
|
||||
* the sole authoritative location signal either way.
|
||||
*/
|
||||
function useBestEffortGeolocation(): BestEffortGeolocation {
|
||||
const [state, setState] = useState<BestEffortGeolocation>({
|
||||
coords: undefined,
|
||||
availability: "pending",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const geolocation = navigator.geolocation;
|
||||
if (!geolocation) {
|
||||
setState({ coords: undefined, availability: "unavailable" });
|
||||
return;
|
||||
}
|
||||
geolocation.getCurrentPosition(
|
||||
(position) => setState({ coords: position.coords, availability: "captured" }),
|
||||
() => setState({ coords: undefined, availability: "unavailable" }),
|
||||
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 60_000 },
|
||||
);
|
||||
}, []);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
export function ReportHazardForm() {
|
||||
const [segmentId, setSegmentId] = useState(TUNNEL_GRAPH.segments[0].id);
|
||||
const [status, setStatus] = useState<HazardStatus>(HAZARD_STATUSES[0]);
|
||||
const [submitStatus, setSubmitStatus] = useState<SubmitStatus>("idle");
|
||||
const [errorMessage, setErrorMessage] = useState<string>();
|
||||
const { coords, availability } = useBestEffortGeolocation();
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setSubmitStatus("submitting");
|
||||
setErrorMessage(undefined);
|
||||
try {
|
||||
await reportHazard({ segmentId, status });
|
||||
await reportHazard({
|
||||
segmentId,
|
||||
status,
|
||||
// Optional provenance metadata only - segment selection above stays
|
||||
// the sole authoritative location signal; omitted entirely whenever
|
||||
// the browser never supplied a real fix.
|
||||
...(coords
|
||||
? {
|
||||
coords: {
|
||||
latitude: coords.latitude,
|
||||
longitude: coords.longitude,
|
||||
accuracy: coords.accuracy,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
// Best-effort cross-device sync (plan todo 3): fire-and-forget, never
|
||||
// blocks or affects the local-first write that just completed above.
|
||||
void trySyncWithBackend();
|
||||
@@ -75,6 +128,15 @@ export function ReportHazardForm() {
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<p className={styles.locationStatus} data-testid="tunnel-safety-report-location-status">
|
||||
{availability === "pending" && "Locating..."}
|
||||
{availability === "captured" &&
|
||||
coords &&
|
||||
`Location captured (${coords.latitude.toFixed(4)}, ${coords.longitude.toFixed(4)}, \u00b1${Math.round(coords.accuracy)}m)`}
|
||||
{availability === "unavailable" &&
|
||||
"Location unavailable - segment selection above is used instead."}
|
||||
</p>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className={styles.submit}
|
||||
|
||||
Reference in new issue
Block a user