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
57 changes: 54 additions & 3 deletions BarWidget.qml
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,56 @@ BarWidget {
}
}

// ---- This plugin's own updates. `omarchy plugin update` puts newer
// code on disk, but the shell keeps running what it loaded until it
// restarts (it re-creates the widget, from its cached copy). The helper
// fingerprints the manifest and QML on disk and remembers the
// fingerprint the running shell loaded. A difference offers a restart:
// in the panel, in the menu, and in one notification per newer copy. A
// sign-in under way survives the restart, since its helper runs outside
// the shell.
property string loadedCode: ""
property string loadedVersion: ""
property string installedCode: ""
property string installedVersion: ""
property string _notifiedCode: ""
readonly property bool pluginUpdated: loadedCode !== "" && installedCode !== "" && installedCode !== loadedCode

function checkPluginUpdate() { if (!pluginProc.running) pluginProc.running = true }
function restartShell() { Quickshell.execDetached(["omarchy", "restart", "shell"]) }
function syncMenuArgs() {
return [menuHelper, "sync-menu"].concat(pluginUpdated ? ["--restart", installedVersion || "update"] : [])
}

Process {
id: pluginProc
running: false
command: [root.menuHelper, "plugin-info"]
stdout: StdioCollector { id: pluginStdout; waitForEnd: true }
onExited: function (exitCode) {
var doc = null
if (exitCode === 0) { try { doc = JSON.parse(String(pluginStdout.text || "")) } catch (e) {} }
if (!doc || !doc.code || !doc.loadedCode) return
root.loadedCode = doc.loadedCode
root.loadedVersion = doc.loadedVersion || ""
root.installedCode = doc.code
root.installedVersion = doc.version || ""
if (root.pluginUpdated && root._notifiedCode !== doc.code) {
root._notifiedCode = doc.code
Quickshell.execDetached([root.menuHelper, "notify-plugin-update", root.installedVersion])
Quickshell.execDetached(root.syncMenuArgs())
}
}
}

Timer {
interval: 60 * 1000
running: true
repeat: true
triggeredOnStart: true
onTriggered: root.checkPluginUpdate()
}

// Hourly; the helper only goes to the network once its cache is stale.
Timer {
interval: 3600 * 1000
Expand Down Expand Up @@ -194,7 +244,7 @@ BarWidget {
root.errorDetail = ""
// Keep the omarchy-menu submenu in step with session state (it no-ops
// and skips the menu refresh when nothing changed).
Quickshell.execDetached([root.menuHelper, "sync-menu"])
Quickshell.execDetached(root.syncMenuArgs())
}

readonly property string menuHelper:
Expand Down Expand Up @@ -301,7 +351,7 @@ BarWidget {
root.errorDetail = err.trim() || "varlatch not found"
}
// The menu offers installing the CLI while it is missing.
Quickshell.execDetached([root.menuHelper, "sync-menu"])
Quickshell.execDetached(root.syncMenuArgs())
if (root._refreshQueued) { root._refreshQueued = false; Qt.callLater(root.refresh) }
}
}
Expand Down Expand Up @@ -364,7 +414,7 @@ BarWidget {
panelLoader.item.expandedServer = server
}
function debugState(): string {
return JSON.stringify({ sessionState: root.sessionState, servers: root.servers, pendingLogin: root.pendingLogin, cliVersion: root.cliVersion, cliInstall: root.cliInstall, latestVersion: root.latestVersion, updateAvailable: root.updateAvailable, errorDetail: root.errorDetail, opened: root.opened, hasPanel: !!panelLoader.item, connecting: panelLoader.item ? panelLoader.item.connecting : false, connectFocused: panelLoader.item ? panelLoader.item.connectFocused : false, expandedServer: panelLoader.item ? panelLoader.item.expandedServer : "" })
return JSON.stringify({ sessionState: root.sessionState, servers: root.servers, pendingLogin: root.pendingLogin, cliVersion: root.cliVersion, cliInstall: root.cliInstall, latestVersion: root.latestVersion, updateAvailable: root.updateAvailable, errorDetail: root.errorDetail, opened: root.opened, hasPanel: !!panelLoader.item, connecting: panelLoader.item ? panelLoader.item.connecting : false, connectFocused: panelLoader.item ? panelLoader.item.connectFocused : false, expandedServer: panelLoader.item ? panelLoader.item.expandedServer : "", loadedVersion: root.loadedVersion, installedVersion: root.installedVersion, pluginUpdated: root.pluginUpdated })
}
}

Expand All @@ -383,6 +433,7 @@ BarWidget {
: s.expiresAt ? remainingText(s.expiresAt, now) : "no expiry recorded"))
}
if (updateAvailable) lines.push("CLI " + latestVersion + " available")
if (pluginUpdated) lines.push("Restart the shell to load Varlatch for Omarchy " + (installedVersion || "update"))
return "Varlatch\n" + lines.join("\n")
}

Expand Down
45 changes: 40 additions & 5 deletions Panel.qml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@ Panel {
onOpenedChanged: {
if (opened) {
nowMs = Date.now()
if (hostWidget) hostWidget.refreshVersion(3600)
if (hostWidget) {
hostWidget.refreshVersion(3600)
hostWidget.checkPluginUpdate()
}
} else {
connecting = false
connectError = ""
Expand Down Expand Up @@ -642,12 +645,44 @@ Panel {
}
}

// ---- Footer: CLI version, and a newer release when checkUpdates
// finds one. "update" only for the release build the plugin can
// replace; a source checkout or custom command gets the notes.
// ---- Footer: newer plugin code waiting for a shell restart; the
// CLI version, and a newer release when checkUpdates finds one.
// "update" only for the release build the plugin can replace; a
// source checkout or custom command gets the notes.
PanelSeparator {
visible: footer.visible
visible: footer.visible || pluginUpdate.visible
width: parent.width
}

Item {
id: pluginUpdate
visible: !!root.hostWidget && root.hostWidget.pluginUpdated
width: parent.width
height: Math.max(pluginUpdateText.implicitHeight, restartChip.implicitHeight)

Text {
id: pluginUpdateText
anchors.left: parent.left
anchors.right: restartChip.left
anchors.rightMargin: Style.space(8)
anchors.verticalCenter: parent.verticalCenter
wrapMode: Text.WordWrap
text: root.hostWidget && root.hostWidget.installedVersion
&& root.hostWidget.installedVersion !== root.hostWidget.loadedVersion
? "Varlatch for Omarchy " + root.hostWidget.installedVersion + " is installed"
: "A newer copy of this widget is installed"
color: "#e0993e"
font.family: root.fontFamily
font.pixelSize: Style.font.caption
}

Chip {
id: restartChip
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
label: "restart"
onClicked: root.hostWidget.restartShell()
}
}

Item {
Expand Down
54 changes: 52 additions & 2 deletions bin/varlatch-menu
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,48 @@ case "${1:-}" in
refresh_widget
;;

plugin-info)
# The plugin's version and a fingerprint of the code the shell loads
# (the manifest and the QML), now on disk and as the running shell
# loaded it. `omarchy plugin update` (or an edit) puts newer code on
# disk, and the shell does re-create the widget, but from the copy it
# cached when it started, so only a shell restart loads it. The first
# call from a shell process (the widget runs this directly, so the
# shell is the parent) records what it loaded, keyed by that process's
# id and start time; later calls from it, re-created widgets included,
# get the same answer. The helper itself runs fresh on every call.
dir=$(cd "$(dirname "$0")/.." && pwd)
code=$(cat "$dir/manifest.json" "$dir"/*.qml 2>/dev/null | sha256sum | cut -d' ' -f1)
version=$(jq -r '.version // empty' "$dir/manifest.json" 2>/dev/null || true)
started=$(sed -E 's/^.*\) //' "/proc/$PPID/stat" 2>/dev/null | awk '{print $20}' || true)
key="$(boot_id):$PPID:${started:-0}"
loaded_file="$STATE_DIR/plugin-loaded.json"
mkdir -p "$STATE_DIR"
known="{}"
[ -f "$loaded_file" ] && known=$(jq -c 'if type == "object" then . else {} end' "$loaded_file" 2>/dev/null || echo "{}")
# Drop records of shell processes that are gone.
boot=$(boot_id)
for k in $(jq -r 'keys[]' <<<"$known"); do
IFS=: read -r b p s <<<"$k"
alive=$(sed -E 's/^.*\) //' "/proc/$p/stat" 2>/dev/null | awk '{print $20}' || true)
if [ "$b" != "$boot" ] || [ "$alive" != "$s" ]; then known=$(jq -c --arg k "$k" 'del(.[$k])' <<<"$known"); fi
done
if ! jq -e --arg k "$key" 'has($k)' <<<"$known" >/dev/null; then
known=$(jq -c --arg k "$key" --arg c "$code" --arg v "$version" '.[$k] = {code: $c, version: $v}' <<<"$known")
fi
printf '%s\n' "$known" > "$loaded_file"
jq -cn --arg v "$version" --arg c "$code" --argjson l "$(jq -c --arg k "$key" '.[$k]' <<<"$known")" \
'{version: $v, code: $c, loadedVersion: $l.version, loadedCode: $l.code}'
;;

notify-plugin-update)
# One notification per newer copy, with a button to restart the shell.
version="${2:-}"
msg="Varlatch for Omarchy${version:+ $version} is installed. Restart the shell to load it."
choice=$(notify-send -a Varlatch -A "restart=Restart now" --wait "Varlatch" "$msg" || true)
[ "$choice" = "restart" ] && exec omarchy restart shell
;;

version-info)
# One JSON line for the widget: the CLI version, how it is installed,
# and (checkUpdates on) the latest release, cached in $UPDATE_FILE.
Expand Down Expand Up @@ -653,11 +695,14 @@ case "${1:-}" in
;;

sync-menu)
# `--restart <version>`: the widget saw newer plugin code on disk.
restart_version=""
[ "${2:-}" = --restart ] && restart_version="${3:-}"
# Regenerate this plugin's managed block in omarchy-menu.jsonc from the
# current session state, so the submenu shows what you are logged in to
# and offers only the actions that make sense. The menu hot-reloads the
# file; we only rewrite (and refresh) when the content actually changed.
VARLATCH_MENU_CMD="$CMD" VARLATCH_SHOW_LOCALHOST="$(show_localhost && echo on || echo off)" python3 - <<'PY'
VARLATCH_RESTART_VERSION="$restart_version" VARLATCH_MENU_CMD="$CMD" VARLATCH_SHOW_LOCALHOST="$(show_localhost && echo on || echo off)" python3 - <<'PY'
import json, os, re, subprocess, sys
from datetime import datetime, timezone

Expand Down Expand Up @@ -807,6 +852,11 @@ if ver.get("updateAvailable") and ver.get("install") == "release":
entries.append(("varlatch.update", {"icon": "", "label": "Update CLI",
"description": f"{ver.get('current')} → {ver.get('latest')}",
"action": f"omarchy-launch-floating-terminal-with-presentation {bin_path} upgrade-cli {ver.get('latest')}"}))
if os.environ.get("VARLATCH_RESTART_VERSION"):
entries.append(("varlatch.restart", {"icon": "\uf021",
"label": "Restart to load Varlatch for Omarchy " + os.environ["VARLATCH_RESTART_VERSION"],
"description": "Newer widget code is installed; restarts the Omarchy shell",
"action": "omarchy restart shell"}))
status = {"icon": "", "label": "Show full status", "action": f"{bin_path} status-notify"}
if ver.get("current"):
status["description"] = f"CLI {ver['current']}"
Expand Down Expand Up @@ -852,7 +902,7 @@ PY
;;

*)
echo "Usage: varlatch-menu <has-credentials|status-notify|verify|notify-session <server> <state> <message>|login [server]|login-device [server]|login-cancel|login-check|logout [server]|web [server]|refresh|sync-menu|version-info [--force|--max-age <s>]|notify-update <current> <latest> <install>|upgrade-cli [version]|install-cli>" >&2
echo "Usage: varlatch-menu <has-credentials|status-notify|verify|notify-session <server> <state> <message>|login [server]|login-device [server]|login-cancel|login-check|logout [server]|web [server]|refresh|plugin-info|notify-plugin-update <version>|sync-menu [--restart <version>]|version-info [--force|--max-age <s>]|notify-update <current> <latest> <install>|upgrade-cli [version]|install-cli>" >&2
exit 1
;;
esac
38 changes: 38 additions & 0 deletions tests/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,44 @@ check "CLI 0.13.0: no device button on a failure" "! calls | grep notify-send |
: > "$T/calls.log"; "$H" notify-session https://vl.example.com warning "expires soon"
check "expiry notification: Renew now and Another device" "calls | grep -q -- '-A login=Renew now -A device=Another device --wait'"

# --------------------------------------------------------------------------
section "plugin updates (plugin-info, notify-plugin-update)"
new_home
# A copy of the plugin, so the test can change its files.
COPY="$T/plugin-copy"; mkdir -p "$COPY"
cp -R "$ROOT/bin" "$ROOT/manifest.json" "$COPY/"; cp "$ROOT"/*.qml "$COPY/"
info() { "$COPY/bin/varlatch-menu" plugin-info; }
first=$(info)
check "plugin-info: version and a code fingerprint, loaded = on disk at first" \
"jq -e --arg v \"\$(jq -r .version '$ROOT/manifest.json')\" '.version == \$v and (.code | test(\"^[0-9a-f]{64}$\")) and .loadedCode == .code' <<<'$first' >/dev/null"
echo "# notes" >> "$COPY/README.md"
check "a change outside the manifest and QML keeps the fingerprint" '[ "$(info)" = "$first" ]'
echo "// changed" >> "$COPY/Panel.qml"
# shellcheck disable=SC2034 # read by check
second=$(info)
check "a QML change: newer code on disk, the same shell still has the old" \
'[ "$(jq -r .code <<<"$second")" != "$(jq -r .code <<<"$first")" ] && [ "$(jq -r .loadedCode <<<"$second")" = "$(jq -r .code <<<"$first")" ]'
# A new shell process (here: another parent process) loads what is on disk.
# shellcheck disable=SC2034 # read by check
# (A second command keeps bash from exec'ing the helper in its own place.)
third=$(bash -c '"$1/bin/varlatch-menu" plugin-info; true' _ "$COPY")
check "a new shell process records what is on disk now" \
'[ "$(jq -r .loadedCode <<<"$third")" = "$(jq -r .code <<<"$second")" ]'
info >/dev/null
check "the next call drops records of exited processes" \
"[ \"\$(jq 'length' '$S/plugin-loaded.json')\" -eq 1 ]" "$(cat "$S/plugin-loaded.json" 2>/dev/null)"
: > "$T/calls.log"; FAKE_CHOICE=restart "$H" notify-plugin-update 9.9.9
check "notification offers Restart now and restarts the shell" \
"calls | grep -q -- '-A restart=Restart now --wait Varlatch Varlatch for Omarchy 9.9.9 is installed' && calls | grep -q '^omarchy restart shell'"
: > "$T/calls.log"; FAKE_CHOICE='' "$H" notify-plugin-update 9.9.9
check "dismissed: no restart" "! calls | grep -q '^omarchy restart shell'"
session https://vl.example.com false
"$H" sync-menu --restart 9.9.9
check "menu: Restart to load the newer copy" \
"menu_has '.[\"varlatch.restart\"] | (.action == \"omarchy restart shell\") and (.label | endswith(\"9.9.9\")) and .icon != \"\"'"
"$H" sync-menu
check "menu: no restart row without newer code" "menu_has 'has(\"varlatch.restart\") | not'"

# --------------------------------------------------------------------------
section "release check (version-info)"
new_home
Expand Down
Loading