The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop-update): port the status panel to JXA with the Fourier Flow loader
ethernet1cf9d27b818d
diff --git a/hermes_cli/update_stage.py b/hermes_cli/update_stage.pyindex 8e85147fcc0..fbbd3cfc556 100644--- a/hermes_cli/update_stage.py+++ b/hermes_cli/update_stage.py@@ -101,7 +101,7 @@ def ensure_panel(update_root: Path) -> None:An old shim has no panel of its own and skipped its browser window on anon-Chromium default — its whole update then runs invisible. The freshly- pulled tree ships update-panel.applescript, so the takeover child can+ pulled tree ships update-panel.js, so the takeover child canstart it against the discovered status file. Best-effort end to end: anyfailure leaves the update running exactly as UI-less as before."""@@ -109,7 +109,7 @@ def ensure_panel(update_root: Path) -> None:returnif status_file() is None:return- panel = update_root / "scripts" / "desktop-update" / "update-panel.applescript"+ panel = update_root / "scripts" / "desktop-update" / "update-panel.js"if not panel.is_file():returntry:@@ -123,7 +123,7 @@ def ensure_panel(update_root: Path) -> None:# same way the shim-spawned UI outlives the shim's stages, and it# self-exits when the shim publishes a terminal state.subprocess.Popen(- ["/usr/bin/osascript", str(panel), str(status_file())],+ ["/usr/bin/osascript", "-l", "JavaScript", str(panel), str(status_file())],stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL, start_new_session=True,)diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.shindex cb96ced715e..7865a7b9835 100755--- a/scripts/desktop-update/posix.sh+++ b/scripts/desktop-update/posix.sh@@ -244,15 +244,15 @@ for entry in data.get("LSHandlers", []):esac}-start_status_panel() { # the macOS no-browser shim: osascript AppKit panel.+start_status_panel() { # the macOS no-browser shim: osascript (JXA) panel.# Best-effort by design: osascript missing or the panel exiting instantly# (syntax, headless session) just means no UI, exactly as before. The panel# polls $STATUS itself and self-exits after a terminal state, so this pid# only needs killing on OUR early teardown paths.- local py="$1" panel="$SCRIPT_DIR/update-panel.applescript"+ local py="$1" panel="$SCRIPT_DIR/update-panel.js"[ -n "$py" ] || py="/usr/bin/python3" # unused by osascript; keeps the wrapper shape"$py" -c 'import os, signal, sys; os.setsid(); signal.signal(signal.SIGTERM, signal.SIG_IGN); os.execv(sys.argv[1], sys.argv[1:])' \- /usr/bin/osascript "$panel" "$STATUS" >>"$LOG" 2>&1 &+ /usr/bin/osascript -l JavaScript "$panel" "$STATUS" >>"$LOG" 2>&1 &UI_PANEL_PID=$!sleep 1kill -0 "$UI_PANEL_PID" 2>/dev/null || { UI_PANEL_PID=""; return; }@@ -269,7 +269,7 @@ start_ui() {log "shim: default browser is not Chromium-family; skipping UI window"browser=""fi- if [ "$(uname)" = "Darwin" ] && [ -z "$browser" ] && [ -x "$SCRIPT_DIR/update-panel.applescript" ]; then+ if [ "$(uname)" = "Darwin" ] && [ -z "$browser" ] && [ -f "$SCRIPT_DIR/update-panel.js" ]; then# No Chromium renderer may host ui.html (Safari/Firefox default, or no# Chrome): draw the same progress as a native panel instead. Reads the# same $STATUS JSON — no server, no browser, no other-app scripting.diff --git a/scripts/desktop-update/update-panel.applescript b/scripts/desktop-update/update-panel.applescriptdeleted file mode 100644index ef207906015..00000000000--- a/scripts/desktop-update/update-panel.applescript+++ /dev/null@@ -1,122 +0,0 @@-# update-panel.applescript — the renderer-free macOS shim.-#-# When no Chromium-family browser may host ui.html (Safari/Firefox default, or-# no Chrome installed), this draws the same progress as a tiny native panel:-# an AppKit window whose label polls the SAME status file serve-ui.py's HTTP-# page reads (write_status JSON: {"status":..,"message":..}). No network, no-# browser, and no scripting of other apps, so no TCC automation prompt —-# AppKit is driven in-process under /usr/bin/osascript.-#-# Lifecycle mirrors the browser shim: poll until a terminal status, then linger-# (stop_ui leave-window sleeps 15s before killing us on manual/error; "done"-# tears down immediately, so exit on our own shortly after). A closed window-# ends the process — the user is allowed to dismiss us.-#-# /usr/bin/osascript update-panel.applescript <status-file>-#-# Must remain here, next to posix.sh: the desktop spawns this directory as-is-# (see resolvePosixScriptHandoff) and the script references it via $SCRIPT_DIR.--use framework "Foundation"-use framework "AppKit"-use scripting additions--# Set once the status file has been seen to exist; a LATER disappearance-# means the shim published a terminal state and cleaned up (see run handler).-property everPublished : false--on run argv- if (count of argv) < 1 then error "usage: osascript update-panel.applescript <status-file>"- set statusFile to (item 1 of argv as text)-- set nsapp to current application's NSApplication's sharedApplication()- # Accessory: no Dock icon — this is a status panel, not an app.- nsapp's setActivationPolicy:(current application's NSApplicationActivationPolicyAccessory)-- set win to current application's NSWindow's alloc()'s initWithContentRect:(current application's NSMakeRect(0, 0, 340, 110)) styleMask:3 backing:(current application's NSBackingStoreBuffered) defer:(current application's NSNumber's numberWithBool:true)- win's setTitle:"Hermes update"- win's |center|()- win's setReleasedWhenClosed:(current application's NSNumber's numberWithBool:false)-- set label to current application's NSTextField's wrappingLabelWithString:"Preparing update…"- label's setFrameSize:(current application's NSMakeSize(316, 50))- label's setFrameOrigin:(current application's NSMakePoint(12, 46))- label's setEditable:(current application's NSNumber's numberWithBool:false)- label's setBordered:(current application's NSNumber's numberWithBool:false)- label's setDrawsBackground:(current application's NSNumber's numberWithBool:false)- label's setFont:(current application's NSFont's systemFontOfSize:(13))-- set bar to current application's NSProgressIndicator's alloc()'s initWithFrame:(current application's NSMakeRect(12, 14, 316, 16))- bar's setIndeterminate:(current application's NSNumber's numberWithBool:true)- bar's startAnimation:(missing value)-- set content to win's contentView()- content's addSubview:label- content's addSubview:bar- win's makeKeyAndOrderFront:(missing value)- nsapp's activateIgnoringOtherApps:(true)-- set state to "running"- set runloop to current application's NSRunLoop's currentRunLoop()- repeat- set stPair to my readStatus(statusFile)- if stPair is not missing value then- set state to item 1 of stPair- set message to item 2 of stPair- if message is not "" then label's setStringValue:message- if state is in {"done", "manual", "error"} then- bar's stopAnimation:(missing value)- exit repeat- end if- else if my everPublished then- # The status file vanished after having existed: the shim removes- # it right after publishing a terminal state and tearing down the- # browser/panel UI. Waiting forever here stranded the panel on its- # last stage ("Installing the new app") — observed on a real- # update. Treat the disappearance as done; an error publish keeps- # its file alive through the 15s leave-window grace, so this- # cannot mask a failure.- set state to "done"- bar's stopAnimation:(missing value)- exit repeat- else- set everPublished to true- end if- # Pump the main runloop: without this the window never repaints and- # macOS beachballs the panel (label frozen on its initial string).- runloop's runMode:(current application's NSDefaultRunLoopMode) beforeDate:(current application's NSDate's dateWithTimeIntervalSinceNow:0.5)- end repeat- if state is "done" then- # The app is coming back; the shim's job is over.- delay 1.5- else- # manual/error: mirror stop_ui leave-window so the message is readable- # even without it (the durable result dialog covers the rest).- delay 15- end if-end run--on readStatus(statusFile)- # write_status emits a flat, one-line JSON pair we control, so field- # extraction beats NSJSONSerialization here (whose |error|: label this- # osascript rejects in by-ref position). Values are json_escaped by the- # writer; only \" can appear inside them and it carries no delimiter risk- # for the "..."-capturing pattern below. A missing/unreadable status file- # just yields no update this tick — the writer's atomic mv guarantees we- # never see a partial file.- set raw to ""- try- set raw to do shell script "/usr/bin/grep -o '\\\"status\\\":\\\"[^\\\"]*\\\"' " & quoted form of statusFile & " | /usr/bin/head -1"- end try- if raw is "" then return missing value- set AppleScript's text item delimiters to "\""- set state to text item 4 of raw- set rawMsg to ""- try- set rawMsg to do shell script "/usr/bin/grep -o '\\\"message\\\":\\\"[^\\\"]*\\\"' " & quoted form of statusFile & " | /usr/bin/head -1"- end try- set msg to ""- if rawMsg is not "" then set msg to text item 4 of rawMsg- set AppleScript's text item delimiters to ""- return {state, msg}-end readStatusdiff --git a/scripts/desktop-update/update-panel.js b/scripts/desktop-update/update-panel.jsnew file mode 100644index 00000000000..8dac2834477--- /dev/null+++ b/scripts/desktop-update/update-panel.js@@ -0,0 +1,261 @@+/*+ * update-panel.js — the renderer-free macOS shim, drawn like ui.html.+ *+ * When no Chromium-family browser may host ui.html (Safari/Firefox default,+ * or no Chrome installed), this draws the SAME visual as the browser shim:+ * the Fourier Flow curve (math ported verbatim from ui.html / loader.tsx),+ * one title, one stage line, dark/light following the OS — an AppKit window+ * polling the SAME status file serve-ui.py's HTTP page reads (write_status+ * JSON: {"status":..,"message":..}). No network, no browser, and no+ * scripting of other apps, so no TCC automation prompt. Runs in-process:+ *+ * /usr/bin/osascript -l JavaScript update-panel.js <status-file>+ *+ * JXA over AppleScript: the curve math below is character-for-character the+ * ui.html math (real JS), and the window/animation drive the same AppKit+ * calls the previous AppleScript panel hand-rolled.+ *+ * Lifecycle mirrors the browser shim: poll until a terminal status, then+ * linger (stop_ui leave-window sleeps 15s before killing us on manual/error;+ * "done" tears down immediately, so exit on our own shortly after). A closed+ * window ends the process — the user is allowed to dismiss us. The status+ * file vanishing after having existed means the shim published a terminal+ * state and cleaned up: treat it as done (an error publish keeps its file+ * alive through the grace window, so this cannot mask a failure).+ *+ * Must remain here, next to posix.sh: the desktop spawns this directory+ * as-is (see resolvePosixScriptHandoff) and the script references it via+ * its own path.+ */+ObjC.import('AppKit')+ObjC.import('QuartzCore') // CACurrentMediaTime++// ── Fourier Flow — constants and math ported verbatim from ui.html ──────────+// Keep in sync with ui.html / apps/desktop/src/components/ui/loader.tsx:+// durationMs 2200, particleCount 92, pulseDurationMs 2000, strokeWidth 4.2,+// trailSpan 0.31, PATH_STEPS 240, viewBox 0 0 100 100 (center 50,50).+const TWO_PI = Math.PI * 2++const CURVE = {+ durationMs: 2200,+ particleCount: 92,+ pulseDurationMs: 2000,+ strokeWidth: 4.2,+ trailSpan: 0.31,+ point(progress, detailScale) {+ const t = progress * TWO_PI+ const mix = 1 + detailScale * 0.16+ const x = 17 * Math.cos(t) + 7.5 * Math.cos(3 * t + 0.6 * mix) + 3.2 * Math.sin(5 * t - 0.4)+ const y = 15 * Math.sin(t) + 8.2 * Math.sin(2 * t + 0.25) - 4.2 * Math.cos(4 * t - 0.5 * mix)++ return { x: 50 + x, y: 50 + y }+ }+}++const PATH_STEPS = 240+const norm = progress => ((progress % 1) + 1) % 1++function detailScaleFor (time, phaseOffset) {+ const p = ((time + phaseOffset * CURVE.pulseDurationMs) % CURVE.pulseDurationMs) / CURVE.pulseDurationMs++ return 0.52 + ((Math.sin(p * TWO_PI + 0.55) + 1) / 2) * 0.48+}++function particleFor (index, progress, detailScale) {+ const tail = index / (CURVE.particleCount - 1)+ const { x, y } = CURVE.point(norm(progress - tail * CURVE.trailSpan), detailScale)+ const fade = (1 - tail) ** 0.56++ return { x, y, opacity: 0.04 + fade * 0.96, radius: 0.9 + fade * 2.7 }+}++// Render one animation frame into an 80x80 NSImage (the JS analog of the+// page's <svg> repaint). AppKit is bottom-left origin; the curve math is+// top-left like SVG, so flip Y around the 50,50 center — the math itself is+// untouched.+function renderLoaderFrame (timeMs, phaseOffset, fg) {+ const size = 80+ const img = $.NSImage.alloc.initWithSize($.NSMakeSize(size, size))+ img.lockFocus++ const progress = norm(timeMs / CURVE.durationMs)+ const detailScale = detailScaleFor(timeMs, phaseOffset)++ const ghost = fg.colorWithAlphaComponent(0.1)+ ghost.set+ const path = $.NSBezierPath.bezierPath+ for (let i = 0; i <= PATH_STEPS; i++) {+ const { x, y } = CURVE.point(i / PATH_STEPS, detailScale)+ const px = x / 100 * size+ const py = size - y / 100 * size+ if (i === 0) path.moveToPoint($.NSMakePoint(px, py))+ else path.lineToPoint($.NSMakePoint(px, py))+ }+ path.setLineWidth(CURVE.strokeWidth)+ path.setLineCapStyle($.NSRoundLineCapStyle)+ path.setLineJoinStyle($.NSRoundLineJoinStyle)+ path.stroke++ for (let index = 0; index < CURVE.particleCount; index++) {+ const p = particleFor(index, progress, detailScale)+ const px = p.x / 100 * size+ const py = size - p.y / 100 * size+ fg.colorWithAlphaComponent(p.opacity).set+ $.NSBezierPath.bezierPathWithOvalInRect(+ $.NSMakeRect(px - p.radius, py - p.radius, p.radius * 2, p.radius * 2)+ ).fill+ }++ img.unlockFocus+ return img+}++function isDarkAppearance () {+ const app = $.NSApplication.sharedApplication+ const match = app.effectiveAppearance.bestMatchFromAppearancesWithNames(+ $(['NSAppearanceNameAqua', 'NSAppearanceNameDarkAqua'])+ )+ return ObjC.unwrap(match) === 'NSAppearanceNameDarkAqua'+}++// ui.html: light fg #1a1a1a; dark #d6d6d6 on #232323.+function colors () {+ return isDarkAppearance()+ ? {+ bg: $.NSColor.colorWithCalibratedRedGreenBlueAlpha(35 / 255, 35 / 255, 35 / 255, 1),+ fg: $.NSColor.colorWithCalibratedRedGreenBlueAlpha(214 / 255, 214 / 255, 214 / 255, 1)+ }+ : {+ bg: $.NSColor.whiteColor,+ fg: $.NSColor.colorWithCalibratedRedGreenBlueAlpha(26 / 255, 26 / 255, 26 / 255, 1)+ }+}++function readStatus (path) {+ // write_status emits a flat, one-line JSON pair we control, so a missing+ // or malformed file simply yields undefined (no update this tick). The+ // writer's atomic mv guarantees we never observe a partial file.+ try {+ const data = $.NSString.stringWithContentsOfFileEncodingError(path, $.NSUTF8StringEncoding, null)+ if (data.js === '') return undefined+ const state = JSON.parse(ObjC.unwrap(data))+ if (!state || typeof state.status !== 'string') return undefined+ return state+ } catch (_) {+ return undefined+ }+}++function wrappedLabel (text, font, color, frame) {+ const label = $.NSTextField.wrappingLabelWithString(text)+ label.font = font+ if (color) label.textColor = color+ label.editable = false+ label.bordered = false+ label.drawsBackground = false+ label.alignment = $.NSTextAlignmentCenter+ label.frame = frame+ return label+}++function run (argv) {+ if (argv.length < 1) throw new Error('usage: osascript -l JavaScript update-panel.js <status-file>')+ const statusPath = argv[0]++ const app = $.NSApplication.sharedApplication+ // Accessory: no Dock icon — this is a status panel, not an app.+ app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)++ const { bg, fg } = colors()++ // 280x320 like the Chrome --window-size the shim uses.+ const win = $.NSWindow.alloc.initWithContentRectStyleMaskBackingDefer(+ $.NSMakeRect(0, 0, 280, 320), 3, $.NSBackingStoreBuffered, false+ )+ win.title = 'Hermes'+ win.center+ win.releasedWhenClosed = false+ win.backgroundColor = bg+ const content = win.contentView++ // Loader: 80x80, centered horizontally, near the top (AppKit Y-up).+ const loaderView = $.NSImageView.alloc.initWithFrame($.NSMakeRect(100, 220, 80, 80))+ loaderView.imageScaling = $.NSImageScaleProportionallyUpOrDown+ content.addSubview(loaderView)++ const title = wrappedLabel('Updating Hermes', $.NSFont.systemFontOfSize(18), fg,+ $.NSMakeRect(12, 180, 256, 26))+ const line = wrappedLabel('Hermes will open once done.', $.NSFont.systemFontOfSize(12), null,+ $.NSMakeRect(24, 116, 232, 54))+ content.addSubview(title)+ content.addSubview(line)++ win.makeKeyAndOrderFront(null)+ app.activateIgnoringOtherApps(true)++ // Elapsed clock = when the panel started, like serve-ui.py's started_at.+ // Random phase like the page's Math.random() phaseOffset.+ const startedAtMs = $.CACurrentMediaTime() * 1000+ const phaseOffset = Math.random()+ const runloop = $.NSRunLoop.currentRunLoop+ let everPublished = false+ let settled = null // null = running; else 'done' | 'manual' | 'error'+ let message = ''++ while (settled === null) {+ const state = readStatus(statusPath)+ if (state) {+ everPublished = true+ if (state.message) {+ message = String(state.message)+ line.stringValue = message+ }+ if (['done', 'manual', 'error'].includes(state.status)) settled = state.status+ } else if (everPublished) {+ // The status file vanished after having existed: the shim removes it+ // right after publishing a terminal state and tearing down its UI.+ // Waiting forever stranded the panel on its last stage — observed on a+ // real update. A disappearance reads as done; an error publish keeps+ // its file alive through the 15s leave-window grace, so this cannot+ // mask a failure.+ settled = 'done'+ }++ if (settled === null) {+ loaderView.image = renderLoaderFrame($.CACurrentMediaTime() * 1000 - startedAtMs, phaseOffset, fg)+ // Pump the main runloop: without this the window never repaints and+ // macOS beachballs the panel. The pump also drives the next poll.+ runloop.runModeBeforeDate($.NSDefaultRunLoopMode,+ $.NSDate.dateWithTimeIntervalSinceNow(0.03))+ }+ }++ // Terminal states: swap the loader for the glyph; title/line verbatim+ // from ui.html's apply().+ loaderView.hidden = true+ title.stringValue = settled === 'error' ? 'Failed to update' : 'Update complete'+ if (settled === 'done') {+ line.stringValue = 'Opening Hermes…\nYou can close this window.'+ } else if (settled === 'manual') {+ line.stringValue = message || 'Reopen Hermes to finish.'+ } else {+ line.stringValue = 'Run hermes debug share in a terminal to send a report.'+ }+ const glyph = wrappedLabel(settled === 'error' ? '✕' : '✓',+ $.NSFont.systemFontOfSize(44), fg, $.NSMakeRect(100, 220, 80, 80))+ content.addSubview(glyph)++ if (settled === 'done') {+ // The app is coming back; the shim's job is over.+ linger(1.5)+ } else {+ // manual/error: mirror stop_ui leave-window so the message is readable+ // even without it (the durable result dialog covers the rest).+ linger(15)+ }+}++function linger (seconds) {+ $.NSRunLoop.currentRunLoop.runModeBeforeDate($.NSDefaultRunLoopMode,+ $.NSDate.dateWithTimeIntervalSinceNow(seconds))+}