From d8980e4f6d9f85d08ef2ec45bf484534c8f7909d Mon Sep 17 00:00:00 2001 From: Gr-linkk <280405187+Gr-linkk@users.noreply.github.com> Date: Fri, 30 Oct 2026 12:48:04 -0700 Subject: [PATCH] omamobile-shell 0.2.45: bound widget reads and stop stale work An expanded OWL screen could keep sources and every triggers running while home was paused. Source completions could also update a replacement instance, and unchanged source values scheduled state writes on every refresh. A busy stream could postpone the restarted save timer forever. Honor the global pause, cancel pending source reads, and bind callbacks to their instance and subscription. Save only changed persisted data with a fixed coalescing interval, flushing pending state before reload. Share bounded command collection between OWL and QML widgets. Discard output beyond 64 KiB per pipe while allowing commands to finish, preserve split UTF-8, and abort HTTP responses as received bytes exceed 1 MiB. Verified with failing-before/passing-after lifecycle tests and real offscreen Qt/Quickshell command and HTTP fixtures. tests/packages omamobile-shell passes. No phone smoke or battery measurement yet. Assisted-by: Codex --- .../plugins/omamobile.home/BoundedProcess.qml | 53 +++++++ .../plugins/omamobile.home/OwlCell.qml | 1 + .../plugins/omamobile.home/OwlPhoneHost.qml | 57 ++++---- .../plugins/omamobile.home/WidgetHost.qml | 20 +-- .../plugins/omamobile.home/owl/OwlWidget.qml | 70 +++++++--- packages/omamobile-shell/test/all | 8 ++ packages/omamobile-shell/test/owl-idle | 3 +- packages/omamobile-shell/test/owl-idle.qml | 10 ++ .../omamobile-shell/test/owl-lifecycle.qml | 129 ++++++++++++++++++ packages/omamobile-shell/test/widget-host.py | 78 +++++++++++ packages/omamobile-shell/test/widget-host.qml | 90 ++++++++++++ packages/omamobile-shell/version | 2 +- 12 files changed, 460 insertions(+), 61 deletions(-) create mode 100644 packages/omamobile-shell/plugins/omamobile.home/BoundedProcess.qml create mode 100644 packages/omamobile-shell/test/owl-lifecycle.qml create mode 100644 packages/omamobile-shell/test/widget-host.py create mode 100644 packages/omamobile-shell/test/widget-host.qml diff --git a/packages/omamobile-shell/plugins/omamobile.home/BoundedProcess.qml b/packages/omamobile-shell/plugins/omamobile.home/BoundedProcess.qml new file mode 100644 index 000000000..bcc59ac42 --- /dev/null +++ b/packages/omamobile-shell/plugins/omamobile.home/BoundedProcess.qml @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: MIT +import QtQuick +import Quickshell.Io + +// Both widget formats share the same command-output bound. Once a pipe +// reaches 64 KiB, detaching its collector makes QProcess discard further +// output without interrupting the command. Collect raw bytes until then: +// decoding arbitrary SplitParser chunks would corrupt split UTF-8. +Process { + id: proc + property var done: null + property string out: "" + property string err: "" + + stdout: StdioCollector { + id: stdoutCollector + waitForEnd: false + onDataChanged: if (data.byteLength >= 65536) { proc.out = proc.prefix(text); proc.stdout = null } + } + stderr: StdioCollector { + id: stderrCollector + waitForEnd: false + onDataChanged: if (data.byteLength >= 65536) { proc.err = proc.prefix(text); proc.stderr = null } + } + + // Trim on a character boundary, counting UTF-8 bytes, not UTF-16 units. + function prefix(text) { + let end = 0, remaining = 65536 + while (end < text.length) { + const point = text.codePointAt(end) + const bytes = point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4 + if (bytes > remaining) break + remaining -= bytes + end += point > 0xffff ? 2 : 1 + } + return text.slice(0, end) + } + + function stop() { + proc.done = null + // GNU timeout forwards TERM to the command's process group, with its + // existing -k grace period. Keep the Process alive until it exits. + proc.running = false + } + onExited: function(code) { + const finish = proc.done + proc.done = null + if (proc.stdout) proc.out = proc.prefix(stdoutCollector.text) + if (proc.stderr) proc.err = proc.prefix(stderrCollector.text) + if (finish) finish(code, proc.out, proc.err) + proc.destroy() + } +} diff --git a/packages/omamobile-shell/plugins/omamobile.home/OwlCell.qml b/packages/omamobile-shell/plugins/omamobile.home/OwlCell.qml index 43aef7710..3613bf0e9 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/OwlCell.qml +++ b/packages/omamobile-shell/plugins/omamobile.home/OwlCell.qml @@ -44,6 +44,7 @@ Item { themeColors: owlCell.home ? owlCell.home.owlPalette : ({}) approval: owlCell.card.approval active: owlCell.running && owlCell.shown && !!owlCell.home && !!owlCell.entry + paused: !owlCell.home || owlCell.home.owlPaused // While its screen is open, the screen's size is the view's own. tileVars: Phone.tileVars(owlCell.width, owlCell.height, owlCell.dp, owl.screenOpen ? view.width : owlCell.home ? owlCell.home.owlScreenWidth : owlCell.width, diff --git a/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml b/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml index 1b241627b..92fa6619f 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml +++ b/packages/omamobile-shell/plugins/omamobile.home/OwlPhoneHost.qml @@ -46,14 +46,12 @@ QtObject { function runSource(widget, spec, arg, headers, done) { if (spec.kind === "http") { if (!host.networkAllowed(widget)) { done({ error: "the internet is off for this widget" }); return } - host.get(arg, headers, Phone.sourceLimits(spec, false).timeout, spec, done) - return + return host.get(arg, headers, Phone.sourceLimits(spec, false).timeout, spec, done) } if (spec.kind === "file") { host.readFile(arg, done); return } if (spec.kind === "cmd") { if (host.usesNetwork(arg) && !host.networkAllowed(widget)) { done({ error: "the internet is off for this widget" }); return } - host.command(widget, arg, Phone.sourceLimits(spec, false).timeout, done) - return + return host.command(widget, arg, Phone.sourceLimits(spec, false).timeout, done) } done({ error: "unknown source " + spec.kind }) } @@ -63,35 +61,52 @@ QtObject { command: ["timeout", "-k", "2", String(Math.max(1, Math.min(Phone.LIMITS.timeoutMax, seconds))), "bash", "-c", String(text)] }) proc.done = function(code, out, err) { - done({ code: code, ok: code === 0, out: out.slice(0, Phone.LIMITS.cmdOutput), err: err.slice(0, Phone.LIMITS.cmdOutput) }) + done({ code: code, ok: code === 0, out: out, err: err }) } proc.running = true + return { stop: function() { proc.stop() } } } function get(url, headers, seconds, spec, done) { const xhr = new XMLHttpRequest() let finished = false const timer = timerComponent.createObject(host, { interval: seconds * 1000 }) - timer.triggered.connect(function() { + const stop = function() { if (finished) return finished = true + timer.stop() xhr.abort() timer.destroy() + } + timer.triggered.connect(function() { + if (finished) return + stop() done(spec.status ? { code: 124, ok: false, out: "", err: "timed out" } : { error: "timed out" }) }) xhr.onreadystatechange = function() { - if (xhr.readyState !== XMLHttpRequest.DONE || finished) return + if (finished || xhr.readyState < XMLHttpRequest.LOADING) return + // Qt emits LOADING on each received chunk. Check raw bytes there, + // before a chunked or compressed reply can grow without a bound. + if (xhr.response.byteLength > Phone.LIMITS.bodyBytes) { + stop() + done({ error: "the answer is over 1 MB" }) + return + } + if (xhr.readyState !== XMLHttpRequest.DONE) return finished = true + timer.stop() timer.destroy() const body = String(xhr.responseText || "") - if (body.length > Phone.LIMITS.bodyBytes) { done({ error: "the answer is over 1 MB" }); return } const ok = xhr.status >= 200 && xhr.status < 300 done({ code: xhr.status, ok: ok, out: body, err: ok ? "" : "HTTP " + xhr.status }) } xhr.open("GET", url) + // Qt still supplies responseText for decoding at DONE. + xhr.responseType = "arraybuffer" for (const name in headers) xhr.setRequestHeader(name, String(headers[name])) timer.start() xhr.send() + return { stop: stop } } function readFile(path, done) { @@ -145,19 +160,18 @@ QtObject { // and mako's modes, system from /proc and df. function android(widget, kind, done) { const fromCommand = function(text, parse) { - host.command(widget, text, 5, function(r) { done({ value: parse(String(r.out || "")) }) }) + return host.command(widget, text, 5, function(r) { done({ value: parse(String(r.out || "")) }) }) } - if (kind === "volume") { fromCommand("wpctl get-volume @DEFAULT_AUDIO_SINK@", Phone.volumeFrom); return } - if (kind === "media") { fromCommand("playerctl metadata --format " + JSON.stringify(Phone.MEDIA_FORMAT) + " 2>/dev/null", Phone.mediaFrom); return } - if (kind === "modes") { fromCommand("brightnessctl --device=white:torch get 2>/dev/null || echo; makoctl mode 2>/dev/null", Phone.modesFrom); return } + if (kind === "volume") return fromCommand("wpctl get-volume @DEFAULT_AUDIO_SINK@", Phone.volumeFrom) + if (kind === "media") return fromCommand("playerctl metadata --format " + JSON.stringify(Phone.MEDIA_FORMAT) + " 2>/dev/null", Phone.mediaFrom) + if (kind === "modes") return fromCommand("brightnessctl --device=white:torch get 2>/dev/null || echo; makoctl mode 2>/dev/null", Phone.modesFrom) if (kind === "system") { - fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1", function(t) { + return fromCommand("cat /proc/meminfo; echo '@@'; cat /proc/uptime; echo '@@'; uname -r; echo '@@'; df -B1 --output=size,used / | tail -1", function(t) { const parts = t.split("@@\n") return Phone.systemFrom(parts[0], parts[1], parts[2], parts[3]) }) - return } - if (kind === "battery") { fromCommand(Phone.BATTERY_COMMAND, Phone.batteryFrom); return } + if (kind === "battery") return fromCommand(Phone.BATTERY_COMMAND, Phone.batteryFrom) if (kind === "alarm") { done({ value: { set: false, time: null, app: null } }); return } if (kind === "notifications") { done({ value: { available: false, count: 0, items: [] } }); return } if (kind === "device") { done({ value: { model: "Pixel 7 Pro", maker: "Google", android: null, sdk: null, soc: "gs201" } }); return } @@ -267,18 +281,7 @@ QtObject { // ---------------------------------------------------------------- parts property Component processComponent: Component { - Process { - id: proc - property var done: null - stdout: StdioCollector { id: out; waitForEnd: true } - stderr: StdioCollector { id: err; waitForEnd: true } - onExited: function(code) { - const finish = proc.done - proc.done = null - if (finish) finish(code, String(out.text || ""), String(err.text || "")) - proc.destroy() - } - } + BoundedProcess { } } property Component timerComponent: Component { Timer { } } diff --git a/packages/omamobile-shell/plugins/omamobile.home/WidgetHost.qml b/packages/omamobile-shell/plugins/omamobile.home/WidgetHost.qml index 334aebf3a..aaa3bad2b 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/WidgetHost.qml +++ b/packages/omamobile-shell/plugins/omamobile.home/WidgetHost.qml @@ -63,10 +63,10 @@ QtObject { var seconds = UserWidgets.runTimeout(options) lastStart = Date.now() var proc = processComponent.createObject(host, { command: UserWidgets.timeoutArgv(argv, seconds) }) - proc.done = function(result) { + proc.done = function(code, out, err) { host.running = null if (typeof callback === "function") { - try { callback(result) } catch (e) { console.warn("omamobile.home: widget " + host.widgetId + ": " + e) } + try { callback(UserWidgets.runResult(code, out, err)) } catch (e) { console.warn("omamobile.home: widget " + host.widgetId + ": " + e) } } } running = proc @@ -102,23 +102,11 @@ QtObject { } property Component processComponent: Component { - Process { - id: proc - property var done: null - stdout: StdioCollector { id: out; waitForEnd: true } - stderr: StdioCollector { id: err; waitForEnd: true } - onExited: function(code) { - var result = UserWidgets.runResult(code, out.text, err.text) - var finish = proc.done - proc.done = null - if (finish) finish(result) - proc.destroy() - } - } + BoundedProcess { } } // A widget that goes away takes its command with it. Component.onDestruction: { - if (running) { running.done = null; running.running = false } + if (running) running.stop() } } diff --git a/packages/omamobile-shell/plugins/omamobile.home/owl/OwlWidget.qml b/packages/omamobile-shell/plugins/omamobile.home/owl/OwlWidget.qml index 8c68415c4..1292d1d9d 100644 --- a/packages/omamobile-shell/plugins/omamobile.home/owl/OwlWidget.qml +++ b/packages/omamobile-shell/plugins/omamobile.home/owl/OwlWidget.qml @@ -31,6 +31,8 @@ Item { // seen: its page shows (a neighbour too while the pages move) and nothing // covers the home screen. The host sets it. property bool active: false + // Global pause wins even over an expanded widget screen. + property bool paused: false // State to start with when nothing is saved yet: { name: value }. property var seedState: ({}) // The approval this widget runs under ({ commands, network }), for the host. @@ -56,6 +58,8 @@ Item { Component.onCompleted: Qt.callLater(widget.load) function load() { + widget.saveNow() + widget.stopSources() widget.stopLive() widget.screenOpen = false widget.screenTree = null @@ -74,9 +78,12 @@ Item { return } const saved = Object.assign({}, widget.seedState || {}, widget.host && widget.stateKey ? widget.host.loadState(widget.stateKey) || {} : {}) - widget.instance = new Runtime.Instance(widget.program, widget.bridge, saved) + const next = new Runtime.Instance(widget.program, widget.bridge, saved) + widget.lastSaved = JSON.stringify(next.persisted()) + // Publishing the instance lets OwlCell seed location/state immediately. + widget.instance = next widget.render() - if (widget.active) { widget.refresh(); widget.startLive() } + if (widget.live) { widget.refresh(); widget.startLive() } } // What the instance calls back into. @@ -88,7 +95,8 @@ Item { tile: function(name) { return widget.tileVars ? widget.tileVars[name] : null }, act: function(name, args) { widget.act(name, args) }, runInto: function(command, slot) { - if (widget.host) widget.host.runInto(widget, command, function(out) { if (widget.instance) widget.instance.setState(slot, out) }) + const owner = widget.instance + if (widget.host) widget.host.runInto(widget, command, function(out) { if (owner && widget.instance === owner) owner.setState(slot, out) }) }, report: function(message) { widget.report(message) }, changed: function() { widget.changed() }, @@ -98,15 +106,15 @@ Item { onThemeColorsChanged: if (widget.instance) { widget.instance.invalidate(); widget.render() } onTileVarsChanged: if (widget.instance) { widget.instance.invalidate(); widget.render() } // Sources keep running while the screen is open, whatever page shows. - readonly property bool live: widget.active || widget.screenOpen + readonly property bool live: !widget.paused && (widget.active || widget.screenOpen) // Shown again, it catches up once: what fell due while it was hidden runs // now (a source whose period turned over, an `every` that passed), and // nothing else; the frame clock picks up at the current `time`. onLiveChanged: { if (widget.live) { widget.catchUp(); widget.startLive() } - else widget.stopLive() + else { widget.stopSources(); widget.stopLive() } } - Component.onDestruction: { widget.stopLive(); widget.saveNow() } + Component.onDestruction: { widget.stopSources(); widget.stopLive(); widget.saveNow(); widget.instance = null } // ---------------------------------------------------------------- drawing @@ -220,10 +228,13 @@ Item { return } if (!widget.host || widget.running[s.slot]) return - widget.running[s.slot] = true + const owner = widget.instance + const pending = { stop: null } + widget.running[s.slot] = pending const finish = function(result) { - widget.running[s.slot] = false - if (!widget.instance || !result) return + if (widget.instance !== owner || widget.running[s.slot] !== pending) return + delete widget.running[s.slot] + if (!result) return if (result.error) { widget.report(s.name + ": " + result.error); return } if (result.value !== undefined) { widget.instance.setSource(s.slot, V.fromPlain(result.value)); return } if (s.status) { @@ -237,8 +248,19 @@ Item { if (!result.ok && result.err) widget.report(s.name + ": " + String(result.err).split("\n")[0]) widget.instance.setSource(s.slot, String(result.out === undefined ? "" : result.out)) } - if (s.kind.indexOf("android.") === 0) widget.host.android(widget, s.kind.slice(8), finish) - else widget.host.runSource(widget, s, s.arg(), s.headers(), finish) + const handle = s.kind.indexOf("android.") === 0 ? widget.host.android(widget, s.kind.slice(8), finish) + : widget.host.runSource(widget, s, s.arg(), s.headers(), finish) + if (handle) pending.stop = handle.stop + } + + function stopSources() { + const pending = widget.running + widget.running = ({}) + for (const slot in pending) { + // A cancelled read has no value: try again when shown. + delete widget.lastRun[slot] + if (pending[slot].stop) pending[slot].stop() + } } // A state's value by name (undefined: no such state), and setting one as @@ -259,15 +281,20 @@ Item { // `stream(...)` (a line is a value) and `file(...)` (read again when it // changes): started while the widget shows, stopped when it doesn't. property var liveHandles: [] + property int liveGeneration: 0 function startLive() { - if (!widget.instance || !widget.host || widget.liveHandles.length) return + if (!widget.live || !widget.instance || !widget.host || widget.liveHandles.length) return + const owner = widget.instance + const generation = ++widget.liveGeneration const specs = widget.instance.sources() const handles = [] for (let i = 0; i < specs.length; i++) { const s = specs[i] if (s.kind !== "stream" && s.kind !== "file") continue const slot = s.slot - const onValue = function(text) { if (widget.instance) widget.instance.setSource(slot, String(text)) } + const onValue = function(text) { + if (widget.instance === owner && widget.liveGeneration === generation) owner.setSource(slot, String(text)) + } const h = s.kind === "stream" ? widget.host.stream(widget, s, s.arg(), onValue) : widget.host.watch(widget, s, s.arg(), onValue) if (h) handles.push(h) @@ -275,6 +302,7 @@ Item { widget.liveHandles = handles } function stopLive() { + widget.liveGeneration++ const handles = widget.liveHandles widget.liveHandles = [] for (let i = 0; i < handles.length; i++) handles[i].stop() @@ -291,13 +319,23 @@ Item { // ---------------------------------------------------------------- persisted state - function saveSoon() { if (widget.stateKey) saveTimer.restart() } + property string lastSaved: "" + function saveSoon() { + if (widget.instance && widget.stateKey && !saveTimer.running + && JSON.stringify(widget.instance.persisted()) !== widget.lastSaved) saveTimer.start() + } Timer { id: saveTimer interval: 1000 - onTriggered: if (widget.instance && widget.host && widget.stateKey) widget.host.saveState(widget.stateKey, widget.instance.persisted()) + onTriggered: widget.saveNow() } function saveNow() { - if (widget.instance && widget.host && widget.stateKey && saveTimer.running) widget.host.saveState(widget.stateKey, widget.instance.persisted()) + saveTimer.stop() + if (!widget.instance || !widget.host || !widget.stateKey) return + const data = widget.instance.persisted() + const json = JSON.stringify(data) + if (json === widget.lastSaved) return + widget.host.saveState(widget.stateKey, data) + widget.lastSaved = json } } diff --git a/packages/omamobile-shell/test/all b/packages/omamobile-shell/test/all index a15a4a8a6..f7f2275f6 100755 --- a/packages/omamobile-shell/test/all +++ b/packages/omamobile-shell/test/all @@ -411,6 +411,14 @@ elif [[ $rc != 0 ]]; then else pass "home widgets stop when nobody can see them: no sources, every or frames hidden, one catch-up, 20/30 fps, half rate when slow" fi +rc=0; out=$(python3 -B test/widget-host.py 2>&1) || rc=$? +if [[ $rc == 77 ]]; then + pass "widget host output limits # SKIP no Quickshell" +elif [[ $rc != 0 ]]; then + printf '%s\n' "$out" >&2; fail "widget host output limits" +else + pass "widget host output limits, cancellation and state" +fi # The weather widgets' position: locate.sh against a fake where-am-i. bash -n plugins/omamobile.home/locate.sh || fail "locate.sh parses" diff --git a/packages/omamobile-shell/test/owl-idle b/packages/omamobile-shell/test/owl-idle index 1b6b236de..8e3b8049b 100755 --- a/packages/omamobile-shell/test/owl-idle +++ b/packages/omamobile-shell/test/owl-idle @@ -18,6 +18,7 @@ work=$(mktemp -d) trap 'rm -rf "$work"' EXIT cp -r "$plugin/owl" "$work/owl" cp "$here/owl-idle.qml" "$work/tst_owl_idle.qml" +cp "$here/owl-lifecycle.qml" "$work/tst_owl_lifecycle.qml" export QT_QPA_PLATFORM=offscreen QT_QUICK_BACKEND=software QML_DISABLE_DISK_CACHE=1 -exec "$runner" -input "$work/tst_owl_idle.qml" +"$runner" -input "$work" diff --git a/packages/omamobile-shell/test/owl-idle.qml b/packages/omamobile-shell/test/owl-idle.qml index 28645fe56..c895b5600 100644 --- a/packages/omamobile-shell/test/owl-idle.qml +++ b/packages/omamobile-shell/test/owl-idle.qml @@ -42,6 +42,7 @@ Item { text: 'widget "idle" {\n meta { owl: 4 }\n source n = cmd("echo hi") every 2s\n state ticks = 0\n every 1s { ticks = ticks + 1 }\n Text { text: fixed(time, 1) }\n}' host: fixture active: top.shown + paused: scheduler.paused } OwlView { @@ -134,6 +135,15 @@ Item { tryVerify(function() { return !scheduler.framing }, 500, "covered or off: no frames") verify(scheduler.tickInterval > Phone.CLOCK.tickMs + 5, "the tick slows while paused (" + scheduler.tickInterval + " ms)") const frames = top.frames + const runs = fixture.runs + const ticks = top.ticks() + // An expanded screen must not bypass the global pause. + owl.screenOpen = true + fixture.t += 10 + scheduler.tick() + compare(fixture.runs, runs, "no sources while paused, even with a screen open") + compare(top.ticks(), ticks, "no `every` while paused") + owl.screenOpen = false wait(300) compare(top.frames, frames) scheduler.paused = false diff --git a/packages/omamobile-shell/test/owl-lifecycle.qml b/packages/omamobile-shell/test/owl-lifecycle.qml new file mode 100644 index 000000000..cc71bce3c --- /dev/null +++ b/packages/omamobile-shell/test/owl-lifecycle.qml @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: MIT +import QtQuick +import QtTest +import "owl" + +TestCase { + id: test + name: "OwlLifecycle" + when: windowShown + property var widget: null + property var requests: [] + property var writes: [] + property var saved: ({}) + property int cancelled: 0 + property bool setOnLoad: false + + QtObject { + id: fixtureHost + function now() { return 1000 } + function interval(spec) { return spec.every } + function loadState(key) { return test.saved } + function saveState(key, data) { + test.saved = data + test.writes.push(data) + } + function report(widget, message) { console.warn(message) } + function runSource(widget, spec, arg, headers, done) { + test.requests.push(done) + return { stop: function() { test.cancelled++ } } + } + function runInto(widget, command, done) { test.requests.push(done) } + function stream(widget, spec, arg, onValue) { + test.requests.push(onValue) + return { stop: function() { test.cancelled++ } } + } + } + + Component { + id: widgetComponent + OwlWidget { + host: fixtureHost + stateKey: "fixture" + // OwlCell fills the initial location from this signal. + onInstanceChanged: if (test.setOnLoad && instance) setStateValue("count", 7) + } + } + + function init() { + requests = []; writes = []; saved = ({}); cancelled = 0; setOnLoad = false + widget = createTemporaryObject(widgetComponent, test) + verify(widget !== null) + load('source n = cmd("fixture") every 1s\nstate count = 0 persist') + } + function cleanup() { widget.destroy(); widget = null } + function load(body) { + widget.text = 'widget "test" {\n' + body + '\nText { text: "test" }\n}' + wait(0) + verify(widget.instance !== null, widget.error) + } + function answer(callback, value) { callback({ ok: true, code: 0, out: value, err: "" }) } + + function test_reload_discards_old_source_and_action_results() { + widget.active = true + const oldSource = requests[0] + widget.bridge.runInto("fixture", widget.instance.stateSlot("count")) + const oldAction = requests[1] + load('source n = cmd("replacement") every 1s\nstate count = 0 persist') + compare(requests.length, 3, "the replacement starts its own source") + answer(oldSource, "old") + oldAction("old") + compare(widget.stateValue("count"), 0, "an old action cannot update the replacement") + compare(widget.instance.values[0], null, "an old source cannot update the replacement") + widget.tick(1002) + compare(requests.length, 3, "an old completion cannot clear the new request's busy flag") + answer(requests[2], "new") + compare(widget.instance.values[0], "new") + compare(cancelled, 1, "reload cancels the previous source") + } + + function test_source_updates_do_not_write_unchanged_state() { + widget.active = true + answer(requests[0], "one") + widget.tick(1001) + answer(requests[1], "two") + wait(1150) + compare(writes.length, 0, "source values are not persisted") + widget.setStateValue("count", 1) + tryCompare(test, "saved", { count: 1 }, 1600) + compare(writes.length, 1) + widget.setStateValue("count", 1) + wait(1150) + compare(writes.length, 1, "setting the same persisted value does not write again") + } + + function test_frequent_history_updates_cannot_postpone_saving_forever() { + load('source n = stream("fixture")\nlet samples = history(n, 3) persist') + widget.active = true + for (let i = 0; i < 7; i++) { requests[0](String(i)); wait(200) } + verify(writes.length > 0, "a busy stream saves within the interval") + widget.saveNow() + compare(saved.samples, ["4", "5", "6"], "persisted history keeps the newest samples") + } + + function test_reload_flushes_pending_state() { + widget.setStateValue("count", 8) + load('state count = 0 persist') + compare(widget.stateValue("count"), 8) + compare(writes.length, 1) + } + + function test_state_set_by_the_host_on_load_is_saved() { + setOnLoad = true + load('state count = 0 persist') + compare(widget.stateValue("count"), 7) + tryCompare(test, "saved", { count: 7 }, 1600) + } + + function test_stopped_stream_cannot_update_a_new_subscription() { + load('source n = stream("fixture")') + widget.active = true + const old = requests[0] + widget.active = false + widget.active = true + old("stale") + compare(widget.instance.values[0], null) + requests[1]("fresh") + compare(widget.instance.values[0], "fresh") + } +} diff --git a/packages/omamobile-shell/test/widget-host.py b/packages/omamobile-shell/test/widget-host.py new file mode 100644 index 000000000..e098984f5 --- /dev/null +++ b/packages/omamobile-shell/test/widget-host.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Exercise the real Quickshell hosts with bounded output and local HTTP.""" +import http.server +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import threading +import time + + +class Replies(http.server.BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def do_GET(self): + self.send_response(200) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.end_headers() + try: + if self.path == "/large": + # No Content-Length, and fewer than 1 MB of characters: + # the byte limit must be checked during receipt. + for _ in range(12): + self.wfile.write(("é" * 65536).encode()) + self.wfile.flush() + time.sleep(0.025) + time.sleep(10) + else: + if self.path == "/slow": + time.sleep(0.5) + self.wfile.write("small café ☕".encode()) + except (BrokenPipeError, ConnectionResetError): + pass + + +def main(): + qs = shutil.which("quickshell") or shutil.which("qs") + if not qs: + print("widget-host: no Quickshell") + return 77 + here = Path(__file__).resolve().parent + with tempfile.TemporaryDirectory() as tmp, http.server.ThreadingHTTPServer(("127.0.0.1", 0), Replies) as server: + work = Path(tmp) + plugin = here.parent / "plugins/omamobile.home" + (work / "home/owl").mkdir(parents=True) + for filename in ("OwlPhoneHost.qml", "WidgetHost.qml", "BoundedProcess.qml", "HomeModel.js", "UserWidgets.js", + "owl/phone.js", "owl/values.js", "owl/terminal.js"): + shutil.copyfile(plugin / filename, work / "home" / filename) + shutil.copyfile(here / "widget-host.qml", work / "shell.qml") + (work / "runtime").mkdir(mode=0o700) + environment = dict(os.environ, QT_QPA_PLATFORM="offscreen", QT_QUICK_BACKEND="software", + QML_DISABLE_DISK_CACHE="1", XDG_RUNTIME_DIR=str(work / "runtime"), + XDG_STATE_HOME=str(work / "state"), XDG_CACHE_HOME=str(work / "cache"), + FIXTURE_URL=f"http://127.0.0.1:{server.server_port}", FIXTURE_DIR=tmp) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + result = subprocess.run([qs, "-p", str(work / "shell.qml")], env=environment, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=15) + except subprocess.TimeoutExpired as error: + print((error.stdout or b"").decode(errors="replace")) + print("widget-host: Quickshell did not finish") + return 1 + finally: + server.shutdown() + if result.returncode or "widget-host: PASS" not in result.stdout: + print(result.stdout) + return 1 + assert not (work / "cancelled-command-finished").exists(), "cancel must terminate the child command" + print("widget-host: PASS (bounded commands/HTTP, cancellation, state)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/omamobile-shell/test/widget-host.qml b/packages/omamobile-shell/test/widget-host.qml new file mode 100644 index 000000000..7e56838e3 --- /dev/null +++ b/packages/omamobile-shell/test/widget-host.qml @@ -0,0 +1,90 @@ +// SPDX-License-Identifier: MIT +import QtQuick +import Quickshell +import "home" as Home + +ShellRoot { + id: test + Home.OwlPhoneHost { id: owlHost } + Home.WidgetHost { id: qmlHost; capabilities: ["commands"] } + property string url: Quickshell.env("FIXTURE_URL") + property int remaining: 7 + property var cancelCommand: null + property var cancelRequest: null + property var captured: null + + function check(ok, message) { + if (ok) return + console.error("widget-host: " + message) + Qt.exit(1) + throw new Error(message) + } + function pass() { + remaining-- + if (!remaining) { console.log("widget-host: PASS"); Qt.quit() } + } + + Component.onCompleted: { + owlHost.command(null, "python3 -c 'import sys; sys.stdout.write(\"x\"*3000000); sys.stderr.write(\"y\"*3000000)'", 5, function(r) { + check(r.ok && r.out === "x".repeat(65536) && r.err === "y".repeat(65536), "command output is bounded on both pipes") + pass() + }) + qmlHost.run(["python3", "-c", "import sys,time; b='☕'.encode(); sys.stdout.buffer.write(b[:1]); sys.stdout.flush(); time.sleep(.05); sys.stdout.buffer.write(b[1:]+('é'*200000).encode())"], function(r) { + check(r.code === 0 && r.stdout === "☕" + "é".repeat(32766), "QML commands preserve split UTF-8 and use the same byte bound") + pass() + }) + owlHost.get(url + "/small", {}, 3, {}, function(r) { + check(r.ok && r.out === "small café ☕", "small HTTP response decodes correctly") + pass() + }) + owlHost.get(url + "/large", {}, 3, {}, function(r) { + check(r.error === "the answer is over 1 MB", "HTTP is rejected during receipt, before timeout or EOF") + pass() + }) + owlHost.get(url + "/slow", {}, 0.1, { status: true }, function(r) { + check(r.code === 124 && !r.ok && r.err === "timed out", "HTTP timeout retains status semantics") + pass() + }) + cancelRequest = owlHost.get(url + "/slow", {}, 3, {}, function() { check(false, "cancelled HTTP callback") }) + cancelCommand = owlHost.command(null, "sleep 1; touch \"$FIXTURE_DIR/cancelled-command-finished\"", 5, + function() { check(false, "cancelled command callback") }) + // Inspect the collector while the command is still running, not just + // its final callback: truncating only at exit would miss the problem. + captured = collector.createObject(test) + captured.running = true + cancel.start() + settle.start() + deadline.start() + } + Component { + id: collector + Home.BoundedProcess { + command: ["timeout", "-k", "2", "5", "bash", "-c", "python3 -c 'print(\"x\"*3000000, end=\"\")'; sleep 5"] + } + } + Timer { + id: cancel + interval: 100 + onTriggered: { test.cancelRequest.stop(); test.cancelCommand.stop() } + } + Timer { + id: settle + interval: 1500 + onTriggered: { + test.check(test.captured.running && test.captured.stdout === null && test.captured.out.length === 65536, "collector is bounded before exit") + test.captured.stop() + test.pass() + owlHost.saveState("fixture", { count: 7 }) + stateCheck.start() + } + } + Timer { + id: stateCheck + interval: 150 + onTriggered: { + test.check(owlHost.loadState("fixture").count === 7, "first state save reaches disk") + test.pass() + } + } + Timer { id: deadline; interval: 6000; onTriggered: test.check(false, "test timed out") } +} diff --git a/packages/omamobile-shell/version b/packages/omamobile-shell/version index 37b3d79e6..16c9e92a2 100644 --- a/packages/omamobile-shell/version +++ b/packages/omamobile-shell/version @@ -1 +1 @@ -0.2.44 +0.2.45