Show native navigation progress and cancel loads from icon toolbar

This commit is contained in:
waozi committed 2026-11-15 20:20:05 -03:00
1 parent 5d24f54790
commit 35e1bc5d1d
13 files changed
+206 -30

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ test: check $(QUICKJS_ARCHIVE)
$(ZIRAN) build --project --root tests --target=c --entry transport_test:Main --exe -o build/transport-test tests/transport_test.zi
python3 tests/transport_test.py build/transport-test/transport_test
window-test: build
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 xvfb-run -a -s '-screen 0 1280x1024x24' env BROWSER_PRIVATE_XVFB=1 python3 tests/window_test.py
env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u SESSION_MANAGER HARMONY_DESKTOP_RECOVERY=0 YUE_DESKTOP_RECOVERY=0 xvfb-run -a -s '-screen 0 1280x1024x24' env BROWSER_PRIVATE_XVFB=1 python3 tests/window_test.py
install: build
mkdir -p "$(PREFIX)/bin" "$(PREFIX)/share/applications" "$(PREFIX)/share/icons/hicolor/scalable/apps" "$(PREFIX)/share/licenses/kryon-browser"
install -m 755 build/browser-desktop "$(PREFIX)/bin/kryon-browser"
+34 -2
View File
@@ -7,7 +7,11 @@ independently from the desktop. No Chromium or WebKit engine renders pages.
Classic inline JavaScript runs in a statically linked, pinned QuickJS engine.
Enter an HTTP(S) address or local `file:///` URL. Links navigate within the app.
Back and Next restore history and scroll positions. Pages wrap to the window
Back and Next restore history and scroll positions. Toolbar controls use icons
with accessible names and hover tooltips. Loading shows a status and colored
bar immediately; Reload becomes Stop (X). Stop cancels and reaps the curl
loader, discards its partial response, and preserves the displayed page.
Reload retries the requested URL; entering another address can replace a load. Pages wrap to the window
and scroll independently. Ctrl+L selects the address. Pages load outside the
UI frame: `src/transport.zi` streams curl through Ziran's process channel
and `src/url.zi` resolves links, so the whole browser is Ziran plus curl.
@@ -23,7 +27,9 @@ surface includes `document.getElementById`, `document.querySelector` (the first
`#id`, `.class`, or tag match), element `textContent`, and `document.title`.
Each navigation gets a fresh QuickJS runtime with a 16 MiB engine-memory limit,
a 256 KiB stack limit, and a 100 ms total deadline. Exceptions are contained
and later inline scripts are still attempted. QuickJS's `std` and `os` modules
and later inline scripts are still attempted. Bounded exception details appear
in the local status (not console logs); unsupported external/module script tags
produce a compatibility notice instead of silently implying full support. QuickJS's `std` and `os` modules
are not loaded, and pages get no file, process, shell, or network host API. The
official QuickJS 2026-06-04 source archive is verified against a pinned SHA-256
before it is built.
@@ -59,3 +65,29 @@ display/session variables and start private Xvfb, then exercise address input,
HTML/CSS rendering, script mutations and limits, relative links, history,
scrolling and a narrow window. Screenshots are written under
`build/screenshots/`.
## X compatibility diagnosis
An anonymous request using this browser's curl options on 2026-11-15 returned
HTTP 200, 13,517 bytes of HTML from https://x.com/ (below the input limit).
Its inline bootstrap uses `document.cookie.match`, `document.documentElement`,
`getElementsByTagName`, element creation, events, `window`, `self`,
`ReadableStream`, and `performance`; it injects an external module client.
The native private-Xvfb reproduction ran three inline scripts, with three
failures and no script-limit hit. Its first exception was
`TypeError: cannot read property 'match' of undefined`, from
`document.cookie.match(...)`. The bounded HTML preview stops before all eight
script tags in this response can be collected. These are missing browser host
APIs, rather than evidence that JavaScript is
disabled or that QuickJS cannot parse modern JavaScript. This patch exposes
the real exceptions instead of the previous generic “JavaScript exception”.
The snapshot DOM cannot run X's application. Full support requires a live DOM,
external/module loading, an event loop and events/timers, fetch/streams, storage
and cookies, additional Web APIs, and substantially richer CSS/layout. No X
login or interactive compatibility is claimed. Network responses can vary; a
403 from a different fetch path does not explain this local HTTP 200 response.
Reproduce a bounded anonymous native-window diagnostic with
`BROWSER_DIAGNOSE_X=1 build-queue -- make window-test`; this writes only URL,
script counts, limits and exception/status into `build/x-com-diagnosis.json`.
The test uses private Xvfb and never the owner's running window.
+27 -6
View File
@@ -1,4 +1,5 @@
BoxWidget :: #import "kryon/box";
TooltipWidget :: #import "kryon/tooltip";
ButtonWidget :: #import "kryon/button";
LinkWidget :: #import "kryon/link";
ScrollWidget :: #import "kryon/scroll";
@@ -23,10 +24,15 @@ SystemThemeLinux :: #import "kryon/SystemThemeLinux";
#import "std/timer_linux"
theme_ready: bool;
base: StyleRules;
tooltips: [5]TooltipWidget.TooltipState;
Action :: (session: Session, id: s32, label: string, bounds: Rectangle, enabled: bool) -> bool {
Window.Record(id,label,bounds.x,bounds.y,bounds.width,bounds.height,enabled)
props: ButtonWidget.Props; props.key=cast(u64)id; props.id=id; props.bounds=bounds; props.label=label; props.disabled=!enabled
props: ButtonWidget.Props; props.key=cast(u64)id; props.id=id; props.bounds=bounds; props.label=label; props.disabled=!enabled; props.icon_only=true
if id==10 { props.icon_shape="S2rr:M19 12H5M12 5L5 12L12 19" }
if id==11 || id==13 { props.icon_shape="S2rr:M5 12H19M12 5L19 12L12 19" }
if id==12 { props.icon_shape="S2rr:M3 10L12 3L21 10V21H15V14H9V21H3Z" }
if id==14 { props.icon_shape=ifx State.loading then "S2rr:M6 6L18 18M18 6L6 18" else "S2rr:M20 7V3M20 7H16M20 7C17 2 9 2 5 7C1 12 4 21 12 21C16 21 19 19 21 15" }
return ButtonWidget.Draw(session,props)==1
}
Paint :: (session: Session, viewport: Rectangle) {
@@ -65,18 +71,33 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
if (modifiers & KeyModifierControl)!=0 && key==76 { State.focused=true; State.anchor=0; State.cursor=cast(s32)TextUntilNul(State.address[:]).count }
chrome: BoxWidget.Props; chrome.key=1; chrome.bounds=viewport; chrome.fill=StyleTokenColor("surface"); unused BoxWidget.Draw(session,chrome)
x:=viewport.x+12.0; y:=viewport.y+10.0; width:=viewport.width-24.0
if Action(session,10,"Back",.{x,y,62.0,38.0},!State.loading && State.position>0) { State.Back(-1) }
if Action(session,11,"Next",.{x+68.0,y,62.0,38.0},!State.loading && State.position+1<State.history_count) { State.Back(1) }
if Action(session,12,"Home",.{x+136.0,y,62.0,38.0},!State.loading) { State.Navigate("about:start") }
field_bounds: Rectangle=.{x+210.0,y,width-280.0,38.0}
if Action(session,10,"Back",.{x,y,38.0,38.0},!State.loading && State.position>0) { State.Back(-1) }
if Action(session,11,"Next",.{x+44.0,y,38.0,38.0},!State.loading && State.position+1<State.history_count) { State.Back(1) }
if Action(session,12,"Home",.{x+88.0,y,38.0,38.0},!State.loading) { State.Navigate("about:start") }
if Action(session,14,ifx State.loading then "Stop loading" else "Reload",.{x+132.0,y,38.0,38.0},true) { if State.loading { State.Stop() } else { State.Reload() } }
field_bounds: Rectangle=.{x+182.0,y,width-232.0,38.0}
result:=AddressField(session,field_bounds,key,modifiers,typed); State.cursor=result.cursor; State.anchor=result.anchor; State.focused=result.focused
if result.edit.changed { State.Edit(result.edit.start,result.edit.end,result.edit.replacement) }
Window.Record(20,"Address",field_bounds.x,field_bounds.y,field_bounds.width,field_bounds.height,true)
if Action(session,13,ifx State.loading then "Wait" else "Go",.{x+width-62.0,y,62.0,38.0},!State.loading) || (result.committed && !State.loading) { State.Navigate(TextUntilNul(State.address[:]),true,true); State.focused=false }
if Action(session,13,"Go",.{x+width-38.0,y,38.0,38.0},true) || result.committed { if State.loading { State.Stop() }; State.Navigate(TextUntilNul(State.address[:]),true,true); State.focused=false }
page: Rectangle=.{viewport.x,viewport.y+60.0,viewport.width,viewport.height-92.0}
background: BoxWidget.Props; background.key=2; background.bounds=page; background.fill=ColorFromPacked(Document.page_color); unused BoxWidget.Draw(session,background)
if Document.count>0 { Paint(session,page) }
if State.loading {
indicator: BoxWidget.Props; indicator.key=4; indicator.bounds=.{viewport.x,viewport.y+56.0,viewport.width,3.0}; indicator.fill=StyleTokenColorOr("accent",ColorFromPacked(0x4c8dffff)); unused BoxWidget.Draw(session,indicator)
}
status: TextWidget.Props; status.key=3; status.bounds=.{x,viewport.y+viewport.height-26.0,width,22.0}; status.text=TextUntilNul(State.message[:]); status.size=13; status.wrap=.TextWrapNone; TextWidget.Draw(session,status)
// Draw overlays last so the page cannot cover them.
pointer:=Desktop.PollPointer()
for i: 0..Window.control_count-1 {
id:=Window.control_ids[i]
if id<10 || id>14 { continue }
bounds:=Window.control_bounds[i]
tip: TooltipWidget.Props; tip.key=cast(u64)(5000+id); tip.anchor=.{bounds[0],bounds[1],bounds[2],bounds[3]}; tip.viewport=viewport
tip.text=TextUntilNul(Window.control_labels[i][:]); tip.now_ms=MonotonicMilliseconds(); tip.delay_ms=500
tip.pointer.over_anchor=pointer.x>=bounds[0] && pointer.x<bounds[0]+bounds[2] && pointer.y>=bounds[1] && pointer.y<bounds[1]+bounds[3]
unused TooltipWidget.Draw(session,tip,*tooltips[id-10])
}
return 0
}
AddressField :: (session: Session, bounds: Rectangle, key: s32, modifiers: s32, typed: string) -> TextFieldWidget.Result {
+1
View File
@@ -33,6 +33,7 @@ Publish :: () {
name: [32]u8; Model.Set(name[:],"_HARMONY_APP_STATE"); atom:=Atom(info.display,*name[0],0)
out: Vec(u8); BuilderPrint(*out,"{\"interface\":\"harmony.app-state.v1\",\"app\":\"browser\",\"loading\":%",Model.loading)
Model.Property(*out,"url",TextFromCString(*Model.url[0])); Model.Property(*out,"title",TextFromCString(*Document.title[0]))
Model.Property(*out,"status",TextFromCString(*Model.message[0])); Model.Property(*out,"script_error",TextFromCString(*Document.script_error[0]))
BuilderPrint(*out,",\"scroll\":%,\"nodes\":%,\"scripts\":%,\"script_failures\":%,\"script_limited\":%,\"controls\":[",Model.scroll,Document.count,Document.scripts_run,Document.scripts_failed,Document.script_limited)
for i: 0..control_count-1 {
BuilderPrint(*out,"%{\"control\":\"%\",\"role\":1,\"enabled\":%,\"x\":%,\"y\":%,\"width\":%,\"height\":%,\"label\":",ifx i==0 then "" else ",",control_ids[i],control_enabled[i],control_bounds[i][0],control_bounds[i][1],control_bounds[i][2],control_bounds[i][3])
+3 -1
View File
@@ -46,6 +46,7 @@ height: float32;
truncated: bool;
scripts: [ScriptLimit]string;
script_count: s32;
scripts_unsupported: s32;
scripts_run: s32;
scripts_failed: s32;
script_limited: bool;
@@ -296,7 +297,7 @@ RunScripts :: () {
}
Load :: (html: string) {
count=0; rule_count=0; truncated=false; title[0]=0; page_color=0xffffffff
script_count=0; scripts_run=0; scripts_failed=0; script_limited=false; script_error[0]=0; script_output[0]=0
script_count=0; scripts_unsupported=0; scripts_run=0; scripts_failed=0; script_limited=false; script_error[0]=0; script_output[0]=0
unused Add(-1,"document"); stack: [64]s32; depth: s32=1; stack[0]=0; i: s32=0
while i<cast(s32)html.count && count<Limit {
if html[i]!=60 {
@@ -331,6 +332,7 @@ Load :: (html: string) {
if close<0 { break }
if Same(tag,"style") { ParseCSS(html[i:close]) }
if Same(tag,"title") { Copy(title[:],Trim(html[i:close])) }
if Same(tag,"script") && !ClassicScript(attributes) { scripts_unsupported+=1 }
if Same(tag,"script") && ClassicScript(attributes) {
if script_count<ScriptLimit { scripts[script_count]=html[i:close]; script_count+=1 }
else { script_limited=true }
+17 -2
View File
@@ -50,6 +50,22 @@ static void discard_exception(BrowserScript *script) {
JS_FreeValue(script->context, exception);
}
/* Render the exception only into the local page status, never a console/log.
Conversion is still under the page deadline (including hostile toString). */
static void exception_error(BrowserScript *script, uint8_t *output,
uint64_t capacity) {
JSValue exception = JS_GetException(script->context);
const char *text = JS_ToCString(script->context, exception);
set_error(output, capacity, text ? text : "JavaScript exception");
if (output && capacity) {
for (uint64_t i = 0; i < capacity && output[i]; i++)
if (output[i] < 32 || output[i] == 127) output[i] = ' ';
}
if (text) JS_FreeCString(script->context, text);
else discard_exception(script);
JS_FreeValue(script->context, exception);
}
static JSValue eval_bytes(BrowserScript *script, const uint8_t *source,
uint64_t source_size, const char *filename) {
char *terminated = malloc((size_t)source_size + 1);
@@ -156,12 +172,11 @@ int32_t browser_script_eval(void *handle, const uint8_t *source,
script->interrupted = 0;
value = eval_bytes(script, source, source_size, "<inline-script>");
if (JS_IsException(value)) {
discard_exception(script);
exception_error(script, error, error_capacity);
if (script->interrupted) {
set_error(error, error_capacity, "JavaScript time limit reached");
return 2;
}
set_error(error, error_capacity, "JavaScript exception");
return 1;
}
JS_FreeValue(script->context, value);
+29 -7
View File
@@ -20,6 +20,9 @@ cursor: s32;
anchor: s32;
focused: bool;
scroll: s32;
pending_remember: bool;
pending_position: s32;
last_target: [4097]u8;
// JSON helpers for the desktop host's state reply (desktop.zi).
Release :: (value: string) { descriptor:=cast(*TextDescriptor)(*value); Free(cast(*void)descriptor.data) }
@@ -37,25 +40,44 @@ Set :: (out: []u8, value: string) { Document.Copy(out,value) }
Navigate :: (target: string, remember: bool=true, typed: bool=false) {
if loading || target=="" { return }
if remember && position>=0 { history_scroll[position]=scroll }
if remember {
if position>=63 { for i: 0..cast(s32)62 { history[i]=history[i+1]; history_scroll[i]=history_scroll[i+1] }; position=62 }
position+=1; history_count=position+1; Set(history[position][:],target); history_scroll[position]=0
}
pending_position=position
pending_remember=remember
Set(last_target[:],target)
base: [4097]u8; if !typed { Set(base[:],TextUntilNul(url[:])) }
loading=Transport.Start(target,TextUntilNul(base[:]))
if loading { Set(last_target[:],TextView(Transport.request_url[0:Transport.request_length])) }
Set(message[:],ifx loading then "Loading…" else Transport.error)
}
Stop :: () {
unused Transport.Stop(); loading=false; position=pending_position; pending_remember=false; Set(message[:],"Loading stopped")
}
Reload :: () {
if position>=0 { history_scroll[position]=scroll }
target: [4097]u8; Set(target[:],TextUntilNul(last_target[:]))
if target[0]==0 { Set(target[:],TextUntilNul(url[:])) }
Navigate(TextUntilNul(target[:]),TextUntilNul(target[:])!=TextUntilNul(url[:]),true)
}
Back :: (delta: s32) {
if loading || position+delta<0 || position+delta>=history_count { return }
history_scroll[position]=scroll; position+=delta; target: [4097]u8; Set(target[:],TextUntilNul(history[position][:])); Navigate(TextUntilNul(target[:]),false)
previous:=position; history_scroll[position]=scroll; position+=delta; target: [4097]u8; Set(target[:],TextUntilNul(history[position][:])); Navigate(TextUntilNul(target[:]),false); pending_position=previous
}
Tick :: () {
if !started { started=true; Navigate("about:start") }
if !Transport.Poll() { return }; loading=false
if Transport.error!="" { Set(message[:],Transport.error); return }
if Transport.error!="" { position=pending_position; pending_remember=false; Set(message[:],Transport.error); return }
if pending_remember {
if position>=63 { for i: 0..cast(s32)62 { history[i]=history[i+1]; history_scroll[i]=history_scroll[i+1] }; position=62 }
position+=1; history_count=position+1; history_scroll[position]=0
}
pending_remember=false
Set(url[:],Transport.CurrentUrl()); Set(html[:],Transport.Html()); Set(address[:],TextUntilNul(url[:])); Set(history[position][:],TextUntilNul(url[:]))
Set(last_target[:],TextUntilNul(url[:]))
Document.Load(TextUntilNul(html[:])); changed=true; scroll=history_scroll[position]; cursor=cast(s32)TextUntilNul(address[:]).count; anchor=cursor
if Document.script_error[0]!=0 { Set(message[:],TextUntilNul(Document.script_error[:])) }
if Document.script_error[0]!=0 {
out: Vec(u8); BuilderPrint(*out,"JavaScript: % (limited browser APIs)",TextUntilNul(Document.script_error[:]))
status:=BuilderFinish(out); Set(message[:],status); Release(status)
}
else if Document.scripts_unsupported>0 { Set(message[:],"Limited compatibility: external/module scripts are not supported") }
else { Set(message[:],ifx Document.truncated then "Page preview limit reached" else TextUntilNul(Document.title[:])) }
}
Edit :: (start: s32, end: s32, replacement: string) {
+14
View File
@@ -239,6 +239,7 @@ Start :: (target: string, base: string) -> bool {
if problem == Url.ERROR_LENGTH { error = Url.ERROR_LENGTH }
return false
}
request_length = cast(s32)url.count
if url == "about:start" {
page_length = StartPage.Write(page[:])
final_length = Url.Append(final_url[:], 0, "about:start")
@@ -269,6 +270,19 @@ Start :: (target: string, base: string) -> bool {
return true
}
// Cancel and reap only the owned loader. No partial response is published.
#program_export
Stop :: () -> bool {
cancelled:=true
if loading && !ready { cancelled=Channel.CancelChannel(*channel) }
loading = false
ready = false
received_size = 0
page_length = 0
error = ""
return cancelled
}
// True once the current load finished, successfully or with error set.
#program_export
Poll :: () -> bool {
+4
View File
@@ -40,6 +40,10 @@ Main :: () -> s32 {
Check(TextUntilNul(title[:])=="Loop contained" && FindText("Still rendered")>=0 && script_limited,"infinite loop is interrupted without unloading the page")
Load("<p id='fresh'>Original</p><script>document.getElementById('fresh').textContent=typeof pageValue==='undefined'?'Fresh runtime':'Leaked runtime'</script>")
Check(FindText("Fresh runtime")>=0 && scripts_failed==0 && !script_limited,"navigation resets JavaScript runtime state")
Load("<p>X bootstrap regression</p><script>document.cookie.match(/night_mode/)</script>")
Check(scripts_failed==1 && !script_limited && TextUntilNul(script_error[:])!="JavaScript exception","missing browser APIs report the actual exception, not a language or resource-limit failure")
Load("<script type='module' src='https://abs.twimg.com/example.js'></script>")
Check(scripts_unsupported==1 && scripts_run==0,"unsupported module loading is counted for compatibility reporting")
if failures==0 { print("HTML, CSS, bounded QuickJS DOM mutation, recovery, limits and navigation reset verified\n") }
return failures
}
+15 -2
View File
@@ -56,8 +56,8 @@ int main(void) {
"no std, os, process, or require API");
check(browser_script_eval(script, (const uint8_t *)throws,
strlen(throws), error, sizeof(error)) == 1 &&
strcmp((const char *)error, "JavaScript exception") == 0,
"script errors are generic and contained");
strcmp((const char *)error, "Error: page-private secret") == 0,
"script error detail is returned to the caller and contained");
check(browser_script_eval(script, exact_recovery.data,
sizeof(exact_recovery.data), error,
sizeof(error)) == 0,
@@ -100,6 +100,19 @@ int main(void) {
check(0, "create memory-limited runtime");
}
script = browser_script_create(
(const uint8_t *)bootstrap, strlen(bootstrap), UINT64_C(8388608),
UINT64_C(262144), 35, error, sizeof(error));
if (script) {
static const char hostile[] = "throw {toString(){for(;;){}}}";
double started = seconds();
check(browser_script_eval(script, (const uint8_t *)hostile,
strlen(hostile), error, sizeof(error)) == 2 &&
seconds() - started < 0.75,
"exception formatting remains inside the page deadline");
browser_script_destroy(script);
} else check(0, "create exception-formatting runtime");
if (failures == 0)
puts("QuickJS isolation, exception recovery, deadline and memory limit verified");
return failures != 0;
+6 -2
View File
@@ -6,6 +6,7 @@ import subprocess
import sys
import tempfile
import threading
import time
LIMIT = 524288
@@ -25,7 +26,10 @@ class Handler(BaseHTTPRequestHandler):
pass # curl stops oversized documents early, as intended
def do_GET(self):
if self.path == "/redirect":
if self.path == "/slow":
time.sleep(3)
self.send(200, "text/html", b"<h1>Slow response</h1>")
elif self.path == "/redirect":
self.send(302, "", b"", [("Location", "/pages/index.html")])
elif self.path == "/pages/index.html":
self.send(200, "text/html; charset=utf-8", b"<h1>HTTP document</h1><a href='next.html'>Next</a>")
@@ -44,7 +48,7 @@ class Handler(BaseHTTPRequestHandler):
def main():
binary = Path(sys.argv[1]).resolve()
with tempfile.TemporaryDirectory(prefix="browser-transport-") as folder:
with tempfile.TemporaryDirectory(prefix="browser-transport-", dir=Path("build").resolve()) as folder:
root = Path(folder)
(root / "local page.html").write_text("<h1>Local HTML</h1>")
(root / "big.html").write_bytes(b"x" * (LIMIT + 1))
+9
View File
@@ -112,6 +112,15 @@ Main :: () -> s32 {
Check(Load(TextView(notes_url[0:notes_length]), "") && Transport.Html() == "<pre>a &lt;b&gt; &amp; c</pre>",
"text file shown as escaped preformatted text")
Check(Transport.Start(Join(origin,"/slow"),""),"start slow transport")
unused TestSleep(100000)
Check(!Transport.Poll() && Transport.loading,"slow transport remains pending")
Check(Transport.Stop(),"cancel and reap owned channel")
Check(!Transport.loading && !Transport.Poll(),"Stop reaps curl, closes its socket and cannot publish a stale response")
Check(Load("about:start","") && Transport.error=="","navigation after cancellation")
Check(Transport.Start(Join(origin,"/slow"),""),"retry cancelled URL")
Check(Transport.Stop() && Transport.Stop(),"repeated Stop is safe")
redirect: [4096]u8
redirect_length := Url.Append(redirect[:], 0, Join(origin, "/redirect"))
Check(Load(TextView(redirect[0:redirect_length]), "") && Transport.error == "" &&
+46 -7
View File
@@ -6,6 +6,8 @@ from pathlib import Path
import subprocess
import tempfile
import time
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
ROOT = Path(__file__).resolve().parents[1]
assert os.environ.get("BROWSER_PRIVATE_XVFB") == "1", "Use make window-test"
@@ -18,20 +20,24 @@ def xdo(*args):
return subprocess.check_output(["xdotool", *map(str, args)], text=True).strip()
def state(url=None):
def state(url=None, loading=False):
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
raw = subprocess.check_output(["xprop", "-id", window, "_HARMONY_APP_STATE"], text=True)
if " = " in raw:
value = json.loads(ast.literal_eval(raw.split(" = ", 1)[1].strip()))
if not value["loading"] and value["nodes"] > 0 and (url is None or value["url"] == url):
decoded = ast.literal_eval(raw.split(" = ", 1)[1].strip())
# xprop escapes UTF-8 bytes as octal in its C string.
try: decoded = decoded.encode("latin1").decode("utf-8")
except UnicodeError: pass
value = json.loads(decoded)
if value["loading"] == loading and value["nodes"] > 0 and (url is None or value["url"] == url):
return value
time.sleep(.1)
raise AssertionError("Browser did not load " + str(url))
def action(label):
control = next(c for c in state()["controls"] if c["label"] == label and c["enabled"])
def action(label, loading=False):
control = next(c for c in state(loading=loading)["controls"] if c["label"] == label and c["enabled"])
xdo("mousemove", "--window", window, int(control["x"] + control["width"] / 2), int(control["y"] + control["height"] / 2))
xdo("click", "1")
time.sleep(.2)
@@ -51,7 +57,40 @@ try:
xdo("windowsize", window, 1060, 800)
state("about:start")
subprocess.run(["import", "-window", window, str(output / "start.png")], check=True)
with tempfile.TemporaryDirectory() as folder:
if os.environ.get("BROWSER_DIAGNOSE_X"):
action("Address"); xdo("key", "ctrl+a"); xdo("type", "--clearmodifiers", "https://x.com"); xdo("key", "Return")
observed = state("https://x.com/")
# Bounded diagnostics; no page body, cookies or initial-data payload.
diagnosis = {key: observed[key] for key in ("url", "scripts", "script_failures", "script_limited", "script_error", "status")}
(ROOT / "build/x-com-diagnosis.json").write_text(json.dumps(diagnosis, indent=2))
print(json.dumps(diagnosis))
action("Home"); state("about:start")
class SlowHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/slow": time.sleep(3)
body=b"<title>Transport recovered</title><h1>Loaded</h1>"
self.send_response(200); self.send_header("Content-Length", str(len(body))); self.end_headers()
try: self.wfile.write(body)
except (BrokenPipeError, ConnectionResetError): pass
def log_message(self, *args): pass
server=ThreadingHTTPServer(("127.0.0.1",0), SlowHandler)
threading.Thread(target=server.serve_forever,daemon=True).start()
try:
slow=f"http://127.0.0.1:{server.server_port}/slow"
action("Address"); xdo("key", "ctrl+a"); xdo("type", "--clearmodifiers", slow); xdo("key", "Return")
pending=state(loading=True)
assert pending["status"] == "Loading…"
assert any(c["label"] == "Stop loading" and c["enabled"] for c in pending["controls"])
subprocess.run(["import", "-window", window, str(output / "loading.png")], check=True)
action("Stop loading", loading=True)
assert state()["status"] == "Loading stopped"
action("Reload")
state(loading=True); state(slow)
action("Reload"); state(loading=True); state(slow)
action("Home"); state("about:start")
finally:
server.shutdown(); server.server_close()
with tempfile.TemporaryDirectory(dir=ROOT / "build") as folder:
path = Path(folder) / "index.html"
second = Path(folder) / "next.html"
loop = Path(folder) / "loop.html"
@@ -94,7 +133,7 @@ try:
xdo("windowsize", window, 640, 800)
time.sleep(.5)
subprocess.run(["import", "-window", window, str(output / "narrow.png")], check=True)
print("Native HTML/CSS, bounded QuickJS DOM changes, loop recovery, navigation state, scrolling and narrow window verified")
print("Native icon toolbar, loading status, Stop/retry/reload, HTML/CSS, bounded QuickJS DOM changes, loop recovery, history, scrolling and narrow window verified")
finally:
process.terminate()
try: