Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 83 additions & 12 deletions apps/rustgis-web/smoke/run.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Browser smoke test for the web app: starts a `trunk build` in headless Chrome, offline, and
// works it from the keyboard as a user would. Add Data from Command Search, a command, Undo and
// Redo, Save (a download), then a fresh page that opens the saved file and saves it again. It
// fails on any page error, console error or panic, and on a saved project that doesn't hold what
// was done. CI compiles the browser build; this runs it, where a clock or blocking call that only
// drives the app as a user would. Add Data from Command Search, Move Down, Undo and Redo, Save,
// then a fresh page that opens the saved file and saves it again. Open Script from Command Search,
// paste and run a script that edits the table, exports it as CSV, then exports the map as PNG.
// Check the downloaded rows and image pixels.
// It fails on any page error, console error or panic, and on files that don't reflect what was done.
// CI compiles the browser build; this runs it, where a clock or blocking call that only
// fails at run time shows (AGENTS.md › Never break wasm).
//
// cd apps/rustgis-web && trunk build --release && cargo xtask web-pwa ../../dist/web
Expand All @@ -12,7 +14,7 @@
//
// No packages: Node's standard library, and Chrome driven through its DevTools protocol on a pipe.
// The app's interface is drawn on a canvas, so the test uses only what doesn't move when the
// interface is rearranged: shortcuts, Command Search by name, the browser's file chooser and
// interface is rearranged: shortcuts, Command Search by name, paste, the browser's file chooser and
// downloads. Nothing waits a fixed time; each step waits for the event it causes, and the project
// state is read from saved copies.

Expand Down Expand Up @@ -242,9 +244,13 @@ const onCanvas = (what) => until(`document.activeElement?.id === "rustgis_canvas
// frame or on a focus event it can miss while busy (starting up), so an idle app can drop the
// next key. Moving the pointer over the map makes it draw, and so check, first.
let nudges = 0;
const shortcut = async (key, what) => {
await onCanvas(what);
await send("Input.dispatchMouseEvent", { type: "mouseMoved", x: 800 + (nudges++ % 2), y: 450 }, session);
const shortcut = async (key, what, ready = onCanvas) => {
await ready(what);
const { x, y } = await js(`(() => {
const bounds = document.getElementById("rustgis_canvas").getBoundingClientRect();
return { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };
})()`);
await send("Input.dispatchMouseEvent", { type: "mouseMoved", x: x + (nudges++ % 2), y }, session);
await frames();
await press(key, true);
};
Expand Down Expand Up @@ -318,6 +324,13 @@ const finished = new Set();
listeners.add(({ method, params }) => {
if (method === "Browser.downloadProgress" && params.state === "completed") finished.add(params.guid);
});
const download = async (begun, what) => {
const { guid, suggestedFilename } = await begun;
if (!finished.has(guid)) {
await event("Browser.downloadProgress", `completed download of ${what}`, (p) => p.guid === guid && p.state === "completed");
}
return { bytes: readFileSync(join(downloads, guid)), suggestedFilename };
};
// Saves the project and returns the downloaded file. Ctrl+S asks for a file name the first time
// (Save As, whose name box takes Enter); a project with a name downloads straight away.
let saves = 0;
Expand All @@ -335,11 +348,10 @@ const save = async () => {
if (crashed || Date.now() > deadline) break;
await frames();
}
const { guid, suggestedFilename } = await begun;
if (!finished.has(guid)) await event("Browser.downloadProgress", "finished download", (p) => p.guid === guid && p.state === "completed");
const { bytes, suggestedFilename } = await download(begun, "the saved project");
const file = join(downloads, `save-${++saves}-${suggestedFilename.replace(/[^\w.-]/g, "_")}`);
writeFileSync(file, readFileSync(join(downloads, guid)));
return { file, project: JSON.parse(readFileSync(file, "utf8")) };
writeFileSync(file, bytes);
return { file, project: JSON.parse(bytes.toString("utf8")) };
};
// Saves until the project passes `ready`: the app reads files and runs work between frames, so a
// save shows when it has landed. Fails after the limit, saying what the last save held.
Expand All @@ -355,6 +367,40 @@ const saveUntil = async (what, ready) => {
const layerNames = (p) => JSON.stringify((p.maps?.[0]?.layers ?? []).map((l) => l.name));
const value = (cell) => (cell && typeof cell === "object" ? Object.values(cell)[0] : cell);

const checkCsv = (bytes) => {
// The fixture only has plain cells: no commas, quotes or newlines within a cell.
const [header, ...rows] = bytes.toString("utf8").replace(/\r?\n$/, "").split(/\r?\n/);
if (header !== "parcel_id,value_usd") throw new Error(`CSV header: expected parcel_id,value_usd, got ${JSON.stringify(header)}`);
if (rows.length !== 3) throw new Error(`CSV row count: expected 3, got ${rows.length}`);
const edited = rows.map((row) => row.split(",")).find(([id]) => id === "00101");
if (edited?.[1] !== "100500") throw new Error(`CSV parcel 00101: expected edited value 100500, got ${edited?.[1] ?? "no row"}`);
step(`CSV: ${rows.length} rows, parcel 00101 = ${edited[1]}`);
};

const checkPng = async (bytes, width, height) => {
if (!bytes.subarray(0, 8).equals(Buffer.from("89504e470d0a1a0a", "hex"))) throw new Error("PNG signature is missing");
// Let Chrome decode the downloaded bytes so this check does not need a PNG library.
const image = await js(`(async () => {
const bytes = Uint8Array.from(atob("${bytes.toString("base64")}"), (c) => c.charCodeAt(0));
const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" }));
const { width, height } = bitmap;
if (width !== ${width} || height !== ${height}) {
bitmap.close();
return { width, height };
}
const ctx = new OffscreenCanvas(width, height).getContext("2d");
ctx.drawImage(bitmap, 0, 0);
bitmap.close();
const pixels = new Uint32Array(ctx.getImageData(0, 0, width, height).data.buffer);
return { width, height, varied: pixels.some((pixel) => pixel !== pixels[0]) };
})()`).catch(() => { throw new Error("PNG download could not be decoded"); });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .catch turns every failure of the decode script into "PNG download could not be decoded", including a page error or a Chrome stop that the js helper reports. That hides the cause in the failure message, which is what this smoke test exists to report. Keep the original error, or add it to the message:

Suggested change
})()`).catch(() => { throw new Error("PNG download could not be decoded"); });
})()`).catch((e) => { throw new Error(`PNG download could not be decoded: ${e.message}`); });

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

if (image.width !== width || image.height !== height) {
throw new Error(`PNG dimensions: expected ${width}×${height}, got ${image.width}×${image.height}`);
}
if (!image.varied) throw new Error("PNG is one flat colour");
step(`PNG: ${width}×${height}, ${bytes.length} bytes, more than one colour`);
};

try {
await send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: downloads, eventsEnabled: true });
const { targetId } = await send("Target.createTarget", { url: "about:blank" });
Expand Down Expand Up @@ -409,6 +455,31 @@ try {
const data = (p) => JSON.stringify([p.maps.map((m) => m.layers.map((l) => [l.name, l.dataset])), p.tables]);
if (data(again.project) !== data(redone.project)) failures.push("the reopened project's layers or tables differ from the saved ones");
step(`${saves} saves; layers ${order(again.project)}`);

step("Script: edit assessments, then export the table to CSV and the map to PNG");
const [csv, png] = ["edited-assessments.csv", "parcels-map.png"];
const [width, height] = [320, 240];
const script = [
'edit.calculateField {"table":"assessments","field":"value_usd","expression":"value_usd + 500"}',
`share.exportTable ${JSON.stringify({ table: "assessments", path: csv })}`,
"map.zoomFull {}",
`share.exportMap ${JSON.stringify({ path: png, width, height })}`,
].join("\n");
await search("Script");
await typing("the Script editor after Command Search");
// Pass a paste to eframe without reading or changing the host clipboard.
await js(`(() => {
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", ${JSON.stringify(script)});
document.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low-confidence robustness note on the synthetic paste. new ClipboardEvent("paste", …) is created without bubbles: true, so it only reaches listeners on document itself. If eframe's paste handler is attached to window or to the hidden text input, the paste never arrives and the script never runs. The run is still fail-loud (the CSV wait times out), and the author reports ten passing runs, so this may already work. Adding bubbles: true (and dispatching on the focused element if eframe listens there) would remove the dependence on where the listener sits.

Suggested change
document.dispatchEvent(new ClipboardEvent("paste", { clipboardData, cancelable: true }));
document.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));

Category: quality

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left for the release quality pass.

return true;
})()`);
const begun = (name) => event("Browser.downloadWillBegin", `script download of ${name}`, (p) => p.suggestedFilename === name);
const csvStarted = begun(csv);
const pngStarted = begun(png);
await shortcut("Enter", "the pasted script", typing);
checkCsv((await download(csvStarted, csv)).bytes);
await checkPng((await download(pngStarted, png)).bytes, width, height);
} catch (e) {
failures.push(e.message);
if (shot && !closed) {
Expand Down
6 changes: 6 additions & 0 deletions crates/ui-egui/src/analysispane.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ pub struct Workflow {
#[cfg(not(target_arch = "wasm32"))]
similar_next: u64,
pub script: String,
/// Focus the editor when the Script pane next draws, after Command Search closes.
pub(crate) script_focus_requested: bool,
pub script_out: Vec<(String, bool)>,
/// The Script pane's last run, shown above its results.
pub script_last: Option<ScriptRun>,
Expand Down Expand Up @@ -2535,6 +2537,10 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) {
}
out
});
if std::mem::take(&mut app.workflow.script_focus_requested) {
out.inner.response.request_focus();
ui.ctx().request_repaint();
}
// The same for its error's click (see the mark's paint above).
let stopped = stopped.filter(|_| !out.inner.response.changed());
let clicked = crate::scriptcomplete::show(ui, box_id, &out.inner, out.inner_rect, &app.workflow.script, &app.session);
Expand Down
26 changes: 26 additions & 0 deletions crates/ui-egui/src/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,7 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[
("ui.pane.diagnosticLog", "Messages", "View › Windows"),
("ui.pane.assistant", "AI Assistant", "Analyze › AI"),
("ui.pane.sql", "SQL Pane", "Analyze › Workflows"),
("ui.pane.script", "Script", "Analyze › Geoprocessing"),
("ui.pane.directions", "Directions", "Home › Navigate"),
("ui.pane.bookmarks", "Bookmarks Pane", "Home › Navigate › Bookmarks"),
("ui.theme", "Toggle Dark Mode", "Settings › Theme"),
Expand Down Expand Up @@ -2103,6 +2104,9 @@ pub fn command_search(app: &mut RustGisApp, ctx: &egui::Context) {
};
} else {
let _ = app.run_by_user(&id, Value::Null);
if id == "ui.pane.script" && app.ui.right == Some(crate::RightPane::Script) {
app.workflow.script_focus_requested = true;
}
}
}
ctx.with_plugin::<CommandSearchEscape, _>(|input| input.open = keep);
Expand Down Expand Up @@ -2431,6 +2435,28 @@ mod tests {
}
}

#[test]
fn command_search_opens_and_focuses_the_script_pane() {
use crate::RightPane;

let mut app = RustGisApp::with_sample();
app.ui.command_search = Some("Script".into());
let mut h = egui_kittest::Harness::builder().with_size(vec2(800.0, 600.0)).build_ui_state(
|ui, app: &mut RustGisApp| {
if app.ui.right == Some(RightPane::Script) {
crate::analysispane::script_pane(app, ui, &Tokens::light());
}
command_search(app, ui.ctx());
},
app,
);
h.run();
h.key_press(Key::Enter);
h.run_steps(2);
assert_eq!(h.state().ui.right, Some(RightPane::Script));
assert!(h.ctx.memory(|m| m.has_focus(egui::Id::unique("script_text"))));
}

/// Command Search closed with a row picked and opened again on the next pass starts from the
/// first row: Enter runs it, not the row picked before.
#[test]
Expand Down
Loading